-
Notifications
You must be signed in to change notification settings - Fork 586
/
NuGet.fs
1301 lines (1049 loc) · 47.6 KB
/
NuGet.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.NuGet
/// <summary>
/// Contains helper functions and task which allow to inspect, create and publish
/// <a href="https://www.nuget.org/">NuGet</a> packages.
/// There is also a tutorial about <a href="/articles/dotnet-nuget.html">nuget package creating</a> available.
/// </summary>
module NuGet =
open Fake.IO
open Fake.IO.FileSystemOperators
open Fake.Core
open System
open System.IO
open System.Text
open System.Xml.Linq
open Fake.DotNet.NuGet.Restore
type NugetDependencies = (string * string) list
type NugetFrameworkDependencies =
{ FrameworkVersion: string
Dependencies: NugetDependencies }
type NugetReferences = string list
type NugetFrameworkReferences =
{ FrameworkVersion: string
References: NugetReferences }
type NugetFrameworkAssemblyReferences =
{ FrameworkVersions: string list
AssemblyName: string }
/// Specifies that the package contains sources and symbols.
type NugetSymbolPackage =
/// Do not build symbol packages
| None = 0
/// Build a symbol package using a project file, if provided
| ProjectFile = 1
/// Build a symbol package using the nuspec file
| Nuspec = 2
type internal ToolOptions =
{
/// The NuGet executable path
ToolPath: string
/// The NuGet command to execute
Command: string
/// The working directory to execute the command in
WorkingDir: string
/// Mark if to use full framework or not
IsFullFramework: bool
}
static member Create toolPath command workingDir isFullFramework =
{ ToolPath = toolPath
Command = command
WorkingDir = workingDir
IsFullFramework = isFullFramework }
/// <summary>
/// Nuget base parameter type
/// </summary>
type NuGetParams =
{
/// The path to the NuGet executable
ToolPath: string
/// The timeout to use to restrict NuGet command run time
TimeOut: TimeSpan
/// The package version
Version: string
/// The list of authors of the package
Authors: string list
/// The project name of the package
Project: string
/// The package title
Title: string
/// The summary description of the package
Summary: string
/// The descriptive text of the package
Description: string
/// Tags referring to the package
Tags: string
/// The release notes file path of the package
ReleaseNotes: string
/// The copyright text of the package
Copyright: string
/// The working directory to execute command in
WorkingDir: string
/// Sets the base path of the files defined in the .nuspec file.
BasePath: string option
/// Specifies the folder in which the created package is stored. If no folder is specified,
/// the current folder is used.
OutputPath: string
/// Specifies the server URL. NuGet identifies a UNC or local folder source and simply
/// copies the file there instead of pushing it using HTTP
PublishUrl: string
/// NuGet API access key
AccessKey: string
/// Specifies the symbol server URL.
SymbolPublishUrl: string
/// NuGet symbol API access key
SymbolAccessKey: string
/// Prevents default exclusion of NuGet package files and files and folders starting with a dot,
/// such as <c>.svn</c> and <c>.gitignore</c>.
NoDefaultExcludes: bool
/// Specifies that pack should not run package analysis after building the package.
NoPackageAnalysis: bool
/// The project file to use
ProjectFile: string
/// The list of dependencies of the package. <c>dependencies</c>
Dependencies: NugetDependencies
/// The list of dependencies of the package grouped by Framework. <c>dependencies</c>
DependenciesByFramework: NugetFrameworkDependencies list
/// The list of packages that reference the package. <c>references</c>
References: NugetReferences
/// The list of packages that reference the package grouped by Framework. <c>references</c>
ReferencesByFramework: NugetFrameworkReferences list
/// The list of <c>frameworkAssemblies</c>
FrameworkAssemblies: NugetFrameworkAssemblyReferences list
/// Mark if to include list of projects that reference the package
IncludeReferencedProjects: bool
/// mark if to publish a trial version of the package
PublishTrials: int
/// mark if to publish the package or not
Publish: bool
/// `NugetSymbolPackage` parameters
SymbolPackage: NugetSymbolPackage
/// Should appear last on the command line after other options. Specifies a list of properties
/// that override values in the project file
Properties: list<string * string>
/// The list of files to include or exclude. <c>files</c>
Files: list<string * string option * string option>
/// The list of content files to include or exclude. <c>contentFiles</c>
ContentFiles: list<string * string option * string option * bool option * bool option>
/// The package language. <c>language</c>
Language: string
}
/// NuGet default parameters
let NuGetDefaults () =
{ ToolPath = findNuget (Shell.pwd () @@ "tools" @@ "NuGet")
TimeOut = TimeSpan.FromMinutes 5.
Version =
if not BuildServer.isLocalBuild then
BuildServer.buildVersion
else
"0.1.0.0"
Authors = []
Project = ""
Title = ""
Summary = null
ProjectFile = null
Description = null
Tags = null
ReleaseNotes = null
Copyright = null
Dependencies = []
DependenciesByFramework = []
References = []
ReferencesByFramework = []
FrameworkAssemblies = []
IncludeReferencedProjects = false
BasePath = None
OutputPath = "./NuGet"
WorkingDir = "./NuGet"
PublishUrl = "https://www.nuget.org/api/v2/package"
AccessKey = null
SymbolPublishUrl = null
SymbolAccessKey = null
NoDefaultExcludes = false
NoPackageAnalysis = false
PublishTrials = 5
Publish = false
SymbolPackage = NugetSymbolPackage.ProjectFile
Properties = []
Files = []
ContentFiles = []
Language = null }
/// <summary>
/// Creates a string which tells NuGet that you require exactly this package version.
/// </summary>
///
/// <param name="version">The exact version to require</param>
let RequireExactly version = sprintf "[%s]" version
/// NuGet package versioning breaking changes point
type BreakingPoint =
/// Breaking on major component of SemVer
| SemVer
/// Breaking on minor component of SemVer
| Minor
/// Breaking on patch component of SemVer
| Patch
/// <summary>
/// Require a version by given breaking point and version
/// See <a href="https://docs.nuget.org/create/versioning">NuGet Versioning</a>
/// </summary>
///
/// <param name="breakingPoint">The breaking point for version range. See <c>BreakingPoint</c> type</param>
/// <param name="version">The version to use to find the range</param>
let RequireRange breakingPoint version =
let v = SemVer.parse version
match breakingPoint with
| SemVer -> sprintf "[%s,%d.0)" version (v.Major + 1u)
| Minor -> // Like Semver but we assume that the increase of a minor version is already breaking
sprintf "[%s,%d.%d)" version v.Major (v.Minor + 1u)
| Patch -> // Every update breaks
version |> RequireExactly
let private packageFileName parameters =
sprintf "%s.%s.nupkg" parameters.Project parameters.Version
/// <summary>
/// Gets the version no. for a given package in the deployments folder
/// </summary>
///
/// <param name="deploymentsDir">The deployment directory to look into</param>
/// <param name="package">The package id to look for</param>
let GetPackageVersion deploymentsDir package =
try
if Directory.Exists deploymentsDir |> not then
failwithf
"Package %s was not found, because the deployment directory %s doesn't exist."
package
deploymentsDir
let version =
let dirs = Directory.GetDirectories(deploymentsDir, sprintf "%s*" package)
if Seq.isEmpty dirs then
failwithf "Package %s was not found." package
let folder = Seq.head dirs
let index = folder.LastIndexOf package + package.Length + 1
if index < folder.Length then
folder.Substring index
else
let nuspec = Directory.GetFiles(folder, sprintf "%s.nuspec" package) |> Seq.head
let doc = XDocument.Load(nuspec)
let vers = doc.Descendants(XName.Get("version", doc.Root.Name.NamespaceName))
(Seq.head vers).Value
Trace.logfn "Version %s found for package %s" version package
version
with exn ->
Exception("Could not detect package version for " + package, exn) |> raise
let private createNuSpecFromTemplate parameters (templateNuSpec: FileInfo) =
let specFile =
parameters.WorkingDir
@@ (templateNuSpec.Name.Replace("nuspec", "") + parameters.Version + ".nuspec")
|> Path.getFullName
Trace.tracefn "Creating .nuspec file at %s" specFile
templateNuSpec.CopyTo(specFile, true) |> ignore
let getFrameworkGroup (frameworkTags: (string * string) seq) =
frameworkTags
|> Seq.map (fun (frameworkVersion, tags) ->
if String.isNullOrEmpty frameworkVersion then
sprintf "<group>%s</group>" tags
else
sprintf "<group targetFramework=\"%s\">%s</group>" frameworkVersion tags)
|> String.toLines
let getGroup items toTags =
if List.isEmpty items then
""
else
sprintf "<group>%s</group>" (items |> toTags)
let getReferencesTags references =
references
|> Seq.map (fun assembly -> sprintf "<reference file=\"%s\" />" assembly)
|> String.toLines
let references = getGroup parameters.References getReferencesTags
let referencesByFramework =
parameters.ReferencesByFramework
|> Seq.map (fun x -> (x.FrameworkVersion, getReferencesTags x.References))
|> getFrameworkGroup
let referencesXml =
sprintf "<references>%s</references>" (references + referencesByFramework)
let getFrameworkAssemblyTags references =
references
|> Seq.map (fun x ->
if List.isEmpty x.FrameworkVersions then
sprintf "<frameworkAssembly assemblyName=\"%s\" />" x.AssemblyName
else
sprintf
"<frameworkAssembly assemblyName=\"%s\" targetFramework=\"%s\" />"
x.AssemblyName
(x.FrameworkVersions |> String.separated ", "))
|> String.toLines
let frameworkAssembliesXml =
if List.isEmpty parameters.FrameworkAssemblies then
""
else
sprintf
"<frameworkAssemblies>%s</frameworkAssemblies>"
(parameters.FrameworkAssemblies |> getFrameworkAssemblyTags)
let getDependenciesTags dependencies =
dependencies
|> Seq.map (fun (package, version) -> sprintf "<dependency id=\"%s\" version=\"%s\" />" package version)
|> String.toLines
let dependencies = getGroup parameters.Dependencies getDependenciesTags
let dependenciesByFramework =
parameters.DependenciesByFramework
|> Seq.map (fun x -> (x.FrameworkVersion, getDependenciesTags x.Dependencies))
|> getFrameworkGroup
let dependenciesXml =
sprintf "<dependencies>%s</dependencies>" (dependencies + dependenciesByFramework)
let contentFilesTags =
parameters.ContentFiles
|> Seq.map (fun (incl, exclArg, buildActionArg, copyToOutputArg, flattenArg) ->
let excl =
match exclArg with
| Some x -> sprintf " exclude=\"%s\"" x
| _ -> String.Empty
let buildAction =
match buildActionArg with
| Some x -> sprintf " buildAction=\"%s\"" x
| _ -> String.Empty
let copyToOutput =
match copyToOutputArg with
| Some x -> sprintf " copyToOutput=\"%b\"" x
| _ -> String.Empty
let flatten =
match flattenArg with
| Some x -> sprintf " flatten=\"%b\"" x
| _ -> String.Empty
sprintf "<files include=\"%s\"%s%s%s%s />" incl excl buildAction copyToOutput flatten)
|> String.toLines
let contentFilesXml = sprintf "<contentFiles>%s</contentFiles>" contentFilesTags
let filesTags =
parameters.Files
|> Seq.map (fun (source, target, exclude) ->
let excludeStr =
if exclude.IsSome then
sprintf " exclude=\"%s\"" exclude.Value
else
String.Empty
let targetStr =
if target.IsSome then
sprintf " target=\"%s\"" target.Value
else
String.Empty
sprintf "<file src=\"%s\"%s%s />" source targetStr excludeStr)
|> String.toLines
let filesXml = sprintf "<files>%s</files>" filesTags
let xmlEncode (notEncodedText: string) =
if String.IsNullOrWhiteSpace notEncodedText then
""
else
XText(notEncodedText).ToString().Replace("�", "ß")
let toSingleLine (text: string) =
if isNull text then
null
else
text.Replace("\r", "").Replace("\n", "").Replace(" ", " ")
let replacements =
[ "@build.number@", parameters.Version
"@title@", parameters.Title
"@authors@", parameters.Authors |> String.separated ", "
"@project@", parameters.Project
"@summary@", parameters.Summary |> toSingleLine
"@description@", parameters.Description |> toSingleLine
"@tags@", parameters.Tags
"@releaseNotes@", parameters.ReleaseNotes
"@copyright@", parameters.Copyright
"@language@", parameters.Language ]
|> List.map (fun (placeholder, replacement) -> placeholder, xmlEncode replacement)
|> List.append
[ "@dependencies@", dependenciesXml
"@references@", referencesXml
"@frameworkAssemblies@", frameworkAssembliesXml
"@contentFiles@", contentFilesXml
"@files@", filesXml ]
Templates.replaceInFiles replacements [ specFile ]
Trace.tracefn "Created nuspec file %s" specFile
specFile
let private createNuSpecFromTemplateIfNotProjFile parameters nuSpecOrProjFile =
let nuSpecOrProjFileInfo = FileInfo.ofPath nuSpecOrProjFile
match nuSpecOrProjFileInfo.Extension.ToLower().EndsWith("proj") with
| true -> None
| false -> Some(createNuSpecFromTemplate parameters nuSpecOrProjFileInfo)
let private propertiesParam =
function
| [] -> ""
| lst ->
"-Properties "
+ (lst |> List.map (fun p -> (fst p) + "=\"" + (snd p) + "\"") |> String.concat ";")
/// Creates a NuGet package without templating (including symbols package if enabled)
let private pack parameters nuspecFile =
if String.isNotNullOrEmpty parameters.AccessKey then
TraceSecrets.register "<NuGetKey>" parameters.AccessKey
if String.isNotNullOrEmpty parameters.SymbolAccessKey then
TraceSecrets.register "<NuGetSymbolKey>" parameters.SymbolAccessKey
let nuspecFile = Path.getFullName nuspecFile
let properties = propertiesParam parameters.Properties
let basePath =
parameters.BasePath
|> Option.map (sprintf "-BasePath \"%s\"")
|> Option.defaultValue ""
let outputPath =
(Path.getFullName (parameters.OutputPath.TrimEnd('\\').TrimEnd('/')))
let packageAnalysis =
if parameters.NoPackageAnalysis then
"-NoPackageAnalysis"
else
""
let defaultExcludes =
if parameters.NoDefaultExcludes then
"-NoDefaultExcludes"
else
""
let includeReferencedProjects =
if parameters.IncludeReferencedProjects then
"-IncludeReferencedProjects"
else
""
if Directory.Exists parameters.OutputPath |> not then
failwithf "OutputDir %s does not exist." parameters.OutputPath
let execute args =
let errorResults = System.Collections.Generic.List<string>()
let outputResults = System.Collections.Generic.List<string>()
let errorF msg = errorResults.Add msg
let messageF msg = outputResults.Add msg
let processResult =
CreateProcess.fromRawCommandLine parameters.ToolPath args
|> CreateProcess.withTimeout parameters.TimeOut
|> CreateProcess.withFramework
|> CreateProcess.withWorkingDirectory (Path.getFullName parameters.WorkingDir)
|> CreateProcess.redirectOutput
|> CreateProcess.withOutputEventsNotNull messageF errorF
|> Proc.run
if processResult.ExitCode <> 0 || errorResults.Count > 0 then
failwithf
"Error during NuGet package creation. %s %s\r\n%s"
parameters.ToolPath
args
(String.toLines errorResults)
match parameters.SymbolPackage with
| NugetSymbolPackage.ProjectFile ->
if not (String.isNullOrEmpty parameters.ProjectFile) then
sprintf
"pack -Symbols -Version %s -OutputDirectory \"%s\" \"%s\" %s %s %s %s %s"
parameters.Version
outputPath
(Path.getFullName parameters.ProjectFile)
packageAnalysis
defaultExcludes
includeReferencedProjects
properties
basePath
|> execute
sprintf
"pack -Version %s -OutputDirectory \"%s\" \"%s\" %s %s %s %s %s"
parameters.Version
outputPath
nuspecFile
packageAnalysis
defaultExcludes
includeReferencedProjects
properties
basePath
|> execute
| NugetSymbolPackage.Nuspec ->
sprintf
"pack -Symbols -Version %s -OutputDirectory \"%s\" \"%s\" %s %s %s %s %s"
parameters.Version
outputPath
nuspecFile
packageAnalysis
defaultExcludes
includeReferencedProjects
properties
basePath
|> execute
| _ ->
sprintf
"pack -Version %s -OutputDirectory \"%s\" \"%s\" %s %s %s %s %s"
parameters.Version
outputPath
nuspecFile
packageAnalysis
defaultExcludes
includeReferencedProjects
properties
basePath
|> execute
/// <summary>
/// dotnet nuget push command options
/// </summary>
type NuGetPushParams =
{
/// Disables buffering when pushing to an HTTP(S) server to reduce memory usage.
DisableBuffering: bool
/// The API key for the server
ApiKey: string option
/// Doesn't push symbols (even if present).
NoSymbols: bool
/// Doesn't append "api/v2/package" to the source URL.
NoServiceEndpoint: bool
/// Specifies the server URL. This option is required unless DefaultPushSource config value is set in
/// the NuGet config file.
Source: string option
/// The API key for the symbol server.
SymbolApiKey: string option
/// Specifies the symbol server URL.
SymbolSource: string option
/// Specifies the timeout for pushing to a server.
Timeout: TimeSpan option
/// Number of times to retry pushing the package
PushTrials: int
}
static member Create() =
{ DisableBuffering = false
ApiKey = None
NoSymbols = false
NoServiceEndpoint = false
Source = None
SymbolApiKey = None
SymbolSource = None
Timeout = None
PushTrials = 5 }
type NuGetParams with
member internal x.NuGetPushOptions =
let normalize str =
if String.isNullOrEmpty str then None else Some str
{ DisableBuffering = false
ApiKey = normalize x.AccessKey
NoSymbols = false
NoServiceEndpoint = false
Source = normalize x.PublishUrl
SymbolApiKey = normalize x.SymbolAccessKey
SymbolSource = normalize x.SymbolPublishUrl
Timeout = Some x.TimeOut
PushTrials = x.PublishTrials }
member internal x.ToolOptions = ToolOptions.Create x.ToolPath "push" x.WorkingDir true
member internal x.Nupkg = (x.OutputPath @@ packageFileName x |> Path.getFullName)
let internal toPushCliArgs param =
let toSeconds (t: TimeSpan) = t.TotalSeconds |> int |> string
let stringToArg name values =
values |> List.collect (fun v -> [ "-" + name; v ])
let boolToArg name value =
match value with
| true -> [ sprintf "-%s" name ]
| false -> []
[ param.ApiKey |> Option.toList |> stringToArg "ApiKey"
param.DisableBuffering |> boolToArg "DisableBuffering"
param.NoSymbols |> boolToArg "NoSymbols"
param.NoServiceEndpoint |> boolToArg "NoServiceEndpoint"
param.Source |> Option.toList |> stringToArg "Source"
param.SymbolApiKey |> Option.toList |> stringToArg "SymbolApiKey"
param.SymbolSource |> Option.toList |> stringToArg "SymbolSource"
param.Timeout |> Option.map toSeconds |> Option.toList |> stringToArg "Timeout" ]
|> List.concat
|> List.filter (not << String.IsNullOrEmpty)
let rec private push (options: ToolOptions) (parameters: NuGetPushParams) nupkg =
parameters.ApiKey
|> Option.iter (fun key -> TraceSecrets.register "<NuGetKey>" key)
parameters.SymbolApiKey
|> Option.iter (fun key -> TraceSecrets.register "<NuGetSymbolKey>" key)
let pushArgs = parameters |> toPushCliArgs |> Args.toWindowsCommandLine
let args = sprintf "%s \"%s\" %s" options.Command nupkg pushArgs
sprintf
"%s %s in WorkingDir: %s Trials left: %d"
options.ToolPath
args
(Path.getFullName options.WorkingDir)
parameters.PushTrials
|> TraceSecrets.guardMessage
|> Trace.trace
try
let result =
CreateProcess.fromRawCommandLine options.ToolPath args
|> CreateProcess.withWorkingDirectory options.WorkingDir
|> CreateProcess.withTimeout (parameters.Timeout |> Option.defaultValue (TimeSpan.FromMinutes 5.0))
|> (fun p ->
if options.IsFullFramework then
p |> CreateProcess.withFramework
else
p)
|> Proc.run
if result.ExitCode <> 0 then
sprintf "Error during NuGet push. %s %s" options.ToolPath args
|> TraceSecrets.guardMessage
|> failwith
with _ when parameters.PushTrials > 0 ->
push options { parameters with PushTrials = parameters.PushTrials - 1 } nupkg
let private publish (parameters: NuGetParams) =
push parameters.ToolOptions parameters.NuGetPushOptions parameters.Nupkg
/// push package to symbol server (and try again if something fails)
let rec private publishSymbols parameters =
let args =
sprintf "push -source %s \"%s\" %s" parameters.PublishUrl (packageFileName parameters) parameters.AccessKey
Trace.tracefn
"%s %s in WorkingDir: %s Trials left: %d"
parameters.ToolPath
args
(Path.getFullName parameters.WorkingDir)
parameters.PublishTrials
try
let result =
let tracing = Process.shouldEnableProcessTracing ()
try
Process.setEnableProcessTracing false
let processResult =
CreateProcess.fromRawCommandLine parameters.ToolPath args
|> CreateProcess.withTimeout parameters.TimeOut
|> CreateProcess.withFramework
|> CreateProcess.withWorkingDirectory (Path.getFullName parameters.WorkingDir)
|> Proc.run
processResult.ExitCode
finally
Process.setEnableProcessTracing tracing
if result <> 0 then
sprintf "Error during NuGet symbol push. %s %s" parameters.ToolPath args
|> TraceSecrets.guardMessage
|> failwith
with _ when parameters.PublishTrials > 0 ->
publish { parameters with PublishTrials = parameters.PublishTrials - 1 }
/// <summary>
/// Creates a new NuGet package based on the given .nuspec or project file.
/// The .nuspec / projectfile is passed as-is (no templating is performed)
/// </summary>
///
/// <param name="setParams">Function used to manipulate the default NuGet parameters.</param>
/// <param name="nuspecOrProjectFile">The .nuspec or project file name.</param>
let NuGetPackDirectly setParams nuspecOrProjectFile =
use __ = Trace.traceTask "NuGetPackDirectly" nuspecOrProjectFile
let parameters = NuGetDefaults() |> setParams
try
pack parameters nuspecOrProjectFile
with exn ->
(if not (isNull exn.InnerException) then
exn.Message + "\r\n" + exn.InnerException.Message
else
exn.Message)
|> TraceSecrets.guardMessage
|> failwith
__.MarkSuccess()
/// <summary>
/// Creates a new NuGet package based on the given .nuspec or project file.
/// Template parameter substitution is performed when passing a .nuspec
/// </summary>
///
/// <param name="setParams">Function used to manipulate the default NuGet parameters.</param>
/// <param name="nuspecOrProjectFile">The .nuspec or project file name.</param>
let NuGetPack setParams nuspecOrProjectFile =
use __ = Trace.traceTask "NuGetPack" nuspecOrProjectFile
let parameters = NuGetDefaults() |> setParams
try
match (createNuSpecFromTemplateIfNotProjFile parameters nuspecOrProjectFile) with
| Some nuspecTemplateFile ->
pack parameters nuspecTemplateFile
File.delete nuspecTemplateFile
| None -> pack parameters nuspecOrProjectFile
with exn ->
(if not (isNull exn.InnerException) then
exn.Message + "\r\n" + exn.InnerException.Message
else
exn.Message)
|> TraceSecrets.guardMessage
|> failwith
__.MarkSuccess()
/// <summary>
/// Publishes a NuGet package to the nuget server.
/// </summary>
///
/// <param name="setParams">Function used to manipulate the default NuGet parameters.</param>
let NuGetPublish setParams =
let parameters = NuGetDefaults() |> setParams
use __ = Trace.traceTask "NuGet-Push" (packageFileName parameters)
try
publish parameters
with exn ->
if not (isNull exn.InnerException) then
exn.Message + "\r\n" + exn.InnerException.Message
else
exn.Message
|> TraceSecrets.guardMessage
|> failwith
__.MarkSuccess()
/// <summary>
/// Creates a new NuGet package, and optionally publishes it.
/// Template parameter substitution is performed when passing a .nuspec
/// </summary>
///
/// <param name="setParams">Function used to manipulate the default NuGet parameters.</param>
/// <param name="nuspecOrProjectFile">The .nuspec file name.</param>
let NuGet setParams nuspecOrProjectFile =
use __ = Trace.traceTask "NuGet" nuspecOrProjectFile
let parameters = NuGetDefaults() |> setParams
try
match (createNuSpecFromTemplateIfNotProjFile parameters nuspecOrProjectFile) with
| Some nuspecTemplateFile ->
pack parameters nuspecTemplateFile
File.delete nuspecTemplateFile
| None -> pack parameters nuspecOrProjectFile
if parameters.Publish then
publish parameters
if not (isNull parameters.ProjectFile) then
publishSymbols parameters
with exn ->
(if not (isNull exn.InnerException) then
exn.Message + "\r\n" + exn.InnerException.Message
else
exn.Message)
|> TraceSecrets.guardMessage
|> failwith
__.MarkSuccess()
/// <summary>
/// NuSpec metadata type Please see
/// <a href="https://docs.microsoft.com/en-us/nuget/reference/nuspec">NuSpec reference</a>
/// </summary>
type NuSpecPackage =
{
/// The case-insensitive package identifier
Id: string
/// The version of the package, following the major.minor.patch pattern. Version numbers may
/// include a pre-release suffix
Version: string
/// A comma-separated list of packages authors, matching the profile names on nuget.org.
Authors: string
/// A comma-separated list of the package creators using profile names on nuget.org.
Owners: string
/// A URL for the package's home page, often shown in UI displays as well as nuget.org.
Url: string
/// Holds if the package is the latest version published or not
IsLatestVersion: bool
/// The creation date of the package
Created: DateTime
/// The published date of the package
Published: DateTime
/// The unique hash of the package
PackageHash: string
/// The package hash algorithm used
PackageHashAlgorithm: string
/// package license URL
LicenseUrl: string
/// The package project URL
ProjectUrl: string
/// Mark if the package need usage acceptance before using it by license
RequireLicenseAcceptance: bool
/// The package description
Description: string
/// The package language
Language: string
/// The release notes file of the package
ReleaseNotes: string
/// tags referencing the package
Tags: string
}
member x.Name = sprintf "%s %s" x.Id x.Version
override x.ToString() = x.Name
member x.DirectoryName = sprintf "%s.%s" x.Id x.Version
member x.FileName = sprintf "%s.%s.nupkg" x.Id x.Version
/// <summary>
/// Parses nuspec metadata from a nuspec file.
/// </summary>
///
/// <param name="nuspec">The .nuspec file content.</param>
let getNuspecProperties (nuspec: string) =
let doc = Xml.createDoc nuspec
let namespaces =
[ "x", "http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd"
"y", "http://schemas.microsoft.com/packaging/2011/08/nuspec.xsd"
"default", ""
"inDoc", doc.DocumentElement.NamespaceURI ]
let getValue name =
let getWith ns =
try
doc
|> Xml.selectXPathValue (sprintf "%s:metadata/%s:%s" ns ns name) namespaces
|> Some
with exn ->
None
namespaces
|> Seq.map fst
|> Seq.tryPick (fun ns -> getWith ns)
|> (fun x -> if x.IsSome then x.Value else "")
{ Id = getValue "id"
Version = getValue "version"
Authors = getValue "authors"
Owners = getValue "owners"
LicenseUrl = getValue "licenseUrl"
ProjectUrl = getValue "projectUrl"
RequireLicenseAcceptance = (getValue "requireLicenseAcceptance").ToLower() = "true"
Description = getValue "description"
Language = getValue "language"
Tags = getValue "tags"
ReleaseNotes = getValue "releaseNotes"
Url = String.Empty
IsLatestVersion = false
Created = DateTime.MinValue
Published = DateTime.MinValue
PackageHash = String.Empty
PackageHashAlgorithm = String.Empty }
/// <summary>
/// NuGet package information
/// </summary>
type NugetPackageInfo =
{
/// The case-insensitive package identifier
Id: string
/// The version of the package, following the major.minor.patch pattern. Version numbers may
/// include a pre-release suffix
Version: string
/// The package description
Description: string
/// The package summary notes
Summary: string
/// Holds if the package is the latest version published or not
IsLatestVersion: bool
/// A comma-separated list of packages authors, matching the profile names on nuget.org.
Authors: string
/// A comma-separated list of the package creators using profile names on nuget.org.
Owners: string
/// tags referencing the package
Tags: string
/// The package project URL
ProjectUrl: string
/// package license URL
LicenseUrl: string
/// The package title
Title: string
}
/// Default NuGet feed. Using V3 feed: <c>https://api.nuget.org/v3/index.json</c>
let galleryV3 = "https://api.nuget.org/v3/index.json"
#if NETSTANDARD