<commit_before>const fs = require('fs');

module.exports = function(grunt) {
    // Programatically find out what packages we include. This is used to factor
    // out our node packages from our actual code.
    const pkg = grunt.file.readJSON('./package.json');
    const dependencies = Object.keys(pkg.dependencies);

    let product = grunt.option('product') || process.env.MACHETE_PRODUCT;
    if (!['seller', 'sp'].includes(product)) {
        throw new Error('unknown product: ' + product);
    }

    let sourceDirs = {
        sp: ['background', 'campaign', 'dashboard'],
        seller: ['seller-background', 'seller-dash'],
    };

    const releaseTag = grunt.option('release') ? 'release' : 'beta';
    const targetJson = `config/${product}-${releaseTag}.json`;
    const env = grunt.file.readJSON(targetJson);
    if (grunt.option('noDebug')) {
        env.NODE_ENV = 'production';
    }
    const manifest = grunt.file.readJSON(`${product}-manifest.json`);

    const local = grunt.option('local') || process.env.MACHETE_LOCAL;
    if (local) {
        env.MACHETE_LOCAL = 1;
    }

    let vendorTransforms = [];
    if (releaseTag == 'release') {
        vendorTransforms = [
            ['envify', Object.assign({ global: true }, env)],
            ['uglifyify', { global: true }],
            ['babelify', { presets: ['react'] }]
        ];
    }
    else {
        vendorTransforms = [
            ['envify', Object.assign({ global: true }, env)],
            ['babelify', { presets: ['react'] }]
        ];
    }

    const pkgPath = `machete-${product}-${releaseTag}.zip`;

    const gruntConfig = {
        pkg,
        execute: {
            manifest: {
                call: (grunt, options) => {
                    manifest.name = env.NAME;
                    manifest.permissions.push(`https://${env.HOSTNAME}/*`);
                    grunt.file.write(`out/${product}/manifest.json`, JSON.stringify(manifest));
                },
            }
        },
        eslint: {
            options: { extensions: ['.js', '.jsx'] },
            components: ['src/components'],
            common: ['src/common'],
            /* More targets created programatically */
        },
        browserify: {
            vendor: {
                src: [],
                dest: `out/${product}/src/vendor.js`,
                options: {
                    require: dependencies,
                    transform: vendorTransforms,
                },
            },
            /* More targets created programatically */
        },
        copy: {
            css: { expand: true, src: 'css/**', dest: `out/${product}`, },
            img: { expand: true, src: 'images/**', dest: `out/${product}`, },
            html: { expand: true, flatten: true, src: `html/${product}/**`, dest: `out/${product}/html`, },
            datepickerCss: { src: 'node_modules/react-datepicker/dist/react-datepicker.css', dest: `out/${product}/css/react-datepicker.css` },
            tableCss: { src: 'node_modules/react-table/react-table.css', dest: `out/${product}/css/react-table.css` },
            selectCss: { src: 'node_modules/react-select/dist/react-select.min.css', dest: `out/${product}/css/react-select.css` },
        },
        watch: {
            components: {
                files: ['src/components/*.jsx'],
                tasks: ['eslint:components', 'app']
            },
            common: {
                files: ['src/common/*.js'],
                tasks: ['eslint:common', 'app']
            },
            copy: {
                files: ['css/**', 'images/**', 'html/**'],
                tasks: ['copy'],
            },
            manifest: {
                files: [`${product}-manifest.json`],
                tasks: ['execute:manifest']
            },
            /* Targets created programatically */
        },
        zip: {
            [pkgPath]: [`out/${product}/**`],
        },
        run: {
            publish: {
                cmd: 'node',
                args: ['upload-package.js', env.APP_ID, pkgPath],
            }
        },
        gittag: {
            publish: {
                options: {
                    tag: manifest.version_name,
                }
            }
        },
        gitpush: {
            github: {
                options: {
                    remote: 'github',
                    tags: true,
                }
            },
            origin: {
                options: {
                    remote: 'origin',
                    tags: true,
                }
            }
        }
    };

    // Handle JS source directories. For each such directory aside from
    // 'common', create a watch, browserify, and eslint task
    const nobuild = ['common', 'components'];
    for (name of sourceDirs[product]) {
        gruntConfig.eslint[name] = [`src/${name}`];
        gruntConfig.browserify[name] = {
            src: [`src/${name}/*.js`],
            dest: `out/${product}/src/${name}.js`,
            options: {
                external: dependencies,
                transform: [
                    ['babelify', {presets: ['react']}],
                    ['envify', env],
                ]
            },
        };
        gruntConfig.watch[`${name}-eslint`] = {
            files: [`src/${name}/**`],
            tasks: [`eslint:${name}`, `browserify:${name}`]
        };
    }

    grunt.initConfig(gruntConfig);

    grunt.loadNpmTasks('grunt-browserify');
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-eslint');
    grunt.loadNpmTasks('grunt-zip');
    grunt.loadNpmTasks('grunt-execute');
    grunt.loadNpmTasks('grunt-run');
    grunt.loadNpmTasks('grunt-git');

    grunt.registerTask('app', ['execute', ...sourceDirs[product].map(x => `browserify:${x}`)]);
    grunt.registerTask('default', ['execute', 'eslint', 'browserify', 'copy', 'zip']);

    const publishTasks = ['default', 'run:publish', 'gittag:publish', 'gitpush:origin'];
    if (releaseTag == 'release')
        pushTasks.push('gitpush:github');
    grunt.registerTask('publish', publishTasks);
};
<commit_msg>use the short version and not the long version_name for git tags<commit_after>const fs = require('fs');

module.exports = function(grunt) {
    // Programatically find out what packages we include. This is used to factor
    // out our node packages from our actual code.
    const pkg = grunt.file.readJSON('./package.json');
    const dependencies = Object.keys(pkg.dependencies);

    let product = grunt.option('product') || process.env.MACHETE_PRODUCT;
    if (!['seller', 'sp'].includes(product)) {
        throw new Error('unknown product: ' + product);
    }

    let sourceDirs = {
        sp: ['background', 'campaign', 'dashboard'],
        seller: ['seller-background', 'seller-dash'],
    };

    const releaseTag = grunt.option('release') ? 'release' : 'beta';
    const targetJson = `config/${product}-${releaseTag}.json`;
    const env = grunt.file.readJSON(targetJson);
    if (grunt.option('noDebug')) {
        env.NODE_ENV = 'production';
    }
    const manifest = grunt.file.readJSON(`${product}-manifest.json`);

    const local = grunt.option('local') || process.env.MACHETE_LOCAL;
    if (local) {
        env.MACHETE_LOCAL = 1;
    }

    let vendorTransforms = [];
    if (releaseTag == 'release') {
        vendorTransforms = [
            ['envify', Object.assign({ global: true }, env)],
            ['uglifyify', { global: true }],
            ['babelify', { presets: ['react'] }]
        ];
    }
    else {
        vendorTransforms = [
            ['envify', Object.assign({ global: true }, env)],
            ['babelify', { presets: ['react'] }]
        ];
    }

    const pkgPath = `machete-${product}-${releaseTag}.zip`;

    const gruntConfig = {
        pkg,
        execute: {
            manifest: {
                call: (grunt, options) => {
                    manifest.name = env.NAME;
                    manifest.permissions.push(`https://${env.HOSTNAME}/*`);
                    grunt.file.write(`out/${product}/manifest.json`, JSON.stringify(manifest));
                },
            }
        },
        eslint: {
            options: { extensions: ['.js', '.jsx'] },
            components: ['src/components'],
            common: ['src/common'],
            /* More targets created programatically */
        },
        browserify: {
            vendor: {
                src: [],
                dest: `out/${product}/src/vendor.js`,
                options: {
                    require: dependencies,
                    transform: vendorTransforms,
                },
            },
            /* More targets created programatically */
        },
        copy: {
            css: { expand: true, src: 'css/**', dest: `out/${product}`, },
            img: { expand: true, src: 'images/**', dest: `out/${product}`, },
            html: { expand: true, flatten: true, src: `html/${product}/**`, dest: `out/${product}/html`, },
            datepickerCss: { src: 'node_modules/react-datepicker/dist/react-datepicker.css', dest: `out/${product}/css/react-datepicker.css` },
            tableCss: { src: 'node_modules/react-table/react-table.css', dest: `out/${product}/css/react-table.css` },
            selectCss: { src: 'node_modules/react-select/dist/react-select.min.css', dest: `out/${product}/css/react-select.css` },
        },
        watch: {
            components: {
                files: ['src/components/*.jsx'],
                tasks: ['eslint:components', 'app']
            },
            common: {
                files: ['src/common/*.js'],
                tasks: ['eslint:common', 'app']
            },
            copy: {
                files: ['css/**', 'images/**', 'html/**'],
                tasks: ['copy'],
            },
            manifest: {
                files: [`${product}-manifest.json`],
                tasks: ['execute:manifest']
            },
            /* Targets created programatically */
        },
        zip: {
            [pkgPath]: [`out/${product}/**`],
        },
        run: {
            publish: {
                cmd: 'node',
                args: ['upload-package.js', env.APP_ID, pkgPath],
            }
        },
        gittag: {
            publish: {
                options: {
                    tag: manifest.version,
                }
            }
        },
        gitpush: {
            github: {
                options: {
                    remote: 'github',
                    tags: true,
                }
            },
            origin: {
                options: {
                    remote: 'origin',
                    tags: true,
                }
            }
        }
    };

    // Handle JS source directories. For each such directory aside from
    // 'common', create a watch, browserify, and eslint task
    const nobuild = ['common', 'components'];
    for (name of sourceDirs[product]) {
        gruntConfig.eslint[name] = [`src/${name}`];
        gruntConfig.browserify[name] = {
            src: [`src/${name}/*.js`],
            dest: `out/${product}/src/${name}.js`,
            options: {
                external: dependencies,
                transform: [
                    ['babelify', {presets: ['react']}],
                    ['envify', env],
                ]
            },
        };
        gruntConfig.watch[`${name}-eslint`] = {
            files: [`src/${name}/**`],
            tasks: [`eslint:${name}`, `browserify:${name}`]
        };
    }

    grunt.initConfig(gruntConfig);

    grunt.loadNpmTasks('grunt-browserify');
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-eslint');
    grunt.loadNpmTasks('grunt-zip');
    grunt.loadNpmTasks('grunt-execute');
    grunt.loadNpmTasks('grunt-run');
    grunt.loadNpmTasks('grunt-git');

    grunt.registerTask('app', ['execute', ...sourceDirs[product].map(x => `browserify:${x}`)]);
    grunt.registerTask('default', ['execute', 'eslint', 'browserify', 'copy', 'zip']);

    const publishTasks = ['default', 'run:publish', 'gittag:publish', 'gitpush:origin'];
    if (releaseTag == 'release')
        pushTasks.push('gitpush:github');
    grunt.registerTask('publish', publishTasks);
};
<|endoftext|>


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

	require('load-grunt-tasks')(grunt);

	grunt.initConfig({
		sass: {
			compile: {
				options: {
					style: 'compressed'
				},
				files: {
					'styles/screen.css': 'styles/screen.scss'
				}
			}
		},
		autoprefixer: {
			prefix: {
				src: 'styles/screen.css'
			}
		},
		jekyll: {
			full: {},
			limit: {
				options: {
					limit_posts: 150
				}
			}
		},
		htmlmin: {
			site: {
				options: {
					removeComments: true,
					collapseWhitespace: true
				},
				expand: true,
				cwd: '_site/',
				src: '**/*.html',
				dest: '_site/'
			}
		},
		watch: {
			styles: {
				files: 'styles/*.scss',
				tasks: ['sass', 'autoprefixer', 'copy']
			},
			limit: {
				files: [
					'**',
					'!_site/**',
					'!node_modules/**',
					'!.sass-cache/**',
					'!styles/*',
					'!Gruntfile.js',
					'!README.md',
					'!LICENSE.md',
					'!package.json',
					'!.git/**'
				],
				tasks: ['jekyll:limit', 'htmlmin']
			}
		},
		copy: {
			css: {
				files: {
					'_site/styles/screen.css' : 'styles/screen.css'
				}
			}
		},
		rsync: {
			options: {
				args: [
					// Note: the next line is commented out to avoid deleting the
					// `extension-docs` directory, which is generated from a separate
					// repository at the moment. As soon as the extension docs are merged
					// with the main `devopera` repository, we should re-enable it.
					//'--delete', // delete extraneous files on the receiving side
					'--times', // preserve modification times…
					'--omit-dir-times', // …except for directories
					'--compress', // compress data during the transfer
					'--verbose' // increase verbosity
				],
				exclude: ['.DS_Store'],
				recursive: true
			},
			deploy: {
				options: {
					src: '_site/',
					dest: '/var/www/html/',
					host: '54.213.240.91'
				}
			}
		}
	});

	grunt.registerTask('default', function() {
		grunt.log.subhead('Please use one of the following commands:');
		grunt.log.writeln('• grunt watch  — for quick dev build');
		grunt.log.writeln('• grunt build  — for full site build');
		grunt.log.writeln('• grunt deploy — for deploying build');
	});

	grunt.registerTask('build', [
		'sass',
		'autoprefixer',
		'jekyll:full',
		'htmlmin'
	]);

	grunt.registerTask('deploy', ['rsync']);

};
<commit_msg>grunt-rsync: `chmod` new files<commit_after>module.exports = function(grunt) {

	require('load-grunt-tasks')(grunt);

	grunt.initConfig({
		sass: {
			compile: {
				options: {
					style: 'compressed'
				},
				files: {
					'styles/screen.css': 'styles/screen.scss'
				}
			}
		},
		autoprefixer: {
			prefix: {
				src: 'styles/screen.css'
			}
		},
		jekyll: {
			full: {},
			limit: {
				options: {
					limit_posts: 150
				}
			}
		},
		htmlmin: {
			site: {
				options: {
					removeComments: true,
					collapseWhitespace: true
				},
				expand: true,
				cwd: '_site/',
				src: '**/*.html',
				dest: '_site/'
			}
		},
		watch: {
			styles: {
				files: 'styles/*.scss',
				tasks: ['sass', 'autoprefixer', 'copy']
			},
			limit: {
				files: [
					'**',
					'!_site/**',
					'!node_modules/**',
					'!.sass-cache/**',
					'!styles/*',
					'!Gruntfile.js',
					'!README.md',
					'!LICENSE.md',
					'!package.json',
					'!.git/**'
				],
				tasks: ['jekyll:limit', 'htmlmin']
			}
		},
		copy: {
			css: {
				files: {
					'_site/styles/screen.css' : 'styles/screen.css'
				}
			}
		},
		rsync: {
			options: {
				args: [
					// Note: the next line is commented out to avoid deleting the
					// `extension-docs` directory, which is generated from a separate
					// repository at the moment. As soon as the extension docs are merged
					// with the main `devopera` repository, we should re-enable it.
					//'--delete', // delete extraneous files on the receiving side
					'--times', // preserve modification times…
					'--omit-dir-times', // …except for directories
					'--compress', // compress data during the transfer
					'--verbose', // increase verbosity
					'--chmod=ug=rwX,o=rX' // `chmod` new files
				],
				exclude: ['.DS_Store'],
				recursive: true
			},
			deploy: {
				options: {
					src: '_site/',
					dest: '/var/www/html/',
					host: '54.213.240.91'
				}
			}
		}
	});

	grunt.registerTask('default', function() {
		grunt.log.subhead('Please use one of the following commands:');
		grunt.log.writeln('• grunt watch  — for quick dev build');
		grunt.log.writeln('• grunt build  — for full site build');
		grunt.log.writeln('• grunt deploy — for deploying build');
	});

	grunt.registerTask('build', [
		'sass',
		'autoprefixer',
		'jekyll:full',
		'htmlmin'
	]);

	grunt.registerTask('deploy', ['rsync']);

};
<|endoftext|>


<commit_before>// To use this file in WebStorm, right click on the file name in the Project Panel (normally left) and select "Open Grunt Console"

/** @namespace __dirname */
/* jshint -W097 */// jshint strict:false
/*jslint node: true */
"use strict";

module.exports = function (grunt) {
    var fs          = require('fs');
    var http        = require('http');
    var https       = require('https');

    var srcDir      = __dirname + "/";
    var dstDir      = __dirname + "/delivery/";
    var gruntDir    = __dirname + "/build/";
    var pkg         = grunt.file.readJSON('package.json');
    var iocore      = {};//grunt.file.readJSON('io-package.json');
    var words       = null;

    var download = function(url, dest, cb) {
        var file = fs.createWriteStream(dest);
        var request = http.get(url, function(response) {
            response.pipe(file);
            file.on('finish', function() {
                file.close(cb);
            });
        });
    }

    var couchDBlink = "http://apache.lauf-forum.at/couchdb/binary/win/1.6.1/setup-couchdb-1.6.1_R16B02.exe";
    var modules     = [
        "js-controller"
    ];

    // Project configuration.
    grunt.initConfig({
        pkg: pkg,
        curl: {
            'io-package': {
                src: 'https://github.com/ioBroker/ioBroker.<%= grunt.task.current.args[0] %>/raw/master/io-package.json',
                dest: 'tmp/ioBroker.<%= grunt.task.current.args[0] %>.io-package.json'
            },
            'iobroker': {
                src: 'https://github.com/ioBroker/ioBroker.<%= grunt.task.current.args[0] %>/archive/master.zip',
                dest: 'tmp/ioBroker.<%= grunt.task.current.args[0] %>.zip'
            },
            'couchDB': {
                src: couchDBlink,
                dest: 'build/windows/couchDB/couchDBsetup.exe'
            }
        },
        clean: {
            all: [gruntDir + '.build', gruntDir + '.debian-pi-control', gruntDir + '.debian-pi-ready', gruntDir + '.windows-ready', "tmp"],
            'debian-pi-control': [gruntDir + '.debian-pi-ready/DEBIAN'],
            'debian-pi-control-sysroot': [gruntDir + '.debian-pi-ready/sysroot']
        },
        replace: {
            'debian-pi-version': {
                options: {
                    force: true,
                    patterns: [
                        {
                            match: 'version',
                            replacement: '<%= grunt.task.current.args[3] %>'
                        },
                        {
                            match: 'architecture',
                            replacement: '<%= grunt.task.current.args[2] %>'
                        },
                        {
                            match: "size",
                            replacement: '<%= grunt.task.current.args[0] %>'
                        },
                        {
                            match: "user",
                            replacement: '<%= grunt.task.current.args[1] %>'
                        },
                        {
                            match: "user",
                            replacement: '<%= grunt.task.current.args[1] %>'
                        },
                        {
                            match: /"node\-windows": "\~[\.0-9]*",/g,
                            replacement: ''
                        }
                    ]
                },
                files: [
                    {
                        expand:  true,
                        flatten: true,
                        src:     [gruntDir + 'debian/control/*'],
                        dest:    gruntDir + '.debian-pi-control/control/'
                    },
                    {
                        expand:  true,
                        flatten: true,
                        src:     [gruntDir + 'debian/redeb.sh'],
                        dest:    gruntDir + '.debian-pi-ready/'
                    },
                    {
                        expand:  true,
                        flatten: true,
                        src:     [gruntDir + 'debian/etc/init.d/iobroker.sh'],
                        dest:    gruntDir + '.debian-pi-control/'
                    }
                ]
            },
            'debian-pi-modules': {
                options: {
                    force: true,
                    patterns: [
                        {
                            match: /"node\-windows": "\~[\.0-9]*",/g,
                            replacement: ''
                        }
                    ]
                },
                files: [
                    {
                        expand:  true,
                        flatten: true,
                        src:     [gruntDir + '.debian-pi-ready/sysroot/opt/iobroker/package.json'],
                        dest:    gruntDir + '.debian-pi-ready/sysroot/opt/iobroker/'
                    }
                ]

            },
            windowsVersion: {
                options: {
                    force: true,
                    excludeBuiltins: true,
                    patterns: [
                        {
                            match: 'version',
                            replacement: '<%= grunt.task.current.args[0] %>'
                        }
                    ]
                },
                files: [
                    {
                        expand:  true,
                        flatten: true,
                        src:     [gruntDir + 'windows/ioBroker.iss'],
                        dest:    gruntDir + '.windows-ready/'
                    }
                ]
            }
        },
        copy: {
            static: {
                files: [
                    {
                        expand: true,
                        cwd: srcDir,
                        src: [
                            'cert/*',
                            'doc/*',
                            'node_modules/**/*',
                            'scripts/*',
                            'www/control/**/*',
                            'www/lib/**/*',
                            'www/index.html',
                            '*.json',
                            '*.js',
                            'utils/*/**',
                            'adapter/scriptEngine/*',
                            'adapter/webServer/*',
                            'adapter/demoAdapter/*',
                            'adapter/email/*',
                            'adapter/pushover/*',
                            '!main.js',
                            '!speech.js'],
                        dest: '.build/'
                    }
                ]
            },
            'debian-pi': {
                files: [
                    {
                        expand: true,
                        cwd: gruntDir + '../tmp/ioBroker.js-controller-master',
                        src: ['**/*', '!*.bat', '!Gruntfile.js', '!tasks/*'],
                        dest: gruntDir + '.debian-pi-ready/sysroot/opt/iobroker/'
                    },
                    {
                        expand: true,
                        cwd: gruntDir + '.debian-pi-control/control',
                        src: ['**/*'],
                        dest: gruntDir + '.debian-pi-ready/DEBIAN/'
                    },
                    {
                        expand: true,
                        cwd: gruntDir + '.debian-pi-control/',
                        src: ['iobroker.sh'],
                        dest: gruntDir + '.debian-pi-ready/sysroot/etc/init.d/'
                    }
                ]
            },
            windows: {
                files: [
                    {
                        expand: true,
                        cwd: gruntDir + 'windows',
                        src: ['*.js', 'redis-*/**/*', 'couchDB*/**/*', 'nodejs-*/**/*', '*.ico', '*.bat', '!service_ioBroker.bat'],
                        dest: gruntDir + '.windows-ready/'
                    },
                    {
                        expand: true,
                        cwd: gruntDir + '../tmp/ioBroker.js-controller-master',
                        src: ['**/*', '!install.sh', '!iobroker', '!Gruntfile.js', '!tasks/*'],
                        dest: gruntDir + '.windows-ready/data/'
                    },
                    {
                        expand: true,
                        cwd: gruntDir + 'windows',
                        src: ['service_ioBroker.bat', 'node_modules/**/*', '*.cmd'],
                        dest: gruntDir + '.windows-ready/data/'
                    }
                ]
            },
            localRepository: {
                files: [
                    {
                        src: [gruntDir + 'io-repository.json'],
                        dest: './delivery/'
                    }
                ]
            },
            adapter:{
                files:
                [
                    {
                        expand: true,
                        cwd: srcDir + 'tmp/iobroker.<%= grunt.task.current.args[0] %>-master/',
                        src: [
                            '**/*',
                            '!task.js',
                            '!Gruntfile.js'],
                        dest: gruntDir + 'tmp/iobroker.js-controller/adapter/<%= grunt.task.current.args[0] %>'
                    }
                ]
            }
        },
        lineending: {               // Task
            dist: {                   // Target
                options: {              // Target options
                    eol: 'lf',
                        overwrite: true
                },
                files: [
                    {
                        expand:  true,
                        flatten: true,
                        src:     [gruntDir + '.debian-pi-ready/redeb.sh']
                    },
                    {
                        expand:  true,
                        flatten: true,
                        src:     [gruntDir + '.debian-pi-control/control/*']
                    },
                    {
                        expand:  true,
                        flatten: true,
                        src:     [gruntDir + '.debian-pi-control/iobroker.sh']
                    }
                ]
            }
        },
        compress: {
            adapter: {
                options: {
                    archive: dstDir + '<%= grunt.task.current.args[1] %>'
                },
                files: [
                    {expand: true, src: ['**'],  dest: '/', cwd: srcDir + 'adapter/<%= grunt.task.current.args[0] %>/'}
                ]
            },
            'debian-pi-control': {
                options: {
                    archive: gruntDir + '.debian-pi-ready/control.tar.gz'
                },
                files: [
                    {
                        expand: true,
                        src: ['**/*'],
                        dest: '/',
                        cwd: gruntDir + '.debian-pi-control/control/'
                    }
                ]
            },
            'debian-pi-data': {
                options: {
                    archive: gruntDir + '.debian-pi-ready/data.tar.gz'
                },
                files: [
                    {
                        expand: true,
                        src: ['**/*'],
                        dest: '/',
                        cwd: gruntDir + '.debian-pi-ready/sysroot/'
                    }
                ]
            }
        },
        command: {
            makeWindowsMSI: {
                // type : 'bat',
                cmd: '"' + gruntDir + 'windows\\InnoSetup5\\ISCC.exe" "' + gruntDir + '.windows-ready\\ioBroker.iss" > "' + gruntDir + '.windows-ready\\setup.log"'
            },
            makeDebian: {
                // type : 'bat',
                cmd: 'cd ' + gruntDir + '.debian-pi-ready; sudo sh /redeb.sh && cp ioBroker* ../../delivery/'
            }
        },

        // Used for build repository
        unzip: {
            // Skip/exclude files via `router`
            unzipIo: {
                // If router returns a falsy varaible, the file will be skipped
                router: function (filepath) {
                    if (filepath.indexOf('io-addon.json') != -1 || filepath.indexOf('io-core.json') != -1 || filepath.indexOf('io-adapter.json') != -1) {
                        return filepath;
                    } else {
                        // Otherwise, skip it
                        return null;
                    }
                },
                src: [dstDir + '<%= grunt.task.current.args[0] %>'],
                dest: '.rep-work/<%= grunt.task.current.args[1] %>/'
            },
            iobroker: {
                src: ['tmp/ioBroker.<%= grunt.task.current.args[0] %>.zip'],
                dest: 'tmp/'
            },
            "iobroker-js-controller": {
                src: ['tmp/ioBroker.js-controller.zip'],
                dest: 'tmp/'
            }        },
        exec: {
            npm: {
                cmd: 'npm install --production',
                cwd: srcDir + "/tmp/ioBroker.js-controller-master/"
            },
             "npm-adapter": {
                cmd: 'npm install --production',
                cwd: srcDir + "/tmp/ioBroker.<%= grunt.task.current.args[0] %>-master/"
            }
        }
    });

    grunt.registerTask('debian-pi-packet', function () {
        // Calculate size of directory
        var path = require('path');

        function readDirSize(item) {
            var stats = fs.lstatSync(item);
            var total = stats.size;

            if (stats.isDirectory()) {
                var list = fs.readdirSync(item);
                for (var i = 0; i < list.length; i++) {
                    total += readDirSize(path.join(item, list[i]));
                }
                return total;
            } else {
                return total;
            }
        }

        var size = readDirSize('tmp/ioBroker.js-controller-master');
        iocore = grunt.file.readJSON('tmp/ioBroker.js-controller-master/io-package.json');
        console.log(JSON.stringify(iocore));
        grunt.task.run([
            'clean:debian-pi-control',
            'replace:debian-pi-version:' + (Math.round(size / 1024) + 8) + ':pi:armhf:' + iocore.common.version, // Settings for raspbian
            'lineending',
            'copy:debian-pi',
            'replace:debian-pi-modules',
            'compress:debian-pi-data',
            'clean:debian-pi-control-sysroot'
        ]);
        if (/^linux/.test(process.platform)) {
            // This must be tested
            grunt.task.run(['makeDebian']);
        } else {
            console.log('========= Copy .debian-pi-ready directory to Raspbery PI and start "sudo bash redeb.sh" =============');
        }
    });

    grunt.registerTask('buildAllAdapters', function () {
        // Calculate size of directory
        var e = grunt.file.readJSON('tmp/ioBroker.js-controller-master/conf/sources-dist.json');
        var tasks = [];
        tasks.push('exec:npm');
        for (var adapter in e) {
            if (adapter == "js-controller") continue;
            if (!e[adapter].url) continue;
            tasks.push('curl:iobroker:' + adapter);
            tasks.push('unzip:iobroker:' + adapter);
            tasks.push('exec:npm-adapter:' + adapter);
            tasks.push('copy:adapter:' + adapter);
        }
        grunt.task.run(tasks);
    });

    grunt.registerTask('loadIoPackage', function () {
        iocore = grunt.file.readJSON('tmp/ioBroker.' + grunt.task.current.args[0] + '-master/io-package.json');
        console.log(JSON.stringify(iocore));
        grunt.task.run(['replace:windowsVersion:' + iocore.common.version]);
    });

    grunt.registerTask('windows-msi', function () {
        if (/^win/.test(process.platform)) {
            grunt.task.run([
                'loadIoPackage:js-controller',
                'copy:windows',
                'exec:npm-windows',// Remove it if not the FULL MODE
                'command:makeWindowsMSI'
            ]);
            console.log('========= Please wait a little (ca 1 min). The msi file will be created in ioBroker/delivery directory after the grunt is finished.');
            console.log('========= you can start batch file .windows-ready\\createSetup.bat manually');
            // Sometimes command:makeWindowsMSI does not work, you can start batch file manually
            grunt.file.write(gruntDir + '.windows-ready\\createSetup.bat', '"' + gruntDir + 'windows\\InnoSetup5\\ISCC.exe" "' + gruntDir + '.windows-ready\\ioBroker.iss"');
        } else {
            console.log('Cannot create windows setup, while host is not windows');
        }
    });

    grunt.registerTask('createJsonInfo', function () {
       grunt.file.copy(srcDir + '/io-core.json', dstDir + 'ioBroker.core.' + iocore.common.version + '.json');
    });

    var gruntTasks = [
        'grunt-replace',
        'grunt-contrib-clean',
        'grunt-contrib-concat',
        'grunt-contrib-copy',
        'grunt-contrib-compress',
        'grunt-contrib-commands',
        'grunt-exec',
        'grunt-zip',
        'grunt-lineending',
        'grunt-curl'
    ];
    var i;

    for (i in gruntTasks) {
        grunt.loadNpmTasks(gruntTasks[i]);
    }

    grunt.registerTask('default', [
        'clean:all',
        'curl:io-package:js-controller',
        //'curl:couchDB',
        'curl:iobroker:js-controller',
        'unzip:iobroker:js-controller',
        'buildAllAdapters',
        'windows-msi',
        'debian-pi-packet'
    ]);
};<commit_msg>(bluefox) support of FULL build mode<commit_after>// To use this file in WebStorm, right click on the file name in the Project Panel (normally left) and select "Open Grunt Console"

/** @namespace __dirname */
/* jshint -W097 */// jshint strict:false
/*jslint node: true */
"use strict";

module.exports = function (grunt) {
    var fs          = require('fs');
    var http        = require('http');
    var https       = require('https');

    var srcDir      = __dirname + "/";
    var dstDir      = __dirname + "/delivery/";
    var gruntDir    = __dirname + "/build/";
    var pkg         = grunt.file.readJSON('package.json');
    var iocore      = {};//grunt.file.readJSON('io-package.json');
    var words       = null;

    var download = function(url, dest, cb) {
        var file = fs.createWriteStream(dest);
        var request = http.get(url, function(response) {
            response.pipe(file);
            file.on('finish', function() {
                file.close(cb);
            });
        });
    }

    //var couchDBlink = "http://apache.lauf-forum.at/couchdb/binary/win/1.6.1/setup-couchdb-1.6.1_R16B02.exe";

    // Project configuration.
    grunt.initConfig({
        pkg: pkg,
        curl: {
            'io-package': {
                src: 'https://github.com/ioBroker/ioBroker.<%= grunt.task.current.args[0] %>/raw/master/io-package.json',
                dest: 'tmp/ioBroker.<%= grunt.task.current.args[0] %>.io-package.json'
            },
            'iobroker': {
                src: 'https://github.com/ioBroker/ioBroker.<%= grunt.task.current.args[0] %>/archive/master.zip',
                dest: 'tmp/ioBroker.<%= grunt.task.current.args[0] %>.zip'
            }/*,
            'couchDB': {
                src: couchDBlink,
                dest: 'build/windows/couchDB/couchDBsetup.exe'
            }*/
        },
        clean: {
            all: [gruntDir + '.build', gruntDir + '.debian-pi-control', gruntDir + '.debian-pi-ready', gruntDir + '.windows-ready', "tmp"],
            'debian-pi-control': [gruntDir + '.debian-pi-ready/DEBIAN'],
            'debian-pi-control-sysroot': [gruntDir + '.debian-pi-ready/sysroot']
        },
        replace: {
            'debian-pi-version': {
                options: {
                    force: true,
                    patterns: [
                        {
                            match: 'version',
                            replacement: '<%= grunt.task.current.args[3] %>'
                        },
                        {
                            match: 'architecture',
                            replacement: '<%= grunt.task.current.args[2] %>'
                        },
                        {
                            match: "size",
                            replacement: '<%= grunt.task.current.args[0] %>'
                        },
                        {
                            match: "user",
                            replacement: '<%= grunt.task.current.args[1] %>'
                        },
                        {
                            match: "user",
                            replacement: '<%= grunt.task.current.args[1] %>'
                        },
                        {
                            match: /"node\-windows": "\~[\.0-9]*",/g,
                            replacement: ''
                        }
                    ]
                },
                files: [
                    {
                        expand:  true,
                        flatten: true,
                        src:     [gruntDir + 'debian/control/*'],
                        dest:    gruntDir + '.debian-pi-control/control/'
                    },
                    {
                        expand:  true,
                        flatten: true,
                        src:     [gruntDir + 'debian/redeb.sh'],
                        dest:    gruntDir + '.debian-pi-ready/'
                    },
                    {
                        expand:  true,
                        flatten: true,
                        src:     [gruntDir + 'debian/etc/init.d/iobroker.sh'],
                        dest:    gruntDir + '.debian-pi-control/'
                    }
                ]
            },
            'debian-pi-modules': {
                options: {
                    force: true,
                    patterns: [
                        {
                            match: /"node\-windows": "\~[\.0-9]*",/g,
                            replacement: ''
                        }
                    ]
                },
                files: [
                    {
                        expand:  true,
                        flatten: true,
                        src:     [gruntDir + '.debian-pi-ready/sysroot/opt/iobroker/package.json'],
                        dest:    gruntDir + '.debian-pi-ready/sysroot/opt/iobroker/'
                    }
                ]

            },
            windowsVersion: {
                options: {
                    force: true,
                    excludeBuiltins: true,
                    patterns: [
                        {
                            match: 'version',
                            replacement: '<%= grunt.task.current.args[0] %>'
                        }
                    ]
                },
                files: [
                    {
                        expand:  true,
                        flatten: true,
                        src:     [gruntDir + 'windows/ioBroker.iss'],
                        dest:    gruntDir + '.windows-ready/'
                    }
                ]
            },
            noNpm: {
                options: {
                    force: true,
                    excludeBuiltins: true,
                    patterns: [
                        {
                            match: /call npm install --production/,
                            replacement: ''
                        },
                        {
                            match: /npm install --production/g,
                            replacement: ''
                        }
                    ]
                },
                files: [
                    {
                        expand:  true,
                        flatten: true,
                        src:     [srcDir + 'tmp/ioBroker.js-controller-master/install.bat', srcDir + 'tmp/ioBroker.js-controller-master/install.sh'],
                        dest:    srcDir + 'tmp/ioBroker.js-controller-master/'
                    }
                ]

            }
        },
        copy: {
            static: {
                files: [
                    {
                        expand: true,
                        cwd: srcDir,
                        src: [
                            'cert/*',
                            'doc/*',
                            'node_modules/**/*',
                            'scripts/*',
                            'www/control/**/*',
                            'www/lib/**/*',
                            'www/index.html',
                            '*.json',
                            '*.js',
                            'utils/*/**',
                            'adapter/scriptEngine/*',
                            'adapter/webServer/*',
                            'adapter/demoAdapter/*',
                            'adapter/email/*',
                            'adapter/pushover/*',
                            '!main.js',
                            '!speech.js'],
                        dest: '.build/'
                    }
                ]
            },
            'debian-pi': {
                files: [
                    {
                        expand: true,
                        cwd: gruntDir + '../tmp/ioBroker.js-controller-master',
                        src: ['**/*', '!*.bat', '!Gruntfile.js', '!tasks/*'],
                        dest: gruntDir + '.debian-pi-ready/sysroot/opt/iobroker/'
                    },
                    {
                        expand: true,
                        cwd: gruntDir + '.debian-pi-control/control',
                        src: ['**/*'],
                        dest: gruntDir + '.debian-pi-ready/DEBIAN/'
                    },
                    {
                        expand: true,
                        cwd: gruntDir + '.debian-pi-control/',
                        src: ['iobroker.sh'],
                        dest: gruntDir + '.debian-pi-ready/sysroot/etc/init.d/'
                    }
                ]
            },
            windows: {
                files: [
                    {
                        expand: true,
                        cwd: gruntDir + 'windows',
                        src: ['*.js', 'redis-*/**/*', 'couchDB*/**/*', 'nodejs-*/**/*', '*.ico', '*.bat', '!service_ioBroker.bat'],
                        dest: gruntDir + '.windows-ready/'
                    },
                    {
                        expand: true,
                        cwd: gruntDir + '../tmp/ioBroker.js-controller-master',
                        src: ['**/*', '!install.sh', '!iobroker', '!Gruntfile.js', '!tasks/*'],
                        dest: gruntDir + '.windows-ready/data/'
                    },
                    {
                        expand: true,
                        cwd: gruntDir + 'windows',
                        src: ['service_ioBroker.bat', 'node_modules/**/*', '*.cmd'],
                        dest: gruntDir + '.windows-ready/data/'
                    }
                ]
            },
            localRepository: {
                files: [
                    {
                        src: [gruntDir + 'io-repository.json'],
                        dest: './delivery/'
                    }
                ]
            },
            adapter:{
                files:
                [
                    {
                        expand: true,
                        cwd: srcDir + 'tmp/iobroker.<%= grunt.task.current.args[0] %>-master/',
                        src: [
                            '**/*',
                            '!task.js',
                            '!Gruntfile.js'],
                        dest: srcDir + 'tmp/iobroker.js-controller-master/adapter/<%= grunt.task.current.args[0] %>'
                    }
                ]
            }
        },
        lineending: {               // Task
            dist: {                   // Target
                options: {              // Target options
                    eol: 'lf',
                        overwrite: true
                },
                files: [
                    {
                        expand:  true,
                        flatten: true,
                        src:     [gruntDir + '.debian-pi-ready/redeb.sh']
                    },
                    {
                        expand:  true,
                        flatten: true,
                        src:     [gruntDir + '.debian-pi-control/control/*']
                    },
                    {
                        expand:  true,
                        flatten: true,
                        src:     [gruntDir + '.debian-pi-control/iobroker.sh']
                    }
                ]
            }
        },
        compress: {
            adapter: {
                options: {
                    archive: dstDir + '<%= grunt.task.current.args[1] %>'
                },
                files: [
                    {expand: true, src: ['**'],  dest: '/', cwd: srcDir + 'adapter/<%= grunt.task.current.args[0] %>/'}
                ]
            },
            'debian-pi-control': {
                options: {
                    archive: gruntDir + '.debian-pi-ready/control.tar.gz'
                },
                files: [
                    {
                        expand: true,
                        src: ['**/*'],
                        dest: '/',
                        cwd: gruntDir + '.debian-pi-control/control/'
                    }
                ]
            },
            'debian-pi-data': {
                options: {
                    archive: gruntDir + '.debian-pi-ready/data.tar.gz'
                },
                files: [
                    {
                        expand: true,
                        src: ['**/*'],
                        dest: '/',
                        cwd: gruntDir + '.debian-pi-ready/sysroot/'
                    }
                ]
            }
        },
        command: {
            makeWindowsMSI: {
                // type : 'bat',
                cmd: '"' + gruntDir + 'windows\\InnoSetup5\\ISCC.exe" "' + gruntDir + '.windows-ready\\ioBroker.iss" > "' + gruntDir + '.windows-ready\\setup.log"'
            },
            makeDebian: {
                // type : 'bat',
                cmd: 'cd ' + gruntDir + '.debian-pi-ready; sudo sh /redeb.sh && cp ioBroker* ../../delivery/'
            }
        },

        // Used for build repository
        unzip: {
            // Skip/exclude files via `router`
            unzipIo: {
                // If router returns a falsy varaible, the file will be skipped
                router: function (filepath) {
                    if (filepath.indexOf('io-addon.json') != -1 || filepath.indexOf('io-core.json') != -1 || filepath.indexOf('io-adapter.json') != -1) {
                        return filepath;
                    } else {
                        // Otherwise, skip it
                        return null;
                    }
                },
                src: [dstDir + '<%= grunt.task.current.args[0] %>'],
                dest: '.rep-work/<%= grunt.task.current.args[1] %>/'
            },
            iobroker: {
                src: ['tmp/ioBroker.<%= grunt.task.current.args[0] %>.zip'],
                dest: 'tmp/'
            },
            "iobroker-js-controller": {
                src: ['tmp/ioBroker.js-controller.zip'],
                dest: 'tmp/'
            }        },
        exec: {
            npm: {
                cmd: 'npm install --production',
                cwd: srcDir + "/tmp/ioBroker.js-controller-master/"
            },
             "npm-adapter": {
                force: true,
                cmd: 'npm install --production',
                cwd: srcDir + "/tmp/ioBroker.<%= grunt.task.current.args[0] %>-master/"
            }
        }
    });

    grunt.registerTask('debian-pi-packet', function () {
        // Calculate size of directory
        var path = require('path');

        function readDirSize(item) {
            var stats = fs.lstatSync(item);
            var total = stats.size;

            if (stats.isDirectory()) {
                var list = fs.readdirSync(item);
                for (var i = 0; i < list.length; i++) {
                    total += readDirSize(path.join(item, list[i]));
                }
                return total;
            } else {
                return total;
            }
        }

        var size = readDirSize('tmp/ioBroker.js-controller-master');
        iocore = grunt.file.readJSON('tmp/ioBroker.js-controller-master/io-package.json');
        console.log(JSON.stringify(iocore));
        grunt.task.run([
            'clean:debian-pi-control',
            'replace:debian-pi-version:' + (Math.round(size / 1024) + 8) + ':pi:armhf:' + iocore.common.version, // Settings for raspbian
            'lineending',
            'copy:debian-pi',
            'replace:debian-pi-modules',
            'compress:debian-pi-data',
            'clean:debian-pi-control-sysroot'
        ]);
        if (/^linux/.test(process.platform)) {
            // This must be tested
            grunt.task.run(['makeDebian']);
        } else {
            console.log('========= Copy .debian-pi-ready directory to Raspbery PI and start "sudo bash redeb.sh" =============');
        }
    });

    grunt.registerTask('buildAllAdapters', function () {
        // Calculate size of directory
        var e = grunt.file.readJSON('tmp/ioBroker.js-controller-master/conf/sources-dist.json');
        var tasks = [];
        tasks.push('exec:npm');
        for (var adapter in e) {
            if (adapter == "js-controller") continue;
            if (adapter == "artnet") continue;
            if (adapter == "cul") continue;
            if (adapter == "highcharts") continue;
            if (adapter == "zwave") continue;
            if (!e[adapter].url) continue;
            if (!grunt.file.exists(srcDir + 'tmp/ioBroker.' + adapter + '.zip'))
                tasks.push('curl:iobroker:' + adapter);
            if (!grunt.file.isDir(srcDir + 'tmp/ioBroker.' + adapter + '-master'))
                tasks.push('unzip:iobroker:' + adapter);
            if (!grunt.file.isDir(srcDir + 'tmp/ioBroker.' + adapter + '-master/node_modules'))
                tasks.push('exec:npm-adapter:' + adapter);
            tasks.push('copy:adapter:' + adapter);
        }
        grunt.task.run(tasks);
    });

    grunt.registerTask('loadIoPackage', function () {
        iocore = grunt.file.readJSON('tmp/ioBroker.' + grunt.task.current.args[0] + '-master/io-package.json');
        console.log(JSON.stringify(iocore));
        grunt.task.run(['replace:windowsVersion:' + iocore.common.version]);
    });

    grunt.registerTask('windows-msi', function () {
        if (/^win/.test(process.platform)) {
            grunt.task.run([
                'loadIoPackage:js-controller',
                'copy:windows',
                'command:makeWindowsMSI'
            ]);
            console.log('========= Please wait a little (ca 1 min). The msi file will be created in ioBroker/delivery directory after the grunt is finished.');
            console.log('========= you can start batch file .windows-ready\\createSetup.bat manually');
            // Sometimes command:makeWindowsMSI does not work, you can start batch file manually
            grunt.file.write(gruntDir + '.windows-ready\\createSetup.bat', '"' + gruntDir + 'windows\\InnoSetup5\\ISCC.exe" "' + gruntDir + '.windows-ready\\ioBroker.iss"');
        } else {
            console.log('Cannot create windows setup, while host is not windows');
        }
    });

    var gruntTasks = [
        'grunt-replace',
        'grunt-contrib-clean',
        'grunt-contrib-concat',
        'grunt-contrib-copy',
        'grunt-contrib-compress',
        'grunt-contrib-commands',
        'grunt-exec',
        'grunt-zip',
        'grunt-lineending',
        'grunt-curl'
    ];
    var i;

    for (i in gruntTasks) {
        grunt.loadNpmTasks(gruntTasks[i]);
    }

    grunt.registerTask('default', [
        'clean:all',
        'curl:io-package:js-controller',
        //'curl:couchDB',
        'curl:iobroker:js-controller',
        'unzip:iobroker:js-controller',
        'windows-msi',
        'debian-pi-packet'
    ]);
    grunt.registerTask('full', [
        'clean:all',
        'curl:io-package:js-controller',
        //'curl:couchDB',
        'curl:iobroker:js-controller',
        'unzip:iobroker:js-controller',
        'buildAllAdapters',
        'replace:noNpm',
        'windows-msi'//,
//        'debian-pi-packet'
    ]);};<|endoftext|>


<commit_before>/* Gruntfile.js
 *
 * A Gruntfile defines automated tasks for the command-line tool grunt. You use a Gruntfile to specify everything that needs
 * to happen for your project to be built. Here, we're configuring grunt to compile our SASS files into CSS as part of the default task.
 *
 * You can find instructions for installing grunt on your computer here: http://gruntjs.com/installing-grunt
 *
 */

module.exports = function(Grunt) {
	/*
	 * Configuration options for grunt.
	 */
	Grunt.initConfig({
		/*
		 * Tell grunt where to find the package.json file.
		 * This line is optional, because grunt knows to look for package.json in the project root, but it's good to be explicit.
		 */

		pkg: Grunt.file.readJSON('package.json'),
		/*
		 * Configuration options for grunt-contrib-sass.
		 *
		 * https://github.com/gruntjs/grunt-contrib-sass/blob/master/README.md
		 */
		sass: {
<<<<<<< HEAD
			dist: {
				options: {
					/*
					 * Output our CSS in exapanded form so that it's easy to read.
					 * In a production environment, you would want to change this option to compressed, to save space.
					 */
					style: 'expanded'
				},
				files: {
					/*
					 * Tells grunt where our sass files are, and where to put the converted CSS files.
					 */
					"css/main.css": "sass/main.sass"
				}
			}
=======
						options: {
				/*
				 * Output our CSS in exapanded form so that it's easy to read.
				 * In a production environment, you would want to change this option to compressed, to save space.
				 */
				style: 'expanded'
			},
			files: [{
				/*
				 * Tells grunt where our sass files are, and where to put the converted CSS files.
				 */
				expand: true,
				cwd: 'sass',
				src: ['*.sass'],
				dest: '../css',
				ext: '.css'
			}]
>>>>>>> 7cb452ca6cd76baf88dd3e41fb9f3542a5506e34
		}
	});

	Grunt.loadNpmTasks('grunt-contrib-sass');
	Grunt.registerTask('default', ['sass']);
}<commit_msg>Fix more problems with Gruntfile.js<commit_after>/* Gruntfile.js
 *
 * A Gruntfile defines automated tasks for the command-line tool grunt. You use a Gruntfile to specify everything that needs
 * to happen for your project to be built. Here, we're configuring grunt to compile our SASS files into CSS as part of the default task.
 *
 * You can find instructions for installing grunt on your computer here: http://gruntjs.com/installing-grunt
 *
 */

module.exports = function(Grunt) {
	/*
	 * Configuration options for grunt.
	 */
	Grunt.initConfig({
		/*
		 * Tell grunt where to find the package.json file.
		 * This line is optional, because grunt knows to look for package.json in the project root, but it's good to be explicit.
		 */

		pkg: Grunt.file.readJSON('package.json'),
		/*
		 * Configuration options for grunt-contrib-sass.
		 *
		 * https://github.com/gruntjs/grunt-contrib-sass/blob/master/README.md
		 */
		sass: {
			dist: {
				options: {
					/*
					 * Output our CSS in exapanded form so that it's easy to read.
					 * In a production environment, you would want to change this option to compressed, to save space.
					 */
					style: 'expanded'
				},
				files: {
					/*
					 * Tells grunt where our sass files are, and where to put the converted CSS files.
					 */
					"css/main.css": "sass/main.sass"
				}
			}

		}
	});

	Grunt.loadNpmTasks('grunt-contrib-sass');
	Grunt.registerTask('default', ['sass']);
}<|endoftext|>


<commit_before>"use strict";

module.exports = function(grunt) {

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

    grunt.initConfig({

        // Define Directory
        dirs: {
            js:     "src/js",
            coffee: "src/coffee",
            build:  "dist"
        },

        // Metadata
        pkg: grunt.file.readJSON("package.json"),
        banner:
        "\n" +
        "/*\n" +
         " * -------------------------------------------------------\n" +
         " * Project: <%= pkg.title %>\n" +
         " * Version: <%= pkg.version %>\n" +
         " *\n" +
         " * Author:  <%= pkg.author.name %>\n" +
         " * Site:     <%= pkg.author.url %>\n" +
         " * Contact: <%= pkg.author.email %>\n" +
         " *\n" +
         " *\n" +
         " * Copyright (c) <%= grunt.template.today(\"yyyy\") %> <%= pkg.author.name %>\n" +
         " * -------------------------------------------------------\n" +
         " */\n" +
         "\n",

        // Compile CoffeeScript
        coffee: {
            compileBare: {
              options: {
                bare: true
              },
              files: {
                "<%= dirs.js %>/main.js" : "<%= dirs.coffee %>/main.coffee",
                "<%= dirs.js %>/asset.js" : "<%= dirs.coffee %>/asset.coffee",
                "<%= dirs.js %>/assetManager.js" : "<%= dirs.coffee %>/assetManager.coffee"
              }
            }
        },

        // Minify and Concat archives
        uglify: {
            options: {
                mangle: false,
                banner: "<%= banner %>"
            },
            dist: {
              files: {
                  "<%= dirs.build %>/uam.min.js": [
                      "<%= dirs.js %>/main.js",
                      "<%= dirs.js %>/asset.js",
                      "<%= dirs.js %>/assetManager.js"
                  ]
              }
            }
        },

        // Notifications
        notify: {
          coffee: {
            options: {
              title: "CoffeeScript - <%= pkg.title %>",
              message: "Compiled and minified with success!"
            }
          },
          js: {
            options: {
              title: "Javascript - <%= pkg.title %>",
              message: "Minified and validated with success!"
            }
          }
        }
});

    // Register Taks
    // --------------------------

    // Observe changes, concatenate, minify and validate files
    grunt.registerTask( "default", [ "coffee", "notify:coffee", "uglify", "notify:js" ]);

};<commit_msg>Simpler gruntfile<commit_after>"use strict";

module.exports = function(grunt) {

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

    grunt.initConfig({

        // Define Directory
        dirs: {
            js:     "src/js",
            coffee: "src/coffee",
            build:  "dist"
        },

        // Metadata
        pkg: grunt.file.readJSON("package.json"),
        banner:
        "\n" +
        "/*\n" +
         " * -------------------------------------------------------\n" +
         " * Project: <%= pkg.title %>\n" +
         " * Version: <%= pkg.version %>\n" +
         " *\n" +
         " * Author:  <%= pkg.author.name %>\n" +
         " * Site:     <%= pkg.author.url %>\n" +
         " * Contact: <%= pkg.author.email %>\n" +
         " *\n" +
         " *\n" +
         " * Copyright (c) <%= grunt.template.today(\"yyyy\") %> <%= pkg.author.name %>\n" +
         " * -------------------------------------------------------\n" +
         " */\n" +
         "\n",

        // Compile CoffeeScript
        coffee: {
            compileBare: {
              options: {
                bare: true
              },
              files: {
                "<%= dirs.js %>/uam.js" : [
                    "<%= dirs.coffee %>/main.coffee",
                    "<%= dirs.coffee %>/asset.coffee",
                    "<%= dirs.coffee %>/assetManager.coffee"
                ]
              }
            }
        },

        // Minify and Concat archives
        uglify: {
            options: {
                mangle: false,
                banner: "<%= banner %>"
            },
            dist: {
              files: {
                  "<%= dirs.build %>/uam.min.js": "<%= dirs.js %>/uam.js"
              }
            }
        },

        // Notifications
        notify: {
          coffee: {
            options: {
              title: "CoffeeScript - <%= pkg.title %>",
              message: "Compiled and minified with success!"
            }
          },
          js: {
            options: {
              title: "Javascript - <%= pkg.title %>",
              message: "Minified and validated with success!"
            }
          }
        }
});

    // Register Taks
    // --------------------------

    // Observe changes, concatenate, minify and validate files
    grunt.registerTask( "default", [ "coffee", "notify:coffee", "uglify", "notify:js" ]);

};<|endoftext|>


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

    "use strict";

    var browserifyFiles = {
        "./dist/build.js": "./src/*.js"
    };

    grunt.initConfig({
        pkg: grunt.file.readJSON("package.json"),
        browserify: {
            prod: {
                files: browserifyFiles
            }
        }
    });

    grunt.loadNpmTasks("grunt-browserify");

    grunt.registerTask("build", ["browserify:prod"]);
};<commit_msg>Add settings for watch & load task<commit_after>module.exports = function(grunt) {

    "use strict";

    var browserifyFiles = {
        "./dist/build.js": "./src/*.js"
    };

    grunt.initConfig({
        pkg: grunt.file.readJSON("package.json"),
        browserify: {
            prod: {
                files: browserifyFiles
            }
        },
        watch: {
            scripts: {
                files: ["src/*.js"],
                tasks: ["build"]
            }
        }
    });

    grunt.loadNpmTasks("grunt-browserify");
    grunt.loadNpmTasks("grunt-contrib-watch");

    grunt.registerTask("build", ["browserify:prod"]);
};<|endoftext|>


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

    grunt.initConfig({
        browserify: {
            dist: {
                options: {
                    transform: [
                        ['babelify', { presets: 'es2015' } ]
                    ]
                },
                files: {
                    'dist/client.js': ['src/js/main.js']
                }
            }
        },
        bowercopy: {
            dist: {
                options: {
                    srcPrefix: 'bower_components',
                    destPrefix: 'dist'
                },
                files: {
                    'pixi.js':          'pixi.js/bin/pixi.js',
                    'pixi.min.js':      'pixi.js/bin/pixi.min.js',
                    'howler.js':        'howler.js/howler.js',
                    'howler.min.js':    'howler.js/howler.min.js'
                }
            }
        },
        copy: {
            index: {
                src: 'src/index.html',
                dest: 'dist/index.html'
            }
        },
        watch: {
            js: {
                files: ['src/js/**/*.js'],
                tasks: ['browserify']
            },
            index: {
                files: ['src/index.html'],
                tasks: ['copy:index']
            }
        },
        connect: {
            server: {
                options: {
                    port: 8080,
                    base: 'dist'
                }
            }
        }
    });

    grunt.loadNpmTasks('grunt-browserify');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-bowercopy');
    grunt.loadNpmTasks('grunt-contrib-connect');
    grunt.loadNpmTasks('grunt-contrib-copy');

    grunt.registerTask('default', ['browserify', 'bowercopy', 'copy', 'connect', 'watch']);
};
<commit_msg>Configure Grunt to watch and copy asset files<commit_after>module.exports = function(grunt) {

    grunt.initConfig({
        browserify: {
            dist: {
                options: {
                    transform: [
                        ['babelify', { presets: 'es2015' } ]
                    ]
                },
                files: {
                    'dist/client.js': ['src/js/main.js']
                }
            }
        },
        bowercopy: {
            dist: {
                options: {
                    srcPrefix: 'bower_components',
                    destPrefix: 'dist'
                },
                files: {
                    'pixi.js':          'pixi.js/bin/pixi.js',
                    'pixi.min.js':      'pixi.js/bin/pixi.min.js',
                    'howler.js':        'howler.js/howler.js',
                    'howler.min.js':    'howler.js/howler.min.js'
                }
            }
        },
        copy: {
            index: {
                src: 'src/index.html',
                dest: 'dist/index.html'
            },
            media: {
                src: 'media/assets/*',
                dest: 'dist/assets/'
            }
        },
        watch: {
            js: {
                files: ['src/js/**/*.js'],
                tasks: ['browserify']
            },
            index: {
                files: ['src/index.html'],
                tasks: ['copy:index']
            },
            media: {
                files: ['media/assets/*'],
                tasks: ['copy:media'] // TODO: This could be modified to copy only the modified file(s)
            }
        },
        connect: {
            server: {
                options: {
                    port: 8080,
                    base: 'dist'
                }
            }
        }
    });

    grunt.loadNpmTasks('grunt-browserify');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-bowercopy');
    grunt.loadNpmTasks('grunt-contrib-connect');
    grunt.loadNpmTasks('grunt-contrib-copy');

    grunt.registerTask('default', ['browserify', 'bowercopy', 'copy', 'connect', 'watch']);
};
<|endoftext|>


