<commit_before>'use strict';

const argv = require('yargs').argv
const gulp = require('gulp-help')(require('gulp'));
const async = require('async');
const del = require('del');
const merge = require('merge2');
const path = require('path');

// load gulp plugins
const jeditor = require('gulp-json-editor');
const G$ = require('gulp-load-plugins')({ lazy: true });
const chalk = G$.util.colors;

// constants
const PROJECT_VAR = '{project}';

// load settings
const settings = require('./gulp.json');
const tsconfig = require('./tsconfig.master.json');
const projects = require('./projects.json');
const projectNames = Object.keys(projects);

function expandPaths(globArray) {
    const expandedGlob = [];
    globArray.forEach(item => {
        if (item.indexOf(PROJECT_VAR) > 0) {
            projectNames.forEach(project => {
                expandedGlob.push(item.replace(PROJECT_VAR, project));
            });
        } else {
            expandedGlob.push(item);
        }
    });
    return expandedGlob;
}

function wildcharPaths(globArray) {
    const expandedGlob = [];
    globArray.forEach(item => {
        if (item.indexOf(PROJECT_VAR) > 0) {
            expandedGlob.push(item.replace(PROJECT_VAR, '*'));
        } else {
            expandedGlob.push(item);
        }
    });
    return expandedGlob;
}

function mapPaths(globArray, project) {
    return globArray.map(path =>
        mapPath(path, project));
}

function mapPath(path, project) {
    return path.replace(PROJECT_VAR, project);
}

function plumberErrorHandler(err) {
    console.log(err.stack);
    this.emit('end'); // For gulp watch
}

const exec = require('child_process').exec;

function runCommand(command, options, callback) {
    try {
        exec(command, options, (error, stdout, stderr) => {
            console.log(`${path.resolve(options.cwd || '.')} ${chalk.cyan(command)}`);
            console.log(stdout);
            console.log(stderr);
            if (error !== null) {
                console.log('exec error: ', error);
            }
            callback();
        });
    } catch (ex) {
        console.log('rc ex', ex);
    }
}

/*
 * {cmd: "", cwd: ""}
 */
function runCommands(commands, parallel, callback) {
    if (parallel === true) {
        async.each(commands, (command, done) => {
            runCommand(command.cmd, { cwd: command.cwd }, done);
        }, () => {
            callback();
        });
    } else {
        async.eachSeries(commands, (command, done) => {
            runCommand(command.cmd, { cwd: command.cwd }, done);
        }, () => {
            callback();
        });
    }
}

// Setup

gulp.task('setup', 'Install all modules and link projects', callback => {
    G$.sequence('install', 'link', callback);
});

gulp.task('teardown', 'Clean all and unlink projects', callback => {
    G$.sequence('unlink', 'deepclean', callback);
});

// npm install

gulp.task('install', 'Install all npm modules', callback => {
    const commands = [];
    let packageNpmInstall = 'npm install'
    if (argv.optional == false) packageNpmInstall += ' --no-optional';
    if (argv.buildFromSource) packageNpmInstall += ' --build-from-source'
    if (argv.target_arch) packageNpmInstall += ` --target_arch=${argv.target_arch}`;
    projectNames.forEach(name => {
        commands.push({ cmd: packageNpmInstall, cwd: `projects/${name}` });
    });
    runCommands(commands, true, callback);
});

// npm link

gulp.task('link', 'Link dependencies on local disk', callback => {
    linker(true, callback);
});

gulp.task('unlink', 'Unlink dependencies on local disk', callback => {
    linker(false, callback);
});

function linker(mode, callback) {
    const linkCommands = [];
    const packageLinkCommands = [];
    projectNames.forEach(project => {
        linkCommands.push({ cmd: `npm ${mode ? 'link' : 'unlink'} --no-bin-links`, cwd: `projects/${project}` });
    });
    if (mode) {
        projectNames.forEach(project => {
            if (projects[project].dependencies) {
                projects[project].dependencies.forEach(dep => {
                    const packageName = require(`./projects/${dep}/package.json`).name;
                    packageLinkCommands.push({ cmd: `npm ${mode ? 'link' : 'unlink'} ${packageName} --no-bin-links`, cwd: `projects/${project}` });
                });
            }
        });
    }
    runCommands(linkCommands, true, () => {
        runCommands(packageLinkCommands, true, callback)
    });
    // info about "--no-bin-links" : see http://stackoverflow.com/questions/17990647/npm-install-errors-with-error-enoent-chmod
}

// Building

gulp.task('build', 'Compiles all TypeScript source files and updates module references', callback => {
    G$.sequence(['tslint', 'clean'], 'ts-all', callback);
});

gulp.task('watch', 'Contiuous build', ['build'], () => {
    projectNames.forEach(project => {
        gulp.watch(mapPaths(Array.prototype.concat(settings.tsfiles, settings.jsFiles), project), [`ts-${project}`]);
    });
});

// see https://www.npmjs.com/package/tslint
gulp.task('tslint', 'Lints all TypeScript source files', () => {
    return gulp.src(wildcharPaths(settings.tsfiles))
        .pipe(G$.tslint({ formatter: 'verbose' }))
        .pipe(G$.tslint.report({ emitError: false }));
});

// Cleaning

gulp.task('clean', 'Cleans the generated files from lib directory', () => {
    return del(expandPaths(settings.clean));
});

gulp.task('deepclean', 'Cleans the generated files from lib directory and all node_modules', () => {
    return del(expandPaths(settings.deepClean));
});

// Transpiling
projectNames.forEach(project => {
    gulp.task(`ts-${project}`, `Transpile ${chalk.green(project)}`, () => {
        const tsResult = gulp.src(mapPaths(settings.tsfiles, project))
            .pipe(G$.sourcemaps.init())
            .pipe(G$.typescript.createProject(tsconfig.compilerOptions)());
        const dest = mapPath(settings.dest, project);
        return merge([
            tsResult.dts.pipe(gulp.dest(dest)),
            tsResult.js
                .pipe(G$.sourcemaps.write('.')) // separate .js.map files
                .pipe(gulp.dest(dest)),
            // JS files
            gulp.src(mapPaths(settings.jsFiles, project)).pipe(G$.babel({
                presets: ['es2015']
            })).pipe(gulp.dest(dest)),
            // all other files
            gulp.src(mapPaths(settings.resources, project)).pipe(gulp.dest(dest))
        ]);
    });
});

gulp.task('ts-all', 'Transpile all projects', callback => {
    G$.sequence(projectNames.map(name => `ts-${name}`), callback);
});

// Extras

gulp.task('npm-i', `Install and save a ${chalk.cyan('pack')}age to a ${chalk.cyan('project')}`, callback => {
    const pack = argv.pack;
    const project = argv.project;
    runCommand(`npm install --save ${pack}`, { cwd: mapPath(settings.projectPath, project) }, () => {
        callback();
    });
}, {
        options: {
            pack: 'Package name',
            project: `Project name: ${chalk.green(projectNames.join(chalk.white(', ')))}`
        }
    });

gulp.task('npm-u', `Uninstall and save a ${chalk.cyan('pack')}age to a ${chalk.cyan('project')}`, callback => {
    const pack = argv.pack;
    const project = argv.project;
    runCommand(`npm uninstall --save ${pack}`, { cwd: mapPath(settings.projectPath, project) }, () => {
        callback();
    });
}, {
        options: {
            pack: 'Package name',
            project: `Project name: ${chalk.green(projectNames.join(chalk.white(', ')))}`
        }
    });

gulp.task('stats', 'Get lines of code', () => {
    const project = argv.project;
    console.log(project);
    if (project) {
        console.log(`Source Lines of Code: ${chalk.green(project)}`);
        gulp.src(mapPaths(settings.sloc_project, project)).pipe(G$.sloc({ tolerant: true }));
    } else {
        console.log(`Source Lines of Code: ${chalk.white('ALL')}`);
        gulp.src(settings.sloc_all).pipe(G$.sloc({ tolerant: true }));
    }
}, {
        options: {
            project: `Project name: ${chalk.green(projectNames.join(chalk.white(', ')))}`
        }
    });

gulp.task('size', 'Get size of code', () => {
    const project = argv.project;
    console.log(project);
    if (project) {
        console.log(`Source Lines of Code: ${chalk.green(project)}`);
        gulp.src(mapPaths(settings.runtimeFiles, project)).pipe(G$.size({ showFiles: true }));
    } else {
        console.log(`Source Lines of Code: ${chalk.white('ALL')}`);
        gulp.src(expandPaths(settings.runtimeFiles)).pipe(G$.size({ showFiles: true }));
    }
}, {
        options: {
            project: `Project name: ${chalk.green(projectNames.join(chalk.white(', ')))}`
        }
    });

// Deploying

function getPackageName(packagePath) {
    const packageFile = require(path.join(path.resolve(packagePath), 'package.json'));
    return `${packageFile.name}_${packageFile.version}`;
}

gulp.task('package', false, () => {
    const packageFileName = `${getPackageName(settings.edgeDir)}.tar`;
    return gulp.src(settings.packageFiles, { follow: true })
        .pipe(gulp.dest('dist/droplit-edge'))
        .pipe(G$.debug({ title: 'package:' }))
        .pipe(G$.tar(packageFileName))
        .pipe(G$.gzip())
        .pipe(gulp.dest('dist'));
});

gulp.task('clean-dist', false, () => {
    return del('dist');
});

gulp.task('move-temp', false, () => {
    return gulp.src(settings.edgeFiles, { follow: true })
        .pipe(gulp.dest('temp/droplit-edge'));
});

gulp.task('clean-temp', false, () => {
    return del('temp');
});

gulp.task('setup-package', false, () => {
    return gulp.src('./temp/droplit-edge/package.json')
        .pipe(jeditor((json) => {
            const localConfig = require('./temp/droplit-edge/localsettings.json');
            if (Array.isArray(localConfig.plugins))
                localConfig.plugins.forEach(plugin => {
                    if (typeof plugin === 'string') {
                        json.dependencies[plugin] = `../../projects/${plugin}`;
                        return;
                    }

                    if (typeof plugin === 'object' && plugin.hasOwnProperty('name') && plugin.enabled !== false)
                        json.dependencies[plugin.name] = `../../projects/${plugin.name}`;
                });
            else
                Object.keys(localConfig.plugins).forEach(plugin => {
                    if (localConfig.plugins[plugin] && localConfig.plugins[plugin].enabled !== false) {
                        json.dependencies[plugin] = `../../projects/${plugin}`;
                    }
                });
            return json;
        }))
        .pipe(gulp.dest('temp/droplit-edge/'));
});

gulp.task('pre-install-dist', false, () => {
    return del('temp/droplit-edge/node_modules');
});

gulp.task('install-dist', false, callback => {
    let npmInstall = 'npm install'
    if (argv.optional == false) npmInstall += ' --no-optional';
    if (argv.buildFromSource) npmInstall += ' --build-from-source'
    if (argv.target_arch) npmInstall += ` --target_arch=${argv.target_arch}`;
    runCommand(npmInstall, { cwd: 'temp/droplit-edge' }, () => {
        console.log('done');
        callback();
    });
});

gulp.task('build-dist', false, callback => {
    G$.sequence('clean-dist', 'build', 'unlink', 'move-temp', 'setup-package', 'pre-install-dist', 'install-dist', 'package', 'clean-temp', callback);
});

gulp.task('deploy', 'Glob the Droplit Edge for embedding', callback => {
    G$.sequence('setup', 'build-dist', callback);
});

// Testing for improving package
gulp.task('prep', false, () => {
    return del(expandPaths(settings.prep));
});

// Version bump

const bumpOpts = {
    options: {
        major: 'when you make incompatible API changes',
        minor: 'when you add functionality in a backwards-compatible manner',
        patch: 'when you make backwards-compatible bug fixes',
        project: `Project name: ${chalk.green(projectNames.join(chalk.white(', ')))}`
    }
};

gulp.task('bump', 'Version bump a project.', () => {
    const major = argv.major;
    const minor = argv.minor;
    const patch = argv.patch;
    const project = argv.project;
    if (!project)
        return console.log(`${chalk.red('No project specified!')}`);

    const typeFlags = { 1: 'major', 2: 'minor', 4: 'patch' };
    const typeValue = (major << 0) + (minor << 1) + (patch << 2);
    const type = typeFlags[typeValue];
    if (!type)
        return console.log(`${chalk.red('Specify one version type to bump!')}`);

    const cwd = `projects/${project}/`;
    return gulp.src('./package.json', { cwd })
        .pipe(G$.bump({ type }))
        .pipe(gulp.dest('./', { cwd }));
}, bumpOpts);

gulp.task('debug', 'Debug droplit-edge', () => {
    const project = 'droplit-edge';
    G$.nodemon({
        script: `${project}.js`,
        ext: 'js',
        env: {
            DEBUG: 'droplit:*'
        },
        delay: 1, // Sec
        watch: `projects/${project}`,
        ignore: `projects/${project}/src`
    });
});

// .pipe(G$.plumber()) // exit gracefully if something fails after this

// gulp.task('test', 'Runs all tests', [], () => {
//     $.util.log(colors.cyan(`Testing ${settings.testGlob}`));

//     return gulp
//         .src(settings.testGlob, { read: true })
//         .pipe($.plumber()) // exit gracefully if something fails after this
//         .pipe($.mocha({ reporter: 'spec' }));
// });

// Attitional reference: https://github.com/johnpapa/gulp-patterns
// http://www.bennadel.com/blog/2169-where-does-node-js-and-require-look-for-modules.htm<commit_msg>Fix linting<commit_after>'use strict';

const argv = require('yargs').argv;
const gulp = require('gulp-help')(require('gulp'));
const async = require('async');
const del = require('del');
const merge = require('merge2');
const path = require('path');

// load gulp plugins
const jeditor = require('gulp-json-editor');
const G$ = require('gulp-load-plugins')({ lazy: true });
const chalk = G$.util.colors;

// constants
const PROJECT_VAR = '{project}';

// load settings
const settings = require('./gulp.json');
const tsconfig = require('./tsconfig.master.json');
const projects = require('./projects.json');
const projectNames = Object.keys(projects);

function expandPaths(globArray) {
    const expandedGlob = [];
    globArray.forEach(item => {
        if (item.indexOf(PROJECT_VAR) > 0) {
            projectNames.forEach(project => {
                expandedGlob.push(item.replace(PROJECT_VAR, project));
            });
        } else {
            expandedGlob.push(item);
        }
    });
    return expandedGlob;
}

function wildcharPaths(globArray) {
    const expandedGlob = [];
    globArray.forEach(item => {
        if (item.indexOf(PROJECT_VAR) > 0) {
            expandedGlob.push(item.replace(PROJECT_VAR, '*'));
        } else {
            expandedGlob.push(item);
        }
    });
    return expandedGlob;
}

function mapPaths(globArray, project) {
    return globArray.map(path =>
        mapPath(path, project));
}

function mapPath(path, project) {
    return path.replace(PROJECT_VAR, project);
}

function plumberErrorHandler(err) {
    console.log(err.stack);
    this.emit('end'); // For gulp watch
}

const exec = require('child_process').exec;

function runCommand(command, options, callback) {
    try {
        exec(command, options, (error, stdout, stderr) => {
            console.log(`${path.resolve(options.cwd || '.')} ${chalk.cyan(command)}`);
            console.log(stdout);
            console.log(stderr);
            if (error !== null) {
                console.log('exec error: ', error);
            }
            callback();
        });
    } catch (ex) {
        console.log('rc ex', ex);
    }
}

/*
 * {cmd: "", cwd: ""}
 */
function runCommands(commands, parallel, callback) {
    if (parallel === true) {
        async.each(commands, (command, done) => {
            runCommand(command.cmd, { cwd: command.cwd }, done);
        }, () => {
            callback();
        });
    } else {
        async.eachSeries(commands, (command, done) => {
            runCommand(command.cmd, { cwd: command.cwd }, done);
        }, () => {
            callback();
        });
    }
}

// Setup

gulp.task('setup', 'Install all modules and link projects', callback => {
    G$.sequence('install', 'link', callback);
});

gulp.task('teardown', 'Clean all and unlink projects', callback => {
    G$.sequence('unlink', 'deepclean', callback);
});

// npm install

gulp.task('install', 'Install all npm modules', callback => {
    const commands = [];
    let packageNpmInstall = 'npm install';
    if (argv.optional === false) packageNpmInstall += ' --no-optional';
    if (argv.buildFromSource) packageNpmInstall += ' --build-from-source';
    if (argv.target_arch) packageNpmInstall += ` --target_arch=${argv.target_arch}`;
    projectNames.forEach(name => {
        commands.push({ cmd: packageNpmInstall, cwd: `projects/${name}` });
    });
    runCommands(commands, true, callback);
});

// npm link

gulp.task('link', 'Link dependencies on local disk', callback => {
    linker(true, callback);
});

gulp.task('unlink', 'Unlink dependencies on local disk', callback => {
    linker(false, callback);
});

function linker(mode, callback) {
    const linkCommands = [];
    const packageLinkCommands = [];
    projectNames.forEach(project => {
        linkCommands.push({ cmd: `npm ${mode ? 'link' : 'unlink'} --no-bin-links`, cwd: `projects/${project}` });
    });
    if (mode) {
        projectNames.forEach(project => {
            if (projects[project].dependencies) {
                projects[project].dependencies.forEach(dep => {
                    const packageName = require(`./projects/${dep}/package.json`).name;
                    packageLinkCommands.push({ cmd: `npm ${mode ? 'link' : 'unlink'} ${packageName} --no-bin-links`, cwd: `projects/${project}` });
                });
            }
        });
    }
    runCommands(linkCommands, true, () => {
        runCommands(packageLinkCommands, true, callback);
    });
    // info about "--no-bin-links" : see http://stackoverflow.com/questions/17990647/npm-install-errors-with-error-enoent-chmod
}

// Building

gulp.task('build', 'Compiles all TypeScript source files and updates module references', callback => {
    G$.sequence(['tslint', 'clean'], 'ts-all', callback);
});

gulp.task('watch', 'Contiuous build', ['build'], () => {
    projectNames.forEach(project => {
        gulp.watch(mapPaths(Array.prototype.concat(settings.tsfiles, settings.jsFiles), project), [`ts-${project}`]);
    });
});

// see https://www.npmjs.com/package/tslint
gulp.task('tslint', 'Lints all TypeScript source files', () =>
    gulp.src(wildcharPaths(settings.tsfiles))
        .pipe(G$.tslint({ formatter: 'verbose' }))
        .pipe(G$.tslint.report({ emitError: false }))
);

// Cleaning

gulp.task('clean', 'Cleans the generated files from lib directory', () =>
    del(expandPaths(settings.clean))
);

gulp.task('deepclean', 'Cleans the generated files from lib directory and all node_modules', () =>
    del(expandPaths(settings.deepClean))
);

// Transpiling
projectNames.forEach(project => {
    gulp.task(`ts-${project}`, `Transpile ${chalk.green(project)}`, () => {
        const tsResult = gulp.src(mapPaths(settings.tsfiles, project))
            .pipe(G$.sourcemaps.init())
            .pipe(G$.typescript.createProject(tsconfig.compilerOptions)());
        const dest = mapPath(settings.dest, project);
        return merge([
            tsResult.dts.pipe(gulp.dest(dest)),
            tsResult.js
                .pipe(G$.sourcemaps.write('.')) // separate .js.map files
                .pipe(gulp.dest(dest)),
            // JS files
            gulp.src(mapPaths(settings.jsFiles, project)).pipe(G$.babel({
                presets: ['es2015']
            })).pipe(gulp.dest(dest)),
            // all other files
            gulp.src(mapPaths(settings.resources, project)).pipe(gulp.dest(dest))
        ]);
    });
});

gulp.task('ts-all', 'Transpile all projects', callback => {
    G$.sequence(projectNames.map(name => `ts-${name}`), callback);
});

// Extras

gulp.task('npm-i', `Install and save a ${chalk.cyan('pack')}age to a ${chalk.cyan('project')}`, callback => {
    const pack = argv.pack;
    const project = argv.project;
    runCommand(`npm install --save ${pack}`, { cwd: mapPath(settings.projectPath, project) }, () => {
        callback();
    });
}, {
    options: {
        pack: 'Package name',
        project: `Project name: ${chalk.green(projectNames.join(chalk.white(', ')))}`
    }
});

gulp.task('npm-u', `Uninstall and save a ${chalk.cyan('pack')}age to a ${chalk.cyan('project')}`, callback => {
    const pack = argv.pack;
    const project = argv.project;
    runCommand(`npm uninstall --save ${pack}`, { cwd: mapPath(settings.projectPath, project) }, () => {
        callback();
    });
}, {
    options: {
        pack: 'Package name',
        project: `Project name: ${chalk.green(projectNames.join(chalk.white(', ')))}`
    }
});

gulp.task('stats', 'Get lines of code', () => {
    const project = argv.project;
    console.log(project);
    if (project) {
        console.log(`Source Lines of Code: ${chalk.green(project)}`);
        gulp.src(mapPaths(settings.sloc_project, project)).pipe(G$.sloc({ tolerant: true }));
    } else {
        console.log(`Source Lines of Code: ${chalk.white('ALL')}`);
        gulp.src(settings.sloc_all).pipe(G$.sloc({ tolerant: true }));
    }
}, {
    options: {
        project: `Project name: ${chalk.green(projectNames.join(chalk.white(', ')))}`
    }
});

gulp.task('size', 'Get size of code', () => {
    const project = argv.project;
    console.log(project);
    if (project) {
        console.log(`Source Lines of Code: ${chalk.green(project)}`);
        gulp.src(mapPaths(settings.runtimeFiles, project)).pipe(G$.size({ showFiles: true }));
    } else {
        console.log(`Source Lines of Code: ${chalk.white('ALL')}`);
        gulp.src(expandPaths(settings.runtimeFiles)).pipe(G$.size({ showFiles: true }));
    }
}, {
    options: {
        project: `Project name: ${chalk.green(projectNames.join(chalk.white(', ')))}`
    }
});

// Deploying

function getPackageName(packagePath) {
    const packageFile = require(path.join(path.resolve(packagePath), 'package.json'));
    return `${packageFile.name}_${packageFile.version}`;
}

gulp.task('package', false, () => {
    const packageFileName = `${getPackageName(settings.edgeDir)}.tar`;
    return gulp.src(settings.packageFiles, { follow: true })
        .pipe(gulp.dest('dist/droplit-edge'))
        .pipe(G$.debug({ title: 'package:' }))
        .pipe(G$.tar(packageFileName))
        .pipe(G$.gzip())
        .pipe(gulp.dest('dist'));
});

gulp.task('clean-dist', false, () => del('dist'));

gulp.task('move-temp', false, () =>
    gulp.src(settings.edgeFiles, { follow: true })
        .pipe(gulp.dest('temp/droplit-edge'))
);

gulp.task('clean-temp', false, () => del('temp'));

gulp.task('setup-package', false, () =>
    gulp.src('./temp/droplit-edge/package.json')
        .pipe(jeditor(json => {
            const localConfig = require('./temp/droplit-edge/localsettings.json');
            if (Array.isArray(localConfig.plugins))
                localConfig.plugins.forEach(plugin => {
                    if (typeof plugin === 'string') {
                        json.dependencies[plugin] = `../../projects/${plugin}`;
                        return;
                    }

                    if (typeof plugin === 'object' && plugin.hasOwnProperty('name') && plugin.enabled !== false)
                        json.dependencies[plugin.name] = `../../projects/${plugin.name}`;
                });
            else
                Object.keys(localConfig.plugins).forEach(plugin => {
                    if (localConfig.plugins[plugin] && localConfig.plugins[plugin].enabled !== false) {
                        json.dependencies[plugin] = `../../projects/${plugin}`;
                    }
                });
            return json;
        }))
        .pipe(gulp.dest('temp/droplit-edge/'))
);

gulp.task('pre-install-dist', false, () => del('temp/droplit-edge/node_modules'));

gulp.task('install-dist', false, callback => {
    let npmInstall = 'npm install';
    if (argv.optional === false) npmInstall += ' --no-optional';
    if (argv.buildFromSource) npmInstall += ' --build-from-source';
    if (argv.target_arch) npmInstall += ` --target_arch=${argv.target_arch}`;
    runCommand(npmInstall, { cwd: 'temp/droplit-edge' }, () => {
        console.log('done');
        callback();
    });
});

gulp.task('build-dist', false, callback => {
    G$.sequence('clean-dist', 'build', 'unlink', 'move-temp', 'setup-package', 'pre-install-dist', 'install-dist', 'package', 'clean-temp', callback);
});

gulp.task('deploy', 'Glob the Droplit Edge for embedding', callback => {
    G$.sequence('setup', 'build-dist', callback);
});

// Testing for improving package
gulp.task('prep', false, () => del(expandPaths(settings.prep)));

// Version bump

const bumpOpts = {
    options: {
        major: 'when you make incompatible API changes',
        minor: 'when you add functionality in a backwards-compatible manner',
        patch: 'when you make backwards-compatible bug fixes',
        project: `Project name: ${chalk.green(projectNames.join(chalk.white(', ')))}`
    }
};

gulp.task('bump', 'Version bump a project.', () => {
    const major = argv.major;
    const minor = argv.minor;
    const patch = argv.patch;
    const project = argv.project;
    if (!project)
        return console.log(`${chalk.red('No project specified!')}`);

    const typeFlags = { 1: 'major', 2: 'minor', 4: 'patch' };
    const typeValue = (major << 0) + (minor << 1) + (patch << 2);
    const type = typeFlags[typeValue];
    if (!type)
        return console.log(`${chalk.red('Specify one version type to bump!')}`);

    const cwd = `projects/${project}/`;
    return gulp.src('./package.json', { cwd })
        .pipe(G$.bump({ type }))
        .pipe(gulp.dest('./', { cwd }));
}, bumpOpts);

gulp.task('debug', 'Debug droplit-edge', () => {
    const project = 'droplit-edge';
    G$.nodemon({
        script: `${project}.js`,
        ext: 'js',
        env: {
            DEBUG: 'droplit:*'
        },
        delay: 1, // Sec
        watch: `projects/${project}`,
        ignore: `projects/${project}/src`
    });
});

// .pipe(G$.plumber()) // exit gracefully if something fails after this

// gulp.task('test', 'Runs all tests', [], () => {
//     $.util.log(colors.cyan(`Testing ${settings.testGlob}`));

//     return gulp
//         .src(settings.testGlob, { read: true })
//         .pipe($.plumber()) // exit gracefully if something fails after this
//         .pipe($.mocha({ reporter: 'spec' }));
// });

// Attitional reference: https://github.com/johnpapa/gulp-patterns
// http://www.bennadel.com/blog/2169-where-does-node-js-and-require-look-for-modules.htm<|endoftext|>


<commit_before>var gulp = require('gulp'),
    gutil = require('gulp-util'),
    bower = require('gulp-bower'),
    rename = require('gulp-rename'),
    less = require('gulp-less'),
    minifyCss = require('gulp-minify-css'),
    uglifyJs = require('gulp-uglifyjs'),
    rimraf = require('gulp-rimraf'),
    buildTypeEnum = {dev: 'dev', prod: 'prod'};

function buildTypeToDistDir(buildType) {
    "use strict";

    if (buildType === buildTypeEnum.dev) {
        return 'dist/dev';
    } else if (buildType === buildTypeEnum.prod) {
        return 'dist/prod';
    } else {
        gutil.log(gutil.colors.red('Invalid build type!'));
    }
}

// todo: add running jshint (with coverage)

// todo: add running unit tests

gulp.task('default', function () {
    // todo: Figure out which task should be the default.
});

////////////////////////////////////////////////////////////////////////////////
// Build
////////////////////////////////////////////////////////////////////////////////

//
// Stage server
//
(function () {
    "use strict";

    function stageServer(buildType) {
        return gulp.src('server/**/*', {cwdbase: true})
            .pipe(gulp.dest(buildTypeToDistDir(buildType)));
    }

    gulp.task('stageServer:dev', function () {
        return stageServer(buildTypeEnum.dev);
    });

    gulp.task('stageServer:prod', function () {
        return stageServer(buildTypeEnum.prod);
    });
})();

//
// Stage Bower components
//
(function () {
    "use strict";

    function stageBowerFiles(buildType) {
        var bowerDir = buildTypeToDistDir(buildType) + '/www/bower_components'
        bower(bowerDir);
    }

    gulp.task('stageBowerFiles:dev', function () {
        return stageBowerFiles(buildTypeEnum.dev);
    });

    gulp.task('stageBowerFiles:prod', function () {
        return stageBowerFiles(buildTypeEnum.prod);
    });

})();

//
// Stage index.html
//
(function () {
    "use strict";

    function stageIndex(buildType) {
        var indexFileName = 'www/index-' + buildType + '.html';

        return gulp.src(indexFileName, {cwdbase: true})
            .pipe(rename({basename: 'index'}))
            .pipe(gulp.dest(buildTypeToDistDir(buildType)));

    }

    gulp.task('stageIndex:dev', function () {
        return stageIndex(buildTypeEnum.dev);
    });

    gulp.task('stageIndex:prod', function () {
        return stageIndex(buildTypeEnum.prod);
    });

})();

//
// Stage app Less
//
(function () {
    "use strict";

    function stageAppLess(buildType) {
        return gulp.src('www/styles/*.less', {cwdbase: true})
            .pipe(less({paths: [], relativeUrls: true}))
            .pipe(buildType === buildTypeEnum.prod ? minifyCss() : gutil.noop())
            .pipe(buildType === buildTypeEnum.prod ? rename({suffix: '.min'}) : gutil.noop())
            .pipe(gulp.dest(buildTypeToDistDir(buildType)));
    }

    gulp.task('stageAppLess:dev', function () {
        return stageAppLess(buildTypeEnum.dev);
    });

    gulp.task('stageAppLess:prod', function () {
        return stageAppLess(buildTypeEnum.prod);
    });

})();

//
// Stage app resources
//
(function () {
    "use strict";

    function stageAppResources(buildType) {
        var globs = [
            'www/fonts/**/*',
            'www/images/**/*',
            'www/js/**/*.html',
            '!www/js/**/*.tc.html' // Don't include templates that are placed in the template cache
        ];

        return gulp.src(globs, {cwdbase: true})
            .pipe(gulp.dest(buildTypeToDistDir(buildType)));
    }

    gulp.task('stageAppResources:dev', function () {
        return stageAppResources(buildTypeEnum.dev);
    });

    gulp.task('stageAppResources:prod', function () {
        return stageAppResources(buildTypeEnum.prod);
    });

})();

//
// Stage app JavaScript
//
(function () {
    "use strict";

    function stageAppJs(buildType) {
        var globs = [
            'www/js/**/*.js'
        ];

        return gulp.src(globs, {cwdbase: true})
            .pipe(buildType === buildTypeEnum.prod ? uglifyJs('www/js/app.min.js') : gutil.noop())
            .pipe(gulp.dest(buildTypeToDistDir(buildType)));
    }

    gulp.task('stageAppJs:dev', function () {
        return stageAppJs(buildTypeEnum.dev);
    });

    gulp.task('stageAppJs:prod', function () {
        return stageAppJs(buildTypeEnum.prod);
    });
})();

gulp.task(
    'build:dev',
    [
        'stageServer:dev', 'stageBowerFiles:dev', 'stageIndex:dev',
        'stageAppLess:dev', 'stageAppResources:dev', 'stageAppJs:dev'
    ]
);
gulp.task(
    'build:prod',
    [
        'stageServer:prod', 'stageBowerFiles:prod', 'stageIndex:prod',
        'stageAppLess:prod', 'stageAppResources:prod', 'stageAppJs:prod'
    ]
);
gulp.task('build', ['build:dev', 'build:prod']);

////////////////////////////////////////////////////////////////////////////////
// Clean
////////////////////////////////////////////////////////////////////////////////

(function () {
    "use strict";

    gulp.task('clean', function () {
        var globs = [
            'www/**/*.css',
            'dist/dev',
            'dist/prod',
            'artifacts/*'
        ];

        return gulp.src(globs, {read: false})
            .pipe(rimraf());
    });
})();<commit_msg>Minor fixes for gulpfile.js.<commit_after>var gulp = require('gulp'),
    gutil = require('gulp-util'),
    bower = require('gulp-bower'),
    rename = require('gulp-rename'),
    less = require('gulp-less'),
    minifyCss = require('gulp-minify-css'),
    uglifyJs = require('gulp-uglifyjs'),
    rimraf = require('gulp-rimraf'),
    buildTypeEnum = {dev: 'dev', prod: 'prod'};

function buildTypeToDistDir(buildType) {
    "use strict";

    if (buildType === buildTypeEnum.dev) {
        return 'dist/dev';
    } else if (buildType === buildTypeEnum.prod) {
        return 'dist/prod';
    } else {
        gutil.log(gutil.colors.red('Invalid build type!'));
    }
}

// todo: add running jshint (with coverage)

// todo: add running unit tests

gulp.task('default', function () {
    // todo: Figure out which task should be the default.
});

////////////////////////////////////////////////////////////////////////////////
// Build
////////////////////////////////////////////////////////////////////////////////

//
// Stage server
//
(function () {
    "use strict";

    function stageServer(buildType) {
        return gulp.src('server/**/*', {cwdbase: true})
            .pipe(gulp.dest(buildTypeToDistDir(buildType)));
    }

    gulp.task('stageServer:dev', function () {
        return stageServer(buildTypeEnum.dev);
    });

    gulp.task('stageServer:prod', function () {
        return stageServer(buildTypeEnum.prod);
    });
})();

//
// Stage Bower components
//
(function () {
    "use strict";

    function stageBowerFiles(buildType) {
        var bowerDir = buildTypeToDistDir(buildType) + '/www/bower_components';
        bower(bowerDir);
    }

    gulp.task('stageBowerFiles:dev', function () {
        return stageBowerFiles(buildTypeEnum.dev);
    });

    gulp.task('stageBowerFiles:prod', function () {
        return stageBowerFiles(buildTypeEnum.prod);
    });

})();

//
// Stage index.html
//
(function () {
    "use strict";

    function stageIndex(buildType) {
        var indexFileName = 'www/index-' + buildType + '.html';

        return gulp.src(indexFileName, {cwdbase: true})
            .pipe(rename({basename: 'index'}))
            .pipe(gulp.dest(buildTypeToDistDir(buildType)));

    }

    gulp.task('stageIndex:dev', function () {
        return stageIndex(buildTypeEnum.dev);
    });

    gulp.task('stageIndex:prod', function () {
        return stageIndex(buildTypeEnum.prod);
    });

})();

