<commit_before>'use strict';

const fs = require('fs');
const util = require('util');
const gulp = require('gulp');
const del = require('del');
const install = require('gulp-install');
const zip = require('gulp-zip');
const runSequence = require('run-sequence');
const AWS = require('aws-sdk');
const s3 = new AWS.S3();
const cloudFormation = new AWS.CloudFormation();
const lambda = new AWS.Lambda();

let config;
try {
	config = require('./config.json');
} catch (ex) {
	config = {};
}

const stackName = 'cognito-identity-pool';

gulp.task('clean', () => del([
	'./build/*',
	'./dist/*',
	'./dist.zip'
]));

gulp.task('js', () => gulp
	.src([
		'index.js'
	])
	.pipe(gulp.dest('./dist'))
);

gulp.task('npm', () => gulp
	.src('./package.json')
	.pipe(gulp.dest('./dist'))
	.pipe(install({production: true}))
);

gulp.task('zip', () => gulp
	.src([
		'dist/**/*',
		'!dist/package.json',
		'dist/.*'
	])
	.pipe(zip('dist.zip'))
	.pipe(gulp.dest('./'))
);

gulp.task('upload', cb => s3
	.upload({
		Bucket: config.LambdaS3Bucket,
		Key: config.LambdaS3Key,
		Body: fs.createReadStream('./dist.zip')
	}, cb)
);

gulp.task('listStacks', () => cloudFormation
	.listStacks({
		StackStatusFilter: [
			'CREATE_COMPLETE',
			'UPDATE_COMPLETE'
		]
	})
	.promise()
	.then(data => console.log(data))
	.catch(err => console.error(err))
);

gulp.task('deployStack', () => {
	return cloudFormation.describeStacks({
		StackName: stackName
	}, function(err) {
		var operation = err ? 'createStack' : 'updateStack';

		return cloudFormation[operation]({
			StackName: stackName,
			Capabilities: [
				'CAPABILITY_IAM'
			],
			Parameters: Object
				.keys(config)
				.map(key => ({
					ParameterKey: key,
					ParameterValue: typeof config[key] === 'string' ? config[key] : JSON.stringify(config[key])
				})),
			TemplateBody: fs.readFileSync('./cloudformation.json', {encoding: 'utf8'})
		})
			.promise()
			.then(console.log)
			.catch(console.error);
	});
});

gulp.task('updateConfig', () => cloudFormation
	.waitFor(
		'stackCreateComplete',
		{
			StackName: stackName
		}
	)
	.promise()
	.then(data => {
		console.log(util.inspect(data, {depth:5}));

		let configParams = {
			'AccessKey': 'accessKeyId',
			'AccessSecret': 'secretAccessKey'
		};

		data.Stacks[0].Outputs.forEach(item => {
			config[configParams[item.OutputKey]] = item.OutputValue;
		});

		fs.writeFileSync(
			'./config.json',
			JSON.stringify(config, null, '\t'),
			'utf8'
		);
	})
);

// Once the stack is deployed, this will update the function if the code is changed without recreating the stack
gulp.task('updateCode', () => cloudFormation
	.describeStackResource({
		StackName: stackName,
		LogicalResourceId: 'Lambda'
	})
	.promise()
	.then(data => lambda
		.updateFunctionCode({
			FunctionName: data.StackResourceDetail.PhysicalResourceId,
			S3Bucket: config.LambdaS3Bucket,
			S3Key: config.LambdaS3Key
		})
		.promise()
	)
);

gulp.task('build', cb => {
	return runSequence(
		'clean',
		['js', 'npm'],
		'zip',
		cb
	);
});

// Builds the function and uploads
gulp.task('build-upload', cb => {
	return runSequence(
		'build',
		'upload',
		cb
	);
});

// For an already created stack
gulp.task('update', cb => {
	return runSequence(
		'updateConfig',
		'build-upload',
		'updateCode',
		cb
	);
});

// For a new stack (or you change cloudformation.json)
gulp.task('default', cb => {
	return runSequence(
		'build-upload',
		'deployStack',
		cb
	);
});<commit_msg>Change S3 upload to S3 putObject with promise<commit_after>'use strict';

const fs = require('fs');
const util = require('util');
const gulp = require('gulp');
const del = require('del');
const install = require('gulp-install');
const zip = require('gulp-zip');
const runSequence = require('run-sequence');
const AWS = require('aws-sdk');
const s3 = new AWS.S3();
const cloudFormation = new AWS.CloudFormation();
const lambda = new AWS.Lambda();

let config;
try {
	config = require('./config.json');
} catch (ex) {
	config = {};
}

const stackName = 'cognito-identity-pool';

gulp.task('clean', () => del([
	'./build/*',
	'./dist/*',
	'./dist.zip'
]));

gulp.task('js', () => gulp
	.src([
		'index.js'
	])
	.pipe(gulp.dest('./dist'))
);

gulp.task('npm', () => gulp
	.src('./package.json')
	.pipe(gulp.dest('./dist'))
	.pipe(install({production: true}))
);

gulp.task('zip', () => gulp
	.src([
		'dist/**/*',
		'!dist/package.json',
		'dist/.*'
	])
	.pipe(zip('dist.zip'))
	.pipe(gulp.dest('./'))
);

gulp.task('upload', s3
	.putObject({
		Bucket: config.LambdaS3Bucket,
		Key: config.LambdaS3Key,
		Body: fs.createReadStream('./dist.zip')
	})
	.promise()
);

gulp.task('listStacks', () => cloudFormation
	.listStacks({
		StackStatusFilter: [
			'CREATE_COMPLETE',
			'UPDATE_COMPLETE'
		]
	})
	.promise()
	.then(data => console.log(data))
	.catch(err => console.error(err))
);

gulp.task('deployStack', () => {
	return cloudFormation.describeStacks({
		StackName: stackName
	}, function(err) {
		var operation = err ? 'createStack' : 'updateStack';

		return cloudFormation[operation]({
			StackName: stackName,
			Capabilities: [
				'CAPABILITY_IAM'
			],
			Parameters: Object
				.keys(config)
				.map(key => ({
					ParameterKey: key,
					ParameterValue: typeof config[key] === 'string' ? config[key] : JSON.stringify(config[key])
				})),
			TemplateBody: fs.readFileSync('./cloudformation.json', {encoding: 'utf8'})
		})
			.promise()
			.then(console.log)
			.catch(console.error);
	});
});

gulp.task('updateConfig', () => cloudFormation
	.waitFor(
		'stackCreateComplete',
		{
			StackName: stackName
		}
	)
	.promise()
	.then(data => {
		console.log(util.inspect(data, {depth:5}));

		let configParams = {
			'AccessKey': 'accessKeyId',
			'AccessSecret': 'secretAccessKey'
		};

		data.Stacks[0].Outputs.forEach(item => {
			config[configParams[item.OutputKey]] = item.OutputValue;
		});

		fs.writeFileSync(
			'./config.json',
			JSON.stringify(config, null, '\t'),
			'utf8'
		);
	})
);

// Once the stack is deployed, this will update the function if the code is changed without recreating the stack
gulp.task('updateCode', () => cloudFormation
	.describeStackResource({
		StackName: stackName,
		LogicalResourceId: 'Lambda'
	})
	.promise()
	.then(data => lambda
		.updateFunctionCode({
			FunctionName: data.StackResourceDetail.PhysicalResourceId,
			S3Bucket: config.LambdaS3Bucket,
			S3Key: config.LambdaS3Key
		})
		.promise()
	)
);

gulp.task('build', cb => {
	return runSequence(
		'clean',
		['js', 'npm'],
		'zip',
		cb
	);
});

// Builds the function and uploads
gulp.task('build-upload', cb => {
	return runSequence(
		'build',
		'upload',
		cb
	);
});

// For an already created stack
gulp.task('update', cb => {
	return runSequence(
		'updateConfig',
		'build-upload',
		'updateCode',
		cb
	);
});

// For a new stack (or you change cloudformation.json)
gulp.task('default', cb => {
	return runSequence(
		'build-upload',
		'deployStack',
		cb
	);
});<|endoftext|>


<commit_before>module.exports = function(grunt) {

    // Project configuration.
    grunt.initConfig({

        pkg: grunt.file.readJSON('package.json'),

        copy: {
            main: {
                files: [

                // Util
                {
                    src: 'src/util/typeof.js',
                    dest: '../browser/src/util/typeof.js',
                },{
                    src: 'src/util/promise.js',
                    dest: '../browser/src/util/promise.js',
                },{
                    src: 'src/util/path.js',
                    dest: '../browser/src/util/path.js',
                },{
                    src: 'src/util/merge.js',
                    dest: '../browser/src/util/merge.js',
                },{
                    src: 'src/util/arguments.js',
                    dest: '../browser/src/util/arguments.js',
                },{
                    src: 'src/util/getsetdelete.js',
                    dest: '../browser/src/util/getsetdelete.js',
                }

                // Core
                ,{
                    src: 'src/core/parse.js',
                    dest: '../browser/src/core/parse.js',
                },{
                    src: 'src/core/stringify.js',
                    dest: '../browser/src/core/stringify.js',
                },{
                    src: 'src/core/protocol.js',
                    dest: '../browser/src/core/protocol.js',
                },{
                    src: 'src/core/osp.js',
                    dest: '../browser/src/core/osp.js',
                },{
                    src: 'src/core/configure.js',
                    dest: '../browser/src/core/configure.js',
                },{
                    src: 'src/core/observe.js',
                    dest: '../browser/src/core/observe.js',
                },{
                    src: 'src/core/create_remote_function.js',
                    dest: '../browser/src/core/create_remote_function.js',
                },{
                    src: 'src/core/request.js',
                    dest: '../browser/src/core/request.js',
                },{
                    src: 'src/core/response.js',
                    dest: '../browser/src/core/response.js',
                },{
                    src: 'src/core/resolve.js',
                    dest: '../browser/src/core/resolve.js',
                },{
                    src: 'src/core/reject.js',
                    dest: '../browser/src/core/reject.js',
                }

                // OSP
                ,{
                    src: 'src/on/request.js',
                    dest: '../browser/src/on/request.js',
                },{
                    src: 'src/on/_request.js',
                    dest: '../browser/src/on/_request.js',
                }

                // API
                ,{
                    src: 'src/user/request.js',
                    dest: '../browser/src/api/request.js',
                }

                ],
            }
        },

        // symlink: {
        //     expanded: {
        //         files: [{
        //             src: 'src/core/protocol.js',
        //             dest: '../browser/src/core/protocol.js'
        //         }, {
        //             src: 'src/util/typeof.js',
        //             dest: '../browser/src/core/typeof.js'
        //         }],
        //     }
        // },

        concat: {
            options: {
                process: function(src, filepath) {
                    return '\n\n\n\n//////////  ' + filepath + '\n' + src;
                }
            },
            dist: {
                src: [
                    'src/syncio.js',
                    'src/core/*',
                    'src/api/*',
                    'src/on/*',
                    'src/user/*',
                    'src/util/*',
                    'src/connector/*'
                ],
                dest: 'lib/<%= pkg.name %>.js'
            }
        }
    });

    // grunt.loadNpmTasks('grunt-contrib-symlink');
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-contrib-concat');

    //grunt.registerTask('default', ['symlink', 'concat', 'uglify', 'jshint', 'watch']);
    grunt.registerTask('default', ['copy','concat']);

};
<commit_msg>Added watch to grunt<commit_after>module.exports = function(grunt) {

    // Project configuration.
    grunt.initConfig({

        pkg: grunt.file.readJSON('package.json'),

        copy: {
            main: {
                files: [

                // Util
                {
                    src: 'src/util/typeof.js',
                    dest: '../browser/src/util/typeof.js',
                },{
                    src: 'src/util/promise.js',
                    dest: '../browser/src/util/promise.js',
                },{
                    src: 'src/util/path.js',
                    dest: '../browser/src/util/path.js',
                },{
                    src: 'src/util/merge.js',
                    dest: '../browser/src/util/merge.js',
                },{
                    src: 'src/util/arguments.js',
                    dest: '../browser/src/util/arguments.js',
                },{
                    src: 'src/util/getsetdelete.js',
                    dest: '../browser/src/util/getsetdelete.js',
                }

                // Core
                ,{
                    src: 'src/core/parse.js',
                    dest: '../browser/src/core/parse.js',
                },{
                    src: 'src/core/stringify.js',
                    dest: '../browser/src/core/stringify.js',
                },{
                    src: 'src/core/protocol.js',
                    dest: '../browser/src/core/protocol.js',
                },{
                    src: 'src/core/osp.js',
                    dest: '../browser/src/core/osp.js',
                },{
                    src: 'src/core/configure.js',
                    dest: '../browser/src/core/configure.js',
                },{
                    src: 'src/core/observe.js',
                    dest: '../browser/src/core/observe.js',
                },{
                    src: 'src/core/create_remote_function.js',
                    dest: '../browser/src/core/create_remote_function.js',
                },{
                    src: 'src/core/request.js',
                    dest: '../browser/src/core/request.js',
                },{
                    src: 'src/core/response.js',
                    dest: '../browser/src/core/response.js',
                },{
                    src: 'src/core/resolve.js',
                    dest: '../browser/src/core/resolve.js',
                },{
                    src: 'src/core/reject.js',
                    dest: '../browser/src/core/reject.js',
                }

                // OSP
                ,{
                    src: 'src/on/request.js',
                    dest: '../browser/src/on/request.js',
                },{
                    src: 'src/on/_request.js',
                    dest: '../browser/src/on/_request.js',
                }

                // API
                ,{
                    src: 'src/user/request.js',
                    dest: '../browser/src/api/request.js',
                }

                ],
            }
        },

        // symlink: {
        //     expanded: {
        //         files: [{
        //             src: 'src/core/protocol.js',
        //             dest: '../browser/src/core/protocol.js'
        //         }, {
        //             src: 'src/util/typeof.js',
        //             dest: '../browser/src/core/typeof.js'
        //         }],
        //     }
        // },

        concat: {
            options: {
                process: function(src, filepath) {
                    return '\n\n\n\n//////////  ' + filepath + '\n' + src;
                }
            },
            dist: {
                src: [
                    'src/syncio.js',
                    'src/core/*',
                    'src/api/*',
                    'src/on/*',
                    'src/user/*',
                    'src/util/*',
                    'src/connector/*'
                ],
                dest: 'lib/<%= pkg.name %>.js'
            }
        },

        watch: {
            scripts: {
                files: ['src/*','src/*/*'],
                tasks: ['default'],
                options: {
                    spawn: false,
                },
            },
        },

    });

    // grunt.loadNpmTasks('grunt-contrib-symlink');
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.loadNpmTasks('grunt-contrib-watch');

    //grunt.registerTask('default', ['symlink', 'concat', 'uglify', 'jshint', 'watch']);
    grunt.registerTask('default', ['copy','concat','watch']);

};
<|endoftext|>


