Skip to content

Instantly share code, notes, and snippets.

@kruperfone
Created October 7, 2019 14:18
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kruperfone/ee842f5186af32b4be0669a79b6ee535 to your computer and use it in GitHub Desktop.
Save kruperfone/ee842f5186af32b4be0669a79b6ee535 to your computer and use it in GitHub Desktop.
#!/usr/bin/swift
/* Git commit hook. Place it into your .git/hooks folder with 'prepare-commit-msg' name
#!/bin/sh
echo "Start prepare-commit-msg hook"
COMMIT_MSG_FILE=$1
COMMIT_SOURCE=$2
#SHA1=$3
PATH=path-to-file
PREFIX=prefix
swift $PATH $PREFIX $COMMIT_MSG_FILE $COMMIT_SOURCE
echo "End prepare-commit-msg hook"
*/
import Foundation
// MARK: Bash
func shell(launchPath: String, arguments: [String]) -> String
{
let task = Process()
task.launchPath = launchPath
task.arguments = arguments
let pipe = Pipe()
task.standardOutput = pipe
task.launch()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = String(data: data, encoding: String.Encoding.utf8)!
if output.count > 0 {
//remove newline character.
let count = output.count-1
return String(output.prefix(count))
}
return output
}
func bash(_ command: String, _ arguments: String...) -> String {
let whichPathForCommand = shell(launchPath: "/bin/bash", arguments: [ "-l", "-c", "which \(command)" ])
return shell(launchPath: whichPathForCommand, arguments: arguments)
}
// MARK: Helpers
func extractTicket(branch: String) -> String? {
guard let data = branch.split(separator: "/").last?.split(separator: "-").map({ String($0) }) else { return nil }
guard data.count >= 2 else { return nil }
guard data[0] == ticketPrefix else { return nil }
guard let number = Int(data[1]) else { return nil }
return "\(ticketPrefix)-\(number)"
}
// MARK: Script
let ticketPrefix = CommandLine.arguments[1]
let commitMessageFile = "\(bash("pwd"))/\(CommandLine.arguments[2])"
let commitSource = CommandLine.arguments[3]
let branch = bash("git", "symbolic-ref", "--short", "HEAD")
let ignoredCommitSources = ["merge"]
func main() throws {
print("Commit source: \(commitSource)")
print("Ticket prefix: \(ticketPrefix)")
print("Branch name: \(branch)")
guard !ignoredCommitSources.contains(commitSource) else {
print("Ignored commit source: \(commitSource)")
return
}
guard let ticket = extractTicket(branch: branch) else {
print("Ticket can not be extracted")
return
}
let commitText = try String(contentsOfFile: commitMessageFile, encoding: .utf8)
let editedCommit = "\(commitText)\n\n\(ticket)"
try editedCommit.write(toFile: commitMessageFile, atomically: false, encoding: .utf8)
print("Attached ticket: \(ticket)")
}
do {
try main()
} catch let error {
print(error.localizedDescription)
fatalError()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment