<commit_before>var gulp = require('gulp'),
  pug = require('gulp-pug'),
  sass = require('gulp-sass'),
  imagemin = require('gulp-imagemin'),
  pngquant = require('imagemin-pngquant'),
  webserver = require('gulp-webserver'),
  plumber = require('gulp-plumber'),
  watch = require('gulp-watch'),
  cleaner = require('rimraf'),
  sequence = require('gulp-sequence'),
  bower = require('main-bower-files'),
  fs = require('fs'),
  rename = require('gulp-rename'),
  path = {
    src: {
      html: 'resources/views/pages/**/*.pug',
      css: 'resources/styles/style.scss',
      js: 'resources/scripts/*.js',
      img: 'resources/images/**/*.*',
      tags: 'resources/data/tags.json',
      descriptions: 'resources/data/descriptions/'
    },
    watch: {
      html: 'resources/views/**/*.pug',
      css: 'resources/styles/**/*.scss',
      js: 'resources/scripts/*.js',
      img: 'resources/images/**/*.*',
	    descriptions: 'resources/data/descriptions/*.html'
    },
    build: {
      html: 'build/',
      css: 'build/css/',
      js: 'build/js/',
      img: 'build/img/'
    }
  };

var cache = [];
var tags;

// Запуск локального сервера
gulp.task('localserver', function() {
  gulp.src(path.build.html)
    .pipe(webserver({
      livereload: true,
      open: true,
      fallback: 'index.html'
    }));
});

// Чистка папки продакшена
gulp.task('clean', function (cb) {
  cleaner(path.build.html, cb);
});

gulp.task('indexJSON', function () {
	tags = JSON.parse(fs.readFileSync(path.src.tags));
});

