<commit_before>var gulp          = require('gulp');
var plugins       = require('gulp-load-plugins')();
var templatecache = require('gulp-angular-templatecache');
var karma         = require('karma').server;
var _             = require('lodash');
var browserSync   = require('browser-sync');
var at            = require('gulp-asset-transform');
var protractor    = require('gulp-protractor').protractor;
var del           = require('del');

var paths = {
  css         : ['src/assets/css/*.css', 'src/app/**/*.css'],
  fonts       : 'src/assets/fonts/*.*',
  images      : 'src/assets/images/**',
  index       : 'src/index.html',
  integration : 'test/integration/*.js',
  js          : 'src/app/**/*.js',
  less        : ['src/assets/less/*.less', 'src/app/components/**/*.less'],
  templates   : 'src/app/components/**/*.html'
};

var config = {
  jshint : 'config/jshint.conf',
  karma  : require('./config/karma.conf')
};

gulp.task('copy-images', function() {
  return gulp.src(paths.images)
    .pipe(plugins.plumber())
    .pipe(plugins.imagemin({ optimizationLevel: 3, progressive: true, interlaced: true }))
    .pipe(plugins.size({ title: 'images', showFiles: true }))
    .pipe(gulp.dest('develop/images'));
});

gulp.task('copy-fonts', function() {
  return gulp.src(paths.fonts)
    .pipe(plugins.plumber())
    .pipe(plugins.size({ title: 'fonts' }))
    .pipe(gulp.dest('develop/fonts'));
});

gulp.task('at-build', function() {
  return gulp.src(paths.index)
    .pipe(plugins.plumber())
    .pipe(at({
      css: {
        tasks: ['concat',
                plugins.size({ title: 'css', showFiles: true })]
      },
      js: {
        tasks: ['concat',
                plugins.size({ title: 'js', showFiles: true })]
      },
      js_lib: {
        tasks: ['concat',
                plugins.size({ title: 'js_lib', showFiles: true })]
      },
      less: {
        tasks: [plugins.less(),
                'concat',
                plugins.size({ title: 'less', showFiles: true})]
      }
    }))
    .pipe(gulp.dest('develop/'))
    .pipe(browserSync.reload({ stream: true }));
});

gulp.task('templates', function () {
  return gulp.src(paths.templates)
    .pipe(plugins.plumber())
    .pipe(templatecache('templates.js', { standalone: true }))
    .pipe(plugins.size({ title: 'templates' }))
    .pipe(gulp.dest('develop/js'))
    .pipe(browserSync.reload({ stream: true }));
});

gulp.task('jshint', function() {
  gulp.src(paths.js)
    .pipe(plugins.jshint(config.jshint))
    .pipe(plugins.jshint.reporter('jshint-stylish'));
});

gulp.task('less-lint', function() {
  gulp.src(paths.less)
    .pipe(plugins.plumber())
    .pipe(plugins.recess())
    .pipe(plugins.recess.reporter());
});

gulp.task('clean', function(done) {
  del(['develop/**'], done);
});

gulp.task('karma', function(done) {
  karma.start(_.assign({}, config.karma, { singleRun: true, colors: true }), done);
});

gulp.task('karma-ci', function(done) {
  karma.start(_.assign({}, config.karma, { singleRun: false, colors: true, autoWatch: true }), done);
});

gulp.task('integration', ['server'], function(done) {
  gulp.src(paths.integration)
    .pipe(protractor({
      configFile: 'config/protractor.conf',
      args: ['--baseUrl', 'http://localhost:3000/#/']
    }))
    .on('error', function(e) { browserSync.exit(); throw e; })
    .on('end', function() { browserSync.exit(); done(); });
});

gulp.task('server', function() {
  browserSync({
    server: {
      baseDir: 'develop'
    },
    logConnections: true,
    open: false
  });
});

gulp.task('watch', function() {
  gulp.watch([paths.index, paths.css, paths.less, paths.js], ['at-build']);
  gulp.watch([paths.images, paths.fonts], ['copy-assets']);
  gulp.watch([paths.templates], ['templates']);
  gulp.watch([paths.js], ['jshint']);
  gulp.watch([paths.less], ['less-lint']);
});

gulp.task('copy-assets', ['copy-images', 'copy-fonts']);
gulp.task('build', ['at-build', 'templates', 'copy-assets']);
gulp.task('develop', ['build', 'server', 'watch', 'karma-ci']);
<commit_msg>Refactor plugin variable name into something shorter<commit_after>var gulp          = require('gulp');
var $             = require('gulp-load-plugins')();
var templatecache = require('gulp-angular-templatecache');
var karma         = require('karma').server;
var _             = require('lodash');
var browserSync   = require('browser-sync');
var at            = require('gulp-asset-transform');
var protractor    = require('gulp-protractor').protractor;
var del           = require('del');

var paths = {
  css         : ['src/assets/css/*.css', 'src/app/**/*.css'],
  fonts       : 'src/assets/fonts/*.*',
  images      : 'src/assets/images/**',
  index       : 'src/index.html',
  integration : 'test/integration/*.js',
  js          : 'src/app/**/*.js',
  less        : ['src/assets/less/*.less', 'src/app/components/**/*.less'],
  templates   : 'src/app/components/**/*.html'
};

var config = {
  jshint : 'config/jshint.conf',
  karma  : require('./config/karma.conf')
};

gulp.task('copy-images', function() {
  return gulp.src(paths.images)
    .pipe($.plumber())
    .pipe($.imagemin({ optimizationLevel: 3, progressive: true, interlaced: true }))
    .pipe($.size({ title: 'images', showFiles: true }))
    .pipe(gulp.dest('develop/images'));
});

gulp.task('copy-fonts', function() {
  return gulp.src(paths.fonts)
    .pipe($.plumber())
    .pipe($.size({ title: 'fonts' }))
    .pipe(gulp.dest('develop/fonts'));
});

gulp.task('at-build', function() {
  return gulp.src(paths.index)
    .pipe($.plumber())
    .pipe(at({
      css: {
        tasks: ['concat',
                $.size({ title: 'css', showFiles: true })]
      },
      js: {
        tasks: ['concat',
                $.size({ title: 'js', showFiles: true })]
      },
      js_lib: {
        tasks: ['concat',
                $.size({ title: 'js_lib', showFiles: true })]
      },
      less: {
        tasks: [$.less(),
                'concat',
                $.size({ title: 'less', showFiles: true})]
      }
    }))
    .pipe(gulp.dest('develop/'))
    .pipe(browserSync.reload({ stream: true }));
});

gulp.task('templates', function () {
  return gulp.src(paths.templates)
    .pipe($.plumber())
    .pipe(templatecache('templates.js', { standalone: true }))
    .pipe($.size({ title: 'templates' }))
    .pipe(gulp.dest('develop/js'))
    .pipe(browserSync.reload({ stream: true }));
});

gulp.task('jshint', function() {
  gulp.src(paths.js)
    .pipe($.jshint(config.jshint))
    .pipe($.jshint.reporter('jshint-stylish'));
});

gulp.task('less-lint', function() {
  gulp.src(paths.less)
    .pipe($.plumber())
    .pipe($.recess())
    .pipe($.recess.reporter());
});

gulp.task('clean', function(done) {
  del(['develop/**'], done);
});

gulp.task('karma', function(done) {
  karma.start(_.assign({}, config.karma, { singleRun: true, colors: true }), done);
});

gulp.task('karma-ci', function(done) {
  karma.start(_.assign({}, config.karma, { singleRun: false, colors: true, autoWatch: true }), done);
});

gulp.task('integration', ['server'], function(done) {
  gulp.src(paths.integration)
    .pipe(protractor({
      configFile: 'config/protractor.conf',
      args: ['--baseUrl', 'http://localhost:3000/#/']
    }))
    .on('error', function(e) { browserSync.exit(); throw e; })
    .on('end', function() { browserSync.exit(); done(); });
});

gulp.task('server', function() {
  browserSync({
    server: {
      baseDir: 'develop'
    },
    logConnections: true,
    open: false
  });
});

gulp.task('watch', function() {
  gulp.watch([paths.index, paths.css, paths.less, paths.js], ['at-build']);
  gulp.watch([paths.images, paths.fonts], ['copy-assets']);
  gulp.watch([paths.templates], ['templates']);
  gulp.watch([paths.js], ['jshint']);
  gulp.watch([paths.less], ['less-lint']);
});

gulp.task('copy-assets', ['copy-images', 'copy-fonts']);
gulp.task('build', ['at-build', 'templates', 'copy-assets']);
gulp.task('develop', ['build', 'server', 'watch', 'karma-ci']);
<|endoftext|>


<commit_before>var gulp = require('gulp');
var npdcGulp = require('npdc-gulp');
var config = npdcGulp.baseConfig;
config.COMMON_VERSION = '4.7';
npdcGulp.loadAppTasks(gulp, config);
<commit_msg>newest version of common<commit_after>var gulp = require('gulp');
var npdcGulp = require('npdc-gulp');
var config = npdcGulp.baseConfig;
config.COMMON_VERSION = '4.7.6';
npdcGulp.loadAppTasks(gulp, config);
<|endoftext|>


<commit_before>var gulp = require('gulp');
var npdcGulp = require('npdc-gulp');
var config = npdcGulp.baseConfig;
config.COMMON_VERSION = '4.11.3';
npdcGulp.loadAppTasks(gulp, config);
<commit_msg>DRY npdc-common versioning<commit_after>var gulp = require('gulp');
var npdcGulp = require('npdc-gulp');
var config = npdcGulp.baseConfig;
var package = require('./package.json');
config.COMMON_VERSION = package.dependencies['npdc-common'].split("npdc-common#v")[1];
npdcGulp.loadAppTasks(gulp, config);
<|endoftext|>


<commit_before>// Import modules:
var gulp = require('gulp')
,   pkg = require('./package.json')
,   less = require('gulp-less')
,   minifyCSS = require('gulp-minify-css')
,   gutils = require('gulp-util')
,   concat = require('gulp-concat')
,   rename = require('gulp-rename')
,   replace = require('gulp-replace')
,   uglify = require('gulp-uglify')
,   jshint = require('gulp-jshint')
,   header = require('gulp-header')
,   footer = require('gulp-footer')
,   qunit = require('node-qunit-phantomjs')
,   version = pkg.version;

//Add Trailing slash to projectPath if not exists.
if (pkg.projectPath !== "")
  pkg.projectPath = pkg.projectPath.replace(/\/?$/, '/');

// Define header for ChUI files:
var chocolatechipjsHeader = ['/*',
  '    pO\\',
  '   6  /\\',
  '     /OO\\',
  '    /OOOO\\',
  '   /OOOOOO\\',
  '  (OOOOOOOO)',
  '   \\:~==~:/',
  '',
  '<%= pkg.title %>',
  'Copyright ' + gutils.date("yyyy") + ' Sourcebits www.sourcebits.com',
  'License: <%= pkg.licences[0].type %>',
  'Version: <%= pkg.version %>',
  '*/\n'].join('\n');

// Define header for minfied ChUI files:
var chocolatechipjsHeaderMin = ['/*',
  '<%= pkg.title %>',
  'Copyright ' + gutils.date("yyyy") + ' Sourcebits www.sourcebits.com',
  'License: <%= pkg.licences[0].type %>',
  'Version: <%= pkg.version %>',
  '*/\n'].join('\n');

var testHeader = [
  "<!doctype html>",
  "<html>",
  "   <head>",
  "      <meta charset='UTF-8'>",
  "      <meta http-equiv='content-type' content='text/html; charset=utf-8'>",
  "      <title>QUnit ChocolateChipJS</title>",
  "      <link rel='stylesheet' href='../qunit/qunit.css'>",
  "      <script src='../../dist/chocolatechip-<%= pkg.version %>.js'></script>",
  "      <script src='../qunit/qunit.js'></script>",
  "  </head>\n"
].join('\n');

