forked from MarkBind/markbind
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·220 lines (196 loc) · 6.81 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
#!/usr/bin/env node
// Entry file for Markbind project
const chokidar = require('chokidar');
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 = ['init', 'build', 'serve', 'deploy'];
const ACCEPTED_COMMANDS_ALIAS = ['i', 'b', 's', 'd'];
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;
}
program
.allowUnknownOption()
.usage(' <command>');
program
.version(CLI_VERSION);
program
.command('init [root]')
.alias('i')
.description('init a markbind website project')
.action((root) => {
const rootFolder = path.resolve(root || process.cwd());
printHeader();
Site.initSite(rootFolder)
.then(() => {
logger.info('Initialization success.');
})
.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>', 'render and serve only a single page in the site')
.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);
} catch (err) {
handleError(err);
}
const logsFolder = path.join(rootFolder, '_markbind/logs');
const outputFolder = path.join(rootFolder, '_site');
if (options.onePage) {
// replace slashes for paths on Windows
// eslint-disable-next-line no-param-reassign
options.onePage = ensurePosix(options.onePage);
}
const site = new Site(rootFolder, outputFolder, options.onePage, options.forceReload, options.siteConfig);
const addHandler = (filePath) => {
logger.info(`[${new Date().toLocaleTimeString()}] Reload for file add: ${filePath}`);
Promise.resolve('').then(() => {
if (fsUtil.isSourceFile(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)) {
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)) {
return site.rebuildSourceFiles(filePath);
}
return site.removeAsset(filePath);
}).catch((err) => {
logger.error(err.message);
});
};
// server config
const serverConfig = {
open: options.open && (options.onePage ? `/${options.onePage.replace(/\.(md|mbd)$/, '.html')}` : true),
logLevel: 0,
root: outputFolder,
port: options.port || 8080,
mount: [],
};
printHeader();
site
.readSiteConfig()
.then((config) => {
serverConfig.mount.push([config.baseUrl || '/', outputFolder]);
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('deploy')
.alias('d')
.description('deploy the site to the repo\'s Github pages.')
.option('-t, --travis [tokenVar]', 'deploy the site in Travis [GITHUB_TOKEN]')
.action((options) => {
const rootFolder = path.resolve(process.cwd());
const outputRoot = path.join(rootFolder, '_site');
new Site(rootFolder, outputRoot).deploy(options.travis)
.then(() => {
logger.info('Deployed!');
})
.catch(handleError);
printHeader();
});
program
.command('build [root] [output]')
.alias('b')
.option('--baseUrl [baseUrl]',
'optional flag which overrides baseUrl in site.json, leave argument empty for empty baseUrl')
.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);
} catch (err) {
handleError(err);
}
const defaultOutputRoot = path.join(rootFolder, '_site');
const outputFolder = output ? path.resolve(process.cwd(), output) : defaultOutputRoot;
printHeader();
new Site(rootFolder, outputFolder)
.generate(baseUrl)
.then(() => {
logger.info('Build success!');
})
.catch(handleError);
});
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 {
printHeader();
program.help();
}
}