-
Notifications
You must be signed in to change notification settings - Fork 587
/
DotNet.fs
2064 lines (1698 loc) · 78 KB
/
DotNet.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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
namespace Fake.DotNet
/// <summary>
/// .NET Core + CLI tools helpers
/// </summary>
[<RequireQualifiedAccess>]
module DotNet =
// NOTE: The #if can be removed once we have a working release with the "new" API
// Currently we #load this file in build.fsx
open Fake.Core
open Fake.IO
open Fake.IO.FileSystemOperators
open Fake.DotNet.NuGet
open System
open System.IO
open System.Security.Cryptography
open System.Text
open Newtonsoft.Json.Linq
/// <summary>
/// .NET Core SDK default install directory (set to default SDK installer paths
/// (<c>%HOME/.dotnet</c> or <c>%LOCALAPPDATA%/Microsoft/dotnet</c>).
/// </summary>
let defaultUserInstallDir =
if Environment.isUnix then
Environment.environVar "HOME" @@ ".dotnet"
else
Environment.environVar "LocalAppData" @@ "Microsoft" @@ "dotnet"
/// <summary>
/// .NET Core SDK default install directory (set to default SDK installer paths
/// (<c>/usr/local/share/dotnet</c> or <c>C:\Program Files\dotnet</c>))
/// </summary>
let defaultSystemInstallDir =
if Environment.isUnix then
"/usr/local/share/dotnet"
else
@"C:\Program Files\dotnet"
/// <summary>
/// Tries to get the DotNet SDK from the global.json, starts searching in the given directory.
/// Returns None if global.json is not found
/// </summary>
///
/// <param name="startDir">The directory to start search from</param>
let internal tryGetSDKVersionFromGlobalJsonDir startDir : string option =
let globalJsonPaths rootDir =
let rec loop (dir: DirectoryInfo) =
seq {
match dir.GetFiles "global.json" with
| [| json |] -> yield json
| _ -> ()
if not (isNull dir.Parent) then
yield! loop dir.Parent
}
loop (DirectoryInfo rootDir)
match Seq.tryHead (globalJsonPaths startDir) with
| None -> None
| Some globalJson ->
try
let content = File.ReadAllText globalJson.FullName
let json = JObject.Parse content
let sdk = json.Item("sdk") :?> JObject
match sdk.Property("version") with
| null -> None
| version ->
let versionValue = version.Value.ToString()
let _ = Version.Parse(versionValue)
Some versionValue
with exn ->
failwithf "Could not parse `sdk.version` from global.json at '%s': %s" globalJson.FullName exn.Message
/// <summary>
/// Gets the DotNet SDK from the global.json, starts searching in the given directory.
/// </summary>
let internal getSDKVersionFromGlobalJsonDir startDir : string =
tryGetSDKVersionFromGlobalJsonDir startDir
|> function
| Some version -> version
| None -> failwithf "global.json not found"
/// <summary>
/// Tries the DotNet SDK from the global.json. This file can exist in the working
/// directory or any of the parent directories Returns None if global.json is not found
/// </summary>
let tryGetSDKVersionFromGlobalJson () : string option = tryGetSDKVersionFromGlobalJsonDir "."
/// <summary>
/// Gets the DotNet SDK from the global.json. This file can exist in the working
/// directory or any of the parent directories
/// </summary>
let getSDKVersionFromGlobalJson () : string = getSDKVersionFromGlobalJsonDir "."
/// <summary>
/// Get dotnet cli executable path. Probes the provided path first, then as a fallback tries the system PATH
/// </summary>
///
/// <param name="dotnetCliDir">the path to check else will probe system PATH</param>
let findPossibleDotnetCliPaths dotnetCliDir =
seq {
let fileName = if Environment.isUnix then "dotnet" else "dotnet.exe"
yield!
ProcessUtils.findFilesOnPath "dotnet"
|> Seq.filter File.Exists
|> Seq.filter (fun dotPath -> dotPath.EndsWith fileName)
let userInstallDir = defaultUserInstallDir </> fileName
if File.exists userInstallDir then
yield userInstallDir
let systemInstallDir = defaultSystemInstallDir </> fileName
if File.exists systemInstallDir then
yield systemInstallDir
match dotnetCliDir with
| Some userSetPath ->
let defaultCliPath = userSetPath @@ fileName
match File.Exists defaultCliPath with
| true -> yield defaultCliPath
| _ -> ()
| None -> ()
}
/// <summary>
/// Get .NET Core SDK download uri
/// </summary>
let private getGenericDotNetCliInstallerUrl branch installerName =
sprintf "https://raw.githubusercontent.com/dotnet/cli/%s/scripts/obtain/%s" branch installerName
let private getPowershellDotNetCliInstallerUrl branch =
getGenericDotNetCliInstallerUrl branch "dotnet-install.ps1"
let private getBashDotNetCliInstallerUrl branch =
getGenericDotNetCliInstallerUrl branch "dotnet-install.sh"
/// <summary>
/// Download .NET Core SDK installer
/// </summary>
let private downloadDotNetInstallerFromUrl (url: string) fileName =
//let url = getDotNetCliInstallerUrl branch
#if USE_HTTPCLIENT
let h = new System.Net.Http.HttpClient()
use f = File.Open(fileName, FileMode.Create)
h.GetStreamAsync(url).Result.CopyTo(f)
#else
use w = new System.Net.WebClient()
w.DownloadFile(url, fileName) // Http.RequestStream url
#endif
//use outFile = File.Open(fileName, FileMode.Create)
//installScript.ResponseStream.CopyTo(outFile)
Trace.trace (sprintf "downloaded dotnet installer (%s) to %s" url fileName)
let private md5 (data: byte array) : string =
use md5 = MD5.Create()
(StringBuilder(), md5.ComputeHash(data))
||> Array.fold (fun sb b -> sb.Append(b.ToString("x2")))
|> string
/// <summary>
/// .NET Core SDK installer download options
/// </summary>
type InstallerOptions =
{
/// Always download install script (otherwise install script is cached in temporary folder)
AlwaysDownload: bool
/// Download installer from this github branch
Branch: string
// Use the given directory to download the script into. If None the temp-dir is used
CustomDownloadDir: string option
}
/// Parameter default values.
static member Default =
{ AlwaysDownload = false
Branch = "master"
CustomDownloadDir = None }
/// <summary>
/// Download .NET Core SDK installer
/// </summary>
///
/// <param name="setParams">set download installer options</param>
let downloadInstaller setParams =
let param = InstallerOptions.Default |> setParams
let ext = if Environment.isUnix then "sh" else "ps1"
let getInstallerUrl =
if Environment.isUnix then
getBashDotNetCliInstallerUrl
else
getPowershellDotNetCliInstallerUrl
let scriptName =
sprintf "dotnet_install_%s.%s" (md5 (Encoding.ASCII.GetBytes(param.Branch))) ext
let tempDir =
match param.CustomDownloadDir with
| None -> Path.GetTempPath()
| Some d -> d
let tempInstallerScript = tempDir @@ scriptName
// maybe download installer script
if param.AlwaysDownload || not (File.Exists(tempInstallerScript)) then
let url = getInstallerUrl param.Branch
downloadDotNetInstallerFromUrl url tempInstallerScript
tempInstallerScript
/// .NET Core SDK architecture
type CliArchitecture =
/// this value represents currently running OS architecture
| Auto
| X86
| X64
/// .NET Core SDK version (used to specify version when installing .NET Core SDK)
type CliVersion =
/// Latest build on the channel (used with the -Channel option).
| Latest
/// Latest coherent build on the channel; uses the latest stable package combination (used with Branch name
/// -Channel options).
| Coherent
/// Three-part version in X.Y.Z format representing a specific build version; supersedes the -Channel option.
/// For example: 2.0.0-preview2-006120.
| Version of string
/// Take version from global.json and fail if it is not found.
| GlobalJson
/// <summary>
/// Specifies the source channel for the installation.
/// </summary>
module CliChannel =
/// Long-Term Support channel (most current supported release).
let LTS = Some "LTS"
/// Most current release.
let Current = Some "Current"
/// Two-part version in X.Y format representing a specific release (for example, 2.0 or 1.0).
let Version major minor = Some(sprintf "%d.%d" major minor)
/// Branch name. For example, release/2.0.0, release/2.0.0-preview2, or master (for nightly releases).
let Branch branchName = Some branchName
/// <summary>
/// .NET Core SDK install options
/// </summary>
[<NoComparison>]
[<NoEquality>]
type CliInstallOptions =
{
/// Custom installer obtain (download) options
InstallerOptions: InstallerOptions -> InstallerOptions
/// <summary>
/// Specifies the source channel for the installation. The possible values are:
/// <list type="number">
/// <item>
/// <c>Current</c> - Most current release.
/// </item>
/// <item>
/// <c>LTS</c> - Long-Term Support channel (most current supported release).
/// </item>
/// <item>
/// Two-part version in <c>X.Y</c> format representing a specific release (for example, <c>2.0</c> or
/// <c>1.0</c>).
/// </item>
/// <item>
/// Branch name. For example, release/2.0.0, release/2.0.0-preview2, or master (for nightly releases).
/// </item>
/// </list>
/// The default value is <c>LTS</c>. For more information on .NET support channels, see the
/// .NET Support Policy page.
/// </summary>
/// <remarks>
/// Use the <c>CliChannel</c> module, for example <c>CliChannel.Current</c>
/// </remarks>
Channel: string option
/// .NET Core SDK version
Version: CliVersion
/// Custom installation directory (for local build installation)
CustomInstallDir: string option
/// Always download and run the installer, ignore potentially existing installations.
ForceInstall: bool
/// Architecture
Architecture: CliArchitecture
/// Include symbols in the installation (Switch does not work yet. Symbols zip is not being uploaded yet)
DebugSymbols: bool
/// If set it will not perform installation but instead display what command line to use
DryRun: bool
/// Do not update path variable
NoPath: bool
/// Command working directory
WorkingDirectory: string
}
/// Parameter default values.
static member Default =
{ InstallerOptions = id
Channel = None
Version = Latest
CustomInstallDir = None
ForceInstall = false
Architecture = Auto
DebugSymbols = false
DryRun = false
NoPath = true
WorkingDirectory = "." }
/// <summary>
/// The a list of well-known versions to install
/// </summary>
module Versions =
/// .NET Core SDK install options preconfigured for preview2 tooling
let internal Preview2ToolingOptions options =
{ options with
InstallerOptions = (fun io -> { io with Branch = "v1.0.0-preview2" })
Channel = Some "preview"
Version = Version "1.0.0-preview2-003121" }
/// .NET Core SDK install options preconfigured for preview4 tooling
let internal LatestPreview4ToolingOptions options =
{ options with
InstallerOptions = (fun io -> { io with Branch = "rel/1.0.0-preview4" })
Channel = None
Version = Latest }
/// .NET Core SDK install options preconfigured for preview4 tooling
let internal Preview4_004233ToolingOptions options =
{ options with
InstallerOptions = (fun io -> { io with Branch = "rel/1.0.0-preview4" })
Channel = None
Version = Version "1.0.0-preview4-004233" }
/// .NET Core SDK install options preconfigured for preview4 tooling
let internal RC4_004771ToolingOptions options =
{ options with
InstallerOptions = (fun io -> { io with Branch = "rel/1.0.0-rc3" })
Channel = None
Version = Version "1.0.0-rc4-004771" }
/// .NET Core SDK install options preconfigured for preview4 tooling, this is marketized as v1.0.1
/// release of the .NET Core tools
let internal RC4_004973ToolingOptions options =
{ options with
InstallerOptions = (fun io -> { io with Branch = "rel/1.0.1" })
Channel = None
Version = Version "1.0.3-rc4-004973" }
let Release_1_0_4 options =
{ options with
InstallerOptions = (fun io -> { io with Branch = "release/2.0.0" })
Channel = None
Version = Version "1.0.4" }
let Release_2_0_0 options =
{ options with
InstallerOptions = (fun io -> { io with Branch = "release/2.0.0" })
Channel = None
Version = Version "2.0.0" }
let Release_2_0_3 options =
{ options with
InstallerOptions = (fun io -> { io with Branch = "release/2.0.0" })
Channel = None
Version = Version "2.0.3" }
let Release_2_1_4 options =
{ options with
InstallerOptions = (fun io -> { io with Branch = "release/2.1" })
Channel = None
Version = Version "2.1.4" }
let Release_2_1_300_RC1 option =
{ option with
InstallerOptions = (fun io -> { io with Branch = "release/2.1" })
Channel = None
Version = Version "2.1.300-rc1-008673" }
let Release_2_1_300 option =
{ option with
InstallerOptions = (fun io -> { io with Branch = "release/2.1" })
Channel = None
Version = Version "2.1.300" }
let Release_2_1_301 option =
{ option with
InstallerOptions = (fun io -> { io with Branch = "release/2.1" })
Channel = None
Version = Version "2.1.301" }
let Release_2_1_302 option =
{ option with
InstallerOptions = (fun io -> { io with Branch = "release/2.1" })
Channel = None
Version = Version "2.1.302" }
let Release_2_1_400 option =
{ option with
InstallerOptions = (fun io -> { io with Branch = "release/2.1" })
Channel = None
Version = Version "2.1.400" }
let Release_2_1_401 option =
{ option with
InstallerOptions = (fun io -> { io with Branch = "release/2.1" })
Channel = None
Version = Version "2.1.401" }
let Release_2_1_402 option =
{ option with
InstallerOptions = (fun io -> { io with Branch = "release/2.1" })
Channel = None
Version = Version "2.1.402" }
let FromGlobalJson option =
{ option with
InstallerOptions = id
Channel = None
Version = CliVersion.GlobalJson }
let private optionToParam option paramFormat =
match option with
| Some value -> sprintf paramFormat value
| None -> ""
let private boolToFlag value flagParam =
match value with
| true -> flagParam
| false -> ""
let private buildDotNetCliInstallArgs (param: CliInstallOptions) =
let versionParamValue =
match param.Version with
| Latest -> "latest"
| Coherent -> "coherent"
| Version ver -> ver
| GlobalJson -> getSDKVersionFromGlobalJson ()
// get channel value from installer branch info
let channelParamValue =
match param.Channel with
| Some ch -> ch
| None ->
let installerOptions = InstallerOptions.Default |> param.InstallerOptions
installerOptions.Branch |> String.replace "/" "-"
let architectureParamValue =
match param.Architecture with
| Auto -> None
| X86 -> Some "x86"
| X64 -> Some "x64"
Arguments.Empty
|> Arguments.appendIf true "-Verbose"
|> Arguments.appendNotEmpty "-Channel" channelParamValue
|> Arguments.appendNotEmpty "-Version" versionParamValue
|> Arguments.appendOption "-Architecture" architectureParamValue
|> Arguments.appendNotEmpty "-InstallDir" (defaultArg param.CustomInstallDir defaultUserInstallDir)
|> Arguments.appendIf param.DebugSymbols "-DebugSymbols"
|> Arguments.appendIf param.DryRun "-DryRun"
|> Arguments.appendIf param.NoPath "-NoPath"
/// dotnet restore verbosity
type Verbosity =
| Quiet
| Minimal
| Normal
| Detailed
| Diagnostic
/// <summary>
/// dotnet cli command execution options
/// </summary>
type Options =
{
/// DotNet cli executable path
DotNetCliPath: string
/// Write a global.json with the given version (required to make SDK choose the correct version)
Version: string option
/// Command working directory
WorkingDirectory: string
/// Process timeout, kills the process after the specified time
Timeout: TimeSpan option
/// Custom parameters
CustomParams: string option
/// Logging verbosity (<c>--verbosity</c>)
Verbosity: Verbosity option
/// Restore logging verbosity (<c>--diagnostics</c>)
Diagnostics: bool
/// If true the function will redirect the output of the called process (but will disable colors, false
/// by default)
RedirectOutput: bool
/// If RedirectOutput is true this flag decides if FAKE emits the output into the standard output/error
/// otherwise the flag is ignored.
/// True by default.
PrintRedirectedOutput: bool
/// Gets the environment variables that apply to this process and its child processes.
/// NOTE: Recommendation is to not use this Field, but instead use the helper function in the Proc module
/// (for example <c>Process.setEnvironmentVariable</c>)
/// NOTE: This field is ignored when UseShellExecute is true.
Environment: Map<string, string>
}
/// <summary>
/// Create a default setup for executing the <c>dotnet</c> command line.
/// This function tries to take current <c>global.json</c> into account and tries to find the correct
/// installation. To overwrite this behavior set <c>DotNetCliPath</c> manually (for example to the first
/// result of <c>ProcessUtils.findFilesOnPath "dotnet"</c>)
/// </summary>
static member Create() =
{ DotNetCliPath =
let version = tryGetSDKVersionFromGlobalJson ()
findPossibleDotnetCliPaths None
|> Seq.tryFind (fun cliPath ->
match version with
| Some version ->
version
|> Path.combine "sdk"
|> Path.combine (Path.getDirectory cliPath)
|> Directory.Exists
| None -> true)
|> Option.defaultWith (fun () -> if Environment.isUnix then "dotnet" else "dotnet.exe")
WorkingDirectory = Directory.GetCurrentDirectory()
Timeout = None
CustomParams = None
Version = None
Verbosity = None
Diagnostics = false
RedirectOutput = false
PrintRedirectedOutput = true
Environment =
Process.createEnvironmentMap ()
|> Map.remove "MSBUILD_EXE_PATH"
|> Map.remove "MSBuildExtensionsPath"
|> Map.remove "MSBuildLoadMicrosoftTargetsReadOnly"
|> Map.remove "MSBuildSDKsPath"
|> Map.remove "DOTNET_HOST_PATH" }
/// Sets the current environment variables.
member x.WithEnvironment map = { x with Environment = map }
/// Sets a value indicating whether the output for the given process is redirected.
member x.WithRedirectOutput shouldRedirect =
{ x with RedirectOutput = shouldRedirect }
/// Sets a value indicating whether the redirected output should be printed to standard-output/error stream.
member x.WithPrintRedirectedOutput shouldPrint =
{ x with PrintRedirectedOutput = shouldPrint }
/// Changes the "Common" properties according to the given function
member inline x.WithCommon f = f x
module Options =
let inline lift (f: Options -> Options) (x: ^a) =
let inline withCommon s e =
(^a: (member WithCommon: (Options -> Options) -> ^a) (s, e))
withCommon x f
let inline withEnvironment map x = lift (fun o -> o.WithEnvironment map) x
let inline withRedirectOutput shouldRedirect x =
lift (fun o -> o.WithRedirectOutput shouldRedirect) x
let inline withRedirectedOutput shouldPrint x =
lift (fun o -> o.WithPrintRedirectedOutput shouldPrint) x
let inline withWorkingDirectory wd x =
lift (fun o -> { o with WorkingDirectory = wd }) x
let inline withTimeout t x =
lift (fun o -> { o with Timeout = t }) x
let inline withDiagnostics diag x =
lift (fun o -> { o with Diagnostics = diag }) x
let inline withVerbosity verb x =
lift (fun o -> { o with Verbosity = verb }) x
let inline withCustomParams args x =
lift (fun o -> { o with CustomParams = args }) x
/// Sets custom command-line arguments expressed as a sequence of strings.
/// This function overwrites and gets overwritten by `withCustomParams`.
let inline withAdditionalArgs args x =
withCustomParams
(args
|> Args.toWindowsCommandLine
|> (function
| "" -> None
| x -> Some x))
x
let inline withDotNetCliPath path x =
lift (fun o -> { o with DotNetCliPath = path }) x
let private argList2 name values =
values |> List.collect (fun v -> [ "--" + name; v ])
let private argOption name value =
match value with
| true -> [ sprintf "--%s" name ]
| false -> []
let private argOptionExplicit name value = [ sprintf "--%s=%A" name value ]
let private buildCommonArgs (param: Options) =
[ defaultArg param.CustomParams "" |> Args.fromWindowsCommandLine |> Seq.toList
param.Verbosity
|> Option.toList
|> List.map (fun v -> v.ToString().ToLowerInvariant())
|> argList2 "verbosity" ]
|> List.concat
|> List.filter (not << String.IsNullOrEmpty)
let private buildSdkOptionsArgs (param: Options) =
[ param.Diagnostics |> argOption "--diagnostics" ]
|> List.concat
|> List.filter (not << String.IsNullOrEmpty)
let internal withGlobalJsonDispose workDir version =
let globalJsonPath =
if (Path.GetFullPath workDir).StartsWith(Path.GetFullPath ".") then
"global.json"
else
workDir </> "global.json"
let writtenJson =
match version with
| Some version when Directory.Exists workDir ->
// make sure to write global.json if we did not read the version from it
// We need to do this as the SDK will use this file to select the actual version
// See https://github.com/fsharp/FAKE/pull/1963 and related discussions
if File.Exists globalJsonPath then
false
else
let template = sprintf """{ "sdk": { "version": "%s" } }""" version
File.WriteAllText(globalJsonPath, template)
true
| _ -> false
{ new IDisposable with
member x.Dispose() =
if writtenJson then
File.delete globalJsonPath }
let internal withGlobalJson workDir version f =
use d = withGlobalJsonDispose workDir version
f ()
let internal buildCommand command args options =
let sdkOptions = buildSdkOptionsArgs options
let commonOptions = buildCommonArgs options
[ sdkOptions
command // |> Args.fromWindowsCommandLine |> Seq.toList
commonOptions
args ] // |> Args.fromWindowsCommandLine |> Seq.toList ]
|> List.concat
[<RequireQualifiedAccess>]
type FirstArgReplacement =
| UsePreviousFile
| ReplaceWith of string list
let internal runRaw (firstArg: FirstArgReplacement) options (c: CreateProcess<'a>) =
//let timeout = TimeSpan.MaxValue
let results = System.Collections.Generic.List<ConsoleMessage>()
let errorF msg =
if options.PrintRedirectedOutput then
Trace.traceError msg
results.Add(ConsoleMessage.CreateError msg)
let messageF msg =
if options.PrintRedirectedOutput then
Trace.trace msg
results.Add(ConsoleMessage.CreateOut msg)
let dir = Path.GetDirectoryName options.DotNetCliPath
let oldPath = options |> Process.getEnvironmentVariable "PATH"
let newArgs =
match firstArg with
| FirstArgReplacement.UsePreviousFile -> Arguments.withPrefix [ c.Command.Executable ] c.Command.Arguments
| FirstArgReplacement.ReplaceWith args ->
(Arguments.ofList args).ToStartInfo + " " + c.Command.Arguments.ToStartInfo
|> Arguments.OfStartInfo
let cmd = RawCommand(options.DotNetCliPath, newArgs)
c
|> CreateProcess.withCommand cmd
|> (if c.WorkingDirectory.IsNone then
CreateProcess.withWorkingDirectory options.WorkingDirectory
else
id)
|> (match options.Timeout with
| Some timeout -> CreateProcess.withTimeout timeout
| None -> id)
|> CreateProcess.withEnvironmentMap (EnvMap.ofMap options.Environment)
|> CreateProcess.setEnvironmentVariable
"PATH"
(match oldPath with
| Some oldPath -> sprintf "%s%c%s" dir Path.PathSeparator oldPath
| None -> dir)
|> CreateProcess.appendSimpleFuncs
(fun _ -> withGlobalJsonDispose options.WorkingDirectory options.Version)
(fun state p -> ())
(fun prev state exitCode -> prev)
(fun s -> s.Dispose())
|> (if options.RedirectOutput then
CreateProcess.redirectOutputIfNotRedirected
>> CreateProcess.withOutputEventsNotNull messageF errorF
else
id)
|> CreateProcess.map (fun prev -> prev, (results |> List.ofSeq))
let internal run cmdArgs options : ProcessResult =
CreateProcess.fromCommand (Command.RawCommand(options.DotNetCliPath, Arguments.ofList (List.ofSeq cmdArgs)))
|> runRaw (FirstArgReplacement.ReplaceWith []) options
|> CreateProcess.map (fun (r, results) -> ProcessResult.New r.ExitCode results)
|> Proc.run
let internal setOptions (buildOptions: Options -> Options) = buildOptions (Options.Create())
/// <summary>
/// Execute raw dotnet cli command
/// </summary>
///
/// <param name="buildOptions">build common execution options</param>
/// <param name="command">the sdk command to execute <c>test</c>, <c>new</c>, <c>build</c>, ...</param>
/// <param name="args">command arguments</param>
let exec (buildOptions: Options -> Options) (command: string) (args: string) =
let options = setOptions buildOptions
let cmdArgs =
buildCommand
(command |> Args.fromWindowsCommandLine |> Seq.toList)
(args |> Args.fromWindowsCommandLine |> Seq.toList)
options
run cmdArgs options
/// <summary>
/// Execute raw dotnet cli command.
/// Similar to 'exec' but takes a string list instead of a single string.
/// </summary>
///
/// <param name="buildOptions">build common execution options</param>
/// <param name="command">the sdk command to execute <c>test</c>, <c>new</c>, <c>build</c>, ...</param>
/// <param name="args">command arguments</param>
let private execArgsList (buildOptions: Options -> Options) (command: string) (args: string list) =
let options = setOptions buildOptions
let cmdArgs =
buildCommand (command |> Args.fromWindowsCommandLine |> Seq.toList) args options
run cmdArgs options
/// <summary>
/// Replace the current <c>CreateProcess</c> instance to run with dotnet.exe
/// </summary>
///
/// <param name="buildOptions">build common execution options</param>
/// <param name="firstArg">the first argument (like t)</param>
/// <param name="args">command arguments</param>
let prefixProcess (buildOptions: Options -> Options) (firstArgs: string list) (c: CreateProcess<'a>) =
let options = setOptions buildOptions
c
|> runRaw (FirstArgReplacement.ReplaceWith firstArgs) options
|> CreateProcess.map fst
/// <summary>
/// Setup the environment (<c>PATH</c> and <c>DOTNET_ROOT</c>) in such a way that started processes use the given
/// dotnet SDK installation. This is useful for example when using fable,
/// see <a href="https://github.com/fsharp/FAKE/issues/2405">issue #2405</a>
/// </summary>
///
/// <param name="install">The SDK to use (result of <c>DotNet.install</c>)</param>
let setupEnv (install: Options -> Options) =
let options = setOptions install
let dotnetTool = Path.GetFullPath options.DotNetCliPath
let dotnetFolder = Path.GetDirectoryName dotnetTool
let currentPath = Environment.environVar "PATH"
match currentPath with
| null
| "" -> Environment.setEnvironVar "PATH" dotnetFolder
| _ when not (currentPath.Contains dotnetFolder) ->
Environment.setEnvironVar "PATH" (dotnetFolder + string Path.PathSeparator + currentPath)
| _ -> ()
let currentDotNetRoot = Environment.environVar "DOTNET_ROOT"
let realFolder =
if not Environment.isWindows then
#if !FX_NO_POSIX
// resolve potential symbolic link to the real location
// https://stackoverflow.com/questions/58326739/how-can-i-find-the-target-of-a-linux-symlink-in-c-sharp
Mono.Unix.UnixPath.GetRealPath(dotnetTool) |> Path.GetDirectoryName
#else
eprintf
"Setting 'DOTNET_ROOT' to '%s' this might be wrong as we didn't follow the symlink. Please upgrade to netcore."
dotnetFolder
dotnetFolder
#endif
else
dotnetFolder
if
String.IsNullOrEmpty currentDotNetRoot
|| not (currentDotNetRoot.Contains realFolder)
then
Environment.setEnvironVar "DOTNET_ROOT" realFolder
/// <summary>
/// dotnet --info command options
/// </summary>
type InfoOptions =
{
/// Common tool options
Common: Options
}
/// Parameter default values.
static member Create() =
{ Common = Options.Create().WithRedirectOutput(true).WithPrintRedirectedOutput(false) }
/// Gets the current environment
member x.Environment = x.Common.Environment
/// Sets the current environment variables.
member x.WithEnvironment map =
{ x with Common = { x.Common with Environment = map } }
/// Sets a value indicating whether the output for the given process is redirected.
member x.WithRedirectOutput shouldRedirect =
{ x with Common = x.Common.WithRedirectOutput shouldRedirect }
/// Changes the "Common" properties according to the given function
member inline x.WithCommon f = { x with Common = f x.Common }
/// <summary>
/// dotnet info result
/// </summary>
type InfoResult =
{
/// Common tool options
RID: string
}
/// <summary>
/// Execute dotnet --info command
/// </summary>
///
/// <param name="setParams">set info command parameters</param>
let info setParams =
use __ = Trace.traceTask "DotNet:info" "running dotnet --info"
let param = InfoOptions.Create() |> setParams
let args = "--info" // project (buildPackArgs param)
let result = exec (fun _ -> param.Common) "" args
let rawOutput =
result.Results
|> Seq.map (fun c -> sprintf "%s: %s" (if c.IsError then "stderr: " else "stdout: ") c.Message)
|> fun s -> String.Join("\n", s)
if not result.OK then
failwithf "dotnet --info failed with code '%i': \n%s" result.ExitCode rawOutput
let rid =
result.Messages
|> Seq.tryFind (fun m -> m.Contains "RID:")
|> Option.map (fun line -> line.Split([| ':' |]).[1].Trim())
if rid.IsNone then
failwithf "could not read rid from output: \n%s" rawOutput
__.MarkSuccess()
{ RID = rid.Value }
/// <summary>
/// dotnet --version command options
/// </summary>
type VersionOptions =
{
/// Common tool options
Common: Options
}
/// Parameter default values.
static member Create() =
{ Common = Options.Create().WithRedirectOutput true }
/// Gets the current environment
member x.Environment = x.Common.Environment
/// Changes the "Common" properties according to the given function
member inline x.WithCommon f = { x with Common = f x.Common }
/// Sets the current environment variables.
member x.WithEnvironment map =
x.WithCommon(fun c -> { c with Environment = map })
/// Sets a value indicating whether the output for the given process is redirected.
member x.WithRedirectOutput shouldRedirect =
{ x with Common = x.Common.WithRedirectOutput shouldRedirect }
/// <summary>
/// dotnet info result
/// </summary>
type VersionResult = string
/// <summary>
/// Execute dotnet --version command
/// </summary>
///
/// <param name="setParams">set version command parameters</param>
let getVersion setParams =
use __ = Trace.traceTask "DotNet:version" "running dotnet --version"
let param = VersionOptions.Create() |> setParams
let args = "--version"
let result = exec (fun _ -> param.Common) "" args
if not result.OK then
failwithf "dotnet --version failed with code %i" result.ExitCode
let version = result.Messages |> String.separated "\n" |> String.trim
if String.isNullOrWhiteSpace version then
failwithf "could not read version from output: \n%s" (String.Join("\n", result.Messages))
__.MarkSuccess()
version
/// <summary>
/// Install .NET Core SDK if required
/// </summary>
///
/// <param name="setParams">set installation options</param>
let install setParams : Options -> Options =
let param = CliInstallOptions.Default |> setParams
let dir = defaultArg param.CustomInstallDir defaultUserInstallDir
let checkVersion, fromGlobalJson =
match param.Version with
| Version version -> Some version, false
| CliVersion.Coherent -> None, false
| CliVersion.Latest -> None, false
| CliVersion.GlobalJson -> Some(getSDKVersionFromGlobalJson ()), true
let dotnetInstallations =
if param.ForceInstall then
Seq.empty
else
findPossibleDotnetCliPaths (Some dir)