]> git.gir.st - VimFx.git/blob - gulpfile.coffee
Get rid of "<anonymous>" gulp tasks
[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-only', ->
134 gulp.src("#{DEST}/**/*")
135 .pipe(zip(XPI, {compress: false}))
136 .pipe(gulp.dest(DEST))
137 )
138
139 gulp.task('xpi', gulp.series('build', 'xpi-only'))
140
141 gulp.task('push-only', ->
142 body = fs.readFileSync(join(DEST, XPI))
143 request.post({url: 'http://localhost:8888', body})
144 )
145
146 gulp.task('push', gulp.series('xpi', 'push-only'))
147
148 gulp.task('default', gulp.series('push'))
149
150 gulp.task('lint', ->
151 gulp.src(['extension/**/*.coffee', 'gulpfile.coffee'])
152 .pipe(coffeelint())
153 .pipe(coffeelint.reporter())
154 )
155
156 gulp.task('sloc', ->
157 gulp.src([
158 'extension/bootstrap.coffee'
159 'extension/lib/!(migrations|legacy).coffee'
160 ])
161 .pipe(sloc())
162 )
163
164 gulp.task('release', (callback) ->
165 {version} = pkg
166 message = "VimFx v#{version}"
167 today = new Date().toISOString()[...10]
168 merge([
169 gulp.src('package.json')
170 gulp.src('CHANGELOG.md')
171 .pipe(header("### #{version} (#{today})\n\n"))
172 .pipe(gulp.dest('.'))
173 ])
174 .pipe(git.commit(message))
175 .on('end', ->
176 git.tag("v#{version}", message, callback)
177 )
178 return
179 )
180
181 gulp.task('changelog', (callback) ->
182 num = 1
183 for arg in argv when /^-[1-9]$/.test(arg)
184 num = Number(arg[1])
185 entries = read('CHANGELOG.md').split(/^### .+/m)[1..num].join('')
186 process.stdout.write(html(entries))
187 callback()
188 )
189
190 gulp.task('readme', (callback) ->
191 process.stdout.write(html(read('README.md')))
192 callback()
193 )
194
195 # Reduce markdown to the small subset of HTML that AMO allows. Note that AMO
196 # converts newlines to `<br>`.
197 html = (string) ->
198 return marked(string)
199 .replace(/// <h\d [^>]*> ([^<>]+) </h\d> ///g, '\n\n<b>$1</b>')
200 .replace(///\s* <p> ((?: [^<] | <(?!/p>) )+) </p>///g, (match, text) ->
201 return "\n#{text.replace(/\s*\n\s*/g, ' ')}\n\n"
202 )
203 .replace(///<li> ((?: [^<] | <(?!/li>) )+) </li>///g, (match, text) ->
204 return "<li>#{text.replace(/\s*\n\s*/g, ' ')}</li>"
205 )
206 .replace(/<br>/g, '\n')
207 .replace(///<(/?)kbd>///g, '<$1code>')
208 .replace(/<img[^>]*>\s*/g, '')
209 .replace(/\n\s*\n/g, '\n\n')
210 .trim() + '\n'
211
212 gulp.task('faster', ->
213 gulp.src('gulpfile.coffee')
214 .pipe(coffee({bare: true}))
215 .pipe(gulp.dest('.'))
216 )
217
218 gulp.task('sync-locales', (callback) ->
219 baseLocale = BASE_LOCALE
220 compareLocale = null
221 for arg in argv when arg[...2] == '--'
222 name = arg[2..]
223 if name[-1..] == '?' then compareLocale = name[...-1] else baseLocale = name
224
225 results = fs.readdirSync(join(LOCALE, baseLocale))
226 .filter((file) -> path.extname(file) == '.properties')
227 .map(syncLocale.bind(null, baseLocale))
228
229 if baseLocale == BASE_LOCALE
230 report = []
231 for {fileName, untranslated, total} in results
232 report.push("#{fileName}:")
233 for localeName, strings of untranslated
234 paddedName = "#{localeName}: "[...6]
235 percentage = Math.round((1 - strings.length / total) * 100)
236 if localeName == compareLocale or compareLocale == null
237 report.push(" #{paddedName} #{percentage}%")
238 if localeName == compareLocale
239 report.push(strings.map((string) -> " #{string}")...)
240 process.stdout.write(report.join('\n') + '\n')
241
242 callback()
243 )
244
245 syncLocale = (baseLocaleName, fileName) ->
246 basePath = join(LOCALE, baseLocaleName, fileName)
247 base = parseLocaleFile(read(basePath))
248 untranslated = {}
249 for localeName in fs.readdirSync(LOCALE)
250 localePath = join(LOCALE, localeName, fileName)
251 locale = parseLocaleFile(read(localePath))
252 untranslated[localeName] = []
253 newLocale = base.template.map((line, index) ->
254 if Array.isArray(line)
255 [key] = line
256 baseValue = base.keys[key]
257 value =
258 if UPDATE_ALL.test(baseValue) or key not of locale.keys
259 baseValue.replace(UPDATE_ALL, '')
260 else
261 locale.keys[key]
262 result = "#{key}=#{value}"
263 if value == base.keys[key] and value != ''
264 untranslated[localeName].push("#{index + 1}: #{result}")
265 return result
266 else
267 return line
268 )
269 fs.writeFileSync(localePath, newLocale.join(base.newline))
270 delete untranslated[baseLocaleName]
271 return {fileName, untranslated, total: Object.keys(base.keys).length}
272
273 parseLocaleFile = (fileContents) ->
274 keys = {}
275 lines = []
276 [newline] = fileContents.match(/\r?\n/)
277 for line in fileContents.split(newline)
278 line = line.trim()
279 [match, key, value] = line.match(///^ ([^=]+) = (.*) $///) ? []
280 if match
281 keys[key] = value
282 lines.push([key])
283 else
284 lines.push(line)
285 return {keys, template: lines, newline}
286
287 generateHTMLTask = (filename, message) ->
288 gulp.task(filename, (callback) ->
289 unless fs.existsSync(filename)
290 process.stdout.write(message(filename))
291 callback()
292 return
293 gulp.src(filename)
294 .pipe(tap((file) ->
295 file.contents = new Buffer(generateTestHTML(file.contents.toString()))
296 ))
297 .pipe(gulp.dest('.'))
298 )
299
300 generateHTMLTask('help.html', (filename) -> """
301 First enable the “Copy to clipboard” line in help.coffee, show the help
302 dialog and finally dump the clipboard into #{filename}.
303 """)
304
305 generateHTMLTask('hints.html', (filename) -> """
306 First enable the “Copy to clipboard” line in modes.coffee, show the
307 hint markers, activate the “Increase count” command and finally dump the
308 clipboard into #{filename}.
309 """)
310
311 testHTMLPrelude = '''
312 <!doctype html>
313 <meta charset=utf-8>
314 <title>VimFx test</title>
315 <style>
316 * {margin: 0;}
317 body > :first-child {min-height: 100vh; width: 100vw;}
318 </style>
319 <link rel=stylesheet href=extension/skin/style.css>
320 '''
321
322 generateTestHTML = (dumpedHTML) ->
323 return testHTMLPrelude + dumpedHTML
324 .replace(/^<\w+ xmlns="[^"]+"/, '<div')
325 .replace(/\w+>$/, 'div>')
326 .replace(/<(\w+)([^>]*)\/>/g, '<$1$2></$1>')
Imprint / Impressum