<commit_before>/**
 * Copyright 2017 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';

require('source-map-support').install();

const del = require('del');
const gulp = require('gulp');
const merge = require('merge2');
const sourcemaps = require('gulp-sourcemaps');
const spawn = require('child_process').spawn;
const ts = require('gulp-typescript');
const path = require('path');
const process = require('process');
const tslint = require('gulp-tslint');
const clangFormat = require('clang-format');
const format = require('gulp-clang-format');

const tsconfigPath = path.join(__dirname, 'tsconfig.json');
const tslintPath = path.join(__dirname, 'tslint.json');
const outDir = 'build';
const sources = ['src/**/*.ts'];
const unitTests = ['test/**/*.ts'];
const systemTests = ['system-test/**/*.ts'];
const allFiles = sources.concat(unitTests).concat(systemTests);

let exitOnError = true;
function onError() {
  if (exitOnError) {
    process.exit(1);
  }
}

gulp.task('test.check-format', () => {
  return gulp.src(sources)
      .pipe(format.checkFormat('file', clangFormat))
      .on('warning', onError);
});

gulp.task('format', () => {
  return gulp.src(sources, {base: '.'})
      .pipe(format.format('file', clangFormat))
      .pipe(gulp.dest('.'));
});

gulp.task('test.check-lint', () => {
  const program = require('tslint').Linter.createProgram('./tsconfig.json');
  return gulp.src(sources)
    .pipe(tslint(
      {
        configuration: tslintPath,
        formatter: 'prose', program
      }))
    .pipe(tslint.report())
      .on('warning', onError);
});

gulp.task('clean', () => {
  return del(['build']);
});

gulp.task('compile', () => {
  const tsResult = gulp.src(sources)
                       .pipe(sourcemaps.init())
                       .pipe(ts.createProject(tsconfigPath)())
                       .on('error', onError);
  return merge([
    tsResult.dts.pipe(gulp.dest(`${outDir}/types`)),
    tsResult.js
        .pipe(sourcemaps.write(
            '.', {includeContent: false, sourceRoot: '../../src'}))
        .pipe(gulp.dest(`${outDir}/src`)),
    tsResult.js.pipe(gulp.dest(`${outDir}/src`))
  ]);
});

gulp.task('test.system.copy', () => {
  return gulp.src(['system-test/**/*'])
             .pipe(gulp.dest(`${outDir}/system-test`));
});

gulp.task('test.system.compile', ['compile', 'test.system.copy'], () => {
  const tsResult = gulp.src(systemTests)
                       .pipe(sourcemaps.init())
                       .pipe(ts.createProject(tsconfigPath)())
                       .on('error', onError);
  return merge([
    tsResult.js
        .pipe(sourcemaps.write(
            '.', {includeContent: false, sourceRoot: '../../system-test'}))
        .pipe(gulp.dest(`${outDir}/system-test`)),
    tsResult.js.pipe(gulp.dest(`${outDir}/system-test`))
  ]);
});

gulp.task('test.packagejson.copy', () => {
  return gulp.src(['package.json'])
             .pipe(gulp.dest(`${outDir}`));
});

gulp.task('test.unit.copy', () => {
  return gulp.src(['test/**/*'])
             .pipe(gulp.dest(`${outDir}/test`));
});

gulp.task('test.unit.compile', ['test.unit.copy', 'test.packagejson.copy', 'compile'], () => {
  const tsResult = gulp.src(unitTests)
                       .pipe(sourcemaps.init())
                       .pipe(ts.createProject(tsconfigPath)())
                       .on('error', onError);
  return merge([
    tsResult.js
        .pipe(sourcemaps.write(
            '.', {includeContent: false, sourceRoot: '../../test'}))
        .pipe(gulp.dest(`${outDir}/test`)),
    tsResult.js.pipe(gulp.dest(`${outDir}/test`))
  ]);
});

function runTests(withCoverage, cb) {
  var args = [path.join('.', 'bin', 'run-test.sh')];
  if (withCoverage) {
    args = args.concat('-c');
  }
  spawn('bash', args, {
    stdio : 'inherit'
  }).on('close', cb);
}

gulp.task('test.run', ['test.unit.compile', 'test.system.compile'], cb => {
  runTests(false, cb);
});

gulp.task('test.coverage.run', ['test.unit.compile', 'test.system.compile'], cb => {
  runTests(true, cb);
});

gulp.task('watch', () => {
  exitOnError = false;
  gulp.start(['test.compile']);
  // TODO: also run unit tests in a non-fatal way
  return gulp.watch(sources, ['test.compile']);
});