<commit_before>/*
 * logsearch-website
 *
 * Ryan Holder
 * https://github.com/ryanholder/logsearch-website
 *
 * Copyright (c) 2014
 * Licensed under the MIT license.
 */

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

	// Delete after first run
	if (!grunt.file.exists('vendor/bootstrap')) {
		grunt.fail.fatal('>> Please run "bower install" before continuing.');
	}

	// Project configuration.
	grunt.initConfig({

		// Project metadata
		pkg: grunt.file.readJSON('package.json'),
		vendor: grunt.file.readJSON('.bowerrc').directory,
		site: grunt.file.readYAML('_config.yml'),
		bootstrap: '<%= vendor %>/bootstrap',

		// Before generating any new files, remove files from previous build.
		clean: {
			example: ['<%= site.dest %>/*.html'],
		},

		// Lint JavaScript
		jshint: {
			all: ['Gruntfile.js', 'templates/helpers/*.js'],
			options: {
				jshintrc: '.jshintrc'
			}
		},

		// Build HTML from templates and data
		assemble: {
			options: {
				flatten: true,
				production: false,
				assets: '<%= site.assets %>',
				postprocess: require('pretty'),

				// Metadata
				pkg: '<%= pkg %>',
				site: '<%= site %>',
				data: ['<%= site.data %>'],

				// Templates
				partials: '<%= site.includes %>',
				layoutdir: '<%= site.layouts %>',
				layout: '<%= site.layout %>',

				// Extensions
				helpers: '<%= site.helpers %>',
				plugins: '<%= site.plugins %>'
			},
			example: {
				files: {'<%= site.dest %>/': ['<%= site.templates %>/*.hbs']}
			}
		},

		// Compile LESS to CSS
		less: {
			options: {
				vendor: 'vendor',
				paths: [
					'<%= site.theme %>',
					'<%= site.theme %>/bootstrap',
					'<%= site.theme %>/components',
					'<%= site.theme %>/utils'
				],
			},
			site: {
				src: ['<%= site.theme %>/site.less'],
				dest: '<%= site.assets %>/css/site.css'
			}
		},

		// Copy Bootstrap's assets to site assets
		copy: {
			// Keep this target as a getting started point
			assets: {
				files: [
					{expand: true, cwd: '<%= site.images %>', src: ['*.*'], dest: '<%= site.assets %>/images/'},
					{expand: true, cwd: '<%= bootstrap %>/dist/fonts', src: ['*.*'], dest: '<%= site.assets %>/fonts/'},
					{expand: true, cwd: '<%= bootstrap %>/dist/js', src: ['*.*'], dest: '<%= site.assets %>/js/'}
				]
			},
            docs: {
                files: [
					{expand: true, cwd: '<%= site.docs %>', src: ['**/*'], dest: '<%= site.dest %>/docs/'}
				]
            }
		},

		watch: {
			all: {
				files: ['<%= jshint.all %>'],
				tasks: ['jshint', 'nodeunit']
			},
			site: {
				files: ['Gruntfile.js', '<%= less.options.paths %>/*.less', 'templates/**/*.hbs', 'docs/**/*'],
				tasks: ['design']
			}
		},

		connect: {
    			server: {
      				options: {
        				useAvailablePort: true,
        				base: '_gh_pages'
      				}
    			}
  		}
	});

	// Load npm plugins to provide necessary tasks.
	grunt.loadNpmTasks('grunt-contrib-clean');
	grunt.loadNpmTasks('grunt-contrib-copy');
	grunt.loadNpmTasks('grunt-contrib-jshint');
	grunt.loadNpmTasks('grunt-contrib-watch');
	grunt.loadNpmTasks('grunt-contrib-connect');
	grunt.loadNpmTasks('grunt-readme');
	grunt.loadNpmTasks('grunt-sync-pkg');
	grunt.loadNpmTasks('assemble-less');
	grunt.loadNpmTasks('assemble');

	// Build HTML, compile LESS and watch for changes. You must first run "bower install"
	// or install Bootstrap to the "vendor" directory before running this command.
	grunt.registerTask('design', ['clean', 'assemble', 'less:site', 'watch:site']);

	grunt.registerTask('server', ['clean', 'assemble', 'less:site', 'connect:server', 'watch:site']);

	grunt.registerTask('docs', ['readme', 'sync']);

	// Use this going forward.
	grunt.registerTask('default', ['clean', 'jshint', 'copy', 'assemble', 'less', 'docs']);
};
<commit_msg>Fix W099: Mixed spaces and tabs error<commit_after>/*
 * logsearch-website
 *
 * Ryan Holder
 * https://github.com/ryanholder/logsearch-website
 *
 * Copyright (c) 2014
 * Licensed under the MIT license.
 */

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

	// Delete after first run
	if (!grunt.file.exists('vendor/bootstrap')) {
		grunt.fail.fatal('>> Please run "bower install" before continuing.');
	}

	// Project configuration.
	grunt.initConfig({

		// Project metadata
		pkg: grunt.file.readJSON('package.json'),
		vendor: grunt.file.readJSON('.bowerrc').directory,
		site: grunt.file.readYAML('_config.yml'),
		bootstrap: '<%= vendor %>/bootstrap',

		// Before generating any new files, remove files from previous build.
		clean: {
			example: ['<%= site.dest %>/*.html'],
		},

		// Lint JavaScript
		jshint: {
			all: ['Gruntfile.js', 'templates/helpers/*.js'],
			options: {
				jshintrc: '.jshintrc'
			}
		},

		// Build HTML from templates and data
		assemble: {
			options: {
				flatten: true,
				production: false,
				assets: '<%= site.assets %>',
				postprocess: require('pretty'),

				// Metadata
				pkg: '<%= pkg %>',
				site: '<%= site %>',
				data: ['<%= site.data %>'],

				// Templates
				partials: '<%= site.includes %>',
				layoutdir: '<%= site.layouts %>',
				layout: '<%= site.layout %>',

				// Extensions
				helpers: '<%= site.helpers %>',
				plugins: '<%= site.plugins %>'
			},
			example: {
				files: {'<%= site.dest %>/': ['<%= site.templates %>/*.hbs']}
			}
		},

		// Compile LESS to CSS
		less: {
			options: {
				vendor: 'vendor',
				paths: [
					'<%= site.theme %>',
					'<%= site.theme %>/bootstrap',
					'<%= site.theme %>/components',
					'<%= site.theme %>/utils'
				],
			},
			site: {
				src: ['<%= site.theme %>/site.less'],
				dest: '<%= site.assets %>/css/site.css'
			}
		},

		// Copy Bootstrap's assets to site assets
		copy: {
			// Keep this target as a getting started point
			assets: {
				files: [
					{expand: true, cwd: '<%= site.images %>', src: ['*.*'], dest: '<%= site.assets %>/images/'},
					{expand: true, cwd: '<%= bootstrap %>/dist/fonts', src: ['*.*'], dest: '<%= site.assets %>/fonts/'},
					{expand: true, cwd: '<%= bootstrap %>/dist/js', src: ['*.*'], dest: '<%= site.assets %>/js/'}
				]
			},
            docs: {
                files: [
					{expand: true, cwd: '<%= site.docs %>', src: ['**/*'], dest: '<%= site.dest %>/docs/'}
				]
            }
		},

		watch: {
			all: {
				files: ['<%= jshint.all %>'],
				tasks: ['jshint', 'nodeunit']
			},
			site: {
				files: ['Gruntfile.js', '<%= less.options.paths %>/*.less', 'templates/**/*.hbs', 'docs/**/*'],
				tasks: ['design']
			}
		},
		connect: {
			server: {
					options: {
						useAvailablePort: true,
						base: '_gh_pages'
				}
			}
		}
	});

	// Load npm plugins to provide necessary tasks.
	grunt.loadNpmTasks('grunt-contrib-clean');
	grunt.loadNpmTasks('grunt-contrib-copy');
	grunt.loadNpmTasks('grunt-contrib-jshint');
	grunt.loadNpmTasks('grunt-contrib-watch');
	grunt.loadNpmTasks('grunt-contrib-connect');
	grunt.loadNpmTasks('grunt-readme');
	grunt.loadNpmTasks('grunt-sync-pkg');
	grunt.loadNpmTasks('assemble-less');
	grunt.loadNpmTasks('assemble');

	// Build HTML, compile LESS and watch for changes. You must first run "bower install"
	// or install Bootstrap to the "vendor" directory before running this command.
	grunt.registerTask('design', ['clean', 'assemble', 'less:site', 'watch:site']);

	grunt.registerTask('server', ['clean', 'assemble', 'less:site', 'connect:server', 'watch:site']);

	grunt.registerTask('docs', ['readme', 'sync']);

	// Use this going forward.
	grunt.registerTask('default', ['clean', 'jshint', 'copy', 'assemble', 'less', 'docs']);
};
<|endoftext|>


<commit_before>"use strict"

var config = require('./app/config')
var _ = require('underscore')
var fs = require('fs')

