Created
December 3, 2013 22:36
-
-
Save andreadipersio/7778862 to your computer and use it in GitHub Desktop.
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" | |
"flag" | |
"strings" | |
"os/exec" | |
"net/http" | |
"encoding/json" | |
) | |
var ( | |
httpPort int | |
watchRepo string | |
) | |
func init() { | |
flag.IntVar(&httpPort, "port", 26000, "HTTP Server port") | |
flag.StringVar(&watchRepo, "repo", "", "Repository name") | |
flag.Parse() | |
} | |
type PostReceiveHook struct { | |
Ref string | |
Repository struct { | |
Name string | |
} | |
HeadCommit struct { | |
Added, Modified, Removed []string | |
} `json:"head_commit"` | |
} | |
func rootHandler(w http.ResponseWriter, r *http.Request) { | |
payload := r.FormValue("payload") | |
postHook := &PostReceiveHook{} | |
var cmdName string | |
if err := json.Unmarshal([]byte(payload), postHook); err != nil { | |
log.Printf("Cannot decode: %v", err) | |
http.Error(w, fmt.Sprintf("Cannot decode: %v", err), 500) | |
return | |
} | |
hasChanged := func() (branch string) { | |
repoName, ref := postHook.Repository.Name, postHook.Ref | |
if repoName != watchRepo { | |
log.Println("Wrong repo!") | |
return "" | |
} | |
if refParts := strings.Split(ref, "/"); len(refParts) == 0 { | |
log.Println("Ref is empty, should not be!") | |
return "" | |
} else { | |
branch = refParts[len(refParts) - 1] | |
} | |
return | |
} | |
branch := hasChanged() | |
if branch == "" { | |
log.Println("Unchanged") | |
return | |
} else { | |
cmdName = fmt.Sprintf("statics-%v-post-commit.sh", branch) | |
log.Printf("Branch %v has changed, executing hook: %v", branch, cmdName) | |
} | |
cmd := exec.Command(cmdName) | |
if err := cmd.Run(); err != nil { | |
log.Printf("Cannot execute hook: %v", err) | |
http.Error(w, fmt.Sprintf("Cannot run post commit hook: %v", err), 500) | |
return | |
} | |
fmt.Fprint(w, "OK") | |
} | |
func main() { | |
httpAddr := fmt.Sprintf(":%v", httpPort) | |
log.Printf("Listening on: %v", httpAddr) | |
http.HandleFunc("/favicon.ico", http.NotFound) | |
http.HandleFunc("/", rootHandler) | |
log.Fatal(http.ListenAndServe(httpAddr, nil)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment