<commit_before>import httpStatus from 'http-status'

import {
  DEFAULT_LIMIT,
  DEFAULT_OFFSET,
  prepareAnimalResponseAll,
} from './base'

import Animal from '../models/animal'
import Conversation, {
  ConversationBelongsToManyAnimal,
  ConversationHasManyMessage,
} from '../models/conversation'
import Message from '../models/message'

import pick from '../utils/pick'
import { APIError } from '../helpers/errors'

const permittedFields = [
  'text',
  'title',
]

function prepareResponse(conversation) {
  const response = conversation.toJSON()

  if (response.animals) {
    response.animals = prepareAnimalResponseAll(response.animals)
  }

  if (response.messages) {
    response.lastMessage = response.messages[0]
    delete response.messages
  }

  return response
}

function prepareResponseAll(rows) {
  return rows.map(row => prepareResponse(row))
}

export default {
  create: (req, res, next) => {
    const values = pick(permittedFields, req.body)
    const animalIds = req.body.animalIds

    // get all receiving animals
    return Animal.findAll({
      where: {
        id: {
          $in: animalIds,
        },
      },
    }, {
      returning: true,
    })
      .then(receivingAnimals => {
        // check if receiving animal is not myself
        const isMyself = receivingAnimals.find(animal => {
          return animal.userId === req.user.id
        })

        if (isMyself) {
          next(
            new APIError(
              'You can\'t send a message to yourself',
              httpStatus.BAD_REQUEST
            )
          )
          return null
        }

        // are all receiving animals given?
        if (receivingAnimals.length !== animalIds.length) {
          next(
            new APIError(
              'One of the receiving animals does not exist',
              httpStatus.BAD_REQUEST
            )
          )
          return null
        }

        // create an animal for myself (the sending user)
        return Animal.create({
          userId: req.user.id,
        }, {
          returning: true,
        })
          .then(sendingAnimal => {
            const animals = receivingAnimals.concat([sendingAnimal])

            // create the new conversation
            return Conversation.create({
              title: values.title,
              animalId: sendingAnimal.id,
            })
              .then(conversation => {
                return conversation.setAnimals(animals)
                  .then(() => {
                    // create first message in conversation
                    return Message.create({
                      animalId: sendingAnimal.id,
                      conversationId: conversation.id,
                      text: values.text,
                    })
                      .then(() => {
                        res.json({ status: 'ok' })
                      })
                  })
              })
          })
      })
      .catch(err => next(err))
  },
  findAll: (req, res, next) => {
    const {
      limit = DEFAULT_LIMIT,
      offset = DEFAULT_OFFSET,
    } = req.query

    return Conversation.findAndCountAll({
      distinct: true,
      include: [
        {
          association: ConversationBelongsToManyAnimal,
          where: {
            userId: req.user.id,
          },
        },
        {
          association: ConversationHasManyMessage,
          group: 'conversationId',
        },
      ],
      limit,
      offset,
      order: [
        ['createdAt', 'ASC'],
        [ConversationHasManyMessage, 'createdAt', 'DESC'],
      ],
    })
      .then(result => {
        res.json({
          data: prepareResponseAll(result.rows),
          limit: parseInt(limit, 10),
          offset: parseInt(offset, 10),
          total: result.count,
        })
      })
      .catch(err => next(err))
  },
  lookup: (req, res, next) => {
    Conversation.findById(req.params.resourceId, {
      include: [
        {
          association: ConversationBelongsToManyAnimal,
          where: {
            userId: req.user.id,
          },
        },
      ],
      rejectOnEmpty: true,
    })
      .then(conversation => {
        req.conversation = conversation
        next()
      })
      .catch(err => next(err))
  },
  findOne: (req, res, next) => {
    return Conversation.findById(req.params.resourceId, {
      include: [
        ConversationBelongsToManyAnimal,
      ],
      rejectOnEmpty: true,
    })
      .then(conversation => res.json(prepareResponse(conversation)))
      .catch(err => next(err))
  },
}
<commit_msg>Newest conversations are at the top<commit_after>import httpStatus from 'http-status'

import {
  DEFAULT_LIMIT,
  DEFAULT_OFFSET,
  prepareAnimalResponseAll,
} from './base'

import Animal from '../models/animal'
import Conversation, {
  ConversationBelongsToManyAnimal,
  ConversationHasManyMessage,
} from '../models/conversation'
import Message from '../models/message'

import pick from '../utils/pick'
import { APIError } from '../helpers/errors'

const permittedFields = [
  'text',
  'title',
]

function prepareResponse(conversation) {
  const response = conversation.toJSON()

  if (response.animals) {
    response.animals = prepareAnimalResponseAll(response.animals)
  }

  if (response.messages) {
    response.lastMessage = response.messages[0]
    delete response.messages
  }

  return response
}

function prepareResponseAll(rows) {
  return rows.map(row => prepareResponse(row))
}

export default {
  create: (req, res, next) => {
    const values = pick(permittedFields, req.body)
    const animalIds = req.body.animalIds

    // get all receiving animals
    return Animal.findAll({
      where: {
        id: {
          $in: animalIds,
        },
      },
    }, {
      returning: true,
    })
      .then(receivingAnimals => {
        // check if receiving animal is not myself
        const isMyself = receivingAnimals.find(animal => {
          return animal.userId === req.user.id
        })

        if (isMyself) {
          next(
            new APIError(
              'You can\'t send a message to yourself',
              httpStatus.BAD_REQUEST
            )
          )
          return null
        }

        // are all receiving animals given?
        if (receivingAnimals.length !== animalIds.length) {
          next(
            new APIError(
              'One of the receiving animals does not exist',
              httpStatus.BAD_REQUEST
            )
          )
          return null
        }

        // create an animal for myself (the sending user)
        return Animal.create({
          userId: req.user.id,
        }, {
          returning: true,
        })
          .then(sendingAnimal => {
            const animals = receivingAnimals.concat([sendingAnimal])

            // create the new conversation
            return Conversation.create({
              title: values.title,
              animalId: sendingAnimal.id,
            })
              .then(conversation => {
                return conversation.setAnimals(animals)
                  .then(() => {
                    // create first message in conversation
                    return Message.create({
                      animalId: sendingAnimal.id,
                      conversationId: conversation.id,
                      text: values.text,
                    })
                      .then(() => {
                        res.json({ status: 'ok' })
                      })
                  })
              })
          })
      })
      .catch(err => next(err))
  },
  findAll: (req, res, next) => {
    const {
      limit = DEFAULT_LIMIT,
      offset = DEFAULT_OFFSET,
    } = req.query

    return Conversation.findAndCountAll({
      distinct: true,
      include: [
        {
          association: ConversationBelongsToManyAnimal,
          where: {
            userId: req.user.id,
          },
        },
        {
          association: ConversationHasManyMessage,
          group: 'conversationId',
        },
      ],
      limit,
      offset,
      order: [
        [ConversationHasManyMessage, 'createdAt', 'DESC'],
      ],
    })
      .then(result => {
        res.json({
          data: prepareResponseAll(result.rows),
          limit: parseInt(limit, 10),
          offset: parseInt(offset, 10),
          total: result.count,
        })
      })
      .catch(err => next(err))
  },
  lookup: (req, res, next) => {
    Conversation.findById(req.params.resourceId, {
      include: [
        {
          association: ConversationBelongsToManyAnimal,
          where: {
            userId: req.user.id,
          },
        },
      ],
      rejectOnEmpty: true,
    })
      .then(conversation => {
        req.conversation = conversation
        next()
      })
      .catch(err => next(err))
  },
  findOne: (req, res, next) => {
    return Conversation.findById(req.params.resourceId, {
      include: [
        ConversationBelongsToManyAnimal,
      ],
      rejectOnEmpty: true,
    })
      .then(conversation => res.json(prepareResponse(conversation)))
      .catch(err => next(err))
  },
}
<|endoftext|>


<commit_before>// Dependencies that makes this all work! Yay packages!
var gulp = require('gulp'),
    cleanCSS = require('gulp-clean-css'),
    del = require('del'),
    inlineCSS = require('gulp-inline-css'),
    preprocess = require('gulp-preprocess'),
    rename = require('gulp-rename'),
    strip = require('gulp-strip-comments');

// Load in environment variables from .boilerplate.defaults first and then .boilerplate.custom if it exists
var boilerplateConfig = require('dotenv-extended').load(
    {
        encoding: 'utf8',
        silent: true,
        path: '.boilerplate.custom',
        defaults: '.boilerplate.defaults',
        errorOnMissing: false,
        errorOnExtra: false,
        assignToProcessEnv: true,
        overrideProcessEnv: true
    }
);

// We only want to target this file for HTML processing, the guidelines version is static and legacy
email_boilerplate_file = 'app/email-boilerplate.html.preprocess';

// Clean out the build directories
gulp.task('clean', function () {
    return del(
        [
            'tmp/css/**',
            'tmp/html-samples/**',
            'dist/boilerplate/**'
        ]
    ).then(paths => {
        console.log('Cleaning directories :\n', paths.join('\n'));
    });
});

// Pre-process CSS files with config values
gulp.task('preprocess-css', function() {
    var stream = gulp.src('./app/css/*.css')
    .pipe(preprocess())
    .pipe(gulp.dest('./tmp/css/'))
    return stream;
});

// Minify processed CSS for inclusion in the email boilerplate
gulp.task('minify-css', ['preprocess-css'], function() {
    var stream = gulp.src('./tmp/css/*.css')
    .pipe(cleanCSS(
        {
            // We don't want to go too crazy when minifying, this is email after all!
            advanced: false,
            aggressiveMerging: false,
            debug: true, // Needed for the size output on before and after min files
            keepBreaks: true,
            keepSpecialComments: 0,
            shorthandCompacting: false,
            // Defensive for less friendly email clients
            compatibility: '*,' +
            '-properties.colors,' +
            '-properties.zeroUnits'
        },
        // Log original size and minified size in gulp output
        function(details) {
            console.log(details.name + ': ' + details.stats.originalSize);
            console.log(details.name + '.min' + ': ' + details.stats.minifiedSize);
        })
    )
    .pipe(rename({ extname: '.css.min' }))
    .pipe(gulp.dest('./tmp/css/'));
    return stream;
});

// Build all HTML samples and strip comments to be included in boilerplate
gulp.task('build-html-samples', function() {
    gulp.src('./app/html-samples/*.html')
    .pipe(preprocess())
    .pipe(strip(
        {
            safe: true,
            trim: true
        }
    ))
    .pipe(gulp.dest('./tmp/html-samples/'));
});

// Build email boilerplate HTML and put everything together!
gulp.task('preprocess-boilerplate', ['minify-css'], function() {
    var stream = gulp.src(email_boilerplate_file)
    .pipe(preprocess({ extension: 'html' }))
    .pipe(rename('email-boilerplate.html'))
    .pipe(gulp.dest('./dist/boilerplate/'))
    return stream;
});

// Inline CSS to main layout elements after boilerplate is generated and update it
gulp.task('inline-css', ['preprocess-boilerplate'], function () {

    // We need to check if DOCTYPE_VERSION is using an XHTML value
    var currentSetDoctype = process.env.DOCTYPE_VERSION;
    if (/XHTML/i.test(currentSetDoctype)) {
        xmlMode = true;
    } else {
        xmlMode = false;
    }

    var stream = gulp.src('./dist/boilerplate/email-boilerplate.html')
    .pipe(inlineCSS(
        {
            applyTableAttributes: true,
            applyStyleTags: false,
            applyLinkTags: true,
            applyWidthAttributes: true,
            removeStyleTags: false,
            removeLinkTags: true,
            xmlMode: xmlMode
        }
    ))
    .pipe(gulp.dest('./dist/boilerplate/'));
    return stream;
});

// The order is important! The CSS pre-process stuff must happen first otherwise minify will break everything!
gulp.task('default',
    [
        'clean',
        'preprocess-css',
        'minify-css',
        'build-html-samples',
        'preprocess-boilerplate',
        'inline-css'
    ]
);
<commit_msg>Log message for older .env file being found<commit_after>// Dependencies that makes this all work! Yay packages!
var gulp = require('gulp'),
    cleanCSS = require('gulp-clean-css'),
    del = require('del'),
    inlineCSS = require('gulp-inline-css'),
    preprocess = require('gulp-preprocess'),
    rename = require('gulp-rename'),
    strip = require('gulp-strip-comments');

// Load in environment variables from .boilerplate.defaults first and then .boilerplate.custom if it exists
var boilerplateConfig = require('dotenv-extended').load(
    {
        encoding: 'utf8',
        silent: true,
        path: '.boilerplate.custom',
        defaults: '.boilerplate.defaults',
        errorOnMissing: false,
        errorOnExtra: false,
        assignToProcessEnv: true,
        overrideProcessEnv: true
    }
);

// We only want to target this file for HTML processing, the guidelines version is static and legacy
email_boilerplate_file = 'app/email-boilerplate.html.preprocess';

// Clean out the build directories
gulp.task('clean', function () {
    return del(
        [
            'tmp/css/**',
            'tmp/html-samples/**',
            'dist/boilerplate/**'
        ]
    ).then(paths => {
        console.log('Cleaning directories :\n', paths.join('\n'));
    });
});

// Pre-process CSS files with config values
gulp.task('preprocess-css', function() {
    var stream = gulp.src('./app/css/*.css')
    .pipe(preprocess())
    .pipe(gulp.dest('./tmp/css/'))
    return stream;
});

// Minify processed CSS for inclusion in the email boilerplate
gulp.task('minify-css', ['preprocess-css'], function() {
    var stream = gulp.src('./tmp/css/*.css')
    .pipe(cleanCSS(
        {
            // We don't want to go too crazy when minifying, this is email after all!
            advanced: false,
            aggressiveMerging: false,
            debug: true, // Needed for the size output on before and after min files
            keepBreaks: true,
            keepSpecialComments: 0,
            shorthandCompacting: false,
            // Defensive for less friendly email clients
            compatibility: '*,' +
            '-properties.colors,' +
            '-properties.zeroUnits'
        },
        // Log original size and minified size in gulp output
        function(details) {
            console.log(details.name + ': ' + details.stats.originalSize);
            console.log(details.name + '.min' + ': ' + details.stats.minifiedSize);
        })
    )
    .pipe(rename({ extname: '.css.min' }))
    .pipe(gulp.dest('./tmp/css/'));
    return stream;
});

// Build all HTML samples and strip comments to be included in boilerplate
gulp.task('build-html-samples', function() {
    gulp.src('./app/html-samples/*.html')
    .pipe(preprocess())
    .pipe(strip(
        {
            safe: true,
            trim: true
        }
    ))
    .pipe(gulp.dest('./tmp/html-samples/'));
});

// Build email boilerplate HTML and put everything together!
gulp.task('preprocess-boilerplate', ['minify-css'], function() {
    var stream = gulp.src(email_boilerplate_file)
    .pipe(preprocess({ extension: 'html' }))
    .pipe(rename('email-boilerplate.html'))
    .pipe(gulp.dest('./dist/boilerplate/'))
    return stream;
});

// Inline CSS to main layout elements after boilerplate is generated and update it
gulp.task('inline-css', ['preprocess-boilerplate'], function () {

    // We need to check if DOCTYPE_VERSION is using an XHTML value
    var currentSetDoctype = process.env.DOCTYPE_VERSION;
    if (/XHTML/i.test(currentSetDoctype)) {
        xmlMode = true;
    } else {
        xmlMode = false;
    }

    var stream = gulp.src('./dist/boilerplate/email-boilerplate.html')
    .pipe(inlineCSS(
        {
            applyTableAttributes: true,
            applyStyleTags: false,
            applyLinkTags: true,
            applyWidthAttributes: true,
            removeStyleTags: false,
            removeLinkTags: true,
            xmlMode: xmlMode
        }
    ))
    .pipe(gulp.dest('./dist/boilerplate/'));
    return stream;
});

// Check if older .env file is present and log to console
gulp.task('old-env-check', ['inline-css'], function() {
    var fs = require('fs');
    fs.stat('.env', function(err, stat) {
        if(err == null) {
            console.log('Note: .env is deprecated, please rename your custom settings file to .boilerplate.custom');
        }
    });
});

// The order is important! The CSS pre-process stuff must happen first otherwise minify will break everything!
gulp.task('default',
    [
        'clean',
        'preprocess-css',
        'minify-css',
        'build-html-samples',
        'preprocess-boilerplate',
        'inline-css',
        'old-env-check'
    ]
);
<|endoftext|>


<commit_before>/* global browser */
/*eslint-env node */
"use strict";

// npm install --save-dev gulp gulp-util chalk gulp-replace-task gulp-cleanhtml gulp-strip-debug gulp-concat gulp-uglify gulp-rm gulp-zip gulp-eslint through2 gulp-minify-css gulp-load-plugins chai gulp-spawn-mocha sinon sinon-chai jsdom

var chalk = require('chalk');
var cleanhtml = require('gulp-cleanhtml');
var concat = require('gulp-concat');
var eslint = require('gulp-eslint');
var gulp = require('gulp');
var gulpUtil = require('gulp-util');
var minifyCSS = require('gulp-minify-css');
var mocha = require('gulp-spawn-mocha');
var replace = require('gulp-replace-task');
var rm = require('gulp-rm');
var stripdebug = require('gulp-strip-debug');
var uglify = require('gulp-uglify');
var zip = require('gulp-zip');
var argv = require('yargs').argv;
var webdriver = require('gulp-webdriver');
var connect = require('gulp-connect');

// this can be used to debug gulp runs
// .pipe(debug({verbose: true}))
/*eslint-disable no-unused-vars */
var debug = require('gulp-debug');
/*eslint-enable no-unused-vars */

// Load the manifest as JSON
var manifest = require('./src/manifest');

// The final .zip filename that gets uploaded to https://chrome.google.com/webstore/developer/dashboard
var distFilename = manifest.name.replace(/[ ]/g, "_").toLowerCase() + "-v-" + manifest.version + ".zip";

//
// Replacements config for gulp-replace
//
// 1.  Sets debug: false (in utils.js)
// 2.  Removes Logger statements
// 3.  Remove everything in .js files between "// REMOVE START" and "REMOVE END"
//     These blocks contain development code that gets optimized away
// 4.  Remove everything in .html files between "<!-- REMOVE START" and "REMOVE END -->"
//     These blocks contain development code that gets optimized away
// 5.  Activate blocks between "<!-- BUILD START" and "BUILD END -->"
//     These contain the optimized files for the final build
// 6.  Remove the "js:" array from the manifest
//     These blocks contain development code that gets optimized away
// 7.  Remove the "scripts:" array from the manifest
//     These blocks contain development code that gets optimized away
// 8.  Rename the "jsBuild" part in the manifest to be the "js" part
//     These contain the optimized files for the final build
// 9.  Rename the "scriptsBuild" part in the manifest to be the "scripts" part
//     These contain the optimized files for the final build
// 10. Replace ##VERSION## with the correct version string from the manifest
var replaceOpts = {
  preserveOrder: true,
  patterns: [
    {
      match: /debug\s*:\s*true,/g,
      replacement: "debug: false,"
    },
    {
      match: /.*Logger.*/g,
      replacement: ""
    },
    {
      match: /^.*\/\/ REMOVE START[\s\S]*?\/\/ REMOVE END.*$/gm,
      replacement: ""
    },
    {
      match: /<!-- REMOVE START[\s\S]*?REMOVE END -->/gm,
      replacement: ""
    },
    {
      match: /<!-- BUILD START/g,
      replacement: ""
    },
    {
      match: /BUILD END -->/g,
      replacement: ""
    },
    {
      match: /^.*"js":[\s\S]*?\],.*$/gm,
      replacement: ""
    },
    {
      match: /^.*"scripts"[\s\S]*?\],.*$/gm,
      replacement: ""
    },
    {
      match: /"jsBuild"/g,
      replacement: "\"js\""
    },
    {
      match: /"scriptsBuild"/g,
      replacement: "\"scripts\""
    },
    {
      match: /##VERSION##/g,
      replacement: manifest.version
    },
    {
      match: /"management",\n/g,
      replacement: ""
    }
  ]
};

var runTests = function() {
  return gulp.src(['test/**/*_spec.js'], {read: false}).pipe(mocha({
    R: 'dot',
    c: true,
    debug: true
  })).on('error', console.warn.bind(console));
};

// Output which version to build where to
gulp.task('announce', function() {
  gulpUtil.log(
    'Building version', chalk.cyan(manifest.version),
    'of', chalk.cyan(manifest.name),
    'as', chalk.cyan("dist/" + distFilename)
  );
});

// Cleans build and dist dirs
// I sense a bug here!
gulp.task('clean', ["announce"], function() {
  return gulp.src(['build/**'], {read: false})
  .pipe(rm({async: false}));
});

// ESLINT the javascript BEFORE uglifier ran over them
gulp.task('lint', function () {
  return gulp.src(['src/js/**/*.js'])
  .pipe(eslint())
  .pipe(eslint.format())
  .pipe(eslint.failOnError());
});

// Optimize CSS
gulp.task('css', ['clean'], function () {
  return gulp.src(["src/css/*.css", "!src/css/content.css", "!src/css/popup.css"], { nonegate: false })
  .pipe(replace(replaceOpts))
  .pipe(concat('formofill.css'))
  .pipe(minifyCSS())
  .pipe(gulp.dest('build/css/'));
});

// Build global.js
// Sadly until I use require.js here the order is important :(
gulp.task('globalJs', ['clean'], function () {
  return gulp.src([
    "src/js/global/utils.js",
    "src/js/global/jsonf.js",
    "src/js/global/storage.js",
    "src/js/global/rule.js",
    "src/js/global/rules.js",
    "src/js/global/i18n.js",
    "src/js/global/libs.js",
    "src/js/global/workflow.js"
  ])
  .pipe(replace(replaceOpts))
  .pipe(concat('global.js'))
  .pipe(stripdebug())
  .pipe(uglify())
  .pipe(gulp.dest('build/js/'));
});

// Build background.js
gulp.task('backgroundJs', ['clean'], function () {
  return gulp.src("src/js/background/*.js")
  .pipe(replace(replaceOpts))
  .pipe(concat('background.js'))
  .pipe(stripdebug())
  .pipe(uglify())
  .pipe(gulp.dest('build/js/'));
});

// Build content.js
gulp.task('contentJs', ['clean'], function () {
  return gulp.src("src/js/content/*.js")
  .pipe(replace(replaceOpts))
  .pipe(concat('content.js'))
  .pipe(stripdebug())
  .pipe(uglify())
  .pipe(gulp.dest('build/js/'));
});

// Build options.js
gulp.task('optionsJs', ['clean'], function () {
  return gulp.src(["src/js/options/*.js", "!src/js/options/logs.js"], { nonegate: false })
  .pipe(replace(replaceOpts))
  .pipe(concat('options.js'))
  .pipe(stripdebug())
  .pipe(uglify())
  .pipe(gulp.dest('build/js/'));
});

// Build popup.js
gulp.task('popupJs', ['clean'], function () {
  return gulp.src("src/js/popup.js")
  .pipe(replace(replaceOpts))
  .pipe(stripdebug())
  .pipe(uglify())
  .pipe(gulp.dest('build/js'));
});

// Copies files that can be copied without changes
gulp.task('copyUnchanged', ['clean'], function() {
  ["fonts", "images", "vendor", "_locales", "!src/vendor/jquery/jquery-2.1.3.js"].forEach(function (dir) {
    gulp.src('src/' + dir + '/**/*', { nonegate: false })
    .pipe(gulp.dest('build/' + dir));
  });

  return gulp.src(['src/css/content.css', 'src/css/popup.css'])
  .pipe(minifyCSS())
  .pipe(replace(replaceOpts))
  .pipe(gulp.dest('build/css'));
});

// Copies HTML files and removes comment and blocks (see above)
gulp.task('copyHtml', ['copyUnchanged'], function() {
  return gulp.src(['src/html/**/*.html', '!src/html/options/_logs_*.html'], { nonegate: false })
  .pipe(replace(replaceOpts))
  .pipe(cleanhtml())
  .pipe(gulp.dest('build/html'));
});

// Copies and replaces the manifest.json file (see above)
gulp.task('mangleManifest', [ 'clean' ], function() {
  return gulp.src('src/manifest.json')
  .pipe(replace(replaceOpts))
  .pipe(gulp.dest('build'));
});

// Build a distribution
gulp.task('build', ['announce', 'clean', 'test', 'lint', 'copyHtml', 'css', 'globalJs', 'backgroundJs', 'contentJs', 'optionsJs', 'popupJs', 'mangleManifest'], function() {
  gulp.src(['build/**'])
  .pipe(zip(distFilename))
  .pipe(gulp.dest('dist'));
});

// Run tests
gulp.task('test', function () {
  gulpUtil.log('Running tests');
  return runTests().on('error', function (e) {
    throw e;
  });
});

// Run tests through watching
gulp.task('watch', function () {
  gulp.watch(['src/js/**/*.js', 'test/**/*.js'], runTests);
});

// Starts a simple webserver
gulp.task('webserver:start', function() {
  connect.server({
    root: "testcases/docroot-for-testing",
    livereload: false,
    port: 9292
  });
});

// Kills the server
gulp.task('webserver:stop', connect.serverClose);

gulp.task("integration", [ "webserver:start", "integration:run" ], function() {
  connect.serverClose();
});

// Integration testing (end-to-end)
// Uses webdriverio as an abstraction layer over chromedriver
//
// You can specify a single spec to run via:
// gulp integration --spec test/integration/some_spec_scene.js
//
// Specify a single spec with
// gulp integration --grep "a\sregex"
gulp.task('integration:run', [ "webserver:start" ], function () {

  var specs = [
    "./test/integration/test_setup_scene.js",
    "./test/integration/all_types_scene.js",
    "./test/integration/form_filling_scene.js",
    "./test/integration/shared_rules_scene.js",
    "./test/integration/popup_scene.js",
    "./test/integration/form_extraction_scene.js",
    "./test/integration/options_scene.js"
  ];

  // Allow --spec parameter
  if (argv.spec) {
    specs = [argv.spec];
  }

  var mochaOpts = {
    R: 'spec',
    c: true,
    debug: false,
    inlineDiffs: true
  };

  // Allow --grep as mocha opt
  if (argv.grep) {
    mochaOpts.grep = argv.grep;
  }

  return gulp.src(specs, {read: false})
  .pipe(webdriver({desiredCapabilities: {
    browserName: "chrome"
  }}));
});

// running "gulp" will execute this
gulp.task('default', function () {
  runTests();
});
<commit_msg>add intor.css to build<commit_after>/* global browser */
/*eslint-env node */
"use strict";

// npm install --save-dev gulp gulp-util chalk gulp-replace-task gulp-cleanhtml gulp-strip-debug gulp-concat gulp-uglify gulp-rm gulp-zip gulp-eslint through2 gulp-minify-css gulp-load-plugins chai gulp-spawn-mocha sinon sinon-chai jsdom

var chalk = require('chalk');
var cleanhtml = require('gulp-cleanhtml');
var concat = require('gulp-concat');
var eslint = require('gulp-eslint');
var gulp = require('gulp');
var gulpUtil = require('gulp-util');
var minifyCSS = require('gulp-minify-css');
var mocha = require('gulp-spawn-mocha');
var replace = require('gulp-replace-task');
var rm = require('gulp-rm');
var stripdebug = require('gulp-strip-debug');
var uglify = require('gulp-uglify');
var zip = require('gulp-zip');
var argv = require('yargs').argv;
var webdriver = require('gulp-webdriver');
var connect = require('gulp-connect');

// this can be used to debug gulp runs
// .pipe(debug({verbose: true}))
/*eslint-disable no-unused-vars */
var debug = require('gulp-debug');
/*eslint-enable no-unused-vars */

// Load the manifest as JSON
var manifest = require('./src/manifest');

// The final .zip filename that gets uploaded to https://chrome.google.com/webstore/developer/dashboard
var distFilename = manifest.name.replace(/[ ]/g, "_").toLowerCase() + "-v-" + manifest.version + ".zip";

//
// Replacements config for gulp-replace
//
// 1.  Sets debug: false (in utils.js)
// 2.  Removes Logger statements
// 3.  Remove everything in .js files between "// REMOVE START" and "REMOVE END"
//     These blocks contain development code that gets optimized away
// 4.  Remove everything in .html files between "<!-- REMOVE START" and "REMOVE END -->"
//     These blocks contain development code that gets optimized away
// 5.  Activate blocks between "<!-- BUILD START" and "BUILD END -->"
//     These contain the optimized files for the final build
// 6.  Remove the "js:" array from the manifest
//     These blocks contain development code that gets optimized away
// 7.  Remove the "scripts:" array from the manifest
//     These blocks contain development code that gets optimized away
// 8.  Rename the "jsBuild" part in the manifest to be the "js" part
//     These contain the optimized files for the final build
// 9.  Rename the "scriptsBuild" part in the manifest to be the "scripts" part
//     These contain the optimized files for the final build
// 10. Replace ##VERSION## with the correct version string from the manifest
var replaceOpts = {
  preserveOrder: true,
  patterns: [
    {
      match: /debug\s*:\s*true,/g,
      replacement: "debug: false,"
    },
    {
      match: /.*Logger.*/g,
      replacement: ""
    },
    {
      match: /^.*\/\/ REMOVE START[\s\S]*?\/\/ REMOVE END.*$/gm,
      replacement: ""
    },
    {
      match: /<!-- REMOVE START[\s\S]*?REMOVE END -->/gm,
      replacement: ""
    },
    {
      match: /<!-- BUILD START/g,
      replacement: ""
    },
    {
      match: /BUILD END -->/g,
      replacement: ""
    },
    {
      match: /^.*"js":[\s\S]*?\],.*$/gm,
      replacement: ""
    },
    {
      match: /^.*"scripts"[\s\S]*?\],.*$/gm,
      replacement: ""
    },
    {
      match: /"jsBuild"/g,
      replacement: "\"js\""
    },
    {
      match: /"scriptsBuild"/g,
      replacement: "\"scripts\""
    },
    {
      match: /##VERSION##/g,
      replacement: manifest.version
    },
    {
      match: /"management",\n/g,
      replacement: ""
    }
  ]
};

var runTests = function() {
  return gulp.src(['test/**/*_spec.js'], {read: false}).pipe(mocha({
    R: 'dot',
    c: true,
    debug: true
  })).on('error', console.warn.bind(console));
};

// Output which version to build where to
gulp.task('announce', function() {
  gulpUtil.log(
    'Building version', chalk.cyan(manifest.version),
    'of', chalk.cyan(manifest.name),
    'as', chalk.cyan("dist/" + distFilename)
  );
});

// Cleans build and dist dirs
// I sense a bug here!
gulp.task('clean', ["announce"], function() {
  return gulp.src(['build/**'], {read: false})
  .pipe(rm({async: false}));
});

// ESLINT the javascript BEFORE uglifier ran over them
gulp.task('lint', function () {
  return gulp.src(['src/js/**/*.js'])
  .pipe(eslint())
  .pipe(eslint.format())
  .pipe(eslint.failOnError());
});

// Optimize CSS
gulp.task('css', ['clean'], function () {
  return gulp.src(["src/vendor/intro.js/introjs.min.css", "src/css/*.css", "!src/css/content.css", "!src/css/popup.css"], { nonegate: false })
  .pipe(replace(replaceOpts))
  .pipe(concat('formofill.css'))
  .pipe(minifyCSS())
  .pipe(gulp.dest('build/css/'));
});

// Build global.js
// Sadly until I use require.js here the order is important :(
gulp.task('globalJs', ['clean'], function () {
  return gulp.src([
    "src/js/global/utils.js",
    "src/js/global/jsonf.js",
    "src/js/global/storage.js",
    "src/js/global/rule.js",
    "src/js/global/rules.js",
    "src/js/global/i18n.js",
    "src/js/global/libs.js",
    "src/js/global/workflow.js"
  ])
  .pipe(replace(replaceOpts))
  .pipe(concat('global.js'))
  .pipe(stripdebug())
  .pipe(uglify())
  .pipe(gulp.dest('build/js/'));
});

// Build background.js
gulp.task('backgroundJs', ['clean'], function () {
  return gulp.src("src/js/background/*.js")
  .pipe(replace(replaceOpts))
  .pipe(concat('background.js'))
  .pipe(stripdebug())
  .pipe(uglify())
  .pipe(gulp.dest('build/js/'));
});

// Build content.js
gulp.task('contentJs', ['clean'], function () {
  return gulp.src("src/js/content/*.js")
  .pipe(replace(replaceOpts))
  .pipe(concat('content.js'))
  .pipe(stripdebug())
  .pipe(uglify())
  .pipe(gulp.dest('build/js/'));
});

// Build options.js
gulp.task('optionsJs', ['clean'], function () {
  return gulp.src(["src/js/options/*.js", "!src/js/options/logs.js"], { nonegate: false })
  .pipe(replace(replaceOpts))
  .pipe(concat('options.js'))
  .pipe(stripdebug())
  .pipe(uglify())
  .pipe(gulp.dest('build/js/'));
});

// Build popup.js
gulp.task('popupJs', ['clean'], function () {
  return gulp.src("src/js/popup.js")
  .pipe(replace(replaceOpts))
  .pipe(stripdebug())
  .pipe(uglify())
  .pipe(gulp.dest('build/js'));
});

// Copies files that can be copied without changes
gulp.task('copyUnchanged', ['clean'], function() {
  ["fonts", "images", "vendor", "_locales", "!src/vendor/jquery/jquery-2.1.3.js"].forEach(function (dir) {
    gulp.src('src/' + dir + '/**/*', { nonegate: false })
    .pipe(gulp.dest('build/' + dir));
  });

  return gulp.src(['src/css/content.css', 'src/css/popup.css'])
  .pipe(minifyCSS())
  .pipe(replace(replaceOpts))
  .pipe(gulp.dest('build/css'));
});

// Copies HTML files and removes comment and blocks (see above)
gulp.task('copyHtml', ['copyUnchanged'], function() {
  return gulp.src(['src/html/**/*.html', '!src/html/options/_logs_*.html'], { nonegate: false })
  .pipe(replace(replaceOpts))
  .pipe(cleanhtml())
  .pipe(gulp.dest('build/html'));
});

// Copies and replaces the manifest.json file (see above)
gulp.task('mangleManifest', [ 'clean' ], function() {
  return gulp.src('src/manifest.json')
  .pipe(replace(replaceOpts))
  .pipe(gulp.dest('build'));
});

// Build a distribution
gulp.task('build', ['announce', 'clean', 'test', 'lint', 'copyHtml', 'css', 'globalJs', 'backgroundJs', 'contentJs', 'optionsJs', 'popupJs', 'mangleManifest'], function() {
  gulp.src(['build/**'])
  .pipe(zip(distFilename))
  .pipe(gulp.dest('dist'));
});

// Run tests
gulp.task('test', function () {
  gulpUtil.log('Running tests');
  return runTests().on('error', function (e) {
    throw e;
  });
});

// Run tests through watching
gulp.task('watch', function () {
  gulp.watch(['src/js/**/*.js', 'test/**/*.js'], runTests);
});

// Starts a simple webserver
gulp.task('webserver:start', function() {
  connect.server({
    root: "testcases/docroot-for-testing",
    livereload: false,
    port: 9292
  });
});

// Kills the server
gulp.task('webserver:stop', connect.serverClose);

gulp.task("integration", [ "webserver:start", "integration:run" ], function() {
  connect.serverClose();
});

// Integration testing (end-to-end)
// Uses webdriverio as an abstraction layer over chromedriver
//
// You can specify a single spec to run via:
// gulp integration --spec test/integration/some_spec_scene.js
//
// Specify a single spec with
// gulp integration --grep "a\sregex"
gulp.task('integration:run', [ "webserver:start" ], function () {

  var specs = [
    "./test/integration/test_setup_scene.js",
    "./test/integration/all_types_scene.js",
    "./test/integration/form_filling_scene.js",
    "./test/integration/shared_rules_scene.js",
    "./test/integration/popup_scene.js",
    "./test/integration/form_extraction_scene.js",
    "./test/integration/options_scene.js"
  ];

  // Allow --spec parameter
  if (argv.spec) {
    specs = [argv.spec];
  }

  var mochaOpts = {
    R: 'spec',
    c: true,
    debug: false,
    inlineDiffs: true
  };

  // Allow --grep as mocha opt
  if (argv.grep) {
    mochaOpts.grep = argv.grep;
  }

  return gulp.src(specs, {read: false})
  .pipe(webdriver({desiredCapabilities: {
    browserName: "chrome"
  }}));
});

// running "gulp" will execute this
gulp.task('default', function () {
  runTests();
});
<|endoftext|>


<commit_before><commit_msg>[feat]: start locationRoutes<commit_after>var models = require('../models');
var locationController = require('../controllers/locationController.js');

module.exports = function(app) {
  app.post('/locations');
}<|endoftext|>


<commit_before>var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var open = require('open');
var bowerFiles = require('main-bower-files');
var series = require('stream-series');
var runSequence = require('run-sequence');
var webpack = require('webpack-stream');

gulp.task('watch', ['server'], function() {
  $.livereload.listen();
  gulp.start('test:watch');
  gulp.watch('src/*.js', ['eslint', 'webpack']);
  gulp.watch(['./index.html', './webpack/**']).on('change', $.livereload.changed);
});

gulp.task('server', function() {
  $.connect.server({
    root: ['./'],
    port: 8000,
    livereload: false
  });

  open('http://localhost:8000');
});

gulp.task('webpack', function() {
  return gulp.src('src/angular-bluebird-promises.js')
    .pipe(webpack({
      output: {
        filename: 'angular-bluebird-promises.js'
      },
      externals: {
        angular: 'angular',
        bluebird: 'Promise'
      },
      devtool: 'source-map'
    }))
    .pipe(gulp.dest('webpack'));
});

var pkg = require('./bower.json');
var banner = ['/**',
  ' * <%= pkg.name %> - <%= pkg.description %>',
  ' * @version v<%= pkg.version %>',
  ' * @link <%= pkg.homepage %>',
  ' * @license <%= pkg.license %>',
  ' */',
  ''].join('\n');

gulp.task('build', ['webpack'], function() {

  return gulp.src('webpack/*.js')
    .pipe($.sourcemaps.init({
      loadMaps: true
    }))
    .pipe($.header(banner, { pkg : pkg } ))
    .pipe($.ngAnnotate())
    .pipe(gulp.dest('dist'))
    .pipe($.rename('angular-bluebird-promises.min.js'))
    .pipe($.uglify())
    .pipe($.header(banner, { pkg : pkg } ))
    .pipe($.sourcemaps.write('.'))
    .pipe(gulp.dest('dist'));

});

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

function runTests(action, onDistCode) {
  var vendorJs = gulp.src(bowerFiles({includeDev: true}));
  if (onDistCode) {
    var appJs = gulp.src('dist/angular-bluebird-promises.min.js');
  } else {
    var appJs = gulp.src('webpack/angular-bluebird-promises.js');
  }
  var test = gulp.src('test/angular-bluebird-promises.spec.js');

  return series(vendorJs, appJs, test)
    .pipe($.karma({
      configFile: 'karma.conf.js',
      action: action
    }));
}

gulp.task('test:src', ['webpack'], function() {
  return runTests('run').on('error', function(err) {
    throw err;
  });
});

gulp.task('test:dist', function() {
  return runTests('run', true).on('error', function(err) {
    throw err;
  });
});

gulp.task('test:watch', function() {
  gulp.watch('src/*.js', ['eslint', 'webpack']);
  return runTests('watch');
});

function eslint(failOnError) {
  var stream = gulp.src(['src/*.js'])
    .pipe($.eslint())
    .pipe($.eslint.format());

  if (failOnError) {
    return stream.pipe($.eslint.failOnError());
  } else {
    return stream;
  }
}

gulp.task('eslint', function() {
  return eslint();
});

gulp.task('ci:eslint', function() {
  return eslint(true);
});

gulp.task('ci', function(done) {
  runSequence('ci:eslint', 'build', 'test:dist', done);
});
<commit_msg>Remove unncescary watch<commit_after>var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var open = require('open');
var bowerFiles = require('main-bower-files');
var series = require('stream-series');
var runSequence = require('run-sequence');
var webpack = require('webpack-stream');

gulp.task('watch', ['server'], function() {
  $.livereload.listen();
  gulp.start('test:watch');
  gulp.watch('src/*.js', ['eslint', 'webpack']);
  gulp.watch(['./index.html', './webpack/**']).on('change', $.livereload.changed);
});

gulp.task('server', function() {
  $.connect.server({
    root: ['./'],
    port: 8000,
    livereload: false
  });

  open('http://localhost:8000');
});

gulp.task('webpack', function() {
  return gulp.src('src/angular-bluebird-promises.js')
    .pipe(webpack({
      output: {
        filename: 'angular-bluebird-promises.js'
      },
      externals: {
        angular: 'angular',
        bluebird: 'Promise'
      },
      devtool: 'source-map'
    }))
    .pipe(gulp.dest('webpack'));
});

var pkg = require('./bower.json');
var banner = ['/**',
  ' * <%= pkg.name %> - <%= pkg.description %>',
  ' * @version v<%= pkg.version %>',
  ' * @link <%= pkg.homepage %>',
  ' * @license <%= pkg.license %>',
  ' */',
  ''].join('\n');

gulp.task('build', ['webpack'], function() {

  return gulp.src('webpack/*.js')
    .pipe($.sourcemaps.init({
      loadMaps: true
    }))
    .pipe($.header(banner, { pkg : pkg } ))
    .pipe($.ngAnnotate())
    .pipe(gulp.dest('dist'))
    .pipe($.rename('angular-bluebird-promises.min.js'))
    .pipe($.uglify())
    .pipe($.header(banner, { pkg : pkg } ))
    .pipe($.sourcemaps.write('.'))
    .pipe(gulp.dest('dist'));

});

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

function runTests(action, onDistCode) {
  var vendorJs = gulp.src(bowerFiles({includeDev: true}));
  if (onDistCode) {
    var appJs = gulp.src('dist/angular-bluebird-promises.min.js');
  } else {
    var appJs = gulp.src('webpack/angular-bluebird-promises.js');
  }
  var test = gulp.src('test/angular-bluebird-promises.spec.js');

  return series(vendorJs, appJs, test)
    .pipe($.karma({
      configFile: 'karma.conf.js',
      action: action
    }));
}

gulp.task('test:src', ['webpack'], function() {
  return runTests('run').on('error', function(err) {
    throw err;
  });
});

gulp.task('test:dist', function() {
  return runTests('run', true).on('error', function(err) {
    throw err;
  });
});

gulp.task('test:watch', function() {
  return runTests('watch');
});

function eslint(failOnError) {
  var stream = gulp.src(['src/*.js'])
    .pipe($.eslint())
    .pipe($.eslint.format());

  if (failOnError) {
    return stream.pipe($.eslint.failOnError());
  } else {
    return stream;
  }
}

gulp.task('eslint', function() {
  return eslint();
});

gulp.task('ci:eslint', function() {
  return eslint(true);
});

gulp.task('ci', function(done) {
  runSequence('ci:eslint', 'build', 'test:dist', done);
});
<|endoftext|>


<commit_before>const gulp          = require('gulp'),
      notify        = require('gulp-notify'),
      del           = require('del'),
      concat        = require('gulp-concat'),
      vendorFiles   = require('gulp-main-bower-files'),
      minify        = require('gulp-minify'),
      gulpFilter    = require('gulp-filter'),
      source        = require('vinyl-source-stream'),
      cleanCSS      = require('gulp-clean-css'),
      fileinclude   = require('gulp-file-include'),
      uglify        = require('gulp-uglify'),
      rename        = require("gulp-rename"),
      fs            = require("fs"),
      merge         = require('merge-stream'),
      server        = require('karma').Server;

function  interceptErrors(error) {
    let args = Array.prototype.slice.call(arguments);
    notify.onError({
	title: 'Compile Error',
	message: '<%= error.message %>'
    }).apply(this, args);
    this.emit('end');
}

const config = JSON.parse(fs.readFileSync('./config.json'));
const db_name = config.db_name || 'database';
const app_name = config.app_name || 'acution.js';
const debug = config.debug || true;
const main_css = config.main_css || 'bundle.css';
const name = config.name || 'tender';

gulp.task('fonts', () => {
    return gulp.src(config.fonts)
	.on('error', interceptErrors)
	.pipe(gulp.dest(config.buildDir+'/fonts/'));
});

gulp.task('png-images', () => {
    return gulp.src(config.img.png)
	.on('error', interceptErrors)
	.pipe(gulp.dest(config.buildDir));
});

gulp.task('icons', () => {
    return gulp.src(config.img.icons)
	.on('error', interceptErrors)
	.pipe(gulp.dest(config.buildDir+'/img/'));
});

gulp.task('bower-main', () => {
    return allJs = gulp.src('./bower.json')
	.pipe(vendorFiles({
            base: "src/lib",}))
	.pipe(gulpFilter(['**/*.js']))
	.pipe(gulp.dest(config.buildDir + '/vendor/'));
});

gulp.task('all-js', ['bower-main'], () => {
    // TODO: uglify only on debug == false
    return gulp.src([
	config.buildDir + '/vendor/angular/angular.min.js',
	config.buildDir + '/vendor/**/**/*.js',
	'./src/lib/moment/locale/uk.js',
	'./src/lib/moment/locale/ru.js',
	'./src/lib/puchdb/**/*.js',
    ])
	.pipe(concat('vendor.js'))
	.pipe(gulp.dest(config.buildDir));
});

gulp.task('css', () => {
    return gulp.src(config.styles)
	.pipe(concat(main_css))
	.pipe(cleanCSS())
	.on('error', interceptErrors)
	.pipe(gulp.dest(config.buildDir));
});

gulp.task('htmlPages', () => {
    return merge(config.html.map((page) => {
	return gulp.src('./templates/base.html')
	    .pipe(fileinclude({
		prefix: '@@',
		indent: true,
		context: {
		    title: page.title,
		    name: page.name,
		    scripts: page.scripts,
		    styles: page.styles,
		    controller: page.controller,
		    db_name: db_name,
		    auctions_server: config.auctions_server
		}}))
	    .on('error', interceptErrors)
	    .pipe(rename(page.name +'.html'))
	    .pipe(gulp.dest(config.buildDir));

    }));
});

gulp.task('listingApp', () => {
    // TODO: uglify
    return gulp.src(['./src/app/index.js',
		     './src/app/config.js',
		     './src/app/controllers/ListingCtrl.js'
		    ])
	.pipe(concat('index_app_simple.js'))
	.pipe(gulp.dest(config.buildDir));
});

gulp.task('archiveApp', () => {
    // TODO: uglify
    return gulp.src(['./src/app/archive.js',
		     './src/app/config.js',
		     './src/app/controllers/ArchiveCtl.js'])
	.pipe(concat('archive_app_simple.js'))
	.pipe(gulp.dest(config.buildDir));
});

gulp.task('auctionApp', () => {
    return gulp.src(['./src/app/auction.js',
		     './src/app/filters/*.js',
		     './src/app/translations.js',
		     './src/app/config.js',
		     './src/app/factories/*.js',
		     './src/app/controllers/AuctionCtl.js',
		     './src/app/controllers/OffCanvasCtl.js',
		     './src/app/directives/*.js'])
	.pipe(concat(app_name))
	.pipe(gulp.dest(config.buildDir));
});

