forked from revel/revel.github.io
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdocfile.go
94 lines (79 loc) · 2.42 KB
/
docfile.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
// This program generates per-file godoc.
//
// go run docfile.go -templates ~/Dropbox/Public/revel/docs/godoc -out ~/Dropbox/Public/revel/docs ~/code/gocode/src/github.com/revel/revel/*.go
package main
import (
"bytes"
"flag"
"log"
"os"
"os/exec"
"path"
"path/filepath"
"strings"
)
var (
templates = flag.String("templates", "", "Path to the package.html template")
out = flag.String("out", "out", "Path to the generated stuff")
)
func main() {
flag.Parse()
// Find godoc
gdPath, err := exec.LookPath("godoc")
if err != nil {
log.Fatalln(err)
}
// Create a temp directory to use for linking the files
tempDirPath := path.Join(os.TempDir(), "docfile")
// Decide where the generated files are going.
docPath := path.Join(*out, "godoc")
srcPath := path.Join(*out, "src")
// Link each file in turn.
for _, filename := range flag.Args() {
if !strings.HasSuffix(filename, ".go") || strings.HasSuffix(filename, "_test.go") {
continue
}
log.Println("Processing", filename)
filename, err := filepath.Abs(filename)
must(err)
// Delete, recreate the tempdir, and link in the source file.
basename := path.Base(filename)
must(os.RemoveAll(tempDirPath))
must(os.MkdirAll(tempDirPath, 0777))
must(os.Symlink(filename, path.Join(tempDirPath, basename)))
// Get the target html file ready.
htmlname := basename[:len(basename)-3] + ".html"
log.Println("Writing", path.Join(docPath, htmlname))
htmlFile, err := os.Create(path.Join(docPath, htmlname))
must(err)
// Print the docs to html.
cmd := exec.Command(gdPath, "-html", "-templates", *templates, tempDirPath)
b, err := cmd.CombinedOutput()
must(err)
_, err = htmlFile.Write(replace(b, basename, htmlname))
must(err)
must(htmlFile.Close())
// Now print the source to html.
log.Println("Writing", path.Join(srcPath, htmlname))
srcFile, err := os.Create(path.Join(srcPath, htmlname))
must(err)
cmd = exec.Command(gdPath, "-src", "-html", "-templates", *templates, tempDirPath)
b, err = cmd.CombinedOutput()
must(err)
_, err = srcFile.Write(replace(b, basename, htmlname))
must(err)
must(srcFile.Close())
}
}
func replace(b []byte, basename, htmlname string) []byte {
b = bytes.Replace(b, []byte("%%TITLE%%"),
[]byte(strings.Title(basename[:len(basename)-3])), -1)
b = bytes.Replace(b, []byte("/target/"+basename),
[]byte("../src/"+htmlname), -1)
return b
}
func must(err error) {
if err != nil {
log.Fatal(err)
}
}