//
// Stage app Less
//
(function () {
    "use strict";

    function stageAppLess(buildType) {
        return gulp.src('www/styles/*.less', {cwdbase: true})
            .pipe(less({paths: [], relativeUrls: true}))
            .pipe(buildType === buildTypeEnum.prod ? minifyCss() : gutil.noop())
            .pipe(buildType === buildTypeEnum.prod ? rename({suffix: '.min'}) : gutil.noop())
            .pipe(gulp.dest(buildTypeToDistDir(buildType)));
    }

    gulp.task('stageAppLess:dev', function () {
        return stageAppLess(buildTypeEnum.dev);
    });

    gulp.task('stageAppLess:prod', function () {
        return stageAppLess(buildTypeEnum.prod);
    });

})();

//
// Stage app resources
//
(function () {
    "use strict";

    function stageAppResources(buildType) {
        var globs = [
            'www/fonts/**/*',
            'www/images/**/*',
            'www/js/**/*.html',
            '!www/js/**/*.tc.html' // Don't include templates that are placed in the template cache
        ];

        return gulp.src(globs, {cwdbase: true})
            .pipe(gulp.dest(buildTypeToDistDir(buildType)));
    }

    gulp.task('stageAppResources:dev', function () {
        return stageAppResources(buildTypeEnum.dev);
    });

    gulp.task('stageAppResources:prod', function () {
        return stageAppResources(buildTypeEnum.prod);
    });

})();

//
// Stage app JavaScript
//
(function () {
    "use strict";

    function stageAppJs(buildType) {
        var globs = [
            'www/js/**/*.js'
        ];

        // todo: Create sourcemaps for prod builds

        return gulp.src(globs, {cwdbase: true})
            .pipe(buildType === buildTypeEnum.prod ? uglifyJs('www/js/app.min.js') : gutil.noop())
            .pipe(gulp.dest(buildTypeToDistDir(buildType)));
    }

    gulp.task('stageAppJs:dev', function () {
        return stageAppJs(buildTypeEnum.dev);
    });

    gulp.task('stageAppJs:prod', function () {
        return stageAppJs(buildTypeEnum.prod);
    });
})();

gulp.task(
    'build:dev',
    [
        'stageServer:dev', 'stageBowerFiles:dev', 'stageIndex:dev',
        'stageAppLess:dev', 'stageAppResources:dev', 'stageAppJs:dev'
    ]
);
gulp.task(
    'build:prod',
    [
        'stageServer:prod', 'stageBowerFiles:prod', 'stageIndex:prod',
        'stageAppLess:prod', 'stageAppResources:prod', 'stageAppJs:prod'
    ]
);
gulp.task('build', ['build:dev', 'build:prod']);

////////////////////////////////////////////////////////////////////////////////
// Clean
////////////////////////////////////////////////////////////////////////////////

(function () {
    "use strict";

    gulp.task('clean', function () {
        var globs = [
            'www/**/*.css',
            'dist/dev',
            'dist/prod',
            'artifacts/*'
        ];

        return gulp.src(globs, {read: false})
            .pipe(rimraf());
    });
})();<|endoftext|>


<commit_before>const { gulp, series, parallel, dest, src, watch } = require('gulp');
const babel = require('gulp-babel');
const browserSync = require('browser-sync');
const concat = require('gulp-concat');
const connect = require('gulp-connect-php');
const del = require('del');
const fs = require('fs');
const gutil = require('gulp-util');
const imagemin = require('gulp-imagemin');
const inject = require('gulp-inject-string');
const partialimport = require('postcss-easy-import');
const plumber = require('gulp-plumber');
const postcss = require('gulp-postcss');
const postCSSMixins = require('postcss-mixins');
const postcssPresetEnv = require('postcss-preset-env');
const remoteSrc = require('gulp-remote-src');
const sourcemaps = require('gulp-sourcemaps');
const uglify = require('gulp-uglify');
const zip = require('gulp-vinyl-zip');

/* -------------------------------------------------------------------------------------------------
Theme Name
-------------------------------------------------------------------------------------------------- */
const themeName = 'wordpressify';

/* -------------------------------------------------------------------------------------------------
PostCSS Plugins
-------------------------------------------------------------------------------------------------- */
const pluginsListDev = [
	partialimport,
	postCSSMixins,
	postcssPresetEnv({
		stage: 0,
		features: {
			'nesting-rules': true,
			'color-mod-function': true,
			'custom-media': true,
		},
	}),
];
const pluginsListProd = [
	partialimport,
	postCSSMixins,
	postcssPresetEnv({
		stage: 0,
		features: {
			'nesting-rules': true,
			'color-mod-function': true,
			'custom-media': true,
		},
	}),
];

/* -------------------------------------------------------------------------------------------------
Header & Footer JavaScript Boundles
-------------------------------------------------------------------------------------------------- */
const headerJS = [
	'node_modules/jquery/dist/jquery.js',
	'node_modules/nprogress/nprogress.js',
	'node_modules/aos/dist/aos.js',
	'node_modules/isotope-layout/dist/isotope.pkgd.js',
];
const footerJS = ['src/js/**'];

/* -------------------------------------------------------------------------------------------------
Installation Tasks
-------------------------------------------------------------------------------------------------- */
async function cleanup() {
	await del(['./build/**']);
	await del(['./dist/**']);
}

async function downloadWordPress() {
	await remoteSrc(['latest.zip'], {
		base: 'https://wordpress.org/',
	}).pipe(dest('./build/'));
}

async function unzipWordPress() {
	return await zip.src('./build/latest.zip').pipe(dest('./build/'));
}

async function copyConfig() {
	if (await fs.existsSync('./wp-config.php')) {
		return src('./wp-config.php')
			.pipe(inject.after("define('DB_COLLATE', '');", "\ndefine('DISABLE_WP_CRON', true);"))
			.pipe(dest('./build/wordpress'))
	}
}

async function installationDone() {
	await gutil.beep();
	await gutil.log(devServerReady);
	await gutil.log(thankYou);
}

exports.setup = series(cleanup, downloadWordPress);
exports.install = series(unzipWordPress, copyConfig, installationDone);

/* -------------------------------------------------------------------------------------------------
Development Tasks
-------------------------------------------------------------------------------------------------- */
function devServer() {
	connect.server(
		{
			base: './build/wordpress',
			port: '3020',
		},
		() => {
			browserSync({
				logPrefix: 'WordPressify',
				proxy: '127.0.0.1:3020',
				host: '127.0.0.1',
				port: '3010',
				open: 'external',
			});
		},
	);

	watch('./src/style/**/*.css', stylesDev);
	watch('./src/js/**', series(footerScriptsDev, Reload));
	watch('./src/fonts/**', series(copyFontsDev, Reload));
	watch('./src/theme/**', series(copyThemeDev, Reload));
	watch('./src/plugins/**', series(pluginsDev, Reload));
	watch('./build/wordpress/wp-config.php', { events: 'add' }, series(disableCron));
}

function Reload(done) {
	browserSync.reload();
	done();
}

function copyThemeDev() {
	if (!fs.existsSync('./build')) {
		gutil.log(buildNotFound);
		process.exit(1);
	} else {
		return src('./src/theme/**').pipe(dest('./build/wordpress/wp-content/themes/' + themeName));
	}
}

function copyFontsDev() {
	return src('./src/fonts/**').pipe(
		dest('./build/wordpress/wp-content/themes/' + themeName + '/fonts'),
	);
}

function stylesDev() {
	return src('./src/style/style.css')
		.pipe(plumber({ errorHandler: onError }))
		.pipe(sourcemaps.init())
		.pipe(postcss(pluginsListDev))
		.pipe(sourcemaps.write('.'))
		.pipe(dest('./build/wordpress/wp-content/themes/' + themeName))
		.pipe(browserSync.stream({ match: '**/*.css' }));
}

function headerScriptsDev() {
	return src(headerJS)
		.pipe(plumber({ errorHandler: onError }))
		.pipe(sourcemaps.init())
		.pipe(concat('header-bundle.js'))
		.pipe(sourcemaps.write('.'))
		.pipe(dest('./build/wordpress/wp-content/themes/' + themeName + '/js'));
}

function footerScriptsDev() {
	return src(footerJS)
		.pipe(plumber({ errorHandler: onError }))
		.pipe(sourcemaps.init())
		.pipe(
			babel({
				presets: ['@babel/preset-env'],
			}),
		)
		.pipe(concat('footer-bundle.js'))
		.pipe(sourcemaps.write('.'))
		.pipe(dest('./build/wordpress/wp-content/themes/' + themeName + '/js'));
}

function pluginsDev() {
	return src('./src/plugins/**').pipe(gulp.dest('./build/wordpress/wp-content/plugins'));
}

exports.start = series(
	copyThemeDev,
	copyFontsDev,
	stylesDev,
	headerScriptsDev,
	footerScriptsDev,
	devServer,
);

/* -------------------------------------------------------------------------------------------------
Production Tasks
-------------------------------------------------------------------------------------------------- */
async function cleanProd() {
	await del(['./dist/**']);
}

function copyThemeProd() {
	return src(['./src/theme/**', '!./src/theme/img/**']).pipe(dest('./dist/themes/' + themeName));
}

function copyFontsProd() {
	return src('./src/fonts/**').pipe(dest('./dist/themes/' + themeName + '/fonts'));
}

function stylesProd() {
	return src('./src/style/style.css')
		.pipe(plumber({ errorHandler: onError }))
		.pipe(postcss(pluginsListProd))
		.pipe(dest('./build/wordpress/wp-content/themes/' + themeName));
}

function headerScriptsProd() {
	return src(headerJS)
		.pipe(plumber({ errorHandler: onError }))
		.pipe(concat('header-bundle.js'))
		.pipe(uglify())
		.pipe(dest('./build/wordpress/wp-content/themes/' + themeName + '/js'));
}

function footerScriptsProd() {
	return src(footerJS)
		.pipe(plumber({ errorHandler: onError }))
		.pipe(
			babel({
				presets: ['@babel/preset-env'],
			}),
		)
		.pipe(concat('footer-bundle.js'))
		.pipe(uglify())
		.pipe(dest('./build/wordpress/wp-content/themes/' + themeName + '/js'));
}

function pluginsProd() {
	return src(['./src/plugins/**', '!./src/plugins/**/*.md']).pipe(dest('./dist/plugins'));
}

function processImages() {
	return src(['./src/theme/img/**', '!./src/theme/img/**/*.ico'])
		.pipe(plumber({ errorHandler: onError }))
		.pipe(
			imagemin([imagemin.svgo({ plugins: [{ removeViewBox: true }] })], {
				verbose: true,
			}),
		)
		.pipe(dest('./dist/themes/' + themeName + '/img'));
}

function zipProd() {
	return src('./dist/themes/' + themeName + '/**/*')
		.pipe(zip.dest('./dist/' + themeName + '.zip'))
		.on('end', () => {
			gutil.beep();
			gutil.log(pluginsGenerated);
			gutil.log(filesGenerated);
			gutil.log(thankYou);
		});
}

exports.prod = series(
	cleanProd,
	copyThemeProd,
	copyFontsProd,
	stylesProd,
	headerScriptsProd,
	footerScriptsProd,
	pluginsProd,
	processImages,
	zipProd,
);

/* -------------------------------------------------------------------------------------------------
Utility Tasks
-------------------------------------------------------------------------------------------------- */
const onError = err => {
	gutil.beep();
	gutil.log(wpFy + ' - ' + errorMsg + ' ' + err.toString());
	this.emit('end');
};

