<commit_before>var gulp = require('gulp');
var gutil = require('gulp-util');
var bower = require('bower');
var concat = require('gulp-concat');
var insert = require('gulp-insert');
var stripComments = require('gulp-strip-comments');
var removeEmptyLines = require('gulp-remove-empty-lines');
var clipEmptyFiles = require('gulp-clip-empty-files');
var sass = require('gulp-sass');
var minifyCss = require('gulp-minify-css');
var rename = require('gulp-rename');
var tap = require('gulp-tap');
var fs = require('fs');
var through = require('through');
var path = require('path');
var File = gutil.File;
var gulpSlash = require('gulp-slash');
var ngAnnotate = require('gulp-ng-annotate');

var license = '' +
  '// (C) Copyright 2015 Martin Dougiamas\n' +
  '//\n' +
  '// Licensed under the Apache License, Version 2.0 (the "License");\n' +
  '// you may not use this file except in compliance with the License.\n' +
  '// You may obtain a copy of the License at\n' +
  '//\n' +
  '//     http://www.apache.org/licenses/LICENSE-2.0\n' +
  '//\n' +
  '// Unless required by applicable law or agreed to in writing, software\n' +
  '// distributed under the License is distributed on an "AS IS" BASIS,\n' +
  '// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n' +
  '// See the License for the specific language governing permissions and\n' +
  '// limitations under the License.\n\n',
  buildFile = 'mm.bundle.js';

var paths = {
  build: './www/build',
  js: [
    './www/app.js',
    './www/core/main.js',
    './www/core/lib/*.js',
    './www/core/filters/*.js',
    './www/core/directives/*.js',
    './www/core/components/**/main.js',
    './www/core/components/**/*.js',
    './www/addons/**/main.js',
    './www/addons/**/*.js',
    '!./www/**/tests/*.js'
  ],
  sass: {
    core: [
      './www/core/scss/*.scss',
      './www/core/components/**/scss/*.scss',
      './www/addons/**/scss/*.scss',
    ],
    custom: [
      './scss/app.scss',
      './scss/**/*.scss'
    ]
  },
  lang: [
    './www/core/lang/',
    './www/core/components/**/lang/',
    './www/addons/**/lang/',
    './www/core/assets/countries/'
  ],
  config: './www/config.json'
};

gulp.task('default', ['build', 'sass', 'lang', 'config']);

gulp.task('sass-build', function(done) {
  gulp.src(paths.sass.core)
    .pipe(concat('mm.bundle.scss'))
    .pipe(gulp.dest(paths.build))
    .on('end', done);
});

gulp.task('sass', ['sass-build'], function(done) {
  gulp.src(paths.sass.custom)
    .pipe(concat('mm.bundle.css'))
    .pipe(sass())
    .pipe(gulp.dest(paths.build))
    .pipe(minifyCss({
      keepSpecialComments: 0
    }))
    .pipe(rename({ extname: '.min.css' }))
    .pipe(gulp.dest(paths.build))
    .on('end', done);
});

gulp.task('watch', function() {
  gulp.watch(paths.sass.core, ['sass']);
  gulp.watch(paths.sass.custom, ['sass']);
  gulp.watch(paths.js, ['build', 'config']);
  var langsPaths = paths.lang.map(function(path) {
    return path + '*.json';
  });
  gulp.watch(langsPaths, ['lang']);
  gulp.watch(paths.config, ['config']);
});

gulp.task('build', function(done) {
  var dependencies = ["'mm.core'"],
      componentRegex = /core\/components\/([^\/]+)\/main.js/,
      pluginRegex = /addons\/([^\/]+)\/main.js/;

  gulp.src(paths.js)
    .pipe(gulpSlash())
    .pipe(clipEmptyFiles())
    .pipe(tap(function(file, t) {
      if (componentRegex.test(file.path)) {
        dependencies.push("'mm.core." + file.path.match(componentRegex)[1] + "'");
      } else if (pluginRegex.test(file.path)) {
        dependencies.push("'mm.addons." + file.path.match(pluginRegex)[1] + "'");
      }
    }))

    // Remove comments, remove empty lines, concat and add license.
    .pipe(stripComments())
    .pipe(removeEmptyLines())
    .pipe(ngAnnotate()) // This step fixes DI declarations for FirefoxOS.
    .pipe(concat(buildFile))
    .pipe(insert.prepend(license))

    // Add dependencies, this assumes that the mm module is declared on one line.
    .pipe(insert.transform(function(contents) {
      return contents.replace(
        "angular.module('mm', ['ionic'",
        "angular.module('mm', ['ionic', " + dependencies.join(', '));
    }))
    .pipe(gulp.dest(paths.build))
    .on('end', done);
});

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

  /**
   * Get the names of the JSON files inside a directory.
   * @param  {String} dir Directory's path.
   * @return {Array}      List of filenames.
   */
  function getFilenames(dir) {
    return fs.readdirSync(dir)
      .filter(function(file) {
        return file.indexOf('.json') > -1;
      })
  }

  /**
   * Copy a property from one object to another, adding a prefix to the key if needed.
   * @param {Object} target Object to copy the properties to.
   * @param {Object} source Object to copy the properties from.
   * @param {String} prefix Prefix to add to the keys.
   */
  function addProperties(target, source, prefix) {
    for (var property in source) {
      target[prefix + property] = source[property];
    }
  }

  /**
   * Treats the merged JSON data, adding prefixes depending on the component.
   * @param  {Object} data Merged data.
   * @return {Buffer}      Buffer with the treated data.
   */
  function treatMergedData(data) {
    var merged = {};

    for (var filepath in data) {

      if (filepath.indexOf('core/lang') == 0) {

        addProperties(merged, data[filepath], 'mm.core.');

      } else if (filepath.indexOf('core/components') == 0) {

        var componentName = filepath.replace('core/components/', '');
        componentName = componentName.substr(0, componentName.indexOf('/'));
        addProperties(merged, data[filepath], 'mm.'+componentName+'.');

      } else if (filepath.indexOf('addons') == 0) {

        var pluginName = filepath.replace('addons/', '');
        pluginName = pluginName.substr(0, pluginName.indexOf('/'));
        addProperties(merged, data[filepath], 'mma.'+pluginName+'.');

      } else if (filepath.indexOf('core/assets/countries') == 0) {

        addProperties(merged, data[filepath], 'mm.core.country-');

      }

    }

    return new Buffer(JSON.stringify(merged, null, 4));
  }

  /**
   * Treats a file to merge JSONs. This function is based on gulp-jsoncombine module.
   * https://github.com/reflog/gulp-jsoncombine
   * @param  {Object} file File treated.
   */
  function treatFile(file, data) {
    if (file.isNull() || file.isStream()) {
      return; // ignore
    }
    try {
      var path = file.path.substr(file.path.indexOf('/www/') + 5, file.path.length-5);
      data[path] = JSON.parse(file.contents.toString());
    } catch (err) {
      console.log('Error parsing JSON: ' + err);
    }
  }

  // Get filenames to know which languages are available.
  var filenames = getFilenames(paths.lang[0]);

  filenames.forEach(function(filename) {

    var language = filename.replace('.json', '');

    var langpaths = paths.lang.map(function(path) {
      if (path.slice(-1) != '/') {
        path = path + '/';
      }
      return path + language + '.json';
    });

    var data = {};
    var firstFile = null;

    gulp.src(langpaths)
      .pipe(gulpSlash())
      .pipe(clipEmptyFiles())
      .pipe(through(function(file) {
        if (!firstFile) {
          firstFile = file;
        }
        return treatFile(file, data);
      }, function() {
        /* This implementation is based on gulp-jsoncombine module.
         * https://github.com/reflog/gulp-jsoncombine */
        if (firstFile) {
          var joinedPath = path.join(firstFile.base, language+'.json');

          var joinedFile = new File({
            cwd: firstFile.cwd,
            base: firstFile.base,
            path: joinedPath,
            contents: treatMergedData(data)
          });

          this.emit('data', joinedFile);
        }
        this.emit('end');
      }))
      .pipe(gulp.dest(paths.build + '/lang'));

  });
});

// Convert config.json into an AngularJS constant and append it to build file.
gulp.task('config', ['build'], function(done) {
  var source = [paths.build + '/' + buildFile, paths.config],
    configName = paths.config.substr(paths.config.lastIndexOf('/') + 1);

  gulp.src(source)
    .pipe(through(function(file) {
      if (file.path.indexOf(configName) > -1) {
        // It's config.json, let's convert it to an AngularJS constant.
        var contents = "angular.module('mm.core')\n\n" +
                       ".constant('mmCoreConfigConstants', " + file.contents.toString() + ");";
        file.contents = new Buffer(contents);
      }
      this.emit('data', file);
    }))
    .pipe(concat(buildFile))
    .pipe(gulp.dest(paths.build))
    .on('end', done);
});
<commit_msg>MOBILE-1528 gulp: Increase gulp watch interval<commit_after>var gulp = require('gulp');
var gutil = require('gulp-util');
var bower = require('bower');
var concat = require('gulp-concat');
var insert = require('gulp-insert');
var stripComments = require('gulp-strip-comments');
var removeEmptyLines = require('gulp-remove-empty-lines');
var clipEmptyFiles = require('gulp-clip-empty-files');
var sass = require('gulp-sass');
var minifyCss = require('gulp-minify-css');
var rename = require('gulp-rename');
var tap = require('gulp-tap');
var fs = require('fs');
var through = require('through');
var path = require('path');
var File = gutil.File;
var gulpSlash = require('gulp-slash');
var ngAnnotate = require('gulp-ng-annotate');

var license = '' +
  '// (C) Copyright 2015 Martin Dougiamas\n' +
  '//\n' +
  '// Licensed under the Apache License, Version 2.0 (the "License");\n' +
  '// you may not use this file except in compliance with the License.\n' +
  '// You may obtain a copy of the License at\n' +
  '//\n' +
  '//     http://www.apache.org/licenses/LICENSE-2.0\n' +
  '//\n' +
  '// Unless required by applicable law or agreed to in writing, software\n' +
  '// distributed under the License is distributed on an "AS IS" BASIS,\n' +
  '// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n' +
  '// See the License for the specific language governing permissions and\n' +
  '// limitations under the License.\n\n',
  buildFile = 'mm.bundle.js';

var paths = {
  build: './www/build',
  js: [
    './www/app.js',
    './www/core/main.js',
    './www/core/lib/*.js',
    './www/core/filters/*.js',
    './www/core/directives/*.js',
    './www/core/components/**/main.js',
    './www/core/components/**/*.js',
    './www/addons/**/main.js',
    './www/addons/**/*.js',
    '!./www/**/tests/*.js'
  ],
  sass: {
    core: [
      './www/core/scss/*.scss',
      './www/core/components/**/scss/*.scss',
      './www/addons/**/scss/*.scss',
    ],
    custom: [
      './scss/app.scss',
      './scss/**/*.scss'
    ]
  },
  lang: [
    './www/core/lang/',
    './www/core/components/**/lang/',
    './www/addons/**/lang/',
    './www/core/assets/countries/'
  ],
  config: './www/config.json'
};

gulp.task('default', ['build', 'sass', 'lang', 'config']);

gulp.task('sass-build', function(done) {
  gulp.src(paths.sass.core)
    .pipe(concat('mm.bundle.scss'))
    .pipe(gulp.dest(paths.build))
    .on('end', done);
});

gulp.task('sass', ['sass-build'], function(done) {
  gulp.src(paths.sass.custom)
    .pipe(concat('mm.bundle.css'))
    .pipe(sass())
    .pipe(gulp.dest(paths.build))
    .pipe(minifyCss({
      keepSpecialComments: 0
    }))
    .pipe(rename({ extname: '.min.css' }))
    .pipe(gulp.dest(paths.build))
    .on('end', done);
});

