/
Build.fsx
462 lines (379 loc) · 20.8 KB
/
Build.fsx
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
#r @"build/tools/FAKE.Core/tools/FakeLib.dll"
#r @"build/tools/FAKE.Core/tools/ICSharpCode.SharpZipLib.dll"
open Fake
open Fake.AppVeyor
open Fake.DotNetCli
open Fake.Testing
open System
open System.Diagnostics;
open System.Text.RegularExpressions
let buildDir = getBuildParamOrDefault "BuildDir" "build"
let buildToolsDir = buildDir </> "tools"
let testResultsFolder = buildDir </> "TestResults" |> FullName
let nuGetOutputFolder = buildDir </> "NuGetPackages"
let nuGetPackages = !! (nuGetOutputFolder </> "*.nupkg" )
// Skip symbol packages because NuGet publish symbols automatically when package is published.
-- (nuGetOutputFolder </> "*.symbols.nupkg")
let solutionToBuild = "Src/All.sln"
let configuration = getBuildParamOrDefault "BuildConfiguration" "Release"
let bakFileExt = ".orig"
let repositoryUrlsOnGitHub = [ "git@github.com:AutoFixture/AutoFixture.git"
"https://github.com/AutoFixture/AutoFixture.git" ]
type BuildVersionCalculationSource = { major: int; minor: int; revision: int; preSuffix: string;
commitsNum: int; sha: string; buildNumber: int }
let getVersionSourceFromGit buildNumber =
// The --fist-parent flag is required to correctly work for vNext branch.
// Example of output for a release tag: v3.50.2-288-g64fd5c5b, for a prerelease tag: v3.50.2-alpha1-288-g64fd5c5b.
let desc = Git.CommandHelper.runSimpleGitCommand "" "describe --tags --long --abbrev=40 --first-parent --match=v*"
// Previously repository contained a few broken tags like "v.3.21.1". They were removed, but could still exist
// in forks. We handle them as well to not fail on such repositories.
let result = Regex.Match(desc,
@"^v(\.)?(?<maj>\d+)\.(?<min>\d+)\.(?<rev>\d+)(?<pre>-\w+\d*)?-(?<num>\d+)-g(?<sha>[a-z0-9]+)$",
RegexOptions.IgnoreCase)
.Groups
let getMatch (name:string) = result.[name].Value
{ major = getMatch "maj" |> int
minor = getMatch "min" |> int
revision = getMatch "rev" |> int
preSuffix = getMatch "pre"
commitsNum = getMatch "num" |> int
sha = getMatch "sha"
buildNumber = buildNumber
}
type BuildVersionInfo = { assemblyVersion:string; fileVersion:string; infoVersion:string; nugetVersion:string;
source: Option<BuildVersionCalculationSource> }
let calculateVersion source =
let s = source
let (major, minor, revision, preReleaseSuffix, commitsNum, sha, buildNumber) =
(s.major, s.minor, s.revision, s.preSuffix, s.commitsNum, s.sha, s.buildNumber)
let assemblyVersion = sprintf "%d.%d.0.0" major minor
let fileVersion = sprintf "%d.%d.%d.%d" major minor revision buildNumber
// If number of commits since last tag is greater than zero, we append another identifier with number of commits.
// The produced version is larger than the last tag version.
// If we are on a tag, we use version without modification.
// Examples of output: 3.50.2.1, 3.50.2.215, 3.50.1-rc1.3, 3.50.1-rc3.35
let nugetVersion = match commitsNum with
| 0 -> sprintf "%d.%d.%d%s" major minor revision preReleaseSuffix
| _ -> sprintf "%d.%d.%d%s.%d" major minor revision preReleaseSuffix commitsNum
let infoVersion = match commitsNum with
| 0 -> nugetVersion
| _ -> sprintf "%s-%s" nugetVersion sha
{ assemblyVersion=assemblyVersion; fileVersion=fileVersion; infoVersion=infoVersion; nugetVersion=nugetVersion;
source = Some source }
// Calculate version that should be used for the build. Define globally as data might be required by multiple targets.
// Please never name the build parameter with version as "Version" - it might be consumed by the MSBuild, override
// the defined properties and break some tasks (e.g. NuGet restore).
let mutable buildVersion = match getBuildParamOrDefault "BuildVersion" "git" with
| "git" -> getBuildParamOrDefault "BuildNumber" "0"
|> int
|> getVersionSourceFromGit
|> calculateVersion
| assemblyVer -> { assemblyVersion = assemblyVer
fileVersion = getBuildParamOrDefault "BuildFileVersion" assemblyVer
infoVersion = getBuildParamOrDefault "BuildInfoVersion" assemblyVer
nugetVersion = getBuildParamOrDefault "BuildNugetVersion" assemblyVer
source = None }
let setVNextBranchVersion vNextVersion =
buildVersion <-
match buildVersion.source with
// Don't update version if it was explicitly specified.
| None -> buildVersion
// Don't update version if tag with current major version is already present (e.g. rc is released).
| Some s when s.major >= vNextVersion -> buildVersion
| Some source ->
// The trick is the "git describe" command contains the --first-parent flag.
// Because of that git matched the last release tag before the fork was created and calculated number
// of commits since that release. We are perfectly fine, as this number will constantly increase only.
// Set version to X.0.0-alpha.NUM, where X - major version, NUM - commits since last release before fork.
{ source with major = vNextVersion
minor = 0
revision = 0
preSuffix = "-alpha" }
|> calculateVersion
let addBakExt path = sprintf "%s%s" path bakFileExt
Target "PatchAssemblyVersions" (fun _ ->
printfn
"Patching assembly versions. Assembly version: %s, File version: %s, Informational version: %s"
buildVersion.assemblyVersion
buildVersion.fileVersion
buildVersion.infoVersion
// .NET Core SDK creates attributes for C# automatically, therefore only F# files should be updated.
// Patching and backup restore should be completely deleted after F# supports auto-generated attributes.
let filesToPatch = !! "Src/*/Properties/AssemblyInfo.fs"
-- addBakExt "Src/*/Properties/*"
// Backup the original file versions.
filesToPatch
|> Seq.iter (fun f ->
let bakFilePath = addBakExt f
CopyFile bakFilePath f
printfn "Backed up %s to %s" f bakFilePath
)
ReplaceAssemblyInfoVersionsBulk filesToPatch
(fun f -> { f with AssemblyVersion = buildVersion.assemblyVersion
AssemblyFileVersion = buildVersion.fileVersion
AssemblyInformationalVersion = buildVersion.infoVersion })
)
Target "RestorePatchedAssemblyVersionFiles" (fun _ ->
!! (addBakExt "Src/*/Properties/AssemblyInfo.fs")
|> Seq.iter (fun bakFile ->
let originalPath = bakFile.Substring(0, bakFile.Length - bakFileExt.Length)
DeleteFile originalPath
Rename originalPath bakFile
printfn "Restored %s to %s" bakFile originalPath
)
)
let mutable enableSourceLink = false
let runMsBuild target configuration properties =
let verbosity = match getBuildParam "BuildVerbosity" |> toLower with
| "quiet" | "q" -> Quiet
| "minimal" | "m" -> Minimal
| "normal" | "n" -> Normal
| "detailed" | "d" -> Detailed
| "diagnostic" | "diag" -> Diagnostic
| _ -> Minimal
let configProperty = match configuration with
| Some c -> [ "Configuration", c ]
| _ -> []
let sourceLinkCreatePropertyValue = match enableSourceLink with
| true -> "true"
| false -> "false"
let properties = configProperty @ properties
@ [ "AssemblyVersion", buildVersion.assemblyVersion
"FileVersion", buildVersion.fileVersion
"InformationalVersion", buildVersion.infoVersion
"PackageVersion", buildVersion.nugetVersion
"SourceLinkCreateOverride", sourceLinkCreatePropertyValue ]
solutionToBuild
|> build (fun p -> { p with MaxCpuCount = Some None
Verbosity = Some verbosity
Targets = [ target ]
Properties = properties })
let rebuild configuration = runMsBuild "Rebuild" (Some configuration) []
Target "CleanTestResultsFolder" (fun _ -> CleanDir testResultsFolder)
Target "RestoreNuGetPackages" (fun _ -> runMsBuild "Restore" None [])
Target "EnableSourceLinkGeneration" (fun _ ->
let areEqual s1 s2 = String.Equals(s1, s2, StringComparison.OrdinalIgnoreCase)
// A set of sanity checks to fail with meaningful errors.
let originUrl = Git.CommandHelper.runSimpleGitCommand "" "config --get remote.origin.url"
if (repositoryUrlsOnGitHub |> Seq.exists (areEqual originUrl) |> not) then
failwithf
"Current repository has invalid git origin URL and will produce incorrect SourceLink info. Current: '%s'. Expected any of: '[%s]'."
originUrl
(separated ", " repositoryUrlsOnGitHub)
let lineEndingConversion = Git.CommandHelper.runSimpleGitCommand "" "config --get core.autocrlf"
if(areEqual lineEndingConversion "input" |> not) then
failwithf "For correct SourceLink work git line conversion should be set to 'input'. Current: '%s'." lineEndingConversion
enableSourceLink <- true
)
Target "VerifyOnly" (fun _ ->
try
rebuild "Verify"
with
| BuildException (msg, errors) ->
let msg = sprintf
"%s\r\nHINT: To simplify the fix process it's recommended to switch to the 'Verify' configuration \
in the IDE. This way you will get Roslyn quick fixes for the violated rules."
msg
raise (BuildException(msg, errors))
)
Target "BuildOnly" (fun _ -> rebuild configuration)
Target "TestOnly" (fun _ ->
let findProjects pattern = System.IO.Directory.GetDirectories("Src", pattern)
let getTestAssemblies framework projDirs =
projDirs
|> Seq.map (fun proj -> !! (sprintf "bin/%s/%s/*Test.dll" configuration framework)
|> SetBaseDir proj)
|> Seq.collect id
let flip f x y = f y x
let nUnit2TestProjects = findProjects "AutoFixture.NUnit2.*Test"
let nUnit3TestProjects = findProjects "AutoFixture.NUnit3.*Test"
let xUnitTestProjects = findProjects "*Test"
|> Seq.except nUnit2TestProjects
|> Seq.except nUnit3TestProjects
let xUnitCoreAppAssemblies = xUnitTestProjects
|> getTestAssemblies "netcoreapp*"
let xUnitDesktopFrameworkAssemblies = xUnitTestProjects
|> getTestAssemblies "*"
|> Seq.except xUnitCoreAppAssemblies
// Run xUnit desktop tests.
xUnitDesktopFrameworkAssemblies
// A bit hacky way to pass custom parameter to xUnit, but it works.
|> flip Seq.append [ "-noautoreporters" ]
|> xUnit2 (fun p -> { p with ToolPath = buildToolsDir </> "xunit.runner.console/tools/net452/xunit.console.exe"
XmlOutputPath = testResultsFolder </> "xunit-desktop.xml" |> FullName |> Some
Parallel = Collections })
// Run xUnit .NET Core tests.
DotNetCli.RunCommand id
(sprintf "exec \"%s\" %s -xml \"%s\" -noautoreporters"
(buildToolsDir </> "xunit.runner.console/tools/netcoreapp2.0/xunit.console.dll")
(separated " " xUnitCoreAppAssemblies)
(testResultsFolder </> "xunit-netcore.xml" |> FullName)
)
nUnit2TestProjects
|> getTestAssemblies "*"
|> NUnitSequential.NUnit (fun p -> { p with StopOnError = false
ShowLabels = false
OutputFile = testResultsFolder </> "NUnit2TestResult.xml"
ToolPath = buildToolsDir </> "NUnit.Runners.2.6.2" </> "tools" })
// Save test results in MSTest format in the test results folder.
// In future NUnit test runner should support AppVeyor directly.
// See more detail: http://help.appveyor.com/discussions/questions/7805-nunit-test-results-on-net-core
nUnit3TestProjects
|> Seq.iter (fun projDir ->
DotNetCli.RunCommand (fun p -> { p with WorkingDir = projDir })
(sprintf
"test --no-build --configuration %s --logger:trx --results-directory \"%s\""
configuration
testResultsFolder)
)
)
Target "Verify" DoNothing
Target "Build" DoNothing
Target "Test" DoNothing
Target "CleanNuGetPackages" (fun _ ->
CleanDir nuGetOutputFolder
)
Target "NuGetPack" (fun _ ->
// Pack projects using MSBuild.
runMsBuild "Pack" (Some configuration) [ "IncludeSource", "true"
"IncludeSymbols", "true"
"PackageOutputPath", FullName nuGetOutputFolder
"NoBuild", "true" ]
let findDependencyNode name (doc:Xml.XmlDocument) =
doc.SelectSingleNode(sprintf "//*[local-name()='dependency' and @id='%s']" name)
// Verify that AutoFixture reference is valid.
let dependencyVersion = !! "AutoFixture.AutoNSubstitute*"
|> SetBaseDir nuGetOutputFolder
|> Seq.head
|> ZipHelper.UnzipFirstMatchingFileInMemory (fun ze -> ze.Name.EndsWith ".nuspec")
|> XMLDoc
|> findDependencyNode "AutoFixture"
|> getAttribute "version"
if(buildVersion.nugetVersion <> dependencyVersion)
then failwithf "Invalid dependency version in the produced package. Actual: '%s' Expected: '%s'"
dependencyVersion
buildVersion.nugetVersion
else logfn "Verified the dependency version. Actual: '%s' Expected: '%s'"
dependencyVersion
buildVersion.nugetVersion
)
let publishPackagesWithSymbols packageFeed symbolFeed accessKey =
nuGetPackages
|> Seq.map (fun pkg ->
let meta = GetMetaDataFromPackageFile pkg
meta.Id, meta.Version
)
|> Seq.iter (fun (id, version) -> NuGetPublish (fun p -> { p with Project = id
Version = version
OutputPath = nuGetOutputFolder
PublishUrl = packageFeed
AccessKey = accessKey
SymbolPublishUrl = symbolFeed
SymbolAccessKey = accessKey
WorkingDir = nuGetOutputFolder
ToolPath = buildToolsDir </> "nuget.exe" }))
Target "PublishNuGetPublic" (fun _ ->
let feed = "https://www.nuget.org/api/v2/package"
let key = getBuildParam "NuGetPublicKey"
publishPackagesWithSymbols feed "" key
)
Target "PublishNuGetPrivate" (fun _ ->
let packageFeed = "https://www.myget.org/F/autofixture/api/v2/package"
let symbolFeed = "https://www.myget.org/F/autofixture/symbols/api/v2/package"
let key = getBuildParam "NuGetPrivateKey"
publishPackagesWithSymbols packageFeed symbolFeed key
)
Target "CompleteBuild" DoNothing
Target "PublishNuGetAll" DoNothing
"RestoreNuGetPackages" ==> "Verify"
"EnableSourceLinkGeneration" ?=> "Verify"
"VerifyOnly" ==> "Verify"
"Verify" ==> "Build"
"PatchAssemblyVersions" ==> "Build"
"BuildOnly" ==> "Build"
"RestorePatchedAssemblyVersionFiles" ==> "Build"
"BuildOnly" ?=> "RestorePatchedAssemblyVersionFiles"
"BuildOnly" ==> "TestOnly"
"CleanTestResultsFolder" ==> "TestOnly"
"Build" ==> "Test"
"TestOnly" ==> "Test"
"CleanNuGetPackages" ==> "NuGetPack"
"Test" ==> "NuGetPack"
"NuGetPack" ==> "CompleteBuild"
"NuGetPack" ==> "PublishNuGetPublic"
"EnableSourceLinkGeneration" ==> "PublishNuGetPublic"
"NuGetPack" ==> "PublishNuGetPrivate"
"EnableSourceLinkGeneration" ==> "PublishNuGetPrivate"
"PublishNuGetPublic" ==> "PublishNuGetAll"
"PublishNuGetPrivate" ==> "PublishNuGetAll"
// ==============================================
// ================== AppVeyor ==================
// ==============================================
// Add a helper to identify whether current trigger is PR.
type AppVeyorEnvironment with
static member IsPullRequest = isNotNullOrEmpty AppVeyorEnvironment.PullRequestNumber
type AppVeyorTrigger = SemVerTag | CustomTag | PR | VNextBranch | Unknown
let anAppVeyorTrigger =
let tag = if AppVeyorEnvironment.RepoTag then Some AppVeyorEnvironment.RepoTagName else None
let isPR = AppVeyorEnvironment.IsPullRequest
let branch = if isNotNullOrEmpty AppVeyorEnvironment.RepoBranch then Some AppVeyorEnvironment.RepoBranch else None
match tag, isPR, branch with
| Some t, _, _ when "v\d+.*" >** t -> SemVerTag
| Some _, _, _ -> CustomTag
| _, true, _ -> PR
// Branch name should be checked after the PR flag, because for PR it's set to the upstream branch name.
| _, _, Some br when "v\d+" >** br -> VNextBranch
| _ -> Unknown
Target "AppVeyor_SetVNextVersion" (fun _ ->
// vNext branch has the following name: "vX", where X is the next version.
AppVeyorEnvironment.RepoBranch.Substring(1)
|> int
|> setVNextBranchVersion
)
Target "AppVeyor_UploadTestReports" (fun _ ->
let uploadResults pattern format =
async {
!! pattern
|> SetBaseDir testResultsFolder
|> Seq.iter (fun file -> AppVeyor.UploadTestResultsFile format file)
}
[ uploadResults "xunit-desktop.xml" Xunit;
uploadResults "xunit-netcore.xml" Xunit;
uploadResults "NUnit2TestResult.xml" NUnit;
uploadResults "*.trx" MsTest ]
|> Async.Parallel
|> Async.RunSynchronously
|> ignore
)
FinalTarget "AppVeyor_UpdateVersion" (fun _ ->
// Artifacts might be deployable, so we update build version to find them later by file version.
let versionSuffix = if AppVeyorEnvironment.IsPullRequest then
let appVeyorVersion = AppVeyorEnvironment.BuildVersion;
appVeyorVersion.Substring(appVeyorVersion.IndexOf('-'))
else
""
UpdateBuildVersion (buildVersion.fileVersion + versionSuffix)
)
Target "AppVeyor" DoNothing
"AppVeyor_SetVNextVersion" =?> ("PatchAssemblyVersions", anAppVeyorTrigger = VNextBranch)
"TestOnly" ==> "AppVeyor_UploadTestReports"
"AppVeyor_UploadTestReports" ?=> "Test"
// Add logic to resolve action based on current trigger info.
dependency "AppVeyor" <| match anAppVeyorTrigger with
| SemVerTag -> "PublishNuGetPublic"
| VNextBranch -> "PublishNuGetPrivate"
| PR | CustomTag | Unknown -> "CompleteBuild"
"EnableSourceLinkGeneration" ==> "AppVeyor"
"AppVeyor_UploadTestReports" ==> "AppVeyor"
// Print state info at the very beginning.
if buildServer = BuildServer.AppVeyor
then logfn "[AppVeyor state] Is tag: %b, tag name: '%s', is PR: %b, branch name: '%s', trigger: %A, build version: '%s'"
AppVeyorEnvironment.RepoTag
AppVeyorEnvironment.RepoTagName
AppVeyorEnvironment.IsPullRequest
AppVeyorEnvironment.RepoBranch
anAppVeyorTrigger
AppVeyorEnvironment.BuildVersion
ActivateFinalTarget "AppVeyor_UpdateVersion"
// ========= ENTRY POINT =========
RunTargetOrDefault "CompleteBuild"