<commit_before>/******************************************************
 * PATTERN LAB NODE
 * EDITION-NODE-GULP
 * The gulp wrapper around patternlab-node core, providing tasks to interact with the core library and move supporting frontend assets.
******************************************************/
var dist = {
  "root":"./dist/",
  "templates":"./dist/templates/",
  "js":"./dist/js",
  "images":"./dist/images",
  "fonts":"./dist/fonts",
  "css":"./dist/css"
};

var templates = [
  "02-organisms-00-global/*.*",
  "02-organisms-00-global-footer/*.*",
  "02-organisms-00-global-header/*.*"
];

var gulp = require('gulp'),
  Promise = require("bluebird");
  gutil = require('gulp-util'),
  git = Promise.promisifyAll(require('gulp-git')),
  sass = require('gulp-sass'),
  sassLint = require('gulp-sass-lint'),
  path = require('path'),
  browserSync = require('browser-sync').create(),
  argv = require('minimist')(process.argv.slice(2));

function resolvePath(pathInput) {
  return path.resolve(pathInput).replace(/\\/g,"/");
}

// SASS compilation
gulp.task('pl-sass', function(){
  return gulp.src(path.resolve(paths().source.css, '**/*.scss'))
    .pipe(sass().on('error', sass.logError))
    .pipe(gulp.dest(path.resolve(paths().source.css)));
});

/******************************************************
 * COPY TASKS - stream assets from source to destination
******************************************************/
// JS copy
gulp.task('pl-copy:js', function(){
  return gulp.src('**/*.js', {cwd: resolvePath(paths().source.js)} )
    .pipe(gulp.dest(resolvePath(paths().public.js)));
});

// JS copy dist
gulp.task('dist-copy:js', function(){
  return gulp.src('**/*.js', {cwd: resolvePath(paths().public.js)} )
    .pipe(gulp.dest(resolvePath(dist.js)));
});

// Images copy
gulp.task('pl-copy:img', function(){
  return gulp.src('**/*.*',{cwd: resolvePath(paths().source.images)} )
    .pipe(gulp.dest(resolvePath(paths().public.images)));
});

// Images copy dist
gulp.task('dist-copy:img', function(){
  return gulp.src('**/*.*',{cwd: resolvePath(paths().public.images)} )
    .pipe(gulp.dest(resolvePath(dist.images)));
});

// Favicon copy
gulp.task('pl-copy:favicon', function(){
  return gulp.src('favicon.ico', {cwd: resolvePath(paths().source.root)} )
    .pipe(gulp.dest(resolvePath(paths().public.root)));
});

// Favicon copy dist
gulp.task('dist-copy:favicon', function(){
  return gulp.src('favicon.ico', {cwd: resolvePath(paths().public.root)} )
    .pipe(gulp.dest(resolvePath(dist.root)));
});

// Fonts copy
gulp.task('pl-copy:font', function(){
  return gulp.src('*', {cwd: resolvePath(paths().source.fonts)})
    .pipe(gulp.dest(resolvePath(paths().public.fonts)));
});

// Fonts copy dist
gulp.task('dist-copy:font', function(){
  return gulp.src('*', {cwd: resolvePath(paths().public.fonts)})
    .pipe(gulp.dest(resolvePath(dist.fonts)));
});

// CSS Copy
gulp.task('pl-copy:css', function(){
  return gulp.src(resolvePath(paths().source.css) + '/*.css')
    .pipe(gulp.dest(resolvePath(paths().public.css)))
    .pipe(browserSync.stream());
});

// CSS Copy dist
gulp.task('dist-copy:css', function(){
  return gulp.src(resolvePath(paths().public.css) + '/*.css')
    .pipe(gulp.dest(resolvePath(dist.css)));
});

// Styleguide Copy everything but css
gulp.task('pl-copy:styleguide', function(){
  return gulp.src(resolvePath(paths().source.styleguide) + '/**/!(*.css)')
    .pipe(gulp.dest(resolvePath(paths().public.root)))
    .pipe(browserSync.stream());
});

// Styleguide Copy and flatten css
gulp.task('pl-copy:styleguide-css', function(){
  return gulp.src(resolvePath(paths().source.styleguide) + '/**/*.css')
    .pipe(gulp.dest(function(file){
      //flatten anything inside the styleguide into a single output dir per http://stackoverflow.com/a/34317320/1790362
      file.path = path.join(file.base, path.basename(file.path));
      return resolvePath(path.join(paths().public.styleguide, '/css'));
    }))
    .pipe(browserSync.stream());
});

// Templates copy to dist from public
gulp.task('dist-copy:templates', function(){
    return gulp.src(templates, {cwd: resolvePath(paths().public.patterns)})
      .pipe(gulp.dest(resolvePath(dist.templates)));
});

/******************************************************
 * PATTERN LAB CONFIGURATION - API with core library
******************************************************/
//read all paths from our namespaced config file
var config = require('./patternlab-config.json'),
  patternlab = require('patternlab-node')(config);

function paths() {
  return config.paths;
}

function getConfiguredCleanOption() {
  return config.cleanPublic;
}

function build(done) {
  patternlab.build(done, getConfiguredCleanOption());
}

gulp.task('pl-assets', gulp.series(
  gulp.parallel(
    'pl-copy:js',
    'pl-copy:img',
    'pl-copy:favicon',
    'pl-copy:font',
    gulp.series('pl-sass', 'pl-copy:css', function(done){done();}),
    'pl-copy:styleguide',
    'pl-copy:styleguide-css'
  ),
  function(done){
    done();
  })
);

gulp.task('dist-assets',
  gulp.parallel(
    'dist-copy:js',
    'dist-copy:img',
    'dist-copy:css',
    'dist-copy:favicon',
    'dist-copy:font'
  )
);

gulp.task('patternlab:version', function (done) {
  patternlab.version();
  done();
});

gulp.task('patternlab:help', function (done) {
  patternlab.help();
  done();
});

gulp.task('patternlab:patternsonly', function (done) {
  patternlab.patternsonly(done, getConfiguredCleanOption());
});

gulp.task('patternlab:liststarterkits', function (done) {
  patternlab.liststarterkits();
  done();
});

gulp.task('patternlab:loadstarterkit', function (done) {
  patternlab.loadstarterkit(argv.kit, argv.clean);
  done();
});

gulp.task('patternlab:build', gulp.series('pl-assets', build, function(done){
  done();
}));

gulp.task('patternlab:installplugin', function (done) {
  patternlab.installplugin(argv.plugin);
  done();
});

gulp.task('dist', gulp.series('patternlab:build', 'dist-assets', 'dist-copy:templates', function (done) {
  done();
}));
/******************************************************
 * SERVER AND WATCH TASKS
******************************************************/
// watch task utility functions
function getSupportedTemplateExtensions() {
  var engines = require('./node_modules/patternlab-node/core/lib/pattern_engines');
  return engines.getSupportedFileExtensions();
}
function getTemplateWatches() {
  return getSupportedTemplateExtensions().map(function (dotExtension) {
    return resolvePath(paths().source.patterns) + '/**/*' + dotExtension;
  });
}

function reload() {
  browserSync.reload();
}

function reloadCSS() {
  browserSync.reload('*.css');
}

function watch() {
  gulp.watch(resolvePath(paths().source.css) + '/**/*.css', { awaitWriteFinish: true }).on('change', gulp.series('pl-copy:css', reloadCSS));
  gulp.watch(resolvePath(paths().source.styleguide) + '/**/*.*', { awaitWriteFinish: true }).on('change', gulp.series('pl-copy:styleguide', 'pl-copy:styleguide-css', reloadCSS));

  gulp.watch(path.resolve(paths().source.css, '**/*.scss')).on('change', gulp.series('pl-sass'));

  var patternWatches = [
    resolvePath(paths().source.patterns) + '/**/*.json',
    resolvePath(paths().source.patterns) + '/**/*.md',
    resolvePath(paths().source.data) + '/*.json',
    resolvePath(paths().source.fonts) + '/*',
    resolvePath(paths().source.images) + '/*',
    resolvePath(paths().source.meta) + '/*',
    resolvePath(paths().source.annotations) + '/*'
  ].concat(getTemplateWatches());

  console.log(patternWatches);

  gulp.watch(patternWatches, { awaitWriteFinish: true }).on('change', gulp.series(build, reload));
}

gulp.task('patternlab:connect', gulp.series(function(done) {
  browserSync.init({
    server: {
      baseDir: resolvePath(paths().public.root)
    },
    snippetOptions: {
      // Ignore all HTML files within the templates folder
      blacklist: ['/index.html', '/', '/?*']
    },
    notify: {
      styles: [
        'display: none',
        'padding: 15px',
        'font-family: sans-serif',
        'position: fixed',
        'font-size: 1em',
        'z-index: 9999',
        'bottom: 0px',
        'right: 0px',
        'border-top-left-radius: 5px',
        'background-color: #1B2032',
        'opacity: 0.4',
        'margin: 0',
        'color: white',
        'text-align: center'
      ]
    }
  }, function(){
    console.log('PATTERN LAB NODE WATCHING FOR CHANGES');
    done();
  });
}));

/******************************************************
 * COMPOUND TASKS
******************************************************/
gulp.task('default', gulp.series('patternlab:build'));
gulp.task('patternlab:watch', gulp.series('patternlab:build', watch));
gulp.task('patternlab:serve', gulp.series('patternlab:build', 'patternlab:connect', watch));

/******************************************************
 * CUSTOM TASKS - tasks unique to this repo
******************************************************/

// Linting
gulp.task('scsslint', function () {
  return gulp.src('source/css/**/*.s+(a|c)ss')
    .pipe(sassLint())
    .pipe(sassLint.format())
    .pipe(sassLint.failOnError())
});

// Compound tasks
gulp.task('lint', gulp.parallel('scsslint'));
gulp.task('commitdist', gulp.series('dist', function(done) {
  var version = require('./package.json').version;
  var tag;
  var branch;

  git.revParseAsync({args: '--abbrev-ref HEAD'})
  .then(function(parsedBranch) {
      branch = parsedBranch;
      if (branch === 'master') {
        tag = new Date().toISOString().replace(/:/g, '.') + '-' + version;
      } else if (branch === 'release') {
        tag = version;
      } else {
          tag = branch + '-' + new Date().toISOString().replace(/:/g, '.') + '-' + version;
      }
  }).then(function() {
    return git.checkoutAsync(tag, {args: '-b'})
  }).then(function() {
    gutil.log('Force adding dist to git');
    var stream = gulp.src('dist/')
      .pipe(git.add({args: '-f'}))
      .pipe(git.commit('Distribution for ' + version));
    stream.on('end', function() {
      gutil.log('Tagging');
      git.tagAsync(tag, '')
      .then(function() {
        gutil.log('Checking out original branch');
        return git.checkoutAsync(branch);
      }).then(function() {
        gutil.log('Pushing tag to remote');
        return git.pushAsync('origin', [], {args: " --tags"});
      }).error(function(err) {
        throw err;
        gutil.log('Added and commited');
      }).done(function() {
        done()
      })
    });
  }).error(function(err) {
    throw err;
  });
}));
<commit_msg>Properly handle branch names in TravisCI<commit_after>/******************************************************
 * PATTERN LAB NODE
 * EDITION-NODE-GULP
 * The gulp wrapper around patternlab-node core, providing tasks to interact with the core library and move supporting frontend assets.
******************************************************/
var dist = {
  "root":"./dist/",
  "templates":"./dist/templates/",
  "js":"./dist/js",
  "images":"./dist/images",
  "fonts":"./dist/fonts",
  "css":"./dist/css"
};

var templates = [
  "02-organisms-00-global/*.*",
  "02-organisms-00-global-footer/*.*",
  "02-organisms-00-global-header/*.*"
];

var gulp = require('gulp'),
  Promise = require("bluebird");
  gutil = require('gulp-util'),
  git = Promise.promisifyAll(require('gulp-git')),
  sass = require('gulp-sass'),
  sassLint = require('gulp-sass-lint'),
  path = require('path'),
  browserSync = require('browser-sync').create(),
  argv = require('minimist')(process.argv.slice(2));

function resolvePath(pathInput) {
  return path.resolve(pathInput).replace(/\\/g,"/");
}