module.exports = function (grunt) {
  // Config
  var external = ['react', 'react-dom', 'jquery', 'underscore'],
    scss_src = 'style/main.scss',
    static_src = 'static',
    module_src = 'app/modules',
    module_dest = 'modules',
    prod_dest = 'dist',
    dev_dest = 'public',
    css_dest = 'main.css',
    vendor_dest = 'vendor.js',
    asset_map_dest = 'assetMap.json',
    browserify_options_dev,
    browserify_options_prod,
    browserify_options_vendor_dev,
    browserify_options_vendor_prod,
    browserify_files_dev,
    browserify_files_prod,
    browserify_vendor_files_dev =  { [`${dev_dest}/${vendor_dest}`]: external },
    browserify_vendor_files_prod = { [`${prod_dest}/${vendor_dest}`]: external }

  browserify_options_dev =  {
    transform: [ ['babelify', {presets: ['es2015']}] ],
    watch: true,
    keepAlive: true,
    external: external,
    browserifyOptions: {
      debug: true,
      extensions: '.js'
    },
    watchifyOptions: {
      poll: 100,
      debug: true
    }
  }

  // extend dev options
  browserify_options_prod = {}
  _.extend(browserify_options_prod, browserify_options_dev, {
    watch: false,
    keepAlive: false,
    browserifyOptions: {
      debug: false
    },
    watchifyOptions: {}
  })
  // uglify prod build
  browserify_options_prod.transform.push('uglifyify')

  // vendor browserify options
  browserify_options_vendor_dev = {
    require: external
  }
  browserify_options_vendor_prod = {}
  _.extend(browserify_options_vendor_prod, browserify_options_vendor_dev, {
    transform: ['uglifyify']
  })

  // generate files from modules array
  browserify_files_dev = {}
  browserify_files_prod = {}

  for (let module of config.modules) {
    browserify_files_dev[`${dev_dest}/${module_dest}/${module}.js`] =
      browserify_files_prod[`${prod_dest}/${module_dest}/${module}.js`] =
      [`${module_src}/${module}/client.js`]
  }

  // Project configuration
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    browserify: {
      vendor_dev: {
        files: browserify_vendor_files_dev,
        options: browserify_options_vendor_dev
      },
      vendor_prod: {
        files: browserify_vendor_files_prod,
        options: browserify_options_vendor_prod
      },
      dev: {
        files: browserify_files_dev,
        options: browserify_options_dev
      },
      prod: {
        files: browserify_files_prod,
        options: browserify_options_prod
      }
    },
    sass: {
      dev: {
        files: {
          [`${dev_dest}/${css_dest}`]: scss_src
        }
      },
      prod: {
        files: {
          [`${prod_dest}/${css_dest}`]: scss_src
        }
      }
    },
    postcss: {
      options: {
        processors: [
          require('autoprefixer')({browsers: 'last 2 versions'}),
          require('cssnano')(),
        ]
      },
      dev: {
        src: `${dev_dest}/${css_dest}`,
        options: {
          map: true
        }
      },
      prod: {
        src: `${prod_dest}/${css_dest}`,
        options: {
          map: false
        },
      },
    },
    rsync: {
      options: {
        args: ["--verbose"],
        exclude: [".git*"],
        recursive: true
      },
      dev: {
        options: {
          src: static_src,
          dest: dev_dest
        }
      },
      prod: {
        options: {
          src: static_src,
          dest: prod_dest
        }
      },
    },
    filerev: {
      options: {},
      prod: {
        src: `${prod_dest}/**/*.{css,js,pdf,png,ico}`,
      },
    },
    watch: {
      style: {
        files: 'style/**/*.scss',
        tasks: ['sass:dev', 'postcss:dev']
      },
      rsync: {
        files: `${static_src}/**/*`,
        tasks: ['rsync:dev']
      },
    },
    s3: {
      options: {
        accessKeyId: process.env.S3_ACCESS_KEY_ID,
        secretAccessKey: process.env.S3_SECRET_ACCESS_KEY,
        bucket: process.env.S3_BUCKET,
        region: process.env.S3_REGION,
        headers: {
          CacheControl: 31536000 /* 1yr */
        }
      },
      prod: {
        cwd: prod_dest,
        src: '**'
      },
    },
    clean: {
      dev: [`${dev_dest}/**/*`],
      prod: [`${prod_dest}/**/*`]
    }
  })

  // Load plugins
  grunt.loadNpmTasks('grunt-browserify')
  grunt.loadNpmTasks('grunt-contrib-sass')
  grunt.loadNpmTasks('grunt-postcss')
  grunt.loadNpmTasks('grunt-contrib-watch')
  grunt.loadNpmTasks('grunt-rsync')
  grunt.loadNpmTasks('grunt-filerev')
  grunt.loadNpmTasks('grunt-contrib-clean')
  grunt.loadNpmTasks('grunt-aws')

  // Default is run and watch everything BUT browserify
  grunt.registerTask('default', [
    'clean:dev', 'sass:dev', 'postcss:dev', 'rsync:dev', 'watch'
  ])

  // TODO: break this out better
  grunt.registerTask('write_filerev', () => {
    var finalPaths = {}
    var substrIndex = prod_dest.length
    for (var orig in grunt.filerev.summary) {
      finalPaths[orig.substring(substrIndex)] = grunt.filerev.summary[orig].substring(substrIndex)
    }
    fs.writeFileSync(`${prod_dest}/${asset_map_dest}`, JSON.stringify(finalPaths))
  })

  // TODO: break this better
  grunt.registerTask('filerev_apply', () => {
    var fs = require('fs'),
      substrIndex = prod_dest.length,
      cssFile = grunt.filerev.summary[`${prod_dest}/main.css`],
      content = fs.readFileSync(cssFile, "utf8"),
      prefix = process.env.CDN_ROOT ? '//' + process.env.CDN_ROOT : ''

    content = content.replace(/url\(["']?([\w\@\.\-\/]+)["']?\)/gi, (match, p1) => {
      var rev_file = prefix + grunt.filerev.summary[`${prod_dest}${p1}`].substring(substrIndex)
      console.log(`Replaced ${p1} with ${rev_file}`)
      return `url(${rev_file})`
    })

    fs.writeFileSync(cssFile, content)
  })

  // Build for production
  grunt.registerTask('production', [
    'clean:prod', 'sass:prod', 'postcss:prod', 'rsync:prod',
    'browserify:vendor_prod', 'browserify:prod', 'filerev:prod', 'filerev_apply',
    'write_filerev'
  ])
}
<commit_msg>Fixed uglify not applying to deps<commit_after>"use strict"

var config = require('./app/config')
var _ = require('underscore')
var fs = require('fs')

module.exports = function (grunt) {
  // Config
  var external = ['react', 'react-dom', 'jquery', 'underscore'],
    scss_src = 'style/main.scss',
    static_src = 'static',
    module_src = 'app/modules',
    module_dest = 'modules',
    prod_dest = 'dist',
    dev_dest = 'public',
    css_dest = 'main.css',
    vendor_dest = 'vendor.js',
    asset_map_dest = 'assetMap.json',
    browserify_options_dev,
    browserify_options_prod,
    browserify_options_vendor_dev,
    browserify_options_vendor_prod,
    browserify_files_dev,
    browserify_files_prod,
    browserify_vendor_files_dev =  { [`${dev_dest}/${vendor_dest}`]: external },
    browserify_vendor_files_prod = { [`${prod_dest}/${vendor_dest}`]: external }

  browserify_options_dev =  {
    transform: [ ['babelify', {presets: ['es2015']}] ],
    watch: true,
    keepAlive: true,
    external: external,
    browserifyOptions: {
      debug: true,
      extensions: '.js'
    },
    watchifyOptions: {
      poll: 100,
      debug: true
    }
  }

  // extend dev options
  browserify_options_prod = {}
  _.extend(browserify_options_prod, browserify_options_dev, {
    watch: false,
    keepAlive: false,
    browserifyOptions: {
      debug: false
    },
    watchifyOptions: {}
  })
  // uglify prod build
  browserify_options_prod.transform.push(['uglifyify', {global: true}])

  // vendor browserify options
  browserify_options_vendor_dev = {
    require: external
  }
  browserify_options_vendor_prod = {}
  _.extend(browserify_options_vendor_prod, browserify_options_vendor_dev, {
    transform: [['uglifyify', {global: true}]]
  })

  // generate files from modules array
  browserify_files_dev = {}
  browserify_files_prod = {}

  for (let module of config.modules) {
    browserify_files_dev[`${dev_dest}/${module_dest}/${module}.js`] =
      browserify_files_prod[`${prod_dest}/${module_dest}/${module}.js`] =
      [`${module_src}/${module}/client.js`]
  }

  // Project configuration
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    browserify: {
      vendor_dev: {
        files: browserify_vendor_files_dev,
        options: browserify_options_vendor_dev
      },
      vendor_prod: {
        files: browserify_vendor_files_prod,
        options: browserify_options_vendor_prod
      },
      dev: {
        files: browserify_files_dev,
        options: browserify_options_dev
      },
      prod: {
        files: browserify_files_prod,
        options: browserify_options_prod
      }
    },
    sass: {
      dev: {
        files: {
          [`${dev_dest}/${css_dest}`]: scss_src
        }
      },
      prod: {
        files: {
          [`${prod_dest}/${css_dest}`]: scss_src
        }
      }
    },
    postcss: {
      options: {
        processors: [
          require('autoprefixer')({browsers: 'last 2 versions'}),
          require('cssnano')(),
        ]
      },
      dev: {
        src: `${dev_dest}/${css_dest}`,
        options: {
          map: true
        }
      },
      prod: {
        src: `${prod_dest}/${css_dest}`,
        options: {
          map: false
        },
      },
    },
    rsync: {
      options: {
        args: ["--verbose"],
        exclude: [".git*"],
        recursive: true
      },
      dev: {
        options: {
          src: static_src,
          dest: dev_dest
        }
      },
      prod: {
        options: {
          src: static_src,
          dest: prod_dest
        }
      },
    },
    filerev: {
      options: {},
      prod: {
        src: `${prod_dest}/**/*.{css,js,pdf,png,ico}`,
      },
    },
    watch: {
      style: {
        files: 'style/**/*.scss',
        tasks: ['sass:dev', 'postcss:dev']
      },
      rsync: {
        files: `${static_src}/**/*`,
        tasks: ['rsync:dev']
      },
    },
    s3: {
      options: {
        accessKeyId: process.env.S3_ACCESS_KEY_ID,
        secretAccessKey: process.env.S3_SECRET_ACCESS_KEY,
        bucket: process.env.S3_BUCKET,
        region: process.env.S3_REGION,
        headers: {
          CacheControl: 31536000 /* 1yr */
        }
      },
      prod: {
        cwd: prod_dest,
        src: '**'
      },
    },
    clean: {
      dev: [`${dev_dest}/**/*`],
      prod: [`${prod_dest}/**/*`]
    }
  })

  // Load plugins
  grunt.loadNpmTasks('grunt-browserify')
  grunt.loadNpmTasks('grunt-contrib-sass')
  grunt.loadNpmTasks('grunt-postcss')
  grunt.loadNpmTasks('grunt-contrib-watch')
  grunt.loadNpmTasks('grunt-rsync')
  grunt.loadNpmTasks('grunt-filerev')
  grunt.loadNpmTasks('grunt-contrib-clean')
  grunt.loadNpmTasks('grunt-aws')

  // Default is run and watch everything BUT browserify
  grunt.registerTask('default', [
    'clean:dev', 'sass:dev', 'postcss:dev', 'rsync:dev', 'watch'
  ])

  // TODO: break this out better
  grunt.registerTask('write_filerev', () => {
    var finalPaths = {}
    var substrIndex = prod_dest.length
    for (var orig in grunt.filerev.summary) {
      finalPaths[orig.substring(substrIndex)] = grunt.filerev.summary[orig].substring(substrIndex)
    }
    fs.writeFileSync(`${prod_dest}/${asset_map_dest}`, JSON.stringify(finalPaths))
  })

  // TODO: break this better
  grunt.registerTask('filerev_apply', () => {
    var fs = require('fs'),
      substrIndex = prod_dest.length,
      cssFile = grunt.filerev.summary[`${prod_dest}/main.css`],
      content = fs.readFileSync(cssFile, "utf8"),
      prefix = process.env.CDN_ROOT ? '//' + process.env.CDN_ROOT : ''

    content = content.replace(/url\(["']?([\w\@\.\-\/]+)["']?\)/gi, (match, p1) => {
      var rev_file = prefix + grunt.filerev.summary[`${prod_dest}${p1}`].substring(substrIndex)
      console.log(`Replaced ${p1} with ${rev_file}`)
      return `url(${rev_file})`
    })

    fs.writeFileSync(cssFile, content)
  })

  // Build for production
  grunt.registerTask('production', [
    'clean:prod', 'sass:prod', 'postcss:prod', 'rsync:prod',
    'browserify:vendor_prod', 'browserify:prod', 'filerev:prod', 'filerev_apply',
    'write_filerev'
  ])
}
<|endoftext|>