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

/* eslint-env node */

module.exports = function (grunt) {
    "use strict";

    // If main task is debug, this flag gets set at the beginning
    if (grunt.cli.tasks[0] === "debug") {
        grunt.option("DEV_MODE", true);
    }

    // Matches every root folder in src/nls into a locale name
    // If we are in dev mode, compiles only English
    var DEV_MODE = grunt.option("DEV_MODE") !== undefined,
        ALL_LOCALES = DEV_MODE ? ["en"] : grunt.file.expand({
            filter: "isDirectory",
            cwd: "src/nls"
        }, "*");

    process.env.SPACES_LOCALES = ALL_LOCALES;
    process.env.SPACES_DEV_MODE = DEV_MODE;

    grunt.initConfig({
        eslint: {
            options: {
                configFile: ".eslintrc.json"
            },
            all: [
                "*.js",
                "*.json",
                "src/**/*.js",
                "src/**/*.jsx",
                "test/**/*.js",
                "test/**/*.jsx",
                "!npm-shrinkwrap.json",
                "!manifest.json",
                "!package.json"
            ]
        },
        jscs: {
            main: {
                src: [
                    "*.js",
                    "*.json",
                    "src/**/*.js",
                    "src/**/*.jsx"
                ],
                options: {
                    config: ".jscsrc"
                }
            },
            secondary: {
                src: [
                    "test/**/*.js",
                    "test/**/*.jsx"
                ],
                options: {
                    config: ".jscsrc",
                    jsDoc: false
                }
            }
        },
        jsdoc: {
            dist: {
                src: ["src"],
                options: {
                    destination: "docs/jsdoc",
                    recurse: true
                }
            }
        },
        jsonlint: {
            src: [
                "*.json",
                "src/**/*.json",
                "test/**/*.json"
            ]
        },
        lintspaces: {
            src: [
                "*",
                "src/**/*.json",
                "src/**/*.jsx",
                "src/**/*.js",
                "src/**/*.svg",
                "src/**/*.less",
                "!src/**/*.gif"
            ],
            options: {
                newline: true,
                newlineMaximum: 1
            }
        },
        // Preparation tasks
        // Concatenates the multiple dictionary files
        // into a single json file per locale
        "concat-json": {
            i18n: {
                files: ALL_LOCALES.map(function (locale) {
                    return {
                        dest: "build/nls/" + locale + ".json",
                        src: "*.json",
                        cwd: "src/nls/" + locale
                    };
                })
            },
            options: {
                space: " "
            }
        },
        // Merges the non-en locale dictionaries with English so any missing string
        // is replaced by the English one
        "merge-json": {
            i18n: {
                files: ALL_LOCALES.reduce(function (map, locale) {
                    // No need to merge English
                    if (locale === "en") {
                        return map;
                    }

                    var source = "build/nls/" + locale + ".json",
                        target = "build/nls/" + locale + ".json";

                    map[target] = ["build/nls/en.json", source];
                    return map;
                }, {})
            },
            options: {
                space: " "
            }
        },
        // Utility tasks
        clean: {
            build: ["./build"],
            i18n: ["./build/nls"]
        },
        copy: {
            htmlRelease: { src: "src/index.html", dest: "build/index.html" },
            htmlDebug: { src: "src/index-debug.html", dest: "build/index.html" },
            img: { expand: true, cwd: "src/img", src: "**", dest: "build/img/" }
        },
        watch: {
            styles: {
                files: ["src/style/**/*"],
                tasks: ["less", "notify:less"],
                options: {
                    spawn: false,
                    interrupt: true,
                    reload: true
                }
            },
            dictionaries: {
                files: ["src/nls/**/*"],
                tasks: ["i18n"],
                options: {
                    spawn: false,
                    interrupt: true
                }
            },
            sources: {
                files: ["src/**/*"],
                options: {
                    interval: 500
                }
            }
        },
        // Build tasks
        less: {
            style: {
                files: {
                    "build/style.css": "src/style/main.less"
                },
                options: {
                    sourceMap: grunt.option("DEV_MODE"),
                    sourceMapFileInline: true,
                    outputSourceFiles: true,
                    sourceMapRootpath: "../"
                }
            }
        },
        webpack: {
            options: require("./webpack.config.js"),
            compile: {
                watch: false
            },
            watch: {
                watch: true,
                keepalive: true,
                failOnError: false
            }
        },
        uglify: {
            design: {
                options: {
                    compress: {
                        unused: false // This saves us about half an hour, losing 200 KB
                    },
                    define: {
                        __PG_DEBUG__: false
                    }
                },
                files: ALL_LOCALES.reduce(function (map, locale) {
                    var target = "build/spaces-design-" + locale + ".js";

                    map[target] = [target];
                    return map;
                }, {})
            }
        },
        concurrent: {
            test: ["checkDependencies", "eslint", "jscs", "jsdoc", "jsonlint", "lintspaces"],
            build: {
                tasks: ["watch:styles", "watch:dictionaries", "watch:sources", "webpack:watch"],
                options: {
                    logConcurrentOutput: true
                }
            }
        },
        notify: {
            less: {
                options: {
                    title: "LESS",
                    message: "Build Successful"
                }
            }
        },
        checkDependencies: {
            this: {},
        }
    });

    grunt.loadNpmTasks("grunt-eslint");
    grunt.loadNpmTasks("grunt-jscs");
    grunt.loadNpmTasks("grunt-jsdoc");
    grunt.loadNpmTasks("grunt-jsonlint");
    grunt.loadNpmTasks("grunt-lintspaces");

    grunt.loadNpmTasks("grunt-contrib-clean");
    grunt.loadNpmTasks("grunt-contrib-copy");
    grunt.loadNpmTasks("grunt-contrib-less");
    grunt.loadNpmTasks("grunt-contrib-uglify");
    grunt.loadNpmTasks("grunt-contrib-watch");

    grunt.loadNpmTasks("grunt-webpack");

    grunt.loadNpmTasks("grunt-concurrent");
    grunt.loadNpmTasks("grunt-concat-json");
    grunt.loadNpmTasks("grunt-merge-json");
    grunt.loadNpmTasks("grunt-notify");
    grunt.loadNpmTasks('grunt-check-dependencies');

    grunt.registerTask("seqtest", "Runs the linter tests sequentially",
        ["eslint", "jscs", "jsdoc", "jsonlint", "lintspaces"]
    );
    grunt.registerTask("test", "Runs linter tests",
        ["concurrent:test"]
    );
    grunt.registerTask("i18n", "Prepares the localization dictionaries",
        ["clean:i18n", "concat-json", "merge-json"]
    );
    grunt.registerTask("compile", "Bundles Design Space in Release mode, for all locales",
        ["checkDependencies", "test", "clean:build", "i18n", "copy:img", "copy:htmlRelease",
         "less", "webpack:compile", "uglify", "clean:i18n"]
    );
    grunt.registerTask("debug", "Bundles Design Space in Debug mode, for English only",
        ["checkDependencies", "clean", "i18n", "copy:img", "copy:htmlDebug", "less", "concurrent:build"]
    );
    grunt.registerTask("default", "Runs linter tests", ["test"]);
};
<commit_msg>Continuously monitor package.json file when the debug task is running.<commit_after>/*
 * Copyright (c) 2014 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

/* eslint-env node */

module.exports = function (grunt) {
    "use strict";

    // If main task is debug, this flag gets set at the beginning
    if (grunt.cli.tasks[0] === "debug") {
        grunt.option("DEV_MODE", true);
    }

    // Matches every root folder in src/nls into a locale name
    // If we are in dev mode, compiles only English
    var DEV_MODE = grunt.option("DEV_MODE") !== undefined,
        ALL_LOCALES = DEV_MODE ? ["en"] : grunt.file.expand({
            filter: "isDirectory",
            cwd: "src/nls"
        }, "*");

    process.env.SPACES_LOCALES = ALL_LOCALES;
    process.env.SPACES_DEV_MODE = DEV_MODE;

    grunt.initConfig({
        eslint: {
            options: {
                configFile: ".eslintrc.json"
            },
            all: [
                "*.js",
                "*.json",
                "src/**/*.js",
                "src/**/*.jsx",
                "test/**/*.js",
                "test/**/*.jsx",
                "!npm-shrinkwrap.json",
                "!manifest.json",
                "!package.json"
            ]
        },
        jscs: {
            main: {
                src: [
                    "*.js",
                    "*.json",
                    "src/**/*.js",
                    "src/**/*.jsx"
                ],
                options: {
                    config: ".jscsrc"
                }
            },
            secondary: {
                src: [
                    "test/**/*.js",
                    "test/**/*.jsx"
                ],
                options: {
                    config: ".jscsrc",
                    jsDoc: false
                }
            }
        },
        jsdoc: {
            dist: {
                src: ["src"],
                options: {
                    destination: "docs/jsdoc",
                    recurse: true
                }
            }
        },
        jsonlint: {
            src: [
                "*.json",
                "src/**/*.json",
                "test/**/*.json"
            ]
        },
        lintspaces: {
            src: [
                "*",
                "src/**/*.json",
                "src/**/*.jsx",
                "src/**/*.js",
                "src/**/*.svg",
                "src/**/*.less",
                "!src/**/*.gif"
            ],
            options: {
                newline: true,
                newlineMaximum: 1
            }
        },
        // Preparation tasks
        // Concatenates the multiple dictionary files
        // into a single json file per locale
        "concat-json": {
            i18n: {
                files: ALL_LOCALES.map(function (locale) {
                    return {
                        dest: "build/nls/" + locale + ".json",
                        src: "*.json",
                        cwd: "src/nls/" + locale
                    };
                })
            },
            options: {
                space: " "
            }
        },
        // Merges the non-en locale dictionaries with English so any missing string
        // is replaced by the English one
        "merge-json": {
            i18n: {
                files: ALL_LOCALES.reduce(function (map, locale) {
                    // No need to merge English
                    if (locale === "en") {
                        return map;
                    }

                    var source = "build/nls/" + locale + ".json",
                        target = "build/nls/" + locale + ".json";

                    map[target] = ["build/nls/en.json", source];
                    return map;
                }, {})
            },
            options: {
                space: " "
            }
        },
        // Utility tasks
        clean: {
            build: ["./build"],
            i18n: ["./build/nls"]
        },
        copy: {
            htmlRelease: { src: "src/index.html", dest: "build/index.html" },
            htmlDebug: { src: "src/index-debug.html", dest: "build/index.html" },
            img: { expand: true, cwd: "src/img", src: "**", dest: "build/img/" }
        },
        watch: {
            styles: {
                files: ["src/style/**/*"],
                tasks: ["less", "notify:less"],
                options: {
                    spawn: false,
                    interrupt: true,
                    reload: true
                }
            },
            dictionaries: {
                files: ["src/nls/**/*"],
                tasks: ["i18n"],
                options: {
                    spawn: false,
                    interrupt: true
                }
            },
            sources: {
                files: ["src/**/*"],
                options: {
                    interval: 500
                }
            },
            dependencies: {
                files: ["package.json"],
                tasks: ["checkDependencies"]
            }
        },
        // Build tasks
        less: {
            style: {
                files: {
                    "build/style.css": "src/style/main.less"
                },
                options: {
                    sourceMap: grunt.option("DEV_MODE"),
                    sourceMapFileInline: true,
                    outputSourceFiles: true,
                    sourceMapRootpath: "../"
                }
            }
        },
        webpack: {
            options: require("./webpack.config.js"),
            compile: {
                watch: false
            },
            watch: {
                watch: true,
                keepalive: true,
                failOnError: false
            }
        },
        uglify: {
            design: {
                options: {
                    compress: {
                        unused: false // This saves us about half an hour, losing 200 KB
                    },
                    define: {
                        __PG_DEBUG__: false
                    }
                },
                files: ALL_LOCALES.reduce(function (map, locale) {
                    var target = "build/spaces-design-" + locale + ".js";

                    map[target] = [target];
                    return map;
                }, {})
            }
        },
        concurrent: {
            test: ["eslint", "jscs", "jsdoc", "jsonlint", "lintspaces"],
            build: {
                tasks: ["watch:styles", "watch:dictionaries", "watch:sources", "webpack:watch", "watch:dependencies"],
                options: {
                    logConcurrentOutput: true
                }
            }
        },
        notify: {
            less: {
                options: {
                    title: "LESS",
                    message: "Build Successful"
                }
            }
        },
        checkDependencies: {
            this: {}
        }
    });

    grunt.loadNpmTasks("grunt-eslint");
    grunt.loadNpmTasks("grunt-jscs");
    grunt.loadNpmTasks("grunt-jsdoc");
    grunt.loadNpmTasks("grunt-jsonlint");
    grunt.loadNpmTasks("grunt-lintspaces");

    grunt.loadNpmTasks("grunt-contrib-clean");
    grunt.loadNpmTasks("grunt-contrib-copy");
    grunt.loadNpmTasks("grunt-contrib-less");
    grunt.loadNpmTasks("grunt-contrib-uglify");
    grunt.loadNpmTasks("grunt-contrib-watch");

    grunt.loadNpmTasks("grunt-webpack");

    grunt.loadNpmTasks("grunt-concurrent");
    grunt.loadNpmTasks("grunt-concat-json");
    grunt.loadNpmTasks("grunt-merge-json");
    grunt.loadNpmTasks("grunt-notify");
    grunt.loadNpmTasks("grunt-check-dependencies");

    grunt.registerTask("seqtest", "Runs the linter tests sequentially",
        ["eslint", "jscs", "jsdoc", "jsonlint", "lintspaces"]
    );
    grunt.registerTask("test", "Runs linter tests",
        ["checkDependencies", "concurrent:test"]
    );
    grunt.registerTask("i18n", "Prepares the localization dictionaries",
        ["clean:i18n", "concat-json", "merge-json"]
    );
    grunt.registerTask("compile", "Bundles Design Space in Release mode, for all locales",
        ["checkDependencies", "test", "clean:build", "i18n", "copy:img", "copy:htmlRelease",
         "less", "webpack:compile", "uglify", "clean:i18n"]
    );
    grunt.registerTask("debug", "Bundles Design Space in Debug mode, for English only",
        ["checkDependencies", "clean", "i18n", "copy:img", "copy:htmlDebug", "less", "concurrent:build"]
    );
    grunt.registerTask("default", "Runs linter tests", ["test"]);
};
<|endoftext|>


<commit_before>/*
 * Copyright 2014 Apereo Foundation (AF) Licensed under the
 * Educational Community License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may
 * obtain a copy of the License at
 *
 *     http://opensource.org/licenses/ECL-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an "AS IS"
 * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */

module.exports = function(grunt) {
    var _ = require('underscore');
    var path = require('path');
    var shell = require('shelljs');
    var util = require('util');
    var mocha_grep = process.env['MOCHA_GREP'] || undefined;

    // Timeout used to determine when a test has failed
    var MOCHA_TIMEOUT = 60000;

    var regexErrors = false;

    // Project configuration.
    grunt.initConfig({
        'pkg': grunt.file.readJSON('package.json'),
        'jslint': {
            'files': [
                'Gruntfile.js',
                'node_modules/oae-*/lib/**/*.js',
                'node_modules/oae-*/tests/**/*.js',
                'node_modules/oae-*/config/**/*.js'
            ]
        },
        'jshint': {
            'options': {
                'node': true,
                'sub': true,
                'indent': 4,
                'trailing': true,
                'quotmark': 'single',
                'curly': true,
                'white': false,
                'strict': false,
                'globals': {
                    'it': true,
                    'describe': true,
                    'before': true,
                    'beforeEach': true,
                    'after': true,
                    'afterEach': true
                }
            },
            'files': '<%= jslint.files %>'
        },
        'mocha-hack': {
            'all': {
                'src': ['node_modules/oae-tests/runner/beforeTests.js', 'node_modules/oae-*/tests/**/*.js'],
                'options': {
                    'timeout': MOCHA_TIMEOUT,
                    'ignoreLeaks': true,
                    'reporter': 'spec',
                    'grep': mocha_grep,
                    'bail': false,
                    'slow': 500
                }
            }
        },
        'clean': ['target/'],
        'replace': {
            'check-style': {
                'src': ['node_modules/oae-*/**/*.js'],
                'overwrite': true,
                'replacements': [
                    {
                        'from': /@param (\S|\s\s)/,
                        'to': function(matchedWord, index, fullText, regexMatches) {
                            var msg ='@param should be followed by 2 spaces';
                            return logMatch(msg, matchedWord, index, fullText, regexMatches);
                        }
                    },
                    {
                        'from': /@return \s/,
                        'to': function(matchedWord, index, fullText, regexMatches) {
                            var msg ='@return should be followed by 1 space';
                            return logMatch(msg, matchedWord, index, fullText, regexMatches);
                        }
                    },
                    {
                        'from': /@returns/,
                        'to': function(matchedWord, index, fullText, regexMatches) {
                            var msg ='Use @return instead of @returns';
                            return logMatch(msg, matchedWord, index, fullText, regexMatches);
                        }
                    },
                    {
                        'from': /@throws \s/,
                        'to': function(matchedWord, index, fullText, regexMatches) {
                            var msg ='@throws should be followed by 1 space';
                            return logMatch(msg, matchedWord, index, fullText, regexMatches);
                        }
                    },
                    {
                        'from': /(tenant|globalAdmin)Server\.(get|post|put|head|del)\((.*)/,
                        'to': function(matchedWord, index, fullText, regexMatches) {
                            var msg = 'Do not use the tenantServer or globalAdminServer to bind routes. Use the Router object like this:\n\n  ' + regexMatches[0] + 'Router.on(\'' + regexMatches[1] + '\', ' + regexMatches[2];
                            return logMatch(msg, matchedWord, index, fullText, regexMatches);
                        }
                    }
                ]
            }
        }
    });

    // Utility function for logging regex matches
    var logMatch = function(msg, matchedWord, index, fullText, regexMatches) {
        var lineNum = fullText.substring(0, index).match(/\n/g).length + 1;
        var line = fullText.split('\n')[lineNum - 1];
        grunt.log.writeln(msg.red + ': ' + lineNum + ': ' + line);
        regexErrors = true;
        return matchedWord;
    };

    // Task to run the regex task and fail if it matches anything
    grunt.registerTask('check-style', ['replace', 'jshint', 'checkRegexErrors']);
    grunt.registerTask('checkRegexErrors', function() {
        grunt.task.requires('replace');
        if (regexErrors) {
            grunt.warn('Style rule validation failed');
        }
    });

    // Override default test task to use mocha-hack
    grunt.registerTask('test', ['mocha-hack']);

    // Make a task for running tests on a single module
    grunt.registerTask('test-module', 'Test a single module', function(module) {
        var config = {
            'src': ['node_modules/oae-tests/runner/beforeTests.js', 'node_modules/' + module + '/tests/**/*.js'],
            'options': {
                'timeout': MOCHA_TIMEOUT,
                'ignoreLeaks': true,
                'reporter': 'spec',
                'grep': mocha_grep
            }
        };
        grunt.config.set('mocha-hack.' + module, config);
        grunt.task.run('mocha-hack:' + module);
    });

    // Runs the unit tests and dumps some coverage data
    grunt.registerTask('test-instrumented', function(report) {
        // If no report format was provided, we default to `lcov` which generates lcov and html
        report = report || 'lcov';

        // Get the modules that should be excluded
        var nonOaeModules = grunt.file.expand({'filter': 'isDirectory'}, 'node_modules/*', '!node_modules/oae-*');
        var nonOaeModulesParameters = _.map(nonOaeModules, function(module) {
            return util.format('-x %s/\\*\\*', module);
        });

        // Exclude the tests from the coverage reports
        var oaeModules = grunt.file.expand({'filter': 'isDirectory'}, 'node_modules/oae-*');
        var testDirectories = _.map(oaeModules, function(directory) {
            return util.format('-x %s/tests/\\*\\*', directory);
        });
        var testUtilDirectories = _.map(oaeModules, function(directory) {
            return util.format('-x %s/lib/test/\\*\\*', directory);
        });

        // Exclude the config directories
        var configDirectories = _.map(oaeModules, function(module) {
            return util.format('-x %s/config/\\*\\*', module);
        });

        // Build up one big set of exlusion filters
        var excludeFilters = _.union(nonOaeModulesParameters, testDirectories, testUtilDirectories, configDirectories);
        excludeFilters.push('-x Gruntfile.js');

        var cmd = util.format('node_modules/.bin/istanbul cover --verbose --dir target --no-default-excludes %s --report %s ./node_modules/grunt-cli/bin/grunt', excludeFilters.join(' '), report);
        var code = shell.exec(cmd).code;
        if (code !== 0) {
            process.exit(code);
        }
    });

    // Sends a coverage report to coveralls.io
    grunt.registerTask('coveralls', function() {
        // This assumes we're executing within the context of Travis CI
        // If not, you'll have to add a .converalls.yml file with `repo_token: ...` in it
        shell.exec('cat ./target/lcov.info | ./node_modules/coveralls/bin/coveralls.js');
    });

    // Run test coverage and open the report
    grunt.registerTask('test-coverage', ['clean', 'test-instrumented', 'showFile:target/lcov-report/index.html']);

    // Run test coverage
    grunt.registerTask('test-coverage-coveralls', ['clean', 'test-instrumented:lcovonly', 'coveralls']);

    // Make a task to open the browser
    grunt.registerTask('showFile', 'Open a file with the OS default viewer', function(file) {
        var browser = shell.env['BROWSER'];
        if (! browser) {
            if (process.platform === 'linux') {
                browser = 'xdg-open';
            } else if (process.platform === 'darwin') {
                browser = 'open';
            } else if (process.platform === 'win32') {
                browser = 'explorer.exe';
            }
        }
        if (browser) {
            shell.exec(browser + ' '  + ( file || 'target/coverage.html' ));
        }
    });

    // Bring in tasks from npm
    // Temporary work around till https://github.com/yaymukund/grunt-simple-mocha/issues/16 lands.
    grunt.loadNpmTasks('grunt-mocha-hack');
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-contrib-clean');
    grunt.loadNpmTasks('grunt-text-replace');

    // Copies the files that need to go in the release.
    // We remove the test files and the Grunt file as it could be potentially
    // devestating to run the tests in a production environment.
    // Example:
    //     grunt release:/tmp/release
    // will copy only those files you really need in order to run Hilary in a folder at `/tmp/release`.
    grunt.registerTask('release', function(outputDir) {
        if (!outputDir) {
            return grunt.log.writeln('Please provide a path where the files should be copied to'.red);
        }

        shell.exec('bin/package -so ' + outputDir);
    });

    // Default task.
    grunt.registerTask('default', ['check-style', 'test']);

};
<commit_msg>(Gruntfile) Exclude node_modules of external oae-* modules<commit_after>/*
 * Copyright 2014 Apereo Foundation (AF) Licensed under the
 * Educational Community License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may
 * obtain a copy of the License at
 *
 *     http://opensource.org/licenses/ECL-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an "AS IS"
 * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */

module.exports = function(grunt) {
    var _ = require('underscore');
    var path = require('path');
    var shell = require('shelljs');
    var util = require('util');
    var mocha_grep = process.env['MOCHA_GREP'] || undefined;

    // Timeout used to determine when a test has failed
    var MOCHA_TIMEOUT = 60000;

    var regexErrors = false;

    // Project configuration.
    grunt.initConfig({
        'pkg': grunt.file.readJSON('package.json'),
        'jslint': {
            'files': [
                'Gruntfile.js',
                'node_modules/oae-*/lib/**/*.js',
                'node_modules/oae-*/tests/**/*.js',
                'node_modules/oae-*/config/**/*.js'
            ]
        },
        'jshint': {
            'options': {
                'node': true,
                'sub': true,
                'indent': 4,
                'trailing': true,
                'quotmark': 'single',
                'curly': true,
                'white': false,
                'strict': false,
                'globals': {
                    'it': true,
                    'describe': true,
                    'before': true,
                    'beforeEach': true,
                    'after': true,
                    'afterEach': true
                }
            },
            'files': '<%= jslint.files %>'
        },
        'mocha-hack': {
            'all': {
                'src': ['node_modules/oae-tests/runner/beforeTests.js', 'node_modules/oae-*/tests/**/*.js'],
                'options': {
                    'timeout': MOCHA_TIMEOUT,
                    'ignoreLeaks': true,
                    'reporter': 'spec',
                    'grep': mocha_grep,
                    'bail': false,
                    'slow': 500
                }
            }
        },
        'clean': ['target/'],
        'replace': {
            'check-style': {
                'src': ['node_modules/oae-*/**/*.js', '!node_modules/oae-*/node_modules/**/*.js'],
                'overwrite': true,
                'replacements': [
                    {
                        'from': /@param (\S|\s\s)/,
                        'to': function(matchedWord, index, fullText, regexMatches) {
                            var msg ='@param should be followed by 2 spaces';
                            return logMatch(msg, matchedWord, index, fullText, regexMatches);
                        }
                    },
                    {
                        'from': /@return \s/,
                        'to': function(matchedWord, index, fullText, regexMatches) {
                            var msg ='@return should be followed by 1 space';
                            return logMatch(msg, matchedWord, index, fullText, regexMatches);
                        }
                    },
                    {
                        'from': /@returns/,
                        'to': function(matchedWord, index, fullText, regexMatches) {
                            var msg ='Use @return instead of @returns';
                            return logMatch(msg, matchedWord, index, fullText, regexMatches);
                        }
                    },
                    {
                        'from': /@throws \s/,
                        'to': function(matchedWord, index, fullText, regexMatches) {
                            var msg ='@throws should be followed by 1 space';
                            return logMatch(msg, matchedWord, index, fullText, regexMatches);
                        }
                    },
                    {
                        'from': /(tenant|globalAdmin)Server\.(get|post|put|head|del)\((.*)/,
                        'to': function(matchedWord, index, fullText, regexMatches) {
                            var msg = 'Do not use the tenantServer or globalAdminServer to bind routes. Use the Router object like this:\n\n  ' + regexMatches[0] + 'Router.on(\'' + regexMatches[1] + '\', ' + regexMatches[2];
                            return logMatch(msg, matchedWord, index, fullText, regexMatches);
                        }
                    }
                ]
            }
        }
    });

    // Utility function for logging regex matches
    var logMatch = function(msg, matchedWord, index, fullText, regexMatches) {
        var lineNum = fullText.substring(0, index).match(/\n/g).length + 1;
        var line = fullText.split('\n')[lineNum - 1];
        grunt.log.writeln(msg.red + ': ' + lineNum + ': ' + line);
        regexErrors = true;
        return matchedWord;
    };

    // Task to run the regex task and fail if it matches anything
    grunt.registerTask('check-style', ['replace', 'jshint', 'checkRegexErrors']);
    grunt.registerTask('checkRegexErrors', function() {
        grunt.task.requires('replace');
        if (regexErrors) {
            grunt.warn('Style rule validation failed');
        }
    });

    // Override default test task to use mocha-hack
    grunt.registerTask('test', ['mocha-hack']);

    // Make a task for running tests on a single module
    grunt.registerTask('test-module', 'Test a single module', function(module) {
        var config = {
            'src': ['node_modules/oae-tests/runner/beforeTests.js', 'node_modules/' + module + '/tests/**/*.js'],
            'options': {
                'timeout': MOCHA_TIMEOUT,
                'ignoreLeaks': true,
                'reporter': 'spec',
                'grep': mocha_grep
            }
        };
        grunt.config.set('mocha-hack.' + module, config);
        grunt.task.run('mocha-hack:' + module);
    });

    // Runs the unit tests and dumps some coverage data
    grunt.registerTask('test-instrumented', function(report) {
        // If no report format was provided, we default to `lcov` which generates lcov and html
        report = report || 'lcov';

        // Get the modules that should be excluded
        var nonOaeModules = grunt.file.expand({'filter': 'isDirectory'}, 'node_modules/*', '!node_modules/oae-*');
        var nonOaeModulesParameters = _.map(nonOaeModules, function(module) {
            return util.format('-x %s/\\*\\*', module);
        });

        // Exclude the tests from the coverage reports
        var oaeModules = grunt.file.expand({'filter': 'isDirectory'}, 'node_modules/oae-*');
        var testDirectories = _.map(oaeModules, function(directory) {
            return util.format('-x %s/tests/\\*\\*', directory);
        });
        var testUtilDirectories = _.map(oaeModules, function(directory) {
            return util.format('-x %s/lib/test/\\*\\*', directory);
        });

        // Exclude the config directories
        var configDirectories = _.map(oaeModules, function(module) {
            return util.format('-x %s/config/\\*\\*', module);
        });

        // Build up one big set of exlusion filters
        var excludeFilters = _.union(nonOaeModulesParameters, testDirectories, testUtilDirectories, configDirectories);
        excludeFilters.push('-x Gruntfile.js');

        var cmd = util.format('node_modules/.bin/istanbul cover --verbose --dir target --no-default-excludes %s --report %s ./node_modules/grunt-cli/bin/grunt', excludeFilters.join(' '), report);
        var code = shell.exec(cmd).code;
        if (code !== 0) {
            process.exit(code);
        }
    });

    // Sends a coverage report to coveralls.io
    grunt.registerTask('coveralls', function() {
        // This assumes we're executing within the context of Travis CI
        // If not, you'll have to add a .converalls.yml file with `repo_token: ...` in it
        shell.exec('cat ./target/lcov.info | ./node_modules/coveralls/bin/coveralls.js');
    });

    // Run test coverage and open the report
    grunt.registerTask('test-coverage', ['clean', 'test-instrumented', 'showFile:target/lcov-report/index.html']);

    // Run test coverage
    grunt.registerTask('test-coverage-coveralls', ['clean', 'test-instrumented:lcovonly', 'coveralls']);

    // Make a task to open the browser
    grunt.registerTask('showFile', 'Open a file with the OS default viewer', function(file) {
        var browser = shell.env['BROWSER'];
        if (! browser) {
            if (process.platform === 'linux') {
                browser = 'xdg-open';
            } else if (process.platform === 'darwin') {
                browser = 'open';
            } else if (process.platform === 'win32') {
                browser = 'explorer.exe';
            }
        }
        if (browser) {
            shell.exec(browser + ' '  + ( file || 'target/coverage.html' ));
        }
    });

    // Bring in tasks from npm
    // Temporary work around till https://github.com/yaymukund/grunt-simple-mocha/issues/16 lands.
    grunt.loadNpmTasks('grunt-mocha-hack');
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-contrib-clean');
    grunt.loadNpmTasks('grunt-text-replace');

    // Copies the files that need to go in the release.
    // We remove the test files and the Grunt file as it could be potentially
    // devestating to run the tests in a production environment.
    // Example:
    //     grunt release:/tmp/release
    // will copy only those files you really need in order to run Hilary in a folder at `/tmp/release`.
    grunt.registerTask('release', function(outputDir) {
        if (!outputDir) {
            return grunt.log.writeln('Please provide a path where the files should be copied to'.red);
        }

        shell.exec('bin/package -so ' + outputDir);
    });

    // Default task.
    grunt.registerTask('default', ['check-style', 'test']);

};
<|endoftext|>


<commit_before>module.exports = function(grunt) {
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    concat: {
      options: {
        separator: ';\n',
        banner: '/*!\n'
              + ' * Selectors.js - https://github.com/JamesDonnelly/Selectors.js\n\n'
              + ' * Released under the MIT license\n'
              + ' * https://github.com/JamesDonnelly/Selectors.js/blob/master/LICENSE.md\n\n'
              + ' * Last built: <%= grunt.template.today("dddd, dS mmmm yyyy; h:MM:ss TT") %>\n'
              + ' */\n\n'
              + '"use strict";',
        process: function(src, filepath) {
          return '\n/* Source: ' + filepath
              + '\n * -------------------------------------------------------------------------------------'
              + src.replace(/^\/\* https:\/\/github.com\/JamesDonnelly\/Selectors\.js/, '');
        },
      },
      dist: {
        src: [
          'src/selectors.js',
          'src/helper.js',
          'src/W3Core.js',
          'src/W3Extended.js',
          'src/W3Grammar.js',
          'src/pseudo.js'
        ],
        dest: 'dist/selectors.js'
      }
    },
    uglify: {
      options: {
        banner: '/*! Selectors.js v<%= pkg.version %> | '
						  + '(c) https://github.com/JamesDonnelly/Selectors.js | https://github.com/JamesDonnelly/Selectors.js/blob/master/LICENSE.md */\n',
      },
      dist: {
        files: {
          'dist/selectors.min.js': ['dist/selectors.js']
        }
      }
    },
    jasmine: {
      coverage: {
        src: "dist/selectors.min.js",
        options: {
          specs: "test/**/*.js",
          template: require('grunt-template-jasmine-istanbul'),
          templateOptions: {
            coverage: 'bin/coverage/coverage.json',
            report: {
              type: 'lcov',
              options: {
                dir: 'bin/coverage/lcov'
              }
            },
            thresholds: {
              lines: 50,
              statements: 50,
              branches: 50,
              functions: 50
            }
          }
        }
      }
    }
  });

  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-jasmine');
  grunt.loadNpmTasks('grunt-coveralls');

  grunt.registerTask('test', ['jasmine', 'coveralls']);
  grunt.registerTask('default', ['concat', 'uglify', 'jasmine']);
};<commit_msg>And again...<commit_after>module.exports = function(grunt) {
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    concat: {
      options: {
        separator: ';\n',
        banner: '/*!\n'
              + ' * Selectors.js - https://github.com/JamesDonnelly/Selectors.js\n\n'
              + ' * Released under the MIT license\n'
              + ' * https://github.com/JamesDonnelly/Selectors.js/blob/master/LICENSE.md\n\n'
              + ' * Last built: <%= grunt.template.today("dddd, dS mmmm yyyy; h:MM:ss TT") %>\n'
              + ' */\n\n'
              + '"use strict";',
        process: function(src, filepath) {
          return '\n/* Source: ' + filepath
              + '\n * -------------------------------------------------------------------------------------'
              + src.replace(/^\/\* https:\/\/github.com\/JamesDonnelly\/Selectors\.js/, '');
        },
      },
      dist: {
        src: [
          'src/selectors.js',
          'src/helper.js',
          'src/W3Core.js',
          'src/W3Extended.js',
          'src/W3Grammar.js',
          'src/pseudo.js'
        ],
        dest: 'dist/selectors.js'
      }
    },
    uglify: {
      options: {
        banner: '/*! Selectors.js v<%= pkg.version %> | '
						  + '(c) https://github.com/JamesDonnelly/Selectors.js | https://github.com/JamesDonnelly/Selectors.js/blob/master/LICENSE.md */\n',
      },
      dist: {
        files: {
          'dist/selectors.min.js': ['dist/selectors.js']
        }
      }
    },
    jasmine: {
      coverage: {
        src: "dist/selectors.min.js",
        options: {
          specs: "test/**/*.js",
          template: require('grunt-template-jasmine-istanbul'),
          templateOptions: {
            coverage: 'bin/coverage/coverage.json',
            report: {
              type: 'lcov',
              options: {
                dir: 'bin/coverage/lcov'
              }
            },
            thresholds: {
              lines: 50,
              statements: 50,
              branches: 50,
              functions: 50
            }
          }
        }
      }
    }
  });

  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-jasmine');

  grunt.registerTask('test', ['jasmine']);
  grunt.registerTask('default', ['concat', 'uglify', 'jasmine']);
};<|endoftext|>


<commit_before>//need to allow script urls so that mocha: works below
/* jshint scripturl:true */
module.exports = function(grunt) {
    var glob = require('glob'),
        source = glob.sync('src/**/*.js').filter(function(v) { return v.indexOf('vendor') === -1; }),
        testPort = grunt.option('port-test') || 9002;
        //banner = [
        //    '/**',
        //    ' * @license',
        //    ' * <%= pkg.longName %> - v<%= pkg.version %>',
        //    ' * Copyright (c) 2012, Chad Engler',
        //    ' * <%= pkg.homepage %>',
        //    ' *',
        //    ' * Compiled: <%= grunt.template.today("yyyy-mm-dd") %>',
        //    ' *',
        //    ' * <%= pkg.longName %> is licensed under the <%= pkg.license %> License.',
        //    ' * <%= pkg.licenseUrl %>',
        //    ' */',
        //    ''
        //].join('\n');

    //Project Configuration
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        dirs: {
            dist: 'build',
            docs: 'docs',
            src: 'src',
            test: 'test',
            tools: 'tools',
            vendor: 'vendor'
        },
        files: {
            dev: '<%= dirs.dist %>/<%= pkg.name %>.js',
            dist: '<%= dirs.dist %>/<%= pkg.name %>.min.js',
            main: 'core.js'
        },
        replace: {
            dist: {
                options: {
                    variables: {
                        'VERSION': '<%= pkg.version %>'
                    },
                    prefix: '@@'
                },
                files: [
                    {
                        expand: true,
                        flatten: true,
                        src: ['<%= files.dev %>', '<%= files.dist %>'],
                        dest: '<%= dirs.dist %>'
                    }
                ]
            }
        },
        jshint: {
            src: source.concat('Gruntfile.js'),
            options: {
                jshintrc: '.jshintrc'
            }
        },
        connect: {
            test: {
                options: {
                    port: testPort,
                    base: './'
                }
            },
            dev: {
                options: {
                    port: testPort,
                    base: './',
                    keepalive: true
                }
            }
        },
        yuidoc: {
            compile: {
                name: '<%= pkg.longName %>',
                description: '<%= pkg.description %>',
                version: 'v<%= pkg.version %>',
                url: '<%= pkg.homepage %>',
                logo: 'https://en.gravatar.com/userimage/49218683/8654d0c767f327312ebb1ace7f5a8d8d.png',
                options: {
                    paths: '<%= dirs.src %>',
                    exclude: 'vendor',
                    outdir: '<%= dirs.docs %>'
                }
            }
        },
        urequire: {
            dev: {
                template: 'combined',
                path: '<%= dirs.src %>',
                dstPath: '<%= files.dev %>',
                main: '<%= files.main %>'
            },

            dist: {
                template: 'combined',
                path: '<%= dirs.src %>',
                dstPath: '<%= files.dist %>',
                main: '<%= files.main %>',
                optimize: true
            },

            _defaults: {
                build: {
                    debugLevel: 0,
                    verbose: false,
                    scanAllow: true,
                    allNodeRequires: true,
                    noRootExports: false
                },
                dependencies: {
                    exports: {
                        root: {
                            'core': ['gf']
                        }
                    }
                }
            }
        },
        mocha: {
            dist: {
                src: ['test/unit/index.html'],
                options: {
                    mocha: {
                        ignoreLeaks: false,
                    },
                    log: true,
                    reporter: 'Spec',
                    run: true
                }
            }
        }
    });

    //xunit file directory, if none is passed
    if(!process.env.XUNIT_FILE)
        process.env.XUNIT_FILE = './test/result/unit.xml';

    //load npm tasks
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-contrib-connect');
    grunt.loadNpmTasks('grunt-contrib-yuidoc');
    grunt.loadNpmTasks('grunt-mocha');
    grunt.loadNpmTasks('grunt-replace');
    grunt.loadNpmTasks('grunt-urequire');

    //setup shortcut tasks
    grunt.registerTask('default', ['jshint', 'build']);
    grunt.registerTask('build', ['urequire:dev', 'urequire:dist', 'replace:dist']);
    grunt.registerTask('test', ['mocha:dist']);
    grunt.registerTask('testci', ['jshint', 'mocha:dist']);
    grunt.registerTask('docs', ['yuidoc']);
};<commit_msg>Add remote debugger items, but commented out<commit_after>//need to allow script urls so that mocha: works below
/* jshint scripturl:true */
module.exports = function(grunt) {
    var glob = require('glob'),
        source = glob.sync('src/**/*.js').filter(function(v) { return v.indexOf('vendor') === -1; }),
        testPort = grunt.option('port-test') || 9002;
        //banner = [
        //    '/**',
        //    ' * @license',
        //    ' * <%= pkg.longName %> - v<%= pkg.version %>',
        //    ' * Copyright (c) 2012, Chad Engler',
        //    ' * <%= pkg.homepage %>',
        //    ' *',
        //    ' * Compiled: <%= grunt.template.today("yyyy-mm-dd") %>',
        //    ' *',
        //    ' * <%= pkg.longName %> is licensed under the <%= pkg.license %> License.',
        //    ' * <%= pkg.licenseUrl %>',
        //    ' */',
        //    ''
        //].join('\n');

    //Project Configuration
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        dirs: {
            dist: 'build',
            docs: 'docs',
            src: 'src',
            test: 'test',
            tools: 'tools',
            vendor: 'vendor'
        },
        files: {
            dev: '<%= dirs.dist %>/<%= pkg.name %>.js',
            dist: '<%= dirs.dist %>/<%= pkg.name %>.min.js',
            main: 'core.js'
        },
        replace: {
            dist: {
                options: {
                    variables: {
                        'VERSION': '<%= pkg.version %>'
                    },
                    prefix: '@@'
                },
                files: [
                    {
                        expand: true,
                        flatten: true,
                        src: ['<%= files.dev %>', '<%= files.dist %>'],
                        dest: '<%= dirs.dist %>'
                    }
                ]
            }
        },
        jshint: {
            src: source.concat('Gruntfile.js'),
            options: {
                jshintrc: '.jshintrc'
            }
        },
        connect: {
            test: {
                options: {
                    port: testPort,
                    base: './'
                }
            },
            dev: {
                options: {
                    port: testPort,
                    base: './',
                    keepalive: true
                }
            }
        },
        yuidoc: {
            compile: {
                name: '<%= pkg.longName %>',
                description: '<%= pkg.description %>',
                version: 'v<%= pkg.version %>',
                url: '<%= pkg.homepage %>',
                logo: 'https://en.gravatar.com/userimage/49218683/8654d0c767f327312ebb1ace7f5a8d8d.png',
                options: {
                    paths: '<%= dirs.src %>',
                    exclude: 'vendor',
                    outdir: '<%= dirs.docs %>'
                }
            }
        },
        urequire: {
            dev: {
                template: 'combined',
                path: '<%= dirs.src %>',
                dstPath: '<%= files.dev %>',
                main: '<%= files.main %>'
            },

            dist: {
                template: 'combined',
                path: '<%= dirs.src %>',
                dstPath: '<%= files.dist %>',
                main: '<%= files.main %>',
                optimize: true
            },

            _defaults: {
                build: {
                    debugLevel: 0,
                    verbose: false,
                    scanAllow: true,
                    allNodeRequires: true,
                    noRootExports: false
                },
                dependencies: {
                    exports: {
                        root: {
                            'core': ['gf']
                        }
                    }
                }
            }
        },
        mocha: {
            dist: {
                src: ['test/unit/index.html'],
                options: {
                    mocha: {
                        ignoreLeaks: false,
                    },
                    log: true,
                    reporter: 'Spec',
                    run: true/*,
                    '--remote-debugger-port': 9000,
                    '--proxy-type=none': 'none'*/
                }
            }
        }
    });

    //xunit file directory, if none is passed
    if(!process.env.XUNIT_FILE)
        process.env.XUNIT_FILE = './test/result/unit.xml';

    //load npm tasks
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-contrib-connect');
    grunt.loadNpmTasks('grunt-contrib-yuidoc');
    grunt.loadNpmTasks('grunt-mocha');
    grunt.loadNpmTasks('grunt-replace');
    grunt.loadNpmTasks('grunt-urequire');

    //setup shortcut tasks
    grunt.registerTask('default', ['jshint', 'build']);
    grunt.registerTask('build', ['urequire:dev', 'urequire:dist', 'replace:dist']);
    grunt.registerTask('test', ['mocha:dist']);
    grunt.registerTask('testci', ['jshint', 'mocha:dist']);
    grunt.registerTask('docs', ['yuidoc']);
};<|endoftext|>


<commit_before>/*global module*/

module.exports = function (grunt) {
    'use strict';

    // Define the configuration for all the tasks
    grunt.initConfig({
        copy: {
            test_build: {
                src: 'build/*',
                dest: 'src/javascripts/test/fixtures/examples/blog/'
            },
            test_sample_app: {
                src: 'examples/blog/*',
                dest: 'src/javascripts/test/fixtures/',
                options: {
                    process: function(content) {
                        return content.replace(/http\:\/\/localhost\:8000\//g, '/');
                    }
                }
            },
            test_fakerest: {
                src: 'node_modules/fakerest/dist/FakeRest.min.js',
                dest: 'src/javascripts/test/fixtures/examples/blog/build/fakerest.js'
            },
            test_sinon_server: {
                src: 'node_modules/sinon/pkg/sinon-server-1.16.1.js',
                dest: 'src/javascripts/test/fixtures/examples/blog/build/sinon-server.js'
            }
        },
        connect: {
            dev: {
                options: {
                    port: 8000,
                    base: 'examples/blog/',
                    keepalive: false,
                    livereload: false
                }
            },
            test: {
                options: {
                    port: 8001,
                    base: 'src/javascripts/test/fixtures/examples/blog/',
                    keepalive: false,
                    livereload: false
                }
            }
        },
        karma: {
            unit: {
                configFile: 'src/javascripts/test/karma.conf.js',
                singleRun: process.env.KARMA_SINGLE_RUN !== 'false'
            }
        },
        protractor: {
            e2e: {
                configFile: 'src/javascripts/test/protractor.conf.js',
                keepAlive: true,
                debug: true
            }
        },
        exec: {
            webpack: './node_modules/webpack/bin/webpack.js'
        }
    });

    grunt.loadNpmTasks('grunt-contrib-connect');
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-exec');
    grunt.loadNpmTasks('grunt-protractor-runner');
    grunt.loadNpmTasks('grunt-karma');
    grunt.loadNpmTasks('grunt-mocha-test');

    grunt.registerTask('test', ['karma', 'test:e2e']);
    grunt.registerTask('test:e2e', ['test:e2e:prepare', 'connect:test', 'protractor']);
    grunt.registerTask('test:e2e:prepare', ['exec:webpack', 'copy:test_sample_app', 'copy:test_build', 'copy:test_fakerest', 'copy:test_sinon_server']);

    grunt.registerTask('test:local', ['karma', 'test:local:e2e']);
    grunt.registerTask('test:local:e2e', ['test:e2e:prepare', 'connect:test', 'protractor']);
};
<commit_msg>use sinon 14.1 in grunt too<commit_after>/*global module*/

module.exports = function (grunt) {
    'use strict';

    // Define the configuration for all the tasks
    grunt.initConfig({
        copy: {
            test_build: {
                src: 'build/*',
                dest: 'src/javascripts/test/fixtures/examples/blog/'
            },
            test_sample_app: {
                src: 'examples/blog/*',
                dest: 'src/javascripts/test/fixtures/',
                options: {
                    process: function(content) {
                        return content.replace(/http\:\/\/localhost\:8000\//g, '/');
                    }
                }
            },
            test_fakerest: {
                src: 'node_modules/fakerest/dist/FakeRest.min.js',
                dest: 'src/javascripts/test/fixtures/examples/blog/build/fakerest.js'
            },
            test_sinon_server: {
                src: 'node_modules/sinon/pkg/sinon-server-1.14.1.js',
                dest: 'src/javascripts/test/fixtures/examples/blog/build/sinon-server.js'
            }
        },
        connect: {
            dev: {
                options: {
                    port: 8000,
                    base: 'examples/blog/',
                    keepalive: false,
                    livereload: false
                }
            },
            test: {
                options: {
                    port: 8001,
                    base: 'src/javascripts/test/fixtures/examples/blog/',
                    keepalive: false,
                    livereload: false
                }
            }
        },
        karma: {
            unit: {
                configFile: 'src/javascripts/test/karma.conf.js',
                singleRun: process.env.KARMA_SINGLE_RUN !== 'false'
            }
        },
        protractor: {
            e2e: {
                configFile: 'src/javascripts/test/protractor.conf.js',
                keepAlive: true,
                debug: true
            }
        },
        exec: {
            webpack: './node_modules/webpack/bin/webpack.js'
        }
    });

    grunt.loadNpmTasks('grunt-contrib-connect');
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-exec');
    grunt.loadNpmTasks('grunt-protractor-runner');
    grunt.loadNpmTasks('grunt-karma');
    grunt.loadNpmTasks('grunt-mocha-test');

    grunt.registerTask('test', ['karma', 'test:e2e']);
    grunt.registerTask('test:e2e', ['test:e2e:prepare', 'connect:test', 'protractor']);
    grunt.registerTask('test:e2e:prepare', ['exec:webpack', 'copy:test_sample_app', 'copy:test_build', 'copy:test_fakerest', 'copy:test_sinon_server']);

    grunt.registerTask('test:local', ['karma', 'test:local:e2e']);
    grunt.registerTask('test:local:e2e', ['test:e2e:prepare', 'connect:test', 'protractor']);
};
<|endoftext|>


<commit_before>/* jshint node: true */

module.exports = function(grunt) {
  "use strict";

  // Project configuration.
  grunt.initConfig({

    // Metadata.
    pkg: grunt.file.readJSON('package.json'),
    banner: '/*!\n' +
              ' * TODC Bootstrap v<%= pkg.version %> by todc\n' +
              ' *\n' +
              ' * Copyright <%= grunt.template.today("yyyy") %> <%= pkg.author %>\n' +
              ' * Licensed under the <%= _.pluck(pkg.licenses, "type").join(", ") %> License\n' +
              ' * <%= _.pluck(pkg.licenses, "url").join(", ") %>\n' +
              ' *\n' +
              ' * This is a Google style theme that is intended to be used on top of Bootstrap.\n' +
              ' *\n' +
              ' * Constructed by Tim O\'Donnell (http://github.com/todc)\n' +
              ' */\n\n',
    jqueryCheck: 'if (typeof jQuery === "undefined") { throw new Error("Bootstrap requires jQuery") }\n\n',

    // Bootstrap variables
    bootstrapDir: 'bootstrap',
    bootstrapGit: 'https://github.com/twbs/bootstrap.git',
    bootstrapVersion: 'v3.0.0',

    // Task configuration.
    clean: {
      dist: ['dist']
    },

    recess: {
      options: {
        compile: true,
        banner: '<%= banner %>'
      },
      todc_bootstrap: {
        src: ['less/todc-bootstrap.less'],
        dest: 'dist/css/<%= pkg.name %>.css'
      },
      min: {
        options: {
          compress: true
        },
        src: ['less/todc-bootstrap.less'],
        dest: 'dist/css/<%= pkg.name %>.min.css'
      }
    },

    copy: {
      images: {
        expand: true,
        src: ["img/*"],
        dest: 'dist/'
      },
      bootstrap: {
        expand: true,
        flatten: false,
        cwd: '<%= bootstrapDir %>/dist',
        src: '**',
        dest: 'dist/'
      }
    },

    compress: {
      main: {
        options: {
          archive: 'dist/<%= pkg.name %>-<%= pkg.version %>-dist.zip',
          mode: 'zip',
          pretty: true
        },
        expand: true,
        cwd: 'dist',
        src: '**',
        dest: 'todc-bootstrap/'
      }
    },

    jekyll: {
      docs: {}
    },

    validation: {
      options: {
        reset: true,
        relaxerror: [
            "Bad value X-UA-Compatible for attribute http-equiv on element meta.",
            "Element img is missing required attribute src."
        ]
      },
      files: {
        src: ["_gh_pages/**/*.html"]
      }
    },

    watch: {
      recess: {
        files: 'less/*.less',
        tasks: ['recess']
      }
    },

    // checkout-bootstrap task
    shell: {
      gitclone: {
        command: 'git clone <%= bootstrapGit %> <%= bootstrapDir %>',
        options: {
          failOnError: true,
          stderr: true,
          stdout: true
        }
      },
      gitcheckout: {
        command: 'git checkout tags/<%= bootstrapVersion %>',
        options: {
          stderr: true,
          stdout: true,
          execOptions: {
            cwd: '<%= bootstrapDir %>'
          }
        }
      }
    }
  });

  // These plugins provide necessary tasks.
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-compress');
  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-html-validation');
  grunt.loadNpmTasks('grunt-jekyll');
  grunt.loadNpmTasks('grunt-recess');
  grunt.loadNpmTasks('grunt-shell');

  // Clone bootstrap and checkout the appropriate tag task.
  grunt.registerTask('checkout-bootstrap', ['shell']);

  // Docs HTML validation task
  grunt.registerTask('validate-html', ['jekyll', 'validation']);

  // CSS distribution task.
  grunt.registerTask('dist-css', ['recess']);

  // // Full distribution task.
  // grunt.registerTask('dist', ['clean', 'dist-css', 'dist-fonts', 'dist-js']);
  grunt.registerTask('dist', ['clean', 'dist-css', 'copy']);

  // // Default task.
  grunt.registerTask('default', ['dist']);
};
<commit_msg>update bootstrapVersion to 3.0.1<commit_after>/* jshint node: true */

module.exports = function(grunt) {
  "use strict";

  // Project configuration.
  grunt.initConfig({

    // Metadata.
    pkg: grunt.file.readJSON('package.json'),
    banner: '/*!\n' +
              ' * TODC Bootstrap v<%= pkg.version %> by todc\n' +
              ' *\n' +
              ' * Copyright <%= grunt.template.today("yyyy") %> <%= pkg.author %>\n' +
              ' * Licensed under the <%= _.pluck(pkg.licenses, "type").join(", ") %> License\n' +
              ' * <%= _.pluck(pkg.licenses, "url").join(", ") %>\n' +
              ' *\n' +
              ' * This is a Google style theme that is intended to be used on top of Bootstrap.\n' +
              ' *\n' +
              ' * Constructed by Tim O\'Donnell (http://github.com/todc)\n' +
              ' */\n\n',
    jqueryCheck: 'if (typeof jQuery === "undefined") { throw new Error("Bootstrap requires jQuery") }\n\n',

    // Bootstrap variables
    bootstrapDir: 'bootstrap',
    bootstrapGit: 'https://github.com/twbs/bootstrap.git',
    bootstrapVersion: 'v3.0.1',

    // Task configuration.
    clean: {
      dist: ['dist']
    },

    recess: {
      options: {
        compile: true,
        banner: '<%= banner %>'
      },
      todc_bootstrap: {
        src: ['less/todc-bootstrap.less'],
        dest: 'dist/css/<%= pkg.name %>.css'
      },
      min: {
        options: {
          compress: true
        },
        src: ['less/todc-bootstrap.less'],
        dest: 'dist/css/<%= pkg.name %>.min.css'
      }
    },

    copy: {
      images: {
        expand: true,
        src: ["img/*"],
        dest: 'dist/'
      },
      bootstrap: {
        expand: true,
        flatten: false,
        cwd: '<%= bootstrapDir %>/dist',
        src: '**',
        dest: 'dist/'
      }
    },

    compress: {
      main: {
        options: {
          archive: 'dist/<%= pkg.name %>-<%= pkg.version %>-dist.zip',
          mode: 'zip',
          pretty: true
        },
        expand: true,
        cwd: 'dist',
        src: '**',
        dest: 'todc-bootstrap/'
      }
    },

    jekyll: {
      docs: {}
    },

    validation: {
      options: {
        reset: true,
        relaxerror: [
            "Bad value X-UA-Compatible for attribute http-equiv on element meta.",
            "Element img is missing required attribute src."
        ]
      },
      files: {
        src: ["_gh_pages/**/*.html"]
      }
    },

    watch: {
      recess: {
        files: 'less/*.less',
        tasks: ['recess']
      }
    },

    // checkout-bootstrap task
    shell: {
      gitclone: {
        command: 'git clone <%= bootstrapGit %> <%= bootstrapDir %>',
        options: {
          failOnError: true,
          stderr: true,
          stdout: true
        }
      },
      gitcheckout: {
        command: 'git checkout tags/<%= bootstrapVersion %>',
        options: {
          stderr: true,
          stdout: true,
          execOptions: {
            cwd: '<%= bootstrapDir %>'
          }
        }
      }
    }
  });

  // These plugins provide necessary tasks.
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-compress');
  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-html-validation');
  grunt.loadNpmTasks('grunt-jekyll');
  grunt.loadNpmTasks('grunt-recess');
  grunt.loadNpmTasks('grunt-shell');

  // Clone bootstrap and checkout the appropriate tag task.
  grunt.registerTask('checkout-bootstrap', ['shell']);

  // Docs HTML validation task
  grunt.registerTask('validate-html', ['jekyll', 'validation']);

  // CSS distribution task.
  grunt.registerTask('dist-css', ['recess']);

  // // Full distribution task.
  // grunt.registerTask('dist', ['clean', 'dist-css', 'dist-fonts', 'dist-js']);
  grunt.registerTask('dist', ['clean', 'dist-css', 'copy']);

  // // Default task.
  grunt.registerTask('default', ['dist']);
};
<|endoftext|>


<commit_before>var os = require("os");

var now = new Date().toISOString();

function shallowCopy(obj) {
	var result = {};
	Object.keys(obj).forEach(function (key) {
		result[key] = obj[key];
	});
	return result;
}

function getBuildVersion(version) {
	var buildVersion = version !== undefined ? version : process.env["BUILD_NUMBER"];
	if (process.env["BUILD_CAUSE_GHPRBCAUSE"]) {
		buildVersion = "PR" + buildVersion;
	}

	return buildVersion;
}

module.exports = function (grunt) {

	// Windows cmd does not accept paths with / and unix shell does not accept paths with \\ and we need to execute from a sub-dir.
	// To circumvent the issue, hack our environment's PATH and let the OS deal with it, which in practice works
	process.env.path = process.env.path + (os.platform() === "win32" ? ";" : ":") + "node_modules/.bin";

	var isPackageJsonModified = false;

	var defaultEnvironment = "sit";
	// When there are node_modules inside lib\common directory, CLI behaves incorrectly, so delete this dir.
	var path = require("path");
	var commonLibNodeModules = path.join("lib", "common", "node_modules");
	if (require("fs").existsSync(commonLibNodeModules)) {
		grunt.file.delete(commonLibNodeModules);
	}
	grunt.file.write(path.join("lib", "common", ".d.ts"), "");

	grunt.initConfig({
		deploymentEnvironment: process.env["DeploymentEnvironment"] || defaultEnvironment,
		resourceDownloadEnvironment: process.env["ResourceDownloadEnvironment"] || defaultEnvironment,
		jobName: process.env["JOB_NAME"] || defaultEnvironment,
		buildNumber: process.env["BUILD_NUMBER"] || "non-ci",
		dateString: now.substr(0, now.indexOf("T")),

		pkg: grunt.file.readJSON("package.json"),
		ts: {
			options: {
				target: 'es5',
				module: 'commonjs',
				sourceMap: true,
				declaration: false,
				removeComments: false,
				noImplicitAny: true,
				experimentalDecorators: true
			},

			devlib: {
				src: ["lib/**/*.ts", "!lib/common/node_modules/**/*.ts", "!lib/common/messages/**/*.ts"],
				reference: "lib/.d.ts"
			},

			devall: {
				src: ["lib/**/*.ts", "test/**/*.ts", "!lib/common/node_modules/**/*.ts", "lib/common/test/unit-tests/**/*.ts", "definitions/**/*.ts", "!lib/common/test/.d.ts", "!lib/common/messages/**/*.ts"],
				reference: "lib/.d.ts"
			},

			release_build: {
				src: ["lib/**/*.ts", "test/**/*.ts", "!lib/common/node_modules/**/*.ts", "!lib/common/messages/**/*.ts"],
				reference: "lib/.d.ts",
				options: {
					sourceMap: false,
					removeComments: true
				}
			}
		},

		tslint: {
            build: {
                files: {
                    src: ["lib/**/*.ts", "test/**/*.ts", "!lib/common/node_modules/**/*.ts", "!lib/common/messages/**/*.ts", "lib/common/test/unit-tests/**/*.ts", "definitions/**/*.ts", "!**/*.d.ts"]
                },
                options: {
                    configuration: grunt.file.readJSON("./tslint.json")
                }
            }
        },

		watch: {
			devall: {
				files: ["lib/**/*.ts", 'test/**/*.ts', "!lib/common/node_modules/**/*.ts", "!lib/common/messages/**/*.ts"],
				tasks: ['ts:devall'],
				options: {
					atBegin: true,
					interrupt: true
				}
			}
		},

		shell: {
			options: {
				stdout: true,
				stderr: true
			},

			apply_resources_environment: {
				command: "node bin/appbuilder.js dev-config-apply <%= resourceDownloadEnvironment %>"
			},

			prepare_resources: {
				command: "node bin/appbuilder.js dev-prepackage"
			},

			ci_unit_tests: {
				command: "npm test",
				options: {
					execOptions: {
						env: (function () {
							var env = shallowCopy(process.env);
							env["XUNIT_FILE"] = "test-reports.xml";
							env["LOG_XUNIT"] = "true";
							return env;
						})()
					}
				}
			},

			apply_deployment_environment: {
				command: "node bin/appbuilder.js dev-config-apply <%= deploymentEnvironment %>"
			},

			build_package: {
				command: "npm pack",
				options: {
					execOptions: {
						env: (function () {
							var env = shallowCopy(process.env);
							env["APPBUILDER_SKIP_POSTINSTALL_TASKS"] = "1";
							return env;
						})()
					}
				}
			}
		},

		clean: {
			src: ["test/**/*.js*", "lib/**/*.js*", "!lib/common/vendor/*.js", "!lib/hooks/**/*.js", "!lib/common/**/*.json", "!lib/common/Gruntfile.js", "!lib/common/node_modules/**/*", "!lib/common/hooks/**/*.js", "!lib/common/bin/*.js", "*.tgz"]
		}
	});

	grunt.loadNpmTasks("grunt-contrib-clean");
	grunt.loadNpmTasks("grunt-contrib-watch");
	grunt.loadNpmTasks("grunt-shell");
	grunt.loadNpmTasks("grunt-ts");
	grunt.loadNpmTasks("grunt-tslint");

	grunt.registerTask("set_package_version", function (version) {
		var buildVersion = getBuildVersion(version);
		var packageJson = grunt.file.readJSON("package.json");
		packageJson.buildVersion = buildVersion;
		grunt.file.write("package.json", JSON.stringify(packageJson, null, "  "));
	});

	grunt.registerTask("setPackageName", function (version) {
		var fs = require("fs");
		var fileExtension = ".tgz";
		var buildVersion = getBuildVersion(version);
		var packageJson = grunt.file.readJSON("package.json");
		var oldFileName = packageJson.name + "-" + packageJson.version;
		var newFileName = oldFileName + "-" + buildVersion;
		fs.renameSync(oldFileName + fileExtension, newFileName + fileExtension);
	});

	grunt.registerTask("delete_coverage_dir", function () {
		var done = this.async();
		var rimraf = require("rimraf");
		rimraf("coverage", function (err) {
			if (err) {
				console.log("Error while deleting coverage directory from the package.");
				done(false);
			}

			done();
		});
	});

	grunt.registerTask("test", ["ts:devall", "shell:ci_unit_tests"]);

	grunt.registerTask("remove_prepublish_script", function () {
		var packageJson = grunt.file.readJSON("package.json");
		if (packageJson && packageJson.scripts && packageJson.scripts.prepublish) {
			delete packageJson.scripts.prepublish;
			grunt.file.write("package.json", JSON.stringify(packageJson, null, "  "));
			isPackageJsonModified = true;
		}
	});

	grunt.registerTask("printPackageJsonWarning", function () {
		if (isPackageJsonModified) {
			require("colors");
			console.log("NOTE: `grunt pack` command modified package.json. DO NOT COMMIT these changes, they are required only for the produced .tgz.".red.bold);
		}
	});

	grunt.registerTask("pack", [
		"clean",

		"ts:release_build",

		"remove_prepublish_script",

		"shell:apply_resources_environment",
		"shell:prepare_resources",
		"shell:apply_deployment_environment",
		"shell:ci_unit_tests",

		"set_package_version",
		"delete_coverage_dir",
		"shell:build_package",
		"setPackageName",
		"printPackageJsonWarning"
	]);
	grunt.registerTask("lint", ["tslint:build"]);
	grunt.registerTask("all", ["clean", "test", "lint"]);
	grunt.registerTask("rebuild", ["clean", "ts:devlib"]);
	grunt.registerTask("default", "ts:devlib");
};
<commit_msg>Add bundle-pack grunt task<commit_after>var os = require("os");

var now = new Date().toISOString();

function shallowCopy(obj) {
	var result = {};
	Object.keys(obj).forEach(function (key) {
		result[key] = obj[key];
	});
	return result;
}

function getBuildVersion(version) {
	var buildVersion = version !== undefined ? version : process.env["BUILD_NUMBER"];
	if (process.env["BUILD_CAUSE_GHPRBCAUSE"]) {
		buildVersion = "PR" + buildVersion;
	}

	return buildVersion;
}

module.exports = function (grunt) {

	// Windows cmd does not accept paths with / and unix shell does not accept paths with \\ and we need to execute from a sub-dir.
	// To circumvent the issue, hack our environment's PATH and let the OS deal with it, which in practice works
	process.env.path = process.env.path + (os.platform() === "win32" ? ";" : ":") + "node_modules/.bin";

	var isPackageJsonModified = false;

	var defaultEnvironment = "sit";
	// When there are node_modules inside lib\common directory, CLI behaves incorrectly, so delete this dir.
	var path = require("path");
	var commonLibNodeModules = path.join("lib", "common", "node_modules");
	if (require("fs").existsSync(commonLibNodeModules)) {
		grunt.file.delete(commonLibNodeModules);
	}
	grunt.file.write(path.join("lib", "common", ".d.ts"), "");

	grunt.initConfig({
		deploymentEnvironment: process.env["DeploymentEnvironment"] || defaultEnvironment,
		resourceDownloadEnvironment: process.env["ResourceDownloadEnvironment"] || defaultEnvironment,
		jobName: process.env["JOB_NAME"] || defaultEnvironment,
		buildNumber: process.env["BUILD_NUMBER"] || "non-ci",
		dateString: now.substr(0, now.indexOf("T")),

		pkg: grunt.file.readJSON("package.json"),
		ts: {
			options: {
				target: 'es5',
				module: 'commonjs',
				sourceMap: true,
				declaration: false,
				removeComments: false,
				noImplicitAny: true,
				experimentalDecorators: true
			},

			devlib: {
				src: ["lib/**/*.ts", "!lib/common/node_modules/**/*.ts", "!lib/common/messages/**/*.ts"],
				reference: "lib/.d.ts"
			},

			devall: {
				src: ["lib/**/*.ts", "test/**/*.ts", "!lib/common/node_modules/**/*.ts", "lib/common/test/unit-tests/**/*.ts", "definitions/**/*.ts", "!lib/common/test/.d.ts", "!lib/common/messages/**/*.ts"],
				reference: "lib/.d.ts"
			},

			release_build: {
				src: ["lib/**/*.ts", "test/**/*.ts", "!lib/common/node_modules/**/*.ts", "!lib/common/messages/**/*.ts"],
				reference: "lib/.d.ts",
				options: {
					sourceMap: false,
					removeComments: true
				}
			}
		},

		tslint: {
            build: {
                files: {
                    src: ["lib/**/*.ts", "test/**/*.ts", "!lib/common/node_modules/**/*.ts", "!lib/common/messages/**/*.ts", "lib/common/test/unit-tests/**/*.ts", "definitions/**/*.ts", "!**/*.d.ts"]
                },
                options: {
                    configuration: grunt.file.readJSON("./tslint.json")
                }
            }
        },

		watch: {
			devall: {
				files: ["lib/**/*.ts", 'test/**/*.ts', "!lib/common/node_modules/**/*.ts", "!lib/common/messages/**/*.ts"],
				tasks: ['ts:devall'],
				options: {
					atBegin: true,
					interrupt: true
				}
			}
		},

		shell: {
			options: {
				stdout: true,
				stderr: true
			},

			apply_resources_environment: {
				command: "node bin/appbuilder.js dev-config-apply <%= resourceDownloadEnvironment %>"
			},

			prepare_resources: {
				command: "node bin/appbuilder.js dev-prepackage"
			},

			ci_unit_tests: {
				command: "npm test",
				options: {
					execOptions: {
						env: (function () {
							var env = shallowCopy(process.env);
							env["XUNIT_FILE"] = "test-reports.xml";
							env["LOG_XUNIT"] = "true";
							return env;
						})()
					}
				}
			},

			apply_deployment_environment: {
				command: "node bin/appbuilder.js dev-config-apply <%= deploymentEnvironment %>"
			},

			build_package: {
				command: "npm pack",
				options: {
					execOptions: {
						env: (function () {
							var env = shallowCopy(process.env);
							env["APPBUILDER_SKIP_POSTINSTALL_TASKS"] = "1";
							return env;
						})()
					}
				}
			}
		},

		clean: {
			src: ["test/**/*.js*", "lib/**/*.js*", "!lib/common/vendor/*.js", "!lib/hooks/**/*.js", "!lib/common/**/*.json", "!lib/common/Gruntfile.js", "!lib/common/node_modules/**/*", "!lib/common/hooks/**/*.js", "!lib/common/bin/*.js", "*.tgz"]
		}
	});

	grunt.loadNpmTasks("grunt-contrib-clean");
	grunt.loadNpmTasks("grunt-contrib-watch");
	grunt.loadNpmTasks("grunt-shell");
	grunt.loadNpmTasks("grunt-ts");
	grunt.loadNpmTasks("grunt-tslint");

	grunt.registerTask("set_package_version", function (version) {
		var buildVersion = getBuildVersion(version);
		var packageJson = grunt.file.readJSON("package.json");
		packageJson.buildVersion = buildVersion;
		grunt.file.write("package.json", JSON.stringify(packageJson, null, "  "));
	});

	grunt.registerTask("setBundleDependencies", function (version) {
		var buildVersion = getBuildVersion(version);
		var packageJson = grunt.file.readJSON("package.json");
		packageJson.bundleDependencies = Object.keys(packageJson.dependencies);
		grunt.file.write("package.json", JSON.stringify(packageJson, null, "  "));
	});

	grunt.registerTask("setPackageName", function (version) {
		var fs = require("fs");
		var fileExtension = ".tgz";
		var buildVersion = getBuildVersion(version);
		var packageJson = grunt.file.readJSON("package.json");
		var oldFileName = packageJson.name + "-" + packageJson.version;
		var newFileName = oldFileName + "-" + buildVersion;
		fs.renameSync(oldFileName + fileExtension, newFileName + fileExtension);
	});

	grunt.registerTask("delete_coverage_dir", function () {
		var done = this.async();
		var rimraf = require("rimraf");
		rimraf("coverage", function (err) {
			if (err) {
				console.log("Error while deleting coverage directory from the package.");
				done(false);
			}

			done();
		});
	});

	grunt.registerTask("test", ["ts:devall", "shell:ci_unit_tests"]);

	grunt.registerTask("remove_prepublish_script", function () {
		var packageJson = grunt.file.readJSON("package.json");
		if (packageJson && packageJson.scripts && packageJson.scripts.prepublish) {
			delete packageJson.scripts.prepublish;
			grunt.file.write("package.json", JSON.stringify(packageJson, null, "  "));
			isPackageJsonModified = true;
		}
	});

	grunt.registerTask("printPackageJsonWarning", function () {
		if (isPackageJsonModified) {
			require("colors");
			console.log("NOTE: `grunt pack` command modified package.json. DO NOT COMMIT these changes, they are required only for the produced .tgz.".red.bold);
		}
	});

	grunt.registerTask("pack", [
		"clean",

		"ts:release_build",

		"remove_prepublish_script",

		"shell:apply_resources_environment",
		"shell:prepare_resources",
		"shell:apply_deployment_environment",
		"shell:ci_unit_tests",

		"set_package_version",
		"delete_coverage_dir",
		"shell:build_package",
		"setPackageName",
		"printPackageJsonWarning"
	]);
	grunt.registerTask("bundle-pack", ["setBundleDependencies", "pack"]);
	grunt.registerTask("lint", ["tslint:build"]);
	grunt.registerTask("all", ["clean", "test", "lint"]);
	grunt.registerTask("rebuild", ["clean", "ts:devlib"]);
	grunt.registerTask("default", "ts:devlib");
};
<|endoftext|>