Last active
July 13, 2016 19:07
-
-
Save kylebrandt/c4c9099118bea6e4ab793e6b657a1c2c to your computer and use it in GitHub Desktop.
hook for bosun conf file saving to push to git
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"log" | |
"os" | |
"os/exec" | |
"path/filepath" | |
) | |
const Git = "git" | |
func main() { | |
if len(os.Args) < 4 { | |
log.Fatal("error: not enough arguments, expected filename, user, message") | |
} | |
fileArg := os.Args[1] | |
user := os.Args[2] | |
message := os.Args[3] | |
if fileArg == "" { | |
log.Fatal("error: missing config file name") | |
} | |
if user == "" { | |
log.Fatal("error: missing user") | |
} | |
if message == "" { | |
log.Fatal("error: missing message") | |
} | |
fileDir := filepath.Dir(fileArg) | |
gitCommand := func(args ...string) (string, error) { | |
args = append([]string{"-C", fileDir}, args...) | |
gitCmd := exec.Command(Git, args...) | |
output, err := gitCmd.CombinedOutput() | |
if err != nil { | |
return string(output), err | |
} | |
return string(output), nil | |
} | |
// We clean (except maybe other files) | |
output, err := gitCommand("status", "-uno", "--porcelain") | |
if err != nil { | |
log.Fatal(fmt.Sprintf("failed to get git status to see if the working tree is clean")) | |
} | |
if output == "" { | |
log.Println("nothing to do since the working tree is clean") | |
os.Exit(0) | |
} | |
// Commit | |
output, err = gitCommand("commit", "-a", "-m", message, "--author", user) | |
if err != nil { | |
log.Fatal(fmt.Sprintf("could not issue commit: %v %v", err, output)) | |
} | |
// Push | |
output, err = gitCommand("push", "origin", "master") | |
if err != nil { | |
_, err2 := gitCommand("git", "reset", "HEAD", "--hard") | |
gitReset := "successful" | |
if err2 != nil { | |
gitReset = "failed" | |
} | |
log.Fatal(fmt.Sprintf("could not issue commit (issued a git reset hard which was %v): %v %v", gitReset, err, output)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment