forked from MarkBind/markbind
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·303 lines (268 loc) · 10.4 KB
/
index.js
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
#!/usr/bin/env node
// Entry file for Markbind project
const chokidar = require('chokidar');
const fs = require('fs-extra-promise');
const liveServer = require('live-server');
const path = require('path');
const program = require('commander');
const Promise = require('bluebird');
const _ = {};
_.isBoolean = require('lodash/isBoolean');
const cliUtil = require('./src/util/cliUtil');
const { ensurePosix } = require('./src/lib/markbind/src/utils');
const fsUtil = require('./src/util/fsUtil');
const logger = require('./src/util/logger');
const Site = require('./src/Site');
const {
ACCEPTED_COMMANDS,
ACCEPTED_COMMANDS_ALIAS,
INDEX_MARKDOWN_FILE,
LAZY_LOADING_SITE_FILE_NAME,
} = require('./src/constants');
const CLI_VERSION = require('./package.json').version;
process.title = 'MarkBind';
process.stdout.write(
`${String.fromCharCode(27)}]0; MarkBind${String.fromCharCode(7)}`,
);
function printHeader() {
logger.logo();
logger.log(` v${CLI_VERSION}`);
}
function handleError(error) {
logger.error(error.message);
process.exitCode = 1;
}
// We want to customize the help message to print MarkBind's header,
// but commander.js does not provide an API directly for doing so.
// Hence we override commander's outputHelp() completely.
program.defaultOutputHelp = program.outputHelp;
program.outputHelp = function (cb) {
printHeader();
this.defaultOutputHelp(cb);
};
program
.allowUnknownOption()
.usage('<command>');
program
.name('markbind')
.version(CLI_VERSION);
program
.command('init [root]')
.option('-c, --convert', 'convert a GitHub wiki or docs folder to a MarkBind website')
.option('-t, --template <type>', 'initialise markbind with a specified template', 'default')
.alias('i')
.description('init a markbind website project')
.action((root, options) => {
const rootFolder = path.resolve(root || process.cwd());
const outputRoot = path.join(rootFolder, '_site');
printHeader();
if (options.convert) {
if (fs.existsSync(path.resolve(rootFolder, 'site.json'))) {
logger.error('Cannot convert an existing MarkBind website!');
return;
}
}
Site.initSite(rootFolder, options.template)
.then(() => {
logger.info('Initialization success.');
})
.then(() => {
if (options.convert) {
logger.info('Converting to MarkBind website.');
new Site(rootFolder, outputRoot).convert()
.then(() => {
logger.info('Conversion success.');
})
.catch(handleError);
}
})
.catch(handleError);
});
program
.command('serve [root]')
.alias('s')
.description('build then serve a website from a directory')
.option('-f, --force-reload', 'force a full reload of all site files when a file is changed')
.option('-n, --no-open', 'do not automatically open the site in browser')
.option('-o, --one-page [file]', 'build and serve only a single page in the site initially,'
+ 'building more pages when they are navigated to. Also lazily rebuilds only the page being viewed when'
+ 'there are changes to the source files (if needed), building others when navigated to')
.option('-p, --port <port>', 'port for server to listen on (Default is 8080)')
.option('-s, --site-config <file>', 'specify the site config file (default: site.json)')
.action((userSpecifiedRoot, options) => {
let rootFolder;
try {
rootFolder = cliUtil.findRootFolder(userSpecifiedRoot, options.siteConfig);
if (options.forceReload && options.onePage) {
handleError(new Error('Oops! You shouldn\'t need to use the --force-reload option with --one-page.'));
process.exit();
}
} catch (err) {
handleError(err);
}
const logsFolder = path.join(rootFolder, '_markbind/logs');
const outputFolder = path.join(rootFolder, '_site');
let onePagePath = options.onePage === true ? INDEX_MARKDOWN_FILE : options.onePage;
onePagePath = onePagePath ? ensurePosix(onePagePath) : onePagePath;
const site = new Site(rootFolder, outputFolder, onePagePath, options.forceReload, options.siteConfig);
const addHandler = (filePath) => {
logger.info(`[${new Date().toLocaleTimeString()}] Reload for file add: ${filePath}`);
Promise.resolve('').then(() => {
if (fsUtil.isSourceFile(filePath) || site.isPluginSourceFile(filePath)) {
return site.rebuildSourceFiles(filePath);
}
return site.buildAsset(filePath);
}).catch((err) => {
logger.error(err.message);
});
};
const changeHandler = (filePath) => {
logger.info(`[${new Date().toLocaleTimeString()}] Reload for file change: ${filePath}`);
Promise.resolve('').then(() => {
if (fsUtil.isSourceFile(filePath) || site.isPluginSourceFile(filePath)) {
return site.rebuildAffectedSourceFiles(filePath);
}
return site.buildAsset(filePath);
}).catch((err) => {
logger.error(err.message);
});
};
const removeHandler = (filePath) => {
logger.info(`[${new Date().toLocaleTimeString()}] Reload for file deletion: ${filePath}`);
Promise.resolve('').then(() => {
if (fsUtil.isSourceFile(filePath) || site.isPluginSourceFile(filePath)) {
return site.rebuildSourceFiles(filePath);
}
return site.removeAsset(filePath);
}).catch((err) => {
logger.error(err.message);
});
};
const onePageHtmlUrl = onePagePath && `/${onePagePath.replace(/\.(md|mbd|mbdf)$/, '.html')}`;
// server config
const serverConfig = {
open: options.open && (onePageHtmlUrl || true),
logLevel: 0,
root: outputFolder,
port: options.port || 8080,
middleware: [],
mount: [],
};
printHeader();
site
.readSiteConfig()
.then((config) => {
serverConfig.mount.push([config.baseUrl || '/', outputFolder]);
if (onePagePath) {
const lazyReloadMiddleware = function (req, res, next) {
const urlExtension = path.posix.extname(req.url);
const hasEndingSlash = req.url.endsWith('/');
const hasNoExtension = urlExtension === '';
const isHtmlFileRequest = urlExtension === '.html' || hasEndingSlash || hasNoExtension;
if (!isHtmlFileRequest || req.url.endsWith('._include_.html')) {
next();
return;
}
if (hasNoExtension && !hasEndingSlash) {
// Urls of type 'host/userGuide' - check if 'userGuide' is a raw file or does not exist
const diskFilePath = path.resolve(rootFolder, req.url);
if (!fs.existsSync(diskFilePath) || !fs.isDirectorySync(diskFilePath)) {
// Request for a raw file
next();
return;
}
}
const urlWithoutBaseUrl = req.url.replace(config.baseUrl, '');
// Map 'hostname/userGuide/' and 'hostname/userGuide' to hostname/userGuide/index.
const urlWithIndex = (hasNoExtension || hasEndingSlash)
? path.posix.join(urlWithoutBaseUrl, 'index')
: urlWithoutBaseUrl;
const urlWithoutExtension = fsUtil.removeExtension(urlWithIndex);
const didInitiateRebuild = site.changeCurrentPage(urlWithoutExtension);
if (didInitiateRebuild) {
req.url = ensurePosix(path.join(config.baseUrl || '/', LAZY_LOADING_SITE_FILE_NAME));
}
next();
};
serverConfig.middleware.push(lazyReloadMiddleware);
}
return site.generate();
})
.then(() => {
const watcher = chokidar.watch(rootFolder, {
ignored: [
logsFolder,
outputFolder,
/(^|[/\\])\../,
x => x.endsWith('___jb_tmp___'), x => x.endsWith('___jb_old___'), // IDE temp files
],
ignoreInitial: true,
});
watcher
.on('add', addHandler)
.on('change', changeHandler)
.on('unlink', removeHandler);
})
.then(() => {
const server = liveServer.start(serverConfig);
server.addListener('listening', () => {
const address = server.address();
const serveHost = address.address === '0.0.0.0' ? '127.0.0.1' : address.address;
const serveURL = `http://${serveHost}:${address.port}`;
logger.info(`Serving "${outputFolder}" at ${serveURL}`);
logger.info('Press CTRL+C to stop ...');
});
})
.catch(handleError);
});
program
.command('build [root] [output]')
.alias('b')
.option('--baseUrl [baseUrl]',
'optional flag which overrides baseUrl in site.json, leave argument empty for empty baseUrl')
.option('-s, --site-config <file>', 'specify the site config file (default: site.json)')
.description('build a website')
.action((userSpecifiedRoot, output, options) => {
// if --baseUrl contains no arguments (options.baseUrl === true) then set baseUrl to empty string
const baseUrl = _.isBoolean(options.baseUrl) ? '' : options.baseUrl;
let rootFolder;
try {
rootFolder = cliUtil.findRootFolder(userSpecifiedRoot, options.siteConfig);
} catch (err) {
handleError(err);
}
const defaultOutputRoot = path.join(rootFolder, '_site');
const outputFolder = output ? path.resolve(process.cwd(), output) : defaultOutputRoot;
printHeader();
new Site(rootFolder, outputFolder, undefined, undefined, options.siteConfig)
.generate(baseUrl)
.then(() => {
logger.info('Build success!');
})
.catch(handleError);
});
program
.command('deploy')
.alias('d')
.description('deploy the site to the repo\'s Github pages')
.option('-t, --travis [tokenVar]', 'deploy the site in Travis [GITHUB_TOKEN]')
.option('-s, --site-config <file>', 'specify the site config file (default: site.json)')
.action((options) => {
const rootFolder = path.resolve(process.cwd());
const outputRoot = path.join(rootFolder, '_site');
new Site(rootFolder, outputRoot, undefined, undefined, options.siteConfig).deploy(options.travis)
.then(() => {
logger.info('Deployed!');
})
.catch(handleError);
printHeader();
});
program.parse(process.argv);
if (!program.args.length
|| !(ACCEPTED_COMMANDS.concat(ACCEPTED_COMMANDS_ALIAS)).includes(process.argv[2])) {
if (program.args.length) {
logger.warn(`Command '${program.args[0]}' doesn't exist, run "markbind --help" to list commands.`);
} else {
program.help();
}
}