gulp.task('watch', function() {
  gulp.watch(paths.sass.core, { interval: 500 }, ['sass']);
  gulp.watch(paths.sass.custom, { interval: 500 }, ['sass']);
  gulp.watch(paths.js, { interval: 500 }, ['build', 'config']);
  var langsPaths = paths.lang.map(function(path) {
    return path + '*.json';
  });
  gulp.watch(langsPaths, { interval: 500 }, ['lang']);
  gulp.watch(paths.config, { interval: 500 }, ['config']);
});

gulp.task('build', function(done) {
  var dependencies = ["'mm.core'"],
      componentRegex = /core\/components\/([^\/]+)\/main.js/,
      pluginRegex = /addons\/([^\/]+)\/main.js/;

  gulp.src(paths.js)
    .pipe(gulpSlash())
    .pipe(clipEmptyFiles())
    .pipe(tap(function(file, t) {
      if (componentRegex.test(file.path)) {
        dependencies.push("'mm.core." + file.path.match(componentRegex)[1] + "'");
      } else if (pluginRegex.test(file.path)) {
        dependencies.push("'mm.addons." + file.path.match(pluginRegex)[1] + "'");
      }
    }))

    // Remove comments, remove empty lines, concat and add license.
    .pipe(stripComments())
    .pipe(removeEmptyLines())
    .pipe(ngAnnotate()) // This step fixes DI declarations for FirefoxOS.
    .pipe(concat(buildFile))
    .pipe(insert.prepend(license))

    // Add dependencies, this assumes that the mm module is declared on one line.
    .pipe(insert.transform(function(contents) {
      return contents.replace(
        "angular.module('mm', ['ionic'",
        "angular.module('mm', ['ionic', " + dependencies.join(', '));
    }))
    .pipe(gulp.dest(paths.build))
    .on('end', done);
});

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

  /**
   * Get the names of the JSON files inside a directory.
   * @param  {String} dir Directory's path.
   * @return {Array}      List of filenames.
   */
  function getFilenames(dir) {
    return fs.readdirSync(dir)
      .filter(function(file) {
        return file.indexOf('.json') > -1;
      })
  }

  /**
   * Copy a property from one object to another, adding a prefix to the key if needed.
   * @param {Object} target Object to copy the properties to.
   * @param {Object} source Object to copy the properties from.
   * @param {String} prefix Prefix to add to the keys.
   */
  function addProperties(target, source, prefix) {
    for (var property in source) {
      target[prefix + property] = source[property];
    }
  }

  /**
   * Treats the merged JSON data, adding prefixes depending on the component.
   * @param  {Object} data Merged data.
   * @return {Buffer}      Buffer with the treated data.
   */
  function treatMergedData(data) {
    var merged = {};

    for (var filepath in data) {

      if (filepath.indexOf('core/lang') == 0) {

        addProperties(merged, data[filepath], 'mm.core.');

      } else if (filepath.indexOf('core/components') == 0) {

        var componentName = filepath.replace('core/components/', '');
        componentName = componentName.substr(0, componentName.indexOf('/'));
        addProperties(merged, data[filepath], 'mm.'+componentName+'.');

      } else if (filepath.indexOf('addons') == 0) {

        var pluginName = filepath.replace('addons/', '');
        pluginName = pluginName.substr(0, pluginName.indexOf('/'));
        addProperties(merged, data[filepath], 'mma.'+pluginName+'.');

      } else if (filepath.indexOf('core/assets/countries') == 0) {

        addProperties(merged, data[filepath], 'mm.core.country-');

      }

    }

    return new Buffer(JSON.stringify(merged, null, 4));
  }

  /**
   * Treats a file to merge JSONs. This function is based on gulp-jsoncombine module.
   * https://github.com/reflog/gulp-jsoncombine
   * @param  {Object} file File treated.
   */
  function treatFile(file, data) {
    if (file.isNull() || file.isStream()) {
      return; // ignore
    }
    try {
      var path = file.path.substr(file.path.indexOf('/www/') + 5, file.path.length-5);
      data[path] = JSON.parse(file.contents.toString());
    } catch (err) {
      console.log('Error parsing JSON: ' + err);
    }
  }

  // Get filenames to know which languages are available.
  var filenames = getFilenames(paths.lang[0]);

  filenames.forEach(function(filename) {

    var language = filename.replace('.json', '');

    var langpaths = paths.lang.map(function(path) {
      if (path.slice(-1) != '/') {
        path = path + '/';
      }
      return path + language + '.json';
    });

    var data = {};
    var firstFile = null;

    gulp.src(langpaths)
      .pipe(gulpSlash())
      .pipe(clipEmptyFiles())
      .pipe(through(function(file) {
        if (!firstFile) {
          firstFile = file;
        }
        return treatFile(file, data);
      }, function() {
        /* This implementation is based on gulp-jsoncombine module.
         * https://github.com/reflog/gulp-jsoncombine */
        if (firstFile) {
          var joinedPath = path.join(firstFile.base, language+'.json');

          var joinedFile = new File({
            cwd: firstFile.cwd,
            base: firstFile.base,
            path: joinedPath,
            contents: treatMergedData(data)
          });

          this.emit('data', joinedFile);
        }
        this.emit('end');
      }))
      .pipe(gulp.dest(paths.build + '/lang'));

  });
});

// Convert config.json into an AngularJS constant and append it to build file.
gulp.task('config', ['build'], function(done) {
  var source = [paths.build + '/' + buildFile, paths.config],
    configName = paths.config.substr(paths.config.lastIndexOf('/') + 1);

  gulp.src(source)
    .pipe(through(function(file) {
      if (file.path.indexOf(configName) > -1) {
        // It's config.json, let's convert it to an AngularJS constant.
        var contents = "angular.module('mm.core')\n\n" +
                       ".constant('mmCoreConfigConstants', " + file.contents.toString() + ");";
        file.contents = new Buffer(contents);
      }
      this.emit('data', file);
    }))
    .pipe(concat(buildFile))
    .pipe(gulp.dest(paths.build))
    .on('end', done);
});
<|endoftext|>


<commit_before>var browserify = require('browserify'),
    concat = require('gulp-concat'),
    es6ify = require('es6ify'),
    gulp = require('gulp'),
    jshint = require('gulp-jshint'),
    gutil = require('gulp-util'),
    jade = require('gulp-jade'),
    jshint = require('gulp-jshint'),
    less = require('gulp-less'),
    minifyCss = require('gulp-minify-css'),
    minifyHtml = require('gulp-minify-html'),
    nodemon = require('gulp-nodemon'),
    path = require('path'),
    rev = require('gulp-rev'),
    source = require('vinyl-source-stream'),
    streamify = require('gulp-streamify'),
    stringify = require('stringify'),
    uglify = require('gulp-uglify'),
    karma = require('gulp-karma'),
    watchify = require('watchify'),
    mocha = require('gulp-mocha');

var paths = {
    public: 'public/**',
    jade: 'app/**/*.jade',
    scripts: 'app/**/*.js',
    libTests: ['mocha.js'],
    styles: 'app/styles/*.+(less|css)'
}

var testFiles = [
    'public/lib/angular/angular.js',
    'public/lib/angular-mocks/angular-mocks.js',
    'public/lib/moment/moment.js',
    'public/lib/firebase/firebase.js',
    'public/lib/angular-aria/angular-aria.js',
    'public/lib/angular-ui-router/release/angular-ui-router.min.js',
    'public/lib/hammerjs/hammer.min.js',
    'public/lib/angular-material/angular-material.js',
    'public/lib/angular-route/angular-route.js',
    'public/lib/angular-cookies/angular-cookies.js',
    'public/lib/angular-bootstrap/ui-bootstrap.js',
    'public/lib/angular-animate/angular-animate.js',
    'public/lib/angular-sanitize/angular-sanitize.js',
    'public/lib/angularfire/dist/angularfire.js',
    'public/js/index.js',
    'app/test/specs.js'
];

gulp.task('lint', function() {
  return gulp.src('./lib/*.js')
    .pipe(jshint())
    .pipe(jshint.reporter('YOUR_REPORTER_HERE'));
});

gulp.task('jade', function() {
    gulp.src('./app/**/*.jade')
        .pipe(jade())
        .pipe(gulp.dest('./public/'))
});

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

gulp.task('lint', function() {
    gulp.src('./**/*.js').pipe(jshint())
});

//'app/**',
gulp.task('nodemon', function() {
    nodemon({
            script: 'index.js',
            ext: 'js',
            ignore: ['public/']
        })
        .on('change', ['lint'])
        .on('restart', function() {
            console.log('>> node restart');
        })
});

gulp.task('watch', function() {
    // livereload.listen({ port: 35729 });
    gulp.watch(paths.jade, ['jade']);
    gulp.watch(paths.styles, ['less']);
    // gulp.watch(paths.public).on('change', livereload.changed);
});

gulp.task('watchify', function() {
    var bundler = watchify(browserify('./app/application.js', watchify.args));

    bundler.transform(stringify(['.html']));
    // bundler.transform(es6ify);

    bundler.on('update', rebundle);

    function rebundle() {
        return bundler.bundle()
            // log errors if they happen
            .on('error', gutil.log.bind(gutil, 'Browserify Error'))
            .pipe(source('index.js'))
            .pipe(gulp.dest('./public/js'));
    }

    return rebundle();
});

// gulp.task('usemin', function() {
//   gulp.src('public/*.html')
//     .pipe(usemin({
//       css: [minifyCss(), 'concat'],
//       html: [minifyHtml({empty: true})],
//       js: [uglify(), rev()]
//     }))
//     .pipe(gulp.dest('public'));
// });

gulp.task('mocha', function() {
    return gulp.src(paths.libTests)
        .pipe(mocha({
            reporter: 'dot'
        }))
        .pipe(exit());
});

gulp.task('test', function() {
    // Be sure to return the stream
    return gulp.src(testFiles)
        .pipe(karma({
            configFile: 'karma.conf.js',
            action: 'run'
        }))
        .on('error', function(err) {
            // Make sure failed tests cause gulp to exit non-zero
            //throw err;
        });
});
gulp.task('heroku:production', ['scripts', 'jade', 'less']);
gulp.task('production', ['nodemon']);
gulp.task('default', ['nodemon', 'jade', 'less', 'watch', 'watchify']);
gulp.task('build', ['jade', 'less', 'watchify']);
<commit_msg>Configured gulp lint task to report jshint<commit_after>var browserify = require('browserify'),
    concat = require('gulp-concat'),
    es6ify = require('es6ify'),
    gulp = require('gulp'),
    jshint = require('gulp-jshint'),
    gutil = require('gulp-util'),
    jade = require('gulp-jade'),
    jshint = require('gulp-jshint'),
    less = require('gulp-less'),
    minifyCss = require('gulp-minify-css'),
    minifyHtml = require('gulp-minify-html'),
    nodemon = require('gulp-nodemon'),
    path = require('path'),
    rev = require('gulp-rev'),
    source = require('vinyl-source-stream'),
    streamify = require('gulp-streamify'),
    stringify = require('stringify'),
    uglify = require('gulp-uglify'),
    karma = require('gulp-karma'),
    watchify = require('watchify'),
    mocha = require('gulp-mocha');

var paths = {
    public: 'public/**',
    jade: 'app/**/*.jade',
    scripts: 'app/**/*.js',
    libTests: ['mocha.js'],
    styles: 'app/styles/*.+(less|css)'
}

var testFiles = [
    'public/lib/angular/angular.js',
    'public/lib/angular-mocks/angular-mocks.js',
    'public/lib/moment/moment.js',
    'public/lib/firebase/firebase.js',
    'public/lib/angular-aria/angular-aria.js',
    'public/lib/angular-ui-router/release/angular-ui-router.min.js',
    'public/lib/hammerjs/hammer.min.js',
    'public/lib/angular-material/angular-material.js',
    'public/lib/angular-route/angular-route.js',
    'public/lib/angular-cookies/angular-cookies.js',
    'public/lib/angular-bootstrap/ui-bootstrap.js',
    'public/lib/angular-animate/angular-animate.js',
    'public/lib/angular-sanitize/angular-sanitize.js',
    'public/lib/angularfire/dist/angularfire.js',
    'public/js/index.js',
    'app/test/specs.js'
];

gulp.task('lint', function() {
  return gulp.src('./lib/*.js')
    .pipe(jshint())
    .pipe(jshint.reporter('YOUR_REPORTER_HERE'));
});

gulp.task('jade', function() {
    gulp.src('./app/**/*.jade')
        .pipe(jade())
        .pipe(gulp.dest('./public/'))
});

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

gulp.task('lint', function() {
    gulp.src(['index.js','./app/**/*.js']).pipe(jshint())
    .pipe(jshint.reporter('default'));
});

//'app/**',
gulp.task('nodemon', function() {
    nodemon({
            script: 'index.js',
            ext: 'js',
            ignore: ['public/']
        })
        .on('change', ['lint'])
        .on('restart', function() {
            console.log('>> node restart');
        })
});

gulp.task('watch', function() {
    // livereload.listen({ port: 35729 });
    gulp.watch(paths.jade, ['jade']);
    gulp.watch(paths.styles, ['less']);
    // gulp.watch(paths.public).on('change', livereload.changed);
});

gulp.task('watchify', function() {
    var bundler = watchify(browserify('./app/application.js', watchify.args));

    bundler.transform(stringify(['.html']));
    // bundler.transform(es6ify);

    bundler.on('update', rebundle);

    function rebundle() {
        return bundler.bundle()
            // log errors if they happen
            .on('error', gutil.log.bind(gutil, 'Browserify Error'))
            .pipe(source('index.js'))
            .pipe(gulp.dest('./public/js'));
    }

    return rebundle();
});

// gulp.task('usemin', function() {
//   gulp.src('public/*.html')
//     .pipe(usemin({
//       css: [minifyCss(), 'concat'],
//       html: [minifyHtml({empty: true})],
//       js: [uglify(), rev()]
//     }))
//     .pipe(gulp.dest('public'));
// });

gulp.task('mocha', function() {
    return gulp.src(paths.libTests)
        .pipe(mocha({
            reporter: 'dot'
        }))
        .pipe(exit());
});

gulp.task('test', function() {
    // Be sure to return the stream
    return gulp.src(testFiles)
        .pipe(karma({
            configFile: 'karma.conf.js',
            action: 'run'
        }))
        .on('error', function(err) {
            // Make sure failed tests cause gulp to exit non-zero
            //throw err;
        });
});
gulp.task('heroku:production', ['scripts', 'jade', 'less']);
gulp.task('production', ['nodemon']);
gulp.task('default', ['nodemon', 'jade', 'less', 'watch', 'watchify']);
gulp.task('build', ['jade', 'less', 'watchify']);
<|endoftext|>


<commit_before>'use strict';

// Require the needed npm modules.
const gulp = require('gulp'),
	uglify = require('gulp-uglify'),
	rename = require('gulp-rename'),
	sass = require('gulp-sass'),
	maps = require('gulp-sourcemaps'),
	useref = require('gulp-useref'),
	iff = require('gulp-if'),
	csso = require('gulp-csso'),
	concat = require('gulp-concat'),
	del = require('del');

// This task may be redundant due to 'minifyScripts' task.  Delete it?
// gulp.task('concatScripts', function() {
// 	return gulp.src(['js/**/*', 'js/*'])
// 			.pipe(concat('all.js'))
// 			.pipe(gulp.dest('js'));
// });

gulp.task('scripts', ['jsMap'], function() {
	gulp.src(['js/**/**', 'js/*'])
		.pipe(concat('all.js'))
		.pipe(uglify())
		.pipe(rename('all.min.js'))
		.pipe(gulp.dest('dist/scripts/'));
});

gulp.task('jsMap', function() {
	return gulp.src('js/**/*')
	.pipe(maps.init())
	.pipe(concat('all.js'))
	.pipe(maps.write('./'))
	.pipe(gulp.dest('dist/scripts'));
});

gulp.task('styles', function() {
	return gulp.src('sass/global.scss')
		.pipe(maps.init())
		.pipe(sass())
		.pipe(maps.write('./'))
		.pipe(gulp.dest('dist/styles'));
});

//
<commit_msg>Added 'clean' task & gulp default task.<commit_after>'use strict';

// Require the needed npm modules.
const gulp = require('gulp'),
	uglify = require('gulp-uglify'),
	rename = require('gulp-rename'),
	sass = require('gulp-sass'),
	maps = require('gulp-sourcemaps'),
	useref = require('gulp-useref'),
	iff = require('gulp-if'),
	csso = require('gulp-csso'),
	concat = require('gulp-concat'),
	del = require('del');

// This task may be redundant due to 'minifyScripts' task.  Delete it?
// gulp.task('concatScripts', function() {
// 	return gulp.src(['js/**/*', 'js/*'])
// 			.pipe(concat('all.js'))
// 			.pipe(gulp.dest('js'));
// });

gulp.task('scripts', ['jsMap'], function() {
	gulp.src(['js/**/**', 'js/*'])
		.pipe(concat('all.js'))
		.pipe(uglify())
		.pipe(rename('all.min.js'))
		.pipe(gulp.dest('dist/scripts/'));
	del('dist/scripts/all.js');
});

gulp.task('jsMap', function() {
	return gulp.src('js/**/*')
	.pipe(maps.init())
	.pipe(concat('all.js'))
	.pipe(maps.write('./'))
	.pipe(gulp.dest('dist/scripts'));
});

gulp.task('styles', function() {
	return gulp.src('sass/global.scss')
		.pipe(maps.init())
		.pipe(sass())
		.pipe(maps.write('./'))
		.pipe(gulp.dest('dist/styles'));
});

gulp.task('clean', function() {
	return del('dist/*');
});

gulp.task('default', ['clean'], function() {
	// gulp.start('build');
});

//
<|endoftext|>


<commit_before>const projects = require('../../db/model/projects');
const projectDelete = require('../../db/model/project-delete');
const parse = require('co-body');
const status = require('http-status');
const ra = require('../resource-access');
const Router = require('koa-router');

const samples = require('./samples');
const files = require('./files');
const directories = require('./directories');
const processes = require('./processes');
const shares = require('./shares');
const experiments = require('./experiments');

function* create(next){
    let user = this.reqctx.user;
    let attrs = yield parse(this);
    let rv = yield projects.createProject(user,attrs);
    if (rv.error) {
        this.status = status.BAD_REQUEST;
        this.body = rv;
    } else {
        this.body = rv.val;
    }
    yield next;
}

function* all(next) {
    let user = this.reqctx.user;
    if (this.query.simple) {
        this.body = yield projects.forUserSimple(user);
    } else {
        this.body = yield projects.forUser(user);
    }
    yield next;
}

function* getProject(next) {
    let rv = yield projects.getProject(this.params.project_id);
    if (rv.error) {
        this.status = status.BAD_REQUEST;
        this.body = rv;
    } else {
        this.body = rv.val;
    }
    yield next;
}

function* deleteProject(next) {
    yield projectDelete.quickProjectDelete(this.params.project_id);
    this.body = {
        val: {
            project_id: this.params.project_id
        }
    };

    yield next;
}

function* deleteProjectFull(next) {
    let options = {
        dryRun: false
    };
    let rv = yield projectDelete.deleteProject(this.params.project_id,options);
    if (rv.error) {
        this.status = status.BAD_REQUEST;
        this.body = rv;
    } else {
        this.body = rv.val;
    }
    yield next;
}

function* update(next) {
    let attrs = yield parse(this);
    this.body = yield projects.update(this.params.project_id, attrs);
    yield next;
}

function* getUserAccessForProject(next) {
    this.body = yield projects.getUserAccessForProject(this.params.project_id);
    yield next;
}

function* updateUserAccessForProject(next) {
    let attrs = yield parse(this);
    this.body = yield projects.updateUserAccessForProject(this.params.project_id,attrs);
    yield next;
}

function createResource() {
    const router = new Router();
    router.get('/', all);
    router.post('/',create);
    router.use('/:project_id', ra.validateProjectAccess);
    router.put('/:project_id', update);
    router.get('/:project_id', getProject);
    router.delete('/:project_id', ra.validateProjectOwner, deleteProject);

    router.get('/:project_id/access', ra.validateProjectOwner, getUserAccessForProject);
    router.put('/:project_id/access', ra.validateProjectOwner, updateUserAccessForProject);

    let samplesResource = samples.createResource();
    router.use('/:project_id/samples', samplesResource.routes(), samplesResource.allowedMethods());

    let filesResource = files.createResource();
    router.use('/:project_id/files', filesResource.routes(), filesResource.allowedMethods());

    let directoriesResource = directories.createResource();
    router.use('/:project_id/directories', directoriesResource.routes(), directoriesResource.allowedMethods());

    let processesResource = processes.createResource();
    router.use('/:project_id/processes', processesResource.routes(), processesResource.allowedMethods());

    let sharesResource = shares.createResource();
    router.use('/:project_id/shares', sharesResource.routes(), sharesResource.allowedMethods());

    let experimentsResource = experiments.createResource();
    router.use('/:project_id/experiments', experimentsResource.routes(), experimentsResource.allowedMethods());

    return router;
}

module.exports = {
    createResource
};
<commit_msg>delete project returns id<commit_after>const projects = require('../../db/model/projects');
const projectDelete = require('../../db/model/project-delete');
const parse = require('co-body');
const status = require('http-status');
const ra = require('../resource-access');
const Router = require('koa-router');

const samples = require('./samples');
const files = require('./files');
const directories = require('./directories');
const processes = require('./processes');
const shares = require('./shares');
const experiments = require('./experiments');

function* create(next){
    let user = this.reqctx.user;
    let attrs = yield parse(this);
    let rv = yield projects.createProject(user,attrs);
    if (rv.error) {
        this.status = status.BAD_REQUEST;
        this.body = rv;
    } else {
        this.body = rv.val;
    }
    yield next;
}

function* all(next) {
    let user = this.reqctx.user;
    if (this.query.simple) {
        this.body = yield projects.forUserSimple(user);
    } else {
        this.body = yield projects.forUser(user);
    }
    yield next;
}

function* getProject(next) {
    let rv = yield projects.getProject(this.params.project_id);
    if (rv.error) {
        this.status = status.BAD_REQUEST;
        this.body = rv;
    } else {
        this.body = rv.val;
    }
    yield next;
}

function* deleteProject(next) {
    yield projectDelete.quickProjectDelete(this.params.project_id);
    this.body = this.params.project_id
    yield next;
}

function* deleteProjectFull(next) {
    let options = {
        dryRun: false
    };
    let rv = yield projectDelete.deleteProject(this.params.project_id,options);
    if (rv.error) {
        this.status = status.BAD_REQUEST;
        this.body = rv;
    } else {
        this.body = rv.val;
    }
    yield next;
}

function* update(next) {
    let attrs = yield parse(this);
    this.body = yield projects.update(this.params.project_id, attrs);
    yield next;
}

function* getUserAccessForProject(next) {
    this.body = yield projects.getUserAccessForProject(this.params.project_id);
    yield next;
}

function* updateUserAccessForProject(next) {
    let attrs = yield parse(this);
    this.body = yield projects.updateUserAccessForProject(this.params.project_id,attrs);
    yield next;
}

function createResource() {
    const router = new Router();
    router.get('/', all);
    router.post('/',create);
    router.use('/:project_id', ra.validateProjectAccess);
    router.put('/:project_id', update);
    router.get('/:project_id', getProject);
    router.delete('/:project_id', ra.validateProjectOwner, deleteProject);

    router.get('/:project_id/access', ra.validateProjectOwner, getUserAccessForProject);
    router.put('/:project_id/access', ra.validateProjectOwner, updateUserAccessForProject);

    let samplesResource = samples.createResource();
    router.use('/:project_id/samples', samplesResource.routes(), samplesResource.allowedMethods());

    let filesResource = files.createResource();
    router.use('/:project_id/files', filesResource.routes(), filesResource.allowedMethods());

    let directoriesResource = directories.createResource();
    router.use('/:project_id/directories', directoriesResource.routes(), directoriesResource.allowedMethods());

    let processesResource = processes.createResource();
    router.use('/:project_id/processes', processesResource.routes(), processesResource.allowedMethods());

    let sharesResource = shares.createResource();
    router.use('/:project_id/shares', sharesResource.routes(), sharesResource.allowedMethods());

    let experimentsResource = experiments.createResource();
    router.use('/:project_id/experiments', experimentsResource.routes(), experimentsResource.allowedMethods());

    return router;
}

module.exports = {
    createResource
};
<|endoftext|>


<commit_before>var gulp = require('gulp');
var concat = require('gulp-concat');
var nodemon = require('gulp-nodemon');

gulp.task('build', function () {
    return gulp
        .src(['./src/translate.js', './src/**/*.js'])
        .pipe(concat('mutant-ng-translate.js'))
        .pipe(gulp.dest('./build/'));
});

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

gulp.task('server', function() {
    nodemon({
        script: './demo/server.js'
    });
});<commit_msg>add visual studio binding to start watch and server tasks when project opened<commit_after>/// <binding ProjectOpened='watch, server' />
var gulp = require('gulp');
var concat = require('gulp-concat');
var nodemon = require('gulp-nodemon');

gulp.task('build', function () {
    return gulp
        .src(['./src/translate.js', './src/**/*.js'])
        .pipe(concat('mutant-ng-translate.js'))
        .pipe(gulp.dest('./build/'));
});

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

gulp.task('server', function() {
    nodemon({
        script: './demo/server.js'
    });
});<|endoftext|>


<commit_before>var gulp = require('gulp');
var browserify = require('browserify');
var webserver = require('gulp-webserver');
var del = require('del');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var watchify = require('watchify');
var gutil = require('gulp-util');
var sass = require('gulp-sass');
var concat = require('gulp-concat');
var autoprefixer = require('gulp-autoprefixer');
var cacheBuster = require('gulp-cache-bust');
var uglify = require('gulp-uglify');
var pump = require('pump');
var uglifycss = require('gulp-uglifycss');

gulp.task('clean',
    function() {
        return del.sync(['public/**/*']);
    }
)

gulp.task('buildHTML', function () {
    return gulp.src('src/html/**/*.html').pipe(gulp.dest('public/'));
});

// Hack to enable configurable watchify watching
var watching = false;
gulp.task('enable-watch-mode', function() {
    gulp.watch('src/html/**/*.html', ['buildHTML']);
    gulp.watch('src/sass/**/*.scss', ['buildCSS']);
    watching = true;
});

gulp.task('buildJS', function() {
    var bundler = browserify('src/js/index.js', { cache: {}, packageCache: {} });

    function bundle() {
        bundler.ignore('reactstrap-tether');

        return bundler.transform('babelify', {presets: ['es2015', 'react']})
            .bundle()
            .on('error', gutil.log.bind(gutil, 'Browserify Error'))
            .pipe(source('index.js'))
            .pipe(buffer())
            .pipe(gulp.dest('public/js'));
    }

    if(watching === true) {
        bundler.plugin(watchify);
        bundler.on('update', bundle);
        bundler.on('log', gutil.log);
    }
    return bundle();
});

gulp.task('buildCSS', function() {
    return gulp.src('src/sass/**/*.scss')
        .pipe(sass().on('error', sass.logError))
        .pipe(concat('style.css'))
        .pipe(autoprefixer({
            browsers: ['last 3 versions']
        }))
        .pipe(gulp.dest('public/css'));
});

gulp.task('compressJS',  ['buildJS'], function (cb) {
    pump([gulp.src('public/js/**/*.js'),
        uglify(),
        gulp.dest('public/js')
        ], cb);
});

gulp.task('compressCSS',  ['buildCSS'], function (cb) {
    pump([gulp.src('public/css/**/*.css'),
        uglifycss(),
        gulp.dest('public/css/')
        ], cb);
});

gulp.task('cacheBust', ['compressJS', 'compressCSS', 'buildHTML'], function () {
    return gulp.src('public/index.html')
        .pipe(cacheBuster())
        .pipe(gulp.dest('public/'));
});

gulp.task('serve', function() {
    return gulp.src('public').pipe(webserver({
        livereload: false,
        host: '0.0.0.0',
        port: 8080
    }));
});

gulp.task('build', ['clean', 'buildJS', 'buildCSS', 'buildHTML']);

gulp.task('default', ['enable-watch-mode', 'build', 'serve']);

gulp.task('dist', ['build', 'compressCSS', 'compressJS', 'cacheBust']);

gulp.task('distRun', ['dist', 'serve']);<commit_msg>Support assets in build<commit_after>var gulp = require('gulp');
var browserify = require('browserify');
var webserver = require('gulp-webserver');
var del = require('del');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var watchify = require('watchify');
var gutil = require('gulp-util');
var sass = require('gulp-sass');
var concat = require('gulp-concat');
var autoprefixer = require('gulp-autoprefixer');
var cacheBuster = require('gulp-cache-bust');
var uglify = require('gulp-uglify');
var pump = require('pump');
var uglifycss = require('gulp-uglifycss');

gulp.task('clean',
    function() {
        return del.sync(['public/**/*']);
    }
);

gulp.task('copyAssets', function () {
    return gulp.src('src/assets/**/*').pipe(gulp.dest('public/'));
});

gulp.task('buildHTML', function () {
    return gulp.src('src/html/**/*.html').pipe(gulp.dest('public/'));
});

// Hack to enable configurable watchify watching
var watching = false;
gulp.task('enable-watch-mode', function() {
    gulp.watch('src/html/**/*.html', ['buildHTML']);
    gulp.watch('src/sass/**/*.scss', ['buildCSS']);
    watching = true;
});

gulp.task('buildJS', function() {
    var bundler = browserify('src/js/index.js', { cache: {}, packageCache: {} });

    function bundle() {
        bundler.ignore('reactstrap-tether');

        return bundler.transform('babelify', {presets: ['es2015', 'react']})
            .bundle()
            .on('error', gutil.log.bind(gutil, 'Browserify Error'))
            .pipe(source('index.js'))
            .pipe(buffer())
            .pipe(gulp.dest('public/js'));
    }

    if(watching === true) {
        bundler.plugin(watchify);
        bundler.on('update', bundle);
        bundler.on('log', gutil.log);
    }
    return bundle();
});

gulp.task('buildCSS', function() {
    return gulp.src('src/sass/**/*.scss')
        .pipe(sass().on('error', sass.logError))
        .pipe(concat('style.css'))
        .pipe(autoprefixer({
            browsers: ['last 3 versions']
        }))
        .pipe(gulp.dest('public/css'));
});

gulp.task('compressJS',  ['buildJS'], function (cb) {
    pump([gulp.src('public/js/**/*.js'),
        uglify(),
        gulp.dest('public/js')
        ], cb);
});

gulp.task('compressCSS',  ['buildCSS'], function (cb) {
    pump([gulp.src('public/css/**/*.css'),
        uglifycss(),
        gulp.dest('public/css/')
        ], cb);
});

gulp.task('cacheBust', ['compressJS', 'compressCSS', 'buildHTML'], function () {
    return gulp.src('public/index.html')
        .pipe(cacheBuster())
        .pipe(gulp.dest('public/'));
});

gulp.task('serve', function() {
    return gulp.src('public').pipe(webserver({
        livereload: false,
        host: '0.0.0.0',
        port: 8080
    }));
});

gulp.task('build', ['clean', 'buildJS', 'buildCSS', 'buildHTML', 'copyAssets']);

gulp.task('default', ['enable-watch-mode', 'build', 'serve']);

gulp.task('dist', ['build', 'compressCSS', 'compressJS', 'cacheBust']);

gulp.task('distRun', ['dist', 'serve']);<|endoftext|>


<commit_before>"use strict";

const fs = require("fs");
const gulp = require("gulp");
const del = require('del');
const sequence = require("run-sequence");
const merge = require('event-stream').merge;
const jshint = require("gulp-jshint");
const browserify = require("browserify");
const source = require("vinyl-source-stream");
const gzip = require("gulp-gzip");
const mocha = require("gulp-mocha");
const istanbul = require("gulp-istanbul");
const webserver = require('gulp-webserver');
const jsdoc = require("gulp-jsdoc");
const bower = require('gulp-bower');
const ghPages = require('gulp-gh-pages');
const bump = require('gulp-bump');
const argv = require('minimist')(process.argv.slice(2));
const git = require('gulp-git');

gulp.task("clean", (done) => {
    return del([
        ".publish/",
        "coverage/",
        "build/",
        "publish/"
    ], done);
});

gulp.task("build", [ "clean" ], () => {
    return browserify({
        entries: [ "src/kuromoji.js" ],
        standalone: "kuromoji" // window.kuromoji
    })
        .bundle()
        .pipe(source("kuromoji.js"))
        .pipe(gulp.dest("build/"));
});

gulp.task("watch", () => {
    gulp.watch([ "src/**/*.js", "test/**/*.js" ], [ "lint", "build", "jsdoc" ]);
});

gulp.task("clean-dict", (done) => {
    return del([ "dict/" ], done);
});

gulp.task("create-dat-files", (done) => {
    const IPADic = require('mecab-ipadic-seed');
    const kuromoji = require("./src/kuromoji.js");

    if (!fs.existsSync("dict/")) {
        fs.mkdirSync("dict/");
    }

    // To node.js Buffer
    function toBuffer (typed) {
        var ab = typed.buffer;
        var buffer = new Buffer(ab.byteLength);
        var view = new Uint8Array(ab);
        for (var i = 0; i < buffer.length; ++i) {
            buffer[i] = view[i];
        }
        return buffer;
    }

    const dic = new IPADic();
    const builder = kuromoji.dictionaryBuilder();

    // Build token info dictionary
    const tokenInfoPromise = dic.readTokenInfo((line) => {
        builder.addTokenInfoDictionary(line);
    }).then(() => {
        console.log('Finishied to read token info dics');
    });

    // Build connection costs matrix
    const matrixDefPromise = dic.readMatrixDef((line) => {
        builder.putCostMatrixLine(line);
    }).then(() => {
        console.log('Finishied to read matrix.def');
    });

    // Build unknown dictionary
    const unkDefPromise = dic.readUnkDef((line) => {
        builder.putUnkDefLine(line);
    }).then(() => {
        console.log('Finishied to read unk.def');
    });

    // Build character definition dictionary
    const charDefPromise = dic.readCharDef((line) => {
        builder.putCharDefLine(line);
    }).then(() => {
        console.log('Finishied to read char.def');
    });

    // Build kuromoji.js binary dictionary
    Promise.all([ tokenInfoPromise, matrixDefPromise, unkDefPromise, charDefPromise ]).then(() => {
        console.log('Finishied to read all seed dictionary files');
        console.log('Building binary dictionary ...');
        return builder.build();
    }).then((dic) => {
        const base_buffer = toBuffer(dic.trie.bc.getBaseBuffer());
        const check_buffer = toBuffer(dic.trie.bc.getCheckBuffer());
        const token_info_buffer = toBuffer(dic.token_info_dictionary.dictionary.buffer);
        const tid_pos_buffer = toBuffer(dic.token_info_dictionary.pos_buffer.buffer);
        const tid_map_buffer = toBuffer(dic.token_info_dictionary.targetMapToBuffer());
        const connection_costs_buffer = toBuffer(dic.connection_costs.buffer);
        const unk_buffer = toBuffer(dic.unknown_dictionary.dictionary.buffer);
        const unk_pos_buffer = toBuffer(dic.unknown_dictionary.pos_buffer.buffer);
        const unk_map_buffer = toBuffer(dic.unknown_dictionary.targetMapToBuffer());
        const char_map_buffer = toBuffer(dic.unknown_dictionary.character_definition.character_category_map);
        const char_compat_map_buffer = toBuffer(dic.unknown_dictionary.character_definition.compatible_category_map);
        const invoke_definition_map_buffer = toBuffer(dic.unknown_dictionary.character_definition.invoke_definition_map.toBuffer());

        fs.writeFileSync("dict/base.dat", base_buffer);
        fs.writeFileSync("dict/check.dat", check_buffer);
        fs.writeFileSync("dict/tid.dat", token_info_buffer);
        fs.writeFileSync("dict/tid_pos.dat", tid_pos_buffer);
        fs.writeFileSync("dict/tid_map.dat", tid_map_buffer);
        fs.writeFileSync("dict/cc.dat", connection_costs_buffer);
        fs.writeFileSync("dict/unk.dat", unk_buffer);
        fs.writeFileSync("dict/unk_pos.dat", unk_pos_buffer);
        fs.writeFileSync("dict/unk_map.dat", unk_map_buffer);
        fs.writeFileSync("dict/unk_char.dat", char_map_buffer);
        fs.writeFileSync("dict/unk_compat.dat", char_compat_map_buffer);
        fs.writeFileSync("dict/unk_invoke.dat", invoke_definition_map_buffer);

        done();
    });
});

gulp.task("compress-dict", () => {
    return gulp.src("dict/*.dat")
        .pipe(gzip())
        .pipe(gulp.dest("dict/"));
});

gulp.task("clean-dat-files", (done) => {
    return del([ "dict/*.dat" ], done);
});

gulp.task("build-dict", [ "build", "clean-dict" ], () => {
    sequence("create-dat-files", "compress-dict", "clean-dat-files");
});

gulp.task("test", [ "build" ], () => {
    return gulp.src("test/**/*.js", { read: false })
        .pipe(mocha({ reporter: "list" }));
});

gulp.task("coverage", [ "test" ], (done) => {
    gulp.src([ "src/**/*.js" ])
        .pipe(istanbul())
        .pipe(istanbul.hookRequire())
        .on("finish", () => {
            gulp.src([ "test/**/*.js" ])
                .pipe(mocha({ reporter: "mocha-lcov-reporter" }))
                .pipe(istanbul.writeReports())
                .on("end", done);
        });
});

gulp.task("lint", () => {
    return gulp.src([ "src/**/*.js" ])
        .pipe(jshint())
        .pipe(jshint.reporter("default"));
});

gulp.task("clean-jsdoc", (done) => {
    return del([ "publish/jsdoc/" ], done);
});

gulp.task("jsdoc", [ "clean-jsdoc" ], () => {
    return gulp.src([ "src/**/*.js" ])
        .pipe(jsdoc("publish/jsdoc"));
});

gulp.task("clean-demo", (done) => {
    return del([ "publish/demo/" ], done);
});

gulp.task("copy-demo", [ "clean-demo", "build" ], () => {
    return merge(
        gulp.src('demo/**/*')
            .pipe(gulp.dest('publish/demo/')),
        gulp.src('build/**/*')
            .pipe(gulp.dest('publish/demo/kuromoji/build/')),
        gulp.src('dict/**/*')
            .pipe(gulp.dest('publish/demo/kuromoji/dict/')));
});

gulp.task("build-demo", [ "copy-demo" ], () => {
    return bower({ cwd: 'publish/demo/' });
});

gulp.task("webserver", [ "build-demo", "jsdoc" ], () => {
    gulp.src("publish/")
        .pipe(webserver({
            port: 8000,
            livereload: true,
            directoryListing: true
        }));
});

gulp.task("deploy", [ "build-demo", "jsdoc" ], () => {
    return gulp.src('publish/**/*')
        .pipe(ghPages());
});

gulp.task("version", function () {
    let type = 'patch';
    if (argv['minor']) {
        type = 'minor';
    }
    if (argv['major']) {
        type = 'major';
    }
    if (argv['prerelease']) {
        type = 'prerelease';
    }
    return gulp.src([ './bower.json', './package.json' ])
        .pipe(bump({ type: type }))
        .pipe(gulp.dest('./'));
});

gulp.task("release-commit", function () {
    var version = JSON.parse(fs.readFileSync('./package.json', 'utf8')).version;
    return gulp.src('.')
        .pipe(git.add())
        .pipe(git.commit(`chore: release ${version}`));
});

gulp.task("release-tag", function (callback) {
    var version = JSON.parse(fs.readFileSync('./package.json', 'utf8')).version;
    git.tag(version, `${version} release`, function (error) {
        if (error) {
            return callback(error);
        }
        callback(); // git.push('origin', 'master', {args: '--tags'}, callback);
    });
});

gulp.task("release", [ "test" ], () => {
    sequence("release-commit", "release-tag");
});
<commit_msg>style: remove commented-out code in gulpfile.js<commit_after>"use strict";

const fs = require("fs");
const gulp = require("gulp");
const del = require('del');
const sequence = require("run-sequence");
const merge = require('event-stream').merge;
const jshint = require("gulp-jshint");
const browserify = require("browserify");
const source = require("vinyl-source-stream");
const gzip = require("gulp-gzip");
const mocha = require("gulp-mocha");
const istanbul = require("gulp-istanbul");
const webserver = require('gulp-webserver');
const jsdoc = require("gulp-jsdoc");
const bower = require('gulp-bower');
const ghPages = require('gulp-gh-pages');
const bump = require('gulp-bump');
const argv = require('minimist')(process.argv.slice(2));
const git = require('gulp-git');

gulp.task("clean", (done) => {
    return del([
        ".publish/",
        "coverage/",
        "build/",
        "publish/"
    ], done);
});

gulp.task("build", [ "clean" ], () => {
    return browserify({
        entries: [ "src/kuromoji.js" ],
        standalone: "kuromoji" // window.kuromoji
    })
        .bundle()
        .pipe(source("kuromoji.js"))
        .pipe(gulp.dest("build/"));
});

gulp.task("watch", () => {
    gulp.watch([ "src/**/*.js", "test/**/*.js" ], [ "lint", "build", "jsdoc" ]);
});

gulp.task("clean-dict", (done) => {
    return del([ "dict/" ], done);
});

gulp.task("create-dat-files", (done) => {
    const IPADic = require('mecab-ipadic-seed');
    const kuromoji = require("./src/kuromoji.js");

    if (!fs.existsSync("dict/")) {
        fs.mkdirSync("dict/");
    }

    // To node.js Buffer
    function toBuffer (typed) {
        var ab = typed.buffer;
        var buffer = new Buffer(ab.byteLength);
        var view = new Uint8Array(ab);
        for (var i = 0; i < buffer.length; ++i) {
            buffer[i] = view[i];
        }
        return buffer;
    }

    const dic = new IPADic();
    const builder = kuromoji.dictionaryBuilder();

    // Build token info dictionary
    const tokenInfoPromise = dic.readTokenInfo((line) => {
        builder.addTokenInfoDictionary(line);
    }).then(() => {
        console.log('Finishied to read token info dics');
    });

    // Build connection costs matrix
    const matrixDefPromise = dic.readMatrixDef((line) => {
        builder.putCostMatrixLine(line);
    }).then(() => {
        console.log('Finishied to read matrix.def');
    });

    // Build unknown dictionary
    const unkDefPromise = dic.readUnkDef((line) => {
        builder.putUnkDefLine(line);
    }).then(() => {
        console.log('Finishied to read unk.def');
    });

    // Build character definition dictionary
    const charDefPromise = dic.readCharDef((line) => {
        builder.putCharDefLine(line);
    }).then(() => {
        console.log('Finishied to read char.def');
    });

    // Build kuromoji.js binary dictionary
    Promise.all([ tokenInfoPromise, matrixDefPromise, unkDefPromise, charDefPromise ]).then(() => {
        console.log('Finishied to read all seed dictionary files');
        console.log('Building binary dictionary ...');
        return builder.build();
    }).then((dic) => {
        const base_buffer = toBuffer(dic.trie.bc.getBaseBuffer());
        const check_buffer = toBuffer(dic.trie.bc.getCheckBuffer());
        const token_info_buffer = toBuffer(dic.token_info_dictionary.dictionary.buffer);
        const tid_pos_buffer = toBuffer(dic.token_info_dictionary.pos_buffer.buffer);
        const tid_map_buffer = toBuffer(dic.token_info_dictionary.targetMapToBuffer());
        const connection_costs_buffer = toBuffer(dic.connection_costs.buffer);
        const unk_buffer = toBuffer(dic.unknown_dictionary.dictionary.buffer);
        const unk_pos_buffer = toBuffer(dic.unknown_dictionary.pos_buffer.buffer);
        const unk_map_buffer = toBuffer(dic.unknown_dictionary.targetMapToBuffer());
        const char_map_buffer = toBuffer(dic.unknown_dictionary.character_definition.character_category_map);
        const char_compat_map_buffer = toBuffer(dic.unknown_dictionary.character_definition.compatible_category_map);
        const invoke_definition_map_buffer = toBuffer(dic.unknown_dictionary.character_definition.invoke_definition_map.toBuffer());

        fs.writeFileSync("dict/base.dat", base_buffer);
        fs.writeFileSync("dict/check.dat", check_buffer);
        fs.writeFileSync("dict/tid.dat", token_info_buffer);
        fs.writeFileSync("dict/tid_pos.dat", tid_pos_buffer);
        fs.writeFileSync("dict/tid_map.dat", tid_map_buffer);
        fs.writeFileSync("dict/cc.dat", connection_costs_buffer);
        fs.writeFileSync("dict/unk.dat", unk_buffer);
        fs.writeFileSync("dict/unk_pos.dat", unk_pos_buffer);
        fs.writeFileSync("dict/unk_map.dat", unk_map_buffer);
        fs.writeFileSync("dict/unk_char.dat", char_map_buffer);
        fs.writeFileSync("dict/unk_compat.dat", char_compat_map_buffer);
        fs.writeFileSync("dict/unk_invoke.dat", invoke_definition_map_buffer);

        done();
    });
});

gulp.task("compress-dict", () => {
    return gulp.src("dict/*.dat")
        .pipe(gzip())
        .pipe(gulp.dest("dict/"));
});

gulp.task("clean-dat-files", (done) => {
    return del([ "dict/*.dat" ], done);
});

gulp.task("build-dict", [ "build", "clean-dict" ], () => {
    sequence("create-dat-files", "compress-dict", "clean-dat-files");
});

gulp.task("test", [ "build" ], () => {
    return gulp.src("test/**/*.js", { read: false })
        .pipe(mocha({ reporter: "list" }));
});

gulp.task("coverage", [ "test" ], (done) => {
    gulp.src([ "src/**/*.js" ])
        .pipe(istanbul())
        .pipe(istanbul.hookRequire())
        .on("finish", () => {
            gulp.src([ "test/**/*.js" ])
                .pipe(mocha({ reporter: "mocha-lcov-reporter" }))
                .pipe(istanbul.writeReports())
                .on("end", done);
        });
});

gulp.task("lint", () => {
    return gulp.src([ "src/**/*.js" ])
        .pipe(jshint())
        .pipe(jshint.reporter("default"));
});

gulp.task("clean-jsdoc", (done) => {
    return del([ "publish/jsdoc/" ], done);
});

gulp.task("jsdoc", [ "clean-jsdoc" ], () => {
    return gulp.src([ "src/**/*.js" ])
        .pipe(jsdoc("publish/jsdoc"));
});

gulp.task("clean-demo", (done) => {
    return del([ "publish/demo/" ], done);
});

gulp.task("copy-demo", [ "clean-demo", "build" ], () => {
    return merge(
        gulp.src('demo/**/*')
            .pipe(gulp.dest('publish/demo/')),
        gulp.src('build/**/*')
            .pipe(gulp.dest('publish/demo/kuromoji/build/')),
        gulp.src('dict/**/*')
            .pipe(gulp.dest('publish/demo/kuromoji/dict/')));
});

gulp.task("build-demo", [ "copy-demo" ], () => {
    return bower({ cwd: 'publish/demo/' });
});

gulp.task("webserver", [ "build-demo", "jsdoc" ], () => {
    gulp.src("publish/")
        .pipe(webserver({
            port: 8000,
            livereload: true,
            directoryListing: true
        }));
});

gulp.task("deploy", [ "build-demo", "jsdoc" ], () => {
    return gulp.src('publish/**/*')
        .pipe(ghPages());
});

