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

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

        copy: {
            main: {
                files: [

                    // includes files within path and its sub-directories
                    {expand: true, flatten: true, src: ['bower_components/jquery/dist/*'], dest: 'js/vendor/'},
                    {expand: true, flatten: true, src: ['bower_components/bootstrap/dist/js/*'], dest: 'js/vendor/'},
                    {expand: true, flatten: true, src: ['bower_components/bootstrap/dist/css/*'], dest: 'css/vendor/'},
                    {expand: true, flatten: true, src: ['bower_components/fitvids/jquery.fitvids.js'], dest: 'js/vendor/'}

                ]
            }
        },

        less: {
            development: {
                options: {
                    paths: ["css"]
                },
                files: {
                    "css/main.css": "css/main.less"
                }
            },
            production: {
                options: {
                    paths: ["css"]
                },
                files: {
                    "css/main.css": "css/main.less"
                }
            }
        }

    });

    //grunt.loadNpmTasks('grunt-contrib-uglify');
    //grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-contrib-less');

    grunt.registerTask('default', ['copy']);

};<commit_msg>removing development less task for now since it was pointless to have two that did exactly the same thing<commit_after>module.exports = function(grunt) {

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

        copy: {
            main: {
                files: [

                    // includes files within path and its sub-directories
                    {expand: true, flatten: true, src: ['bower_components/jquery/dist/*'], dest: 'js/vendor/'},
                    {expand: true, flatten: true, src: ['bower_components/bootstrap/dist/js/*'], dest: 'js/vendor/'},
                    {expand: true, flatten: true, src: ['bower_components/bootstrap/dist/css/*'], dest: 'css/vendor/'},
                    {expand: true, flatten: true, src: ['bower_components/fitvids/jquery.fitvids.js'], dest: 'js/vendor/'}

                ]
            }
        },

        less: {

            production: {
                options: {
                    paths: ["css"]
                },
                files: {
                    "css/main.css": "css/main.less"
                }
            }
        }

    });

    //grunt.loadNpmTasks('grunt-contrib-uglify');
    //grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-contrib-less');

    grunt.registerTask('default', ['copy']);

};<|endoftext|>


<commit_before>/**
 * Requires npm, which is part of node.js <http://nodejs.org/>
 * To run:
 *   npm install
 *   grunt
 */
module.exports = function(grunt) {
  grunt.initConfig({
    custom_config: grunt.file.readJSON('.env.json'),
    pkg: grunt.file.readJSON('package.json'),
    paths: {
      shared: 'endpoints/shared',
      frontend: 'endpoints/frontend',
      backend: 'endpoints/backend',
      sass: 'includes/scss',
      css: 'includes/css',
      js: 'includes/js',
      src: 'app/src',
      tests: 'app/tests',
      docs: 'docs',
      views: 'app/views',
      routes: 'app/routes.php',
      config: 'app/config',
      storage: 'app/storage'
    },

    clean: {
      symlink: [
        '<%= paths.frontend %>/includes/shared',
        '<%= paths.backend %>/includes/shared',
      ],
      sass: [
        '<%= paths.frontend %>/<%= paths.css %>/dist',
        '<%= paths.backend %>/<%= paths.css %>/dist'
      ],
      js: [
        '<%= paths.frontend %>/<%= paths.js %>/dist',
        '<%= paths.backend %>/<%= paths.js %>/dist'
      ],
      bower: [
        '<%= paths.frontend %>/includes/vendor',
        '<%= paths.backend %>/includes/vendor'
      ],
      viewStorage: [
        '<%= paths.storage %>/views/*'
      ]
    },
    symlink: {
      includes: {
        files: [
            {
              src: '<%= paths.shared %>',
              dest: '<%= paths.frontend %>/includes/shared'
            },
            {
              src: '<%= paths.shared %>',
              dest: '<%= paths.backend %>/includes/shared'
            }
        ]
      }
    },
    chmod: {
        options: {
          mode: '777'
        },
        logs: {
          src: [
            'app/storage/',
            'app/storage/cache/',
            'app/storage/logs/',
            'app/storage/meta/',
            'app/storage/sessions/',
            'app/storage/views/',
            'vendor/ezyang/htmlpurifier/library/HTMLPurifier/DefinitionCache/Serializer'
          ]
        }
    },
    phpunit: {
      classes: {
        dir: '<%= paths.tests %>/phpunit'
      },
      options: {
        colors: true
      }
    },
    phpdocumentor: {
      dist: {
        options: {
          directory : '<%= paths.src %>',
          target : '<%= paths.docs %>'
        }
      }
    },
    shell: {
      bowerFrontend: {
        command: 'bower install',
        options: {
          execOptions: {
            cwd: '<%= paths.frontend %>'
          }
        }
      },
      bowerBackend: {
        command: 'bower install',
        options: {
          execOptions: {
            cwd: '<%= paths.backend %>'
          }
        }
      },
      migrate: {
        command: function() {
          return 'php artisan migrate';
        }
      },
      dbseed: {
        command: function() {
          return 'php artisan db:seed';
        }
      },
      composer: {
        command: 'composer install'
      },
      composerDontPromptForChanges: {
        command: [
          'composer config --global discard-changes true',
          'composer install --no-interaction'
        ].join('&&')
      },
      clearCache: {
        // sudo because cache files owned by apache on server, and not writable
        command: 'sudo php artisan cache:clear'
      }
    },
    copy: {
      css: {
        files: [
          { src: '<%= paths.frontend %>/<%= paths.css %>/dist/main.min.css',
            dest: ".backup/<%= grunt.template.today('yyyy-mm-dd-HH-MM-ss') %>/" },
          { src: '<%= paths.backend %>/<%= paths.css %>/dist/main.min.css',
            dest: ".backup/<%= grunt.template.today('yyyy-mm-dd-HH-MM-ss') %>/" }
        ]
      },
      js: {
        files: [
          { src: '<%= paths.frontend %>/<%= paths.js %>/dist/vendor.combined.min.js',
            dest: ".backup/<%= grunt.template.today('yyyy-mm-dd-HH-MM-ss') %>/" },
          { src: '<%= paths.backend %>/<%= paths.js %>/dist/vendor.combined.min.js',
            dest: ".backup/<%= grunt.template.today('yyyy-mm-dd-HH-MM-ss') %>/" }
        ]
      }
    },
    sass: {
      backend: {
        options: {
          // outputStyle: 'compressed',
          includePaths: [
            '<%= paths.backend %>/includes/vendor/foundation/scss',
            '<%= paths.backend %>/includes/vendor/admin-theme/src/scss',
          ]
        },
        files: {
          '<%= paths.backend %>/<%= paths.css %>/dist/main.min.css':
            '<%= paths.backend %>/<%= paths.sass %>/main.scss'
        }
      },
      frontend: {
        options: {
          // outputStyle: 'compressed',
          includePaths: ['<%= paths.frontend %>/includes/vendor/foundation/scss']
        },
        files: {
          '<%= paths.frontend %>/<%= paths.css %>/dist/main.min.css':
            '<%= paths.frontend %>/<%= paths.sass %>/main.scss'
        }
      }
    },
    wiredep: {
      localBackend: {
        src: [
          'app/views/packages/npmweb/admin-theme-laravel-layout/scripts/bower/_local.blade.php'
        ],
        options: {
          directory: 'endpoints/backend/includes/vendor',
          bowerJson: require('./endpoints/backend/bower.json'),
          ignorePath: '../../../../../../../endpoints/backend/',
          exclude: [/tinymce/]
        },
        fileTypes: {
          html: {
            replace: {
              js: '<script src="\{\{asset(\'{{filePath}}\')\}\}"></script>',
            }
          },
        }
      },
      localFrontend: {
        src: [
          'app/views/frontend/layouts/scripts/bower/_local.blade.php'
        ],
        options: {
          directory: 'endpoints/frontend/includes/vendor',
          bowerJson: require('./endpoints/frontend/bower.json'),
          ignorePath: '../../../../../../endpoints/frontend/',
        },
        fileTypes: {
          html: {
            replace: {
              js: '<script src="\{\{asset(\'{{filePath}}\')\}\}"></script>',
            }
          },
        }
      },
      releaseBackend: {
        src: [
          'app/views/packages/npmweb/admin-theme-laravel-layout/scripts/bower/_for_usemin.blade.php'
        ],
        options: {
          directory: 'endpoints/backend/includes/vendor',
          bowerJson: require('./endpoints/backend/bower.json'),
          ignorePath: '../../../../../../../endpoints/backend/',
          exclude: [/tinymce/]
        }
      },
      releaseFrontend: {
        src: [
          'app/views/frontend/layouts/scripts/bower/_for_usemin.blade.php'
        ],
        options: {
          directory: 'endpoints/frontend/includes/vendor',
          bowerJson: require('./endpoints/frontend/bower.json'),
          ignorePath: '../../../../../../endpoints/frontend/',
        }
      }
    },
    useminPrepare: {
      backend: {
        src: 'app/views/packages/npmweb/admin-theme-laravel-layout/scripts/bower/_for_usemin.blade.php',
        options: {
          dest: 'endpoints/backend'
        }
      },
      frontend: {
        src: 'app/views/frontend/layouts/scripts/bower/_for_usemin.blade.php',
        options: {
          dest: 'endpoints/frontend'
        }
      },
      options: {
        flow: {
          backend: {
            steps: {
              js: ['concat']
            },
            post: {}
          },
          frontend: {
            steps: {
              js: ['concat']
            },
            post: {}
          }
        }
      }
    },
    db_dump: {
      db: {
        options: {
          title: "<%= custom_config.DB_SCHEMA %>",
          host: "<%= custom_config.DB_HOST %>",
          database: "<%= custom_config.DB_SCHEMA %>",
          user: "<%= custom_config.DB_USERNAME %>",
          pass: "<%= custom_config.DB_PASSWORD %>",
          backup_to: "backups/<%= custom_config.DB_SCHEMA %>-<%= grunt.template.today('yyyy-mm-dd-HH-MM-ss') %>.sql"
        },
      }
    },
    watch: {
      bowerFrontend: {
        files: [
          '<%= paths.frontend %>/bower.json',
        ],
        tasks: [
          'shell:bowerFrontend',
          'wiredep:localFrontend'
        ]
      },
      bowerBackend: {
        files: [
          '<%= paths.backend %>/bower.json',
        ],
        tasks: [
          'shell:bowerBackend',
          'wiredep:localBackend'
        ]
      },
      phpunit: {
        files: [
          '<%= paths.tests %>/phpunit/**/*.php',
          '<%= paths.src %>/**/*.php'
        ],
        tasks: ['phpunit','notify:phpunit']
      },
      sass: {
        files: [
          '<%= paths.backend %>/<%= paths.sass %>/**/*.scss',
          '<%= paths.frontend %>/<%= paths.sass %>/**/*.scss'
        ],
        tasks: ['sass','notify:sass']
      }
    },
    notify: {
      phpunit: {
        options: {
          title: 'PHPUnit',
          message: 'All tests passed.'
        }
      },
      sass: {
        options: {
          title: 'Sass',
          message: 'CSS updated.'
        }
      }
    }
  });

  grunt.loadNpmTasks('grunt-chmod');
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-symlink');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-mysql-dump');
  grunt.loadNpmTasks('grunt-notify');
  grunt.loadNpmTasks('grunt-phpunit');
  grunt.loadNpmTasks('grunt-phpdocumentor');
  grunt.loadNpmTasks('grunt-sass');
  grunt.loadNpmTasks('grunt-shell');
  grunt.loadNpmTasks('grunt-wiredep');
  grunt.loadNpmTasks('grunt-usemin');
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-copy');

  grunt.registerTask('default', [
    'shell:composer',
    'symlink',
    'chmod',
    'clean:bower',
    'shell:bowerFrontend',
    'shell:bowerBackend',
    'sass',
    'wiredep:localFrontend',
    'wiredep:localBackend',
    'shell:migrate',
    'shell:dbseed',
    'phpunit'
  ]);
  grunt.registerTask('test', [
    'shell:composerDontPromptForChanges',
    'symlink',
    'chmod',
    'shell:clearCache',
    'clean:viewStorage',
    'clean:bower',
    'shell:bowerFrontend',
    'shell:bowerBackend',
    'sass',
    'myusemin',
    'shell:migrate',
    'shell:dbseed'
  ]);
  grunt.registerTask('production', [
    'shell:composerDontPromptForChanges',
    'symlink',
    'chmod',
    'shell:clearCache',
    'clean:bower',
    'shell:bowerFrontend',
    'shell:bowerBackend',
    'sass',
    'myusemin',
    'shell:migrate'
  ]);
  grunt.registerTask('myusemin', [
    'wiredep:releaseFrontend',
    'wiredep:releaseBackend',
    'useminPrepare:frontend',
    'useminPrepare:backend',
    'concat'
    // don't call usemin itself because it overwrites the block in the file
    // we are using Laravel and a hard-coded script tag to handle that
  ]);
}
<commit_msg>adds db dumping<commit_after>/**
 * Requires npm, which is part of node.js <http://nodejs.org/>
 * To run:
 *   npm install
 *   grunt
 */
module.exports = function(grunt) {
  grunt.initConfig({
    custom_config: grunt.file.readJSON('.env.json'),
    pkg: grunt.file.readJSON('package.json'),
    paths: {
      shared: 'endpoints/shared',
      frontend: 'endpoints/frontend',
      backend: 'endpoints/backend',
      sass: 'includes/scss',
      css: 'includes/css',
      js: 'includes/js',
      src: 'app/src',
      tests: 'app/tests',
      docs: 'docs',
      views: 'app/views',
      routes: 'app/routes.php',
      config: 'app/config',
      storage: 'app/storage'
    },

    clean: {
      symlink: [
        '<%= paths.frontend %>/includes/shared',
        '<%= paths.backend %>/includes/shared',
      ],
      sass: [
        '<%= paths.frontend %>/<%= paths.css %>/dist',
        '<%= paths.backend %>/<%= paths.css %>/dist'
      ],
      js: [
        '<%= paths.frontend %>/<%= paths.js %>/dist',
        '<%= paths.backend %>/<%= paths.js %>/dist'
      ],
      bower: [
        '<%= paths.frontend %>/includes/vendor',
        '<%= paths.backend %>/includes/vendor'
      ],
      viewStorage: [
        '<%= paths.storage %>/views/*'
      ]
    },
    symlink: {
      includes: {
        files: [
            {
              src: '<%= paths.shared %>',
              dest: '<%= paths.frontend %>/includes/shared'
            },
            {
              src: '<%= paths.shared %>',
              dest: '<%= paths.backend %>/includes/shared'
            }
        ]
      }
    },
    chmod: {
        options: {
          mode: '777'
        },
        logs: {
          src: [
            'app/storage/',
            'app/storage/cache/',
            'app/storage/logs/',
            'app/storage/meta/',
            'app/storage/sessions/',
            'app/storage/views/',
            'vendor/ezyang/htmlpurifier/library/HTMLPurifier/DefinitionCache/Serializer'
          ]
        }
    },
    phpunit: {
      classes: {
        dir: '<%= paths.tests %>/phpunit'
      },
      options: {
        colors: true
      }
    },
    phpdocumentor: {
      dist: {
        options: {
          directory : '<%= paths.src %>',
          target : '<%= paths.docs %>'
        }
      }
    },
    shell: {
      bowerFrontend: {
        command: 'bower install',
        options: {
          execOptions: {
            cwd: '<%= paths.frontend %>'
          }
        }
      },
      bowerBackend: {
        command: 'bower install',
        options: {
          execOptions: {
            cwd: '<%= paths.backend %>'
          }
        }
      },
      migrate: {
        command: function() {
          return 'php artisan migrate';
        }
      },
      dbseed: {
        command: function() {
          return 'php artisan db:seed';
        }
      },
      composer: {
        command: 'composer install'
      },
      composerDontPromptForChanges: {
        command: [
          'composer config --global discard-changes true',
          'composer install --no-interaction'
        ].join('&&')
      },
      clearCache: {
        // sudo because cache files owned by apache on server, and not writable
        command: 'sudo php artisan cache:clear'
      }
    },
    copy: {
      css: {
        files: [
          { src: '<%= paths.frontend %>/<%= paths.css %>/dist/main.min.css',
            dest: ".backup/<%= grunt.template.today('yyyy-mm-dd-HH-MM-ss') %>/" },
          { src: '<%= paths.backend %>/<%= paths.css %>/dist/main.min.css',
            dest: ".backup/<%= grunt.template.today('yyyy-mm-dd-HH-MM-ss') %>/" }
        ]
      },
      js: {
        files: [
          { src: '<%= paths.frontend %>/<%= paths.js %>/dist/vendor.combined.min.js',
            dest: ".backup/<%= grunt.template.today('yyyy-mm-dd-HH-MM-ss') %>/" },
          { src: '<%= paths.backend %>/<%= paths.js %>/dist/vendor.combined.min.js',
            dest: ".backup/<%= grunt.template.today('yyyy-mm-dd-HH-MM-ss') %>/" }
        ]
      }
    },
    sass: {
      backend: {
        options: {
          // outputStyle: 'compressed',
          includePaths: [
            '<%= paths.backend %>/includes/vendor/foundation/scss',
            '<%= paths.backend %>/includes/vendor/admin-theme/src/scss',
          ]
        },
        files: {
          '<%= paths.backend %>/<%= paths.css %>/dist/main.min.css':
            '<%= paths.backend %>/<%= paths.sass %>/main.scss'
        }
      },
      frontend: {
        options: {
          // outputStyle: 'compressed',
          includePaths: ['<%= paths.frontend %>/includes/vendor/foundation/scss']
        },
        files: {
          '<%= paths.frontend %>/<%= paths.css %>/dist/main.min.css':
            '<%= paths.frontend %>/<%= paths.sass %>/main.scss'
        }
      }
    },
    wiredep: {
      localBackend: {
        src: [
          'app/views/packages/npmweb/admin-theme-laravel-layout/scripts/bower/_local.blade.php'
        ],
        options: {
          directory: 'endpoints/backend/includes/vendor',
          bowerJson: require('./endpoints/backend/bower.json'),
          ignorePath: '../../../../../../../endpoints/backend/',
          exclude: [/tinymce/]
        },
        fileTypes: {
          html: {
            replace: {
              js: '<script src="\{\{asset(\'{{filePath}}\')\}\}"></script>',
            }
          },
        }
      },
      localFrontend: {
        src: [
          'app/views/frontend/layouts/scripts/bower/_local.blade.php'
        ],
        options: {
          directory: 'endpoints/frontend/includes/vendor',
          bowerJson: require('./endpoints/frontend/bower.json'),
          ignorePath: '../../../../../../endpoints/frontend/',
        },
        fileTypes: {
          html: {
            replace: {
              js: '<script src="\{\{asset(\'{{filePath}}\')\}\}"></script>',
            }
          },
        }
      },
      releaseBackend: {
        src: [
          'app/views/packages/npmweb/admin-theme-laravel-layout/scripts/bower/_for_usemin.blade.php'
        ],
        options: {
          directory: 'endpoints/backend/includes/vendor',
          bowerJson: require('./endpoints/backend/bower.json'),
          ignorePath: '../../../../../../../endpoints/backend/',
          exclude: [/tinymce/]
        }
      },
      releaseFrontend: {
        src: [
          'app/views/frontend/layouts/scripts/bower/_for_usemin.blade.php'
        ],
        options: {
          directory: 'endpoints/frontend/includes/vendor',
          bowerJson: require('./endpoints/frontend/bower.json'),
          ignorePath: '../../../../../../endpoints/frontend/',
        }
      }
    },
    useminPrepare: {
      backend: {
        src: 'app/views/packages/npmweb/admin-theme-laravel-layout/scripts/bower/_for_usemin.blade.php',
        options: {
          dest: 'endpoints/backend'
        }
      },
      frontend: {
        src: 'app/views/frontend/layouts/scripts/bower/_for_usemin.blade.php',
        options: {
          dest: 'endpoints/frontend'
        }
      },
      options: {
        flow: {
          backend: {
            steps: {
              js: ['concat']
            },
            post: {}
          },
          frontend: {
            steps: {
              js: ['concat']
            },
            post: {}
          }
        }
      }
    },
    db_dump: {
      db: {
        options: {
          title: "<%= custom_config.DB_SCHEMA %>",
          host: "<%= custom_config.DB_HOST %>",
          database: "<%= custom_config.DB_SCHEMA %>",
          user: "<%= custom_config.DB_USERNAME %>",
          pass: "<%= custom_config.DB_PASSWORD %>",
          backup_to: "backups/<%= custom_config.DB_SCHEMA %>-<%= grunt.template.today('yyyy-mm-dd-HH-MM-ss') %>.sql"
        },
      }
    },
    watch: {
      bowerFrontend: {
        files: [
          '<%= paths.frontend %>/bower.json',
        ],
        tasks: [
          'shell:bowerFrontend',
          'wiredep:localFrontend'
        ]
      },
      bowerBackend: {
        files: [
          '<%= paths.backend %>/bower.json',
        ],
        tasks: [
          'shell:bowerBackend',
          'wiredep:localBackend'
        ]
      },
      phpunit: {
        files: [
          '<%= paths.tests %>/phpunit/**/*.php',
          '<%= paths.src %>/**/*.php'
        ],
        tasks: ['phpunit','notify:phpunit']
      },
      sass: {
        files: [
          '<%= paths.backend %>/<%= paths.sass %>/**/*.scss',
          '<%= paths.frontend %>/<%= paths.sass %>/**/*.scss'
        ],
        tasks: ['sass','notify:sass']
      }
    },
    notify: {
      phpunit: {
        options: {
          title: 'PHPUnit',
          message: 'All tests passed.'
        }
      },
      sass: {
        options: {
          title: 'Sass',
          message: 'CSS updated.'
        }
      }
    }
  });

  grunt.loadNpmTasks('grunt-chmod');
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-symlink');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-mysql-dump');
  grunt.loadNpmTasks('grunt-notify');
  grunt.loadNpmTasks('grunt-phpunit');
  grunt.loadNpmTasks('grunt-phpdocumentor');
  grunt.loadNpmTasks('grunt-sass');
  grunt.loadNpmTasks('grunt-shell');
  grunt.loadNpmTasks('grunt-wiredep');
  grunt.loadNpmTasks('grunt-usemin');
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-copy');

  grunt.registerTask('default', [
    'shell:composer',
    'symlink',
    'chmod',
    'clean:bower',
    'shell:bowerFrontend',
    'shell:bowerBackend',
    'sass',
    'wiredep:localFrontend',
    'wiredep:localBackend',
    'db_dump',
    'shell:migrate',
    'shell:dbseed',
    'phpunit'
  ]);
  grunt.registerTask('test', [
    'shell:composerDontPromptForChanges',
    'symlink',
    'chmod',
    'shell:clearCache',
    'clean:viewStorage',
    'clean:bower',
    'shell:bowerFrontend',
    'shell:bowerBackend',
    'sass',
    'myusemin',
    'db_dump',
    'shell:migrate',
    'shell:dbseed'
  ]);
  grunt.registerTask('production', [
    'shell:composerDontPromptForChanges',
    'symlink',
    'chmod',
    'shell:clearCache',
    'clean:bower',
    'shell:bowerFrontend',
    'shell:bowerBackend',
    'sass',
    'myusemin',
    'db_dump',
    'shell:migrate'
  ]);
  grunt.registerTask('myusemin', [
    'wiredep:releaseFrontend',
    'wiredep:releaseBackend',
    'useminPrepare:frontend',
    'useminPrepare:backend',
    'concat'
    // don't call usemin itself because it overwrites the block in the file
    // we are using Laravel and a hard-coded script tag to handle that
  ]);
}
<|endoftext|>