// Concat, minify and output JavaScript:
gulp.task('js', function () {
  var chuijs_start = [
    '\(function\() {',
    '  \'use strict\';'
  ].join('\n');
  var chuijs_end = '\n\}\)\();';

  gulp.src([
    "src/chocolatechip/returnResult.js",
    "src/chocolatechip/selectors.js",
    "src/chocolatechip/extend.js",
    "src/chocolatechip/core.js",
    "src/chocolatechip/plugin.js",
    "src/chocolatechip/cache.js",
    "src/chocolatechip/collection.js",
    "src/chocolatechip/domready.js",
    "src/chocolatechip/string.js",
    "src/chocolatechip/form.js",
    "src/chocolatechip/ajax.js",
    "src/chocolatechip/events.js",
    "src/chocolatechip/feature-detection.js",
    "src/chocolatechip/templates.js",
    "src/chocolatechip/pubsub.js",
    "src/chocolatechip/deferred.js",
    "src/chocolatechip/data.js",
    "src/chocolatechip/expose-chocolatechip.js"
  ])

    .pipe(replace(/^\(function\(\)\{\n  \"use strict\";/img, ''))
    .pipe(replace(/^\}\)\(\);/img, ''))
    .pipe(concat("chocolatechip-" + pkg.version + ".js"))
    .pipe(header(chuijs_start))
    .pipe(footer(chuijs_end))
    .pipe(header(chocolatechipjsHeader, { pkg : pkg, chuiName: pkg.title }))
    .pipe(replace(/VERSION_NUMBER/img, '\"' + version + '\"'))
    .pipe(gulp.dest(pkg.projectPath + './dist/'))
    .pipe(uglify())
    .pipe(header(chocolatechipjsHeaderMin, { pkg : pkg, chuiName: pkg.title }))
    .pipe(rename("chocolatechip-" + pkg.version + ".min.js"))
    .pipe(gulp.dest(pkg.projectPath + './dist/'))
});

// JSHint:
gulp.task('jshint', function() {
  gulp.src("dist/chocolatechip-" + pkg.version + ".js")
    // jshint and options:
    .pipe(jshint({
      curly: false,
      browser: true,
      eqeqeq: true,
      forin: false,
      immed: false,
      expr: false,
      indent: false,
      noempty: true,
      plusplus: false,
      unused: false,
      boss: true,
      evil: true,
      laxbreak: true,
      multistr: true,
      scripturl: true,
      "-W030": true,
      "-W083": false
    }))
    .pipe(jshint.reporter('default'));
});

// Create Tests:
gulp.task('tests', function(finishedCallback) {
  gulp.src('src/tests/qunit/*')
    .pipe(gulp.dest('tests/qunit'));

  gulp.src('src/tests/chocolatechip/*.js')
    .pipe(gulp.dest('tests/chocolatechip'));

  gulp.src('src/tests/chocolatechip/*.html')
    .pipe(header(testHeader, {pkg: pkg}))
    .pipe(gulp.dest('tests/chocolatechip'));

  testCount = 0;
  testCountStream = gulp.src('tests/chocolatechip/*.html');
  testCountStream.on('data', function(file) {
    testCount++;
  });
  testCountStream.on('end', function() {
    testRunStream = gulp.src('tests/chocolatechip/*.html');
    testRunStream.on('data', function(file) {
      qunit(file.path, {}, function() {
        testCount--;
        if (testCount == 0)
          finishedCallback();
      });
    });
  });
});

/*
   Define default task:
   To build, just enter gulp in terminal.
*/
gulp.task('default', ['js', 'jshint', 'tests']);
<commit_msg>Run tests only after they have been copied<commit_after>// Import modules:
var gulp = require('gulp')
,   pkg = require('./package.json')
,   less = require('gulp-less')
,   minifyCSS = require('gulp-minify-css')
,   gutils = require('gulp-util')
,   concat = require('gulp-concat')
,   rename = require('gulp-rename')
,   replace = require('gulp-replace')
,   uglify = require('gulp-uglify')
,   jshint = require('gulp-jshint')
,   header = require('gulp-header')
,   footer = require('gulp-footer')
,   qunit = require('node-qunit-phantomjs')
,   version = pkg.version;

//Add Trailing slash to projectPath if not exists.
if (pkg.projectPath !== "")
  pkg.projectPath = pkg.projectPath.replace(/\/?$/, '/');

// Define header for ChUI files:
var chocolatechipjsHeader = ['/*',
  '    pO\\',
  '   6  /\\',
  '     /OO\\',
  '    /OOOO\\',
  '   /OOOOOO\\',
  '  (OOOOOOOO)',
  '   \\:~==~:/',
  '',
  '<%= pkg.title %>',
  'Copyright ' + gutils.date("yyyy") + ' Sourcebits www.sourcebits.com',
  'License: <%= pkg.licences[0].type %>',
  'Version: <%= pkg.version %>',
  '*/\n'].join('\n');

// Define header for minfied ChUI files:
var chocolatechipjsHeaderMin = ['/*',
  '<%= pkg.title %>',
  'Copyright ' + gutils.date("yyyy") + ' Sourcebits www.sourcebits.com',
  'License: <%= pkg.licences[0].type %>',
  'Version: <%= pkg.version %>',
  '*/\n'].join('\n');

var testHeader = [
  "<!doctype html>",
  "<html>",
  "   <head>",
  "      <meta charset='UTF-8'>",
  "      <meta http-equiv='content-type' content='text/html; charset=utf-8'>",
  "      <title>QUnit ChocolateChipJS</title>",
  "      <link rel='stylesheet' href='../qunit/qunit.css'>",
  "      <script src='../../dist/chocolatechip-<%= pkg.version %>.js'></script>",
  "      <script src='../qunit/qunit.js'></script>",
  "  </head>\n"
].join('\n');

// Concat, minify and output JavaScript:
gulp.task('js', function () {
  var chuijs_start = [
    '\(function\() {',
    '  \'use strict\';'
  ].join('\n');
  var chuijs_end = '\n\}\)\();';

  gulp.src([
    "src/chocolatechip/returnResult.js",
    "src/chocolatechip/selectors.js",
    "src/chocolatechip/extend.js",
    "src/chocolatechip/core.js",
    "src/chocolatechip/plugin.js",
    "src/chocolatechip/cache.js",
    "src/chocolatechip/collection.js",
    "src/chocolatechip/domready.js",
    "src/chocolatechip/string.js",
    "src/chocolatechip/form.js",
    "src/chocolatechip/ajax.js",
    "src/chocolatechip/events.js",
    "src/chocolatechip/feature-detection.js",
    "src/chocolatechip/templates.js",
    "src/chocolatechip/pubsub.js",
    "src/chocolatechip/deferred.js",
    "src/chocolatechip/data.js",
    "src/chocolatechip/expose-chocolatechip.js"
  ])

    .pipe(replace(/^\(function\(\)\{\n  \"use strict\";/img, ''))
    .pipe(replace(/^\}\)\(\);/img, ''))
    .pipe(concat("chocolatechip-" + pkg.version + ".js"))
    .pipe(header(chuijs_start))
    .pipe(footer(chuijs_end))
    .pipe(header(chocolatechipjsHeader, { pkg : pkg, chuiName: pkg.title }))
    .pipe(replace(/VERSION_NUMBER/img, '\"' + version + '\"'))
    .pipe(gulp.dest(pkg.projectPath + './dist/'))
    .pipe(uglify())
    .pipe(header(chocolatechipjsHeaderMin, { pkg : pkg, chuiName: pkg.title }))
    .pipe(rename("chocolatechip-" + pkg.version + ".min.js"))
    .pipe(gulp.dest(pkg.projectPath + './dist/'))
});

// JSHint:
gulp.task('jshint', function() {
  gulp.src("dist/chocolatechip-" + pkg.version + ".js")
    // jshint and options:
    .pipe(jshint({
      curly: false,
      browser: true,
      eqeqeq: true,
      forin: false,
      immed: false,
      expr: false,
      indent: false,
      noempty: true,
      plusplus: false,
      unused: false,
      boss: true,
      evil: true,
      laxbreak: true,
      multistr: true,
      scripturl: true,
      "-W030": true,
      "-W083": false
    }))
    .pipe(jshint.reporter('default'));
});

// Create Tests:
gulp.task('tests', function() {
  gulp.src('src/tests/qunit/*')
    .pipe(gulp.dest('tests/qunit'));

  gulp.src('src/tests/chocolatechip/*.js')
    .pipe(gulp.dest('tests/chocolatechip'));

  stream = gulp.src('src/tests/chocolatechip/*.html')
    .pipe(header(testHeader, {pkg: pkg}))
    .pipe(gulp.dest('tests/chocolatechip'));

  return stream;
});

// Run Tests
gulp.task('qunit', ['tests'], function(finishedCallback) {
  testCount = 0;
  testCountStream = gulp.src('tests/chocolatechip/*.html');
  testCountStream.on('data', function(file) {
    testCount++;
  });

  testCountStream.on('end', function() {
    testRunStream = gulp.src('tests/chocolatechip/*.html');
    testRunStream.on('data', function(file) {
      qunit(file.path, {}, function() {
        testCount--;
        if (testCount == 0)
          finishedCallback();
      });
    });
  });
});
/*
   Define default task:
   To build, just enter gulp in terminal.
*/
gulp.task('default', ['js', 'jshint', 'tests', 'qunit']);
<|endoftext|>


<commit_before>'use strict';

var fs = require('fs');
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var request = require('request');

var isOnTravis = process.env.CIRCLECI === 'true';
var isOnTravisAndMaster = isOnTravis && process.env.CI_PULL_REQUEST === '' && process.env.CIRCLE_BRANCH === 'master';

gulp.task('swagger:clean', $.shell.task([
   'rm -rf build',
   'mkdir build'
]));

gulp.task('swagger:resolve', ['swagger:clean'], function(done){
    request({ url: 'http://28msec.github.io/cellstore-pro/swagger-aggregated.json' }, function(err, resp){
        fs.writeFileSync('build/swagger-aggregated.json', resp.body);
        done();
    });
});

gulp.task('swagger:install-codegen', ['swagger:resolve'], $.shell.task('cd build && curl -L -o swagger-codegen.zip https://github.com/28msec/swagger-codegen/archive/2149dc04d52811cbf89ac72ab17a57be6a6150ac.zip && unzip -q swagger-codegen.zip && cd swagger-codegen-2149dc04d52811cbf89ac72ab17a57be6a6150ac && mvn package && cp modules/swagger-codegen-cli/target/swagger-codegen-cli.jar ..'));

gulp.task('swagger:generate-csharp', ['swagger:install-codegen'], $.shell.task([
    'cd build && java -jar swagger-codegen-cli.jar generate -i swagger-aggregated.json -l csharp  -o .'
]));

gulp.task('swagger:csharp', ['swagger:generate-csharp'], $.shell.task([
    'cd build && mcs -sdk:4.5 -r:bin/Newtonsoft.Json.dll,bin/RestSharp.dll,System.Runtime.Serialization.dll -target:library -out:bin/out-x86x64.dll -recurse:src/*.cs -doc:bin/out-x86x64.xml -platform:anycpu'
]));

gulp.task('swagger:publish', ['swagger:csharp'], function(done){
    if(true || isOnTravisAndMaster) {
        $.nugetPack({
            id: 'CellStore.NET',
            version: '0.0.2',
            authors: '28msec',
            owners: 'dknochen',
            licenseUrl: 'https://raw.githubusercontent.com/28msec/cellstore-csharp/master/LICENSE',
            projectUrl: 'https://github.com/28msec/cellstore-csharp',
            iconUrl: 'http://www.28.io/images/favicon/32x32.png',
            requireLicenseAcceptance: false,
            description: 'A CSharp Library for interfacing with the 28msec\'s Cell Store API',
            copyright: 'Copyright 2015 28msec',
            tags: 'CellStore JSONiq',
            dependencies: [
                { id: 'RestSharp', version: '103.0.0' },
                { id: 'Newtonsoft.Json', version: '7.0.1' }
            ]
        }, [
            { src: 'build/bin/CellStore.dll', dest: 'lib/CellStore.dll' },
            { src: 'build/bin/CellStore.xml', dest: 'doc/CellStore.xml' }
        ], done);
    } else {
        done();
    }
});

gulp.task('default', ['swagger:publish']);
<commit_msg>:wrench:<commit_after>'use strict';

var fs = require('fs');
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var request = require('request');

var isOnTravis = process.env.CIRCLECI === 'true';
var isOnTravisAndMaster = isOnTravis && process.env.CI_PULL_REQUEST === '' && process.env.CIRCLE_BRANCH === 'master';

gulp.task('swagger:clean', $.shell.task([
   'rm -rf build',
   'mkdir build'
]));

gulp.task('swagger:resolve', ['swagger:clean'], function(done){
    request({ url: 'http://28msec.github.io/cellstore-pro/swagger-aggregated.json' }, function(err, resp){
        fs.writeFileSync('build/swagger-aggregated.json', resp.body);
        done();
    });
});

gulp.task('swagger:install-codegen', ['swagger:resolve'], $.shell.task('cd build && curl -L -o swagger-codegen.zip https://github.com/28msec/swagger-codegen/archive/2149dc04d52811cbf89ac72ab17a57be6a6150ac.zip && unzip -q swagger-codegen.zip && cd swagger-codegen-2149dc04d52811cbf89ac72ab17a57be6a6150ac && mvn package && cp modules/swagger-codegen-cli/target/swagger-codegen-cli.jar ..'));

gulp.task('swagger:generate-csharp', ['swagger:install-codegen'], $.shell.task([
    'cd build && java -jar swagger-codegen-cli.jar generate -i swagger-aggregated.json -l csharp  -o .'
]));

gulp.task('swagger:csharp', ['swagger:generate-csharp'], $.shell.task([
    'cd build && mcs -sdk:4.5 -r:bin/Newtonsoft.Json.dll,bin/RestSharp.dll,System.Runtime.Serialization.dll -target:library -out:bin/out-x86x64.dll -recurse:src/*.cs -doc:bin/out-x86x64.xml -platform:anycpu'
]));

gulp.task('swagger:publish', ['swagger:csharp'], function(done){
    if(true || isOnTravisAndMaster) {
        $.nugetPack({
            id: 'CellStore.NET',
            version: '0.0.2',
            authors: '28msec',
            owners: 'dknochen',
            licenseUrl: 'https://raw.githubusercontent.com/28msec/cellstore-csharp/master/LICENSE',
            projectUrl: 'https://github.com/28msec/cellstore-csharp',
            iconUrl: 'http://www.28.io/images/favicon/32x32.png',
            requireLicenseAcceptance: false,
            description: 'A CSharp Library for interfacing with the 28msec\'s Cell Store API',
            copyright: 'Copyright 2015 28msec',
            tags: 'CellStore JSONiq',
            dependencies: [
                { id: 'RestSharp', version: '(105.2.3, )' },
                { id: 'Newtonsoft.Json', version: '7.0.1' }
            ]
        }, [
            { src: 'build/bin/CellStore.dll', dest: 'lib/CellStore.dll' },
            { src: 'build/bin/CellStore.xml', dest: 'doc/CellStore.xml' }
        ], done);
    } else {
        done();
    }
});

gulp.task('default', ['swagger:publish']);
<|endoftext|>


<commit_before>var gulp        = require('gulp');
var browserify  = require('gulp-browserify');
var jade        = require('gulp-jade');
var minifyCss   = require('gulp-minify-css');
var uglify      = require('gulp-uglify');
var concat      = require('gulp-concat');
var rename      = require('gulp-rename');
var browserSync = require('browser-sync').create();

var dist = './dist';
var src  = './src';

// default task
gulp.task('default', ['browser-sync'], function () {
  gulp.watch('dist/*.html', ['reload']);
  gulp.watch('dist/*.css', ['reload']);
  gulp.watch('dist/*.js', ['reload']);
});

// sync browser
gulp.task('browser-sync', function() {
  browserSync.init({
    port: 8080,
    server: {
      baseDir: 'dist',
      index: 'popup.html'
    }
  });
});

// reload browser
gulp.task('reload', function () {
  browserSync.reload();
});

// copy bootflat files into src

// convert jade to html
gulp.task('jade', function() {
  gulp.src('./src/jade/*.jade')
    .pipe(jade())
    .pipe(gulp.dest('./dist/'));
});

// convert sass to css

// minify and concat css
gulp.task('css', function() {
  gulp.src([
    './node_modules/bootflat/bootflat/css/bootflat.min.css'
  ])
  .pipe(minifyCss())
  .pipe(concat('app.css'))
  .pipe(gulp.dest('dist/css'));
});

// minify and concat js
gulp.task('js', function() {
  gulp.src([
    './node_modules/bootflat/js/bootstrap.min.js'
  ])
  .pipe(uglify({
    preserveComments: 'license'
  }))
  .pipe(concat('app.js'))
  .pipe(gulp.dest('dist/js'));
});

// convert and minify and distribution into dist

// watch src
<commit_msg>Tweak<commit_after>var gulp        = require('gulp');
var browserify  = require('gulp-browserify');
var jade        = require('gulp-jade');
var minifyCss   = require('gulp-minify-css');
var uglify      = require('gulp-uglify');
var concat      = require('gulp-concat');
var rename      = require('gulp-rename');
var browserSync = require('browser-sync').create();

var dist = './dist';
var src  = './src';

// default task
gulp.task('default', ['browser-sync'], function () {
  gulp.watch('dist/*.html', ['reload']);
  gulp.watch('dist/*.css', ['reload']);
  gulp.watch('dist/*.js', ['reload']);
});

// sync browser
gulp.task('browser-sync', function() {
  browserSync.init({
    port: 8080,
    server: {
      baseDir: 'dist',
      index: 'popup.html'
    }
  });
});

// reload browser
gulp.task('reload', function () {
  browserSync.reload();
});

// copy bootflat files into src

// convert jade to html
gulp.task('jade', function() {
  gulp.src('./src/jade/*.jade')
  .pipe(jade())
  .pipe(gulp.dest('./dist/'));
});

// convert sass to css
gulp.task('convert-sass', function() {
});

// minify and concat css
gulp.task('css', function() {
  gulp.src([
    './node_modules/bootflat/bootflat/css/bootflat.min.css'
  ])
  .pipe(minifyCss())
  .pipe(concat('app.css'))
  .pipe(gulp.dest('dist/css'));
});

// minify and concat js
gulp.task('js', function() {
  gulp.src([
    './node_modules/bootflat/js/bootstrap.min.js'
  ])
  .pipe(uglify({
    preserveComments: 'license'
  }))
  .pipe(concat('app.js'))
  .pipe(gulp.dest('dist/js'));
});

// convert and minify and distribution into dist

// watch src
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	errorHandler = require('./errors.server.controller'),
	Participant = mongoose.model('Participant'),
	_ = require('lodash');

/**
 * Create a Participant
 */
exports.create = function(req, res) {
	var participant = new Participant(req.body);
	participant.displayName = participant.firstName + ' ' + participant.lastName;
	participant.user = req.user;

	participant.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(participant);
		}
	});
};

/**
 * Show the current Participant
 */
exports.read = function(req, res) {
	res.jsonp(req.participant);
};

/**
 * Update a Participant
 */
exports.update = function(req, res) {
	var participant = req.participant ;

	participant = _.extend(participant , req.body);
	participant.displayName = participant.firstName + ' ' + participant.lastName;

	participant.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(participant);
		}
	});
};