gulp.task("version", function () {
    let type = 'patch';
    if (argv['minor']) {
        type = 'minor';
    }
    if (argv['major']) {
        type = 'major';
    }
    if (argv['prerelease']) {
        type = 'prerelease';
    }
    return gulp.src([ './bower.json', './package.json' ])
        .pipe(bump({ type: type }))
        .pipe(gulp.dest('./'));
});

gulp.task("release-commit", function () {
    var version = JSON.parse(fs.readFileSync('./package.json', 'utf8')).version;
    return gulp.src('.')
        .pipe(git.add())
        .pipe(git.commit(`chore: release ${version}`));
});

gulp.task("release-tag", function (callback) {
    var version = JSON.parse(fs.readFileSync('./package.json', 'utf8')).version;
    git.tag(version, `${version} release`, function (error) {
        if (error) {
            return callback(error);
        }
        callback();
    });
});

gulp.task("release", [ "test" ], () => {
    sequence("release-commit", "release-tag");
});
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp');
var sass = require('gulp-sass');
var browserify = require('browserify');
var uglify = require('gulp-uglify');
var through2 = require('through2');
var path = require('path');
var rename = require('gulp-rename');

var demos = ['notepad'];

gulp.task('assets', function () {
  demos.forEach(function(demoFolder) {
    gulp.src(demoFolder+'/index.html')
          .pipe(gulp.dest('dist/'+demoFolder));
  });
  gulp.src('index.html')
        .pipe(gulp.dest('dist'));
});

gulp.task('sass', function() {
  demos.forEach(function(demoFolder) {
    gulp.src('./'+demoFolder+'/app.scss')
      .pipe(sass().on('error', sass.logError))
      .pipe(rename('app.css'))
      .pipe(gulp.dest('./dist/'+demoFolder));
  });

  gulp.src('node_modules/font-awesome/fonts/*')
    .pipe(gulp.dest('./dist/fonts'));
});

gulp.task('browserify', function() {
    demos.forEach(function(demoFolder) {
      gulp.src('./'+demoFolder+'/app.js')
        .pipe(through2.obj(function (file, enc, next) {
            browserify(file.path)
            .bundle(function (err, res) {
              if (err) { return next(err); }
              file.contents = res;
              next(null, file);
            });
        }))
        .on('error', function (error) {
            console.log(error.stack);
            this.emit('end');
        })
        .pipe(uglify().on('error', function(err){console.log(err)}))
        .pipe(gulp.dest('./dist/'+demoFolder));
    });

});

gulp.task('default', ['assets', 'sass', 'browserify']);<commit_msg>Include collabwriter/ghostwriter to examples build.<commit_after>'use strict';

var gulp = require('gulp');
var sass = require('gulp-sass');
var browserify = require('browserify');
var uglify = require('gulp-uglify');
var through2 = require('through2');
var rename = require('gulp-rename');

var demos = ['notepad', 'collabwriter', 'ghostwriter'];

gulp.task('assets', function () {
  demos.forEach(function(demoFolder) {
    gulp.src(demoFolder+'/index.html')
          .pipe(gulp.dest('dist/'+demoFolder));
  });
  gulp.src('index.html')
        .pipe(gulp.dest('dist'));
});

gulp.task('sass', function() {
  demos.forEach(function(demoFolder) {
    gulp.src('./'+demoFolder+'/app.scss')
      .pipe(sass().on('error', sass.logError))
      .pipe(rename('app.css'))
      .pipe(gulp.dest('./dist/'+demoFolder));
  });

  gulp.src('node_modules/font-awesome/fonts/*')
    .pipe(gulp.dest('./dist/fonts'));
});

gulp.task('browserify', function() {
    demos.forEach(function(demoFolder) {
      gulp.src('./'+demoFolder+'/app.js')
        .pipe(through2.obj(function (file, enc, next) {
            browserify(file.path)
            .bundle(function (err, res) {
              if (err) { return next(err); }
              file.contents = res;
              next(null, file);
            });
        }))
        .on('error', function (error) {
            console.log(error.stack);
            this.emit('end');
        })
        .pipe(uglify().on('error', function(err){console.log(err); }))
        .pipe(gulp.dest('./dist/'+demoFolder));
    });

});

gulp.task('default', ['assets', 'sass', 'browserify']);<|endoftext|>


<commit_before>'use strict'

const gulp = require('gulp')
const watch = require('gulp-watch')
const pug = require('gulp-pug')
const scss = require('gulp-sass')
const prefix = require('gulp-autoprefixer')

const dev = 'src'
const server = 'dist'

const build_html = function() {
    return gulp.src(dev + '/pug/*.pug')
        .pipe(pug({pretty: true}))
        .pipe(gulp.dest(server));
}

const build_css = function() {
    return gulp.src(dev+'/scss/*.scss')
        .pipe(scss())
        .pipe(prefix())
        .pipe(gulp.dest(server+'/css'));
}

gulp.task('watch', function() {
    watch(dev+'/pug/*.pug', build_html);
    watch(dev+'/scss/**/*.scss', build_css);
});

gulp.task('build_html', build_html);
gulp.task('build_css', build_css);<commit_msg>Disable pug compiling from watch. The pug compiler is crashing on node 10<commit_after>'use strict'

const gulp = require('gulp')
const watch = require('gulp-watch')
const pug = require('gulp-pug')
const scss = require('gulp-sass')
const prefix = require('gulp-autoprefixer')

const dev = 'src'
const server = 'dist'

const build_html = function() {
    return gulp.src(dev + '/pug/*.pug')
        .pipe(pug({pretty: true}))
        .pipe(gulp.dest(server));
}

const build_css = function() {
    return gulp.src(dev+'/scss/*.scss')
        .pipe(scss())
        .pipe(prefix())
        .pipe(gulp.dest(server+'/css'));
}

gulp.task('watch', function() {
    // watch(dev+'/pug/*.pug', build_html);
    watch(dev+'/scss/**/*.scss', build_css);
});

gulp.task('build_html', build_html);
gulp.task('build_css', build_css);<|endoftext|>


<commit_before>'use strict';

let gulp = require('gulp');
let $ = require('gulp-load-plugins')();
let mainBowerFiles = require('main-bower-files');
let path = require('path');
let fs = require('fs');
let del = require('del');
let spawn = require('child_process').spawn;
let electron = require('electron-prebuilt');
let Promise2 = require('bluebird');

let config = JSON.parse(fs.readFileSync(path.join(__dirname, '.neutronrc')));
let du = require('./lib/dep-utils');
let deps = config.dependencies;

// Helper function to DRY things up!
let toTarget = subDir => {
  let target = subDir ? path.join(config.targetDir, subDir) : config.targetDir;
  return gulp.dest(target);
};

// Import corresponding tasks
Object.keys(deps).forEach(pluginName => {
  let Plugin = require('./lib/plugins/' + pluginName);
  let instance = new Plugin();

  gulp.task(pluginName, () => (
    gulp.src(du.srcGlob(pluginName))
      .pipe(instance.getTask(config))
      .pipe(gulp.dest(config.targetDir))
  ));
});

gulp.task('eslint', () => (
  gulp.src([`${config.baseDir}/**/*.js`, 'gulpfile.js', 'lib/**/*.js'])
    .pipe($.eslint())
    .pipe($.eslint.format())
    .pipe($.eslint.failAfterError())
));

gulp.task('bootstrap', (cb) => {
  let pluginNames = Object.keys(deps);
  $.util.log('Trying to install plugins:', $.util.colors.cyan(pluginNames.join(', ')));

  // Boostrap plugins
  let instances = pluginNames.map(pluginName => {
    let Plugin = require(`./lib/plugins/${pluginName}`);
    return new Plugin();
  });

  Promise2.map(instances, instance => instance.install())
  .then(Promise2.map(instances, instance => instance.configure()))
  .then(() => cb());
});

gulp.task('statics', () => {
  let statics = [];
  Object.keys(config.statics).forEach(key => {
    let globs = config.statics[key].map(ext => `${config.baseDir}/**/*.${ext}`);
    statics = statics.concat(globs);
  });

  return gulp.src(statics)
    .pipe(toTarget());
});

gulp.task('electron-manifest', () => {
  let pkg = require('./package.json');

  $.file('package.json', JSON.stringify({
    name: pkg.name,
    version: pkg.version,
    main: 'main.js'
  }, null, 2), {src: true}).pipe(toTarget());
});

gulp.task('bower-js-assets', () => {
  if (fs.existsSync('bower.json')) {
    return gulp.src(mainBowerFiles('**/*.js'))
      .pipe(toTarget('js'));
  }
});

gulp.task('bower-css-assets', () => {
  if (fs.existsSync('bower.json')) {
    return gulp.src(mainBowerFiles('**/*.css'))
      .pipe(toTarget('css'));
  }
});

// Create bower static assets
let bowerStaticTasks = [];
if (fs.existsSync('bower.json')) {
  Object.keys(config.statics).forEach(key => {
    let taskName = 'bower-static:' + key;

    gulp.task(taskName, () => {
      let globs = config.statics[key].map(ext => '/**/*.' + ext);
      return gulp.src(mainBowerFiles(globs))
        .pipe(toTarget(key));
    });

    bowerStaticTasks.push(taskName);
  });
}
gulp.task('bower-static-assets', bowerStaticTasks);

gulp.task('clean', (cb) => {
  let defaults = [`${config.targetDir}/**/*`, 'package/', `!${config.targetDir}/package.json`];
  let userDefined = config.cleanIgnore.map((path) => `!${config.targetDir}/${path}`);

  del(defaults.concat(userDefined));
});

gulp.task('watch', ['build'], () => {
  Object.keys(deps).forEach((task) => {
    gulp.watch(du.srcGlob(task), [task]);
  });
});

gulp.task('start', ['watch'], () => {
  let env = process.env;
  env.ELECTRON_ENV = 'development';
  env.NODE_PATH = path.join(__dirname, config.targetDir, 'node_modules');

  let e = spawn(electron, [config.targetDir], {
    env: env
  });

  e.stdout.on('data', (data) => {
    $.util.log(data.toString().trim());
  });

  e.stderr.on('data', (data) => {
    $.util.log($.util.colors.red(data.toString().trim()));
  });
});

gulp.task('package', ['build'], (cb) => {
  var packager = require('electron-packager');
  packager(config.packager, (err, appPath) => {
    if (err) {
      $.util.log('Error while creating the package!', err);
    } else {
      cb();
    }
  });
});

gulp.task('bower-assets', ['bower-css-assets', 'bower-js-assets', 'bower-static-assets']);

gulp.task('lint', ['eslint']);

gulp.task('build', Object.keys(deps).concat('bower-assets', 'statics'));
<commit_msg>Fix gulpfile lint errors<commit_after>'use strict';

let gulp = require('gulp');
let $ = require('gulp-load-plugins')();
let mainBowerFiles = require('main-bower-files');
let path = require('path');
let fs = require('fs');
let del = require('del');
let spawn = require('child_process').spawn;
let electron = require('electron-prebuilt');
let Promise2 = require('bluebird');

let config = JSON.parse(fs.readFileSync(path.join(__dirname, '.neutronrc')));
let du = require('./lib/dep-utils');
let deps = config.dependencies;

// Helper function to DRY things up!
let toTarget = subDir => {
  let target = subDir ? path.join(config.targetDir, subDir) : config.targetDir;
  return gulp.dest(target);
};

// Import corresponding tasks
Object.keys(deps).forEach(pluginName => {
  let Plugin = require('./lib/plugins/' + pluginName);
  let instance = new Plugin();

  gulp.task(pluginName, () => (
    gulp.src(du.srcGlob(pluginName))
      .pipe(instance.getTask(config))
      .pipe(gulp.dest(config.targetDir))
  ));
});

gulp.task('eslint', () => (
  gulp.src([`${config.baseDir}/**/*.js`, 'gulpfile.js', 'lib/**/*.js'])
    .pipe($.eslint())
    .pipe($.eslint.format())
    .pipe($.eslint.failAfterError())
));

