-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.go
284 lines (231 loc) · 7.43 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
package main
import (
_ "embed"
"fmt"
"os"
"runtime"
"strings"
"time"
"github.com/go-git/go-billy/v5/memfs"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/storage/memory"
_ "github.com/mattn/go-sqlite3"
"github.com/shirou/gopsutil/v3/mem"
)
func logo() {
fmt.Println(" __ __ ")
fmt.Println(" / /_ ____ _____/ /__ ")
fmt.Println(" / __ \\/ __ \\/ ___/ //_/ ")
fmt.Println(" / /_/ / /_/ / /__/ ,< ")
fmt.Println(" /_.___/\\____/\\___/_/|_| ")
fmt.Println(" v" + VERSION + " ")
fmt.Println(" ")
}
var help = `
--in=<path> Absolute path to where your markdown articles are
stored. This is expected to be a git repository.
If it is not, you must supply the
--without-revisions flag to generate your wiki.
--out=<path> Where to write the output. This folder should not
exist before you run me.
--with-json-files Generate JSON source files. None are generated
by default.
--with-raw-markdown-files Generate raw markdown source files. None are
generated by default.
--without-revisions Do not article revisions based on git history.
These are generated by default. This is a *much*
faster option if you're not that interested in
viewing article revision histories.
--using-disk-fs Use on-disk filesystem to clone your article
repository. This is slower; your repo is cloned
to memory by default.
--version Show version
--help Show this message
`
func main() {
articleRoot := ""
generateJSON := false
generateRaw := false
generateRevisions := true
outputFolder := ""
useOnDiskFS := false
// Parse arguments as longopts. Yes, there's the `flags` package but I like
// double dashes for my flags.
args := os.Args[1:]
if len(args) == 0 {
logo()
fmt.Println(help)
os.Exit(0)
}
for _, arg := range args {
switch {
case strings.HasPrefix(arg, "--in="):
articleRoot = arg[len("--in="):]
case strings.HasPrefix(arg, "--out="):
outputFolder = arg[len("--out="):]
case arg == "--with-json-files":
generateJSON = true
case arg == "--with-raw-markdown-files":
generateRaw = true
case arg == "--without-revisions":
generateRevisions = false
case arg == "--using-disk-fs":
useOnDiskFS = true
case arg == "--version":
fmt.Println(VERSION)
os.Exit(0)
case arg == "--help":
logo()
fmt.Println(help)
os.Exit(0)
default:
fmt.Println("I don't know what this means:", arg)
fmt.Println("Use --help to see usage.")
os.Exit(EXIT_INVALID_FLAG_SUPPLIED)
}
}
if articleRoot == "" {
fmt.Println("You must give me an article root (--in=<path>)")
os.Exit(EXIT_NO_ARTICLE_ROOT)
}
if outputFolder == "" {
fmt.Println("You must give me an output folder (--out=<path>)")
os.Exit(EXIT_NO_OUTPUT_FOLDER)
}
// Some bookkeeping. Tick.
start := time.Now()
v, _ := mem.VirtualMemory()
// Check if provided root exists
if _, err := os.Stat(articleRoot); os.IsNotExist(err) {
fmt.Println("That article root is not a folder or does not exist.")
os.Exit(EXIT_BAD_ARTICLE_ROOT)
}
// Check if it can be read as a git repository only if we're generating
// revisions
var repository *git.Repository
var repoErr error
var repoStatus git.Status
if generateRevisions {
if useOnDiskFS {
repository, repoErr = git.PlainOpen(articleRoot)
} else {
fs := memfs.New()
repository, repoErr = git.Clone(
memory.NewStorage(),
fs,
&git.CloneOptions{
URL: articleRoot,
},
)
}
if repoErr != nil {
fmt.Println("That article root does not appear to be a git repository.")
fmt.Println("You can try running me again with '--without-revisions' and I won't check if it's a git repository.")
os.Exit(EXIT_NOT_A_GIT_REPO)
}
// Get the working tree's status
workingTree, _ := repository.Worktree()
repoStatus, _ = workingTree.Status()
if !repoStatus.IsClean() {
fmt.Println("WARN: Working tree is not clean!")
}
} else {
fmt.Println("I am not going to generate article revisions.")
}
// Gather basic things. Create the output folder first.
articleRoot = strings.TrimRight(articleRoot, "/")
outputFolder = strings.TrimRight(outputFolder, "/")
fmt.Println("Making", outputFolder, "if it doesn't exist")
os.MkdirAll(outputFolder, os.ModePerm)
// App config
config := BockConfig{
articleRoot: articleRoot,
entityTree: nil,
listOfArticles: nil,
database: nil,
outputFolder: outputFolder,
meta: Meta{
Architecture: runtime.GOARCH,
ArticleCount: 0,
BuildDate: time.Now().UTC(),
CPUCount: runtime.NumCPU(),
GenerateJSON: generateJSON,
GenerateRaw: generateRaw,
GenerateRevisions: generateRevisions,
GenerationTime: 0,
MemoryInGB: int(v.Total / (1024 * 1024 * 1024)),
Platform: runtime.GOOS,
RevisionCount: 0,
},
started: time.Now(),
repository: repository,
workTreeStatus: &repoStatus,
}
// Make a flat list of absolute article paths. Use these to build the entity
// tree. We do this to prevent unnecessary and empty folders from being
// created.
listOfArticles, listOfFolders, _ := makeListOfEntities(&config)
// Do we even build anything?
if len(listOfArticles) == 0 {
fmt.Println("I could not find any articles to render :/")
fmt.Println("Quitting.")
os.Exit(EXIT_NO_ARTICLES_TO_RENDER)
}
// We have things to build. Continue configuring.
config.listOfArticles = &listOfArticles
config.listOfFolders = &listOfFolders
config.meta.ArticleCount = len(listOfArticles)
config.meta.FolderCount = len(listOfFolders)
fmt.Println("Found", config.meta.ArticleCount, "articles")
// Make a tree of entities: articles and folders
entityTree := makeEntityTree(&config)
config.entityTree = &entityTree
// Database setup
db := makeDatabase(&config)
defer db.Close()
config.database = db
// Copy static assets over
fmt.Print("Creating template assets")
copyTemplateAssets(&config)
fmt.Println("... done")
fmt.Print("Copying assets")
copyError := copyAssets(&config)
if copyError != nil {
fmt.Println("; could not find '__assets' in repository. Ignoring.")
} else {
fmt.Println("... done")
}
// Process all articles. TODO: Errors?
writeEntities(&config)
// Write the index page and other pages
fmt.Print("Writing index page")
writeIndex(&config)
fmt.Println("... done")
fmt.Print("Writing 404 page")
write404(&config)
fmt.Println("... done")
fmt.Print("Writing archive page")
writeArchive(&config)
fmt.Println("... done")
fmt.Print("Writing tree")
writeTree(&config)
fmt.Println("... done")
fmt.Print("Writing random page")
writeRandom(&config)
fmt.Println("... done")
// Tock
end := time.Now()
generationTime := end.Sub(start)
config.meta.GenerationTime = generationTime
config.meta.GenerationTimeRounded = generationTime.Round(time.Second)
fmt.Print("Writing /Home: ")
writeHome(&config)
fmt.Println("... done")
fmt.Printf(
"\nDone! Finished processing %d articles, %d folders, and %d revisions in %s\n",
config.meta.ArticleCount,
config.meta.FolderCount,
config.meta.RevisionCount,
config.meta.GenerationTime,
)
}