<commit_before>const gulp = require('gulp');
const parameterized = require('gulp-parameterized');

const colors = require('ansi-colors');
const del = require('del');
const { exec } = require('child_process');
const merge = require('merge2');
const path = require('path');

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

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

const PROJECT_VAR = '{project}';

/* npm install */
const install = done => {
    gulp.parallel(
        [undefined].concat(...projectNames)
            .map(command => {
                const run = cb =>
                    runCommand('npm install', { cwd: command ? `projects/${command}` : undefined }, cb);
                run.displayName = `install-${command || 'root'}`;
                return run;
            })
    )(done);
};

/* npm link */
const link = done => { linker(true, done); };

const unlink = done => { linker(false, done); };

const linker = (mode, done) => {
    const projectLinks = projectNames.map(project => {
        const linkPhrase = mode ? 'link' : 'unlink';
        const run = cb =>
            runCommand(`npm ${linkPhrase} --no-bin-links`, { cwd: `projects/${project}` }, cb);
        run.displayName = `${linkPhrase}-${project}`;
        return run;
    });

    const tasks = [gulp.parallel(projectLinks)];
    if (mode) {
        const dependencyLinks = projectNames
            .filter(p => projects[p].hasOwnProperty('dependencies'))
            .reduce((p, c) =>
                p.concat(...projects[c].dependencies.map(dependency => {
                    const { name } = require(`./projects/${dependency}/package.json`); // eslint-disable-line global-require
                    const run = cb =>
                        runCommand(`npm link ${name} --no-bin-links`, { cwd: `projects/${c}` }, cb);
                    run.displayName = `link:${name}->${c}`;
                    return run;
                })), []
            );
        if (dependencyLinks.length > 0)
            tasks.push(dependencyLinks);
    }

    gulp.series(tasks)(done);
};

/* Cleaning */
const clean = () => del(expandGlobs(settings.clean));

const deepClean = () => del(expandGlobs(settings.deepClean));

/* Building */
const tslint = () =>
    gulp.src(wildcardPaths(settings.tsfiles))
        .pipe(G$.tslint({ formatter: 'verbose' }))
        .pipe(G$.tslint.report({ emitError: false }));

/* Transpiling */
const transpileProjects = projects => () => {
    const jsSources = Array.from(new Set(projects.reduce((globs, project) => globs.concat(mapPaths(settings.jsFiles, project)), [])));
    const tsSources = Array.from(new Set(projects.reduce((globs, project) => globs.concat(mapPaths(settings.tsfiles, project)), [])));
    const resources = Array.from(new Set(projects.reduce((globs, project) => globs.concat(mapPaths(settings.resources, project)), [])));

    const tsResult = gulp.src(tsSources)
        .pipe(G$.sourcemaps.init())
        .pipe(G$.typescript.createProject(tsconfig.compilerOptions)());

    const destTrans = file =>
        file.base.replace(/.+?(?:\\|\/)projects(?:\\|\/)(.+?)(?:\\|\/)src(?:\\|\/.+)?/, 'projects\/$1\/lib\/');

    return merge([
        tsResult.dts.pipe(gulp.dest(destTrans)),
        tsResult.js // separate .js.map files
            .pipe(G$.sourcemaps.write('.'))
            .pipe(gulp.dest(destTrans)),
        // JS files
        gulp.src(jsSources)
            .pipe(G$.babel({ presets: ['es2015'] }))
            .pipe(gulp.dest(destTrans)),
        // all other files
        gulp.src(resources).pipe(gulp.dest(destTrans))
    ]);
};

const watch = () => {
    projectNames.forEach(project =>
        gulp.watch(mapPaths(Array.prototype.concat(settings.tsfiles, settings.jsFiles), project), gulp.parallel(`ts-${project}`)));
};

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

/* Dependencies */
const npmInstall = (done, params) => {
    if (!params.pack || !params.project) {
        console.error('Must specify a package and project');
        return done();
    }

    runCommand(`npm install --save ${params.pack}`, { cwd: mapPath(settings.projectPath, params.project) }, done);
};

const npmUninstall = (done, params) => {
    if (!params.pack || !params.project) {
        console.error('Must specify a package and project');
        return done();
    }

    runCommand(`npm uninstall --save ${params.pack}`, { cwd: mapPath(settings.projectPath, params.project) }, done);
};

/* Code analysis */
const stats = (done, params) => {
    if (params.project) {
        console.log(`Source Lines of Code: ${colors.green(params.project)}`);
        return gulp.src(mapPaths(settings.sloc_project, params.project)).pipe(G$.sloc({ tolerant: true }));
    }

    console.log(`Source Lines of Code: ${colors.white('ALL')}`);
    return gulp.src(settings.sloc_all).pipe(G$.sloc({ tolerant: true }));
};

const size = (done, params) => {
    if (params.project) {
        console.log(`Source Lines of Code: ${colors.green(params.project)}`);
        return gulp.src(mapPaths(settings.runtimeFiles, params.project)).pipe(G$.size({ showFiles: true }));
    }

    console.log(`Source Lines of Code: ${colors.white('ALL')}`);
    return gulp.src(expandGlobs(settings.runtimeFiles)).pipe(G$.size({ showFiles: true }));
};

/* Deployment */
const cleanDist = () => del('dist');

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

const setupPackage = () =>
    gulp.src('./temp/droplit-edge/package.json')
        .pipe(jeditor(json => {
            const localConfig = require('./temp/droplit-edge/localsettings.json'); // eslint-disable-line global-require
            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)
                    .filter(plugin => localConfig.plugins[plugin] && localConfig.plugins[plugin].enabled !== false)
                    .forEach(plugin => (json.dependencies[plugin] = `../../projects/${plugin}`));

            return json;
        }))
        .pipe(gulp.dest('temp/droplit-edge/'));

const preInstallDist = () => del('temp/droplit-edge/node_modules');

const installDist = done => runCommand('npm install', { cwd: 'temp/droplit-edge' }, done);

const packageTask = () => {
    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'));
};

const cleanTemp = () => del('temp');

/* Testing for improving package */
const prep = () => del(expandGlobs(settings.prep));

/* Version bumb */
const bump = (done, params) => {
    if (!params.project) {
        console.error(`${colors.red('No project specified!')}`);
        return done();
    }
    const typeFlags = { 1: 'major', 2: 'minor', 4: 'patch' };
    const typeValue = (params.hasOwnProperty('major') << 0) + (params.hasOwnProperty('minor') << 1) + (params.hasOwnProperty('patch') << 2);
    const typeName = typeFlags[typeValue];
    if (!typeName) {
        console.error(`${colors.red('Specify one version type to bump!')}`);
        return done();
    }

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

/* Configure tasks */
gulp.task('install', install);
gulp.task('install').description = 'Install all npm modules';

gulp.task('link', link);
gulp.task('link').description = 'Link dependencies on local disk';

gulp.task('unlink', unlink);
gulp.task('unlink').description = 'Unlink dependencies on local disk';

gulp.task('clean', clean);
gulp.task('clean').description = 'Cleans the generated files from lib directory';

gulp.task('deep-clean', deepClean);
gulp.task('deep-clean').description = 'Cleans the generated files from lib directory and all node_modules';

gulp.task('setup', gulp.series('install', 'link'));
gulp.task('setup').description = 'Install all modules and link projects';

gulp.task('teardown', gulp.series('unlink', 'deep-clean'));
gulp.task('teardown').description = 'Clean all and unlink projects';

gulp.task('tslint', tslint);
gulp.task('tslint').description = 'Lints all TypeScript source files';

// Make project specific tasks
gulp.task('ts-all', gulp.series(transpileProjects(projectNames)));
gulp.task('ts-all').description = 'Transpile all projects';

projectNames.forEach(project => {
    gulp.task(`ts-${project}`, transpileProjects([project]));
    gulp.task(`ts-${project}`).description = `Transpile ${colors.green(project)}`;
});

gulp.task('build', gulp.series(gulp.parallel('tslint', 'clean'), 'ts-all'));
gulp.task('build').description = 'Compiles all TypeScript source files and updates module references';

gulp.task('watch', gulp.series('build', watch));
gulp.task('watch').description = 'Contiuous build';

gulp.task('debug', debug);
gulp.task('debug').description = 'Debug droplit-edge';

const installFlags = {
    '--pack': 'Package name',
    '--project': `Project name: (ex. ${colors.green(projectNames[0])})`
};

gulp.task('npm-i', parameterized(npmInstall));
gulp.task('npm-i').description = `Install and save a ${colors.cyan('pack')}age to a ${colors.cyan('project')}`;
gulp.task('npm-i').flags = installFlags;

gulp.task('npm-u', parameterized(npmUninstall));
gulp.task('npm-u').description = `Uninstall and save a ${colors.cyan('pack')}age to a ${colors.cyan('project')}`;
gulp.task('npm-u').flags = installFlags;

const projFlags = { '--project': `Project name: (ex. ${colors.green(projectNames[0])}}` };

gulp.task('stats', parameterized(stats));
gulp.task('stats').description = 'Get lines of code';
gulp.task('stats').flags = projFlags;

gulp.task('size', parameterized(size));
gulp.task('size').description = 'Get physical size of code';
gulp.task('size').flags = projFlags;

gulp.task('deploy', gulp.series('setup', cleanDist, 'build', 'unlink', moveTemp, setupPackage, preInstallDist, installDist, packageTask, cleanTemp));
gulp.task('deploy').description = 'Glob the Droplit Edge for embedding';

gulp.task('prep', prep);

gulp.task('bump', parameterized(bump));
gulp.task('bump').description = 'Version bump a project';
gulp.task('bump').flags = {
    '--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: (ex. ${colors.green(projectNames[0])})`
};

gulp.task('default', done => runCommand('gulp --tasks', { cwd: './' }, done));

/* Auxiliary functions */
function expandGlobs(globs) {
    return globs.reduce((p, c) =>
        p.concat(...(
            (c.indexOf(PROJECT_VAR) > 0) ? projectNames.map(name => c.replace(PROJECT_VAR, name)) : [c])
        ), []);
}

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

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

function mapPaths(globs, project) {
    return globs.map(glob => mapPath(glob, project));
}

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

function wildcardPaths(globs) {
    return globs.reduce((p, c) =>
        p.concat((c.indexOf(PROJECT_VAR) > 0) ? c.replace(PROJECT_VAR, '*') : c), []);
}<commit_msg>Fix transpile does not emit if projects in path<commit_after>const gulp = require('gulp');
const parameterized = require('gulp-parameterized');

const colors = require('ansi-colors');
const del = require('del');
const { exec } = require('child_process');
const merge = require('merge2');
const path = require('path');

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

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

const PROJECT_VAR = '{project}';

/* npm install */
const install = done => {
    gulp.parallel(
        [undefined].concat(...projectNames)
            .map(command => {
                const run = cb =>
                    runCommand('npm install', { cwd: command ? `projects/${command}` : undefined }, cb);
                run.displayName = `install-${command || 'root'}`;
                return run;
            })
    )(done);
};

/* npm link */
const link = done => { linker(true, done); };

const unlink = done => { linker(false, done); };

const linker = (mode, done) => {
    const projectLinks = projectNames.map(project => {
        const linkPhrase = mode ? 'link' : 'unlink';
        const run = cb =>
            runCommand(`npm ${linkPhrase} --no-bin-links`, { cwd: `projects/${project}` }, cb);
        run.displayName = `${linkPhrase}-${project}`;
        return run;
    });

    const tasks = [gulp.parallel(projectLinks)];
    if (mode) {
        const dependencyLinks = projectNames
            .filter(p => projects[p].hasOwnProperty('dependencies'))
            .reduce((p, c) =>
                p.concat(...projects[c].dependencies.map(dependency => {
                    const { name } = require(`./projects/${dependency}/package.json`); // eslint-disable-line global-require
                    const run = cb =>
                        runCommand(`npm link ${name} --no-bin-links`, { cwd: `projects/${c}` }, cb);
                    run.displayName = `link:${name}->${c}`;
                    return run;
                })), []
            );
        if (dependencyLinks.length > 0)
            tasks.push(dependencyLinks);
    }

    gulp.series(tasks)(done);
};

/* Cleaning */
const clean = () => del(expandGlobs(settings.clean));

const deepClean = () => del(expandGlobs(settings.deepClean));

/* Building */
const tslint = () =>
    gulp.src(wildcardPaths(settings.tsfiles))
        .pipe(G$.tslint({ formatter: 'verbose' }))
        .pipe(G$.tslint.report({ emitError: false }));

/* Transpiling */
const transpileProjects = projects => () => {
    const jsSources = Array.from(new Set(projects.reduce((globs, project) => globs.concat(mapPaths(settings.jsFiles, project)), [])));
    const tsSources = Array.from(new Set(projects.reduce((globs, project) => globs.concat(mapPaths(settings.tsfiles, project)), [])));
    const resources = Array.from(new Set(projects.reduce((globs, project) => globs.concat(mapPaths(settings.resources, project)), [])));

    const tsResult = gulp.src(tsSources)
        .pipe(G$.sourcemaps.init())
        .pipe(G$.typescript.createProject(tsconfig.compilerOptions)());

    const destTrans = file =>
        path.relative(file.cwd, file.base).replace(/projects(?:\\|\/)(.+?)(?:\\|\/)src(?:\\|\/.+)?/, 'projects\/$1\/lib\/');

    return merge([
        tsResult.dts.pipe(gulp.dest(destTrans)),
        tsResult.js // separate .js.map files
            .pipe(G$.sourcemaps.write('.'))
            .pipe(gulp.dest(destTrans)),
        // JS files
        gulp.src(jsSources)
            .pipe(G$.babel({ presets: ['es2015'] }))
            .pipe(gulp.dest(destTrans)),
        // all other files
        gulp.src(resources).pipe(gulp.dest(destTrans))
    ]);
};

const watch = () => {
    projectNames.forEach(project =>
        gulp.watch(mapPaths(Array.prototype.concat(settings.tsfiles, settings.jsFiles), project), gulp.parallel(`ts-${project}`)));
};

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

/* Dependencies */
const npmInstall = (done, params) => {
    if (!params.pack || !params.project) {
        console.error('Must specify a package and project');
        return done();
    }

    runCommand(`npm install --save ${params.pack}`, { cwd: mapPath(settings.projectPath, params.project) }, done);
};

const npmUninstall = (done, params) => {
    if (!params.pack || !params.project) {
        console.error('Must specify a package and project');
        return done();
    }

    runCommand(`npm uninstall --save ${params.pack}`, { cwd: mapPath(settings.projectPath, params.project) }, done);
};

/* Code analysis */
const stats = (done, params) => {
    if (params.project) {
        console.log(`Source Lines of Code: ${colors.green(params.project)}`);
        return gulp.src(mapPaths(settings.sloc_project, params.project)).pipe(G$.sloc({ tolerant: true }));
    }

    console.log(`Source Lines of Code: ${colors.white('ALL')}`);
    return gulp.src(settings.sloc_all).pipe(G$.sloc({ tolerant: true }));
};

const size = (done, params) => {
    if (params.project) {
        console.log(`Source Lines of Code: ${colors.green(params.project)}`);
        return gulp.src(mapPaths(settings.runtimeFiles, params.project)).pipe(G$.size({ showFiles: true }));
    }

    console.log(`Source Lines of Code: ${colors.white('ALL')}`);
    return gulp.src(expandGlobs(settings.runtimeFiles)).pipe(G$.size({ showFiles: true }));
};

/* Deployment */
const cleanDist = () => del('dist');

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

const setupPackage = () =>
    gulp.src('./temp/droplit-edge/package.json')
        .pipe(jeditor(json => {
            const localConfig = require('./temp/droplit-edge/localsettings.json'); // eslint-disable-line global-require
            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)
                    .filter(plugin => localConfig.plugins[plugin] && localConfig.plugins[plugin].enabled !== false)
                    .forEach(plugin => (json.dependencies[plugin] = `../../projects/${plugin}`));

            return json;
        }))
        .pipe(gulp.dest('temp/droplit-edge/'));

const preInstallDist = () => del('temp/droplit-edge/node_modules');

const installDist = done => runCommand('npm install', { cwd: 'temp/droplit-edge' }, done);

const packageTask = () => {
    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'));
};

const cleanTemp = () => del('temp');

/* Testing for improving package */
const prep = () => del(expandGlobs(settings.prep));

/* Version bumb */
const bump = (done, params) => {
    if (!params.project) {
        console.error(`${colors.red('No project specified!')}`);
        return done();
    }
    const typeFlags = { 1: 'major', 2: 'minor', 4: 'patch' };
    const typeValue = (params.hasOwnProperty('major') << 0) + (params.hasOwnProperty('minor') << 1) + (params.hasOwnProperty('patch') << 2);
    const typeName = typeFlags[typeValue];
    if (!typeName) {
        console.error(`${colors.red('Specify one version type to bump!')}`);
        return done();
    }

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

/* Configure tasks */
gulp.task('install', install);
gulp.task('install').description = 'Install all npm modules';

gulp.task('link', link);
gulp.task('link').description = 'Link dependencies on local disk';

gulp.task('unlink', unlink);
gulp.task('unlink').description = 'Unlink dependencies on local disk';

gulp.task('clean', clean);
gulp.task('clean').description = 'Cleans the generated files from lib directory';

gulp.task('deep-clean', deepClean);
gulp.task('deep-clean').description = 'Cleans the generated files from lib directory and all node_modules';

gulp.task('setup', gulp.series('install', 'link'));
gulp.task('setup').description = 'Install all modules and link projects';

gulp.task('teardown', gulp.series('unlink', 'deep-clean'));
gulp.task('teardown').description = 'Clean all and unlink projects';

gulp.task('tslint', tslint);
gulp.task('tslint').description = 'Lints all TypeScript source files';

// Make project specific tasks
gulp.task('ts-all', gulp.series(transpileProjects(projectNames)));
gulp.task('ts-all').description = 'Transpile all projects';

projectNames.forEach(project => {
    gulp.task(`ts-${project}`, transpileProjects([project]));
    gulp.task(`ts-${project}`).description = `Transpile ${colors.green(project)}`;
});

gulp.task('build', gulp.series(gulp.parallel('tslint', 'clean'), 'ts-all'));
gulp.task('build').description = 'Compiles all TypeScript source files and updates module references';

gulp.task('watch', gulp.series('build', watch));
gulp.task('watch').description = 'Contiuous build';

gulp.task('debug', debug);
gulp.task('debug').description = 'Debug droplit-edge';

const installFlags = {
    '--pack': 'Package name',
    '--project': `Project name: (ex. ${colors.green(projectNames[0])})`
};

gulp.task('npm-i', parameterized(npmInstall));
gulp.task('npm-i').description = `Install and save a ${colors.cyan('pack')}age to a ${colors.cyan('project')}`;
gulp.task('npm-i').flags = installFlags;

gulp.task('npm-u', parameterized(npmUninstall));
gulp.task('npm-u').description = `Uninstall and save a ${colors.cyan('pack')}age to a ${colors.cyan('project')}`;
gulp.task('npm-u').flags = installFlags;

const projFlags = { '--project': `Project name: (ex. ${colors.green(projectNames[0])}}` };

gulp.task('stats', parameterized(stats));
gulp.task('stats').description = 'Get lines of code';
gulp.task('stats').flags = projFlags;

gulp.task('size', parameterized(size));
gulp.task('size').description = 'Get physical size of code';
gulp.task('size').flags = projFlags;

gulp.task('deploy', gulp.series('setup', cleanDist, 'build', 'unlink', moveTemp, setupPackage, preInstallDist, installDist, packageTask, cleanTemp));
gulp.task('deploy').description = 'Glob the Droplit Edge for embedding';

gulp.task('prep', prep);

gulp.task('bump', parameterized(bump));
gulp.task('bump').description = 'Version bump a project';
gulp.task('bump').flags = {
    '--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: (ex. ${colors.green(projectNames[0])})`
};

gulp.task('default', done => runCommand('gulp --tasks', { cwd: './' }, done));

/* Auxiliary functions */
function expandGlobs(globs) {
    return globs.reduce((p, c) =>
        p.concat(...(
            (c.indexOf(PROJECT_VAR) > 0) ? projectNames.map(name => c.replace(PROJECT_VAR, name)) : [c])
        ), []);
}

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

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

function mapPaths(globs, project) {
    return globs.map(glob => mapPath(glob, project));
}

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

function wildcardPaths(globs) {
    return globs.reduce((p, c) =>
        p.concat((c.indexOf(PROJECT_VAR) > 0) ? c.replace(PROJECT_VAR, '*') : c), []);
}<|endoftext|>


<commit_before>/*
 * Copyright (C) 2014 Scott Beck, all rights reserved
 *
 * Licensed under the MIT license
 *
 */
 /* jshint debug: true, strict: true */
(function () {
  'use strict';
  var gulp = require('gulp'),
     gutil = require('gulp-util'),
         $ = require('gulp-load-plugins')(),
       del = require('del'),
      path = require("path"),
      exec = require('child_process').exec,
       pkg = require("./package.json"),
    tinylr = require("tiny-lr");

  var c9WSHost = (pkg.c9.appName || pkg.name) + '-' + pkg.c9.user + '.c9.io';
  var c9Url = 'https://' + (pkg.c9.appName || pkg.name) + '-' + pkg.c9.user + '.c9.io';
  var livereloadUrl = c9Url + '/livereload.js?host=' + c9WSHost + '&port=443';
  var files = {
    docsDest: path.join(process.cwd(), '/docs/dex/' + pkg.version),
    lintSrc: ['./gulpfile.js', './index.js', './lib/**/*.js', 'test/**/*.js', 'bin/*.js'],
    testSrc: ['test/*helper.js', 'test/*spec.js']
  };
  var options = {
    jsdoc: {
      cmd: [
        require.resolve('jsdoc/jsdoc.js'),
        '--configure ./config/jsdoc.json',
        '--verbose',
        '--pedantic',
        '--readme ./README.md',
        '--package ./package.json',
        '--destination ./docs'
      ]
    }
  };
  var tinyLrServer;

  function runCoverage (opts) {
    return gulp.src(files.testSrc, { read: false })
      .pipe($.coverage.instrument({
        pattern: ['./lib/**/*.js'],
        debugDirectory: 'debug'}))
      .pipe($.plumber())
      .pipe($.mocha({reporter: 'spec'})
            .on('error', function (err) { console.log("test error: " + err); this.emit('end'); })) // test errors dropped
      .pipe($.plumber.stop())
      .pipe($.coverage.gather())
      .pipe($.coverage.format(opts));
  }

  gulp.task("clean", function (done) {
    del(["coverage/**/*", "coverage", "debug/**/*", "debug"], done);
  });

  gulp.task('clean-docs', function (done) {
    del(['./docs/**/*'], done);
  });
  gulp.task("lint", function () {
    return gulp.src(files.lintSrc)
      .pipe($.jshint())
      .pipe($.jshint.reporter(require('jshint-table-reporter')));
  });

  gulp.task('docs', ['clean-docs'], function (done) {
    exec(options.jsdoc.cmd.join(' '), function (err, stdout, stderr) {
      gutil.log(stdout);
      gutil.log(stderr);
      if (err) return done(err);
      gulp.src('favicon.ico')
        .pipe(gulp.dest(files.docsDest))
        .on('end', done);
    });
  });
  gulp.task('publish-docs', ['docs'], function () {
    return gulp.src('./docs/dex/**/*', {
        base: files.docsDest
      })
      .pipe($.ghPages());
  });
  gulp.task('test', ['lint'], function () {
    return gulp.src(files.testSrc, {read: false})
      .pipe($.plumber())
      .pipe($.mocha({reporter: 'spec'}).on('error', function (err) { console.log("test error: " + err); this.emit('end'); })) // test errors dropped
      .pipe($.plumber.stop());
  });
  gulp.task('coveralls', ['lint'], function () {
    return runCoverage({reporter: 'lcov'})
      .pipe($.coveralls());
  });
  gulp.task('coverage', ['lint'], function () {
    return runCoverage({outFile: './index.html'})
      /*.pipe($.tap(function (file) {
        file.contents = new Buffer(
          file
            .contents
            .toString()
            .replace(
              /<\/\s*body\s*>\s*(?:<\s*\/html\s*>)?\s*$/,
              ''
            )
        );
        if (tinyLrServer) {
          tinyLrServer.changed({body: { files : file.path }});
        }
      }))*/
      .pipe(gulp.dest('coverage'));
  });
  gulp.task('connect-coverage', ['coverage'], function () {
    $.connect.server({
      root: 'coverage',
      noServer: true,
      https: false,
      port: process.env.PORT,
      host: process.env.IP,
      livereload: { port: process.env.PORT, src: livereloadUrl },
      middleware: function (connect, opt) {
        tinyLrServer = tinylr({app: connect});
        return [
          connect.static(path.join(__dirname, 'coverage')),
          function (req, res, next) {
            console.log("in tinylr request");
            tinyLrServer.handle(req, res, next);
          }
        ];
      }
    });
  });
  gulp.task('watch', function () {
    gulp.watch([files.lintSrc], ['test']);
  });

  gulp.task("default", ['test', "watch"]);
})();
<commit_msg>removed unused tasks. renamed files to paths to be more inline with Gulp style. added watch-coverage to help move forward coverage tests<commit_after>/*
 * Copyright (C) 2014 Scott Beck, all rights reserved
 *
 * Licensed under the MIT license
 *
 */
 /* jshint debug: true, strict: true */
(function () {
  'use strict';
  var gulp = require('gulp'),
     gutil = require('gulp-util'),
         $ = require('gulp-load-plugins')(),
       del = require('del'),
      path = require("path"),
      exec = require('child_process').exec,
       pkg = require("./package.json"),
    tinylr = require("tiny-lr");

  var c9WSHost = (pkg.c9.appName || pkg.name) + '-' + pkg.c9.user + '.c9.io';
  var c9Url = 'https://' + (pkg.c9.appName || pkg.name) + '-' + pkg.c9.user + '.c9.io';
  var livereloadUrl = c9Url + '/livereload.js?host=' + c9WSHost + '&port=443';
  var paths = {
    docsDest: path.join(process.cwd(), '/docs/dex/' + pkg.version),
    lintSrc: ['gulpfile.js', 'index.js', 'lib/**/*.js', 'test/**/*.js'],
    testSrc: ['test/*helper.js', 'test/*spec.js']
  };
  var options = {
    jsdoc: {
      cmd: [
        require.resolve('jsdoc/jsdoc.js'),
        '--configure ./config/jsdoc.json',
        '--verbose',
        '--pedantic',
        '--readme ./README.md',
        '--package ./package.json',
        '--destination ./docs'
      ]
    }
  };
  var tinyLrServer;

  function runCoverage (opts) {
    return gulp.src(paths.testSrc, { read: false })
      .pipe($.coverage.instrument({
        pattern: ['./lib/**/*.js'],
        debugDirectory: 'debug'}))
      .pipe($.plumber())
      .pipe($.mocha({reporter: 'spec'})
            .on('error', function (err) { console.log("test error: " + err); this.emit('end'); })) // test errors dropped
      .pipe($.plumber.stop())
      .pipe($.coverage.gather())
      .pipe($.coverage.format(opts));
  }

  gulp.task("clean", function (done) {
    del(["coverage/**/*", "coverage", "debug/**/*", "debug"], done);
  });

  gulp.task('clean-docs', function (done) {
    del(['./docs/**/*'], done);
  });
  gulp.task("lint", function () {
    return gulp.src(paths.lintSrc)
      .pipe($.jshint())
      .pipe($.jshint.reporter(require('jshint-table-reporter')));
  });

  gulp.task('docs', ['clean-docs'], function (done) {
    exec(options.jsdoc.cmd.join(' '), function (err, stdout, stderr) {
      gutil.log(stdout);
      gutil.log(stderr);
      if (err) return done(err);
      gulp.src('favicon.ico')
        .pipe(gulp.dest(paths.docsDest))
        .on('end', done);
    });
  });
  gulp.task('publish-docs', ['docs'], function () {
    return gulp.src('./docs/dex/**/*', {
        base: paths.docsDest
      })
      .pipe($.ghPages());
  });
  gulp.task('test', ['lint'], function () {
    return gulp.src(paths.testSrc, {read: false})
      .pipe($.plumber())
      .pipe($.mocha({reporter: 'spec'}).on('error', function (err) { console.log("test error: " + err); this.emit('end'); })) // test errors dropped
      .pipe($.plumber.stop());
  });
  gulp.task('coveralls', ['lint'], function () {
    return runCoverage({reporter: 'lcov'})
      .pipe($.coveralls());
  });
  gulp.task('coverage', ['lint'], function () {
    return runCoverage({outFile: './index.html'})
      .pipe(gulp.dest('coverage'));
  });
  gulp.task('watch-coverage', function () {
    gulp.watch(paths.lintSrc, ['coverage']);
  });
  gulp.task('watch', function () {
    gulp.watch(paths.lintSrc, ['test']);
  });

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


<commit_before>var gulp = require('gulp');
var gutil = require('gulp-util');
var buffer = require('vinyl-buffer');
var source = require('vinyl-source-stream');

var path = require('path');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var del = require('del');
var run = require('gulp-run');

gulp.task('clean', clean);
gulp.task('build', build);
gulp.task('test', test);
gulp.task('release', ['clean', 'build', 'test']);
gulp.task('default', watch);

function watch() {
  gulp.watch('src/**/*.js', ['build']);
}

function clean(cb) {
  del(['dist'], cb);
}

function test() {
  new run.Command('npm test').exec();
}

function build() {
  var bundler = require('browserify')('./src/viva.js', {
    standalone: 'Viva'
  });
  var bundle = bundler.bundle()
    .on('error', showError);

  bundle.pipe(source('vivagraph.js'))
    .pipe(buffer())
    .pipe(gulp.dest('./dist/'))
    .pipe(rename('vivagraph.min.js'))
    .pipe(uglify())
    .pipe(gulp.dest('./dist/'));

  function showError(err) {
    gutil.log(gutil.colors.red('Failed to browserify'), gutil.colors.yellow(err.message));
  }
}

function getFiles() {
  // todo: this will be changed when we move to commonjs
  return [ // core
    "Utils/etc.js",
    "Utils/browserInfo.js",
    "Utils/indexOf.js",
    "Utils/getDimensions.js",
    "Utils/events.js",
    "Input/spatialIndex.js", // TODO: Do I need this for SVG?
    "Utils/timer.js",
    "Utils/geom.js",

    "Core/primitives.js",
    "Core/graph.js",
    "Core/operations.js",

    "Physics/primitives.js",
    "Physics/eulerIntegrator.js",
    "Physics/Forces/nbodyForce.js",
    "Physics/Forces/dragForce.js",
    "Physics/Forces/springForce.js",
    "Physics/forceSimulator.js",
    "Layout/forceDirected.js",
    "Layout/constant.js",
    "View/renderer.js",
    // extra
    "Core/serializer.js",
    "Algorithms/centrality.js",
    "Algorithms/Community/community.js",
    "Algorithms/Community/slpa.js",
    "Core/generator.js",
    // svg
    "View/svgGraphics.js",
    "View/svgNodeFactory.js",
    // webgl
    "WebGL/webgl.js",
    "WebGL/webglUIModels.js",
    "WebGL/webglNodeProgram.js",
    "WebGL/webglLinkProgram.js",
    "WebGL/webglImageNodeProgram.js",
    "View/webglGraphics.js",
    "WebGL/webglInputEvents.js",
    "Input/webglInputManager.js"].map(toSrcFolder);
}

function toSrcFolder(name) {
  return path.join('src', name);
}
<commit_msg>Tests should execute after the build<commit_after>var gulp = require('gulp');
var gutil = require('gulp-util');
var buffer = require('vinyl-buffer');
var source = require('vinyl-source-stream');

var path = require('path');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var del = require('del');
var run = require('gulp-run');

gulp.task('clean', clean);
gulp.task('build', build);
gulp.task('test', test);
gulp.task('release', ['clean', 'build'], test);
gulp.task('default', watch);

function watch() {
  gulp.watch('src/**/*.js', ['build']);
}

function clean(cb) {
  del(['dist'], cb);
}

function test() {
  new run.Command('npm test').exec();
}

function build() {
  var bundler = require('browserify')('./src/viva.js', {
    standalone: 'Viva'
  });
  var bundle = bundler.bundle()
    .on('error', showError);

  bundle.pipe(source('vivagraph.js'))
    .pipe(buffer())
    .pipe(gulp.dest('./dist/'))
    .pipe(rename('vivagraph.min.js'))
    .pipe(uglify())
    .pipe(gulp.dest('./dist/'));

  function showError(err) {
    gutil.log(gutil.colors.red('Failed to browserify'), gutil.colors.yellow(err.message));
  }
}

function getFiles() {
  // todo: this will be changed when we move to commonjs
  return [ // core
    "Utils/etc.js",
    "Utils/browserInfo.js",
    "Utils/indexOf.js",
    "Utils/getDimensions.js",
    "Utils/events.js",
    "Input/spatialIndex.js", // TODO: Do I need this for SVG?
    "Utils/timer.js",
    "Utils/geom.js",

    "Core/primitives.js",
    "Core/graph.js",
    "Core/operations.js",

    "Physics/primitives.js",
    "Physics/eulerIntegrator.js",
    "Physics/Forces/nbodyForce.js",
    "Physics/Forces/dragForce.js",
    "Physics/Forces/springForce.js",
    "Physics/forceSimulator.js",
    "Layout/forceDirected.js",
    "Layout/constant.js",
    "View/renderer.js",
    // extra
    "Core/serializer.js",
    "Algorithms/centrality.js",
    "Algorithms/Community/community.js",
    "Algorithms/Community/slpa.js",
    "Core/generator.js",
    // svg
    "View/svgGraphics.js",
    "View/svgNodeFactory.js",
    // webgl
    "WebGL/webgl.js",
    "WebGL/webglUIModels.js",
    "WebGL/webglNodeProgram.js",
    "WebGL/webglLinkProgram.js",
    "WebGL/webglImageNodeProgram.js",
    "View/webglGraphics.js",
    "WebGL/webglInputEvents.js",
    "Input/webglInputManager.js"].map(toSrcFolder);
}

function toSrcFolder(name) {
  return path.join('src', name);
}
<|endoftext|>


<commit_before>require('shelljs/global');
var path = require('path');
var gulp = require('gulp');
var wrap = require('gulp-wrap');
var less = require('gulp-less');
var karma = require('gulp-karma');
var streamify = require('gulp-streamify');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var version = require('./bower').version;

gulp.task('scripts', function () {
  return browserify('./src/scripts/index.js')
    .bundle({standalone: 'sapphire'})
    .pipe(source('sapphire.js'))
    .pipe(streamify(wrap({src: './gulp/wrapper.jst'}, {
      version: version,
      deps: ['d3', 'strain']
    })))
    .pipe(gulp.dest("./build"));
});

gulp.task('scripts:debug', function () {
  return browserify('./src/scripts/index.js')
    .bundle({
      standalone: 'sapphire',
      debug: true
    })
    .pipe(source('sapphire.debug.js'))
    .pipe(gulp.dest("./build"));
});

gulp.task('styles', function () {
  return gulp
    .src('./src/styles/sapphire.less')
    .pipe(less())
    .pipe(gulp.dest('./build'));
});

gulp.task('test', ['scripts:debug', 'styles'], function() {
  return gulp
    .src([
      './bower_components/d3/d3.js',
      './bower_components/strain/strain.js',
      './build/sapphire.css',
      './build/sapphire.debug.js',
      './test/**/*.test.js'
    ])
    .pipe(karma({
      action: 'run',
      frameworks: ['mocha', 'chai'],
      reporters: ['mocha'],
      browsers: ['PhantomJS'],
      preprocessors: {
        './build/sapphire.debug.js': ['sourcemap']
      }
    }));
});

gulp.task('build', function () {
  gulp.start('scripts', 'scripts:debug', 'styles');
});

gulp.task('build:develop', function() {
  var branch = exec('git symbolic-ref --short HEAD', {silent: true})
    .output
    .trim();

  if (branch !== 'develop') { return; }

  gulp.start('build', function() {
    exec('git update-index --no-assume-unchanged ./build/*');
    exec('git add ./build');
    exec('git commit -m "Build"');
    exec('git update-index --assume-unchanged ./build/*');
  });
});

gulp.task('install', function() {
  if (!test('-d', './.git')) { return; }
  mkdir('-p', './.git/hooks');
  exec('git update-index --assume-unchanged ./build/*');

  ['post-commit', 'post-merge'].forEach(function(file) {
    file = path.join('./.git/hooks', file);

    ['#!/bin/sh', 'npm run-script build:develop']
      .join('\n')
      .to(file);

    chmod('+x', file);
  });
});

gulp.task('default', function () {
  gulp.start('build');
});

gulp.task('watch', function() {
  gulp.watch('src/scripts/**/*.js', ['scripts']);
});
<commit_msg>Use post-merge hook only<commit_after>require('shelljs/global');
var gulp = require('gulp');
var wrap = require('gulp-wrap');
var less = require('gulp-less');
var karma = require('gulp-karma');
var streamify = require('gulp-streamify');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var version = require('./bower').version;

gulp.task('scripts', function () {
  return browserify('./src/scripts/index.js')
    .bundle({standalone: 'sapphire'})
    .pipe(source('sapphire.js'))
    .pipe(streamify(wrap({src: './gulp/wrapper.jst'}, {
      version: version,
      deps: ['d3', 'strain']
    })))
    .pipe(gulp.dest("./build"));
});

gulp.task('scripts:debug', function () {
  return browserify('./src/scripts/index.js')
    .bundle({
      standalone: 'sapphire',
      debug: true
    })
    .pipe(source('sapphire.debug.js'))
    .pipe(gulp.dest("./build"));
});

gulp.task('styles', function () {
  return gulp
    .src('./src/styles/sapphire.less')
    .pipe(less())
    .pipe(gulp.dest('./build'));
});

gulp.task('test', ['scripts:debug', 'styles'], function() {
  return gulp
    .src([
      './bower_components/d3/d3.js',
      './bower_components/strain/strain.js',
      './build/sapphire.css',
      './build/sapphire.debug.js',
      './test/**/*.test.js'
    ])
    .pipe(karma({
      action: 'run',
      frameworks: ['mocha', 'chai'],
      reporters: ['mocha'],
      browsers: ['PhantomJS'],
      preprocessors: {
        './build/sapphire.debug.js': ['sourcemap']
      }
    }));
});

gulp.task('build', function () {
  gulp.start('scripts', 'scripts:debug', 'styles');
});

gulp.task('build:develop', function() {
  var branch = exec('git symbolic-ref --short HEAD', {silent: true})
    .output
    .trim();

  if (branch !== 'develop') { return; }

  gulp.start('build', function() {
    exec('git update-index --no-assume-unchanged ./build/*');
    exec('git add ./build');
    exec('git commit -m "Build"');
    exec('git update-index --assume-unchanged ./build/*');
  });
});

gulp.task('install', function() {
  if (!test('-d', './.git')) { return; }
  mkdir('-p', './.git/hooks');
  exec('git update-index --assume-unchanged ./build/*');

  var hookfile = './.git/hooks/post-merge';
  ['#!/bin/sh', 'npm run-script build:develop']
    .join('\n')
    .to(hookfile);
  chmod('+x', hookfile);
});

gulp.task('default', function () {
  gulp.start('build');
});

gulp.task('watch', function() {
  gulp.watch('src/scripts/**/*.js', ['scripts']);
});
<|endoftext|>


<commit_before>// Modules used in this project.
var gulp = require('gulp');
var sequence = require('run-sequence');
var bs = require('browser-sync').create();
var nunjucksRender = require('gulp-nunjucks-render');
var htmlhint = require('gulp-htmlhint');
var stylelint = require('gulp-stylelint');
var jshint = require('gulp-jshint');
var sort = require('gulp-sort');
var uncss = require('gulp-uncss');
var sourcemaps = require('gulp-sourcemaps');
var concat = require('gulp-concat');
var autoprefixer = require('gulp-autoprefixer');
var csso = require('gulp-csso');

// Relevant directories
var css = 'app/styles/**/*.css';
var js = 'app/scripts/*.js';
var njk = 'app/templates/**/*.njk';

// Dictionaries that are used in more than one place
var htmlHintRules = {
    "tagname-lowercase": true,
    "attr-lowercase": true,
    "attr-value-double-quotes": true,
    "attr-value-not-empty": true,
    "attr-no-duplication": true,
    "doctype-first": true,
    "tag-pair": true,
    "tag-self-close": true,
    "spec-char-escape": true,
    "id-unique": true,
    "src-not-empty": true,
    "title-require": true,
    "head-script-disabled": true,
    "alt-require": true,
    "doctype-html5": true,
    "id-class-value": "dash",
    "style-disabled": true,
    "inline-style-disabled": true,
    "inline-script-disabled": true,
    "space-tab-mixed-disabled": "space",
    "id-class-ad-disabled": true,
    "href-abs-or-rel": "rel",
    "attr-unsafe-chars": true
};

// Build web site from available content
gulp.task('build', function() {
    sequence('nunjucks', 'css', 'js');
});

// Setting up the Browser Sync server
gulp.task('browserSync', function() {
    bs.init({
        // Server base directory
        server:                 'dist',
        // Should all the screens connected to this server scroll together
        scrollProportionally:   false
    });
});

// Setting up the Browser Sync server
gulp.task('bsTunnel', function() {
    bs.init({
        // Server base directory
        server:                 'dist',
        // Try to connect to the tunnel service of the following name
        tunnel:                 'creativopty',
        // The manner in which the project opens once the server starts
        open:                   'tunnel',
        // Should all the screens connected to this server scroll together
        scrollProportionally:   false
    });
});

// Defining what should happen if any file changes
gulp.task('default', ['browserSync'], function() {
    // When a CSS file changes
    gulp.watch(css, ['css']);
    // When a JS file changes
    gulp.watch(js, ['js']);
    //When a Nunjucks file changes
    gulp.watch(njk, ['nunjucks']);
});

// Tasks done to css files
gulp.task('css', ['css-lint'], function() {
    return gulp.src(css)
        // Sort files in alphabetical order
        .pipe(sort())
        // Remove any unused CSS rules
        .pipe(uncss({ html: ['dist/**/*.html'] }))
        // Create a source map for future reference
        .pipe(sourcemaps.init())
            // Minify CSS
            .pipe(csso())
            // Combine all of the CSS files into one
            .pipe(concat('main.css'))
            // Prefix CSS rules for browser support
            .pipe(autoprefixer({ browsers: ['> 1%'] }))
        .pipe(sourcemaps.write())
        // Copy app file to dist
        .pipe(gulp.dest('dist/styles'))
        // Reload the dist file in the browser
        .pipe(bs.stream());
});

// Lint CSS files
gulp.task('css-lint', function() {
    return gulp.src([ css, '!' + css.replace('/**/*.css', '/library/**/*.css') ])
    // Use Stylelint to validate this CSS file
    .pipe(stylelint({
        failAfterError: true,
        reporters: [ { formatter: 'string', console: true } ]
    }));
});

// Tasks done to js files
gulp.task('js', function() {
    return gulp.src(js)
        // Sort files in alphabetical order
        .pipe(sort())
        // Use JS Hint to validate this JS file
        .pipe(jshint())
        // Report using JS Hint default reporter
        .pipe(jshint.reporter('default'))
        // Fail this task if there is an error
        .pipe(jshint.reporter('fail'))
        // Copy app file to dist
        .pipe(gulp.dest('dist/scripts'))
        // Reload the dist file in the browser
        .pipe(bs.stream());
});

// Convert Nunjucks templates into HTML files
gulp.task('nunjucks', function() {
    // Gets .html, .nunjucks, and .njk files in templates
    return gulp.src('app/templates/**/*.+(html|nunjucks|njk)')
    // Renders template with nunjucks
    .pipe(nunjucksRender({
        // Location of templates in the project
        path: ['app/templates/']
    }))
    // Use HTML Hint to validate the HTML file
    .pipe(htmlhint(htmlHintRules))
    // Fail this task if there is an error
    .pipe(htmlhint.failReporter())
    // Output files into the dist folder
    .pipe(gulp.dest('dist'))
    // Reload the dist file in the browser
    .pipe(bs.stream());
});
<commit_msg>Provide a pipeline for image assets<commit_after>// Modules used in this project.
var gulp = require('gulp');
var sequence = require('run-sequence');
var bs = require('browser-sync').create();
var nunjucksRender = require('gulp-nunjucks-render');
var htmlhint = require('gulp-htmlhint');
var stylelint = require('gulp-stylelint');
var jshint = require('gulp-jshint');
var sort = require('gulp-sort');
var uncss = require('gulp-uncss');
var sourcemaps = require('gulp-sourcemaps');
var concat = require('gulp-concat');
var autoprefixer = require('gulp-autoprefixer');
var csso = require('gulp-csso');

// Relevant directories
var css = 'app/styles/**/*.css';
var js = 'app/scripts/*.js';
var njk = 'app/templates/**/*.njk';
var img = 'app/images/**/*.+(jpg|png)';

// Dictionaries that are used in more than one place
var htmlHintRules = {
    "tagname-lowercase": true,
    "attr-lowercase": true,
    "attr-value-double-quotes": true,
    "attr-value-not-empty": true,
    "attr-no-duplication": true,
    "doctype-first": true,
    "tag-pair": true,
    "tag-self-close": true,
    "spec-char-escape": true,
    "id-unique": true,
    "src-not-empty": true,
    "title-require": true,
    "head-script-disabled": true,
    "alt-require": true,
    "doctype-html5": true,
    "id-class-value": "dash",
    "style-disabled": true,
    "inline-style-disabled": true,
    "inline-script-disabled": true,
    "space-tab-mixed-disabled": "space",
    "id-class-ad-disabled": true,
    "href-abs-or-rel": "rel",
    "attr-unsafe-chars": true
};

// Build web site from available content
gulp.task('build', function() {
    sequence('nunjucks', 'img', 'css', 'js');
});

// Setting up the Browser Sync server
gulp.task('browserSync', function() {
    bs.init({
        // Server base directory
        server:                 'dist',
        // Should all the screens connected to this server scroll together
        scrollProportionally:   false
    });
});

// Setting up the Browser Sync server
gulp.task('bsTunnel', function() {
    bs.init({
        // Server base directory
        server:                 'dist',
        // Try to connect to the tunnel service of the following name
        tunnel:                 'creativopty',
        // The manner in which the project opens once the server starts
        open:                   'tunnel',
        // Should all the screens connected to this server scroll together
        scrollProportionally:   false
    });
});

// Defining what should happen if any file changes
gulp.task('default', ['browserSync'], function() {
    // When a CSS file changes
    gulp.watch(css, ['css']);
    // When a JS file changes
    gulp.watch(js, ['js']);
    //When a Nunjucks file changes
    gulp.watch(njk, ['nunjucks']);
    // When an image changes
    gulp.watch(img, ['img']);
});

// Tasks done to css files
gulp.task('css', ['css-lint'], function() {
    return gulp.src(css)
        // Sort files in alphabetical order
        .pipe(sort())
        // Remove any unused CSS rules
        .pipe(uncss({ html: ['dist/**/*.html'] }))
        // Create a source map for future reference
        .pipe(sourcemaps.init())
            // Minify CSS
            .pipe(csso())
            // Combine all of the CSS files into one
            .pipe(concat('main.css'))
            // Prefix CSS rules for browser support
            .pipe(autoprefixer({ browsers: ['> 1%'] }))
        .pipe(sourcemaps.write())
        // Copy app file to dist
        .pipe(gulp.dest('dist/styles'))
        // Reload the dist file in the browser
        .pipe(bs.stream());
});

// Lint CSS files
gulp.task('css-lint', function() {
    return gulp.src([ css, '!' + css.replace('/**/*.css', '/library/**/*.css') ])
    // Use Stylelint to validate this CSS file
    .pipe(stylelint({
        failAfterError: true,
        reporters: [ { formatter: 'string', console: true } ]
    }));
});

// Tasks done to js files
gulp.task('js', function() {
    return gulp.src(js)
        // Sort files in alphabetical order
        .pipe(sort())
        // Use JS Hint to validate this JS file
        .pipe(jshint())
        // Report using JS Hint default reporter
        .pipe(jshint.reporter('default'))
        // Fail this task if there is an error
        .pipe(jshint.reporter('fail'))
        // Copy app file to dist
        .pipe(gulp.dest('dist/scripts'))
        // Reload the dist file in the browser
        .pipe(bs.stream());
});

// Convert Nunjucks templates into HTML files
gulp.task('nunjucks', function() {
    // Gets .html, .nunjucks, and .njk files in templates
    return gulp.src('app/templates/**/*.+(html|nunjucks|njk)')
    // Renders template with nunjucks
    .pipe(nunjucksRender({
        // Location of templates in the project
        path: ['app/templates/']
    }))
    // Use HTML Hint to validate the HTML file
    .pipe(htmlhint(htmlHintRules))
    // Fail this task if there is an error
    .pipe(htmlhint.failReporter())
    // Output files into the dist folder
    .pipe(gulp.dest('dist'))
    // Reload the dist file in the browser
    .pipe(bs.stream());
});

// Move the images files from the app folder to the distribution folder
gulp.task('img', function() {
    // Get the images from the app folder
    return gulp.src(img)
    // Output images into the distribution folder
    .pipe(gulp.dest('dist/images'))
    // Reload the distribution file in the browser
    .pipe(bs.stream());
});
<|endoftext|>


<commit_before>var gulp    = require('gulp');
var fs      = require('fs');
var plugins = require('gulp-load-plugins')();
var es      = require('event-stream');
var del     = require('del');

var publicFolderPath = '../public';

var paths = {
  appJavascript:     ['app/js/app.js', 'app/js/**/*.js'],
  appTemplates:      'app/js/**/*.tpl.html',
  appMainSass:       'app/scss/main.scss',
  appStyles:         'app/scss/**/*.scss',
  appImages:         'app/images/**/*',
  indexHtml:         'app/index.html',
  vendorJavascript:  ['vendor/js/angular.js', 'vendor/js/**/*.js'],
  vendorCss:         ['vendor/css/**/*.css'],
  finalAppJsPath:    '/js/app.js',
  finalAppCssPath:   '/css/app.css',
  specFolder:        ['spec/**/*_spec.js'],
  publicFolder:      publicFolderPath,
  publicJavascript:  publicFolderPath + '/js',
  publicAppJs:       publicFolderPath + '/js/app.js',
  publicCss:         publicFolderPath + '/css',
  publicImages:      publicFolderPath + '/images',
  publicIndex:       publicFolderPath + '/angular.html',
  publicJsManifest:  publicFolderPath + '/js/rev-manifest.json',
  publicCssManifest: publicFolderPath + '/css/rev-manifest.json'
};

gulp.task('scripts-dev', function() {
  return gulp.src(paths.vendorJavascript.concat(paths.appJavascript, paths.appTemplates))
    .pipe(plugins.if(/html$/, buildTemplates()))
    .pipe(plugins.sourcemaps.init())
    .pipe(plugins.concat('app.js'))
    .pipe(plugins.sourcemaps.write('.'))
    .pipe(gulp.dest(paths.publicJavascript));
});
gulp.task('scripts-prod', function() {
  return gulp.src(paths.vendorJavascript.concat(paths.appJavascript, paths.appTemplates))
    .pipe(plugins.if(/html$/, buildTemplates()))
    .pipe(plugins.concat('app.js'))
    .pipe(plugins.ngAnnotate())
    .pipe(plugins.uglify())
    .pipe(plugins.rev())
    .pipe(gulp.dest(paths.publicJavascript))
    .pipe(plugins.rev.manifest({path: 'rev-manifest.json'}))
    .pipe(gulp.dest(paths.publicJavascript));
});

gulp.task('styles-dev', function() {
  return gulp.src(paths.vendorCss.concat(paths.appMainSass))
    .pipe(plugins.if(/scss$/, plugins.sass()))
    .pipe(plugins.concat('app.css'))
    .pipe(gulp.dest(paths.publicCss));
});

gulp.task('styles-prod', function() {
  return gulp.src(paths.vendorCss.concat(paths.appMainSass))
    .pipe(plugins.if(/scss$/, plugins.sass()))
    .pipe(plugins.concat('app.css'))
    .pipe(plugins.minifyCss())
    .pipe(plugins.rev())
    .pipe(gulp.dest(paths.publicCss))
    .pipe(plugins.rev.manifest({path: 'rev-manifest.json'}))
    .pipe(gulp.dest(paths.publicCss));
});

gulp.task('images', function() {
  return gulp.src(paths.appImages)
    .pipe(gulp.dest(paths.publicImages));
});

gulp.task('indexHtml-dev', ['scripts-dev', 'styles-dev'], function() {
  var manifest = {
    js: paths.finalAppJsPath,
    css: paths.finalAppCssPath
  };

  return gulp.src(paths.indexHtml)
    .pipe(plugins.template({css: manifest['css'], js: manifest['js']}))
    .pipe(plugins.rename(paths.publicIndex))
    .pipe(gulp.dest(paths.publicFolder));
});

gulp.task('indexHtml-prod', ['scripts-prod', 'styles-prod'], function() {
  var jsManifest  = JSON.parse(fs.readFileSync(paths.publicJsManifest, 'utf8'));
  var cssManifest = JSON.parse(fs.readFileSync(paths.publicCssManifest, 'utf8'));

  var manifest = {
    js: jsManifest['app.js'],
    css: cssManifest['app.css']
  };

  return gulp.src(paths.indexHtml)
    .pipe(plugins.template({css: manifest['css'], js: manifest['js']}))
    .pipe(plugins.rename(paths.publicIndex))
    .pipe(gulp.dest(paths.publicFolder));
});

gulp.task('lint', function() {
  return gulp.src(paths.appJavascript.concat(paths.specFolder))
    .pipe(plugins.jshint())
    .pipe(plugins.jshint.reporter('jshint-stylish'));
});

gulp.task('testem', function() {
  return gulp.src(['']) // We don't need files, that is managed on testem.json
    .pipe(plugins.testem({
      configFile: 'testem.json'
    }));
});

gulp.task('clean', function(cb) {
  del([paths.publicJavascript, paths.publicImages, paths.publicCss, paths.publicIndex], {force: true}, cb);
});

gulp.task('watch', ['indexHtml-dev', 'images'], function() {
  gulp.watch(paths.appJavascript, ['lint', 'scripts-dev']);
  gulp.watch(paths.appTemplates, ['scripts-dev']);
  gulp.watch(paths.vendorJavascript, ['scripts-dev']);
  gulp.watch(paths.appImages, ['images-dev']);
  gulp.watch(paths.specFolder, ['lint']);
  gulp.watch(paths.indexHtml, ['indexHtml-dev']);
  gulp.watch(paths.appStyles, ['styles-dev']);
  gulp.watch(paths.vendorCss, ['styles-dev']);
});

gulp.task('default', ['watch']);
gulp.task('production', ['scripts-prod', 'styles-prod', 'images', 'indexHtml-prod']);

function buildTemplates() {
  return es.pipeline(
    plugins.minifyHtml({
      empty: true,
      spare: true,
      quotes: true
    }),
    plugins.angularTemplatecache({
      module: 'app'
    })
  );
}
<commit_msg>Fix asset paths on production<commit_after>var gulp    = require('gulp');
var fs      = require('fs');
var plugins = require('gulp-load-plugins')();
var es      = require('event-stream');
var del     = require('del');

var publicFolderPath = '../public';

var paths = {
  appJavascript:     ['app/js/app.js', 'app/js/**/*.js'],
  appTemplates:      'app/js/**/*.tpl.html',
  appMainSass:       'app/scss/main.scss',
  appStyles:         'app/scss/**/*.scss',
  appImages:         'app/images/**/*',
  indexHtml:         'app/index.html',
  vendorJavascript:  ['vendor/js/angular.js', 'vendor/js/**/*.js'],
  vendorCss:         ['vendor/css/**/*.css'],
  finalAppJsPath:    '/js/app.js',
  finalAppCssPath:   '/css/app.css',
  specFolder:        ['spec/**/*_spec.js'],
  publicFolder:      publicFolderPath,
  publicJavascript:  publicFolderPath + '/js',
  publicAppJs:       publicFolderPath + '/js/app.js',
  publicCss:         publicFolderPath + '/css',
  publicImages:      publicFolderPath + '/images',
  publicIndex:       publicFolderPath + '/angular.html',
  publicJsManifest:  publicFolderPath + '/js/rev-manifest.json',
  publicCssManifest: publicFolderPath + '/css/rev-manifest.json'
};

gulp.task('scripts-dev', function() {
  return gulp.src(paths.vendorJavascript.concat(paths.appJavascript, paths.appTemplates))
    .pipe(plugins.if(/html$/, buildTemplates()))
    .pipe(plugins.sourcemaps.init())
    .pipe(plugins.concat('app.js'))
    .pipe(plugins.sourcemaps.write('.'))
    .pipe(gulp.dest(paths.publicJavascript));
});
gulp.task('scripts-prod', function() {
  return gulp.src(paths.vendorJavascript.concat(paths.appJavascript, paths.appTemplates))
    .pipe(plugins.if(/html$/, buildTemplates()))
    .pipe(plugins.concat('app.js'))
    .pipe(plugins.ngAnnotate())
    .pipe(plugins.uglify())
    .pipe(plugins.rev())
    .pipe(gulp.dest(paths.publicJavascript))
    .pipe(plugins.rev.manifest({path: 'rev-manifest.json'}))
    .pipe(gulp.dest(paths.publicJavascript));
});

gulp.task('styles-dev', function() {
  return gulp.src(paths.vendorCss.concat(paths.appMainSass))
    .pipe(plugins.if(/scss$/, plugins.sass()))
    .pipe(plugins.concat('app.css'))
    .pipe(gulp.dest(paths.publicCss));
});

gulp.task('styles-prod', function() {
  return gulp.src(paths.vendorCss.concat(paths.appMainSass))
    .pipe(plugins.if(/scss$/, plugins.sass()))
    .pipe(plugins.concat('app.css'))
    .pipe(plugins.minifyCss())
    .pipe(plugins.rev())
    .pipe(gulp.dest(paths.publicCss))
    .pipe(plugins.rev.manifest({path: 'rev-manifest.json'}))
    .pipe(gulp.dest(paths.publicCss));
});

gulp.task('images', function() {
  return gulp.src(paths.appImages)
    .pipe(gulp.dest(paths.publicImages));
});

gulp.task('indexHtml-dev', ['scripts-dev', 'styles-dev'], function() {
  var manifest = {
    js: paths.finalAppJsPath,
    css: paths.finalAppCssPath
  };

  return gulp.src(paths.indexHtml)
    .pipe(plugins.template({css: manifest['css'], js: manifest['js']}))
    .pipe(plugins.rename(paths.publicIndex))
    .pipe(gulp.dest(paths.publicFolder));
});

gulp.task('indexHtml-prod', ['scripts-prod', 'styles-prod'], function() {
  var jsManifest  = JSON.parse(fs.readFileSync(paths.publicJsManifest, 'utf8'));
  var cssManifest = JSON.parse(fs.readFileSync(paths.publicCssManifest, 'utf8'));

  var manifest = {
    js: '/js/' + jsManifest['app.js'],
    css: '/css/' + cssManifest['app.css']
  };

  return gulp.src(paths.indexHtml)
    .pipe(plugins.template({css: manifest['css'], js: manifest['js']}))
    .pipe(plugins.rename(paths.publicIndex))
    .pipe(gulp.dest(paths.publicFolder));
});

gulp.task('lint', function() {
  return gulp.src(paths.appJavascript.concat(paths.specFolder))
    .pipe(plugins.jshint())
    .pipe(plugins.jshint.reporter('jshint-stylish'));
});

gulp.task('testem', function() {
  return gulp.src(['']) // We don't need files, that is managed on testem.json
    .pipe(plugins.testem({
      configFile: 'testem.json'
    }));
});

gulp.task('clean', function(cb) {
  del([paths.publicJavascript, paths.publicImages, paths.publicCss, paths.publicIndex], {force: true}, cb);
});

gulp.task('watch', ['indexHtml-dev', 'images'], function() {
  gulp.watch(paths.appJavascript, ['lint', 'scripts-dev']);
  gulp.watch(paths.appTemplates, ['scripts-dev']);
  gulp.watch(paths.vendorJavascript, ['scripts-dev']);
  gulp.watch(paths.appImages, ['images-dev']);
  gulp.watch(paths.specFolder, ['lint']);
  gulp.watch(paths.indexHtml, ['indexHtml-dev']);
  gulp.watch(paths.appStyles, ['styles-dev']);
  gulp.watch(paths.vendorCss, ['styles-dev']);
});

gulp.task('default', ['watch']);
gulp.task('production', ['scripts-prod', 'styles-prod', 'images', 'indexHtml-prod']);

function buildTemplates() {
  return es.pipeline(
    plugins.minifyHtml({
      empty: true,
      spare: true,
      quotes: true
    }),
    plugins.angularTemplatecache({
      module: 'app'
    })
  );
}
<|endoftext|>


<commit_before>var gulp = require('gulp');
var header = require('gulp-header');
var footer = require('gulp-footer');
var fileImports = require('gulp-imports');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var bump = require('gulp-bump');
var size = require('gulp-size');
var replace = require('gulp-replace');
var mochaPhantomJS = require('gulp-mocha-phantomjs');
var docco = require('gulp-docco');
var merge = require('merge-stream');
var ignore = require('gulp-ignore');
var rimraf = require('gulp-rimraf');
var moment = require('moment');
var _ = require('lodash');
var runSequence = require('run-sequence');
var fs = require('fs');
var extReplace = require('gulp-ext-replace');

var pkg = require('./package.json');
var reporter = 'list';
var statement = 'A solid footing for knockout applications.';
var args   = require('yargs').argv;
var annotatedPageMetaData = fs.readFileSync('docs/templates/annotated-metadata.html','utf8').replace('FOOTWORK_VERSION', pkg.version, 'g');

var banner = ['/**',
  ' * <%= pkg.name %> - <%= pkg.description %>',
  ' * Author: <%= pkg.author %>',
  ' * Version: v<%= pkg.version %>',
  ' * Url: <%= pkg.homepage %>',
  ' * License(s): <% pkg.licenses.forEach(function( license, idx ){ %><%= license.type %><% if(idx !== pkg.licenses.length-1) { %>, <% } %><% }); %>',
  ' */',
  '', ''
];

var rawBanner = [
  '// footwork.js',
  '// ----------------------------------',
  '// v<%= pkg.version %>',
  '//',
  '// Copyright (c)2014 <%= pkg.author %>.',
  '// Distributed under <% pkg.licenses.forEach(function( license, idx ){ %><%= license.type %><% if(idx !== pkg.licenses.length-1) { %>, <% } %><% }); %> license',
  '//',
  '// <%= pkg.homepage %>',
  '', ''
];

var build = function(buildProfile) {
  var headerBanner = banner.slice(0);
  if(buildProfile !== 'raw') {
    headerBanner[3] += '-' + buildProfile;
  }
  headerBanner = headerBanner.join('\n');

  if(buildProfile === 'raw') {
    headerBanner = rawBanner.join("\n") + headerBanner;
  }

  return gulp
    .src(['source/build-profile/' + buildProfile + '.js'])
    .pipe(header(headerBanner, { pkg: pkg }))
    .pipe(fileImports())
    .pipe(replace(/FOOTWORK_VERSION/g, pkg.version))
    .pipe(rename('footwork-' + buildProfile + '.js'))
    .pipe(size({ title: '[' + buildProfile + '] Unminified' }))
    .pipe(gulp.dest('dist/'))
    .pipe(uglify({
      compress: { negate_iife: false }
    }))
    .pipe(header(banner, { pkg: pkg }))
    .pipe(rename('footwork-' + buildProfile + '.min.js'))
    .pipe(size({ title: '[' + buildProfile + '] Minified' }))
    .pipe(size({ title: '[' + buildProfile + '] Minified', gzip: true }))
    .pipe(gulp.dest('dist/'));
};

gulp.task('default', ['build-and-test']);

gulp.task('bump', function () {
  return gulp.src(['./package.json', './bower.json'])
    .pipe(bump())
    .pipe(gulp.dest('./'));
});

// Testing tasks
gulp.task('ci', ['build-and-test']);

gulp.task('build-and-test', ['test_all', 'test_minimal', 'test_bare'], function() {
  return gulp
    .src('spec/runner_all.html')
    .pipe(mochaPhantomJS({ reporter: reporter }));
});

gulp.task('test_all', ['build_all'], function() {
  return gulp
    .src('spec/runner_all.html')
    .pipe(mochaPhantomJS({ reporter: reporter }));
});

gulp.task('test_minimal', ['build_minimal'], function() {
  return gulp
    .src('spec/runner_minimal.html')
    .pipe(mochaPhantomJS({ reporter: reporter }));
});

gulp.task('test_bare', ['build_bare'], function() {
  return gulp
    .src('spec/runner_bare.html')
    .pipe(mochaPhantomJS({ reporter: reporter }));
});

// Building tasks
gulp.task('build-everything', ['build_all', 'build_minimal', 'build_bare', 'build_raw']);

gulp.task('build_prep', function() {
  // we have to force load of lodash instead of underscore
  return gulp
    .src('bower_components/riveter/lib/riveter.js')
    .pipe(replace(/underscore/g, 'lodash'))
    .pipe(gulp.dest('./bower_components/riveter/lib'));
});

gulp.task('build_all', ['build_prep'], function() {
  return build('all');
});

gulp.task('build_minimal', ['build_prep'], function() {
  return build('minimal');
});

gulp.task('build_bare', ['build_prep'], function() {
  return build('bare');
});

gulp.task('build_raw', ['build_prep'], function() {
  return build('raw');
});

// Documentation / release oriented tasks
gulp.task('readyRelease', function(callback) {
  runSequence('set_version', 'build-everything', 'docs', callback);
});

gulp.task('docs', function(callback) {
  runSequence('docs_clean', 'doc_source_annotation', 'doc_js_build_info', callback);
});

gulp.task('docs_clean', function() {
  return merge(
    gulp.src('./docs/pages/annotated.html', { read: false }).pipe(rimraf())
  );
});

gulp.task('doc_source_annotation', function() {
  return gulp.src('dist/footwork-raw.js')
    .pipe(docco({
      // layout: 'parallel'
      template: 'docs/templates/docco.jst'
    }))
    .pipe(footer(annotatedPageMetaData))
    .pipe(rename('annotated.html'))
    .pipe(gulp.dest('docs/pages'));
});

gulp.task('doc_js_build_info', function() {
  return gulp.src('docs/templates/build-info.js')
    .pipe( replace('FOOTWORK_VERSION', pkg.version, 'g') )
    .pipe( replace('FOOTWORK_STATEMENT', statement, 'g') )
    .pipe( replace('FOOTWORK_BUILD_TIMESTAMP', moment().format(), 'g') )
    .pipe( replace('FOOTWORK_CONTRIBUTORS', JSON.stringify(pkg.contributors), 'g') )
    .pipe(gulp.dest('./docs'));
});

gulp.task('set_version', function() {
  var version = pkg.version;
  if(typeof args.ver !== 'undefined') {
    version = args.ver;
    pkg.version = version;
  }

  return merge(
    gulp.src(['docs/package.json', 'docs/bower.json'])
      .pipe(bump({ version: version }))
      .pipe(gulp.dest('./docs')),
    gulp.src(['./package.json', './bower.json'])
      .pipe(bump({ version: version }))
      .pipe(gulp.dest('./'))
  );
});

// tasks used to setup documentation page on server after new release
gulp.task('transformDocIndex', function(callback) {
  return gulp.src('docs/index.html')
    .pipe( replace('<!--FOOTWORK_CONTENT-->', '<?php App::loadView( isset( $bodyView ) ? $bodyView : DEFAULT_BODY_VIEW ); ?>') )
    .pipe(rename('index.php'))
    .pipe(gulp.dest('docs'));
});
gulp.task('removeDocIndexHTML', function() {
  return gulp.src('docs/index.html', { read: false }).pipe(rimraf());
});
gulp.task('removeDocTemplateHTML', function() {
  return gulp.src('docs/pages/*.html', { read: false }).pipe(rimraf());
});
gulp.task('changeDocTemplateExt', function() {
  return gulp.src('docs/pages/*.html')
    .pipe(extReplace('.php'))
    .pipe(gulp.dest('docs/pages'));
});
gulp.task('readyDocServ', function(callback) {
  runSequence('transformDocIndex', 'removeDocIndexHTML', 'changeDocTemplateExt', 'removeDocTemplateHTML');
});<commit_msg>docs updates<commit_after>var gulp = require('gulp');
var header = require('gulp-header');
var footer = require('gulp-footer');
var fileImports = require('gulp-imports');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var bump = require('gulp-bump');
var size = require('gulp-size');
var replace = require('gulp-replace');
var mochaPhantomJS = require('gulp-mocha-phantomjs');
var docco = require('gulp-docco');
var merge = require('merge-stream');
var ignore = require('gulp-ignore');
var rimraf = require('gulp-rimraf');
var moment = require('moment');
var _ = require('lodash');
var runSequence = require('run-sequence');
var fs = require('fs');
var extReplace = require('gulp-ext-replace');

var pkg = require('./package.json');
var reporter = 'list';
var statement = 'A solid footing for knockout applications.';
var args   = require('yargs').argv;
var annotatedPageMetaData = fs.readFileSync('docs/templates/annotated-metadata.html','utf8').replace('FOOTWORK_VERSION', pkg.version, 'g');

var banner = ['/**',
  ' * <%= pkg.name %> - <%= pkg.description %>',
  ' * Author: <%= pkg.author %>',
  ' * Version: v<%= pkg.version %>',
  ' * Url: <%= pkg.homepage %>',
  ' * License(s): <% pkg.licenses.forEach(function( license, idx ){ %><%= license.type %><% if(idx !== pkg.licenses.length-1) { %>, <% } %><% }); %>',
  ' */',
  '', ''
];

var rawBanner = [
  '// footwork.js',
  '// ----------------------------------',
  '// v<%= pkg.version %>',
  '//',
  '// Copyright (c)2014 <%= pkg.author %>.',
  '// Distributed under <% pkg.licenses.forEach(function( license, idx ){ %><%= license.type %><% if(idx !== pkg.licenses.length-1) { %>, <% } %><% }); %> license',
  '//',
  '// <%= pkg.homepage %>',
  '', ''
];

var build = function(buildProfile) {
  var headerBanner = banner.slice(0);
  if(buildProfile !== 'raw') {
    headerBanner[3] += '-' + buildProfile;
  }
  headerBanner = headerBanner.join('\n');

  if(buildProfile === 'raw') {
    headerBanner = rawBanner.join("\n") + headerBanner;
  }

  return gulp
    .src(['source/build-profile/' + buildProfile + '.js'])
    .pipe(header(headerBanner, { pkg: pkg }))
    .pipe(fileImports())
    .pipe(replace(/FOOTWORK_VERSION/g, pkg.version))
    .pipe(rename('footwork-' + buildProfile + '.js'))
    .pipe(size({ title: '[' + buildProfile + '] Unminified' }))
    .pipe(gulp.dest('dist/'))
    .pipe(uglify({
      compress: { negate_iife: false }
    }))
    .pipe(header(banner, { pkg: pkg }))
    .pipe(rename('footwork-' + buildProfile + '.min.js'))
    .pipe(size({ title: '[' + buildProfile + '] Minified' }))
    .pipe(size({ title: '[' + buildProfile + '] Minified', gzip: true }))
    .pipe(gulp.dest('dist/'));
};

gulp.task('default', ['build-and-test']);

gulp.task('bump', function () {
  return gulp.src(['./package.json', './bower.json'])
    .pipe(bump())
    .pipe(gulp.dest('./'));
});

// Testing tasks
gulp.task('ci', ['build-and-test']);

gulp.task('build-and-test', ['test_all', 'test_minimal', 'test_bare'], function() {
  return gulp
    .src('spec/runner_all.html')
    .pipe(mochaPhantomJS({ reporter: reporter }));
});

gulp.task('test_all', ['build_all'], function() {
  return gulp
    .src('spec/runner_all.html')
    .pipe(mochaPhantomJS({ reporter: reporter }));
});

gulp.task('test_minimal', ['build_minimal'], function() {
  return gulp
    .src('spec/runner_minimal.html')
    .pipe(mochaPhantomJS({ reporter: reporter }));
});

gulp.task('test_bare', ['build_bare'], function() {
  return gulp
    .src('spec/runner_bare.html')
    .pipe(mochaPhantomJS({ reporter: reporter }));
});

// Building tasks
gulp.task('build-everything', ['build_all', 'build_minimal', 'build_bare', 'build_raw']);

gulp.task('build_prep', function() {
  // we have to force load of lodash instead of underscore
  return gulp
    .src('bower_components/riveter/lib/riveter.js')
    .pipe(replace(/underscore/g, 'lodash'))
    .pipe(gulp.dest('./bower_components/riveter/lib'));
});

gulp.task('build_all', ['build_prep'], function() {
  return build('all');
});

gulp.task('build_minimal', ['build_prep'], function() {
  return build('minimal');
});

gulp.task('build_bare', ['build_prep'], function() {
  return build('bare');
});

gulp.task('build_raw', ['build_prep'], function() {
  return build('raw');
});

// Documentation / release oriented tasks
gulp.task('readyRelease', function(callback) {
  runSequence('set_version', 'build-everything', 'docs', callback);
});

gulp.task('docs', function(callback) {
  runSequence('docs_clean', 'doc_source_annotation', 'doc_js_build_info', callback);
});

gulp.task('docs_clean', function() {
  return merge(
    gulp.src('./docs/pages/annotated.html', { read: false }).pipe(rimraf())
  );
});

gulp.task('doc_source_annotation', function() {
  return gulp.src('dist/footwork-raw.js')
    .pipe(docco({
      // layout: 'parallel'
      template: 'docs/templates/docco.jst'
    }))
    .pipe(footer(annotatedPageMetaData))
    .pipe(rename('annotated.html'))
    .pipe(gulp.dest('docs/pages'));
});

gulp.task('doc_js_build_info', function() {
  return gulp.src('docs/templates/build-info.js')
    .pipe( replace('FOOTWORK_VERSION', pkg.version, 'g') )
    .pipe( replace('FOOTWORK_STATEMENT', statement, 'g') )
    .pipe( replace('FOOTWORK_BUILD_TIMESTAMP', moment().format(), 'g') )
    .pipe( replace('FOOTWORK_CONTRIBUTORS', JSON.stringify(pkg.contributors), 'g') )
    .pipe(gulp.dest('./docs'));
});

gulp.task('set_version', function() {
  var version = pkg.version;
  if(typeof args.ver !== 'undefined') {
    version = args.ver;
    pkg.version = version;
  }

  return merge(
    gulp.src(['docs/package.json', 'docs/bower.json'])
      .pipe(bump({ version: version }))
      .pipe(gulp.dest('./docs')),
    gulp.src(['./package.json', './bower.json'])
      .pipe(bump({ version: version }))
      .pipe(gulp.dest('./'))
  );
});

// tasks used to setup documentation page on server after new release
gulp.task('transformDocIndex', function(callback) {
  return gulp.src('docs/index.html')
    .pipe( replace('<!--FOOTWORK_CONTENT-->', '<?php App::loadView( isset( $bodyView ) ? $bodyView : DEFAULT_BODY_VIEW ); ?>') )
    .pipe(rename('index.php'))
    .pipe(gulp.dest('docs'));
});
gulp.task('removeDocIndexHTML', function() {
  return gulp.src('docs/index.html', { read: false }).pipe(rimraf());
});
gulp.task('removeDocTemplateHTML', function() {
  return gulp.src('docs/pages/*.html', { read: false }).pipe(rimraf());
});
gulp.task('changeDocTemplateExt', function() {
  return gulp.src('docs/pages/*.html')
    .pipe(extReplace('.php'))
    .pipe(gulp.dest('docs/pages'));
});
gulp.task('readyDocServ', function(callback) {
  runSequence('transformDocIndex', 'removeDocIndexHTML', 'changeDocTemplateExt');
});<|endoftext|>


<commit_before>const gulp = require('gulp');
const mocha = require('gulp-mocha');
const exec = require('child_process').exec;
const runSequence = require('run-sequence');

gulp.task('create-data-directory', function() {
  exec('mkdir -p data', function(err, stdout, stderr) {
    console.log(stdout);
  });
});

gulp.task('start-mongo', function() {
  exec('mongod --fork --syslog --dbpath=data --smallfiles', function(err, stdout, stderr) {
    console.log(stdout);
    console.log(stderr);
  });
});

gulp.task('stop-mongo', function() {
  exec('killall mongod', function(err, stdout, stderr) {
    console.log(stdout);
    console.log(stderr);
  });
});
//gulp.task('start-app', runCommand('node app.js'));

gulp.task('start-tests', () =>
  gulp.src('./test/*', {
    read: false
  })
  // gulp-mocha needs filepaths so you can't have any plugins before it
  .pipe(mocha())
  .once('error', () => {
    runSequence('stop-mongo');
  })
  .once('end', () => {
    runSequence('stop-mongo', 'quit');
  })
);

gulp.task('quit', function() {
  process.exit();
});

gulp.task('default', function() {
  runSequence('create-data-directory', 'start-mongo', 'start-tests', 'stop-mongo', 'quit');
});<commit_msg>Now make config file in Gulp to make Node happy.<commit_after>const gulp = require('gulp');
const mocha = require('gulp-mocha');
const exec = require('child_process').exec;
const runSequence = require('run-sequence');

gulp.task('create-data-directory', function() {
  exec('mkdir -p data', function(err, stdout, stderr) {
    console.log(stdout);
  });
});

gulp.task('create-config-file', function() {
  exec('touch config.js', function(err, stdout, stderr) {
    console.log(stdout);
  });
});

gulp.task('start-mongo', function() {
  exec('mongod --fork --syslog --dbpath=data --smallfiles', function(err, stdout, stderr) {
    console.log(stdout);
    console.log(stderr);
  });
});

gulp.task('stop-mongo', function() {
  exec('killall mongod', function(err, stdout, stderr) {
    console.log(stdout);
    console.log(stderr);
  });
});
//gulp.task('start-app', runCommand('node app.js'));

gulp.task('start-tests', () =>
  gulp.src('./test/*', {
    read: false
  })
  // gulp-mocha needs filepaths so you can't have any plugins before it
  .pipe(mocha())
  .once('error', () => {
    runSequence('stop-mongo');
  })
  .once('end', () => {
    runSequence('stop-mongo', 'quit');
  })
);

gulp.task('quit', function() {
  process.exit();
});

gulp.task('default', function() {
  runSequence('create-data-directory', 'create-config-file', 'start-mongo', 'start-tests', 'stop-mongo', 'quit');
});<|endoftext|>


<commit_before>
var gulp = require('gulp');
var karma = require('karma');

var workflow = require('availity-workflow');

workflow.use({
  gulp: gulp,
  karma: karma
});

gulp.task('default', ['av:default']);
gulp.task('lint', ['av:lint']);

<commit_msg>add gulp test task<commit_after>
var gulp = require('gulp');
var karma = require('karma');

var workflow = require('availity-workflow');

workflow.use({
  gulp: gulp,
  karma: karma
});

gulp.task('default', ['av:default']);
gulp.task('lint', ['av:lint']);
gulp.task('test', ['av:test']);

<|endoftext|>


<commit_before>var gulp = require('gulp');

var config = {
	staticCdn: 'https://s.gjcdn.net',
	injectVersion: 2,
	framework: 'vue',
	sections: ['auth', 'checkout', 'claim'],
	serverSections: ['auth', 'app'],
	translations: 'site-translations',
	translationSections: {
		auth: ['auth/'],
		dash: [
			'app/components/forms/dashboard',
			'app/components/forms/site-analytics',
			'app/views/dashboard',
		],
		checkout: ['checkout/'],
		claim: ['claim/'],
	},
	offlineSupport: ['auth'],
	webAppManifest: {
		app: {
			name: 'Game Jolt',
			short_name: 'Game Jolt',
			description: 'Games for the love of it!',
			background_color: '#191919',
			theme_color: '#191919',
			display: 'standalone',
			start_url: './?utm_source=web_app_manifest',
			icons: [
				{
					src: 'icon-128x128.png',
					size: 128,
				},
				{
					src: 'icon-144x144.png',
					size: 144,
				},
				{
					src: 'chrome-touch-icon-192x192.png',
					size: 192,
				},
			],
		},
	},
};

require('./src/lib/gj-lib-client/gulp/tasks/common.js')(config, __dirname);
// require( './tasks/client.js' )( config );
require('./tasks/app.js')(config);
require('./tasks/terms.js')(config);
require('./tasks/game-api-doc.js')(config);

gulp.task('pre', gulp.parallel('terms', 'game-api-doc:nav', 'game-api-doc:compile'));
<commit_msg>fix offline support section<commit_after>var gulp = require('gulp');

var config = {
	staticCdn: 'https://s.gjcdn.net',
	injectVersion: 2,
	framework: 'vue',
	sections: ['auth', 'checkout', 'claim'],
	serverSections: ['auth', 'app'],
	translations: 'site-translations',
	translationSections: {
		auth: ['auth/'],
		dash: [
			'app/components/forms/dashboard',
			'app/components/forms/site-analytics',
			'app/views/dashboard',
		],
		checkout: ['checkout/'],
		claim: ['claim/'],
	},
	offlineSupport: ['app'],
	webAppManifest: {
		app: {
			name: 'Game Jolt',
			short_name: 'Game Jolt',
			description: 'Games for the love of it!',
			background_color: '#191919',
			theme_color: '#191919',
			display: 'standalone',
			start_url: './?utm_source=web_app_manifest',
			icons: [
				{
					src: 'icon-128x128.png',
					size: 128,
				},
				{
					src: 'icon-144x144.png',
					size: 144,
				},
				{
					src: 'chrome-touch-icon-192x192.png',
					size: 192,
				},
			],
		},
	},
};

require('./src/lib/gj-lib-client/gulp/tasks/common.js')(config, __dirname);
// require( './tasks/client.js' )( config );
require('./tasks/app.js')(config);
require('./tasks/terms.js')(config);
require('./tasks/game-api-doc.js')(config);

gulp.task('pre', gulp.parallel('terms', 'game-api-doc:nav', 'game-api-doc:compile'));
<|endoftext|>


<commit_before>var gulp = require('gulp');
var path = require('path');

var jquery = {
    bowerComponent: 'jquery',
    distFiles: ['dist/jquery.js']
};

var jqueryui = {
    bowerComponent: 'jquery-ui',
    distFiles: ['jquery-ui.js']
};

var underscore = {
    bowerComponent: 'underscore',
    distFiles: ['underscore.js']
}

var handlebars = {
    bowerComponent: 'handlebars',
    distFiles: ['handlebars.js']
};

var backbone = {
    bowerComponent: 'backbone#1.1.2',
    distFiles: ['backbone.js']
}

var aceEditor = {
    id: 'ace-builds',
    bowerComponent: 'git@github.com:ajaxorg/ace-builds.git',
    distFiles: [
        './src/ace.js',
        './src/worker-json.js',
        './src/mode-json.js',
        './src/theme-chrome.js'
    ]
};

var leaflet = {
    bowerComponent: 'leaflet',
    distFiles: [
        'dist/leaflet-src.js',
        'dist/leaflet.css',
        'dist/images/layers.png',
        'dist/images/layers-2x.png',
        'dist/images/marker-icon.png',
        'dist/images/marker-icon-2x.png',
        'dist/images/marker-shadow.png'
    ]
};

var leafletActiveArea = {
    id: 'Leaflet-active-area',
    bowerComponent: 'Mappy/Leaflet-active-area',
    distFiles: ['./src/leaflet.activearea.js']
};

var markercluster = {
    id: 'leaflet.markercluster',
    srcDir: './external/leaflet.markercluster',
    distFiles: ['dist/MarkerCluster.css', 'dist/MarkerCluster.Default.css', 'dist/leaflet.markercluster.js'],
    build: true,
    watch: true
};

var heatmap = {
    id: 'leaflet.heat',
    bowerComponent: 'leaflet/leaflet.heat',
    distFiles: ['dist/leaflet-heat.js']
};

var leafletGeomixer = {
    id: 'Leaflet-GeoMixer',
    srcDir: './external/Leaflet-GeoMixer',
    distFiles: ['./dist/leaflet-geomixer-src.js'],
    build: true,
    watch: false
};

var tileLayerMercator = {
    id: 'Leaflet.TileLayer.Mercator',
    srcDir: './external/Leaflet.TileLayer.Mercator',
    distFiles: ['./src/TileLayer.Mercator.js'],
    build: false,
    watch: false
};

var gmxBaseLayersManager = {
    id: 'Leaflet.gmxBaseLayersManager',
    srcDir: './external/Leaflet.gmxBaseLayersManager',
    distFiles: [
        './src/gmxBaseLayersManager.js',
        './src/initBaseLayerManager.js'
    ],
    build: false,
    watch: false
};

var gmxControls = {
    id: 'gmxControls',
    srcDir: './external/gmxControls',
    distFiles: [
        './dist/gmxControls-src.js',
        './dist/css/gmxControls.css',
        './dist/css/img/band.png',
        './dist/css/img/coords.png',
        './dist/css/img/gmxSprite.png',
        './dist/css/img/logo_footer.png',
        './dist/css/img/logo_footer_color.png'
    ],
    build: true,
    watch: false
};

var iconLayersControl = {
    id: 'Leaflet-IconLayers',
    srcDir: './external/Leaflet-IconLayers',
    distDir: './src',
    build: false
};

var gmxIconLayers = {
    id: 'GmxIconLayers',
    srcDir: './external/GMXCommonComponents/GmxIconLayers',
    build: false
};

var componentsManager = {
    id: 'ComponentsManager',
    srcDir: './external/GMXCommonComponents/ComponentsManager',
    distDir: './build',
    build: true
};

var utils = {
    id: 'Utils',
    srcDir: './external/GMXCommonComponents/Utils',
    build: false
};

var winnieCore = {
    id: 'core',
    srcDir: './core',
    build: false
};

var commonStyles = {
    id: 'CommonStyles',
    srcDir: './external/GMXCommonComponents/CommonStyles',
    distDir: './build',
    build: true
};

var translations = {
    id: 'translations',
    url: 'http://maps.kosmosnimki.ru/api/translations.js'
};

var dropdownMenuWidget = {
    id: 'DropdownMenuWidget',
    srcDir: './external/GMXCommonComponents/DropdownMenuWidget',
    distDir: './build',
    build: true
};

var popover = {
    id: 'Popover',
    srcDir: './external/GMXCommonComponents/Popover',
    distDir: './build',
    build: true
};

var authManager = {
    id: 'AuthManager',
    srcDir: './external/GMXCommonComponents/AuthManager',
    distDir: './build',
    build: true
};

var thorax = {
    id: 'Thorax',
    srcDir: './external/GMXCommonComponents/Thorax',
    distFiles: [
        './thorax.js'
    ],
    build: false,
    watch: false
}

var layersTree = {
    id: 'LayersTree',
    srcDir: './external/GMXCommonComponents/LayersTree',
    distDir: './build',
    build: true
};

var layersDebugger = './external/GMXCommonComponents/LayersDebugger';

var gmxWidget = {
    id: 'GmxWidget',
    srcDir: './external/GMXCommonComponents/GmxWidget',
    build: false
};

var animationHelpers = {
    id: 'animationHelpers',
    srcDir: './external/GMXCommonComponents/animationHelpers',
    build: false
};

var sidebar = {
    id: 'IconSidebarControl',
    srcDir: './external/GMXCommonComponents/IconSidebarControl'
};

var storytellingWidget = {
    id: 'StorytellingControl',
    srcDir: './external/GMXCommonComponents/StorytellingControl',
    build: false
};

var layersTreeWidget = {
    id: 'LayersTreeWidget',
    srcDir: './external/GMXCommonComponents/LayersTreeWidget',
    distDir: './build',
    build: true
};

var dateInterval = {
    id: 'DateInterval',
    srcDir: './external/GMXCommonComponents/DateInterval',
    build: false
};

var calendarWidget = {
    id: 'CalendarWidget',
    srcDir: './external/GMXCommonComponents/CalendarWidget',
    distDir: './build',
    build: true
};

var switchingCollectionWidget = {
    id: 'SwitchingCollectionWidget',
    srcDir: './external/GMXCommonComponents/SwitchingCollectionWidget',
    build: false
};

var bookmarksWidget = {
    id: 'BookmarksWidget',
    srcDir: './external/GMXCommonComponents/BookmarksWidget',
    distDir: './build',
    build: true
};

var stateManager = {
    id: 'StateManager',
    srcDir: './external/GMXCommonComponents/StateManager',
    build: false
};

var alertWidget = {
    id: 'AlertWidget',
    srcDir: './external/GMXCommonComponents/AlertWidget',
    distDir: './build',
    build: true
};

var shareIconControl = {
    id: 'ShareIconControl',
    srcDir: './external/GMXCommonComponents/ShareIconControl',
    distDir: 'build',
    build: true
};

var coreComponents = [
    jquery,
    jqueryui,
    handlebars,
    underscore,
    backbone,
    thorax,
    leaflet,
    leafletActiveArea,
    markercluster,
    heatmap,
    leafletGeomixer,
    tileLayerMercator,
    gmxBaseLayersManager,
    gmxControls,
    layersTree,
    layersDebugger,
    commonStyles,
    popover,
    translations,
    iconLayersControl,
    gmxIconLayers,
    componentsManager,
    utils,
    gmxWidget,
    animationHelpers,
    switchingCollectionWidget,
    sidebar,
    layersTreeWidget,
    dateInterval,
    calendarWidget,
    bookmarksWidget,
    storytellingWidget,
    stateManager,
    winnieCore
];

var virtualLayers = [{
    id: 'leaflet-GIBS',
    srcDir: './external/leaflet-GIBS',
    distFiles: [
        './src/GeoMixerGIBSLayer.js',
        './src/GIBSLayer.js',
        './src/GIBSMetadata.js'
    ],
    build: false
}];

require('./external/GMXBuilder')(gulp, {
    tempDir: './temp',
    distDir: './dist',
    watchExtensions: ['.js', '.css', '.html', '.less', '.svg'],
    distributionExtensions: ['.js', '.css', '.jpg', '.png', '.eot', '.ttf', '.woff', '.svg']
}, [{
    id: 'core',
    components: coreComponents
}, {
    id: 'viewer',
    htmlfile: 'html/viewer.html',
    components: [].concat(coreComponents, virtualLayers, [{
        id: 'viewer',
        srcDir: './viewer'
    }])
}, {
    id: 'index',
    htmlfile: 'html/index.html',
    components: [].concat(coreComponents, virtualLayers, [
        aceEditor,
        dropdownMenuWidget,
        alertWidget,
        shareIconControl,
        authManager, {
            id: 'editor',
            srcDir: './editor',
            distDir: './build',
            build: true
        }
    ])
}]);<commit_msg>add GmxVirtualTileLayer<commit_after>var gulp = require('gulp');
var path = require('path');

var jquery = {
    bowerComponent: 'jquery',
    distFiles: ['dist/jquery.js']
};

var jqueryui = {
    bowerComponent: 'jquery-ui',
    distFiles: ['jquery-ui.js']
};

var underscore = {
    bowerComponent: 'underscore',
    distFiles: ['underscore.js']
}

var handlebars = {
    bowerComponent: 'handlebars',
    distFiles: ['handlebars.js']
};

var backbone = {
    bowerComponent: 'backbone#1.1.2',
    distFiles: ['backbone.js']
}

var aceEditor = {
    id: 'ace-builds',
    bowerComponent: 'git@github.com:ajaxorg/ace-builds.git',
    distFiles: [
        './src/ace.js',
        './src/worker-json.js',
        './src/mode-json.js',
        './src/theme-chrome.js'
    ]
};

var leaflet = {
    bowerComponent: 'leaflet',
    distFiles: [
        'dist/leaflet-src.js',
        'dist/leaflet.css',
        'dist/images/layers.png',
        'dist/images/layers-2x.png',
        'dist/images/marker-icon.png',
        'dist/images/marker-icon-2x.png',
        'dist/images/marker-shadow.png'
    ]
};

var leafletActiveArea = {
    id: 'Leaflet-active-area',
    bowerComponent: 'Mappy/Leaflet-active-area',
    distFiles: ['./src/leaflet.activearea.js']
};

var markercluster = {
    id: 'leaflet.markercluster',
    srcDir: './external/leaflet.markercluster',
    distFiles: ['dist/MarkerCluster.css', 'dist/MarkerCluster.Default.css', 'dist/leaflet.markercluster.js'],
    build: true,
    watch: true
};

var heatmap = {
    id: 'leaflet.heat',
    bowerComponent: 'leaflet/leaflet.heat',
    distFiles: ['dist/leaflet-heat.js']
};

var leafletGeomixer = {
    id: 'Leaflet-GeoMixer',
    srcDir: './external/Leaflet-GeoMixer',
    distFiles: ['./dist/leaflet-geomixer-src.js'],
    build: true,
    watch: false
};

var tileLayerMercator = {
    id: 'Leaflet.TileLayer.Mercator',
    srcDir: './external/Leaflet.TileLayer.Mercator',
    distFiles: ['./src/TileLayer.Mercator.js'],
    build: false,
    watch: false
};

var gmxBaseLayersManager = {
    id: 'Leaflet.gmxBaseLayersManager',
    srcDir: './external/Leaflet.gmxBaseLayersManager',
    distFiles: [
        './src/gmxBaseLayersManager.js',
        './src/initBaseLayerManager.js'
    ],
    build: false,
    watch: false
};

var gmxControls = {
    id: 'gmxControls',
    srcDir: './external/gmxControls',
    distFiles: [
        './dist/gmxControls-src.js',
        './dist/css/gmxControls.css',
        './dist/css/img/band.png',
        './dist/css/img/coords.png',
        './dist/css/img/gmxSprite.png',
        './dist/css/img/logo_footer.png',
        './dist/css/img/logo_footer_color.png'
    ],
    build: true,
    watch: false
};

var iconLayersControl = {
    id: 'Leaflet-IconLayers',
    srcDir: './external/Leaflet-IconLayers',
    distDir: './src',
    build: false
};

var gmxIconLayers = {
    id: 'GmxIconLayers',
    srcDir: './external/GMXCommonComponents/GmxIconLayers',
    build: false
};

var componentsManager = {
    id: 'ComponentsManager',
    srcDir: './external/GMXCommonComponents/ComponentsManager',
    distDir: './build',
    build: true
};

var utils = {
    id: 'Utils',
    srcDir: './external/GMXCommonComponents/Utils',
    build: false
};

var winnieCore = {
    id: 'core',
    srcDir: './core',
    build: false
};

var commonStyles = {
    id: 'CommonStyles',
    srcDir: './external/GMXCommonComponents/CommonStyles',
    distDir: './build',
    build: true
};

var translations = {
    id: 'translations',
    url: 'http://maps.kosmosnimki.ru/api/translations.js'
};

var dropdownMenuWidget = {
    id: 'DropdownMenuWidget',
    srcDir: './external/GMXCommonComponents/DropdownMenuWidget',
    distDir: './build',
    build: true
};

var popover = {
    id: 'Popover',
    srcDir: './external/GMXCommonComponents/Popover',
    distDir: './build',
    build: true
};

var authManager = {
    id: 'AuthManager',
    srcDir: './external/GMXCommonComponents/AuthManager',
    distDir: './build',
    build: true
};

var thorax = {
    id: 'Thorax',
    srcDir: './external/GMXCommonComponents/Thorax',
    distFiles: [
        './thorax.js'
    ],
    build: false,
    watch: false
}

var layersTree = {
    id: 'LayersTree',
    srcDir: './external/GMXCommonComponents/LayersTree',
    distDir: './build',
    build: true
};

var layersDebugger = './external/GMXCommonComponents/LayersDebugger';

var gmxWidget = {
    id: 'GmxWidget',
    srcDir: './external/GMXCommonComponents/GmxWidget',
    build: false
};

var animationHelpers = {
    id: 'animationHelpers',
    srcDir: './external/GMXCommonComponents/animationHelpers',
    build: false
};

var sidebar = {
    id: 'IconSidebarControl',
    srcDir: './external/GMXCommonComponents/IconSidebarControl'
};

var storytellingWidget = {
    id: 'StorytellingControl',
    srcDir: './external/GMXCommonComponents/StorytellingControl',
    build: false
};

var layersTreeWidget = {
    id: 'LayersTreeWidget',
    srcDir: './external/GMXCommonComponents/LayersTreeWidget',
    distDir: './build',
    build: true
};

var dateInterval = {
    id: 'DateInterval',
    srcDir: './external/GMXCommonComponents/DateInterval',
    build: false
};

var calendarWidget = {
    id: 'CalendarWidget',
    srcDir: './external/GMXCommonComponents/CalendarWidget',
    distDir: './build',
    build: true
};

var switchingCollectionWidget = {
    id: 'SwitchingCollectionWidget',
    srcDir: './external/GMXCommonComponents/SwitchingCollectionWidget',
    build: false
};

var bookmarksWidget = {
    id: 'BookmarksWidget',
    srcDir: './external/GMXCommonComponents/BookmarksWidget',
    distDir: './build',
    build: true
};

var stateManager = {
    id: 'StateManager',
    srcDir: './external/GMXCommonComponents/StateManager',
    build: false
};

var alertWidget = {
    id: 'AlertWidget',
    srcDir: './external/GMXCommonComponents/AlertWidget',
    distDir: './build',
    build: true
};

var shareIconControl = {
    id: 'ShareIconControl',
    srcDir: './external/GMXCommonComponents/ShareIconControl',
    distDir: 'build',
    build: true
};

var coreComponents = [
    jquery,
    jqueryui,
    handlebars,
    underscore,
    backbone,
    thorax,
    leaflet,
    leafletActiveArea,
    markercluster,
    heatmap,
    leafletGeomixer,
    tileLayerMercator,
    gmxBaseLayersManager,
    gmxControls,
    layersTree,
    layersDebugger,
    commonStyles,
    popover,
    translations,
    iconLayersControl,
    gmxIconLayers,
    componentsManager,
    utils,
    gmxWidget,
    animationHelpers,
    switchingCollectionWidget,
    sidebar,
    layersTreeWidget,
    dateInterval,
    calendarWidget,
    bookmarksWidget,
    storytellingWidget,
    stateManager,
    winnieCore
];

var virtualLayers = [{
    id: 'GmxVirtualTileLayer',
    srcDir: './external/GMXCommonComponents/GmxVirtualTileLayer',
    build: false
}, {
    id: 'leaflet-GIBS',
    srcDir: './external/leaflet-GIBS',
    distFiles: [
        './src/GeoMixerGIBSLayer.js',
        './src/GIBSLayer.js',
        './src/GIBSMetadata.js'
    ],
    build: false
}];

require('./external/GMXBuilder')(gulp, {
    tempDir: './temp',
    distDir: './dist',
    watchExtensions: ['.js', '.css', '.html', '.less', '.svg'],
    distributionExtensions: ['.js', '.css', '.jpg', '.png', '.eot', '.ttf', '.woff', '.svg']
}, [{
    id: 'core',
    components: coreComponents
}, {
    id: 'viewer',
    htmlfile: 'html/viewer.html',
    components: [].concat(coreComponents, virtualLayers, [{
        id: 'viewer',
        srcDir: './viewer'
    }])
}, {
    id: 'index',
    htmlfile: 'html/index.html',
    components: [].concat(coreComponents, virtualLayers, [
        aceEditor,
        dropdownMenuWidget,
        alertWidget,
        shareIconControl,
        authManager, {
            id: 'editor',
            srcDir: './editor',
            distDir: './build',
            build: true
        }
    ])
}]);<|endoftext|>