gulp.task('bootstrap', cb => {
  let pluginNames = Object.keys(deps);
  $.util.log('Trying to install plugins:',
    $.util.colors.cyan(pluginNames.join(', ')));

  // Boostrap plugins
  let instances = pluginNames.map(pluginName => {
    let Plugin = require(`./lib/plugins/${pluginName}`);
    return new Plugin();
  });

  Promise2.map(instances, instance => instance.install())
  .then(Promise2.map(instances, instance => instance.configure()))
  .then(() => cb());
});

gulp.task('statics', () => {
  let statics = [];
  Object.keys(config.statics).forEach(key => {
    let globs = config.statics[key].map(ext => `${config.baseDir}/**/*.${ext}`);
    statics = statics.concat(globs);
  });

  return gulp.src(statics)
    .pipe(toTarget());
});

gulp.task('electron-manifest', () => {
  let pkg = require('./package.json');

  $.file('package.json', JSON.stringify({
    name: pkg.name,
    version: pkg.version,
    main: 'main.js'
  }, null, 2), {src: true}).pipe(toTarget());
});

gulp.task('bower-js-assets', () => {
  if (fs.existsSync('bower.json')) {
    return gulp.src(mainBowerFiles('**/*.js'))
      .pipe(toTarget('js'));
  }
});

gulp.task('bower-css-assets', () => {
  if (fs.existsSync('bower.json')) {
    return gulp.src(mainBowerFiles('**/*.css'))
      .pipe(toTarget('css'));
  }
});

// Create bower static assets
let bowerStaticTasks = [];
if (fs.existsSync('bower.json')) {
  Object.keys(config.statics).forEach(key => {
    let taskName = 'bower-static:' + key;

    gulp.task(taskName, () => {
      let globs = config.statics[key].map(ext => '/**/*.' + ext);
      return gulp.src(mainBowerFiles(globs))
        .pipe(toTarget(key));
    });

    bowerStaticTasks.push(taskName);
  });
}
gulp.task('bower-static-assets', bowerStaticTasks);

gulp.task('clean', () => {
  let defaults = [
    `${config.targetDir}/**/*`,
    'package/', `!${config.targetDir}/package.json`];
  let userDefined = config.cleanIgnore.map(
    path => `!${config.targetDir}/${path}`);

  del(defaults.concat(userDefined));
});

gulp.task('watch', ['build'], () => {
  Object.keys(deps).forEach(task => {
    gulp.watch(du.srcGlob(task), [task]);
  });
});

gulp.task('start', ['watch'], () => {
  let env = process.env;
  env.ELECTRON_ENV = 'development';
  env.NODE_PATH = path.join(__dirname, config.targetDir, 'node_modules');

  let e = spawn(electron, [config.targetDir], {
    env: env
  });

  e.stdout.on('data', data => {
    $.util.log(data.toString().trim());
  });

  e.stderr.on('data', data => {
    $.util.log($.util.colors.red(data.toString().trim()));
  });
});

gulp.task('package', ['build'], cb => {
  var packager = require('electron-packager');
  packager(config.packager, err => {
    if (err) {
      $.util.log('Error while creating the package!', err);
    } else {
      cb();
    }
  });
});

gulp.task('bower-assets',
  ['bower-css-assets', 'bower-js-assets', 'bower-static-assets']);

gulp.task('lint', ['eslint']);

gulp.task('build', Object.keys(deps).concat('bower-assets', 'statics'));
<|endoftext|>


<commit_before>/* ==========================================================================
   MINIMAL MISTAKES JEKYLL THEME - Gulpfile
   ========================================================================== */

/**
*
* Packages used
*
**/
var gulp         = require("gulp");
var sass         = require("gulp-sass");
var prefix       = require("gulp-autoprefixer");
var plumber      = require("gulp-plumber");
var uglify       = require("gulp-uglifyjs");
var jshint       = require("gulp-jshint");
var rename       = require("gulp-rename");
var imagemin     = require("gulp-imagemin");
var pngquant     = require("imagemin-pngquant");

/**
*
* Styles
* - Compile
* - Compress/Minify
* - Catch errors (gulp-plumber)
* - Run through Autoprefixer
*
**/
gulp.task("css", function() {
  return gulp.src("assets/scss/**/*.scss")
    .pipe(sass({outputStyle: "compressed"}))
    .pipe(prefix("last 2 versions", "> 5%", "ie 9"))
    .pipe(plumber())
    .pipe(gulp.dest("assets/css"));
});

/**
*
* Javascript
* - Concatenate main script with plugins
* - Uglify
* - Rename
*
**/
gulp.task("scripts", function() {
  return gulp.src(["assets/js/vendor/jquery/*.js", "assets/js/plugins/**/*.js", "assets/js/_main*.js"])
    .pipe(uglify())
    .pipe(rename({
      basename: "main",
      suffix: ".min",
    }))
    .pipe(gulp.dest("assets/js"))
});

/**
*
* Javascript
* - Lint for errors
*
**/
gulp.task("jslint", function() {
  return gulp.src("assets/js/_*.js")
    .pipe(jshint())
    .pipe(jshint.reporter("default"))
    .pipe(jshint.reporter("fail"))
});

/**
*
* Images
* - Optimize image assets
*
**/
gulp.task("images", function () {
  return gulp.src("images/*")
    .pipe(imagemin({
      progressive: true,
      svgoPlugins: [{removeViewBox: false}],
      use: [pngquant()]
    }))
    .pipe(gulp.dest("images"));
});

/**
*
* Default task
* - Runs scss, scripts and image tasks
* - Watches for scss, script, and image changes
*
**/
gulp.task("default", ["css", "jslint", "scripts", "images"], function () {
  gulp.watch("assets/scss/**/*.scss", ["css"]);
  gulp.watch("assets/js/_*.js", ["jslint"]);
  gulp.watch(["!assets/js/**/*_.js", "assets/js/plugins/**/*.js", "assets/js/vendor/**/*.js"], ["scripts"]);
  gulp.watch("images/*", ["images"]);
});<commit_msg>Replace " with '<commit_after>/* ==========================================================================
   MINIMAL MISTAKES JEKYLL THEME - Gulpfile
   ========================================================================== */

/**
*
* Packages used
*
**/
var gulp         = require('gulp');
var sass         = require('gulp-sass');
var prefix       = require('gulp-autoprefixer');
var plumber      = require('gulp-plumber');
var uglify       = require('gulp-uglifyjs');
var jshint       = require('gulp-jshint');
var rename       = require('gulp-rename');
var imagemin     = require('gulp-imagemin');
var pngquant     = require('imagemin-pngquant');

/**
*
* Styles
* - Compile
* - Compress/Minify
* - Catch errors (gulp-plumber)
* - Run through Autoprefixer
*
**/
gulp.task('css', function() {
  return gulp.src('assets/scss/**/*.scss')
    .pipe(sass({outputStyle: 'compressed'}))
    .pipe(prefix('last 2 versions', '> 5%', 'ie 9'))
    .pipe(plumber())
    .pipe(gulp.dest('assets/css'));
});

/**
*
* Javascript
* - Concatenate main script with plugins
* - Uglify
* - Rename
*
**/
gulp.task('scripts', function() {
  return gulp.src(['assets/js/vendor/jquery/*.js', 'assets/js/plugins/**/*.js', 'assets/js/_main*.js'])
    .pipe(uglify())
    .pipe(rename({
      basename: 'main',
      suffix: '.min',
    }))
    .pipe(gulp.dest('assets/js'))
});

/**
*
* Javascript
* - Lint for errors
*
**/
gulp.task('jslint', function() {
  return gulp.src('assets/js/_*.js')
    .pipe(jshint())
    .pipe(jshint.reporter('default'))
    .pipe(jshint.reporter('fail'))
});

/**
*
* Images
* - Optimize image assets
*
**/
gulp.task('images', function () {
  return gulp.src('images/*')
    .pipe(imagemin({
      progressive: true,
      svgoPlugins: [{removeViewBox: false}],
      use: [pngquant()]
    }))
    .pipe(gulp.dest('images'));
});

/**
*
* Default task
* - Runs scss, scripts and image tasks
* - Watches for scss, script, and image changes
*
**/
gulp.task('default', ['css', 'jslint', 'scripts', 'images'], function () {
  gulp.watch('assets/scss/**/*.scss', ['css']);
  gulp.watch('assets/js/_*.js', ['jslint']);
  gulp.watch(['!assets/js/**/*_.js', 'assets/js/plugins/**/*.js', 'assets/js/vendor/**/*.js'], ['scripts']);
  gulp.watch('images/*', ['images']);
});<|endoftext|>


<commit_before>  // --------------------
// #GULP
// --------------------

//configure paths
var config = {
  build        :   './app/',
  source       :   './ui_src',
  pugDir      :   './ui_src/pug',
  sassDir      :   './ui_src/scss',
  jsDir        :   './ui_src/javascript',
  iconsDir     :   './ui_src/icons',
  imageDir     :   './ui_src/images',
  fontDir     :   './ui_src/fonts',
  bowerDir     :   './bower_components',
  bootstrapDir :   './bower_components/bootstrap-sass/assets'
}

//include plug-ins
var gulp            = require('gulp'),
    gutil           = require('gulp-util'),
    sourcemaps      = require('gulp-sourcemaps'),
    sass            = require('gulp-sass'),
    notify          = require("gulp-notify"),
    //browserSync     = require('browser-sync').create(),
    bower           = require('gulp-bower');
    bowerFiles      = require('main-bower-files'),
    pug             = require('gulp-pug');
    changed         = require('gulp-changed');
    cached          = require('gulp-cached');
    gulpif          = require('gulp-if');
    filter          = require('gulp-filter'),
    runTimestamp    = Math.round(Date.now()/1000);

gulp.task('fonts', function () {
    return gulp.src('./fonts.list')
        .pipe(googleWebFonts())
        .pipe(gulp.dest(config.build + '/assets/fonts'));
});

//Start Static server
// gulp.task('browser-sync', function() {
//   browserSync.init({
//       server: {
//           baseDir: config.build,
//           directory: true
//       },
//       port: 3000,
//       files: ["*/**/*.css", "*/**/*.html", "*/**/*.js"]

//   });
// });

//SASS TO CSS
gulp.task('build-css', function() {
  return gulp.src(config.sassDir + '/**/*.scss')
    .pipe(sourcemaps.init())  // Process the original sources
    .pipe(sass({
        includePaths: [config.bootstrapDir+"/stylesheets", config.bowerDir+"animate.css"]
      })
      .on("error", notify.onError(function (error) {

                return "Error: " + error.message;

            })))
    .pipe(sourcemaps.write()) // Add the map to modified source.
    .pipe(gulp.dest(config.build + '/assets/stylesheets'))
    // .pipe(browserSync.stream());
});

//pug TO HTML – build .pug to .html
// gulp.task('build-html', function() {
//   gulp.src(config.pugDir + '/**/!(_)*.pug')
//     .pipe(pug({
//         pretty: true,
//         locals: {imagePath: 'assets/i'}
//       })
//       .on("error", notify.onError(function (error) {
//             return "Error: " + error.message;
//           })))
//     .pipe(gulp.dest(config.build));

//     gulp.src(config.source + '/**/*.html')
//       .pipe(gulp.dest(config.build + '/**/*.html'));
// });

//JS
gulp.task('build-once', function() {
  gulp.src(bowerFiles())
    .pipe(filter('*.js'))
    .pipe(gulp.dest(config.build + '/assets/javascript/vendor'));

  gulp.src(config.bootstrapDir + '/fonts/**/*')
    .pipe(gulp.dest(config.build + '/assets/fonts'));

  gulp.src(config.imageDir + '/**/*')
    .pipe(gulp.dest(config.build + '/assets/images'));

  gulp.src(config.fontDir + '/**/*')
    .pipe(gulp.dest(config.build + '/assets/fonts/fa'));
});

//JS
gulp.task('build-js', function() {
  gulp.src(config.source + '/**/*.js')
    .pipe(gulp.dest(config.build + '/assets'));
});

//Watch changes to the file
gulp.task('watch', function() {
  gulp.watch(config.jsDir + '/**/*.js', ['build-js']);
  gulp.watch(config.sassDir + '/**/*.scss', ['build-css']);
  //gulp.watch(config.pugDir + '/**/*.pug', ['build-html']);
  //gulp.watch(config.source + '/**/*.html').on('change', browserSync.reload);
});

// create a default task and just log a message
gulp.task('default', ['build-once','build-css', 'build-js'], function() {
  return gutil.log('Gulp is running in Development mode!');
});<commit_msg>removed gulp dependency<commit_after><|endoftext|>


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

// to be ran from a valid repo directory, else change the first task like so:
// 'forever start src/server.js /path/to/project/'
gulp.task('renderChangelog', shell.task([
    'cd ..',
    'forever start auto-changelog/src/server.js',
    'phantomjs auto-changelog/src/render.js',
    'forever stop auto-changelog/src/server.js'
]));

gulp.task('default', ['renderChangelog']);
<commit_msg>Delete gulpfile.js<commit_after><|endoftext|>


<commit_before>var gulp = require('gulp');
var mocha = require('gulp-mocha');
var istanbul = require('gulp-istanbul');
var coveralls = require('gulp-coveralls');
var gulpif = require('gulp-if');

gulp.task('test', function () {
    return gulp.src('index.js')
        .pipe(istanbul())
        .pipe(istanbul.hookRequire())
        .on('finish', function () {
            gulp.src('test/*.js')
                .pipe(mocha())
                .pipe(istanbul.writeReports({reporters: ['text-summary', 'lcovonly', 'html']}))
                .on('end', function () {
                    gulp.src('coverage/lcov.info')
                        .pipe(gulpif(process.env['TRAVIS'], coveralls()))
                })
        });
});

gulp.task('default', function () {
    gulp.start('test')
});
<commit_msg>CI: Fix: Cannot upload to coveralls.io<commit_after>var gulp = require('gulp');
var mocha = require('gulp-mocha');
var istanbul = require('gulp-istanbul');
var coveralls = require('gulp-coveralls');
var gulpif = require('gulp-if');

var is_travis = process.env['TRAVIS'] !== undefined

gulp.task('test', function (done) {
    return gulp.src('index.js')
        .pipe(istanbul())
        .pipe(istanbul.hookRequire())
        .on('finish', function () {
            gulp.src('test/*.js')
                .pipe(mocha())
                .pipe(istanbul.writeReports({reporters: ['text-summary', 'lcovonly', 'html']}))
                .on('end', function () {
                    gulp.src('coverage/lcov.info')
                        .pipe(gulpif(is_travis, coveralls()))
                        .on('end', done)
                })
        });
});

gulp.task('default', function () {
    gulp.start('test')
});
<|endoftext|>


<commit_before>'use strict';

var fs = require('fs');
var path = require('path');
var gulp = require('gulp');
var sass = require('gulp-sass');
var cached = require('gulp-cached');
var remember = require('gulp-remember');
var jas = require('gulp-jasmine');
var jshint = require('gulp-jshint');
var traceur = require('gulp-traceur');

// var refresh = require('gulp-livereload');
// var livereload = require('tiny-lr');
// var server = livereload();

function pathItem(name) {
	return function(children) {
		var items = [ name ];
		if (this instanceof Function) { items.unshift(this()); }
		if (children) { items.push(children); }

		return path.join.apply(path, items);
	}
}

var PATHS = pathItem('.');
PATHS.bin = pathItem('bin');
PATHS.client = pathItem('client');
PATHS.client.scss_lib = pathItem('scss_lib');
PATHS.server = pathItem('server');
PATHS.build = pathItem('build');
PATHS.build.server = pathItem('server');
PATHS.specs = pathItem('specs');
PATHS.docs = pathItem('docs');
PATHS.docs.libs = pathItem('libs');
PATHS.specs = pathItem('specs');
PATHS.specs.matchers = pathItem('matchers');

/* --  Build tasks -- */

gulp.task('build:js', function() {
  return gulp.src([PATHS.server('**/*.js')], { base: PATHS.server() })
    .pipe(cached('js'))
    .pipe(remember('js'))
    .pipe(traceur({ modules:'commonjs' }))
    .pipe(gulp.dest(PATHS.build.server()));
});

gulp.task('watch:js', function() {
  gulp.watch(PATHS.server('**/*.js'), [ 'build:js', 'test:unit' ]);
});

gulp.task('build:sass', function () {
	// var dest = PATHS.client.public.styles();
	var dest = 'client/';

  return gulp.src([PATHS.client('**/*.scss'), PATHS.client.scss_lib('**/*.scss')])
  		.pipe(cached('scss'))
  		.pipe(remember('scss'))
  		.pipe(sass({
  			includePaths: [ PATHS.client.scss_lib() ]
  		}))
      .pipe(gulp.dest(dest));
});

gulp.task('build', ['build:js', 'build:sass']);

/* -- Test task -- */

gulp.task('test:unit', function() {
  return gulp.src([
      PATHS.specs.matchers('**/*.js'),
      PATHS.build.server('**/*.spec.js'),
      PATHS.client('**/*.spec.js')
    ]).pipe(jas({includeStackTrace: true}));
});

gulp.task('watch:unit', function() {
  // Server source already triggered the tests
  gulp.watch([ PATHS.client('**/*.spec.js')], [ 'test:unit' ]);
});

gulp.task('test:lint', function() {
  return gulp.src([
  		PATHS.bin('*.js'),
  		PATHS.client('**/*.js'),
  		PATHS.server('**/*.js')
  	]).pipe(jshint())
    .pipe(jshint.reporter('default'));
});

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

/* -- Live reload && watchs-- */

// gulp.task('css', function () {
//   gulp.src('app/**/*.css').pipe(refresh(server));
// });

// gulp.task('js', function () {
//   gulp.src('app/**/*.js').pipe(refresh(server));
// });

// gulp.task('livereload-server', function () {
//   server.listen(35729, function (err) {
//     if (err) { return console.log(err); }
//   });
// });

// gulp.task('serve', function () {
//   gulp.run('livereload-server');

//   gulp.watch('app/**/*.css', function (event) {
//     gulp.run('css');
//   });

//   gulp.watch('app/**/*.js', function (event) {
//     gulp.run('js');
//   });
// });

gulp.task('watch', ['watch:js', 'watch:unit']);

/* -- Documentation -- */

gulp.task('docs:install', function() {
	var request = require('request');

	// Fetch the master version of mermaid for documentation
	return request('https://raw.githubusercontent.com/knsv/mermaid/master/dist/mermaid.full.min.js')
		.pipe(fs.createWriteStream(PATHS.docs.libs('mermaid.js')));
});

gulp.task('docs:serve', function() {
	// Somehow provide a way to navigate through documentation
});

gulp.task('docs', ['docs:install', 'docs:serve']);

//default gulp
gulp.task('default', [ 'build', 'test', 'docs' ]);

/**
 * Master task to rebuild all the project
 * Named in hommage to 'Legend of Korra'
 * This will perform all actions to build and test the application.
 */
gulp.task('do_the_thing', function() {
  // Clear all caches to perform a full actions
  cached.caches = {};

  var runSequence = require('run-sequence');
  runSequence('build', 'test', 'docs:install', function() {
    console.log('All things are done Sir :)');
  });
});<commit_msg>Correctly order phases in watch.<commit_after>'use strict';

var fs = require('fs');
var path = require('path');
var gulp = require('gulp');
var sass = require('gulp-sass');
var cached = require('gulp-cached');
var remember = require('gulp-remember');
var jas = require('gulp-jasmine');
var jshint = require('gulp-jshint');
var traceur = require('gulp-traceur');

// var refresh = require('gulp-livereload');
// var livereload = require('tiny-lr');
// var server = livereload();

function pathItem(name) {
	return function(children) {
		var items = [ name ];
		if (this instanceof Function) { items.unshift(this()); }
		if (children) { items.push(children); }

		return path.join.apply(path, items);
	}
}

var PATHS = pathItem('.');
PATHS.bin = pathItem('bin');
PATHS.client = pathItem('client');
PATHS.client.scss_lib = pathItem('scss_lib');
PATHS.server = pathItem('server');
PATHS.build = pathItem('build');
PATHS.build.server = pathItem('server');
PATHS.specs = pathItem('specs');
PATHS.docs = pathItem('docs');
PATHS.docs.libs = pathItem('libs');
PATHS.specs = pathItem('specs');
PATHS.specs.matchers = pathItem('matchers');

/* --  Build tasks -- */

gulp.task('build:js', function() {
  return gulp.src([PATHS.server('**/*.js')], { base: PATHS.server() })
    .pipe(cached('js'))
    .pipe(remember('js'))
    .pipe(traceur({ modules:'commonjs' }))
    .pipe(gulp.dest(PATHS.build.server()));
});

// Special task to order properly tasks
gulp.task('watch:js:test', ['build:js'], function() {
  gulp.run('test:unit');
});

gulp.task('watch:js', function() {
  gulp.watch(PATHS.server('**/*.js'), ['watch:js:test']);
});

gulp.task('build:sass', function () {
	// var dest = PATHS.client.public.styles();
	var dest = 'client/';

  return gulp.src([PATHS.client('**/*.scss'), PATHS.client.scss_lib('**/*.scss')])
  		.pipe(cached('scss'))
  		.pipe(remember('scss'))
  		.pipe(sass({
  			includePaths: [ PATHS.client.scss_lib() ]
  		}))
      .pipe(gulp.dest(dest));
});

gulp.task('build', ['build:js', 'build:sass']);

/* -- Test task -- */

gulp.task('test:unit', function() {
  return gulp.src([
      PATHS.specs.matchers('**/*.js'),
      PATHS.build.server('**/*.spec.js'),
      PATHS.client('**/*.spec.js')
    ]).pipe(jas({includeStackTrace: true}));
});

gulp.task('watch:unit', function() {
  // Server source already triggered the tests
  gulp.watch([ PATHS.client('**/*.spec.js')], [ 'test:unit' ]);
});

gulp.task('test:lint', function() {
  return gulp.src([
  		PATHS.bin('*.js'),
  		PATHS.client('**/*.js'),
  		PATHS.server('**/*.js')
  	]).pipe(jshint())
    .pipe(jshint.reporter('default'));
});

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

/* -- Live reload && watchs-- */

// gulp.task('css', function () {
//   gulp.src('app/**/*.css').pipe(refresh(server));
// });

// gulp.task('js', function () {
//   gulp.src('app/**/*.js').pipe(refresh(server));
// });

// gulp.task('livereload-server', function () {
//   server.listen(35729, function (err) {
//     if (err) { return console.log(err); }
//   });
// });

// gulp.task('serve', function () {
//   gulp.run('livereload-server');

//   gulp.watch('app/**/*.css', function (event) {
//     gulp.run('css');
//   });

//   gulp.watch('app/**/*.js', function (event) {
//     gulp.run('js');
//   });
// });

gulp.task('watch', ['watch:js', 'watch:unit']);

/* -- Documentation -- */

gulp.task('docs:install', function() {
	var request = require('request');

	// Fetch the master version of mermaid for documentation
	return request('https://raw.githubusercontent.com/knsv/mermaid/master/dist/mermaid.full.min.js')
		.pipe(fs.createWriteStream(PATHS.docs.libs('mermaid.js')));
});

gulp.task('docs:serve', function() {
	// Somehow provide a way to navigate through documentation
});

gulp.task('docs', ['docs:install', 'docs:serve']);

//default gulp
gulp.task('default', [ 'build', 'test', 'docs' ]);

/**
 * Master task to rebuild all the project
 * Named in hommage to 'Legend of Korra'
 * This will perform all actions to build and test the application.
 */
gulp.task('do_the_thing', function() {
  // Clear all caches to perform a full actions
  cached.caches = {};

  var runSequence = require('run-sequence');
  runSequence('build', 'test', 'docs:install', function() {
    console.log('All things are done Sir :)');
  });
});<|endoftext|>