gulp.task('build', ['all-js', 'css', 'png-images', 'icons', 'htmlPages', 'listingApp', 'archiveApp', 'auctionApp', 'fonts'], () => {

    let css = gulp.src(`${config.buildDir}/${main_css}`)
	.pipe(gulp.dest(config.outDir + '/static/css/'));

    let listPage = gulp.src(`${config.buildDir}/index.html`)
	.pipe(gulp.dest(config.outDir));

    let listApp = gulp.src(`${config.buildDir}/index_app_simple.js`)
	.pipe(gulp.dest(config.outDir + '/static/'));

    let vendor_js = gulp.src(`${config.buildDir}/vendor.js`)
	.pipe(gulp.dest(config.outDir + '/static/'));

    let archivePage = gulp.src(`${config.buildDir}/archive.html`)
	.pipe(gulp.dest(config.outDir));

    let archiveApp = gulp.src(`${config.buildDir}/archive_app_simple.js`)
	.pipe(gulp.dest(config.outDir + '/static/'));

    let auctionPage = gulp.src(`${config.buildDir}/${name}.html`)
	.pipe(gulp.dest(config.outDir));

    let auctionApp = gulp.src(`${config.buildDir}/${app_name}`)
	.pipe(gulp.dest(config.outDir + '/static/'));

    let png = gulp.src("build/*.png")
	.pipe(gulp.dest(config.outDir + '/static/img/'));

    let icons = gulp.src("build/img/*.png")
	.pipe(gulp.dest(config.outDir+ '/static/img/'));

    let fonts = gulp.src("build/fonts/*")
	.pipe(gulp.dest(config.outDir+'/static/fonts/'));

    let fonts2 = gulp.src("build/fonts/*")
	.pipe(gulp.dest(config.outDir+'/fonts/'));

    return merge(css, png, fonts, vendor_js, listPage, listApp, auctionPage, auctionApp, archivePage, archiveApp, fonts, fonts2, icons);
});

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

gulp.task('clean', function () {
    del.sync([config.buildDir + '*/**', config.outDir + '*/**'], {force: true});
});

gulp.task('test', function(done) {
    new server({
	configFile:__dirname + '/karma.conf.js',
	singleRun: true
    }, done).start();
});
<commit_msg>Added clean before build<commit_after>const gulp          = require('gulp'),
      notify        = require('gulp-notify'),
      del           = require('del'),
      concat        = require('gulp-concat'),
      vendorFiles   = require('gulp-main-bower-files'),
      minify        = require('gulp-minify'),
      gulpFilter    = require('gulp-filter'),
      source        = require('vinyl-source-stream'),
      cleanCSS      = require('gulp-clean-css'),
      fileinclude   = require('gulp-file-include'),
      uglify        = require('gulp-uglify'),
      rename        = require("gulp-rename"),
      fs            = require("fs"),
      merge         = require('merge-stream'),
      server        = require('karma').Server;

function  interceptErrors(error) {
    let args = Array.prototype.slice.call(arguments);
    notify.onError({
	title: 'Compile Error',
	message: '<%= error.message %>'
    }).apply(this, args);
    this.emit('end');
}

const config = JSON.parse(fs.readFileSync('./config.json'));
const db_name = config.db_name || 'database';
const app_name = config.app_name || 'acution.js';
const debug = config.debug || true;
const main_css = config.main_css || 'bundle.css';
const name = config.name || 'tender';

gulp.task('fonts', () => {
    return gulp.src(config.fonts)
	.on('error', interceptErrors)
	.pipe(gulp.dest(config.buildDir+'/fonts/'));
});

gulp.task('png-images', () => {
    return gulp.src(config.img.png)
	.on('error', interceptErrors)
	.pipe(gulp.dest(config.buildDir));
});

gulp.task('icons', () => {
    return gulp.src(config.img.icons)
	.on('error', interceptErrors)
	.pipe(gulp.dest(config.buildDir+'/img/'));
});

gulp.task('bower-main', () => {
    return allJs = gulp.src('./bower.json')
	.pipe(vendorFiles({
            base: "src/lib",}))
	.pipe(gulpFilter(['**/*.js']))
	.pipe(gulp.dest(config.buildDir + '/vendor/'));
});

gulp.task('all-js', ['bower-main'], () => {
    // TODO: uglify only on debug == false
    return gulp.src([
	config.buildDir + '/vendor/angular/angular.min.js',
	config.buildDir + '/vendor/**/**/*.js',
	'./src/lib/moment/locale/uk.js',
	'./src/lib/moment/locale/ru.js',
	'./src/lib/puchdb/**/*.js',
    ])
	.pipe(concat('vendor.js'))
	.pipe(gulp.dest(config.buildDir));
});

gulp.task('css', () => {
    return gulp.src(config.styles)
	.pipe(concat(main_css))
	.pipe(cleanCSS())
	.on('error', interceptErrors)
	.pipe(gulp.dest(config.buildDir));
});

gulp.task('htmlPages', () => {
    return merge(config.html.map((page) => {
	return gulp.src('./templates/base.html')
	    .pipe(fileinclude({
		prefix: '@@',
		indent: true,
		context: {
		    title: page.title,
		    name: page.name,
		    scripts: page.scripts,
		    styles: page.styles,
		    controller: page.controller,
		    db_name: db_name,
		    auctions_server: config.auctions_server
		}}))
	    .on('error', interceptErrors)
	    .pipe(rename(page.name +'.html'))
	    .pipe(gulp.dest(config.buildDir));

    }));
});

gulp.task('listingApp', () => {
    // TODO: uglify
    return gulp.src(['./src/app/index.js',
		     './src/app/config.js',
		     './src/app/controllers/ListingCtrl.js'
		    ])
	.pipe(concat('index_app_simple.js'))
	.pipe(gulp.dest(config.buildDir));
});

gulp.task('archiveApp', () => {
    // TODO: uglify
    return gulp.src(['./src/app/archive.js',
		     './src/app/config.js',
		     './src/app/controllers/ArchiveCtl.js'])
	.pipe(concat('archive_app_simple.js'))
	.pipe(gulp.dest(config.buildDir));
});

gulp.task('auctionApp', () => {
    return gulp.src(['./src/app/auction.js',
		     './src/app/filters/*.js',
		     './src/app/translations.js',
		     './src/app/config.js',
		     './src/app/factories/*.js',
		     './src/app/controllers/AuctionCtl.js',
		     './src/app/controllers/OffCanvasCtl.js',
		     './src/app/directives/*.js'])
	.pipe(concat(app_name))
	.pipe(gulp.dest(config.buildDir));
});

gulp.task('build', ['all-js', 'css', 'png-images', 'icons', 'htmlPages', 'listingApp', 'archiveApp', 'auctionApp', 'fonts'], () => {

    let css = gulp.src(`${config.buildDir}/${main_css}`)
	.pipe(gulp.dest(config.outDir + '/static/css/'));

    let listPage = gulp.src(`${config.buildDir}/index.html`)
	.pipe(gulp.dest(config.outDir));

    let listApp = gulp.src(`${config.buildDir}/index_app_simple.js`)
	.pipe(gulp.dest(config.outDir + '/static/'));

    let vendor_js = gulp.src(`${config.buildDir}/vendor.js`)
	.pipe(gulp.dest(config.outDir + '/static/'));

    let archivePage = gulp.src(`${config.buildDir}/archive.html`)
	.pipe(gulp.dest(config.outDir));

    let archiveApp = gulp.src(`${config.buildDir}/archive_app_simple.js`)
	.pipe(gulp.dest(config.outDir + '/static/'));

    let auctionPage = gulp.src(`${config.buildDir}/${name}.html`)
	.pipe(gulp.dest(config.outDir));

    let auctionApp = gulp.src(`${config.buildDir}/${app_name}`)
	.pipe(gulp.dest(config.outDir + '/static/'));

    let png = gulp.src("build/*.png")
	.pipe(gulp.dest(config.outDir + '/static/img/'));

    let icons = gulp.src("build/img/*.png")
	.pipe(gulp.dest(config.outDir+ '/static/img/'));

    let fonts = gulp.src("build/fonts/*")
	.pipe(gulp.dest(config.outDir+'/static/fonts/'));

    let fonts2 = gulp.src("build/fonts/*")
	.pipe(gulp.dest(config.outDir+'/fonts/'));

    return merge(css, png, fonts, vendor_js, listPage, listApp, auctionPage, auctionApp, archivePage, archiveApp, fonts, fonts2, icons);
});

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

gulp.task('clean', function () {
    del.sync([config.buildDir + '*/**', config.outDir + '*/**'], {force: true});
});

gulp.task('test', function(done) {
    new server({
	configFile:__dirname + '/karma.conf.js',
	singleRun: true
    }, done).start();
});
<|endoftext|>


<commit_before>/**
 *
 *  Web Starter Kit
 *  Copyright 2014 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';

// 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 pagespeed = require('psi');
var reload = browserSync.reload;

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

// Lint JavaScript
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')));
});

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

// Copy All Files At The Root Level (app)
gulp.task('copy', function () {
  return gulp.src([
    'app/*',
    '!app/*.html',
    'node_modules/apache-server-configs/dist/.htaccess'
  ], {
    dot: true
  }).pipe(gulp.dest('.tmp'))
    .pipe(gulp.dest('dist'))
    .pipe($.size({title: 'copy'}));
});

// Compile and Automatically Prefix Stylesheets
gulp.task('styles', function () {
  // For best performance, don't add Sass partials to `gulp.src`
  return gulp.src([
      'app/styles/*.styl',
      'app/styles/**/*.css'
    ])
    .pipe($.changed('styles', {extension: '.styl'}))
    .pipe($.stylus({
      linenos: true
    })
      .on('error', console.error.bind(console))
    )
    .pipe($.autoprefixer(AUTOPREFIXER_BROWSERS))
    // Concatenate And Minify Styles
    .pipe($.if('*.css', $.csso()))
    .pipe(gulp.dest('.tmp/styles'))
    .pipe(gulp.dest('dist/styles'))
    .pipe($.size({title: 'styles'}));
});

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

  var svgs = gulp.src(['app/images/inject-svg/*.svg'])
                 .pipe($.cache($.imagemin()))
                 .pipe($.svgstore({ prefix: 'inject-icon-', inlineSvg: true, transformSvg: transformSvg }));

  function fileContents (filePath, file) {
    return file.contents.toString('utf8');
  }

  function transformSvg ($svg, done) {
    $svg.attr('style', 'display:none');
    done(null, $svg);
  }

  return gulp.src('app/**/*.html')
    .pipe(assets)
    // Concatenate And Minify JavaScript
    .pipe($.if('*.js', $.uglify({preserveComments: 'some'})))
    // Remove Any Unused CSS
    // Note: If not using the Style Guide, you can delete it from
    // the next line to only include styles your project uses.
    .pipe($.if('*.css', $.uncss({
      html: [
        'app/index.html'
      ],
      // CSS Selectors for UnCSS to ignore
      ignore: [
        /.navdrawer-container.open/,
        /.app-bar.open/
      ]
    })))
    // Concatenate And Minify Styles
    // In case you are still using useref build blocks
    .pipe($.if('*.css', $.csso()))
    .pipe(assets.restore())
    .pipe($.useref())
    // inject svg icon into html
    .pipe($.inject(svgs, { transform: fileContents }))
    // Output Files: to .tmp folder
    .pipe(gulp.dest('.tmp'))
    .pipe($.size({title: 'html'}));
});