gulp.task('test', ['test.run', 'test.check-format', 'test.check-lint']);
gulp.task('test.coverage', ['test.coverage.run', 'test.check-format', 'test.check-lint']);
gulp.task('default', ['compile', 'test.unit.compile', 'test.system.compile']);
<commit_msg>Fix `.ts` files being copied to the build dir (#325)<commit_after>/**
 * Copyright 2017 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';

require('source-map-support').install();

const del = require('del');
const gulp = require('gulp');
const merge = require('merge2');
const sourcemaps = require('gulp-sourcemaps');
const spawn = require('child_process').spawn;
const ts = require('gulp-typescript');
const path = require('path');
const process = require('process');
const tslint = require('gulp-tslint');
const clangFormat = require('clang-format');
const format = require('gulp-clang-format');

const tsconfigPath = path.join(__dirname, 'tsconfig.json');
const tslintPath = path.join(__dirname, 'tslint.json');
const outDir = 'build';
const sources = ['src/**/*.ts'];
const unitTests = ['test/**/*.ts'];
const unitTestsSupportFiles = ['test/**/*', '!test/**/*.ts'];
const systemTests = ['system-test/**/*.ts'];
const systemTestsSupportFiles = ['system-test/**/*', '!system-test/**/*.ts'];
const allFiles = sources.concat(unitTests).concat(systemTests);

let exitOnError = true;
function onError() {
  if (exitOnError) {
    process.exit(1);
  }
}

gulp.task('test.check-format', () => {
  return gulp.src(sources)
      .pipe(format.checkFormat('file', clangFormat))
      .on('warning', onError);
});

gulp.task('format', () => {
  return gulp.src(sources, {base: '.'})
      .pipe(format.format('file', clangFormat))
      .pipe(gulp.dest('.'));
});

gulp.task('test.check-lint', () => {
  const program = require('tslint').Linter.createProgram('./tsconfig.json');
  return gulp.src(sources)
    .pipe(tslint(
      {
        configuration: tslintPath,
        formatter: 'prose', program
      }))
    .pipe(tslint.report())
      .on('warning', onError);
});

gulp.task('clean', () => {
  return del(['build']);
});

gulp.task('compile', () => {
  const tsResult = gulp.src(sources)
                       .pipe(sourcemaps.init())
                       .pipe(ts.createProject(tsconfigPath)())
                       .on('error', onError);
  return merge([
    tsResult.dts.pipe(gulp.dest(`${outDir}/types`)),
    tsResult.js
        .pipe(sourcemaps.write(
            '.', {includeContent: false, sourceRoot: '../../src'}))
        .pipe(gulp.dest(`${outDir}/src`)),
    tsResult.js.pipe(gulp.dest(`${outDir}/src`))
  ]);
});

gulp.task('test.system.copy', () => {
  return gulp.src(systemTestsSupportFiles)
             .pipe(gulp.dest(`${outDir}/system-test`));
});

gulp.task('test.system.compile', ['compile', 'test.system.copy'], () => {
  const tsResult = gulp.src(systemTests)
                       .pipe(sourcemaps.init())
                       .pipe(ts.createProject(tsconfigPath)())
                       .on('error', onError);
  return merge([
    tsResult.js
        .pipe(sourcemaps.write(
            '.', {includeContent: false, sourceRoot: '../../system-test'}))
        .pipe(gulp.dest(`${outDir}/system-test`)),
    tsResult.js.pipe(gulp.dest(`${outDir}/system-test`))
  ]);
});

gulp.task('test.packagejson.copy', () => {
  return gulp.src(['package.json'])
             .pipe(gulp.dest(`${outDir}`));
});

gulp.task('test.unit.copy', () => {
  return gulp.src(unitTestsSupportFiles)
             .pipe(gulp.dest(`${outDir}/test`));
});

gulp.task('test.unit.compile', ['test.unit.copy', 'test.packagejson.copy', 'compile'], () => {
  const tsResult = gulp.src(unitTests)
                       .pipe(sourcemaps.init())
                       .pipe(ts.createProject(tsconfigPath)())
                       .on('error', onError);
  return merge([
    tsResult.js
        .pipe(sourcemaps.write(
            '.', {includeContent: false, sourceRoot: '../../test'}))
        .pipe(gulp.dest(`${outDir}/test`)),
    tsResult.js.pipe(gulp.dest(`${outDir}/test`))
  ]);
});

function runTests(withCoverage, cb) {
  var args = [path.join('.', 'bin', 'run-test.sh')];
  if (withCoverage) {
    args = args.concat('-c');
  }
  spawn('bash', args, {
    stdio : 'inherit'
  }).on('close', cb);
}

gulp.task('test.run', ['test.unit.compile', 'test.system.compile'], cb => {
  runTests(false, cb);
});

gulp.task('test.coverage.run', ['test.unit.compile', 'test.system.compile'], cb => {
  runTests(true, cb);
});

gulp.task('watch', () => {
  exitOnError = false;
  gulp.start(['test.compile']);
  // TODO: also run unit tests in a non-fatal way
  return gulp.watch(sources, ['test.compile']);
});

gulp.task('test', ['test.run', 'test.check-format', 'test.check-lint']);
gulp.task('test.coverage', ['test.coverage.run', 'test.check-format', 'test.check-lint']);
gulp.task('default', ['compile', 'test.unit.compile', 'test.system.compile']);
<|endoftext|>


<commit_before>'use strict'

const gulp = require('gulp')
const concat = require('gulp-concat')
const prompt = require('gulp-prompt')
const uglify = require('uglify-js')
// const header = require('gulp-header')
const esprima = require('esprima')
const traverse = require('traverse')
const del = require('del')
const fs = require('fs')
const path = require('path')
const pkg = require('./package.json')
const headerComment = '/**\n  * v' + pkg.version + ' generated on: ' + (new Date()) + '\n  * Copyright (c) 2014-' + (new Date()).getFullYear() + ', Corey Butler. All Rights Reserved.\n  */\n'

const DIR = {
  source: path.resolve('./tags'),
  dist: path.resolve('./dist')
}

const walk = function (dir) {
  let files = []
  fs.readdirSync(dir).forEach(function (filepath) {
    filepath = path.join(dir, filepath)
    const stat = fs.statSync(filepath)
    if (stat.isDirectory()) {
      files = files.concat(walk(filepath))
    } else {
      files.push(filepath)
    }
  })
  return files
}

// Build a release
gulp.task('build', ['version', 'clean', 'copy'])
gulp.task('default', ['create'])

// Check versions for Bower & npm
gulp.task('version', function (next) {
  console.log('Checking versions.')

  // Sync Bower
  var bower = require('./bower.json')
  if (bower.version !== pkg.version) {
    console.log('Updating bower package.')
    bower.version = pkg.version
    fs.writeFileSync(path.resolve('./bower.json'), JSON.stringify(bower, null, 2))
  }
})

// Create a clean build
gulp.task('clean', function (next) {
  console.log('Cleaning distribution.')
  if (fs.existsSync(DIR.dist)) {
    del.sync(DIR.dist)
  }
  fs.mkdirSync(DIR.dist)
  next()
})

gulp.task('copy', function () {
  console.log('Copying distribution files to ', DIR.dist)

  // Process each tag directory
  let ignored = fs.readFileSync(path.resolve('./.buildignore')).toString().trim().split('\n')
  let sources = fs.readdirSync(DIR.source).filter(function (p) {
    if (ignored.indexOf(p) >= 0) {
      return false
    }

    p = path.join(DIR.source, p)

    return fs.statSync(p).isDirectory()
      && fs.existsSync(path.join(p, 'tag.js'))
  })

  sources.forEach(function (dir) {
    let str = fs.readFileSync(path.join(DIR.source, dir, 'tag.js')).toString()

    let initScript = esprima.parse(str, {
      range: true
    })

    let initTplRange = null
    traverse(initScript).reduce(function (acc, x) {
      if (this.node
        && this.node.type
        && this.node.type === 'Property'
        && this.node.key
        && this.node.key.name === 'initTpl') {
        initTplRange = this.node.value.properties.filter(function (p) {
          return p.key.name.trim().toLowerCase() === 'value'
        })[0].value.body.range
      }
    })

    let tpl = null
    let tplfile = path.join(DIR.source, dir, 'template.html')
    if (fs.existsSync(tplfile)) {
      tpl = fs.readFileSync(tplfile).toString()
      tpl = tpl.replace(/\n|\s+/g, ' ').replace(/\s\s/g, ' ')
      tpl = '{\n'
        + '\t\t\t\tdocument.body.classList.add(\'chassis\')\n'
        + '\t\t\t\tvar content = \'' + tpl + '\'.replace(\/<(\\/?)template(.*?)>\/gi,\'\')\n'
        + '\t\t\t\tvar shadow = this.createShadowRoot()\n'
        + '\t\t\t\tvar ph = document.createElement(\'p\')\n'
        + '\t\t\t\tph.insertAdjacentHTML(\'afterbegin\', content)\n'
        + '\t\t\t\tArray.prototype.slice.call(ph.children).forEach(function (el) {\n'
        + '\t\t\t\t\tshadow.appendChild(document.importNode(el, true))\n'
        + '\t\t\t\t})\n'
        + '\t\t\t\tdelete ph\n}\n'
    }
    if (tpl) {
      str = str.replace(str.substr(initTplRange[0], initTplRange[1] - initTplRange[0]), tpl)
    }
    let c = uglify.minify(str.toString(), {
      fromString: true
    })
    fs.writeFileSync(path.join(DIR.dist, dir + '.js'), str)
    fs.writeFileSync(path.join(DIR.dist, dir + '.min.js'), headerComment + c.code)
    fs.writeFileSync(path.join(DIR.dist, dir + '.html'), '<script type="text/javascript">\n' + headerComment + c.code + '\n</script>')
  })
})

gulp.task('create', function () {
  return gulp.src('gulpfile.js')
    .pipe(prompt.prompt([{
      type: 'input',
      name: 'tag',
      message: 'Tag Name:',
      'default': 'chassis-tag',
      validate: function (input) {
        if (input.split('-').filter(function (el) {
          return el.trim().length > 0
        }).length > 1) {
          if (!fs.existsSync(path.join('./tags', input.toLowerCase()))) {
            return true
          }
          return input.toLowerCase() + ' already exists. Choose another name.'
        }
        return 'Must be in the format of [scope]-[tag].'
      }
    },{
      type: 'confirm',
      name: 'tpl',
      message: 'Create an HTML Shadow DOM template?',
      'default': true
    },{
      type: 'confirm',
      name: 'example',
      message: 'Create an example HTML page (for documentation)?',
      'default': true
    }], function (a) {
      // Create the new source directory
      let d = path.join(DIR.source, a.tag.toLowerCase())
      fs.mkdirSync(d)

      // Add the templates
      let tag = fs.readFileSync(path.join(DIR.source, 'tag.template')).toString()
      let readme = fs.readFileSync(path.join(DIR.source, 'README.template')).toString()

      let nm = a.tag.split('-').map(function (el) {
        return el.substr(0,1).toUpperCase() + el.substr(1,el.length)
      }).join('')

      let tpl = [{name: 'tag.js', tpl: tag }, {name:'README.md', tpl: readme}]
      if (a.example) {
        tpl.push({
          name: '../../documentation/examples/example-' + a.tag + '.html',
          tpl: fs.readFileSync(path.join(DIR.source, 'example.html.template')).toString()
        })
      }
      if (a.tpl) {
        tpl.push({
          name: 'template.html',
          tpl: fs.readFileSync(path.join(DIR.source, 'html.template')).toString()
        })
      }

      tpl.forEach(function (file) {
        let content = file.tpl.replace(/\{\{TagName\}\}/gi, a.tag.toLowerCase()).replace(/\{\{TagVariableName\}\}/gi, nm)
        fs.writeFileSync(path.join(d, file.name), content)
      })

      console.log('The custom tag code is ready in', d)
    }))
})

gulp.task('release', function (next) {
  const re = new RegExp('latest: \'' + pkg.version + '\'')
  if (re.exec(data) === null) {
    if (!mh.hasAll(process.env, 'GITHUB_TOKEN', 'GITHUB_ACCOUNT', 'GITHUB_REPO')) {
      throw new Error('Release not possible. Missing data: ' + mh.missing.join(', '))
    }

    // Check if the release already exists.
    const https = require('https')

    https.get({
      hostname: 'api.github.com',
      path: '/repos/' + process.env.GITHUB_ACCOUNT + '/' + process.env.GITHUB_REPO + '/releases',
      headers: {
        'user-agent': 'Release Checker'
      }
    }, function (res) {
      let data = ""
      res.on('data', function (chunk) {
        data += chunk
      })

      res.on('error', function (err) {
        throw err
      })

      res.on('end', function () {
        data = JSON.parse(data).filter(function (release) {
          return release.tag_name === pkg.version
        })

        if (data.length > 0) {
          console.log('Release ' + pkg.version + ' already exists. Aborting without error.')
          process.exit(0)
        }

        const assets = walk(DIR.dist).sort()

        GithubPublisher({
          token: process.env.GITHUB_TOKEN,
          owner: process.env.GITHUB_ACCOUNT,
          repo: process.env.GITHUB_REPO,
          tag: pkg.version,
          name: pkg.version,
          notes: 'Releasing v' + pkg.version,
          draft: false,
          prerelease: false,
          reuseRelease: true,
          reuseDraftOnly: true,
          assets: assets,
          // apiUrl: 'https://myGHEserver/api/v3',
          target_commitish: 'master'
        }, function (err, release) {
          if (err) {
            err.errors.forEach(function (e) {
              console.error((e.resource + ' ' + e.code).red.bold)
            })
            process.exit(1)
          }
          console.log(release)
        })
      })
    })
  } else {
    console.log('The version has not changed (' + pkg.version + '). A new release is unnecessary. Aborting deployment with success code.')
    process.exit(0)
  }
})
<commit_msg>Updated build process.<commit_after>'use strict'

const gulp = require('gulp')
const concat = require('gulp-concat')
const prompt = require('gulp-prompt')
const uglify = require('uglify-js')
// const header = require('gulp-header')
const esprima = require('esprima')
const traverse = require('traverse')
const del = require('del')
const fs = require('fs')
const path = require('path')
const pkg = require('./package.json')
const headerComment = '/**\n  * v' + pkg.version + ' generated on: ' + (new Date()) + '\n  * Copyright (c) 2014-' + (new Date()).getFullYear() + ', Corey Butler. All Rights Reserved.\n  */\n'

const DIR = {
  source: path.resolve('./tags'),
  dist: path.resolve('./dist')
}

const walk = function (dir) {
  let files = []
  fs.readdirSync(dir).forEach(function (filepath) {
    filepath = path.join(dir, filepath)
    const stat = fs.statSync(filepath)
    if (stat.isDirectory()) {
      files = files.concat(walk(filepath))
    } else {
      files.push(filepath)
    }
  })
  return files
}

// Build a release
gulp.task('build', ['version', 'clean', 'copy'])
gulp.task('default', ['create'])

// Check versions for Bower & npm
gulp.task('version', function (next) {
  console.log('Checking versions.')

  // Sync Bower
  var bower = require('./bower.json')
  if (bower.version !== pkg.version) {
    console.log('Updating bower package.')
    bower.version = pkg.version
    fs.writeFileSync(path.resolve('./bower.json'), JSON.stringify(bower, null, 2))
  }
})

// Create a clean build
gulp.task('clean', function (next) {
  console.log('Cleaning distribution.')
  if (fs.existsSync(DIR.dist)) {
    del.sync(DIR.dist)
  }
  fs.mkdirSync(DIR.dist)
  next()
})

gulp.task('copy', function () {
  console.log('Copying distribution files to ', DIR.dist)

  // Process each tag directory
  let ignored = fs.readFileSync(path.resolve('./.buildignore')).toString().trim().split('\n')
  let sources = fs.readdirSync(DIR.source).filter(function (p) {
    if (ignored.indexOf(p) >= 0) {
      return false
    }

    p = path.join(DIR.source, p)

    return fs.statSync(p).isDirectory()
      && fs.existsSync(path.join(p, 'tag.js'))
  })

  sources.forEach(function (dir) {
    let str = fs.readFileSync(path.join(DIR.source, dir, 'tag.js')).toString()

    let initScript = esprima.parse(str, {
      range: true
    })

    let initTplRange = null
    traverse(initScript).reduce(function (acc, x) {
      if (this.node
        && this.node.type
        && this.node.type === 'Property'
        && this.node.key
        && this.node.key.name === 'initTpl') {
        initTplRange = this.node.value.properties.filter(function (p) {
          return p.key.name.trim().toLowerCase() === 'value'
        })[0].value.body.range
      }
    })

    let tpl = null
    let tplfile = path.join(DIR.source, dir, 'template.html')
    if (fs.existsSync(tplfile)) {
      tpl = fs.readFileSync(tplfile).toString()
      tpl = tpl.replace(/\n|\s+/g, ' ').replace(/\s\s/g, ' ')
      tpl = '{\n'
        + '\t\t\t\tdocument.body.classList.add(\'chassis\')\n'
        + '\t\t\t\tvar content = \'' + tpl + '\'.replace(\/<(\\/?)template(.*?)>\/gi,\'\')\n'
        + '\t\t\t\tvar shadow = this.createShadowRoot()\n'
        + '\t\t\t\tvar ph = document.createElement(\'p\')\n'
        + '\t\t\t\tph.insertAdjacentHTML(\'afterbegin\', content)\n'
        + '\t\t\t\tArray.prototype.slice.call(ph.children).forEach(function (el) {\n'
        + '\t\t\t\t\tshadow.appendChild(document.importNode(el, true))\n'
        + '\t\t\t\t})\n'
        + '\t\t\t\tdelete ph\n}\n'
    }
    if (tpl) {
      str = str.replace(str.substr(initTplRange[0], initTplRange[1] - initTplRange[0]), tpl)
    }
    let c = uglify.minify(str.toString(), {
      fromString: true
    })
    fs.writeFileSync(path.join(DIR.dist, dir + '.js'), str)
    fs.writeFileSync(path.join(DIR.dist, dir + '.min.js'), headerComment + c.code)
    fs.writeFileSync(path.join(DIR.dist, dir + '.html'), '<script type="text/javascript">\n' + headerComment + c.code + '\n</script>')
  })
})

gulp.task('create', function () {
  return gulp.src('gulpfile.js')
    .pipe(prompt.prompt([{
      type: 'input',
      name: 'tag',
      message: 'Tag Name:',
      'default': 'chassis-tag',
      validate: function (input) {
        if (input.split('-').filter(function (el) {
          return el.trim().length > 0
        }).length > 1) {
          if (!fs.existsSync(path.join('./tags', input.toLowerCase()))) {
            return true
          }
          return input.toLowerCase() + ' already exists. Choose another name.'
        }
        return 'Must be in the format of [scope]-[tag].'
      }
    },{
      type: 'confirm',
      name: 'tpl',
      message: 'Create an HTML Shadow DOM template?',
      'default': true
    },{
      type: 'confirm',
      name: 'example',
      message: 'Create an example HTML page (for documentation)?',
      'default': true
    }], function (a) {
      // Create the new source directory
      let d = path.join(DIR.source, a.tag.toLowerCase())
      fs.mkdirSync(d)

      // Add the templates
      let tag = fs.readFileSync(path.join(DIR.source, 'tag.template')).toString()
      let readme = fs.readFileSync(path.join(DIR.source, 'README.template')).toString()

      let nm = a.tag.split('-').map(function (el) {
        return el.substr(0,1).toUpperCase() + el.substr(1,el.length)
      }).join('')

      let tpl = [{name: 'tag.js', tpl: tag }, {name:'README.md', tpl: readme}]
      if (a.example) {
        tpl.push({
          name: '../../documentation/examples/example-' + a.tag + '.html',
          tpl: fs.readFileSync(path.join(DIR.source, 'example.html.template')).toString()
        })
      }
      if (a.tpl) {
        tpl.push({
          name: 'template.html',
          tpl: fs.readFileSync(path.join(DIR.source, 'html.template')).toString()
        })
      }

      tpl.forEach(function (file) {
        let content = file.tpl.replace(/\{\{TagName\}\}/gi, a.tag.toLowerCase()).replace(/\{\{TagVariableName\}\}/gi, nm)
        fs.writeFileSync(path.join(d, file.name), content)
      })

      console.log('The custom tag code is ready in', d)
    }))
})

gulp.task('release', function (next) {
  if (!mh.hasAll(process.env, 'GITHUB_TOKEN', 'GITHUB_ACCOUNT', 'GITHUB_REPO')) {
    throw new Error('Release not possible. Missing data: ' + mh.missing.join(', '))
  }

  // Check if the release already exists.
  const https = require('https')

  https.get({
    hostname: 'api.github.com',
    path: '/repos/' + process.env.GITHUB_ACCOUNT + '/' + process.env.GITHUB_REPO + '/releases',
    headers: {
      'user-agent': 'Release Checker'
    }
  }, function (res) {
    let data = ""
    res.on('data', function (chunk) {
      data += chunk
    })

    res.on('error', function (err) {
      throw err
    })

    res.on('end', function () {
      data = JSON.parse(data).filter(function (release) {
        return release.tag_name === pkg.version
      })

      if (data.length > 0) {
        console.log('Release ' + pkg.version + ' already exists. Aborting without error.')
        process.exit(0)
      }

      const assets = walk(DIR.dist).sort()

      GithubPublisher({
        token: process.env.GITHUB_TOKEN,
        owner: process.env.GITHUB_ACCOUNT,
        repo: process.env.GITHUB_REPO,
        tag: pkg.version,
        name: pkg.version,
        notes: 'Releasing v' + pkg.version,
        draft: false,
        prerelease: false,
        reuseRelease: true,
        reuseDraftOnly: true,
        assets: assets,
        // apiUrl: 'https://myGHEserver/api/v3',
        target_commitish: 'master'
      }, function (err, release) {
        if (err) {
          err.errors.forEach(function (e) {
            console.error((e.resource + ' ' + e.code).red.bold)
          })
          process.exit(1)
        }
        console.log(release)
      })
    })
  })
})
<|endoftext|>


<commit_before>/*
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/

'use strict';

// Include Gulp & Tools We'll Use
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var del = require('del');
var runSequence = require('run-sequence');
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var merge = require('merge-stream');
var path = require('path');
var fs = require('fs');
var glob = require('glob');

var AUTOPREFIXER_BROWSERS = [
  'ie >= 10',
  'ie_mob >= 10',
  'ff >= 30',
  'chrome >= 34',
  'safari >= 7',
  'opera >= 23',
  'ios >= 7',
  'android >= 4.4',
  'bb >= 10'
];

var styleTask = function (stylesPath, srcs) {
  return gulp.src(srcs.map(function(src) {
      return path.join('app', stylesPath, src);
    }))
    .pipe($.changed(stylesPath, {extension: '.css'}))
    .pipe($.autoprefixer(AUTOPREFIXER_BROWSERS))
    .pipe(gulp.dest('.tmp/' + stylesPath))
    .pipe($.if('*.css', $.cssmin()))
    .pipe(gulp.dest('dist/' + stylesPath))
    .pipe($.size({title: stylesPath}));
};

// Compile and Automatically Prefix Stylesheets
gulp.task('styles', function () {
  return styleTask('styles', ['**/*.css']);
});