/**
 * Delete an Participant
 */
exports.delete = function(req, res) {
	var participant = req.participant ;

	participant.remove(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(participant);
		}
	});
};

/**
 * List of Participants
 */
exports.list = function(req, res) {
	var conditions = {};
	if (req.query.name) {
		conditions = { $or: [
			{ lastName: new RegExp(req.query.name, 'i') },
			{ firstName: new RegExp(req.query.name, 'i') }
		] };
	}
	Participant.find(conditions).sort('firstName lastName').populate('user', 'displayName').exec(function(err, participants) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(participants);
		}
	});
};

/**
 * Participant middleware
 */
exports.participantByID = function(req, res, next, id) {
	Participant.findById(id).populate('user', 'displayName').exec(function(err, participant) {
		if (err) return next(err);
		if (! participant) return next(new Error('Failed to load Participant ' + id));
		req.participant = participant ;
		next();
	});
};

/**
 * Participant authorization middleware
 */
exports.hasAuthorization = function(req, res, next) {
	if (req.participant.user.id !== req.user.id) {
		return res.status(403).send('User is not authorized');
	}
	next();
};
<commit_msg>Made the participant search a little more robust<commit_after>'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	errorHandler = require('./errors.server.controller'),
	Participant = mongoose.model('Participant'),
	_ = require('lodash');

/**
 * Create a Participant
 */
exports.create = function(req, res) {
	var participant = new Participant(req.body);
	participant.displayName = participant.firstName + ' ' + participant.lastName;
	participant.user = req.user;

	participant.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(participant);
		}
	});
};

/**
 * Show the current Participant
 */
exports.read = function(req, res) {
	res.jsonp(req.participant);
};

/**
 * Update a Participant
 */
exports.update = function(req, res) {
	var participant = req.participant ;

	participant = _.extend(participant , req.body);
	participant.displayName = participant.firstName + ' ' + participant.lastName;

	participant.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(participant);
		}
	});
};

/**
 * Delete an Participant
 */
exports.delete = function(req, res) {
	var participant = req.participant ;

	participant.remove(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(participant);
		}
	});
};

/**
 * List of Participants
 */
exports.list = function(req, res) {
	var conditions = {};
	if (req.query.name) {
		var or_conditions = [];
		var name_parts = req.query.name.split(/[ ,]+/)
		_.each(name_parts, function(part) {
			or_conditions.push({ lastName: new RegExp('^' + part, 'i') });
			or_conditions.push({ firstName: new RegExp('^' + part, 'i') });
		});
		conditions = { $or: or_conditions };
	}
	Participant.find(conditions).sort('firstName lastName').populate('user', 'displayName').exec(function(err, participants) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(participants);
		}
	});
};

/**
 * Participant middleware
 */
exports.participantByID = function(req, res, next, id) {
	Participant.findById(id).populate('user', 'displayName').exec(function(err, participant) {
		if (err) return next(err);
		if (! participant) return next(new Error('Failed to load Participant ' + id));
		req.participant = participant ;
		next();
	});
};

/**
 * Participant authorization middleware
 */
exports.hasAuthorization = function(req, res, next) {
	if (req.participant.user.id !== req.user.id) {
		return res.status(403).send('User is not authorized');
	}
	next();
};
<|endoftext|>


<commit_before>'use strict';

const gulp = require('gulp');
const electron = require('electron-prebuilt');
const electronPackager = require('electron-packager');
var childProcess = require('child_process');

const packageJson = require('./package.json');

const _ = require('underscore');

const RELEASE_SETTINGS = {
    dir: '.',
    name: packageJson.name,
    out: 'dist',
    'app-version': packageJson.version,
    'win32metadata' : {
        ProductName : packageJson.name,
        CompanyName: packageJson.author,
        FileDescription: packageJson.description,
        OriginalFilename: packageJson.name + '.exe',
        ProductVersion : packageJson.version,
    },
    ignore : '/.gitignore|CHANGELOG.md|README.md|gulpfile.js|kongdash-256x256.png/',
    appPath : packageJson.main,
    overwrite: true,
    asar: true,
    prune: true
};

require('gulp-task-list')(gulp);

gulp.task('start', (next) => {
    var child = childProcess.spawn(electron, ['./']);

    child.stdout.on('data', (data) => {
        console.log(data);
    });

    child.on('exit', (code) => {
        console.log('Child exited with code: ' + code);
        return next(code === 1 ? new Error('Error running run task') : null);
    });
});

gulp.task('build-linux32', (next) => {
    electronPackager(_.extend(RELEASE_SETTINGS, {
        platform: 'linux',
        arch: 'ia32'
    }), next)
});

gulp.task('build-linux64', (next) => {
    electronPackager(_.extend(RELEASE_SETTINGS, {
        platform: 'linux',
        arch: 'x64'
    }), next)
});

gulp.task('build-windows32', (next) => {
    electronPackager(_.extend(RELEASE_SETTINGS, {
        platform: 'win32',
        arch: 'ia32',
        icon: 'resources/icons/kongdash-256x256.ico'
    }), next)
});

gulp.task('build-windows64', (next) => {
    electronPackager(_.extend(RELEASE_SETTINGS, {
        platform: 'win32',
        arch: 'x64',
        icon: 'resources/icons/kongdash-256x256.ico'
    }), next)
});<commit_msg>[changed] ignore file list<commit_after>'use strict';

const gulp = require('gulp');
const electron = require('electron-prebuilt');
const electronPackager = require('electron-packager');
var childProcess = require('child_process');

const packageJson = require('./package.json');

const _ = require('underscore');

const RELEASE_SETTINGS = {
    dir: '.',
    name: packageJson.name,
    out: 'dist',
    'app-version': packageJson.version,
    'win32metadata' : {
        ProductName : packageJson.name,
        CompanyName: packageJson.author,
        FileDescription: packageJson.description,
        OriginalFilename: packageJson.name + '.exe',
        ProductVersion : packageJson.version,
    },
    ignore : '/.gitignore|CHANGELOG.md|README.md|gulpfile.js|screenshot.png/',
    appPath : packageJson.main,
    overwrite: true,
    asar: true,
    prune: true
};

require('gulp-task-list')(gulp);

gulp.task('start', (next) => {
    var child = childProcess.spawn(electron, ['./']);

    child.stdout.on('data', (data) => {
        console.log(data);
    });

    child.on('exit', (code) => {
        console.log('Child exited with code: ' + code);
        return next(code === 1 ? new Error('Error running run task') : null);
    });
});

gulp.task('build-linux32', (next) => {
    electronPackager(_.extend(RELEASE_SETTINGS, {
        platform: 'linux',
        arch: 'ia32'
    }), next)
});

gulp.task('build-linux64', (next) => {
    electronPackager(_.extend(RELEASE_SETTINGS, {
        platform: 'linux',
        arch: 'x64'
    }), next)
});

gulp.task('build-windows32', (next) => {
    electronPackager(_.extend(RELEASE_SETTINGS, {
        platform: 'win32',
        arch: 'ia32',
        icon: 'resources/icons/kongdash-256x256.ico'
    }), next)
});