<commit_before>describe('Unit: resizeImage filter', function () {
    beforeEach(module('placesWidgetFilters'));
    var filter;
    beforeEach(inject(function (_$filter_) {
        filter = _$filter_;
    }));

    it('it should pass if "resizeImage" filter returns resized image url', function () {
        var result;
        result = filter('resizeImage')('https://imagelibserver.s3.amazonaws.com/25935164-2add-11e5-9d04-02f7ca55c361/950a50c0-400a-11e5-9af5-3f5e0d725ccb.jpg', 88, 124, 'resize');
        expect(result).toEqual("http://s7obnu.cloudimage.io/s/resizenp/88x124/https://imagelibserver.s3.amazonaws.com/25935164-2add-11e5-9d04-02f7ca55c361/950a50c0-400a-11e5-9af5-3f5e0d725ccb.jpg");
    });

    it('it should give a default image even if parameter is blank', function () {
        var result;
        result = filter('resizeImage')('', 88, 124, 'resize');
        expect(result).toEqual("http://s7obnu.cloudimage.io/s/resizenp/88x124/");
    });
});
describe('Unit: cropImage filter', function () {
    beforeEach(module('placesWidgetFilters'));
    var filter;
    beforeEach(inject(function (_$filter_) {
        filter = _$filter_;
    }));

    it('it should pass if "cropImage" filter returns cropped image url', function () {
        var result;
        result = filter('cropImage')('https://www.facebook.com/photo.php?fbid=1008284442533844&set=a.359021657460129.98766.100000568920267&type=1&theater', 88, 124);
        expect(result).toEqual("http://s7obnu.cloudimage.io/s/crop/88x124/https://www.facebook.com/photo.php?fbid=1008284442533844&set=a.359021657460129.98766.100000568920267&type=1&theater");
    });

    it('it should give a default image even if parameter is blank', function () {
        var result;
        result = filter('cropImage')('', 88, 124);
        expect(result).toEqual("http://s7obnu.cloudimage.io/s/crop/88x124/");
    });
});