gulp.task('inject-html', ['html'], function () {
  return gulp.src('.tmp/**/*.html')
    // inject css into html inline style
    .pipe($.inject(gulp.src(['dist/styles/*.css', 'dist/scripts/*.min.js']), {
      starttag: '<!-- inject:head:{{ext}} -->',
      transform: function (filePath, file) {
        // return file contents as string
        var _ext, tags;
        _ext= filePath.split('.').reverse()[0];

        tags = ('js' === _ext ? 'script' : 'style');

        return '<' + tags + '>' + file.contents.toString('utf8') + '</' + tags + '>';
      }
    }))
    // Minify Any HTML
    .pipe($.if('*.html', $.minifyHtml({quotes: true})))
    // Output Files: to dist folder
    .pipe(gulp.dest('dist'))
    .pipe($.size({title: 'inject-html'}));
});

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

// Watch Files For Changes & Reload
gulp.task('serve', ['default'], function () {
  browserSync({
    notify: false,
    // 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: ['.tmp', 'app']
  });

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

// Build and serve the output from the dist build
gulp.task('serve:dist', ['default'], function () {
  browserSync({
    notify: false,
    // 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'
  });
});

// deploy dist folder to github branch gh-pages
gulp.task('deploy', function () {
  return gulp.src('./dist/**/*')
    .pipe($.ghPages());
});

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

// Run PageSpeed Insights
// Update `url` below to the public URL for your site
gulp.task('pagespeed', pagespeed.bind(null, {
  // By default, we use the PageSpeed Insights
  // free (no API key) tier. You can use a Google
  // Developer API key if you have one. See
  // http://goo.gl/RkN0vE for info key: 'YOUR_API_KEY'
  url: 'http://rplus.github.io/resume/',
  strategy: 'mobile'
}));

// Load custom tasks from the `tasks` directory
try { require('require-dir')('tasks'); } catch (err) {}
<commit_msg>調整擷取來源為 .tmp 檔案<commit_after>/**
 *
 *  Web Starter Kit
 *  Copyright 2014 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';

// 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 pagespeed = require('psi');
var reload = browserSync.reload;

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

// Lint JavaScript
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')));
});

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

// Copy All Files At The Root Level (app)
gulp.task('copy', function () {
  return gulp.src([
    'app/*',
    '!app/*.html',
    'node_modules/apache-server-configs/dist/.htaccess'
  ], {
    dot: true
  }).pipe(gulp.dest('.tmp'))
    .pipe(gulp.dest('dist'))
    .pipe($.size({title: 'copy'}));
});

// Compile and Automatically Prefix Stylesheets
gulp.task('styles', function () {
  // For best performance, don't add Sass partials to `gulp.src`
  return gulp.src([
      'app/styles/*.styl',
      'app/styles/**/*.css'
    ])
    .pipe($.changed('styles', {extension: '.styl'}))
    .pipe($.stylus({
      linenos: true
    })
      .on('error', console.error.bind(console))
    )
    .pipe($.autoprefixer(AUTOPREFIXER_BROWSERS))
    // Concatenate And Minify Styles
    .pipe($.if('*.css', $.csso()))
    .pipe(gulp.dest('.tmp/styles'))
    .pipe(gulp.dest('dist/styles'))
    .pipe($.size({title: 'styles'}));
});

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

  var svgs = gulp.src(['app/images/inject-svg/*.svg'])
                 .pipe($.cache($.imagemin()))
                 .pipe($.svgstore({ prefix: 'inject-icon-', inlineSvg: true, transformSvg: transformSvg }));

  function fileContents (filePath, file) {
    return file.contents.toString('utf8');
  }

  function transformSvg ($svg, done) {
    $svg.attr('style', 'display:none');
    done(null, $svg);
  }

  return gulp.src('app/**/*.html')
    .pipe(assets)
    // Concatenate And Minify JavaScript
    .pipe($.if('*.js', $.uglify({preserveComments: 'some'})))
    // Remove Any Unused CSS
    // Note: If not using the Style Guide, you can delete it from
    // the next line to only include styles your project uses.
    .pipe($.if('*.css', $.uncss({
      html: [
        'app/index.html'
      ],
      // CSS Selectors for UnCSS to ignore
      ignore: [
        /.navdrawer-container.open/,
        /.app-bar.open/
      ]
    })))
    // Concatenate And Minify Styles
    // In case you are still using useref build blocks
    .pipe($.if('*.css', $.csso()))
    .pipe(assets.restore())
    .pipe($.useref())
    // inject svg icon into html
    .pipe($.inject(svgs, { transform: fileContents }))
    // Output Files: to .tmp folder
    .pipe(gulp.dest('.tmp'))
    .pipe($.size({title: 'html'}));
});

gulp.task('inject-html', ['html'], function () {
  return gulp.src('.tmp/**/*.html')
    // inject css into html inline style
    .pipe($.inject(gulp.src(['.tmp/styles/*.css', '.tmp/scripts/*.min.js']), {
      starttag: '<!-- inject:head:{{ext}} -->',
      transform: function (filePath, file) {
        // return file contents as string
        var _ext, tags;
        _ext= filePath.split('.').reverse()[0];

        tags = ('js' === _ext ? 'script' : 'style');

        return '<' + tags + '>' + file.contents.toString('utf8') + '</' + tags + '>';
      }
    }))
    // Minify Any HTML
    .pipe($.if('*.html', $.minifyHtml({quotes: true})))
    // Output Files: to dist folder
    .pipe(gulp.dest('dist'))
    .pipe($.size({title: 'inject-html'}));
});

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

// Watch Files For Changes & Reload
gulp.task('serve', ['default'], function () {
  browserSync({
    notify: false,
    // 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: ['.tmp', 'app']
  });

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

// Build and serve the output from the dist build
gulp.task('serve:dist', ['default'], function () {
  browserSync({
    notify: false,
    // 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'
  });
});

// deploy dist folder to github branch gh-pages
gulp.task('deploy', function () {
  return gulp.src('./dist/**/*')
    .pipe($.ghPages());
});

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

// Run PageSpeed Insights
// Update `url` below to the public URL for your site
gulp.task('pagespeed', pagespeed.bind(null, {
  // By default, we use the PageSpeed Insights
  // free (no API key) tier. You can use a Google
  // Developer API key if you have one. See
  // http://goo.gl/RkN0vE for info key: 'YOUR_API_KEY'
  url: 'http://rplus.github.io/resume/',
  strategy: 'mobile'
}));

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


<commit_before>var less = require('gulp-less');
var path = require('path');
var gulp = require('gulp');
var sourcemaps = require('gulp-sourcemaps');
var livereload = require('gulp-livereload');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');

gulp.task('less', function() {
    gulp.src('./mwach/static/less/main.less')
        .pipe(sourcemaps.init())
        .pipe(less())
        .pipe(sourcemaps.write('./maps'))
        .pipe(gulp.dest('./mwach/static/css'))
        .pipe(livereload());
});

// From: https://medium.com/@dickeyxxx/best-practices-for-building-angular-js-apps-266c1a4a6917
gulp.task('js',function () {
  gulp.src(['./mwach/static/app/mwachx.module.js','mwach/static/app/**/*.js'])
    .pipe(sourcemaps.init())
      .pipe(concat('mwachx.js'))
      // .pipe(uglify())
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest('./mwach/static'))
});

gulp.task('libs',function(){
  gulp.src([
    'mwach/static/bower_components/angular/angular.js',
    'mwach/static/bower_components/angular-ui-router/release/angular-ui-router.js',
    'mwach/static/bower_components/angular-resource/angular-resource.js',
    'mwach/static/bower_components/angular-bootstrap/ui-bootstrap-tpls.js',
    'mwach/static/bower_components/angular-bootstrap-show-errors/src/showErrors.js'
  ])
   .pipe(sourcemaps.init())
    .pipe(concat('components.js'))
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest('./mwach/static'))
});

gulp.task('watch', function() {
	livereload.listen();
    gulp.watch('**/*.less', ['less']);
    /* Trigger a live reload on any Django template changes */
    gulp.watch('**/templates/**/*.html').on('change', livereload.changed);
    gulp.watch('**views.py').on('change', livereload.changed);
    gulp.watch('**admin.py').on('change', livereload.changed);
    gulp.watch('**/*.js').on('change', livereload.changed);
    gulp.watch('**/*.html').on('change', livereload.changed);
});

gulp.task('default', ['less', 'watch'], function() {
	return
});
<commit_msg>feat(gulp) watch and compile js, add restangular to libs<commit_after>var less = require('gulp-less');
var path = require('path');
var gulp = require('gulp');
var sourcemaps = require('gulp-sourcemaps');
var livereload = require('gulp-livereload');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');

gulp.task('less', function() {
    gulp.src('./mwach/static/less/main.less')
        .pipe(sourcemaps.init())
        .pipe(less())
        .pipe(sourcemaps.write('./maps'))
        .pipe(gulp.dest('./mwach/static/css'))
        .pipe(livereload());
});

// From: https://medium.com/@dickeyxxx/best-practices-for-building-angular-js-apps-266c1a4a6917
gulp.task('js',function () {
  gulp.src(['./mwach/static/app/mwachx.module.js','mwach/static/app/**/*.js'])
    .pipe(sourcemaps.init())
      .pipe(concat('mwachx.js'))
      // .pipe(uglify())
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest('./mwach/static'))
});

gulp.task('libs',function(){
  gulp.src([
    'mwach/static/bower_components/angular/angular.js',
    'mwach/static/bower_components/angular-ui-router/release/angular-ui-router.js',
    'mwach/static/bower_components/angular-resource/angular-resource.js',
    'mwach/static/bower_components/angular-bootstrap/ui-bootstrap-tpls.js',
    'mwach/static/bower_components/angular-bootstrap-show-errors/src/showErrors.js',
    'mwach/static/bower_components/lodash/lodash.js',
    'mwach/static/bower_components/restangular/src/restangular.js'
  ])
   .pipe(sourcemaps.init())
    .pipe(concat('components.js'))
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest('./mwach/static'))
});

gulp.task('watch', function() {
	livereload.listen();
    // Recompile less -> css
    gulp.watch('**/*.less', ['less']);
    // Recompile js
    gulp.watch('mwach/static/app/**/*.js',['js']);
    /* Trigger a live reload on any Django template changes */
    gulp.watch('**/templates/**/*.html').on('change', livereload.changed);
    gulp.watch('**views.py').on('change', livereload.changed);
    gulp.watch('**admin.py').on('change', livereload.changed);
    gulp.watch('**/*.js').on('change', livereload.changed);
    gulp.watch('**/*.html').on('change', livereload.changed);
});

gulp.task('default', ['watch'], function() {
	return
});
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp');
var gulpIstanbul = require('gulp-istanbul');
var gulpMocha = require('gulp-mocha');

gulp.task('test', function(cb) {
  gulp.src(['lib/**/**/**/*.js', 'server.js'])
    .pipe(gulpIstanbul())
    .pipe(gulpIstanbul.hookRequire())
    .on('finish', function() {
      gulp.src(['test/**/*.js'])
        .pipe(gulpMocha())
        .pipe(gulpIstanbul.writeReports())
        .on('end', cb);
    });
});
<commit_msg>fixing gulpfile.js<commit_after>'use strict';

var gulp = require('gulp');
var gulpIstanbul = require('gulp-istanbul');
var gulpMocha = require('gulp-mocha');

gulp.task('test', function(cb) {
  gulp.src(['lib/**/*.js', 'index.js'])
    .pipe(gulpIstanbul())
    .pipe(gulpIstanbul.hookRequire())
    .on('finish', function() {
      gulp.src(['test/**/*.js'])
        .pipe(gulpMocha())
        .pipe(gulpIstanbul.writeReports())
        .on('end', cb);
    });
});
<|endoftext|>


<commit_before>var gulp = require('gulp');
var plumber = require('gulp-plumber');
var clean = require('gulp-clean');
var rename = require('gulp-rename');
var flatten = require('gulp-flatten');
var tap = require('gulp-tap');
var header = require('gulp-header');
var jshint = require('gulp-jshint');
var stylish = require('jshint-stylish');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var sass = require('gulp-ruby-sass');
var prefix = require('gulp-autoprefixer');
var minify = require('gulp-minify-css');
var karma = require('gulp-karma');
var package = require('./package.json');