gulp.task('elements', function () {
  return styleTask('elements', ['**/*.css']);
});

// Lint JavaScript
gulp.task('jshint', function () {
  return gulp.src([
      'app/scripts/**/*.js',
      'app/elements/**/*.js',
      'app/elements/**/*.html'
    ])
    .pipe(reload({stream: true, once: true}))
    .pipe($.jshint.extract()) // Extract JS from .html files
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.if(!browserSync.active, $.jshint.reporter('fail')));
});

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

// Copy All Files At The Root Level (app)
gulp.task('copy', function () {
  var app = gulp.src([
    'app/*',
    '!app/test',
    '!app/precache.json'
  ], {
    dot: true
  }).pipe(gulp.dest('dist'));

  var bower = gulp.src([
    'bower_components/**/*'
  ]).pipe(gulp.dest('dist/bower_components'));

  var elements = gulp.src(['app/elements/**/*.html'])
    .pipe(gulp.dest('dist/elements'));

  var swBootstrap = gulp.src(['bower_components/platinum-sw/bootstrap/*.js'])
    .pipe(gulp.dest('dist/elements/bootstrap'));

  var swToolbox = gulp.src(['bower_components/sw-toolbox/*.js'])
    .pipe(gulp.dest('dist/sw-toolbox'));

  var vulcanized = gulp.src(['app/elements/elements.html'])
    .pipe($.rename('elements.vulcanized.html'))
    .pipe(gulp.dest('dist/elements'));

  return merge(app, bower, elements, vulcanized, swBootstrap, swToolbox)
    .pipe($.size({title: 'copy'}));
});

// Copy Web Fonts To Dist
gulp.task('fonts', function () {
  return gulp.src(['app/fonts/**'])
    .pipe(gulp.dest('dist/fonts'))
    .pipe($.size({title: 'fonts'}));
});

// Scan Your HTML For Assets & Optimize Them
gulp.task('html', function () {
  var assets = $.useref.assets({searchPath: ['.tmp', 'app', 'dist']});

  return gulp.src(['app/**/*.html', '!app/{elements,test}/**/*.html'])
    // Replace path for vulcanized assets
    .pipe($.if('*.html', $.replace('elements/elements.html', 'elements/elements.vulcanized.html')))
    .pipe(assets)
    // Concatenate And Minify JavaScript
    .pipe($.if('*.js', $.uglify({preserveComments: 'some'})))
    // Concatenate And Minify Styles
    // In case you are still using useref build blocks
    .pipe($.if('*.css', $.cssmin()))
    .pipe(assets.restore())
    .pipe($.useref())
    // Minify Any HTML
    .pipe($.if('*.html', $.minifyHtml({
      quotes: true,
      empty: true,
      spare: true
    })))
    // Output Files
    .pipe(gulp.dest('dist'))
    .pipe($.size({title: 'html'}));
});

// Vulcanize imports
gulp.task('vulcanize', function () {
  var DEST_DIR = 'dist/elements';

  return gulp.src('dist/elements/elements.vulcanized.html')
    .pipe($.vulcanize({
      dest: DEST_DIR,
      strip: true,
      inlineCss: true,
      inlineScripts: true
    }))
    .pipe(gulp.dest(DEST_DIR))
    .pipe($.size({title: 'vulcanize'}));
});

// Generate a list of files that should be precached when serving from 'dist'.
// The list will be consumed by the <platinum-sw-cache> element.
gulp.task('precache', function (callback) {
  var dir = 'dist';

  glob('{elements,scripts,styles}/**/*.*', {cwd: dir}, function(error, files) {
    if (error) {
      callback(error);
    } else {
      files.push('index.html', './', 'bower_components/webcomponentsjs/webcomponents-lite.min.js');
      var filePath = path.join(dir, 'precache.json');
      fs.writeFile(filePath, JSON.stringify(files), callback);
    }
  });
});

// Clean Output Directory
gulp.task('clean', del.bind(null, ['.tmp', 'dist']));

// Watch Files For Changes & Reload
gulp.task('serve', ['styles', 'elements', 'images'], function () {
  browserSync({
    notify: false,
    snippetOptions: {
      rule: {
        match: '',
        fn: function (snippet) {
          return snippet;
        }
      }
    },
    // Run as an https by uncommenting 'https: true'
    // Note: this uses an unsigned certificate which on first access
    //       will present a certificate warning in the browser.
    // https: true,
    server: {
      baseDir: ['.tmp', 'app'],
      routes: {
        '/bower_components': 'bower_components'
      }
    }
  });

  gulp.watch(['app/**/*.html'], reload);
  gulp.watch(['app/styles/**/*.css'], ['styles', reload]);
  gulp.watch(['app/elements/**/*.css'], ['elements', reload]);
  gulp.watch(['app/{scripts,elements}/**/*.js'], ['jshint']);
  gulp.watch(['app/images/**/*'], reload);
});

// Build and serve the output from the dist build
gulp.task('serve:dist', ['default'], function () {
  browserSync({
    notify: false,
    snippetOptions: {
      rule: {
        match: '',
        fn: function (snippet) {
          return snippet;
        }
      }
    },
    // Run as an https by uncommenting 'https: true'
    // Note: this uses an unsigned certificate which on first access
    //       will present a certificate warning in the browser.
    // https: true,
    server: 'dist'
  });
});

// Build Production Files, the Default Task
gulp.task('default', ['clean'], function (cb) {
  runSequence(
    ['copy', 'styles'],
    'elements',
    ['jshint', 'images', 'fonts', 'html'],
    'vulcanize', 'precache',
    cb);
});

// Load tasks for web-component-tester
// Adds tasks for `gulp test:local` and `gulp test:remote`
try { require('web-component-tester').gulp.init(gulp); } catch (err) {}

// Load custom tasks from the `tasks` directory
try { require('require-dir')('tasks'); } catch (err) {}
<commit_msg>Add a `logPrefix` to browserSync (Closes #183)<commit_after>/*
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/

'use strict';

// Include Gulp & Tools We'll Use
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var del = require('del');
var runSequence = require('run-sequence');
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var merge = require('merge-stream');
var path = require('path');
var fs = require('fs');
var glob = require('glob');

var AUTOPREFIXER_BROWSERS = [
  'ie >= 10',
  'ie_mob >= 10',
  'ff >= 30',
  'chrome >= 34',
  'safari >= 7',
  'opera >= 23',
  'ios >= 7',
  'android >= 4.4',
  'bb >= 10'
];

var styleTask = function (stylesPath, srcs) {
  return gulp.src(srcs.map(function(src) {
      return path.join('app', stylesPath, src);
    }))
    .pipe($.changed(stylesPath, {extension: '.css'}))
    .pipe($.autoprefixer(AUTOPREFIXER_BROWSERS))
    .pipe(gulp.dest('.tmp/' + stylesPath))
    .pipe($.if('*.css', $.cssmin()))
    .pipe(gulp.dest('dist/' + stylesPath))
    .pipe($.size({title: stylesPath}));
};

// Compile and Automatically Prefix Stylesheets
gulp.task('styles', function () {
  return styleTask('styles', ['**/*.css']);
});

gulp.task('elements', function () {
  return styleTask('elements', ['**/*.css']);
});

// Lint JavaScript
gulp.task('jshint', function () {
  return gulp.src([
      'app/scripts/**/*.js',
      'app/elements/**/*.js',
      'app/elements/**/*.html'
    ])
    .pipe(reload({stream: true, once: true}))
    .pipe($.jshint.extract()) // Extract JS from .html files
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.if(!browserSync.active, $.jshint.reporter('fail')));
});

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