describe('Unit: safeHtml filter', function () {
    beforeEach(module('placesWidgetFilters'));
    var filter,$sce,$scope;
    beforeEach(inject(function (_$rootScope_,_$filter_,_$sce_) {
        filter = _$filter_;
        $sce=_$sce_;

        $scope=_$rootScope_;
    }));

    it('safeHtml filter should returns an empty string if html value not provided', function () {
        var result;
        result = filter('safeHtml')(null);
        expect(result).toEqual('');
    });
    it('safeHtml filter should returns an empty string if html value provided', function () {
        var result;
        result = filter('safeHtml')("

Sandeep kumar
");
        expect(typeof result).toEqual('object');
    });
});
<commit_msg>test cases added for filter.js in widget section<commit_after>describe('Unit: resizeImage filter', function () {
    beforeEach(module('placesWidgetFilters'));
    var filter;
    beforeEach(inject(function (_$filter_) {
        filter = _$filter_;
    }));

    it('it should pass if "resizeImage" filter returns resized image url', function () {
        var result;
        result = filter('resizeImage')('https://imagelibserver.s3.amazonaws.com/25935164-2add-11e5-9d04-02f7ca55c361/950a50c0-400a-11e5-9af5-3f5e0d725ccb.jpg', 88, 124, 'resize');
        expect(result).toEqual("http://s7obnu.cloudimage.io/s/resizenp/88x124/https://imagelibserver.s3.amazonaws.com/25935164-2add-11e5-9d04-02f7ca55c361/950a50c0-400a-11e5-9af5-3f5e0d725ccb.jpg");
    });

    it('it should give a default image even if parameter is blank', function () {
        var result;
        result = filter('resizeImage')('', 88, 124, 'resize');
        expect(result).toEqual("http://s7obnu.cloudimage.io/s/resizenp/88x124/");
    });
});
describe('Unit: cropImage filter', function () {
    beforeEach(module('placesWidgetFilters'));
    var filter;
    beforeEach(inject(function (_$filter_) {
        filter = _$filter_;
    }));

    it('it should pass if "cropImage" filter returns cropped image url', function () {
        var result;
        result = filter('cropImage')('https://www.facebook.com/photo.php?fbid=1008284442533844&set=a.359021657460129.98766.100000568920267&type=1&theater', 88, 124);
        expect(result).toEqual("http://s7obnu.cloudimage.io/s/crop/88x124/https://www.facebook.com/photo.php?fbid=1008284442533844&set=a.359021657460129.98766.100000568920267&type=1&theater");
    });

    it('it should give a default image even if parameter is blank', function () {
        var result;
        result = filter('cropImage')('', 88, 124);
        expect(result).toEqual("http://s7obnu.cloudimage.io/s/crop/88x124/");
    });
});

describe('Unit: safeHtml filter', function () {
    beforeEach(module('placesWidgetFilters'));
    var filter,$sce,$scope;
    beforeEach(inject(function (_$rootScope_,_$filter_,_$sce_) {
        filter = _$filter_;
        $sce=_$sce_;

        $scope=_$rootScope_;
    }));

    it('safeHtml filter should returns an empty string if html value not provided', function () {
        var result;
        result = filter('safeHtml')(null);
        expect(result).toEqual('');
    });
    it('safeHtml filter should returns an empty string if html value provided', function () {
        var result;
        result = filter('safeHtml')("

Sandeep kumar
");
        expect(typeof result).toEqual('object');
    });
});

describe('Unit: unique filter', function () {
    beforeEach(module('placesWidgetFilters'));
    var filter,$sce,$scope;
    beforeEach(inject(function (_$rootScope_,_$filter_,_$sce_) {
        filter = _$filter_;
        $sce=_$sce_;

        $scope=_$rootScope_;
    }));

    it('unique filter should returns an empty string if html value not provided', function () {
        var result;
        result = filter('unique')([{'id':'id1'},{'id':'id2'}],'id');
        expect(result.length).toEqual(2);
    });
});
<|endoftext|>


<commit_before>// Generated on 2015-06-11 using generator-angular 0.11.1
'use strict';

// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'

module.exports = function (grunt) {

  // Load grunt tasks automatically
  require('load-grunt-tasks')(grunt);

  // Time how long tasks take. Can help when optimizing build times
  require('time-grunt')(grunt);

  // Configurable paths for the application
  var appConfig = {
    app: require('./bower.json').appPath || 'app',
    dist: 'dist'
  };

  // Define the configuration for all the tasks
  grunt.initConfig({

    // Project settings
    yeoman: appConfig,

    // Watches files for changes and runs tasks based on the changed files
    watch: {
      bower: {
        files: ['bower.json'],
        tasks: ['wiredep']
      },
      js: {
        files: ['<%= yeoman.app %>/scripts/{,*/}*.js'],
        tasks: ['newer:jshint:all'],
        options: {
          livereload: '<%= connect.options.livereload %>'
        }
      },
      jsTest: {
        files: ['test/spec/{,*/}*.js'],
        tasks: ['newer:jshint:test', 'karma']
      },
      compass: {
        files: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
        tasks: ['compass:server', 'autoprefixer']
      },
      gruntfile: {
        files: ['Gruntfile.js']
      },
      livereload: {
        options: {
          livereload: '<%= connect.options.livereload %>'
        },
        files: [
          '<%= yeoman.app %>/{,*/}*.html',
          '.tmp/styles/{,*/}*.css',
          '<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
        ]
      }
    },

    // The actual grunt server settings
    connect: {
      options: {
        port: 9000,
        // Change this to '0.0.0.0' to access the server from outside.
        hostname: 'localhost',
        livereload: 35729
      },
      livereload: {
        options: {
          open: true,
          middleware: function (connect) {
            return [
              connect.static('.tmp'),
              connect().use(
                '/bower_components',
                connect.static('./bower_components')
              ),
              connect().use(
                '/app/styles',
                connect.static('./app/styles')
              ),
              connect.static(appConfig.app)
            ];
          }
        }
      },
      test: {
        options: {
          port: 9001,
          middleware: function (connect) {
            return [
              connect.static('.tmp'),
              connect.static('test'),
              connect().use(
                '/bower_components',
                connect.static('./bower_components')
              ),
              connect.static(appConfig.app)
            ];
          }
        }
      },
      dist: {
        options: {
          open: true,
          base: '<%= yeoman.dist %>'
        }
      }
    },

    // Make sure code styles are up to par and there are no obvious mistakes
    jshint: {
      options: {
        jshintrc: '.jshintrc',
        reporter: require('jshint-stylish')
      },
      all: {
        src: [
          'Gruntfile.js',
          '<%= yeoman.app %>/scripts/{,*/}*.js'
        ]
      },
      test: {
        options: {
          jshintrc: 'test/.jshintrc'
        },
        src: ['test/spec/{,*/}*.js']
      }
    },

    // Empties folders to start fresh
    clean: {
      dist: {
        files: [{
          dot: true,
          src: [
            '.tmp',
            '<%= yeoman.dist %>/{,*/}*',
            '!<%= yeoman.dist %>/.git{,*/}*'
          ]
        }]
      },
      server: '.tmp'
    },

    // Add vendor prefixed styles
    autoprefixer: {
      options: {
        browsers: ['last 1 version']
      },
      server: {
        options: {
          map: true,
        },
        files: [{
          expand: true,
          cwd: '.tmp/styles/',
          src: '{,*/}*.css',
          dest: '.tmp/styles/'
        }]
      },
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/styles/',
          src: '{,*/}*.css',
          dest: '.tmp/styles/'
        }]
      }
    },

    // Automatically inject Bower components into the app
    wiredep: {
      app: {
        src: ['<%= yeoman.app %>/index.html'],
        ignorePath:  /\.\.\//
      },
      test: {
        devDependencies: true,
        src: '<%= karma.unit.configFile %>',
        ignorePath:  /\.\.\//,
        fileTypes:{
          js: {
            block: /(([\s\t]*)\/{2}\s*?bower:\s*?(\S*))(\n|\r|.)*?(\/{2}\s*endbower)/gi,
              detect: {
                js: /'(.*\.js)'/gi
              },
              replace: {
                js: '\'{{filePath}}\','
              }
            }
          }
      },
      sass: {
        src: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
        ignorePath: /(\.\.\/){1,2}bower_components\//
      }
    },

    // Compiles Sass to CSS and generates necessary files if requested
    compass: {
      options: {
        sassDir: '<%= yeoman.app %>/styles',
        cssDir: '.tmp/styles',
        generatedImagesDir: '.tmp/images/generated',
        imagesDir: '<%= yeoman.app %>/images',
        javascriptsDir: '<%= yeoman.app %>/scripts',
        fontsDir: '<%= yeoman.app %>/styles/fonts',
        importPath: './bower_components',
        httpImagesPath: '/images',
        httpGeneratedImagesPath: '/images/generated',
        httpFontsPath: '/styles/fonts',
        relativeAssets: false,
        assetCacheBuster: false,
        raw: 'Sass::Script::Number.precision = 10\n'
      },
      dist: {
        options: {
          generatedImagesDir: '<%= yeoman.dist %>/images/generated'
        }
      },
      server: {
        options: {
          sourcemap: true
        }
      }
    },

    // Renames files for browser caching purposes
    filerev: {
      dist: {
        src: [
          '<%= yeoman.dist %>/scripts/{,*/}*.js',
          '<%= yeoman.dist %>/styles/{,*/}*.css',
          '<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
          '<%= yeoman.dist %>/styles/fonts/*'
        ]
      }
    },

    // Reads HTML for usemin blocks to enable smart builds that automatically
    // concat, minify and revision files. Creates configurations in memory so
    // additional tasks can operate on them
    useminPrepare: {
      html: '<%= yeoman.app %>/index.html',
      options: {
        dest: '<%= yeoman.dist %>',
        flow: {
          html: {
            steps: {
              js: ['concat', 'uglifyjs'],
              css: ['cssmin']
            },
            post: {}
          }
        }
      }
    },

    // Performs rewrites based on filerev and the useminPrepare configuration
    usemin: {
      html: ['<%= yeoman.dist %>/{,*/}*.html'],
      css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
      options: {
        assetsDirs: [
          '<%= yeoman.dist %>',
          '<%= yeoman.dist %>/images',
          '<%= yeoman.dist %>/styles'
        ]
      }
    },

    // The following *-min tasks will produce minified files in the dist folder
    // By default, your `index.html`'s <!-- Usemin block --> will take care of
    // minification. These next options are pre-configured if you do not wish
    // to use the Usemin blocks.
    // cssmin: {
    //   dist: {
    //     files: {
    //       '<%= yeoman.dist %>/styles/main.css': [
    //         '.tmp/styles/{,*/}*.css'
    //       ]
    //     }
    //   }
    // },
    // uglify: {
    //   dist: {
    //     files: {
    //       '<%= yeoman.dist %>/scripts/scripts.js': [
    //         '<%= yeoman.dist %>/scripts/scripts.js'
    //       ]
    //     }
    //   }
    // },
    // concat: {
    //   dist: {}
    // },

    imagemin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>/images',
          src: '{,*/}*.{png,jpg,jpeg,gif}',
          dest: '<%= yeoman.dist %>/images'
        }]
      }
    },

    svgmin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>/images',
          src: '{,*/}*.svg',
          dest: '<%= yeoman.dist %>/images'
        }]
      }
    },

    htmlmin: {
      dist: {
        options: {
          collapseWhitespace: true,
          conservativeCollapse: true,
          collapseBooleanAttributes: true,
          removeCommentsFromCDATA: true,
          removeOptionalTags: true
        },
        files: [{
          expand: true,
          cwd: '<%= yeoman.dist %>',
          src: ['*.html', 'views/{,*/}*.html'],
          dest: '<%= yeoman.dist %>'
        }]
      }
    },

    // ng-annotate tries to make the code safe for minification automatically
    // by using the Angular long form for dependency injection.
    ngAnnotate: {
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/concat/scripts',
          src: '*.js',
          dest: '.tmp/concat/scripts'
        }]
      }
    },

    // Replace Google CDN references
    cdnify: {
      dist: {
        html: ['<%= yeoman.dist %>/*.html']
      }
    },

    // Copies remaining files to places other tasks can use
    copy: {
      dist: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%= yeoman.app %>',
          dest: '<%= yeoman.dist %>',
          src: [
            '*.{ico,png,txt}',
            '.htaccess',
            '*.html',
            'views/{,*/}*.html',
            'images/{,*/}*.{webp}',
            'styles/fonts/{,*/}*.*'
          ]
        }, {
          expand: true,
          cwd: '.tmp/images',
          dest: '<%= yeoman.dist %>/images',
          src: ['generated/*']
        }, {
          expand: true,
          cwd: '.',
          src: 'bower_components/bootstrap-sass-official/assets/fonts/bootstrap/*',
          dest: '<%= yeoman.dist %>'
        }]
      },
      styles: {
        expand: true,
        cwd: '<%= yeoman.app %>/styles',
        dest: '.tmp/styles/',
        src: '{,*/}*.css'
      }
    },

    // Run some tasks in parallel to speed up the build process
    concurrent: {
      server: [
        'compass:server'
      ],
      test: [
        'compass'
      ],
      dist: [
        'compass:dist',
        'imagemin',
        'svgmin'
      ]
    },

    // Test settings
    karma: {
      unit: {
        configFile: 'test/karma.conf.js',
        singleRun: true
      }
    },

    // Grunt task to load coverage results and submit them to Coveralls.io
    coveralls: {
      options: {
        debug: true,
        coverageDir: 'coverage',
        dryRun: true,
        force: true,
        recursive: true
      }
    }
  });

  grunt.registerTask('serve', 'Compile then start a connect web server', function (target) {
    if (target === 'dist') {
      return grunt.task.run(['build', 'connect:dist:keepalive']);
    }

    grunt.task.run([
      'clean:server',
      'wiredep',
      'concurrent:server',
      'autoprefixer:server',
      'connect:livereload',
      'watch'
    ]);
  });

  grunt.registerTask('server', 'DEPRECATED TASK. Use the "serve" task instead', function (target) {
    grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
    grunt.task.run(['serve:' + target]);
  });

  grunt.registerTask('test', [
    'clean:server',
    'wiredep',
    'concurrent:test',
    'autoprefixer',
    'connect:test',
    'karma'
  ]);

  grunt.registerTask('build', [
    'clean:dist',
    'wiredep',
    'useminPrepare',
    'concurrent:dist',
    'autoprefixer',
    'concat',
    'ngAnnotate',
    'copy:dist',
    'cdnify',
    'cssmin',
    'uglify',
    'filerev',
    'usemin',
    'htmlmin'
  ]);

  grunt.registerTask('default', [
    'newer:jshint',
    'test',
    'build'
  ]);
};
<commit_msg>Added coverage<commit_after>// Generated on 2015-06-11 using generator-angular 0.11.1
'use strict';

// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'

