gulpfile.babel.js 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. import gulp from 'gulp';
  2. import loadPlugins from 'gulp-load-plugins';
  3. import del from 'del';
  4. import glob from 'glob';
  5. import path from 'path';
  6. import isparta from 'isparta';
  7. import babelify from 'babelify';
  8. import watchify from 'watchify';
  9. import buffer from 'vinyl-buffer';
  10. import esperanto from 'esperanto';
  11. import browserify from 'browserify';
  12. import runSequence from 'run-sequence';
  13. import source from 'vinyl-source-stream';
  14. import fs from 'fs';
  15. import moment from 'moment';
  16. import docco from 'docco';
  17. import {spawn} from 'child_process';
  18. import manifest from './package.json';
  19. // Load all of our Gulp plugins
  20. const $ = loadPlugins();
  21. // Gather the library data from `package.json`
  22. const config = manifest.babelBoilerplateOptions;
  23. const mainFile = manifest.main;
  24. const destinationFolder = path.dirname(mainFile);
  25. const exportFileName = path.basename(mainFile, path.extname(mainFile));
  26. // Remove a directory
  27. function _clean(dir, done) {
  28. del([dir], done);
  29. }
  30. function cleanDist(done) {
  31. _clean(destinationFolder, done)
  32. }
  33. function cleanTmp() {
  34. _clean('tmp', done)
  35. }
  36. // Send a notification when JSCS fails,
  37. // so that you know your changes didn't build
  38. function _jscsNotify(file) {
  39. if (!file.jscs) { return; }
  40. return file.jscs.success ? false : 'JSCS failed';
  41. }
  42. // Lint a set of files
  43. function lint(files) {
  44. return gulp.src(files)
  45. .pipe($.plumber())
  46. .pipe($.eslint())
  47. .pipe($.eslint.format())
  48. .pipe($.eslint.failOnError())
  49. .pipe($.jscs())
  50. .pipe($.notify(_jscsNotify));
  51. }
  52. function lintSrc() {
  53. return lint('src/**/*.js');
  54. }
  55. function lintTest() {
  56. return lint('test/**/*.js');
  57. }
  58. function build(done) {
  59. esperanto.bundle({
  60. base: 'src',
  61. entry: config.entryFileName,
  62. }).then(bundle => {
  63. const res = bundle.toUmd({
  64. // Don't worry about the fact that the source map is inlined at this step.
  65. // `gulp-sourcemaps`, which comes next, will externalize them.
  66. sourceMap: 'inline',
  67. name: config.mainVarName
  68. });
  69. const head = fs.readFileSync('src/header.js', 'utf8');
  70. $.file(exportFileName + '.js', res.code, { src: true })
  71. .pipe($.plumber())
  72. .pipe($.replace('@@version', manifest.version))
  73. .pipe($.sourcemaps.init({ loadMaps: true }))
  74. .pipe($.babel())
  75. .pipe($.header(head, {pkg: manifest, now: moment()}))
  76. .pipe($.replace('global.$', 'global.jQuery')) // Babel bases itself on the variable name we use. Use jQuery for noconflict users.
  77. .pipe($.sourcemaps.write('./'))
  78. .pipe(gulp.dest(destinationFolder))
  79. .pipe($.filter(['*', '!**/*.js.map']))
  80. .pipe($.rename(exportFileName + '.min.js'))
  81. .pipe($.sourcemaps.init({ loadMaps: true }))
  82. .pipe($.uglify({preserveComments: 'license'}))
  83. .pipe($.sourcemaps.write('./'))
  84. .pipe(gulp.dest(destinationFolder))
  85. .on('end', done);
  86. })
  87. .catch(done);
  88. }
  89. function buildDoc(done) {
  90. var dest = 'doc/annotated-source/';
  91. var sources = glob.sync('src/parsley/*.js');
  92. del.sync([dest + '*']);
  93. docco.document({
  94. layout: 'parallel',
  95. output: dest,
  96. args: sources
  97. }, function() {
  98. gulp.src(dest + '*.html', { base: "./" })
  99. .pipe($.replace('<div id="jump_page">', '<div id="jump_page"><a class="source" href="../index.html"><<< back to documentation</a>'))
  100. .pipe($.replace('</body>', '<script type="text/javascript">var _gaq=_gaq||[];_gaq.push(["_setAccount","UA-37229467-1"]);_gaq.push(["_trackPageview"]);(function(){var e=document.createElement("script");e.type="text/javascript";e.async=true;e.src=("https:"==document.location.protocol?"https://ssl":"http://www")+".google-analytics.com/ga.js";var t=document.getElementsByTagName("script")[0];t.parentNode.insertBefore(e,t)})();</script></body>'))
  101. .pipe(gulp.dest('.'))
  102. .on('end', done);
  103. });
  104. }
  105. function copyI18n(done) {
  106. gulp.src(['src/i18n/*.js'])
  107. .pipe($.replace("import Parsley from '../parsley';", "// Load this after Parsley")) // Quick hack
  108. .pipe($.replace("import Parsley from '../parsley/main';", "")) // en uses special import
  109. .pipe(gulp.dest('dist/i18n/'))
  110. .on('end', done);
  111. }
  112. function writeVersion() {
  113. return gulp.src(['index.html', 'doc/download.html', 'README.md'], { base: "./" })
  114. .pipe($.replace(/class="parsley-version">[^<]*</, `class="parsley-version">v${manifest.version}<`))
  115. .pipe($.replace(/releases\/tag\/[^"]*/, `releases/tag/${manifest.version}`))
  116. .pipe($.replace(/## Version\n\n\S+\n\n/, `## Version\n\n${manifest.version}\n\n`))
  117. .pipe(gulp.dest('.'))
  118. }
  119. function _runBrowserifyBundle(bundler, dest) {
  120. return bundler.bundle()
  121. .on('error', err => {
  122. console.log(err.message);
  123. this.emit('end');
  124. })
  125. .pipe($.plumber())
  126. .pipe(source(dest || './tmp/__spec-build.js'))
  127. .pipe(buffer())
  128. .pipe(gulp.dest(''))
  129. .pipe($.livereload());
  130. }
  131. function browserifyBundler() {
  132. // Our browserify bundle is made up of our unit tests, which
  133. // should individually load up pieces of our application.
  134. // We also include the browserify setup file.
  135. const testFiles = glob.sync('./test/unit/**/*.js');
  136. const allFiles = ['./test/setup/browserify.js'].concat(testFiles);
  137. // Create our bundler, passing in the arguments required for watchify
  138. watchify.args.debug = true;
  139. const bundler = browserify(allFiles, watchify.args);
  140. // Set up Babelify so that ES6 works in the tests
  141. bundler.transform(babelify.configure({
  142. sourceMapRelative: __dirname + '/src'
  143. }));
  144. return bundler;
  145. }
  146. // Build the unit test suite for running tests
  147. // in the browser
  148. function _browserifyBundle() {
  149. let bundler = browserifyBundler();
  150. // Watch the bundler, and re-bundle it whenever files change
  151. bundler = watchify(bundler);
  152. bundler.on('update', () => _runBrowserifyBundle(bundler));
  153. return _runBrowserifyBundle(bundler);
  154. }
  155. function buildDocTest() {
  156. return _runBrowserifyBundle(browserifyBundler(), './doc/assets/spec-build.js');
  157. }
  158. function _mocha() {
  159. return gulp.src(['test/setup/node.js', 'test/unit/**/*.js'], {read: false})
  160. .pipe($.mocha({reporter: 'dot', globals: config.mochaGlobals}));
  161. }
  162. function _registerBabel() {
  163. require('babel-core/register');
  164. }
  165. function test() {
  166. _registerBabel();
  167. return _mocha();
  168. }
  169. function coverage(done) {
  170. _registerBabel();
  171. gulp.src([exportFileName + '.js'])
  172. .pipe($.istanbul({ instrumenter: isparta.Instrumenter }))
  173. .pipe($.istanbul.hookRequire())
  174. .on('finish', () => {
  175. return test()
  176. .pipe($.istanbul.writeReports())
  177. .on('end', done);
  178. });
  179. }
  180. // These are JS files that should be watched by Gulp. When running tests in the browser,
  181. // watchify is used instead, so these aren't included.
  182. const jsWatchFiles = ['src/**/*', 'test/**/*'];
  183. // These are files other than JS files which are to be watched. They are always watched.
  184. const otherWatchFiles = ['package.json', '**/.eslintrc', '.jscsrc'];
  185. // Run the headless unit tests as you make changes.
  186. function watch() {
  187. const watchFiles = jsWatchFiles.concat(otherWatchFiles);
  188. gulp.watch(watchFiles, ['test']);
  189. }
  190. function testBrowser() {
  191. // Ensure that linting occurs before browserify runs. This prevents
  192. // the build from breaking due to poorly formatted code.
  193. runSequence(['lint-src', 'lint-test'], () => {
  194. _browserifyBundle();
  195. $.livereload.listen({port: 35729, host: 'localhost', start: true});
  196. gulp.watch(otherWatchFiles, ['lint-src', 'lint-test']);
  197. });
  198. }
  199. function gitClean() {
  200. $.git.status({args : '--porcelain'}, (err, stdout) => {
  201. if (err) throw err;
  202. if (/^ ?M/.test(stdout)) throw 'You have uncommitted changes!'
  203. });
  204. }
  205. function npmPublish(done) {
  206. spawn('npm', ['publish'], { stdio: 'inherit' }).on('close', done);
  207. }
  208. function gitPush() {
  209. $.git.push('origin', 'master', {args: '--follow-tags'}, err => { if (err) throw err });
  210. }
  211. function gitPushPages() {
  212. $.git.push('origin', 'master:gh-pages', err => { if (err) throw err });
  213. }
  214. function gitTag() {
  215. $.git.tag(manifest.version, {quiet: false}, err => { if (err) throw err });
  216. }
  217. gulp.task('release-git-clean', gitClean);
  218. gulp.task('release-npm-publish', npmPublish);
  219. gulp.task('release-git-push', gitPush);
  220. gulp.task('release-git-push-pages', gitPushPages);
  221. gulp.task('release-git-tag', gitTag);
  222. gulp.task('release', () => {
  223. runSequence('release-git-clean', 'release-git-tag', 'release-git-push', 'release-git-push-pages', 'release-npm-publish');
  224. });
  225. // Remove the built files
  226. gulp.task('clean', cleanDist);
  227. // Remove our temporary files
  228. gulp.task('clean-tmp', cleanTmp);
  229. // Lint our source code
  230. gulp.task('lint-src', lintSrc);
  231. // Lint our test code
  232. gulp.task('lint-test', lintTest);
  233. // Build two versions of the library
  234. gulp.task('build-src', ['lint-src', 'clean', 'build-i18n'], build);
  235. // Build the i18n translations
  236. gulp.task('build-i18n', ['clean'], copyI18n);
  237. // Build the annotated documentation
  238. gulp.task('build-doc', buildDoc);
  239. // Build the annotated documentation
  240. gulp.task('build-doc-test', buildDocTest);
  241. gulp.task('write-version', writeVersion);
  242. gulp.task('build', ['build-src', 'build-i18n', 'build-doc', 'build-doc-test', 'write-version']);
  243. // Lint and run our tests
  244. gulp.task('test', ['lint-src', 'lint-test'], test);
  245. // Set up coverage and run tests
  246. gulp.task('coverage', ['lint-src', 'lint-test'], coverage);
  247. // Set up a livereload environment for our spec runner `test/runner.html`
  248. gulp.task('test-browser', testBrowser);
  249. // Run the headless unit tests as you make changes.
  250. gulp.task('watch', watch);
  251. // An alias of test
  252. gulp.task('default', ['test']);