/
bundle.js
203 lines (173 loc) · 6.38 KB
/
bundle.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
class BuildError extends Error {
constructor(message) {
super(message);
this.isBuild = true;
}
}
function render(filepath, context) {
const ejs = require('ejs');
const fs = require('fs');
return ejs.render(fs.readFileSync(filepath, 'utf8'), context);
}
function getVersion(rootPath) {
const fs = require('fs');
return fs.promise.readFile(`${rootPath}/package.json`)
.then(JSON.parse)
.then(({version}) => version);
}
function getAvailableBrushes(rootPath) {
const glob = require('glob');
return glob.promise(`${rootPath}/repos/brush-*`)
.then(brushes => brushes.map(path => path.match(/brush-(.*)$/)[1]));
}
function getBuildBrushes(rootPath, argv, availableBrushes) {
const fs = require('fs');
const path = require('path');
const Promise = require('songbird');
if (!argv.brushes) {
return Promise.resolve([]);
}
let buildBrushes = (argv.brushes || '').toString().split(',');
if (buildBrushes.length === 0 || buildBrushes[0] === 'true') {
return Promise.reject(new BuildError('Please specify at least one brush or "all".'));
}
if (buildBrushes.length === 1 && buildBrushes[0] === 'all') {
buildBrushes = availableBrushes;
}
return Promise.all(buildBrushes.map(function (name) {
let requirePath = path.resolve(process.cwd(), name);
let sample;
return fs.promise.stat(requirePath)
// handle brushes by full file path
.then(
() => fs.promise.readFile(`${path.dirname(requirePath)}/sample.txt`)
.then(content => sample = content)
.catch(() => null)
.then(() => requirePath = path.relative(`${rootPath}/src`, requirePath))
)
// handle brushes by name only
.catch(function () {
if (availableBrushes.indexOf(name) === -1) {
return Promise.reject(new BuildError(`Unknown brush "${name}".`));
}
requirePath = `brush-${name}`;
return fs.promise.readFile(`${rootPath}/repos/brush-${name}/sample.txt`, 'utf8')
.then(content => sample = content)
.catch(() => null);
})
.then(() => sample = sample || 'no sample.txt found')
.then(() => Promise.props({name, requirePath, sample}));
}));
}
function buildJavaScript(rootPath, outputPath, buildBrushes, version) {
const fs = require('fs');
const webpack = require('webpack');
const banner = render(`${rootPath}/build/templates/banner.js.ejs`, { version, date: (new Date).toUTCString() });
const registerBrushes = render(`${rootPath}/build/templates/bundle-register-brushes.js.ejs`, { buildBrushes });
const core = render(`${rootPath}/src/core.js`, { registerBrushes });
const corePath = `${rootPath}/src/core.js`;
const backupCorePath = `${rootPath}/src/core.js.bak`;
const config = {
entry: `${rootPath}/src/index.js`,
output: {
path: outputPath,
filename: 'syntaxhighlighter.js'
},
externals: [
'shCore'
],
resolve: {
extensions: ['', '.js', '.es6'],
alias: {
'xregexp': 'xregexp/src/xregexp',
},
},
module: {
loaders: [
{
test: [/\.js$/, /\.es6$/],
loader: 'babel',
},
],
},
plugins: [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin({ comments: false }),
new webpack.BannerPlugin(banner),
new webpack.SourceMapDevToolPlugin({
filename: 'syntaxhighlighter.js.map',
append: '\n//# sourceMappingURL=[url]',
}),
]
};
return fs.promise.rename(corePath, backupCorePath)
.then(() => fs.promise.writeFile(corePath, core))
.then(() => webpack.promise(config))
.then(stats =>
fs.promise.unlink(corePath)
.then(() => fs.promise.rename(backupCorePath, corePath))
.then(() => stats)
);
}
function buildCSS(rootPath, outputPath, theme, version) {
const Promise = require('songbird');
const fs = require('fs');
const sass = require('node-sass');
if (!theme) return;
return fs.promise.stat(theme)
.then(() => theme, () => `${rootPath}/repos/theme-${theme}/theme.scss`)
.then(path => fs.promise.readFile(path, 'utf8'))
.then(data => sass.promise.render({ data, includePaths: [`${rootPath}/node_modules/@alexgorbatchev/theme-base`] }))
.then(results => fs.promise.writeFile(`${outputPath}/theme.css`, results.css))
;
}
function copyHtml(rootPath, outputPath, buildBrushes, version) {
const fs = require('fs');
const Promise = require('songbird');
return fs.promise.writeFile(
`${outputPath}/index.html`,
render(`${rootPath}/build/templates/index.html.ejs`, { buildBrushes, version })
);
}
export function bundle(rootPath, destPath, argv) {
return Promise.all([
getAvailableBrushes(rootPath),
getVersion(rootPath),
])
.then(function ([availableBrushes, version]) {
argv = argv || require('yargs')
.describe('brushes', 'Comma separated list of brush names or paths to be bundled.')
.describe('theme', 'Name or path of the CSS theme you want to use.')
.default('output', `${rootPath}/dist`).describe('output', 'Output folder for dist files.')
.epilog(`Available brushes are "all" or ${availableBrushes.join(', ')}.\n\nYou may also pass paths to brush JavaScript files and theme SASS files.`)
.help('help')
.argv;
return getBuildBrushes(rootPath, argv, availableBrushes)
.then(function (buildBrushes) {
return Promise.all([
buildJavaScript(rootPath, argv.output, buildBrushes, version),
buildCSS(rootPath, argv.output, argv.theme, version),
copyHtml(rootPath, argv.output, buildBrushes, version),
])
.then(([stats]) => ({ theme: argv.theme, stats, buildBrushes }));
});
});
}
export default function (gulp, rootPath) {
gulp.task(
'build',
'Builds distribution files to be used via `<script/>` tags. $ gulp build --brushes value1,value2 --theme value',
function (done) {
const gulpUtil = require('gulp-util');
bundle(rootPath, null)
.then(function ({ theme, stats, buildBrushes }) {
const gulpUtil = require('gulp-util');
if (theme) gulpUtil.log(`Theme: ${theme}`);
if (buildBrushes) gulpUtil.log(`Brushes: ${buildBrushes.map(brush => brush.name).join(', ')}`);
gulpUtil.log(stats.toString({ colors: true }));
done();
})
.catch(err => gulpUtil.log(gulpUtil.colors.red(err.isBuild ? err.message : err.stack)))
}
);
}