gulp.task('build-windows64', (next) => {
    electronPackager(_.extend(RELEASE_SETTINGS, {
        platform: 'win32',
        arch: 'x64',
        icon: 'resources/icons/kongdash-256x256.ico'
    }), next)
});<|endoftext|>


<commit_before>var gulp    = require('gulp'),
    sass    = require('gulp-sass'),
    plumber = require('gulp-plumber'),
    csslint = require('gulp-csslint'),
    gutil   = require('gulp-util');

var cssLintSettings = {
    'adjoining-classes'          : false,
    'box-model'                  : false,
    'box-sizing'                 : false,
    'compatible-vendor-prefixes' : false,
    'empty-rules'                : false,
    'display-property-grouping'  : false,
    'duplicate-background-images': false,
    'duplicate-properties'       : false,
    'fallback-colors'            : false,
    'floats'                     : false,
    'font-faces'                 : false,
    'font-sizes'                 : false,
    'gradients'                  : false,
    'ids'                        : false,
    'import'                     : false,
    'important'                  : false,
    'known-properties'           : true,
    'outline-none'               : false,
    'overqualified-elements'     : false,
    'qualified-headings'         : false,
    'regex-selectors'            : false,
    'shorthand'                  : false,
    'star-property-hack'         : false,
    'text-indent'                : false,
    'underscore-property-hack'   : false,
    'unique-headings'            : false,
    'universal-selector'         : false,
    'unqualified-attributes'     : false,
    'vendor-prefix'              : false,
    'zero-units'                 : false
};

// css lint custom formater
function customReporter(file) {
    gutil.log(gutil.colors.cyan(file.csslint.errorCount) + ' errors in ' + gutil.colors.magenta(file.path));

    file.csslint.results.forEach(function(result) {
        if (result.error.type === 'warning') {
            gutil.log( gutil.colors.yellow.bold('[Warining]') + gutil.colors.green(' Line: ' + result.error.line) + gutil.colors.cyan(' Column: ' + result.error.col) + ' ' + gutil.colors.magenta(result.error.message) + ' ' +  gutil.colors.gray(result.error.rule.desc) + ' ' + gutil.colors.red('Browsers: ' + result.error.rule.browsers));
        }
        else {
            gutil.log( gutil.colors.red.bold('[' + result.error.type + ']') + gutil.colors.green(' Line: ' + result.error.line) + gutil.colors.cyan(' Column: ' + result.error.col) + ' ' + gutil.colors.magenta(result.error.message) + ' ' +  gutil.colors.gray(result.error.rule.desc) + ' ' + gutil.colors.red('Browsers: ' + result.error.rule.browsers));
        }
    });
}

gulp.task('default', () => {
    gulp.watch('**/*.scss', ['sass']);
});

gulp.task('sass', () => {
    gulp.src('css/*.scss')
        .pipe(plumber())
        .pipe(sass())
        .pipe(gulp.dest('compiled'));
});

gulp.task('lint', () => {
    gulp.src('compiled/*.css')
        .pipe(plumber())
        .pipe(csslint(cssLintSettings))
        .pipe(csslint.reporter(customReporter))
        .pipe(csslint.reporter('fail'));
});
<commit_msg>Travis CI errors reporting<commit_after>var gulp    = require('gulp'),
    sass    = require('gulp-sass'),
    plumber = require('gulp-plumber'),
    csslint = require('gulp-csslint'),
    gutil   = require('gulp-util');

var cssLintSettings = {
    'adjoining-classes'          : false,
    'box-model'                  : false,
    'box-sizing'                 : false,
    'compatible-vendor-prefixes' : false,
    'empty-rules'                : false,
    'display-property-grouping'  : false,
    'duplicate-background-images': false,
    'duplicate-properties'       : false,
    'fallback-colors'            : false,
    'floats'                     : false,
    'font-faces'                 : false,
    'font-sizes'                 : false,
    'gradients'                  : false,
    'ids'                        : false,
    'import'                     : false,
    'important'                  : false,
    'known-properties'           : true,
    'outline-none'               : false,
    'overqualified-elements'     : false,
    'qualified-headings'         : false,
    'regex-selectors'            : false,
    'shorthand'                  : false,
    'star-property-hack'         : false,
    'text-indent'                : false,
    'underscore-property-hack'   : false,
    'unique-headings'            : false,
    'universal-selector'         : false,
    'unqualified-attributes'     : false,
    'vendor-prefix'              : false,
    'zero-units'                 : false
};

// css lint custom formater
function customReporter(file) {
    gutil.log(gutil.colors.cyan(file.csslint.errorCount) + ' errors in ' + gutil.colors.magenta(file.path));

    file.csslint.results.forEach(function(result) {
        if (result.error.type === 'warning') {
            gutil.log( gutil.colors.yellow.bold('[Warining]') + gutil.colors.green(' Line: ' + result.error.line) + gutil.colors.cyan(' Column: ' + result.error.col) + ' ' + gutil.colors.magenta(result.error.message) + ' ' +  gutil.colors.gray(result.error.rule.desc) + ' ' + gutil.colors.red('Browsers: ' + result.error.rule.browsers));
        }
        else {
            gutil.log( gutil.colors.red.bold('[' + result.error.type + ']') + gutil.colors.green(' Line: ' + result.error.line) + gutil.colors.cyan(' Column: ' + result.error.col) + ' ' + gutil.colors.magenta(result.error.message) + ' ' +  gutil.colors.gray(result.error.rule.desc) + ' ' + gutil.colors.red('Browsers: ' + result.error.rule.browsers));
        }
    });
}

gulp.task('default', () => {
    gulp.watch('**/*.scss', ['sass']);
});

gulp.task('sass', () => {
    gulp.src('css/*.scss')
        .pipe(plumber())
        .pipe(sass())
        .pipe(gulp.dest('compiled'));
});

gulp.task('lint', () => {
    gulp.src('compiled/*.css')
        .pipe(csslint(cssLintSettings))
        .pipe(csslint.reporter(customReporter))
        .pipe(csslint.reporter('fail'));
});
<|endoftext|>


<commit_before>var fs = require('fs');
var gulp = require('gulp');
var usemin = require('gulp-usemin');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
var cleanCSS = require('gulp-clean-css');
var del = require('del')
var rev = require('gulp-rev')
var realFavicon = require('gulp-real-favicon');
var copy = require('gulp-copy');
var postcss = require('gulp-postcss');
var autoprefixer = require('autoprefixer');
var svgInject = require('svg-injectr');
var htmlmin = require('gulp-htmlmin');
var through = require('through2');
var processhtml = require('gulp-processhtml');
var replace = require('gulp-replace');

// File where the favicon markups are stored
var FAVICON_DATA_FILE = 'cache/faviconData.json';

gulp.task('copy:fonts', ['clean'], function() {
  return gulp.src('assets/css/font/**/*.{ttf,woff,woff2,eot,svg}')
      .pipe(gulp.dest('public/font'));
});

gulp.task('copy:assets', ['clean'], function() {
  var assets_paths = [
    'assets/svg/*',
    'assets/img/**/*',
    'vendor/**/*',
    'share.html'
  ]

  return gulp.src(assets_paths)
             .pipe(copy('public'));
});

gulp.task('copy:favicon', ['clean'], function() {
  return gulp.src('cache/favicon/*')
      .pipe(gulp.dest('public'));
});

gulp.task('minify', ['clean'], function() {

  var cleancssOpt = {advanced:false, aggressiveMerging:false, restructuring:false}
  var processors = [autoprefixer({browsers: ['last 2 version']})];

  return gulp.src('index.html')
      .pipe(usemin({
        css: [ cleanCSS(cleancssOpt), postcss(processors) ],
        vendorjs: [ uglify ]
      }))
      .pipe(gulp.dest('public'));
});

gulp.task('clean', function() {
  return del([
    'public/**/**/*',
    // don't remove .gitkeep
    '!public/.gitkeep'
  ]);
});

// Generate the icons. This task takes a few seconds to complete.
// You should run it at least once to create the icons. Then,
// you should run it whenever RealFaviconGenerator updates its
// package (see the check-for-favicon-update task below).
gulp.task('generate-favicon', function(done) {
  realFavicon.generateFavicon({
    masterPicture: 'favicon.svg',
    dest: 'cache/favicon',
    iconsPath: '/',
    design: {
      ios: {
        pictureAspect: 'backgroundAndMargin',
        backgroundColor: '#ffffff',
        margin: '14%'
      },
      desktopBrowser: {},
      windows: {
        pictureAspect: 'noChange',
        backgroundColor: '#da532c',
        onConflict: 'override'
      },
      androidChrome: {
        pictureAspect: 'shadow',
        themeColor: '#ffffff',
        manifest: {
          name: 'Cryptoloji',
          display: 'browser',
          orientation: 'notSet',
          onConflict: 'override',
          declared: true
        }
      },
      safariPinnedTab: {
        pictureAspect: 'silhouette',
        themeColor: '#5bbad5'
      }
    },
    settings: {
      compression: 2,
      scalingAlgorithm: 'Mitchell',
      errorOnImageTooSmall: false
    },
    markupFile: FAVICON_DATA_FILE
  }, function() {
    done();
  });
});

gulp.task('finalhtml', ['copy:assets'], function(){

  var htmlminopt = {collapseWhitespace: true, removeComments:true, collapseWhitespace:true}

  gulp.src('public/index.html')
    .pipe(through.obj(function (chunk, enc, cb) {
      svgInject({source:chunk.path, selector:'data-svg'}, function(res){
        chunk.contents = new Buffer('<!DOCTYPE html>' + res)
        cb(null, chunk);
      })
    }))
    .pipe(realFavicon.injectFaviconMarkups(JSON.parse(fs.readFileSync(FAVICON_DATA_FILE)).favicon.html_code))
    .pipe(processhtml({
      commentMarker: 'process',
      recursive:true,
      data:{version:Math.random()*10000}
    }))
    .pipe(replace('<script src="app.js"></script>', ''))
    .pipe(replace('<link rel="stylesheet" href="style.css">', ''))
    .pipe(htmlmin(htmlminopt))
    .pipe(gulp.dest('public/'))
})

gulp.task('build', ['clean', 'copy:fonts', 'copy:favicon', 'copy:assets', 'minify', 'finalhtml']);
gulp.task('favicon', ['generate-favicon']);
<commit_msg>last fix on builder<commit_after>var fs = require('fs');
var gulp = require('gulp');
var usemin = require('gulp-usemin');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
var cleanCSS = require('gulp-clean-css');
var del = require('del')
var rev = require('gulp-rev')
var realFavicon = require('gulp-real-favicon');
var copy = require('gulp-copy');
var postcss = require('gulp-postcss');
var autoprefixer = require('autoprefixer');
var svgInject = require('svg-injectr');
var htmlmin = require('gulp-htmlmin');
var through = require('through2');
var processhtml = require('gulp-processhtml');
var replace = require('gulp-replace');

// File where the favicon markups are stored
var FAVICON_DATA_FILE = 'cache/faviconData.json';

gulp.task('copy:fonts', ['clean'], function() {
  return gulp.src('assets/css/font/**/*.{ttf,woff,woff2,eot,svg}')
      .pipe(gulp.dest('public/font'));
});

gulp.task('copy:assets', ['clean'], function() {
  var assets_paths = [
    'assets/svg/*',
    'assets/img/**/*',
    'vendor/**/*',
    'share.html',
    'bower_components/youarei/dist/youarei.js'
  ]

  return gulp.src(assets_paths)
             .pipe(copy('public'));
});

gulp.task('copy:favicon', ['clean'], function() {
  return gulp.src('cache/favicon/*')
      .pipe(gulp.dest('public'));
});

gulp.task('minify', ['clean'], function() {

  var cleancssOpt = {advanced:false, aggressiveMerging:false, restructuring:false}
  var processors = [autoprefixer({browsers: ['last 2 version']})];

  return gulp.src('index.html')
      .pipe(usemin({
        css: [ cleanCSS(cleancssOpt), postcss(processors) ],
        vendorjs: [ uglify ]
      }))
      .pipe(gulp.dest('public'));
});

gulp.task('clean', function() {
  return del([
    'public/**/**/*',
    // don't remove .gitkeep
    '!public/.gitkeep'
  ]);
});