var paths = {
	output : 'dist/',
	scripts : {
		input : [ 'src/js/*' ],
		output : 'dist/js/'
	},
	styles : {
		input : 'src/sass/**/*.scss',
		output : 'dist/css/'
	},
	static : 'src/static/**',
	test : {
		spec : [ 'test/spec/**/*.js' ],
		coverage: 'test/coverage/',
		results: 'test/results/'
	}
};

var banner = {
	full :
		'/**\n' +
		' * <%= package.name %> v<%= package.version %>\n' +
		' * <%= package.description %>, by <%= package.author.name %>.\n' +
		' * <%= package.repository.url %>\n' +
		' * \n' +
		' * Free to use under the MIT License.\n' +
		' * http://gomakethings.com/mit/\n' +
		' */\n\n',
	min :
		'/**' +
		' <%= package.name %> v<%= package.version %>, by Chris Ferdinandi' +
		' | <%= package.repository.url %>' +
		' | Licensed under MIT: http://gomakethings.com/mit/' +
		' */\n'
};

gulp.task('scripts', ['clean'], function() {
	return gulp.src(paths.scripts.input)
		.pipe(plumber())
		.pipe(flatten())

		.pipe(tap(function (file, t) {
			if ( file.stat.isDirectory() ) {
				var name = file.relative + '.js';
				return gulp.src(file.path + '/*.js')
					.pipe(concat(name))
					.pipe(header(banner.full, { package : package }))
					.pipe(gulp.dest(paths.scripts.output))
					.pipe(rename({ suffix: '.min' }))
					.pipe(uglify())
					.pipe(header(banner.min, { package : package }))
					.pipe(gulp.dest(paths.scripts.output));
			}
		}))

		// Don't add headers to classList.js
		.pipe(tap(function (file,t) {
			if ( file.relative === 'classList.js' ) {
				return gulp.src( file.path )
					.pipe(gulp.dest(paths.scripts.output))
					.pipe(rename({ suffix: '.min' }))
					.pipe(uglify())
					.pipe(gulp.dest(paths.scripts.output));
			}
		}))

		.pipe(header(banner.full, { package : package }))
		.pipe(gulp.dest(paths.scripts.output))
		.pipe(rename({ suffix: '.min' }))
		.pipe(uglify())
		.pipe(header(banner.min, { package : package }))
		.pipe(gulp.dest(paths.scripts.output));
});

gulp.task('styles', ['clean'], function() {
	return gulp.src(paths.styles.input)
		.pipe(plumber())
		.pipe(sass({style: 'expanded', noCache: true}))
		.pipe(flatten())
		.pipe(prefix('last 2 version', '> 1%'))
		.pipe(header(banner.full, { package : package }))
		.pipe(gulp.dest(paths.styles.output))
		.pipe(rename({ suffix: '.min' }))
		.pipe(minify())
		.pipe(header(banner.min, { package : package }))
		.pipe(gulp.dest(paths.styles.output));
});

gulp.task('static', ['clean'], function() {
	return gulp.src(paths.static)
		.pipe(plumber())
		.pipe(gulp.dest(paths.output));
});

gulp.task('lint', function () {
	return gulp.src(paths.scripts.input)
		.pipe(plumber())
		.pipe(jshint())
		.pipe(jshint.reporter('jshint-stylish'));
});

gulp.task('clean', function () {
	return gulp.src([
				paths.output,
				paths.test.coverage,
				paths.test.results
		], { read: false })
		.pipe(plumber())
		.pipe(clean());
});

gulp.task('test', function() {
	return gulp.src([paths.scripts.input + '/../**/*.js'].concat(paths.test.spec))
		.pipe(plumber())
		.pipe(karma({ configFile: 'test/karma.conf.js' }))
		.on('error', function(err) { throw err; });
});

gulp.task('default', [
	'lint',
	'clean',
	'scripts',
	'styles',
	'static',
	'test'
]);<commit_msg>Updated gulpfile.js<commit_after>// Gulp Packages
var gulp = require('gulp');
var plumber = require('gulp-plumber');
var clean = require('gulp-clean');
var rename = require('gulp-rename');
var flatten = require('gulp-flatten');
var tap = require('gulp-tap');
var header = require('gulp-header');
var jshint = require('gulp-jshint');
var stylish = require('jshint-stylish');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var sass = require('gulp-ruby-sass');
var prefix = require('gulp-autoprefixer');
var minify = require('gulp-minify-css');
var karma = require('gulp-karma');
var package = require('./package.json');

// Paths to project folders
var paths = {
	output : 'dist/',
	temp: 'src/temp/',
	scripts : {
		input : [ 'src/js/*' ],
		output : 'dist/js/'
	},
	styles : {
		input : 'src/sass/**/*.scss',
		output : 'dist/css/'
	},
	static : 'src/static/**',
	test : {
		spec : [ 'test/spec/**/*.js' ],
		coverage: 'test/coverage/',
		results: 'test/results/'
	}
};

// Template for banner to add to file headers
var banner = {
	full :
		'/**\n' +
		' * <%= package.name %> v<%= package.version %>\n' +
		' * <%= package.description %>, by <%= package.author.name %>.\n' +
		' * <%= package.repository.url %>\n' +
		' * \n' +
		' * Free to use under the MIT License.\n' +
		' * http://gomakethings.com/mit/\n' +
		' */\n\n',
	min :
		'/**' +
		' <%= package.name %> v<%= package.version %>, by Chris Ferdinandi' +
		' | <%= package.repository.url %>' +
		' | Licensed under MIT: http://gomakethings.com/mit/' +
		' */\n'
};

// Concatenate scripts in subfolders
gulp.task('concatenate', function() {
	return gulp.src(paths.scripts.input)
		.pipe(plumber())
		.pipe(flatten())

		.pipe(tap(function (file, t) {
			if ( file.stat.isDirectory() ) {
				var name = file.relative + '.js';
				return gulp.src(file.path + '/*.js')
					.pipe(concat(name))
					.pipe(gulp.dest(paths.temp));
			}
		}));
});

// Lint and minify scripts
gulp.task('scripts', ['clean', 'concatenate'], function() {
	return gulp.src([
			paths.scripts.input + '/../*.js',
			paths.temp + '/*.js'
		])
		.pipe(plumber())
		.pipe(flatten())
		.pipe(header(banner.full, { package : package }))
		.pipe(gulp.dest(paths.scripts.output))
		.pipe(rename({ suffix: '.min' }))
		.pipe(uglify())
		.pipe(header(banner.min, { package : package }))
		.pipe(gulp.dest(paths.scripts.output));
});

// Process, lint, and minify Sass files
gulp.task('styles', ['clean'], function() {
	return gulp.src(paths.styles.input)
		.pipe(plumber())
		.pipe(sass({style: 'expanded', noCache: true}))
		.pipe(flatten())
		.pipe(prefix('last 2 version', '> 1%'))
		.pipe(header(banner.full, { package : package }))
		.pipe(gulp.dest(paths.styles.output))
		.pipe(rename({ suffix: '.min' }))
		.pipe(minify())
		.pipe(header(banner.min, { package : package }))
		.pipe(gulp.dest(paths.styles.output));
});

// Copy static files into output folder
gulp.task('static', ['clean'], function() {
	return gulp.src(paths.static)
		.pipe(plumber())
		.pipe(gulp.dest(paths.output));
});

// Lint scripts
gulp.task('lint', function () {
	return gulp.src(paths.scripts.input)
		.pipe(plumber())
		.pipe(jshint())
		.pipe(jshint.reporter('jshint-stylish'));
});

// Remove prexisting content from output and test folders
gulp.task('clean', function () {
	return gulp.src([
			paths.output,
			paths.test.coverage,
			paths.test.results
		], { read: false })
		.pipe(plumber())
		.pipe(clean());
});

// Remove temporary files
gulp.task('cleanTemp', ['scripts'], function () {
	return gulp.src(paths.temp, { read: false })
		.pipe(plumber())
		.pipe(clean());
});

// Run unit tests
gulp.task('test', function() {
	return gulp.src([paths.scripts.input + '/../**/*.js'].concat(paths.test.spec))
		.pipe(plumber())
		.pipe(karma({ configFile: 'test/karma.conf.js' }))
		.on('error', function(err) { throw err; });
});

// Combine tasks into runner
gulp.task('default', [
	'lint',
	'clean',
	'static',
	'concatenate',
	'scripts',
	'styles',
	'cleanTemp',
	'test'
]);<|endoftext|>


<commit_before>require('gulp-coffee/node_modules/coffee-script/register');
require('./gulp.coffee');
<commit_msg>Correct package path<commit_after>require('coffee-script/register');
require('./gulp.coffee');
<|endoftext|>


<commit_before>var gulp = require('gulp');
var rename = require("gulp-rename");
var webpack = require('gulp-webpack');

gulp.task('default', function() {
  return gulp.src('myComponents.js')
    .pipe(webpack({
    watch: true,
    module: {
      loaders: [
        {
          test: /\.js$/,
          exclude: /node_modules/,
          loader: 'babel-loader?stage=0&optional[]=runtime&loose=true'
        },
        {
          test: /bootstrap/,
          loader: 'babel-loader?stage=0&optional[]=runtime&loose=true&nonStandard=true'
        }
      ],
    },
  }))
  .pipe(rename('myComponents.js'))
  .pipe(gulp.dest('dist/'));
});
<commit_msg>fix gulpfile error<commit_after>var gulp = require('gulp');
var rename = require("gulp-rename");
var webpack = require('gulp-webpack');

gulp.task('default', function() {
  return gulp.src('myComponents.js')
    .pipe(webpack({
    watch: true,
    module: {
      loaders: [
        {
          test: /\.js$/,
          exclude: /node_modules/,
          loader: 'babel-loader?stage=0&optional[]=runtime&loose=true&nonStandard=true'
        }
      ],
    },
  }))
  .pipe(rename('myComponents.js'))
  .pipe(gulp.dest('dist/'));
});
<|endoftext|>


<commit_before>var inject = require('gulp-inject'),
	gulp = require('gulp'),
    path = require('path');

gulp.task('build', function () {
	views();
});
gulp.task('views', views);
function views() {
        gulp.src(path.normalize('./frontend/src/*.js'))
        .pipe(gulp.dest(path.normalize('./build/static')));
		gulp.src(path.normalize('./app/index.html'))
	    .pipe(inject(
            gulp.src([path.normalize('./frontend/src/*.js')], {read: false}), {
                transform : function ( filePath, file, i, length ) {
                     var newPath = filePath.replace('/frontend/src', '');
                     console.log('inject script = '+ newPath);
                     return '<script src="/static' + newPath  + '"></script>';
                }
            }
        ))
        .pipe(gulp.dest('./build'));
}
<commit_msg>normalize the replace pattern<commit_after>var inject = require('gulp-inject'),
	gulp = require('gulp'),
    path = require('path');

gulp.task('build', function () {
	views();
});
gulp.task('views', views);
function views() {
        gulp.src(path.normalize('./frontend/src/*.js'))
        .pipe(gulp.dest(path.normalize('./build/static')));
		gulp.src(path.normalize('./app/index.html'))
	    .pipe(inject(
            gulp.src([path.normalize('./frontend/src/*.js')], {read: false}), {
                transform : function ( filePath, file, i, length ) {
                     var newPath = filePath.replace(path.normalize('/frontend/src'), '');
                     console.log('inject script = '+ newPath);
                     return '<script src="/static' + newPath  + '"></script>';
                }
            }
        ))
        .pipe(gulp.dest('./build'));
}
<|endoftext|>


<commit_before>var gulp = require('gulp'),
    autoprefixer = require('gulp-autoprefixer'),
    uglify = require('gulp-uglify'),
    rename = require('gulp-rename'),
    notify = require('gulp-notify');