// SASS compilation
gulp.task('pl-sass', function(){
  return gulp.src(path.resolve(paths().source.css, '**/*.scss'))
    .pipe(sass().on('error', sass.logError))
    .pipe(gulp.dest(path.resolve(paths().source.css)));
});

/******************************************************
 * COPY TASKS - stream assets from source to destination
******************************************************/
// JS copy
gulp.task('pl-copy:js', function(){
  return gulp.src('**/*.js', {cwd: resolvePath(paths().source.js)} )
    .pipe(gulp.dest(resolvePath(paths().public.js)));
});

// JS copy dist
gulp.task('dist-copy:js', function(){
  return gulp.src('**/*.js', {cwd: resolvePath(paths().public.js)} )
    .pipe(gulp.dest(resolvePath(dist.js)));
});

// Images copy
gulp.task('pl-copy:img', function(){
  return gulp.src('**/*.*',{cwd: resolvePath(paths().source.images)} )
    .pipe(gulp.dest(resolvePath(paths().public.images)));
});

// Images copy dist
gulp.task('dist-copy:img', function(){
  return gulp.src('**/*.*',{cwd: resolvePath(paths().public.images)} )
    .pipe(gulp.dest(resolvePath(dist.images)));
});

// Favicon copy
gulp.task('pl-copy:favicon', function(){
  return gulp.src('favicon.ico', {cwd: resolvePath(paths().source.root)} )
    .pipe(gulp.dest(resolvePath(paths().public.root)));
});

// Favicon copy dist
gulp.task('dist-copy:favicon', function(){
  return gulp.src('favicon.ico', {cwd: resolvePath(paths().public.root)} )
    .pipe(gulp.dest(resolvePath(dist.root)));
});

// Fonts copy
gulp.task('pl-copy:font', function(){
  return gulp.src('*', {cwd: resolvePath(paths().source.fonts)})
    .pipe(gulp.dest(resolvePath(paths().public.fonts)));
});

// Fonts copy dist
gulp.task('dist-copy:font', function(){
  return gulp.src('*', {cwd: resolvePath(paths().public.fonts)})
    .pipe(gulp.dest(resolvePath(dist.fonts)));
});

// CSS Copy
gulp.task('pl-copy:css', function(){
  return gulp.src(resolvePath(paths().source.css) + '/*.css')
    .pipe(gulp.dest(resolvePath(paths().public.css)))
    .pipe(browserSync.stream());
});

// CSS Copy dist
gulp.task('dist-copy:css', function(){
  return gulp.src(resolvePath(paths().public.css) + '/*.css')
    .pipe(gulp.dest(resolvePath(dist.css)));
});

// Styleguide Copy everything but css
gulp.task('pl-copy:styleguide', function(){
  return gulp.src(resolvePath(paths().source.styleguide) + '/**/!(*.css)')
    .pipe(gulp.dest(resolvePath(paths().public.root)))
    .pipe(browserSync.stream());
});

// Styleguide Copy and flatten css
gulp.task('pl-copy:styleguide-css', function(){
  return gulp.src(resolvePath(paths().source.styleguide) + '/**/*.css')
    .pipe(gulp.dest(function(file){
      //flatten anything inside the styleguide into a single output dir per http://stackoverflow.com/a/34317320/1790362
      file.path = path.join(file.base, path.basename(file.path));
      return resolvePath(path.join(paths().public.styleguide, '/css'));
    }))
    .pipe(browserSync.stream());
});

// Templates copy to dist from public
gulp.task('dist-copy:templates', function(){
    return gulp.src(templates, {cwd: resolvePath(paths().public.patterns)})
      .pipe(gulp.dest(resolvePath(dist.templates)));
});

/******************************************************
 * PATTERN LAB CONFIGURATION - API with core library
******************************************************/
//read all paths from our namespaced config file
var config = require('./patternlab-config.json'),
  patternlab = require('patternlab-node')(config);

function paths() {
  return config.paths;
}

function getConfiguredCleanOption() {
  return config.cleanPublic;
}

function build(done) {
  patternlab.build(done, getConfiguredCleanOption());
}

gulp.task('pl-assets', gulp.series(
  gulp.parallel(
    'pl-copy:js',
    'pl-copy:img',
    'pl-copy:favicon',
    'pl-copy:font',
    gulp.series('pl-sass', 'pl-copy:css', function(done){done();}),
    'pl-copy:styleguide',
    'pl-copy:styleguide-css'
  ),
  function(done){
    done();
  })
);

gulp.task('dist-assets',
  gulp.parallel(
    'dist-copy:js',
    'dist-copy:img',
    'dist-copy:css',
    'dist-copy:favicon',
    'dist-copy:font'
  )
);

gulp.task('patternlab:version', function (done) {
  patternlab.version();
  done();
});

gulp.task('patternlab:help', function (done) {
  patternlab.help();
  done();
});

gulp.task('patternlab:patternsonly', function (done) {
  patternlab.patternsonly(done, getConfiguredCleanOption());
});

gulp.task('patternlab:liststarterkits', function (done) {
  patternlab.liststarterkits();
  done();
});

gulp.task('patternlab:loadstarterkit', function (done) {
  patternlab.loadstarterkit(argv.kit, argv.clean);
  done();
});

gulp.task('patternlab:build', gulp.series('pl-assets', build, function(done){
  done();
}));

gulp.task('patternlab:installplugin', function (done) {
  patternlab.installplugin(argv.plugin);
  done();
});

gulp.task('dist', gulp.series('patternlab:build', 'dist-assets', 'dist-copy:templates', function (done) {
  done();
}));
/******************************************************
 * SERVER AND WATCH TASKS
******************************************************/
// watch task utility functions
function getSupportedTemplateExtensions() {
  var engines = require('./node_modules/patternlab-node/core/lib/pattern_engines');
  return engines.getSupportedFileExtensions();
}
function getTemplateWatches() {
  return getSupportedTemplateExtensions().map(function (dotExtension) {
    return resolvePath(paths().source.patterns) + '/**/*' + dotExtension;
  });
}

function reload() {
  browserSync.reload();
}

function reloadCSS() {
  browserSync.reload('*.css');
}

function watch() {
  gulp.watch(resolvePath(paths().source.css) + '/**/*.css', { awaitWriteFinish: true }).on('change', gulp.series('pl-copy:css', reloadCSS));
  gulp.watch(resolvePath(paths().source.styleguide) + '/**/*.*', { awaitWriteFinish: true }).on('change', gulp.series('pl-copy:styleguide', 'pl-copy:styleguide-css', reloadCSS));

  gulp.watch(path.resolve(paths().source.css, '**/*.scss')).on('change', gulp.series('pl-sass'));

  var patternWatches = [
    resolvePath(paths().source.patterns) + '/**/*.json',
    resolvePath(paths().source.patterns) + '/**/*.md',
    resolvePath(paths().source.data) + '/*.json',
    resolvePath(paths().source.fonts) + '/*',
    resolvePath(paths().source.images) + '/*',
    resolvePath(paths().source.meta) + '/*',
    resolvePath(paths().source.annotations) + '/*'
  ].concat(getTemplateWatches());

  console.log(patternWatches);

  gulp.watch(patternWatches, { awaitWriteFinish: true }).on('change', gulp.series(build, reload));
}

gulp.task('patternlab:connect', gulp.series(function(done) {
  browserSync.init({
    server: {
      baseDir: resolvePath(paths().public.root)
    },
    snippetOptions: {
      // Ignore all HTML files within the templates folder
      blacklist: ['/index.html', '/', '/?*']
    },
    notify: {
      styles: [
        'display: none',
        'padding: 15px',
        'font-family: sans-serif',
        'position: fixed',
        'font-size: 1em',
        'z-index: 9999',
        'bottom: 0px',
        'right: 0px',
        'border-top-left-radius: 5px',
        'background-color: #1B2032',
        'opacity: 0.4',
        'margin: 0',
        'color: white',
        'text-align: center'
      ]
    }
  }, function(){
    console.log('PATTERN LAB NODE WATCHING FOR CHANGES');
    done();
  });
}));

/******************************************************
 * COMPOUND TASKS
******************************************************/
gulp.task('default', gulp.series('patternlab:build'));
gulp.task('patternlab:watch', gulp.series('patternlab:build', watch));
gulp.task('patternlab:serve', gulp.series('patternlab:build', 'patternlab:connect', watch));

/******************************************************
 * CUSTOM TASKS - tasks unique to this repo
******************************************************/

// Linting
gulp.task('scsslint', function () {
  return gulp.src('source/css/**/*.s+(a|c)ss')
    .pipe(sassLint())
    .pipe(sassLint.format())
    .pipe(sassLint.failOnError())
});

// Compound tasks
gulp.task('lint', gulp.parallel('scsslint'));
gulp.task('commitdist', gulp.series('dist', function(done) {
  var version = require('./package.json').version;
  var tag;
  var branch;

  git.revParseAsync({args: '--abbrev-ref HEAD'})
  .then(function(parsedBranch) {
    if (parsedBranch === 'HEAD') {
      // We're on Travis and need to check it.
      branch = process.env.PULL_REQUEST !== 'false' ?
        process.env.TRAVIS_BRANCH :
        process.env.TRAVIS_PULL_REQUEST_BRANCH;
    } else {
      branch = parsedBranch;
    }
    if (branch === 'master') {
      tag = new Date().toISOString().replace(/:/g, '.') + '-' + version;
    } else if (branch === 'release') {
      tag = version;
    } else {
      tag = branch + '-' + new Date().toISOString().replace(/:/g, '.') + '-' + version;
    }
  }).then(function() {
    return git.checkoutAsync(tag, {args: '-b'})
  }).then(function() {
    gutil.log('Force adding dist to git');
    var stream = gulp.src('dist/')
                 .pipe(git.add({args: '-f'}))
                 .pipe(git.commit('Distribution for ' + version));
    stream.on('end', function() {
      gutil.log('Tagging');
      git.tagAsync(tag, '')
      .then(function() {
        gutil.log('Checking out original branch');
        return git.checkoutAsync(branch);
      }).then(function() {
        gutil.log('Pushing tag to remote');
        return git.pushAsync('origin', [], {args: " --tags"});
      }).error(function(err) {
        throw err;
        gutil.log('Added and commited');
      }).done(function() {
        done()
      })
    });
  }).error(function(err) {
    throw err;
  });
}));
<|endoftext|>


<commit_before>/*
 * The MIT License
 *
 * Copyright (c) 2015, Patrick Fitzgerald
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the 'Software'), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

'use strict';

var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var openURL = require('open');
var lazypipe = require('lazypipe');
var rimraf = require('rimraf');
var wiredep = require('wiredep').stream;
var runSequence = require('run-sequence');

var yeoman = {
  app: require('./bower.json').appPath || 'app',
  dist: 'dist'
};

var paths = {
  scripts: [yeoman.app + '/scripts/**/*.js'],
  styles: [yeoman.app + '/styles/**/*.css'],
  test: ['test/spec/**/*.js'],
  testRequire: [
    yeoman.app + '/bower_components/angular/angular.js',
    yeoman.app + '/bower_components/angular-mocks/angular-mocks.js',
    yeoman.app + '/bower_components/angular-resource/angular-resource.js',
    yeoman.app + '/bower_components/angular-cookies/angular-cookies.js',
    yeoman.app + '/bower_components/angular-sanitize/angular-sanitize.js',
    yeoman.app + '/bower_components/angular-route/angular-route.js',
    'test/mock/**/*.js',
    'test/spec/**/*.js'
  ],
  karma: 'karma.conf.js',
  views: {
    main: yeoman.app + '/index.html',
    files: [ yeoman.app + '/views/**/*.html' ]
  }
};

////////////////////////
// Reusable pipelines //
////////////////////////

var lintScripts = lazypipe()
  .pipe($.jshint, '.jshintrc')
  .pipe($.jshint.reporter, 'jshint-stylish');

var styles = lazypipe()
  .pipe($.autoprefixer, 'last 1 version')
  .pipe(gulp.dest, '.tmp/styles');

///////////
// Tasks //
///////////

gulp.task('styles', function () {
  return gulp.src(paths.styles)
    .pipe(styles());
});

gulp.task('lint:scripts', function () {
  return gulp.src(paths.scripts)
    .pipe(lintScripts());
});

gulp.task('clean:tmp', function (cb) {
  rimraf('./.tmp', cb);
});

gulp.task('watch', function () {
  gulp.watch('bower.json', ['bower']);
});

// inject bower components
gulp.task('bower', function () {
  return gulp.src(paths.views.main)
    .pipe(wiredep({
      directory: yeoman.app + '/bower_components',
      ignorePath: '..'
    }))
  .pipe(gulp.dest(yeoman.app + '/views'));
});

gulp.task('html', function () {
  return gulp.src(yeoman.app + '/views/**/*')
    .pipe(gulp.dest(yeoman.dist + '/views'));
});

gulp.task('html:app', function () {
  return gulp.src(yeoman.app + '/scripts/app/views/**/*.html')
    .pipe(gulp.dest(yeoman.dist + '/scripts/app/views'));
});

gulp.task('html:cluster', function () {
  return gulp.src(yeoman.app + '/scripts/modules/cluster/views/**/*.html')
    .pipe(gulp.dest(yeoman.dist + '/scripts/modules/cluster/views'));
});

gulp.task('html:country', function () {
  return gulp.src(yeoman.app + '/scripts/modules/country/ethiopia/views/**/*.html')
    .pipe(gulp.dest(yeoman.dist + '/scripts/modules/country/ethiopia/views'));
});

///////////
// Build //
///////////

gulp.task('clean:dist', function (cb) {
  rimraf('./dist', cb);
});

gulp.task('client:build', [ 'html', 'html:app', 'html:cluster', 'html:country', 'styles' ], function () {
  var jsFilter = $.filter('**/*.js', {restore: true});
  var cssFilter = $.filter('**/*.css', {restore: true});
  var gulpUtil = require('gulp-util');

  return gulp.src(paths.views.main)
    .pipe($.useref({searchPath: [yeoman.app, '.tmp']}))
    .pipe(jsFilter)
    .pipe($.ngAnnotate())
    // .pipe($.uglify())
    .pipe($.uglify().on('error', gulpUtil.log))
    .pipe(jsFilter.restore())
    .pipe(cssFilter)
    .pipe($.minifyCss({cache: true}))
    .pipe(cssFilter.restore())
    .pipe($.rev())
    .pipe($.revReplace())
    // .pipe(header(getLicense()))
    // .pipe(header('/* ' + pkg.name + ' version ' + pkg.version + ' */ \n' ))
    .pipe(gulp.dest(yeoman.dist));
});

gulp.task('rename:index', function () {
  return gulp.src(yeoman.dist + '/*.html')
    .pipe($.rename('/index.html'))
    .pipe(gulp.dest(yeoman.dist));
});

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

gulp.task('bower:images', function () {
  return gulp.src(yeoman.app + '/../bower_components/**/images/**/*')
    .pipe($.flatten())
    .pipe(gulp.dest(yeoman.dist + '/styles/images'));
});

gulp.task('fullscreen:images', function () {
  return gulp.src(yeoman.app + '/images/fullscreen.png')
    .pipe(gulp.dest(yeoman.dist + '/styles'));
});

gulp.task('copy:static', function () {
  return gulp.src(yeoman.app + '/static/**/*')
    .pipe(gulp.dest(yeoman.dist + '/static'));
});

gulp.task('copy:extras', function () {
  return gulp.src(yeoman.app + '/*/.*', { dot: true })
    .pipe(gulp.dest(yeoman.dist));
});

gulp.task('copy:widgets', function () {
  // widgets
  gulp.src(yeoman.app + '/scripts/widgets/**/*.js')
    .pipe(gulp.dest(yeoman.dist + '/scripts/widgets'));
  // html
  gulp.src(yeoman.app + '/scripts/widgets/**/*.html')
    .pipe(gulp.dest(yeoman.dist + '/scripts/widgets'));
});

gulp.task('copy:fonts', function () {
  return gulp.src(yeoman.app + '/fonts/**/*')
    .pipe(gulp.dest(yeoman.dist + '/fonts'));
});

gulp.task('copy:mfonts', function () {
  return gulp.src(yeoman.app + '/../bower_components/materialize/fonts/**/*')
    .pipe(gulp.dest(yeoman.dist + '/fonts'));
});

gulp.task('build', ['clean:dist'], function () {
  runSequence(['ngm:images', 'bower:images', 'fullscreen:images', 'copy:static', 'copy:extras', 'copy:widgets', 'copy:fonts', 'copy:mfonts', 'client:build'], 'rename:index');
});

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

<commit_msg>ngm: fix for gulp image locations<commit_after>/*
 * The MIT License
 *
 * Copyright (c) 2015, Patrick Fitzgerald
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the 'Software'), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

'use strict';

var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var openURL = require('open');
var lazypipe = require('lazypipe');
var rimraf = require('rimraf');
var wiredep = require('wiredep').stream;
var runSequence = require('run-sequence');

var yeoman = {
  app: require('./bower.json').appPath || 'app',
  dist: 'dist'
};

var paths = {
  scripts: [yeoman.app + '/scripts/**/*.js'],
  styles: [yeoman.app + '/styles/**/*.css'],
  test: ['test/spec/**/*.js'],
  testRequire: [
    yeoman.app + '/bower_components/angular/angular.js',
    yeoman.app + '/bower_components/angular-mocks/angular-mocks.js',
    yeoman.app + '/bower_components/angular-resource/angular-resource.js',
    yeoman.app + '/bower_components/angular-cookies/angular-cookies.js',
    yeoman.app + '/bower_components/angular-sanitize/angular-sanitize.js',
    yeoman.app + '/bower_components/angular-route/angular-route.js',
    'test/mock/**/*.js',
    'test/spec/**/*.js'
  ],
  karma: 'karma.conf.js',
  views: {
    main: yeoman.app + '/index.html',
    files: [ yeoman.app + '/views/**/*.html' ]
  }
};

////////////////////////
// Reusable pipelines //
////////////////////////

var lintScripts = lazypipe()
  .pipe($.jshint, '.jshintrc')
  .pipe($.jshint.reporter, 'jshint-stylish');

var styles = lazypipe()
  .pipe($.autoprefixer, 'last 1 version')
  .pipe(gulp.dest, '.tmp/styles');

///////////
// Tasks //
///////////

gulp.task('styles', function () {
  return gulp.src(paths.styles)
    .pipe(styles());
});

gulp.task('lint:scripts', function () {
  return gulp.src(paths.scripts)
    .pipe(lintScripts());
});

gulp.task('clean:tmp', function (cb) {
  rimraf('./.tmp', cb);
});

gulp.task('watch', function () {
  gulp.watch('bower.json', ['bower']);
});

// inject bower components
gulp.task('bower', function () {
  return gulp.src(paths.views.main)
    .pipe(wiredep({
      directory: yeoman.app + '/bower_components',
      ignorePath: '..'
    }))
  .pipe(gulp.dest(yeoman.app + '/views'));
});

gulp.task('html', function () {
  return gulp.src(yeoman.app + '/views/**/*')
    .pipe(gulp.dest(yeoman.dist + '/views'));
});

gulp.task('html:app', function () {
  return gulp.src(yeoman.app + '/scripts/app/views/**/*.html')
    .pipe(gulp.dest(yeoman.dist + '/scripts/app/views'));
});

gulp.task('html:cluster', function () {
  return gulp.src(yeoman.app + '/scripts/modules/cluster/views/**/*.html')
    .pipe(gulp.dest(yeoman.dist + '/scripts/modules/cluster/views'));
});

gulp.task('html:country', function () {
  return gulp.src(yeoman.app + '/scripts/modules/country/ethiopia/views/**/*.html')
    .pipe(gulp.dest(yeoman.dist + '/scripts/modules/country/ethiopia/views'));
});

///////////
// Build //
///////////

gulp.task('clean:dist', function (cb) {
  rimraf('./dist', cb);
});

gulp.task('client:build', [ 'html', 'html:app', 'html:cluster', 'html:country', 'styles' ], function () {
  var jsFilter = $.filter('**/*.js', {restore: true});
  var cssFilter = $.filter('**/*.css', {restore: true});
  var gulpUtil = require('gulp-util');

  return gulp.src(paths.views.main)
    .pipe($.useref({searchPath: [yeoman.app, '.tmp']}))
    .pipe(jsFilter)
    .pipe($.ngAnnotate())
    // .pipe($.uglify())
    .pipe($.uglify().on('error', gulpUtil.log))
    .pipe(jsFilter.restore())
    .pipe(cssFilter)
    .pipe($.minifyCss({cache: true}))
    .pipe(cssFilter.restore())
    .pipe($.rev())
    .pipe($.revReplace())
    // .pipe(header(getLicense()))
    // .pipe(header('/* ' + pkg.name + ' version ' + pkg.version + ' */ \n' ))
    .pipe(gulp.dest(yeoman.dist));
});

gulp.task('rename:index', function () {
  return gulp.src(yeoman.dist + '/*.html')
    .pipe($.rename('/index.html'))
    .pipe(gulp.dest(yeoman.dist));
});

gulp.task('ngm:images', function () {
  return gulp.src(yeoman.app + '/images/*')
    .pipe($.cache($.imagemin({
        optimizationLevel: 5,
        progressive: true,
        interlaced: true
    })))
    .pipe(gulp.dest(yeoman.dist + '/images'));
});
gulp.task('ngm:imagesCluster', function () {
  return gulp.src(yeoman.app + '/images/cluster/*')
    .pipe($.cache($.imagemin({
        optimizationLevel: 5,
        progressive: true,
        interlaced: true
    })))
    .pipe(gulp.dest(yeoman.dist + '/images/cluster'));
});
gulp.task('ngm:imagesCountry', function () {
  return gulp.src(yeoman.app + '/images/country/**/*')
    .pipe($.cache($.imagemin({
        optimizationLevel: 5,
        progressive: true,
        interlaced: true
    })))
    .pipe(gulp.dest(yeoman.dist + '/images/country'));
});
gulp.task('ngm:imagesSnapshots', function () {
  return gulp.src(yeoman.app + '/images/snapshots/**/*')
    .pipe($.cache($.imagemin({
        optimizationLevel: 5,
        progressive: true,
        interlaced: true
    })))
    .pipe(gulp.dest(yeoman.dist + '/images/snapshots'));
});

gulp.task('bower:images', function () {
  return gulp.src(yeoman.app + '/../bower_components/**/images/**/*')
    .pipe($.flatten())
    .pipe(gulp.dest(yeoman.dist + '/styles/images'));
});

gulp.task('fullscreen:images', function () {
  return gulp.src(yeoman.app + '/images/fullscreen.png')
    .pipe(gulp.dest(yeoman.dist + '/styles'));
});

gulp.task('copy:static', function () {
  return gulp.src(yeoman.app + '/static/**/*')
    .pipe(gulp.dest(yeoman.dist + '/static'));
});

gulp.task('copy:extras', function () {
  return gulp.src(yeoman.app + '/*/.*', { dot: true })
    .pipe(gulp.dest(yeoman.dist));
});

gulp.task('copy:widgets', function () {
  // widgets
  gulp.src(yeoman.app + '/scripts/widgets/**/*.js')
    .pipe(gulp.dest(yeoman.dist + '/scripts/widgets'));
  // html
  gulp.src(yeoman.app + '/scripts/widgets/**/*.html')
    .pipe(gulp.dest(yeoman.dist + '/scripts/widgets'));
});

gulp.task('copy:fonts', function () {
  return gulp.src(yeoman.app + '/fonts/**/*')
    .pipe(gulp.dest(yeoman.dist + '/fonts'));
});

gulp.task('copy:mfonts', function () {
  return gulp.src(yeoman.app + '/../bower_components/materialize/fonts/**/*')
    .pipe(gulp.dest(yeoman.dist + '/fonts'));
});

gulp.task('build', ['clean:dist'], function () {
  runSequence(['ngm:images', 'ngm:imagesCluster', 'ngm:imagesCountry', 'ngm:imagesSnapshots', 'bower:images', 'fullscreen:images', 'copy:static', 'copy:extras', 'copy:widgets', 'copy:fonts', 'copy:mfonts', 'client:build'], 'rename:index');
});

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

<|endoftext|>


<commit_before>'use strict';

const _ = require('lodash'),
	fs = require('fs'),
	defaultAssets = require('./config/assets/assets'),
	gulp = require('gulp'),
	gulpLoadPlugins = require('gulp-load-plugins'),
	ts = require('gulp-typescript'),
	sourcemaps = require('gulp-sourcemaps'),
	path = require('path'),
	plugins = gulpLoadPlugins(),
	webpack = require('webpack'),
	webpack_stream = require('webpack-stream'),
	webpack_config = require('./webpack.config.js');

// Define paths for webpack
const paths = require('./paths');

const tsProject = ts.createProject({
	target: 'es2015',
	module: 'commonjs',
	moduleResolution: 'node',
	sourceMap: true,
	emitDecoratorMetadata: true,
	experimentalDecorators: true,
	removeComments: true,
	noImplicitAny: false,
	allowJs: true,
	outDir: './server-dist',
	esModuleInterop: true
});

// Set NODE_ENV to 'test'
gulp.task('env:test', function() {
	process.env.NODE_ENV = 'test';
});

// Set NODE_ENV to 'development'
gulp.task('env:dev', () => {
	return new Promise((resolve, reject) => {
		process.env.NODE_ENV = 'development';
		resolve();
	});
});

// Set NODE_ENV to 'production'
gulp.task('env:prod', () => {
	return new Promise((resolve, reject) => {
		process.env.NODE_ENV = 'production';
		resolve();
	});
});

// Webpack task with watch
gulp.task('webpack-watch', callback => {
	var webpackStatsConfig = {
		colors: true,
		hash: false,
		version: false,
		timings: false,
		assets: true,
		chunks: false,
		chunkModules: false,
		modules: false,
		children: false,
		cached: false,
		cachedAssets: false,
		reasons: false,
		source: false,
		errorDetails: false,
		chunkOrigins: false
	};

	// load separate webpack configurations for each environment
	const config = webpack_config(process.env.NODE_ENV);
	return webpack_stream(config, webpack, (err, stats) => {
		console.log(stats.toString(webpackStatsConfig));
		callback();
	}).pipe(gulp.dest(`${paths.build}`));
});

// Webpack
gulp.task('webpack', callback => {
	const config = webpack_config(process.env.NODE_ENV);
	return webpack_stream(config).pipe(gulp.dest(`${paths.build}`));
});

// TypeScript (server)
gulp.task('tsc-server', () => {

	return gulp
		.src(_.union(defaultAssets.server.allTS, defaultAssets.server.allJS), { base: './' })
		.pipe(sourcemaps.init())
		.pipe(tsProject())
		.pipe(
			sourcemaps.write('.', {
				mapSources: path => path,
				sourceRoot: file => {
					return path.relative(file.relative, path.join(file.cwd, './server-dist'));
				}
			})
		)
		.pipe(gulp.dest(path.resolve('./server-dist')));
});

// Nodemon task
gulp.task('nodemon', () => {
	return new Promise(resolve => {
		plugins.nodemon({
			script: 'server-dist/server.js',
			nodeArgs: ['--inspect=0.0.0.0:9229', '-r', 'dotenv/config'],
			ext: 'ts,js,html',
			tasks: ['tsc-server'],
			watch: _.union(defaultAssets.server.views, defaultAssets.server.allJS, defaultAssets.server.allTS)
		});
		resolve();
	});
});

// Nodemon debug task
gulp.task('nodemon-debug', function() {
	return new Promise(resolve => {
		plugins.nodemon({
			script: 'server-dist/server.js',
			nodeArgs: ['--inspect-brk=0.0.0.0:9229', '-r', 'dotenv/config'],
			ext: 'ts,js,html',
			verbose: true,
			tasks: ['tsc-server'],
			watch: _.union(defaultAssets.server.views, defaultAssets.server.allJS, defaultAssets.server.allTS)
		});
		resolve();
	});
});

// Make sure upload directory exists
gulp.task('makeUploadsDir', () => {
	return fs.mkdir('modules/core/client/img/uploads', err => {
		if (err && err.code !== 'EEXIST') {
			console.error(err);
		}
	});
});

// Lint project files and run webpack
gulp.task('build', gulp.series('env:prod', 'webpack', 'tsc-server'));

// Run without livereload/webpack watch - used when developing containerized solution to keep machines from spinning up
gulp.task('quiet', gulp.series('env:dev', 'webpack', 'nodemon'));

// Run the project in development mode (watch/livereload on webpack)
gulp.task('default', gulp.series('env:dev', 'webpack-watch', 'nodemon'));

// Run the project but automatically break on init - used for debugging startup issues
gulp.task('debug', gulp.series('env:dev', 'webpack-watch', 'nodemon-debug'));

// Run the project in production mode
gulp.task('prod', gulp.series('env:prod', 'webpack', 'nodemon'));
<commit_msg>BA-1069 - Fix issue where typescript not always build for nodemon task<commit_after>'use strict';

const _ = require('lodash'),
	fs = require('fs'),
	defaultAssets = require('./config/assets/assets'),
	gulp = require('gulp'),
	gulpLoadPlugins = require('gulp-load-plugins'),
	ts = require('gulp-typescript'),
	sourcemaps = require('gulp-sourcemaps'),
	path = require('path'),
	plugins = gulpLoadPlugins(),
	webpack = require('webpack'),
	webpack_stream = require('webpack-stream'),
	webpack_config = require('./webpack.config.js');

// Define paths for webpack
const paths = require('./paths');

const tsProject = ts.createProject({
	target: 'es2015',
	module: 'commonjs',
	moduleResolution: 'node',
	sourceMap: true,
	emitDecoratorMetadata: true,
	experimentalDecorators: true,
	removeComments: true,
	noImplicitAny: false,
	allowJs: true,
	outDir: './server-dist',
	esModuleInterop: true
});

// Set NODE_ENV to 'test'
gulp.task('env:test', function() {
	process.env.NODE_ENV = 'test';
});

// Set NODE_ENV to 'development'
gulp.task('env:dev', () => {
	return new Promise((resolve, reject) => {
		process.env.NODE_ENV = 'development';
		resolve();
	});
});

// Set NODE_ENV to 'production'
gulp.task('env:prod', () => {
	return new Promise((resolve, reject) => {
		process.env.NODE_ENV = 'production';
		resolve();
	});
});

// Webpack task with watch
gulp.task('webpack-watch', callback => {
	var webpackStatsConfig = {
		colors: true,
		hash: false,
		version: false,
		timings: false,
		assets: true,
		chunks: false,
		chunkModules: false,
		modules: false,
		children: false,
		cached: false,
		cachedAssets: false,
		reasons: false,
		source: false,
		errorDetails: false,
		chunkOrigins: false
	};

	// load separate webpack configurations for each environment
	const config = webpack_config(process.env.NODE_ENV);
	return webpack_stream(config, webpack, (err, stats) => {
		console.log(stats.toString(webpackStatsConfig));
		callback();
	}).pipe(gulp.dest(`${paths.build}`));
});

// Webpack
gulp.task('webpack', callback => {
	const config = webpack_config(process.env.NODE_ENV);
	return webpack_stream(config).pipe(gulp.dest(`${paths.build}`));
});

// TypeScript (server)
gulp.task('tsc-server', () => {

	return gulp
		.src(_.union(defaultAssets.server.allTS, defaultAssets.server.allJS), { base: './' })
		.pipe(sourcemaps.init())
		.pipe(tsProject())
		.pipe(
			sourcemaps.write('.', {
				mapSources: path => path,
				sourceRoot: file => {
					return path.relative(file.relative, path.join(file.cwd, './server-dist'));
				}
			})
		)
		.pipe(gulp.dest(path.resolve('./server-dist')));
});

// Nodemon task
gulp.task('nodemon', () => {
	return new Promise(resolve => {
		plugins.nodemon({
			script: 'server-dist/server.js',
			nodeArgs: ['--inspect=0.0.0.0:9229', '-r', 'dotenv/config'],
			ext: 'ts,js,html',
			tasks: ['tsc-server'],
			watch: _.union(defaultAssets.server.views, defaultAssets.server.allJS, defaultAssets.server.allTS)
		});
		resolve();
	});
});

// Nodemon debug task
gulp.task('nodemon-debug', function() {
	return new Promise(resolve => {
		plugins.nodemon({
			script: 'server-dist/server.js',
			nodeArgs: ['--inspect-brk=0.0.0.0:9229', '-r', 'dotenv/config'],
			ext: 'ts,js,html',
			verbose: true,
			tasks: ['tsc-server'],
			watch: _.union(defaultAssets.server.views, defaultAssets.server.allJS, defaultAssets.server.allTS)
		});
		resolve();
	});
});

// Make sure upload directory exists
gulp.task('makeUploadsDir', () => {
	return fs.mkdir('modules/core/client/img/uploads', err => {
		if (err && err.code !== 'EEXIST') {
			console.error(err);
		}
	});
});

// Lint project files and run webpack
gulp.task('build', gulp.series('env:prod', 'webpack', 'tsc-server'));

// Run without livereload/webpack watch - used when developing containerized solution to keep machines from spinning up
gulp.task('quiet', gulp.series('env:dev', 'webpack', 'tsc-server', 'nodemon'));

// Run the project in development mode (watch/livereload on webpack)
gulp.task('default', gulp.series('env:dev', 'webpack-watch', 'tsc-server', 'nodemon'));

// Run the project but automatically break on init - used for debugging startup issues
gulp.task('debug', gulp.series('env:dev', 'webpack-watch', 'tsc-server', 'nodemon-debug'));

// Run the project in production mode
gulp.task('prod', gulp.series('env:prod', 'webpack', 'tsc-server', 'nodemon'));
<|endoftext|>


<commit_before>// ==========================================================================
// Gulp build script
// ==========================================================================
/* global require, __dirname */
/* eslint no-console: "off" */

const del = require('del');
const path = require('path');
const gulp = require('gulp');
const gutil = require('gulp-util');
const concat = require('gulp-concat');
const filter = require('gulp-filter');
const sass = require('gulp-sass');
const cleancss = require('gulp-clean-css');
const run = require('run-sequence');
const header = require('gulp-header');
const prefix = require('gulp-autoprefixer');
const gitbranch = require('git-branch');
const svgstore = require('gulp-svgstore');
const svgmin = require('gulp-svgmin');
const rename = require('gulp-rename');
const s3 = require('gulp-s3');
const replace = require('gulp-replace');
const open = require('gulp-open');
const size = require('gulp-size');
const rollup = require('gulp-better-rollup');
const babel = require('rollup-plugin-babel');
const sourcemaps = require('gulp-sourcemaps');
const uglify = require('gulp-uglify-es').default;
const commonjs = require('rollup-plugin-commonjs');
const resolve = require('rollup-plugin-node-resolve');
const FastlyPurge = require('fastly-purge');
const through = require('through2');

const bundles = require('./bundles.json');
const pkg = require('./package.json');

const minSuffix = '.min';

// Paths
const root = __dirname;
const paths = {
    plyr: {
        // Source paths
        src: {
            sass: path.join(root, 'src/sass/**/*.scss'),
            js: path.join(root, 'src/js/**/*'),
            sprite: path.join(root, 'src/sprite/*.svg'),
        },

        // Output paths
        output: path.join(root, 'dist/'),
    },
    demo: {
        // Source paths
        src: {
            sass: path.join(root, 'demo/src/sass/**/*.scss'),
            js: path.join(root, 'demo/src/js/**/*'),
        },

        // Output paths
        output: path.join(root, 'demo/dist/'),

        // Demo
        root: path.join(root, 'demo/'),
    },
    upload: [
        path.join(root, `dist/*${minSuffix}.*`),
        path.join(root, 'dist/*.css'),
        path.join(root, 'dist/*.svg'),
        path.join(root, `demo/dist/*${minSuffix}.*`),
        path.join(root, 'demo/dist/*.css'),
    ],
};

// Task arrays
const tasks = {
    sass: [],
    js: [],
    sprite: [],
    clean: ['clean'],
};

// Size plugin
const sizeOptions = { showFiles: true, gzip: true };

// Browserlist
const browsers = ['> 1%'];

// Babel config
const babelrc = {
    presets: [
        [
            'env',
            {
                targets: {
                    browsers,
                },
                useBuiltIns: true,
                modules: false,
            },
        ],
    ],
    plugins: ['external-helpers'],
    babelrc: false,
    exclude: 'node_modules/**',
};

// Clean out /dist
gulp.task('clean', () => {
    const dirs = [paths.plyr.output, paths.demo.output].map(dir =>
        path.join(dir, '**/*'),
    );

    // Don't delete the mp4
    dirs.push(`!${path.join(paths.plyr.output, '**/*.mp4')}`);

    del(dirs);
});

const build = {
    js(files, bundle, options) {
        Object.keys(files).forEach(key => {
            const name = `js:${key}`;
            tasks.js.push(name);
            const { output } = paths[bundle];

            return gulp.task(name, () =>
                gulp
                    .src(bundles[bundle].js[key])
                    .pipe(sourcemaps.init())
                    .pipe(concat(key))
                    .pipe(
                        rollup(
                            {
                                plugins: [
                                    resolve(),
                                    commonjs(),
                                    babel(babelrc),
                                ],
                            },
                            options,
                        ),
                    )
                    .pipe(header('typeof navigator === "object" && ')) // "Support" SSR (#935)
                    .pipe(sourcemaps.write(''))
                    .pipe(gulp.dest(output))
                    .pipe(filter('**/*.js'))
                    .pipe(uglify())
                    .pipe(size(sizeOptions))
                    .pipe(rename({ suffix: minSuffix }))
                    .pipe(sourcemaps.write(''))
                    .pipe(gulp.dest(output)),
            );
        });
    },
    sass(files, bundle) {
        Object.keys(files).forEach(key => {
            const name = `sass:${key}`;
            tasks.sass.push(name);

            return gulp.task(name, () =>
                gulp
                    .src(bundles[bundle].sass[key])
                    .pipe(sass())
                    .on('error', gutil.log)
                    .pipe(concat(key))
                    .pipe(prefix(browsers, { cascade: false }))
                    .pipe(cleancss())
                    .pipe(size(sizeOptions))
                    .pipe(gulp.dest(paths[bundle].output)),
            );
        });
    },
    sprite(bundle) {
        const name = `svg:sprite:${bundle}`;
        tasks.sprite.push(name);

        // Process Icons
        return gulp.task(name, () =>
            gulp
                .src(paths[bundle].src.sprite)
                .pipe(
                    svgmin({
                        plugins: [
                            {
                                removeDesc: true,
                            },
                        ],
                    }),
                )
                .pipe(svgstore())
                .pipe(rename({ basename: bundle }))
                .pipe(size(sizeOptions))
                .pipe(gulp.dest(paths[bundle].output)),
        );
    },
};

// Plyr core files
build.js(bundles.plyr.js, 'plyr', { name: 'Plyr', format: 'umd' });
build.sass(bundles.plyr.sass, 'plyr');
build.sprite('plyr');

// Demo files
build.sass(bundles.demo.sass, 'demo');
build.js(bundles.demo.js, 'demo', { format: 'iife' });

// Build all JS
gulp.task('js', () => {
    run(tasks.js);
});

// Watch for file changes
gulp.task('watch', () => {
    // Plyr core
    gulp.watch(paths.plyr.src.js, tasks.js);
    gulp.watch(paths.plyr.src.sass, tasks.sass);
    gulp.watch(paths.plyr.src.sprite, tasks.sprite);

    // Demo
    gulp.watch(paths.demo.src.js, tasks.js);
    gulp.watch(paths.demo.src.sass, tasks.sass);
});

// Build distribution
gulp.task('build', () => {
    run(tasks.clean, tasks.js, tasks.sass, tasks.sprite);
});

// Default gulp task
gulp.task('default', () => {
    run('build', 'watch');
});

// Publish a version to CDN and demo
// --------------------------------------------
// Get deployment config
let credentials = {};
try {
    credentials = require('./credentials.json'); //eslint-disable-line
} catch (e) {
    // Do nothing
}

// If deployment is setup
if (
    Object.keys(credentials).includes('cdn') &&
    Object.keys(credentials).includes('demo')
) {
    const { version } = pkg;
    const { aws, fastly } = credentials;

    // Get branch info
    const branch = {
        current: gitbranch.sync(),
        master: 'master',
        develop: 'develop',
    };

    const maxAge = 31536000; // 1 year
    const options = {
        cdn: {
            headers: {
                'Cache-Control': `max-age=${maxAge}`,
                Vary: 'Accept-Encoding',
            },
        },
        demo: {
            uploadPath: branch.current === branch.develop ? 'beta/' : null,
            headers: {
                'Cache-Control':
                    'no-cache, no-store, must-revalidate, max-age=0',
                Vary: 'Accept-Encoding',
            },
        },
        symlinks(ver, filename) {
            return {
                headers: {
                    // http://stackoverflow.com/questions/2272835/amazon-s3-object-redirect
                    'x-amz-website-redirect-location': `/${ver}/${filename}`,
                    'Cache-Control':
                        'no-cache, no-store, must-revalidate, max-age=0',
                },
            };
        },
    };

    const regex =
        '(?:0|[1-9][0-9]*)\\.(?:0|[1-9][0-9]*).(?:0|[1-9][0-9]*)(?:-[\\da-z\\-]+(?:.[\\da-z\\-]+)*)?(?:\\+[\\da-z\\-]+(?:.[\\da-z\\-]+)*)?';
    const semver = new RegExp(`v${regex}`, 'gi');
    const localPath = new RegExp('(../)?dist', 'gi');
    const versionPath = `https://${aws.cdn.domain}/${version}`;
    const cdnpath = new RegExp(`${aws.cdn.domain}/${regex}/`, 'gi');

    const renameFile = rename(p => {
        p.basename = p.basename.replace(minSuffix, ''); // eslint-disable-line
        p.dirname = p.dirname.replace('.', version); // eslint-disable-line
    });

    // Check we're on the correct branch to deploy
    const canDeploy = () => {
        const allowed = [branch.master, branch.develop];

        if (!allowed.includes(branch.current)) {
            console.error(
                `Must be on ${allowed.join(', ')} to publish! (current: ${
                    branch.current
                })`,
            );

            return false;
        }

        return true;
    };

    gulp.task('version', () => {
        if (!canDeploy()) {
            return null;
        }

        console.log(`Updating versions to '${version}'...`);

        // Replace versioned URLs in source
        const files = ['plyr.js', 'plyr.polyfilled.js', 'defaults.js'];

        return gulp
            .src(files.map(file => path.join(root, `src/js/${file}`)))
            .pipe(replace(semver, `v${version}`))
            .pipe(replace(cdnpath, `${aws.cdn.domain}/${version}/`))
            .pipe(gulp.dest(path.join(root, 'src/js/')));
    });

    // Publish version to CDN bucket
    gulp.task('cdn', () => {
        if (!canDeploy()) {
            return null;
        }

        console.log(`Uploading '${version}' to ${aws.cdn.domain}...`);

        // Upload to CDN
        return (
            gulp
                .src(paths.upload)
                .pipe(renameFile)
                // Remove min suffix from source map URL
                .pipe(
                    replace(
                        /sourceMappingURL=([\w-?.]+)/,
                        (match, p1) =>
                            `sourceMappingURL=${p1.replace(minSuffix, '')}`,
                    ),
                )
                .pipe(
                    size({
                        showFiles: true,
                        gzip: true,
                    }),
                )
                .pipe(replace(localPath, versionPath))
                .pipe(s3(aws.cdn, options.cdn))
        );
    });

    // Purge the fastly cache incase any 403/404 are cached
    gulp.task('purge', () => {
        const list = [];

        return gulp.src(paths.upload).pipe(
            through.obj((file, enc, cb) => {
                const filename = file.path.split('/').pop();
                list.push(`${versionPath}/${filename}`);
                cb(null);
            }),
        ).on('end', () => {
            const purge = new FastlyPurge(fastly.token);

            list.forEach(url => {
                console.log(`Purging ${url}...`);

                purge.url(url, (error, result) => {
                    if (error) {
                        console.log(error);
                    } else if (result) {
                        console.log(result);
                    }
                });
            });
        });
    });

    // Publish to demo bucket
    gulp.task('demo', () => {
        if (!canDeploy()) {
            return null;
        }

        console.log(`Uploading '${version}' demo to ${aws.demo.domain}...`);

        // Replace versioned files in readme.md
        gulp
            .src([`${root}/readme.md`])
            .pipe(replace(cdnpath, `${aws.cdn.domain}/${version}/`))
            .pipe(gulp.dest(root));

        // Replace local file paths with remote paths in demo HTML
        // e.g. "../dist/plyr.js" to "https://cdn.plyr.io/x.x.x/plyr.js"
        const index = `${paths.demo.root}index.html`;
        const error = `${paths.demo.root}error.html`;
        const pages = [index];

        if (branch.current === branch.master) {
            pages.push(error);
        }

        gulp
            .src(pages)
            .pipe(replace(localPath, versionPath))
            .pipe(s3(aws.demo, options.demo));

        // Only update CDN for master (prod)
        if (branch.current !== branch.master) {
            return null;
        }

        // Upload error.html to cdn (as well as demo site)
        return gulp
            .src([error])
            .pipe(replace(localPath, versionPath))
            .pipe(s3(aws.cdn, options.demo));
    });

    // Update symlinks for latest
    /* gulp.task("symlinks", function () {
        console.log("Updating symlinks...");

        return gulp.src(paths.upload)
            .pipe(through.obj(function (chunk, enc, callback) {
                if (chunk.stat.isFile()) {
                    // Get the filename
                    var filename = chunk.path.split("/").reverse()[0];

                    // Create the 0 byte redirect files to upload
                    createFile(filename, "")
                        .pipe(rename(function (path) {
                            path.dirname = path.dirname.replace(".", "latest");
                        }))
                        // Upload to S3 with correct headers
                        .pipe(s3(aws.cdn, options.symlinks(version, filename)));
                }

                callback(null, chunk);
            }));
    }); */

    // Open the demo site to check it's ok
    gulp.task('open', callback => {
        gulp.src(__filename).pipe(
            open({
                uri: `https://${aws.demo.domain}`,
            }),
        );

        callback();
    });

    // Do everything
    gulp.task('deploy', () =>
        run(
            'version',
            tasks.clean,
            tasks.js,
            tasks.sass,
            tasks.sprite,
            'cdn',
            'purge',
            'demo',
            'open',
        ),
    );
}
<commit_msg>Logic fix<commit_after>// ==========================================================================
// Gulp build script
// ==========================================================================
/* global require, __dirname */
/* eslint no-console: "off" */

const del = require('del');
const path = require('path');
const gulp = require('gulp');
const gutil = require('gulp-util');
const concat = require('gulp-concat');
const filter = require('gulp-filter');
const sass = require('gulp-sass');
const cleancss = require('gulp-clean-css');
const run = require('run-sequence');
const header = require('gulp-header');
const prefix = require('gulp-autoprefixer');
const gitbranch = require('git-branch');
const svgstore = require('gulp-svgstore');
const svgmin = require('gulp-svgmin');
const rename = require('gulp-rename');
const s3 = require('gulp-s3');
const replace = require('gulp-replace');
const open = require('gulp-open');
const size = require('gulp-size');
const rollup = require('gulp-better-rollup');
const babel = require('rollup-plugin-babel');
const sourcemaps = require('gulp-sourcemaps');
const uglify = require('gulp-uglify-es').default;
const commonjs = require('rollup-plugin-commonjs');
const resolve = require('rollup-plugin-node-resolve');
const FastlyPurge = require('fastly-purge');
const through = require('through2');

const bundles = require('./bundles.json');
const pkg = require('./package.json');

const minSuffix = '.min';

// Paths
const root = __dirname;
const paths = {
    plyr: {
        // Source paths
        src: {
            sass: path.join(root, 'src/sass/**/*.scss'),
            js: path.join(root, 'src/js/**/*'),
            sprite: path.join(root, 'src/sprite/*.svg'),
        },

        // Output paths
        output: path.join(root, 'dist/'),
    },
    demo: {
        // Source paths
        src: {
            sass: path.join(root, 'demo/src/sass/**/*.scss'),
            js: path.join(root, 'demo/src/js/**/*'),
        },

        // Output paths
        output: path.join(root, 'demo/dist/'),

        // Demo
        root: path.join(root, 'demo/'),
    },
    upload: [
        path.join(root, `dist/*${minSuffix}.*`),
        path.join(root, 'dist/*.css'),
        path.join(root, 'dist/*.svg'),
        path.join(root, `demo/dist/*${minSuffix}.*`),
        path.join(root, 'demo/dist/*.css'),
    ],
};

// Task arrays
const tasks = {
    sass: [],
    js: [],
    sprite: [],
    clean: ['clean'],
};

// Size plugin
const sizeOptions = { showFiles: true, gzip: true };

// Browserlist
const browsers = ['> 1%'];

// Babel config
const babelrc = {
    presets: [
        [
            'env',
            {
                targets: {
                    browsers,
                },
                useBuiltIns: true,
                modules: false,
            },
        ],
    ],
    plugins: ['external-helpers'],
    babelrc: false,
    exclude: 'node_modules/**',
};

// Clean out /dist
gulp.task('clean', () => {
    const dirs = [paths.plyr.output, paths.demo.output].map(dir =>
        path.join(dir, '**/*'),
    );

    // Don't delete the mp4
    dirs.push(`!${path.join(paths.plyr.output, '**/*.mp4')}`);

    del(dirs);
});

const build = {
    js(files, bundle, options) {
        Object.keys(files).forEach(key => {
            const name = `js:${key}`;
            tasks.js.push(name);
            const { output } = paths[bundle];

            return gulp.task(name, () =>
                gulp
                    .src(bundles[bundle].js[key])
                    .pipe(sourcemaps.init())
                    .pipe(concat(key))
                    .pipe(
                        rollup(
                            {
                                plugins: [
                                    resolve(),
                                    commonjs(),
                                    babel(babelrc),
                                ],
                            },
                            options,
                        ),
                    )
                    .pipe(header('typeof navigator === "object" && ')) // "Support" SSR (#935)
                    .pipe(sourcemaps.write(''))
                    .pipe(gulp.dest(output))
                    .pipe(filter('**/*.js'))
                    .pipe(uglify())
                    .pipe(size(sizeOptions))
                    .pipe(rename({ suffix: minSuffix }))
                    .pipe(sourcemaps.write(''))
                    .pipe(gulp.dest(output)),
            );
        });
    },
    sass(files, bundle) {
        Object.keys(files).forEach(key => {
            const name = `sass:${key}`;
            tasks.sass.push(name);

            return gulp.task(name, () =>
                gulp
                    .src(bundles[bundle].sass[key])
                    .pipe(sass())
                    .on('error', gutil.log)
                    .pipe(concat(key))
                    .pipe(prefix(browsers, { cascade: false }))
                    .pipe(cleancss())
                    .pipe(size(sizeOptions))
                    .pipe(gulp.dest(paths[bundle].output)),
            );
        });
    },
    sprite(bundle) {
        const name = `svg:sprite:${bundle}`;
        tasks.sprite.push(name);

        // Process Icons
        return gulp.task(name, () =>
            gulp
                .src(paths[bundle].src.sprite)
                .pipe(
                    svgmin({
                        plugins: [
                            {
                                removeDesc: true,
                            },
                        ],
                    }),
                )
                .pipe(svgstore())
                .pipe(rename({ basename: bundle }))
                .pipe(size(sizeOptions))
                .pipe(gulp.dest(paths[bundle].output)),
        );
    },
};

// Plyr core files
build.js(bundles.plyr.js, 'plyr', { name: 'Plyr', format: 'umd' });
build.sass(bundles.plyr.sass, 'plyr');
build.sprite('plyr');

// Demo files
build.sass(bundles.demo.sass, 'demo');
build.js(bundles.demo.js, 'demo', { format: 'iife' });

// Build all JS
gulp.task('js', () => {
    run(tasks.js);
});

// Watch for file changes
gulp.task('watch', () => {
    // Plyr core
    gulp.watch(paths.plyr.src.js, tasks.js);
    gulp.watch(paths.plyr.src.sass, tasks.sass);
    gulp.watch(paths.plyr.src.sprite, tasks.sprite);

    // Demo
    gulp.watch(paths.demo.src.js, tasks.js);
    gulp.watch(paths.demo.src.sass, tasks.sass);
});

// Build distribution
gulp.task('build', () => {
    run(tasks.clean, tasks.js, tasks.sass, tasks.sprite);
});

// Default gulp task
gulp.task('default', () => {
    run('build', 'watch');
});

// Publish a version to CDN and demo
// --------------------------------------------
// Get deployment config
let credentials = {};
try {
    credentials = require('./credentials.json'); //eslint-disable-line
} catch (e) {
    // Do nothing
}

// If deployment is setup
if (
    Object.keys(credentials).includes('aws') &&
    Object.keys(credentials).includes('fastly')
) {
    const { version } = pkg;
    const { aws, fastly } = credentials;

    // Get branch info
    const branch = {
        current: gitbranch.sync(),
        master: 'master',
        develop: 'develop',
    };

    const maxAge = 31536000; // 1 year
    const options = {
        cdn: {
            headers: {
                'Cache-Control': `max-age=${maxAge}`,
                Vary: 'Accept-Encoding',
            },
        },
        demo: {
            uploadPath: branch.current === branch.develop ? 'beta/' : null,
            headers: {
                'Cache-Control':
                    'no-cache, no-store, must-revalidate, max-age=0',
                Vary: 'Accept-Encoding',
            },
        },
        symlinks(ver, filename) {
            return {
                headers: {
                    // http://stackoverflow.com/questions/2272835/amazon-s3-object-redirect
                    'x-amz-website-redirect-location': `/${ver}/${filename}`,
                    'Cache-Control':
                        'no-cache, no-store, must-revalidate, max-age=0',
                },
            };
        },
    };

    const regex =
        '(?:0|[1-9][0-9]*)\\.(?:0|[1-9][0-9]*).(?:0|[1-9][0-9]*)(?:-[\\da-z\\-]+(?:.[\\da-z\\-]+)*)?(?:\\+[\\da-z\\-]+(?:.[\\da-z\\-]+)*)?';
    const semver = new RegExp(`v${regex}`, 'gi');
    const localPath = new RegExp('(../)?dist', 'gi');
    const versionPath = `https://${aws.cdn.domain}/${version}`;
    const cdnpath = new RegExp(`${aws.cdn.domain}/${regex}/`, 'gi');

    const renameFile = rename(p => {
        p.basename = p.basename.replace(minSuffix, ''); // eslint-disable-line
        p.dirname = p.dirname.replace('.', version); // eslint-disable-line
    });

    // Check we're on the correct branch to deploy
    const canDeploy = () => {
        const allowed = [branch.master, branch.develop];

        if (!allowed.includes(branch.current)) {
            console.error(
                `Must be on ${allowed.join(', ')} to publish! (current: ${
                    branch.current
                })`,
            );

            return false;
        }

        return true;
    };

    gulp.task('version', () => {
        if (!canDeploy()) {
            return null;
        }

        console.log(`Updating versions to '${version}'...`);

        // Replace versioned URLs in source
        const files = ['plyr.js', 'plyr.polyfilled.js', 'defaults.js'];

        return gulp
            .src(files.map(file => path.join(root, `src/js/${file}`)))
            .pipe(replace(semver, `v${version}`))
            .pipe(replace(cdnpath, `${aws.cdn.domain}/${version}/`))
            .pipe(gulp.dest(path.join(root, 'src/js/')));
    });

    // Publish version to CDN bucket
    gulp.task('cdn', () => {
        if (!canDeploy()) {
            return null;
        }

        console.log(`Uploading '${version}' to ${aws.cdn.domain}...`);

        // Upload to CDN
        return (
            gulp
                .src(paths.upload)
                .pipe(renameFile)
                // Remove min suffix from source map URL
                .pipe(
                    replace(
                        /sourceMappingURL=([\w-?.]+)/,
                        (match, p1) =>
                            `sourceMappingURL=${p1.replace(minSuffix, '')}`,
                    ),
                )
                .pipe(
                    size({
                        showFiles: true,
                        gzip: true,
                    }),
                )
                .pipe(replace(localPath, versionPath))
                .pipe(s3(aws.cdn, options.cdn))
        );
    });

    // Purge the fastly cache incase any 403/404 are cached
    gulp.task('purge', () => {
        const list = [];

        return gulp.src(paths.upload).pipe(
            through.obj((file, enc, cb) => {
                const filename = file.path.split('/').pop();
                list.push(`${versionPath}/${filename}`);
                cb(null);
            }),
        ).on('end', () => {
            const purge = new FastlyPurge(fastly.token);

            list.forEach(url => {
                console.log(`Purging ${url}...`);

                purge.url(url, (error, result) => {
                    if (error) {
                        console.log(error);
                    } else if (result) {
                        console.log(result);
                    }
                });
            });
        });
    });

    // Publish to demo bucket
    gulp.task('demo', () => {
        if (!canDeploy()) {
            return null;
        }

        console.log(`Uploading '${version}' demo to ${aws.demo.domain}...`);

        // Replace versioned files in readme.md
        gulp
            .src([`${root}/readme.md`])
            .pipe(replace(cdnpath, `${aws.cdn.domain}/${version}/`))
            .pipe(gulp.dest(root));

        // Replace local file paths with remote paths in demo HTML
        // e.g. "../dist/plyr.js" to "https://cdn.plyr.io/x.x.x/plyr.js"
        const index = `${paths.demo.root}index.html`;
        const error = `${paths.demo.root}error.html`;
        const pages = [index];

        if (branch.current === branch.master) {
            pages.push(error);
        }

        gulp
            .src(pages)
            .pipe(replace(localPath, versionPath))
            .pipe(s3(aws.demo, options.demo));

        // Only update CDN for master (prod)
        if (branch.current !== branch.master) {
            return null;
        }

        // Upload error.html to cdn (as well as demo site)
        return gulp
            .src([error])
            .pipe(replace(localPath, versionPath))
            .pipe(s3(aws.cdn, options.demo));
    });

    // Update symlinks for latest
    /* gulp.task("symlinks", function () {
        console.log("Updating symlinks...");

        return gulp.src(paths.upload)
            .pipe(through.obj(function (chunk, enc, callback) {
                if (chunk.stat.isFile()) {
                    // Get the filename
                    var filename = chunk.path.split("/").reverse()[0];

                    // Create the 0 byte redirect files to upload
                    createFile(filename, "")
                        .pipe(rename(function (path) {
                            path.dirname = path.dirname.replace(".", "latest");
                        }))
                        // Upload to S3 with correct headers
                        .pipe(s3(aws.cdn, options.symlinks(version, filename)));
                }

                callback(null, chunk);
            }));
    }); */

    // Open the demo site to check it's ok
    gulp.task('open', callback => {
        gulp.src(__filename).pipe(
            open({
                uri: `https://${aws.demo.domain}`,
            }),
        );

        callback();
    });

    // Do everything
    gulp.task('deploy', () =>
        run(
            'version',
            tasks.clean,
            tasks.js,
            tasks.sass,
            tasks.sprite,
            'cdn',
            'purge',
            'demo',
            'open',
        ),
    );
}
<|endoftext|>


<commit_before>import { settings } from '../../../settings';
import { Users } from '../../../models';

export function retrieveRegistrationStatus() {
	const info = {
		connectToCloud: settings.get('Register_Server'),
		workspaceRegistered: (settings.get('Cloud_Workspace_Client_Id')) ? true : false,
		workspaceId: settings.get('Cloud_Workspace_Id'),
		uniqueId: settings.get('uniqueID'),
		token: '',
		email: '',
	};

	const firstUser = Users.getOldest({ emails: 1 });
	info.email = firstUser && firstUser.emails[0].address;

	if (settings.get('Organization_Email')) {
		info.email = settings.get('Organization_Email');
	}

	return info;
}
<commit_msg>Update retrieveRegistrationStatus.js<commit_after>import { settings } from '../../../settings';
import { Users } from '../../../models';

export function retrieveRegistrationStatus() {
	const info = {
		connectToCloud: settings.get('Register_Server'),
		workspaceRegistered: (settings.get('Cloud_Workspace_Client_Id')) ? true : false,
		workspaceId: settings.get('Cloud_Workspace_Id'),
		uniqueId: settings.get('uniqueID'),
		token: '',
		email: '',
	};

	const firstUser = Users.getOldest({ emails: 1 });
	info.email = firstUser && firstUser.emails && firstUser.emails[0].address;

	if (settings.get('Organization_Email')) {
		info.email = settings.get('Organization_Email');
	}

	return info;
}
<|endoftext|>


<commit_before>var gulp = require('gulp');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var plumber = require('gulp-plumber');
var clean = require('gulp-clean');
var concat = require('gulp-concat');
var header = require('gulp-header');
var imagemin = require('gulp-imagemin');
var zip = require('gulp-zip');
// var debug = require('gulp-debug');
var runSequence = require('gulp-sequence');
var replace = require('gulp-replace');
var distPath = "dist/crysyan/";
var version = "0.0.9";
var widgetsLoad = [];

(function () {
    // var widgetConfig= require('js/config.js');
    // var widgetBasePath = "js/widget/";
    // var widgets = widgetConfig.CrysyanWidgetConfig.widgets;
    // for (var attr in widgets) {
    //     if (widgets[attr].hasOwnProperty("jsFile") && typeof widgets[attr].jsFile === "string" && widgets[attr].jsFile !== "") {
    //         widgetsLoad.push(widgetBasePath + widgets[attr].jsFile);
    //     }
    // }
    widgetPath="js/widget/";
    // widgetsLoad = [widgetPath+"*.js"]; or
    widgetsLoad = [
        widgetPath+"cursor.js",
        widgetPath+"pencil.js",
        widgetPath+"eraser.js",
        widgetPath+"image.js",
        widgetPath+"undo.js",
        widgetPath+"into-go.js",
        widgetPath+"clear.js"];
})();

gulp.task('clean-all', function () {
    return gulp.src([distPath + "*", distPath, "release/", "release/*"])
        .pipe(clean())
        .pipe(plumber());
});

gulp.task('designer-minify', function () {
    return gulp.src(["js/crysyan-designer.js"])
        .pipe(uglify())
        .pipe(plumber())
        .pipe(rename({suffix: '-min'}))
        .pipe(gulp.dest(distPath));
});

gulp.task('widgets-concat', function () {
    return gulp.src(widgetsLoad)
        .pipe(concat("widgets.js"))
        .pipe(plumber())
        .pipe(gulp.dest(distPath + "js/"));
});

gulp.task('core-concat', function () {
    return gulp.src(["js/util.js", "js/config.js", "js/widget.js", "js/canvas.js", "js/view.js"])
        .pipe(concat("core.js"))
        .pipe(plumber())
        .pipe(gulp.dest(distPath + "js/"));
});

gulp.task('core-header', function () {
    return gulp.src(["js/crysyan.js"])
        .pipe(header('var CrysyanFlag=false;'))
        .pipe(plumber())
        .pipe(gulp.dest(distPath + "js/"));
});

gulp.task('core-widgets-concat-minify', ["widgets-concat", "core-concat",'core-header'], function () {
    return gulp.src([distPath + "js/core.js", distPath + "js/widgets.js",distPath + "js/crysyan.js"])
        .pipe(concat("crysyan-core-min.js"))
        .pipe(plumber())
        .pipe(gulp.dest(distPath))
        .pipe(uglify())
        .pipe(plumber())
        .pipe(gulp.dest(distPath));
});

gulp.task('imagemin', function () {
    return gulp.src(["img/*"])
        .pipe(imagemin())
        .pipe(plumber())
        .pipe(gulp.dest(distPath + "img/"));
});

gulp.task('html-replace-move', function () {
    return gulp.src(["html/*"])
        .pipe(replace('src="../js/crysyan.js"', 'src="../crysyan-core-min.js"'))
        .pipe(plumber())
        .pipe(gulp.dest(distPath + "html/"));
});

gulp.task('guidance-move', function () {
    return gulp.src(["guidance.md"])
        .pipe(gulp.dest(distPath));
});

gulp.task('building', ['clean-all'], function (cb) {
    runSequence(
        ["designer-minify",
            "core-widgets-concat-minify",
            "imagemin",
            "html-replace-move","guidance-move"], cb);
});

gulp.task('after-building-clean', ['building'], function () {
    return gulp.src(['dist/js'])
        .pipe(clean())
        .pipe(plumber());
});

gulp.task('build', ['building','after-building-clean']);

gulp.task('publish', ['build'], function () {
    return gulp.src([distPath+'*', distPath+'**/*', "!"+distPath+'js'])
        .pipe(plumber())
        .pipe(zip('crysyan-' + version + '.zip'))
        .pipe(gulp.dest('release'));
});

gulp.task('default', ["build"]);
<commit_msg>gulp:: add demo-index.html<commit_after>var gulp = require('gulp');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var plumber = require('gulp-plumber');
var clean = require('gulp-clean');
var concat = require('gulp-concat');
var header = require('gulp-header');
var imagemin = require('gulp-imagemin');
var zip = require('gulp-zip');
// var debug = require('gulp-debug');
var runSequence = require('gulp-sequence');
var replace = require('gulp-replace');
var distPath = "dist/crysyan/";
var version = "0.0.9";
var widgetsLoad = [];

(function () {
    // var widgetConfig= require('js/config.js');
    // var widgetBasePath = "js/widget/";
    // var widgets = widgetConfig.CrysyanWidgetConfig.widgets;
    // for (var attr in widgets) {
    //     if (widgets[attr].hasOwnProperty("jsFile") && typeof widgets[attr].jsFile === "string" && widgets[attr].jsFile !== "") {
    //         widgetsLoad.push(widgetBasePath + widgets[attr].jsFile);
    //     }
    // }
    widgetPath="js/widget/";
    // widgetsLoad = [widgetPath+"*.js"]; or
    widgetsLoad = [
        widgetPath+"cursor.js",
        widgetPath+"pencil.js",
        widgetPath+"eraser.js",
        widgetPath+"image.js",
        widgetPath+"undo.js",
        widgetPath+"into-go.js",
        widgetPath+"clear.js"];
})();

gulp.task('clean-all', function () {
    return gulp.src([distPath + "*", distPath, "release/", "release/*"])
        .pipe(clean())
        .pipe(plumber());
});

gulp.task('designer-minify', function () {
    return gulp.src(["js/crysyan-designer.js"])
        .pipe(uglify())
        .pipe(plumber())
        .pipe(rename({suffix: '-min'}))
        .pipe(gulp.dest(distPath));
});

gulp.task('widgets-concat', function () {
    return gulp.src(widgetsLoad)
        .pipe(concat("widgets.js"))
        .pipe(plumber())
        .pipe(gulp.dest(distPath + "js/"));
});

gulp.task('core-concat', function () {
    return gulp.src(["js/util.js", "js/config.js", "js/widget.js", "js/canvas.js", "js/view.js"])
        .pipe(concat("core.js"))
        .pipe(plumber())
        .pipe(gulp.dest(distPath + "js/"));
});

gulp.task('core-header', function () {
    return gulp.src(["js/crysyan.js"])
        .pipe(header('var CrysyanFlag=false;'))
        .pipe(plumber())
        .pipe(gulp.dest(distPath + "js/"));
});

gulp.task('core-widgets-concat-minify', ["widgets-concat", "core-concat",'core-header'], function () {
    return gulp.src([distPath + "js/core.js", distPath + "js/widgets.js",distPath + "js/crysyan.js"])
        .pipe(concat("crysyan-core-min.js"))
        .pipe(plumber())
        .pipe(gulp.dest(distPath))
        .pipe(uglify())
        .pipe(plumber())
        .pipe(gulp.dest(distPath));
});

gulp.task('imagemin', function () {
    return gulp.src(["img/*"])
        .pipe(imagemin())
        .pipe(plumber())
        .pipe(gulp.dest(distPath + "img/"));
});

gulp.task('html-replace-move', function () {
    return gulp.src(["html/*"])
        .pipe(replace('src="../js/crysyan.js"', 'src="../crysyan-core-min.js"'))
        .pipe(plumber())
        .pipe(gulp.dest(distPath + "html/"));
});

gulp.task('demo-replace-move', function () {
    return gulp.src(["index.html"])
        .pipe(replace('src="../js/crysyan.js"', 'src="crysyan-core-min.js"'))
        .pipe(plumber())
        .pipe(rename({prefix: 'demo-'}))
        .pipe(gulp.dest(distPath));
});

gulp.task('guidance-move', function () {
    return gulp.src(["guidance.md"])
        .pipe(gulp.dest(distPath));
});

gulp.task('building', ['clean-all'], function (cb) {
    runSequence(
        ["designer-minify",
            "core-widgets-concat-minify",
            "imagemin",
            "html-replace-move","guidance-move","demo-replace-move"], cb);
});

gulp.task('after-building-clean', ['building'], function () {
    return gulp.src([distPath+'js',distPath+"dist/js/*"])
        .pipe(clean())
        .pipe(plumber());
});

gulp.task('build', ['building','after-building-clean']);

gulp.task('publish', ['build'], function () {
    return gulp.src([distPath+'*', distPath+'**/*', "!"+distPath+'js'])
        .pipe(plumber())
        .pipe(zip('crysyan-' + version + '.zip'))
        .pipe(gulp.dest('release'));
});

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


<commit_before>L.FieldStore.LineSnapStore = L.FieldStore.extend({

    _deserialize: function (value) {
        console.debug("Deserialize " + value);
        value = JSON.parse(value);
        value = value['geom'];
        return L.FieldStore.prototype._deserialize.call(this, value);
    },

    _serialize: function (layer) {
        var str = L.FieldStore.prototype._serialize.call(this, layer);

        var edited = layer.getLayers();
        if (edited.length === 0)
            return '';
        layer = edited[0];

        // Store snaplist
        var n = layer.getLatLngs().length,
            snaplist = new Array(n);
        if (layer.editing._poly.snapediting) {
            for (var i=0; i<n; i++) {
                var marker = layer.editing._poly.snapediting._markers[i];
                if (marker.snap && marker.snap.properties && marker.snap.properties.pk)
                    snaplist[i] = marker.snap.properties.pk;
            }
        }

        var serialized = {geom: str,
                          snap: snaplist};
        console.debug("Serialized to " + JSON.stringify(serialized));
        return JSON.stringify(serialized);
    }
});

MapEntity.GeometryField.GeometryFieldPathMixin = {
    /*
     * Load the path layer in addition to another layer should be reusable.
     * (At least for the fix to propagate events)
     */
    buildPathsLayer: function (objectsLayer) {
        var url_path = window.SETTINGS.urls.path_layer
        var pathsLayer = MapEntity.pathsLayer({style: {clickable: true}, no_draft: objectsLayer.modelname != 'path'});
        if (objectsLayer.modelname != 'path'){
            pathsLayer.load(url_path + '?no_draft=true', true);
        }
        else {
            pathsLayer.load(url_path, true);
        }

        this._map.addLayer(pathsLayer);

        // Propagate mouseover events, from the Path layer (on top)
        // to the objects layer (below).
        // This fixes bug #680
        (function (){
            // Reference to the object layer hovered before the path is hovered
            var overlapped = null;
            objectsLayer.on('mouseover', function (e) {
                overlapped = e.layer;
            });
            // On path hover, propagate events to overlapped layer
            pathsLayer.on('mouseover mouseout', function (e) {
                if (overlapped !== null) {
                    e.layer = overlapped;
                    e.target = overlapped;
                    overlapped.fire(e.type, e);
                }
                if (e.type == 'mouseout') {
                    overlapped = null;
                }
            });
        })();
        return pathsLayer;
    },
};