<commit_before>module.exports = function(grunt) {

  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.loadNpmTasks('grunt-contrib-coffee');
  grunt.loadNpmTasks('grunt-contrib-compass');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-concat');

  grunt.loadNpmTasks('grunt-coffeelint');
  grunt.loadNpmTasks('grunt-html2js');
  grunt.loadNpmTasks('grunt-karma');

  var config = require('./misc/build-config.js')(grunt);

  grunt.initConfig({

    clean: {
      build: config.buildDirectory,
      release: config.releaseDirectory
    },

    // Build the foundation + custom files using compass
    compass: {
      main: {
        options: {
          config: config.compassConfigFile,
          cssDir: config.cssDirectory,
          sassDir: config.sassDirectory,
          force: true,
          environment: 'production'
        }
      }
    },

    // Compiles coffeescript
    coffee: {
      dev: {
        expand: true,
        src: config.sourceFileFilter,
        dest: config.buildDirectory,
        ext: '.js'
      },
      release: {
        src: config.sourceFileFilter,
        dest: config.releaseAppMinPath
      }
    },

    // Lint coffeescript, with the 80l length rule ignored
    coffeelint: {
      options: {
        'max_line_length': {
          'level': 'ignore'
        }
      },
      src: {
        files: {
          src: config.sourceFileFilter
        }
      },
      tests: {
        files: {
          src: config.testFileFilter
        }
      }
    },

    // Creates the index page (ie, add js and css links)
    index: {
      dev: {
        dir: config.buildDirectory,
        src: config.indexTask.dev
      },
      release: {
        dir: config.releaseDirectory,
        src: config.indexTask.release
      }
    },

    // Copy libs js/css and our assets over to the build directory
    // TODO: check if i can improve that part
    copy: {
      libs_js: {
        files: [
          {
            src: config.libs.js,
            dest: config.buildDirectory,
            expand: true
          }
        ]
      },

      libs_css: {
        files: [
          {
            src: config.libs.css,
            dest: config.buildDirectory,
            expand: true
          }
        ]
      },
      // Using src=** and cwd so it doesn't include the src/ folder when copying
      assets: {
        files: [
          {
            src: ['**'],
            dest: config.buildDirectory,
            cwd: config.assetsDirectory,
            expand: true
          }
        ]
      },

      releaseAssets: {
        files: [
          {
            src: ['**'],
            dest: config.releaseDirectory,
            cwd: config.assetsDirectory,
            expand: true
          }
        ]
      },

      releaseCss: {
        files: [
          {
            src: config.cssFilter,
            dest: config.releaseDirectory + 'style/',
            flatten: true,
            expand: true
          }
        ]
      }
    },

    html2js: {
      all: {
        options: {
          module: 'templates'
        },
        src: config.templateFileFilter,
        dest: config.convertedTemplatesPath
      }
    },

    // Testing config
    karma: {
      options: {
        port: 9876,
        runnerPort: 9100,
        autoWatch: false,
        urlRoot: '/',
        browsers: ['Firefox'],
        reporters: 'dots',
        files: config.karmaFiles,
        preprocessors: {
          '**/*.coffee': 'coffee'
        },
        plugins: [
          'karma-mocha',
          'karma-firefox-launcher',
          'karma-coffee-preprocessor',
          'karma-phantomjs-launcher'
        ],
        frameworks: ['mocha']
      },
      dev: {
        background: true,
        singleRun: false
      },
      complete: {
        singleRun: true,
        background: false,
        browsers: ['PhantomJS', 'Firefox']
      }
    },

    uglify: {
      release: {
        options: {
          banner: config.banner
        },
        files: {
          'release/scripts/app.js': config.ownJsToMinifyFilter,
        }
      }
    },

    concat: {
      releaseLibs: {
        src: config.libs.jsMin,
        dest: config.releaseLibsMinPath
      }
    },

    // what to do when a file changes
    watch: {
      coffeeSrc: {
        files: config.sourceFileFilter,
        tasks: ['coffeelint:src', 'coffee', 'karma:dev:run']
      },

      coffeeTests: {
        files: config.testFileFilter,
        tasks: ['coffeelint:tests', 'karma:dev:run']
      },

      sass: {
        files: config.sassFileFilter,
        tasks: ['compass:main']
      },

      templates: {
        files: config.templateFileFilter,
        tasks: ['html2js']
      },

      index: {
        files: config.indexFileFilter,
        tasks: ['index:dev']
      }
    }

  });

  // Filter files according to the given regex
  function filterFor(files, regex) {
    return files.filter(function (file) {
      return file.match(regex);
    });
  }

  /**
   * The index.html template includes the stylesheet and javascript sources
   * based on dynamic names calculated in this Gruntfile. This task assembles
   * the list into variables for the template to use and then runs the
   * compilation.
   */
  grunt.registerMultiTask('index', 'Process index.html template', function () {
    // This regex will remove the 'root' path when inserting in the template
    var dirRE = new RegExp('^(build|release)\/', 'g');
    var jsFiles = filterFor(this.filesSrc, /\.js$/).map(function (file) {
      return file.replace(dirRE, '');
    });
    var cssFiles = filterFor(this.filesSrc, /\.css$/).map(function (file) {
      return file.replace(dirRE, '');
    });

    grunt.file.copy(config.indexFileFilter, this.data.dir + '/index.html', {
      process: function (contents, path) {
        return grunt.template.process(contents, {
          data: {
            scripts: jsFiles,
            styles: cssFiles
          }
        });
      }
    });
  });

  // Builds the app without running the test, used in other tasks
  grunt.registerTask(
    'build',
    [
      'html2js',
      'compass',
      'coffeelint:src',
      'coffee:dev',
      'copy',
      'index:dev'
    ]
  );

  // Task to run whil developing, will watch over changes and run tests/compile sass/etc
  grunt.registerTask(
    'dev',
    [
      'karma:dev', // starts the karma server and browser
      'build',
      'watch'
    ]
  );

  // Alias to run the full test suite
  grunt.registerTask('test', ['karma:complete']);

  // This will create a release folder, containing the app ready to be deployed
  grunt.registerTask(
    'release',
    [
      'build',
      'uglify',
      'concat',
      'copy:releaseAssets',
      'copy:releaseCss',
      'index:release',
      'clean:build'
    ]
  );

};<commit_msg>docs(build): Add some comment on tasks<commit_after>module.exports = function(grunt) {

  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.loadNpmTasks('grunt-contrib-coffee');
  grunt.loadNpmTasks('grunt-contrib-compass');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-concat');

  grunt.loadNpmTasks('grunt-coffeelint');
  grunt.loadNpmTasks('grunt-html2js');
  grunt.loadNpmTasks('grunt-karma');

  var config = require('./misc/build-config.js')(grunt);

  grunt.initConfig({

    clean: {
      build: config.buildDirectory,
      release: config.releaseDirectory
    },

    // Build the foundation + custom files using compass
    compass: {
      main: {
        options: {
          config: config.compassConfigFile,
          cssDir: config.cssDirectory,
          sassDir: config.sassDirectory,
          force: true,
          environment: 'production'
        }
      }
    },

    // Compiles coffeescript
    coffee: {
      dev: {
        expand: true, // keeping the hierarchy while developing
        src: config.sourceFileFilter,
        dest: config.buildDirectory
      },
      release: {
        src: config.sourceFileFilter,
        dest: config.releaseAppMinPath
      }
    },

    // Lint coffeescript files, with the 80l length rule ignored
    coffeelint: {
      options: {
        'max_line_length': {
          'level': 'ignore'
        }
      },
      src: {
        files: {
          src: config.sourceFileFilter
        }
      },
      tests: {
        files: {
          src: config.testFileFilter
        }
      }
    },

    // Creates the index page (ie, add js and css links in the template)
    index: {
      dev: {
        dir: config.buildDirectory,
        src: config.indexTask.dev
      },
      release: {
        dir: config.releaseDirectory,
        src: config.indexTask.release
      }
    },

    // Copy libs js/css and our assets over to the build directory
    copy: {
      libs_js: {
        files: [
          {
            src: config.libs.js,
            dest: config.buildDirectory,
            expand: true
          }
        ]
      },

      libs_css: {
        files: [
          {
            src: config.libs.css,
            dest: config.buildDirectory,
            expand: true
          }
        ]
      },
      // Using src=** and cwd so it doesn't include the src/ folder when copying
      assets: {
        files: [
          {
            src: ['**'],
            dest: config.buildDirectory,
            cwd: config.assetsDirectory,
            expand: true
          }
        ]
      },

      releaseAssets: {
        files: [
          {
            src: ['**'],
            dest: config.releaseDirectory,
            cwd: config.assetsDirectory,
            expand: true
          }
        ]
      },

      releaseCss: {
        files: [
          {
            src: config.cssFilter,
            dest: config.releaseDirectory + 'style/',
            flatten: true,
            expand: true
          }
        ]
      }
    },

    // This will concatenate all the .html files in the src folder and
    // create a js file to be used in an angular app
    html2js: {
      all: {
        options: {
          module: 'templates'
        },
        src: config.templateFileFilter,
        dest: config.convertedTemplatesPath
      }
    },

    // Testing config
    karma: {
      options: {
        port: 9876,
        runnerPort: 9100,
        autoWatch: false,
        urlRoot: '/',
        browsers: ['Firefox'],
        reporters: 'dots',
        files: config.karmaFiles,
        preprocessors: {
          '**/*.coffee': 'coffee'
        },
        plugins: [
          'karma-mocha',
          'karma-firefox-launcher',
          'karma-coffee-preprocessor',
          'karma-phantomjs-launcher'
        ],
        frameworks: ['mocha']
      },
      dev: {
        background: true,
        singleRun: false
      },
      complete: {
        singleRun: true,
        background: false,
        browsers: ['PhantomJS', 'Firefox']
      }
    },

    // uglify our app (not vendors js) and adds a banner to it
    uglify: {
      release: {
        options: {
          banner: config.banner
        },
        files: {
          'release/scripts/app.js': config.ownJsToMinifyFilter,
        }
      }
    },

    // We only want 1 file for the libs so concatenate all of the minified one
    concat: {
      releaseLibs: {
        src: config.libs.jsMin,
        dest: config.releaseLibsMinPath
      }
    },

    // what to do when a file changes
    watch: {
      coffeeSrc: {
        files: config.sourceFileFilter,
        tasks: ['coffeelint:src', 'coffee', 'karma:dev:run']
      },

      coffeeTests: {
        files: config.testFileFilter,
        tasks: ['coffeelint:tests', 'karma:dev:run']
      },

      sass: {
        files: config.sassFileFilter,
        tasks: ['compass:main']
      },

      templates: {
        files: config.templateFileFilter,
        tasks: ['html2js']
      },

      index: {
        files: config.indexFileFilter,
        tasks: ['index:dev']
      }
    }

  });

  // Filter files according to the given regex
  function filterFor(files, regex) {
    return files.filter(function (file) {
      return file.match(regex);
    });
  }

  /**
   * The index.html template includes the stylesheet and javascript sources
   * based on dynamic names calculated in this Gruntfile. This task assembles
   * the list into variables for the template to use and then runs the
   * compilation.
   */
  grunt.registerMultiTask('index', 'Process index.html template', function () {
    // This regex will remove the 'root' path when inserting in the template
    var dirRE = new RegExp('^(build|release)\/', 'g');
    var jsFiles = filterFor(this.filesSrc, /\.js$/).map(function (file) {
      return file.replace(dirRE, '');
    });
    var cssFiles = filterFor(this.filesSrc, /\.css$/).map(function (file) {
      return file.replace(dirRE, '');
    });

    grunt.file.copy(config.indexFileFilter, this.data.dir + '/index.html', {
      process: function (contents, path) {
        return grunt.template.process(contents, {
          data: {
            scripts: jsFiles,
            styles: cssFiles
          }
        });
      }
    });
  });

  // Builds the app without running the test, used in other tasks
  grunt.registerTask(
    'build',
    [
      'html2js',
      'compass',
      'coffeelint:src',
      'coffee:dev',
      'copy',
      'index:dev'
    ]
  );

  // Task to run whil developing, will watch over changes and run tests, compile sass/etc
  grunt.registerTask(
    'dev',
    [
      'karma:dev', // starts the karma server and browser
      'build',
      'watch'
    ]
  );

  // Alias to run the full test suite
  grunt.registerTask('test', ['karma:complete']);

  // This will create a release folder, containing the app ready to be deployed
  grunt.registerTask(
    'release',
    [
      'build',
      'uglify',
      'concat',
      'copy:releaseAssets',
      'copy:releaseCss',
      'index:release',
      'clean:build'
    ]
  );

};<|endoftext|>


<commit_before>'use strict';
//Импортируем необходимые плагины в проект
var gulp = require('gulp'),
	bower = require('gulp-bower'),
    watch = require('gulp-watch'),
    prefixer = require('gulp-autoprefixer'),
    uglify = require('gulp-uglify'),
    sass = require('gulp-sass'),
    sourcemaps = require('gulp-sourcemaps'),
    rigger = require('gulp-rigger'),
    cssmin = require('gulp-clean-css'),
    imagemin = require('gulp-imagemin'),
    pngquant = require('imagemin-pngquant'),
    rimraf = require('rimraf'),
    browserSync = require("browser-sync"),
	filter = require('gulp-filter'),
    reload = browserSync.reload;

//Прописываем объект содержащий все необходимые пути
var path = {
    build: { //Тут мы укажем куда складывать готовые после сборки файлы
        html: 'web/',
        js: 'web/js/',
        css: 'web/css/',
        img: 'web/images/',
        fonts: 'web/fonts/',
		libs: 'web/libs/'
    },
    src: { //Пути откуда брать исходники
        html: 'src/*.html', //Синтаксис src/*.html говорит gulp что мы хотим взять все файлы с расширением .html
        js: 'src/js/common.js',//В скриптах нам понадобятся только common файл
        style: 'src/sass/style.scss', //В стилях берем два файла style и media
		media: 'src/sass/media.scss',
        img: 'src/images/**/*.*', //Синтаксис images/**/*.* означает - взять все файлы всех расширений из папки и из вложенных каталогов
        fonts: 'src/fonts/**/*.*',
		libs: './bower_components/'
    },
    watch: { //Тут мы укажем, за изменением каких файлов мы хотим наблюдать
        html: 'src/**/*.html',
        js: 'src/js/**/*.js',
        style: 'src/sass/**/*.scss',
        img: 'src/images/**/*.*',
        fonts: 'src/fonts/**/*.*'
    },
    clean: './web'
};

//Переменная с настройками dev сервера
var config = {
    server: {
        baseDir: "./web"
    },
    tunnel: false,
    host: 'localhost',
    port: 9000,
    logPrefix: "lucas"
};

//Таск для сборки .html
gulp.task('html:build', function () {
    gulp.src(path.src.html) //Выберем файлы по нужному пути
        .pipe(rigger()) //Прогоним через rigger
        .pipe(gulp.dest(path.build.html)) //Выплюнем их в папку build
        .pipe(reload({stream: true})); //И перезагрузим наш сервер для обновлений
});

//Таск для сборки common.js
gulp.task('js:build', function () {
    gulp.src(path.src.js) //Найдем наш common файл
        .pipe(rigger()) //Прогоним через rigger
//        .pipe(sourcemaps.init()) //Инициализируем sourcemap
//        .pipe(uglify().on('error', function(e){
//				console.log(e); //При возникновении ошибки покажет где проблема
//			  })) //Сожмем наш js
//        .pipe(sourcemaps.write()) //Пропишем карты
        .pipe(gulp.dest(path.build.js)) //Выплюнем готовый файл в build
        .pipe(reload({stream: true})); //И перезагрузим сервер
});

//Таск для сборки .scss файлов
gulp.task('style:build', function () {
	//Кусок для файла style
    gulp.src(path.src.style) //Выберем наш style.scss
//        .pipe(sourcemaps.init()) //То же самое что и с js
        .pipe(sass({
			outputStyle: 'expanded'
		})) //Скомпилируем
        .pipe(prefixer()) //Добавим вендорные префиксы
//        .pipe(cssmin()) //Сожмем
//        .pipe(sourcemaps.write())
        .pipe(gulp.dest(path.build.css)) //И в build
        .pipe(reload({stream: true}));

	//Кусок для файла media
	gulp.src(path.src.media) //Выберем наш media.scss
//        .pipe(sourcemaps.init()) //То же самое что и с js
        .pipe(sass({
			outputStyle: 'expanded'
		})) //Скомпилируем
        .pipe(prefixer()) //Добавим вендорные префиксы
//        .pipe(cssmin()) //Сожмем
//        .pipe(sourcemaps.write())
        .pipe(gulp.dest(path.build.css)) //И в build
        .pipe(reload({stream: true}));
});

//Таск для переваривания картинок
gulp.task('image:build', function () {
    gulp.src(path.src.img) //Выберем наши картинки
        // .pipe(imagemin({ //Сожмем их
        //     progressive: true,
        //     svgoPlugins: [
        //         {removeViewBox: false}
        //     ],
		// 	use: [pngquant()]
        // }))
        .pipe(gulp.dest(path.build.img)) //И бросим в build
        .pipe(reload({stream: true}));
});

//Таск десантирования шрифтов
gulp.task('fonts:build', function() {
    gulp.src(path.src.fonts)
        .pipe(gulp.dest(path.build.fonts))
});

//Таск на просмотр изменения файлов
gulp.task('watch', function(){
    watch([path.watch.html], function(event, cb) { //Посмотрели html
        gulp.start('html:build'); //Выплюнули в билд
    });
    watch([path.watch.style], function(event, cb) { //Посмотрели стили
        gulp.start('style:build'); //Выплюнули в билд
    });
    watch([path.watch.js], function(event, cb) { //Посмотрели скрипты
        gulp.start('js:build'); //Выплюнули в билд
    });
    watch([path.watch.img], function(event, cb) { //Посмотрели картинки
        gulp.start('image:build'); //Выплюнули в билд
    });
    watch([path.watch.fonts], function(event, cb) { //Посмотрели шрифты
        gulp.start('fonts:build'); //Выплюнули в билд
    });
});

//Таск запуска локального сервера с livereload
gulp.task('webserver', function () {
    browserSync(config);
});

//Таск очистки
gulp.task('clean', function (cb) {
    rimraf(path.clean, cb);
});

//Таск сборки сторонних библиотек через bower
gulp.task('bower', function() {
  return bower();
});

//Фильтруем библиотеки и вынимаем только нужные файлы
gulp.task('filter', function() {
	//Настраиваем фильтры для файлов
	const jsFilter = filter(['*.js', '!src/vendor'], {restore: true, passthrough: false});
	const cssFilter = filter(['*.css', '!src/vendor'], {restore: true, passthrough: false});

	//Для нормальных плагинов отработает этот кусок кода
	const stream = gulp.src([
			'bower_components/**/*.min.*',
			'bower_components/**/fonts/*',
			'bower_components/**/*.css',
			'!bower_components/**/*.map'
		])
		// Фильтруем содержимое на наличие js и css
		.pipe(jsFilter)
		.pipe(cssFilter)
		// run them through a plugin
		.pipe(gulp.dest('dist'));

	// Вываливаем в билд
	jsFilter.restore.pipe(gulp.dest('web/libs/'));

	return stream;
});

//Таск "Сделать хорошо"
gulp.task('build', [
    'html:build',
    'js:build',
    'style:build',
    'fonts:build',
    'image:build'
]);

//Дефолтный таск старта
gulp.task('default', ['bower', 'build', 'webserver', 'watch']);
<commit_msg>small fix<commit_after>'use strict';
//Импортируем необходимые плагины в проект
var gulp = require('gulp'),
    bower = require('gulp-bower'),
    watch = require('gulp-watch'),
    prefixer = require('gulp-autoprefixer'),
    uglify = require('gulp-uglify'),
    sass = require('gulp-sass'),
    sourcemaps = require('gulp-sourcemaps'),
    rigger = require('gulp-rigger'),
    cssmin = require('gulp-clean-css'),
    imagemin = require('gulp-imagemin'),
    pngquant = require('imagemin-pngquant'),
    rimraf = require('rimraf'),
    browserSync = require("browser-sync"),
    filter = require('gulp-filter'),
    reload = browserSync.reload;

//Прописываем объект содержащий все необходимые пути
var path = {
    build: { //Тут мы укажем куда складывать готовые после сборки файлы
        html: 'web/',
        js: 'web/js/',
        css: 'web/css/',
        img: 'web/images/',
        fonts: 'web/fonts/',
        libs: 'web/libs/'
    },

    src: { //Пути откуда брать исходники
        html: 'src/*.html', //Синтаксис src/*.html говорит gulp что мы хотим взять все файлы с расширением .html
        js: 'src/js/common.js',//В скриптах нам понадобятся только common файл
        style: 'src/sass/style.scss', //В стилях берем два файла style и media
        media: 'src/sass/media.scss',
        img: 'src/images/**/*.*', //Синтаксис images/**/*.* означает - взять все файлы всех расширений из папки и из вложенных каталогов
        fonts: 'src/fonts/**/*.*',
        libs: './bower_components/'
    },

    watch: { //Тут мы укажем, за изменением каких файлов мы хотим наблюдать
        html: 'src/**/*.html',
        js: 'src/js/**/*.js',
        style: 'src/sass/**/*.scss',
        img: 'src/images/**/*.*',
        fonts: 'src/fonts/**/*.*'
    },
    clean: './web'
};

//Переменная с настройками dev сервера
var config = {
    server: {
        baseDir: "./web"
    },
    tunnel: false,
    host: 'localhost',
    port: 9000,
    logPrefix: "lucas"
};

//Таск для сборки .html
gulp.task('html:build', function () {
    gulp.src(path.src.html) //Выберем файлы по нужному пути
        .pipe(rigger()) //Прогоним через rigger
        .pipe(gulp.dest(path.build.html)) //Выплюнем их в папку build
        .pipe(reload({stream: true})); //И перезагрузим наш сервер для обновлений
});

//Таск для сборки common.js
gulp.task('js:build', function () {
    gulp.src(path.src.js) //Найдем наш common файл
        .pipe(rigger()) //Прогоним через rigger
//        .pipe(sourcemaps.init()) //Инициализируем sourcemap
//        .pipe(uglify().on('error', function(e){
//				console.log(e); //При возникновении ошибки покажет где проблема
//			  })) //Сожмем наш js
//        .pipe(sourcemaps.write()) //Пропишем карты
        .pipe(gulp.dest(path.build.js)) //Выплюнем готовый файл в build
        .pipe(reload({stream: true})); //И перезагрузим сервер
});

//Таск для сборки .scss файлов
gulp.task('style:build', function () {
	//Кусок для файла style
    gulp.src(path.src.style) //Выберем наш style.scss
//        .pipe(sourcemaps.init()) //То же самое что и с js
        .pipe(sass({
			outputStyle: 'expanded'
		})) //Скомпилируем
        .pipe(prefixer()) //Добавим вендорные префиксы
//        .pipe(cssmin()) //Сожмем
//        .pipe(sourcemaps.write())
        .pipe(gulp.dest(path.build.css)) //И в build
        .pipe(reload({stream: true}));

	//Кусок для файла media
	gulp.src(path.src.media) //Выберем наш media.scss
//        .pipe(sourcemaps.init()) //То же самое что и с js
        .pipe(sass({
			outputStyle: 'expanded'
		})) //Скомпилируем
        .pipe(prefixer()) //Добавим вендорные префиксы
//        .pipe(cssmin()) //Сожмем
//        .pipe(sourcemaps.write())
        .pipe(gulp.dest(path.build.css)) //И в build
        .pipe(reload({stream: true}));
});

//Таск для переваривания картинок
gulp.task('image:build', function () {
    gulp.src(path.src.img) //Выберем наши картинки
        // .pipe(imagemin({ //Сожмем их
        //     progressive: true,
        //     svgoPlugins: [
        //         {removeViewBox: false}
        //     ],
		// 	use: [pngquant()]
        // }))
        .pipe(gulp.dest(path.build.img)) //И бросим в build
        .pipe(reload({stream: true}));
});

//Таск десантирования шрифтов
gulp.task('fonts:build', function() {
    gulp.src(path.src.fonts)
        .pipe(gulp.dest(path.build.fonts))
});

//Таск на просмотр изменения файлов
gulp.task('watch', function(){
    watch([path.watch.html], function(event, cb) { //Посмотрели html
        gulp.start('html:build'); //Выплюнули в билд
    });
    watch([path.watch.style], function(event, cb) { //Посмотрели стили
        gulp.start('style:build'); //Выплюнули в билд
    });
    watch([path.watch.js], function(event, cb) { //Посмотрели скрипты
        gulp.start('js:build'); //Выплюнули в билд
    });
    watch([path.watch.img], function(event, cb) { //Посмотрели картинки
        gulp.start('image:build'); //Выплюнули в билд
    });
    watch([path.watch.fonts], function(event, cb) { //Посмотрели шрифты
        gulp.start('fonts:build'); //Выплюнули в билд
    });
});

//Таск запуска локального сервера с livereload
gulp.task('webserver', function () {
    browserSync(config);
});

//Таск очистки
gulp.task('clean', function (cb) {
    rimraf(path.clean, cb);
});

//Таск сборки сторонних библиотек через bower
gulp.task('bower', function() {
  return bower();
});

//Фильтруем библиотеки и вынимаем только нужные файлы
gulp.task('filter', function() {
	//Настраиваем фильтры для файлов
	const jsFilter = filter(['*.js', '!src/vendor'], {restore: true, passthrough: false});
	const cssFilter = filter(['*.css', '!src/vendor'], {restore: true, passthrough: false});

	//Для нормальных плагинов отработает этот кусок кода
	const stream = gulp.src([
			'bower_components/**/*.min.*',
			'bower_components/**/fonts/*',
			'bower_components/**/*.css',
			'!bower_components/**/*.map'
		])
		// Фильтруем содержимое на наличие js и css
		.pipe(jsFilter)
		.pipe(cssFilter)
		// run them through a plugin
		.pipe(gulp.dest('dist'));

	// Вываливаем в билд
	jsFilter.restore.pipe(gulp.dest('web/libs/'));

	return stream;
});

//Таск "Сделать хорошо"
gulp.task('build', [
    'html:build',
    'js:build',
    'style:build',
    'fonts:build',
    'image:build'
]);

//Дефолтный таск старта
gulp.task('default', ['bower', 'build', 'webserver', 'watch']);
<|endoftext|>


<commit_before>module.exports = function(grunt) {

  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-less');
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-cssmin');
  grunt.loadNpmTasks('grunt-usemin');
  grunt.loadNpmTasks('grunt-rev');
  grunt.loadNpmTasks('grunt-manifest');
  grunt.loadNpmTasks('grunt-sed');
  grunt.loadNpmTasks('grunt-docco');
  grunt.loadNpmTasks('grunt-growl');

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),

    watch: {
      less: {
        options: {
          debounceDelay: 250
        },
        files: 'src/less/*.less',
        tasks: ['growl:less', 'less']
      },
      manifest: {
        options: {
          debounceDelay: 250
        },
        files: ['src/index.html', 'src/css/**', 'src/js/**', 'src/img/**'],
        tasks: ['growl:manifest', 'manifest:src']
      }
    },

    growl: {
      less: {
        message : "Recompilation LESS",
        title : "Grunt watcher"
      },
      manifest: {
        message : "Mise à jour de manifest.appcache",
        title : "Grunt watcher"
      }
    },

    less: {
      src: {
        files: {
          "src/css/styles.css": "src/less/styles.less"
        }
      }
    },

    clean: {
      dist: {
        src: 'dist/'
      }
    },

    copy: {
      dist: {
        files: [
          { expand: true, cwd: 'src/', src: ['.htaccess', 'esviji-icon.png', 'favicon.ico', 'index.html', 'manifest.webapp'], dest: 'dist/' },
          { expand: true, cwd: 'src/', src: ['css/font/*'], dest: 'dist/' },
          { expand: true, cwd: 'src/', src: ['img/favicon.png', 'img/firefox-os/*', 'img/ios/*', 'img/windows-8/*'], dest: 'dist/' }
        ]
      }
    },

    useminPrepare: {
      options: {
        dest: 'dist/'
      },
      html: 'src/index.html'
    },
    usemin: {
      html: 'dist/index.html'
    },

    concat: {
      options: {
        separator: ';'
      }
    },

    uglify: {
      options: {
        banner: '/*! <%= pkg.name %> - v<%= pkg.version %> - ' + '<%= grunt.template.today("yyyy-mm-dd") %> */'
      }
    },

    cssmin: {
      options: {
        banner: '/*! <%= pkg.name %> - v<%= pkg.version %> - ' + '<%= grunt.template.today("yyyy-mm-dd") %> */'
      }
    },

    rev: {
      options: {
        algorithm: 'md5',
        length: 8
      },
      assets: {
        files: [{
          src: [
            'dist/img/**/*.{jpg,jpeg,gif,png}',
            'dist/css/**/*.{css}',
            'dist/js/**/*.{js}'
          ]
        }]
      }
    },

    manifest: {
      src: {
        options: {
          basePath: 'src/',
          network: ['*'],
          verbose: true,
          timestamp: true
        },
        src: [
          'favicon.ico',
          'img/favicon.png',
          'js/**/*.js',
          'css/styles.css',
          'css/font/*'
        ],
        dest: 'src/manifest.appcache'
      },
      dist: {
        options: {
          basePath: 'dist/',
          network: ['*'],
          verbose: true,
          timestamp: true
        },
        src: [
          'favicon.ico',
          'img/favicon.png',
          'js/app.js',
          'css/styles.css',
          'css/font/*'
        ],
        dest: 'dist/manifest.appcache'
      }
    },

    sed: {
      version: {
        path: 'dist/',
        recursive: true,
        pattern: '%VERSION%',
        replacement: '<%= pkg.version %>'
      }
    },

    docco: {
      debug: {
        src: ['src/js/esviji.js'],
        options: {
          output: 'docs/'
        }
      }
    }
  });

  grunt.event.on('watch', function(action, filepath) {
    grunt.log.writeln(filepath + ' has ' + action);
  });

  grunt.registerTask('default', ['less', 'manifest:src', 'watch']);
  grunt.registerTask('package', ['less', 'clean', 'copy', 'useminPrepare', 'concat', 'uglify', 'cssmin', 'usemin', /*'rev',*/ 'manifest:dist', 'sed', 'docco']);
};
<commit_msg>cleaning<commit_after>module.exports = function(grunt) {

  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-less');
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-cssmin');
  grunt.loadNpmTasks('grunt-usemin');
  grunt.loadNpmTasks('grunt-rev');
  grunt.loadNpmTasks('grunt-manifest');
  grunt.loadNpmTasks('grunt-sed');
  grunt.loadNpmTasks('grunt-docco');
  grunt.loadNpmTasks('grunt-growl');

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),

    watch: {
      less: {
        options: {
          debounceDelay: 250
        },
        files: 'src/less/*.less',
        tasks: ['growl:less', 'less']
      },
      manifest: {
        options: {
          debounceDelay: 250
        },
        files: ['src/index.html', 'src/css/**', 'src/js/**', 'src/img/**'],
        tasks: ['growl:manifest', 'manifest:src']
      }
    },

    growl: {
      less: {
        message : "LESS compilation…",
        title : "Grunt watcher"
      },
      manifest: {
        message : "Updating manifest.appcache…",
        title : "Grunt watcher"
      }
    },

    less: {
      src: {
        files: {
          "src/css/styles.css": "src/less/styles.less"
        }
      }
    },

    clean: {
      dist: {
        src: 'dist/'
      }
    },

    copy: {
      dist: {
        files: [
          { expand: true, cwd: 'src/', src: ['.htaccess', 'esviji-icon.png', 'favicon.ico', 'index.html', 'manifest.webapp'], dest: 'dist/' },
          { expand: true, cwd: 'src/', src: ['css/font/*'], dest: 'dist/' },
          { expand: true, cwd: 'src/', src: ['img/favicon.png', 'img/firefox-os/*', 'img/ios/*', 'img/windows-8/*'], dest: 'dist/' }
        ]
      }
    },

    useminPrepare: {
      options: {
        dest: 'dist/'
      },
      html: 'src/index.html'
    },
    usemin: {
      html: 'dist/index.html'
    },

    concat: {
      options: {
        separator: ';'
      }
    },

    uglify: {
      options: {
        banner: '/*! <%= pkg.name %> - v<%= pkg.version %> - ' + '<%= grunt.template.today("yyyy-mm-dd") %> */'
      }
    },

    cssmin: {
      options: {
        banner: '/*! <%= pkg.name %> - v<%= pkg.version %> - ' + '<%= grunt.template.today("yyyy-mm-dd") %> */'
      }
    },

    rev: {
      options: {
        algorithm: 'md5',
        length: 8
      },
      assets: {
        files: [{
          src: [
            'dist/img/**/*.{jpg,jpeg,gif,png}',
            'dist/css/**/*.{css}',
            'dist/js/**/*.{js}'
          ]
        }]
      }
    },

    manifest: {
      src: {
        options: {
          basePath: 'src/',
          network: ['*'],
          verbose: true,
          timestamp: true
        },
        src: [
          'favicon.ico',
          'img/favicon.png',
          'js/**/*.js',
          'css/styles.css',
          'css/font/*'
        ],
        dest: 'src/manifest.appcache'
      },
      dist: {
        options: {
          basePath: 'dist/',
          network: ['*'],
          verbose: true,
          timestamp: true
        },
        src: [
          'favicon.ico',
          'img/favicon.png',
          'js/app.js',
          'css/styles.css',
          'css/font/*'
        ],
        dest: 'dist/manifest.appcache'
      }
    },

    sed: {
      version: {
        path: 'dist/',
        recursive: true,
        pattern: '%VERSION%',
        replacement: '<%= pkg.version %>'
      }
    },

    docco: {
      debug: {
        src: ['src/js/esviji.js'],
        options: {
          output: 'docs/'
        }
      }
    }
  });

  grunt.registerTask('default', ['less', 'manifest:src', 'watch']);
  grunt.registerTask('package', ['less', 'clean', 'copy', 'useminPrepare', 'concat', 'uglify', 'cssmin', 'usemin', /*'rev',*/ 'manifest:dist', 'sed', 'docco']);
};
<|endoftext|>