gulp.task('default', function () {
    return gulp.src('cronapi.js')
        .pipe(uglify())
        .pipe(rename('cronapi.min.js'))
        .pipe(gulp.dest('dist/'));
        //.pipe(notify({ message: 'CronApi-JS build finished' }));
});
gulp.task('i18n', function() {
  return gulp.src('i18n/')
    .pipe(gulp.dest('i18n/'))
    .pipe(notify({ message: 'CronApi-JS build finished' }));
});<commit_msg>teste bower<commit_after>var gulp = require('gulp'),
    autoprefixer = require('gulp-autoprefixer'),
    uglify = require('gulp-uglify'),
    rename = require('gulp-rename'),
    notify = require('gulp-notify');
//gulp.task('default', gulp.series('minify', 'i18n'))

gulp.task('default', function () {
    return gulp.src('cronapi.js')
        .pipe(uglify())
        .pipe(rename('cronapi.min.js'))
        .pipe(gulp.dest('dist/'));
        //.pipe(notify({ message: 'CronApi-JS build finished' }));
});
/*gulp.task('i18n', function() {
  return gulp.src('i18n/')
    .pipe(gulp.dest('i18n/'))
    .pipe(notify({ message: 'CronApi-JS build finished' }));
});*/<|endoftext|>


<commit_before>var _ = require('lodash'),
    path = require('path'),
    gulp = require('gulp'),
    gutil = require('gulp-util'),
    args = require('yargs').argv,
    runSequence = require('run-sequence'),
    jshint = require('gulp-jshint'),
    jscs = require('gulp-jscs'),
    jsonlint = require('gulp-json-lint'),
    jshintReporter = require('reporter-plus/jshint'),
    jscsReporter = require('reporter-plus/jscs'),
    jsonlintReporter = require('reporter-plus/jsonlint'),
    gulpMetadata = require('./tools/gulp-metadata.js')(gulp);

/*--- Check Tasks ---*/
gulp.task('check-tools', function() {
  return gulp.src(path.join('tools', '*.js'))
    .pipe(jshint(_.merge(
        {lookup: false},
        require('./runcoms/rc.jshint.json')
      )))
    .pipe(jshint.reporter(jshintReporter))
    .pipe(jscs({
        configPath: path.join(__dirname, '.', 'runcoms', 'rc.jscs.json')
      }))
    .pipe(jscs.reporter(jscsReporter.path));
});
gulpMetadata.addTask('check-tools', {
  description: 'Run all tool files through JSHint and JSCS',
  category: 'checker'
});

gulp.task('check-runcoms', function() {
  return gulp.src(path.join('runcoms', '*.json'))
    .pipe(jsonlint())
    .pipe(jsonlint.report(jsonlintReporter));
});
gulpMetadata.addTask('check-runcoms', {
  description: 'Run all runcom files through JSONLint',
  category: 'checker'
});

/*--- Default Task --*/
gulp.task('default', function(done) {
  runSequence(
    'check-tools',
    'check-runcoms',
    done
  );
});
gulpMetadata.addTask('default', {
  description: 'Run the most important tasks for developing this project',
  category: 'main',
  weight: 0
});

/*--- Versioning Task ---*/
gulp.task('version', function() {
  var versionBump = require('./tools/version-bump.js');

  return gulp.src(path.join('.', 'package.json'), {base: '.'})
    .pipe(versionBump(args.bump))
    .pipe(gulp.dest('.'));
});
gulpMetadata.addTask('version', {
  description: 'Bump this project\'s semantic version number.',
  category: 'misc',
  arguments: {
      'bump': '[Optional] Specifies which part of the version number (major, minor, patch) should be bumped.'
    }
});

/*--- Help task ---*/
gulp.task('help', function() {
  gutil.log(gulpMetadata.describeAll());
});
gulpMetadata.addTask('help', {
  description: 'List all available Gulp tasks and arguments.',
  category: 'misc',
  weight: 999
});
<commit_msg>Update own gulpfile to use new metadata interface<commit_after>var _ = require('lodash'),
    path = require('path'),
    gulp = require('gulp'),
    gutil = require('gulp-util'),
    args = require('yargs').argv,
    runSequence = require('run-sequence'),
    jshint = require('gulp-jshint'),
    jscs = require('gulp-jscs'),
    jsonlint = require('gulp-json-lint'),
    jshintReporter = require('reporter-plus/jshint'),
    jscsReporter = require('reporter-plus/jscs'),
    jsonlintReporter = require('reporter-plus/jsonlint'),
    gulpMetadata = require('./tools/gulp-metadata.js').applyTo(gulp);

/*--- Check Tasks ---*/
gulp.task('check-tools', function() {
  return gulp.src(path.join('tools', '**', '*.js'))
    .pipe(jshint(_.merge(
        {lookup: false},
        require('./runcoms/rc.jshint.json')
      )))
    .pipe(jshint.reporter(jshintReporter))
    .pipe(jscs({
        configPath: path.join(__dirname, '.', 'runcoms', 'rc.jscs.json')
      }))
    .pipe(jscs.reporter(jscsReporter.path));
}, {
  description: 'Run all tool files through JSHint and JSCS',
  category: 'checker'
});

gulp.task('check-runcoms', function() {
  return gulp.src(path.join('runcoms', '*.json'))
    .pipe(jsonlint())
    .pipe(jsonlint.report(jsonlintReporter));
}, {
  description: 'Run all runcom files through JSONLint',
  category: 'checker'
});

/*--- Default Task --*/
gulp.task('default', function(done) {
  runSequence(
    'check-tools',
    'check-runcoms',
    done
  );
}, {
  description: 'Run the most important tasks for developing this project',
  category: 'main',
  weight: 0
});

/*--- Versioning Task ---*/
gulp.task('version', function() {
  var versionBump = require('./tools/misc/version-bump.js');

  return gulp.src(path.join('.', 'package.json'), {base: '.'})
    .pipe(versionBump(args.bump))
    .pipe(gulp.dest('.'));
}, {
  description: 'Bump this project\'s semantic version number.',
  category: 'misc',
  arguments: {
      'bump': '[Optional] Specifies which part of the version number (major, minor, patch) should be bumped.'
    }
});

/*--- Help task ---*/
gulp.task('help', function() {
  gutil.log(gulpMetadata.describeAll());
}, {
  description: 'List all available Gulp tasks and arguments.',
  category: 'misc',
  weight: 999
});
<|endoftext|>


<commit_before>module.exports = function(sequelize, DataTypes) {
  const Job = sequelize.define(
    "Job",
    {
      title: DataTypes.TEXT,
      description: DataTypes.TEXT,
      company_name: DataTypes.TEXT,
      company_url: DataTypes.TEXT,
      company_info: DataTypes.TEXT,
      business_type: DataTypes.TEXT,
      company_logo_url: DataTypes.TEXT,
      start_date: DataTypes.DATE,
      end_date: DataTypes.DATE,
      sector: DataTypes.TEXT,
      location: DataTypes.JSONB,
      meta: DataTypes.JSONB,
      geo: DataTypes.GEOGRAPHY,
      picture: DataTypes.JSONB
    },
    {
      tableName: "job",
      underscored: true,
      indexes: [
        {
          using: "gist",
          fields: ["geo"]
        },
        {
          fields: ["sector"]
        }
      ]
    }
  );
  Job.associate = function(models) {
    Job.belongsTo(models.User, {
      foreignKey: {
        name: "user_id",
        allowNull: false
      }
    });
    models.User.hasMany(models.Job, {
      foreignKey: {
        name: "user_id",
        allowNull: true
      }
    });
  };
  return Job;
};
<commit_msg>add views in Jobs<commit_after>module.exports = function(sequelize, DataTypes) {
  const Job = sequelize.define(
    "Job",
    {
      title: DataTypes.TEXT,
      description: DataTypes.TEXT,
      company_name: DataTypes.TEXT,
      company_url: DataTypes.TEXT,
      company_info: DataTypes.TEXT,
      business_type: DataTypes.TEXT,
      company_logo_url: DataTypes.TEXT,
      start_date: DataTypes.DATE,
      end_date: DataTypes.DATE,
      sector: DataTypes.TEXT,
      location: DataTypes.JSONB,
      meta: DataTypes.JSONB,
      geo: DataTypes.GEOGRAPHY,
      picture: {
        type: DataTypes.JSONB,
        defaultValue: {}
      },
      views: {
        type: DataTypes.INTEGER,
        defaultValue: 0
      },
    },
    {
      tableName: "job",
      underscored: true,
      indexes: [
        {
          using: "gist",
          fields: ["geo"]
        },
        {
          fields: ["sector"]
        }
      ]
    }
  );
  Job.associate = function(models) {
    Job.belongsTo(models.User, {
      foreignKey: {
        name: "user_id",
        allowNull: false
      }
    });
    models.User.hasMany(models.Job, {
      foreignKey: {
        name: "user_id",
        allowNull: true
      }
    });
  };
  return Job;
};
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp');
var watch = require('gulp-watch');
var harp = require('harp');
var browserSync = require('browser-sync');
var ghPages = require('gulp-gh-pages');

var harpServerOptions = {
  port: 9000
};

var browserSynceOptions = {
  open: false,
  proxy: 'localhost:' + harpServerOptions.port,
  notify: false,
  port: 3000
};

var harpConfig = {
  prod: {
    siteUrl: "http://tech.joshegan.com",
    siteEnvironment: "PRODUCTION"
  },
  dev: {
    siteUrl: "http://localhost:" + browserSynceOptions.port,
    siteEnvironment: "DEV"
  }
};

var paths = {
  projectDir: './',
  outputDir: './dist',
  outputFiles: './dist/**/*',
  srcFiles: './public/**/*'
};

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

gulp.task('deploy', ['build-for-prod'], function () {
  return gulp.src(paths.outputFiles)
    .pipe(ghPages());
});

gulp.task('build-for-prod', function (done) {
  applyHarpConfig(harpConfig.prod);
  harp.compile(paths.projectDir, paths.outputDir, done);
});

gulp.task('watch', ['dev-server'], function () {
  browserSync(browserSynceOptions);

  gulp.src(paths.srcFiles)
    .pipe(watch(paths.srcFiles, {verbose: true}))
    .pipe(browserSync.reload({stream: true}));
});

gulp.task('dev-server', function (done) {
  applyHarpConfig(harpConfig.dev);
  harp.server(__dirname, harpServerOptions, done);
});

function applyHarpConfig(config){
  process.env.SITE_URL = config.siteUrl;
  process.env.SITE_ENVIRONMENT = config.siteEnvironment;
}
<commit_msg>Fix typo in variable name<commit_after>'use strict';

var gulp = require('gulp');
var watch = require('gulp-watch');
var harp = require('harp');
var browserSync = require('browser-sync');
var ghPages = require('gulp-gh-pages');

var harpServerOptions = {
  port: 9000
};

var browserSyncOptions = {
  open: false,
  proxy: 'localhost:' + harpServerOptions.port,
  notify: false,
  port: 3000
};

var harpConfig = {
  prod: {
    siteUrl: "http://tech.joshegan.com",
    siteEnvironment: "PRODUCTION"
  },
  dev: {
    siteUrl: "http://localhost:" + browserSyncOptions.port,
    siteEnvironment: "DEV"
  }
};

var paths = {
  projectDir: './',
  outputDir: './dist',
  outputFiles: './dist/**/*',
  srcFiles: './public/**/*'
};

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

gulp.task('deploy', ['build-for-prod'], function () {
  return gulp.src(paths.outputFiles)
    .pipe(ghPages());
});

gulp.task('build-for-prod', function (done) {
  applyHarpConfig(harpConfig.prod);
  harp.compile(paths.projectDir, paths.outputDir, done);
});

gulp.task('watch', ['dev-server'], function () {
  browserSync(browserSyncOptions);

  gulp.src(paths.srcFiles)
    .pipe(watch(paths.srcFiles, {
      verbose: true
    }))
    .pipe(browserSync.reload({
      stream: true
    }));
});

gulp.task('dev-server', function (done) {
  applyHarpConfig(harpConfig.dev);
  harp.server(__dirname, harpServerOptions, done);
});

function applyHarpConfig(config) {
  process.env.SITE_URL = config.siteUrl;
  process.env.SITE_ENVIRONMENT = config.siteEnvironment;
}
<|endoftext|>