// Copy All Files At The Root Level (app)
gulp.task('copy', function () {
  var app = gulp.src([
    'app/*',
    '!app/test',
    '!app/precache.json'
  ], {
    dot: true
  }).pipe(gulp.dest('dist'));

  var bower = gulp.src([
    'bower_components/**/*'
  ]).pipe(gulp.dest('dist/bower_components'));

  var elements = gulp.src(['app/elements/**/*.html'])
    .pipe(gulp.dest('dist/elements'));

  var swBootstrap = gulp.src(['bower_components/platinum-sw/bootstrap/*.js'])
    .pipe(gulp.dest('dist/elements/bootstrap'));

  var swToolbox = gulp.src(['bower_components/sw-toolbox/*.js'])
    .pipe(gulp.dest('dist/sw-toolbox'));

  var vulcanized = gulp.src(['app/elements/elements.html'])
    .pipe($.rename('elements.vulcanized.html'))
    .pipe(gulp.dest('dist/elements'));

  return merge(app, bower, elements, vulcanized, swBootstrap, swToolbox)
    .pipe($.size({title: 'copy'}));
});

// Copy Web Fonts To Dist
gulp.task('fonts', function () {
  return gulp.src(['app/fonts/**'])
    .pipe(gulp.dest('dist/fonts'))
    .pipe($.size({title: 'fonts'}));
});

// Scan Your HTML For Assets & Optimize Them
gulp.task('html', function () {
  var assets = $.useref.assets({searchPath: ['.tmp', 'app', 'dist']});

  return gulp.src(['app/**/*.html', '!app/{elements,test}/**/*.html'])
    // Replace path for vulcanized assets
    .pipe($.if('*.html', $.replace('elements/elements.html', 'elements/elements.vulcanized.html')))
    .pipe(assets)
    // Concatenate And Minify JavaScript
    .pipe($.if('*.js', $.uglify({preserveComments: 'some'})))
    // Concatenate And Minify Styles
    // In case you are still using useref build blocks
    .pipe($.if('*.css', $.cssmin()))
    .pipe(assets.restore())
    .pipe($.useref())
    // Minify Any HTML
    .pipe($.if('*.html', $.minifyHtml({
      quotes: true,
      empty: true,
      spare: true
    })))
    // Output Files
    .pipe(gulp.dest('dist'))
    .pipe($.size({title: 'html'}));
});

// Vulcanize imports
gulp.task('vulcanize', function () {
  var DEST_DIR = 'dist/elements';

  return gulp.src('dist/elements/elements.vulcanized.html')
    .pipe($.vulcanize({
      dest: DEST_DIR,
      strip: true,
      inlineCss: true,
      inlineScripts: true
    }))
    .pipe(gulp.dest(DEST_DIR))
    .pipe($.size({title: 'vulcanize'}));
});

// Generate a list of files that should be precached when serving from 'dist'.
// The list will be consumed by the <platinum-sw-cache> element.
gulp.task('precache', function (callback) {
  var dir = 'dist';

  glob('{elements,scripts,styles}/**/*.*', {cwd: dir}, function(error, files) {
    if (error) {
      callback(error);
    } else {
      files.push('index.html', './', 'bower_components/webcomponentsjs/webcomponents-lite.min.js');
      var filePath = path.join(dir, 'precache.json');
      fs.writeFile(filePath, JSON.stringify(files), callback);
    }
  });
});

// Clean Output Directory
gulp.task('clean', del.bind(null, ['.tmp', 'dist']));

// Watch Files For Changes & Reload
gulp.task('serve', ['styles', 'elements', 'images'], function () {
  browserSync({
    notify: false,
    logPrefix: 'PSK',
    snippetOptions: {
      rule: {
        match: '',
        fn: function (snippet) {
          return snippet;
        }
      }
    },
    // Run as an https by uncommenting 'https: true'
    // Note: this uses an unsigned certificate which on first access
    //       will present a certificate warning in the browser.
    // https: true,
    server: {
      baseDir: ['.tmp', 'app'],
      routes: {
        '/bower_components': 'bower_components'
      }
    }
  });

  gulp.watch(['app/**/*.html'], reload);
  gulp.watch(['app/styles/**/*.css'], ['styles', reload]);
  gulp.watch(['app/elements/**/*.css'], ['elements', reload]);
  gulp.watch(['app/{scripts,elements}/**/*.js'], ['jshint']);
  gulp.watch(['app/images/**/*'], reload);
});

// Build and serve the output from the dist build
gulp.task('serve:dist', ['default'], function () {
  browserSync({
    notify: false,
    logPrefix: 'PSK',
    snippetOptions: {
      rule: {
        match: '',
        fn: function (snippet) {
          return snippet;
        }
      }
    },
    // Run as an https by uncommenting 'https: true'
    // Note: this uses an unsigned certificate which on first access
    //       will present a certificate warning in the browser.
    // https: true,
    server: 'dist'
  });
});

// Build Production Files, the Default Task
gulp.task('default', ['clean'], function (cb) {
  runSequence(
    ['copy', 'styles'],
    'elements',
    ['jshint', 'images', 'fonts', 'html'],
    'vulcanize', 'precache',
    cb);
});

// Load tasks for web-component-tester
// Adds tasks for `gulp test:local` and `gulp test:remote`
try { require('web-component-tester').gulp.init(gulp); } catch (err) {}

// Load custom tasks from the `tasks` directory
try { require('require-dir')('tasks'); } catch (err) {}
<|endoftext|>


<commit_before>/* jshint node:true */
'use strict';
// generated on 2014-12-05 using generator-gulp-webapp 0.2.0
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var browserSync = require('browser-sync');
var reload = browserSync.reload;

gulp.task('views', function () {
  return gulp.src(['app/*.jade', '!app/layout.jade'])
      .pipe($.jade({pretty: true}))
      .pipe(gulp.dest('.tmp'));
});

gulp.task('styles', function () {
  return gulp.src('app/styles/main.scss')
    .pipe($.plumber())
    .pipe($.sass({
      errLogToConsole: true,
      style: 'nested',
      precision: 10,
      includePaths: ['bower_components/foundation/scss']
    }))
    .pipe($.autoprefixer({browsers: ['last 1 version']}))
    .pipe(gulp.dest('.tmp/styles'));
});

gulp.task('jshint', function () {
  return gulp.src('app/scripts/**/*.js')
    .pipe(reload({stream: true, once: true}))
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.if(!browserSync.active, $.jshint.reporter('fail')));
});

gulp.task('html', ['views', 'styles'], function () {
  var assets = $.useref.assets({searchPath: '{.tmp,app}'});

  return gulp.src('.tmp/*.html')
    .pipe(assets)
    .pipe($.if('*.js', $.uglify()))
    .pipe($.if('*.css', $.csso()))
    .pipe(assets.restore())
    .pipe($.useref())
    .pipe(gulp.dest('dist'));
});

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

gulp.task('fonts', function () {
  return gulp.src(require('main-bower-files')().concat('app/fonts/**/*'))
    .pipe($.filter('**/*.{eot,svg,ttf,woff}'))
    .pipe($.flatten())
    .pipe(gulp.dest('dist/fonts'));
});

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

gulp.task('clean', require('del').bind(null, ['.tmp', 'dist']));

gulp.task('serve', ['styles'], function () {
  browserSync({
    notify: false,
    port: 9000,
    server: {
      baseDir: ['.tmp', 'app'],
      routes: {
        '/bower_components': 'bower_components'
      }
    }
  });

  // watch for changes
  gulp.watch(['.tmp/*.html'], reload);
  gulp.watch(['.tmp/styles/**/*.css'], reload);
  gulp.watch(['app/scripts/**/*.js'], ['jshint']);
  gulp.watch(['app/*.jade', 'app/includes/*.jade'], ['views']);
  gulp.watch(['app/images/**/*'], reload);

  gulp.watch(['app/styles/**/*.scss'], ['styles', reload]);
  gulp.watch(['bower.json'], ['wiredep', reload]);
});

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

  gulp.src('app/styles/*.scss')
    .pipe(wiredep())
    .pipe(gulp.dest('app/styles'));

  gulp.src('app/*.jade')
    .pipe(wiredep())
    .pipe(gulp.dest('app'));
});

gulp.task('build', ['jshint', 'html', 'images', 'fonts', 'extras'], function () {
  return gulp.src('dist/**/*').pipe($.size({title: 'build', gzip: true}));
});

gulp.task('default', ['clean'], function () {
  gulp.start('build');
});
<commit_msg>changed sass precision to 9<commit_after>/* jshint node:true */
'use strict';
// generated on 2014-12-05 using generator-gulp-webapp 0.2.0
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var browserSync = require('browser-sync');
var reload = browserSync.reload;

gulp.task('views', function () {
  return gulp.src(['app/*.jade', '!app/layout.jade'])
      .pipe($.jade({pretty: true}))
      .pipe(gulp.dest('.tmp'));
});

gulp.task('styles', function () {
  return gulp.src('app/styles/main.scss')
    .pipe($.plumber())
    .pipe($.sass({
      errLogToConsole: true,
      style: 'nested',
      precision: 9,
      includePaths: ['bower_components/foundation/scss']
    }))
    .pipe($.autoprefixer({browsers: ['last 1 version']}))
    .pipe(gulp.dest('.tmp/styles'));
});

gulp.task('jshint', function () {
  return gulp.src('app/scripts/**/*.js')
    .pipe(reload({stream: true, once: true}))
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.if(!browserSync.active, $.jshint.reporter('fail')));
});

gulp.task('html', ['views', 'styles'], function () {
  var assets = $.useref.assets({searchPath: '{.tmp,app}'});

  return gulp.src('.tmp/*.html')
    .pipe(assets)
    .pipe($.if('*.js', $.uglify()))
    .pipe($.if('*.css', $.csso()))
    .pipe(assets.restore())
    .pipe($.useref())
    .pipe(gulp.dest('dist'));
});

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

gulp.task('fonts', function () {
  return gulp.src(require('main-bower-files')().concat('app/fonts/**/*'))
    .pipe($.filter('**/*.{eot,svg,ttf,woff}'))
    .pipe($.flatten())
    .pipe(gulp.dest('dist/fonts'));
});

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

gulp.task('clean', require('del').bind(null, ['.tmp', 'dist']));

gulp.task('serve', ['styles'], function () {
  browserSync({
    notify: false,
    port: 9000,
    server: {
      baseDir: ['.tmp', 'app'],
      routes: {
        '/bower_components': 'bower_components'
      }
    }
  });

  // watch for changes
  gulp.watch(['.tmp/*.html'], reload);
  gulp.watch(['.tmp/styles/**/*.css'], reload);
  gulp.watch(['app/scripts/**/*.js'], ['jshint']);
  gulp.watch(['app/*.jade', 'app/includes/*.jade'], ['views']);
  gulp.watch(['app/images/**/*'], reload);

  gulp.watch(['app/styles/**/*.scss'], ['styles', reload]);
  gulp.watch(['bower.json'], ['wiredep', reload]);
});

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

  gulp.src('app/styles/*.scss')
    .pipe(wiredep())
    .pipe(gulp.dest('app/styles'));

  gulp.src('app/*.jade')
    .pipe(wiredep())
    .pipe(gulp.dest('app'));
});

gulp.task('build', ['jshint', 'html', 'images', 'fonts', 'extras'], function () {
  return gulp.src('dist/**/*').pipe($.size({title: 'build', gzip: true}));
});

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


<commit_before>
var gulp = require("gulp");
var del = require("del");
var sequence = require("gulp-sequence");
var typescript = require("gulp-typescript");
var json = require('gulp-json-editor');

gulp.task("clean:build", function() {
    return del(["build"]);
});