module.exports = function (grunt) {

  // Load grunt tasks automatically
  require('load-grunt-tasks')(grunt);

  // Time how long tasks take. Can help when optimizing build times
  require('time-grunt')(grunt);

  // Configurable paths for the application
  var appConfig = {
    app: require('./bower.json').appPath || 'app',
    dist: 'dist'
  };

  // Define the configuration for all the tasks
  grunt.initConfig({

    // Project settings
    yeoman: appConfig,

    // Watches files for changes and runs tasks based on the changed files
    watch: {
      bower: {
        files: ['bower.json'],
        tasks: ['wiredep']
      },
      js: {
        files: ['<%= yeoman.app %>/scripts/{,*/}*.js'],
        tasks: ['newer:jshint:all'],
        options: {
          livereload: '<%= connect.options.livereload %>'
        }
      },
      jsTest: {
        files: ['test/spec/{,*/}*.js'],
        tasks: ['newer:jshint:test', 'karma']
      },
      compass: {
        files: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
        tasks: ['compass:server', 'autoprefixer']
      },
      gruntfile: {
        files: ['Gruntfile.js']
      },
      livereload: {
        options: {
          livereload: '<%= connect.options.livereload %>'
        },
        files: [
          '<%= yeoman.app %>/{,*/}*.html',
          '.tmp/styles/{,*/}*.css',
          '<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
        ]
      }
    },

    // The actual grunt server settings
    connect: {
      options: {
        port: 9000,
        // Change this to '0.0.0.0' to access the server from outside.
        hostname: 'localhost',
        livereload: 35729
      },
      livereload: {
        options: {
          open: true,
          middleware: function (connect) {
            return [
              connect.static('.tmp'),
              connect().use(
                '/bower_components',
                connect.static('./bower_components')
              ),
              connect().use(
                '/app/styles',
                connect.static('./app/styles')
              ),
              connect.static(appConfig.app)
            ];
          }
        }
      },
      test: {
        options: {
          port: 9001,
          middleware: function (connect) {
            return [
              connect.static('.tmp'),
              connect.static('test'),
              connect().use(
                '/bower_components',
                connect.static('./bower_components')
              ),
              connect.static(appConfig.app)
            ];
          }
        }
      },
      dist: {
        options: {
          open: true,
          base: '<%= yeoman.dist %>'
        }
      }
    },

    // Make sure code styles are up to par and there are no obvious mistakes
    jshint: {
      options: {
        jshintrc: '.jshintrc',
        reporter: require('jshint-stylish')
      },
      all: {
        src: [
          'Gruntfile.js',
          '<%= yeoman.app %>/scripts/{,*/}*.js'
        ]
      },
      test: {
        options: {
          jshintrc: 'test/.jshintrc'
        },
        src: ['test/spec/{,*/}*.js']
      }
    },

    // Empties folders to start fresh
    clean: {
      dist: {
        files: [{
          dot: true,
          src: [
            '.tmp',
            '<%= yeoman.dist %>/{,*/}*',
            '!<%= yeoman.dist %>/.git{,*/}*'
          ]
        }]
      },
      server: '.tmp'
    },

    // Add vendor prefixed styles
    autoprefixer: {
      options: {
        browsers: ['last 1 version']
      },
      server: {
        options: {
          map: true,
        },
        files: [{
          expand: true,
          cwd: '.tmp/styles/',
          src: '{,*/}*.css',
          dest: '.tmp/styles/'
        }]
      },
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/styles/',
          src: '{,*/}*.css',
          dest: '.tmp/styles/'
        }]
      }
    },

    // Automatically inject Bower components into the app
    wiredep: {
      app: {
        src: ['<%= yeoman.app %>/index.html'],
        ignorePath:  /\.\.\//
      },
      test: {
        devDependencies: true,
        src: '<%= karma.unit.configFile %>',
        ignorePath:  /\.\.\//,
        fileTypes:{
          js: {
            block: /(([\s\t]*)\/{2}\s*?bower:\s*?(\S*))(\n|\r|.)*?(\/{2}\s*endbower)/gi,
              detect: {
                js: /'(.*\.js)'/gi
              },
              replace: {
                js: '\'{{filePath}}\','
              }
            }
          }
      },
      sass: {
        src: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
        ignorePath: /(\.\.\/){1,2}bower_components\//
      }
    },

    // Compiles Sass to CSS and generates necessary files if requested
    compass: {
      options: {
        sassDir: '<%= yeoman.app %>/styles',
        cssDir: '.tmp/styles',
        generatedImagesDir: '.tmp/images/generated',
        imagesDir: '<%= yeoman.app %>/images',
        javascriptsDir: '<%= yeoman.app %>/scripts',
        fontsDir: '<%= yeoman.app %>/styles/fonts',
        importPath: './bower_components',
        httpImagesPath: '/images',
        httpGeneratedImagesPath: '/images/generated',
        httpFontsPath: '/styles/fonts',
        relativeAssets: false,
        assetCacheBuster: false,
        raw: 'Sass::Script::Number.precision = 10\n'
      },
      dist: {
        options: {
          generatedImagesDir: '<%= yeoman.dist %>/images/generated'
        }
      },
      server: {
        options: {
          sourcemap: true
        }
      }
    },

    // Renames files for browser caching purposes
    filerev: {
      dist: {
        src: [
          '<%= yeoman.dist %>/scripts/{,*/}*.js',
          '<%= yeoman.dist %>/styles/{,*/}*.css',
          '<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
          '<%= yeoman.dist %>/styles/fonts/*'
        ]
      }
    },

    // Reads HTML for usemin blocks to enable smart builds that automatically
    // concat, minify and revision files. Creates configurations in memory so
    // additional tasks can operate on them
    useminPrepare: {
      html: '<%= yeoman.app %>/index.html',
      options: {
        dest: '<%= yeoman.dist %>',
        flow: {
          html: {
            steps: {
              js: ['concat', 'uglifyjs'],
              css: ['cssmin']
            },
            post: {}
          }
        }
      }
    },

    // Performs rewrites based on filerev and the useminPrepare configuration
    usemin: {
      html: ['<%= yeoman.dist %>/{,*/}*.html'],
      css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
      options: {
        assetsDirs: [
          '<%= yeoman.dist %>',
          '<%= yeoman.dist %>/images',
          '<%= yeoman.dist %>/styles'
        ]
      }
    },

    // The following *-min tasks will produce minified files in the dist folder
    // By default, your `index.html`'s <!-- Usemin block --> will take care of
    // minification. These next options are pre-configured if you do not wish
    // to use the Usemin blocks.
    // cssmin: {
    //   dist: {
    //     files: {
    //       '<%= yeoman.dist %>/styles/main.css': [
    //         '.tmp/styles/{,*/}*.css'
    //       ]
    //     }
    //   }
    // },
    // uglify: {
    //   dist: {
    //     files: {
    //       '<%= yeoman.dist %>/scripts/scripts.js': [
    //         '<%= yeoman.dist %>/scripts/scripts.js'
    //       ]
    //     }
    //   }
    // },
    // concat: {
    //   dist: {}
    // },

    imagemin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>/images',
          src: '{,*/}*.{png,jpg,jpeg,gif}',
          dest: '<%= yeoman.dist %>/images'
        }]
      }
    },

    svgmin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>/images',
          src: '{,*/}*.svg',
          dest: '<%= yeoman.dist %>/images'
        }]
      }
    },

    htmlmin: {
      dist: {
        options: {
          collapseWhitespace: true,
          conservativeCollapse: true,
          collapseBooleanAttributes: true,
          removeCommentsFromCDATA: true,
          removeOptionalTags: true
        },
        files: [{
          expand: true,
          cwd: '<%= yeoman.dist %>',
          src: ['*.html', 'views/{,*/}*.html'],
          dest: '<%= yeoman.dist %>'
        }]
      }
    },

    // ng-annotate tries to make the code safe for minification automatically
    // by using the Angular long form for dependency injection.
    ngAnnotate: {
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/concat/scripts',
          src: '*.js',
          dest: '.tmp/concat/scripts'
        }]
      }
    },

    // Replace Google CDN references
    cdnify: {
      dist: {
        html: ['<%= yeoman.dist %>/*.html']
      }
    },

    // Copies remaining files to places other tasks can use
    copy: {
      dist: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%= yeoman.app %>',
          dest: '<%= yeoman.dist %>',
          src: [
            '*.{ico,png,txt}',
            '.htaccess',
            '*.html',
            'views/{,*/}*.html',
            'images/{,*/}*.{webp}',
            'styles/fonts/{,*/}*.*'
          ]
        }, {
          expand: true,
          cwd: '.tmp/images',
          dest: '<%= yeoman.dist %>/images',
          src: ['generated/*']
        }, {
          expand: true,
          cwd: '.',
          src: 'bower_components/bootstrap-sass-official/assets/fonts/bootstrap/*',
          dest: '<%= yeoman.dist %>'
        }]
      },
      styles: {
        expand: true,
        cwd: '<%= yeoman.app %>/styles',
        dest: '.tmp/styles/',
        src: '{,*/}*.css'
      }
    },

    // Run some tasks in parallel to speed up the build process
    concurrent: {
      server: [
        'compass:server'
      ],
      test: [
        'compass'
      ],
      dist: [
        'compass:dist',
        'imagemin',
        'svgmin'
      ]
    },

    // Test settings
    karma: {
      unit: {
        configFile: 'test/karma.conf.js',
        singleRun: true
      }
    },

    // Grunt task to load coverage results and submit them to Coveralls.io
    coveralls: {
      options: {
        debug: true,
        coverageDir: 'coverage',
        dryRun: true,
        force: true,
        recursive: true
      }
    }
  });

  grunt.registerTask('serve', 'Compile then start a connect web server', function (target) {
    if (target === 'dist') {
      return grunt.task.run(['build', 'connect:dist:keepalive']);
    }

    grunt.task.run([
      'clean:server',
      'wiredep',
      'concurrent:server',
      'autoprefixer:server',
      'connect:livereload',
      'watch'
    ]);
  });

  grunt.registerTask('server', 'DEPRECATED TASK. Use the "serve" task instead', function (target) {
    grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
    grunt.task.run(['serve:' + target]);
  });

  grunt.registerTask('test', [
    'clean:server',
    'wiredep',
    'concurrent:test',
    'autoprefixer',
    'connect:test',
    'karma',
    'coveralls'
  ]);

  grunt.registerTask('build', [
    'clean:dist',
    'wiredep',
    'useminPrepare',
    'concurrent:dist',
    'autoprefixer',
    'concat',
    'ngAnnotate',
    'copy:dist',
    'cdnify',
    'cssmin',
    'uglify',
    'filerev',
    'usemin',
    'htmlmin'
  ]);

  grunt.registerTask('default', [
    'newer:jshint',
    'test',
    'build'
  ]);
};
<|endoftext|>


<commit_before>var _ = require('underscore');
var timer = require('grunt-timer');
var semver = require('semver');
var jasmineCfg = require('./lib/build/tasks/jasmine.js');
var shrinkwrapDependencies = require('./lib/build/tasks/shrinkwrap-dependencies.js');
var webpackTask = null;

var REQUIRED_NODE_VERSION = '6.9.2';
var REQUIRED_NPM_VERSION = '3.10.9';

var DEVELOPMENT = 'development';

var SHRINKWRAP_MODULES_TO_VALIDATE = [
  'backbone',
  'camshaft-reference',
  'carto',
  'internal-carto.js',
  'cartocolor',
  'd3',
  'jquery',
  'leaflet',
  'perfect-scrollbar',
  'torque.js',
  'turbo-carto'
];

function requireWebpackTask () {
  if (webpackTask === null) {
    webpackTask = require('./lib/build/tasks/webpack/webpack.js');
  }
  return webpackTask;
}

function logVersionsError (err, requiredNodeVersion, requiredNpmVersion) {
  if (err) {
    grunt.log.fail('############### /!\\ CAUTION /!\\ #################');
    grunt.log.fail('PLEASE installed required versions to build CARTO:\n- node: ' + requiredNodeVersion + '\n- node: ' + requiredNpmVersion);
    grunt.log.fail('#################################################');
    process.exit(1);
  }
}

function getTargetDiff () {
  var target = require('child_process').execSync('(git diff --name-only --relative || true;' +
                                                 'git diff origin/master.. --name-only --relative || true;)' +
                                                 '| grep \'\\.js\\?$\' || true').toString();
  if (target.length === 0) {
    target = ['.'];
  } else {
    target = target.split('\n');
    target.splice(-1, 1);
  }
  return target;
}

/**
 *  CartoDB UI assets generation
 */