const date = new Date().toLocaleDateString('en-GB').replace(/\//g, '.');
const errorMsg = '\x1b[41mError\x1b[0m';
const warning = '\x1b[43mWarning\x1b[0m';
const devServerReady =
	'Your development server is ready, start the workflow with the command: $ \x1b[1mnpm run dev\x1b[0m';
const buildNotFound =
	errorMsg +
	' ⚠　- You need to install WordPress first. Run the command: $ \x1b[1mnpm run install:wordpress\x1b[0m';
const filesGenerated =
	'Your ZIP template file was generated in: \x1b[1m' +
	__dirname +
	'/dist/' +
	themeName +
	'.zip\x1b[0m - ✅';
const pluginsGenerated =
	'Plugins are generated in: \x1b[1m' + __dirname + '/dist/plugins/\x1b[0m - ✅';
const backupsGenerated =
	'Your backup was generated in: \x1b[1m' + __dirname + '/backups/' + date + '.zip\x1b[0m - ✅';
const wpFy = '\x1b[42m\x1b[1mWordPressify\x1b[0m';
const wpFyUrl = '\x1b[2m - http://www.wordpressify.co/\x1b[0m';
const thankYou = 'Thank you for using ' + wpFy + wpFyUrl;

async function disableCron() {
	if (fs.existsSync('./build/wordpress/wp-config.php')) {
		await fs.readFile('./build/wordpress/wp-config.php', (err, data) => {
			if (err) {
				gutil.log(wpFy + ' - ' + warning + ' WP_CRON was not disabled!');
			}
			if (data) {
				if (data.indexOf('DISABLE_WP_CRON') >= 0) {
					gutil.log('WP_CRON is already disabled!');
				} else {
					return src('./build/wordpress/wp-config.php')
						.pipe(inject.after("define('DB_COLLATE', '');", "\ndefine('DISABLE_WP_CRON', true);"))
						.pipe(dest('./build/wordpress'));
				}
			}
		});
	}
}

async function freshInstall() {
	await del(['./src/**']).then(() => {
		return src('./tools/fresh-theme/**').pipe(dest('./src'));
	});
}

exports.fresh = series(freshInstall);

function Backup() {
	if (!fs.existsSync('./build')) {
		gutil.log(buildNotFound);
		process.exit(1);
	} else {
		return src('./build/**/*')
			.pipe(zip.dest('./backups/' + date + '.zip'))
			.on('end', () => {
				gutil.beep();
				gutil.log(backupsGenerated);
				gutil.log(thankYou);
			});
	}
}

exports.backup = series(Backup);

/* -------------------------------------------------------------------------------------------------
End of all Tasks
-------------------------------------------------------------------------------------------------- */
<commit_msg>Update<commit_after>const { gulp, series, parallel, dest, src, watch } = require('gulp');
const babel = require('gulp-babel');
const browserSync = require('browser-sync');
const concat = require('gulp-concat');
const connect = require('gulp-connect-php');
const del = require('del');
const fs = require('fs');
const gutil = require('gulp-util');
const imagemin = require('gulp-imagemin');
const inject = require('gulp-inject-string');
const partialimport = require('postcss-easy-import');
const plumber = require('gulp-plumber');
const postcss = require('gulp-postcss');
const postCSSMixins = require('postcss-mixins');
const postcssPresetEnv = require('postcss-preset-env');
const remoteSrc = require('gulp-remote-src');
const sourcemaps = require('gulp-sourcemaps');
const uglify = require('gulp-uglify');
const zip = require('gulp-vinyl-zip');

/* -------------------------------------------------------------------------------------------------
Theme Name
-------------------------------------------------------------------------------------------------- */
const themeName = 'wordpressify';

/* -------------------------------------------------------------------------------------------------
PostCSS Plugins
-------------------------------------------------------------------------------------------------- */
const pluginsListDev = [
	partialimport,
	postCSSMixins,
	postcssPresetEnv({
		stage: 0,
		features: {
			'nesting-rules': true,
			'color-mod-function': true,
			'custom-media': true,
		},
	}),
];
const pluginsListProd = [
	partialimport,
	postCSSMixins,
	postcssPresetEnv({
		stage: 0,
		features: {
			'nesting-rules': true,
			'color-mod-function': true,
			'custom-media': true,
		},
	}),
];

/* -------------------------------------------------------------------------------------------------
Header & Footer JavaScript Boundles
-------------------------------------------------------------------------------------------------- */
const headerJS = [
	'node_modules/jquery/dist/jquery.js',
	'node_modules/nprogress/nprogress.js',
	'node_modules/aos/dist/aos.js',
	'node_modules/isotope-layout/dist/isotope.pkgd.js',
];
const footerJS = ['src/js/**'];

/* -------------------------------------------------------------------------------------------------
Installation Tasks
-------------------------------------------------------------------------------------------------- */
async function cleanup() {
	await del(['./build']);
	await del(['./dist']);
}

async function downloadWordPress() {
	await remoteSrc(['latest.zip'], {
		base: 'https://wordpress.org/',
	}).pipe(dest('./build/'));
}

async function unzipWordPress() {
	return await zip.src('./build/latest.zip').pipe(dest('./build/'));
}

async function copyConfig() {
	if (await fs.existsSync('./wp-config.php')) {
		return src('./wp-config.php')
			.pipe(inject.after("define('DB_COLLATE', '');", "\ndefine('DISABLE_WP_CRON', true);"))
			.pipe(dest('./build/wordpress'))
	}
}

async function installationDone() {
	await gutil.beep();
	await gutil.log(devServerReady);
	await gutil.log(thankYou);
}

exports.setup = series(cleanup, downloadWordPress);
exports.install = series(unzipWordPress, copyConfig, installationDone);

/* -------------------------------------------------------------------------------------------------
Development Tasks
-------------------------------------------------------------------------------------------------- */
function devServer() {
	connect.server(
		{
			base: './build/wordpress',
			port: '3020',
		},
		() => {
			browserSync({
				logPrefix: 'WordPressify',
				proxy: '127.0.0.1:3020',
				host: '127.0.0.1',
				port: '3010',
				open: 'external',
			});
		},
	);

	watch('./src/style/**/*.css', stylesDev);
	watch('./src/js/**', series(footerScriptsDev, Reload));
	watch('./src/fonts/**', series(copyFontsDev, Reload));
	watch('./src/theme/**', series(copyThemeDev, Reload));
	watch('./src/plugins/**', series(pluginsDev, Reload));
	watch('./build/wordpress/wp-config.php', { events: 'add' }, series(disableCron));
}

function Reload(done) {
	browserSync.reload();
	done();
}

function copyThemeDev() {
	if (!fs.existsSync('./build')) {
		gutil.log(buildNotFound);
		process.exit(1);
	} else {
		return src('./src/theme/**').pipe(dest('./build/wordpress/wp-content/themes/' + themeName));
	}
}

function copyFontsDev() {
	return src('./src/fonts/**').pipe(
		dest('./build/wordpress/wp-content/themes/' + themeName + '/fonts'),
	);
}

function stylesDev() {
	return src('./src/style/style.css')
		.pipe(plumber({ errorHandler: onError }))
		.pipe(sourcemaps.init())
		.pipe(postcss(pluginsListDev))
		.pipe(sourcemaps.write('.'))
		.pipe(dest('./build/wordpress/wp-content/themes/' + themeName))
		.pipe(browserSync.stream({ match: '**/*.css' }));
}

function headerScriptsDev() {
	return src(headerJS)
		.pipe(plumber({ errorHandler: onError }))
		.pipe(sourcemaps.init())
		.pipe(concat('header-bundle.js'))
		.pipe(sourcemaps.write('.'))
		.pipe(dest('./build/wordpress/wp-content/themes/' + themeName + '/js'));
}

function footerScriptsDev() {
	return src(footerJS)
		.pipe(plumber({ errorHandler: onError }))
		.pipe(sourcemaps.init())
		.pipe(
			babel({
				presets: ['@babel/preset-env'],
			}),
		)
		.pipe(concat('footer-bundle.js'))
		.pipe(sourcemaps.write('.'))
		.pipe(dest('./build/wordpress/wp-content/themes/' + themeName + '/js'));
}

function pluginsDev() {
	return src('./src/plugins/**').pipe(gulp.dest('./build/wordpress/wp-content/plugins'));
}

exports.start = series(
	copyThemeDev,
	copyFontsDev,
	stylesDev,
	headerScriptsDev,
	footerScriptsDev,
	devServer,
);

/* -------------------------------------------------------------------------------------------------
Production Tasks
-------------------------------------------------------------------------------------------------- */
async function cleanProd() {
	await del(['./dist']);
}

function copyThemeProd() {
	return src(['./src/theme/**', '!./src/theme/img/**']).pipe(dest('./dist/themes/' + themeName));
}

function copyFontsProd() {
	return src('./src/fonts/**').pipe(dest('./dist/themes/' + themeName + '/fonts'));
}

function stylesProd() {
	return src('./src/style/style.css')
		.pipe(plumber({ errorHandler: onError }))
		.pipe(postcss(pluginsListProd))
		.pipe(dest('./build/wordpress/wp-content/themes/' + themeName));
}

function headerScriptsProd() {
	return src(headerJS)
		.pipe(plumber({ errorHandler: onError }))
		.pipe(concat('header-bundle.js'))
		.pipe(uglify())
		.pipe(dest('./build/wordpress/wp-content/themes/' + themeName + '/js'));
}

function footerScriptsProd() {
	return src(footerJS)
		.pipe(plumber({ errorHandler: onError }))
		.pipe(
			babel({
				presets: ['@babel/preset-env'],
			}),
		)
		.pipe(concat('footer-bundle.js'))
		.pipe(uglify())
		.pipe(dest('./build/wordpress/wp-content/themes/' + themeName + '/js'));
}

function pluginsProd() {
	return src(['./src/plugins/**', '!./src/plugins/**/*.md']).pipe(dest('./dist/plugins'));
}

function processImages() {
	return src(['./src/theme/img/**', '!./src/theme/img/**/*.ico'])
		.pipe(plumber({ errorHandler: onError }))
		.pipe(
			imagemin([imagemin.svgo({ plugins: [{ removeViewBox: true }] })], {
				verbose: true,
			}),
		)
		.pipe(dest('./dist/themes/' + themeName + '/img'));
}

function zipProd() {
	return src('./dist/themes/' + themeName + '/**/*')
		.pipe(zip.dest('./dist/' + themeName + '.zip'))
		.on('end', () => {
			gutil.beep();
			gutil.log(pluginsGenerated);
			gutil.log(filesGenerated);
			gutil.log(thankYou);
		});
}

exports.prod = series(
	cleanProd,
	copyThemeProd,
	copyFontsProd,
	stylesProd,
	headerScriptsProd,
	footerScriptsProd,
	pluginsProd,
	processImages,
	zipProd,
);

/* -------------------------------------------------------------------------------------------------
Utility Tasks
-------------------------------------------------------------------------------------------------- */
const onError = err => {
	gutil.beep();
	gutil.log(wpFy + ' - ' + errorMsg + ' ' + err.toString());
	this.emit('end');
};

const date = new Date().toLocaleDateString('en-GB').replace(/\//g, '.');
const errorMsg = '\x1b[41mError\x1b[0m';
const warning = '\x1b[43mWarning\x1b[0m';
const devServerReady =
	'Your development server is ready, start the workflow with the command: $ \x1b[1mnpm run dev\x1b[0m';
const buildNotFound =
	errorMsg +
	' ⚠　- You need to install WordPress first. Run the command: $ \x1b[1mnpm run install:wordpress\x1b[0m';
const filesGenerated =
	'Your ZIP template file was generated in: \x1b[1m' +
	__dirname +
	'/dist/' +
	themeName +
	'.zip\x1b[0m - ✅';
const pluginsGenerated =
	'Plugins are generated in: \x1b[1m' + __dirname + '/dist/plugins/\x1b[0m - ✅';
const backupsGenerated =
	'Your backup was generated in: \x1b[1m' + __dirname + '/backups/' + date + '.zip\x1b[0m - ✅';
const wpFy = '\x1b[42m\x1b[1mWordPressify\x1b[0m';
const wpFyUrl = '\x1b[2m - http://www.wordpressify.co/\x1b[0m';
const thankYou = 'Thank you for using ' + wpFy + wpFyUrl;

async function disableCron() {
	if (fs.existsSync('./build/wordpress/wp-config.php')) {
		await fs.readFile('./build/wordpress/wp-config.php', (err, data) => {
			if (err) {
				gutil.log(wpFy + ' - ' + warning + ' WP_CRON was not disabled!');
			}
			if (data) {
				if (data.indexOf('DISABLE_WP_CRON') >= 0) {
					gutil.log('WP_CRON is already disabled!');
				} else {
					return src('./build/wordpress/wp-config.php')
						.pipe(inject.after("define('DB_COLLATE', '');", "\ndefine('DISABLE_WP_CRON', true);"))
						.pipe(dest('./build/wordpress'));
				}
			}
		});
	}
}

async function freshInstall() {
	await del(['./src/**']).then(() => {
		return src('./tools/fresh-theme/**').pipe(dest('./src'));
	});
}

exports.fresh = series(freshInstall);

function Backup() {
	if (!fs.existsSync('./build')) {
		gutil.log(buildNotFound);
		process.exit(1);
	} else {
		return src('./build/**/*')
			.pipe(zip.dest('./backups/' + date + '.zip'))
			.on('end', () => {
				gutil.beep();
				gutil.log(backupsGenerated);
				gutil.log(thankYou);
			});
	}
}

exports.backup = series(Backup);

/* -------------------------------------------------------------------------------------------------
End of all Tasks
-------------------------------------------------------------------------------------------------- */
<|endoftext|>


<commit_before>'use strict';
/*global require */
var gulp = require('gulp'),
  autoprefixer = require('gulp-autoprefixer'),
  concat = require('gulp-concat'),
  less = require('gulp-less'),
  minifyCss = require('gulp-minify-css'),
  notify = require('gulp-notify'),
  uglify = require('gulp-uglify'),
  util = require('gulp-util');

gulp.task('less', function() {
  return gulp.src(['assets/styles/mashup-theme.less'])
    .pipe(less({
      compress: false
    }))
    .on('error', util.log)
    .pipe(autoprefixer('ie9'))
    .pipe(minifyCss())
    .pipe(gulp.dest('dist/css'))
    .pipe(notify('Less compiled'));
});

gulp.task('compress', function() {
  return gulp.src(['assets/js/transition.js', 'assets/js/modal.js', 'assets/js/bootbox.js'])
    .pipe(concat('mashup.min.js'))
    .pipe(uglify())
    .pipe(gulp.dest('dist/js'));
});
<commit_msg>Remove trailing space<commit_after>'use strict';
/*global require */
var gulp = require('gulp'),
  autoprefixer = require('gulp-autoprefixer'),
  concat = require('gulp-concat'),
  less = require('gulp-less'),
  minifyCss = require('gulp-minify-css'),
  notify = require('gulp-notify'),
  uglify = require('gulp-uglify'),
  util = require('gulp-util');

gulp.task('less', function() {
  return gulp.src(['assets/styles/mashup-theme.less'])
    .pipe(less({
      compress: false
    }))
    .on('error', util.log)
    .pipe(autoprefixer('ie9'))
    .pipe(minifyCss())
    .pipe(gulp.dest('dist/css'))
    .pipe(notify('Less compiled'));
});

gulp.task('compress', function() {
  return gulp.src(['assets/js/transition.js', 'assets/js/modal.js', 'assets/js/bootbox.js'])
    .pipe(concat('mashup.min.js'))
    .pipe(uglify())
    .pipe(gulp.dest('dist/js'));
});
<|endoftext|>


<commit_before>/**
 * The gulpfile controls the "meta" level of this project. Namely,
 * coordinating, validating, etc. the various sub-projects. This file is most
 * appropriate for contributors to the project as a whole, and **not**
 * developers looking to use the `skeleton` or `full` implementations of
 * the examples.
 */
var fs = require("fs"),
  path = require("path"),
  gulp = require("gulp"),
  jshint = require("gulp-jshint"),
  exec = require("gulp-exec"),

  // Oh, gulp, you disappoint me.
  runSeq = require("run-sequence");

// ----------------------------------------------------------------------------
// Helpers
// ----------------------------------------------------------------------------
// Strip comments from JsHint JSON files (naive).
var _jsonCfg = function (name) {
  var raw = fs.readFileSync(name).toString();
  return JSON.parse(raw.replace(/\/\/.*\n/g, ""));
};

// Wrapper for gulp-exec to bridge easily to grunt tasks.
var _execTask = function (cmd, args) {
  return exec(
    "echo \"Running '<%= options.cmd %> <%= options.args %>' in " +
    "'<%= options.dirname(file.path) %>'\" && " +
    "cd \"<%= options.dirname(file.path) %>\" && " +
    "<%= options.cmd %> <%= options.args %>", {
      dirname: path.dirname,
      args: args,
      cmd: cmd
    });
};

var _gruntTask = function (name) {
  return _execTask("./node_modules/.bin/grunt", name);
};

// ----------------------------------------------------------------------------
// JsHint
// ----------------------------------------------------------------------------
gulp.task("jshint:frontend", function () {
  gulp
    .src("*/*/Gruntfile.js")
    .pipe(_gruntTask("jshint"));
});

gulp.task("jshint:backend", function () {
  gulp
    .src([
      "*.js",
      "*/*/Gruntfile.js"
    ])
    .pipe(jshint(_jsonCfg("./_dev/.jshintrc-backend.json")))
    .pipe(jshint.reporter("default"))
    .pipe(jshint.reporter("fail"));
});

gulp.task("jshint", ["jshint:frontend", "jshint:backend"]);

// ----------------------------------------------------------------------------
// Builders
// ----------------------------------------------------------------------------
// Generally speaking, `full` implementations control `skeleton`
// implementations. These tasks bring the skeletons into sync with the fulls.
gulp.task("sync:amd", function (cb) {
  gulp
    .src([
      "full/amd/{.,}*",
      "!full/amd/README.md",

      "full/amd/app/*.html",
      "full/amd/app/js/*.js",
      "full/amd/app/css/**",
      "full/amd/test/*/*.html",
      "full/amd/test/*/js/*.js",

      "!full/amd/bower_components/{.,}**/{.,}*",
      "!full/amd/node_modules/{.,}**/{.,}*"

    ], { base: "full/amd" })
    .pipe(gulp.dest("skeleton/amd"))
    .on("end", cb);
});

gulp.task("install:amd", function (cb) {
  gulp
    .src("*/amd/Gruntfile.js")
    .pipe(_execTask("npm", "install"))
    .on("end", cb);
});

// ----------------------------------------------------------------------------
// Aggregated Tasks
// ----------------------------------------------------------------------------
// No dependencies
gulp.task("check:dev",  ["jshint"]);
gulp.task("check",      ["check:dev"]);

gulp.task("install",    ["install:amd"]);
gulp.task("sync",       ["sync:amd"]);

gulp.task("default", function (cb) {
  // Need tasks **completely** done to get **new** files to run tasks on.
  // Wrap with a `reduceRight` and then execute the outer wrapper.
  [
    "sync",
    "install",
    "check"
  ].reduceRight(function (memo, name) {
    return function () { runSeq([name], memo); };
  }, cb)();
});
<commit_msg>Remove unneeded cb's<commit_after>/**
 * The gulpfile controls the "meta" level of this project. Namely,
 * coordinating, validating, etc. the various sub-projects. This file is most
 * appropriate for contributors to the project as a whole, and **not**
 * developers looking to use the `skeleton` or `full` implementations of
 * the examples.
 */
var fs = require("fs"),
  path = require("path"),
  gulp = require("gulp"),
  jshint = require("gulp-jshint"),
  exec = require("gulp-exec"),

  // Oh, gulp, you disappoint me.
  runSeq = require("run-sequence");

// ----------------------------------------------------------------------------
// Helpers
// ----------------------------------------------------------------------------
// Strip comments from JsHint JSON files (naive).
var _jsonCfg = function (name) {
  var raw = fs.readFileSync(name).toString();
  return JSON.parse(raw.replace(/\/\/.*\n/g, ""));
};

// Wrapper for gulp-exec to bridge easily to grunt tasks.
var _execTask = function (cmd, args) {
  return exec(
    "echo \"Running '<%= options.cmd %> <%= options.args %>' in " +
    "'<%= options.dirname(file.path) %>'\" && " +
    "cd \"<%= options.dirname(file.path) %>\" && " +
    "<%= options.cmd %> <%= options.args %>", {
      dirname: path.dirname,
      args: args,
      cmd: cmd
    });
};

var _gruntTask = function (name) {
  return _execTask("./node_modules/.bin/grunt", name);
};

// ----------------------------------------------------------------------------
// JsHint
// ----------------------------------------------------------------------------
gulp.task("jshint:frontend", function () {
  gulp
    .src("*/*/Gruntfile.js")
    .pipe(_gruntTask("jshint"));
});

gulp.task("jshint:backend", function () {
  gulp
    .src([
      "*.js",
      "*/*/Gruntfile.js"
    ])
    .pipe(jshint(_jsonCfg("./_dev/.jshintrc-backend.json")))
    .pipe(jshint.reporter("default"))
    .pipe(jshint.reporter("fail"));
});

gulp.task("jshint", ["jshint:frontend", "jshint:backend"]);

// ----------------------------------------------------------------------------
// Builders
// ----------------------------------------------------------------------------
// Generally speaking, `full` implementations control `skeleton`
// implementations. These tasks bring the skeletons into sync with the fulls.
gulp.task("sync:amd", function () {
  gulp
    .src([
      "full/amd/{.,}*",
      "!full/amd/README.md",

      "full/amd/app/*.html",
      "full/amd/app/js/*.js",
      "full/amd/app/css/**",
      "full/amd/test/*/*.html",
      "full/amd/test/*/js/*.js",

      "!full/amd/bower_components/{.,}**/{.,}*",
      "!full/amd/node_modules/{.,}**/{.,}*"

    ], { base: "full/amd" })
    .pipe(gulp.dest("skeleton/amd"));
});

gulp.task("install:amd", function () {
  gulp
    .src("*/amd/Gruntfile.js")
    .pipe(_execTask("npm", "install"));
});

// ----------------------------------------------------------------------------
// Aggregated Tasks
// ----------------------------------------------------------------------------
// No dependencies
gulp.task("check:dev",  ["jshint"]);
gulp.task("check",      ["check:dev"]);

gulp.task("install",    ["install:amd"]);
gulp.task("sync",       ["sync:amd"]);

gulp.task("default", function (cb) {
  // Need tasks **completely** done to get **new** files to run tasks on.
  // Wrap with a `reduceRight` and then execute the outer wrapper.
  [
    "sync",
    "install",
    "check"
  ].reduceRight(function (memo, name) {
    return function () { runSeq([name], memo); };
  }, cb)();
});
<|endoftext|>


<commit_before>// *****************************************************************
// USEFUL TASKS
// $ gulp dist -> Compile the distribution folder
// $ gulp compile -> Compile the development files
// $ gulp default -> Compile and start a local webserver + watcher
// $ gulp serve -> Just serve the local webserver
// *****************************************************************

var env = require('./gulp/env.js');
var gulp = require('gulp');

// BASE SINGLE TASKS
gulp.task('style', env.loadTask('sass'));
gulp.task('view', env.loadTask('jade'));
gulp.task('sprite', env.loadTask('sprites'));
gulp.task('script', env.loadTask('typescript'));
gulp.task('font', env.loadTask('fontgen'));
gulp.task('iconfont', env.loadTask('iconfont'));
gulp.task('srcWatch', env.loadTask('src-watch'));
gulp.task('clean', env.loadTask('clean'));
gulp.task('minify', ['move'], env.loadTask('minify'));
gulp.task('move', env.loadTask('move'));
gulp.task('compress', env.loadTask('compress'));

// USEFUL TASKS
gulp.task('dist', ['clean', 'minify']);
gulp.task('compile', ['style', 'view', 'script']);
gulp.task('default', ['compile', 'srcWatch'], env.loadTask('browser-sync'));
gulp.task('serve', ['srcWatch'], env.loadTask('browser-sync'));
<commit_msg>Added copy task on default task<commit_after>// *****************************************************************
// USEFUL TASKS
// $ gulp dist -> Compile the distribution folder
// $ gulp compile -> Compile the development files
// $ gulp default -> Compile and start a local webserver + watcher
// $ gulp serve -> Just serve the local webserver
// *****************************************************************

var env = require('./gulp/env.js');
var gulp = require('gulp');

// BASE SINGLE TASKS
gulp.task('style', env.loadTask('sass'));
gulp.task('view', env.loadTask('jade'));
gulp.task('sprite', env.loadTask('sprites'));
gulp.task('script', env.loadTask('typescript'));
gulp.task('font', env.loadTask('fontgen'));
gulp.task('iconfont', env.loadTask('iconfont'));
gulp.task('srcWatch', env.loadTask('src-watch'));
gulp.task('clean', env.loadTask('clean'));
gulp.task('minify', ['move'], env.loadTask('minify'));
gulp.task('move', env.loadTask('move'));
gulp.task('copy', env.loadTask('copy-assets'));
gulp.task('compress', env.loadTask('compress'));

// USEFUL TASKS
gulp.task('dist', ['clean', 'minify']);
gulp.task('compile', ['style', 'view', 'script']);
gulp.task('default', ['compile', 'srcWatch', 'copy'], env.loadTask('browser-sync'));
gulp.task('serve', ['srcWatch'], env.loadTask('browser-sync'));
<|endoftext|>


<commit_before>var gulp     = require("gulp");
var del      = require("del");
var sass     = require("gulp-sass");
var rename   = require("gulp-rename");
var template = require("gulp-template");
var runseq   = require('run-sequence');
var fs       = require("fs");
var _        = require("lodash");
var proc     = require("child_process");

var isDebug = false;

console.log("gulp> Init.");

//Main Paths
var path = {
    src: "source",
    dst: "deploy"
};

//File Paths
path.js   = { src: path.src+"/js",   dst: path.dst+"/js" };
path.scss = { src: path.src+"/scss", dst: path.dst+"/css" };
path.html = { src: path.src+"/html", dst: path.dst };
path.img  = { src: path.src, dst: path.dst };

//Source Streams
var jsFiles   = gulp.src(path.js.src  +"/**/*.js");
var scssFiles = gulp.src(path.scss.src+"/**/*.scss");
var htmlFiles = gulp.src([path.html.src+"/**/*.html","!"+path.html.src+"/**/*.t.html"]);
var imgFiles  = gulp.src([path.src+"/**/*.png",path.src+"/**/*.jpg",path.src+"/**/*.gif",path.src+"/**/*.svg"]);

//Destination Streams
var jsDst   = gulp.dest(path.js.dst);
var scssDst = gulp.dest(path.scss.dst);
var htmlDst = gulp.dest(path.html.dst);
var imgDst  = gulp.dest(path.img.dst);

//Delete the contents of deploy folder
gulp.task("clean",function clean(){
    return del([path.dst+"/**/*","!"+path.dst+"/CNAME*"]);
})

//Move Javascript files to the deploy folder.
gulp.task("move-js", function moveJS() {
    return jsFiles.pipe(jsDst);
});

//Move HTML files to the deploy folder.
gulp.task("move-html", function moveHTML() {
    return htmlFiles.pipe(htmlDst);
});

//Move img files to the deploy folder.
gulp.task("move-img", function moveImg() {
    return imgFiles.pipe(imgDst);
});

//Build Sass files to CSS deploy folder.
gulp.task("build-scss",function buildScss() {

    scssFiles
    .pipe(sass.sync().on("error", sass.logError))
    .pipe(scssDst);

    scssFiles
    .pipe(sass.sync({outputStyle: "compressed"}).on("error", sass.logError))
    .pipe(rename({suffix: ".min"}))
    .pipe(scssDst);

});

//Build Template files to HTML deploy folder.
gulp.task("build-html",function buildScss() {

    var ctx     = {};
    ctx.data    = require("./"+path.html.src+"/config.json");
    ctx.render  = function render(p_file) {
        var s = fs.readFileSync(path.html.src+"/"+p_file).toString();
        var c = _.template(s);
        return c(ctx);
    };
    htmlFiles
    .pipe(template(ctx))
    .pipe(htmlDst);

});

//Builds the website.
gulp.task("build",function build() {
    //Run 'clean' then asynchronously the rest
    runseq("clean",["move-js","move-img","build-html","build-scss"]);
 });

 //Publish the site in github pages
gulp.task("publish",function build() {
    proc.execSync("git add -A",[],{silent:true});
    proc.execSync("git commit -a -m [vscode-publish-task]",[],{silent:true});
    proc.execSync("git push",[],{silent:true});
    proc.execSync("git subtree push --prefix "+path.dst+" origin master",[],{silent:true});
 });

<commit_msg>[vscode-publish-task]<commit_after>var gulp     = require("gulp");
var del      = require("del");
var sass     = require("gulp-sass");
var rename   = require("gulp-rename");
var template = require("gulp-template");
var runseq   = require('run-sequence');
var fs       = require("fs");
var _        = require("lodash");
var proc     = require("child_process");

var isDebug = false;

console.log("gulp> Init.");

//Main Paths
var path = {
    src: "source",
    dst: "deploy"
};

//File Paths
path.js   = { src: path.src+"/js",   dst: path.dst+"/js" };
path.scss = { src: path.src+"/scss", dst: path.dst+"/css" };
path.html = { src: path.src+"/html", dst: path.dst };
path.img  = { src: path.src, dst: path.dst };

//Source Streams
var jsFiles   = gulp.src(path.js.src  +"/**/*.js");
var scssFiles = gulp.src(path.scss.src+"/**/*.scss");
var htmlFiles = gulp.src([path.html.src+"/**/*.html","!"+path.html.src+"/**/*.t.html"]);
var imgFiles  = gulp.src([path.src+"/**/*.png",path.src+"/**/*.jpg",path.src+"/**/*.gif",path.src+"/**/*.svg"]);

//Destination Streams
var jsDst   = gulp.dest(path.js.dst);
var scssDst = gulp.dest(path.scss.dst);
var htmlDst = gulp.dest(path.html.dst);
var imgDst  = gulp.dest(path.img.dst);

//Just shows the help
function defaultTask() {
    console.log("clean      - Clear all files from [./"+path.dst+"]");
    console.log("move-js    - Moves JS files from [./"+path.js.src+"] to [./"+path.js.dst+"]");
    console.log("move-img   - Moves Image files from [./"+path.img.src+"] to [./"+path.img.dst+"]");
    console.log("build-scss - Build Scss files from [./"+path.scss.src+"] to [./"+path.scss.dst+"]");
    console.log("build-html - Build Html files from [./"+path.html.src+"] to [./"+path.html.dst+"]");
    console.log("build      - Builds all project");
    console.log("publish    - Deploy the project to Github pages");
}

//Helps with the gulp task commands.
gulp.task("?",defaultTask);
gulp.task("default",defaultTask);

//Delete the contents of deploy folder
gulp.task("clean",function clean(){
    return del([path.dst+"/**/*","!"+path.dst+"/CNAME*"]);
});

//Move Javascript files to the deploy folder.
gulp.task("move-js", function moveJS() {
    return jsFiles.pipe(jsDst);
});

//Move img files to the deploy folder.
gulp.task("move-img", function moveImg() {
    return imgFiles.pipe(imgDst);
});

//Build Sass files to CSS deploy folder.
gulp.task("build-scss",function buildScss() {

    scssFiles
    .pipe(sass.sync().on("error", sass.logError))
    .pipe(scssDst);

    scssFiles
    .pipe(sass.sync({outputStyle: "compressed"}).on("error", sass.logError))
    .pipe(rename({suffix: ".min"}))
    .pipe(scssDst);

});

//Build Template files to HTML deploy folder.
gulp.task("build-html",function buildScss() {

    var ctx     = {};
    ctx.data    = require("./"+path.html.src+"/config.json");
    ctx.render  = function render(p_file) {
        var s = fs.readFileSync(path.html.src+"/"+p_file).toString();
        var c = _.template(s);
        return c(ctx);
    };
    htmlFiles
    .pipe(template(ctx))
    .pipe(htmlDst);

});

//Builds the website.
gulp.task("build",function build() {
    //Run 'clean' then asynchronously the rest
    runseq("clean",["move-js","move-img","build-html","build-scss"]);
 });

 //Publish the site in github pages
gulp.task("publish",function build() {
    proc.execSync("git add -A",[],{silent:true});
    proc.execSync("git commit -a -m [vscode-publish-task]",[],{silent:true});
    proc.execSync("git push",[],{silent:true});
    proc.execSync("git subtree push --prefix "+path.dst+" origin master",[],{silent:true});
 });

<|endoftext|>


<commit_before>const gulp = require('gulp');
const path = require('path');
const webpack = require('webpack');
const webpackConfig = require('./webpack.config');
const webpackStream = require('webpack-stream');
const babel = require('gulp-babel');
const mocha = require('gulp-mocha');
const istanbul = require('gulp-babel-istanbul');
const coveralls = require('gulp-coveralls');
const eslint = require('gulp-eslint');

function build() {
  return gulp.src('./src/formwood.js')
    .pipe(webpackStream(webpackConfig, webpack));
}

function sendToCoveralls() {
  gulp.src('coverage/**/lcov.info')
    .pipe(coveralls());
}

function runMochaTests() {
  return gulp.src('test/unit/**/*.js', {read: false})
    .pipe(mocha({
       reporter: 'dot',
       ignoreLeaks: false
    }));
}

function test() {
  require('babel-core/register');
  return gulp.src('src/**/*.js')
    .pipe(istanbul())
    .pipe(istanbul.hookRequire())
    .on('finish', function() {
      runMochaTests()
        .pipe(istanbul.writeReports())
    });
}

function lint() {
  return gulp.src('src/**/*')
    .pipe(eslint())
    .pipe(eslint.format())
    .pipe(eslint.failAfterError());
}

gulp.task('build', build);
gulp.task('test', test);
gulp.task('coveralls', sendToCoveralls);
gulp.task('lint', lint);
gulp.task('default', ['build']);
<commit_msg>Fix indentation<commit_after>const gulp = require('gulp');
const path = require('path');
const webpack = require('webpack');
const webpackConfig = require('./webpack.config');
const webpackStream = require('webpack-stream');
const babel = require('gulp-babel');
const mocha = require('gulp-mocha');
const istanbul = require('gulp-babel-istanbul');
const coveralls = require('gulp-coveralls');
const eslint = require('gulp-eslint');

function build() {
  return gulp.src('./src/formwood.js')
    .pipe(webpackStream(webpackConfig, webpack));
}

function sendToCoveralls() {
  gulp.src('coverage/**/lcov.info')
    .pipe(coveralls());
}

function runMochaTests() {
  return gulp.src('test/unit/**/*.js', {read: false})
    .pipe(mocha({
      reporter: 'dot',
      ignoreLeaks: false
    }));
}

function test() {
  require('babel-core/register');
  return gulp.src('src/**/*.js')
    .pipe(istanbul())
    .pipe(istanbul.hookRequire())
    .on('finish', function() {
      runMochaTests()
        .pipe(istanbul.writeReports())
    });
}

function lint() {
  return gulp.src('src/**/*')
    .pipe(eslint())
    .pipe(eslint.format())
    .pipe(eslint.failAfterError());
}

gulp.task('build', build);
gulp.task('test', test);
gulp.task('coveralls', sendToCoveralls);
gulp.task('lint', lint);
gulp.task('default', ['build']);
<|endoftext|>


<commit_before>// See: http://gulpjs.com/

var gulp = require('gulp');
var mocha = require('gulp-mocha');

gulp.task('test', function () {
    return gulp.src([
            './test/parser-test.js',
            './test/format-file-test.js',
            './test/format-file-name-test.js',
            './test/format-file-dir-test.js',
            './test/creator-test.js',
        ], { read: false })
        .pipe(mocha({
            reporter: 'nyan',
        }));
});

gulp.task('watch', function () {
    gulp.watch([
        './lib/**/*.js',
        './test/**/*.js',
        './test/**/*.yml',
    ], ['test']);
});

gulp.task('default', ['test', 'watch']);
<commit_msg>Restructure: return gulp test<commit_after>// See: http://gulpjs.com/

var gulp = require('gulp');
var mocha = require('gulp-mocha');

gulp.task('test', function () {
    return gulp.src('./test/**/*.js', { read: false })
        .pipe(mocha({
            reporter: 'nyan',
        }));
});

gulp.task('watch', function () {
    gulp.watch([
        './lib/**/*.js',
        './test/**/*.js',
        './test/**/*.yml',
    ], ['test']);
});

gulp.task('default', ['test', 'watch']);
<|endoftext|>


<commit_before>'use strict';
var path = require('path');
var gulp = require('gulp');
var eslint = require('gulp-eslint');
var excludeGitignore = require('gulp-exclude-gitignore');
var mocha = require('gulp-mocha');
var istanbul = require('gulp-istanbul');
var nsp = require('gulp-nsp');
var plumber = require('gulp-plumber');
var coveralls = require('gulp-coveralls');

gulp.task('static', function () {
    return gulp.src('**/*.js')
        .pipe(excludeGitignore())
        .pipe(eslint())
        .pipe(eslint.format())
        .pipe(eslint.failAfterError());
});

gulp.task('nsp', function (cb) {
    nsp({package: path.resolve('package.json')}, cb);
});

gulp.task('pre-test', function () {
    return gulp.src('app.js')
    .pipe(istanbul({
        includeUntested: true
    }))
    .pipe(istanbul.hookRequire());
});

gulp.task('test', ['pre-test'], function (cb) {
    var mochaErr;

    gulp.src('tests/**/*.js')
        .pipe(plumber())
        .pipe(mocha({reporter: 'spec'}))
        .on('error', function (err) {
            mochaErr = err;
        })
        .pipe(istanbul.writeReports())
        .on('end', function () {
            cb(mochaErr);
        });
});

gulp.task('coveralls', ['test'], function () {
    if (!process.env.CI) {
        return;
    }

    return gulp.src(path.join(__dirname, 'coverage/lcov.info'))
        .pipe(coveralls());
});

gulp.task('prepublish', ['nsp']);
gulp.task('default', ['static', 'test', 'coveralls']);
<commit_msg>Adding test coverage<commit_after>'use strict';
var path = require('path');
var gulp = require('gulp');
var eslint = require('gulp-eslint');
var excludeGitignore = require('gulp-exclude-gitignore');
var mocha = require('gulp-mocha');
var istanbul = require('gulp-istanbul');
var nsp = require('gulp-nsp');
var plumber = require('gulp-plumber');
var coveralls = require('gulp-coveralls');

gulp.task('static', function () {
    return gulp.src('**/*.js')
        .pipe(excludeGitignore())
        .pipe(eslint())
        .pipe(eslint.format())
        .pipe(eslint.failAfterError());
});

gulp.task('nsp', function (cb) {
    nsp({package: path.resolve('package.json')}, cb);
});

gulp.task('pre-test', function () {
    return gulp.src('routes/*.js')
    .pipe(istanbul({
        includeUntested: true
    }))
    .pipe(istanbul.hookRequire());
});

gulp.task('test', ['pre-test'], function (cb) {
    var mochaErr;

    gulp.src('tests/*.js')
        .pipe(plumber())
        .pipe(mocha({reporter: 'spec'}))
        .on('error', function (err) {
            mochaErr = err;
        })
        .pipe(istanbul.writeReports())
        .on('end', function () {
            cb(mochaErr);
        });
});

gulp.task('coveralls', ['test'], function () {
    if (!process.env.CI) {
        return;
    }

    return gulp.src(path.join(__dirname, 'coverage/lcov.info'))
        .pipe(coveralls());
});

gulp.task('prepublish', ['nsp']);
gulp.task('default', ['static', 'test', 'coveralls']);
<|endoftext|>


<commit_before>var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var forever =  require('forever');

var srcs = {
	test : 'spec/**/*-spec.js',
	e2e : 'e2e/**/*-spec.js'
};

gulp.task('test', function(){
	return gulp.src(srcs.test)
			.pipe($.jasmine());
});

gulp.task('e2e', function(){
	return gulp.src(srcs.e2e)
		.pipe($.jasmine());
});
<commit_msg>removed forever import from gulpfile<commit_after>var gulp = require('gulp');
var $ = require('gulp-load-plugins')();

var srcs = {
	test : 'spec/**/*-spec.js',
	e2e : 'e2e/**/*-spec.js'
};

gulp.task('test', function(){
	return gulp.src(srcs.test)
			.pipe($.jasmine());
});

gulp.task('e2e', function(){
	return gulp.src(srcs.e2e)
		.pipe($.jasmine());
});
<|endoftext|>


<commit_before>var path = require('path'),
    gulp = require('gulp'),
    uglify = require('gulp-uglify'),
    less = require('gulp-less'),
    htmlmin = require('gulp-htmlmin'),
    jshint = require('gulp-jshint'),
    concat = require('gulp-concat'),
    rename = require('gulp-rename');

gulp.task('default', function(){
  gulp.run('uglify-js', 'less', 'minify-template', 'lint');

  gulp.watch('src/js/**/*.js', function(event) {
    console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
    gulp.run('uglify-js');
  });

  gulp.watch('src/less/**/*.less', function(event) {
    console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
    gulp.run('less');
  });

  gulp.watch('src/template/**/*.html', function(event) {
    console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
    gulp.run('minify-template');
  });
});

gulp.task('debug', function(){
  gulp.run('copy-js', 'less', 'copy-template', 'lint');

  gulp.watch('src/js/**/*.js', function(event) {
    console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
    gulp.run('copy-js');
  });

  gulp.watch('src/less/**/*.less', function(event) {
    console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
    gulp.run('less');
  });

  gulp.watch('src/js/**/*.js', function(event) {
    console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
    gulp.run('copy-template');
  });
});

gulp.task('uglify-js', function () {
  gulp.src('src/js/**/*.js')
    .pipe(concat('ng-breadcrumbs.js'))
    .pipe(gulp.dest('dist/js'))
    .pipe(uglify())
    .pipe(rename('ng-breadcrumbs.min.js'))
    .pipe(gulp.dest('dist/js'));
});

gulp.task('copy-js', function() {
  gulp.src('src/js/**/*.js')
    .pipe(concat('ng-breadcrumbs.js'))
    .pipe(gulp.dest('dist/js'))
    .pipe(rename('ng-breadcrumbs.min.js'))
    .pipe(gulp.dest('dist/js'));
});

gulp.task('minify-template', function() {
  gulp.src('src/template/**/*.html')
    .pipe(htmlmin({ collapseWhitespace: true }))
    .pipe(gulp.dest('public/template'))
});

gulp.task('copy-template', function() {
  gulp.src('src/template/**/*.html')
    .pipe(gulp.dest('public/template'))
});

gulp.task('less', function () {
  gulp.src('src/less/**/*.less')
    .pipe(less({
      paths: [ path.join(__dirname, 'public/less', 'includes') ]
    }))
    .pipe(gulp.dest('public/css'));
});

gulp.task('lint', function () {
  gulp.src('src/js/**/*.js')
    .pipe(jshint())
    .pipe(jshint.reporter('default'));
});<commit_msg>Gulpfile cleanup<commit_after>var path = require('path'),
    gulp = require('gulp'),
    uglify = require('gulp-uglify'),
    less = require('gulp-less'),
    htmlmin = require('gulp-htmlmin'),
    jshint = require('gulp-jshint'),
    concat = require('gulp-concat'),
    rename = require('gulp-rename');

gulp.task('default', function() {
  gulp.run('uglify-js', 'less', 'minify-template', 'lint');

  gulp.watch('src/js/**/*.js', function(event) {
    console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
    gulp.run('uglify-js');
  });

  gulp.watch('src/less/**/*.less', function(event) {
    console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
    gulp.run('less');
  });

  gulp.watch('src/template/**/*.html', function(event) {
    console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
    gulp.run('minify-template');
  });
});

gulp.task('debug', function() {
  gulp.run('copy-js', 'less', 'copy-template', 'lint');

  gulp.watch('src/js/**/*.js', function(event) {
    console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
    gulp.run('copy-js');
  });

  gulp.watch('src/less/**/*.less', function(event) {
    console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
    gulp.run('less');
  });

  gulp.watch('src/js/**/*.js', function(event) {
    console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
    gulp.run('copy-template');
  });
});

gulp.task('uglify-js', function() {
  gulp.src('src/js/**/*.js')
    .pipe(concat('ng-breadcrumbs.js'))
    .pipe(gulp.dest('dist/js'))
    .pipe(uglify())
    .pipe(rename('ng-breadcrumbs.min.js'))
    .pipe(gulp.dest('dist/js'));
});

gulp.task('copy-js', function() {
  gulp.src('src/js/**/*.js')
    .pipe(concat('ng-breadcrumbs.js'))
    .pipe(gulp.dest('dist/js'))
    .pipe(rename('ng-breadcrumbs.min.js'))
    .pipe(gulp.dest('dist/js'));
});

gulp.task('minify-template', function() {
  gulp.src('src/template/**/*.html')
    .pipe(htmlmin({ collapseWhitespace: true }))
    .pipe(gulp.dest('public/template'));
});

gulp.task('copy-template', function() {
  gulp.src('src/template/**/*.html')
    .pipe(gulp.dest('public/template'));
});

gulp.task('less', function() {
  gulp.src('src/less/**/*.less')
    .pipe(less({
      paths: [ path.join(__dirname, 'public/less', 'includes') ]
    }))
    .pipe(gulp.dest('public/css'));
});

gulp.task('lint', function() {
  gulp.src('src/js/**/*.js')
    .pipe(jshint())
    .pipe(jshint.reporter('default'));
});<|endoftext|>