<commit_before>'use strict';

module.exports = function(grunt) {

  var browserifyOpts = {
      transform: [
        [
          "reactify",
          {
            harmony: true,
            stripTypes: true
          }
        ]
      ],
      browserifyOptions: {
        debug: true  // generate a source map
      }
    };

  grunt.initConfig({
    flow: {
      app: {
        src: '.',
        options: {
          background: true,
        }
      }
    },
    watch: {
      flow: {
        files: ['src/**/*.js', 'test/**/*.js'],
        tasks: ['flow:app:status']
      }
    },
    browserify: {
      dist: {
        files: {
          'build/all.js': ['src/**/*.js']
        },
        options: browserifyOpts
      },
      test: {
        files: {
          'build/tests.js': ['test/**/*-test.js']
        },
        options: browserifyOpts
      }
    },
    mocha_phantomjs: {
      all: ['test/**/*.html']
    }
  });

  grunt.loadNpmTasks('grunt-browserify');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-flow-type-check');
  grunt.loadNpmTasks('grunt-mocha-phantomjs');

  grunt.registerTask('watchFlow', ['flow:app:start', 'watch']);
  grunt.registerTask('prod', ['flow:app', 'browserify:dist']);
  grunt.registerTask('browsertests', ['flow:app', 'browserify:test']);
  grunt.registerTask('test', ['browsertests', 'mocha_phantomjs']);
};
<commit_msg>factor out browserifyOpts<commit_after>'use strict';

module.exports = function(grunt) {
  grunt.initConfig({
    flow: {
      app: {
        src: '.',
        options: {
          background: true
        }
      }
    },
    watch: {
      flow: {
        files: ['src/**/*.js', 'test/**/*.js'],
        tasks: ['flow:app:status']
      }
    },
    browserify: {
      dist: {
        files: {
          'build/all.js': ['src/**/*.js']
        },
      },
      test: {
        files: {
          'build/tests.js': ['test/**/*-test.js']
        },
      },
      options: {
        transform: [
          [
            "reactify",
            {
              harmony: true,
              stripTypes: true
            }
          ]
        ],
        browserifyOptions: {
          debug: true  // generate a source map
        }
      }
    },
    mocha_phantomjs: {
      all: ['test/**/*.html']
    }
  });

  grunt.loadNpmTasks('grunt-browserify');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-flow-type-check');
  grunt.loadNpmTasks('grunt-mocha-phantomjs');

  grunt.registerTask('watchFlow', ['flow:app:start', 'watch']);
  grunt.registerTask('prod', ['flow:app', 'browserify:dist']);
  grunt.registerTask('browsertests', ['flow:app', 'browserify:test']);
  grunt.registerTask('test', ['browsertests', 'mocha_phantomjs']);
};
<|endoftext|>


<commit_before>const twilio = require('twilio')
const textProcessor = require('./textprocessor')
const logger = require('winston')
const config = require('../config')
const commandTypes = require('./commandtypes')

const route = (request, response) => {
  const bodyText = request.query['Body'].toLowerCase()
  const fromPhoneNumber = request.query['From']
  logger.log('info', '*** Twilio From:' + fromPhoneNumber + ' Message:' + bodyText)

  // Get Cached ListName
  let cachedListName
  if (request.cookies && request.cookies.listName) {
    cachedListName = request.cookies.listName
  }

  // MAIN LOGIC
  const data = {
    originalText: bodyText,
    cachedListName,
    fromPhoneNumber,
    now: new Date((new Date()).getTime() - 1000 * 60) // 1 minute in the past
  }
  textProcessor.processTextPromise(data).then(result => {
    logger.log('info', '*** after processTextpromise', result)
    cacheListName(result, response) // TODO: Make sure this isn't the case for delete
    sendSMSResponse(result.responseText, response)
  })
}

const sendSMSResponse = (responseText, response) => {
  const twilioResponse = new twilio.TwimlResponse()
  twilioResponse.message(responseText)
  response.send(twilioResponse.toString())
}

const cacheListName = (data, response) => {
  // If there's been an error and list name is now different or if delete list command then expire the cookie
  if ((data.errorMessage && data.list !== data.cacheListName) ||
      data.command === commandTypes.deleteList
  ) {
    logger.log('info', '___twilio.route_cacheListName expire cache')
    response.cookie('listName', '', {expires: new Date(0)})
    return
  }

  // If reminder, cache the old list key
  if (data.list !== config.remindersListKey) {
    logger.log('info', '___twilio.route_cacheListName cache:', data.list)
    response.cookie('listName', data.list, {maxAge: 1000 * 60 * 60 * 72})
  }
}

module.exports = {
  route
}
<commit_msg>do not remove cache for reminders<commit_after>const twilio = require('twilio')
const textProcessor = require('./textprocessor')
const logger = require('winston')
const config = require('../config')
const commandTypes = require('./commandtypes')

const route = (request, response) => {
  const bodyText = request.query['Body'].toLowerCase()
  const fromPhoneNumber = request.query['From']
  logger.log('info', '*** Twilio From:' + fromPhoneNumber + ' Message:' + bodyText)

  // Get Cached ListName
  let cachedListName
  if (request.cookies && request.cookies.listName) {
    cachedListName = request.cookies.listName
  }

  // MAIN LOGIC
  const data = {
    originalText: bodyText,
    cachedListName,
    fromPhoneNumber,
    now: new Date((new Date()).getTime() - 1000 * 60) // 1 minute in the past
  }
  textProcessor.processTextPromise(data).then(result => {
    logger.log('info', '*** after processTextpromise', result)
    cacheListName(result, response) // TODO: Make sure this isn't the case for delete
    sendSMSResponse(result.responseText, response)
  })
}

const sendSMSResponse = (responseText, response) => {
  const twilioResponse = new twilio.TwimlResponse()
  twilioResponse.message(responseText)
  response.send(twilioResponse.toString())
}

const cacheListName = (data, response) => {
  // If there's been an error and list name is now different or if delete list command then expire the cookie
  if ((data.errorMessage && data.list !== data.cacheListName) ||
      data.command === commandTypes.deleteList
  ) {
    logger.log('info', '___twilio.route_cacheListName expire cache')
    response.cookie('listName', '', {expires: new Date(0)})
    return
  }

  logger.log('info', '___twilio.route_cacheListName cache:', data.list)
  response.cookie('listName', data.list, {maxAge: 1000 * 60 * 60 * 72})
}

module.exports = {
  route
}
<|endoftext|>


<commit_before>const gulp   = require('gulp');
const jshint = require('gulp-jshint');
const mocha = require('gulp-mocha');
const istanbul = require('gulp-istanbul');

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

gulp.task('pre-test', () => {
  return gulp.src(['./lib/**/*.js'])
    .pipe(istanbul())
    .pipe(istanbul.hookRequire());
})

gulp.task('test', ['pre-test'], () => {
  return gulp.src('./test/**/*.js')
    .pipe(mocha({reporter: 'spec' }))
    // Ugly hack because the mocha plugin doesn't properly exit with an exit code on test failures
    .on('error', (err) => { process.exit(1) })
    .pipe(istanbul.writeReports())
    .pipe(istanbul.enforceThresholds({ thresholds: { global: 90 } }));
});

gulp.task('default', ['lint', 'test']);<commit_msg>Updating gulpfile to glup v4<commit_after>const gulp   = require('gulp');
const jshint = require('gulp-jshint');
const mocha = require('gulp-mocha');
const istanbul = require('gulp-istanbul');

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

gulp.task('pre-test', () => {
  return gulp.src(['./lib/**/*.js'])
    .pipe(istanbul())
    .pipe(istanbul.hookRequire());
})

gulp.task('test', gulp.series('pre-test', () => {
  return gulp.src('./test/**/*.js')
    .pipe(mocha({reporter: 'spec' }))
    // Ugly hack because the mocha plugin doesn't properly exit with an exit code on test failures
    .on('error', (err) => { process.exit(1) })
    .pipe(istanbul.writeReports())
    .pipe(istanbul.enforceThresholds({ thresholds: { global: 90 } }));
}));

gulp.task('default', gulp.series('lint', 'test'));<|endoftext|>


<commit_before>//* ========================
//compass-generic-config
//Version: 0.5.1
//Author: Raphael DDL Oliveira
//Github: https://github.com/RaphaelDDL/compass-generic-config
//MIT LICENSE
//https://github.com/RaphaelDDL/compass-generic-config/blob/master/LICENSE
//======================== */