// Generate the icons. This task takes a few seconds to complete.
// You should run it at least once to create the icons. Then,
// you should run it whenever RealFaviconGenerator updates its
// package (see the check-for-favicon-update task below).
gulp.task('generate-favicon', function(done) {
  realFavicon.generateFavicon({
    masterPicture: 'favicon.svg',
    dest: 'cache/favicon',
    iconsPath: '/',
    design: {
      ios: {
        pictureAspect: 'backgroundAndMargin',
        backgroundColor: '#ffffff',
        margin: '14%'
      },
      desktopBrowser: {},
      windows: {
        pictureAspect: 'noChange',
        backgroundColor: '#da532c',
        onConflict: 'override'
      },
      androidChrome: {
        pictureAspect: 'shadow',
        themeColor: '#ffffff',
        manifest: {
          name: 'Cryptoloji',
          display: 'browser',
          orientation: 'notSet',
          onConflict: 'override',
          declared: true
        }
      },
      safariPinnedTab: {
        pictureAspect: 'silhouette',
        themeColor: '#5bbad5'
      }
    },
    settings: {
      compression: 2,
      scalingAlgorithm: 'Mitchell',
      errorOnImageTooSmall: false
    },
    markupFile: FAVICON_DATA_FILE
  }, function() {
    done();
  });
});

gulp.task('finalhtml', ['copy:assets'], function(){

  var htmlminopt = {collapseWhitespace: true, removeComments:true, collapseWhitespace:true}

  gulp.src('public/index.html')
    .pipe(through.obj(function (chunk, enc, cb) {
      svgInject({source:chunk.path, selector:'data-svg'}, function(res){
        chunk.contents = new Buffer('<!DOCTYPE html>' + res)
        cb(null, chunk);
      })
    }))
    .pipe(realFavicon.injectFaviconMarkups(JSON.parse(fs.readFileSync(FAVICON_DATA_FILE)).favicon.html_code))
    .pipe(processhtml({
      commentMarker: 'process',
      recursive:true,
      data:{version:Math.random()*10000}
    }))
    .pipe(replace('<script src="app.js"></script>', ''))
    .pipe(replace('<link rel="stylesheet" href="style.css">', ''))
    .pipe(htmlmin(htmlminopt))
    .pipe(gulp.dest('public/'))
})

gulp.task('build', ['clean', 'copy:fonts', 'copy:favicon', 'copy:assets', 'minify', 'finalhtml']);
gulp.task('favicon', ['generate-favicon']);
<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');
var browserify = require('browserify');
var bundleLogger = require('./gulp/bundle-logger.js');
var glob = require('glob');
var gulp = require('gulp');
var mergeStream = require('merge-stream');
var path = require('path');
var precss = require('precss');
var rimraf = require('rimraf');
var source = require('vinyl-source-stream');
var watchify = require('watchify');

var plugins = require('gulp-load-plugins')();

var args = require('yargs').argv;

var paths = {
  js: [
    './static/js/**.js',
    './**/static/js/**.js'
  ],
  jsEntries: [
    './static/js/*.js',
    './**/static/js/*.js'
  ],
  css: [
    './static/css/**/*.scss',
    '!./static/css/**/_*.scss'
  ],
  python: [
    '**/*.py',
    '!**/migrations/*.py',
    '!./tmp/**/*.py',
    '!./node_modules/**/*.py'
  ],
  bootstrapFiles: [
    './node_modules/bootstrap/dist/css/bootstrap.css',
    './node_modules/bootstrap/dist/css/bootstrap.css.map',
    './node_modules/bootstrap/dist/css/bootstrap-theme.css',
    './node_modules/bootstrap/dist/css/bootstrap-theme.css.map'
  ],
  webshimFiles: [
    './node_modules/webshim/js-webshim/minified/shims/**/*'
  ]
};

// Clean up files
gulp.task('clean', function (cb) {
  rimraf('./build', cb);
});

// Lint JavaScript code
gulp.task('lint-js-eslint', function () {
  return gulp.src(paths.js)
    .pipe(plugins.eslint({
      useEslintrc: true,
      rulePaths: [
        path.join(process.env.HOME, '.eslint')
      ]
    }))
    .pipe(plugins.eslint.format());
});

gulp.task('lint-js-jscs', function () {
  return gulp.src(paths.js)
    .pipe(plugins.jscs());
});

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

// Lint Python code
gulp.task('lint-python', function () {
  var shellOptions = {ignoreErrors: true};

  return gulp.src(paths.python)
    .pipe(plugins.shell([
      'flake8 <%= file.path %> | awk \'$0="flake8: "$0\''
    ], shellOptions))
    .pipe(plugins.shell([
      'pylint --rcfile=.pylintrc -r no -f colorized <%= file.path %> ' +
        '--msg-template "{C}: {path}:{line}:{column} {msg} ({symbol})" ' +
        '| awk \'$0="pylint: "$0\''
    ], shellOptions))
    .pipe(plugins.shell([
      'pep257 <%= file.path %> 2>&1 | awk \'$0="pep257: "$0\''
    ], shellOptions));
});

gulp.task('lint', ['lint-js', 'lint-python']);

gulp.task('bootstrap-files', function () {
  return gulp.src(paths.bootstrapFiles)
    .pipe(gulp.dest('./build/vendor'));
});

gulp.task('webshim-files', function () {
  return gulp.src(paths.webshimFiles)
    .pipe(gulp.dest('./build/vendor/shims'));
});

// Collect Bootstrap and other frontend files
gulp.task('frontend-files', ['bootstrap-files', 'webshim-files']);

function browserifyTask(options) {
  options = options || {};

  // XXX: I kind of hate this but couldn't figure out how to start the stream
  // with gulp.src and use the filenames it provides.
  var files = _.reduce(paths.jsEntries, function (allJsEntries, jsEntry) {
    return allJsEntries.concat(glob.sync(jsEntry));
  }, []);

  files = _.uniq(files);

  var browserifyOptions = {debug: true};

  if (options.development) {
    // Add watchify args
    _.extend(browserifyOptions, watchify.args);
  }

  var tasks = files.map(function (js) {
    var basename = 'bundle-' + path.basename(js, '.js');
    var output = basename + '.js';

    var bundler = browserify(js, browserifyOptions)
      .plugin('minifyify', {
        map: '/static/js/' + basename + '.map.json',
        output: './build/js/' + basename + '.map.json'
      });

    function bundle() {
      // Log when bundling starts
      bundleLogger.start(output);

      return bundler
        .bundle()
        .on('error', function (err) {
          console.error(err.toString());

          process.exit(1);
        })
        .pipe(source(basename + '.js'))
        .pipe(gulp.dest('./build/js'))
        .pipe(plugins.if(!args.production, plugins.livereload()));
    }

    if (options.development) {
      // Wrap with watchify and rebundle on changes
      bundler = watchify(bundler);

      // Rebundle on update
      bundler.on('update', bundle);

      bundleLogger.watch(output);
    }

    return bundle();
  });

  return mergeStream.apply(gulp, tasks);
}

// Browserify all of our JavaScript entry points
gulp.task('browserify', function () {
  browserifyTask();
});

// Watchify all of our JavaScript entry points
gulp.task('watchify', function () {
  browserifyTask({development: true});
});

gulp.task('postcss', function () {
  return gulp.src(paths.css)
    .pipe(plugins.postcss([precss()]))
    .pipe(plugins.cssnano())
    .pipe(plugins.rename({extname: '.css'}))
    .pipe(gulp.dest('./build/css'))
    .pipe(plugins.if(!args.production, plugins.livereload()));
});

// Run browserify on JS changes, postcss on css changes
gulp.task('watch', function () {
  gulp.watch(paths.css, ['postcss']);
});

gulp.task('livereload', function () {
  plugins.livereload.listen();
});

// Just build the files in ./build
gulp.task('build', ['frontend-files', 'postcss', 'browserify']);

// Build, livereload, and watch
gulp.task('default', ['frontend-files', 'postcss', 'watch', 'watchify', 'livereload']);
<commit_msg>drastically speed up gulp<commit_after>'use strict';

var _ = require('lodash');
var browserify = require('browserify');
var bundleLogger = require('./gulp/bundle-logger.js');
var glob = require('glob');
var gulp = require('gulp');
var mergeStream = require('merge-stream');
var path = require('path');
var precss = require('precss');
var rimraf = require('rimraf');
var source = require('vinyl-source-stream');
var watchify = require('watchify');

var plugins = require('gulp-load-plugins')();

var args = require('yargs').argv;

var paths = {
  js: [
    './static/js/**.js',
    './**/static/js/**.js'
  ],
  jsEntries: [
    './static/js/*.js',
    './**/static/js/*.js'
  ],
  css: [
    './static/css/**/*.scss',
    '!./static/css/**/_*.scss'
  ],
  python: [
    '**/*.py',
    '!**/migrations/*.py',
    '!./tmp/**/*.py',
    '!./node_modules/**/*.py'
  ],
  bootstrapFiles: [
    './node_modules/bootstrap/dist/css/bootstrap.css',
    './node_modules/bootstrap/dist/css/bootstrap.css.map',
    './node_modules/bootstrap/dist/css/bootstrap-theme.css',
    './node_modules/bootstrap/dist/css/bootstrap-theme.css.map'
  ],
  webshimFiles: [
    './node_modules/webshim/js-webshim/minified/shims/**/*'
  ]
};

// Clean up files
gulp.task('clean', function (cb) {
  rimraf('./build', cb);
});

// Lint JavaScript code
gulp.task('lint-js-eslint', function () {
  return gulp.src(paths.js)
    .pipe(plugins.eslint({
      useEslintrc: true,
      rulePaths: [
        path.join(process.env.HOME, '.eslint')
      ]
    }))
    .pipe(plugins.eslint.format());
});

gulp.task('lint-js-jscs', function () {
  return gulp.src(paths.js)
    .pipe(plugins.jscs());
});

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

// Lint Python code
gulp.task('lint-python', function () {
  var shellOptions = {ignoreErrors: true};

  return gulp.src(paths.python)
    .pipe(plugins.shell([
      'flake8 <%= file.path %> | awk \'$0="flake8: "$0\''
    ], shellOptions))
    .pipe(plugins.shell([
      'pylint --rcfile=.pylintrc -r no -f colorized <%= file.path %> ' +
        '--msg-template "{C}: {path}:{line}:{column} {msg} ({symbol})" ' +
        '| awk \'$0="pylint: "$0\''
    ], shellOptions))
    .pipe(plugins.shell([
      'pep257 <%= file.path %> 2>&1 | awk \'$0="pep257: "$0\''
    ], shellOptions));
});

gulp.task('lint', ['lint-js', 'lint-python']);

gulp.task('bootstrap-files', function () {
  return gulp.src(paths.bootstrapFiles)
    .pipe(gulp.dest('./build/vendor'));
});

gulp.task('webshim-files', function () {
  return gulp.src(paths.webshimFiles)
    .pipe(gulp.dest('./build/vendor/shims'));
});

// Collect Bootstrap and other frontend files
gulp.task('frontend-files', ['bootstrap-files', 'webshim-files']);

function browserifyTask(options) {
  options = options || {};

  // XXX: I kind of hate this but couldn't figure out how to start the stream
  // with gulp.src and use the filenames it provides.
  var files = _.reduce(paths.jsEntries, function (allJsEntries, jsEntry) {
    return allJsEntries.concat(glob.sync(jsEntry));
  }, []);

  files = _.uniq(files);

  var browserifyOptions = {debug: true};

  if (options.development) {
    // Add watchify args
    _.extend(browserifyOptions, watchify.args);
  }

  var tasks = files.map(function (js) {
    var basename = 'bundle-' + path.basename(js, '.js');
    var output = basename + '.js';

    var bundler = browserify(js, browserifyOptions)
      .plugin('minifyify', {
        map: '/static/js/' + basename + '.map.json',
        output: './build/js/' + basename + '.map.json'
      });

    function bundle() {
      // Log when bundling starts
      bundleLogger.start(output);

      return bundler
        .bundle()
        .on('error', function (err) {
          console.error(err.toString());

          process.exit(1);
        })
        .pipe(source(basename + '.js'))
        .pipe(gulp.dest('./build/js'))
        .pipe(plugins.if(!args.production, plugins.livereload()));
    }

    if (options.development) {
      // Wrap with watchify and rebundle on changes
      bundler = watchify(bundler);

      // Rebundle on update
      bundler.on('update', bundle);

      bundleLogger.watch(output);
    }

    return bundle();
  });

  return mergeStream.apply(gulp, tasks);
}

// Browserify all of our JavaScript entry points
gulp.task('browserify', function () {
  browserifyTask();
});

// Watchify all of our JavaScript entry points
gulp.task('watchify', ['frontend-files'], function () {
  browserifyTask({development: true});
});

gulp.task('postcss', function () {
  return gulp.src(paths.css)
    .pipe(plugins.postcss([precss()]))
    .pipe(plugins.cssnano())
    .pipe(plugins.rename({extname: '.css'}))
    .pipe(gulp.dest('./build/css'))
    .pipe(plugins.if(!args.production, plugins.livereload()));
});

// Run browserify on JS changes, postcss on css changes
gulp.task('watch', ['frontend-files'], function () {
  gulp.watch(paths.css, ['postcss']);
});

gulp.task('livereload', ['frontend-files'], function () {
  plugins.livereload.listen();
});

