-
Notifications
You must be signed in to change notification settings - Fork 0
/
wiki.go
351 lines (289 loc) · 8.89 KB
/
wiki.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
347
348
349
350
351
// Copyright 2010 The Go Authors.
// Copyright 2014 Quincy Bowers. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"errors"
"fmt"
"html/template"
"io/ioutil"
"net/http"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"sort"
"strings"
"github.com/russross/blackfriday"
)
// Page represents a single page in the wiki.
type Page struct {
Title string
Filename string
Ingredients template.HTML
Instructions template.HTML
Index []template.HTML
}
type RootPage struct {
Title string
Filename string
Body template.HTML
Index []template.HTML
}
// save writes the page out to disk.
func (p *Page) save() error {
body := fmt.Sprintf("<!-- Ingredients -->\n%s\n<!-- Instructions -->\n%s", p.Ingredients, p.Instructions)
return ioutil.WriteFile(filepath.Join(pagesDir, p.Filename+".txt"), []byte(body), 0600)
}
// loadPage reads a page from disk.
func loadPage(file string) (*Page, error) {
filename := filepath.Join(pagesDir, file+".txt")
body, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
ingredients, instructions := parseRecipe(body)
p := &Page{
Title: convertFilenameToTitle(file),
Filename: filepath.Base(file),
Ingredients: template.HTML(ingredients),
Instructions: template.HTML(instructions)}
return p, nil
}
func loadRoot(file string) (*RootPage, error) {
filename := filepath.Join(pagesDir, file+".txt")
body, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
p := &RootPage{
Title: convertFilenameToTitle(file),
Filename: filepath.Base(file),
Body: template.HTML(body),
Index: pages}
return p, nil
}
// rootHandler prepares the home page.
func rootHandler(w http.ResponseWriter, r *http.Request, title string) {
p, err := loadRoot(title)
p.Body = template.HTML(blackfriday.MarkdownCommon([]byte(p.Body)))
p.Body = template.HTML(convertWikiMarkup([]byte(p.Body)))
err = templates.ExecuteTemplate(w, "root.html", p)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
// viewHandler prepares the page to be rendered by passing it through the
// markdown and wikiMarkup filters.
func viewHandler(w http.ResponseWriter, r *http.Request, title string) {
// Special case for the root page.
if title == rootTitle {
rootHandler(w, r, title)
return
}
p, err := loadPage(title)
if err != nil {
http.Redirect(w, r, "/edit/"+title, http.StatusFound)
return
}
p.Ingredients = template.HTML(blackfriday.MarkdownCommon([]byte(p.Ingredients)))
p.Instructions = template.HTML(blackfriday.MarkdownCommon([]byte(p.Instructions)))
p.Ingredients = template.HTML(convertWikiMarkup([]byte(p.Ingredients)))
p.Instructions = template.HTML(convertWikiMarkup([]byte(p.Instructions)))
renderTemplate(w, "view", p)
}
// editHandler loads an existing page from disk or creates a new empty page to
// be rendered.
func editHandler(w http.ResponseWriter, r *http.Request, title string) {
p, err := loadPage(title)
if err != nil {
p = &Page{Title: title, Filename: title}
}
renderTemplate(w, "edit", p)
}
// saveHandler saves the changes and redirects back to the page's view.
func saveHandler(w http.ResponseWriter, r *http.Request, title string) {
ingredients := r.FormValue("ingredients")
instructions := r.FormValue("instructions")
recipeTitle := r.FormValue("recipeTitle")
filename := convertTitleToFilename(recipeTitle)
p := &Page{
Title: recipeTitle,
Filename: filename,
Ingredients: template.HTML(ingredients),
Instructions: template.HTML(instructions)}
err := p.save()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// If the filename is different than the title then we are renaming and
// should remove the old file.
if filename != title {
oldfile := filepath.Join(pagesDir, title+".txt")
// Only proceed with the rename if the old file exists.
if _, err := os.Stat(oldfile); err == nil {
if err := os.Remove(oldfile); err != nil {
panic(err)
}
}
}
updateIndex()
http.Redirect(w, r, "/view/"+filename, http.StatusFound)
}
func convertTitleToFilename(title string) string {
return strings.Replace(title, " ", "-", -1)
}
func convertFilenameToTitle(filename string) string {
return strings.Replace(filename, "-", " ", -1)
}
// Parse the templates.
var templateDir string = "templates"
var templateFiles []string = []string{
filepath.Join(templateDir, "root.html"),
filepath.Join(templateDir, "edit.html"),
filepath.Join(templateDir, "view.html")}
var templates = template.Must(template.ParseFiles(templateFiles...))
// renderTemplate takes the renders the html for the given template.
func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) {
p.Index = pages
err := templates.ExecuteTemplate(w, tmpl+".html", p)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
// Defines the set of valid URLs to expect.
var validPath = regexp.MustCompile("^/(edit|save|view)/([-a-zA-Z0-9]+)$")
func makeHandler(fn func(http.ResponseWriter, *http.Request, string)) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
m := validPath.FindStringSubmatch(r.URL.Path)
if m == nil {
http.NotFound(w, r)
return
}
fn(w, r, m[2])
}
}
// a wikiLink looks like [[Words]]
var wikiLink = regexp.MustCompile("\\[\\[([-a-zA-Z0-9 ]+)\\]\\]")
// convertWikiMarkup replaces wiki syntax with equivalent html.
func convertWikiMarkup(text []byte) []byte {
var resultText []byte
matches := wikiLink.FindAllSubmatch(text, -1)
for _, v := range matches {
for _, submatch := range v[1:] {
targetText := regexp.MustCompile("\\[\\[(" + string(submatch) + ")\\]\\]")
space := regexp.MustCompile(" ")
linkText := space.ReplaceAll(submatch, []byte("-"))
replacementText := []byte("<a href=\"/view/" + string(linkText) + "\">" + string(submatch) + "</a>")
resultText = targetText.ReplaceAll(text, replacementText)
}
}
return resultText
}
// Ensure the pages directory exists before the program gets going.
var pagesDir string = "pages"
func init() {
if _, err := os.Stat(pagesDir); os.IsNotExist(err) {
if err := os.Mkdir(pagesDir, 0700); err != nil {
panic(err)
}
}
}
// get a list of all of the pages
type Pages []template.HTML
func (p Pages) Len() int {
return len(p)
}
func (p Pages) Less(i, j int) bool {
if p[i] == "Home" {
return true
} else if p[j] == "Home" {
return false
}
return p[i] < p[j]
}
func (p Pages) Swap(i, j int) {
p[i], p[j] = p[j], p[i]
}
var pages Pages
// Get an initial list of all of the pages.
func init() {
updateIndex()
}
// updateIndex reads the list of files in pages/ and creates a sorted index.
// The Home page sorts ahead of all others.
func updateIndex() {
dirs, err := ioutil.ReadDir(pagesDir)
if err != nil {
panic(err)
}
var urls Pages = make([]template.HTML, 0)
for _, v := range dirs {
if !strings.HasPrefix(v.Name(), ".") {
name := strings.Replace(v.Name(), ".txt", "", -1)
if name == rootTitle {
continue
}
title := convertFilenameToTitle(name)
url := fmt.Sprintf("<a href=\"/view/%s\">%s</a>", name, title)
urls = append(urls, template.HTML(url))
}
}
sort.Sort(urls)
home := template.HTML(fmt.Sprintf(`<a href="/view/%s">%s</a>`, rootTitle, rootTitle))
pages = make([]template.HTML, 1)
pages[0] = home
pages = append(pages, urls...)
}
// parseRecipe separates the loaded page into ingredients and instructions.
func parseRecipe(content []byte) (ingredients, instructions template.HTML) {
lines := strings.Split(string(content), "\n")
inIngredients := false
inInstructions := false
for _, line := range lines {
switch line {
case "<!-- Ingredients -->":
inIngredients = true
inInstructions = false
case "<!-- Instructions -->":
inIngredients = false
inInstructions = true
default:
if inIngredients {
ingredients += template.HTML(line + "\n")
} else if inInstructions {
instructions += template.HTML(line + "\n")
} else {
panic(errors.New("Found bad line! " + line))
}
}
}
return
}
var rootTitle string = "Home"
func main() {
var server = "localhost:8080"
// open the default browser to the view/Home endpoint.
var browser *exec.Cmd
var url string = "http://" + server + "/view/" + rootTitle
switch runtime.GOOS {
case "windows":
browser = exec.Command(`C:\Windows\System32\rundll32.exe`, "url.dll,FileProtocolHandler", url)
case "darwin":
browser = exec.Command("open", url)
default:
browser = exec.Command("xdg-open", url)
}
if err := browser.Start(); err != nil {
panic(err)
}
// register the handlers and start the server.
http.HandleFunc("/view/", makeHandler(viewHandler))
http.HandleFunc("/edit/", makeHandler(editHandler))
http.HandleFunc("/save/", makeHandler(saveHandler))
http.Handle("/resources/", http.StripPrefix("/resources/", http.FileServer(http.Dir("resources"))))
http.ListenAndServe(server, nil)
}