//* =============================================
//Section: Grunt Configuration
//================================================ */
module.exports = function(grunt) {
	grunt.initConfig({
		pkg: grunt.file.readJSON('package.json'),

		//* =============================================
		//Section: SASS/COMPASS
		//================================================ */
		compass: {
			options: {
				config: './config.rb',
				watch: false
			},
			dev: {
				options: {
					environment: 'development'
				}
			},
			prod: {
				options: {
					environment: 'production'
				}
			}
		},

		//* =============================================
		//Section: WATCH
		//================================================ */
		watch: {
			compassdev: {
					files: [
						'<%= pkg.folderConfig.user_assets_folder %>/<%= pkg.folderConfig.user_css_folder %>/<%= pkg.folderConfig.user_sass_folder %>/**/*.scss'
					],
					tasks: ['compass:dev']
			},
			compassprod: {
				files: [
					'<%= pkg.folderConfig.user_assets_folder %>/<%= pkg.folderConfig.user_css_folder %>/<%= pkg.folderConfig.user_sass_folder %>/**/*.scss'
				],
				tasks: ['compass:prod']
			}
		},

	}); //grunt.initConfig

	//* =============================================
	//Section: TASK LOADER
	//================================================ */
	grunt.loadNpmTasks('grunt-contrib-compass');
	grunt.loadNpmTasks('grunt-contrib-watch');

	//* =============================================
	//Section: REGISTER TASKS
	//================================================ */
	grunt.registerTask("dev", ["watch:compassdev"]);
	grunt.registerTask("prod", ["watch:compassprod"]);

	// the default task can be run just by typing "grunt" on the command line
	grunt.registerTask('default', 'compass:prod']);
}//module.exports
<commit_msg>version bump<commit_after>//* ========================
//compass-generic-config
//Version: 0.5.2
//Author: Raphael DDL Oliveira
//Github: https://github.com/RaphaelDDL/compass-generic-config
//MIT LICENSE
//https://github.com/RaphaelDDL/compass-generic-config/blob/master/LICENSE
//======================== */

//* =============================================
//Section: Grunt Configuration
//================================================ */
module.exports = function(grunt) {
	grunt.initConfig({
		pkg: grunt.file.readJSON('package.json'),

		//* =============================================
		//Section: SASS/COMPASS
		//================================================ */
		compass: {
			options: {
				config: './config.rb',
				watch: false
			},
			dev: {
				options: {
					environment: 'development'
				}
			},
			prod: {
				options: {
					environment: 'production'
				}
			}
		},

		//* =============================================
		//Section: WATCH
		//================================================ */
		watch: {
			compassdev: {
					files: [
						'<%= pkg.folderConfig.user_assets_folder %>/<%= pkg.folderConfig.user_css_folder %>/<%= pkg.folderConfig.user_sass_folder %>/**/*.scss'
					],
					tasks: ['compass:dev']
			},
			compassprod: {
				files: [
					'<%= pkg.folderConfig.user_assets_folder %>/<%= pkg.folderConfig.user_css_folder %>/<%= pkg.folderConfig.user_sass_folder %>/**/*.scss'
				],
				tasks: ['compass:prod']
			}
		},

	}); //grunt.initConfig

	//* =============================================
	//Section: TASK LOADER
	//================================================ */
	grunt.loadNpmTasks('grunt-contrib-compass');
	grunt.loadNpmTasks('grunt-contrib-watch');

	//* =============================================
	//Section: REGISTER TASKS
	//================================================ */
	grunt.registerTask("dev", ["watch:compassdev"]);
	grunt.registerTask("prod", ["watch:compassprod"]);

	// the default task can be run just by typing "grunt" on the command line
	grunt.registerTask('default', 'compass:prod']);
}//module.exports
<|endoftext|>


<commit_before>"use strict";

var buildConfig = require('./config/build');

module.exports = function (grunt) {

    require("matchdep").filterDev("grunt-*").forEach(grunt.loadNpmTasks);

    var appConfig = {

        // Default Paths
        paths: {
            src: "src",
            dist: "dist"
        },

        // Assets directory
        dirs: {
            js: "<%= paths.src %>/assets/js",
            sass: "<%= paths.src %>/assets/scss",
            css: "<%= paths.src %>/assets/css",
            img: "<%= paths.src %>/assets/images",
            vendor: "<%= paths.src %>/vendor",
            pages: "<%= paths.src %>/pages",
            fonts: "<%= paths.src %>/vendor/topcoat/font"
        },

        // Load package.json
        pkg: grunt.file.readJSON("package.json"),

        // Metadata
        banner: "\n" +
            "/*\n" +
            " * -------------------------------------------------------\n" +
            " * Project: <%= pkg.name %>\n" +
            " * Version: <%= pkg.version %>\n" +
            " *\n" +
            " *\n" +
            " * Copyright (c) <%= grunt.template.today(\"yyyy\") %> <%= pkg.author.name %>\n" +
            " * -------------------------------------------------------\n" +
            " */\n" +
            "\n",

        // Watch files
        watch: {
            options: {
                livereload: true
            },
            css: {
                files: ["<%= dirs.sass %>/{,*/}*.{scss,sass}"],
                tasks: ["compass", "notify:compass"]
            },
            js: {
                files: ["<%= jshint.all %>"],
                tasks: ["jshint", "uglify", "notify:js"]
            },
            html: {
                files: [
                    // carregamento automático do browser para as atualizações das extensões abaixo
                    "/*.{html,htm,shtml,shtm,xhtml,php,jsp,asp,aspx,erb,ctp}"
                ]
            }
        },

        // Files Validation
        jshint: {
            options: {
                jshintrc: ".jshintrc"
            },
            all: [
                "Gruntfile.js",
                "<%= dirs.js %>/main.js"
            ]
        },

        // Minification
        uglify: {
            options: {
                mangle: false,
                banner: "<%= banner %>"
            }
            // ,
            // dist: {
            //     files: {
            //         "<%= dirs.js %>/main.min.js": [
            //         "<%= dirs.js %>/main.js"
            //         ]
            //     }
            // }
        },

        // Compass for SCSS
        /*compass: {
        dist: {
            options: {
                force: true,
                sassDir: "<%= dirs.sass %>",
                cssDir: "<%= dirs.css %>",
                banner: "<%= banner %>",
                specify: "<%= dirs.sass %>/*.scss"
            }
        }
    },*/

        // Notificações
        notify: {
            compass: {
                options: {
                    title: "SASS - <%= pkg.title %>",
                    message: "Build with success!"
                }
            },
            js: {
                options: {
                    title: "Javascript - <%= pkg.title %>",
                    message: "Minified and validated with success!"
                }
            }
        },

        copy: {
            /* COPY FONTS FOLDER */
            distFonts: {
                files: [{
                    expand: true,
                    cwd: "<%= dirs.fonts %>",
                    src: "**",
                    dest: "<%= paths.dist %>/vendor/topcoat/font"
            }]
            },
            distVendor: {
                files: [{
                    expand: true,
                    cwd: "<%= dirs.vendor %>/",
                    src: buildConfig.vendorFiles,
                    dest: "<%= paths.dist %>/vendor/"
            }]
            },
            distHtml: {
                files: [{
                    expand: true,
                    cwd: "<%= paths.src %>/",
                    src: buildConfig.htmlFiles,
                    dest: "<%= paths.dist %>/"
            }]
            },
            distCss: {
                files: [{
                    expand: true,
                    cwd: "<%= dirs.css %>/",
                    src: buildConfig.cssFiles,
                    dest: "<%= paths.dist %>/assets/css"
            }]
            },
            distJs: {
                files: [{
                    expand: true,
                    cwd: "<%= dirs.js %>/",
                    src: buildConfig.jsFiles,
                    dest: "<%= paths.dist %>/assets/js"
            }]
            },
            distImages: {
                files: [{
                    expand: true,
                    cwd: "<%= dirs.img %>/",
                    src: "**",
                    dest: "<%= paths.dist %>/assets/images"
            }]
            },
            distPages: {
                files: [{
                    expand: true,
                    cwd: "<%= dirs.pages %>/",
                    src: "**",
                    dest: "<%= paths.dist %>/pages"
            }]
            }
        },

        /************************************
         * grunt-bump
         * Bump package version, create tag, commit, push...
         ************************************/
        bump: {
            options: {
                files: ['package.json', 'bower.json'],
                updateConfigs: [],
                commit: true,
                commitMessage: '%VERSION%',
                commitFiles: ['package.json', 'bower.json', 'dist/'], // '-a' for all files
                createTag: true,
                tagName: '%VERSION%',
                tagMessage: '%VERSION%',
                push: true,
                pushTo: 'master',
                gitDescribeOptions: '--tags --always --abbrev=1 --dirty=-d' // options to use with '$ git describe'
            }
        }

    };

    // Init grunt configurations
    grunt.initConfig(appConfig);

    // Tasks
    // --------------------------

    // Use grunt-bump for changing version number
    grunt.loadNpmTasks('grunt-bump');

    // Watch Task
    grunt.registerTask('w', ['watch']);

    // Default task
    grunt.registerTask('dist', ['copy']);
    grunt.registerTask('build', ['dist']);
    grunt.registerTask('default', ['dist']);

};<commit_msg>Update Gruntfile.js<commit_after>/*!
 * FastGap's Gruntfile
 * http://fastgap.mobi/
 * Licensed under MIT
 */

"use strict";

var buildConfig = require('./config/build');

module.exports = function (grunt) {

    require("matchdep").filterDev("grunt-*").forEach(grunt.loadNpmTasks);

    var appConfig = {

        // Default Paths
        paths: {
            src: "src",
            dist: "dist"
        },

        // Assets directory
        dirs: {
            js: "<%= paths.src %>/assets/js",
            sass: "<%= paths.src %>/assets/scss",
            css: "<%= paths.src %>/assets/css",
            img: "<%= paths.src %>/assets/images",
            vendor: "<%= paths.src %>/vendor",
            pages: "<%= paths.src %>/pages",
            fonts: "<%= paths.src %>/vendor/topcoat/font"
        },

        // Load package.json
        pkg: grunt.file.readJSON("package.json"),

        // Metadata
        banner: "\n" +
            "/*\n" +
            " * -------------------------------------------------------\n" +
            " * Project: <%= pkg.name %>\n" +
            " * Version: <%= pkg.version %>\n" +
            " *\n" +
            " *\n" +
            " * Copyright (c) <%= grunt.template.today(\"yyyy\") %> <%= pkg.author.name %>\n" +
            " * -------------------------------------------------------\n" +
            " */\n" +
            "\n",

        // Watch files
        watch: {
            options: {
                livereload: true
            },
            css: {
                files: ["<%= dirs.sass %>/{,*/}*.{scss,sass}"],
                tasks: ["compass", "notify:compass"]
            },
            js: {
                files: ["<%= jshint.all %>"],
                tasks: ["jshint", "uglify", "notify:js"]
            },
            html: {
                files: [
                    // carregamento automático do browser para as atualizações das extensões abaixo
                    "/*.{html,htm,shtml,shtm,xhtml,php,jsp,asp,aspx,erb,ctp}"
                ]
            }
        },

        // Files Validation
        jshint: {
            options: {
                jshintrc: ".jshintrc"
            },
            all: [
                "Gruntfile.js",
                "<%= dirs.js %>/main.js"
            ]
        },

        // Minification
        uglify: {
            options: {
                mangle: false,
                banner: "<%= banner %>"
            }
            // ,
            // dist: {
            //     files: {
            //         "<%= dirs.js %>/main.min.js": [
            //         "<%= dirs.js %>/main.js"
            //         ]
            //     }
            // }
        },

        // Compass for SCSS
        /*compass: {
        dist: {
            options: {
                force: true,
                sassDir: "<%= dirs.sass %>",
                cssDir: "<%= dirs.css %>",
                banner: "<%= banner %>",
                specify: "<%= dirs.sass %>/*.scss"
            }
        }
    },*/

        // Notificações
        notify: {
            compass: {
                options: {
                    title: "SASS - <%= pkg.title %>",
                    message: "Build with success!"
                }
            },
            js: {
                options: {
                    title: "Javascript - <%= pkg.title %>",
                    message: "Minified and validated with success!"
                }
            }
        },

        copy: {
            /* COPY FONTS FOLDER */
            distFonts: {
                files: [{
                    expand: true,
                    cwd: "<%= dirs.fonts %>",
                    src: "**",
                    dest: "<%= paths.dist %>/vendor/topcoat/font"
            }]
            },
            distVendor: {
                files: [{
                    expand: true,
                    cwd: "<%= dirs.vendor %>/",
                    src: buildConfig.vendorFiles,
                    dest: "<%= paths.dist %>/vendor/"
            }]
            },
            distHtml: {
                files: [{
                    expand: true,
                    cwd: "<%= paths.src %>/",
                    src: buildConfig.htmlFiles,
                    dest: "<%= paths.dist %>/"
            }]
            },
            distCss: {
                files: [{
                    expand: true,
                    cwd: "<%= dirs.css %>/",
                    src: buildConfig.cssFiles,
                    dest: "<%= paths.dist %>/assets/css"
            }]
            },
            distJs: {
                files: [{
                    expand: true,
                    cwd: "<%= dirs.js %>/",
                    src: buildConfig.jsFiles,
                    dest: "<%= paths.dist %>/assets/js"
            }]
            },
            distImages: {
                files: [{
                    expand: true,
                    cwd: "<%= dirs.img %>/",
                    src: "**",
                    dest: "<%= paths.dist %>/assets/images"
            }]
            },
            distPages: {
                files: [{
                    expand: true,
                    cwd: "<%= dirs.pages %>/",
                    src: "**",
                    dest: "<%= paths.dist %>/pages"
            }]
            }
        },

        /************************************
         * grunt-bump
         * Bump package version, create tag, commit, push...
         ************************************/
        bump: {
            options: {
                files: ['package.json', 'bower.json'],
                updateConfigs: [],
                commit: true,
                commitMessage: '%VERSION%',
                commitFiles: ['package.json', 'bower.json', 'dist/'], // '-a' for all files
                createTag: true,
                tagName: '%VERSION%',
                tagMessage: '%VERSION%',
                push: true,
                pushTo: 'master',
                gitDescribeOptions: '--tags --always --abbrev=1 --dirty=-d' // options to use with '$ git describe'
            }
        }

    };

    // Init grunt configurations
    grunt.initConfig(appConfig);

    // Tasks
    // --------------------------

    // Use grunt-bump for changing version number
    grunt.loadNpmTasks('grunt-bump');

    // Watch Task
    grunt.registerTask('w', ['watch']);

    // Default task
    grunt.registerTask('dist', ['copy']);
    grunt.registerTask('build', ['dist']);
    grunt.registerTask('default', ['dist']);

};
<|endoftext|>


<commit_before>var gulp = require('gulp');
var sass = require('gulp-sass');
var autoprefixer = require('gulp-autoprefixer');
var browserSync = require('browser-sync').create();

// Path config
var config = {
  bootstrapDir: './node_modules/bootstrap-sass',
  publicDir: './dist',
  sourceDir: './src',
  devDir: './src/dev'
};

// Bootstrap Sass (Currently useless)
gulp.task('bootstrapSassConvert', function () {
  return gulp.src(config.sourceDir + '/sass/app.scss')
  .pipe(sass({
    includePaths: [config.bootstrapDir + '/assets/stylesheets']
  }))
  .pipe(gulp.dest(config.devDir + '/css'));
});

// Bootstrap Fonts
gulp.task('fonts', function () {
  return gulp.src(config.bootstrapDir + '/assets/fonts/bootstrap/**/*').pipe(gulp.dest(config.devDir + '/fonts'));
});

// Web Server
gulp.task('browserSync', function () {
  browserSync.init({
    server: './src/dev',
    port: '3000'
  })
});

// Sass to Css
gulp.task('sass', function () {
  gulp.src('./src/sass/*.scss')
    .pipe(sass().on('error', sass.logError))
    .pipe(autoprefixer())
    .pipe(gulp.dest(config.devDir + '/css'))
    .pipe(browserSync.reload({stream: true}));
});

// Watch change
gulp.task('watch', ['browserSync', 'sass'], function () {
  gulp.watch('./src/sass/*.scss', ['sass']);
  gulp.watch('./src/dev/**/*.html', browserSync.reload);
});

// Default task
gulp.task('default', ['watch']);<commit_msg>add task which convert bootstrap sass to bootstrap.css<commit_after>var gulp = require('gulp');
var sass = require('gulp-sass');
var autoprefixer = require('gulp-autoprefixer');
var browserSync = require('browser-sync').create();
var rename = require('gulp-rename');

// Path config
var config = {
  bootstrapDir: './node_modules/bootstrap-sass',
  publicDir: './dist',
  sourceDir: './src',
  devDir: './src/dev'
};

// Bootstrap Sass
gulp.task('bootstrapSassConvert', function () {
  return gulp.src(config.sourceDir + '/sass/app.scss')
  .pipe(sass({
    includePaths: [config.bootstrapDir + '/assets/stylesheets']
  }))
  .pipe(rename({
    basename: 'bootstrap',
    extname: '.css'
  }))
  .pipe(gulp.dest(config.devDir + '/css'));
});

// Bootstrap Fonts
gulp.task('fonts', function () {
  return gulp.src(config.bootstrapDir + '/assets/fonts/bootstrap/**/*').pipe(gulp.dest(config.devDir + '/fonts'));
});

// Web Server
gulp.task('browserSync', function () {
  browserSync.init({
    server: './src/dev',
    port: '3000'
  })
});

// Sass to Css
gulp.task('sass', function () {
  gulp.src('./src/sass/*.scss')
    .pipe(sass().on('error', sass.logError))
    .pipe(autoprefixer())
    .pipe(gulp.dest(config.devDir + '/css'))
    .pipe(browserSync.reload({stream: true}));
});

// Watch change
gulp.task('watch', ['browserSync', 'sass'], function () {
  gulp.watch('./src/sass/*.scss', ['sass']);
  gulp.watch('./src/dev/**/*.html', browserSync.reload);
});

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


<commit_before>'use strict';

const BaseType = require('./base');
const parseFields = require('../util/parseFields');
const addListenersUtil = require('../util/addListeners');
const validate = require('valid-point');
const fields = Symbol();
const addListeners = Symbol();
const applyFieldNames = Symbol();
const applyFieldParent = Symbol();

class ObjectType extends BaseType {

    constructor (fields, options = {}) {
        super(options);
        this.parent = options.parent;
        this.initialize(fields);
    }

    [ addListeners ] () {
        Object.keys(this[fields]).forEach((key) => {
            const field = this[fields][key];
            addListenersUtil(this, field);
        });
    }

    [ applyFieldNames ] () {
        Object.keys(this[fields]).forEach((key) => {
            this[fields][key].fieldName = key;
        });
    }

    [ applyFieldParent ] () {
        Object.keys(this[fields]).forEach((key) => {
            this[fields][key].parent = this.parent;
            if (typeof this[fields][key].setParent === 'function') {
                this[fields][key].setParent();
            }
        });
    }

    apply (data) {
        Object.keys(data).forEach((key) => {
            this[fields][key].apply(data[key]);
        });

        return this;
    }

    initialize (initalFields) {
        this[fields] = parseFields(initalFields);
        this[applyFieldNames]();
        this[applyFieldParent]();
        this[addListeners]();
    }

    get (key) {
        const ArrayType = require('./array');
        const field = this[fields][key];

        // Objects
        if (field instanceof this.constructor) {
            return field;
        }

        // Arrays
        if (field instanceof ArrayType) {
            return field;
        }

        return field.get();
    }

    set (key, value) {
        this[fields][key].set(value);
        return this;
    }

    toJSON () {
        let json = {};

        Object.keys(this[fields]).map((key) => {
            json[key] = this[fields][key].toJSON();
        });

        return json;
    }

    validate (key) {
        if (key) {
            return this[fields][key].validate();
        }

        return Object.keys(this[fields]).map((key) => {
            return this[fields][key].validate();
        });
    }

}

module.exports = ObjectType;
<commit_msg>throwing a more explanitory error when a field is undefined<commit_after>'use strict';

const BaseType = require('./base');
const parseFields = require('../util/parseFields');
const addListenersUtil = require('../util/addListeners');
const validate = require('valid-point');
const fields = Symbol();
const addListeners = Symbol();
const applyFieldNames = Symbol();
const applyFieldParent = Symbol();

class ObjectType extends BaseType {

    constructor (fields, options = {}) {
        super(options);
        this.parent = options.parent;
        this.initialize(fields);
    }

    [ addListeners ] () {
        Object.keys(this[fields]).forEach((key) => {
            const field = this[fields][key];
            addListenersUtil(this, field);
        });
    }

    [ applyFieldNames ] () {
        Object.keys(this[fields]).forEach((key) => {
            this[fields][key].fieldName = key;
        });
    }

    [ applyFieldParent ] () {
        Object.keys(this[fields]).forEach((key) => {
            this[fields][key].parent = this.parent;
            if (typeof this[fields][key].setParent === 'function') {
                this[fields][key].setParent();
            }
        });
    }

    apply (data) {
        Object.keys(data).forEach((key) => {
            this[fields][key].apply(data[key]);
        });

        return this;
    }

    initialize (initalFields) {
        this[fields] = parseFields(initalFields);
        this[applyFieldNames]();
        this[applyFieldParent]();
        this[addListeners]();
    }

    get (key) {
        const ArrayType = require('./array');
        const field = this[fields][key];

        if (!field) {
            throw new Error(`cannot get "${key}." It is undefined in your Cannery model`);
        }

        // Objects
        if (field instanceof this.constructor) {
            return field;
        }

        // Arrays
        if (field instanceof ArrayType) {
            return field;
        }

        return field.get();
    }

    set (key, value) {
        this[fields][key].set(value);
        return this;
    }

    toJSON () {
        let json = {};

        Object.keys(this[fields]).map((key) => {
            json[key] = this[fields][key].toJSON();
        });

        return json;
    }

    validate (key) {
        if (key) {
            return this[fields][key].validate();
        }

        return Object.keys(this[fields]).map((key) => {
            return this[fields][key].validate();
        });
    }

}

module.exports = ObjectType;
<|endoftext|>


<commit_before>module.exports = function(grunt) {
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        concat_in_order: {
            your_target: {
                options: {
                    banner: '/*!\n<%= pkg.name %>\nVersion: <%= pkg.version %>\n<%= pkg.homepage %>\nGIT: <%= pkg.repository %>/commit/<%= meta.revision %>\nLicense: <%= pkg.license %>\n<%= grunt.template.today("UTC:dddd, mmmm dS, yyyy, h:MM:ss TT Z", true) %>\n*/\n',
                    extractRequired: function(filepath, filecontent) {
                        var augments = this.getMatches(/@augments[\s]+([^\s]+)/g, filecontent);
                        var requires = this.getMatches(/@requires[\s]+([^\s]+)/g, filecontent);
                        return augments.concat(requires);
                    },
                    extractDeclared: function(filepath, filecontent) {
                        return this.getMatches(/@class[\s]+([^\s]+)/g, filecontent);
                    },
                    exportConcatenationOrder: 'concatOrder'
                },
                files: {
                    'thefragebogen.js': ['build/*.js']
                }
            }
        },
        includereplace: {
            dist: {
                options: {
                    globals: {},
                },
                files: [{
                    src: '*.js',
                    dest: 'build/',
                    expand: true,
                    cwd: 'src/'
                }, ]
            }
        },
        jsbeautifier: {
            files: ['src/*.js', 'examples/*', 'examples_feasibility/*/src/*.js', 'examples_feasibility/*/*.html', 'tests/*', 'Gruntfile.js', 'package.json'],
            options: {
                js: {
                    indent_size: 4,
                    preserve_newlines: true,
                    wrap_line_length: 0,
                    end_with_newline: true
                },
                css: {
                    indent_size: 4,
                    preserve_newlines: false,
                    max_preserve_newlines: 2,
                    end_with_newline: true
                },
                html: {
                    indent_size: 4,
                    preserve_newlines: true,
                    max_preserve_newlines: 2,
                    end_with_newline: true,
                    indent_inner_html: true,
                    indent_scripts: "keep",
                    extra_liners: ["head", "body", "/html", "script", "style"]
                }
            }
        },
        jshint: {
            all: ['src/*.js', 'examples/*.js', 'examples-feasibility/*/src/*.js', 'Gruntfile.js', 'package.json'],
            options: {
                esversion: 6
            }
        },
        qunit: {
            all: ['tests/qunit*.html'],
            options: {
                puppeteer: {
                    headless: true,
                    //Disable Chrome's security features to be executed on (older) Linux; needed for TravisCI
                    args: ['--no-sandbox', '--disable-setuid-sandbox']
                }
            }
        },
        revision: {
            options: {
                property: 'meta.revision',
                ref: 'HEAD',
                short: false
            }
        },
        run: {
            jsdoc: {
                exec: 'jsdoc --private -d doc thefragebogen.js'
            },
            help: {
                exec: 'grunt --help'
            }
        },
        babel: {
            options: {
                sourceMap: true,
                presets: ['@babel/preset-env']
            },
            dist: {
                files: {
                    'thefragebogen.es5.js': 'thefragebogen.js'
                }
            }
        },
        uglify: {
            options: {
                banner: '/*!\n<%= pkg.name %>\nVersion: <%= pkg.version %>\n<%= pkg.homepage %>\nGIT: <%= pkg.repository %>/commit/<%= meta.revision %>\nLicense: <%= pkg.license %>\n<%= grunt.template.today("UTC:dddd, mmmm dS, yyyy, h:MM:ss TT Z", true) %>\n*/\n',
            },
            dist: {
                files: {
                    'thefragebogen.es5-min.js': ['thefragebogen.es5.js'] //'<%= concat_in_order.dist.dest %>'
                }
            }
        }
    });

    grunt.loadNpmTasks('grunt-concat-in-order');
    grunt.loadNpmTasks('grunt-contrib-qunit');
    grunt.loadNpmTasks("grunt-contrib-uglify");
    grunt.loadNpmTasks('grunt-git-revision');
    grunt.loadNpmTasks('grunt-include-replace');
    grunt.loadNpmTasks("grunt-jsbeautifier");
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-run');
    require("load-grunt-tasks")(grunt);

    //Task(s)
    grunt.registerTask('default', ['includereplace', 'revision', 'concat_in_order']);

    grunt.registerTask('doc', ['default', 'run:jsdoc']);
    grunt.registerTask('dist', ['default', 'babel', 'uglify']);
    grunt.registerTask('format', ['jsbeautifier']);
    grunt.registerTask('help', ['run:help']);
    grunt.registerTask('lint', ['jshint']);
    grunt.registerTask('test', ['default', 'qunit']);
};
<commit_msg>Build toolchain: transpile to dist-folder.<commit_after>module.exports = function(grunt) {
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        concat_in_order: {
            your_target: {
                options: {
                    banner: '/*!\n<%= pkg.name %>\nVersion: <%= pkg.version %>\n<%= pkg.homepage %>\nGIT: <%= pkg.repository %>/commit/<%= meta.revision %>\nLicense: <%= pkg.license %>\n<%= grunt.template.today("UTC:dddd, mmmm dS, yyyy, h:MM:ss TT Z", true) %>\n*/\n',
                    extractRequired: function(filepath, filecontent) {
                        var augments = this.getMatches(/@augments[\s]+([^\s]+)/g, filecontent);
                        var requires = this.getMatches(/@requires[\s]+([^\s]+)/g, filecontent);
                        return augments.concat(requires);
                    },
                    extractDeclared: function(filepath, filecontent) {
                        return this.getMatches(/@class[\s]+([^\s]+)/g, filecontent);
                    },
                    exportConcatenationOrder: 'concatOrder'
                },
                files: {
                    'thefragebogen.js': ['build/*.js']
                }
            }
        },
        includereplace: {
            dist: {
                options: {
                    globals: {},
                },
                files: [{
                    src: '*.js',
                    dest: 'build/',
                    expand: true,
                    cwd: 'src/'
                }, ]
            }
        },
        jsbeautifier: {
            files: ['src/*.js', 'examples/*', 'examples_feasibility/*/src/*.js', 'examples_feasibility/*/*.html', 'tests/*', 'Gruntfile.js', 'package.json'],
            options: {
                js: {
                    indent_size: 4,
                    preserve_newlines: true,
                    wrap_line_length: 0,
                    end_with_newline: true
                },
                css: {
                    indent_size: 4,
                    preserve_newlines: false,
                    max_preserve_newlines: 2,
                    end_with_newline: true
                },
                html: {
                    indent_size: 4,
                    preserve_newlines: true,
                    max_preserve_newlines: 2,
                    end_with_newline: true,
                    indent_inner_html: true,
                    indent_scripts: "keep",
                    extra_liners: ["head", "body", "/html", "script", "style"]
                }
            }
        },
        jshint: {
            all: ['src/*.js', 'examples/*.js', 'examples-feasibility/*/src/*.js', 'Gruntfile.js', 'package.json'],
            options: {
                esversion: 6
            }
        },
        qunit: {
            all: ['tests/qunit*.html'],
            options: {
                puppeteer: {
                    headless: true,
                    //Disable Chrome's security features to be executed on (older) Linux; needed for TravisCI
                    args: ['--no-sandbox', '--disable-setuid-sandbox']
                }
            }
        },
        revision: {
            options: {
                property: 'meta.revision',
                ref: 'HEAD',
                short: false
            }
        },
        run: {
            jsdoc: {
                exec: 'jsdoc --private -d doc thefragebogen.js'
            },
            help: {
                exec: 'grunt --help'
            }
        },
        babel: {
            options: {
                sourceMap: true,
                presets: ['@babel/preset-env']
            },
            dist: {
                files: {
                    'dist/thefragebogen.es5.js': 'thefragebogen.js'
                }
            }
        },
        uglify: {
            options: {
                banner: '/*!\n<%= pkg.name %>\nVersion: <%= pkg.version %>\n<%= pkg.homepage %>\nGIT: <%= pkg.repository %>/commit/<%= meta.revision %>\nLicense: <%= pkg.license %>\n<%= grunt.template.today("UTC:dddd, mmmm dS, yyyy, h:MM:ss TT Z", true) %>\n*/\n',
            },
            dist: {
                files: {
                    'dist/thefragebogen.es5-min.js': ['dist/thefragebogen.es5.js'] //'<%= concat_in_order.dist.dest %>'
                }
            }
        }
    });

    grunt.loadNpmTasks('grunt-concat-in-order');
    grunt.loadNpmTasks('grunt-contrib-qunit');
    grunt.loadNpmTasks("grunt-contrib-uglify");
    grunt.loadNpmTasks('grunt-git-revision');
    grunt.loadNpmTasks('grunt-include-replace');
    grunt.loadNpmTasks("grunt-jsbeautifier");
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-run');
    require("load-grunt-tasks")(grunt);

    //Task(s)
    grunt.registerTask('default', ['includereplace', 'revision', 'concat_in_order']);

    grunt.registerTask('doc', ['default', 'run:jsdoc']);
    grunt.registerTask('dist', ['default', 'babel', 'uglify', 'doc']);
    grunt.registerTask('format', ['jsbeautifier']);
    grunt.registerTask('help', ['run:help']);
    grunt.registerTask('lint', ['jshint']);
    grunt.registerTask('test', ['default', 'qunit']);
};
<|endoftext|>


<commit_before>var path = require('path');
var gulp = require('gulp');
var eslint = require('gulp-eslint');
var excludeGitignore = require('gulp-exclude-gitignore');
var mocha = require('gulp-mocha');
var istanbul = require('gulp-istanbul');
var nsp = require('gulp-nsp');
var plumber = require('gulp-plumber');
var coveralls = require('gulp-coveralls');
var babel = require('gulp-babel');

// Initialize the babel transpiler so ES2015 files gets compiled
// when they're loaded
require('babel-core/register');

gulp.task('static', function () {
  return gulp.src('**/*.js')
    .pipe(excludeGitignore())
    .pipe(eslint())
    .pipe(eslint.format())
    .pipe(eslint.failAfterError());
});

gulp.task('nsp', function (cb) {
  nsp('package.json', cb);
});

gulp.task('pre-test', function () {
  return gulp.src('lib/**/*.js')
    .pipe(babel())
    .pipe(istanbul({includeUntested: true}))
    .pipe(istanbul.hookRequire());
});

gulp.task('test', ['pre-test'], function (cb) {
  gulp.src('test/**/*.js')
    .pipe(plumber())
    .pipe(mocha({reporter: 'spec'}))
    .on('error', function (err) {
      cb(err);
    })
    .pipe(istanbul.writeReports({
      //reporters: ['json', 'text', 'text-summary']
      reporters: ['json', 'text', 'text-summary', 'lcov']
    }));
});

gulp.task('coveralls', ['test'], function () {
  if (!process.env.CI) {
    return;
  }

  return gulp.src(path.join(__dirname, 'coverage/lcov.info'))
    .pipe(coveralls());
});

gulp.task('babel', function () {
  return gulp.src('lib/**/*.js')
    .pipe(babel())
    .pipe(gulp.dest('dist'));
});

gulp.task('prepublish', ['nsp', 'babel']);
gulp.task('default', ['static', 'test', 'coveralls']);
<commit_msg>lcov istambul report error<commit_after>var path = require('path');
var gulp = require('gulp');
var eslint = require('gulp-eslint');
var excludeGitignore = require('gulp-exclude-gitignore');
var mocha = require('gulp-mocha');
var istanbul = require('gulp-istanbul');
var nsp = require('gulp-nsp');
var plumber = require('gulp-plumber');
var coveralls = require('gulp-coveralls');
var babel = require('gulp-babel');

// Initialize the babel transpiler so ES2015 files gets compiled
// when they're loaded
require('babel-core/register');

gulp.task('static', function () {
  return gulp.src('**/*.js')
    .pipe(excludeGitignore())
    .pipe(eslint())
    .pipe(eslint.format())
    .pipe(eslint.failAfterError());
});

gulp.task('nsp', function (cb) {
  nsp('package.json', cb);
});

gulp.task('pre-test', function () {
  return gulp.src('lib/**/*.js')
    .pipe(babel())
    .pipe(istanbul({includeUntested: true}))
    .pipe(istanbul.hookRequire());
});

gulp.task('test', ['pre-test'], function (cb) {
  gulp.src('test/**/*.js')
    .pipe(plumber())
    .pipe(mocha({reporter: 'spec'}))
    .on('error', function (err) {
      cb(err);
    })
    .pipe(istanbul.writeReports({
      reporters: ['json', 'text', 'text-summary']
      //reporters: ['json', 'text', 'text-summary', 'lcov']
    }));
});

gulp.task('coveralls', ['test'], function () {
  if (!process.env.CI) {
    return;
  }

  return gulp.src(path.join(__dirname, 'coverage/lcov.info'))
    .pipe(coveralls());
});

gulp.task('babel', function () {
  return gulp.src('lib/**/*.js')
    .pipe(babel())
    .pipe(gulp.dest('dist'));
});

gulp.task('prepublish', ['nsp', 'babel']);
gulp.task('default', ['static', 'test', 'coveralls']);
<|endoftext|>