// Just build the files in ./build
gulp.task('build', ['frontend-files', 'postcss', 'browserify']);

// Build, livereload, and watch
gulp.task('default', [
  'frontend-files',
  'postcss',
  'watch',
  'watchify',
  'livereload'
]);
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp');
var autoprefixer = require('gulp-autoprefixer');
var sass = require('gulp-sass');
var rename = require('gulp-rename');
var sourcemaps = require('gulp-sourcemaps');
var csso = require('gulp-csso');
var csscomb = require('gulp-csscomb');
var del = require('del');
var basel = require('./package.json');

// Config
var build = {
	css: './dist/assets/css',
	scss: './src/scss/'
};

var minify = true;

var AUTOPREFIXER_BROWSERS = [
	'ie >= 11',
	'edge >= 20',
	'ff >= 40',
	'chrome >= 35',
	'safari >= 8',
	'opera >= 35',
	'ios >= 8'
];

var render = function (layer) {
	'use strict';

	var css = gulp
	.src(build.scss + layer + '.scss')
	.pipe(sourcemaps.init())
	.pipe(sass({
		precision: 10,
		onError: console.error.bind(console, 'Sass error:')
	}))
	.pipe(autoprefixer(AUTOPREFIXER_BROWSERS));

	if (minify) {
		css = css
		.pipe(csso())
		.pipe(rename({
			suffix: '.' + basel.version + '.min',
			extname: '.css'
		}));
	} else {
		css = css
		.pipe(csscomb());
	}

	css = css
	.pipe(sourcemaps.write('./'))
	.pipe(gulp.dest(build.css));

	return css;
};

gulp.task('core', function () {
	render('core');
});

gulp.task('utilities', function () {
	render('utilities');
});

gulp.task('clean', function () {
	del(['dist']);
});

gulp.task('watch', function () {
	gulp.watch('src/scss/*.scss', ['core', 'utilities']);
});

gulp.task('serve', ['watch']);
gulp.task('default', ['core', 'utilities', 'watch']);
<commit_msg>seperate minify out to always perform both funcs<commit_after>'use strict';

var gulp = require('gulp');
var autoprefixer = require('gulp-autoprefixer');
var sass = require('gulp-sass');
var rename = require('gulp-rename');
var sourcemaps = require('gulp-sourcemaps');
var csso = require('gulp-csso');
var csscomb = require('gulp-csscomb');
var del = require('del');
var pkg = require('./package.json');

// Config
var build = {
	css: './dist/assets/css',
	scss: './src/scss/'
};

var AUTOPREFIXER_BROWSERS = [
	'ie >= 11',
	'edge >= 20',
	'ff >= 40',
	'chrome >= 35',
	'safari >= 8',
	'opera >= 35',
	'ios >= 8'
];

var render = function (layer) {
	'use strict';

	var css = gulp
	.src(build.scss + layer + '.scss')
	.pipe(sourcemaps.init())
	.pipe(sass({
		precision: 10,
		onError: console.error.bind(console, 'Sass error:')
	}))
	.pipe(autoprefixer(AUTOPREFIXER_BROWSERS))
	.pipe(rename({
		suffix: '.' + pkg.version,
		extname: '.css'
	}))
	.pipe(sourcemaps.write('./'))
	.pipe(gulp.dest(build.css));

	return css;
};

gulp.task('core', function () {
	render('core');
});

gulp.task('utilities', function () {
	render('utilities');
});

gulp.task('clean', function () {
	del(['dist']);
});

gulp.task('minify', ['core', 'utilities'], function () {
	var css = gulp
	.src(build.css + '/*.' + pkg.version + '.css')
	.pipe(sourcemaps.init())
	.pipe(csso())
	.pipe(rename({
		suffix: '.min',
		extname: '.css'
	}))
	.pipe(sourcemaps.write('./'))
	.pipe(gulp.dest(build.css));

	return css;
});

gulp.task('watch', function () {
	gulp.watch('src/scss/**/*.scss', ['core', 'utilities', 'minify']);
});

gulp.task('serve', ['watch']);
gulp.task('default', ['core', 'utilities', 'minify', 'watch']);
<|endoftext|>


<commit_before>// ## Globals
var argv         = require('minimist')(process.argv.slice(2));
var autoprefixer = require('gulp-autoprefixer');
var browserSync  = require('browser-sync').create();
var changed      = require('gulp-changed');
var concat       = require('gulp-concat');
var flatten      = require('gulp-flatten');
var gulp         = require('gulp');
var gulpif       = require('gulp-if');
var imagemin     = require('gulp-imagemin');
var eslint       = require('gulp-eslint');
var lazypipe     = require('lazypipe');
var less         = require('gulp-less');
var merge        = require('merge-stream');
var minifyCss    = require('gulp-minify-css');
var plumber      = require('gulp-plumber');
var rev          = require('gulp-rev');
var runSequence  = require('run-sequence');
var sass         = require('gulp-sass');
var sourcemaps   = require('gulp-sourcemaps');
var uglify       = require('gulp-uglify');

// See https://github.com/austinpray/asset-builder
var manifest = require('asset-builder')('./assets/manifest.json');

// `path` - Paths to base asset directories. With trailing slashes.
// - `path.source` - Path to the source files. Default: `assets/`
// - `path.dist` - Path to the build directory. Default: `dist/`
var path = manifest.paths;

// `config` - Store arbitrary configuration values here.
var config = manifest.config || {};

// `globs` - These ultimately end up in their respective `gulp.src`.
// - `globs.js` - Array of asset-builder JS dependency objects. Example:
//   ```
//   {type: 'js', name: 'main.js', globs: []}
//   ```
// - `globs.css` - Array of asset-builder CSS dependency objects. Example:
//   ```
//   {type: 'css', name: 'main.css', globs: []}
//   ```
// - `globs.fonts` - Array of font path globs.
// - `globs.images` - Array of image path globs.
// - `globs.bower` - Array of all the main Bower files.
var globs = manifest.globs;

// `project` - paths to first-party assets.
// - `project.js` - Array of first-party JS assets.
// - `project.css` - Array of first-party CSS assets.
var project = manifest.getProjectGlobs();

// CLI options
var enabled = {
  // Enable static asset revisioning when `--production`
  rev: argv.production,
  // Disable source maps when `--production`
  maps: !argv.production,
  // Fail styles task on error when `--production`
  failStyleTask: argv.production,
  // Fail due to ESLint warnings only when `--production`
  failESLint: argv.production,
  // Strip debug statments from javascript when `--production`
  stripJSDebug: argv.production
};

// Path to the compiled assets manifest in the dist directory
var revManifest = path.dist + 'assets.json';

// ## Reusable Pipelines
// See https://github.com/OverZealous/lazypipe

// ### CSS processing pipeline
// Example
// ```
// gulp.src(cssFiles)
//   .pipe(cssTasks('main.css')
//   .pipe(gulp.dest(path.dist + 'styles'))
// ```
var cssTasks = function(filename) {
  return lazypipe()
    .pipe(function() {
      return gulpif(!enabled.failStyleTask, plumber());
    })
    .pipe(function() {
      return gulpif(enabled.maps, sourcemaps.init());
    })
    .pipe(function() {
      return gulpif('*.less', less());
    })
    .pipe(function() {
      return gulpif('*.scss', sass({
        outputStyle: 'nested', // libsass doesn't support expanded yet
        precision: 10,
        includePaths: ['.'],
        errLogToConsole: !enabled.failStyleTask
      }));
    })
    .pipe(concat, filename)
    .pipe(autoprefixer, {
      browsers: [
        'last 2 versions',
        'android 4',
        'opera 12'
      ]
    })
    .pipe(cssNano, {
      advanced: false,
      rebase: false
    })
    .pipe(function() {
      return gulpif(enabled.rev, rev());
    })
    .pipe(function() {
      return gulpif(enabled.maps, sourcemaps.write('.', {
        sourceRoot: 'assets/styles/'
      }));
    })();
};

// ### JS processing pipeline
// Example
// ```
// gulp.src(jsFiles)
//   .pipe(jsTasks('main.js')
//   .pipe(gulp.dest(path.dist + 'scripts'))
// ```
var jsTasks = function(filename) {
  return lazypipe()
    .pipe(function() {
      return gulpif(enabled.maps, sourcemaps.init());
    })
    .pipe(concat, filename)
    .pipe(uglify, {
      compress: {
        'drop_debugger': enabled.stripJSDebug
      }
    })
    .pipe(function() {
      return gulpif(enabled.rev, rev());
    })
    .pipe(function() {
      return gulpif(enabled.maps, sourcemaps.write('.', {
        sourceRoot: 'assets/scripts/'
      }));
    })();
};

// ### Write to rev manifest
// If there are any revved files then write them to the rev manifest.
// See https://github.com/sindresorhus/gulp-rev
var writeToManifest = function(directory) {
  return lazypipe()
    .pipe(gulp.dest, path.dist + directory)
    .pipe(browserSync.stream, {match: '**/*.{js,css}'})
    .pipe(rev.manifest, revManifest, {
      base: path.dist,
      merge: true
    })
    .pipe(gulp.dest, path.dist)();
};

// ## Gulp tasks
// Run `gulp -T` for a task summary

// ### Styles
// `gulp styles` - Compiles, combines, and optimizes Bower CSS and project CSS.
// By default this task will only log a warning if a precompiler error is
// raised. If the `--production` flag is set: this task will fail outright.
gulp.task('styles', ['wiredep'], function() {
  var merged = merge();
  manifest.forEachDependency('css', function(dep) {
    var cssTasksInstance = cssTasks(dep.name);
    if (!enabled.failStyleTask) {
      cssTasksInstance.on('error', function(err) {
        console.error(err.message);
        this.emit('end');
      });
    }
    merged.add(gulp.src(dep.globs, {base: 'styles'})
      .pipe(cssTasksInstance));
  });
  return merged
    .pipe(writeToManifest('styles'));
});

// ### Scripts
// `gulp scripts` - Runs ESLint then compiles, combines, and optimizes Bower JS
// and project JS.
gulp.task('scripts', ['lint'], function() {
  var merged = merge();
  manifest.forEachDependency('js', function(dep) {
    merged.add(
      gulp.src(dep.globs, {base: 'scripts'})
        .pipe(jsTasks(dep.name))
    );
  });
  return merged
    .pipe(writeToManifest('scripts'));
});

// ### Fonts
// `gulp fonts` - Grabs all the fonts and outputs them in a flattened directory
// structure. See: https://github.com/armed/gulp-flatten
gulp.task('fonts', function() {
  return gulp.src(globs.fonts)
    .pipe(flatten())
    .pipe(gulp.dest(path.dist + 'fonts'))
    .pipe(browserSync.stream());
});

// ### Images
// `gulp images` - Run lossless compression on all the images.
gulp.task('images', function() {
  return gulp.src(globs.images)
    .pipe(imagemin({
      progressive: true,
      interlaced: true,
      svgoPlugins: [{removeUnknownsAndDefaults: false}, {cleanupIDs: false}]
    }))
    .pipe(gulp.dest(path.dist + 'images'))
    .pipe(browserSync.stream());
});

// ### ESLint
// `gulp lint` - Lints configuration JSON and project JS.
gulp.task('lint', function() {
  return gulp.src([
    'gulpfile.js'
  ].concat(project.js))
    .pipe(eslint())
    .pipe(eslint.format())
    .pipe(gulpif(enabled.failESLint, eslint.failAfterError()));
});

// ### Clean
// `gulp clean` - Deletes the build folder entirely.
gulp.task('clean', require('del').bind(null, [path.dist]));

// ### Watch
// `gulp watch` - Use BrowserSync to proxy your dev server and synchronize code
// changes across devices. Specify the hostname of your dev server at
// `manifest.config.devUrl`. When a modification is made to an asset, run the
// build step for that asset and inject the changes into the page.
// See: http://www.browsersync.io
gulp.task('watch', function() {
  browserSync.init({
    files: ['{src,templates}/**/*.php'],
    proxy: config.devUrl,
    snippetOptions: {
      whitelist: ['/wp-admin/admin-ajax.php'],
      blacklist: ['/wp-admin/**']
    }
  });
  gulp.watch([path.source + 'styles/**/*'], ['styles']);
  gulp.watch([path.source + 'scripts/**/*'], ['lint', 'scripts']);
  gulp.watch([path.source + 'fonts/**/*'], ['fonts']);
  gulp.watch([path.source + 'images/**/*'], ['images']);
  gulp.watch(['bower.json', 'assets/manifest.json'], ['build']);
});

// ### Build
// `gulp build` - Run all the build tasks but don't clean up beforehand.
// Generally you should be running `gulp` instead of `gulp build`.
gulp.task('build', function(callback) {
  runSequence('styles',
              'scripts',
              ['fonts', 'images'],
              callback);
});

