-
Notifications
You must be signed in to change notification settings - Fork 32
/
build.fsx
519 lines (416 loc) · 21.3 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
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
#I "Source/Solutions/packages/FAKE/tools/"
#I "Source/Solutions/packages/FAKE/FSharp.Data/lib/net40"
#r "FakeLib.dll"
#r "FSharp.Data.dll"
open Fake
open Fake.RestorePackageHelper
open Fake.Git
open System
open System.Diagnostics
open System.IO
open System.Linq
open System.Text
open System.Text.RegularExpressions
open FSharp.Data
open FSharp.Data.JsonExtensions
open FSharp.Data.HttpRequestHeaders
open Fake.FileHelper
open Fake.FileSystemHelper
open Fake.ProcessHelper
open Fake.MSBuildHelper
open AssemblyInfoFile
// https://github.com/krauthaufen/DevILSharp/blob/master/build.fsx
// http://blog.2mas.xyz/take-control-of-your-build-ci-and-deployment-with-fsharp-fake/
let isWindows = System.Environment.OSVersion.Platform = PlatformID.Win32NT
let appveyor = if String.IsNullOrWhiteSpace(System.Environment.GetEnvironmentVariable("APPVEYOR")) then false else true
let appveyor_job_id = System.Environment.GetEnvironmentVariable("APPVEYOR_JOB_ID")
let versionRegex = Regex("(\d+).(\d+).(\d+)-*([a-z]+)*[+-]*(\d+)*", RegexOptions.Compiled)
type BuildVersion(major:int, minor:int, patch: int, build:int, preReleaseString:string, release:bool) =
let major = major
let minor = minor
let patch = patch
let preReleaseString = preReleaseString
member this.Major with get() = major
member this.Minor with get() = minor
member this.Patch with get() = patch
member this.Build with get() = build
member this.PreReleaseString with get() = preReleaseString
member this.AsString() : string =
if String.IsNullOrEmpty(preReleaseString) then
if release then
sprintf "%d.%d.%d" major minor patch
else
sprintf "%d.%d.%d-%d" major minor patch build
else
sprintf "%d.%d.%d-%s-%d" major minor patch preReleaseString build
member this.IsPreRelease with get() : bool = preReleaseString.Length > 0
member this.DoesMajorMinorPatchMatch(other:BuildVersion) =
other.Major = major && other.Minor = minor && other.Patch = patch
new (versionAsString:string) =
BuildVersion(versionAsString,0,false)
new (versionAsString:string, build:int, release:bool) =
let versionResult = versionRegex.Match versionAsString
if versionResult.Success then
let major = versionResult.Groups.[1].Value |> int
let minor = versionResult.Groups.[2].Value |> int
let patch = versionResult.Groups.[3].Value |> int
let build = if versionResult.Groups.Count = 6 && versionResult.Groups.[5].Value.Length > 0 then versionResult.Groups.[5].Value |> int else build
if versionResult.Groups.Count >= 5 then
BuildVersion(major,minor,patch,build,versionResult.Groups.[4].Value,release)
else
BuildVersion(major,minor,patch,build,"",release)
else
failwithf "Unable to resolve version from '%s'" versionAsString
BuildVersion(0,0,0,0,"",false)
let spawnProcess (processName:string, arguments:string) =
let startInfo = new System.Diagnostics.ProcessStartInfo(processName)
startInfo.Arguments <- arguments
startInfo.RedirectStandardInput <- true
startInfo.RedirectStandardOutput <- true
startInfo.RedirectStandardError <- true
startInfo.UseShellExecute <- false
startInfo.CreateNoWindow <- true
startInfo.StandardOutputEncoding = Encoding.Unicode
startInfo.StandardErrorEncoding = Encoding.Unicode
let result = new StringBuilder()
let resultHandler (_sender:obj) (args:DataReceivedEventArgs) = result.AppendLine args.Data |> ignore
let outputHandler (_sender:obj) (args:DataReceivedEventArgs) = Console.WriteLine args.Data
use proc = new System.Diagnostics.Process(StartInfo = startInfo)
proc.EnableRaisingEvents <- true
proc.OutputDataReceived.AddHandler(DataReceivedEventHandler (resultHandler))
proc.ErrorDataReceived.AddHandler(DataReceivedEventHandler (resultHandler))
proc.OutputDataReceived.AddHandler(DataReceivedEventHandler (outputHandler))
proc.ErrorDataReceived.AddHandler(DataReceivedEventHandler (outputHandler))
proc.Start() |> ignore
proc.BeginOutputReadLine()
proc.BeginErrorReadLine()
proc.WaitForExit()
if proc.ExitCode <> 0 then
failwith ("Problems spawning ("+processName+") with arguments ("+arguments+"): \r\n" + proc.StandardError.ReadToEnd())
proc.Close()
result.ToString()
let performGitCommand arguments:string =
spawnProcess("git", arguments)
let gitVersion repositoryDir =
let arguments = sprintf "%s /output json /showvariable SemVer" repositoryDir
let gitVersionExecutable = "Source/Solutions/packages/GitVersion.CommandLine/tools/GitVersion.exe"
let processName = if isWindows then gitVersionExecutable else "mono"
let fullArguments = if isWindows then arguments else sprintf "%s %s" gitVersionExecutable arguments
spawnProcess(processName, fullArguments)
let getCurrentBranch =
performGitCommand("rev-parse --abbrev-ref HEAD").Trim()
let getLatestTag repositoryDir =
//let commitSha = performGitCommand "rev-list --tags --max-count=1"
performGitCommand (sprintf "describe --tag --abbrev=0")
let getVersionFromGitTag(buildNumber:int) =
trace "Get version from Git tag"
if appveyor then
let gitVersionTag = gitVersion "./"
tracef "Git tag version : %s" gitVersionTag
new BuildVersion(gitVersionTag, buildNumber, true)
else
new BuildVersion("1.0.0", 0, false)
let getLatestNuGetVersion =
trace "Get latest NuGet version"
let jsonAsString = Http.RequestString("https://api.nuget.org/v3/registration1/bifrost/index.json", headers = [ Accept HttpContentTypes.Json ])
let json = JsonValue.Parse(jsonAsString)
let items = json?items.AsArray().[0]?items.AsArray()
let item = items.[items.Length-1]
let catalogEntry = item?catalogEntry
let version = (catalogEntry?version.AsString())
new BuildVersion(version)
let updateProjectJsonFile(file:FileInfo, version:BuildVersion) =
tracef "Update version and dependency versions for '%s'" file.FullName
let json = JsonValue.Load file.FullName
let rec fixVersion json =
match json with
| JsonValue.String _ | JsonValue.Boolean _ | JsonValue.Float _ | JsonValue.Number _ | JsonValue.Null -> json
| JsonValue.Record properties ->
properties
|> Array.map (fun (key, value) -> key,
if key.StartsWith("Bifrost") || key.Equals("version") then
(version.AsString()) |> JsonValue.String
else
fixVersion value
)
|> JsonValue.Record
| JsonValue.Array array ->
array
|> Array.map fixVersion
|> JsonValue.Array
let fixedJson = fixVersion json
File.WriteAllText(file.FullName, sprintf "%O" fixedJson)
let updateVersionOnProjectFile(file:string, version:BuildVersion) =
let projectFile = File.ReadAllText(file)
let newVersionString = sprintf "<Version>%s</Version>" (version.AsString())
let updatedProjectFile = projectFile.Replace("<Version>1.0.0</Version>", newVersionString)
File.WriteAllText(file, updatedProjectFile)
let getMsBuildEnginePath() =
let msbuildLocations = [|
"c:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Enterprise\\MSBuild\\15.0\\Bin\\msbuild.exe";
"c:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Professional\\MSBuild\\15.0\\Bin\\msbuild.exe";
"c:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Community\\MSBuild\\15.0\\Bin\\msbuild.exe"
|]
let msbuild = Array.tryFind (fun f -> File.Exists f) msbuildLocations
if msbuild.IsSome then
msbuild.Value
else
""
//*****************************************************************************
//* Globals
//*****************************************************************************
let company = "Dolittle"
let copyright = "(C) 2008 - 2017 Dolittle"
let trademark = ""
let solutionFile = "./Source/Solutions/Bifrost_All.sln"
let sourceDirectory = sprintf "%s/Source" __SOURCE_DIRECTORY__
let artifactsDirectory = sprintf "%s/artifacts" __SOURCE_DIRECTORY__
let nugetDirectory = sprintf "%s/nuget" artifactsDirectory
let msbuild = getMsBuildEnginePath()
let projectsDirectories = File.ReadAllLines "projects.txt" |> Array.map(fun f -> new DirectoryInfo(sprintf "./Source/%s" f))
let specDirectories = File.ReadAllLines "specs.txt" |> Array.map(fun f -> new DirectoryInfo(sprintf "./Source/%s" f))
let currentBranch = getCurrentBranch
// Versioning related
let envBuildNumber = System.Environment.GetEnvironmentVariable("APPVEYOR_BUILD_NUMBER")
let buildNumber = if String.IsNullOrWhiteSpace(envBuildNumber) then 0 else envBuildNumber |> int
let versionFromGitTag = BuildVersion(1, 2, 1, 0, "alpha", false)
// getVersionFromGitTag buildNumber
let lastNuGetVersion = getLatestNuGetVersion
let sameVersion = versionFromGitTag.DoesMajorMinorPatchMatch lastNuGetVersion
// Determine if it is a release build - check if the latest NuGet deployment is a release build matching version number or not.
let isReleaseBuild = false
// not versionFromGitTag.IsPreRelease
// sameVersion && (not versionFromGitTag.IsPreRelease && lastNuGetVersion.IsPreRelease)
System.Environment.SetEnvironmentVariable("RELEASE_BUILD",if isReleaseBuild then "true" else "false")
let buildVersion = BuildVersion(versionFromGitTag.Major, versionFromGitTag.Minor, versionFromGitTag.Patch, buildNumber, versionFromGitTag.PreReleaseString,isReleaseBuild)
// Package related
let nugetPath = "./Source/Solutions/.nuget/NuGet.exe"
let nugetUrl = "https://www.nuget.org/api/v2/package"
let mygetUrl = "https://www.myget.org/F/bifrost/api/v2/package"
let nugetKey = System.Environment.GetEnvironmentVariable("NUGET_KEY")
let mygetKey = System.Environment.GetEnvironmentVariable("MYGET_KEY")
// Documentation related
let documentationUser = System.Environment.GetEnvironmentVariable("DOCS_USER")
let documentationUserToken = System.Environment.GetEnvironmentVariable("DOCS_TOKEN")
let documentationSolutionFile = "Source/Solutions/Bifrost_Documentation.sln"
printfn "<----------------------- BUILD DETAILS ----------------------->"
printfn "Git Branch : %s" currentBranch
printfn "Git Version : %s" (versionFromGitTag.AsString())
printfn "Last NuGet version : %s" (lastNuGetVersion.AsString())
printfn "Last NuGet version - preRelease : %b" (lastNuGetVersion.IsPreRelease)
printfn "Build version : %s" (buildVersion.AsString())
printfn "Build version - preRelease : %b" (buildVersion.IsPreRelease)
printfn "Version Same : %b" sameVersion
printfn "Release Build : %b" isReleaseBuild
printfn "Documentation User : %s" documentationUser
printfn "MSBuild location : %s" msbuild
printfn "<----------------------- BUILD DETAILS ----------------------->"
//*****************************************************************************
//* Restore Packages
//*****************************************************************************
Target "RestorePackages" (fun _ ->
trace "**** Restoring packages ****"
let currentDir = Directory.GetCurrentDirectory()
for directory in projectsDirectories.Concat(specDirectories) do
tracef "Restoring packages for %s" directory.FullName
Directory.SetCurrentDirectory directory.FullName
let allArgs = sprintf "restore"
spawnProcess("dotnet", allArgs) |> ignore
Directory.SetCurrentDirectory(currentDir)
trace "**** Restoring packages DONE ****"
)
//*****************************************************************************
//* Update project json files with correct version
//*****************************************************************************
Target "UpdateVersionOnBuildServer" (fun _ ->
if( appveyor ) then
tracef "Updating build version for AppVeyor to %s" (buildVersion.AsString())
let allArgs = sprintf "UpdateBuild -Version \"%s\"" (buildVersion.AsString())
spawnProcess("appveyor", allArgs) |> ignore
)
//*****************************************************************************
//* Update Assembly Info files with correct information
//*****************************************************************************
Target "UpdateAssemblyInfoFiles" (fun _ ->
let version = sprintf "%d.%d.%d.%d" buildVersion.Major buildVersion.Minor buildVersion.Patch buildVersion.Build
CreateCSharpAssemblyInfoWithConfig "Source/Common/CommonAssemblyInfo.cs" [
Attribute.Company company
Attribute.Copyright copyright
Attribute.Trademark trademark
Attribute.Version version
Attribute.FileVersion version
] <| AssemblyInfoFileConfig(false)
)
//*****************************************************************************
//* Update the version number on the project files
//*****************************************************************************
Target "UpdateVersionOnProjectFiles" (fun _ ->
trace "**** Fixing version number for project files ****"
for directory in projectsDirectories do
let projectFiles = Directory.GetFiles(directory.FullName,"*.csproj")
let file = projectFiles.[0]
tracef "Fixing %s" file
updateVersionOnProjectFile(file, buildVersion)
trace "**** Fixing version number for project files - Done ****"
)
//*****************************************************************************
//* Build
//*****************************************************************************
Target "Build" (fun _ ->
trace "**** Building ****"
for directory in projectsDirectories do
tracef "Building %s" directory.FullName
let allArgs = sprintf "build %s %s" directory.FullName (if isWindows then "" else "-f netstandard1.6")
spawnProcess("dotnet", allArgs)
trace "**** Building Done ****"
)
//*****************************************************************************
//* Run .NET CLI Test
//*****************************************************************************
Target "DotNetTest" (fun _ ->
trace "**** Running Specs ****"
let currentDir = Directory.GetCurrentDirectory()
for directory in specDirectories do
tracef "Running Specs for %s" directory.FullName
Directory.SetCurrentDirectory directory.FullName
let allArgs = sprintf "test %s %s" (if isWindows then "" else "-f netcoreapp1.1") (if appveyor then "\"--logger:trx;LogFileName=results.trx\"" else "")
spawnProcess("dotnet", allArgs)
let resultsFile = "./TestResults/results.trx"
if appveyor && File.Exists(resultsFile) then
let webClient = new System.Net.WebClient()
let url = sprintf "https://ci.appveyor.com/api/testresults/mstest/%s" appveyor_job_id
tracef "Posting results to %s" url
webClient.UploadFile(url, resultsFile) |> ignore
Directory.SetCurrentDirectory(currentDir)
trace "**** Running Specs DONE ****"
)
//*****************************************************************************
//* Package all projects for NuGet
//*****************************************************************************
Target "PackageForNuGet" (fun _ ->
for directory in projectsDirectories do
let allArgs = sprintf "pack --no-build %s --output %s" directory.FullName nugetDirectory
spawnProcess("dotnet", allArgs)
)
//*****************************************************************************
//* Run JavaScript Specifications
//*****************************************************************************
Target "JavaScriptSpecs" (fun _ ->
if Directory.Exists("TestResults") = false then Directory.CreateDirectory("TestResults") |> ignore
let allArgs = sprintf "Forseti.yaml ../TestResults/forseti.testresults.trx BUILD-CI"
let errorCode = ProcessHelper.Shell.Exec("Tools/Forseti/Forseti.Output.exe", args=allArgs, dir="Source")
if errorCode <> 0 then failwith "Running JavaScript Specifications failed"
)
//*****************************************************************************
//* Generate and publish documentation to site
//*****************************************************************************
Target "GenerateAndPublishDocumentation" (fun _ ->
if String.IsNullOrEmpty(documentationUser) then
trace "Skipping building and publishing documentation - user not set"
else
trace "**** Generating Documentation ****"
let currentDir = Directory.GetCurrentDirectory()
tracef "Current directory is : %s" currentDir
Directory.SetCurrentDirectory "./Source/Documentation"
spawnProcess("dotnet", "restore")
spawnProcess("dotnet", "build")
Directory.SetCurrentDirectory(currentDir)
trace "Clone site repository"
let siteDir = "dolittle.github.io"
spawnProcess("git", "clone https://github.com/dolittle/dolittle.github.io.git")
trace "Copy all the content from the generated site"
FileHelper.CopyDir "dolittle.github.io/bifrost" "Source/Documentation/_site" (fun f -> true)
Directory.SetCurrentDirectory(siteDir)
trace "Push back to Git repository"
spawnProcess("git" , "add .") |> ignore
spawnProcess("git" , "config --global user.name \"Bifrost Documentation Account\"") |> ignore
spawnProcess("git" , "config --global user.email \"[email protected]\"") |> ignore
spawnProcess("git" , "commit -m \"<-- Autogenerated : documentation updated -->\"") |> ignore
let remoteUrl = sprintf "remote set-url origin https://%s:%[email protected]/dolittle/dolittle.github.io.git" documentationUser documentationUserToken
spawnProcess("git" , remoteUrl) |> ignore
// if( ProcessHelper.Shell.Exec("git" , args="push 2>nul") <> 0) then failwith "Couldn't push documentation to repository"
spawnProcess("git", "push")
trace "--- Delete content of site dir ---"
FileHelper.DeleteDir siteDir
Directory.SetCurrentDirectory(currentDir)
trace "**** Generating Documentation DONE ****"
)
//*****************************************************************************
//* Deploy to NuGet if release mode
//*****************************************************************************
Target "DeployNugetPackages" (fun _ ->
let key = if( isReleaseBuild && String.IsNullOrEmpty(nugetKey) = false ) then nugetKey else mygetKey
let source = if( isReleaseBuild && String.IsNullOrEmpty(nugetKey) = false ) then nugetUrl else mygetUrl
if( String.IsNullOrEmpty(key) = false ) then
let packages = !! ("artifacts/nuget/*.nupkg")
|> Seq.toArray
for package in packages do
let allArgs = sprintf "push %s %s -Source %s" package key source
spawnProcess(nugetPath, allArgs) |> ignore
else
trace "Not deploying to NuGet - no key set"
)
//*****************************************************************************
//* Deploy to NuGet if release mode
//*****************************************************************************
Target "PackageSamples" (fun _ ->
let sampleProjects = ["Bifrost.QuickStart"]
// "Source/Bifrost.Default/Bifrost.Default.nuspec"
trace "*** Package Sample Projects ***"
for sampleProject in sampleProjects do
let specFile = sprintf "Source/%s/%s.nuspec" sampleProject sampleProject
let projFile = sprintf "Source/%s/%s.csproj" sampleProject sampleProject
tracef "Build %s" projFile
spawnProcess(msbuild, projFile) |> ignore
tracef "Packaging %s %s" specFile
let allArgs = sprintf "pack %s -Version %s -OutputDirectory %s" specFile (buildVersion.AsString()) nugetDirectory
spawnProcess(nugetPath, allArgs) |> ignore
trace "*** Package Sample Projects DONE ***"
)
// ******** Pre Info
// Get Build Number from BuildServer
// Get Version from Git Tag
// Determine if it is a release build - check if the latest NuGet deployment is a release build matching version number or not.
// If tag is not a release tag - Append build number
// ******** BUILD:
// Restore packages
// Create Assembly Version from Tag + Build Number -> Update Assembly Info
// Build
// Run MSpec Specs
// Run JavaScript Specs
//
// If daily or alpha or beta - create nuget packages
// If daily and not alpha or beta -> Deploy to MyGet
// Else deploy to NuGet
// Note: Deploy package only if it is a release build or build parameter saying it should publish package
//
// Clone Documentation Repository
// DocFX for documentation -> Into Documentation repository
// Push changes to Documentation Repository
// Build pipeline
Target "BuildRelease" DoNothing
"UpdateVersionOnBuildServer" ==> "BuildRelease"
"RestorePackages" ==> "BuildRelease"
"Build" ==> "BuildRelease"
// Package pipeline
Target "Package" DoNothing
"UpdateAssemblyInfoFiles" ==> "Package"
"UpdateVersionOnProjectFiles" ==> "Package"
"PackageForNuGet" ==> "Package"
// Deployment pipeline
Target "Deploy" DoNothing
"DeployNugetPackages" ==> "Deploy"
Target "PackageAndDeploy" DoNothing
"GenerateAndPublishDocumentation" ==> "PackageAndDeploy"
"Package" ==> "PackageAndDeploy"
"PackageSamples" ==> "PackageAndDeploy"
"Deploy" ==> "PackageAndDeploy"
Target "All" DoNothing
"BuildRelease" ==> "All"
"DotNetTest" ==> "All"
"JavaScriptSpecs" ==> "All"
"PackageAndDeploy" =?> ("All", currentBranch.Equals("master") or currentBranch.Equals("HEAD"))
Target "Travis" DoNothing
"BuildRelease" ==> "Travis"
"DotNetTest" ==> "Travis"
RunTargetOrDefault "All"