module.exports = function (grunt) {
  if (timer) timer.init(grunt);

  var environment = grunt.option('environment') || DEVELOPMENT;
  grunt.log.writeln('Environment: ' + environment);

  var runningTasks = grunt.cli.tasks;
  if (runningTasks.length === 0) {
    grunt.log.writeln('Running default task.');
  } else {
    grunt.log.writeln('Running tasks: ' + runningTasks);
  }

  function preFlight (requiredNodeVersion, requiredNpmVersion, logFn) {
    function checkVersion (cmd, versionRange, name, logFn) {
      grunt.log.writeln('Required ' + name + ' version: ' + versionRange);
      require('child_process').exec(cmd, function (error, stdout, stderr) {
        var err = null;
        if (error) {
          err = 'failed to check version for ' + name;
        } else {
          var installed = semver.clean(stdout);
          if (!semver.satisfies(installed, versionRange)) {
            err = 'Installed ' + name + ' version does not match with required [' + versionRange + '] Installed: ' + installed;
          }
        }
        if (err) {
          grunt.log.fail(err);
        }
        logFn && logFn(err ? new Error(err) : null);
      });
    }
    checkVersion('node -v', requiredNodeVersion, 'node', logFn);
    checkVersion('npm -v', requiredNpmVersion, 'npm', logFn);
  }

  var mustCheckNodeVersion = grunt.option('no-node-checker');
  if (!mustCheckNodeVersion) {
    preFlight(REQUIRED_NODE_VERSION, REQUIRED_NPM_VERSION, logVersionsError);
    grunt.log.writeln('');
  }

  var duplicatedModules = shrinkwrapDependencies.checkDuplicatedDependencies(require('./npm-shrinkwrap.json'), SHRINKWRAP_MODULES_TO_VALIDATE);
  if (duplicatedModules.length > 0) {
    grunt.log.fail('############### /!\\ CAUTION /!\\ #################');
    grunt.log.fail('Duplicated dependencies found in npm-shrinkwrap.json file.');
    grunt.log.fail(JSON.stringify(duplicatedModules, null, 4));
    grunt.log.fail('#################################################');
    process.exit(1);
  }

  var PUBLIC_DIR = './public/';
  var ROOT_ASSETS_DIR = './public/assets/';
  var ASSETS_DIR = './public/assets/<%= pkg.version %>';

  /**
   * this is being used by `grunt --environment=production release`
   */
  var env = './config/grunt_' + environment + '.json';
  grunt.log.writeln('env: ' + env);

  if (grunt.file.exists(env)) {
    env = grunt.file.readJSON(env);
  } else {
    throw grunt.util.error(env + ' file is missing! See ' + env + '.sample for how it should look like');
  }

  var aws = {};
  if (grunt.file.exists('./lib/build/grunt-aws.json')) {
    aws = grunt.file.readJSON('./lib/build/grunt-aws.json');
  }

  var targetDiff = getTargetDiff();

  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    aws: aws,
    env: env,

    public_dir: PUBLIC_DIR,
    assets_dir: ASSETS_DIR,
    root_assets_dir: ROOT_ASSETS_DIR,

    // Concat task
    concat: require('./lib/build/tasks/concat').task(),

    // JST generation task
    jst: require('./lib/build/tasks/jst').task(),

    // Compass files generation
    compass: require('./lib/build/tasks/compass').task(),

    // Copy assets (stylesheets, javascripts, images...)
    copy: require('./lib/build/tasks/copy').task(grunt),

    // Watch actions
    watch: require('./lib/build/tasks/watch.js').task(),

    // Clean folders before other tasks
    clean: require('./lib/build/tasks/clean').task(),

    jasmine: jasmineCfg,

    // Create a tarball of the static pages for production release
    compress: require('./lib/build/tasks/compress.js').task(),

    s3: require('./lib/build/tasks/s3.js').task(),

    exorcise: require('./lib/build/tasks/exorcise.js').task(),

    uglify: require('./lib/build/tasks/uglify.js').task(),

    browserify: require('./lib/build/tasks/browserify.js').task(),

    connect: require('./lib/build/tasks/connect.js').task(),

    availabletasks: require('./lib/build/tasks/availabletasks.js').task(),

    sass: require('./lib/build/tasks/sass.js').task(),

    eslint: {
      target: targetDiff
    }
  });

  /**
   * `grunt availabletasks`
   */
  grunt.loadNpmTasks('grunt-available-tasks');

  // Load Grunt tasks
  require('load-grunt-tasks')(grunt, {
    pattern: ['grunt-*', '@*/grunt-*', '!grunt-timer']
  });

  require('./lib/build/tasks/manifest').register(grunt, ASSETS_DIR);

  grunt.registerTask('invalidate', 'invalidate cache', function () {
    var done = this.async();
    var url = require('url');
    var https = require('https');

    var options = url.parse(grunt.template.process('https://api.fastly.com/service/<%= aws.FASTLY_CARTODB_SERVICE %>/purge_all'));
    options['method'] = 'POST';
    options['headers'] = {
      'Fastly-Key': aws.FASTLY_API_KEY,
      'Content-Length': '0' // Disables chunked encoding
    };
    console.log(options);

    https.request(options, function (response) {
      if (response.statusCode === 200) {
        grunt.log.ok('CDN invalidated (fastly)');
      } else {
        grunt.log.error('CDN not invalidated (fastly), code: ' + response.statusCode);
      }
      done();
    }).on('error', function () {
      grunt.log.error('CDN not invalidated (fastly)');
      done();
    }).end();
  });

  grunt.registerTask('config', 'generates assets config for current configuration', function () {
    // Set assets url for static assets in our app
    var config = grunt.template.process('cdb.config.set(\'assets_url\', \'<%= env.http_path_prefix %>/assets/<%= pkg.version %>\');');
    config += grunt.template.process('\nconsole.log(\'cartodbui v<%= pkg.version %>\');');
    grunt.file.write('lib/build/app_config.js', config);
  });

  grunt.registerTask('check_release', 'checks release can be done', function () {
    if (environment === DEVELOPMENT) {
      grunt.log.error('you can\'t release running development environment');
      return false;
    }

    grunt.log.ok('************************************************');
    grunt.log.ok(' you are going to deploy to ' + env);
    grunt.log.ok('************************************************');
  });

  grunt.event.on('watch', function (action, filepath, subtask) {
    // Configure copy vendor to only run on changed file
    var vendorFile = 'copy.vendor';
    var vendorFileCfg = grunt.config.get(vendorFile);

    if (filepath.indexOf(vendorFileCfg.cwd) !== -1) {
      grunt.config(vendorFile + '.src', filepath.replace(vendorFileCfg.cwd, ''));
    } else {
      grunt.config(vendorFile + 'src', []);
    }

    // Configure copy app to only run on changed files
    var files = 'copy.app.files';
    var filesCfg = grunt.config.get(files);

    for (var i = 0, l = filesCfg.length; i < l; ++i) {
      var file = files + '.' + i;
      var fileCfg = grunt.config.get(file);

      if (filepath.indexOf(fileCfg.cwd) !== -1) {
        grunt.config(file + '.src', filepath.replace(fileCfg.cwd, ''));
      } else {
        grunt.config(file + '.src', []);
      }
    }
  });

  grunt.registerTask('css', [
    'copy:vendor',
    'copy:app',
    'copy:css_cartodb',
    'compass',
    'sass',
    'concat:css'
  ]);

  grunt.registerTask('run_browserify', 'Browserify task with options', function (option) {
    var skipAllSpecs = false;

    if (environment !== DEVELOPMENT) {
      grunt.log.writeln('Skipping all specs generation by browserify because not in development environment.');
      skipAllSpecs = true;
    }

    if (skipAllSpecs) {
      delete grunt.config.data.browserify['test_specs_for_browserify_modules'];
    }

    grunt.task.run('browserify');
  });

  grunt.registerTask('cdb', 'build cartodb.js', function () {
    var done = this.async();

    require('child_process').exec('make update_cdb', function (error, stdout, stderr) {
      if (error) {
        grunt.log.fail('cartodb.js not updated (due to ' + stdout + ', ' + stderr + ')');
      } else {
        grunt.log.ok('cartodb.js updated');
      }
      done();
    });
  });

  grunt.registerTask('js_editor', [
    'cdb',
    'setConfig:env.browserify_watch:true',
    'npm-carto-node',
    'run_browserify',
    'concat:js',
    'jst'
  ]);

  grunt.registerTask('beforeDefault', [
    'clean',
    'config'
  ]);

  grunt.registerTask('dev-editor', [
    'beforeDefault',
    'js_editor',
    'css',
    'manifest'
  ]);

  registerCmdTask('npm-start', {cmd: 'npm', args: ['run', 'start']});
  registerCmdTask('npm-build', {cmd: 'npm', args: ['run', 'build']});
  registerCmdTask('npm-build-static', {cmd: 'npm', args: ['run', 'build:static']});
  registerCmdTask('npm-carto-node', {cmd: 'npm', args: ['run', 'carto-node']});

  /**
   * `grunt dev`
   */

  grunt.registerTask('editor', [
    'dev-editor',
    'npm-start'
  ]);

  grunt.registerTask('default', [
    'dev-editor',
    'npm-start'
  ]);

  grunt.registerTask('lint', [
    'eslint'
  ]);

  grunt.registerTask('sourcemaps', 'generate sourcemaps, to be used w/ trackjs.com for bughunting', [
    'setConfig:assets_dir:./tmp/sourcemaps',
    'config',
    'js',
    'copy:js',
    'exorcise',
    'uglify'
  ]);

  // -- BUILD TASKS

  grunt.registerTask('build', 'build editor, builder, dashboard and static pages', [
    'build-editor',
    'build-static',
    'npm-build'
  ]);

  grunt.registerTask('build-editor', 'generate editor css and javasript files', [
    'dev-editor',
    'copy:js',
    'exorcise',
    'uglify'
  ]);

  grunt.registerTask('build-static', 'generate static files and needed vendor scripts', [
    'npm-carto-node',
    'npm-build-static'
  ]);

  /**
   * `grunt release`
   * `grunt release --environment=production`
   */
  grunt.registerTask('release', [
    'check_release',
    'build',
    'compress',
    's3',
    'invalidate'
  ]);

  grunt.registerTask('generate_builder_specs', 'Generate only builder specs', function (option) {
    requireWebpackTask().affected.call(this, option, grunt);
  });

  grunt.registerTask('generate_dashboard_specs', 'Generate only dashboard specs', function (option) {
    requireWebpackTask().dashboard.call(this, option, grunt);
  });

  grunt.registerTask('bootstrap_webpack_builder_specs', 'Create the webpack compiler', function () {
    requireWebpackTask().bootstrap.call(this, 'builder_specs', grunt);
  });

  grunt.registerTask('bootstrap_webpack_dashboard_specs', 'Create the webpack compiler', function () {
    requireWebpackTask().bootstrap.call(this, 'dashboard_specs', grunt);
  });

  grunt.registerTask('webpack:builder_specs', 'Webpack compilation task for builder specs', function () {
    requireWebpackTask().compile.call(this, 'builder_specs');
  });

  grunt.registerTask('webpack:dashboard_specs', 'Webpack compilation task for dashboard specs', function () {
    requireWebpackTask().compile.call(this, 'dashboard_specs');
  });

  /**
   * `grunt test`
   */
  grunt.registerTask('test', '(CI env) Re-build JS files and run all tests. For manual testing use `grunt jasmine` directly', [
    'connect:test',
    'beforeDefault',
    'js_editor',
    'jasmine:cartodbui',
    'generate_builder_specs',
    'bootstrap_webpack_builder_specs',
    'webpack:builder_specs',
    'jasmine:builder',
    'generate_dashboard_specs',
    'bootstrap_webpack_dashboard_specs',
    'webpack:dashboard_specs',
    'jasmine:dashboard',
    'lint'
  ]);

  /**
   * `grunt test:browser` compile all Builder specs and launch a webpage in the browser.
   */
  grunt.registerTask('test:browser:builder', 'Build all Builder specs', [
    'generate_builder_specs',
    'bootstrap_webpack_builder_specs',
    'webpack:builder_specs',
    'jasmine:builder:build',
    'connect:specs_builder',
    'watch:js_affected'
  ]);

  /**
   * `grunt dashboard_specs` compile dashboard specs
   */
  grunt.registerTask('test:browser:dashboard', 'Build only dashboard specs', [
    'generate_dashboard_specs',
    'bootstrap_webpack_dashboard_specs',
    'webpack:dashboard_specs',
    'jasmine:dashboard:build',
    'connect:specs_dashboard',
    'watch:dashboard_specs'
  ]);

  grunt.registerTask('setConfig', 'Set a config property', function (name, val) {
    grunt.config.set(name, val);
  });

  /**
   * `grunt affected_editor_specs` compile all Editor specs and launch a webpage in the browser.
   */
  grunt.registerTask('affected_editor_specs', 'Build Editor specs', [
    'jasmine:cartodbui:build',
    'connect:server',
    'watch:js_affected_editor'
  ]);

  /**
   * Delegate task to command line.
   * @param {String} name - If taskname starts with npm it's run a npm script (i.e. `npm run foobar`
   * @param {Object} d - d as in data
   * @param {Array} d.args - arguments to pass to the d.cmd
   * @param {String} [d.cmd = process.execPath]
   * @param {String} [d.desc = ''] - description
   * @param {...string} args space-separated arguments passed to the cmd
   */
  function registerCmdTask (name, opts) {
    opts = _.extend({
      cmd: process.execPath,
      desc: '',
      args: []
    }, opts);
    grunt.registerTask(name, opts.desc, function () {
      // adapted from http://stackoverflow.com/a/24796749
      var done = this.async();
      grunt.util.spawn({
        cmd: opts.cmd,
        args: opts.args,
        opts: { stdio: 'inherit' }
      }, done);
    });
  }
};
<commit_msg>Modify grunt editor<commit_after>var _ = require('underscore');
var timer = require('grunt-timer');
var semver = require('semver');
var jasmineCfg = require('./lib/build/tasks/jasmine.js');
var shrinkwrapDependencies = require('./lib/build/tasks/shrinkwrap-dependencies.js');
var webpackTask = null;

var REQUIRED_NODE_VERSION = '6.9.2';
var REQUIRED_NPM_VERSION = '3.10.9';

var DEVELOPMENT = 'development';

var SHRINKWRAP_MODULES_TO_VALIDATE = [
  'backbone',
  'camshaft-reference',
  'carto',
  'internal-carto.js',
  'cartocolor',
  'd3',
  'jquery',
  'leaflet',
  'perfect-scrollbar',
  'torque.js',
  'turbo-carto'
];

function requireWebpackTask () {
  if (webpackTask === null) {
    webpackTask = require('./lib/build/tasks/webpack/webpack.js');
  }
  return webpackTask;
}

function logVersionsError (err, requiredNodeVersion, requiredNpmVersion) {
  if (err) {
    grunt.log.fail('############### /!\\ CAUTION /!\\ #################');
    grunt.log.fail('PLEASE installed required versions to build CARTO:\n- node: ' + requiredNodeVersion + '\n- node: ' + requiredNpmVersion);
    grunt.log.fail('#################################################');
    process.exit(1);
  }
}

function getTargetDiff () {
  var target = require('child_process').execSync('(git diff --name-only --relative || true;' +
                                                 'git diff origin/master.. --name-only --relative || true;)' +
                                                 '| grep \'\\.js\\?$\' || true').toString();
  if (target.length === 0) {
    target = ['.'];
  } else {
    target = target.split('\n');
    target.splice(-1, 1);
  }
  return target;
}

/**
 *  CartoDB UI assets generation
 */
