-
Notifications
You must be signed in to change notification settings - Fork 1
/
Dangerfile.swift
542 lines (380 loc) · 15.2 KB
/
Dangerfile.swift
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
import Foundation
import Danger
import DangerXCodeSummary // package: https://github.com/f-meloni/danger-swift-xcodesummary.git
import DangerSwiftCoverage // package: https://github.com/f-meloni/danger-swift-coverage.git
import DangerSwiftHammer // package: https://github.com/el-hoshino/DangerSwiftHammer.git
// swiftlint:disable file_length function_body_length
// MARK: - Variables those may change according to each project
let changelogPath = "CHANGELOG.md"
let versionSpecifyingFile = "project.yml"
let versionSpecifyingText = "MARKETING_VERSION: "
// MARK: - A structure to introduce checking result
struct CheckResult {
let title: String
private(set) var warningsCount = 0
private(set) var errorsCount = 0
enum Result {
case good
case acceptable
case rejected
var markdownSymbol: String {
switch self {
case .good:
return ":tada:"
case .acceptable:
return ":thinking:"
case .rejected:
return ":no_good:"
}
}
}
typealias Message = (content: String, result: Result)
private var messages: [Message] = []
private var todos: [String] = []
init(title: String) {
self.title = title
}
mutating func askReviewer(to taskToDo: String) {
todos.append(taskToDo)
}
mutating func check(_ item: String, execution: () -> Result) {
let result = execution()
messages.append((item, result))
switch result {
case .good:
break
case .acceptable:
warningsCount += 1
case .rejected:
errorsCount += 1
}
}
var markdownTitle: String {
"### " + title
}
var markdownMessage: String {
let chartHeader = """
Checking Item | Result
| ---| --- |
"""
let chartContent = messages.map {
"\($0.content) | \($0.result.markdownSymbol)"
} .joined(separator: "\n")
return chartHeader + chartContent
}
var markdownTodos: String {
let todoContent = todos.map {
"- [ ] \($0)"
}
return todoContent.joined(separator: "\n")
}
}
// MARK: - DangerDSL computed properties
extension DangerDSL {
private var headBranch: String {
github.pullRequest.head.ref
}
private var baseBranch: String {
github.pullRequest.base.ref
}
private var additions: Int {
github.pullRequest.additions ?? 0
}
private var deletions: Int {
github.pullRequest.deletions ?? 0
}
private var diffLinesCount: Int {
additions + deletions
}
private func hasModifiedFile(at filepath: String) -> Bool {
git.modifiedFiles.contains(where: { $0 == filepath })
}
var githubIssue: String? {
headBranch.substring(of: #"issue/(\d+)"#, options: .regularExpression)
}
var hasBootstrapSHFileBeenModified: Bool {
hasModifiedFile(at: "bootstrap.sh")
}
var hasBrewfileBeenModified: Bool {
hasModifiedFile(at: "Brewfile")
}
var hasChangelogBeenModified: Bool {
hasModifiedFile(at: changelogPath)
}
var hasMarketingVersionBeenModified: Bool {
hammer.diffLines(in: versionSpecifyingFile).additions.contains(where: { $0.contains(versionSpecifyingText) })
}
var isDevelopPR: Bool {
// Treat PRs merging into develop branch as a develop PR
baseBranch == "develop"
}
var isReleasePR: Bool {
// Treat PRs merging into master branch as a release PR
baseBranch == "master"
}
}
// MARK: - DangerDSL PR content check
extension DangerDSL {
enum BranchType {
case master
case develop
case feature
case refactor
case fix
case issue
case version
case ci
static func parsed(from branchName: String) -> BranchType? {
switch branchName {
case "master":
return .master
case "develop":
return .develop
case let feature where feature.hasPrefix("feature/"):
return .feature
case let refactor where refactor.hasPrefix("refactor/"):
return .refactor
case let fix where fix.hasPrefix("fix/"):
return .fix
case let issue where issue.hasPrefix("issue/"):
return .issue
case let version where version.hasPrefix("version/"):
return .version
case let ci where ci.hasPrefix("ci/"):
return .ci
case _:
return nil
}
}
}
func isHeadBranch(_ branchType: BranchType) -> Bool {
BranchType.parsed(from: headBranch) == branchType
}
func isHeadBranch(anyOf branchTypes: [BranchType]) -> Bool {
branchTypes.contains(where: { isHeadBranch($0) })
}
func isBaseBranch(_ branchType: BranchType) -> Bool {
BranchType.parsed(from: baseBranch) == branchType
}
}
// MARK: - DangerDSL modifications content check
extension DangerDSL {
// Auto PR created by CI
func checkCIAutoPRModification(into result: inout CheckResult) {
result.askReviewer(to: "Check if the automatically-created-by-CI content is correct.")
warn("This PR is created by CI automatically. Please check if the content is correct.")
}
func checkDevelopmentModification(into result: inout CheckResult) {
// It's encouraged to edit changelog in a develop PR
let doChangelogModificationCheckTitle = "Changelog Modification Check"
result.check(doChangelogModificationCheckTitle) {
if hasChangelogBeenModified {
return .good
} else {
warn("This PR doesn't contain any modifications to changelog. Please consider if it's necessary to edit it.")
return .acceptable
}
}
}
func checkReleaseModification(into result: inout CheckResult) {
// It's encouraged to check if there's any issue left before releasing a version
result.askReviewer(to: "Check open issues")
warn("This is a release PR. Please check if there's any issue left to be resolved.")
// It's required to change version number.
let doVersionModificationCheckTitle = "Version Modification Check"
result.check(doVersionModificationCheckTitle) {
if hasMarketingVersionBeenModified {
warn("This is a release PR. Please check if the version has been correctly modified.")
return .acceptable
} else {
fail("This is a release PR, but it seems there's no version modification, which is requried.")
return .rejected
}
}
// It's strongly encouraged to edit changelog in a release PR.
let doChangelogModificationCheckTitle = "Changelog Modification Check"
result.check(doChangelogModificationCheckTitle) {
if hasChangelogBeenModified {
warn("This is a release PR. Please check if the changelog has been correctly modified.")
return .acceptable
} else {
fail("This is a release PR, but it seems there's no changelog modification, which is strongly encouraged.")
return .rejected
}
}
if hasChangelogBeenModified {
result.askReviewer(to: doChangelogModificationCheckTitle)
}
}
}
// MARK: - DangerDSL PR review flow
extension DangerDSL {
func doDevelopPRCheck() -> CheckResult {
var result = CheckResult(title: "Develop PR Check")
// Develop PR should be created from a branch which begins with either `feature/`、`refactor/` 、`fix/`、`issue/`, `version/` or `ci/`.
let doHeadBranchCheckTitle = "PR Head Branch Check"
let validBranches: [BranchType] = [
.feature,
.refactor,
.fix,
.issue,
.version,
.ci,
]
result.check(doHeadBranchCheckTitle) {
if isHeadBranch(anyOf: validBranches) {
return .good
} else {
fail("Please create a develop PR from either a feature, refactor, fix, issue or version branch.")
return .rejected
}
}
// Develop PR should be created into develop branch
let doBaseBranchCheckTitle = "PR Base Branch Check"
result.check(doBaseBranchCheckTitle) {
if isBaseBranch(.develop) {
return .good
} else {
fail("Please create a develop PR into develop branch.")
return .rejected
}
}
// Develop PR shouldn't contain any merge commits.
let doNoMergeCommitsCheckTitle = "Merge Commits Excluded Check"
result.check(doNoMergeCommitsCheckTitle) {
if github.commits.allSatisfy({ $0.commit.parents == nil }) {
return .good
} else {
fail("Develop PR should not contain any merge commits. Please consider rebasing if needed.")
return .rejected
}
}
// The volume of diff should not be over 1,000 lines.
let doDiffAmountCheckTitle = "Diff Volume Check"
result.check(doDiffAmountCheckTitle) {
if diffLinesCount <= 1000 {
return .good
} else {
warn("There's too much diff. Please consider splitting this PR.")
return .acceptable
}
}
if isHeadBranch(.ci) {
// If the PR is created from the branch created by CI, do the CI auto PR modification check.
checkCIAutoPRModification(into: &result)
} else if isHeadBranch(.version) {
// If the PR is created from a version branch, do the release modification check.
checkReleaseModification(into: &result)
} else {
// Otherwise, do the develop modification check.
checkDevelopmentModification(into: &result)
}
return result
}
func doReleasePRCheck() -> CheckResult {
var result = CheckResult(title: "Release PR Check")
// Release PR should be created from develop branch.
let doHeadBranchCheckTitle = "PR Head Branch Check"
result.check(doHeadBranchCheckTitle) {
if isHeadBranch(.develop) {
return .good
} else {
fail("Please create a release PR from develop branch.")
return .rejected
}
}
// Develop PR should be created into master branch
let doBaseBranchCheckTitle = "PR Base Branch Check"
result.check(doBaseBranchCheckTitle) {
if isBaseBranch(.master) {
return .good
} else {
fail("Please create a release PR into master branch.")
return .rejected
}
}
// Do the release modification check.
checkReleaseModification(into: &result)
return result
}
enum RoutineError: Error {
case failedToFindCheckRoutine
}
func checkPR() throws -> CheckResult {
if isDevelopPR {
return doDevelopPRCheck()
} else if isReleasePR {
return doReleasePRCheck()
} else {
throw RoutineError.failedToFindCheckRoutine
}
}
}
// MARK: - Other convenient extensions
private extension Git {
var diffFiles: [File] {
createdFiles + deletedFiles + modifiedFiles
}
}
private extension XCodeSummary {
convenience init(filePath: String, onlyShowSummaryInDiffFiles: Bool) {
if onlyShowSummaryInDiffFiles {
let diffFiles = Danger().git.diffFiles
self.init(filePath: filePath) { [diffFiles] in
guard let path = $0.file else { return false }
return diffFiles.contains(path)
}
} else {
self.init(filePath: filePath)
}
}
}
private extension String {
func substring <S: StringProtocol> (of string: S, options: CompareOptions) -> String? {
guard let range = range(of: string, options: options) else {
return nil
}
return String(self[range])
}
}
private extension ProcessInfo {
static var xcTestResultPath: String {
// If running on Bitrise it should be able to get path from `$BITRISE_XCRESULT_PATH` variable
processInfo.environment["BITRISE_XCRESULT_PATH"] ??
// Else if running locally, remember to pass `Test.xcresult` to `-resultBundlePath` parameter in `xcodebuild` command
"Test.xcresult"
}
}
// MARK: - Check routine
let danger = Danger()
// If there's any modification in bootstrap.sh file, ask the reviewer to check if he needs to update Bitrise workflows.
if danger.hasBrewfileBeenModified {
markdown("- [ ] Check bitrise workflow")
warn("There's modification in bootstrap.sh file. Please remember to check if needed to update Bitrise workflow.")
}
// If the head branch refers to a GitHub issue, comment it in the PR page.
if let githubIssue = danger.githubIssue {
message("Resolve #\(githubIssue)")
}
// SwiftLint format check.
SwiftLint.lint(.modifiedAndCreatedFiles(directory: nil), inline: true)
// Xcode summary warnings check.
XCodeSummary(filePath: "result.json", onlyShowSummaryInDiffFiles: true).report()
// Xcode test coverage check.
Coverage.xcodeBuildCoverage(.xcresultBundle(ProcessInfo.xcTestResultPath), minimumCoverage: 60)
// PR routine check.
do {
let result = try danger.checkPR()
markdown(result.markdownTitle)
if !result.markdownMessage.isEmpty {
markdown(result.markdownMessage)
}
if !result.markdownTodos.isEmpty {
markdown(result.markdownTodos)
}
if result.warningsCount == 0 && result.errorsCount == 0 {
message("Well Done :white_flower:")
}
} catch {
fail("Failed to find out the correct check routine. Please check if your PR is created from or into a correct branch.")
}