forked from fsprojects/fantomas
-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
build.fsx
478 lines (432 loc) · 17.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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
#r "nuget: Fun.Build, 1.0.3"
#r "nuget: CliWrap, 3.6.4"
#r "nuget: FSharp.Data, 6.3.0"
#r "nuget: Ionide.KeepAChangelog, 0.1.8"
#r "nuget: Humanizer.Core, 2.14.1"
open System
open System.IO
open Fun.Build
open CliWrap
open CliWrap.Buffered
open FSharp.Data
open System.Xml.Linq
open System.Xml.XPath
open Ionide.KeepAChangelog
open Ionide.KeepAChangelog.Domain
open SemVersion
open Humanizer
let (</>) a b = Path.Combine(a, b)
let cleanFolders (input: string seq) =
async {
input
|> Seq.iter (fun dir ->
if Directory.Exists(dir) then
Directory.Delete(dir, true))
}
let benchmarkAssembly =
"artifacts/bin/Fantomas.Benchmarks/release/Fantomas.Benchmarks.dll"
let semanticVersioning =
__SOURCE_DIRECTORY__
</> "artifacts"
</> "bin"
</> "Fantomas"
</> "release"
</> "SemanticVersioning.dll"
let pushPackage nupkg =
async {
let key = Environment.GetEnvironmentVariable("NUGET_KEY")
let! result =
Cli
.Wrap("dotnet")
.WithArguments($"nuget push {nupkg} --api-key {key} --source https://api.nuget.org/v3/index.json")
.ExecuteAsync()
.Task
|> Async.AwaitTask
return result.ExitCode
}
let analysisReportsDir = "analysisreports"
pipeline "Build" {
workingDir __SOURCE_DIRECTORY__
stage "RestoreTools" { run "dotnet tool restore" }
stage "Clean" { run (cleanFolders [| analysisReportsDir; "artifacts" |]) }
stage "CheckFormat" { run "dotnet fantomas src docs build.fsx --check" }
stage "Build" { run "dotnet build -c Release --tl" }
stage "UnitTests" { run "dotnet test -c Release --tl" }
stage "Pack" { run "dotnet pack --no-restore -c Release --tl" }
stage "Docs" {
whenNot { platformOSX }
envVars
[| "DOTNET_ROLL_FORWARD_TO_PRERELEASE", "1"
"DOTNET_ROLL_FORWARD", "LatestMajor" |]
run
$"dotnet fsdocs build --clean --properties Configuration=Release --fscoptions \" -r:{semanticVersioning}\" --eval --strict --nonpublic"
}
runIfOnlySpecified false
}
pipeline "Benchmark" {
workingDir __SOURCE_DIRECTORY__
stage "Prepare" { run "dotnet build -c Release src/Fantomas.Benchmarks --tl" }
stage "Benchmark" { run $"dotnet {benchmarkAssembly}" }
runIfOnlySpecified true
}
let runGitCommand (arguments: string) =
async {
let! result =
Cli
.Wrap("git")
.WithArguments(arguments)
.WithWorkingDirectory(__SOURCE_DIRECTORY__)
.ExecuteBufferedAsync()
.Task
|> Async.AwaitTask
return result.ExitCode, result.StandardOutput, result.StandardError
}
let runCmd file (arguments: string) =
async {
let! result = Cli.Wrap(file).WithArguments(arguments).ExecuteAsync().Task |> Async.AwaitTask
return result.ExitCode
}
pipeline "FormatChanged" {
workingDir __SOURCE_DIRECTORY__
stage "Format" {
run (fun _ ->
async {
let! exitCode, stdout, _stdErr = runGitCommand "status --porcelain"
if exitCode <> 0 then
return exitCode
else
let files =
stdout.Split('\n')
|> Array.choose (fun line ->
let line = line.Trim()
if
(line.StartsWith("AM", StringComparison.Ordinal)
|| line.StartsWith("M", StringComparison.Ordinal))
&& (line.EndsWith(".fs", StringComparison.Ordinal)
|| line.EndsWith(".fsx", StringComparison.Ordinal)
|| line.EndsWith(".fsi", StringComparison.Ordinal))
then
Some(line.Replace("AM ", "").Replace("MM ", "").Replace("M ", ""))
else
None)
|> String.concat " "
return! runCmd "dotnet" $"fantomas {files}"
})
}
runIfOnlySpecified true
}
pipeline "PushClient" {
workingDir __SOURCE_DIRECTORY__
stage "Pack" { run "dotnet pack ./src/Fantomas.Client -c Release --tl" }
stage "Push" {
run (fun _ ->
async {
return!
Directory.EnumerateFiles(
"artifacts/package/release",
"Fantomas.Client.*.nupkg",
SearchOption.TopDirectoryOnly
)
|> Seq.tryExactlyOne
|> Option.map pushPackage
|> Option.defaultValue (
async {
printfn "Fantomas.Client package was not found."
return -1
}
)
})
}
runIfOnlySpecified true
}
pipeline "Docs" {
workingDir __SOURCE_DIRECTORY__
stage "Prepare" {
run "dotnet tool restore"
run "dotnet build -c Release src/Fantomas/Fantomas.fsproj"
}
stage "Watch" {
envVars
[| "DOTNET_ROLL_FORWARD_TO_PRERELEASE", "1"
"DOTNET_ROLL_FORWARD", "LatestMajor" |]
run
$"dotnet fsdocs watch --properties Configuration=Release --fscoptions \" -r:{semanticVersioning}\" --eval --nonpublic"
}
runIfOnlySpecified true
}
pipeline "FormatAll" {
workingDir __SOURCE_DIRECTORY__
stage "Fantomas" { run "dotnet fantomas src docs build.fsx" }
runIfOnlySpecified true
}
pipeline "EnsureRepoConfig" {
workingDir __SOURCE_DIRECTORY__
stage "Git" { run "git config core.hooksPath .githooks" }
runIfOnlySpecified true
}
let deps = __SOURCE_DIRECTORY__ </> ".deps"
let fsharpCompilerHash =
let xDoc = XElement.Load(__SOURCE_DIRECTORY__ </> "Directory.Build.props")
xDoc.XPathSelectElements("//FCSCommitHash") |> Seq.head |> (fun xe -> xe.Value)
let updateFileRaw (file: FileInfo) =
let lines = File.ReadAllLines file.FullName
let updatedLines =
lines
|> Array.map (fun line ->
if line.Contains("FSharp.Compiler") then
line.Replace("FSharp.Compiler", "Fantomas.FCS")
else
line)
File.WriteAllLines(file.FullName, updatedLines)
let downloadCompilerFile commitHash relativePath =
async {
let file = FileInfo(deps </> commitHash </> relativePath)
if file.Exists && file.Length <> 0 then
return ()
else
file.Directory.Create()
let fs = file.Create()
let fileName = Path.GetFileName(relativePath)
let url =
$"https://raw.githubusercontent.com/dotnet/fsharp/{commitHash}/{relativePath}"
let! response =
Http.AsyncRequestStream(
url,
headers = [| "Content-Disposition", $"attachment; filename=\"{fileName}\"" |]
)
if response.StatusCode <> 200 then
printfn $"Could not download %s{relativePath}"
do! Async.AwaitTask(response.ResponseStream.CopyToAsync(fs))
fs.Close()
updateFileRaw file
}
pipeline "Init" {
workingDir __SOURCE_DIRECTORY__
stage "Download FCS files" {
run (fun _ ->
[| "src/Compiler/FSComp.txt"
"src/Compiler/FSStrings.resx"
"src/Compiler/Utilities/Activity.fsi"
"src/Compiler/Utilities/Activity.fs"
"src/Compiler/Utilities/sformat.fsi"
"src/Compiler/Utilities/sformat.fs"
"src/Compiler/Utilities/sr.fsi"
"src/Compiler/Utilities/sr.fs"
"src/Compiler/Utilities/ResizeArray.fsi"
"src/Compiler/Utilities/ResizeArray.fs"
"src/Compiler/Utilities/HashMultiMap.fsi"
"src/Compiler/Utilities/HashMultiMap.fs"
"src/Compiler/Utilities/ReadOnlySpan.fsi"
"src/Compiler/Utilities/ReadOnlySpan.fs"
"src/Compiler/Utilities/TaggedCollections.fsi"
"src/Compiler/Utilities/TaggedCollections.fs"
"src/Compiler/Utilities/illib.fsi"
"src/Compiler/Utilities/illib.fs"
"src/Compiler/Utilities/Cancellable.fsi"
"src/Compiler/Utilities/Cancellable.fs"
"src/Compiler/Utilities/FileSystem.fsi"
"src/Compiler/Utilities/FileSystem.fs"
"src/Compiler/Utilities/ildiag.fsi"
"src/Compiler/Utilities/ildiag.fs"
"src/Compiler/Utilities/zmap.fsi"
"src/Compiler/Utilities/zmap.fs"
"src/Compiler/Utilities/zset.fsi"
"src/Compiler/Utilities/zset.fs"
"src/Compiler/Utilities/XmlAdapters.fsi"
"src/Compiler/Utilities/XmlAdapters.fs"
"src/Compiler/Utilities/InternalCollections.fsi"
"src/Compiler/Utilities/InternalCollections.fs"
"src/Compiler/Utilities/lib.fsi"
"src/Compiler/Utilities/lib.fs"
"src/Compiler/Utilities/PathMap.fsi"
"src/Compiler/Utilities/PathMap.fs"
"src/Compiler/Utilities/range.fsi"
"src/Compiler/Utilities/range.fs"
"src/Compiler/Facilities/LanguageFeatures.fsi"
"src/Compiler/Facilities/LanguageFeatures.fs"
"src/Compiler/Facilities/DiagnosticOptions.fsi"
"src/Compiler/Facilities/DiagnosticOptions.fs"
"src/Compiler/Facilities/DiagnosticsLogger.fsi"
"src/Compiler/Facilities/DiagnosticsLogger.fs"
"src/Compiler/Facilities/Hashing.fsi"
"src/Compiler/Facilities/Hashing.fs"
"src/Compiler/Facilities/prim-lexing.fsi"
"src/Compiler/Facilities/prim-lexing.fs"
"src/Compiler/Facilities/prim-parsing.fsi"
"src/Compiler/Facilities/prim-parsing.fs"
"src/Compiler/AbstractIL/illex.fsl"
"src/Compiler/AbstractIL/ilpars.fsy"
"src/Compiler/AbstractIL/il.fsi"
"src/Compiler/AbstractIL/il.fs"
"src/Compiler/AbstractIL/ilascii.fsi"
"src/Compiler/AbstractIL/ilascii.fs"
"src/Compiler/SyntaxTree/PrettyNaming.fsi"
"src/Compiler/SyntaxTree/PrettyNaming.fs"
"src/Compiler/pplex.fsl"
"src/Compiler/pppars.fsy"
"src/Compiler/lex.fsl"
"src/Compiler/pars.fsy"
"src/Compiler/SyntaxTree/UnicodeLexing.fsi"
"src/Compiler/SyntaxTree/UnicodeLexing.fs"
"src/Compiler/SyntaxTree/XmlDoc.fsi"
"src/Compiler/SyntaxTree/XmlDoc.fs"
"src/Compiler/SyntaxTree/SyntaxTrivia.fsi"
"src/Compiler/SyntaxTree/SyntaxTrivia.fs"
"src/Compiler/SyntaxTree/SyntaxTree.fsi"
"src/Compiler/SyntaxTree/SyntaxTree.fs"
"src/Compiler/SyntaxTree/SyntaxTreeOps.fsi"
"src/Compiler/SyntaxTree/SyntaxTreeOps.fs"
"src/Compiler/SyntaxTree/ParseHelpers.fsi"
"src/Compiler/SyntaxTree/ParseHelpers.fs"
"src/Compiler/SyntaxTree/LexHelpers.fsi"
"src/Compiler/SyntaxTree/LexHelpers.fs"
"src/Compiler/SyntaxTree/LexFilter.fsi"
"src/Compiler/SyntaxTree/LexFilter.fs" |]
|> Array.map (downloadCompilerFile fsharpCompilerHash)
|> Async.Parallel
|> Async.Ignore)
}
runIfOnlySpecified true
}
type GithubRelease =
{ Version: string
Title: string
Date: DateTime
PublishedDate: string option
Draft: string }
let mkGithubRelease (v: SemanticVersion, d: DateTime, cd: ChangelogData option) =
match cd with
| None -> failwith "Each Fantomas release is expected to have at least one section."
| Some cd ->
let version = $"{v.Major}.{v.Minor}.{v.Patch}"
let title =
let month = d.ToString("MMMM")
let day = d.Day.Ordinalize()
$"{month} {day} Release"
let prefixedVersion = $"v{version}"
let publishDate =
let cmdResult =
Cli
.Wrap("gh")
.WithArguments($"release view {prefixedVersion} --json publishedAt -t \"{{{{.publishedAt}}}}\"")
.WithValidation(CommandResultValidation.None)
.ExecuteBufferedAsync()
.Task.Result
if cmdResult.ExitCode <> 0 then
None
else
let output = cmdResult.StandardOutput.Trim()
let lastIdx = output.LastIndexOf("Z", StringComparison.Ordinal)
Some(output.Substring(0, lastIdx))
let sections =
[ "Added", cd.Added
"Changed", cd.Changed
"Fixed", cd.Fixed
"Deprecated", cd.Deprecated
"Removed", cd.Removed
"Security", cd.Security
yield! (Map.toList cd.Custom) ]
|> List.choose (fun (header, lines) ->
if lines.IsEmpty then
None
else
lines
|> List.map (fun line -> line.TrimStart())
|> String.concat "\n"
|> sprintf "### %s\n%s" header
|> Some)
|> String.concat "\n\n"
let draft =
$"""# {version}
{sections}"""
{ Version = version
Title = title
Date = d
PublishedDate = publishDate
Draft = draft }
let getReleaseNotes currentRelease (lastRelease: GithubRelease) =
let date = lastRelease.PublishedDate.Value
let authorMsg =
let authors =
Cli
.Wrap("gh")
.WithArguments(
$"pr list -S \"state:closed base:main closed:>{date} -author:app/robot\" --json author --jq \".[].author.login\""
)
.ExecuteBufferedAsync()
.Task.Result.StandardOutput.Split([| '\n' |], StringSplitOptions.RemoveEmptyEntries)
|> Array.distinct
|> Array.sort
if authors.Length = 1 then
$"Special thanks to @%s{authors.[0]}!"
else
let lastAuthor = Array.last authors
let otherAuthors =
if authors.Length = 2 then
$"@{authors.[0]}"
else
authors
|> Array.take (authors.Length - 1)
|> Array.map (sprintf "@%s")
|> String.concat ", "
$"Special thanks to %s{otherAuthors} and @%s{lastAuthor}!"
$"""{currentRelease.Draft}
{authorMsg}
[https://www.nuget.org/packages/fantomas/{currentRelease.Version}](https://www.nuget.org/packages/fantomas/{currentRelease.Version})
"""
let getCurrentAndLastReleaseFromChangelog () =
let changelog = FileInfo(__SOURCE_DIRECTORY__ </> "CHANGELOG.md")
let changeLogResult =
match Parser.parseChangeLog changelog with
| Error error -> failwithf "%A" error
| Ok result -> result
let lastReleases =
changeLogResult.Releases
|> List.filter (fun (v, _, _) -> String.IsNullOrEmpty v.Prerelease)
|> List.sortByDescending (fun (_, d, _) -> d)
|> List.take 2
match lastReleases with
| [ current; last ] -> mkGithubRelease current, mkGithubRelease last
| _ -> failwith "Could not find the current and last release from CHANGELOG.md"
pipeline "Release" {
workingDir __SOURCE_DIRECTORY__
stage "Release" {
run (fun _ ->
async {
let currentRelease, lastRelease = getCurrentAndLastReleaseFromChangelog ()
if Option.isSome currentRelease.PublishedDate then
return 0
else
// Push packages to NuGet
let nugetPackages =
Directory.EnumerateFiles("artifacts/package/release", "*.nupkg", SearchOption.TopDirectoryOnly)
|> Seq.filter (fun nupkg -> not (nupkg.Contains("Fantomas.Client")))
|> Seq.toArray
let! nugetExitCodes = nugetPackages |> Array.map pushPackage |> Async.Sequential
let notes = getReleaseNotes currentRelease lastRelease
let noteFile = Path.GetTempFileName()
File.WriteAllText(noteFile, notes)
let files = nugetPackages |> String.concat " "
// We create a draft release for minor and majors. Those that requires a manual publish.
// This is to allow us to add additional release notes when it makes sense.
let! draftResult =
let isDraft =
let isRevision = lastRelease.Version.Split('.') |> Array.last |> int |> (<>) 0
if isRevision then String.Empty else "--draft"
Cli
.Wrap("gh")
.WithArguments(
$"release create v{currentRelease.Version} {files} {isDraft} --title \"{currentRelease.Title}\" --notes-file \"{noteFile}\""
)
.WithValidation(CommandResultValidation.None)
.ExecuteAsync()
.Task
|> Async.AwaitTask
if File.Exists noteFile then
File.Delete(noteFile)
return Seq.max [| yield! nugetExitCodes; yield draftResult.ExitCode |]
})
}
runIfOnlySpecified true
}
tryPrintPipelineCommandHelp ()