MapEntity.GeometryField.GeometryFieldSnap = MapEntity.GeometryField.extend({
    options: {
        field_store_class: L.FieldStore.LineSnapStore
    },

    includes: MapEntity.GeometryField.GeometryFieldPathMixin,

    initialize: function (options) {
        MapEntity.GeometryField.prototype.initialize.call(this, options);

        L.Handler.MarkerSnap.mergeOptions({
            snapDistance: window.SETTINGS.map.snap_distance
        });

        this._geometry = null;
        this._guidesLayers = [];
        this._pathsLayer = null;
        this._objectsLayer = null;
    },

    buildObjectsLayer: function () {
        this._objectsLayer = MapEntity.GeometryField.prototype.buildObjectsLayer(arguments);
        this._guidesLayers.push(this._objectsLayer);

        if (this.getModelName() != 'path') {
            // If current model is not path, we should add the path layer
            // as a guide layer.
            this._pathsLayer = this.buildPathsLayer(this._objectsLayer);
            this._guidesLayers.push(this._pathsLayer);
        }
        else {
            // It should like paths everywhere in the application
            var style = window.SETTINGS.map.styles.path;
            this._objectsLayer.options.style = style;
            this._objectsLayer.options.styles.default = style;
        }

        if (this._geometry) {
            // null if not loaded (e.g. creation form)
            this._initSnap(this._geometry);
        }

        return this._objectsLayer;
    },

    guidesLayers: function () {
        return this._guidesLayers;
    },

    _initSnap: function (layer) {
        var handlerClass = null;
        if (layer instanceof L.Marker) {
            handlerClass = L.Handler.MarkerSnap;
        }
        else if (layer instanceof L.Polyline) {
            handlerClass = L.Handler.PolylineSnap;
        }
        else {
            console.warn('Unsupported layer type for snap.');
            return;
        }
        layer.editing = new handlerClass(this._map, layer);
        for (var i=0, n=this._guidesLayers.length; i<n; i++) {
            layer.editing.addGuideLayer(this._guidesLayers[i]);
        }

        // Since snapping happens only once the geometry is created.
        // We are out of Leaflet.Draw.
        layer.on('move edit', function (e) {
            this.store.save(this.drawnItems);
        }, this);

        // On edition, show start and end markers as snapped
        this._map.on('draw:editstart', function (e) {
            setTimeout(function () {
                if (!layer.editing) {
                    console.warn('Layer has no snap editing');
                    return;  // should never happen ;)
                }
                var markers = layer.editing._markers;
                var first = markers[0],
                    last = markers[markers.length - 1];
                first.fire('move');
                last.fire('move');
            }, 0);
        });

    },

    onCreated: function (e) {
        MapEntity.GeometryField.prototype.onCreated.call(this, e);
        this._initSnap(e.layer);
    },

    load: function () {
        this._geometry = MapEntity.GeometryField.prototype.load.call(this);
        return this._geometry;
    }

});
<commit_msg>Fix condition, load url_path<commit_after>L.FieldStore.LineSnapStore = L.FieldStore.extend({

    _deserialize: function (value) {
        console.debug("Deserialize " + value);
        value = JSON.parse(value);
        value = value['geom'];
        return L.FieldStore.prototype._deserialize.call(this, value);
    },

    _serialize: function (layer) {
        var str = L.FieldStore.prototype._serialize.call(this, layer);

        var edited = layer.getLayers();
        if (edited.length === 0)
            return '';
        layer = edited[0];

        // Store snaplist
        var n = layer.getLatLngs().length,
            snaplist = new Array(n);
        if (layer.editing._poly.snapediting) {
            for (var i=0; i<n; i++) {
                var marker = layer.editing._poly.snapediting._markers[i];
                if (marker.snap && marker.snap.properties && marker.snap.properties.pk)
                    snaplist[i] = marker.snap.properties.pk;
            }
        }

        var serialized = {geom: str,
                          snap: snaplist};
        console.debug("Serialized to " + JSON.stringify(serialized));
        return JSON.stringify(serialized);
    }
});

MapEntity.GeometryField.GeometryFieldPathMixin = {
    /*
     * Load the path layer in addition to another layer should be reusable.
     * (At least for the fix to propagate events)
     */
    buildPathsLayer: function (objectsLayer) {
        var url_path = window.SETTINGS.urls.path_layer
        var pathsLayer = MapEntity.pathsLayer({style: {clickable: true}, no_draft: objectsLayer.modelname != 'path'});
        if (objectsLayer.modelname != 'path')
            url_path += '?no_draft=true';
        pathsLayer.load(url_path, true);

        this._map.addLayer(pathsLayer);

        // Propagate mouseover events, from the Path layer (on top)
        // to the objects layer (below).
        // This fixes bug #680
        (function (){
            // Reference to the object layer hovered before the path is hovered
            var overlapped = null;
            objectsLayer.on('mouseover', function (e) {
                overlapped = e.layer;
            });
            // On path hover, propagate events to overlapped layer
            pathsLayer.on('mouseover mouseout', function (e) {
                if (overlapped !== null) {
                    e.layer = overlapped;
                    e.target = overlapped;
                    overlapped.fire(e.type, e);
                }
                if (e.type == 'mouseout') {
                    overlapped = null;
                }
            });
        })();
        return pathsLayer;
    },
};

MapEntity.GeometryField.GeometryFieldSnap = MapEntity.GeometryField.extend({
    options: {
        field_store_class: L.FieldStore.LineSnapStore
    },

    includes: MapEntity.GeometryField.GeometryFieldPathMixin,

    initialize: function (options) {
        MapEntity.GeometryField.prototype.initialize.call(this, options);

        L.Handler.MarkerSnap.mergeOptions({
            snapDistance: window.SETTINGS.map.snap_distance
        });

        this._geometry = null;
        this._guidesLayers = [];
        this._pathsLayer = null;
        this._objectsLayer = null;
    },

    buildObjectsLayer: function () {
        this._objectsLayer = MapEntity.GeometryField.prototype.buildObjectsLayer(arguments);
        this._guidesLayers.push(this._objectsLayer);

        if (this.getModelName() != 'path') {
            // If current model is not path, we should add the path layer
            // as a guide layer.
            this._pathsLayer = this.buildPathsLayer(this._objectsLayer);
            this._guidesLayers.push(this._pathsLayer);
        }
        else {
            // It should like paths everywhere in the application
            var style = window.SETTINGS.map.styles.path;
            this._objectsLayer.options.style = style;
            this._objectsLayer.options.styles.default = style;
        }

        if (this._geometry) {
            // null if not loaded (e.g. creation form)
            this._initSnap(this._geometry);
        }

        return this._objectsLayer;
    },

    guidesLayers: function () {
        return this._guidesLayers;
    },

    _initSnap: function (layer) {
        var handlerClass = null;
        if (layer instanceof L.Marker) {
            handlerClass = L.Handler.MarkerSnap;
        }
        else if (layer instanceof L.Polyline) {
            handlerClass = L.Handler.PolylineSnap;
        }
        else {
            console.warn('Unsupported layer type for snap.');
            return;
        }
        layer.editing = new handlerClass(this._map, layer);
        for (var i=0, n=this._guidesLayers.length; i<n; i++) {
            layer.editing.addGuideLayer(this._guidesLayers[i]);
        }

        // Since snapping happens only once the geometry is created.
        // We are out of Leaflet.Draw.
        layer.on('move edit', function (e) {
            this.store.save(this.drawnItems);
        }, this);

        // On edition, show start and end markers as snapped
        this._map.on('draw:editstart', function (e) {
            setTimeout(function () {
                if (!layer.editing) {
                    console.warn('Layer has no snap editing');
                    return;  // should never happen ;)
                }
                var markers = layer.editing._markers;
                var first = markers[0],
                    last = markers[markers.length - 1];
                first.fire('move');
                last.fire('move');
            }, 0);
        });

    },

    onCreated: function (e) {
        MapEntity.GeometryField.prototype.onCreated.call(this, e);
        this._initSnap(e.layer);
    },

    load: function () {
        this._geometry = MapEntity.GeometryField.prototype.load.call(this);
        return this._geometry;
    }

});
<|endoftext|>


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

// Include plugins
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var stripDebug = require('gulp-strip-debug');
var sass = require('gulp-sass');
var optipng = require('gulp-optipng');
var options = ['-o2'];

/**
 *	TASK: optipng
 *	USES: gulp-optipng
 *  DESCRIPTION: Optimize all .png files
 */
gulp.task('optipng', function() {
	return gulp.src('img/logos/*.png')
		.pipe(optipng(options))
		.pipe(gulp.dest('img/optimized/'));
});

/**
 *	TASK: scripts
 *	USES: gulp-concat, gulp-rename, gulp-uglify
 *  DESCRIPTION: Concats all js files, compresses, and renames with .min
 */
gulp.task('scripts', function(){
	return gulp.src([
		'assets/js/jquery.min.js',
		'assets/js/bootstrap.min.js',
		'assets/js/lunr.min.js',
		'assets/js/set-query.js',
		'assets/js/main.js',
		'assets/js/modalizer.js',
		'assets/js/search.js',
		'assets/js/results.js'
		])
		.pipe(concat('all.js'))
		.pipe(rename({ suffix: '.min' }))
		.pipe(uglify())
		.pipe(gulp.dest('assets-dist/js/'));
});

/**
 *	TASK: sass
 *	USES: gulp-concat, gulp-sass, gulp-rename
 *  DESCRIPTION: Concats all scss files, compresses, and renames with .min
 */
var sassOptions = {
	errLogToConsole: true,
	outputStyle: 'compressed'
};
gulp.task('sass', function() {
	return gulp.src([
		'assets/scss/typography.scss',
		'assets/scss/variables.scss',
		'assets/scss/mixins.scss',
		'assets/scss/bootstrap-overrides.scss',
		'assets/scss/base.scss',
		'assets/scss/layouts.scss',
		'assets/scss/includes.scss'
		])
		.pipe(concat('all.scss'))
		.pipe(sass(sassOptions).on('error', sass.logError))
		.pipe(rename({ suffix: '.min' }))
		.pipe(gulp.dest('dist/css'))
});

/**
 *	TASK: stripdebug
 *	USES: gulp-strip-debug
 *  DESCRIPTION: Removes all console.log and debugging messages from js files
 */
gulp.task('stripdebug', function() {
	return gulp.src('assets/js/*.js')
	.pipe(stripDebug())
	.pipe(gulp.dest('dist/js/'));
});

// Default task
gulp.task('default', ['scripts', 'sass']);
<commit_msg>Remove strip-debug task. Manually removing console.logs. Resolves #62.<commit_after>// Include gulp
var gulp = require('gulp');

// Include plugins
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var stripDebug = require('gulp-strip-debug');
var sass = require('gulp-sass');
var optipng = require('gulp-optipng');
var options = ['-o2'];

/**
 *	TASK: optipng
 *	USES: gulp-optipng
 *  DESCRIPTION: Optimize all .png files
 */
gulp.task('optipng', function() {
	return gulp.src('img/logos/*.png')
		.pipe(optipng(options))
		.pipe(gulp.dest('img/optimized/'));
});

/**
 *	TASK: scripts
 *	USES: gulp-concat, gulp-rename, gulp-uglify
 *  DESCRIPTION: Concats all js files, compresses, and renames with .min
 */
gulp.task('scripts', function(){
	return gulp.src([
		'assets/js/jquery.min.js',
		'assets/js/bootstrap.min.js',
		'assets/js/lunr.min.js',
		'assets/js/set-query.js',
		'assets/js/main.js',
		'assets/js/modalizer.js',
		'assets/js/search.js',
		'assets/js/results.js'
		])
		.pipe(concat('all.js'))
		.pipe(rename({ suffix: '.min' }))
		.pipe(uglify())
		.pipe(gulp.dest('assets-dist/js/'));
});

/**
 *	TASK: sass
 *	USES: gulp-concat, gulp-sass, gulp-rename
 *  DESCRIPTION: Concats all scss files, compresses, and renames with .min
 */
var sassOptions = {
	errLogToConsole: true,
	outputStyle: 'compressed'
};
gulp.task('sass', function() {
	return gulp.src([
		'assets/scss/typography.scss',
		'assets/scss/variables.scss',
		'assets/scss/mixins.scss',
		'assets/scss/bootstrap-overrides.scss',
		'assets/scss/base.scss',
		'assets/scss/layouts.scss',
		'assets/scss/includes.scss'
		])
		.pipe(concat('all.scss'))
		.pipe(sass(sassOptions).on('error', sass.logError))
		.pipe(rename({ suffix: '.min' }))
		.pipe(gulp.dest('dist/css'))
});

// Default task
gulp.task('default', ['scripts', 'sass']);
<|endoftext|>