// ### Wiredep
// `gulp wiredep` - Automatically inject Less and Sass Bower dependencies. See
// https://github.com/taptapship/wiredep
gulp.task('wiredep', function() {
  var wiredep = require('wiredep').stream;
  return gulp.src(project.css)
    .pipe(wiredep())
    .pipe(changed(path.source + 'styles', {
      hasChanged: changed.compareSha1Digest
    }))
    .pipe(gulp.dest(path.source + 'styles'));
});

// ### Gulp
// `gulp` - Run a complete build. To compile for production run `gulp --production`.
gulp.task('default', ['clean'], function() {
  gulp.start('build');
});
<commit_msg>Missed during rebase<commit_after>// ## Globals
var argv         = require('minimist')(process.argv.slice(2));
var autoprefixer = require('gulp-autoprefixer');
var browserSync  = require('browser-sync').create();
var changed      = require('gulp-changed');
var concat       = require('gulp-concat');
var flatten      = require('gulp-flatten');
var gulp         = require('gulp');
var gulpif       = require('gulp-if');
var imagemin     = require('gulp-imagemin');
var eslint       = require('gulp-eslint');
var lazypipe     = require('lazypipe');
var less         = require('gulp-less');
var merge        = require('merge-stream');
var cssNano      = require('gulp-cssnano');
var plumber      = require('gulp-plumber');
var rev          = require('gulp-rev');
var runSequence  = require('run-sequence');
var sass         = require('gulp-sass');
var sourcemaps   = require('gulp-sourcemaps');
var uglify       = require('gulp-uglify');

// See https://github.com/austinpray/asset-builder
var manifest = require('asset-builder')('./assets/manifest.json');

// `path` - Paths to base asset directories. With trailing slashes.
// - `path.source` - Path to the source files. Default: `assets/`
// - `path.dist` - Path to the build directory. Default: `dist/`
var path = manifest.paths;

// `config` - Store arbitrary configuration values here.
var config = manifest.config || {};

// `globs` - These ultimately end up in their respective `gulp.src`.
// - `globs.js` - Array of asset-builder JS dependency objects. Example:
//   ```
//   {type: 'js', name: 'main.js', globs: []}
//   ```
// - `globs.css` - Array of asset-builder CSS dependency objects. Example:
//   ```
//   {type: 'css', name: 'main.css', globs: []}
//   ```
// - `globs.fonts` - Array of font path globs.
// - `globs.images` - Array of image path globs.
// - `globs.bower` - Array of all the main Bower files.
var globs = manifest.globs;

// `project` - paths to first-party assets.
// - `project.js` - Array of first-party JS assets.
// - `project.css` - Array of first-party CSS assets.
var project = manifest.getProjectGlobs();

// CLI options
var enabled = {
  // Enable static asset revisioning when `--production`
  rev: argv.production,
  // Disable source maps when `--production`
  maps: !argv.production,
  // Fail styles task on error when `--production`
  failStyleTask: argv.production,
  // Fail due to ESLint warnings only when `--production`
  failESLint: argv.production,
  // Strip debug statments from javascript when `--production`
  stripJSDebug: argv.production
};

// Path to the compiled assets manifest in the dist directory
var revManifest = path.dist + 'assets.json';

// ## Reusable Pipelines
// See https://github.com/OverZealous/lazypipe

// ### CSS processing pipeline
// Example
// ```
// gulp.src(cssFiles)
//   .pipe(cssTasks('main.css')
//   .pipe(gulp.dest(path.dist + 'styles'))
// ```
var cssTasks = function(filename) {
  return lazypipe()
    .pipe(function() {
      return gulpif(!enabled.failStyleTask, plumber());
    })
    .pipe(function() {
      return gulpif(enabled.maps, sourcemaps.init());
    })
    .pipe(function() {
      return gulpif('*.less', less());
    })
    .pipe(function() {
      return gulpif('*.scss', sass({
        outputStyle: 'nested', // libsass doesn't support expanded yet
        precision: 10,
        includePaths: ['.'],
        errLogToConsole: !enabled.failStyleTask
      }));
    })
    .pipe(concat, filename)
    .pipe(autoprefixer, {
      browsers: [
        'last 2 versions',
        'android 4',
        'opera 12'
      ]
    })
    .pipe(cssNano, {
      safe: true
    })
    .pipe(function() {
      return gulpif(enabled.rev, rev());
    })
    .pipe(function() {
      return gulpif(enabled.maps, sourcemaps.write('.', {
        sourceRoot: 'assets/styles/'
      }));
    })();
};

// ### JS processing pipeline
// Example
// ```
// gulp.src(jsFiles)
//   .pipe(jsTasks('main.js')
//   .pipe(gulp.dest(path.dist + 'scripts'))
// ```
var jsTasks = function(filename) {
  return lazypipe()
    .pipe(function() {
      return gulpif(enabled.maps, sourcemaps.init());
    })
    .pipe(concat, filename)
    .pipe(uglify, {
      compress: {
        'drop_debugger': enabled.stripJSDebug
      }
    })
    .pipe(function() {
      return gulpif(enabled.rev, rev());
    })
    .pipe(function() {
      return gulpif(enabled.maps, sourcemaps.write('.', {
        sourceRoot: 'assets/scripts/'
      }));
    })();
};

// ### Write to rev manifest
// If there are any revved files then write them to the rev manifest.
// See https://github.com/sindresorhus/gulp-rev
var writeToManifest = function(directory) {
  return lazypipe()
    .pipe(gulp.dest, path.dist + directory)
    .pipe(browserSync.stream, {match: '**/*.{js,css}'})
    .pipe(rev.manifest, revManifest, {
      base: path.dist,
      merge: true
    })
    .pipe(gulp.dest, path.dist)();
};

// ## Gulp tasks
// Run `gulp -T` for a task summary

// ### Styles
// `gulp styles` - Compiles, combines, and optimizes Bower CSS and project CSS.
// By default this task will only log a warning if a precompiler error is
// raised. If the `--production` flag is set: this task will fail outright.
gulp.task('styles', ['wiredep'], function() {
  var merged = merge();
  manifest.forEachDependency('css', function(dep) {
    var cssTasksInstance = cssTasks(dep.name);
    if (!enabled.failStyleTask) {
      cssTasksInstance.on('error', function(err) {
        console.error(err.message);
        this.emit('end');
      });
    }
    merged.add(gulp.src(dep.globs, {base: 'styles'})
      .pipe(cssTasksInstance));
  });
  return merged
    .pipe(writeToManifest('styles'));
});

// ### Scripts
// `gulp scripts` - Runs ESLint then compiles, combines, and optimizes Bower JS
// and project JS.
gulp.task('scripts', ['lint'], function() {
  var merged = merge();
  manifest.forEachDependency('js', function(dep) {
    merged.add(
      gulp.src(dep.globs, {base: 'scripts'})
        .pipe(jsTasks(dep.name))
    );
  });
  return merged
    .pipe(writeToManifest('scripts'));
});

// ### Fonts
// `gulp fonts` - Grabs all the fonts and outputs them in a flattened directory
// structure. See: https://github.com/armed/gulp-flatten
gulp.task('fonts', function() {
  return gulp.src(globs.fonts)
    .pipe(flatten())
    .pipe(gulp.dest(path.dist + 'fonts'))
    .pipe(browserSync.stream());
});

// ### Images
// `gulp images` - Run lossless compression on all the images.
gulp.task('images', function() {
  return gulp.src(globs.images)
    .pipe(imagemin({
      progressive: true,
      interlaced: true,
      svgoPlugins: [{removeUnknownsAndDefaults: false}, {cleanupIDs: false}]
    }))
    .pipe(gulp.dest(path.dist + 'images'))
    .pipe(browserSync.stream());
});

// ### ESLint
// `gulp lint` - Lints configuration JSON and project JS.
gulp.task('lint', function() {
  return gulp.src([
    'gulpfile.js'
  ].concat(project.js))
    .pipe(eslint())
    .pipe(eslint.format())
    .pipe(gulpif(enabled.failESLint, eslint.failAfterError()));
});

// ### Clean
// `gulp clean` - Deletes the build folder entirely.
gulp.task('clean', require('del').bind(null, [path.dist]));

// ### Watch
// `gulp watch` - Use BrowserSync to proxy your dev server and synchronize code
// changes across devices. Specify the hostname of your dev server at
// `manifest.config.devUrl`. When a modification is made to an asset, run the
// build step for that asset and inject the changes into the page.
// See: http://www.browsersync.io
gulp.task('watch', function() {
  browserSync.init({
    files: ['{src,templates}/**/*.php'],
    proxy: config.devUrl,
    snippetOptions: {
      whitelist: ['/wp-admin/admin-ajax.php'],
      blacklist: ['/wp-admin/**']
    }
  });
  gulp.watch([path.source + 'styles/**/*'], ['styles']);
  gulp.watch([path.source + 'scripts/**/*'], ['lint', 'scripts']);
  gulp.watch([path.source + 'fonts/**/*'], ['fonts']);
  gulp.watch([path.source + 'images/**/*'], ['images']);
  gulp.watch(['bower.json', 'assets/manifest.json'], ['build']);
});

// ### Build
// `gulp build` - Run all the build tasks but don't clean up beforehand.
// Generally you should be running `gulp` instead of `gulp build`.
gulp.task('build', function(callback) {
  runSequence('styles',
              'scripts',
              ['fonts', 'images'],
              callback);
});

// ### Wiredep
// `gulp wiredep` - Automatically inject Less and Sass Bower dependencies. See
// https://github.com/taptapship/wiredep
gulp.task('wiredep', function() {
  var wiredep = require('wiredep').stream;
  return gulp.src(project.css)
    .pipe(wiredep())
    .pipe(changed(path.source + 'styles', {
      hasChanged: changed.compareSha1Digest
    }))
    .pipe(gulp.dest(path.source + 'styles'));
});

// ### Gulp
// `gulp` - Run a complete build. To compile for production run `gulp --production`.
gulp.task('default', ['clean'], function() {
  gulp.start('build');
});
<|endoftext|>


<commit_before>'use strict';
// generated on 2014-09-24 using generator-gulp-webapp 0.1.0

var gulp = require('gulp');

// load plugins
var $ = require('gulp-load-plugins')();

gulp.task('styles', function () {
    return gulp.src('app/styles/main.css')
        .pipe($.autoprefixer('last 1 version'))
        .pipe(gulp.dest('.tmp/styles'))
        .pipe($.size());
});

gulp.task('scripts', function () {
    return gulp.src('app/scripts/**/*.js')
        .pipe($.jshint())
        .pipe($.jshint.reporter(require('jshint-stylish')))
        .pipe($.size());
});

gulp.task('html', ['styles', 'scripts'], function () {
    var jsFilter = $.filter('**/*.js');
    var cssFilter = $.filter('**/*.css');

    return gulp.src('app/*.html')
        .pipe($.useref.assets({searchPath: '{.tmp,app}'}))
        .pipe(jsFilter)
        .pipe($.uglify())
        .pipe(jsFilter.restore())
        .pipe(cssFilter)
        .pipe($.csso())
        .pipe(cssFilter.restore())
        .pipe($.useref.restore())
        .pipe($.useref())
        .pipe(gulp.dest('dist'))
        .pipe($.size());
});

gulp.task('images', function () {
    return gulp.src('app/images/**/*')
        .pipe($.cache($.imagemin({
            optimizationLevel: 3,
            progressive: true,
            interlaced: true
        })))
        .pipe(gulp.dest('dist/images'))
        .pipe($.size());
});

gulp.task('fonts', function () {
    return $.bowerFiles()
        .pipe($.filter('**/*.{eot,svg,ttf,woff}'))
        .pipe($.flatten())
        .pipe(gulp.dest('dist/fonts'))
        .pipe($.size());
});

gulp.task('extras', function () {
    return gulp.src(['app/*.*', '!app/*.html'], { dot: true })
        .pipe(gulp.dest('dist'));
});

gulp.task('clean', function () {
    return gulp.src(['.tmp', 'dist'], { read: false }).pipe($.clean());
});

gulp.task('build', ['html', 'images', 'fonts', 'extras']);

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

gulp.task('connect', function () {
    var connect = require('connect');
    var app = connect()
        .use(require('connect-livereload')({ port: 35729 }))
        .use(connect.static('app'))
        .use(connect.static('.tmp'))
        .use(connect.directory('app'));

    require('http').createServer(app)
        .listen(9000)
        .on('listening', function () {
            console.log('Started connect web server on http://localhost:9000');
        });
});

gulp.task('serve', ['connect'], function () {
    require('opn')('http://localhost:9000');
});

// inject bower components
gulp.task('wiredep', function () {
    var wiredep = require('wiredep').stream;

    gulp.src('app/*.html')
        .pipe(wiredep({
            directory: 'app/bower_components'
        }))
        .pipe(gulp.dest('app'));
});

