Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const gulp = require('gulp-help')(require('gulp'));
- const AWS = require('aws-sdk');
- const runSequence = require('run-sequence');
- const logger = require('log4js').getLogger('Revgen Build');
- const jsdoc = require('gulp-jsdoc3');
- const mime = require('mime');
- const request = require('request');
- const mocha = require('gulp-mocha');
- const babel = require('babel-core/register');
- const uglify = require('gulp-uglify');
- const browserify = require('browserify');
- const del = require('del');
- const source = require('vinyl-source-stream');
- const tap = require('gulp-tap');
- const git = require('gulp-git');
- const pkg = require('./package.json');
- const minimist = require('minimist');
- const _ = require('lodash');
- /*
- * Initializations
- */
- const s3 = new AWS.S3();
- /*
- * Paths
- */
- const globs = {
- src: `./src/**/*[!${pkg.build.testFilePattern}].js`,
- tests: `./**[!node_modules]/*${pkg.build.testFilePattern}.js`,
- dist: './dist/',
- };
- const files = {
- concatFileName: `${pkg.deployment.compiledFileName}.concat.js`,
- concatPath: `${globs.dist}${pkg.deployment.compiledFileName}.concat.js`,
- compiled: `${globs.dist}${pkg.deployment.compiledFileName}.js`,
- };
- const gitOpts = {
- cwd: pkg.deployment.repoPath,
- };
- /**
- Command Line
- **/
- const opts = minimist(process.argv.slice(2));
- opts.user = opts.user || process.env.bamboo_prod_user;
- opts.password = opts.password || process.env.bamboo_prod_password;
- // bamboo puts these in the env variables, so if they don't come through cmd line we get them here
- opts.target_branch = opts.target_branch || process.env.bamboo_target_branch;
- // set env
- process.env.NODE_ENV = opts.env || process.env.bamboo_env || 'production';
- const slackParams = {
- url: opts.slack_webhook || process.env.bamboo_slack_webhook,
- channel: opts.slack_channel || process.env.bamboo_slack_channel,
- username: opts.slack_user || process.env.bamboo_slack_user,
- icon_url: opts.slack_icon || process.env.bamboo_slack_icon,
- icon_emoji: opts.slack_emoji || process.env.bamboo_slack_emoji,
- };
- logger.setLevel(opts.loglevel || 'DEBUG');
- const notifyParams = {
- buildNumber: process.env.bamboo_buildNumber || 'N/A',
- pkgName: pkg.name,
- resultsUrl: process.env.bamboo_buildResultsUrl || 'N/A',
- branchName: process.env.bamboo_planRepository_branchName || 'N/A',
- };
- function sendSlackMessage(messageTemplate, params, cb) {
- const message = _.template(messageTemplate)(params);
- const reqBody = _.clone(slackParams);
- delete reqBody.url;
- reqBody.text = message;
- return request.post(slackParams.url, { body: reqBody, json: true }, (err, response, body) => {
- logger.debug(`Slack response: ${body}`);
- if (!err) logger.info(`Slack channel ${reqBody.channel} updated.`);
- else {
- logger.fatal(err);
- }
- if (cb && typeof cb === 'function') cb(err);
- });
- }
- /**
- Tasks
- **/
- gulp.task('default', 'shows the help', () =>
- gulp.start('help')
- );
- /**
- * Cleans the dist directory
- */
- gulp.task('clean', 'Cleans the dist directory', (cb) =>
- del(globs.dist, cb)
- );
- /**
- * Concatenates then browserifies the src files. Uses the ordered-concat task as a dependency
- */
- gulp.task('browserify', 'Browserifies the src files. Uses the ordered-concat task as a dependency', () => {
- const bundler = browserify({ entries: pkg.build.indexFile, debug: process.env.NODE_ENV !== 'production' });
- bundler.transform('rollupify');
- bundler.transform('envify', {
- NODE_ENV: process.env.NODE_ENV,
- });
- return bundler.transform('babelify', {
- compact: false,
- presets: ['es2015'],
- }).bundle()
- .on('error', (err) => {
- logger.fatal(err);
- })
- .pipe(source(`${pkg.deployment.compiledFileName}.js`))
- .pipe(gulp.dest('./dist'));
- });
- gulp.task('uglify-dist', 'Uglifies the src code found in the dist directory', () => {
- if (process.env.NODE_ENV === 'production') {
- gulp.src(`${globs.dist}**/*`)
- .pipe(uglify())
- .on('end', () => {
- logger.debug('Files uglified.');
- })
- .pipe(gulp.dest(globs.dist));
- }
- });
- gulp.task('watch', 'Watches the source files and builds and documents them as they change.', () => {
- gulp.watch(globs.src, () =>
- gulp.start('browserify')).on('change', (file) => {
- logger.info(`Documenting: ${file.path}`);
- return gulp.src(file.path)
- .pipe(jsdoc());
- });
- });
- gulp.task('checkout', 'Checks out the appropriate branch of the static final repository', (cb) => {
- git.checkout(opts.target_branch, gitOpts, (err => {
- if (err) {
- logger.fatal(err.message);
- logger.fatal(`Unable to checkout branch: ${opts.target_branch}. Stopping.`);
- sendSlackMessage(pkg.deployment.fail_message, notifyParams);
- }
- cb(err);
- }));
- });
- gulp.task('docs', 'Generates docs for all src files.', () => {
- return gulp.src(globs.src)
- .pipe(jsdoc());
- });
- /**
- * Executes unit test utilizing the nyan cat reporter
- */
- gulp.task('test', 'Executes unit test utilizing the nyan cat reporter', () =>
- gulp.src(globs.tests, {
- read: true, // leaves the vinyl contents empty as mocha only requires the paths
- })
- .pipe(mocha({
- reporter: 'nyan',
- compilers: {
- js: babel
- }
- }))
- );
- /**
- * Runs test using the Bamboo specific reporter
- */
- gulp.task('test-bamboo', 'Runs test using the Bamboo specific reporter', () => {
- function handleError(err) {
- logger.error(err);
- this.emit('end');
- }
- return gulp.src(globs.tests, {
- read: false, // leaves the vinyl contents empty as mocha only requires the paths
- })
- .pipe(mocha({
- reporter: 'mocha-bamboo-reporter',
- compilers: {
- js: babel
- }
- })).on('error', handleError);
- });
- gulp.task('copy-dist', 'Copies the compiled assets from dist to the final repo folder', () =>
- gulp.src(`${globs.dist}**/*`)
- .pipe(tap((file) => logger.debug(`Copying ${file.path}`)))
- .pipe(gulp.dest(pkg.deployment.deployPath))
- );
- gulp.task('push-changes', 'Pushes the latest static final commits to the remote branch.', (cb) => {
- logger.debug('Attempting to push branch to deployment.');
- return git.push('deployment', opts.target_branch, gitOpts, (err) => {
- if (err) logger.fatal(err);
- else {
- logger.info('Successfully deployed.');
- sendSlackMessage(pkg.deployment.deploy_message, notifyParams);
- }
- cb(err);
- });
- });
- gulp.task('deploy-final', 'Copies the compiled files over to the static final repository and pushes to remote', () => {
- const remoteUrl = _.template(pkg.deployment.remoteUrl)(opts);
- function onCommitError(errorObj) {
- logger.warn(errorObj.message);
- logger.warn('Nothing to commit.');
- sendSlackMessage(pkg.deployment.build_message, notifyParams);
- this.emit('end', true);
- }
- git.addRemote('deployment', remoteUrl, gitOpts, (err) => {
- if (err) {
- if (err.code === 128) {
- logger.warn(err.message); // means remote already exists.. was this repo already present?
- } else {
- logger.fatal(err.message);
- sendSlackMessage(pkg.deployment.fail_message, notifyParams);
- }
- } else {
- logger.debug('Attempting to add and commit new revgen files.');
- gulp.src(`${pkg.deployment.deployPath}/**/*`)
- .pipe(tap((file) => {
- logger.debug(`Adding file: ${file.path}`);
- }))
- .pipe(git.add(gitOpts))
- .pipe(git.commit(`Automated deployment of build #${notifyParams.buildNumber} of branch ${notifyParams.branchName} of ${pkg.name} to static final.`, gitOpts))
- .on('error', onCommitError)
- .on('end', (stop) => {
- if (!stop) gulp.start('push-changes'); // no end event is emitted when error is present
- });
- }
- });
- });
- gulp.task('deploy-docs', 'Gathers up the files from the docs folder and uploads them to S3', (cb) => {
- const params = {
- Bucket: 'revgen-docs',
- Key: pkg.name,
- ACL: 'public-read',
- };
- return gulp.src('./docs/gen/**/*')
- .pipe(tap((file, t) => {
- params.Key = `${pkg.name}${file.path.replace(process.cwd(), '')}`;
- params.Body = file.contents;
- params.ContentType = mime.lookup(file.path);
- s3.putObject(params, (err, response) => {
- if (err) {
- logger.fatal(err);
- cb(err);
- } else {
- logger.info(`Successfully deployed ${file.path.replace(process.cwd(), '')} to S3. Etag = ${JSON.stringify(response)}`);
- }
- });
- }));
- });
- gulp.task('deploy', 'Runs a sequence of tasks that will build and deploy.', (cb) => {
- runSequence('clean', 'browserify', 'uglify-dist', 'checkout', 'copy-dist', 'deploy-final', cb);
- });
- gulp.task('build', 'Runs a sequence of tasks that will build but WONT deploy.', (cb) => {
- runSequence('clean', 'browserify', 'uglify-dist', cb);
- });
- /**
- * Builds the test file that requires revgen instead of having a script tag
- */
- gulp.task('require', () => {
- const bundler = browserify('./.vscode/require_test.js');
- bundler.transform('rollupify');
- bundler.transform('envify', {
- NODE_ENV: process.env.NODE_ENV,
- });
- return bundler.transform('babelify', {
- presets: ['es2015'],
- }).bundle()
- .on('error', (err) => {
- logger.fatal(err);
- })
- .pipe(source('revgen.min.js'))
- .pipe(gulp.dest('./dist'));
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement