-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.go
484 lines (400 loc) · 13 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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
package main
import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/cheggaaa/pb/v3"
log "github.com/sirupsen/logrus"
)
type Config struct {
ZipFile string
Workdir string
WhiteList string
Default string
}
type VersionInfo struct {
Uid string `json:"uid"`
Title string `json:"title"`
Kind string `json:"kind"`
Description string `json:"description"`
Path string `json:"path"`
Href string `json:"href"`
DocumentURL string `json:"documentURL"`
CreatedAt string `json:"createdAt"`
Pages []VersionInfo `json:"pages"`
Visited bool `json:"-"`
}
type Revision struct {
Versions map[string]TopLevelVersion `json:"versions"`
}
type TopLevelVersion struct {
Page VersionInfo `json:"page"`
}
type TaskInfo struct {
ZipPath string
WhiteList []string
Default string
GitBookPath string
DistPath string
ReactProjectTemplatePath string
}
type VersionRouteInfo struct {
Component string
ImportPath string
Version string
}
type PageRouteInfo struct {
Component string
ImportPath string
PagePath string
PageUid string
}
type AssetsInfo struct {
Size int64
Name string
}
type Section struct {
Title string
Anchor string
Content string
}
type IndexData struct {
Uid string // file name as uid
Path string // URL path
Page string // from revision.json
Sections []Section
}
func (c *Config) TaskInfo() *TaskInfo {
t := TaskInfo{
ZipPath: filepath.Join(c.Workdir, "zip"),
WhiteList: strings.Split(c.WhiteList, ","),
Default: c.Default,
GitBookPath: filepath.Join(c.Workdir, "src", "gitbook"),
DistPath: filepath.Join(c.Workdir, "dist"),
ReactProjectTemplatePath: filepath.Join(c.Workdir, "react-project-template"),
}
return &t
}
var cfg Config
var task *TaskInfo
func main() {
flag.StringVar(&cfg.ZipFile, "zip", "./gitbook.zip", "gitbook exported zip file path")
flag.StringVar(&cfg.Workdir, "dir", "./", "working directory")
flag.StringVar(&cfg.WhiteList, "white", "", "white list")
flag.StringVar(&cfg.Default, "default", "", "default version")
flag.Parse()
task = cfg.TaskInfo()
unzipSourceFiles(cfg.ZipFile)
json2tsx()
makeAppRoot()
Copy("react-project-template", filepath.Join(cfg.Workdir, "src"))
Copy("static", task.DistPath)
Copy(filepath.Join(task.GitBookPath, "assets"), filepath.Join(task.DistPath, "assets"))
makeAssetsPath()
makeHtmlTemplate()
}
// unzipSourceFiles decompress the zip file
func unzipSourceFiles(fileName string) {
log.Printf("unzip %v to %v", cfg.ZipFile, task.GitBookPath)
_, err := Unzip(cfg.ZipFile, task.GitBookPath)
if err != nil {
log.Fatal(err)
}
}
// 生成依赖文件的映射关系
func makeAssetsPath() {
log.Infof("moving assets from %v", task.GitBookPath)
pathJSON := map[string]AssetsInfo{}
WalkDir(filepath.Join(task.GitBookPath, "assets"), func(filePath string, filename string) {
fileName := filename
file, _ := os.Stat(filePath)
pathJSON[fileName] = AssetsInfo{
Size: file.Size(),
Name: file.Name(),
}
})
marshalpathJSON, _ := json.Marshal(pathJSON)
pathJSONStr := string(marshalpathJSON)
WriteFile(filepath.Join(task.GitBookPath, "assets.js"), "module.exports = "+pathJSONStr)
}
// json2tsx generates typescripts for react project based on the JSON files
func json2tsx() {
originDirPath := filepath.Join(task.GitBookPath, "versions")
targetDirPath := filepath.Join(task.GitBookPath, "versions")
// Read dir under "/build_temp/src/gitbook/versions"
fileinfoList, err := ioutil.ReadDir(originDirPath)
if err != nil {
log.Fatal(err)
}
for i := range fileinfoList {
versionName := fileinfoList[i].Name()
// Generate document index by version for full-text search
genSearchIndex(versionName)
if !strings.Contains(filepath.Join(originDirPath, versionName), ".DS_Store") {
formatTargetVersion(
filepath.Join(originDirPath, versionName),
filepath.Join(targetDirPath, versionName),
versionName,
)
}
}
}
// 获得指定版本内的json文件
func formatTargetVersion(versionPath string, targetDir string, versionName string) {
// Read dir under "/build_temp/src/gitbook/versions/${versionName}"
fileinfoList, err := ioutil.ReadDir(versionPath)
if err != nil {
log.Fatal(err, versionPath)
}
log.Infof("converting json into typescript files for: %v", versionPath)
bar := pb.StartNew(len(fileinfoList))
defer bar.Finish()
for i := range fileinfoList {
fileName := fileinfoList[i].Name()
jsonPath := filepath.Join(versionPath, fileName)
pageUID := GetBasenamePrefix(jsonPath)
if WriteFile(filepath.Join(targetDir, pageUID+".tsx"), makeTSX(jsonPath, versionName, pageUID)) {
// Remove document in JSON format after transformation to .tsx is finished
os.Remove(jsonPath)
} else {
log.Warn(pageUID, ".tsx creation failed")
}
bar.Increment()
}
}
// 最后的html文件的模版函数
func makeHtmlTemplate() {
template := `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" href="/static/favicon.ico" type="image/x-icon">
<style>
html,
body {
color: #242A31;
width: 100%;
height: 100%;
margin: 0;
padding: 0;
font-size: 15px;
box-sizing: border-box;
font-family: "Roboto", sans-serif;
line-height: 1em;
font-smoothing: antialiased;
text-size-adjust: 100%;
-ms-text-size-adjust: 100%;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
-webkit-text-size-adjust: 100%;
}
</style>
<title>TigerGraph Documentation</title>
</head>
<body>
<div id='root'></div>
<script type="text/javascript" src='/vendor.js'></script>
<script type="text/javascript" src='/bundle.js'></script>
</body>
</html>
`
WriteFile(filepath.Join(task.DistPath, "index.html"), template)
}
// 将转译好的jsx字符串写至tsx模版文件
func makeTSX(jsonPath string, versionName string, pageUID string) string {
htmlDom := Parser(jsonPath, versionName, pageUID)
return RenderTsxTemplate(htmlDom)
}
// 获取目录下所有文件
func WalkDir(path string, cb func(filePath string, filename string)) {
files, err := ioutil.ReadDir(path)
if err != nil {
fmt.Println(err.Error())
} else {
for _, v := range files {
p := filepath.Join(path, v.Name())
if v.IsDir() {
WalkDir(p, cb)
} else {
cb(p, v.Name())
}
}
}
}
// 生成spa的入口文件并且也是一个路由部分,里面包含了各版本目录下的的路由入口文件
func makeAppRoot() {
appRootPath := filepath.Join(task.GitBookPath, "_appRoute.tsx")
versionDirPath := filepath.Join(task.GitBookPath, "versions")
versions, _ := ioutil.ReadDir(versionDirPath)
versionList := []VersionRouteInfo{}
for i, v := range versions {
for _, w := range task.WhiteList {
if w == v.Name() {
name := filepath.Base(v.Name())
fileInfo, _ := os.Stat(filepath.Join(versionDirPath, name))
if fileInfo.IsDir() {
makeVersionRoot(name)
}
versionList = append(versionList, VersionRouteInfo{
Component: fmt.Sprintf("Version_%v", i),
ImportPath: fmt.Sprintf("import Version_%v from './versions/%v/_versionRoute';", i, name),
Version: strings.Replace(name, ".tsx", "", 1),
})
}
}
}
if len(versionList) == 0 {
return
}
routeImportPath := ""
routesElements := ""
defaultVersion := versionList[0].Version
if len(task.Default) > 0 {
defaultVersion = task.Default
}
defaultRoute := fmt.Sprintf("<Redirect to={'/%v'}/>", defaultVersion)
for _, v := range versionList {
routeImportPath += v.ImportPath + "\n"
routesElements += fmt.Sprintf("<Route path={'/%v'} component={%v} />", v.Version, v.Component) + "\n"
}
content := fmt.Sprintf(`
import * as React from 'react'
import * as ReactDom from 'react-dom'
import { Route, Redirect, Switch } from 'react-router';
import { BrowserRouter } from 'react-router-dom';
import 'antd/dist/antd.css';
import 'katex/dist/katex.min.css';
import '../styles/global.css';
%v
const revision = require('./revision-lite.json');
const space = require('./space.json');
(window as any)['revision'] = revision;
(window as any)['space'] = space;
(window as any)['whiteList'] = "%v";
// versions
const App = () => {
return <BrowserRouter>
<Switch>
%v
%v
</Switch>
</BrowserRouter>
}
ReactDom.render(<App />, document.getElementById('root'));
`, routeImportPath, strings.Join(task.WhiteList, ","), routesElements, defaultRoute)
WriteFile(appRootPath, content)
}
// 生成版本目录下的的路由入口文件
func makeVersionRoot(versionName string) {
versionPath := filepath.Join(task.GitBookPath, "versions", versionName)
versionRootPath := filepath.Join(versionPath, "_versionRoute.tsx")
pages, _ := ioutil.ReadDir(versionPath)
revisionJSON, _ := ioutil.ReadFile(filepath.Join(task.GitBookPath, "revision.json"))
revision := Revision{}
json.Unmarshal(revisionJSON, &revision)
currentVersion := revision.Versions[versionName]
pagesList := []PageRouteInfo{}
for i, v := range pages {
name := filepath.Base(v.Name())
targetUid := strings.Replace(name, ".tsx", "", 1)
_path := ""
if currentVersion.Page.Uid == targetUid {
_path = currentVersion.Page.Path
} else if len(currentVersion.Page.Pages) != 0 {
pageInfo, ok := deepFindPage(currentVersion.Page.Path, currentVersion.Page.Pages, targetUid)
if ok {
_path = pageInfo.Path
}
}
pagesList = append(pagesList, PageRouteInfo{
Component: fmt.Sprintf(`Page_%v`, i),
ImportPath: fmt.Sprintf(`import Page_%v from './%v';`, i, GetBasenamePrefix(name)),
PagePath: _path,
PageUid: targetUid,
})
}
// Write content to revision-lite.json
revisionLiteJSON, err := ioutil.ReadFile(filepath.Join(task.GitBookPath, "revision-lite.json"))
updatedRevision, _ := json.Marshal(revision)
if err == nil {
revisionLite := Revision{}
json.Unmarshal(revisionLiteJSON, &revisionLite)
revisionLite.Versions[versionName] = revision.Versions[versionName]
updatedRevision, _ = json.Marshal(revisionLite)
}
WriteFile(filepath.Join(task.GitBookPath, "revision-lite.json"), string(updatedRevision))
routeImportPath := ""
routesElements := ""
defaultRoute := ""
for _, v := range pagesList {
routeImportPath += v.ImportPath + "\n"
if v.PagePath == "master" {
routesElements += fmt.Sprintf("<Route path={`${props.match.url}`} exact component={%v} />", v.Component) + "\n"
defaultRoute = "<Redirect to={`${props.match.url}`}/>"
} else {
routesElements += fmt.Sprintf("<Route path={`${props.match.url}/%v`} exact component={%v} />", v.PagePath, v.Component) + "\n"
}
}
content := fmt.Sprintf(`
import * as React from 'react'
import { Route, withRouter, Redirect, Switch } from 'react-router';
%v
export default withRouter(props => {
return <Switch>
%v
%v
</Switch>
})`, routeImportPath, routesElements, defaultRoute)
WriteFile(versionRootPath, content)
}
// 根据目标uid递归寻找revision下的page json
func deepFindPage(parentPath string, childPages []VersionInfo, targetUid string) (VersionInfo, bool) {
for i := range childPages {
// Skip the path of top level page which call `deepFindPage()`
if parentPath != "master" && !childPages[i].Visited {
childPages[i].Visited = true
childPages[i].Path = fmt.Sprintf("%v/%v", parentPath, childPages[i].Path)
}
if childPages[i].Uid == targetUid {
return childPages[i], true
}
if len(childPages[i].Pages) != 0 {
childPage, ok := deepFindPage(childPages[i].Path, childPages[i].Pages, targetUid)
if ok {
return childPage, ok
}
}
}
return VersionInfo{}, false
}
func genSearchIndex(versionName string) {
versionPath := filepath.Join(task.GitBookPath, "versions", versionName)
revisionJSON, _ := ioutil.ReadFile(filepath.Join(task.GitBookPath, "revision.json"))
revision := Revision{}
json.Unmarshal(revisionJSON, &revision)
// For full-text search index
versionIndex := ProcessRevision(revision, versionName)
for i, page := range versionIndex {
// Read document
filename := page.Uid + ".json"
docJSON, _ := ioutil.ReadFile(filepath.Join(versionPath, filename))
doc := JSONInfo{}
err := json.Unmarshal(docJSON, &doc)
if err != nil {
return
}
// Fill content to index
sections := []Section{}
doc.Document.CollectIndexContent(§ions, false, true, map[string]int{})
versionIndex[i].Sections = sections
}
versionIndexJSON, _ := JSONMarshal(versionIndex)
indexFilename := versionName + ".json"
WriteFile(filepath.Join(task.GitBookPath, "search-index", indexFilename), string(versionIndexJSON))
}