<commit_before>var pkg            = require('./package.json'),
    gulp           = require('gulp'),

    atImport       = require('postcss-import'),
    babel          = require('gulp-babel'),
    colorFunction  = require('postcss-color-function'),
    concat         = require('gulp-concat'),
    connect        = require('gulp-connect'),
    cssnext        = require("postcss-cssnext"),
    del            = require('del'),
    ghPages        = require('gulp-gh-pages'),
    imagemin       = require('gulp-imagemin'),
    jade           = require('gulp-jade'),
    lost           = require('lost'),
    nested         = require('postcss-nested'),
    mixins         = require('postcss-mixins'),
    plumber        = require('gulp-plumber'),
    postcss        = require('gulp-postcss'),
    runSequence    = require('run-sequence'),
    simplevars     = require('postcss-simple-vars'),
    sourcemaps     = require('gulp-sourcemaps'),
    uglify         = require('gulp-uglify');

var paths = {
  assets  : 'src/assets/**/*',
  cname   : 'src/CNAME',
  images  : 'src/images/**/*.{png,jpg,gif}',
  jade    : 'src/**/*.jade',
  scripts : 'src/script/**/*.js',
  lib     : '/src/_lib/**/*.js',
  css     : 'src/css/**/*.css',
  release : 'release/'
};

var locals = {
  title       : pkg.name,
  author      : pkg.author,
  description : pkg.description,
  version     : pkg.version
}

gulp.task('clean', function() {
  del(paths.release);
});

gulp.task('watch', function () {
  gulp.watch(paths.scripts, ['js:dev']);
  gulp.watch(paths.jade, ['html:dev']);
  gulp.watch(paths.css, ['css:dev']);
  gulp.watch(paths.images, ['imagemin:dev']);
  gulp.watch(paths.assets, ['assets']);
});

gulp.task('deploy', function() {
  gulp.src('./release/**/*')
    .pipe(ghPages());
});

gulp.task('assets', function() {
  return gulp.src(paths.assets)
    .pipe(plumber())
    .pipe(gulp.dest(paths.release + 'assets/'));
});

gulp.task('cname', function() {
  return gulp.src(paths.cname)
    .pipe(gulp.dest(paths.release));
});

gulp.task('connect:dev', function() {
  connect.server({
    root: paths.release,
    port: 8000,
    livereload: true
  });
});

gulp.task('connect:rel', function() {
  connect.server({
    root: paths.release,
    port: 8000
  });
});

gulp.task('css:dev', function() {
  return gulp.src([paths.css, '!**/_*.css'])
    .pipe(plumber())
      .pipe(sourcemaps.init())
    .pipe(postcss([
      atImport,
      mixins,
      simplevars,
      nested,
      lost,
      colorFunction,
      cssnext({
        browsers: ['last 1 version']
      })
    ]))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest(paths.release + 'css/'))
    .pipe(connect.reload());
});

gulp.task('css:rel', function() {
  return gulp.src([paths.css, '!**/_*.css'])
  .pipe(postcss([
    atImport,
    mixins,
    simplevars,
    nested,
    lost,
    colorFunction,
    cssnext({
      browsers: ['last 1 version'],
      compress: true
    })
  ]))
    .pipe(gulp.dest(paths.release + 'css/'))
});

gulp.task('html:dev', function() {
  return gulp.src([paths.jade, '!**/_*.jade'])
    .pipe(plumber())
    .pipe(jade({
      pretty: true,
      locals: locals
    }))
    .pipe(gulp.dest(paths.release))
    .pipe(connect.reload());
});

gulp.task('html:rel', function() {
  return gulp.src([paths.jade, '!**/_*.jade'])
    .pipe(jade({
      locals: locals
    }))
    .pipe(gulp.dest(paths.release))
});

gulp.task('imagemin:dev', function() {
  return gulp.src(paths.images)
    .pipe(plumber())
    .pipe(gulp.dest(paths.release + 'images/'))
});

gulp.task('imagemin:rel', function() {
  return gulp.src(paths.images)
    .pipe(imagemin())
    .pipe(gulp.dest(paths.release + 'images/'))
});

gulp.task('js:dev', function() {
  return gulp.src([paths.scripts, '!**/_*.js'])
    .pipe(plumber())
    .pipe(sourcemaps.init())
    .pipe(babel({
      presets: ['es2015']
    }))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest(paths.release + 'js/'))
    .pipe(connect.reload());
});

gulp.task('js:rel', function() {
  return gulp.src([paths.scripts, '!**/_*.js'])
    .pipe(babel({
      presets: ['es2015']
    }))
    .pipe(uglify())
    .pipe(gulp.dest(paths.release + 'js/'))
});

gulp.task('lib:dev', function() {
  return gulp.src([paths.lib, '!**/_*.js'])
    .pipe(sourcemaps.init())
    .pipe(concat('lib.js'))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest(paths.release + 'js/'))
});

gulp.task('lib:rel', function() {
  return gulp.src([paths.lib, '!**/_*.js'])
    .pipe(sourcemaps.init())
    .pipe(concat('lib.js'))
    .pipe(gulp.dest(paths.release + 'js/'))
});

// Start server in development mode
gulp.task('default', ['clean'], function() {
  runSequence([
      'html:dev',
      'css:dev',
      'js:dev',
      'lib:dev',
      'assets',
      'imagemin:dev',
    ], [
      'connect:dev',
      'watch'
    ]);
});

// Start server in preview mode
gulp.task('preview', ['clean'], function() {
  runSequence([
      'html:rel',
      'csss:rel',
      'js:rel',
      'lib:rel',
      'assets',
      'imagemin:rel',
    ],
    'connect:rel');
});

// Build optimized files
gulp.task('build', function() {
  runSequence('clean', [
    'html:rel',
    'css:rel',
    'js:rel',
    'lib:rel',
    'assets',
    'cname',
    'imagemin:rel'
  ])
});

// Deploy to GitHub Pages
gulp.task('shipit', function() {
  runSequence('build', 'deploy');
});
<commit_msg>Append root directory to Gulp paths<commit_after>var pkg            = require('./package.json'),
    gulp           = require('gulp'),

    atImport       = require('postcss-import'),
    babel          = require('gulp-babel'),
    colorFunction  = require('postcss-color-function'),
    concat         = require('gulp-concat'),
    connect        = require('gulp-connect'),
    cssnext        = require("postcss-cssnext"),
    del            = require('del'),
    ghPages        = require('gulp-gh-pages'),
    imagemin       = require('gulp-imagemin'),
    jade           = require('gulp-jade'),
    lost           = require('lost'),
    nested         = require('postcss-nested'),
    mixins         = require('postcss-mixins'),
    plumber        = require('gulp-plumber'),
    postcss        = require('gulp-postcss'),
    runSequence    = require('run-sequence'),
    simplevars     = require('postcss-simple-vars'),
    sourcemaps     = require('gulp-sourcemaps'),
    uglify         = require('gulp-uglify');

var paths = {
  assets  : __dirname + 'src/assets/**/*',
  cname   : __dirname + 'src/CNAME',
  images  : __dirname + 'src/images/**/*.{png,jpg,gif}',
  jade    : __dirname + 'src/**/*.jade',
  scripts : __dirname + 'src/script/**/*.js',
  lib     : __dirname + '/src/_lib/**/*.js',
  css     : __dirname + 'src/css/**/*.css',
  release : __dirname + 'release/'
};

var locals = {
  title       : pkg.name,
  author      : pkg.author,
  description : pkg.description,
  version     : pkg.version
}

gulp.task('clean', function() {
  del(paths.release);
});

gulp.task('watch', function () {
  gulp.watch(paths.scripts, ['js:dev']);
  gulp.watch(paths.jade, ['html:dev']);
  gulp.watch(paths.css, ['css:dev']);
  gulp.watch(paths.images, ['imagemin:dev']);
  gulp.watch(paths.assets, ['assets']);
});

gulp.task('deploy', function() {
  gulp.src('./release/**/*')
    .pipe(ghPages());
});

gulp.task('assets', function() {
  return gulp.src(paths.assets)
    .pipe(plumber())
    .pipe(gulp.dest(paths.release + 'assets/'));
});

gulp.task('cname', function() {
  return gulp.src(paths.cname)
    .pipe(gulp.dest(paths.release));
});

gulp.task('connect:dev', function() {
  connect.server({
    root: paths.release,
    port: 8000,
    livereload: true
  });
});

gulp.task('connect:rel', function() {
  connect.server({
    root: paths.release,
    port: 8000
  });
});

gulp.task('css:dev', function() {
  return gulp.src([paths.css, '!**/_*.css'])
    .pipe(plumber())
      .pipe(sourcemaps.init())
    .pipe(postcss([
      atImport,
      mixins,
      simplevars,
      nested,
      lost,
      colorFunction,
      cssnext({
        browsers: ['last 1 version']
      })
    ]))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest(paths.release + 'css/'))
    .pipe(connect.reload());
});

gulp.task('css:rel', function() {
  return gulp.src([paths.css, '!**/_*.css'])
  .pipe(postcss([
    atImport,
    mixins,
    simplevars,
    nested,
    lost,
    colorFunction,
    cssnext({
      browsers: ['last 1 version'],
      compress: true
    })
  ]))
    .pipe(gulp.dest(paths.release + 'css/'))
});

gulp.task('html:dev', function() {
  return gulp.src([paths.jade, '!**/_*.jade'])
    .pipe(plumber())
    .pipe(jade({
      pretty: true,
      locals: locals
    }))
    .pipe(gulp.dest(paths.release))
    .pipe(connect.reload());
});

gulp.task('html:rel', function() {
  return gulp.src([paths.jade, '!**/_*.jade'])
    .pipe(jade({
      locals: locals
    }))
    .pipe(gulp.dest(paths.release))
});

gulp.task('imagemin:dev', function() {
  return gulp.src(paths.images)
    .pipe(plumber())
    .pipe(gulp.dest(paths.release + 'images/'))
});

gulp.task('imagemin:rel', function() {
  return gulp.src(paths.images)
    .pipe(imagemin())
    .pipe(gulp.dest(paths.release + 'images/'))
});

gulp.task('js:dev', function() {
  return gulp.src([paths.scripts, '!**/_*.js'])
    .pipe(plumber())
    .pipe(sourcemaps.init())
    .pipe(babel({
      presets: ['es2015']
    }))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest(paths.release + 'js/'))
    .pipe(connect.reload());
});

gulp.task('js:rel', function() {
  return gulp.src([paths.scripts, '!**/_*.js'])
    .pipe(babel({
      presets: ['es2015']
    }))
    .pipe(uglify())
    .pipe(gulp.dest(paths.release + 'js/'))
});

gulp.task('lib:dev', function() {
  return gulp.src([paths.lib, '!**/_*.js'])
    .pipe(sourcemaps.init())
    .pipe(concat('lib.js'))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest(paths.release + 'js/'))
});

gulp.task('lib:rel', function() {
  return gulp.src([paths.lib, '!**/_*.js'])
    .pipe(sourcemaps.init())
    .pipe(concat('lib.js'))
    .pipe(gulp.dest(paths.release + 'js/'))
});

// Start server in development mode
gulp.task('default', ['clean'], function() {
  runSequence([
      'html:dev',
      'css:dev',
      'js:dev',
      'lib:dev',
      'assets',
      'imagemin:dev',
    ], [
      'connect:dev',
      'watch'
    ]);
});

// Start server in preview mode
gulp.task('preview', ['clean'], function() {
  runSequence([
      'html:rel',
      'csss:rel',
      'js:rel',
      'lib:rel',
      'assets',
      'imagemin:rel',
    ],
    'connect:rel');
});

// Build optimized files
gulp.task('build', function() {
  runSequence('clean', [
    'html:rel',
    'css:rel',
    'js:rel',
    'lib:rel',
    'assets',
    'cname',
    'imagemin:rel'
  ])
});

// Deploy to GitHub Pages
gulp.task('shipit', function() {
  runSequence('build', 'deploy');
});
<|endoftext|>


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

// plugins
var jshint = require('gulp-jshint');
var jscs = require('gulp-jscs');
var argv   = require('yargs').argv;
var gulpIgnore = require('gulp-ignore');

var filesJSToScan =  (argv.js ? argv.js : 'src/**/*.js');
var filesJSToIgnore = [
    '**/*jquery*',
    '**/*min*',
    '**/wowslider*',
    '**/wowSlider/engine1/script.js',
    '**/js/bootstrap.js',
    '**/js/wowSliderForm.js'
];

gulp.task('jscs', function () {
    return gulp.src(filesJSToScan)
        .pipe(gulpIgnore.exclude(filesJSToIgnore))
        .pipe(jscs());
});

gulp.task('jshint', function () {
    gulp.src(filesJSToScan)
        .pipe(gulpIgnore.exclude(filesJSToIgnore))
        .pipe(jshint())
        .pipe(jshint.reporter('default'));
});

gulp.task('default',
    ['jshint', 'jscs']
);
<commit_msg>Delete non present ignore files from gulp parsing<commit_after>// gulp
var gulp = require('gulp');

