
钩子脚本代码如下,(用swift写的钩子脚本):
#!/usr/bin/env xcrun swift
import Foundation
let commitMessageFile = CommandLine.arguments[1]
print("LBLog commitMessageFile \(commitMessageFile)")
guard let data = FileManager.default.contents(atPath: commitMessageFile), let commitMessage = String(data: data, encoding: .utf8) else{
// 返回状态码大于1 终止此次提交
exit(1)
}
func shell(_ command: String) -> String {
let task = Process()
let outputPipe = Pipe()
let errorPipe = Pipe()
task.standardOutput = outputPipe
task.standardError = errorPipe
task.arguments = ["-c", command]
task.executableURL = URL(fileURLWithPath: "/bin/zsh")
do {
try task.run()
task.waitUntilExit()
} catch {
print("There was an error running the command: \(command)")
print(error.localizedDescription)
exit(1)
}
guard let outputData = try? outputPipe.fileHandleForReading.readToEnd(),
let outputString = String(data: outputData, encoding: .utf8) else {
// Print error if needed
if let errorData = try? errorPipe.fileHandleForReading.readToEnd(),
let errorString = String(data: errorData, encoding: .utf8) {
print("Encountered the following error running the command:")
print(errorString)
}
exit(1)
}
return outputString
}
func writeAppendString(prefix: String) {
print("LBLog final commit msg is \(prefix) \(commitMessage)")
do {
try "\(prefix) \(commitMessage.trimmingCharacters(in: .newlines))"
.write(toFile: commitMessageFile, atomically: true, encoding: .utf8)
} catch {
print("Could not write to file \(commitMessageFile)")
exit(1)
}
}
//校验提交的msg是否格式正确 正确直接提交
//feat:s-15890 对接租约中心
func checkCommitMsgIsRight(){
guard let regex = try? NSRegularExpression(pattern: #"[:][S s]-\d{1,10} [\u4e00-\u9fa5 a-z A-Z]{3,}"#, options: .anchorsMatchLines),
let _ = regex.firstMatch(in: commitMessage, range: NSRange.init(location: 0, length: commitMessage.count)) else {
print("LBLog input commit msg is not valid formatter , will auto change it")
return
}
// 输入的格式正确 直接exit掉
exit(0)
}
checkCommitMsgIsRight()
let gitBranchName = shell("git rev-parse --abbrev-ref HEAD")
.trimmingCharacters(in: .newlines)
let stringRange = NSRange(location: 0, length: gitBranchName.utf16.count)
//分支不是S-11825-11807-11688-09月28号-上线分支的格式的
guard let regex = try? NSRegularExpression(pattern: #"[S s]-.*-"#, options: .anchorsMatchLines),
let match = regex.firstMatch(in: gitBranchName, range: stringRange) else {
//没有匹配到 把分支名拼上
writeAppendString(prefix: "feat:s-\(gitBranchName)")
exit(0)
}
let range = match.range(at: 0)
let ticketNumber = (gitBranchName as NSString)
.substring(with: range)
.trimmingCharacters(in: .newlines)
if !commitMessage.contains(ticketNumber) {
let prefix = (ticketNumber as NSString).substring(to: ticketNumber.count - 1)
writeAppendString(prefix: "feat:\(prefix)")
}
网友评论