-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPostRewriteHookCommand.swift
More file actions
104 lines (76 loc) Β· 3 KB
/
PostRewriteHookCommand.swift
File metadata and controls
104 lines (76 loc) Β· 3 KB
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
import Foundation
import PathKit
import Commander
import SwiftCLIToolbox
public class PostRewriteHookCommand: CommandProtocol {
public static func make() -> CommandType {
let postRewriteHookCommand = command {
let action = PostRewriteHookCommandAction()
action.doAction()
}
return postRewriteHookCommand
}
}
struct CommitDiff {
var oldHash: String
var newHash: String
}
class PostRewriteHookCommandAction {
lazy var provider = CommitsDiffReader()
lazy var git: GitProtocol.Type = Git.self
lazy var system: SystemProtocol = System()
lazy var request = CommentRequest.defaultRequest()
func doAction() {
let commitsDiff = provider.commitsDiff()
let repoName = git.repoName()
let branchName = git.branchName()
commitsDiff.forEach { commitDiff in
guard let issuesNumber = processIssuesNumber(commitDiff) else {
return
}
let content =
"""
Commit already rewrite,
\(commitDiff.oldHash) -> \(commitDiff.newHash)
\(commitMessage(commitDiff))
"""
let context = CommentContext(content: content,
authorName: authorName(commitDiff),
gitRepoName: repoName,
gitBranchName: branchName)
issuesNumber.forEach({ issueNumber in
request.send(to: issueNumber, wtih: context)
})
}
}
private func commitMessage(_ commitDiff: CommitDiff) -> String {
guard let commitMessage = git.commitMessage(commitDiff.newHash) else {
system.printFatalError("Ran `git show` fail with sha \(commitDiff.newHash)")
}
return commitMessage
}
private func authorName(_ commitDiff: CommitDiff) -> String {
guard let authorName = git.authorName(commitDiff.newHash) else {
system.printFatalError("Ran `git show` fail with sha \(commitDiff.newHash)")
}
return authorName
}
private func processIssuesNumber(_ commitDiff: CommitDiff) -> [Int]? {
guard let issuesNumber = git.commitTitle(commitDiff.newHash)?.findIssuesNumber() else {
return nil
}
// Remove issue string's `#`, i.g. #12345 -> 12345
return issuesNumber.map { Int($0.dropFirst())! }
}
}
class CommitsDiffReader {
public func commitsDiff() -> [CommitDiff] {
var commitsDiff = [CommitDiff]()
while let string = readLine() {
let hashSplit = string.split(separator: " ").map{ String($0) }
let commitDiff = CommitDiff(oldHash: hashSplit[0], newHash: hashSplit[1])
commitsDiff.append(commitDiff)
}
return commitsDiff
}
}