gulp.task("clean:package", function() {
    return del(["package"]);
});

gulp.task("clean", sequence("clean:build", "clean:package"));

gulp.task("build", function () {
    var config = typescript.createProject("./tsconfig.json");

    return gulp
        .src("src/**/*.ts")
        .pipe(config())
        .pipe(gulp.dest("build"));
});

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

gulp.task("package:copy", function () {
    return gulp.src('build/**/*')
        .pipe(gulp.dest('package'));
});

gulp.task('package:license', function() {
    return gulp.src('./LICENSE')
        .pipe(gulp.dest('package'));
});

gulp.task("package:package.json", function () {
    return gulp.src('package.json')
        .pipe(json({ 'main': 'index.js', 'types': 'index.d.ts' }))
        .pipe(gulp.dest('package'));
});

gulp.task("package", sequence("clean", "build", "package:copy", "package:license", "package:package.json"));<commit_msg>Gulp build task performs clean<commit_after>
var gulp = require("gulp");
var del = require("del");
var sequence = require("gulp-sequence");
var typescript = require("gulp-typescript");
var json = require('gulp-json-editor');

gulp.task("clean:build", function() {
    return del(["build"]);
});

gulp.task("clean:package", function() {
    return del(["package"]);
});

gulp.task("clean", sequence("clean:build", "clean:package"));

gulp.task("build", ["clean:build"], function () {
    var config = typescript.createProject("./tsconfig.json");

    return gulp
        .src("src/**/*.ts")
        .pipe(config())
        .pipe(gulp.dest("build"));
});

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

gulp.task("package:copy", function () {
    return gulp.src('build/**/*')
        .pipe(gulp.dest('package'));
});

gulp.task('package:license', function() {
    return gulp.src('./LICENSE')
        .pipe(gulp.dest('package'));
});

gulp.task("package:package.json", function () {
    return gulp.src('package.json')
        .pipe(json({ 'main': 'index.js', 'types': 'index.d.ts' }))
        .pipe(gulp.dest('package'));
});

gulp.task("package", sequence("clean", "build", "package:copy", "package:license", "package:package.json"));<|endoftext|>


<commit_before>var gulp = require('gulp')
var nodemon = require('gulp-nodemon')
var rem = require('rimraf')
var sourcemaps = require('gulp-sourcemaps')
var uglify = require('gulp-uglify')
var browserSync = require('browser-sync')
var buildSemantic = require('./client/semantic/tasks/build')
var watchSemantic = require('./client/semantic/tasks/watch')

var BROWSER_SYNC_RELOAD_DELAY = 500

gulp.task('build', ['scripts', 'css'])
gulp.task('build-semantic', buildSemantic)
gulp.task('watch-semantic', watchSemantic)

gulp.task('dev', ['build'], function (cb) {
  gulp.watch(['client/js/**/*.js'], ['scripts'])
  gulp.watch(['client/css/**/*.css'], ['css'])
  gulp.watch(['public/js/**/*.js', 'server/views/**/*'], browserSync.reload)
  gulp.start('watch-semantic')
  gulp.start('browsersync')
  cb()
})

gulp.task('scripts', function () {
  rem('public/js/**/*', function () {
    gulp.src(['client/js/**/*.js'])
      .pipe(sourcemaps.init())
      .pipe(uglify({mangle: true}))
      .pipe(sourcemaps.write('./'))
      .pipe(gulp.dest('public/js'))
  })
})

gulp.task('css', function () {
  rem('public/css/**/*', function () {
    gulp.src(['client/css/**/*.css'])
      .pipe(gulp.dest('public/css'))
      .pipe(browserSync.stream())
  })
})

// browsersync - watches client files and reloads browser
gulp.task('browsersync', ['nodemon'], function () {
  // for more browser-sync config options: http://www.browsersync.io/docs/options/
  browserSync.init({
    proxy: 'http://localhost:8080',
    port: 3000
  })
})

// nodemon - watches server files and restart server on change
gulp.task('nodemon', function (cb) {
  return nodemon({
    script: 'index.js',
    ignore: ['server/views/**/*'],
    // watch core server file(s) that require server restart on change
    watch: ['index.js', 'config.example.json', 'config.json', 'server/**/*']
  })
  .once('start', function onStart () {
    setTimeout(function () {
      cb()
    }, 1500)
  })
  .on('restart', function onRestart () {
    setTimeout(function reload () {
      browserSync.reload({
        stream: false
      })
    }, BROWSER_SYNC_RELOAD_DELAY)
  })
})
<commit_msg>no notify on browser sync<commit_after>var gulp = require('gulp')
var nodemon = require('gulp-nodemon')
var rem = require('rimraf')
var sourcemaps = require('gulp-sourcemaps')
var uglify = require('gulp-uglify')
var browserSync = require('browser-sync')
var buildSemantic = require('./client/semantic/tasks/build')
var watchSemantic = require('./client/semantic/tasks/watch')

var BROWSER_SYNC_RELOAD_DELAY = 500

gulp.task('build', ['scripts', 'css'])
gulp.task('build-semantic', buildSemantic)
gulp.task('watch-semantic', watchSemantic)

gulp.task('dev', ['build'], function (cb) {
  gulp.watch(['client/js/**/*.js'], ['scripts'])
  gulp.watch(['client/css/**/*.css'], ['css'])
  gulp.watch(['public/js/**/*.js', 'server/views/**/*'], browserSync.reload)
  gulp.start('watch-semantic')
  gulp.start('browsersync')
  cb()
})

gulp.task('scripts', function () {
  rem('public/js/**/*', function () {
    gulp.src(['client/js/**/*.js'])
      .pipe(sourcemaps.init())
      .pipe(uglify({mangle: true}))
      .pipe(sourcemaps.write('./'))
      .pipe(gulp.dest('public/js'))
  })
})

gulp.task('css', function () {
  rem('public/css/**/*', function () {
    gulp.src(['client/css/**/*.css'])
      .pipe(gulp.dest('public/css'))
      .pipe(browserSync.stream())
  })
})

// browsersync - watches client files and reloads browser
gulp.task('browsersync', ['nodemon'], function () {
  // for more browser-sync config options: http://www.browsersync.io/docs/options/
  browserSync.init({
    proxy: 'http://localhost:8080',
    port: 3000,
    notify: false
  })
})

// nodemon - watches server files and restart server on change
gulp.task('nodemon', function (cb) {
  return nodemon({
    script: 'index.js',
    ignore: ['server/views/**/*'],
    // watch core server file(s) that require server restart on change
    watch: ['index.js', 'config.example.json', 'config.json', 'server/**/*']
  })
  .once('start', function onStart () {
    setTimeout(function () {
      cb()
    }, 1500)
  })
  .on('restart', function onRestart () {
    setTimeout(function reload () {
      browserSync.reload({
        stream: false
      })
    }, BROWSER_SYNC_RELOAD_DELAY)
  })
})
<|endoftext|>


<commit_before>/**********Gulp Cconfiguration file*************/
'use strict';
//create a gulp instance
var gulp = require('gulp');
var browserSync = require('browser-sync');
var nodemon = require('gulp-nodemon');

gulp.task('default', ['browser-sync'], function () {
});

gulp.task('browser-sync', ['nodemon'], function() {
	browserSync.init(null, {
		proxy: "http://localhost:4000",
        files: ["public/**/*.*"],
        ///browser: "google chrome",
        port: 7000,
	});
});
gulp.task('nodemon', function (cb) {

	var started = false;

	return nodemon({
		script: './bin/www'
	}).on('start', function () {
		// to avoid nodemon being started multiple times
		// thanks @matthisk
		if (!started) {
			cb();
			started = true;
		}
	});
});
<commit_msg>comments<commit_after>/**********Gulp Cconfiguration file*************/
'use strict';
//create a gulp instance
var gulp = require('gulp');
//create browser-sync instance
var browserSync = require('browser-sync');
//create gulp-nodemon instance
var nodemon = require('gulp-nodemon');

//create and set default task
gulp.task('default', ['browser-sync'], function() {});

//create and set browser-sync task and inject nodemon task
gulp.task('browser-sync', ['nodemon'], function() {
    browserSync.init(null, {
        //set express app url
        proxy: "http://localhost:4000",
        //files to watch
        files: ["public/**/*.*"],
        ///browser: "google chrome",
        //set port for gulp
        port: 7000,
    });
});

//create and set nodemon task
gulp.task('nodemon', function(cb) {
    var started = false;
    //set starting script of express app
    return nodemon({
        script: './bin/www'
    }).on('start', function() {
        // to avoid nodemon being started multiple times
        // thanks @matthisk
        if (!started) {
            cb();
            started = true;
        }
    });
});
<|endoftext|>


<commit_before>/**
 * Copyright 2013-2015, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

'use strict';

var babel = require('gulp-babel');
var babelPluginDEV = require('fbjs/scripts/babel/dev-expression');
var babelPluginModules = require('fbjs/scripts/babel/rewrite-modules');
var del = require('del');
var derequire = require('gulp-derequire');
var envify = require('envify/custom');
var flatten = require('gulp-flatten');
var gulp = require('gulp');
var gulpUtil = require('gulp-util');
var header = require('gulp-header');
var objectAssign = require('object-assign');
var runSequence = require('run-sequence');
var webpackStream = require('webpack-stream');

var DEVELOPMENT_HEADER = [
  '/**',
  ' * Relay v<%= version %>',
  ' */'
].join('\n') + '\n';
var PRODUCTION_HEADER = [
  '/**',
  ' * Relay v<%= version %>',
  ' *',
  ' * Copyright 2013-2015, Facebook, Inc.',
  ' * All rights reserved.',
  ' *',
  ' * This source code is licensed under the BSD-style license found in the',
  ' * LICENSE file in the root directory of this source tree. An additional grant',
  ' * of patent rights can be found in the PATENTS file in the same directory.',
  ' *',
  ' */'
].join('\n') + '\n';

var babelOpts = {
  nonStandard: true,
  loose: [
    'es6.classes'
  ],
  stage: 1,
  optional: ['runtime'],
  plugins: [babelPluginDEV, babelPluginModules],
  _moduleMap: objectAssign({}, require('fbjs/module-map'), {
    'crc32': 'crc32',
    'React': 'react',
    'StaticContainer.react': 'react-static-container'
  })
};

var buildDist = function(opts) {
  var webpackOpts = {
    debug: opts.debug,
    externals: {
      react: 'React'
    },
    module: {
      loaders: [
        {test: /\.js$/, loader: 'babel'}
      ],
    },
    output: {
      filename: opts.output,
      libraryTarget: 'var',
      library: 'Relay'
    },
    plugins: [
      new webpackStream.webpack.DefinePlugin({
        'process.env.NODE_ENV': JSON.stringify(
          opts.debug ? 'development' : 'production'
        ),
      }),
      new webpackStream.webpack.optimize.OccurenceOrderPlugin(),
      new webpackStream.webpack.optimize.DedupePlugin()
    ]
  };
  if (!opts.debug) {
    webpackOpts.plugins.push(
      new webpackStream.webpack.optimize.UglifyJsPlugin({
        compress: {
          hoist_vars: true,
          screw_ie8: true,
          warnings: false
        }
      })
    );
  }
  return webpackStream(webpackOpts, null, function(err, stats) {
    if (err) {
      throw new gulpUtil.PluginError('webpack', err);
    }
    if (stats.compilation.errors.length) {
      gulpUtil.log('webpack', '\n' + stats.toString({colors: true}));
    }
  });
};

var paths = {
  dist: 'dist',
  entry: 'lib/Relay.js',
  lib: 'lib',
  src: [
    '*src/**/*.js',
    '!src/**/__tests__/**/*.js',
    '!src/**/__mocks__/**/*.js'
  ],
};

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

gulp.task('modules', function() {
  return gulp
    .src(paths.src)
    .pipe(babel(babelOpts))
    .pipe(flatten())
    .pipe(gulp.dest(paths.lib));
});

gulp.task('dist', ['modules'], function () {
  var distOpts = {
    debug: true,
    output: 'relay.js'
  };
  return gulp.src(paths.entry)
    .pipe(buildDist(distOpts))
    .pipe(derequire())
    .pipe(header(DEVELOPMENT_HEADER, {
      version: process.env.npm_package_version
    }))
    .pipe(gulp.dest(paths.dist));
});

gulp.task('dist:min', ['modules'], function () {
  var distOpts = {
    debug: false,
    output: 'relay.min.js'
  };
  return gulp.src(paths.entry)
    .pipe(buildDist(distOpts))
    .pipe(header(PRODUCTION_HEADER, {
      version: process.env.npm_package_version
    }))
    .pipe(gulp.dest(paths.dist));
});

gulp.task('website:check-version', function(cb) {
  var version = require('./package').version;
  var websiteVersion = require('./website/core/SiteData').version;
  if (websiteVersion !== version) {
    return cb(
      new Error('Website version does not match package.json. Saw ' + websiteVersion + ' but expected ' + version)
    );
  }
  cb();
});

gulp.task('watch', function() {
  gulp.watch(paths.src, ['modules']);
});

gulp.task('default', function(cb) {
  runSequence('clean', 'website:check-version', 'modules', ['dist', 'dist:min'], cb);
});
<commit_msg>Build the dist/ bundles with the UMD. Closes #65<commit_after>/**
 * Copyright 2013-2015, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

'use strict';

var babel = require('gulp-babel');
var babelPluginDEV = require('fbjs/scripts/babel/dev-expression');
var babelPluginModules = require('fbjs/scripts/babel/rewrite-modules');
var del = require('del');
var derequire = require('gulp-derequire');
var envify = require('envify/custom');
var flatten = require('gulp-flatten');
var gulp = require('gulp');
var gulpUtil = require('gulp-util');
var header = require('gulp-header');
var objectAssign = require('object-assign');
var runSequence = require('run-sequence');
var webpackStream = require('webpack-stream');

var DEVELOPMENT_HEADER = [
  '/**',
  ' * Relay v<%= version %>',
  ' */'
].join('\n') + '\n';
var PRODUCTION_HEADER = [
  '/**',
  ' * Relay v<%= version %>',
  ' *',
  ' * Copyright 2013-2015, Facebook, Inc.',
  ' * All rights reserved.',
  ' *',
  ' * This source code is licensed under the BSD-style license found in the',
  ' * LICENSE file in the root directory of this source tree. An additional grant',
  ' * of patent rights can be found in the PATENTS file in the same directory.',
  ' *',
  ' */'
].join('\n') + '\n';

var babelOpts = {
  nonStandard: true,
  loose: [
    'es6.classes'
  ],
  stage: 1,
  optional: ['runtime'],
  plugins: [babelPluginDEV, babelPluginModules],
  _moduleMap: objectAssign({}, require('fbjs/module-map'), {
    'crc32': 'crc32',
    'React': 'react',
    'StaticContainer.react': 'react-static-container'
  })
};

var buildDist = function(opts) {
  var webpackOpts = {
    debug: opts.debug,
    externals: {
      react: 'React'
    },
    module: {
      loaders: [
        {test: /\.js$/, loader: 'babel'}
      ],
    },
    output: {
      filename: opts.output,
      libraryTarget: 'umd',
      library: 'Relay'
    },
    plugins: [
      new webpackStream.webpack.DefinePlugin({
        'process.env.NODE_ENV': JSON.stringify(
          opts.debug ? 'development' : 'production'
        ),
      }),
      new webpackStream.webpack.optimize.OccurenceOrderPlugin(),
      new webpackStream.webpack.optimize.DedupePlugin()
    ]
  };
  if (!opts.debug) {
    webpackOpts.plugins.push(
      new webpackStream.webpack.optimize.UglifyJsPlugin({
        compress: {
          hoist_vars: true,
          screw_ie8: true,
          warnings: false
        }
      })
    );
  }
  return webpackStream(webpackOpts, null, function(err, stats) {
    if (err) {
      throw new gulpUtil.PluginError('webpack', err);
    }
    if (stats.compilation.errors.length) {
      gulpUtil.log('webpack', '\n' + stats.toString({colors: true}));
    }
  });
};

var paths = {
  dist: 'dist',
  entry: 'lib/Relay.js',
  lib: 'lib',
  src: [
    '*src/**/*.js',
    '!src/**/__tests__/**/*.js',
    '!src/**/__mocks__/**/*.js'
  ],
};

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

gulp.task('modules', function() {
  return gulp
    .src(paths.src)
    .pipe(babel(babelOpts))
    .pipe(flatten())
    .pipe(gulp.dest(paths.lib));
});

gulp.task('dist', ['modules'], function () {
  var distOpts = {
    debug: true,
    output: 'relay.js'
  };
  return gulp.src(paths.entry)
    .pipe(buildDist(distOpts))
    .pipe(derequire())
    .pipe(header(DEVELOPMENT_HEADER, {
      version: process.env.npm_package_version
    }))
    .pipe(gulp.dest(paths.dist));
});

gulp.task('dist:min', ['modules'], function () {
  var distOpts = {
    debug: false,
    output: 'relay.min.js'
  };
  return gulp.src(paths.entry)
    .pipe(buildDist(distOpts))
    .pipe(header(PRODUCTION_HEADER, {
      version: process.env.npm_package_version
    }))
    .pipe(gulp.dest(paths.dist));
});

gulp.task('website:check-version', function(cb) {
  var version = require('./package').version;
  var websiteVersion = require('./website/core/SiteData').version;
  if (websiteVersion !== version) {
    return cb(
      new Error('Website version does not match package.json. Saw ' + websiteVersion + ' but expected ' + version)
    );
  }
  cb();
});

gulp.task('watch', function() {
  gulp.watch(paths.src, ['modules']);
});

gulp.task('default', function(cb) {
  runSequence('clean', 'website:check-version', 'modules', ['dist', 'dist:min'], cb);
});
<|endoftext|>


<commit_before>require('./index.js')(require('gulp'))
<commit_msg>gulp dev again<commit_after>var gulp = require('./index.js')(require('gulp'))

gulp.task('dev', 'DEVELOP', [
  'build',
  'sourcegate:watch',
  'build:watch'
])
<|endoftext|>


<commit_before>/*jslint node: true, vars: true */

"use strict";

var exec = require("child_process").exec;
var gulp = require("gulp");
var jshint = require("gulp-jshint");
var jslint = require("gulp-jslint-simple");
var monitorCtrlC = require("monitorctrlc");
var taskFromStreams = require("gulp-taskfromstreams");

var srcFiles = "{.,./lib}/*.js*";
var testFiles = "tests/*.js";

gulp.task("lint", taskFromStreams(function () {
    return [
        gulp.src([srcFiles, testFiles]),
        jshint(),
        jslint.run(),
        jslint.report({ emitErrorAtEnd: true })
    ];
}));

gulp.task("test", ["lint"], function (cb) {
    exec("node run-tests.js '" + testFiles + "'", function (err, stdout) {
        if (err) { return cb(err); }
        process.stdout.write(stdout);
        cb();
    });
});

gulp.task("watch", function () {
    monitorCtrlC();
    gulp.watch([srcFiles, testFiles], ["test"]);
    gulp.start("test");
});
<commit_msg>Fail 'test' task *after* printing test output.<commit_after>/*jslint node: true, vars: true */

"use strict";

var exec = require("child_process").exec;
var gulp = require("gulp");
var jshint = require("gulp-jshint");
var jslint = require("gulp-jslint-simple");
var monitorCtrlC = require("monitorctrlc");
var taskFromStreams = require("gulp-taskfromstreams");

var srcFiles = "{.,./lib}/*.js*";
var testFiles = "tests/*.js";

gulp.task("lint", taskFromStreams(function () {
    return [
        gulp.src([srcFiles, testFiles]),
        jshint(),
        jslint.run(),
        jslint.report({ emitErrorAtEnd: true })
    ];
}));

gulp.task("test", ["lint"], function (cb) {
    exec("node run-tests.js '" + testFiles + "'", function (err, stdout) {
        process.stdout.write(stdout);
        cb(err ? "Test failure" : null);
    });
});

gulp.task("watch", function () {
    monitorCtrlC();
    gulp.watch([srcFiles, testFiles], ["test"]);
    gulp.start("test");
});
<|endoftext|>


<commit_before>var fs       = require('fs'),
    glob     = require('glob'),
    zlib     = require('zlib'),
    path     = require('path'),
    args     = require('yargs').argv,
    util     = require('gulp-util'),
    merge    = require('merge-stream'),
    concat   = require('gulp-concat-util'),
    replace  = require('gulp-replace'),
    through  = require('through2'),
    compiler = require('closure-compiler-stream'),
    gulp     = require('gulp-npm-run')(require('gulp'));

var COMPIER_JAR_PATH = 'bower_components/closure-compiler/compiler.jar';
var PRECOMPILED_MIN_DIR = 'release/precompiled/minified/';
var PRECOMPILED_DEV_DIR = 'release/precompiled/development/';

var HELP_MESSAGE = [
  '',
  '    %Usage%',
  '',
  '      gulp [TASK] [OPTIONS]',
  '',
  '    %Tasks%',
  '',
  '      |dev|                          Build non-minified (concatenate files only).',
  '      |min|                          Build minified release.',
  '      |help|                         Show this message.',
  '',
  '    %Options%',
  '',
  '      -p, --packages PACKAGES      Comma separated packages to include. Packages listed below (non-default marked with |*|).',
  '      -r, --release RELEASE        Release name. Default: "custom".',
  '',
  '    %Packages%',
  '',
  '      array',
  '      date',
  '      function',
  '      number',
  '      object',
  '      range',
  '      regexp',
  '      string',
  '      es5 |*|',
  '      locales |*|',
  '      language |*|',
  '      inflections |*|',
  ''
].join('\n');

var DEFAULT_PACKAGES = [
  'array',
  'date',
  'range',
  'function',
  'number',
  'object',
  'regexp',
  'string'
];

var ALL_PACKAGES = [
  'array',
  'date',
  'range',
  'function',
  'number',
  'object',
  'regexp',
  'string',
  'inflections',
  'language',
  'locales'
];

function getPackages() {
  return args.p || args.packages || 'default';
}

function getFiles(packages, skipLocales) {
  var arr, files = [];
  files.push('lib/core.js');
  files.push('lib/common.js');
  switch(packages) {
    case 'core':
      return ['lib/core.js'];
    case 'default':
      arr = DEFAULT_PACKAGES;
    break;
    case 'all':
      arr = ALL_PACKAGES;
    break;
    default:
      arr = packages.split(',');
  }
  arr.forEach(function(p) {
    if (p === 'locales' && !skipLocales) {
      files = files.concat(glob.sync('lib/locales/*.js'));
    } else {
      files.push('lib/' + p + '.js');
    }
  });
  return files;
}

function getModules(files) {
  var modules = [], locales = [];
  files.forEach(function(f) {
    var name = f.match(/(\w+)\.js/)[1];
    if (name === 'core') {
      modules.push(['core:1', f]);
    } else if (f.match(/locales/)) {
      locales.push(f);
    } else {
      modules.push([name + ':1:core', f]);
    }
  });
  if (locales.length) {
    modules.push(['locales:' + locales.length + ':core'].concat(locales));
  }
  return modules;
}

function showHelpMessage() {
  var msg = HELP_MESSAGE
    .replace(/%\w+%/g, function(match) {
      return util.colors.underline(match.replace(/%/g, ''));
    })
  .replace(/\|.+\|/g, function(match) {
    if(match === '|*|') {
      return util.colors.yellow(match.replace(/\|/g, ''));
    } else {
      return util.colors.cyan(match.replace(/\|/g, ''));
    }
  });
  console.info(msg);
}

function getFilename(name, min) {
  return name + (min ? '.min' : '') + '.js';
}

function getPackageFilename(packages, min) {
  switch(packages) {
    case 'default':
      return getFilename('sugar', min);
    case 'all':
      return getFilename('sugar-full', min);
    default:
      return getFilename('sugar-custom', min);
  }
}

function getRelease() {
  return args.r || args.release || 'custom';
}

function getLicense() {
  var release = getRelease();
  return fs.readFileSync('release/copyright.txt', 'utf-8')
    .replace(/VERSION/, release.match(/[\d.]+/) ? 'v' + release : release)
    .replace(/YEAR/, new Date().getFullYear())
    .replace(/\n$/, '');
}

function buildDevelopment(packages) {
  var template = [
    getLicense(),
    '(function() {',
      "  'use strict';",
      '$1',
    '})();'
  ].join('\n');
  var filename = getPackageFilename(packages);
  var files = getFiles(packages);
  util.log(util.colors.yellow('Building:', packages));
  return gulp.src(files)
    .pipe(concat(filename, { newLine: '' }))
    .pipe(replace(/^\s*'use strict';\n/g, ''))
    .pipe(replace(/^([\s\S]+)$/m, template))
    .pipe(gulp.dest('release'));
}

function buildMinified(packages) {
  try {
    fs.lstatSync(COMPIER_JAR_PATH);
  } catch(e) {
    util.log(util.colors.red('Closure compiler missing!'), 'Run', util.colors.yellow('bower install'));
    return;
  }
  var filename = getPackageFilename(packages, true);
  var files = getFiles(packages);
  util.log(util.colors.yellow('Minifying:', packages));
  return gulp.src(files).pipe(compileSingle('release/' + filename));
}

// -------------- Compiler ----------------

function compileModules(modules) {
  var flags = getDefaultFlags();
  flags.module = modules;
  flags.module_output_path_prefix = PRECOMPILED_MIN_DIR;
  return compiler(flags);
}

function compileSingle(path) {
  var flags = getDefaultFlags();
  flags.js_output_file = path;
  return compiler(flags);
}

function getDefaultFlags() {
  return {
    jar: COMPIER_JAR_PATH,
    compilation_level: 'ADVANCED_OPTIMIZATIONS',
    warning_level: 'QUIET',
    output_wrapper: getLicense() + "\n(function(){'use strict';%output%}).call(window);",
    externs: 'lib/extras/externs.js',
  }
}

// -------------- Build ----------------

gulp.task('default', showHelpMessage);

gulp.task('help', showHelpMessage);

gulp.task('dev', function() {
  return buildDevelopment(getPackages());
});

gulp.task('dev:all', function() {
  return buildDevelopment('all');
});

gulp.task('min', function(done) {
  return buildMinified(getPackages());
});

gulp.task('release', function() {
  util.log(util.colors.blue('-------------------------------'));
  util.log(util.colors.blue('Creating release:', getRelease()));
  util.log(util.colors.blue('-------------------------------'));
  return merge(buildDevelopment('default'), buildMinified('default'), buildDevelopment('all'), buildMinified('all'));
});

gulp.task('precompile:dev', function() {
  var files = getFiles('all').filter(function(path) {
    return !path.match(/locales/);
  });
  return merge(gulp.src(files), gulp.src('lib/locales/*.js')
      .pipe(concat('locales.js', { newLine: '' })))
    .pipe(replace(/^\s*'use strict';\n/g, ''))
    .pipe(gulp.dest(PRECOMPILED_DEV_DIR));
});

gulp.task('precompile:min', function() {
  var files = getFiles('all');
  var modules = getModules(files);
  return gulp.src(files).pipe(compileModules(modules));
});

// -------------- npm ----------------

var NPM_MODULES = [
  {
    name: 'sugar',
    files: 'default'
  },
  {
    name: 'sugar-full',
    files: 'all'
  },
  {
    name: 'sugar-core',
    files: 'core'
  },
  {
    name: 'sugar-array',
    files: 'array'
  },
  {
    name: 'sugar-date',
    files: 'date'
  },
  {
    name: 'sugar-date-locales',
    files: 'date,locales'
  },
  {
    name: 'sugar-range',
    files: 'range'
  },
  {
    name: 'sugar-function',
    files: 'function'
  },
  {
    name: 'sugar-number',
    files: 'number'
  },
  {
    name: 'sugar-object',
    files: 'object'
  },
  {
    name: 'sugar-regexp',
    files: 'regexp'
  },
  {
    name: 'sugar-string',
    files: 'string'
  },
  {
    name: 'sugar-inflections',
    files: 'string,inflections'
  },
  {
    name: 'sugar-language',
    files: 'language'
  }
];

gulp.task('npm', function() {
  var template = [
    '(function() {',
      "  'use strict';",
      '$1',
      '  module.exports = Sugar;',
      '',
    '})();'
  ].join('\n');
  var streams = [];
  for (var i = 0; i < NPM_MODULES.length; i++) {
    var module = NPM_MODULES[i];
    streams.push(
      gulp.src(getFiles(module.files))
        .pipe(concat(module.name + '.js', { newLine: '' }))
        .pipe(replace(/^\s*'use strict';\n/g, ''))
        .pipe(replace(/^.*\/\/ npm ignore\n/gim, ''))
        .pipe(replace(/^([\s\S]+)$/m, template))
        .pipe(gulp.dest('release/npm/' + module.name))
    );
  }
  return merge(streams);
});

// -------------- Test ----------------

gulp.task('test:watch', function() {
  gulp.watch(['lib/**/*.js'], ['dev:all', 'test']);
  gulp.watch(['test/**/*.js'], ['test']);
});

// -------------- Docs ----------------

gulp.task('docs', function() {
  var files = getFiles('all', true), packages = {}, methodsByNamespace = {};
  var output = args.f || args.file || 'docs.json';
  var basename = path.basename(output);
  var dirname = path.dirname(output);

  return gulp.src(files)
    .pipe(through.obj(function(file, enc, cb) {
      var text, lines, currentNamespace, currentPackage;

      text = file.contents.toString('utf-8')
      lines = text.split('\n');

      function extractMethodNameAndArgs(obj, str) {
        var match = str.match(/(\w+\.)?([^(]+)\(([^\)]*)\)/), args = [];
        var klass = match[1];
        var name  = match[2];

        match[3].split(',').forEach(function(a) {
          var o = a.split(' = '), arg = {};
          var required = true;
          var argName = o[0].trim().replace(/[<>]/g, '').replace(/[\[\]]/g, function(s) {
            required = false;
            return '';
          });
          if (!argName) {
            return;
          } else if (argName == '...') {
            obj['glob'] = true;
            return;
          }
          arg['name'] = argName;
          if (o[1]) {
            arg['default'] = o[1];
            arg['type'] = eval('typeof ' + o[1]);
          }
          if (!required) {
            arg['optional'] = true;
          }
          args.push(arg);
        });
        if (!klass) {
          obj['instance'] = true;
        }
        if (args.length) {
          obj['args'] = args;
        }
        return name;
      }

      function getLineNumber(name) {
        var lineNum;
        var reg = RegExp('@method ' + name + '\\b');
        lines.some(function(l, i) {
          if (l.match(reg)) {
            lineNum = i + 1;
            return true;
          }
        });
        return lineNum;
      }

      function switchNamespace(name) {
        currentNamespace = methodsByNamespace[name];
        if (!currentNamespace) {
          currentNamespace = methodsByNamespace[name] = {};
        }
      }

      function getMultiline(str) {
        var result = [], fOpen = false;
        str.split('\n').forEach(function(l) {
          l = l.replace(/^[\s*]+|[\s*]+$/g, '').replace(/\s+->.+$/, '');
          if (l) {
            if (fOpen) {
              result[result.length - 1] += '\n' + l;
            } else {
              result.push(l);
            }
          }
          if (l.match(/\{$/)) {
            fOpen = true;
          } else if (l.match(/^\}/)) {
            fOpen = false;
          }
        });
        return result;
      }

      function getFileSize(path) {
        return fs.statSync(path).size;
      }

      function getGzippedFileSize(path) {
        return zlib.gzipSync(fs.readFileSync(path, 'utf-8')).length;
      }

      function getPackageSize(package) {
        var name = package.replace(/\s/g, '_').toLowerCase();
        var dPath = 'release/precompiled/development/' + name + '.js';
        var mPath = 'release/precompiled/minified/' + name + '.js';
        packages[package]['size'] = getFileSize(dPath);
        packages[package]['min_size'] = getGzippedFileSize(mPath);
      }

      text.replace(/\*\*\*([\s\S]+?)[\s\n*]*(?=\*\*\*)/gm, function(m, tags) {
        var obj = {};
        tags.replace(/@(\w+)\s?([^@]*)/g, function(all, key, val) {
          val = val.replace(/^[\s*]/gm, '').replace(/[\s*]+$/, '');
          switch(key) {
            case 'package':
              packages[val] = obj;
              currentPackage = val;
              if (DEFAULT_PACKAGES.indexOf(val.toLowerCase()) !== -1) {
                obj['supplemental'] = true;
              }
              switchNamespace(val);
              getPackageSize(val);
              break;
            case 'namespace':
              switchNamespace(val);
              break;
            case 'method':
              var name = extractMethodNameAndArgs(obj, val);
              obj.line = getLineNumber(name);
              obj.package = currentPackage;
              currentNamespace[name] = obj;
              break;
            case 'set':
              obj[key] = getMultiline(val);
              break;
            case 'example':
              obj[key] = getMultiline(val);
              break;
            default:
              obj[key] = val;
          }
        });
      });
      this.push(file);
      cb();
    }))
    .pipe(concat(basename, { newLine: '' }))
    .pipe(through.obj(function(file, enc, cb) {
      file.contents = new Buffer(JSON.stringify({
        packages: packages,
        methodsByNamespace: methodsByNamespace
      }), "utf8");
      this.push(file);
      cb();
    }))
    .pipe(gulp.dest(dirname));
});
<commit_msg>gulp-npm-run doesn't seem to be needed anymore<commit_after>var fs       = require('fs'),
    gulp     = require('gulp'),
    glob     = require('glob'),
    zlib     = require('zlib'),
    path     = require('path'),
    args     = require('yargs').argv,
    util     = require('gulp-util'),
    merge    = require('merge-stream'),
    concat   = require('gulp-concat-util'),
    replace  = require('gulp-replace'),
    through  = require('through2'),
    compiler = require('closure-compiler-stream');

var COMPIER_JAR_PATH = 'bower_components/closure-compiler/compiler.jar';
var PRECOMPILED_MIN_DIR = 'release/precompiled/minified/';
var PRECOMPILED_DEV_DIR = 'release/precompiled/development/';

var HELP_MESSAGE = [
  '',
  '    %Usage%',
  '',
  '      gulp [TASK] [OPTIONS]',
  '',
  '    %Tasks%',
  '',
  '      |dev|                          Build non-minified (concatenate files only).',
  '      |min|                          Build minified release.',
  '      |help|                         Show this message.',
  '',
  '    %Options%',
  '',
  '      -p, --packages PACKAGES      Comma separated packages to include. Packages listed below (non-default marked with |*|).',
  '      -r, --release RELEASE        Release name. Default: "custom".',
  '',
  '    %Packages%',
  '',
  '      array',
  '      date',
  '      function',
  '      number',
  '      object',
  '      range',
  '      regexp',
  '      string',
  '      es5 |*|',
  '      locales |*|',
  '      language |*|',
  '      inflections |*|',
  ''
].join('\n');

var DEFAULT_PACKAGES = [
  'array',
  'date',
  'range',
  'function',
  'number',
  'object',
  'regexp',
  'string'
];

