-
Notifications
You must be signed in to change notification settings - Fork 5
/
ProfectFileInfo.fs
405 lines (324 loc) · 15.4 KB
/
ProfectFileInfo.fs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
module FSharp.Editing.ProjectSystem.ProfectFileInfo
open System
open System.IO
open Microsoft.CodeAnalysis
open System.Runtime.Versioning
open Microsoft.Build
open Microsoft.Build.Execution
open Microsoft.Build.Evaluation
open Microsoft.Build.Framework
open System.Xml.Linq
open Microsoft.FSharp.Compiler.SourceCodeServices
open FSharp.Editing
module PropertyConverter =
// TODO - railway this
let toGuid propertyValue =
match Guid.TryParse propertyValue with
| true, value -> Some value
| _ -> None
let toDefineConstants propertyValue =
if String.IsNullOrWhiteSpace propertyValue then [||]
else propertyValue.Split([| ';' |], StringSplitOptions.RemoveEmptyEntries)
// TODO - railway this
let toBoolean propertyValue =
if propertyValue = String.Empty then false else
match Boolean.TryParse propertyValue with
| true, value -> value
| _ -> failwithf "Couldn't parse '%s' into a Boolean" propertyValue
let toBooleanOr propertyValue defaultArg =
match Boolean.TryParse propertyValue with
| true, value -> value
| _ -> defaultArg
let inline localName x = (^a:(member Name:XName) x).LocalName
let inline private matchName (name:string) x = name = (localName x)
/// Helper function to filter a seq of XElements by matching their local name against the provided string
let inline private nameFilter name sqs = sqs |> Seq.filter ^ matchName name
let inline private hasNamed name sqs = sqs |> Seq.exists ^ matchName name
let inline private getNamed name sqs = sqs |> Seq.find ^ matchName name
let inline private tryGetNamed name sqs =
(None, sqs) ||> Seq.fold ^ fun acc elm ->
match acc with
| Some _ -> acc
| None -> if matchName name elm then Some elm else None
[<RequireQualifiedAccess>]
module XDoc =
let elements (xdoc:#XDocument) = xdoc.Elements()
let hasElement name (xdoc:#XDocument) =
elements xdoc |> hasNamed name
let getElement name (xdoc:#XDocument) =
elements xdoc |> getNamed name
let tryGetElement name (xdoc:#XDocument) =
elements xdoc |> tryGetNamed name
let getElements name (xdoc:#XDocument) =
elements xdoc |> nameFilter name
[<RequireQualifiedAccess>]
module XAttr =
let value (xattr:XAttribute) = xattr.Value
let parent (xattr:XAttribute) = xattr.Parent
let previous (xattr:XAttribute) = xattr.PreviousAttribute
let next (xattr:XAttribute) = xattr.NextAttribute
[<RequireQualifiedAccess>]
/// Functions for operating on XElements
module XElem =
let getAttribute name (xelem:#XElement) =
xelem.Attribute ^ XName.Get name
type ProjectInstance with
member self.TryGetPropertyValue propertyName =
let value = self.GetPropertyValue propertyName
if String.IsNullOrEmpty value then None else Some value
open Microsoft.CodeAnalysis.Diagnostics
// open ProtoWorkspace.Loaders
let getFullPath (projectItem : ProjectItemInstance) = projectItem.GetMetadataValue MetadataName.FullPath
let isProjectReference (projectItem : ProjectItemInstance) : bool =
projectItem.GetMetadataValue(MetadataName.ReferenceSourceTarget)
.Equals(ItemName.ProjectReference, StringComparison.OrdinalIgnoreCase)
let internal projectCollection = new ProjectCollection()
let internal loadProject (projectFilePath:string) =
let projectFilePath = Path.GetFullPath projectFilePath
if not (File.Exists projectFilePath) then failwithf "No project file found at '%s'" projectFilePath else
let projXDoc = XDocument.Load(projectFilePath)
let toolsVersion =
match XDoc.tryGetElement "Project" projXDoc with
| None -> "15.0"
| Some xelem -> xelem |> XElem.getAttribute "ToolsVersion" |> XAttr.value
// let toolsVersion =
// if toolsVersion <> "15.0" then "14.0" else "15.0"
let globalProps =
dict [
"BuildingInsideVisualStudio", "true" // necessary to force the resolution of references in projects with project references
"VisualStudioVersion", toolsVersion
]
// projectCollection.LoadProject(projectFilePath,globalProps,toolsVersion)
globalProps
|> Seq.iter(fun kvp ->projectCollection.SetGlobalProperty(kvp.Key,kvp.Value) )
projectCollection.LoadProject(projectFilePath)
let create (projectFilePath:string) =
if not (File.Exists projectFilePath) then failwithf "No project file found at '%s'" projectFilePath else
// let manager = BuildManager.DefaultBuildManager
//
// let buildParam = BuildParameters(DetailedSummary=true)
// let project = Project projectFilePath
// let projectInstance = project.CreateProjectInstance()
let project = loadProject projectFilePath
use manager = BuildManager.DefaultBuildManager
let buildParam = BuildParameters(DetailedSummary=true)
let projectInstance = project.CreateProjectInstance()
let requestReferences =
BuildRequestData (projectInstance,
[| "ResolveReferences"
"ResolveAssemblyReferences"
"ResolveProjectReferences"
"ResolveReferenceDependencies"
|])
manager.Build (buildParam,requestReferences) |> ignore
// let result = manager.Build(buildParam,requestReferences)
// let fromBuildRes targetName =
// if result.ResultsByTarget.ContainsKey targetName then
// result.ResultsByTarget.[targetName].Items
// |> Seq.map(fun r -> r.ItemSpec)
// |> Array.ofSeq
// else
// [||]
//
// let _projectReferences = fromBuildRes "ResolveProjectReferences"
//
// let references = fromBuildRes "ResolveAssemblyReferences"
let references =
projectInstance.GetItems ItemName.ReferencePath
|> Seq.append ^ projectInstance.GetItems ItemName.ChildProjectReferences
|> Seq.map ^ fun item -> item.EvaluatedInclude
let projectReferences =
projectInstance.GetItems ItemName.ProjectReference
|> Seq.filter isProjectReference
|> Seq.map getFullPath
let getItems itemType =
if project.ItemTypes.Contains itemType then
project.GetItems itemType
|> Seq.map(fun item -> item.EvaluatedInclude)
else
Seq.empty
let getProperty propName =
let s = project.GetPropertyValue propName
if String.IsNullOrWhiteSpace s then None
else Some s
let outFileOpt = getProperty "TargetPath"
let getbool (s:string option) =
match s with
| None -> false
| Some s ->
match Boolean.TryParse s with
| true, result -> result | false, _ -> false
let split (s:string option) (cs:char[]) =
match s with
| None -> [||]
| Some s ->
if String.IsNullOrWhiteSpace s then [||]
else s.Split(cs, StringSplitOptions.RemoveEmptyEntries)
let fxVer = getProperty "TargetFrameworkVersion"
let optimize = getProperty "Optimize" |> getbool
let _assemblyNameOpt = getProperty "AssemblyName"
let tailcalls = getProperty "Tailcalls" |> getbool
let _outputPathOpt = getProperty "OutputPath"
let docFileOpt = getProperty "DocumentationFile"
let outputTypeOpt = getProperty "OutputType"
let debugTypeOpt = getProperty "DebugType"
let baseAddressOpt = getProperty "BaseAddress"
let sigFileOpt = getProperty "GenerateSignatureFile"
let keyFileOpt = getProperty "KeyFile"
let pdbFileOpt = getProperty "PdbFile"
let platformOpt = getProperty "Platform"
let targetTypeOpt = getProperty "TargetType"
let versionFileOpt = getProperty "VersionFile"
let targetProfileOpt = getProperty "TargetProfile"
let warnLevelOpt = getProperty "Warn"
let subsystemVersionOpt = getProperty "SubsystemVersion"
let win32ResOpt = getProperty "Win32ResourceFile"
let heOpt = getProperty "HighEntropyVA" |> getbool
let win32ManifestOpt = getProperty "Win32ManifestFile"
let debugSymbols = getProperty "DebugSymbols" |> getbool
let prefer32bit = getProperty "Prefer32Bit" |> getbool
let warnAsError = getProperty "TreatWarningsAsErrors" |> getbool
let defines = split (getProperty "DefineConstants") [| ';'; ','; ' ' |]
let nowarn = split (getProperty "NoWarn") [| ';'; ','; ' ' |]
let warningsAsError = split (getProperty "WarningsAsErrors") [| ';'; ','; ' ' |]
let libPaths = split (getProperty "ReferencePath") [| ';'; ',' |]
let otherFlags = split (getProperty "OtherFlags") [| ' ' |]
let isLib =
match outputTypeOpt with
| None -> false
| Some prop -> prop ="Library"
let pages = getItems "Page"
let embeddedResources = getItems "EmbeddedResource"
let files = getItems "Compile"
let resources = getItems "Resource"
let _noaction = getItems "None"
let content = getItems "Content"
let fscFlag str (opt:string option) = seq{
match opt with
| None -> ()
| Some s -> yield str + s
}
let fscFlags flag (ls:string []) = seq {
for x in ls do
if not (String.IsNullOrWhiteSpace x) then yield flag + x
}
let options = [
yield "--simpleresolution"
yield "--noframework"
yield! fscFlag "--out:" outFileOpt
yield! fscFlag "--doc:" docFileOpt
yield! fscFlag "--baseaddress:" baseAddressOpt
yield! fscFlag "--keyfile:" keyFileOpt
yield! fscFlag "--sig:" sigFileOpt
yield! fscFlag "--pdb:" pdbFileOpt
yield! fscFlag "--versionfile:" versionFileOpt
yield! fscFlag "--warn:" warnLevelOpt
yield! fscFlag "--subsystemversion:" subsystemVersionOpt
if heOpt then yield "--highentropyva+"
yield! fscFlag "--win32res:" win32ResOpt
yield! fscFlag "--win32manifest:" win32ManifestOpt
yield! fscFlag "--targetprofile:" targetProfileOpt
yield "--fullpaths"
yield "--flaterrors"
if warnAsError then yield "--warnaserror"
yield
if isLib then "--target:library"
else "--target:exe"
yield! fscFlags "--define:" defines
yield! fscFlags "--nowarn:" nowarn
yield! fscFlags "--warnaserror:" warningsAsError
yield if debugSymbols then "--debug+" else "--debug-"
yield if optimize then "--optimize+" else "--optimize-"
yield if tailcalls then "--tailcalls+" else "--tailcalls-"
match debugTypeOpt with
| None -> ()
| Some debugType ->
match debugType.ToUpperInvariant() with
| "NONE" -> ()
| "PDBONLY" -> yield "--debug:pdbonly"
| "FULL" -> yield "--debug:full"
| _ -> ()
match platformOpt |> Option.map (fun o -> o.ToUpperInvariant()), prefer32bit,
targetTypeOpt |> Option.map (fun o -> o.ToUpperInvariant()) with
| Some "ANYCPU", true, Some "EXE" | Some "ANYCPU", true, Some "WINEXE" -> yield "--platform:anycpu32bitpreferred"
| Some "ANYCPU", _, _ -> yield "--platform:anycpu"
| Some "X86", _, _ -> yield "--platform:x86"
| Some "X64", _, _ -> yield "--platform:x64"
| Some "ITANIUM", _, _ -> yield "--platform:Itanium"
| _ -> ()
match targetTypeOpt |> Option.map (fun o -> o.ToUpperInvariant()) with
| Some "LIBRARY" -> yield "--target:library"
| Some "EXE" -> yield "--target:exe"
| Some "WINEXE" -> yield "--target:winexe"
| Some "MODULE" -> yield "--target:module"
| _ -> ()
yield! otherFlags
yield! Seq.map((+)"--resource:") resources
yield! Seq.map((+)"--lib:") libPaths
yield! Seq.map((+)"-r:") references
yield! files
]
let getItemPaths itemName =
projectInstance.GetItems itemName |> Seq.map getFullPath
let filterItemPaths predicate itemName =
projectInstance.GetItems itemName
|> Seq.filter predicate
|> Seq.map getFullPath
let isScriptFile path =
String.equalsIC (path |> Path.GetExtension) ".fsx"
let sourceFiles = getItemPaths ItemName.Compile
let otherFiles =
filterItemPaths (fun x -> not ^ isScriptFile x.EvaluatedInclude) ItemName.None
let scriptFiles =
filterItemPaths (fun x -> isScriptFile x.EvaluatedInclude) ItemName.None
let references =
projectInstance.GetItems ItemName.ReferencePath
|> Seq.filter (not<<isProjectReference)
|> Seq.map getFullPath
let projectReferences =
projectInstance.GetItems ItemName.ProjectReference
|> Seq.filter isProjectReference
|> Seq.map getFullPath
let analyzers = getItemPaths ItemName.Analyzer
let projectGuid =
projectInstance.TryGetPropertyValue Property.ProjectGuid
|> Option.bind PropertyConverter.toGuid
// let projectId =
// defaultArg (projectGuid |> Option.map ^ fun x -> ProjectId.CreateFromSerialized x)
// (ProjectId.CreateNewId())
let defineConstants =
projectInstance.GetPropertyValue Property.DefineConstants
|> PropertyConverter.toDefineConstants
let projectName = projectInstance.TryGetPropertyValue Property.ProjectName
let assemblyName = projectInstance.GetPropertyValue Property.AssemblyName
let targetPath = projectInstance.GetPropertyValue Property.TargetPath
let targetFramework = projectInstance.TryGetPropertyValue Property.TargetFrameworkMoniker //|> Option.map FrameworkName
let assemblyKeyFile = projectInstance.TryGetPropertyValue Property.AssemblyOriginatorKeyFile
let signAssembly = PropertyConverter.toBoolean <| projectInstance.GetPropertyValue Property.SignAssembly
let outputType = OutputType.Parse <| projectInstance.GetPropertyValue Property.OutputType
let xmlDocs = projectInstance.TryGetPropertyValue Property.DocumentationFile
{ ProjectFilePath = projectFilePath
ProjectGuid = projectGuid
// ProjectId = projectId
Name = projectName
TargetFramework = targetFramework
FrameworkVersion = fxVer
AssemblyName = assemblyName
OutputPath = targetPath
OutputType = outputType
SignAssembly = signAssembly
AssemblyOriginatorKeyFile = assemblyKeyFile
GenerateXmlDocumentation = xmlDocs
PreprocessorSymbolNames = defineConstants |> Array.ofSeq
CompileFiles = sourceFiles |> Array.ofSeq
PageFiles = pages |> Array.ofSeq
ContentFiles = content |> Array.ofSeq
ScriptFiles = scriptFiles |> Array.ofSeq
ResourceFiles = resources |> Array.ofSeq
EmbeddedResourceFiles = embeddedResources |> Array.ofSeq
OtherFiles = otherFiles |> Array.ofSeq
References = references |> Array.ofSeq
ProjectReferences = projectReferences |> Array.ofSeq
Analyzers = analyzers |> Array.ofSeq
Options = options |> Array.ofSeq
}