]> git.gir.st - VimFx.git/blob - gulpfile.coffee
Update to gulp 4 (#915)
[VimFx.git] / gulpfile.coffee
1 fs = require('fs')
2 path = require('path')
3 gulp = require('gulp')
4 coffee = require('gulp-coffee')
5 coffeelint = require('gulp-coffeelint')
6 git = require('gulp-git')
7 header = require('gulp-header')
8 mustache = require('gulp-mustache')
9 preprocess = require('gulp-preprocess')
10 sloc = require('gulp-sloc')
11 tap = require('gulp-tap')
12 zip = require('gulp-zip')
13 marked = require('marked')
14 merge = require('merge2')
15 precompute = require('require-precompute')
16 request = require('request')
17 rimraf = require('rimraf')
18 pkg = require('./package.json')
19
20 DEST = 'build'
21 XPI = 'VimFx.xpi'
22 LOCALE = 'extension/locale'
23 TEST = 'extension/test'
24
25 BASE_LOCALE = 'en-US'
26 UPDATE_ALL = /\s*UPDATE_ALL$/
27
28 ADDON_PATH = 'chrome://vimfx'
29 BUILD_TIME = Date.now()
30
31 argv = process.argv.slice(2)
32
33 {join} = path
34 read = (filepath) -> fs.readFileSync(filepath).toString()
35 template = (data) -> mustache(data, {extension: ''})
36
37 gulp.task('clean', (callback) ->
38 rimraf(DEST, callback)
39 )
40
41 gulp.task('copy', ->
42 gulp.src(['extension/**/!(*.coffee|*.tmpl)', 'LICENSE', 'LICENSE-MIT'])
43 .pipe(gulp.dest(DEST))
44 )
45
46 gulp.task('node_modules', ->
47 dependencies = (name for name of pkg.dependencies)
48 # Note: When installing or updating node modules, make sure that the following
49 # glob does not include too much or too little!
50 gulp.src(
51 "node_modules/+(#{dependencies.join('|')})/\
52 {LICENSE*,{,**/!(test|examples)/}!(*min|*test*|*bench*).js}"
53 )
54 .pipe(gulp.dest("#{DEST}/node_modules"))
55 )
56
57 gulp.task('coffee', ->
58 test = '--test' in argv or '-t' in argv
59 gulp.src(
60 [
61 'extension/bootstrap.coffee'
62 'extension/lib/**/*.coffee'
63 ].concat(if test then 'extension/test/**/*.coffee' else []),
64 {base: 'extension'}
65 )
66 .pipe(preprocess({context: {
67 BUILD_TIME
68 ADDON_PATH: JSON.stringify(ADDON_PATH)
69 REQUIRE_DATA: JSON.stringify(precompute('.'), null, 2)
70 TESTS:
71 if test
72 JSON.stringify(fs.readdirSync(TEST)
73 .map((name) -> name.match(/^(test-.+)\.coffee$/)?[1])
74 .filter(Boolean)
75 )
76 else
77 null
78 }}))
79 .pipe(coffee({bare: true}))
80 .pipe(gulp.dest(DEST))
81 )
82
83 gulp.task('bootstrap-frame.js', ->
84 gulp.src('extension/bootstrap-frame.js.tmpl')
85 .pipe(mustache({ADDON_PATH}))
86 .pipe(tap((file) ->
87 file.path = file.path.replace(/\.js\.tmpl$/, "-#{BUILD_TIME}.js")
88 ))
89 .pipe(gulp.dest(DEST))
90 )
91
92 gulp.task('chrome.manifest', ->
93 gulp.src('extension/chrome.manifest.tmpl')
94 .pipe(template({locales: fs.readdirSync(LOCALE).map((locale) -> {locale})}))
95 .pipe(gulp.dest(DEST))
96 )
97
98 gulp.task('install.rdf', ->
99 [[{name: creator}], developers, contributors, translators] =
100 read('PEOPLE.md').trim().replace(/^#.+\n|^\s*-\s*/mg, '').split('\n\n')
101 .map((block) -> block.split('\n').map((name) -> {name}))
102
103 getDescription = (locale) -> read(join(LOCALE, locale, 'description')).trim()
104
105 descriptions = fs.readdirSync(LOCALE)
106 .filter((locale) -> locale != BASE_LOCALE)
107 .map((locale) -> {locale, description: getDescription(locale)})
108
109 gulp.src('extension/install.rdf.tmpl')
110 .pipe(template({
111 idSuffix: if '--unlisted' in argv or '-u' in argv then '-unlisted' else ''
112 version: pkg.version
113 minVersion: pkg.firefoxVersions.min
114 maxVersion: pkg.firefoxVersions.max
115 creator, developers, contributors, translators
116 defaultDescription: getDescription(BASE_LOCALE)
117 descriptions
118 }))
119 .pipe(gulp.dest(DEST))
120 )
121
122 gulp.task('templates', gulp.parallel(
123 'bootstrap-frame.js'
124 'chrome.manifest'
125 'install.rdf'
126 ))
127
128 gulp.task('build', gulp.series(
129 'clean',
130 gulp.parallel('copy', 'node_modules', 'coffee', 'templates')
131 ))
132
133 gulp.task('xpi', gulp.series('build', ->
134 gulp.src("#{DEST}/**/*")
135 .pipe(zip(XPI, {compress: false}))
136 .pipe(gulp.dest(DEST))
137 ))
138
139 gulp.task('push', gulp.series('xpi', ->
140 body = fs.readFileSync(join(DEST, XPI))
141 request.post({url: 'http://localhost:8888', body})
142 ))
143
144 gulp.task('default', gulp.series('push'))
145
146 gulp.task('lint', ->
147 gulp.src(['extension/**/*.coffee', 'gulpfile.coffee'])
148 .pipe(coffeelint())
149 .pipe(coffeelint.reporter())
150 )
151
152 gulp.task('sloc', ->
153 gulp.src([
154 'extension/bootstrap.coffee'
155 'extension/lib/!(migrations|legacy).coffee'
156 ])
157 .pipe(sloc())
158 )
159
160 gulp.task('release', (callback) ->
161 {version} = pkg
162 message = "VimFx v#{version}"
163 today = new Date().toISOString()[...10]
164 merge([
165 gulp.src('package.json')
166 gulp.src('CHANGELOG.md')
167 .pipe(header("### #{version} (#{today})\n\n"))
168 .pipe(gulp.dest('.'))
169 ])
170 .pipe(git.commit(message))
171 .on('end', ->
172 git.tag("v#{version}", message, callback)
173 )
174 return
175 )
176
177 gulp.task('changelog', ->
178 num = 1
179 for arg in argv when /^-[1-9]$/.test(arg)
180 num = Number(arg[1])
181 entries = read('CHANGELOG.md').split(/^### .+/m)[1..num].join('')
182 process.stdout.write(html(entries))
183 )
184
185 gulp.task('readme', ->
186 process.stdout.write(html(read('README.md')))
187 )
188
189 # Reduce markdown to the small subset of HTML that AMO allows. Note that AMO
190 # converts newlines to `<br>`.
191 html = (string) ->
192 return marked(string)
193 .replace(/// <h\d [^>]*> ([^<>]+) </h\d> ///g, '\n\n<b>$1</b>')
194 .replace(///\s* <p> ((?: [^<] | <(?!/p>) )+) </p>///g, (match, text) ->
195 return "\n#{text.replace(/\s*\n\s*/g, ' ')}\n\n"
196 )
197 .replace(///<li> ((?: [^<] | <(?!/li>) )+) </li>///g, (match, text) ->
198 return "<li>#{text.replace(/\s*\n\s*/g, ' ')}</li>"
199 )
200 .replace(/<br>/g, '\n')
201 .replace(///<(/?)kbd>///g, '<$1code>')
202 .replace(/<img[^>]*>\s*/g, '')
203 .replace(/\n\s*\n/g, '\n\n')
204 .trim() + '\n'
205
206 gulp.task('faster', ->
207 gulp.src('gulpfile.coffee')
208 .pipe(coffee({bare: true}))
209 .pipe(gulp.dest('.'))
210 )
211
212 gulp.task('sync-locales', ->
213 baseLocale = BASE_LOCALE
214 compareLocale = null
215 for arg in argv when arg[...2] == '--'
216 name = arg[2..]
217 if name[-1..] == '?' then compareLocale = name[...-1] else baseLocale = name
218
219 results = fs.readdirSync(join(LOCALE, baseLocale))
220 .filter((file) -> path.extname(file) == '.properties')
221 .map(syncLocale.bind(null, baseLocale))
222
223 if baseLocale == BASE_LOCALE
224 report = []
225 for {fileName, untranslated, total} in results
226 report.push("#{fileName}:")
227 for localeName, strings of untranslated
228 paddedName = "#{localeName}: "[...6]
229 percentage = Math.round((1 - strings.length / total) * 100)
230 if localeName == compareLocale or compareLocale == null
231 report.push(" #{paddedName} #{percentage}%")
232 if localeName == compareLocale
233 report.push(strings.map((string) -> " #{string}")...)
234 process.stdout.write(report.join('\n') + '\n')
235 )
236
237 syncLocale = (baseLocaleName, fileName) ->
238 basePath = join(LOCALE, baseLocaleName, fileName)
239 base = parseLocaleFile(read(basePath))
240 untranslated = {}
241 for localeName in fs.readdirSync(LOCALE)
242 localePath = join(LOCALE, localeName, fileName)
243 locale = parseLocaleFile(read(localePath))
244 untranslated[localeName] = []
245 newLocale = base.template.map((line, index) ->
246 if Array.isArray(line)
247 [key] = line
248 baseValue = base.keys[key]
249 value =
250 if UPDATE_ALL.test(baseValue) or key not of locale.keys
251 baseValue.replace(UPDATE_ALL, '')
252 else
253 locale.keys[key]
254 result = "#{key}=#{value}"
255 if value == base.keys[key] and value != ''
256 untranslated[localeName].push("#{index + 1}: #{result}")
257 return result
258 else
259 return line
260 )
261 fs.writeFileSync(localePath, newLocale.join(base.newline))
262 delete untranslated[baseLocaleName]
263 return {fileName, untranslated, total: Object.keys(base.keys).length}
264
265 parseLocaleFile = (fileContents) ->
266 keys = {}
267 lines = []
268 [newline] = fileContents.match(/\r?\n/)
269 for line in fileContents.split(newline)
270 line = line.trim()
271 [match, key, value] = line.match(///^ ([^=]+) = (.*) $///) ? []
272 if match
273 keys[key] = value
274 lines.push([key])
275 else
276 lines.push(line)
277 return {keys, template: lines, newline}
278
279 generateHTMLTask = (filename, message) ->
280 gulp.task(filename, ->
281 unless fs.existsSync(filename)
282 process.stdout.write(message(filename))
283 return
284 gulp.src(filename)
285 .pipe(tap((file) ->
286 file.contents = new Buffer(generateTestHTML(file.contents.toString()))
287 ))
288 .pipe(gulp.dest('.'))
289 )
290
291 generateHTMLTask('help.html', (filename) -> """
292 First enable the “Copy to clipboard” line in help.coffee, show the help
293 dialog and finally dump the clipboard into #{filename}.
294 """)
295
296 generateHTMLTask('hints.html', (filename) -> """
297 First enable the “Copy to clipboard” line in modes.coffee, show the
298 hint markers, activate the “Increase count” command and finally dump the
299 clipboard into #{filename}.
300 """)
301
302 testHTMLPrelude = '''
303 <!doctype html>
304 <meta charset=utf-8>
305 <title>VimFx test</title>
306 <style>
307 * {margin: 0;}
308 body > :first-child {min-height: 100vh; width: 100vw;}
309 </style>
310 <link rel=stylesheet href=extension/skin/style.css>
311 '''
312
313 generateTestHTML = (dumpedHTML) ->
314 return testHTMLPrelude + dumpedHTML
315 .replace(/^<\w+ xmlns="[^"]+"/, '<div')
316 .replace(/\w+>$/, 'div>')
317 .replace(/<(\w+)([^>]*)\/>/g, '<$1$2></$1>')
Imprint / Impressum