gulp.task('watch', ['connect', 'serve'], function () {
    var server = $.livereload();

    // watch for changes

    gulp.watch([
        'app/**/*.html',
        '.tmp/styles/**/*.css',
        'app/scripts/**/*.js',
        'app/images/**/*'
    ]).on('change', function (file) {
        server.changed(file.path);
    });

    gulp.watch('app/styles/**/*.css', ['styles']);
    gulp.watch('app/scripts/**/*.js', ['scripts']);
    gulp.watch('app/images/**/*', ['images']);
    gulp.watch('bower.json', ['wiredep']);
});
<commit_msg>excluding discounts.js from jshint<commit_after>'use strict';
// generated on 2014-09-24 using generator-gulp-webapp 0.1.0

var gulp = require('gulp');

// load plugins
var $ = require('gulp-load-plugins')();
var condition = '!./**/discounts.js';

gulp.task('styles', function () {
    return gulp.src('app/styles/main.css')
        .pipe($.autoprefixer('last 1 version'))
        .pipe(gulp.dest('.tmp/styles'))
        .pipe($.size());
});

gulp.task('scripts', function () {
    return gulp.src(['app/scripts/**/*.js', condition])
        .pipe($.jshint())
        .pipe($.jshint.reporter(require('jshint-stylish')))
        .pipe($.size());
});

gulp.task('html', ['styles', 'scripts'], function () {
    var jsFilter = $.filter('**/*.js');
    var cssFilter = $.filter('**/*.css');

    return gulp.src('app/*.html')
        .pipe($.useref.assets({searchPath: '{.tmp,app}'}))
        .pipe(jsFilter)
        .pipe($.uglify())
        .pipe(jsFilter.restore())
        .pipe(cssFilter)
        .pipe($.csso())
        .pipe(cssFilter.restore())
        .pipe($.useref.restore())
        .pipe($.useref())
        .pipe(gulp.dest('dist'))
        .pipe($.size());
});

gulp.task('images', function () {
    return gulp.src('app/images/**/*')
        .pipe($.cache($.imagemin({
            optimizationLevel: 3,
            progressive: true,
            interlaced: true
        })))
        .pipe(gulp.dest('dist/images'))
        .pipe($.size());
});

gulp.task('fonts', function () {
    return $.bowerFiles()
        .pipe($.filter('**/*.{eot,svg,ttf,woff}'))
        .pipe($.flatten())
        .pipe(gulp.dest('dist/fonts'))
        .pipe($.size());
});

gulp.task('extras', function () {
    return gulp.src(['app/*.*', '!app/*.html'], { dot: true })
        .pipe(gulp.dest('dist'));
});

gulp.task('clean', function () {
    return gulp.src(['.tmp', 'dist'], { read: false }).pipe($.clean());
});

gulp.task('build', ['html', 'images', 'fonts', 'extras']);

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

gulp.task('connect', function () {
    var connect = require('connect');
    var app = connect()
        .use(require('connect-livereload')({ port: 35729 }))
        .use(connect.static('app'))
        .use(connect.static('.tmp'))
        .use(connect.directory('app'));

    require('http').createServer(app)
        .listen(9000)
        .on('listening', function () {
            console.log('Started connect web server on http://localhost:9000');
        });
});

gulp.task('serve', ['connect'], function () {
    require('opn')('http://localhost:9000');
});

// inject bower components
gulp.task('wiredep', function () {
    var wiredep = require('wiredep').stream;

    gulp.src('app/*.html')
        .pipe(wiredep({
            directory: 'app/bower_components'
        }))
        .pipe(gulp.dest('app'));
});

gulp.task('watch', ['connect', 'serve'], function () {
    var server = $.livereload();

    // watch for changes

    gulp.watch([
        'app/**/*.html',
        '.tmp/styles/**/*.css',
        'app/scripts/**/*.js',
        'app/images/**/*'
    ]).on('change', function (file) {
        server.changed(file.path);
    });

    gulp.watch('app/styles/**/*.css', ['styles']);
    gulp.watch('app/scripts/**/*.js', ['scripts']);
    gulp.watch('app/images/**/*', ['images']);
    gulp.watch('bower.json', ['wiredep']);
});
<|endoftext|>


<commit_before>var isProduction = process.argv.slice(-1)[0] === 'production',

    browserSync = require('browser-sync'),
    reload      = browserSync.reload,
    colors      = require('colors'),

    gulp        = require('gulp'),
    gulpif      = require('gulp-if'),

    concat      = require('gulp-concat'),
    insert      = require('gulp-insert'),
    uglify      = require('gulp-uglify'),
    es          = require('event-stream'),

    // Typescript
    typescript  = require('gulp-typescript'),
    tsConfig    = typescript.createProject('tsconfig.json', {
                      typescript: require('typescript')
                  }),

    // useful gulp debug
    print       = require('gulp-print')

    mocha       = require('gulp-spawn-mocha'),
    stylus      = require('gulp-stylus');

// - - - - - - - - - - - - - - - - - - - - - - - -
// - - - - - - - - - - STYLUS: - - - - - - - - - -
// - - - - - - - - - - - - - - - - - - - - - - - -
gulp.task('stylus', function() {
    gulp.src('./frontend/styl/*.styl')
        // склеиваем, чтобы подтянулись конфиги
        .pipe(concat('style.styl'))
        .pipe(stylus(
         // { use: ['nib'] }
        )) // собираем stylus
    .on('error', console.log) // Если есть ошибки, выводим и продолжаем
    .pipe(gulp.dest('./public/css/')) // записываем css
    .pipe(reload({stream: true}));
});

//TODO: можно собирать requirejs https://github.com/RobinThrift/gulp-requirejs
// - - - - - - - - - - - - - - - - - - - - - - - -
// - - - - - - -JS/TypeScript BUILD: - - - - - - -
// - - - - - - - - - - - - - - - - - - - - - - - -
gulp.task('js', function() {

    function ts() {
        return gulp.src('./frontend/js/modules/**/*.ts')
            .pipe(typescript(tsConfig))
            .on('error', function(e) { console.error(e.message); });
    }

    function js() {
        return gulp.src([
            './frontend/js/modules/**/*.js',
            '!*.test.js' // Dont build tests as modules
        ]);
    }

    return es.merge(ts(), js())
            .pipe(gulpif(isProduction, uglify()))
            .pipe(gulp.dest('./public/js/'))
            .pipe(reload({stream: true}));
});

// - - - - - - - - - - - - - - - - - - - - - - - -
// - - - - - - - - - - MAIN TASKS: - - - - - - - -
// - - - - - - - - - - - - - - - - - - - - - - - -

gulp.task('default', ['dev'], function() {});
gulp.task('dev', ['stylus', 'js'], function() {
    browserSync({
       proxy: "localhost:8080"
    });

    gulp.watch('./frontend/styl/*.styl', ['stylus']);
    gulp.watch('./frontend/js/**/*.js', ['js']).on('change', reload);
    gulp.watch('./frontend/js/**/*.ts', ['js']).on('change', reload);

    gulp.watch('./views/**/*.jade').on('change', reload);
});

gulp.task('production', ['stylus', 'js']);

console.log('Started as '.green + (isProduction ? 'production'.red : 'Dev'.blue ));

// - - - - - - - - - - - - - - - - - - - - - - - -
// - - - - - - - - - - - TEST RUNNING: - - - - - -
// - - - - - - - - - - - - - - - - - - - - - - - -
gulp.task('client-test', ['js'], function() {

    const commonTestsConfig = `
        'use strict';

        // Импорт зависимых библиотек
        let _ = require('lodash'),
            sinon = require('sinon'),
            {assert} = require('chai');

        let requirejs = require('requirejs');

        // Конфиг для require.
        requirejs.config({
            baseUrl: './public/js',
            nodeRequire: require
        });
    `;

    gulp.src('./frontend/js/**/*.test.js')
    // Подписываем файлы, чтобы удобнее было смотреть склеенный файл
    .pipe(insert.transform(function(contents, file) {
        var comment = `\n/* Test file path: ${file.path} */\n`;
        return comment + contents;
    }))
    .pipe(concat('all.test.js')) // TODO: gulp-insert
     // Подключаем конфиги для require(единоразово),
     // чтобы подключать файл по зависимостям из тестов
    .pipe(insert.prepend(commonTestsConfig))
    .pipe(gulp.dest('./tests/'))
    .pipe(mocha({
        reporter: 'nyan'
    }));

});
<commit_msg>gulpfile minor fix<commit_after>var isProduction = process.argv.slice(-1)[0] === 'production',

    browserSync = require('browser-sync'),
    reload      = browserSync.reload,
    colors      = require('colors'),

    gulp        = require('gulp'),
    gulpif      = require('gulp-if'),

    concat      = require('gulp-concat'),
    insert      = require('gulp-insert'),
    uglify      = require('gulp-uglify'),
    es          = require('event-stream'),

    // Typescript
    typescript  = require('gulp-typescript'),
    tsConfig    = typescript.createProject('tsconfig.json', {
                      typescript: require('typescript')
                  }),

    // useful gulp debug
    print       = require('gulp-print')

    mocha       = require('gulp-spawn-mocha'),
    stylus      = require('gulp-stylus');

// - - - - - - - - - - - - - - - - - - - - - - - -
// - - - - - - - - - - STYLUS: - - - - - - - - - -
// - - - - - - - - - - - - - - - - - - - - - - - -
gulp.task('stylus', function() {
    gulp.src('./frontend/styl/*.styl')
        // склеиваем, чтобы подтянулись конфиги
        .pipe(concat('style.styl'))
        .pipe(stylus(
         // { use: ['nib'] }
        )) // собираем stylus
    .on('error', console.log) // Если есть ошибки, выводим и продолжаем
    .pipe(gulp.dest('./public/css/')) // записываем css
    .pipe(reload({stream: true}));
});

//TODO: можно собирать requirejs https://github.com/RobinThrift/gulp-requirejs
// - - - - - - - - - - - - - - - - - - - - - - - -
// - - - - - - -JS/TypeScript BUILD: - - - - - - -
// - - - - - - - - - - - - - - - - - - - - - - - -
gulp.task('js', function() {

    function ts() {
        return gulp.src('./frontend/js/modules/**/*.ts')
            .pipe(typescript(tsConfig))
            .on('error', function(e) { console.error(e.message); });
    }

    function js() {
        return gulp.src([
            './frontend/js/modules/**/*.js',
            '!*.test.js' // Dont build tests as modules
        ]);
    }

    return es.merge(ts(), js())
            .pipe(gulpif(isProduction, uglify()))
            .pipe(gulp.dest('./public/js/'))
            .pipe(reload({stream: true}));
});

// - - - - - - - - - - - - - - - - - - - - - - - -
// - - - - - - - - - - MAIN TASKS: - - - - - - - -
// - - - - - - - - - - - - - - - - - - - - - - - -

gulp.task('default', ['dev'], function() {});
gulp.task('dev', ['stylus', 'js'], function() {
    browserSync({
       proxy: "localhost:8080"
    });

    gulp.watch('./frontend/styl/*.styl', ['stylus']);
    gulp.watch('./frontend/js/**/*.js', ['js']).on('change', reload);
    gulp.watch('./frontend/js/**/*.ts', ['js']).on('change', reload);

    gulp.watch('./views/**/*.jade').on('change', reload);
});

gulp.task('production', ['stylus', 'js']);

console.log('Started as '.green + (isProduction ? 'production'.red : 'Dev'.blue ));

// - - - - - - - - - - - - - - - - - - - - - - - -
// - - - - - - - - - - - TEST RUNNING: - - - - - -
// - - - - - - - - - - - - - - - - - - - - - - - -
gulp.task('client-test', ['js'], function() {

    const commonTestsConfig = `
        'use strict';

        // Импорт зависимых библиотек
        let _ = require('lodash'),
            sinon = require('sinon'),
            {assert} = require('chai');

        let requirejs = require('requirejs');

        // Конфиг для require.
        requirejs.config({
            baseUrl: './public/js',
            nodeRequire: require
        });
    `;

    gulp.src('./frontend/js/**/*.test.js')
    // Подписываем файлы, чтобы удобнее было смотреть склеенный файл
    .pipe(insert.transform(function(contents, file) {
        var comment = `\n/* Test file path: ${file.path} */\n`;
        return comment + contents;
    }))
    // Объединяем в один для того, чтобы единоразово подтянуть общий код для всех тестов
    .pipe(concat('all.test.js'))
     // Подключаем конфиги для require(единоразово),
     // чтобы подключать файл по зависимостям из тестов
    .pipe(insert.prepend(commonTestsConfig))
    .pipe(gulp.dest('./tests/'))
    .pipe(mocha({
        reporter: 'nyan'
    }));

});
<|endoftext|>