/
main.go
346 lines (301 loc) · 7.72 KB
/
main.go
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
package main
import (
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"os/exec"
"path/filepath"
"sync"
"gopkg.in/yaml.v2"
)
type config struct {
App struct {
Remote struct {
SiteRepo string `yaml:"site_repo"`
PostsRepo string `yaml:"posts_repo"`
Username string `yaml:"username"`
Password string `yaml:"password"`
}
}
}
type proxy struct {
Server http.Handler
}
func (p *proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
p.Server.ServeHTTP(w, r)
}
const (
BUILD_A = "BUILD_A"
BUILD_B = "BUILD_B"
SITE_DIR = "./jekyll"
POSTS_DIR = "./jekyll/_posts"
UPLOADS_DIR = "./jekyll/uploads"
POSTS_REPO_DIR = "./posts"
DEFAULT_SETTINGS_PATH = "./defaults.yml"
SETTINGS_PATH = "./settings.yml"
)
var (
settings config
jekyllRepo string
postsRepo string
currentBuild string
buildAFileServer http.Handler
buildBFileServer http.Handler
mu sync.Mutex
currentServer proxy
currentPostsHash string
currentSiteHash string
)
func main() {
// Read our config from settings.yml
err := readSettings()
if err != nil {
log.Fatal(err)
}
// Construct the repo strings (with username/password)
jekyllRepo = fmt.Sprintf(
settings.App.Remote.SiteRepo,
settings.App.Remote.Username,
settings.App.Remote.Password,
)
postsRepo = fmt.Sprintf(
settings.App.Remote.PostsRepo,
settings.App.Remote.Username,
settings.App.Remote.Password,
)
// Make sure the build folders exist
err = initStaticDirectories()
if err != nil {
log.Fatal("Could not init Build Directories")
}
// Get updated Jekyll Site
err = updateRepo(jekyllRepo, SITE_DIR)
if err != nil {
log.Fatal("Could not update from Jekyll Repo")
}
// Get updated posts
err = updateRepo(postsRepo, POSTS_REPO_DIR)
if err != nil {
log.Fatal("Could not update from Posts Repo")
}
// Track the jekyll repo's latest hash
currentSiteHash, err = getMasterHash(SITE_DIR)
if err != nil {
log.Fatal("Could not get SHA1 hash of origin/master from Site Repo")
}
// Track the posts repo's latest hash
currentPostsHash, err = getMasterHash(POSTS_REPO_DIR)
if err != nil {
log.Fatal("Could not get SHA1 hash of origin/master from Posts Repo")
}
// Symlink the "posts" and "uploads" folder into the jekyll folder
err = symlinkDirs()
if err != nil {
log.Println("Could not symlink posts and uploads dir into jekyll dir")
log.Fatal(err)
}
// Run Jekyll Command to Build Site
err = buildSite("./" + BUILD_A)
if err != nil {
log.Fatal("Could not build site")
}
// Our http handlers
buildAFileServer = http.FileServer(http.Dir("./" + BUILD_A))
buildBFileServer = http.FileServer(http.Dir("./" + BUILD_B))
// We initially build into "BUILD_A" folder
currentBuild = BUILD_A
currentServer.Server = buildAFileServer
// Serve the site
mux := http.NewServeMux()
mux.Handle("/", ¤tServer)
// Our endpoint to handle git webhook
mux.HandleFunc("/__updateposts__", handleGitWebhook)
http.ListenAndServe(":8080", mux)
}
func handleGitWebhook(w http.ResponseWriter, r *http.Request) {
mu.Lock()
defer mu.Unlock()
// Get up-to-date jekyll site + posts
err := updateRepo(jekyllRepo, SITE_DIR)
if err != nil {
log.Printf("Could not update Jekyll Repo: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
err = updateRepo(postsRepo, POSTS_REPO_DIR)
if err != nil {
log.Printf("Could not update Posts Repo: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
// Get the latest origin/master hashes
postsHash, err := getMasterHash(POSTS_REPO_DIR)
if err != nil {
log.Printf("Could not get updated post hash: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
siteHash, err := getMasterHash(SITE_DIR)
if err != nil {
log.Printf("Could not get updated site hash: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
// Symlink the "posts" and "uploads" folder into the jekyll folder
err = symlinkDirs()
if err != nil {
log.Printf("Could not resymlink: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
// Try to rebuild the site if the hashes are different
if (postsHash != currentPostsHash) || (siteHash != currentSiteHash) {
dest := "./" + BUILD_A
if currentBuild == BUILD_A {
dest = "./" + BUILD_B
}
err = buildSite(dest)
if err != nil {
log.Println("Error occured while trying to build the site")
w.WriteHeader(http.StatusInternalServerError)
return
}
// Build was successful; we update the current hash to track
// the new hashes and begin serving the site from the new build folder
currentPostsHash = postsHash
currentSiteHash = siteHash
if currentBuild == BUILD_A {
currentBuild = BUILD_B
currentServer.Server = buildBFileServer
} else {
currentBuild = BUILD_A
currentServer.Server = buildAFileServer
}
log.Printf("Successfully Built Site to: %s", currentBuild)
w.WriteHeader(http.StatusOK)
return
}
w.WriteHeader(http.StatusNoContent)
}
// Read settings from Yaml Files
func readSettings() (err error) {
defaultSettings, err := ioutil.ReadFile(DEFAULT_SETTINGS_PATH)
if err != nil {
return err
}
err = yaml.Unmarshal(defaultSettings, &settings)
if err != nil {
return err
}
// Check if there is a settings.yml to read (for overrides)
if _, err := os.Stat(SETTINGS_PATH); err == nil {
fileSettings, err := ioutil.ReadFile(SETTINGS_PATH)
if err != nil {
return err
}
err = yaml.Unmarshal(fileSettings, &settings)
if err != nil {
return err
}
}
return nil
}
// Create BUILD Folders
func initStaticDirectories() (err error) {
if _, err := os.Stat("./" + BUILD_A); os.IsNotExist(err) {
err = os.Mkdir("./"+BUILD_A, 0755)
if err != nil {
return err
}
} else {
return err
}
if _, err := os.Stat("./" + BUILD_B); os.IsNotExist(err) {
err = os.Mkdir("./"+BUILD_B, 0755)
if err != nil {
return err
}
} else {
return err
}
return nil
}
// Update any Repos
func updateRepo(repo string, dest string) (err error) {
_, err = os.Stat(dest)
// Clone it if the folder doesn't exist
if err != nil {
if os.IsNotExist(err) {
err = exec.Command("git", "clone", repo, dest).Run()
if err != nil {
return err
}
} else {
return err
}
}
// Update otherwise with "git fetch; git reset; git clean"
cmd := exec.Command("git", "fetch", "origin")
cmd.Dir = dest
err = cmd.Run()
if err != nil {
return err
}
cmd = exec.Command("git", "reset", "origin/master", "--hard")
cmd.Dir = dest
err = cmd.Run()
if err != nil {
return err
}
cmd = exec.Command("git", "clean", "-f", "-x", "-d")
cmd.Dir = dest
err = cmd.Run()
if err != nil {
return err
}
return nil
}
func symlinkDirs() (err error) {
err = os.RemoveAll(SITE_DIR + "/_posts")
if err != nil {
return err
}
err = os.RemoveAll(SITE_DIR + "/uploads")
if err != nil {
return err
}
postsAbs, err := filepath.Abs(POSTS_REPO_DIR + "/posts")
if err != nil {
return errors.New("Unable to get absolute path of posts directory")
}
uploadsAbs, err := filepath.Abs(POSTS_REPO_DIR + "/uploads")
if err != nil {
return errors.New("Unable to get absolute path of uploads directory")
}
err = os.Symlink(postsAbs, SITE_DIR+"/_posts")
if err != nil {
return err
}
err = os.Symlink(uploadsAbs, SITE_DIR+"/uploads")
if err != nil {
return err
}
return nil
}
// Get the hash of origin/master for a repo
func getMasterHash(repoDir string) (hash string, err error) {
cmd := exec.Command("git", "rev-parse", "origin/master")
cmd.Dir = repoDir
output, err := cmd.Output()
if err != nil {
return "", err
}
return string(output), nil
}
// Build The Site
func buildSite(dest string) (err error) {
return exec.Command("jekyll", "build", "--source", SITE_DIR, "--destination", dest).Run()
}