module.exports = function (grunt) {
  if (timer) timer.init(grunt);

  var environment = grunt.option('environment') || DEVELOPMENT;
  grunt.log.writeln('Environment: ' + environment);

  var runningTasks = grunt.cli.tasks;
  if (runningTasks.length === 0) {
    grunt.log.writeln('Running default task.');
  } else {
    grunt.log.writeln('Running tasks: ' + runningTasks);
  }

  function preFlight (requiredNodeVersion, requiredNpmVersion, logFn) {
    function checkVersion (cmd, versionRange, name, logFn) {
      grunt.log.writeln('Required ' + name + ' version: ' + versionRange);
      require('child_process').exec(cmd, function (error, stdout, stderr) {
        var err = null;
        if (error) {
          err = 'failed to check version for ' + name;
        } else {
          var installed = semver.clean(stdout);
          if (!semver.satisfies(installed, versionRange)) {
            err = 'Installed ' + name + ' version does not match with required [' + versionRange + '] Installed: ' + installed;
          }
        }
        if (err) {
          grunt.log.fail(err);
        }
        logFn && logFn(err ? new Error(err) : null);
      });
    }
    checkVersion('node -v', requiredNodeVersion, 'node', logFn);
    checkVersion('npm -v', requiredNpmVersion, 'npm', logFn);
  }

  var mustCheckNodeVersion = grunt.option('no-node-checker');
  if (!mustCheckNodeVersion) {
    preFlight(REQUIRED_NODE_VERSION, REQUIRED_NPM_VERSION, logVersionsError);
    grunt.log.writeln('');
  }

  var duplicatedModules = shrinkwrapDependencies.checkDuplicatedDependencies(require('./npm-shrinkwrap.json'), SHRINKWRAP_MODULES_TO_VALIDATE);
  if (duplicatedModules.length > 0) {
    grunt.log.fail('############### /!\\ CAUTION /!\\ #################');
    grunt.log.fail('Duplicated dependencies found in npm-shrinkwrap.json file.');
    grunt.log.fail(JSON.stringify(duplicatedModules, null, 4));
    grunt.log.fail('#################################################');
    process.exit(1);
  }

  var PUBLIC_DIR = './public/';
  var ROOT_ASSETS_DIR = './public/assets/';
  var ASSETS_DIR = './public/assets/<%= pkg.version %>';

  /**
   * this is being used by `grunt --environment=production release`
   */
  var env = './config/grunt_' + environment + '.json';
  grunt.log.writeln('env: ' + env);

  if (grunt.file.exists(env)) {
    env = grunt.file.readJSON(env);
  } else {
    throw grunt.util.error(env + ' file is missing! See ' + env + '.sample for how it should look like');
  }

  var aws = {};
  if (grunt.file.exists('./lib/build/grunt-aws.json')) {
    aws = grunt.file.readJSON('./lib/build/grunt-aws.json');
  }

  var targetDiff = getTargetDiff();

  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    aws: aws,
    env: env,

    public_dir: PUBLIC_DIR,
    assets_dir: ASSETS_DIR,
    root_assets_dir: ROOT_ASSETS_DIR,

    // Concat task
    concat: require('./lib/build/tasks/concat').task(),

    // JST generation task
    jst: require('./lib/build/tasks/jst').task(),

    // Compass files generation
    compass: require('./lib/build/tasks/compass').task(),

    // Copy assets (stylesheets, javascripts, images...)
    copy: require('./lib/build/tasks/copy').task(grunt),

    // Watch actions
    watch: require('./lib/build/tasks/watch.js').task(),

    // Clean folders before other tasks
    clean: require('./lib/build/tasks/clean').task(),

    jasmine: jasmineCfg,

    // Create a tarball of the static pages for production release
    compress: require('./lib/build/tasks/compress.js').task(),

    s3: require('./lib/build/tasks/s3.js').task(),

    exorcise: require('./lib/build/tasks/exorcise.js').task(),

    uglify: require('./lib/build/tasks/uglify.js').task(),

    browserify: require('./lib/build/tasks/browserify.js').task(),

    connect: require('./lib/build/tasks/connect.js').task(),

    availabletasks: require('./lib/build/tasks/availabletasks.js').task(),

    sass: require('./lib/build/tasks/sass.js').task(),

    eslint: {
      target: targetDiff
    }
  });

  /**
   * `grunt availabletasks`
   */
  grunt.loadNpmTasks('grunt-available-tasks');

  // Load Grunt tasks
  require('load-grunt-tasks')(grunt, {
    pattern: ['grunt-*', '@*/grunt-*', '!grunt-timer']
  });

  require('./lib/build/tasks/manifest').register(grunt, ASSETS_DIR);

  grunt.registerTask('invalidate', 'invalidate cache', function () {
    var done = this.async();
    var url = require('url');
    var https = require('https');

    var options = url.parse(grunt.template.process('https://api.fastly.com/service/<%= aws.FASTLY_CARTODB_SERVICE %>/purge_all'));
    options['method'] = 'POST';
    options['headers'] = {
      'Fastly-Key': aws.FASTLY_API_KEY,
      'Content-Length': '0' // Disables chunked encoding
    };
    console.log(options);

    https.request(options, function (response) {
      if (response.statusCode === 200) {
        grunt.log.ok('CDN invalidated (fastly)');
      } else {
        grunt.log.error('CDN not invalidated (fastly), code: ' + response.statusCode);
      }
      done();
    }).on('error', function () {
      grunt.log.error('CDN not invalidated (fastly)');
      done();
    }).end();
  });

  grunt.registerTask('config', 'generates assets config for current configuration', function () {
    // Set assets url for static assets in our app
    var config = grunt.template.process('cdb.config.set(\'assets_url\', \'<%= env.http_path_prefix %>/assets/<%= pkg.version %>\');');
    config += grunt.template.process('\nconsole.log(\'cartodbui v<%= pkg.version %>\');');
    grunt.file.write('lib/build/app_config.js', config);
  });

  grunt.registerTask('check_release', 'checks release can be done', function () {
    if (environment === DEVELOPMENT) {
      grunt.log.error('you can\'t release running development environment');
      return false;
    }

    grunt.log.ok('************************************************');
    grunt.log.ok(' you are going to deploy to ' + env);
    grunt.log.ok('************************************************');
  });

  grunt.event.on('watch', function (action, filepath, subtask) {
    // Configure copy vendor to only run on changed file
    var vendorFile = 'copy.vendor';
    var vendorFileCfg = grunt.config.get(vendorFile);

    if (filepath.indexOf(vendorFileCfg.cwd) !== -1) {
      grunt.config(vendorFile + '.src', filepath.replace(vendorFileCfg.cwd, ''));
    } else {
      grunt.config(vendorFile + 'src', []);
    }

    // Configure copy app to only run on changed files
    var files = 'copy.app.files';
    var filesCfg = grunt.config.get(files);

    for (var i = 0, l = filesCfg.length; i < l; ++i) {
      var file = files + '.' + i;
      var fileCfg = grunt.config.get(file);

      if (filepath.indexOf(fileCfg.cwd) !== -1) {
        grunt.config(file + '.src', filepath.replace(fileCfg.cwd, ''));
      } else {
        grunt.config(file + '.src', []);
      }
    }
  });

  grunt.registerTask('css', [
    'copy:vendor',
    'copy:app',
    'copy:css_cartodb',
    'compass',
    'sass',
    'concat:css'
  ]);

  grunt.registerTask('run_browserify', 'Browserify task with options', function (option) {
    var skipAllSpecs = false;

    if (environment !== DEVELOPMENT) {
      grunt.log.writeln('Skipping all specs generation by browserify because not in development environment.');
      skipAllSpecs = true;
    }

    if (skipAllSpecs) {
      delete grunt.config.data.browserify['test_specs_for_browserify_modules'];
    }

    grunt.task.run('browserify');
  });

  grunt.registerTask('cdb', 'build cartodb.js', function () {
    var done = this.async();

    require('child_process').exec('make update_cdb', function (error, stdout, stderr) {
      if (error) {
        grunt.log.fail('cartodb.js not updated (due to ' + stdout + ', ' + stderr + ')');
      } else {
        grunt.log.ok('cartodb.js updated');
      }
      done();
    });
  });

  grunt.registerTask('js_editor', [
    'cdb',
    'setConfig:env.browserify_watch:true',
    'npm-carto-node',
    'run_browserify',
    'concat:js',
    'jst'
  ]);

  grunt.registerTask('beforeDefault', [
    'clean',
    'config'
  ]);

  grunt.registerTask('dev-editor', [
    'beforeDefault',
    'js_editor',
    'css',
    'manifest'
  ]);

  registerCmdTask('npm-start', {cmd: 'npm', args: ['run', 'start']});
  registerCmdTask('npm-build', {cmd: 'npm', args: ['run', 'build']});
  registerCmdTask('npm-build-static', {cmd: 'npm', args: ['run', 'build:static']});
  registerCmdTask('npm-carto-node', {cmd: 'npm', args: ['run', 'carto-node']});

  /**
   * `grunt dev`
   */

  grunt.registerTask('editor', [
    'dev-editor',
    'watch:css'
  ]);

  grunt.registerTask('default', [
    'dev-editor',
    'npm-start'
  ]);

  grunt.registerTask('lint', [
    'eslint'
  ]);

  grunt.registerTask('sourcemaps', 'generate sourcemaps, to be used w/ trackjs.com for bughunting', [
    'setConfig:assets_dir:./tmp/sourcemaps',
    'config',
    'js',
    'copy:js',
    'exorcise',
    'uglify'
  ]);

  // -- BUILD TASKS

  grunt.registerTask('build', 'build editor, builder, dashboard and static pages', [
    'build-editor',
    'build-static',
    'npm-build'
  ]);

  grunt.registerTask('build-editor', 'generate editor css and javasript files', [
    'dev-editor',
    'copy:js',
    'exorcise',
    'uglify'
  ]);

  grunt.registerTask('build-static', 'generate static files and needed vendor scripts', [
    'npm-carto-node',
    'npm-build-static'
  ]);

  /**
   * `grunt release`
   * `grunt release --environment=production`
   */
  grunt.registerTask('release', [
    'check_release',
    'build',
    'compress',
    's3',
    'invalidate'
  ]);

  grunt.registerTask('generate_builder_specs', 'Generate only builder specs', function (option) {
    requireWebpackTask().affected.call(this, option, grunt);
  });

  grunt.registerTask('generate_dashboard_specs', 'Generate only dashboard specs', function (option) {
    requireWebpackTask().dashboard.call(this, option, grunt);
  });

  grunt.registerTask('bootstrap_webpack_builder_specs', 'Create the webpack compiler', function () {
    requireWebpackTask().bootstrap.call(this, 'builder_specs', grunt);
  });

  grunt.registerTask('bootstrap_webpack_dashboard_specs', 'Create the webpack compiler', function () {
    requireWebpackTask().bootstrap.call(this, 'dashboard_specs', grunt);
  });

  grunt.registerTask('webpack:builder_specs', 'Webpack compilation task for builder specs', function () {
    requireWebpackTask().compile.call(this, 'builder_specs');
  });

  grunt.registerTask('webpack:dashboard_specs', 'Webpack compilation task for dashboard specs', function () {
    requireWebpackTask().compile.call(this, 'dashboard_specs');
  });

  /**
   * `grunt test`
   */
  grunt.registerTask('test', '(CI env) Re-build JS files and run all tests. For manual testing use `grunt jasmine` directly', [
    'connect:test',
    'beforeDefault',
    'js_editor',
    'jasmine:cartodbui',
    'generate_builder_specs',
    'bootstrap_webpack_builder_specs',
    'webpack:builder_specs',
    'jasmine:builder',
    'generate_dashboard_specs',
    'bootstrap_webpack_dashboard_specs',
    'webpack:dashboard_specs',
    'jasmine:dashboard',
    'lint'
  ]);

  /**
   * `grunt test:browser` compile all Builder specs and launch a webpage in the browser.
   */
  grunt.registerTask('test:browser:builder', 'Build all Builder specs', [
    'generate_builder_specs',
    'bootstrap_webpack_builder_specs',
    'webpack:builder_specs',
    'jasmine:builder:build',
    'connect:specs_builder',
    'watch:js_affected'
  ]);

  /**
   * `grunt dashboard_specs` compile dashboard specs
   */
  grunt.registerTask('test:browser:dashboard', 'Build only dashboard specs', [
    'generate_dashboard_specs',
    'bootstrap_webpack_dashboard_specs',
    'webpack:dashboard_specs',
    'jasmine:dashboard:build',
    'connect:specs_dashboard',
    'watch:dashboard_specs'
  ]);

  grunt.registerTask('setConfig', 'Set a config property', function (name, val) {
    grunt.config.set(name, val);
  });

  /**
   * `grunt affected_editor_specs` compile all Editor specs and launch a webpage in the browser.
   */
  grunt.registerTask('affected_editor_specs', 'Build Editor specs', [
    'jasmine:cartodbui:build',
    'connect:server',
    'watch:js_affected_editor'
  ]);

  /**
   * Delegate task to command line.
   * @param {String} name - If taskname starts with npm it's run a npm script (i.e. `npm run foobar`
   * @param {Object} d - d as in data
   * @param {Array} d.args - arguments to pass to the d.cmd
   * @param {String} [d.cmd = process.execPath]
   * @param {String} [d.desc = ''] - description
   * @param {...string} args space-separated arguments passed to the cmd
   */
  function registerCmdTask (name, opts) {
    opts = _.extend({
      cmd: process.execPath,
      desc: '',
      args: []
    }, opts);
    grunt.registerTask(name, opts.desc, function () {
      // adapted from http://stackoverflow.com/a/24796749
      var done = this.async();
      grunt.util.spawn({
        cmd: opts.cmd,
        args: opts.args,
        opts: { stdio: 'inherit' }
      }, done);
    });
  }
};
<|endoftext|>


<commit_before>/*!
 * ribs
 * Copyright (c) 2013 Nicolas Gryman <ngryman@gmail.com>
 * LGPL Licensed
 */

'use strict';

module.exports = function(grunt) {
	// loads npm tasks
	require('load-grunt-tasks')(grunt);

	grunt.initConfig({
		pkg: grunt.file.readJSON('package.json'),
		config: {
			lib: 'lib/*.js',
			test: 'test/*.js'
		},
		meta: {
			banner: '/*! <%%= pkg.name %> - v<%%= pkg.version %> - ' +
				'<%%= grunt.template.today("yyyy-mm-dd") %>\n' +
				'<%%= pkg.homepage ? "* " + pkg.homepage + "\\n" : "" %>' +
				'* Copyright (c) <%%= grunt.template.today("yyyy") %> <%%= pkg.author.name %>;' +
				' Licensed <%%= pkg.license %> */\n'
		},
		// TODO: use eslint when available
		jshint: {
			options: grunt.file.readJSON('.jshintrc'),
			lib: ['<%= config.lib %>'],
			unit: {
				options: {
					expr: true
				},
				src: ['<%= config.test %>']
			},
			misc: ['Gruntfile.js']
		},
		mochacli: {
			unit: {
				options: {
					reporter: 'spec',
					bail: true
				},
				src: ['<%= config.test %>']
			}
		}
	});

	// front tasks
	grunt.registerTask('test', ['jshint', 'mochacli']);
};<commit_msg>added a debug mode to tests.<commit_after>/*!
 * ribs
 * Copyright (c) 2013 Nicolas Gryman <ngryman@gmail.com>
 * LGPL Licensed
 */

'use strict';

module.exports = function(grunt) {
	// loads npm tasks
	require('load-grunt-tasks')(grunt);

	grunt.initConfig({
		pkg: grunt.file.readJSON('package.json'),
		config: {
			lib: 'lib/*.js',
			test: 'test/*.js'
		},
		meta: {
			banner: '/*! <%%= pkg.name %> - v<%%= pkg.version %> - ' +
				'<%%= grunt.template.today("yyyy-mm-dd") %>\n' +
				'<%%= pkg.homepage ? "* " + pkg.homepage + "\\n" : "" %>' +
				'* Copyright (c) <%%= grunt.template.today("yyyy") %> <%%= pkg.author.name %>;' +
				' Licensed <%%= pkg.license %> */\n'
		},
		// TODO: use eslint when available
		jshint: {
			options: grunt.file.readJSON('.jshintrc'),
			lib: ['<%= config.lib %>'],
			unit: {
				options: {
					expr: true
				},
				src: ['<%= config.test %>']
			},
			misc: ['Gruntfile.js']
		},
		mochacli: {
			options: {
				reporter: 'spec',
				bail: true
			},
			unit: ['<%= config.test %>'],
			debug: {
				options: {
					'debug-brk': true
				},
				src: ['<%= config.test %>']
			}
		}
	});

	// front tasks
	grunt.registerTask('test', ['jshint', 'mochacli:unit']);
	grunt.registerTask('debug', ['mochacli:debug']);
};<|endoftext|>