gulp.task('indexDESCS', function () {
	tags.forEach(function (tag, index) {
		var filePath = path.src.descriptions + tag.name +'.html';
		var isExistFilePath = fs.existsSync(filePath);

		if(!tag.description) {
			if(!isExistFilePath) fs.appendFileSync(filePath, '
Описания пока нет...
', 'utf8');

			cache[index] = fs.readFileSync(filePath, 'utf8');
		}
	});
});

// Запуск компиляции HTML
gulp.task('html', function() {

  return gulp.src(path.src.html)
    .pipe(plumber())
    .pipe(pug({
      pretty: true,
      data: {
        tags: tags,
        time: new Date()
      }
    }))
    .pipe(gulp.dest(path.build.html));
});

gulp.task('tags_page', function () {

  tags.forEach(function(tag, index) {
	  if(!tag.description) tag.description = cache[index];

	  gulp.src('resources/views/pages/tag.pug')
		  .pipe(pug({
			  pretty: true,
			  data: tag
		  }))
		  .pipe(rename({
			  basename: tag.name
		  }))
		  .pipe(gulp.dest(path.build.html));
  });
});

// Запуск компиляции CSS
gulp.task('css', function() {
  gulp.src(path.src.css)
    .pipe(plumber())
    .pipe(sass({
      outputStyle: 'compressed'
    }))
    .pipe(gulp.dest(path.build.css));
});

// Сжатие javascript
gulp.task('js', function() {
  return gulp.src(path.src.js)
    .pipe(plumber())
    // .pipe(uglyjs())
    // .pipe(rename(function (path) {
    //   path.basename += ".min"
    // }))
    .pipe(gulp.dest(path.build.js));
});

// Сжатие изображений
gulp.task('image', function() {
  return gulp.src(path.src.img)
    .pipe(plumber())
    .pipe(imagemin({
      progressive: true,
      svgoPlugins: [{removeViewBox: false}],
      use: [pngquant()]
    }))
    .pipe(gulp.dest(path.build.img));
});

gulp.task('vendors', function() {
  var styles = gulp.src(bower({group: 'css'}))
    .pipe(plumber())
    .pipe(gulp.dest(path.build.css +'/vendors'));

  var scripts = gulp.src(bower({group: 'js'}))
    .pipe(plumber())
    .pipe(gulp.dest(path.build.js +'/vendors'));

  return [styles, scripts];
});

// Копирование файлов
gulp.task('copy', function () {
  gulp.src('./resources/fonts/**/*.{ttf,woff,woff2,eof,eot,svg}')
    .pipe(gulp.dest('./build/fonts'))
});

// Наблюдение за изменением файлов
gulp.task('default', ['localserver', 'indexJSON', 'indexDESCS'], function() {

	watch(path.watch.html, function () {
		gulp.start('html', 'tags_page');
	});

	watch(path.src.tags, function () {
		gulp.start('indexJSON', 'indexDESCS', 'html', 'tags_page');
	});

	watch(path.watch.descriptions, function () {
		gulp.start('indexDESCS', 'tags_page');
	});

  watch(path.watch.css, function(event, cb) {
    gulp.start('css');
  });
  watch(path.watch.js, function(event, cb) {
    gulp.start('js');
  });
  watch([path.watch.img], function(event, cb) {
    gulp.start('image');
  });
});

// Выполнение всех тасков по порядку
gulp.task('build', sequence('clean', 'html', ['tags_page', 'css'], 'js', 'image', 'vendors', 'copy'));<commit_msg>bug fixing<commit_after>var gulp = require('gulp'),
  pug = require('gulp-pug'),
  sass = require('gulp-sass'),
  imagemin = require('gulp-imagemin'),
  pngquant = require('imagemin-pngquant'),
  webserver = require('gulp-webserver'),
  plumber = require('gulp-plumber'),
  watch = require('gulp-watch'),
  cleaner = require('rimraf'),
  sequence = require('gulp-sequence'),
  bower = require('main-bower-files'),
  fs = require('fs'),
  rename = require('gulp-rename'),
  path = {
    src: {
      html: 'resources/views/pages/**/*.pug',
      css: 'resources/styles/style.scss',
      js: 'resources/scripts/*.js',
      img: 'resources/images/**/*.*',
      tags: 'resources/data/tags.json',
      descriptions: 'resources/data/descriptions/'
    },
    watch: {
      html: 'resources/views/**/*.pug',
      css: 'resources/styles/**/*.scss',
      js: 'resources/scripts/*.js',
      img: 'resources/images/**/*.*',
	    descriptions: 'resources/data/descriptions/*.html'
    },
    build: {
      html: 'build/',
      css: 'build/css/',
      js: 'build/js/',
      img: 'build/img/'
    }
  };

var cache = [];
var tags;

// Запуск локального сервера
gulp.task('localserver', function() {
  gulp.src(path.build.html)
    .pipe(webserver({
      livereload: true,
      open: true,
      fallback: 'index.html'
    }));
});

// Чистка папки продакшена
gulp.task('clean', function (cb) {
  cleaner(path.build.html, cb);
});

gulp.task('indexJSON', function () {
	tags = JSON.parse(fs.readFileSync(path.src.tags));
});

gulp.task('indexDESCS', function () {
	tags.forEach(function (tag, index) {
		var filePath = path.src.descriptions + tag.name +'.html';
		var isExistFilePath = fs.existsSync(filePath);

		if(!tag.description && !isExistFilePath) {
			fs.appendFileSync(filePath, '
Описания элемента <'+ tag.name +'> пока нет...
', 'utf8');
		} else if(isExistFilePath) {
			tags[index].description = fs.readFileSync(filePath, 'utf8');
		}
	});
});

// Запуск компиляции HTML
gulp.task('html', function() {

  return gulp.src(path.src.html)
    .pipe(plumber())
    .pipe(pug({
      pretty: true,
      data: {
        tags: tags,
        time: new Date()
      }
    }))
    .pipe(gulp.dest(path.build.html));
});

gulp.task('tags_page', function () {

  tags.forEach(function(tag, index) {
	  if(index) tag.prev = tags[index - 1].name;
	  if(index !== tags.length - 1) tag.next = tags[index + 1].name;

	  gulp.src('resources/views/pages/tag.pug')
		  .pipe(pug({
			  pretty: true,
			  data: tag
		  }))
		  .pipe(rename({
			  basename: tag.name
		  }))
		  .pipe(gulp.dest(path.build.html));
  });
});

// Запуск компиляции CSS
gulp.task('css', function() {
  gulp.src(path.src.css)
    .pipe(plumber())
    .pipe(sass({
      outputStyle: 'compressed'
    }))
    .pipe(gulp.dest(path.build.css));
});

// Сжатие javascript
gulp.task('js', function() {
  return gulp.src(path.src.js)
    .pipe(plumber())
    // .pipe(uglyjs())
    // .pipe(rename(function (path) {
    //   path.basename += ".min"
    // }))
    .pipe(gulp.dest(path.build.js));
});

// Сжатие изображений
gulp.task('image', function() {
  return gulp.src(path.src.img)
    .pipe(plumber())
    .pipe(imagemin({
      progressive: true,
      svgoPlugins: [{removeViewBox: false}],
      use: [pngquant()]
    }))
    .pipe(gulp.dest(path.build.img));
});

gulp.task('vendors', function() {
  var styles = gulp.src(bower({group: 'css'}))
    .pipe(plumber())
    .pipe(gulp.dest(path.build.css +'/vendors'));

  var scripts = gulp.src(bower({group: 'js'}))
    .pipe(plumber())
    .pipe(gulp.dest(path.build.js +'/vendors'));

  return [styles, scripts];
});

// Копирование файлов
gulp.task('copy', function () {
  gulp.src('./resources/fonts/**/*.{ttf,woff,woff2,eof,eot,svg}')
    .pipe(gulp.dest('./build/fonts'))
});

// Наблюдение за изменением файлов
gulp.task('default', ['localserver', 'indexJSON', 'indexDESCS'], function() {

	watch(path.watch.html, function () {
		gulp.start('html', 'tags_page');
	});

	watch(path.src.tags, function () {
		gulp.start('indexJSON', 'indexDESCS', 'html', 'tags_page');
	});

	watch(path.watch.descriptions, function () {
		gulp.start('indexDESCS', 'tags_page');
	});

  watch(path.watch.css, function(event, cb) {
    gulp.start('css');
  });
  watch(path.watch.js, function(event, cb) {
    gulp.start('js');
  });
  watch([path.watch.img], function(event, cb) {
    gulp.start('image');
  });
});

// Выполнение всех тасков по порядку
gulp.task('build', sequence('clean', 'indexJSON', 'indexDESCS', ['html', 'tags_page', 'css'], 'js', 'image', 'vendors', 'copy'));<|endoftext|>


<commit_before>// load everything
var gulp = require('gulp');

var browserSync = require('browser-sync').create();
var clean = require('gulp-clean');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var postcss = require('gulp-postcss');
var autoprefixer = require('autoprefixer');
var csso = require('gulp-csso');
var twig = require('gulp-twig');
var fs = require('fs');

// a task to delete all css files in dist folder
gulp.task('cssclean', function(){
    return gulp.src(['dist/*.css', 'dist/*.map'], { read: false }).pipe(clean());
});

// CSS compilation (also deletes css files first using previously defined task)
gulp.task('csscompile', ['cssclean'], function(){
    return gulp
        .src('src/scss/index.scss') // this is the source of for compilation
        .pipe(sass().on('error', sass.logError)) // compile sass to css and also tell us about a problem if happens
        .pipe(sourcemaps.init()) // initalizes a sourcemap
        .pipe(postcss([autoprefixer( // supported browsers (from Bootstrap 4 alpha 6)
            'Chrome >= 35',
            'Firefox >= 38',
            'Edge >= 12',
            'Explorer >= 10',
            'iOS >= 8',
            'Safari >= 8',
            'Android 2.3',
            'Android >= 4',
            'Opera >= 12'
        ), require('postcss-flexbugs-fixes')]))
        .pipe(csso()) // compresses CSS
        .pipe(sourcemaps.write('.')) // writes the sourcemap
        .pipe(gulp.dest('./dist')) // destination of the resulting css
        .pipe(browserSync.stream()); // tell browsersync to reload CSS (injects compiled CSS)
});

// delete all html files in dist folder
gulp.task('htmlclean', function(){
    return gulp.src(['dist/**/*.html'], { read: false }).pipe(clean());
});

// HTML compilation from templates
gulp.task('htmlcompile', ['htmlclean'], function(){
    return gulp.src('src/templates/**/*.twig')
    // compile twig templates to html files
        .pipe(twig({ data: JSON.parse(fs.readFileSync('src/templates/data.json')) })) // import from data.json
        .pipe(gulp.dest('./dist/')) // where to put compiled html
        .on('end', function(){ // after compilation finishes…
            browserSync.reload() // … tell Browsersync to reload
        });
});

// delete all files from src except css
gulp.task('staticclean', function(){
    return gulp.src([
        'dist/**/*',
        '!dist/**/*.html',
        '!dist/**/*.css',
        '!dist/**/*.map'
    ], { read: false }).pipe(clean());
});

// copy everything except scss from src folder
gulp.task('staticcopy', ['staticclean'], function(){
    return gulp.src(['src/static/**/*']).pipe(gulp.dest('dist'));
});

// build everything
gulp.task('build', ['csscompile', 'htmlcompile', 'staticcopy']);

// development with automatic refreshing
gulp.task('develop', ['build'], function(){
    browserSync.init({ // initalize Browsersync
        // set what files be served
        server: {
            baseDir: './dist/' // serve from this folder
        }
    });
    gulp.watch('src/scss/**/*', ['csscompile']); // watch for changes in scss
    gulp.watch('src/templates/**/*', ['htmlcompile']); // watch for changes in templates
    gulp.watch(['src/static/**/*'], ['staticcopy']); // watch for changes in static files
});

// set develop as a default task (gulp runs this when you don't specify a task)
gulp.task('default', ['develop']);
<commit_msg>autoprefixer settings updated to BS4beta<commit_after>// load everything
var gulp = require('gulp');

var browserSync = require('browser-sync').create();
var clean = require('gulp-clean');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var postcss = require('gulp-postcss');
var autoprefixer = require('autoprefixer');
var csso = require('gulp-csso');
var twig = require('gulp-twig');
var fs = require('fs');

// a task to delete all css files in dist folder
gulp.task('cssclean', function(){
    return gulp.src(['dist/*.css', 'dist/*.map'], { read: false }).pipe(clean());
});

// CSS compilation (also deletes css files first using previously defined task)
gulp.task('csscompile', ['cssclean'], function(){
    return gulp
        .src('src/scss/index.scss') // this is the source of for compilation
        .pipe(sass().on('error', sass.logError)) // compile sass to css and also tell us about a problem if happens
        .pipe(sourcemaps.init()) // initalizes a sourcemap
        .pipe(postcss([autoprefixer( // supported browsers (from Bootstrap 4 beta: https://github.com/twbs/bootstrap/blob/v4-dev/build/postcss.config.js)
            //
            // Official browser support policy:
            // https://v4-alpha.getbootstrap.com/getting-started/browsers-devices/#supported-browsers
            //
            'Chrome >= 45', // Exact version number here is kinda arbitrary
            'Firefox ESR',
            // Note: Edge versions in Autoprefixer & Can I Use refer to the EdgeHTML rendering engine version,
            // NOT the Edge app version shown in Edge's "About" screen.
            // For example, at the time of writing, Edge 20 on an up-to-date system uses EdgeHTML 12.
            // See also https://github.com/Fyrd/caniuse/issues/1928
            'Edge >= 12',
            'Explorer >= 10',
            // Out of leniency, we prefix these 1 version further back than the official policy.
            'iOS >= 9',
            'Safari >= 9',
            // The following remain NOT officially supported, but we're lenient and include their prefixes to avoid severely breaking in them.
            'Android >= 4.4',
            'Opera >= 30'
        ), require('postcss-flexbugs-fixes')]))
        .pipe(csso()) // compresses CSS
        .pipe(sourcemaps.write('.')) // writes the sourcemap
        .pipe(gulp.dest('./dist')) // destination of the resulting css
        .pipe(browserSync.stream()); // tell browsersync to reload CSS (injects compiled CSS)
});

// delete all html files in dist folder
gulp.task('htmlclean', function(){
    return gulp.src(['dist/**/*.html'], { read: false }).pipe(clean());
});

// HTML compilation from templates
gulp.task('htmlcompile', ['htmlclean'], function(){
    return gulp.src('src/templates/**/*.twig')
    // compile twig templates to html files
        .pipe(twig({ data: JSON.parse(fs.readFileSync('src/templates/data.json')) })) // import from data.json
        .pipe(gulp.dest('./dist/')) // where to put compiled html
        .on('end', function(){ // after compilation finishes…
            browserSync.reload() // … tell Browsersync to reload
        });
});

// delete all files from src except css
gulp.task('staticclean', function(){
    return gulp.src([
        'dist/**/*',
        '!dist/**/*.html',
        '!dist/**/*.css',
        '!dist/**/*.map'
    ], { read: false }).pipe(clean());
});

// copy everything except scss from src folder
gulp.task('staticcopy', ['staticclean'], function(){
    return gulp.src(['src/static/**/*']).pipe(gulp.dest('dist'));
});

// build everything
gulp.task('build', ['csscompile', 'htmlcompile', 'staticcopy']);

// development with automatic refreshing
gulp.task('develop', ['build'], function(){
    browserSync.init({ // initalize Browsersync
        // set what files be served
        server: {
            baseDir: './dist/' // serve from this folder
        }
    });
    gulp.watch('src/scss/**/*', ['csscompile']); // watch for changes in scss
    gulp.watch('src/templates/**/*', ['htmlcompile']); // watch for changes in templates
    gulp.watch(['src/static/**/*'], ['staticcopy']); // watch for changes in static files
});

// set develop as a default task (gulp runs this when you don't specify a task)
gulp.task('default', ['develop']);
<|endoftext|>


<commit_before>var fs = require( "fs" ),
    util = require( "util" ),
    path = require( "path" ),
    coverage = require( "./coverage" ),
    spawn = require( "child_process" ).spawn;

var options = exports.options = {
        errorsOnly: false,
        errorStack: true,
        summary: true,
        coverage: true,
        paths: null,
        deps: null
    };

/**
 * Format or colorize a message for console
 * @param {String} f
 * @param {String} str
 */
function format( str, f ) {
    switch ( f ) {
        case "red":
            return "\033[31m" + str + "\033[39m";
        case "green":
            return "\033[32m" + str + "\033[39m";
        case "bold":
            return "\033[1m" + str + "\033[22m";
    }
}

/**
 * Print out test report object
 * @param {Object} obj
 */
function logTest( obj ) {
    var descr = "[" + (obj.module ? obj.module + ": " : "") + obj.name + "] ";

    obj.message = obj.message || "";

    if ( obj.errorStack ) {
        util.print( format(  "[Error]" + descr + obj.message, "red" ) );
        if ( options.errorStack ) {
            util.print( "\n" + format( obj.errorStack, "red" ) + "\n" );
        }
    } else if ( !options.errorsOnly ) {
        util.print( format( "[OK]", "green" ) + descr + obj.message + "\n" );
    }

}

/**
 * Print out summery results for all tests
 * @param {Object} report
 * @param {Object} cov
 */
function printSummary( report, cov ) {
    util.print(
        "\nFiles: " + report.files +
        "\nTests: " + report.tests +
        "\nAssertions: " + report.assertions +
        "\nSuccesses: " + report.success +
        "\n" + format( "Errors: " + report.errors, "red" ) +
        "\n\nTime: " + report.time +  " ms\n\n"
    );

    if ( cov ) {
        coverage.reportCoverage( cov );
    }
}

/**
 * Run one spawned instance with tests
 * @param {Object} opts
 * @param {Object} report
 * @param {Function} callback
 */
function run( opts, report, callback ) {
    var child,
        testname,
        cov;

    child = spawn( process.execPath, [__dirname + "/bootstrap.js", JSON.stringify( opts )] );

    child.stdout.on( "data", function ( buf ) {
        buf.toString().split( "\n" ).forEach(function( data ) {

            if ( data.length <=0 ) {
                return;
            }

            data = JSON.parse( data );

            report.assertions++;

            // its coverage json
            if ( data.cov ) {
                cov = data.cov;
                return;
            }

            if ( data.name !== testname ) {
                report.tests++;
                testname = data.name;
            }

            if ( data.errorStack ) {
                report.errors++;
            }

            logTest( data );
        });
    });

    child.stderr.on( "data", function ( buf ) {
        util.print( "stderr: " + buf );
    });

    child.on( "exit", function( code ) {
        report.files++;

        if ( typeof callback === "function" ) {
            callback( cov );
        }
    });
}

/**
 * Make an absolute path from relative
 * @param {String|Object} file
 * @return {String|Object}
 */
function absPath( file ) {
    if ( typeof file === "string" && file.charAt(0) !== "/" ) {
        file = path.join( process.cwd(), file );
    } else if ( file.file && file.file.charAt(0) !== "/" ) {
        file.file = path.join( process.cwd(), file.file );
    }

    return file;
}

/**
 * Convert path or array of paths to array of abs paths
 * @param {Array|String|Object} files
 * @return {Array}
 */
function toArray( files ) {
    var ret = [];

    if ( Array.isArray(files) ) {
        files.forEach( function( file ) {
            ret.push( absPath(file) );
        });
    } else {
        ret.push( absPath(files) );
    }

    return ret;
}

/**
 * Run tests in spawned node instance async for every test.
 * @param {Object|Array} files
 * @param {Function} callback optional
 */
exports.run = function( files, callback ) {

    if ( !(files instanceof Array) ) {
        files = [files];
    }

    var report = {
            files: 0,
            tests: 0,
            assertions: 0,
            errors: 0,
            success: 0,
            time: Date.now()
        };

    files.forEach( function( opts ) {

        opts =  {
            deps: toArray( opts.deps || options.deps ),
            code: absPath( opts.code ),
            as: opts.as,
            tests: toArray( opts.tests ),
            paths: opts.paths || options.paths,
            coverage: opts.coverage || options.coverage
        };

        function finished( cov ) {
            if ( report.files < files.length ) {
                return;
            }

            if ( options.summary ) {
                report.success = report.assertions - report.errors;
                report.time = Date.now() - report.time;
                printSummary( report, cov );
            }

            if ( typeof callback === "function" ) {
                callback( report );
            }
        }

        if ( opts.coverage ) {
            coverage.instrument( opts.code.file, function( newCodePath, cleanup ) {
                opts.code.file = newCodePath;
                run( opts, report, function(cov) {
                    cleanup();
                    finished(cov);
                });
            });
        } else {
            run( opts, report, finished );
        }
    });
};<commit_msg>Added try/catch and logging so weird buffer splitting issue doesn't kill tests<commit_after>var fs = require( "fs" ),
    util = require( "util" ),
    path = require( "path" ),
    coverage = require( "./coverage" ),
    spawn = require( "child_process" ).spawn;

var options = exports.options = {
        errorsOnly: false,
        errorStack: true,
        summary: true,
        coverage: true,
        paths: null,
        deps: null
    };

/**
 * Format or colorize a message for console
 * @param {String} f
 * @param {String} str
 */
function format( str, f ) {
    switch ( f ) {
        case "red":
            return "\033[31m" + str + "\033[39m";
        case "green":
            return "\033[32m" + str + "\033[39m";
        case "bold":
            return "\033[1m" + str + "\033[22m";
    }
}

/**
 * Print out test report object
 * @param {Object} obj
 */
function logTest( obj ) {
    var descr = "[" + (obj.module ? obj.module + ": " : "") + obj.name + "] ";

    obj.message = obj.message || "";

    if ( obj.errorStack ) {
        util.print( format(  "[Error]" + descr + obj.message, "red" ) );
        if ( options.errorStack ) {
            util.print( "\n" + format( obj.errorStack, "red" ) + "\n" );
        }
    } else if ( !options.errorsOnly ) {
        util.print( format( "[OK]", "green" ) + descr + obj.message + "\n" );
    }

}

/**
 * Print out summery results for all tests
 * @param {Object} report
 * @param {Object} cov
 */
function printSummary( report, cov ) {
    util.print(
        "\nFiles: " + report.files +
        "\nTests: " + report.tests +
        "\nAssertions: " + report.assertions +
        "\nSuccesses: " + report.success +
        "\n" + format( "Errors: " + report.errors, "red" ) +
        "\n\nTime: " + report.time +  " ms\n\n"
    );

    if ( cov ) {
        coverage.reportCoverage( cov );
    }
}

/**
 * Run one spawned instance with tests
 * @param {Object} opts
 * @param {Object} report
 * @param {Function} callback
 */
function run( opts, report, callback ) {
    var child,
        testname,
        cov;

    child = spawn( process.execPath, [__dirname + "/bootstrap.js", JSON.stringify( opts )] );

    child.stdout.on( "data", function ( buf ) {
        buf.toString().split( "\n" ).forEach(function( data ) {

            if ( data.length <=0 ) {
                return;
            }

            try {
            data = JSON.parse( data );
            } catch(e) {
                util.print( "bad data: " + data );
                return;
            }

            report.assertions++;

            // its coverage json
            if ( data.cov ) {
                cov = data.cov;
                return;
            }

            if ( data.name !== testname ) {
                report.tests++;
                testname = data.name;
            }

            if ( data.errorStack ) {
                report.errors++;
            }

            logTest( data );
        });
    });

    child.stderr.on( "data", function ( buf ) {
        util.print( "stderr: " + buf );
    });

    child.on( "exit", function( code ) {
        report.files++;

        if ( typeof callback === "function" ) {
            callback( cov );
        }
    });
}

/**
 * Make an absolute path from relative
 * @param {String|Object} file
 * @return {String|Object}
 */
function absPath( file ) {
    if ( typeof file === "string" && file.charAt(0) !== "/" ) {
        file = path.join( process.cwd(), file );
    } else if ( file.file && file.file.charAt(0) !== "/" ) {
        file.file = path.join( process.cwd(), file.file );
    }

    return file;
}

/**
 * Convert path or array of paths to array of abs paths
 * @param {Array|String|Object} files
 * @return {Array}
 */
function toArray( files ) {
    var ret = [];

    if ( Array.isArray(files) ) {
        files.forEach( function( file ) {
            ret.push( absPath(file) );
        });
    } else {
        ret.push( absPath(files) );
    }

    return ret;
}

/**
 * Run tests in spawned node instance async for every test.
 * @param {Object|Array} files
 * @param {Function} callback optional
 */
exports.run = function( files, callback ) {

    if ( !(files instanceof Array) ) {
        files = [files];
    }

    var report = {
            files: 0,
            tests: 0,
            assertions: 0,
            errors: 0,
            success: 0,
            time: Date.now()
        };

    files.forEach( function( opts ) {

        opts =  {
            deps: toArray( opts.deps || options.deps ),
            code: absPath( opts.code ),
            as: opts.as,
            tests: toArray( opts.tests ),
            paths: opts.paths || options.paths,
            coverage: opts.coverage || options.coverage
        };

        function finished( cov ) {
            if ( report.files < files.length ) {
                return;
            }

            if ( options.summary ) {
                report.success = report.assertions - report.errors;
                report.time = Date.now() - report.time;
                printSummary( report, cov );
            }

            if ( typeof callback === "function" ) {
                callback( report );
            }
        }

        if ( opts.coverage ) {
            coverage.instrument( opts.code.file, function( newCodePath, cleanup ) {
                opts.code.file = newCodePath;
                run( opts, report, function(cov) {
                    cleanup();
                    finished(cov);
                });
            });
        } else {
            run( opts, report, finished );
        }
    });
};<|endoftext|>


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

gulp.task('clean', function () {
    return gulp.src('dist').pipe(clean());
});

gulp.task('default', ['clean'], function () {
    return gulp.src([
        'src/**/crt/**',
        'src/**/client/**',
    ])
        .pipe(gulp.dest('dist'));
});<commit_msg>构建迁移 views 文件夹<commit_after>const gulp = require('gulp');
const clean = require('gulp-clean');

gulp.task('clean', function () {
    return gulp.src('dist').pipe(clean());
});

gulp.task('default', ['clean'], function () {
    return gulp.src([
        'src/**/crt/**',
        'src/**/client/**',
        'src/**/views/**',
    ])
        .pipe(gulp.dest('dist'));
});<|endoftext|>


<commit_before>module.exports = class Radar {
  constructor(github, config) {
    this.github = github;
    this.config = Object.assign({}, require('./defaults'), config || {});
    this.logger = config.logger || console;
  }

  //return most recent blocked issues
  async getIssuesWithLabel(){
    const {owner, repo, labels} = this.config;
    this.logger.info(owner, repo, labels);
    var all_issues = [];
    labels.forEach(label => {
      var query = `repo:${owner}/${repo} is:issue is:open label:${label} `
      const params = {
        q: query,
        sort: 'updated',
        order: 'desc',
        per_page: 100
      };

      this.logger.info(params, 'searching %s/%s for blocked issues', owner, repo);
      issues = await this.github.search.issues(params);
      all_issues.push(issues);
    });

    this.logger.info("all_issues:", all_issues)
    return all_issues;
  }
};
<commit_msg>add await one level higher since it can't be in a non-async function<commit_after>module.exports = class Radar {
  constructor(github, config) {
    this.github = github;
    this.config = Object.assign({}, require('./defaults'), config || {});
    this.logger = config.logger || console;
  }

  //return most recent blocked issues
  async getIssuesWithLabel(){
    const {owner, repo, labels} = this.config;
    this.logger.info(owner, repo, labels);
    var all_issues = [];
    await labels.forEach(label => {
      var query = `repo:${owner}/${repo} is:issue is:open label:${label} `
      const params = {
        q: query,
        sort: 'updated',
        order: 'desc',
        per_page: 100
      };

      this.logger.info(params, 'searching %s/%s for blocked issues', owner, repo);
      issues = this.github.search.issues(params);
      all_issues.push(issues);
    });

    this.logger.info("all_issues:", all_issues)
    return all_issues;
  }
};
<|endoftext|>


<commit_before>"use strict";
/*global require*/
var _                = require("lodash");
var del              = require("del");
var path             = require("path");
var runSequence      = require("run-sequence");

var gulp             = require("gulp");
var harmonize        = require("harmonize");
var awspublish       = require("gulp-awspublish");
var rename           = require("gulp-rename");
var parallelize      = require("concurrent-transform");
var gutil            = require("gulp-util");
var deploy           = require("gulp-gh-pages");
var notifier         = require("node-notifier");
var merge            = require('merge-stream');

var ngrok            = require('ngrok');
var webpack          = require("webpack");
var WebpackDevServer = require("webpack-dev-server");

// Get our Config.
var config           = require("./config");
var webpackConfig    = require("./webpack.config");

harmonize();

var notify = function(message){
  notifier.notify({title: config.displayName+" Gulp",message:message});
};

// Setup a Ngrok server
var ngrokServe = function(subdomain){
  var options = { port: config.serverPort };
  var env = process.env;
  if (env.NGROK_AUTHTOKEN) {
    options.authtoken = env.NGROK_AUTHTOKEN;
  }
  if(env.NGROK_SUBDOMAIN || subdomain){
    options.subdomain = (env.NGROK_SUBDOMAIN || subdomain).replace(/-/g,'');
  }
  ngrok.connect(options, function (error, url) {
    if (error) {
      throw new gutil.PluginError('ship:server', error);
    }

    url = url.replace('https', 'http');
    notify({message:"Ngrok Started on "+url});

    gutil.log('[ship:server]', url);
  });
}

gulp.task("default", ["server"]);
gulp.task("serve",   ["server"]);
gulp.task("clean",   function(callback) {del(["./"+config.outputFolder+"/**/*"], callback); });

gulp.task("server",  function(callback) {runSequence("clean", "copy-files:watch", "webpack:server", callback); });
gulp.task("build",   function(callback) {runSequence("clean", "copy-files", "webpack:build", callback); });
gulp.task("deploy",  function(callback) {runSequence("build", "publish:sha", callback); });
gulp.task("deploy:release",  function(callback) {runSequence("build", "publish:release", callback); });

var notify = function(message){
  notifier.notify({title: config.displayName+" Gulp", message: message});
};
var handleError = function(err, taskName){
  if(err){
    notify(taskName+" Error: "+ err);
    throw new gutil.PluginError("webpack:build", err);
  }
};
// Copy static files from the source to the destination
var copyFiles = function(callback){
  _.map(config.files, function(dest, src){
    gulp.src(src).pipe(gulp.dest(dest));
  });
  notify("Vendors Updated");
  if (_.isFunction(callback)){
    callback();
  }
};

gulp.task("copy-files", copyFiles);

gulp.task("copy-files:watch", function(){
  copyFiles();
  gulp.watch(_.keys(config.files), copyFiles);
});

//Production Build.
//Minified, clean code. No demo keys inside.
//demo.html WILL NOT WORK with this build.
//
//Webpack handles CSS/SCSS, JS, and HTML files.
var afterBuild = function(err, stats){
  if (!!err) {throw new gutil.PluginError("webpack:build", err); }

  var jsonStats = stats.toJson();

  if (jsonStats.errors.length > 0) {
    return new gutil.PluginError("webpack:build", JSON.stringify(jsonStats.errors));
  }

  if (jsonStats.warnings.length > 0) {
    new gutil.PluginError("webpack:build", JSON.stringify(jsonStats.warnings));
  }

  gutil.log("[webpack:build]", stats.toString({colors: true}));
  notify("App Built");
};
gulp.task("webpack:build", function(callback) {
  // Then, use Webpack to bundle all JS and html files to the destination folder
  notify("Building App");
  webpack(_.values(webpackConfig.production), function(err, stats) {
    afterBuild(err, stats);
    webpack(_.values(webpackConfig.debug), function(err, stats){
      afterBuild(err, stats);
      callback();
    });
  });
});

// Dev Build
// Create the webpack compiler here for caching and performance.
var devCompiler = webpack(webpackConfig.development.browser);

// Build a Dev version of the project. Launched once on startup so we can have eveything copied.
gulp.task("webpack:build:dev", function(callback) {
  // run webpack with Dev profile.
  // Embeds the Hull config keys, and the necessary stuff to make demo.html work
  devCompiler.run(function(err, stats) {
    if (err){
      throw new gutil.PluginError("webpack:build:dev", err);
    }

    var jsonStats = stats.toJson();

    if(jsonStats.errors.length > 0){
      return new gutil.PluginError("webpack:build:dev", JSON.stringify(jsonStats.errors));
    }

    if(jsonStats.warnings.length > 0){
      new gutil.PluginError("webpack:build:dev", JSON.stringify(jsonStats.warnings));
    }

    gutil.log("[webpack:build:dev]", stats.toString({colors: true}));
    notify({message: "Webpack Updated"});
    callback();
  });
});

// Launch webpack dev server.
gulp.task("webpack:server", function() {
  var taskName = "webpack:server";
  new WebpackDevServer(devCompiler, {
    contentBase: config.outputFolder,
    publicPath: config.assetsFolder+"/",
    hot: config.hotReload,
    stats: {colors: true }
  }).listen(config.serverPort, function(err) {
    handleError(err, taskName);
    // Dump the preview URL in the console, and open Chrome when launched for convenience.
    notify({message: "Dev Server Started"});
    var url = webpackConfig.development.browser.output.publicPath+"webpack-dev-server/";
    ngrokServe(config.libName)
    gutil.log("["+taskName+"]", url);
  });
});

var publish = function(versions){
  var aws = config.aws
  var publisher = awspublish.create(aws.config);
  var files  = path.join(config.outputFolder, config.assetsFolder, "*")
  var streams = [];
  for (var i = 0; i < versions.length; i++) {
    var version = versions[i];
    if(version){
      console.log('Deploying to ',version);
      var plain = gulp.src(files)
      .pipe(rename(function(p){
        p.dirname += '/'+version;
        console.log('Publishing '+path.join(p.dirname,p.basename+p.extname))
      }))
      var gzip = gulp.src(files)
      .pipe(rename(function(p){
        p.dirname += '/'+version;
        console.log('Publishing '+path.join(p.dirname,p.basename+p.extname))
      }))
      .pipe(awspublish.gzip(aws.gzip))

      streams.push(plain);
      streams.push(gzip);
    }
  };
  return merge.apply(merge,streams)
  .pipe(parallelize(publisher.publish(aws.publish.headers,aws.publish.options)))
  .pipe(publisher.cache())
  .pipe(awspublish.reporter())
;
}

// Deploys to S3
gulp.task('publish:sha',function(){
  var SHA1 = process.env.CIRCLE_SHA1;
  // if( !SHA1 ){ return; }
  return publish([SHA1]);
});

gulp.task('publish:release',function(){
  var SHA1 = process.env.CIRCLE_SHA1;
  var RELEASE = config.pkg.version;
  // if( !SHA1 || !RELEASE ){ return; }
  return publish([SHA1,RELEASE]);
});
<commit_msg>enable safeguard. Don't deploy unless we have what we need<commit_after>"use strict";
/*global require*/
var _                = require("lodash");
var del              = require("del");
var path             = require("path");
var runSequence      = require("run-sequence");

var gulp             = require("gulp");
var harmonize        = require("harmonize");
var awspublish       = require("gulp-awspublish");
var rename           = require("gulp-rename");
var parallelize      = require("concurrent-transform");
var gutil            = require("gulp-util");
var deploy           = require("gulp-gh-pages");
var notifier         = require("node-notifier");
var merge            = require('merge-stream');

var ngrok            = require('ngrok');
var webpack          = require("webpack");
var WebpackDevServer = require("webpack-dev-server");

// Get our Config.
var config           = require("./config");
var webpackConfig    = require("./webpack.config");

harmonize();

var notify = function(message){
  notifier.notify({title: config.displayName+" Gulp",message:message});
};

// Setup a Ngrok server
var ngrokServe = function(subdomain){
  var options = { port: config.serverPort };
  var env = process.env;
  if (env.NGROK_AUTHTOKEN) {
    options.authtoken = env.NGROK_AUTHTOKEN;
  }
  if(env.NGROK_SUBDOMAIN || subdomain){
    options.subdomain = (env.NGROK_SUBDOMAIN || subdomain).replace(/-/g,'');
  }
  ngrok.connect(options, function (error, url) {
    if (error) {
      throw new gutil.PluginError('ship:server', error);
    }

    url = url.replace('https', 'http');
    notify({message:"Ngrok Started on "+url});

    gutil.log('[ship:server]', url);
  });
}

gulp.task("default", ["server"]);
gulp.task("serve",   ["server"]);
gulp.task("clean",   function(callback) {del(["./"+config.outputFolder+"/**/*"], callback); });

gulp.task("server",  function(callback) {runSequence("clean", "copy-files:watch", "webpack:server", callback); });
gulp.task("build",   function(callback) {runSequence("clean", "copy-files", "webpack:build", callback); });
gulp.task("deploy",  function(callback) {runSequence("build", "publish:sha", callback); });
gulp.task("deploy:release",  function(callback) {runSequence("build", "publish:release", callback); });

var notify = function(message){
  notifier.notify({title: config.displayName+" Gulp", message: message});
};
var handleError = function(err, taskName){
  if(err){
    notify(taskName+" Error: "+ err);
    throw new gutil.PluginError("webpack:build", err);
  }
};
// Copy static files from the source to the destination
var copyFiles = function(callback){
  _.map(config.files, function(dest, src){
    gulp.src(src).pipe(gulp.dest(dest));
  });
  notify("Vendors Updated");
  if (_.isFunction(callback)){
    callback();
  }
};

gulp.task("copy-files", copyFiles);

gulp.task("copy-files:watch", function(){
  copyFiles();
  gulp.watch(_.keys(config.files), copyFiles);
});

//Production Build.
//Minified, clean code. No demo keys inside.
//demo.html WILL NOT WORK with this build.
//
//Webpack handles CSS/SCSS, JS, and HTML files.
var afterBuild = function(err, stats){
  if (!!err) {throw new gutil.PluginError("webpack:build", err); }

  var jsonStats = stats.toJson();

  if (jsonStats.errors.length > 0) {
    return new gutil.PluginError("webpack:build", JSON.stringify(jsonStats.errors));
  }

  if (jsonStats.warnings.length > 0) {
    new gutil.PluginError("webpack:build", JSON.stringify(jsonStats.warnings));
  }

  gutil.log("[webpack:build]", stats.toString({colors: true}));
  notify("App Built");
};
gulp.task("webpack:build", function(callback) {
  // Then, use Webpack to bundle all JS and html files to the destination folder
  notify("Building App");
  webpack(_.values(webpackConfig.production), function(err, stats) {
    afterBuild(err, stats);
    webpack(_.values(webpackConfig.debug), function(err, stats){
      afterBuild(err, stats);
      callback();
    });
  });
});

// Dev Build
// Create the webpack compiler here for caching and performance.
var devCompiler = webpack(webpackConfig.development.browser);

// Build a Dev version of the project. Launched once on startup so we can have eveything copied.
gulp.task("webpack:build:dev", function(callback) {
  // run webpack with Dev profile.
  // Embeds the Hull config keys, and the necessary stuff to make demo.html work
  devCompiler.run(function(err, stats) {
    if (err){
      throw new gutil.PluginError("webpack:build:dev", err);
    }

    var jsonStats = stats.toJson();

    if(jsonStats.errors.length > 0){
      return new gutil.PluginError("webpack:build:dev", JSON.stringify(jsonStats.errors));
    }

    if(jsonStats.warnings.length > 0){
      new gutil.PluginError("webpack:build:dev", JSON.stringify(jsonStats.warnings));
    }

    gutil.log("[webpack:build:dev]", stats.toString({colors: true}));
    notify({message: "Webpack Updated"});
    callback();
  });
});

// Launch webpack dev server.
gulp.task("webpack:server", function() {
  var taskName = "webpack:server";
  new WebpackDevServer(devCompiler, {
    contentBase: config.outputFolder,
    publicPath: config.assetsFolder+"/",
    hot: config.hotReload,
    stats: {colors: true }
  }).listen(config.serverPort, function(err) {
    handleError(err, taskName);
    // Dump the preview URL in the console, and open Chrome when launched for convenience.
    notify({message: "Dev Server Started"});
    var url = webpackConfig.development.browser.output.publicPath+"webpack-dev-server/";
    ngrokServe(config.libName)
    gutil.log("["+taskName+"]", url);
  });
});

var publish = function(versions){
  var aws = config.aws
  var publisher = awspublish.create(aws.config);
  var files  = path.join(config.outputFolder, config.assetsFolder, "*")
  var streams = [];
  for (var i = 0; i < versions.length; i++) {
    var version = versions[i];
    if(version){
      console.log('Deploying to ',version);
      var plain = gulp.src(files)
      .pipe(rename(function(p){
        p.dirname += '/'+version;
        console.log('Publishing '+path.join(p.dirname,p.basename+p.extname))
      }))
      var gzip = gulp.src(files)
      .pipe(rename(function(p){
        p.dirname += '/'+version;
        console.log('Publishing '+path.join(p.dirname,p.basename+p.extname))
      }))
      .pipe(awspublish.gzip(aws.gzip))

      streams.push(plain);
      streams.push(gzip);
    }
  };
  return merge.apply(merge,streams)
  .pipe(parallelize(publisher.publish(aws.publish.headers,aws.publish.options)))
  .pipe(publisher.cache())
  .pipe(awspublish.reporter())
;
}

// Deploys to S3
gulp.task('publish:sha',function(){
  var SHA1 = process.env.CIRCLE_SHA1;
  if( !SHA1 ){ return; }
  return publish([SHA1]);
});

gulp.task('publish:release',function(){
  var SHA1 = process.env.CIRCLE_SHA1;
  var RELEASE = config.pkg.version;
  if( !SHA1 || !RELEASE ){ return; }
  return publish([SHA1,RELEASE]);
});
<|endoftext|>


<commit_before>const Ajv   = require('ajv');
const {Map} = require('immutable');
const is    = require('is_js');

const {randomInt} = require('./random');

class Ratio {
  constructor(param) {
    this.map = Ratio.validate(param);

    [this.ranges, this.max] = this.map
      .filter((v) => v > 0)
      .reduce(([map, sum], v, k) => {
        const upper = sum + v;
        return [map.set(k, [sum + 1, upper]), upper];
      }, [Map(), 0]);
  }

  sample() {
    const sample = randomInt(1, this.max);
    const key    = this.ranges.findKey(([lower, upper]) => lower <= sample && sample <= upper);
    return is.existy(key) ? key : null;
  }

  static validate(param) {
    const schema = {
      type                : 'object',
      additionalProperties: {type: ['null', 'integer']},
    };
    const ajv     = new Ajv();
    const isValid = ajv.validate(schema, param);
    if (!isValid) {
      throw new Error('1st argument{k_1: v_1, ...} must satisfy any v_i is "null" or "integer"');
    }
    return Map(param).filter(is.existy);
  }
}

module.exports = Ratio;
<commit_msg>Add notification comment<commit_after>const Ajv   = require('ajv');
const {Map} = require('immutable');
const is    = require('is_js');

const {randomInt} = require('./random');

class Ratio {
  constructor(param) {
    this.map = Ratio.validate(param);

    [this.ranges, this.max] = this.map
      .filter((v) => v > 0)
      .reduce(([map, sum], v, k) => {
        const upper = sum + v;
        return [map.set(k, [sum + 1, upper]), upper];
      }, [Map(), 0]);
  }

  sample() {
    const sample = randomInt(1, this.max);
    const key    = this.ranges.findKey(([lower, upper]) => lower <= sample && sample <= upper);
    return is.existy(key) ? key : null;
  }

  static validate(param) {
    // NOTICE: keys with "undefined" are not ignored!
    const schema = {
      type                : 'object',
      additionalProperties: {type: ['null', 'integer']},
    };
    const ajv     = new Ajv();
    const isValid = ajv.validate(schema, param);
    if (!isValid) {
      throw new Error('1st argument{k_1: v_1, ...} must satisfy any v_i is "null" or "integer"');
    }
    return Map(param).filter(is.existy);
  }
}

module.exports = Ratio;
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp');
var run = require('run-sequence');

// Load ngFactory tasks
require('./ng-factory');

gulp.task('build', ['dist']);
gulp.task('serve', ['docs']);

gulp.task('readme', function() {
  run('ng-factory:docs/ngdocs', 'ng-factory:docs/readme');
});

gulp.task('dist', function() {
  run('ng-factory:src/clean', ['ng-factory:src/templates', 'ng-factory:src/styles', 'ng-factory:src/scripts']);
});

gulp.task('docs', function() {
  run(
    'ng-factory:docs/clean',
    ['ng-factory:docs/views', 'ng-factory:docs/scripts', 'ng-factory:docs/styles', 'ng-factory:docs/connect'],
    ['ng-factory:docs/watch', 'ng-factory:docs/open']
  );
});

gulp.task('pages', function() {
  run('ng-factory:clean/docs(pages)', ['ng-factory:views/docs(pages)', 'connect:src'], ['open:src', 'watch:src']);
});

gulp.task('lint', function (cb) {
  run([
    'ng-factory:src/jshint',
    'ng-factory:test/jshint'
  ], cb);
});

gulp.task('karma', function(cb){
  run(
    'ng-factory:src/clean',
    'ng-factory:src/templates:to(src.tmp)',
    'ng-factory:src/karma',
    cb);
});

gulp.task('coverage', function (cb) {
  run(
    'ng-factory:src/clean',
    'ng-factory:src/templates:to(src.tmp)',
    'ng-factory:src/karma:with(coverage)',
    cb);
});

// var runSequence = require('run-sequence');
// gulp.task('default', ['dist']);
// gulp.task('build', ['dist']);
// gulp.task('test', function() {
//   runSequence('clean:test', 'templates:test', ['jshint', 'karma:unit']);
// });
// gulp.task('test:server', function() {
//   runSequence('clean:test', 'templates:test', 'karma:server');
// });
// gulp.task('dist', function() {
//   runSequence('clean:dist', ['templates:dist', 'scripts:dist']);
// });
// gulp.task('pages', function() {
//   runSequence('clean:pages', 'styles:docs', 'views:pages', ['templates:pages', 'scripts:pages', 'copy:pages']);
// });
// gulp.task('serve', function() {
//   runSequence('clean:tmp', ['styles:docs', 'connect:docs'], ['open:docs', 'watch:docs']); // , 'watch:dev'
// });
// gulp.task('serve:pages', ['connect:pages', 'open:pages']);
<commit_msg>chore(task): add default task<commit_after>'use strict';

var gulp = require('gulp');
var run = require('run-sequence');

// Load ngFactory tasks
require('./ng-factory');
gulp.task('default', ['lint', 'karma']);
gulp.task('build', ['dist']);
gulp.task('serve', ['docs']);

gulp.task('readme', function() {
  run('ng-factory:docs/ngdocs', 'ng-factory:docs/readme');
});

gulp.task('dist', function() {
  run('ng-factory:src/clean', ['ng-factory:src/templates', 'ng-factory:src/styles', 'ng-factory:src/scripts']);
});

gulp.task('docs', function() {
  run(
    'ng-factory:docs/clean',
    ['ng-factory:docs/views', 'ng-factory:docs/scripts', 'ng-factory:docs/styles', 'ng-factory:docs/connect'],
    ['ng-factory:docs/watch', 'ng-factory:docs/open']
  );
});

gulp.task('pages', function() {
  run('ng-factory:clean/docs(pages)', ['ng-factory:views/docs(pages)', 'connect:src'], ['open:src', 'watch:src']);
});

gulp.task('lint', function (cb) {
  run([
    'ng-factory:src/jshint',
    'ng-factory:test/jshint'
  ], cb);
});

gulp.task('karma', function(cb){
  run(
    'ng-factory:src/clean',
    'ng-factory:src/templates:to(src.tmp)',
    'ng-factory:src/karma',
    cb);
});

gulp.task('coverage', function (cb) {
  run(
    'ng-factory:src/clean',
    'ng-factory:src/templates:to(src.tmp)',
    'ng-factory:src/karma:with(coverage)',
    cb);
});

// var runSequence = require('run-sequence');
// gulp.task('default', ['dist']);
// gulp.task('build', ['dist']);
// gulp.task('test', function() {
//   runSequence('clean:test', 'templates:test', ['jshint', 'karma:unit']);
// });
// gulp.task('test:server', function() {
//   runSequence('clean:test', 'templates:test', 'karma:server');
// });
// gulp.task('dist', function() {
//   runSequence('clean:dist', ['templates:dist', 'scripts:dist']);
// });
// gulp.task('pages', function() {
//   runSequence('clean:pages', 'styles:docs', 'views:pages', ['templates:pages', 'scripts:pages', 'copy:pages']);
// });
// gulp.task('serve', function() {
//   runSequence('clean:tmp', ['styles:docs', 'connect:docs'], ['open:docs', 'watch:docs']); // , 'watch:dev'
// });
// gulp.task('serve:pages', ['connect:pages', 'open:pages']);
<|endoftext|>


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

var chug = require('gulp-chug');
var clean = require('gulp-rimraf');
var jshint = require('gulp-jshint');
var rename = require('gulp-rename');
var render = require('gulp-dust-render');
var uglify_ = require('gulp-uglify');

var pretty = {
    mangle : false,
    output : { beautify : true },
    compress : false,
    preserveComments : 'all'
};
var optimal = {};
var uglify = function () { return uglify_(pretty); };

gulp.task('watch', function () {
    gulp.watch('./src/**/*.js');
    gulp.watch([
         './src/template/decode/**/*',
        '!./src/template/decode/script{,/**}'
    ], ['decode']);
});

gulp.task('build', ['decode']);

gulp.task('decode', ['buildDecode'], function () {
    return gulp.src('./src/decode/script/**/*.js')
        .pipe(jshint())
        .pipe(jshint.reporter('default'))
        .pipe(gulp.dest('./lib/decode'));
});

gulp.task('buildDecode', function () {
    return gulp.src('./src/decode/gulpfile.js', { read : false })
        .pipe(chug({ tasks : ['build'] }))
});

//gulp.task('ci', function () {
//    return gulp.src('./src/decode/gulpfile.js', { read : false })
//        .pipe(chug({ tasks : ['ci'] }));
//});

gulp.task('clean', ['cleanDecode'], function () {
    return gulp.src('./lib/**/*')
        .pipe(clean());
});

gulp.task('cleanDecode', function () {
    return gulp.src('./src/decode/gulpfile.js', { read : false })
        .pipe(chug({ tasks : ['clean'] }))
});

var file = require('./lib/decode/file');
gulp.task('generator', function() {
    return gulp.src('./generator/schema.js')
        .pipe(render(file))
        .pipe(uglify())
        .pipe(rename('reader.js'))
        .pipe(jshint())
        .pipe(jshint.reporter('default'))
        .pipe(gulp.dest('generator'));
});
<commit_msg>Clobber built code generator request reader on clean<commit_after>var gulp = require('gulp');

var chug = require('gulp-chug');
var clean = require('gulp-rimraf');
var jshint = require('gulp-jshint');
var rename = require('gulp-rename');
var render = require('gulp-dust-render');
var uglify_ = require('gulp-uglify');

var pretty = {
    mangle : false,
    output : { beautify : true },
    compress : false,
    preserveComments : 'all'
};
var optimal = {};
var uglify = function () { return uglify_(pretty); };

gulp.task('watch', function () {
    gulp.watch('./src/**/*.js');
    gulp.watch([
         './src/template/decode/**/*',
        '!./src/template/decode/script{,/**}'
    ], ['decode']);
});

gulp.task('build', ['decode']);

gulp.task('decode', ['buildDecode'], function () {
    return gulp.src('./src/decode/script/**/*.js')
        .pipe(jshint())
        .pipe(jshint.reporter('default'))
        .pipe(gulp.dest('./lib/decode'));
});

gulp.task('buildDecode', function () {
    return gulp.src('./src/decode/gulpfile.js', { read : false })
        .pipe(chug({ tasks : ['build'] }))
});

//gulp.task('ci', function () {
//    return gulp.src('./src/decode/gulpfile.js', { read : false })
//        .pipe(chug({ tasks : ['ci'] }));
//});

gulp.task('clean', ['cleanDecode'], function () {
    return gulp.src(['./lib/**/*', './generator/reader.js'])
        .pipe(clean());
});

gulp.task('cleanDecode', function () {
    return gulp.src('./src/decode/gulpfile.js', { read : false })
        .pipe(chug({ tasks : ['clean'] }))
});

var file = require('./lib/decode/file');
gulp.task('generator', function() {
    return gulp.src('./generator/schema.js')
        .pipe(render(file))
        .pipe(uglify())
        .pipe(rename('reader.js'))
        .pipe(jshint())
        .pipe(jshint.reporter('default'))
        .pipe(gulp.dest('generator'));
});
<|endoftext|>


<commit_before>var gulp        = require('gulp'),
    bowerSrc    = require('gulp-bower'),
    uglify      = require('gulp-uglify'),
    rimraf      = require('rimraf'),
    concat      = require('gulp-concat');

gulp.task('bower', function () {
    return bowerSrc()
        .pipe(gulp.dest('bower'));
});

gulp.task('bower-concat', ['bower'], function () {
    return gulp
        .src([
            'bower_components/angularjs/angular.js',
            'bower_components/timeline/timeline.min.js'
        ])
        .pipe(concat('bower-deps.min.js'))
        .pipe(uglify())
        .pipe(gulp.dest('static/js/'));
});

gulp.task('scripts', ['bower-concat'], function () {
    return gulp.
        src('static/js/src/*.js')
        .pipe(concat('main-deps.min.js'))
        .pipe(uglify())
        .pipe(gulp.dest('static/js/'));
});

gulp.task('default', ['scripts'], function () {
    rimraf('bower_components', function () {
    });

    rimraf('bower', function () {
    });
});
<commit_msg>Added gulp tasks for extracting css and fonts for Bootstrap<commit_after>var gulp        = require('gulp'),
    bowerSrc    = require('gulp-bower'),
    uglify      = require('gulp-uglify'),
    rimraf      = require('rimraf'),
    concat      = require('gulp-concat');

gulp.task('bower', function () {
    return bowerSrc();
});

gulp.task('bower-extract-bootstrap-fonts', ['bower'], function () {
    return gulp
        .src([
            'bower_components/bootstrap/fonts/*'
        ])
        .pipe(gulp.dest('static/fonts/'));
});

gulp.task('bower-concat-css', ['bower'], function () {
    return gulp
        .src([
            'bower_components/bootstrap/dist/css/bootstrap.css',
            'bower_components/bootstrap/dist/css/bootstrap-theme.css'
        ])
        .pipe(concat('bower-deps.min.css'))
        .pipe(gulp.dest('static/css/'));
});

gulp.task('bower-concat-js', ['bower'], function () {
    return gulp
        .src([
            'bower_components/angularjs/angular.js',
            'bower_components/bootstrap/dist/js/bootstrap.js',
            'bower_components/timeline/timeline.min.js'
        ])
        .pipe(concat('bower-deps.min.js'))
        .pipe(uglify())
        .pipe(gulp.dest('static/js/'));
});

gulp.task('scripts', ['bower-concat-js', 'bower-concat-css', 'bower-extract-bootstrap-fonts'], function () {
    return gulp.
        src('static/js/src/*.js')
        .pipe(concat('main-deps.min.js'))
        .pipe(uglify())
        .pipe(gulp.dest('static/js/'));
});

gulp.task('default', ['scripts'], function () {
    rimraf('bower_components', function () {
    });
});
<|endoftext|>


<commit_before>var gulp       = require('gulp'),
    ts         = require('gulp-typescript'),
    merge      = require('merge2'),
    mocha      = require('gulp-mocha'),
    sourcemaps = require('gulp-sourcemaps'),
    tsd        = require('gulp-tsd'),
    gutil      = require('gulp-util'),
    del        = require('del'),
    gsync       = require('gulp-sync')(gulp),
    bump       = require('gulp-bump');

var PATHS = {
    lib: 'lib',
    build: 'build',
    test: 'test'
};

var tsProject = ts.createProject({
    declarationFiles: true,
    noEmitOnError: true,
    module: 'commonjs',
    target: 'es5',
    sortOutput: true,
    typescript: require('typescript') //usefull during typescript 1.5 alpha
});

/**
 * BUMP tasks
 */
gulp.task('bump', function() {
    gulp.src('./package.json')
        .pipe(bump())
        .pipe(gulp.dest('./'));
});
gulp.task('bump:minor', function() {
    gulp.src('./package.json')
        .pipe(bump({type: 'minor'}))
        .pipe(gulp.dest('./'));
});
gulp.task('bump:major', function() {
    gulp.src('./package.json')
        .pipe(bump({type: 'major'}))
        .pipe(gulp.dest('./'));
});

/**
 * BUILD task
 */
gulp.task('build', function() {
    var tsResult = gulp.src([
        'cli.ts',
        PATHS.lib + '/**/*.ts'
    ])
        .pipe(sourcemaps.init())
        .pipe(ts(tsProject));

    return merge([ // Merge the two output streams, so this task is finished when the IO of both operations are done.
        tsResult.dts.pipe(gulp.dest(PATHS.build + '/definitions')),
        tsResult.js
            .pipe(sourcemaps.write())
            .pipe(gulp.dest(PATHS.build + '/js'))
    ]);
});
gulp.task('build:watch', ['build'], function() {
    gulp.watch([
        PATHS.lib + '/**/*.ts'
    ], ['build']);
});
gulp.task('tsd:install', function(callback) {
    tsd({
        command: 'reinstall',
        config: './tsd.json'
    }, callback);
});

/**
 * TEST tasks
 */
gulp.task('test', function () {
    return gulp.src(PATHS.test + '/**/*.js', {read: false})
        .pipe(mocha({
            reporter: 'spec',
            globals: {
                should: require('should')
            }
        }))
        .on('error', gutil.log);
});
gulp.task('test:watch', ['test'], function () {
    gulp.watch([
        PATHS.lib + '/**/*.js',
        PATHS.test + '/**/*.js'
    ], ['test']);
});

gulp.task('clean', function(cb) {
    del([
        'build',
        'typings'
    ], cb);
});

gulp.task('ci', gsync.sync(['clean', 'tsd:install', 'build', 'test']));
<commit_msg>chore: review gulp file<commit_after>var gulp       = require('gulp'),
    ts         = require('gulp-typescript'),
    merge      = require('merge2'),
    mocha      = require('gulp-mocha'),
    sourcemaps = require('gulp-sourcemaps'),
    tsd        = require('gulp-tsd'),
    gutil      = require('gulp-util'),
    del        = require('del'),
    gsync       = require('gulp-sync')(gulp),
    bump       = require('gulp-bump');

var PATHS = {
    lib: 'lib',
    build: 'build',
    test: 'test'
};

var tsProject = ts.createProject({
    declarationFiles: true,
    noEmitOnError: true,
    module: 'commonjs',
    target: 'es5',
    sortOutput: true,
    typescript: require('typescript') //usefull during typescript 1.5 alpha
});

/**
 * BUMP tasks
 */
gulp.task('bump', function() {
    gulp.src('./package.json')
        .pipe(bump())
        .pipe(gulp.dest('./'));
});
gulp.task('bump:minor', function() {
    gulp.src('./package.json')
        .pipe(bump({type: 'minor'}))
        .pipe(gulp.dest('./'));
});
gulp.task('bump:major', function() {
    gulp.src('./package.json')
        .pipe(bump({type: 'major'}))
        .pipe(gulp.dest('./'));
});

/**
 * BUILD task
 */
gulp.task('build', function() {
    var tsResult = gulp.src([
        'cli.ts',
        PATHS.lib + '/**/*.ts'
    ])
        .pipe(sourcemaps.init())
        .pipe(ts(tsProject));

    return merge([ // Merge the two output streams, so this task is finished when the IO of both operations are done.
        tsResult.dts.pipe(gulp.dest(PATHS.build + '/definitions')),
        tsResult.js
            .pipe(sourcemaps.write())
            .pipe(gulp.dest(PATHS.build + '/js'))
    ]);
});
gulp.task('build:watch', ['build'], function() {
    gulp.watch([
        PATHS.lib + '/**/*.ts'
    ], ['build']);
});
gulp.task('tsd:install', function(callback) {
    tsd({
        command: 'reinstall',
        config: './tsd.json'
    }, callback);
});

/**
 * TEST tasks
 */
gulp.task('test', function () {
    return gulp.src(PATHS.test + '/**/*.js', {read: false})
        .pipe(mocha({
            reporter: 'spec',
            globals: {
                should: require('should')
            }
        }))
        .on('error', gutil.log);
});
gulp.task('test:watch', ['test'], function () {
    gulp.watch([
        PATHS.lib + '/**/*.js',
        PATHS.test + '/**/*.js'
    ], ['test']);
});

/**
 * CLEANING tasks
 */
gulp.task('clean', function(cb) {
    del([
        'build',
        'typings'
    ], cb);
});

/**
 * CI tasks
 */
gulp.task('ci', gsync.sync(['clean', 'tsd:install', 'build', 'test']));
<|endoftext|>


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

var jshint = require('gulp-jshint');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var concat = require('gulp-concat');
var clean = require('gulp-clean');
var header = require('gulp-header');
var streamify = require('gulp-streamify');
var qunit = require('gulp-qunit');
var pkg = require('./package.json');
var shell = require('gulp-shell');

var banner = ['/**',
    ' * <%= pkg.name %> - <%= pkg.description %>',
    ' * @version v<%= pkg.version %>',
    ' * @link <%= pkg.homepage %>',
    ' * @license <%= pkg.license %>',
    ' */',
].join('\n');

var filePath = {
    src: './src/*.js',
    dest: './openui5/googlemaps'
};

gulp.task('clean', function() {
    return gulp.src(filePath.dest, {
        read: false
    }).pipe(clean());
});

//TODO - all scripts tasks with one stream
gulp.task('scripts-dbg', function() {
    gulp.src(filePath.src)
        .pipe(header(banner, {
            pkg: pkg
        }))
        .pipe(rename({
            suffix: '-dbg'
        }))
        .pipe(gulp.dest(filePath.dest));
});

gulp.task('scripts-min', function() {
    gulp.src(filePath.src)
        .pipe(streamify(uglify()))
        .pipe(gulp.dest(filePath.dest))
        .pipe(concat('library-all.js'))
        .pipe(gulp.dest(filePath.dest));
});

// JSHint task
gulp.task('lint', function() {
    gulp.src(filePath.src)
        .pipe(jshint())
        .pipe(jshint.reporter('default'));
});

gulp.task('watch', function() {
    gulp.watch(filePath.src, ['lint']);
});

gulp.task('test', function() {
    return gulp.src('./test/*.qunit.html')
        .pipe(qunit());
});

gulp.task('docs', function() {
    gulp.src(filePath.src)
        .pipe(yuidoc())
        .pipe(gulp.dest('./docs'));
});

gulp.task('commit',
    shell.task([
        'echo start',
        'git add ./src',
        'git add ./openui5/googlemaps',
        'git add ./samples',
        'git commit -a -m \"test gulp commit\"',
        'git push'
    ])
);

gulp.task('develop ', ['build', 'watch']);
gulp.task('build', ['scripts-dbg', 'scripts-min']);
gulp.task('cleanbuild', ['clean']);<commit_msg>test gulp commit<commit_after>var gulp = require('gulp');

var jshint = require('gulp-jshint');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var concat = require('gulp-concat');
var clean = require('gulp-clean');
var header = require('gulp-header');
var streamify = require('gulp-streamify');
var qunit = require('gulp-qunit');
var pkg = require('./package.json');
var shell = require('gulp-shell');

var banner = ['/**',
    ' * <%= pkg.name %> - <%= pkg.description %>',
    ' * @version v<%= pkg.version %>',
    ' * @link <%= pkg.homepage %>',
    ' * @license <%= pkg.license %>',
    ' */',
].join('\n');

var filePath = {
    src: './src/*.js',
    dest: './openui5/googlemaps'
};

gulp.task('clean', function() {
    return gulp.src(filePath.dest, {
        read: false
    }).pipe(clean());
});

//TODO - all scripts tasks with one stream
gulp.task('scripts-dbg', function() {
    gulp.src(filePath.src)
        .pipe(header(banner, {
            pkg: pkg
        }))
        .pipe(rename({
            suffix: '-dbg'
        }))
        .pipe(gulp.dest(filePath.dest));
});

gulp.task('scripts-min', function() {
    gulp.src(filePath.src)
        .pipe(streamify(uglify()))
        .pipe(gulp.dest(filePath.dest))
        .pipe(concat('library-all.js'))
        .pipe(gulp.dest(filePath.dest));
});

// JSHint task
gulp.task('lint', function() {
    gulp.src(filePath.src)
        .pipe(jshint())
        .pipe(jshint.reporter('default'));
});

gulp.task('watch', function() {
    gulp.watch(filePath.src, ['lint']);
});

gulp.task('test', function() {
    return gulp.src('./test/*.qunit.html')
        .pipe(qunit());
});

gulp.task('commit',
    shell.task([
        'echo start',
        'git add ./src',
        'git add ./openui5/googlemaps',
        'git add ./samples',
        'git commit -a -m \"test gulp commit\"',
        'git push'
    ])
);

gulp.task('develop ', ['build', 'watch']);
gulp.task('build', ['scripts-dbg', 'scripts-min']);
gulp.task('cleanbuild', ['clean']);<|endoftext|>


<commit_before>var path = require('path');
var gulp = require('gulp');
var useref = require('gulp-useref');
var gulpif = require('gulp-if');
var uglify = require('gulp-uglify');
var minifyCss = require('gulp-minify-css');
var origin = 'bower_components';
var destinationJS = path.join('ui', 'lib');
var destinationCSS = path.join('ui', 'css');

gulp.task('moveDeps', function() {
    // angular
    gulp.src(path.join(origin, 'angular', 'angular.js'))
    .pipe(gulp.dest(destinationJS));

    // angular-animate
    gulp.src(path.join(origin, 'angular-animate', 'angular-animate.js'))
    .pipe(gulp.dest(destinationJS));

    // angular-aria
    gulp.src(path.join(origin, 'angular-aria', 'angular-aria.js'))
    .pipe(gulp.dest(destinationJS));

    // angular-material
    gulp.src(path.join(origin, 'angular-material', 'angular-material.js'))
    .pipe(gulp.dest(destinationJS));
    gulp.src(path.join(origin, 'angular-material', 'angular-material.css'))
    .pipe(gulp.dest(destinationCSS));

    // angular-messages
    gulp.src(path.join(origin, 'angular-messages', 'angular-messages.js'))
    .pipe(gulp.dest(destinationJS));
});

gulp.task('buildProd', function() {
    gulp.src('ui/index.html')
    .pipe(useref())
    .pipe(gulpif('*.js', uglify()))
    .pipe(gulpif('*.css', minifyCss()))
    .pipe(gulp.dest('www'));

    gulp.src('ui/icons/*')
    .pipe(gulp.dest('www/icons'));
});<commit_msg>Added views to buildProd<commit_after>var path = require('path');
var gulp = require('gulp');
var useref = require('gulp-useref');
var gulpif = require('gulp-if');
var uglify = require('gulp-uglify');
var minifyCss = require('gulp-minify-css');
var origin = 'bower_components';
var destinationJS = path.join('ui', 'lib');
var destinationCSS = path.join('ui', 'css');

gulp.task('moveDeps', function() {
    // angular
    gulp.src(path.join(origin, 'angular', 'angular.js'))
    .pipe(gulp.dest(destinationJS));

    // angular-animate
    gulp.src(path.join(origin, 'angular-animate', 'angular-animate.js'))
    .pipe(gulp.dest(destinationJS));

    // angular-aria
    gulp.src(path.join(origin, 'angular-aria', 'angular-aria.js'))
    .pipe(gulp.dest(destinationJS));

    // angular-material
    gulp.src(path.join(origin, 'angular-material', 'angular-material.js'))
    .pipe(gulp.dest(destinationJS));
    gulp.src(path.join(origin, 'angular-material', 'angular-material.css'))
    .pipe(gulp.dest(destinationCSS));

    // angular-messages
    gulp.src(path.join(origin, 'angular-messages', 'angular-messages.js'))
    .pipe(gulp.dest(destinationJS));
});

gulp.task('buildProd', function() {
    gulp.src('ui/index.html')
    .pipe(useref())
    .pipe(gulpif('*.js', uglify()))
    .pipe(gulpif('*.css', minifyCss()))
    .pipe(gulp.dest('www'));

    gulp.src('ui/icons/*')
    .pipe(gulp.dest('www/icons'));

    gulp.src('ui/views/*')
    .pipe(gulp.dest('www/views'));
});<|endoftext|>


<commit_before>var gulp   = require("gulp");
var babel  = require("gulp-babel");
var server = require('gulp-server-livereload');
var rimraf = require('gulp-rimraf');
var jshint = require('gulp-jshint');

var path = {
  in: {
    lib: "./lib/**/*.js",
    dist: "./dist/**/*.js",
    examples: "./examples/**/*.js"
  },
  out: {
    dist: "./dist",
    examples: "./examples"
  }
};

gulp.task('babel', function() {
  return gulp.src(path.in.lib)
    .pipe(babel())
    .pipe(gulp.dest(path.out.dist));
});

gulp.task('default', ['server']);

gulp.task('clean', function() {
  return gulp.src(path.out.dist, {
    read: false
  }).pipe(rimraf({
    force: true
  }));
});

gulp.task('lint', function() {
  return gulp.src([path.in.lib, path.in.examples])
    .pipe(jshint({
      linter: require('jshint-jsx').JSXHINT
    }))
    .pipe(jshint.reporter('default'));
});

gulp.task('server', ['babel', 'lint'], function() {
  gulp.watch(path.in.lib, ['babel']);

  gulp.watch([path.in.lib, path.in.examples], ['lint']);

  gulp.src(["./examples/**", "./dist/**"])
    .pipe(server({
      livereload: true,
      defaultFile: 'basic-map.html'
    }));
});
<commit_msg>clean up paths<commit_after>var gulp   = require("gulp");
var babel  = require("gulp-babel");
var server = require('gulp-server-livereload');
var rimraf = require('gulp-rimraf');
var jshint = require('gulp-jshint');

var paths = {
  in: {
    lib: {
      js: "./lib/**/*.js"
    },
    examples: {
      js: "./examples/**/*.js"
    }
  },
  out: {
    dist: {
      all: "./dist/**",
      dir: "./dist"
    },
    examples: {
      all: "./examples/**"
    }
  }
};

gulp.task('babel', function() {
  return gulp.src(paths.in.lib.js)
    .pipe(babel())
    .pipe(gulp.dest(paths.out.dist.dir));
});

gulp.task('default', ['server']);

gulp.task('clean', function() {
  return gulp.src(paths.out.dist.dir, {
    read: false
  }).pipe(rimraf({
    force: true
  }));
});

gulp.task('lint', function() {
  return gulp.src([paths.in.lib.js, paths.in.examples.js])
    .pipe(jshint({
      linter: require('jshint-jsx').JSXHINT
    }))
    .pipe(jshint.reporter('default'));
});

gulp.task('server', ['babel', 'lint'], function() {
  gulp.watch(paths.in.lib.js, ['babel']);

  gulp.watch([paths.in.lib.js, paths.in.examples.js], ['lint']);

  gulp.src([paths.out.examples.all, paths.out.dist.all])
    .pipe(server({
      livereload: true,
      defaultFile: 'basic-map.html'
    }));
});
<|endoftext|>


<commit_before>(function () {
// IMPORTS
//##########################################################
'use strict';
/* global require */
var gulp = require('gulp');
var uglify = require('gulp-uglify');
var jshint = require('gulp-jshint');
var imagemin = require('gulp-imagemin');
var browser = require('browser-sync');

// SETTINGS
//##########################################################
var paths = {
    'css': './static/css/',
    'html': './templates/',
    'images': './static/img/',
    'js': './static/js/',
    'media': './tmp/media/',
    'sass': './private/sass/'
};

var patterns = {
    'images': [paths.images+'*', paths.images+'**/*', '!'+paths.images+'/dummy/*/**'],
    'js': [paths.js+'*.js', paths.js+'**/*.js', '!'+paths.js+'*.min.js', '!'+paths.js+'**/*.min.js'],
    'media': [paths.media+'**/*'],
    'sass': [paths.sass+'*', paths.sass+'**/*']
};

var port = process.env.PORT || '8000';

// TASKS
//##########################################################
// TASKS/javascript
gulp.task('lint', function() {
    gulp.src(patterns.js.concat([paths.js+'!libs/*.js', './gulpfile.js']))
        .pipe(jshint())
        .pipe(jshint.reporter('jshint-stylish'));
});

// TASK/browser reload
gulp.task('browser', function() {
    var files = [
        paths.css+'base.css',
        paths.html+'**/*.html',
        paths.js+'**/*.js'
    ];

    // http://www.browsersync.io/docs/options/
    browser.init(files, {
        'proxy': '0.0.0.0:' + port,
        'port': port
    });
});

// TASK/image preprocessing
gulp.task('static', function () {
    gulp.src(patterns.images)
        .pipe(imagemin())
        .pipe(gulp.dest(paths.images));
});

gulp.task('media', function () {
    gulp.src(patterns.media)
        .pipe(imagemin())
        .pipe(gulp.dest(paths.media));
});

// TASK/watchers
gulp.task('watch', function() {
    gulp.watch(patterns.js.concat(['./gulpfile.js']), ['lint']);
});

// RUNNERS
//##########################################################
gulp.task('default', ['lint', 'browser', 'watch']);

// end of gulpfile.js
}());<commit_msg>add timer for browsersync<commit_after>(function () {
// IMPORTS
//##########################################################
'use strict';
/* global require */
var gulp = require('gulp');
var uglify = require('gulp-uglify');
var jshint = require('gulp-jshint');
var imagemin = require('gulp-imagemin');
var browserSync = require('browser-sync');

// SETTINGS
//##########################################################
var paths = {
    'css': './static/css/',
    'html': './templates/',
    'images': './static/img/',
    'js': './static/js/',
    'media': './tmp/media/',
    'sass': './private/sass/'
};

var patterns = {
    'images': [paths.images+'*', paths.images+'**/*', '!'+paths.images+'/dummy/*/**'],
    'js': [paths.js+'*.js', paths.js+'**/*.js', '!'+paths.js+'*.min.js', '!'+paths.js+'**/*.min.js'],
    'media': [paths.media+'**/*'],
    'sass': [paths.sass+'*', paths.sass+'**/*']
};

var port = process.env.PORT || '8000';

// TASKS
//##########################################################
// TASKS/javascript
gulp.task('lint', function() {
    gulp.src(patterns.js.concat([paths.js+'!libs/*.js', './gulpfile.js']))
        .pipe(jshint())
        .pipe(jshint.reporter('jshint-stylish'));
});

// TASK/browser reload
gulp.task('browser', function() {
    var files = [
        paths.css+'base.css',
        paths.html+'**/*.html',
        paths.js+'**/*.js'
    ];

    // http://www.browsersync.io/docs/options/
    setTimeout(function () {
        browserSync.init(files, {
            'proxy': '0.0.0.0:' + port,
            'port': port
        });
    }, 1000);
});

// TASK/image preprocessing
gulp.task('static', function () {
    gulp.src(patterns.images)
        .pipe(imagemin())
        .pipe(gulp.dest(paths.images));
});

gulp.task('media', function () {
    gulp.src(patterns.media)
        .pipe(imagemin())
        .pipe(gulp.dest(paths.media));
});

// TASK/watchers
gulp.task('watch', function() {
    gulp.watch(patterns.js.concat(['./gulpfile.js']), ['lint']);
});

// RUNNERS
//##########################################################
gulp.task('default', ['lint', 'browser', 'watch']);

// end of gulpfile.js
}());<|endoftext|>


<commit_before>var gulp = require('gulp'),
    config = require('./config');
    $ = require('gulp-load-plugins')({
        pattern: ['gulp-*', 'gulp.*'],
        replaceString: /\bgulp[\-.]/
    });

var runSequence = require('run-sequence');
var extend = require('extend');
$.browser = require('browser-sync');

var DEFAULT_OPTIONS = {
    min: false,
    d: config.defaultDir || ''
};
var APP_PATH = config.appPath;
var OPTIONS = parseOption(process.argv);
function parseOption(argv) {
    var options = extend({},DEFAULT_OPTIONS);
    for(var i = 0, len = argv.length; i < len; i++) {
        if (argv[i].charAt(0) === '-') {
            var match = argv[i].substring(1).split('=');
            var key = match[0];
            var value = match[1] || true;
            options[key] = value;
        }
    }
    return options;
}

/**
 * パス生成関数
 * @param name
 * @param prop
 * @returns {string}
 */
function getPath(name, prop) {
    prop = prop || 'src';
    if (!config.path[name] || !config.path[name][prop]) {
        return console.log('[ERROR] not found path - ' + name + '.' + prop);
    }
    return generatePath(config.path[name][prop]);
}
function generatePath(path,relative) {
    var appPath = relative ? '.' : APP_PATH;
    if (typeof path === 'object') {
        return path.map(function (val) {
            if (val.charAt(0) === '!') {
                return '!' + appPath + '/' + replaceTypeTag(val.substring(1));
            }
            return appPath + '/' + replaceTypeTag(val);
        });
    } else {
        path = path || '';
        return appPath + '/' + replaceTypeTag(path);
    }
}
function replaceTypeTag(val) {
    if (OPTIONS.d) {
        return val.replace(/%type%/g, OPTIONS.d);
    }
    return val.replace(/\/%type%/g, '');
}

// globalに共通変数書き出し
global.frontplate = {
    plugins: $,
    config: config,
    getPath: getPath,
    path: generatePath,
    option: OPTIONS
};

gulp.task('watch', function() {
    gulp.watch(getPath('ejs','watch'), ['ejs']);
    gulp.watch(getPath('html'), ['html']);
    gulp.watch(getPath('sass'), ['style']);
    gulp.watch(getPath('sprite','watch'), ['sprite']);
    gulp.watch(getPath('images'), ['imagemin']);
});

// gulpディレクトリのタスク読み込み
var tasks = require('./gulp/load');
gulp.task('build',['clean'], function(callback) {
    return runSequence(['copy','ejs','sprite','style', 'script'], 'imagemin', callback);
});
gulp.task('default',['server','watch','watchScript'], function() {});<commit_msg>testをwatchに追加<commit_after>var gulp = require('gulp'),
    config = require('./config');
    $ = require('gulp-load-plugins')({
        pattern: ['gulp-*', 'gulp.*'],
        replaceString: /\bgulp[\-.]/
    });

var runSequence = require('run-sequence');
var extend = require('extend');
$.browser = require('browser-sync');

var DEFAULT_OPTIONS = {
    min: false,
    d: config.defaultDir || ''
};
var APP_PATH = config.appPath;
var OPTIONS = parseOption(process.argv);
function parseOption(argv) {
    var options = extend({},DEFAULT_OPTIONS);
    for(var i = 0, len = argv.length; i < len; i++) {
        if (argv[i].charAt(0) === '-') {
            var match = argv[i].substring(1).split('=');
            var key = match[0];
            var value = match[1] || true;
            options[key] = value;
        }
    }
    return options;
}

/**
 * パス生成関数
 * @param name
 * @param prop
 * @returns {string}
 */
function getPath(name, prop) {
    prop = prop || 'src';
    if (!config.path[name] || !config.path[name][prop]) {
        return console.log('[ERROR] not found path - ' + name + '.' + prop);
    }
    return generatePath(config.path[name][prop]);
}
function generatePath(path,relative) {
    var appPath = relative ? '.' : APP_PATH;
    if (typeof path === 'object') {
        return path.map(function (val) {
            if (val.charAt(0) === '!') {
                return '!' + appPath + '/' + replaceTypeTag(val.substring(1));
            }
            return appPath + '/' + replaceTypeTag(val);
        });
    } else {
        path = path || '';
        return appPath + '/' + replaceTypeTag(path);
    }
}
function replaceTypeTag(val) {
    if (OPTIONS.d) {
        return val.replace(/%type%/g, OPTIONS.d);
    }
    return val.replace(/\/%type%/g, '');
}

// globalに共通変数書き出し
global.frontplate = {
    plugins: $,
    config: config,
    getPath: getPath,
    path: generatePath,
    option: OPTIONS
};

gulp.task('watch', function() {
    gulp.watch(getPath('ejs','watch'), ['ejs']);
    gulp.watch(getPath('html'), ['html']);
    gulp.watch(getPath('sass'), ['style']);
    gulp.watch(getPath('sprite','watch'), ['sprite']);
    gulp.watch(getPath('images'), ['imagemin']);
});

// gulpディレクトリのタスク読み込み
var tasks = require('./gulp/load');
gulp.task('build',['clean'], function(callback) {
    return runSequence(['copy','ejs','sprite','style', 'script'], 'imagemin', callback);
});
gulp.task('default',['server','watch','watchScript','testWatch'], function() {});<|endoftext|>


<commit_before>var autoprefixer = require("gulp-autoprefixer");
var concat       = require("gulp-concat");
var del          = require("del");
var gulp         = require("gulp");
var imagemin     = require("gulp-imagemin");
var jshint       = require("gulp-jshint");
var less         = require("gulp-less");
var minifyCss    = require("gulp-minify-css");
var minifyHtml   = require("gulp-minify-html");
var pixrem       = require("gulp-pixrem");
var rev          = require("gulp-rev");
var revReplace   = require("gulp-rev-replace");
var uglify       = require("gulp-uglify");

gulp.task("clean", function() {
    return del([
        "./dist/css/*.css",
        "./dist/js/*.js"
    ]);
});

gulp.task("copy-assets", function() {
    return gulp.src("./node_modules/normalize.css/normalize.css")
        .pipe(gulp.dest("./src/css/lib"));
});

gulp.task("images", function() {
    return gulp.src("./src/img/**/*.{gif,jpg,png,svg}")
        .pipe(imagemin())
        .pipe(gulp.dest("./dist/img"));
});

gulp.task("css", ["clean", "copy-assets"], function() {
    return gulp.src("./src/less/main.less")
        .pipe(less())
        .pipe(pixrem())
        .pipe(autoprefixer())
        .pipe(minifyCss({ "noAdvanced": true })) // noAdvanced is true so pixrem fallback styles don't get removed
        .pipe(gulp.dest("./dist/css"));
});

gulp.task("js-lint", function() {
    return gulp.src("./src/js/*.js")
        .pipe(jshint())
        .pipe(jshint.reporter("default"))
        .pipe(jshint.reporter("fail"));
});

gulp.task("js-build", ["clean", "js-lint"], function() {
    return gulp.src(["./src/js/lib/jquery-1.7.2.min.js", "./src/js/main.js"])
        .pipe(concat("main.js"))
        .pipe(uglify())
        .pipe(gulp.dest("./dist/js/"));
});

gulp.task("html", function() {
    return gulp.src("./src/**/*.html")
        .pipe(minifyHtml())
        .pipe(gulp.dest("./dist/"));
});

gulp.task("revision", ["css", "js-build"], function() {
    return gulp.src(["./dist/**/*.css", "./dist/**/*.js"])
        .pipe(rev())
        .pipe(gulp.dest("./dist"))
        .pipe(rev.manifest())
        .pipe(gulp.dest("./dist"));
});

gulp.task("revisionReplace", ["revision"], function() {
    var manifest = gulp.src("./dist/rev-manifest.json");

    return gulp.src("./dist/**/*.html")
        .pipe(revReplace({"manifest": manifest}))
        .pipe(gulp.dest("./dist"));
});

gulp.task("default", [
    "clean",
    "copy-assets",
    "images",
    "css",
    "js-lint",
    "js-build",
    "html",
    "revision",
    "revisionReplace"
]);
<commit_msg>Removed unnecessary ./ prefixes for paths in the gulpfile.<commit_after>var autoprefixer = require("gulp-autoprefixer");
var concat       = require("gulp-concat");
var del          = require("del");
var gulp         = require("gulp");
var imagemin     = require("gulp-imagemin");
var jshint       = require("gulp-jshint");
var less         = require("gulp-less");
var minifyCss    = require("gulp-minify-css");
var minifyHtml   = require("gulp-minify-html");
var pixrem       = require("gulp-pixrem");
var rev          = require("gulp-rev");
var revReplace   = require("gulp-rev-replace");
var uglify       = require("gulp-uglify");

gulp.task("clean", function() {
    return del([
        "dist/css/*.css",
        "dist/js/*.js"
    ]);
});

gulp.task("copy-assets", function() {
    return gulp.src("node_modules/normalize.css/normalize.css")
        .pipe(gulp.dest("src/css/lib"));
});

gulp.task("images", function() {
    return gulp.src("src/img/**/*.{gif,jpg,png,svg}")
        .pipe(imagemin())
        .pipe(gulp.dest("dist/img"));
});

gulp.task("css", ["clean", "copy-assets"], function() {
    return gulp.src("src/less/main.less")
        .pipe(less())
        .pipe(pixrem())
        .pipe(autoprefixer())
        .pipe(minifyCss({ "noAdvanced": true })) // noAdvanced is true so pixrem fallback styles don't get removed
        .pipe(gulp.dest("dist/css"));
});

gulp.task("js-lint", function() {
    return gulp.src("src/js/*.js")
        .pipe(jshint())
        .pipe(jshint.reporter("default"))
        .pipe(jshint.reporter("fail"));
});

gulp.task("js-build", ["clean", "js-lint"], function() {
    return gulp.src(["src/js/lib/jquery-1.7.2.min.js", "src/js/main.js"])
        .pipe(concat("main.js"))
        .pipe(uglify())
        .pipe(gulp.dest("dist/js/"));
});

gulp.task("html", function() {
    return gulp.src("src/**/*.html")
        .pipe(minifyHtml())
        .pipe(gulp.dest("dist/"));
});

gulp.task("revision", ["css", "js-build"], function() {
    return gulp.src(["dist/**/*.css", "dist/**/*.js"])
        .pipe(rev())
        .pipe(gulp.dest("dist"))
        .pipe(rev.manifest())
        .pipe(gulp.dest("dist"));
});

gulp.task("revisionReplace", ["revision"], function() {
    var manifest = gulp.src("dist/rev-manifest.json");

    return gulp.src("dist/**/*.html")
        .pipe(revReplace({"manifest": manifest}))
        .pipe(gulp.dest("dist"));
});

gulp.task("default", [
    "clean",
    "copy-assets",
    "images",
    "css",
    "js-lint",
    "js-build",
    "html",
    "revision",
    "revisionReplace"
]);
<|endoftext|>


<commit_before>"use strict";
const gulp = require('gulp');
const watch = require('gulp-watch');
const batch = require('gulp-batch');
const jsonTransform = require('gulp-json-transform');
const gsourcemaps = require('gulp-sourcemaps');
const ts = require('typescript');
const gts = require('gulp-typescript');
const tslint = require('tslint');
const gtslint = require('gulp-tslint');
const path = require('path');
const del = require('del');
const merge = require('merge-stream');
const runSequence = require('run-sequence');
// ==================================================================================
const packageJson = require('./package.json');
const tsConfig = require('./tsconfig.json');
// ==================================================================================
// settings:

const outDir = 'dist'; // keep it simple (for 'del' package)
const tsConfigFile = 'tsconfig.json';
const tsLintFile = 'tslint.json';

const srcRootDir = tsConfig.compilerOptions.rootDir;
const watching = [path.join(srcRootDir,'**','*')];

const transformDefinition = [
  {
    src: 'package.json',
    base: '.',
    out: outDir,
    jsonTransFunc: (data, file) => {
      // scripts: delete this section, because it will be non-functional
      if (!!data.scripts) {
        delete data.scripts;
      }
      // main: remove outDir prefix
      if (data.main) {
        if (!data.main.startsWith(outDir)) {
          console.warn(
            `packages.json: 'main' attribute not starting with '${outDir}'`);
        } else {
          data.main = data.main.substr(outDir.length);
          if (data.main.length && data.main[0] === '/') {
            data.main = data.main.substr(1);
          }
        }
      }
      // devDependencies: delete this section, which is not required anymore
      if (!!data.devDependencies) {
        delete data.devDependencies;
      }
      return data;
    },
    jsonTransWhitespace: 2
  },
  {
    src: '.npmignore',
    base: '.',
    out: outDir
  },
  {
    src: 'README.md',
    base: '.',
    out: outDir
  }
];

// ==================================================================================
// clean

gulp.task('clean', function () {
  // do not clean 'node_modules' to make 'npm link' happy
  return del([path.join(outDir, '**'), '!' + outDir, '!' + path.join(outDir, 'node_modules', '**')]);
})

// ==================================================================================
// transform-data

gulp.task('transform-data', function () {

  var transformpipes = [];

  transformDefinition.forEach((transformItem) => {
    if (transformItem.jsonTransFunc) {
      transformpipes.push(gulp.src(transformItem.src, { base: transformItem.base })
        .pipe(jsonTransform(transformItem.jsonTransFunc, transformItem.jsonTransWhitespace || 0))
        .pipe(gulp.dest(transformItem.out)));
    } else {
      transformpipes.push(gulp.src(transformItem.src, { base: transformItem.base }).pipe(gulp.dest(transformItem.out)));
    }
  });

  return merge(transformpipes);
})

// ==================================================================================
// tsc - transpile typescript sources

gulp.task('tsc', function () {
  var tsProject = gts.createProject(tsConfigFile, { typescript: ts });

  var tsOutDir = tsProject.config.compilerOptions.outDir;

  var relTSOutDir = path.relative(tsOutDir, '.');
  var relMYOutDir = path.relative(outDir, '.');
  if (relMYOutDir !== relTSOutDir) {
    console.warn(
      `different dist-directory defined in gulpfile.js '${outDir}' vs tsconfig.js '${tsOutDir}'`);
  }

  return tsProject.src()
    .pipe(gsourcemaps.init())
    .pipe(tsProject(gts.reporter.longReporter()))
    .pipe(gsourcemaps.write('.', { includeContent: false, sourceRoot: '.' }))
    .pipe(gulp.dest(outDir));
});

// ==================================================================================
// tslint - typescript linter

gulp.task('tslint', function () {
  var tsProject = gts.createProject(tsConfigFile, { typescript: ts });

  return tsProject.src()
    .pipe(gtslint({ configuration: tsLintFile, tslint: tslint }))
    .pipe(gtslint.report());
})

// ==================================================================================
// build

gulp.task('build', ['transform-data', 'tsc', 'tslint']);

// ==================================================================================
// rebuild

gulp.task('rebuild', function (callback) {
  // runSequence will be obsolet after gulp 4 transistion
  runSequence('clean', 'build', callback);
});

// ==================================================================================
// watch

gulp.task('watch-build', ['transform-data', 'tsc']);

gulp.task('watch', ['build'], function () {
  watch(watching, batch(function (events, done) { gulp.start('watch-build', done); }));
});

// ==================================================================================
// default

gulp.task('default', ['build']);
<commit_msg>update tslint to version 4.3.0: tslint was unhappy with gulp-tslint default option formattersDirectory=null<commit_after>"use strict";
const gulp = require('gulp');
const watch = require('gulp-watch');
const batch = require('gulp-batch');
const jsonTransform = require('gulp-json-transform');
const gsourcemaps = require('gulp-sourcemaps');
const ts = require('typescript');
const gts = require('gulp-typescript');
const tslint = require('tslint');
const gtslint = require('gulp-tslint');
const path = require('path');
const del = require('del');
const merge = require('merge-stream');
const runSequence = require('run-sequence');
// ==================================================================================
const packageJson = require('./package.json');
const tsConfig = require('./tsconfig.json');
// ==================================================================================
// settings:

const outDir = 'dist'; // keep it simple (for 'del' package)
const tsConfigFile = 'tsconfig.json';
const tsLintFile = 'tslint.json';

const srcRootDir = tsConfig.compilerOptions.rootDir;
const watching = [path.join(srcRootDir,'**','*')];

const transformDefinition = [
  {
    src: 'package.json',
    base: '.',
    out: outDir,
    jsonTransFunc: (data, file) => {
      // scripts: delete this section, because it will be non-functional
      if (!!data.scripts) {
        delete data.scripts;
      }
      // main: remove outDir prefix
      if (data.main) {
        if (!data.main.startsWith(outDir)) {
          console.warn(
            `packages.json: 'main' attribute not starting with '${outDir}'`);
        } else {
          data.main = data.main.substr(outDir.length);
          if (data.main.length && data.main[0] === '/') {
            data.main = data.main.substr(1);
          }
        }
      }
      // devDependencies: delete this section, which is not required anymore
      if (!!data.devDependencies) {
        delete data.devDependencies;
      }
      return data;
    },
    jsonTransWhitespace: 2
  },
  {
    src: '.npmignore',
    base: '.',
    out: outDir
  },
  {
    src: 'README.md',
    base: '.',
    out: outDir
  }
];

// ==================================================================================
// clean

gulp.task('clean', function () {
  // do not clean 'node_modules' to make 'npm link' happy
  return del([path.join(outDir, '**'), '!' + outDir, '!' + path.join(outDir, 'node_modules', '**')]);
})

// ==================================================================================
// transform-data

gulp.task('transform-data', function () {

  var transformpipes = [];

  transformDefinition.forEach((transformItem) => {
    if (transformItem.jsonTransFunc) {
      transformpipes.push(gulp.src(transformItem.src, { base: transformItem.base })
        .pipe(jsonTransform(transformItem.jsonTransFunc, transformItem.jsonTransWhitespace || 0))
        .pipe(gulp.dest(transformItem.out)));
    } else {
      transformpipes.push(gulp.src(transformItem.src, { base: transformItem.base }).pipe(gulp.dest(transformItem.out)));
    }
  });

  return merge(transformpipes);
})

// ==================================================================================
// tsc - transpile typescript sources

gulp.task('tsc', function () {
  var tsProject = gts.createProject(tsConfigFile, { typescript: ts });

  var tsOutDir = tsProject.config.compilerOptions.outDir;

  var relTSOutDir = path.relative(tsOutDir, '.');
  var relMYOutDir = path.relative(outDir, '.');
  if (relMYOutDir !== relTSOutDir) {
    console.warn(
      `different dist-directory defined in gulpfile.js '${outDir}' vs tsconfig.js '${tsOutDir}'`);
  }

  return tsProject.src()
    .pipe(gsourcemaps.init())
    .pipe(tsProject(gts.reporter.longReporter()))
    .pipe(gsourcemaps.write('.', { includeContent: false, sourceRoot: '.' }))
    .pipe(gulp.dest(outDir));
});

// ==================================================================================
// tslint - typescript linter

gulp.task('tslint', function () {
  var tsProject = gts.createProject(tsConfigFile, { typescript: ts });

  return tsProject.src()
    .pipe(gtslint({ configuration: tsLintFile, tslint: tslint, formattersDirectory: 'tslint' }))
    .pipe(gtslint.report());
})

// ==================================================================================
// build

gulp.task('build', ['transform-data', 'tsc', 'tslint']);

// ==================================================================================
// rebuild

gulp.task('rebuild', function (callback) {
  // runSequence will be obsolet after gulp 4 transistion
  runSequence('clean', 'build', callback);
});

// ==================================================================================
// watch

gulp.task('watch-build', ['transform-data', 'tsc']);

gulp.task('watch', ['build'], function () {
  watch(watching, batch(function (events, done) { gulp.start('watch-build', done); }));
});

// ==================================================================================
// default

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