Advertisement
Guest User

Untitled

a guest
Dec 4th, 2016
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.30 KB | None | 0 0
  1. const gulp = require('gulp-help')(require('gulp'));
  2. const AWS = require('aws-sdk');
  3. const runSequence = require('run-sequence');
  4. const logger = require('log4js').getLogger('Revgen Build');
  5. const jsdoc = require('gulp-jsdoc3');
  6. const mime = require('mime');
  7. const request = require('request');
  8.  
  9. const mocha = require('gulp-mocha');
  10. const babel = require('babel-core/register');
  11. const uglify = require('gulp-uglify');
  12. const browserify = require('browserify');
  13. const del = require('del');
  14. const source = require('vinyl-source-stream');
  15. const tap = require('gulp-tap');
  16. const git = require('gulp-git');
  17.  
  18. const pkg = require('./package.json');
  19.  
  20. const minimist = require('minimist');
  21. const _ = require('lodash');
  22.  
  23. /*
  24. * Initializations
  25. */
  26. const s3 = new AWS.S3();
  27.  
  28. /*
  29. * Paths
  30. */
  31.  
  32. const globs = {
  33. src: `./src/**/*[!${pkg.build.testFilePattern}].js`,
  34. tests: `./**[!node_modules]/*${pkg.build.testFilePattern}.js`,
  35. dist: './dist/',
  36. };
  37.  
  38. const files = {
  39. concatFileName: `${pkg.deployment.compiledFileName}.concat.js`,
  40. concatPath: `${globs.dist}${pkg.deployment.compiledFileName}.concat.js`,
  41. compiled: `${globs.dist}${pkg.deployment.compiledFileName}.js`,
  42. };
  43.  
  44. const gitOpts = {
  45. cwd: pkg.deployment.repoPath,
  46. };
  47.  
  48. /**
  49. Command Line
  50. **/
  51.  
  52. const opts = minimist(process.argv.slice(2));
  53. opts.user = opts.user || process.env.bamboo_prod_user;
  54. opts.password = opts.password || process.env.bamboo_prod_password;
  55. // bamboo puts these in the env variables, so if they don't come through cmd line we get them here
  56.  
  57. opts.target_branch = opts.target_branch || process.env.bamboo_target_branch;
  58.  
  59. // set env
  60. process.env.NODE_ENV = opts.env || process.env.bamboo_env || 'production';
  61.  
  62. const slackParams = {
  63. url: opts.slack_webhook || process.env.bamboo_slack_webhook,
  64. channel: opts.slack_channel || process.env.bamboo_slack_channel,
  65. username: opts.slack_user || process.env.bamboo_slack_user,
  66. icon_url: opts.slack_icon || process.env.bamboo_slack_icon,
  67. icon_emoji: opts.slack_emoji || process.env.bamboo_slack_emoji,
  68. };
  69.  
  70. logger.setLevel(opts.loglevel || 'DEBUG');
  71.  
  72. const notifyParams = {
  73. buildNumber: process.env.bamboo_buildNumber || 'N/A',
  74. pkgName: pkg.name,
  75. resultsUrl: process.env.bamboo_buildResultsUrl || 'N/A',
  76. branchName: process.env.bamboo_planRepository_branchName || 'N/A',
  77. };
  78.  
  79. function sendSlackMessage(messageTemplate, params, cb) {
  80. const message = _.template(messageTemplate)(params);
  81. const reqBody = _.clone(slackParams);
  82. delete reqBody.url;
  83. reqBody.text = message;
  84.  
  85. return request.post(slackParams.url, { body: reqBody, json: true }, (err, response, body) => {
  86. logger.debug(`Slack response: ${body}`);
  87. if (!err) logger.info(`Slack channel ${reqBody.channel} updated.`);
  88. else {
  89. logger.fatal(err);
  90. }
  91.  
  92. if (cb && typeof cb === 'function') cb(err);
  93. });
  94. }
  95.  
  96. /**
  97. Tasks
  98. **/
  99.  
  100. gulp.task('default', 'shows the help', () =>
  101. gulp.start('help')
  102. );
  103.  
  104. /**
  105. * Cleans the dist directory
  106. */
  107. gulp.task('clean', 'Cleans the dist directory', (cb) =>
  108. del(globs.dist, cb)
  109. );
  110.  
  111. /**
  112. * Concatenates then browserifies the src files. Uses the ordered-concat task as a dependency
  113. */
  114. gulp.task('browserify', 'Browserifies the src files. Uses the ordered-concat task as a dependency', () => {
  115. const bundler = browserify({ entries: pkg.build.indexFile, debug: process.env.NODE_ENV !== 'production' });
  116.  
  117. bundler.transform('rollupify');
  118.  
  119. bundler.transform('envify', {
  120. NODE_ENV: process.env.NODE_ENV,
  121. });
  122.  
  123. return bundler.transform('babelify', {
  124. compact: false,
  125. presets: ['es2015'],
  126. }).bundle()
  127. .on('error', (err) => {
  128. logger.fatal(err);
  129. })
  130. .pipe(source(`${pkg.deployment.compiledFileName}.js`))
  131. .pipe(gulp.dest('./dist'));
  132. });
  133.  
  134. gulp.task('uglify-dist', 'Uglifies the src code found in the dist directory', () => {
  135. if (process.env.NODE_ENV === 'production') {
  136. gulp.src(`${globs.dist}**/*`)
  137. .pipe(uglify())
  138. .on('end', () => {
  139. logger.debug('Files uglified.');
  140. })
  141. .pipe(gulp.dest(globs.dist));
  142. }
  143. });
  144. gulp.task('watch', 'Watches the source files and builds and documents them as they change.', () => {
  145. gulp.watch(globs.src, () =>
  146. gulp.start('browserify')).on('change', (file) => {
  147. logger.info(`Documenting: ${file.path}`);
  148. return gulp.src(file.path)
  149. .pipe(jsdoc());
  150. });
  151. });
  152.  
  153. gulp.task('checkout', 'Checks out the appropriate branch of the static final repository', (cb) => {
  154. git.checkout(opts.target_branch, gitOpts, (err => {
  155. if (err) {
  156. logger.fatal(err.message);
  157. logger.fatal(`Unable to checkout branch: ${opts.target_branch}. Stopping.`);
  158. sendSlackMessage(pkg.deployment.fail_message, notifyParams);
  159. }
  160. cb(err);
  161. }));
  162. });
  163.  
  164. gulp.task('docs', 'Generates docs for all src files.', () => {
  165. return gulp.src(globs.src)
  166. .pipe(jsdoc());
  167. });
  168. /**
  169. * Executes unit test utilizing the nyan cat reporter
  170. */
  171. gulp.task('test', 'Executes unit test utilizing the nyan cat reporter', () =>
  172. gulp.src(globs.tests, {
  173. read: true, // leaves the vinyl contents empty as mocha only requires the paths
  174. })
  175. .pipe(mocha({
  176. reporter: 'nyan',
  177. compilers: {
  178. js: babel
  179. }
  180. }))
  181. );
  182.  
  183. /**
  184. * Runs test using the Bamboo specific reporter
  185. */
  186. gulp.task('test-bamboo', 'Runs test using the Bamboo specific reporter', () => {
  187. function handleError(err) {
  188. logger.error(err);
  189. this.emit('end');
  190. }
  191.  
  192. return gulp.src(globs.tests, {
  193. read: false, // leaves the vinyl contents empty as mocha only requires the paths
  194. })
  195. .pipe(mocha({
  196. reporter: 'mocha-bamboo-reporter',
  197. compilers: {
  198. js: babel
  199. }
  200. })).on('error', handleError);
  201. });
  202.  
  203. gulp.task('copy-dist', 'Copies the compiled assets from dist to the final repo folder', () =>
  204. gulp.src(`${globs.dist}**/*`)
  205. .pipe(tap((file) => logger.debug(`Copying ${file.path}`)))
  206. .pipe(gulp.dest(pkg.deployment.deployPath))
  207. );
  208.  
  209. gulp.task('push-changes', 'Pushes the latest static final commits to the remote branch.', (cb) => {
  210. logger.debug('Attempting to push branch to deployment.');
  211. return git.push('deployment', opts.target_branch, gitOpts, (err) => {
  212. if (err) logger.fatal(err);
  213. else {
  214. logger.info('Successfully deployed.');
  215. sendSlackMessage(pkg.deployment.deploy_message, notifyParams);
  216. }
  217. cb(err);
  218. });
  219. });
  220.  
  221. gulp.task('deploy-final', 'Copies the compiled files over to the static final repository and pushes to remote', () => {
  222. const remoteUrl = _.template(pkg.deployment.remoteUrl)(opts);
  223. function onCommitError(errorObj) {
  224. logger.warn(errorObj.message);
  225. logger.warn('Nothing to commit.');
  226. sendSlackMessage(pkg.deployment.build_message, notifyParams);
  227. this.emit('end', true);
  228. }
  229.  
  230. git.addRemote('deployment', remoteUrl, gitOpts, (err) => {
  231. if (err) {
  232. if (err.code === 128) {
  233. logger.warn(err.message); // means remote already exists.. was this repo already present?
  234. } else {
  235. logger.fatal(err.message);
  236. sendSlackMessage(pkg.deployment.fail_message, notifyParams);
  237. }
  238. } else {
  239. logger.debug('Attempting to add and commit new revgen files.');
  240. gulp.src(`${pkg.deployment.deployPath}/**/*`)
  241. .pipe(tap((file) => {
  242. logger.debug(`Adding file: ${file.path}`);
  243. }))
  244. .pipe(git.add(gitOpts))
  245. .pipe(git.commit(`Automated deployment of build #${notifyParams.buildNumber} of branch ${notifyParams.branchName} of ${pkg.name} to static final.`, gitOpts))
  246. .on('error', onCommitError)
  247. .on('end', (stop) => {
  248. if (!stop) gulp.start('push-changes'); // no end event is emitted when error is present
  249. });
  250. }
  251. });
  252. });
  253.  
  254. gulp.task('deploy-docs', 'Gathers up the files from the docs folder and uploads them to S3', (cb) => {
  255. const params = {
  256. Bucket: 'revgen-docs',
  257. Key: pkg.name,
  258. ACL: 'public-read',
  259. };
  260.  
  261. return gulp.src('./docs/gen/**/*')
  262. .pipe(tap((file, t) => {
  263. params.Key = `${pkg.name}${file.path.replace(process.cwd(), '')}`;
  264. params.Body = file.contents;
  265. params.ContentType = mime.lookup(file.path);
  266. s3.putObject(params, (err, response) => {
  267. if (err) {
  268. logger.fatal(err);
  269. cb(err);
  270. } else {
  271. logger.info(`Successfully deployed ${file.path.replace(process.cwd(), '')} to S3. Etag = ${JSON.stringify(response)}`);
  272. }
  273. });
  274. }));
  275. });
  276.  
  277. gulp.task('deploy', 'Runs a sequence of tasks that will build and deploy.', (cb) => {
  278. runSequence('clean', 'browserify', 'uglify-dist', 'checkout', 'copy-dist', 'deploy-final', cb);
  279. });
  280.  
  281. gulp.task('build', 'Runs a sequence of tasks that will build but WONT deploy.', (cb) => {
  282. runSequence('clean', 'browserify', 'uglify-dist', cb);
  283. });
  284.  
  285. /**
  286. * Builds the test file that requires revgen instead of having a script tag
  287. */
  288. gulp.task('require', () => {
  289. const bundler = browserify('./.vscode/require_test.js');
  290. bundler.transform('rollupify');
  291. bundler.transform('envify', {
  292. NODE_ENV: process.env.NODE_ENV,
  293. });
  294.  
  295. return bundler.transform('babelify', {
  296. presets: ['es2015'],
  297. }).bundle()
  298. .on('error', (err) => {
  299. logger.fatal(err);
  300. })
  301. .pipe(source('revgen.min.js'))
  302. .pipe(gulp.dest('./dist'));
  303. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement