-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
183 lines (146 loc) · 5.68 KB
/
index.js
File metadata and controls
183 lines (146 loc) · 5.68 KB
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
const fastify = require('fastify')({logger: true})
const util = require('util');
const exec = util.promisify(require('child_process').exec);
const path = require('node:path')
const fs = require('fs').promises
const fsAsync = require('fs')
const showdown = require('showdown');
const converter = new showdown.Converter();
let GIT_REPO_NAME = null
let GIT_REPO = null
let BUILD_ACCESS_TOKEN = null
let URL_PATH_PREFIX = ""
if (process.env.GIT_REPO_NAME){
GIT_REPO_NAME = process.env.GIT_REPO_NAME
}
if (process.env.GIT_REPO){
GIT_REPO = process.env.GIT_REPO
}
if (process.env.BUILD_ACCESS_TOKEN){
BUILD_ACCESS_TOKEN = process.env.BUILD_ACCESS_TOKEN
}
if (process.env.URL_PATH_PREFIX){
URL_PATH_PREFIX = process.env.URL_PATH_PREFIX
}
if (process.env.PATH_TO_MENU_TEMPLATE){
PATH_TO_MENU_TEMPLATE = process.env.PATH_TO_MENU_TEMPLATE
}
let currentlyBuilding = false
let currentlyBuildingQueue = []
let header_html = fsAsync.readFileSync('templates/header.html',{ encoding: 'utf8' });
let footer_html = fsAsync.readFileSync('templates/footer.html',{ encoding: 'utf8' });
fastify.register(require('@fastify/static'), {
root: path.join(__dirname, 'app/manual'),
prefix: `${URL_PATH_PREFIX}/`, // optional: default '/'
// constraints: { host: 'example.com' } // optional: default {}
})
fastify.post(`${URL_PATH_PREFIX}/build`, function (req, reply) {
if (BUILD_ACCESS_TOKEN){
console.log(req.headers)
if (!req.headers['x-gitlab-token']){
reply
.code(401)
.header('Content-Type', 'application/json; charset=utf-8')
.send({ message: "You did not supply the header needed to trigger the build process." })
return false
}
if (req.headers['x-gitlab-token'] && req.headers['x-gitlab-token'] != BUILD_ACCESS_TOKEN){
reply
.code(403)
.header('Content-Type', 'application/json; charset=utf-8')
.send({ message: "Invalid build token." })
return false
}
}
currentlyBuildingQueue.push(Math.floor(Date.now() / 1000))
reply
.code(200)
.header('Content-Type', 'application/json; charset=utf-8')
.send({ buildQueue: currentlyBuildingQueue })
})
// Run the server!
fastify.listen({ port: 6565, host: '0.0.0.0' }, (err, address) => {
if (err) throw err
// Server is now listening on ${address}
})
let convertDir = async function(path){
const dir = await fs.opendir(path)
let base_path = path.replace(`data/${GIT_REPO_NAME}`,'data/output')
// does this dir exist yet?
if (!fsAsync.existsSync(base_path)){
fs.mkdir(base_path, { recursive: true });
}
let menuHtml = ""
if (PATH_TO_MENU_TEMPLATE){
// A menu template was provided, so we need render it an add it to all the files
let menuMd = `data/${GIT_REPO_NAME}/${PATH_TO_MENU_TEMPLATE}`
menuHtml = '<div class="menu">MENU TEMPLATE NOT FOUND!</div>'
if (fsAsync.existsSync(menuMd)){
let markdownText = fsAsync.readFileSync(menuMd,{ encoding: 'utf8' });
let generatedHtml = converter.makeHtml(markdownText);
menuHtml = `<div class="menu">${generatedHtml}</div>`
}
}
for await (const dirent of dir) {
let thisFilePath = `${dirent.path}/${dirent.name}`
const stat = await fs.lstat(thisFilePath);
if (stat.isDirectory()){
await convertDir(thisFilePath)
}else if (dirent.name.toLowerCase().endsWith(".md")){
let markdownText = fsAsync.readFileSync(thisFilePath,{ encoding: 'utf8' });
let generatedHtml = converter.makeHtml(markdownText);
let useName = dirent.name.replace(".md",'.html').replace(".MD",'.html')
if (dirent.name.toLocaleLowerCase() == 'readme.md'){
useName = 'index.html'
}
fsAsync.writeFileSync(base_path + '/' + useName, `${header_html}\n\n${menuHtml}${generatedHtml}\n\n${footer_html}`);
}else if (dirent.name.toLowerCase().endsWith(".png") || dirent.name.toLowerCase().endsWith(".jpg") || dirent.name.toLowerCase().endsWith(".gif")){
fs.copyFile(thisFilePath,base_path + '/' + dirent.name )
}
}
}
let convertDocs = async function(){
if (!GIT_REPO_NAME){
console.error("No GIT_REPO_NAME set!")
return false
}
if (fsAsync.existsSync('data/output')){
fsAsync.rmSync(`data/output`, { recursive: true, force: true });
}
await convertDir(`data/${GIT_REPO_NAME}`)
if (fsAsync.existsSync('app/manual')){
fsAsync.rmSync(`app/manual`, { recursive: true, force: true });
}
fsAsync.renameSync('data/output', 'app/manual')
}
let cloneRepo = async function(){
if (GIT_REPO){
if (fsAsync.existsSync(`data/${GIT_REPO_NAME}`)){
fsAsync.rmSync(`data/${GIT_REPO_NAME}`, { recursive: true, force: true });
}
const { stdout, stderr } = await exec(`cd data && git clone ${GIT_REPO}`);
console.log('stdout:', stdout);
console.log('stderr:', stderr);
}else{
console.error("GIT_REPO not set")
}
}
// check ever X seconds to see if we have to build the page
setInterval(async ()=>{
if (currentlyBuildingQueue.length>0){
// don't run if already running
if (currentlyBuilding){
return false
}
currentlyBuilding = true
console.log("Cloning...")
await cloneRepo()
console.log("Building...")
await convertDocs()
console.log("Done.")
// remove a queue'd run
currentlyBuildingQueue.pop()
currentlyBuilding = false
}
// console.log(currentlyBuildingQueue)
},5000)