var ALL_PACKAGES = [
  'array',
  'date',
  'range',
  'function',
  'number',
  'object',
  'regexp',
  'string',
  'inflections',
  'language',
  'locales'
];

function getPackages() {
  return args.p || args.packages || 'default';
}

function getFiles(packages, skipLocales) {
  var arr, files = [];
  files.push('lib/core.js');
  files.push('lib/common.js');
  switch(packages) {
    case 'core':
      return ['lib/core.js'];
    case 'default':
      arr = DEFAULT_PACKAGES;
    break;
    case 'all':
      arr = ALL_PACKAGES;
    break;
    default:
      arr = packages.split(',');
  }
  arr.forEach(function(p) {
    if (p === 'locales' && !skipLocales) {
      files = files.concat(glob.sync('lib/locales/*.js'));
    } else {
      files.push('lib/' + p + '.js');
    }
  });
  return files;
}

function getModules(files) {
  var modules = [], locales = [];
  files.forEach(function(f) {
    var name = f.match(/(\w+)\.js/)[1];
    if (name === 'core') {
      modules.push(['core:1', f]);
    } else if (f.match(/locales/)) {
      locales.push(f);
    } else {
      modules.push([name + ':1:core', f]);
    }
  });
  if (locales.length) {
    modules.push(['locales:' + locales.length + ':core'].concat(locales));
  }
  return modules;
}

function showHelpMessage() {
  var msg = HELP_MESSAGE
    .replace(/%\w+%/g, function(match) {
      return util.colors.underline(match.replace(/%/g, ''));
    })
  .replace(/\|.+\|/g, function(match) {
    if(match === '|*|') {
      return util.colors.yellow(match.replace(/\|/g, ''));
    } else {
      return util.colors.cyan(match.replace(/\|/g, ''));
    }
  });
  console.info(msg);
}

function getFilename(name, min) {
  return name + (min ? '.min' : '') + '.js';
}

function getPackageFilename(packages, min) {
  switch(packages) {
    case 'default':
      return getFilename('sugar', min);
    case 'all':
      return getFilename('sugar-full', min);
    default:
      return getFilename('sugar-custom', min);
  }
}

function getRelease() {
  return args.r || args.release || 'custom';
}

function getLicense() {
  var release = getRelease();
  return fs.readFileSync('release/copyright.txt', 'utf-8')
    .replace(/VERSION/, release.match(/[\d.]+/) ? 'v' + release : release)
    .replace(/YEAR/, new Date().getFullYear())
    .replace(/\n$/, '');
}

function buildDevelopment(packages) {
  var template = [
    getLicense(),
    '(function() {',
      "  'use strict';",
      '$1',
    '})();'
  ].join('\n');
  var filename = getPackageFilename(packages);
  var files = getFiles(packages);
  util.log(util.colors.yellow('Building:', packages));
  return gulp.src(files)
    .pipe(concat(filename, { newLine: '' }))
    .pipe(replace(/^\s*'use strict';\n/g, ''))
    .pipe(replace(/^([\s\S]+)$/m, template))
    .pipe(gulp.dest('release'));
}

function buildMinified(packages) {
  try {
    fs.lstatSync(COMPIER_JAR_PATH);
  } catch(e) {
    util.log(util.colors.red('Closure compiler missing!'), 'Run', util.colors.yellow('bower install'));
    return;
  }
  var filename = getPackageFilename(packages, true);
  var files = getFiles(packages);
  util.log(util.colors.yellow('Minifying:', packages));
  return gulp.src(files).pipe(compileSingle('release/' + filename));
}

// -------------- Compiler ----------------

function compileModules(modules) {
  var flags = getDefaultFlags();
  flags.module = modules;
  flags.module_output_path_prefix = PRECOMPILED_MIN_DIR;
  return compiler(flags);
}

function compileSingle(path) {
  var flags = getDefaultFlags();
  flags.js_output_file = path;
  return compiler(flags);
}

function getDefaultFlags() {
  return {
    jar: COMPIER_JAR_PATH,
    compilation_level: 'ADVANCED_OPTIMIZATIONS',
    warning_level: 'QUIET',
    output_wrapper: getLicense() + "\n(function(){'use strict';%output%}).call(window);",
    externs: 'lib/extras/externs.js',
  }
}

// -------------- Build ----------------

gulp.task('default', showHelpMessage);

gulp.task('help', showHelpMessage);

gulp.task('dev', function() {
  return buildDevelopment(getPackages());
});

gulp.task('dev:all', function() {
  return buildDevelopment('all');
});

gulp.task('min', function(done) {
  return buildMinified(getPackages());
});

gulp.task('release', function() {
  util.log(util.colors.blue('-------------------------------'));
  util.log(util.colors.blue('Creating release:', getRelease()));
  util.log(util.colors.blue('-------------------------------'));
  return merge(buildDevelopment('default'), buildMinified('default'), buildDevelopment('all'), buildMinified('all'));
});

gulp.task('precompile:dev', function() {
  var files = getFiles('all').filter(function(path) {
    return !path.match(/locales/);
  });
  return merge(gulp.src(files), gulp.src('lib/locales/*.js')
      .pipe(concat('locales.js', { newLine: '' })))
    .pipe(replace(/^\s*'use strict';\n/g, ''))
    .pipe(gulp.dest(PRECOMPILED_DEV_DIR));
});

gulp.task('precompile:min', function() {
  var files = getFiles('all');
  var modules = getModules(files);
  return gulp.src(files).pipe(compileModules(modules));
});

// -------------- npm ----------------

var NPM_MODULES = [
  {
    name: 'sugar',
    files: 'default'
  },
  {
    name: 'sugar-full',
    files: 'all'
  },
  {
    name: 'sugar-core',
    files: 'core'
  },
  {
    name: 'sugar-array',
    files: 'array'
  },
  {
    name: 'sugar-date',
    files: 'date'
  },
  {
    name: 'sugar-date-locales',
    files: 'date,locales'
  },
  {
    name: 'sugar-range',
    files: 'range'
  },
  {
    name: 'sugar-function',
    files: 'function'
  },
  {
    name: 'sugar-number',
    files: 'number'
  },
  {
    name: 'sugar-object',
    files: 'object'
  },
  {
    name: 'sugar-regexp',
    files: 'regexp'
  },
  {
    name: 'sugar-string',
    files: 'string'
  },
  {
    name: 'sugar-inflections',
    files: 'string,inflections'
  },
  {
    name: 'sugar-language',
    files: 'language'
  }
];

gulp.task('npm', function() {
  var template = [
    '(function() {',
      "  'use strict';",
      '$1',
      '  module.exports = Sugar;',
      '',
    '})();'
  ].join('\n');
  var streams = [];
  for (var i = 0; i < NPM_MODULES.length; i++) {
    var module = NPM_MODULES[i];
    streams.push(
      gulp.src(getFiles(module.files))
        .pipe(concat(module.name + '.js', { newLine: '' }))
        .pipe(replace(/^\s*'use strict';\n/g, ''))
        .pipe(replace(/^.*\/\/ npm ignore\n/gim, ''))
        .pipe(replace(/^([\s\S]+)$/m, template))
        .pipe(gulp.dest('release/npm/' + module.name))
    );
  }
  return merge(streams);
});

// -------------- Test ----------------

gulp.task('test:watch', function() {
  gulp.watch(['lib/**/*.js'], ['dev:all', 'test']);
  gulp.watch(['test/**/*.js'], ['test']);
});

// -------------- Docs ----------------

gulp.task('docs', function() {
  var files = getFiles('all', true), packages = {}, methodsByNamespace = {};
  var output = args.f || args.file || 'docs.json';
  var basename = path.basename(output);
  var dirname = path.dirname(output);

  return gulp.src(files)
    .pipe(through.obj(function(file, enc, cb) {
      var text, lines, currentNamespace, currentPackage;

      text = file.contents.toString('utf-8')
      lines = text.split('\n');

      function extractMethodNameAndArgs(obj, str) {
        var match = str.match(/(\w+\.)?([^(]+)\(([^\)]*)\)/), args = [];
        var klass = match[1];
        var name  = match[2];

        match[3].split(',').forEach(function(a) {
          var o = a.split(' = '), arg = {};
          var required = true;
          var argName = o[0].trim().replace(/[<>]/g, '').replace(/[\[\]]/g, function(s) {
            required = false;
            return '';
          });
          if (!argName) {
            return;
          } else if (argName == '...') {
            obj['glob'] = true;
            return;
          }
          arg['name'] = argName;
          if (o[1]) {
            arg['default'] = o[1];
            arg['type'] = eval('typeof ' + o[1]);
          }
          if (!required) {
            arg['optional'] = true;
          }
          args.push(arg);
        });
        if (!klass) {
          obj['instance'] = true;
        }
        if (args.length) {
          obj['args'] = args;
        }
        return name;
      }

      function getLineNumber(name) {
        var lineNum;
        var reg = RegExp('@method ' + name + '\\b');
        lines.some(function(l, i) {
          if (l.match(reg)) {
            lineNum = i + 1;
            return true;
          }
        });
        return lineNum;
      }

      function switchNamespace(name) {
        currentNamespace = methodsByNamespace[name];
        if (!currentNamespace) {
          currentNamespace = methodsByNamespace[name] = {};
        }
      }

      function getMultiline(str) {
        var result = [], fOpen = false;
        str.split('\n').forEach(function(l) {
          l = l.replace(/^[\s*]+|[\s*]+$/g, '').replace(/\s+->.+$/, '');
          if (l) {
            if (fOpen) {
              result[result.length - 1] += '\n' + l;
            } else {
              result.push(l);
            }
          }
          if (l.match(/\{$/)) {
            fOpen = true;
          } else if (l.match(/^\}/)) {
            fOpen = false;
          }
        });
        return result;
      }

      function getFileSize(path) {
        return fs.statSync(path).size;
      }

      function getGzippedFileSize(path) {
        return zlib.gzipSync(fs.readFileSync(path, 'utf-8')).length;
      }

      function getPackageSize(package) {
        var name = package.replace(/\s/g, '_').toLowerCase();
        var dPath = 'release/precompiled/development/' + name + '.js';
        var mPath = 'release/precompiled/minified/' + name + '.js';
        packages[package]['size'] = getFileSize(dPath);
        packages[package]['min_size'] = getGzippedFileSize(mPath);
      }

      text.replace(/\*\*\*([\s\S]+?)[\s\n*]*(?=\*\*\*)/gm, function(m, tags) {
        var obj = {};
        tags.replace(/@(\w+)\s?([^@]*)/g, function(all, key, val) {
          val = val.replace(/^[\s*]/gm, '').replace(/[\s*]+$/, '');
          switch(key) {
            case 'package':
              packages[val] = obj;
              currentPackage = val;
              if (DEFAULT_PACKAGES.indexOf(val.toLowerCase()) !== -1) {
                obj['supplemental'] = true;
              }
              switchNamespace(val);
              getPackageSize(val);
              break;
            case 'namespace':
              switchNamespace(val);
              break;
            case 'method':
              var name = extractMethodNameAndArgs(obj, val);
              obj.line = getLineNumber(name);
              obj.package = currentPackage;
              currentNamespace[name] = obj;
              break;
            case 'set':
              obj[key] = getMultiline(val);
              break;
            case 'example':
              obj[key] = getMultiline(val);
              break;
            default:
              obj[key] = val;
          }
        });
      });
      this.push(file);
      cb();
    }))
    .pipe(concat(basename, { newLine: '' }))
    .pipe(through.obj(function(file, enc, cb) {
      file.contents = new Buffer(JSON.stringify({
        packages: packages,
        methodsByNamespace: methodsByNamespace
      }), "utf8");
      this.push(file);
      cb();
    }))
    .pipe(gulp.dest(dirname));
});
<|endoftext|>