This repository was archived by the owner on Sep 5, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathmain.go
More file actions
100 lines (86 loc) · 1.79 KB
/
main.go
File metadata and controls
100 lines (86 loc) · 1.79 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
package main
import (
"encoding/json"
"flag"
"io/ioutil"
"log"
"net/http"
"os"
"os/exec"
)
type Repository struct {
Name string
}
type GithubJson struct {
Repository Repository
Ref string
}
type Config struct {
Hooks []Hook
}
type Hook struct {
Repo string
Branch string
Shell string
}
func loadConfig(configFile *string) {
var config Config
configData, err := ioutil.ReadFile(*configFile)
if err != nil {
log.Fatal(err)
}
err = json.Unmarshal(configData, &config)
if err != nil {
log.Fatal(err)
}
for i := 0; i < len(config.Hooks); i++ {
addHandler(config.Hooks[i].Repo, config.Hooks[i].Branch, config.Hooks[i].Shell)
}
}
func setLog(logFile *string) {
log_handler, err := os.OpenFile(*logFile, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0777)
if err != nil {
panic("cannot write log")
}
log.SetOutput(log_handler)
log.SetFlags(5)
}
func startWebserver() {
log.Println("starting webserver")
http.ListenAndServe(":"+*port, nil)
}
func addHandler(repo, branch, shell string) {
uri := branch
branch = "refs/heads/" + branch
http.HandleFunc("/"+repo+"_"+uri, func(w http.ResponseWriter, r *http.Request) {
decoder := json.NewDecoder(r.Body)
var data GithubJson
err := decoder.Decode(&data)
if err != nil {
log.Println(err)
}
if data.Repository.Name == repo && data.Ref == branch {
executeShell(shell)
}
})
}
func executeShell(shell string) {
out, err := exec.Command(shell).Output()
if err != nil {
log.Fatal(err)
}
log.Printf("Shell output was: %s\n", out)
}
var (
port = flag.String("port", "7654", "port to listen on")
configFile = flag.String("config", "./config.json", "config")
logFile = flag.String("log", "./log", "log file")
)
func init() {
flag.Parse()
}
func main() {
setLog(logFile)
loadConfig(configFile)
startWebserver()
}