// plugins
var jshint = require('gulp-jshint');
var jscs = require('gulp-jscs');
var argv   = require('yargs').argv;
var gulpIgnore = require('gulp-ignore');

var filesJSToScan =  (argv.js ? argv.js : 'src/**/*.js');
var filesJSToIgnore = [
];

gulp.task('jscs', function () {
    return gulp.src(filesJSToScan)
        .pipe(gulpIgnore.exclude(filesJSToIgnore))
        .pipe(jscs());
});

gulp.task('jshint', function () {
    gulp.src(filesJSToScan)
        .pipe(gulpIgnore.exclude(filesJSToIgnore))
        .pipe(jshint())
        .pipe(jshint.reporter('default'));
});

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


<commit_before>var fs        = require('fs');
var path      = require('path');
var jshint    = require('gulp-jshint');
var stylish   = require('jshint-stylish');
var concat    = require('gulp-concat');
var uglify    = require('gulp-uglify');
var imagemin  = require('gulp-imagemin');
var sourcemaps = require('gulp-sourcemaps');
var notify    = require('gulp-notify');
var rename    = require('gulp-rename');
var cache     = require('gulp-cache');
var minifycss = require('gulp-minify-css');
var less      = require('gulp-less');
var path      = require('path');
var browserSync = require('browser-sync').create();
var reload = browserSync.reload;
var webserver = require('gulp-webserver');
var plumber   = require('gulp-plumber');
var gutil = require('gulp-util');
var filesize = require('gulp-filesize');
var beep = require('beepbeep');
var gulp      = require('gulp');
var Server = require('karma').Server;
var plugins   = require('gulp-load-plugins')(); // Load all gulp plugins
                                              // automatically and attach
                                              // them to the `plugins` object

var runSequence = require('run-sequence');    // Temporary solution until gulp 4
                                              // https://github.com/gulpjs/gulp/issues/355

var pkg  = require('./package.json');
var dirs = pkg['h5bp-configs'].directories;

//Beep Error Messaging + Red Coloring FTW.
var onError = function (err) {
    beep([1000, 500, 1500]);
    gutil.log(gutil.colors.red(err));
};

// ---------------------------------------------------------------------
// | Helper tasks                                                      |
// ---------------------------------------------------------------------

gulp.task('archive:create_archive_dir', function () {
    fs.mkdirSync(path.resolve(dirs.archive), '0755');
});

gulp.task('archive:zip', function (done) {

    var archiveName = path.resolve(dirs.archive, pkg.name + '_v' + pkg.version + '.zip');
    var archiver = require('archiver')('zip');
    var files = require('glob').sync('**/*.*', {
        'cwd': dirs.dist,
        'dot': true // include hidden files
    });
    var output = fs.createWriteStream(archiveName);

    archiver.on('error', function (error) {
        done();
        throw error;
    });

    output.on('close', done);

    files.forEach(function (file) {

        var filePath = path.resolve(dirs.dist, file);

        // `archiver.bulk` does not maintain the file
        // permissions, so we need to add files individually
        archiver.append(fs.createReadStream(filePath), {
            'name': file,
            'mode': fs.statSync(filePath)
        });

    });

    archiver.pipe(output);
    archiver.finalize();

});

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

gulp.task('copy', [
    'copy:.htaccess',
    'copy:index.html',
    'copy:jquery',
    'copy:license',
    'copy:main.css',
    'copy:misc',
    'copy:normalize'
]);

gulp.task('copy:.htaccess', function () {
    return gulp.src('node_modules/apache-server-configs/dist/.htaccess')
               .pipe(plugins.replace(/# ErrorDocument/g, 'ErrorDocument'))
               .pipe(gulp.dest(dirs.dist));
});

gulp.task('copy:index.html', function () {
    return gulp.src(dirs.src + '/index.html')
               .pipe(plugins.replace(/{{JQUERY_VERSION}}/g, pkg.devDependencies.jquery))
               .pipe(gulp.dest(dirs.dist));
});

gulp.task('copy:jquery', function () {
    return gulp.src(['node_modules/jquery/dist/jquery.min.js'])
               .pipe(plugins.rename('jquery-' + pkg.devDependencies.jquery + '.min.js'))
               .pipe(gulp.dest(dirs.dist + '/js/vendor'));
});

gulp.task('copy:license', function () {
    return gulp.src('LICENSE.txt')
               .pipe(gulp.dest(dirs.dist));
});

gulp.task('copy:main.css', function () {

    var banner = '/*! HTML5 Boilerplate v' + pkg.version +
                    ' | ' + pkg.license.type + ' License' +
                    ' | ' + pkg.homepage + ' */\n\n';

    return gulp.src(dirs.src + '/css/main.css')
               .pipe(plugins.header(banner))
               .pipe(plugins.autoprefixer({
                   browsers: ['last 2 versions', 'ie >= 8', '> 1%'],
                   cascade: false
               }))
               .pipe(gulp.dest(dirs.dist + '/css'));
});

gulp.task('copy:misc', function () {
    return gulp.src([

        // Copy all files
        dirs.src + '/**/*',

        // Exclude the following files
        // (other tasks will handle the copying of these files)
        '!' + dirs.src + '/css/main.css',
        '!' + dirs.src + '/index.html'

    ], {

        // Include hidden files by default
        dot: true

    }).pipe(gulp.dest(dirs.dist));
});

gulp.task('copy:normalize', function () {
    return gulp.src('node_modules/normalize.css/normalize.css')
               .pipe(gulp.dest(dirs.dist + '/css'));
});

gulp.task('lint:js', function () {
    return gulp.src([
        'gulpfile.js',
        dirs.src + '/app/**/*.js'
    ]).pipe(plugins.jscs())
      .pipe(plugins.jshint())
      .pipe(plugins.jshint.reporter('jshint-stylish'))
      .pipe(plugins.jshint.reporter('fail'));
});

gulp.task('webserver', function () {
    gulp.src('src')
    .pipe(webserver({
        livereload: true,
        directoryListing: false,
        open: true
    }));
});

gulp.task('jshint', function () {
    return gulp.src('src/app/**/*.js')
    .pipe(plumber())
    .pipe(jshint('.jshintrc'))
    .pipe(jshint.reporter('jshint-stylish'))
    .pipe(jshint.reporter('fail'))
    .pipe(plumber({errorHandler: onError}))
    .pipe(concat('main.js'))
    .pipe(gulp.dest('dist/js'))
    .pipe(filesize())
    .pipe(rename({suffix: '.min'}))
    .pipe(uglify())
    .pipe(gulp.dest('dist/js'))
    .pipe(filesize())
    .pipe(browserSync.stream({stream:true}))
    .pipe(notify({ message: 'Jshint task complete'}))
    .on('error', gutil.log);
});

gulp.task('less', function () {
    return gulp.src('src/less/main.less')
    .pipe(plumber({errorHandler: onError}))
    .pipe(sourcemaps.init())
    .pipe(less())
    .pipe(sourcemaps.write())
    .pipe(gulp.dest('src/css'))
    .pipe(filesize())
    .pipe(rename({suffix: '.min'}))
    .pipe(minifycss())
    .pipe(gulp.dest('dist/css'))
    .pipe(filesize())
    .pipe(browserSync.stream({stream:true}))
    .pipe(notify({ message: 'Less task complete'}))
    .on('error', gutil.log);
});

gulp.task('images', function () {
    return gulp.src('src/img/**/*')
    .pipe(plumber({errorHandler: onError}))
    .pipe(cache(imagemin({ optimizationLevel: 5, progressive: true, interlaced: true })))
    .pipe(gulp.dest('dist/img'))
    .pipe(browserSync.stream({stream:true}))
    .pipe(notify({ message: 'Image task complete'}));
});

gulp.task('html', function (){
    return gulp.src('src/**/*.html')
    .pipe(plumber({errorHandler: onError}))
    .pipe(gulp.dest('dist/'))
    .pipe(browserSync.stream({stream:true}))
    .pipe(notify({ message: 'Html task complete'}));
});

gulp.slurped = false; //step 1

gulp.task('watch', function () {
    if(!gulp.slurped){ //step 2
        gulp.watch('src/img/**/*', ['images'], browserSync.reload);
        gulp.watch('src/app/**/*.js', ['jshint'], browserSync.reload);
        gulp.watch('src/less/*.less', ['less'], browserSync.reload);
        gulp.watch('src/**/*.html', ['html'], browserSync.reload);
        gulp.watch('src/**/*.html').on('change', browserSync.reload);
        gulp.slurped = true; //step 3
    }
});

gulp.task('serve', ['images', 'jshint', 'html', 'less'], function () {
     browserSync.init({
        server: {
            baseDir: "src/.",
            open: "local",
            browser: "google chrome"
        }
    });
});

// ---------------------------------------------------------------------
// | Main tasks                                                        |
// ---------------------------------------------------------------------
gulp.task('test', function (done) {
  new Server({
    configFile: __dirname + '/karma.conf.js',
    singleRun: false
  }, done).start();
});

gulp.task('archive', function (done) {
    runSequence(
        'build',
        'archive:create_archive_dir',
        'archive:zip',
    done);
});

gulp.task('build', ['images', 'jshint', 'less', 'html']);

gulp.task('default', ['clean'], function(){
    gulp.start('serve','watch', browserSync.reload);
});
<commit_msg>Master - Added made references call tasks instead of actual<commit_after>var fs        = require('fs');
var path      = require('path');
var jshint    = require('gulp-jshint');
var stylish   = require('jshint-stylish');
var concat    = require('gulp-concat');
var uglify    = require('gulp-uglify');
var imagemin  = require('gulp-imagemin');
var sourcemaps = require('gulp-sourcemaps');
var notify    = require('gulp-notify');
var rename    = require('gulp-rename');
var cache     = require('gulp-cache');
var minifycss = require('gulp-minify-css');
var less      = require('gulp-less');
var path      = require('path');
var browserSync = require('browser-sync').create();
var reload = browserSync.reload;
var webserver = require('gulp-webserver');
var plumber   = require('gulp-plumber');
var gutil = require('gulp-util');
var filesize = require('gulp-filesize');
var beep = require('beepbeep');
var gulp      = require('gulp');
var Server = require('karma').Server;
var plugins   = require('gulp-load-plugins')(); // Load all gulp plugins
                                              // automatically and attach
                                              // them to the `plugins` object

var runSequence = require('run-sequence');    // Temporary solution until gulp 4
                                              // https://github.com/gulpjs/gulp/issues/355

var pkg  = require('./package.json');
var dirs = pkg['h5bp-configs'].directories;

//Beep Error Messaging + Red Coloring FTW.
var onError = function (err) {
    beep([1000, 500, 1500]);
    gutil.log(gutil.colors.red(err));
};

// ---------------------------------------------------------------------
// | Helper tasks                                                      |
// ---------------------------------------------------------------------

gulp.task('archive:create_archive_dir', function () {
    fs.mkdirSync(path.resolve(dirs.archive), '0755');
});

gulp.task('archive:zip', function (done) {

    var archiveName = path.resolve(dirs.archive, pkg.name + '_v' + pkg.version + '.zip');
    var archiver = require('archiver')('zip');
    var files = require('glob').sync('**/*.*', {
        'cwd': dirs.dist,
        'dot': true // include hidden files
    });
    var output = fs.createWriteStream(archiveName);

    archiver.on('error', function (error) {
        done();
        throw error;
    });

    output.on('close', done);

    files.forEach(function (file) {

        var filePath = path.resolve(dirs.dist, file);

        // `archiver.bulk` does not maintain the file
        // permissions, so we need to add files individually
        archiver.append(fs.createReadStream(filePath), {
            'name': file,
            'mode': fs.statSync(filePath)
        });

    });

    archiver.pipe(output);
    archiver.finalize();

});

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

gulp.task('copy', [
    'copy:.htaccess',
    'copy:index.html',
    'copy:jquery',
    'copy:license',
    'copy:main.css',
    'copy:misc',
    'copy:normalize'
]);

gulp.task('copy:.htaccess', function () {
    return gulp.src('node_modules/apache-server-configs/dist/.htaccess')
               .pipe(plugins.replace(/# ErrorDocument/g, 'ErrorDocument'))
               .pipe(gulp.dest(dirs.dist));
});

gulp.task('copy:index.html', function () {
    return gulp.src(dirs.src + '/index.html')
               .pipe(plugins.replace(/{{JQUERY_VERSION}}/g, pkg.devDependencies.jquery))
               .pipe(gulp.dest(dirs.dist));
});

gulp.task('copy:jquery', function () {
    return gulp.src(['node_modules/jquery/dist/jquery.min.js'])
               .pipe(plugins.rename('jquery-' + pkg.devDependencies.jquery + '.min.js'))
               .pipe(gulp.dest(dirs.dist + '/js/vendor'));
});

gulp.task('copy:license', function () {
    return gulp.src('LICENSE.txt')
               .pipe(gulp.dest(dirs.dist));
});

gulp.task('copy:main.css', function () {

    var banner = '/*! HTML5 Boilerplate v' + pkg.version +
                    ' | ' + pkg.license.type + ' License' +
                    ' | ' + pkg.homepage + ' */\n\n';

    return gulp.src(dirs.src + '/css/main.css')
               .pipe(plugins.header(banner))
               .pipe(plugins.autoprefixer({
                   browsers: ['last 2 versions', 'ie >= 8', '> 1%'],
                   cascade: false
               }))
               .pipe(gulp.dest(dirs.dist + '/css'));
});

gulp.task('copy:misc', function () {
    return gulp.src([

        // Copy all files
        dirs.src + '/**/*',

        // Exclude the following files
        // (other tasks will handle the copying of these files)
        '!' + dirs.src + '/css/main.css',
        '!' + dirs.src + '/index.html'

    ], {

        // Include hidden files by default
        dot: true

    }).pipe(gulp.dest(dirs.dist));
});

gulp.task('copy:normalize', function () {
    return gulp.src('node_modules/normalize.css/normalize.css')
               .pipe(gulp.dest(dirs.dist + '/css'));
});

gulp.task('lint:js', function () {
    return gulp.src([
        'gulpfile.js',
        dirs.src + '/app/**/*.js'
    ]).pipe(plugins.jscs())
      .pipe(plugins.jshint())
      .pipe(plugins.jshint.reporter(stylish))
      .pipe(plugins.jshint.reporter('fail'));
});

gulp.task('webserver', function () {
    gulp.src('src')
    .pipe(webserver({
        livereload: true,
        directoryListing: false,
        open: true
    }));
});

gulp.task('jshint', function () {
    return gulp.src('src/app/**/*.js')
    .pipe(plumber())
    .pipe(jshint('.jshintrc'))
    .pipe(jshint.reporter(stylish))
    .pipe(jshint.reporter('fail'))
    .pipe(plumber({errorHandler: onError}))
    .pipe(concat('main.js'))
    .pipe(gulp.dest('dist/js'))
    .pipe(filesize())
    .pipe(rename({suffix: '.min'}))
    .pipe(uglify())
    .pipe(gulp.dest('dist/js'))
    .pipe(filesize())
    .pipe(browserSync.stream({stream:true}))
    .pipe(notify({ message: 'Jshint task complete'}))
    .on('error', gutil.log);
});

gulp.task('less', function () {
    return gulp.src('src/less/main.less')
    .pipe(plumber({errorHandler: onError}))
    .pipe(sourcemaps.init())
    .pipe(less())
    .pipe(sourcemaps.write())
    .pipe(gulp.dest('src/css'))
    .pipe(filesize())
    .pipe(rename({suffix: '.min'}))
    .pipe(minifycss())
    .pipe(gulp.dest('dist/css'))
    .pipe(filesize())
    .pipe(browserSync.stream({stream:true}))
    .pipe(notify({ message: 'Less task complete'}))
    .on('error', gutil.log);
});

gulp.task('images', function () {
    return gulp.src('src/img/**/*')
    .pipe(plumber({errorHandler: onError}))
    .pipe(cache(imagemin({ optimizationLevel: 5, progressive: true, interlaced: true })))
    .pipe(gulp.dest('dist/img'))
    .pipe(browserSync.stream({stream:true}))
    .pipe(notify({ message: 'Image task complete'}));
});

gulp.task('html', function (){
    return gulp.src('src/**/*.html')
    .pipe(plumber({errorHandler: onError}))
    .pipe(gulp.dest('dist/'))
    .pipe(browserSync.stream({stream:true}))
    .pipe(notify({ message: 'Html task complete'}));
});

//watches the gulpfile as its running as well
gulp.slurped = false; //step 1

gulp.task('watch', function () {
    if(!gulp.slurped){ //step 2
        gulp.watch('src/img/**/*', ['images'], reload);
        gulp.watch('src/app/**/*.js', ['jshint'], reload);
        gulp.watch('src/less/*.less', ['less'], reload);
        gulp.watch('src/**/*.html', ['html'], reload);
        gulp.watch('src/**/*.html').on('change', reload);
        gulp.slurped = true; //step 3
    }
});

gulp.task('serve', ['images', 'jshint', 'html', 'less'], function () {
     browserSync.init({
        server: {
            baseDir: "src/.",
            open: "local",
            browser: "google chrome"
        }
    });
});

// ---------------------------------------------------------------------
// | Main tasks                                                        |
// ---------------------------------------------------------------------
gulp.task('test', function (done) {
  new Server({
    configFile: __dirname + '/karma.conf.js',
    singleRun: false
  }, done).start();
});

gulp.task('archive', function (done) {
    runSequence(
        'build',
        'archive:create_archive_dir',
        'archive:zip',
    done);
});

gulp.task('build', ['images', 'jshint', 'less', 'html']);

gulp.task('default', ['clean'], function(){
    gulp.start('serve','watch', reload);
});
<|endoftext|>


<commit_before>// Require babel hook included to load all subsequent files required by
// gulp with the extensions .es6, .es, .jsx, .js and transpile them
// with babel. This will also automatically require the polyfill.
require("babel-register");

// Load gulp configuration
var conf = require('./config/gulpfile.conf.js');

// ```
// gulpfile.js
// (c) 2016 David Newman
// david.r.niciforovic@gmail.com
// gulpfile.js may be freely distributed under the MIT license
// ```
<commit_msg>working<commit_after>// Require babel hook included to load all subsequent files required by
// gulp with the extensions .es6, .es, .jsx, .js and transpile them
// with babel. This will also automatically require the polyfill.
require("babel-register");

// Load gulp configuration
var conf = require('./config/gulpfile.conf.js');
<|endoftext|>


<commit_before>'use strict';

const _ = require('lodash');
const gulp = require('gulp');
const babel = require('gulp-babel');
const clean = require('gulp-clean');
const less = require('gulp-less');
const cssmin = require('gulp-cssmin');
const concat = require('gulp-concat');
const packager = require('electron-packager');
const spawn = require('child_process').spawn;
const exec = require('child_process').exec;
const replace = require('gulp-replace');

const grunt = require('gulp-grunt');

const paths = {
  internalScripts: ['src/**/*.js'],
  externalScripts: ['node_modules/gmusic.js/dist/gmusic.min.js',
                    'node_modules/gmusic-theme.js/dist/gmusic-theme.min.js',
                    'node_modules/gmusic-mini-player.js/dist/gmusic-mini-player.min.js'],
  utilityScripts: ['node_modules/jquery/dist/jquery.min.js',
                    'node_modules/materialize-css/dist/js/materialize.min.js',
                    'node_modules/materialize-css/extras/noUiSlider/nouislider.min.js'],
  html: 'src/public_html/**/*.html',
  less: 'src/assets/less/**/*.less',
  fonts: ['node_modules/materialize-css/dist/font/**/*',
          '!node_modules/materialize-css/dist/font/material-design-icons/*',
          'node_modules/material-design-icons-iconfont/dist/fonts/**/*'],
  images: ['src/assets/icons/**/*', 'src/assets/img/**/*'],
};

const packageJSON = require('./package.json');
let version = packageJSON.dependencies['electron-prebuilt'];
if (version.substr(0, 1) !== '0') {
  version = version.substr(1);
}

const defaultPackageConf = {
  dir: '.',
  name: packageJSON.productName,
  'build-version': packageJSON.version,
  version,
  platform: 'all',
  arch: 'all',
  'app-bundle-id': packageJSON.name,
  'app-version': packageJSON.version,
  icon: './build/assets/img/main',
  out: './dist/',
  overwrite: true,
  prune: true,
  ignore: 'dist/.*',
  'version-string': {
    CompanyName: 'Samuel Attard',
    LegalCopyright: 'Copyright © 2016 Samuel Attard, All rights reserved.',
    FileDescription: 'Google Play Music Desktop Player by Samuel Attard',
    ProductName: 'Google Play Music Desktop Player',
    InternalName: 'Google Play Music Desktop Player',
  },
};

const cleanGlob = (glob) => {
  return () => {
    return gulp.src(glob, { read: false })
      .pipe(clean({ force: true }));
  };
};

gulp.task('clean', cleanGlob(['./build', './dist']));
gulp.task('clean-dist-win', cleanGlob(`./dist/${packageJSON.productName}-win32-ia32`));
gulp.task('clean-dist-darwin', cleanGlob(`./dist/${packageJSON.productName}-darwin-ia32`));
gulp.task('clean-dist-linux', cleanGlob([
  `./dist/${packageJSON.productName}-linux-ia32`,
  `./dist/${packageJSON.productName}-linux-x64`,
]));
gulp.task('clean-external', cleanGlob('./build/external.js'));
gulp.task('clean-material', cleanGlob('./build/assets/material'));
gulp.task('clean-utility', cleanGlob('./build/assets/util'));
gulp.task('clean-html', cleanGlob('./build/public_html'));
gulp.task('clean-internal', cleanGlob(['./build/*.js', './build/**/*.js', '!./build/assets/**/*']));
gulp.task('clean-fonts', cleanGlob('./build/assets/font'));
gulp.task('clean-less', cleanGlob('./build/assets/css'));
gulp.task('clean-images', cleanGlob('./build/assets/img'));

gulp.task('external', ['clean-external'], () => {
  return gulp.src(paths.externalScripts)
    .pipe(concat('external.js'))
    .pipe(gulp.dest('./build/assets'));
});

gulp.task('materialize-js', ['clean-material'], () => {
  return gulp.src('node_modules/materialize-css/dist/js/materialize.min.js')
    .pipe(gulp.dest('./build/assets/material'));
});

gulp.task('utility-js', ['clean-utility'], () => {
  return gulp.src(paths.utilityScripts)
    .pipe(gulp.dest('./build/assets/util'));
});

gulp.task('html', ['clean-html'], () => {
  return gulp.src(paths.html)
    .pipe(gulp.dest('./build/public_html'));
});

gulp.task('transpile', ['clean-internal'], () => {
  gulp.src(paths.internalScripts)
    .pipe(babel({
      presets: ['es2015'],
    }))
    .on('error', (err) => { console.error(err); }) // eslint-disable-line
    .pipe(replace(/process\.env\.(.+)\;/gi, (envCall, envKey) => {
      return `'${process.env[envKey]}'`;
    }))
    .pipe(gulp.dest('./build/'));
});

gulp.task('fonts', ['clean-fonts'], () => {
  return gulp.src(paths.fonts)
    .pipe(gulp.dest('./build/assets/font'));
});

gulp.task('less', ['clean-less'], () => {
  gulp.src(paths.less)
    .pipe(less())
    .on('error', (err) => { console.error(err); }) // eslint-disable-line
    .pipe(cssmin())
    .pipe(concat('core.css'))
    .pipe(gulp.dest('./build/assets/css'));
});

// Copy all static images
gulp.task('images', ['clean-images'], () => {
  return gulp.src(paths.images)
    .pipe(gulp.dest('./build/assets/img/'));
});

// Rerun the task when a file changes
gulp.task('watch', ['build'], () => {
  gulp.watch(paths.internalScripts, ['transpile']);
  gulp.watch(paths.html, ['html']);
  gulp.watch(paths.images, ['images']);
  gulp.watch(paths.less, ['less']);
});

gulp.task('package:win', ['clean-dist-win', 'build'], (done) => {
  packager(_.extend({}, defaultPackageConf, { platform: 'win32', arch: 'ia32' }), () => {
    setTimeout(() => {
      exec(`vendor\\signtool sign /f ".cert.pfx" /p ${process.env.SIGN_CERT_PASS} /fd sha1 /tr "http://timestamp.geotrust.com/tsa" /v /as "dist/${packageJSON.productName}-win32-ia32/${packageJSON.productName}.exe"`, {}, () => {
        exec(`vendor\\signtool sign /f ".cert.pfx" /p ${process.env.SIGN_CERT_PASS} /fd sha256 /tr "http://timestamp.geotrust.com/tsa" /v /as "dist/${packageJSON.productName}-win32-ia32/${packageJSON.productName}.exe"`, {}, () => {
          done();
        });
      });
    }, 1000);
  });
});

gulp.task('make:win', ['package:win'], (done) => {
  grunt.tasks()['grunt-build:win32'](() => {
    exec(`vendor\\signtool sign /f ".cert.pfx" /p ${process.env.SIGN_CERT_PASS} /fd sha1 /tr "http://timestamp.geotrust.com/tsa" /v /as "dist/win32/${packageJSON.productName}Setup.exe"`, {}, () => {
      exec(`vendor\\signtool sign /f ".cert.pfx" /p ${process.env.SIGN_CERT_PASS} /fd sha256 /tr "http://timestamp.geotrust.com/tsa" /v /as "dist/win32/${packageJSON.productName}Setup.exe"`, {}, () => {
        done();
      });
    });
  });
});

gulp.task('package:darwin', ['clean-dist-darwin', 'build'], (done) => {
  packager(_.extend({}, defaultPackageConf, { platform: 'darwin', sign: 'Developer ID Application: Samuel Attard (S7WPQ45ZU2)' }), done); // eslint-disable-line
});

gulp.task('make:darwin', ['package:darwin'], (done) => {
  const pathEscapedName = packageJSON.productName.replace(/ /gi, '\ ');
  const child = spawn('zip', ['-r', '-y',
    `${pathEscapedName}.zip`,
    `${pathEscapedName}.app`],
    {
      cwd: `./dist/${packageJSON.productName}-darwin-x64`,
    });

  console.log(`Zipping "${packageJSON.productName}.app"`); // eslint-disable-line

  // spit stdout to screen
  child.stdout.on('data', (data) => { process.stdout.write(data.toString()); });

  // Send stderr to the main console
  child.stderr.on('data', (data) => {
    process.stdout.write(data.toString());
  });

  child.on('close', (code) => {
    console.log('Finished zipping with code ' + code); // eslint-disable-line
    done();
  });
});

gulp.task('package:linux', ['clean-dist-linux', 'build'], (done) => {
  packager(_.extend({}, defaultPackageConf, { platform: 'linux' }), done);
});

gulp.task('deb:linux', ['package:linux'], (done) => {
  let count = 0;
  const next = (err) => {
    if (err) {
      done(err);
    } else if (count > 0) {
      done();
    } else {
      count++;
    }
  };

  const debian = require('electron-installer-debian');

  const defaults = {
    bin: packageJSON.productName,
    dest: 'dist/installers/debian',
    depends: ['libappindicator1'],
    maintainer: 'Samuel Attard <samuel.r.attard@gmail.com>',
    homepage: 'http://www.googleplaymusicdesktopplayer.com',
    icon: 'build/assets/img/main.png',
  };

  debian(_.extend({}, defaults, {
    src: `dist/${packageJSON.productName}-linux-ia32`,
    arch: 'i386',
  }), (err) => {
    console.log('32bit deb package built');
    if (err) return next(err);
    next();
  });

  debian(_.extend({}, defaults, {
    src: `dist/${packageJSON.productName}-linux-x64`,
    arch: 'amd64',
  }), (err) => {
    console.log('64bit deb package built');
    if (err) return next(err);
    next();
  });
});

gulp.task('rpm:linux', ['package:linux'], (done) => {
  let count = 0;
  const next = (err) => {
    if (err) {
      done(err);
    } else if (count > 0) {
      done();
    } else {
      count++;
    }
  };

  const redhat  = require('electron-installer-redhat');

  const defaults = {
    bin: packageJSON.productName,
    dest: 'dist/installers/fedora',
    depends: ['libappindicator1'],
    maintainer: 'Samuel Attard <samuel.r.attard@gmail.com>',
    homepage: 'http://www.googleplaymusicdesktopplayer.com',
    icon: 'build/assets/img/main.png',
  };

  redhat(_.extend({}, defaults, {
    src: `dist/${packageJSON.productName}-linux-ia32`,
    arch: 'i386',
  }), (err) => {
    console.log('32bit rpm package built');
    if (err) return next(err);
    next();
  });

  redhat(_.extend({}, defaults, {
    src: `dist/${packageJSON.productName}-linux-x64`,
    arch: 'amd64',
  }), (err) => {
    console.log('64bit rpm package built');
    if (err) return next(err);
    next();
  });
});

gulp.task('make:linux', ['deb:linux', 'rpm:linux'], (done) => {
  // Zip Linux x86
  const child = spawn('zip', ['-r', '-y',
    `installers.zip`,
    `.`],
    {
      cwd: `./dist/installers`,
    });

  console.log(`Zipping the linux Installers`); // eslint-disable-line

  // spit stdout to screen
  child.stdout.on('data', (data) => { process.stdout.write(data.toString()); });

  // Send stderr to the main console
  child.stderr.on('data', (data) => {
    process.stdout.write(data.toString());
  });

  child.on('close', (code) => {
    console.log('Finished zipping with code ' + code); // eslint-disable-line
    done();
  });
});

gulp.task('make:deb', ['deb:linux'], (done) => {
  // Zip Linux x86
  const child = spawn('zip', ['-r', '-y',
    `installers.zip`,
    `.`],
    {
      cwd: `./dist/installers/debian`,
    });

  console.log(`Zipping the linux Installers`); // eslint-disable-line

  // spit stdout to screen
  child.stdout.on('data', (data) => { process.stdout.write(data.toString()); });

  // Send stderr to the main console
  child.stderr.on('data', (data) => {
    process.stdout.write(data.toString());
  });

  child.on('close', (code) => {
    console.log('Finished zipping with code ' + code); // eslint-disable-line
    done();
  });
});

gulp.task('make:rpm', ['deb:redhat'], (done) => {
  // Zip Linux x86
  const child = spawn('zip', ['-r', '-y',
    `installers.zip`,
    `.`],
    {
      cwd: `./dist/installers/rpm`,
    });

  console.log(`Zipping the linux Installers`); // eslint-disable-line

  // spit stdout to screen
  child.stdout.on('data', (data) => { process.stdout.write(data.toString()); });

  // Send stderr to the main console
  child.stderr.on('data', (data) => {
    process.stdout.write(data.toString());
  });

  child.on('close', (code) => {
    console.log('Finished zipping with code ' + code); // eslint-disable-line
    done();
  });
});

// The default task (called when you run `gulp` from cli)
gulp.task('default', ['watch', 'transpile', 'images']);
gulp.task('build', ['external', 'materialize-js', 'utility-js', 'transpile', 'images', 'less',
                    'fonts', 'html']);
gulp.task('package', ['package:win', 'package:darwin', 'package:linux']);
<commit_msg>Fixed gulpfile<commit_after>'use strict';

const _ = require('lodash');
const gulp = require('gulp');
const babel = require('gulp-babel');
const clean = require('gulp-clean');
const less = require('gulp-less');
const cssmin = require('gulp-cssmin');
const concat = require('gulp-concat');
const packager = require('electron-packager');
const spawn = require('child_process').spawn;
const exec = require('child_process').exec;
const replace = require('gulp-replace');

const grunt = require('gulp-grunt');

const paths = {
  internalScripts: ['src/**/*.js'],
  externalScripts: ['node_modules/gmusic.js/dist/gmusic.min.js',
                    'node_modules/gmusic-theme.js/dist/gmusic-theme.min.js',
                    'node_modules/gmusic-mini-player.js/dist/gmusic-mini-player.min.js'],
  utilityScripts: ['node_modules/jquery/dist/jquery.min.js',
                    'node_modules/materialize-css/dist/js/materialize.min.js',
                    'node_modules/materialize-css/extras/noUiSlider/nouislider.min.js'],
  html: 'src/public_html/**/*.html',
  less: 'src/assets/less/**/*.less',
  fonts: ['node_modules/materialize-css/dist/font/**/*',
          '!node_modules/materialize-css/dist/font/material-design-icons/*',
          'node_modules/material-design-icons-iconfont/dist/fonts/**/*'],
  images: ['src/assets/icons/**/*', 'src/assets/img/**/*'],
};

const packageJSON = require('./package.json');
let version = packageJSON.dependencies['electron-prebuilt'];
if (version.substr(0, 1) !== '0') {
  version = version.substr(1);
}

const defaultPackageConf = {
  dir: '.',
  name: packageJSON.productName,
  'build-version': packageJSON.version,
  version,
  platform: 'all',
  arch: 'all',
  'app-bundle-id': packageJSON.name,
  'app-version': packageJSON.version,
  icon: './build/assets/img/main',
  out: './dist/',
  overwrite: true,
  prune: true,
  ignore: 'dist/.*',
  'version-string': {
    CompanyName: 'Samuel Attard',
    LegalCopyright: 'Copyright © 2016 Samuel Attard, All rights reserved.',
    FileDescription: 'Google Play Music Desktop Player by Samuel Attard',
    ProductName: 'Google Play Music Desktop Player',
    InternalName: 'Google Play Music Desktop Player',
  },
};

const cleanGlob = (glob) => {
  return () => {
    return gulp.src(glob, { read: false })
      .pipe(clean({ force: true }));
  };
};

gulp.task('clean', cleanGlob(['./build', './dist']));
gulp.task('clean-dist-win', cleanGlob(`./dist/${packageJSON.productName}-win32-ia32`));
gulp.task('clean-dist-darwin', cleanGlob(`./dist/${packageJSON.productName}-darwin-ia32`));
gulp.task('clean-dist-linux', cleanGlob([
  `./dist/${packageJSON.productName}-linux-ia32`,
  `./dist/${packageJSON.productName}-linux-x64`,
]));
gulp.task('clean-external', cleanGlob('./build/external.js'));
gulp.task('clean-material', cleanGlob('./build/assets/material'));
gulp.task('clean-utility', cleanGlob('./build/assets/util'));
gulp.task('clean-html', cleanGlob('./build/public_html'));
gulp.task('clean-internal', cleanGlob(['./build/*.js', './build/**/*.js', '!./build/assets/**/*']));
gulp.task('clean-fonts', cleanGlob('./build/assets/font'));
gulp.task('clean-less', cleanGlob('./build/assets/css'));
gulp.task('clean-images', cleanGlob('./build/assets/img'));

gulp.task('external', ['clean-external'], () => {
  return gulp.src(paths.externalScripts)
    .pipe(concat('external.js'))
    .pipe(gulp.dest('./build/assets'));
});

gulp.task('materialize-js', ['clean-material'], () => {
  return gulp.src('node_modules/materialize-css/dist/js/materialize.min.js')
    .pipe(gulp.dest('./build/assets/material'));
});

gulp.task('utility-js', ['clean-utility'], () => {
  return gulp.src(paths.utilityScripts)
    .pipe(gulp.dest('./build/assets/util'));
});

gulp.task('html', ['clean-html'], () => {
  return gulp.src(paths.html)
    .pipe(gulp.dest('./build/public_html'));
});

gulp.task('transpile', ['clean-internal'], () => {
  gulp.src(paths.internalScripts)
    .pipe(babel({
      presets: ['es2015'],
    }))
    .on('error', (err) => { console.error(err); }) // eslint-disable-line
    .pipe(replace(/process\.env\.(.+)\;/gi, (envCall, envKey) => {
      return `'${process.env[envKey]}'`;
    }))
    .pipe(gulp.dest('./build/'));
});

gulp.task('fonts', ['clean-fonts'], () => {
  return gulp.src(paths.fonts)
    .pipe(gulp.dest('./build/assets/font'));
});

gulp.task('less', ['clean-less'], () => {
  gulp.src(paths.less)
    .pipe(less())
    .on('error', (err) => { console.error(err); }) // eslint-disable-line
    .pipe(cssmin())
    .pipe(concat('core.css'))
    .pipe(gulp.dest('./build/assets/css'));
});

// Copy all static images
gulp.task('images', ['clean-images'], () => {
  return gulp.src(paths.images)
    .pipe(gulp.dest('./build/assets/img/'));
});

// Rerun the task when a file changes
gulp.task('watch', ['build'], () => {
  gulp.watch(paths.internalScripts, ['transpile']);
  gulp.watch(paths.html, ['html']);
  gulp.watch(paths.images, ['images']);
  gulp.watch(paths.less, ['less']);
});

gulp.task('package:win', ['clean-dist-win', 'build'], (done) => {
  packager(_.extend({}, defaultPackageConf, { platform: 'win32', arch: 'ia32' }), () => {
    setTimeout(() => {
      exec(`vendor\\signtool sign /f ".cert.pfx" /p ${process.env.SIGN_CERT_PASS} /fd sha1 /tr "http://timestamp.geotrust.com/tsa" /v /as "dist/${packageJSON.productName}-win32-ia32/${packageJSON.productName}.exe"`, {}, () => {
        exec(`vendor\\signtool sign /f ".cert.pfx" /p ${process.env.SIGN_CERT_PASS} /fd sha256 /tr "http://timestamp.geotrust.com/tsa" /v /as "dist/${packageJSON.productName}-win32-ia32/${packageJSON.productName}.exe"`, {}, () => {
          done();
        });
      });
    }, 1000);
  });
});

gulp.task('make:win', ['package:win'], (done) => {
  grunt.tasks()['grunt-build:win32'](() => {
    exec(`vendor\\signtool sign /f ".cert.pfx" /p ${process.env.SIGN_CERT_PASS} /fd sha1 /tr "http://timestamp.geotrust.com/tsa" /v /as "dist/win32/${packageJSON.productName}Setup.exe"`, {}, () => {
      exec(`vendor\\signtool sign /f ".cert.pfx" /p ${process.env.SIGN_CERT_PASS} /fd sha256 /tr "http://timestamp.geotrust.com/tsa" /v /as "dist/win32/${packageJSON.productName}Setup.exe"`, {}, () => {
        done();
      });
    });
  });
});

gulp.task('package:darwin', ['clean-dist-darwin', 'build'], (done) => {
  packager(_.extend({}, defaultPackageConf, { platform: 'darwin', sign: 'Developer ID Application: Samuel Attard (S7WPQ45ZU2)' }), done); // eslint-disable-line
});

gulp.task('make:darwin', ['package:darwin'], (done) => {
  const pathEscapedName = packageJSON.productName.replace(/ /gi, '\ ');
  const child = spawn('zip', ['-r', '-y',
    `${pathEscapedName}.zip`,
    `${pathEscapedName}.app`],
    {
      cwd: `./dist/${packageJSON.productName}-darwin-x64`,
    });

  console.log(`Zipping "${packageJSON.productName}.app"`); // eslint-disable-line

  // spit stdout to screen
  child.stdout.on('data', (data) => { process.stdout.write(data.toString()); });

  // Send stderr to the main console
  child.stderr.on('data', (data) => {
    process.stdout.write(data.toString());
  });

  child.on('close', (code) => {
    console.log('Finished zipping with code ' + code); // eslint-disable-line
    done();
  });
});

gulp.task('package:linux', ['clean-dist-linux', 'build'], (done) => {
  packager(_.extend({}, defaultPackageConf, { platform: 'linux' }), done);
});

gulp.task('deb:linux', ['package:linux'], (done) => {
  const debian = require('electron-installer-debian');

  const defaults = {
    bin: packageJSON.productName,
    dest: 'dist/installers/debian',
    depends: ['libappindicator1'],
    maintainer: 'Samuel Attard <samuel.r.attard@gmail.com>',
    homepage: 'http://www.googleplaymusicdesktopplayer.com',
    icon: 'build/assets/img/main.png',
  };

  debian(_.extend({}, defaults, {
    src: `dist/${packageJSON.productName}-linux-ia32`,
    arch: 'i386',
  }), (err) => {
    console.log('32bit deb package built');
    if (err) return done(err);

    debian(_.extend({}, defaults, {
      src: `dist/${packageJSON.productName}-linux-x64`,
      arch: 'amd64',
    }), (err) => {
      console.log('64bit deb package built');
      if (err) return done(err);
      done();
    });
  });
});

gulp.task('rpm:linux', ['package:linux'], (done) => {
  const redhat  = require('electron-installer-redhat');

  const defaults = {
    bin: packageJSON.productName,
    dest: 'dist/installers/fedora',
    depends: ['libappindicator1'],
    maintainer: 'Samuel Attard <samuel.r.attard@gmail.com>',
    homepage: 'http://www.googleplaymusicdesktopplayer.com',
    icon: 'build/assets/img/main.png',
  };

  redhat(_.extend({}, defaults, {
    src: `dist/${packageJSON.productName}-linux-ia32`,
    arch: 'i386',
  }), (err) => {
    console.log('32bit rpm package built');
    if (err) return done(err);

    redhat(_.extend({}, defaults, {
      src: `dist/${packageJSON.productName}-linux-x64`,
      arch: 'amd64',
    }), (err) => {
      console.log('64bit rpm package built');
      if (err) return done(err);
      done();
    });
  });
});

gulp.task('make:linux', ['deb:linux', 'rpm:linux'], (done) => {
  // Zip Linux x86
  const child = spawn('zip', ['-r', '-y',
    `installers.zip`,
    `.`],
    {
      cwd: `./dist/installers`,
    });

  console.log(`Zipping the linux Installers`); // eslint-disable-line

  // spit stdout to screen
  child.stdout.on('data', (data) => { process.stdout.write(data.toString()); });

  // Send stderr to the main console
  child.stderr.on('data', (data) => {
    process.stdout.write(data.toString());
  });

  child.on('close', (code) => {
    console.log('Finished zipping with code ' + code); // eslint-disable-line
    done();
  });
});

gulp.task('make:deb', ['deb:linux'], (done) => {
  // Zip Linux x86
  const child = spawn('zip', ['-r', '-y',
    `installers.zip`,
    `.`],
    {
      cwd: `./dist/installers/debian`,
    });

  console.log(`Zipping the linux Installers`); // eslint-disable-line

  // spit stdout to screen
  child.stdout.on('data', (data) => { process.stdout.write(data.toString()); });

  // Send stderr to the main console
  child.stderr.on('data', (data) => {
    process.stdout.write(data.toString());
  });

  child.on('close', (code) => {
    console.log('Finished zipping with code ' + code); // eslint-disable-line
    done();
  });
});

gulp.task('make:rpm', ['rpm:linux'], (done) => {
  // Zip Linux x86
  const child = spawn('zip', ['-r', '-y',
    `installers.zip`,
    `.`],
    {
      cwd: `./dist/installers/fedora`,
    });

  console.log(`Zipping the RPM Installers`); // eslint-disable-line

  // spit stdout to screen
  child.stdout.on('data', (data) => { process.stdout.write(data.toString()); });

  // Send stderr to the main console
  child.stderr.on('data', (data) => {
    process.stdout.write(data.toString());
  });

  child.on('close', (code) => {
    console.log('Finished zipping with code ' + code); // eslint-disable-line
    done();
  });
});

// The default task (called when you run `gulp` from cli)
gulp.task('default', ['watch', 'transpile', 'images']);
gulp.task('build', ['external', 'materialize-js', 'utility-js', 'transpile', 'images', 'less',
                    'fonts', 'html']);
gulp.task('package', ['package:win', 'package:darwin', 'package:linux']);
<|endoftext|>


<commit_before>// ==UserScript==
// @name         HRK tlk.io Autoref Helper
// @namespace    HRK
// @version      0.2
// @description  insert your ref link at yourref, go to https://tlk.io/hrk, enable script, let it run!
// @author       Tackyou
// @match        *tlk.io/hrk*
// @license      https://raw.githubusercontent.com/Tackyou/HRK-Drop-Key-Referral-Helper/master/LICENSE
// @supportURL   https://github.com/Tackyou/HRK-Drop-Key-Referral-Helper/issues
// @updateURL    https://raw.githubusercontent.com/Tackyou/orlygiftHRK-Drop-Key-Referral-Helper/master/hrkdropkey.user.js
// @downloadURL  https://raw.githubusercontent.com/Tackyou/HRK-Drop-Key-Referral-Helper/master/hrkdropkey.user.js
// @grant        none
// ==/UserScript==

var yourref = 'http://www.hrkgame.com/profile/referral/dropkey?ref=96dcc6a2ee97f37';
var data = new prepare();
$(function(){
    setTimeout(function(){letsgo(data)}, 2000);
});

$(window).unload(function() {
    data.helper.close();
});

function prepare() {
    this.helper = window.open('http://start.zro.co/','','width=15,height=15,resizable=no,status=no,toolbar=no,scrollbars=no,menubar=no,location=no');
    this.helper.blur();
    this.helper.resizeTo(0,0);
    this.helper.moveTo(window.screen.availWidth+500,0);
    window.focus();

    this.alreadyOpened = new Array();

    var data = this;
}

function letsgo(data){
    console.log('[HRK tlk.io] Start');
    $('#message_body').val(yourref);
    $('form#new_message').submit();
    console.log('[HRK tlk.io] Link posted');
    var time = 2000;
    $('#chat dl dd a').each(function(){
        var url = $(this).attr('href');
        if($.inArray(url, data.alreadyOpened) == -1 && url.indexOf('http://www.hrkgame.com/profile/referral/dropkey?ref=') > -1){
            setTimeout( function(){
                console.log('[HRK tlk.io] Opening ... ' + url);
                data.alreadyOpened.push(url);
                data.helper.location.href = url;
            }, time);
            time += 2000;
        }
    });

    setTimeout(function(){letsgo(data)}, time+10000);
}

// ignore this
//var reflink = $('.col-md-8.dkrefferal p input').val();
//console.log('Your ref link:'+reflink);
//$('button.btn.active.btn-danger.btn-lg.uppercase.rfrbtn').trigger('click');
<commit_msg>Version 0.3 - please follow the readme<commit_after>// ==UserScript==
// @name         HRK tlk.io Autoref Helper
// @namespace    HRK
// @version      0.3
// @description  insert your ref link at yourref, go to https://tlk.io/hrk, enable script, let it run!
// @author       Tackyou
// @match        *tlk.io/hrk*
// @license      https://raw.githubusercontent.com/Tackyou/HRK-Drop-Key-Referral-Helper/master/LICENSE
// @supportURL   https://github.com/Tackyou/HRK-Drop-Key-Referral-Helper/issues
// @updateURL    https://raw.githubusercontent.com/Tackyou/orlygiftHRK-Drop-Key-Referral-Helper/master/hrkdropkey.user.js
// @downloadURL  https://raw.githubusercontent.com/Tackyou/HRK-Drop-Key-Referral-Helper/master/hrkdropkey.user.js
// @grant        none
// ==/UserScript==

var yourref = 'http://www.hrkgame.com/profile/referral/dropkey?ref=96dcc6a2ee97f37';
var data = new prepare();
$(function(){
    setTimeout(function(){letsgo(data)}, 2000);
});

$(window).unload(function() {
    data.helper.close();
});

function prepare() {
    this.helper = window.open('http://start.zro.co/','','width=15,height=15,resizable=no,status=no,toolbar=no,scrollbars=no,menubar=no,location=no');
    this.helper.blur();
    this.helper.resizeTo(0,0);
    this.helper.moveTo(window.screen.availWidth+500,0);
    window.focus();

    this.alreadyOpened = new Array();

    var data = this;
}

function letsgo(data){
    console.log('[HRK tlk.io] Start');
    $('#message_body').val('Help me:' + yourref);
    $('form#new_message').submit();
    console.log('[HRK tlk.io] Link posted');
    var time = 2000;
    $('#chat dl dd a').each(function(){
        var url = $(this).attr('href');
        if($.inArray(url, data.alreadyOpened) == -1 && url.indexOf('http://www.hrkgame.com/profile/referral/dropkey?ref=') > -1){
            setTimeout( function(){
                console.log('[HRK tlk.io] Opening ... ' + url);
                data.alreadyOpened.push(url);
                data.helper.location.href = url;
            }, time);
            time += 2000;
        }
    });

    setTimeout(function(){letsgo(data)}, time+10000);
}

// ignore this
//var reflink = $('.col-md-8.dkrefferal p input').val();
//console.log('Your ref link:'+reflink);
//$('button.btn.active.btn-danger.btn-lg.uppercase.rfrbtn').trigger('click');
<|endoftext|>


<commit_before>(function(){
  'use strict';

  var gulp = require('gulp');
  var gulpWebpack = require('gulp-webpack');
  var gulpConnect = require('gulp-connect');
  var karma = require('gulp-karma');
  var webpackConfig = require('./webpack-config');
  var gulpMocha = require('gulp-mocha');
  var gulpMerger = require ('lcov-result-merger');
  var gulpIstanbul = require('gulp-istanbul');
  var gulpCoveralls = require('gulp-coveralls');

  var testFiles = [
    './test/client/hello.js',
    './test/client/**/*_spec.js'
  ];

  gulp.task('test:client', function() {
    return gulp.src(testFiles)
      .pipe(karma({configFile: 'karma.conf.js', action: 'run'}))
      .on('error', function(err) { throw err; });
  });

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

  gulp.task('test:server:coverage', function(){
    gulp.src(['lib/**/*.js'])
      .pipe(gulpIstanbul())
      .pipe(gulpIstanbul.hookRequire())
      .on('finish', function(){
        gulp.src(['test/server/**/*.js'])
          .pipe(gulpMocha({reporter: 'spec'}))
          .pipe(gulpIstanbul.writeReports('coverage'));
      });
  });

  gulp.task('karma', function() {
    gulp.src(testFiles)
      .pipe(karma({configFile: 'karma.conf.js', action: 'watch'}));
  });

  gulp.task('build', function(){
    gulp.src(webpackConfig.entry.app)
      .pipe(gulpWebpack(webpackConfig))
      .pipe(gulp.dest('./public/js/prod'));
  });

  gulp.task('serve', function(){
    gulpConnect.server({
      root: './public',
      port: 8000,
      livereload: true
    });
  });

  gulp.task('cover', ['test:server:coverage', 'test:client'], function() {
    return gulp.src('./coverage/lcov*.info')
      .pipe(gulpMerger())
      .pipe(gulp.dest('./coverage'));
  });

  gulp.task('coveralls', ['cover'], function(){
    return gulp.src('coverage/lcov.info')
      .pipe(gulpCoveralls());
  });

  gulp.task('reload', function() {
    gulp.src(['./public/js/**/*.js', '!./public/js/prod/*.js'])
      .pipe(gulpConnect.reload());
  });

  gulp.task('watch', function() {
    gulp.watch(['./public/js/**/*.js', '!./public/js/prod/*.js'], ['build']);
    gulp.watch(['./lib/**/*.js', './test/server/**/*.js'], ['test:server']);
    gulp.src(testFiles)
      .pipe(karma({configFile: 'karma.conf.js', action: 'watch'}));
    gulp.watch(['./public/js/**/*.js', '!./public/js/prod/*.js'], ['reload']);
  });

  gulp.task('default', ['serve', 'watch']);
})();

<commit_msg>Refine watch target in gulpfile<commit_after>(function(){
  'use strict';

  var gulp = require('gulp');
  var gulpWebpack = require('gulp-webpack');
  var gulpConnect = require('gulp-connect');
  var karma = require('gulp-karma');
  var webpackConfig = require('./webpack-config');
  var gulpMocha = require('gulp-mocha');
  var gulpMerger = require ('lcov-result-merger');
  var gulpIstanbul = require('gulp-istanbul');
  var gulpCoveralls = require('gulp-coveralls');

  var testFiles = [
    './test/client/hello.js',
    './test/client/**/*_spec.js'
  ];

  gulp.task('test:client', function() {
    return gulp.src(testFiles)
      .pipe(karma({configFile: 'karma.conf.js', action: 'run'}))
      .on('error', function(err) { throw err; });
  });

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

  gulp.task('test:server:coverage', function(){
    gulp.src(['lib/**/*.js'])
      .pipe(gulpIstanbul())
      .pipe(gulpIstanbul.hookRequire())
      .on('finish', function(){
        gulp.src(['test/server/**/*.js'])
          .pipe(gulpMocha({reporter: 'spec'}))
          .pipe(gulpIstanbul.writeReports('coverage'));
      });
  });

  gulp.task('karma', function() {
    gulp.src(testFiles)
      .pipe(karma({configFile: 'karma.conf.js', action: 'watch'}));
  });

  gulp.task('build', function(){
    gulp.src(webpackConfig.entry.app)
      .pipe(gulpWebpack(webpackConfig))
      .pipe(gulp.dest('./public/js/prod'));
  });

  gulp.task('serve', function(){
    gulpConnect.server({
      root: './public',
      port: 8000,
      livereload: true
    });
  });

  gulp.task('cover', ['test:server:coverage', 'test:client'], function() {
    return gulp.src('./coverage/lcov*.info')
      .pipe(gulpMerger())
      .pipe(gulp.dest('./coverage'));
  });

  gulp.task('coveralls', ['cover'], function(){
    return gulp.src('coverage/lcov.info')
      .pipe(gulpCoveralls());
  });

  gulp.task('reload', function() {
    gulp.src(['./public/js/**/*.js', '!./public/js/prod/*.js'])
      .pipe(gulpConnect.reload());
  });

  gulp.task('watch', function() {
    gulp.watch(['./public/**/*.js', '!./public/js/prod/*.js'], ['build']);
    gulp.watch(['./lib/**/*.js', './test/server/**/*.js'], ['test:server']);
    gulp.src(testFiles)
      .pipe(karma({configFile: 'karma.conf.js', action: 'watch'}));
    gulp.watch(['./public/js/**/*.js', '!./public/js/prod/*.js'], ['reload']);
  });

  gulp.task('default', ['serve', 'watch']);
})();

<|endoftext|>


<commit_before>var gulp = require('gulp');
var sass = require('gulp-ruby-sass');
var autoprefixer = require('gulp-autoprefixer');
var minifycss = require('gulp-minify-css');
var jshint = require('gulp-jshint');
var uglify = require('gulp-uglify');
var imagemin = require('gulp-imagemin');
var rename = require('gulp-rename');
var del = require('del');
var stripDebug = require('gulp-strip-debug');
var args = require('yargs').argv;
var gulpif = require('gulp-if');
var gzip = require('gulp-gzip');
var fileInclude = require('gulp-file-include');
var markdown = require('gulp-markdown');
var source = require('vinyl-source-stream');
var browserify = require('browserify');
var frontMatter = require('gulp-front-matter');
var concat = require('gulp-concat');
var es = require('event-stream');
var mustache = require('mustache');
var fs = require('fs');
var sort = require('sort-stream');
var moment = require('moment');

var destination = '../www';

// command line params
// for instance: $ gulp --type production
var isProduction = args.type === 'production';

// blog page pipeline
gulp.task('blog', ['blog-posts-list'], function () {
  // taking the blog post list from the 'blog-posts-list' step
  // and including it into the blog.html template
  return gulp.src('src/blog/blog.html')
    .pipe(fileInclude())
    .pipe(rename('blog/index.html'))
    .pipe(gulp.dest(destination));
});

// blog post list for blog page
gulp.task('blog-posts-list', ['blog-posts-html'], function () {
  var postlist = String(fs.readFileSync('src/blog/blogposts.html'));

  return gulp.src('src/blog/markdown/**/*.md')
    // extract the frontmatter from the .md add to file attributes
    .pipe(frontMatter({
      property: 'frontMatter',
      remove: true
    }))
    // use the frontmatter to populate a blog post list
    .pipe(es.map(function (file, cb) {
      var html = mustache.render(postlist, {
        post: file.frontMatter,
        date: moment(file.frontMatter.date).format('MMMM d, YYYY'),
        authors: file.frontMatter.authors
      });
      file.contents = new Buffer(html);
      cb(null, file);
    }))
    // sort the list newest-first
    .pipe(sort(function (a, b) {
      if (a.frontMatter.date > b.frontMatter.date) return -1;
      if (a.frontMatter.date < b.frontMatter.date) return 1;
      return 0;
    }))
    // concat the list into a single html
    .pipe(concat('blogposts.html'))
    .pipe(gulp.dest(destination));
});

// fill out the blog post templates
gulp.task('blog-posts-html', ['blog-posts-partials'], function () {
  var post = String(fs.readFileSync('src/blog/post.html'));
  var dir = '';
  return gulp.src('src/blog/markdown/**/*.md')
    // extract frontmatter from markdown, append to file attributes
    .pipe(frontMatter({
      property: 'frontMatter',
      remove: true
    }))
    // insert handlebars value from frontmatter into post template
    .pipe(es.map(function (file, cb) {
      var html = mustache.render(post, {
        include: file.frontMatter.readfullarticle,
        date: moment(file.frontMatter.date).format('MMMM d, YYYY'),
        authors: file.frontMatter.authors
      });
      file.contents = new Buffer(html);
      cb(null, file);
    }))
    // include the rendered partials into the post template
    .pipe(fileInclude())
    // get the blog post directory name from the .md file name
    .pipe(es.map(function (file, cb) {
      dir = file.path.split('/');
      dir = dir[dir.length - 1].replace('.md', '');
      cb(null, file);
    }))
    // rename the destination path for the file (avoiding .html)
    .pipe(rename(function (path) {
      path.dirname = dir;
      path.basename = "index";
      path.extname = ".html";
    }))
    .pipe(gulp.dest(destination));
});

// create the partials for the post template
gulp.task('blog-posts-partials', function () {
  return gulp.src('src/blog/markdown/**/*.md')
    // only running frontmatter here to remove the frontmatter
    // since gulp-markdown can't handle it
    .pipe(frontMatter({
      property: 'frontMatter',
      remove: true
    }))
    .pipe(markdown())
    .pipe(gulp.dest(destination));
});

// html
gulp.task('html', ['blog'], function () {
  var dir = '';
  return gulp.src('src/html/**/*.html')
    .pipe(fileInclude())
    .pipe(gulpif(isProduction, gzip()))
    // get the blog post directory name from the .md file name
    .pipe(es.map(function (file, cb) {
      dir = file.path.split('/');
      dir = dir[dir.length - 1].replace('.html', '');
      cb(null, file);
    }))
    // rename the destination path for the file (avoiding .html)
    // unless it is index.html in which case just ignore it
    .pipe(rename(function (path) {
      if (path.basename !== 'index') {
        path.dirname = dir;
        path.basename = "index";
        path.extname = ".html";
      }
    }))
    .pipe(gulp.dest(destination));
});

// copy some fonts over
gulp.task('fonts', function () {
  gulp.src('src/fonts/**/*.*', { base: './src/fonts/' })
    .pipe(gulp.dest(destination + '/assets/fonts'));
});

// sass
gulp.task('styles', ['fonts'], function() {
  return gulp.src('src/styles/**/*.scss')
    .pipe(sass({ style: 'expanded', container: './tmp' }))
    .pipe(autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'))
    .pipe(gulpif(isProduction, rename({suffix: '.min'})))
    .pipe(gulpif(isProduction, minifycss()))
    .pipe(gulpif(isProduction, gzip()))
    .pipe(gulp.dest(destination + '/assets/css'));
});

// browserify
gulp.task('browserify', ['jshint'], function () {
  return browserify('./src/scripts/main.js')
    .bundle()
    //Pass desired output filename to vinyl-source-stream
    .pipe(source('bundle.js'))
    // Start piping stream to tasks!
    .pipe(gulp.dest(destination + '/assets/js'));
});

// jshint
gulp.task('jshint', function() {
  return gulp.src('src/scripts/**/*.js')
    .pipe(jshint('.jshintrc'))
    .pipe(jshint.reporter('default'));
});

// js
gulp.task('scripts', ['browserify'], function() {
  return gulp.src(destination + '/assets/js/bundle.js')
    .pipe(gulpif(isProduction, rename({suffix: '.min'})))
    .pipe(gulpif(isProduction, uglify()))
    .pipe(gulpif(isProduction, stripDebug()))
    .pipe(gulpif(isProduction, gzip()))
    .pipe(gulp.dest(destination + '/assets/js'));
});

// images
gulp.task('images', function() {
  return gulp.src(['src/images/**/*.png', 'src/images/**/*.jpg', 'src/images/**/*.svg'])
    .pipe(
      gulpif(
        isProduction,
        imagemin(
          {
            optimizationLevel: 5,
            progressive: true,
            interlaced: true
          }
        )
      )
    )
    .pipe(gulp.dest(destination + '/assets/img'));
});

gulp.task('clean', function(cb) {
  // hmm can't delete directory above
  // skip clean for now

  //del([destination + '/*', destination + '/assets/css', destination + '/assets/fonts', destination + '/assets/js', destination + '/assets/img', destination + '/prototype'], cb);
});

// default build task
gulp.task('default', /*['clean'],*/ function() {
  // clean first, then these
  gulp.start('html', 'styles', 'scripts', 'images');
});

// watch
gulp.task('watch', ['default'], function() {
  // if anything changes, rebuild
  gulp.watch('src/markdown/**/*.md', ['html']);
  gulp.watch('src/templates/**/*.tpl', ['html']);
  gulp.watch('src/html/**/*.html', ['html']);
  gulp.watch('src/blog/**/*.md', ['html']);
  gulp.watch('src/styles/**/*.scss', ['styles']);
  gulp.watch('src/fonts/**/*.*', ['fonts']);
  gulp.watch('src/scripts/**/*.js', ['scripts']);
  gulp.watch('src/images/**/*', ['images']);
});<commit_msg>CLBWEBSITE-112 Update post date format<commit_after>var gulp = require('gulp');
var sass = require('gulp-ruby-sass');
var autoprefixer = require('gulp-autoprefixer');
var minifycss = require('gulp-minify-css');
var jshint = require('gulp-jshint');
var uglify = require('gulp-uglify');
var imagemin = require('gulp-imagemin');
var rename = require('gulp-rename');
var del = require('del');
var stripDebug = require('gulp-strip-debug');
var args = require('yargs').argv;
var gulpif = require('gulp-if');
var gzip = require('gulp-gzip');
var fileInclude = require('gulp-file-include');
var markdown = require('gulp-markdown');
var source = require('vinyl-source-stream');
var browserify = require('browserify');
var frontMatter = require('gulp-front-matter');
var concat = require('gulp-concat');
var es = require('event-stream');
var mustache = require('mustache');
var fs = require('fs');
var sort = require('sort-stream');
var moment = require('moment');

var destination = '../www';

// command line params
// for instance: $ gulp --type production
var isProduction = args.type === 'production';

// blog page pipeline
gulp.task('blog', ['blog-posts-list'], function () {
  // taking the blog post list from the 'blog-posts-list' step
  // and including it into the blog.html template
  return gulp.src('src/blog/blog.html')
    .pipe(fileInclude())
    .pipe(rename('blog/index.html'))
    .pipe(gulp.dest(destination));
});

// blog post list for blog page
gulp.task('blog-posts-list', ['blog-posts-html'], function () {
  var postlist = String(fs.readFileSync('src/blog/blogposts.html'));

  return gulp.src('src/blog/markdown/**/*.md')
    // extract the frontmatter from the .md add to file attributes
    .pipe(frontMatter({
      property: 'frontMatter',
      remove: true
    }))
    // use the frontmatter to populate a blog post list
    .pipe(es.map(function (file, cb) {
      var html = mustache.render(postlist, {
        post: file.frontMatter,
        date: moment(file.frontMatter.date).format('MMMM D, YYYY'),
        authors: file.frontMatter.authors
      });
      file.contents = new Buffer(html);
      cb(null, file);
    }))
    // sort the list newest-first
    .pipe(sort(function (a, b) {
      if (a.frontMatter.date > b.frontMatter.date) return -1;
      if (a.frontMatter.date < b.frontMatter.date) return 1;
      return 0;
    }))
    // concat the list into a single html
    .pipe(concat('blogposts.html'))
    .pipe(gulp.dest(destination));
});

// fill out the blog post templates
gulp.task('blog-posts-html', ['blog-posts-partials'], function () {
  var post = String(fs.readFileSync('src/blog/post.html'));
  var dir = '';
  return gulp.src('src/blog/markdown/**/*.md')
    // extract frontmatter from markdown, append to file attributes
    .pipe(frontMatter({
      property: 'frontMatter',
      remove: true
    }))
    // insert handlebars value from frontmatter into post template
    .pipe(es.map(function (file, cb) {
      var html = mustache.render(post, {
        include: file.frontMatter.readfullarticle,
        date: moment(file.frontMatter.date).format('MMMM D, YYYY'),
        authors: file.frontMatter.authors
      });
      file.contents = new Buffer(html);
      cb(null, file);
    }))
    // include the rendered partials into the post template
    .pipe(fileInclude())
    // get the blog post directory name from the .md file name
    .pipe(es.map(function (file, cb) {
      dir = file.path.split('/');
      dir = dir[dir.length - 1].replace('.md', '');
      cb(null, file);
    }))
    // rename the destination path for the file (avoiding .html)
    .pipe(rename(function (path) {
      path.dirname = dir;
      path.basename = "index";
      path.extname = ".html";
    }))
    .pipe(gulp.dest(destination));
});

// create the partials for the post template
gulp.task('blog-posts-partials', function () {
  return gulp.src('src/blog/markdown/**/*.md')
    // only running frontmatter here to remove the frontmatter
    // since gulp-markdown can't handle it
    .pipe(frontMatter({
      property: 'frontMatter',
      remove: true
    }))
    .pipe(markdown())
    .pipe(gulp.dest(destination));
});

// html
gulp.task('html', ['blog'], function () {
  var dir = '';
  return gulp.src('src/html/**/*.html')
    .pipe(fileInclude())
    .pipe(gulpif(isProduction, gzip()))
    // get the blog post directory name from the .md file name
    .pipe(es.map(function (file, cb) {
      dir = file.path.split('/');
      dir = dir[dir.length - 1].replace('.html', '');
      cb(null, file);
    }))
    // rename the destination path for the file (avoiding .html)
    // unless it is index.html in which case just ignore it
    .pipe(rename(function (path) {
      if (path.basename !== 'index') {
        path.dirname = dir;
        path.basename = "index";
        path.extname = ".html";
      }
    }))
    .pipe(gulp.dest(destination));
});

// copy some fonts over
gulp.task('fonts', function () {
  gulp.src('src/fonts/**/*.*', { base: './src/fonts/' })
    .pipe(gulp.dest(destination + '/assets/fonts'));
});

// sass
gulp.task('styles', ['fonts'], function() {
  return gulp.src('src/styles/**/*.scss')
    .pipe(sass({ style: 'expanded', container: './tmp' }))
    .pipe(autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'))
    .pipe(gulpif(isProduction, rename({suffix: '.min'})))
    .pipe(gulpif(isProduction, minifycss()))
    .pipe(gulpif(isProduction, gzip()))
    .pipe(gulp.dest(destination + '/assets/css'));
});

// browserify
gulp.task('browserify', ['jshint'], function () {
  return browserify('./src/scripts/main.js')
    .bundle()
    //Pass desired output filename to vinyl-source-stream
    .pipe(source('bundle.js'))
    // Start piping stream to tasks!
    .pipe(gulp.dest(destination + '/assets/js'));
});

// jshint
gulp.task('jshint', function() {
  return gulp.src('src/scripts/**/*.js')
    .pipe(jshint('.jshintrc'))
    .pipe(jshint.reporter('default'));
});

// js
gulp.task('scripts', ['browserify'], function() {
  return gulp.src(destination + '/assets/js/bundle.js')
    .pipe(gulpif(isProduction, rename({suffix: '.min'})))
    .pipe(gulpif(isProduction, uglify()))
    .pipe(gulpif(isProduction, stripDebug()))
    .pipe(gulpif(isProduction, gzip()))
    .pipe(gulp.dest(destination + '/assets/js'));
});

// images
gulp.task('images', function() {
  return gulp.src(['src/images/**/*.png', 'src/images/**/*.jpg', 'src/images/**/*.svg'])
    .pipe(
      gulpif(
        isProduction,
        imagemin(
          {
            optimizationLevel: 5,
            progressive: true,
            interlaced: true
          }
        )
      )
    )
    .pipe(gulp.dest(destination + '/assets/img'));
});

gulp.task('clean', function(cb) {
  // hmm can't delete directory above
  // skip clean for now

  //del([destination + '/*', destination + '/assets/css', destination + '/assets/fonts', destination + '/assets/js', destination + '/assets/img', destination + '/prototype'], cb);
});

// default build task
gulp.task('default', /*['clean'],*/ function() {
  // clean first, then these
  gulp.start('html', 'styles', 'scripts', 'images');
});

// watch
gulp.task('watch', ['default'], function() {
  // if anything changes, rebuild
  gulp.watch('src/markdown/**/*.md', ['html']);
  gulp.watch('src/templates/**/*.tpl', ['html']);
  gulp.watch('src/html/**/*.html', ['html']);
  gulp.watch('src/blog/**/*.md', ['html']);
  gulp.watch('src/styles/**/*.scss', ['styles']);
  gulp.watch('src/fonts/**/*.*', ['fonts']);
  gulp.watch('src/scripts/**/*.js', ['scripts']);
  gulp.watch('src/images/**/*', ['images']);
});<|endoftext|>


<commit_before>"use strict";

var args = require('minimist')(process.argv.slice(2));
var gulp = require('gulp');
var bower = require('gulp-bower');
var map = require('map-stream');
var fs = require('fs-extra');
var globalVar = require('./template/tasks/global-variables');
var gutil = require('gulp-util');
var _ = require('lodash');
var runSequence = require('run-sequence');
var hyd = require("hydrolysis");
var jsonfile = require('jsonfile');
var StreamFromArray = require('stream-from-array');
var rename = require("gulp-rename");
var marked = require('marked');

var libDir = __dirname + '/lib/';
var tplDir = __dirname + '/template/';

var helpers = require(tplDir + "helpers");
require('require-dir')(tplDir + 'tasks');

// Using global because if we try to pass it to templates via the helper or any object
// we need to call merge which makes a copy of the structure per template slowing down
// the performance.
global.parsed = []; // we store all parsed objects so as we can iterate or find behaviors

gulp.task('clean:target', function() {
  fs.removeSync(globalVar.clientDir + 'element');
  fs.removeSync(globalVar.clientDir + 'widget');
});

gulp.task('clean:resources', function() {
  fs.removeSync(globalVar.publicDir);
});

gulp.task('clean', ['clean:target', 'clean:resources']);

gulp.task('bower:configure', ['clean:resources'], function(done) {
  jsonfile.readFile('.bowerrc', function (err, obj) {
    if (!err) {
      fs.copySync('.bowerrc', globalVar.publicDir + '/.bowerrc');
      if(obj.directory) {
        globalVar.bowerDir = globalVar.publicDir + '/' + obj.directory + '/';
      }
    }
    done();
  });
});

gulp.task('bower:install', ['clean', 'bower:configure'], function() {
  if (globalVar.bowerPackages) {
    return bower({ cmd: 'install', cwd: globalVar.publicDir}, [globalVar.bowerPackages]);
  } else {
    gutil.log('No --package provided. Using package(s) from bower_components folder.');
    return gulp.src('./bower_components/**/*', {base: '.'}).pipe(gulp.dest(globalVar.publicDir));
  }
});

gulp.task('parse', ['analyze'], function(cb) {
  global.parsed.forEach(function(item) {
    if (!helpers.isBehavior(item) && item.behaviors && item.behaviors.length) {
      item.behaviors.forEach(function(name) {
        var nestedBehaviors = helpers.getNestedBehaviors(item, name);
        item.properties = _.union(item.properties, nestedBehaviors.properties);

        // merge events
        if (nestedBehaviors.events && nestedBehaviors.events.length) {
          nestedBehaviors.events.forEach(function (event) {
            var notDuplicate = _.filter(item.events, function (e) {
                return e.name == event.name;
              }).length === 0;
            if (notDuplicate) {
              item.events.push(event);
            }
          });
        }
      });
    }
    if (item.events) {
      item.events.forEach(function(event) {
        var p = [];
        event.params.forEach(function(param) {
          var notDuplicate = _.filter(p, function (p) {
              return p.name == param.name;
          }).length === 0;
          // remove duplicated, and more than one level nested (detail.file.src)
          if (notDuplicate && !/\..+\./.test(param.name)) {
            p.push(param);
          }
        });
        event.params = p;
      });
    }

    // We don't want to wrap any private api
    helpers.removePrivateApi(item.properties, 'name');
  });
  cb();
});

gulp.task('analyze', ['clean:target', 'pre-analyze'], function() {
  return gulp.src([globalVar.bowerDir + "*/*.html",
    // vaadin elements
    globalVar.bowerDir + "*/vaadin-*/vaadin-*.html",
    // ignore all demo.html, index.html and metadata.html files
    "!" + globalVar.bowerDir + "*/*demo.html",
    "!" + globalVar.bowerDir + "*/*index.html",
    "!" + globalVar.bowerDir + "*/*metadata.html",
    // includes a set of js files only, and some do not exist
    "!" + globalVar.bowerDir + "*/*web-animations.html",
    // Not useful in gwt and also has spurious event names
    "!" + globalVar.bowerDir + "*/*iron-jsonp-library.html",
    ])
    .pipe(map(function(file, cb) {
      hyd.Analyzer.analyze(globalVar.bowerDir + file.relative).then(function(result) {
        var jsonArray = _.union(result.elements, result.behaviors);
        jsonArray.forEach(function(item) {
          var path = file.relative.replace(/\\/, '/');
          if (item.is) {
            item.name = item.is;
            item.path = path;

            var bowerFile = file.base + path.split("/")[0] + "/bower.json";
            var bowerFileContent = fs.readFileSync(bowerFile);
            item.bowerData = bowerFileContent ? JSON.parse(bowerFileContent) : {};

            // Save all items in an array for later processing
            global.parsed.push(item);
          }
        });
        cb(null, file);
      })
      ['catch'](function(e){
        gutil.log(e.stack);
        cb(null, file);
      });
    }));
});

// Parse a template and generates a .java file.
// template: file in the templates folder
// obj:      context object for the template
// name:     name of the item parsed
// dir:      folder relative to the client folder to write the file
// suffix:   extra suffix for the name
function parseTemplate(template, obj, name, dir, suffix) {
  var className = helpers.camelCase(name) + suffix;
  // If there is a base .java file we extend it.
  var classBase = helpers.camelCase(name) + suffix + "Base";

  // We have to compute the appropriate name-space for the component.
  var prefix =
    // For events we prefer the first word of the name if they are standard ones.
    /^Event/.test(suffix) && /^(polymer|iron|paper|neon)-/.test(name) ? name :
    // Otherwise we try the name from its bower.json, then the sub-folder name in
    // bower_components, and finally from its name.
    obj.bowerData && obj.bowerData.name || obj.path.replace(/.*\/+(.+)\/+[^\/]+/, '$1') || name;
  //  Then we take the first part before first dash
  prefix = prefix.split('-')[0].replace(/\./g,'');

  obj.ns = globalVar.ns + '.' + prefix;

  var targetPath = globalVar.clientDir + prefix + '/' + dir;
  var targetFile = targetPath + className + ".java";
  fs.ensureFileSync(targetFile);

  var baseFile = libDir + globalVar.nspath + '/' + prefix + '/' + dir + classBase + ".java";
  if (!fs.existsSync(baseFile)) {
    var baseFile = './lib/' + globalVar.nspath + '/' + prefix + '/' + dir + classBase + ".java";
  }
  if (fs.existsSync(baseFile)) {
    obj.base = classBase;
    gutil.log("Copying: ", baseFile);
    fs.copySync(baseFile, targetPath + classBase + ".java");
  } else {
    obj.base = '';
  }

  gutil.log("Generating: ", targetFile);
  var tpl = _.template(fs.readFileSync(tplDir + template + '.template'));
  fs.writeFileSync(targetFile, new Buffer(tpl(_.merge({}, null, obj, helpers))));
}

gulp.task('generate:elements', ['parse'], function() {
  return StreamFromArray(global.parsed,{objectMode: true})
   .on('data', function(item) {
     if (helpers.isBehavior(item)) {
       parseTemplate('Behavior', item, item.is, '', '');
     } else {
       parseTemplate('Element', item, item.is, '', 'Element');
     }
   });
});

gulp.task('generate:events', ['parse'], function() {
  return StreamFromArray(global.parsed,{objectMode: true})
   .on('data', function(item) {
      if (item.events) {
        item.events.forEach(function(event) {
          event.bowerData = item.bowerData;
          event.name = event.name.replace(/\s.*$/,'');
          parseTemplate('ElementEvent', event, event.name, 'event/', 'Event');
        });
      }
   });
});

gulp.task('generate:widgets', ['parse'], function() {
  return StreamFromArray(global.parsed,{objectMode: true})
   .on('data', function(item) {
      if (!helpers.isBehavior(item)) {
        parseTemplate('Widget', item, item.is, 'widget/', '');
      }
   });
});

gulp.task('generate:widget-events', ['parse'], function() {
  return StreamFromArray(global.parsed,{objectMode: true})
   .on('data', function(item) {
      if (item.events) {
        item.events.forEach(function(event) {
          event.bowerData = item.bowerData;
          event.name = event.name.replace(/\s.*$/,'');
          parseTemplate('WidgetEvent', event, event.name, 'widget/event/', 'Event');
          parseTemplate('WidgetEventHandler', event, event.name, 'widget/event/', 'EventHandler');
        });
      }
   });
});

gulp.task('generate:gwt-module', function () {
  if (args.moduleName != 'Elements' || args.groupId != 'com.vaadin.polymer') {
    var dest = globalVar.publicDir.replace(/[^\/]+\/?$/, '');
    gutil.log("Generating Module: " + dest + args.moduleName + ".gwt.xml");
    return gulp.src(tplDir + "GwtModule.template")
      .pipe(rename(args.moduleName + ".gwt.xml"))
      .pipe(gulp.dest(dest));
  }
});

gulp.task('generate:elements-all', ['generate:elements', 'generate:events']);

gulp.task('generate:widgets-all', ['generate:widgets', 'generate:widget-events']);

gulp.task('generate', ['generate:elements-all', 'generate:widgets-all', 'generate:gwt-module'], function() {
  gutil.log('Done.');
});

gulp.task('copy:lib', function() {
  if (!args.excludeLib) {
    return gulp.src(libDir + '**')
      .pipe(gulp.dest(globalVar.clientDirBase));
  }
});

gulp.task('copy:pom', function() {
  var tpl = _.template(fs.readFileSync(tplDir + "pom.template"));
  var pom = globalVar.currentDir + "pom.xml";

  // Try to get some configuration from a package.json
  // otherwise use default values
  var pkgFile = globalVar.currentDir + 'package.json';
  globalVar.pkg = {};
  try {
    var pkgContent = fs.readFileSync(pkgFile);
    globalVar.pkg = JSON.parse(pkgContent);
  } catch(ignore) {
  }
  globalVar.pkg.pom = globalVar.pkg.pom || {};
  globalVar.pkg.pom.version = args.version || globalVar.pkg.pom.version || globalVar.pkg.version;

  fs.ensureFileSync(pom);
  fs.writeFileSync(pom, new Buffer(tpl(_.merge({}, null, globalVar, helpers))));
});

gulp.task('default', function(){
  if(args.pom) {
    runSequence('clean', 'bower:install', 'generate', 'copy:lib', 'copy:pom');
  } else {
    runSequence('clean', 'bower:install', 'generate', 'copy:lib');
  }
});
<commit_msg>Fix generating the undefined.gwt.xml file<commit_after>"use strict";

var args = require('minimist')(process.argv.slice(2));
var gulp = require('gulp');
var bower = require('gulp-bower');
var map = require('map-stream');
var fs = require('fs-extra');
var globalVar = require('./template/tasks/global-variables');
var gutil = require('gulp-util');
var _ = require('lodash');
var runSequence = require('run-sequence');
var hyd = require("hydrolysis");
var jsonfile = require('jsonfile');
var StreamFromArray = require('stream-from-array');
var rename = require("gulp-rename");
var marked = require('marked');

var libDir = __dirname + '/lib/';
var tplDir = __dirname + '/template/';

var helpers = require(tplDir + "helpers");
require('require-dir')(tplDir + 'tasks');

// Using global because if we try to pass it to templates via the helper or any object
// we need to call merge which makes a copy of the structure per template slowing down
// the performance.
global.parsed = []; // we store all parsed objects so as we can iterate or find behaviors

gulp.task('clean:target', function() {
  fs.removeSync(globalVar.clientDir + 'element');
  fs.removeSync(globalVar.clientDir + 'widget');
});

gulp.task('clean:resources', function() {
  fs.removeSync(globalVar.publicDir);
});

gulp.task('clean', ['clean:target', 'clean:resources']);

gulp.task('bower:configure', ['clean:resources'], function(done) {
  jsonfile.readFile('.bowerrc', function (err, obj) {
    if (!err) {
      fs.copySync('.bowerrc', globalVar.publicDir + '/.bowerrc');
      if(obj.directory) {
        globalVar.bowerDir = globalVar.publicDir + '/' + obj.directory + '/';
      }
    }
    done();
  });
});

gulp.task('bower:install', ['clean', 'bower:configure'], function() {
  if (globalVar.bowerPackages) {
    return bower({ cmd: 'install', cwd: globalVar.publicDir}, [globalVar.bowerPackages]);
  } else {
    gutil.log('No --package provided. Using package(s) from bower_components folder.');
    return gulp.src('./bower_components/**/*', {base: '.'}).pipe(gulp.dest(globalVar.publicDir));
  }
});

gulp.task('parse', ['analyze'], function(cb) {
  global.parsed.forEach(function(item) {
    if (!helpers.isBehavior(item) && item.behaviors && item.behaviors.length) {
      item.behaviors.forEach(function(name) {
        var nestedBehaviors = helpers.getNestedBehaviors(item, name);
        item.properties = _.union(item.properties, nestedBehaviors.properties);

        // merge events
        if (nestedBehaviors.events && nestedBehaviors.events.length) {
          nestedBehaviors.events.forEach(function (event) {
            var notDuplicate = _.filter(item.events, function (e) {
                return e.name == event.name;
              }).length === 0;
            if (notDuplicate) {
              item.events.push(event);
            }
          });
        }
      });
    }
    if (item.events) {
      item.events.forEach(function(event) {
        var p = [];
        event.params.forEach(function(param) {
          var notDuplicate = _.filter(p, function (p) {
              return p.name == param.name;
          }).length === 0;
          // remove duplicated, and more than one level nested (detail.file.src)
          if (notDuplicate && !/\..+\./.test(param.name)) {
            p.push(param);
          }
        });
        event.params = p;
      });
    }

    // We don't want to wrap any private api
    helpers.removePrivateApi(item.properties, 'name');
  });
  cb();
});

gulp.task('analyze', ['clean:target', 'pre-analyze'], function() {
  return gulp.src([globalVar.bowerDir + "*/*.html",
    // vaadin elements
    globalVar.bowerDir + "*/vaadin-*/vaadin-*.html",
    // ignore all demo.html, index.html and metadata.html files
    "!" + globalVar.bowerDir + "*/*demo.html",
    "!" + globalVar.bowerDir + "*/*index.html",
    "!" + globalVar.bowerDir + "*/*metadata.html",
    // includes a set of js files only, and some do not exist
    "!" + globalVar.bowerDir + "*/*web-animations.html",
    // Not useful in gwt and also has spurious event names
    "!" + globalVar.bowerDir + "*/*iron-jsonp-library.html",
    ])
    .pipe(map(function(file, cb) {
      hyd.Analyzer.analyze(globalVar.bowerDir + file.relative).then(function(result) {
        var jsonArray = _.union(result.elements, result.behaviors);
        jsonArray.forEach(function(item) {
          var path = file.relative.replace(/\\/, '/');
          if (item.is) {
            item.name = item.is;
            item.path = path;

            var bowerFile = file.base + path.split("/")[0] + "/bower.json";
            var bowerFileContent = fs.readFileSync(bowerFile);
            item.bowerData = bowerFileContent ? JSON.parse(bowerFileContent) : {};

            // Save all items in an array for later processing
            global.parsed.push(item);
          }
        });
        cb(null, file);
      })
      ['catch'](function(e){
        gutil.log(e.stack);
        cb(null, file);
      });
    }));
});

// Parse a template and generates a .java file.
// template: file in the templates folder
// obj:      context object for the template
// name:     name of the item parsed
// dir:      folder relative to the client folder to write the file
// suffix:   extra suffix for the name
function parseTemplate(template, obj, name, dir, suffix) {
  var className = helpers.camelCase(name) + suffix;
  // If there is a base .java file we extend it.
  var classBase = helpers.camelCase(name) + suffix + "Base";

  // We have to compute the appropriate name-space for the component.
  var prefix =
    // For events we prefer the first word of the name if they are standard ones.
    /^Event/.test(suffix) && /^(polymer|iron|paper|neon)-/.test(name) ? name :
    // Otherwise we try the name from its bower.json, then the sub-folder name in
    // bower_components, and finally from its name.
    obj.bowerData && obj.bowerData.name || obj.path.replace(/.*\/+(.+)\/+[^\/]+/, '$1') || name;
  //  Then we take the first part before first dash
  prefix = prefix.split('-')[0].replace(/\./g,'');

  obj.ns = globalVar.ns + '.' + prefix;

  var targetPath = globalVar.clientDir + prefix + '/' + dir;
  var targetFile = targetPath + className + ".java";
  fs.ensureFileSync(targetFile);

  var baseFile = libDir + globalVar.nspath + '/' + prefix + '/' + dir + classBase + ".java";
  if (!fs.existsSync(baseFile)) {
    var baseFile = './lib/' + globalVar.nspath + '/' + prefix + '/' + dir + classBase + ".java";
  }
  if (fs.existsSync(baseFile)) {
    obj.base = classBase;
    gutil.log("Copying: ", baseFile);
    fs.copySync(baseFile, targetPath + classBase + ".java");
  } else {
    obj.base = '';
  }

  gutil.log("Generating: ", targetFile);
  var tpl = _.template(fs.readFileSync(tplDir + template + '.template'));
  fs.writeFileSync(targetFile, new Buffer(tpl(_.merge({}, null, obj, helpers))));
}

gulp.task('generate:elements', ['parse'], function() {
  return StreamFromArray(global.parsed,{objectMode: true})
   .on('data', function(item) {
     if (helpers.isBehavior(item)) {
       parseTemplate('Behavior', item, item.is, '', '');
     } else {
       parseTemplate('Element', item, item.is, '', 'Element');
     }
   });
});

gulp.task('generate:events', ['parse'], function() {
  return StreamFromArray(global.parsed,{objectMode: true})
   .on('data', function(item) {
      if (item.events) {
        item.events.forEach(function(event) {
          event.bowerData = item.bowerData;
          event.name = event.name.replace(/\s.*$/,'');
          parseTemplate('ElementEvent', event, event.name, 'event/', 'Event');
        });
      }
   });
});

gulp.task('generate:widgets', ['parse'], function() {
  return StreamFromArray(global.parsed,{objectMode: true})
   .on('data', function(item) {
      if (!helpers.isBehavior(item)) {
        parseTemplate('Widget', item, item.is, 'widget/', '');
      }
   });
});

gulp.task('generate:widget-events', ['parse'], function() {
  return StreamFromArray(global.parsed,{objectMode: true})
   .on('data', function(item) {
      if (item.events) {
        item.events.forEach(function(event) {
          event.bowerData = item.bowerData;
          event.name = event.name.replace(/\s.*$/,'');
          parseTemplate('WidgetEvent', event, event.name, 'widget/event/', 'Event');
          parseTemplate('WidgetEventHandler', event, event.name, 'widget/event/', 'EventHandler');
        });
      }
   });
});

gulp.task('generate:gwt-module', function () {
  if (globalVar.moduleName != 'Elements' || globalVar.ns != 'com.vaadin.polymer') {
    var dest = globalVar.publicDir.replace(/[^\/]+\/?$/, '');
    gutil.log("Generating Module: " + dest + globalVar.moduleName + ".gwt.xml");
    return gulp.src(tplDir + "GwtModule.template")
      .pipe(rename(globalVar.moduleName + ".gwt.xml"))
      .pipe(gulp.dest(dest));
  }
});

gulp.task('generate:elements-all', ['generate:elements', 'generate:events']);

gulp.task('generate:widgets-all', ['generate:widgets', 'generate:widget-events']);

gulp.task('generate', ['generate:elements-all', 'generate:widgets-all', 'generate:gwt-module'], function() {
  gutil.log('Done.');
});

gulp.task('copy:lib', function() {
  if (!args.excludeLib) {
    return gulp.src(libDir + '**')
      .pipe(gulp.dest(globalVar.clientDirBase));
  }
});

gulp.task('copy:pom', function() {
  var tpl = _.template(fs.readFileSync(tplDir + "pom.template"));
  var pom = globalVar.currentDir + "pom.xml";

  // Try to get some configuration from a package.json
  // otherwise use default values
  var pkgFile = globalVar.currentDir + 'package.json';
  globalVar.pkg = {};
  try {
    var pkgContent = fs.readFileSync(pkgFile);
    globalVar.pkg = JSON.parse(pkgContent);
  } catch(ignore) {
  }
  globalVar.pkg.pom = globalVar.pkg.pom || {};
  globalVar.pkg.pom.version = args.version || globalVar.pkg.pom.version || globalVar.pkg.version;

  fs.ensureFileSync(pom);
  fs.writeFileSync(pom, new Buffer(tpl(_.merge({}, null, globalVar, helpers))));
});

gulp.task('default', function(){
  if(args.pom) {
    runSequence('clean', 'bower:install', 'generate', 'copy:lib', 'copy:pom');
  } else {
    runSequence('clean', 'bower:install', 'generate', 'copy:lib');
  }
});
<|endoftext|>