<commit_before>'use strict';

const path = require('path');
const format = require('util').format;
const cli = require('x-commander/extra');
const pkg = require('../package.json');
const deprecate = require('../lib/deprecate');

// TODO: remove in v1
const $ = require('x-node');

cli.l10n({
    'output usage information': 'Output usage information',
    'output the version number': 'Display this application version'
});

cli.deprecate = message => null;

const util = {
    /**
     * @param {String} type
     * @param {String} value
     * @returns {String}
     */
    prepare: (type, value) => {
        if ('name' == type) {
            let name = path.basename(process.cwd());
            if (process.env.WHALER_DAEMON_NAME) {
                name = process.env.WHALER_DAEMON_NAME;
            }

            return value || name;

        } else if ('ref' == type) {
            let ref = path.basename(process.cwd());
            if (process.env.WHALER_DAEMON_NAME) {
                ref = process.env.WHALER_DAEMON_NAME;
            }

            if (value) {
                const parts = value.split('.');
                if (2 == parts.length) {
                    if (!parts[1]) {
                        value += ref;
                    }
                }

                return value;
            }

            return ref;

        } else if ('path' == type) {
            value = value || process.cwd();
            if (!path.isAbsolute(value)) {
                value = path.join(process.cwd(), path.normalize(value));
            }

            return value;
        }

        return value;
    },

    /**
     * @param {Object} options
     * @param {Array} keys
     * @returns {Object}
     */
    filter: (options, keys) => {
        const result = {};
        for (let key of keys) {
            result[key] = options.hasOwnProperty(key) ? options[key] : undefined;
        }
        return result;
    }
};

/**
 * @param status
 */
cli.Command.prototype.ignoreEndLine = function(status) {
    this.__ignoreEndLine = status;
    return this;
};

cli.Command.prototype._action = cli.Command.prototype.action;
cli.Command.prototype.action = function(fn) {
    const done = err => {
        if (err) {
            console.error('\n[%s] %s\n', process.pid, err.message);
        } else if (true !== this.__ignoreEndLine) {
            console.log('');
        }
    };

    // TODO: remove in v1
    if ($.isGenerator(fn)) {
        cli.deprecate(
            deprecate(trace => '"cli.action" support for generators will be removed in v1.')
        );
        this.util = util;
        fn = fn.bind(this);
        return this._action($.async(fn, done));
    } else {
        return this._action(async (...args) => {
            let err = null;
            try {
                await fn(...args, util);
            } catch (e) {
                err = e;
            }
            await Promise.resolve();
            done(err);
        });
    }
};

cli._name = pkg.name;

cli._printer.error = function(...args) {
    throw new Error(format.apply(null, args));
};

try {
    const dev = require('../dev.json');
    cli.version(dev.version + (dev.sha ? ' ' + dev.sha.substr(0, 7) : ''));
} catch(e) {
    cli.version(pkg.version);
}

cli.option(
    '-H, --host <HOST>',
    'Host to use'
);

cli.addUnknownCommand();

module.exports = cli;
<commit_msg>cli bug fix<commit_after>'use strict';

const path = require('path');
const format = require('util').format;
const cli = require('x-commander/extra');
const pkg = require('../package.json');
const deprecate = require('../lib/deprecate');

// TODO: remove in v1
const $ = require('x-node');

cli.l10n({
    'output usage information': 'Output usage information',
    'output the version number': 'Display this application version'
});

cli.deprecate = message => null;

const util = {
    /**
     * @param {String} type
     * @param {String} value
     * @returns {String}
     */
    prepare: (type, value) => {
        if ('name' == type) {
            let name = path.basename(process.cwd());
            if (process.env.WHALER_DAEMON_NAME) {
                name = process.env.WHALER_DAEMON_NAME;
            }

            return value || name;

        } else if ('ref' == type) {
            let ref = path.basename(process.cwd());
            if (process.env.WHALER_DAEMON_NAME) {
                ref = process.env.WHALER_DAEMON_NAME;
            }

            if (value) {
                const parts = value.split('.');
                if (2 == parts.length) {
                    if (!parts[1]) {
                        value += ref;
                    }
                }

                return value;
            }

            return ref;

        } else if ('path' == type) {
            value = value || process.cwd();
            if (!path.isAbsolute(value)) {
                value = path.join(process.cwd(), path.normalize(value));
            }

            return value;
        }

        return value;
    },

    /**
     * @param {Object} options
     * @param {Array} keys
     * @returns {Object}
     */
    filter: (options, keys) => {
        const result = {};
        for (let key of keys) {
            result[key] = options.hasOwnProperty(key) ? options[key] : undefined;
        }
        return result;
    }
};

/**
 * @param status
 */
cli.Command.prototype.ignoreEndLine = function(status) {
    this.__ignoreEndLine = status;
    return this;
};

cli.Command.prototype._action = cli.Command.prototype.action;
cli.Command.prototype.action = function(fn) {
    const done = err => {
        if (err) {
            console.error('\n[%s] %s\n', process.pid, err.message || err);
        } else if (true !== this.__ignoreEndLine) {
            console.log('');
        }
    };

    // TODO: remove in v1
    if ($.isGenerator(fn)) {
        cli.deprecate(
            deprecate(trace => '"cli.action" support for generators will be removed in v1.')
        );
        this.util = util;
        fn = fn.bind(this);
        return this._action($.async(fn, done));
    } else {
        return this._action(async (...args) => {
            let err = null;
            try {
                await fn(...args, util);
            } catch (e) {
                err = e;
            }
            await Promise.resolve();
            done(err);
        });
    }
};

cli._name = pkg.name;

cli._printer.error = function(...args) {
    throw new Error(format.apply(null, args));
};

try {
    const dev = require('../dev.json');
    cli.version(dev.version + (dev.sha ? ' ' + dev.sha.substr(0, 7) : ''));
} catch(e) {
    cli.version(pkg.version);
}

cli.option(
    '-H, --host <HOST>',
    'Host to use'
);

cli.addUnknownCommand();

module.exports = cli;
<|endoftext|>


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

    grunt.registerTask('install', 'install the backend and frontend dependencies', function () {
        var exec = require('child_process').exec;
        var cb = this.async();

        exec('npm install less -g', {}, function (err, stdout, stderr) {
            console.log(stdout);
            console.log(stderr);
            exec('npm install', {}, function (err, stdout, stderr) {
                console.log(stdout);
                console.log(stderr);
                exec('node node_modules/bower/bin/bower install', {}, function (err, stdout, stderr) {
                    console.log(stdout);
                    console.log(stderr);
                    cb();
                });
            });
        });

    });

    var gtx = require('gruntfile-gtx').wrap(grunt);

    gtx.loadAuto();

    gtx.alias('dokku:production', ['install']);

    gtx.finalise();
}
<commit_msg>Package<commit_after>module.exports = function (grunt) {

    grunt.registerTask('install', 'install the backend and frontend dependencies', function () {
        var exec = require('child_process').exec;
        var cb = this.async();

        exec('npm install less coffee-script -g', {}, function (err, stdout, stderr) {
            console.log(stdout);
            console.log(stderr);
            exec('npm install', {}, function (err, stdout, stderr) {
                console.log(stdout);
                console.log(stderr);
                exec('node node_modules/bower/bin/bower install', {}, function (err, stdout, stderr) {
                    console.log(stdout);
                    console.log(stderr);
                    cb();
                });
            });
        });

    });

    var gtx = require('gruntfile-gtx').wrap(grunt);

    gtx.loadAuto();

    gtx.alias('dokku:production', ['install']);

    gtx.finalise();
}
<|endoftext|>


<commit_before>#!/usr/bin/env node

import path from 'path';
import yargs from 'yargs';

import { downloadSchema, generate } from '.';

yargs
  .command(
    'download-schema <server>',
    'Download a GraphQL schema from a server',
    {
      output: {
        demand: true,
        describe: 'Output path for GraphQL schema file',
        normalize: true
      }
    },
    async argv => {
      const outputPath = path.resolve(argv.output);
      try {
        await downloadSchema(argv.server, outputPath);
      } catch (error) {
        console.error(error);
      }
    }
  )
  .command(
    'generate <input...>',
    'Generate code from a GraphQL schema and query documents',
    {
      schema: {
        demand: true,
        describe: 'Path to GraphQL schema file',
        normalize: true
      },
      output: {
        demand: true,
        describe: 'Output directory for the generated files',
        normalize: true
      }
    },
    argv => {
      try {
        const inputPaths = argv.input.map(input => path.resolve(input));
        const schemaPath = path.resolve(argv.schema);
        const outputPath = path.resolve(argv.output);
        generate(inputPaths, schemaPath, outputPath);
      } catch (error) {
        console.error(error.stack);
      }
    },
  )
  .showHelpOnFail(false)
  .help()
  .strict()
  .argv
<commit_msg>Make sure errors result in a non-zero exit code<commit_after>#!/usr/bin/env node

import process from 'process';
import path from 'path';
import yargs from 'yargs';

import { downloadSchema, generate } from '.';

// Make sure unhandled errors in async code are propagated correctly
process.on('unhandledRejection', (error) => { throw error });

yargs
  .command(
    'download-schema <server>',
    'Download a GraphQL schema from a server',
    {
      output: {
        demand: true,
        describe: 'Output path for GraphQL schema file',
        normalize: true
      }
    },
    async argv => {
      const outputPath = path.resolve(argv.output);
      await downloadSchema(argv.server, outputPath);
    }
  )
  .command(
    'generate <input...>',
    'Generate code from a GraphQL schema and query documents',
    {
      schema: {
        demand: true,
        describe: 'Path to GraphQL schema file',
        normalize: true
      },
      output: {
        demand: true,
        describe: 'Output directory for the generated files',
        normalize: true
      }
    },
    argv => {
      const inputPaths = argv.input.map(input => path.resolve(input));
      const schemaPath = path.resolve(argv.schema);
      const outputPath = path.resolve(argv.output);
      generate(inputPaths, schemaPath, outputPath);
    },
  )
  .showHelpOnFail(false)
  .help()
  .strict()
  .argv
<|endoftext|>


<commit_before>module.exports = function(grunt) {
  require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);
  var config = require('./config');
  var styleguide = require('sc5-styleguide');
  var path = require('path');
  var wiredep = require('wiredep');
  var cors_proxy = require('cors-anywhere');

  var gulp = require('gulp');
  // registering promisies for gulp...
  require("any-promise/register")("bluebird");
  var sass = require('gulp-sass');
  var bless = require('gulp-bless');
  var sourcemaps = require('gulp-sourcemaps');
  var concat = require('gulp-concat');
  var replace = require('gulp-replace');

  grunt.loadNpmTasks('grunt-ngdocs');

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    clean: ['build', 'quality'],
    jshint: {
      options: {
        undef: false,
        strict: false,
        '-W030': true,
        unused: false,
        passfail: true,
        reporter: 'checkstyle',
        reporterOutput: 'quality/js/checkstyle-results.xml'
      },
      all: [config.app.src + '/webapp/public/js/**/*.js']
    },
    sasslint: {
      src: [
        path.join(config.app.src,'**/*.scss'),
        '!**/ng-grid.scss'
      ],
      options: {
        bench: false,
        config: '.sasslint.json'
      }
    },
    watch: {
      files: config.app.src + '/**/*',
      tasks: ['build'],
      options: {
        spawn: false
      }
    },
    uglify: {
      options: {
        mangle: false,
        beautify: true,
        report: 'min',
        preserveComments: false
      },
      files: {
        cwd: config.app.dest + '/public/',
        src: ['**/*.js'],
        dest: config.app.dest + '/public/',
        expand: true,
        flatten: false
      }
    },
    connect: {
      server: {
        options: {
          keepalive: true,
          debug: true,
          port: 9000,
          base: config.app.dest
        }
      }
    },
    karma: {
      options: {
        configFile: 'karma.config.js'
      },
      unit: {
        // default
      },
      tdd: {
        singleRun: false
      }
    },
    replace: {
      serverurl: {
        src: [config.app.dest + '/public/**/*.js'],
        overwrite: true,
        replacements: [{
          from: '@@OPENLMIS_SERVER_URL',
          to: makeURL('openlmisServerURL')
        },{
          from: '@@AUTH_SERVICE_URL',
          to: makeURL('authServiceURL')
        },{
          from: '@@REQUISITION_SERVICE_URL',
          to: makeURL('requisitionServiceURL')
        }]
      }
    },
    concat: {
      js: {
        options: {
          sourceMap: true
        },
        src: function(){
          var appFiles = [
            // Module registration
            config.app.src + '/webapp/public/**/module/*.js',
            config.app.src + '/webapp/public/**/*.module.js',
            // Legacy files
            config.app.src + '/webapp/public/js/shared/util.js',
            config.app.src + '/webapp/public/js/shared/*.js',
            config.app.src + '/webapp/public/js/shared/services/services.js',
            config.app.src + '/webapp/public/js/shared/**/*.js',
            // Special file types....
            config.app.src + '/webapp/public/**/*.config.js',
            config.app.src + '/webapp/public/**/*.routes.js',
            '!' + config.app.src + '/webapp/public/app.routes.js',
            // Everything else
            config.app.src + '/webapp/public/**/*.js',
            '!' + config.app.src + '/**/*.spec.js',
            '!' + config.app.src + '/webapp/public/app.js',
            '!' + config.app.src + '/webapp/public/app.routes.js',
            // Run time
            // NEED file to declare openlmis-app
            config.app.src + '/webapp/public/app.js',
            config.app.src + '/webapp/public/app.routes.js'
          ];
          // hack to make jquery load first
          return [
              'bower_components/jquery/dist/jquery.js',
              'bower_components/jquery-ui/jquery-ui.js'
            ].concat(
              wiredep().js,
              [
                'vendor/ng-grid-2.0.7.min.js',
                'vendor/base2.js'
              ],
              appFiles
            );
        }(),
        dest: config.app.dest + '/public/openlmis.js'
      }
    },
    copy: {
      main: {
        files: [
          {
            expand: true,
            cwd: config.app.src + '/webapp/',
            src: ['*'],
            dest: config.app.dest + '/public',
            filter: 'isFile'
          }
        ],
      },
      images: {
        files: [
          {
            expand: true,
            cwd: config.app.src + '/webapp/public/',
            src: [
              '**/*.png',
              '**/*.jpg',
              '**/*.gif'
            ],
            dest: config.app.dest + '/public'
          }
        ],
      },
      img: {
        files: [
          {
            expand: true,
            flatten: true,
            cwd: config.app.src + '/webapp/public/lib/',
            src: ['**/img/**'],
            dest: config.app.dest + '/public/img'
          }
        ],
      },
      fonts: {
        files: [
          {
            expand: true,
            cwd: config.app.src + '/webapp/public/fonts/',
            src: ['**'],
            dest: config.app.dest + '/public/fonts'
          }
        ],
      },
      pages: {
        files: [
          {
            expand: true,
            cwd: config.app.src + '/webapp/public/',
            src: ['index.html'],
            dest: config.app.dest + '/public'
          }
        ],
      },
      messages: {
        files: [
          {
            expand: true,
            cwd: config.app.src + '/resources',
            src: ['messages_*.json'],
            dest: config.app.dest + '/public/messages'
          }
        ]
      },
      credentials: {
        files: [
          {
            expand: true,
            cwd: config.app.src + '/resources',
            src: ['auth_server_client.json'],
            dest: config.app.dest + '/public/credentials'
          }
        ]
      },
      fontAwesomeFonts: {
        files: [
          {
            expand: true,
            cwd: 'bower_components/font-awesome/fonts/',
            src: '*',
            dest: path.join(config.app.dest, 'public/fonts')
          }
        ]
      },
      uiGridFonts: {
        files: [
          {
            expand: true,
            cwd: 'bower_components/angular-ui-grid/',
            src: [
              'ui-grid.eot',
              'ui-grid.svg',
              'ui-grid.ttf',
              'ui-grid.woff'
            ],
            dest: config.app.dest + '/public/fonts'
          }
        ]
      },
      bootstrapFonts: {
        files: [
          {
            expand: true,
            cwd: 'bower_components/bootstrap/fonts/',
            src: [
              'glyphicons-halflings-regular.eot',
              'glyphicons-halflings-regular.svg',
              'glyphicons-halflings-regular.ttf',
              'glyphicons-halflings-regular.woff',
              'glyphicons-halflings-regular.woff2'
            ],
            dest: config.app.dest + '/public/fonts/bootstrap'
          }
        ]
      },
      selectTwoImages: {
        expand: true,
        cwd: 'bower_components/select2/',
        src: [
            '*.png',
            '*.gif'
        ],
        dest: path.join(config.app.dest, 'public/images')
      }
    },
    ngdocs: {
      options:{
        dest: "./build/docs",
        title: "OpenLMIS-UI Documentation"
      },
      api: {
        src: [
          path.join(config.app.src, "**/*.js"),
          "!" + path.join(config.app.src, "**/*.spec.js")
        ],
        title: "API"
      }
    },
    gulp: {
      'styleguide-generate': function() {
        return gulp.src([
                        path.join(config.styleguide.src,"**/*.scss"),
                        "!"+path.join(config.styleguide.src,"**/scss/*.scss")
                        ])
          .pipe(styleguide.generate({
            title: 'OpenLMIS Styleguide',
            appRoot: "http://replaceThis",
            disableHtml5Mode: true,
            overviewPath: path.join(config.docs.src, 'styleguide.md')
          }))
          .pipe(gulp.dest(config.styleguide.dest));
      },
      'styleguide-applystyles': function() {
        return gulp.src([
                  path.join(config.app.dest,"/public/openlmis*.css")
                  ])
          .pipe(styleguide.applyStyles())
          .pipe(gulp.dest(config.styleguide.dest));
      },
      'styleguide-fonts': function() {
        return gulp.src([
            path.join(config.app.dest, "public/fonts/*"),
          ])
          .pipe(gulp.dest(path.join(config.styleguide.dest,"fonts")));
      },
      'styleguide-png': function() {
        return gulp.src([
                    config.app.dest + "/public/images/*",
                    config.app.dest + "/public/images/*"
                   ])
          .pipe(gulp.dest(path.join(config.styleguide.dest,"images")));
      },
      'styleguide-index-replace': function(){
        return gulp.src([
            path.join(config.styleguide.dest, 'index.html'),
            path.join(config.styleguide.dest, 'styleguide-app.css')
          ])
          .pipe(replace("http://replaceThis/", ""))
          .pipe(replace("font-family: 'FontAwesome';", ""))
          .pipe(gulp.dest(config.styleguide.dest));
      },
      'sass': function(){
   var includePaths = require('node-bourbon').includePaths.concat([
        config.app.src,
        'bower_components/font-awesome/scss',
        'bower_components/bootstrap-sass/assets/stylesheets',
        'bower_components/select2/src/scss'
    ]);

    var bowerCss = wiredep().css;
    var bowerSass = wiredep().scss;

    var files = [].concat(
      [
        path.join(config.app.src, "**/*variables.scss"),
        path.join(config.app.src, "**/*.variables.scss")
      ],
      bowerSass,
      bowerCss,
      [
        path.join(config.app.src, "/**/*mixins.scss"),
        path.join(config.app.src, "/**/*.mixins.scss"),
        path.join(config.app.src, '**/*.css'),
        path.join(config.app.src, '**/*.scss'),
        "!" + path.join(config.app.src, "webapp/public/scss/*")
      ]);

    var outputStyle = "expanded";
    if(grunt.option('production')) outputStyle = "compressed";

    return gulp.src(files)
   .pipe(sourcemaps.init())
    .pipe(concat({
      path:'openlmis.scss'
    }))
    .pipe(sass({
      includePaths: includePaths,
      outputStyle: outputStyle,
    }))
    .pipe(sourcemaps.write())
    .pipe(concat('openlmis.css'))
    .pipe(sass().on('error', sass.logError))
    .pipe(replace('../','')) // remove non-relative strings
    //Replace UI-Grid font paths
    .pipe(replace('ui-grid.eot','fonts/ui-grid.eot'))
    .pipe(replace('ui-grid.ttf','fonts/ui-grid.ttf'))
    .pipe(replace('ui-grid.woff','fonts/ui-grid.woff'))
    .pipe(replace('ui-grid.svg','fonts/ui-grid.svg'))
    //Replace Select2 image locations
    .pipe(replace('select2.png','images/select2.png'))
    .pipe(replace('select2-spinner.gif','images/select2-spinner.gif'))
    .pipe(replace('select2x2.png','images/select2x2.png'))
    .pipe(bless())
    .pipe(gulp.dest(
      path.join(config.app.dest, "public")
    ));
      }
    },
    ngtemplates: {
      app: {
        cwd:      config.app.src + '/webapp/public',
        src:      ['**/**.html', '!index.html'],
        dest:     '.tmp/templates.js',
        options: {
          module:   'openlmis',
          concat:   'js'
        }
      }
    }
  });

  grunt.registerTask('sass', ['gulp:sass']);

  function makeURL(key){
    if (!key) {
      return false;
    }
    var url = grunt.option(key) || config[key];
    if (grunt.option('addProxyService') && url && url.substr(0,4).toLowerCase() == "http") {
      return 'http://127.0.0.1:3030/' + url;
    } else {
      return url;
    }
  }

  grunt.registerTask('serve:proxy', 'Start proxy server', function(){
    var host = '127.0.0.1';
    var port = 3030;

    if (grunt.option('addProxyService')){
      grunt.log.writeln('starting proxy server at ' + host + ':' + port);
      cors_proxy.createServer().listen(port, host);
    }
  });

  grunt.registerTask('serve', ['serve:proxy', 'connect:server']);

  var buildTasks = ['clean', 'ngtemplates', 'copy', 'concat', 'sass', 'replace'];
  var styleguideTasks = ['gulp:styleguide-generate', 'gulp:styleguide-png', 'gulp:styleguide-fonts', 'gulp:styleguide-applystyles', 'gulp:styleguide-index-replace'];

  var fullBuildTasks = [].concat(buildTasks);
  if(grunt.option('production')) fullBuildTasks.push('uglify');
  if(!grunt.option('noTest') && !grunt.option('appOnly')) fullBuildTasks.push('karma:unit');
  if(!grunt.option('noStyleguide') && !grunt.option('appOnly')) fullBuildTasks = fullBuildTasks.concat(styleguideTasks);
  if(!grunt.option('noDocs') && !grunt.option('appOnly')) fullBuildTasks.push('ngdocs');

  grunt.registerTask('build', fullBuildTasks);

  grunt.registerTask('check', ['clean', 'jshint', 'sasslint']);

  grunt.registerTask('docs', ['build'].concat('ngdocs'));
  grunt.registerTask('styleguide', buildTasks.concat(styleguideTasks));
};
<commit_msg>OLMIS-1341: Move templates back to olmis-core<commit_after>module.exports = function(grunt) {
  require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);
  var config = require('./config');
  var styleguide = require('sc5-styleguide');
  var path = require('path');
  var wiredep = require('wiredep');
  var cors_proxy = require('cors-anywhere');

  var gulp = require('gulp');
  // registering promisies for gulp...
  require("any-promise/register")("bluebird");
  var sass = require('gulp-sass');
  var bless = require('gulp-bless');
  var sourcemaps = require('gulp-sourcemaps');
  var concat = require('gulp-concat');
  var replace = require('gulp-replace');

  grunt.loadNpmTasks('grunt-ngdocs');

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    clean: ['build', 'quality'],
    jshint: {
      options: {
        undef: false,
        strict: false,
        '-W030': true,
        unused: false,
        passfail: true,
        reporter: 'checkstyle',
        reporterOutput: 'quality/js/checkstyle-results.xml'
      },
      all: [config.app.src + '/webapp/public/js/**/*.js']
    },
    sasslint: {
      src: [
        path.join(config.app.src,'**/*.scss'),
        '!**/ng-grid.scss'
      ],
      options: {
        bench: false,
        config: '.sasslint.json'
      }
    },
    watch: {
      files: config.app.src + '/**/*',
      tasks: ['build'],
      options: {
        spawn: false
      }
    },
    uglify: {
      options: {
        mangle: false,
        beautify: true,
        report: 'min',
        preserveComments: false
      },
      files: {
        cwd: config.app.dest + '/public/',
        src: ['**/*.js'],
        dest: config.app.dest + '/public/',
        expand: true,
        flatten: false
      }
    },
    connect: {
      server: {
        options: {
          keepalive: true,
          debug: true,
          port: 9000,
          base: config.app.dest
        }
      }
    },
    karma: {
      options: {
        configFile: 'karma.config.js'
      },
      unit: {
        // default
      },
      tdd: {
        singleRun: false
      }
    },
    replace: {
      serverurl: {
        src: [config.app.dest + '/public/**/*.js'],
        overwrite: true,
        replacements: [{
          from: '@@OPENLMIS_SERVER_URL',
          to: makeURL('openlmisServerURL')
        },{
          from: '@@AUTH_SERVICE_URL',
          to: makeURL('authServiceURL')
        },{
          from: '@@REQUISITION_SERVICE_URL',
          to: makeURL('requisitionServiceURL')
        }]
      }
    },
    concat: {
      js: {
        options: {
          sourceMap: true
        },
        src: function(){
          var appFiles = [
            // Module registration
            config.app.src + '/webapp/public/**/module/*.js',
            config.app.src + '/webapp/public/**/*.module.js',
            // Legacy files
            config.app.src + '/webapp/public/js/shared/util.js',
            config.app.src + '/webapp/public/js/shared/*.js',
            config.app.src + '/webapp/public/js/shared/services/services.js',
            config.app.src + '/webapp/public/js/shared/**/*.js',
            // Special file types....
            config.app.src + '/webapp/public/**/*.config.js',
            config.app.src + '/webapp/public/**/*.routes.js',
            '!' + config.app.src + '/webapp/public/app.routes.js',
            // Everything else
            config.app.src + '/webapp/public/**/*.js',
            '!' + config.app.src + '/**/*.spec.js',
            '!' + config.app.src + '/webapp/public/app.js',
            '!' + config.app.src + '/webapp/public/app.routes.js',
            // Run time
            // NEED file to declare openlmis-app
            config.app.src + '/webapp/public/app.js',
            config.app.src + '/webapp/public/app.routes.js'
          ];
          // hack to make jquery load first
          return [
              'bower_components/jquery/dist/jquery.js',
              'bower_components/jquery-ui/jquery-ui.js'
            ].concat(
              wiredep().js,
              [
                'vendor/ng-grid-2.0.7.min.js',
                'vendor/base2.js'
              ],
              appFiles
            );
        }(),
        dest: config.app.dest + '/public/openlmis.js'
      }
    },
    copy: {
      main: {
        files: [
          {
            expand: true,
            cwd: config.app.src + '/webapp/',
            src: ['*'],
            dest: config.app.dest + '/public',
            filter: 'isFile'
          }
        ],
      },
      images: {
        files: [
          {
            expand: true,
            cwd: config.app.src + '/webapp/public/',
            src: [
              '**/*.png',
              '**/*.jpg',
              '**/*.gif'
            ],
            dest: config.app.dest + '/public'
          }
        ],
      },
      img: {
        files: [
          {
            expand: true,
            flatten: true,
            cwd: config.app.src + '/webapp/public/lib/',
            src: ['**/img/**'],
            dest: config.app.dest + '/public/img'
          }
        ],
      },
      fonts: {
        files: [
          {
            expand: true,
            cwd: config.app.src + '/webapp/public/fonts/',
            src: ['**'],
            dest: config.app.dest + '/public/fonts'
          }
        ],
      },
      pages: {
        files: [
          {
            expand: true,
            cwd: config.app.src + '/webapp/public/',
            src: ['index.html'],
            dest: config.app.dest + '/public'
          }
        ],
      },
      messages: {
        files: [
          {
            expand: true,
            cwd: config.app.src + '/resources',
            src: ['messages_*.json'],
            dest: config.app.dest + '/public/messages'
          }
        ]
      },
      credentials: {
        files: [
          {
            expand: true,
            cwd: config.app.src + '/resources',
            src: ['auth_server_client.json'],
            dest: config.app.dest + '/public/credentials'
          }
        ]
      },
      fontAwesomeFonts: {
        files: [
          {
            expand: true,
            cwd: 'bower_components/font-awesome/fonts/',
            src: '*',
            dest: path.join(config.app.dest, 'public/fonts')
          }
        ]
      },
      uiGridFonts: {
        files: [
          {
            expand: true,
            cwd: 'bower_components/angular-ui-grid/',
            src: [
              'ui-grid.eot',
              'ui-grid.svg',
              'ui-grid.ttf',
              'ui-grid.woff'
            ],
            dest: config.app.dest + '/public/fonts'
          }
        ]
      },
      bootstrapFonts: {
        files: [
          {
            expand: true,
            cwd: 'bower_components/bootstrap/fonts/',
            src: [
              'glyphicons-halflings-regular.eot',
              'glyphicons-halflings-regular.svg',
              'glyphicons-halflings-regular.ttf',
              'glyphicons-halflings-regular.woff',
              'glyphicons-halflings-regular.woff2'
            ],
            dest: config.app.dest + '/public/fonts/bootstrap'
          }
        ]
      },
      selectTwoImages: {
        expand: true,
        cwd: 'bower_components/select2/',
        src: [
            '*.png',
            '*.gif'
        ],
        dest: path.join(config.app.dest, 'public/images')
      }
    },
    ngdocs: {
      options:{
        dest: "./build/docs",
        title: "OpenLMIS-UI Documentation"
      },
      api: {
        src: [
          path.join(config.app.src, "**/*.js"),
          "!" + path.join(config.app.src, "**/*.spec.js")
        ],
        title: "API"
      }
    },
    gulp: {
      'styleguide-generate': function() {
        return gulp.src([
                        path.join(config.styleguide.src,"**/*.scss"),
                        "!"+path.join(config.styleguide.src,"**/scss/*.scss")
                        ])
          .pipe(styleguide.generate({
            title: 'OpenLMIS Styleguide',
            appRoot: "http://replaceThis",
            disableHtml5Mode: true,
            overviewPath: path.join(config.docs.src, 'styleguide.md')
          }))
          .pipe(gulp.dest(config.styleguide.dest));
      },
      'styleguide-applystyles': function() {
        return gulp.src([
                  path.join(config.app.dest,"/public/openlmis*.css")
                  ])
          .pipe(styleguide.applyStyles())
          .pipe(gulp.dest(config.styleguide.dest));
      },
      'styleguide-fonts': function() {
        return gulp.src([
            path.join(config.app.dest, "public/fonts/*"),
          ])
          .pipe(gulp.dest(path.join(config.styleguide.dest,"fonts")));
      },
      'styleguide-png': function() {
        return gulp.src([
                    config.app.dest + "/public/images/*",
                    config.app.dest + "/public/images/*"
                   ])
          .pipe(gulp.dest(path.join(config.styleguide.dest,"images")));
      },
      'styleguide-index-replace': function(){
        return gulp.src([
            path.join(config.styleguide.dest, 'index.html'),
            path.join(config.styleguide.dest, 'styleguide-app.css')
          ])
          .pipe(replace("http://replaceThis/", ""))
          .pipe(replace("font-family: 'FontAwesome';", ""))
          .pipe(gulp.dest(config.styleguide.dest));
      },
      'sass': function(){
   var includePaths = require('node-bourbon').includePaths.concat([
        config.app.src,
        'bower_components/font-awesome/scss',
        'bower_components/bootstrap-sass/assets/stylesheets',
        'bower_components/select2/src/scss'
    ]);

    var bowerCss = wiredep().css;
    var bowerSass = wiredep().scss;

    var files = [].concat(
      [
        path.join(config.app.src, "**/*variables.scss"),
        path.join(config.app.src, "**/*.variables.scss")
      ],
      bowerSass,
      bowerCss,
      [
        path.join(config.app.src, "/**/*mixins.scss"),
        path.join(config.app.src, "/**/*.mixins.scss"),
        path.join(config.app.src, '**/*.css'),
        path.join(config.app.src, '**/*.scss'),
        "!" + path.join(config.app.src, "webapp/public/scss/*")
      ]);

    var outputStyle = "expanded";
    if(grunt.option('production')) outputStyle = "compressed";

    return gulp.src(files)
   .pipe(sourcemaps.init())
    .pipe(concat({
      path:'openlmis.scss'
    }))
    .pipe(sass({
      includePaths: includePaths,
      outputStyle: outputStyle,
    }))
    .pipe(sourcemaps.write())
    .pipe(concat('openlmis.css'))
    .pipe(sass().on('error', sass.logError))
    .pipe(replace('../','')) // remove non-relative strings
    //Replace UI-Grid font paths
    .pipe(replace('ui-grid.eot','fonts/ui-grid.eot'))
    .pipe(replace('ui-grid.ttf','fonts/ui-grid.ttf'))
    .pipe(replace('ui-grid.woff','fonts/ui-grid.woff'))
    .pipe(replace('ui-grid.svg','fonts/ui-grid.svg'))
    //Replace Select2 image locations
    .pipe(replace('select2.png','images/select2.png'))
    .pipe(replace('select2-spinner.gif','images/select2-spinner.gif'))
    .pipe(replace('select2x2.png','images/select2x2.png'))
    .pipe(bless())
    .pipe(gulp.dest(
      path.join(config.app.dest, "public")
    ));
      }
    },
    ngtemplates: {
      app: {
        cwd:      config.app.src + '/webapp/public',
        src:      ['**/**.html', '!index.html'],
        dest:     '.tmp/templates.js',
        options: {
          module:   'openlmis-core',
          concat:   'js'
        }
      }
    }
  });

  grunt.registerTask('sass', ['gulp:sass']);

  function makeURL(key){
    if (!key) {
      return false;
    }
    var url = grunt.option(key) || config[key];
    if (grunt.option('addProxyService') && url && url.substr(0,4).toLowerCase() == "http") {
      return 'http://127.0.0.1:3030/' + url;
    } else {
      return url;
    }
  }

  grunt.registerTask('serve:proxy', 'Start proxy server', function(){
    var host = '127.0.0.1';
    var port = 3030;

    if (grunt.option('addProxyService')){
      grunt.log.writeln('starting proxy server at ' + host + ':' + port);
      cors_proxy.createServer().listen(port, host);
    }
  });

  grunt.registerTask('serve', ['serve:proxy', 'connect:server']);

  var buildTasks = ['clean', 'ngtemplates', 'copy', 'concat', 'sass', 'replace'];
  var styleguideTasks = ['gulp:styleguide-generate', 'gulp:styleguide-png', 'gulp:styleguide-fonts', 'gulp:styleguide-applystyles', 'gulp:styleguide-index-replace'];

  var fullBuildTasks = [].concat(buildTasks);
  if(grunt.option('production')) fullBuildTasks.push('uglify');
  if(!grunt.option('noTest') && !grunt.option('appOnly')) fullBuildTasks.push('karma:unit');
  if(!grunt.option('noStyleguide') && !grunt.option('appOnly')) fullBuildTasks = fullBuildTasks.concat(styleguideTasks);
  if(!grunt.option('noDocs') && !grunt.option('appOnly')) fullBuildTasks.push('ngdocs');

  grunt.registerTask('build', fullBuildTasks);

  grunt.registerTask('check', ['clean', 'jshint', 'sasslint']);

  grunt.registerTask('docs', ['build'].concat('ngdocs'));
  grunt.registerTask('styleguide', buildTasks.concat(styleguideTasks));
};
<|endoftext|>


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

	require('jit-grunt')(grunt, {
		cachebreaker : 	'grunt-cache-breaker',
		replace: 		'grunt-text-replace'
	});

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

		developmentPath: 'dev',
		productionPath: 'dist',
		modulePath: 'git_submodules',

		compass: {
			options: {
				cssDir: 'assets/css',
				sassDir: 'assets/sass',
				imagesDir: 'assets/img',
				javascriptsDir: 'assets/js',
				fontsDir: 'assets/webfonts',
				relativeAssets: true,
				quiet: true,
				require : [
					'sass-globbing',
				]
			},
			development: {
				options: {
					basePath: '<%= developmentPath %>/',
					environment: 'development',
					outputStyle: 'expanded',
					noLineComments: false,
					sourcemap: true
				}
			}
		},

		svgstore: {
			development: {
				files: {
					'<%= productionPath %>/assets/img/layout/svg-sprite.svg': [
						'<%= developmentPath %>/assets/img/layout/svg/**/*.svg'
					]
				},
				options: {
					cleanup: true,
					cleanupdefs: true,
					prefix : 'glyph-',
					inheritviewbox: true
				}
			}
		},

		concat: {
			options: {
				separator: ';',
				sourceMap: true
			},
			modules : {
				src: (function () {
					var cwd = "<%= modulePath %>/";
					var files = [
						"**/tipi.*.js",
					];

					files = files.map(function (file) {
						return cwd + file;
					});

					return files;
				}()),
				dest: '<%= productionPath %>/assets/js/lib/tipi/tipi.js',
			}
		},

		zetzer: {
			options: {
				partials: "<%= developmentPath %>/inc/partials/",
				templates: "<%= developmentPath %>/inc/templates/"
			},
			development: {
				files: [{
					expand: true,
					cwd: '<%= developmentPath %>/',
					src: '*.html',
					dest: '<%= productionPath %>/',
					ext: '.html',
					flatten: false
				}]
			},
			modules: {
				files: [{
					expand: true,
					cwd: '<%= modulePath %>/',
					src: 'tipi.*/*.html',
					dest: '<%= productionPath %>/pages/',
					ext: '.html',
					flatten: false
				}]
			}
		},

		clean: {
			development: {
				src: [
					'<%= productionPath %>'
				]
			}
		},

		copy: {
			development: {
				expand: true,
				cwd: '<%= developmentPath %>/',
				src: [
					'assets/**'
				],
				dest: '<%= productionPath %>/'
			},
			img: {
				expand: true,
				cwd: '<%= developmentPath %>/',
				src: [
					'assets/**/*.{.png,jpg,gif,svg}'
				],
				dest: '<%= productionPath %>/'
			}
		},

		combine_mq: {
			production: {
				expand: true,
				cwd: '<%= developmentPath %>/assets/css/',
				src: ['**/*.css', '!**/*.min.css'],
				dest: '<%= developmentPath %>/assets/css/'
			}
		},

		cssmin: {
			production: {
				files: [{
					expand: true,
					cwd: '<%= developmentPath %>/assets/css',
					src: ['*.css', '!*.min.css'],
					dest: '<%= productionPath %>/assets/css',
					ext: '.min.css'
				}]
			}
		},

		image: {
			production: {
				options: {
					jpegRecompress: true,
					jpegoptim: true,
					mozjpeg: true,
					svgo: true
				},
				files: [{
					expand: true,
					cwd: '<%= productionPath %>/assets/img/',
					src: ['**/*.{png,jpg,gif,svg}'],
					dest: '<%= productionPath %>/assets/img/'
				}]
			}
		},

		replace: {
			production: {
				src: ['<%= productionPath%>/**/*.html'],
				dest: '<%= productionPath%>/',
				replacements: [
					{
						from: 'tipi.css',
						to: 'tipi.min.css'
					},
					{
						from: 'main.js',
						to: 'main.min.js'
					},
					{
						from: 'tipi.js',
						to: 'tipi.min.js'
					}
				]
			}
		},

		cachebreaker: {
			production: {
				options: {
					match: [
						'cached',
						'css/*/tipi.min.css',
						'js/*/tipi.min.js'
					]
				},
				files: {
					src: [
						'<%= productionPath %>/**/*.html'
					]
				}
			}
		},

		watch: {
			options: {
				interrupt: true,
			},
			scss: {
				files: [
					'<%= developmentPath %>/assets/sass/**/*.scss',
					'<%= modulePath %>/**/*.scss',

					'!**/node_modules/**',
				],
				tasks: [
					'compass:development',
					'svgstore:development',
					'newer:copy:development'
				],
				options: {
					spawn : true
				}
			},
			img: {
				files: [
					'<%= developmentPath %>/assets/img/**/*.{png,jpg,gif,svg}',

					'!**/node_modules/**'
				],
				tasks: [
					'newer:copy:img'
				],
				options : {
					event: ['added', 'deleted']
				}
			},
			svg: {
				files: [
					'<%= developmentPath %>/**/*.svg'
				],
				tasks: [
					'svgstore:development',
					'newer:copy:development'
				]
			},
			js: {
				files: [
					'<%= modulePath %>/**/tipi.*.js'
				],
				tasks: [
					'concat:modules'
				]
			},
			html: {
				files: [
					'<%= developmentPath %>/**/*.html',
					'<%= modulePath %>/tipi.*/*.html'
				],
				tasks: [
					'zetzer:development',
					'zetzer:modules',
				]
			},
			reload: {
				files: [
					'<%= productionPath %>/**/*.css'
				],
				options : {
					livereload : true,
					livereloadOnError: false
				}
			},
			config: {
				files : [
					'Gruntfile.js'
				],
				options : {
					reload : true
				}
			}
		},

		connect: {
			development: {
				options: {
					port: 8000,
					base: '<%= productionPath %>',
					livereload: true,
					open: {
						target: 'http://localhost:8000'
					}
				}
			}
		},

		concurrent: {
			development: [
				'compass:development',
				'svgstore:development',
				'concat:modules',
				'zetzer:development',
				'zetzer:modules',
			],
			production: [
				'combine_mq:production',
				'cssmin:production',
				'newer:image:production'
			]
		}
	});

	grunt.registerTask(
		'default', [
			'clean:development',
			'concurrent:development',
			'copy:development'
		]
	);

	grunt.registerTask(
		'serve', [
			'clean:development',
			'concurrent:development',
			'copy:development',
			'connect:development',
			'watch'
		]
	);

	grunt.registerTask(
		'build', [
			'clean:development',
			'concurrent:development',
			'copy:development',
			'concurrent:production',
			'replace:production',
			'cachebreaker:production'
		]
	);
};<commit_msg>Fix: Watch grunt files within the module folder<commit_after>module.exports = function(grunt) {

	require('jit-grunt')(grunt, {
		cachebreaker : 	'grunt-cache-breaker',
		replace: 		'grunt-text-replace'
	});

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

		developmentPath: 'dev',
		productionPath: 'dist',
		modulePath: 'git_submodules',

		compass: {
			options: {
				cssDir: 'assets/css',
				sassDir: 'assets/sass',
				imagesDir: 'assets/img',
				javascriptsDir: 'assets/js',
				fontsDir: 'assets/webfonts',
				relativeAssets: true,
				quiet: true,
				require : [
					'sass-globbing',
				]
			},
			development: {
				options: {
					basePath: '<%= developmentPath %>/',
					environment: 'development',
					outputStyle: 'expanded',
					noLineComments: false,
					sourcemap: true
				}
			}
		},

		svgstore: {
			development: {
				files: {
					'<%= productionPath %>/assets/img/layout/svg-sprite.svg': [
						'<%= developmentPath %>/assets/img/layout/svg/**/*.svg'
					]
				},
				options: {
					cleanup: true,
					cleanupdefs: true,
					prefix : 'glyph-',
					inheritviewbox: true
				}
			}
		},

		concat: {
			options: {
				separator: ';',
				sourceMap: true
			},
			modules : {
				src: (function () {
					var cwd = "<%= modulePath %>/";
					var files = [
						"**/tipi.*.js",
					];

					files = files.map(function (file) {
						return cwd + file;
					});

					return files;
				}()),
				dest: '<%= productionPath %>/assets/js/lib/tipi/tipi.js',
			}
		},

		zetzer: {
			options: {
				partials: "<%= developmentPath %>/inc/partials/",
				templates: "<%= developmentPath %>/inc/templates/"
			},
			development: {
				files: [{
					expand: true,
					cwd: '<%= developmentPath %>/',
					src: '*.html',
					dest: '<%= productionPath %>/',
					ext: '.html',
					flatten: false
				}]
			},
			modules: {
				files: [{
					expand: true,
					cwd: '<%= modulePath %>/',
					src: 'tipi.*/*.html',
					dest: '<%= productionPath %>/pages/',
					ext: '.html',
					flatten: false
				}]
			}
		},

		clean: {
			development: {
				src: [
					'<%= productionPath %>'
				]
			}
		},

		copy: {
			development: {
				expand: true,
				cwd: '<%= developmentPath %>/',
				src: [
					'assets/**'
				],
				dest: '<%= productionPath %>/'
			},
			img: {
				expand: true,
				cwd: '<%= developmentPath %>/',
				src: [
					'assets/**/*.{.png,jpg,gif,svg}'
				],
				dest: '<%= productionPath %>/'
			}
		},

		combine_mq: {
			production: {
				expand: true,
				cwd: '<%= developmentPath %>/assets/css/',
				src: ['**/*.css', '!**/*.min.css'],
				dest: '<%= developmentPath %>/assets/css/'
			}
		},

		cssmin: {
			production: {
				files: [{
					expand: true,
					cwd: '<%= developmentPath %>/assets/css',
					src: ['*.css', '!*.min.css'],
					dest: '<%= productionPath %>/assets/css',
					ext: '.min.css'
				}]
			}
		},

		image: {
			production: {
				options: {
					jpegRecompress: true,
					jpegoptim: true,
					mozjpeg: true,
					svgo: true
				},
				files: [{
					expand: true,
					cwd: '<%= productionPath %>/assets/img/',
					src: ['**/*.{png,jpg,gif,svg}'],
					dest: '<%= productionPath %>/assets/img/'
				}]
			}
		},

		replace: {
			production: {
				src: ['<%= productionPath%>/**/*.html'],
				dest: '<%= productionPath%>/',
				replacements: [
					{
						from: 'tipi.css',
						to: 'tipi.min.css'
					},
					{
						from: 'main.js',
						to: 'main.min.js'
					},
					{
						from: 'tipi.js',
						to: 'tipi.min.js'
					}
				]
			}
		},

		cachebreaker: {
			production: {
				options: {
					match: [
						'cached',
						'css/*/tipi.min.css',
						'js/*/tipi.min.js'
					]
				},
				files: {
					src: [
						'<%= productionPath %>/**/*.html'
					]
				}
			}
		},

		watch: {
			options: {
				interrupt: true,
			},
			scss: {
				files: [
					'<%= developmentPath %>/assets/sass/**/*.scss',
					'<%= modulePath %>/**/*.scss',

					'!**/node_modules/**',
				],
				tasks: [
					'compass:development',
					'svgstore:development',
					'newer:copy:development'
				],
				options: {
					spawn : true
				}
			},
			img: {
				files: [
					'<%= developmentPath %>/assets/img/**/*.{png,jpg,gif,svg}',

					'!**/node_modules/**'
				],
				tasks: [
					'newer:copy:img'
				],
				options : {
					event: ['added', 'deleted']
				}
			},
			svg: {
				files: [
					'<%= developmentPath %>/**/*.svg'
				],
				tasks: [
					'svgstore:development',
					'newer:copy:development'
				]
			},
			js: {
				files: [
					'<%= modulePath %>/**/tipi.*.js'
				],
				tasks: [
					'concat:modules'
				]
			},
			html: {
				files: [
					'<%= developmentPath %>/**/*.html',
					'<%= modulePath %>/**/*.html'
				],
				tasks: [
					'zetzer:development',
					'zetzer:modules',
				]
			},
			reload: {
				files: [
					'<%= productionPath %>/**/*.css'
				],
				options : {
					livereload : true,
					livereloadOnError: false
				}
			},
			config: {
				files : [
					'Gruntfile.js'
				],
				options : {
					reload : true
				}
			}
		},

		connect: {
			development: {
				options: {
					port: 8000,
					base: '<%= productionPath %>',
					livereload: true,
					open: {
						target: 'http://localhost:8000'
					}
				}
			}
		},

		concurrent: {
			development: [
				'compass:development',
				'svgstore:development',
				'concat:modules',
				'zetzer:development',
				'zetzer:modules',
			],
			production: [
				'combine_mq:production',
				'cssmin:production',
				'newer:image:production'
			]
		}
	});

	grunt.registerTask(
		'default', [
			'clean:development',
			'concurrent:development',
			'copy:development'
		]
	);

	grunt.registerTask(
		'serve', [
			'clean:development',
			'concurrent:development',
			'copy:development',
			'connect:development',
			'watch'
		]
	);

	grunt.registerTask(
		'build', [
			'clean:development',
			'concurrent:development',
			'copy:development',
			'concurrent:production',
			'replace:production',
			'cachebreaker:production'
		]
	);
};<|endoftext|>


<commit_before>(function( jQuery ) {

var ralpha = /alpha\([^)]*\)/i,
	ropacity = /opacity=([^)]*)/,
	rdashAlpha = /-([a-z])/ig,
	rupper = /([A-Z])/g,
	rnumpx = /^-?\d+(?:px)?$/i,
	rnum = /^-?\d/,

	cssShow = { position: "absolute", visibility: "hidden", display: "block" },
	cssWidth = [ "Left", "Right" ],
	cssHeight = [ "Top", "Bottom" ],
	curCSS,

	getComputedStyle,
	currentStyle,

	fcamelCase = function( all, letter ) {
		return letter.toUpperCase();
	};

jQuery.fn.css = function( name, value ) {
	// Setting 'undefined' is a no-op
	if ( arguments.length === 2 && value === undefined ) {
		return this;
	}

	return jQuery.access( this, name, value, true, function( elem, name, value ) {
		return value !== undefined ?
			jQuery.style( elem, name, value ) :
			jQuery.css( elem, name );
	});
};

jQuery.extend({
	// Add in style property hooks for overriding the default
	// behavior of getting and setting a style property
	cssHooks: {
		opacity: {
			get: function( elem, computed ) {
				if ( computed ) {
					// We should always get a number back from opacity
					var ret = curCSS( elem, "opacity", "opacity" );
					return ret === "" ? "1" : ret;

				} else {
					return elem.style.opacity;
				}
			}
		}
	},

	// Exclude the following css properties to add px
	cssNumber: {
		"zIndex": true,
		"fontWeight": true,
		"opacity": true,
		"zoom": true,
		"lineHeight": true
	},

	// Add in properties whose names you wish to fix before
	// setting or getting the value
	cssProps: {
		// normalize float css property
		"float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat"
	},

	// Get and set the style property on a DOM Node
	style: function( elem, name, value, extra ) {
		// Don't set styles on text and comment nodes
		if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
			return;
		}

		// Make sure that we're working with the right name
		var ret, origName = jQuery.camelCase( name ),
			style = elem.style, hooks = jQuery.cssHooks[ origName ];

		name = jQuery.cssProps[ origName ] || origName;

		// Check if we're setting a value
		if ( value !== undefined ) {
			// Make sure that NaN and null values aren't set. See: #7116
			if ( typeof value === "number" && isNaN( value ) || value == null ) {
				return;
			}

			// If a number was passed in, add 'px' to the (except for certain CSS properties)
			if ( typeof value === "number" && !jQuery.cssNumber[ origName ] ) {
				value += "px";
			}

			// If a hook was provided, use that value, otherwise just set the specified value
			if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value )) !== undefined ) {
				// Wrapped to prevent IE from throwing errors when 'invalid' values are provided
				// Fixes bug #5509
				try {
					style[ name ] = value;
				} catch(e) {}
			}

		} else {
			// If a hook was provided get the non-computed value from there
			if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
				return ret;
			}

			// Otherwise just get the value from the style object
			return style[ name ];
		}
	},

	css: function( elem, name, extra ) {
		// Make sure that we're working with the right name
		var ret, origName = jQuery.camelCase( name ),
			hooks = jQuery.cssHooks[ origName ];

		name = jQuery.cssProps[ origName ] || origName;

		// If a hook was provided get the computed value from there
		if ( hooks && "get" in hooks && (ret = hooks.get( elem, true, extra )) !== undefined ) {
			return ret;

		// Otherwise, if a way to get the computed value exists, use that
		} else if ( curCSS ) {
			return curCSS( elem, name, origName );
		}
	},

	// A method for quickly swapping in/out CSS properties to get correct calculations
	swap: function( elem, options, callback ) {
		var old = {};

		// Remember the old values, and insert the new ones
		for ( var name in options ) {
			old[ name ] = elem.style[ name ];
			elem.style[ name ] = options[ name ];
		}

		callback.call( elem );

		// Revert the old values
		for ( name in options ) {
			elem.style[ name ] = old[ name ];
		}
	},

	camelCase: function( string ) {
		return string.replace( rdashAlpha, fcamelCase );
	}
});

// DEPRECATED, Use jQuery.css() instead
jQuery.curCSS = jQuery.css;

jQuery.each(["height", "width"], function( i, name ) {
	jQuery.cssHooks[ name ] = {
		get: function( elem, computed, extra ) {
			var val;

			if ( computed ) {
				if ( elem.offsetWidth !== 0 ) {
					val = getWH( elem, name, extra );

				} else {
					jQuery.swap( elem, cssShow, function() {
						val = getWH( elem, name, extra );
					});
				}

				if ( val <= 0 ) {
					val = curCSS( elem, name, name );

					if ( val === "0px" && currentStyle ) {
						val = currentStyle( elem, name, name );
					}

					if ( val != null ) {
						// Should return "auto" instead of 0, use 0 for
						// temporary backwards-compat
						return val === "" ? "0px" : val;
					}
				}

				if ( val < 0 || val == null ) {
					val = elem.style[ name ];

					// Should return "auto" instead of 0, use 0 for
					// temporary backwards-compat
					return val === "" ? "0px" : val;
				}

				return typeof val === "string" ? val : val + "px";
			}
		},

		set: function( elem, value ) {
			if ( rnumpx.test( value ) ) {
				// ignore negative width and height values #1599
				value = parseFloat(value);

				if ( value >= 0 ) {
					return value + "px";
				}

			} else {
				return value;
			}
		}
	};
});

if ( !jQuery.support.opacity ) {
	jQuery.cssHooks.opacity = {
		get: function( elem, computed ) {
			// IE uses filters for opacity
			return ropacity.test((computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "") ?
				(parseFloat(RegExp.$1) / 100) + "" :
				computed ? "1" : "";
		},

		set: function( elem, value ) {
			var style = elem.style;

			// IE has trouble with opacity if it does not have layout
			// Force it by setting the zoom level
			style.zoom = 1;

			// Set the alpha filter to set the opacity
			var opacity = jQuery.isNaN(value) ?
				"" :
				"alpha(opacity=" + value * 100 + ")",
				filter = style.filter || "";

			style.filter = ralpha.test(filter) ?
				filter.replace(ralpha, opacity) :
				style.filter + ' ' + opacity;
		}
	};
}

if ( document.defaultView && document.defaultView.getComputedStyle ) {
	getComputedStyle = function( elem, newName, name ) {
		var ret, defaultView, computedStyle;

		name = name.replace( rupper, "-$1" ).toLowerCase();

		if ( !(defaultView = elem.ownerDocument.defaultView) ) {
			return undefined;
		}

		if ( (computedStyle = defaultView.getComputedStyle( elem, null )) ) {
			ret = computedStyle.getPropertyValue( name );
			if ( ret === "" && !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) {
				ret = jQuery.style( elem, name );
			}
		}

		return ret;
	};
}

if ( document.documentElement.currentStyle ) {
	currentStyle = function( elem, name ) {
		var left, rsLeft,
			ret = elem.currentStyle && elem.currentStyle[ name ],
			style = elem.style;

		// From the awesome hack by Dean Edwards
		// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291

		// If we're not dealing with a regular pixel number
		// but a number that has a weird ending, we need to convert it to pixels
		if ( !rnumpx.test( ret ) && rnum.test( ret ) ) {
			// Remember the original values
			left = style.left;
			rsLeft = elem.runtimeStyle.left;

			// Put in the new values to get a computed value out
			elem.runtimeStyle.left = elem.currentStyle.left;
			style.left = name === "fontSize" ? "1em" : (ret || 0);
			ret = style.pixelLeft + "px";

			// Revert the changed values
			style.left = left;
			elem.runtimeStyle.left = rsLeft;
		}

		return ret === "" ? "auto" : ret;
	};
}

curCSS = getComputedStyle || currentStyle;

function getWH( elem, name, extra ) {
	var which = name === "width" ? cssWidth : cssHeight,
		val = name === "width" ? elem.offsetWidth : elem.offsetHeight;

	if ( extra === "border" ) {
		return val;
	}

	jQuery.each( which, function() {
		if ( !extra ) {
			val -= parseFloat(jQuery.css( elem, "padding" + this )) || 0;
		}

		if ( extra === "margin" ) {
			val += parseFloat(jQuery.css( elem, "margin" + this )) || 0;

		} else {
			val -= parseFloat(jQuery.css( elem, "border" + this + "Width" )) || 0;
		}
	});

	return val;
}

if ( jQuery.expr && jQuery.expr.filters ) {
	jQuery.expr.filters.hidden = function( elem ) {
		var width = elem.offsetWidth,
			height = elem.offsetHeight;

		return (width === 0 && height === 0) || (!jQuery.support.reliableHiddenOffsets && (elem.style.display || jQuery.css( elem, "display" )) === "none");
	};

	jQuery.expr.filters.visible = function( elem ) {
		return !jQuery.expr.filters.hidden( elem );
	};
}

})( jQuery );
<commit_msg>Need to also handle the case where 'auto' is being returned, as in Firefox. Follow-up to #7395.<commit_after>(function( jQuery ) {

var ralpha = /alpha\([^)]*\)/i,
	ropacity = /opacity=([^)]*)/,
	rdashAlpha = /-([a-z])/ig,
	rupper = /([A-Z])/g,
	rnumpx = /^-?\d+(?:px)?$/i,
	rnum = /^-?\d/,

	cssShow = { position: "absolute", visibility: "hidden", display: "block" },
	cssWidth = [ "Left", "Right" ],
	cssHeight = [ "Top", "Bottom" ],
	curCSS,

	getComputedStyle,
	currentStyle,

	fcamelCase = function( all, letter ) {
		return letter.toUpperCase();
	};

jQuery.fn.css = function( name, value ) {
	// Setting 'undefined' is a no-op
	if ( arguments.length === 2 && value === undefined ) {
		return this;
	}

	return jQuery.access( this, name, value, true, function( elem, name, value ) {
		return value !== undefined ?
			jQuery.style( elem, name, value ) :
			jQuery.css( elem, name );
	});
};

jQuery.extend({
	// Add in style property hooks for overriding the default
	// behavior of getting and setting a style property
	cssHooks: {
		opacity: {
			get: function( elem, computed ) {
				if ( computed ) {
					// We should always get a number back from opacity
					var ret = curCSS( elem, "opacity", "opacity" );
					return ret === "" ? "1" : ret;

				} else {
					return elem.style.opacity;
				}
			}
		}
	},

	// Exclude the following css properties to add px
	cssNumber: {
		"zIndex": true,
		"fontWeight": true,
		"opacity": true,
		"zoom": true,
		"lineHeight": true
	},

	// Add in properties whose names you wish to fix before
	// setting or getting the value
	cssProps: {
		// normalize float css property
		"float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat"
	},

	// Get and set the style property on a DOM Node
	style: function( elem, name, value, extra ) {
		// Don't set styles on text and comment nodes
		if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
			return;
		}

		// Make sure that we're working with the right name
		var ret, origName = jQuery.camelCase( name ),
			style = elem.style, hooks = jQuery.cssHooks[ origName ];

		name = jQuery.cssProps[ origName ] || origName;

		// Check if we're setting a value
		if ( value !== undefined ) {
			// Make sure that NaN and null values aren't set. See: #7116
			if ( typeof value === "number" && isNaN( value ) || value == null ) {
				return;
			}

			// If a number was passed in, add 'px' to the (except for certain CSS properties)
			if ( typeof value === "number" && !jQuery.cssNumber[ origName ] ) {
				value += "px";
			}

			// If a hook was provided, use that value, otherwise just set the specified value
			if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value )) !== undefined ) {
				// Wrapped to prevent IE from throwing errors when 'invalid' values are provided
				// Fixes bug #5509
				try {
					style[ name ] = value;
				} catch(e) {}
			}

		} else {
			// If a hook was provided get the non-computed value from there
			if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
				return ret;
			}

			// Otherwise just get the value from the style object
			return style[ name ];
		}
	},

	css: function( elem, name, extra ) {
		// Make sure that we're working with the right name
		var ret, origName = jQuery.camelCase( name ),
			hooks = jQuery.cssHooks[ origName ];

		name = jQuery.cssProps[ origName ] || origName;

		// If a hook was provided get the computed value from there
		if ( hooks && "get" in hooks && (ret = hooks.get( elem, true, extra )) !== undefined ) {
			return ret;

		// Otherwise, if a way to get the computed value exists, use that
		} else if ( curCSS ) {
			return curCSS( elem, name, origName );
		}
	},

	// A method for quickly swapping in/out CSS properties to get correct calculations
	swap: function( elem, options, callback ) {
		var old = {};

		// Remember the old values, and insert the new ones
		for ( var name in options ) {
			old[ name ] = elem.style[ name ];
			elem.style[ name ] = options[ name ];
		}

		callback.call( elem );

		// Revert the old values
		for ( name in options ) {
			elem.style[ name ] = old[ name ];
		}
	},

	camelCase: function( string ) {
		return string.replace( rdashAlpha, fcamelCase );
	}
});

// DEPRECATED, Use jQuery.css() instead
jQuery.curCSS = jQuery.css;

jQuery.each(["height", "width"], function( i, name ) {
	jQuery.cssHooks[ name ] = {
		get: function( elem, computed, extra ) {
			var val;

			if ( computed ) {
				if ( elem.offsetWidth !== 0 ) {
					val = getWH( elem, name, extra );

				} else {
					jQuery.swap( elem, cssShow, function() {
						val = getWH( elem, name, extra );
					});
				}

				if ( val <= 0 ) {
					val = curCSS( elem, name, name );

					if ( val === "0px" && currentStyle ) {
						val = currentStyle( elem, name, name );
					}

					if ( val != null ) {
						// Should return "auto" instead of 0, use 0 for
						// temporary backwards-compat
						return val === "" || val === "auto" ? "0px" : val;
					}
				}

				if ( val < 0 || val == null ) {
					val = elem.style[ name ];

					// Should return "auto" instead of 0, use 0 for
					// temporary backwards-compat
					return val === "" || val === "auto" ? "0px" : val;
				}

				return typeof val === "string" ? val : val + "px";
			}
		},

		set: function( elem, value ) {
			if ( rnumpx.test( value ) ) {
				// ignore negative width and height values #1599
				value = parseFloat(value);

				if ( value >= 0 ) {
					return value + "px";
				}

			} else {
				return value;
			}
		}
	};
});

if ( !jQuery.support.opacity ) {
	jQuery.cssHooks.opacity = {
		get: function( elem, computed ) {
			// IE uses filters for opacity
			return ropacity.test((computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "") ?
				(parseFloat(RegExp.$1) / 100) + "" :
				computed ? "1" : "";
		},

		set: function( elem, value ) {
			var style = elem.style;

			// IE has trouble with opacity if it does not have layout
			// Force it by setting the zoom level
			style.zoom = 1;

			// Set the alpha filter to set the opacity
			var opacity = jQuery.isNaN(value) ?
				"" :
				"alpha(opacity=" + value * 100 + ")",
				filter = style.filter || "";

			style.filter = ralpha.test(filter) ?
				filter.replace(ralpha, opacity) :
				style.filter + ' ' + opacity;
		}
	};
}

if ( document.defaultView && document.defaultView.getComputedStyle ) {
	getComputedStyle = function( elem, newName, name ) {
		var ret, defaultView, computedStyle;

		name = name.replace( rupper, "-$1" ).toLowerCase();

		if ( !(defaultView = elem.ownerDocument.defaultView) ) {
			return undefined;
		}

		if ( (computedStyle = defaultView.getComputedStyle( elem, null )) ) {
			ret = computedStyle.getPropertyValue( name );
			if ( ret === "" && !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) {
				ret = jQuery.style( elem, name );
			}
		}

		return ret;
	};
}

if ( document.documentElement.currentStyle ) {
	currentStyle = function( elem, name ) {
		var left, rsLeft,
			ret = elem.currentStyle && elem.currentStyle[ name ],
			style = elem.style;

		// From the awesome hack by Dean Edwards
		// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291

		// If we're not dealing with a regular pixel number
		// but a number that has a weird ending, we need to convert it to pixels
		if ( !rnumpx.test( ret ) && rnum.test( ret ) ) {
			// Remember the original values
			left = style.left;
			rsLeft = elem.runtimeStyle.left;

			// Put in the new values to get a computed value out
			elem.runtimeStyle.left = elem.currentStyle.left;
			style.left = name === "fontSize" ? "1em" : (ret || 0);
			ret = style.pixelLeft + "px";

			// Revert the changed values
			style.left = left;
			elem.runtimeStyle.left = rsLeft;
		}

		return ret === "" ? "auto" : ret;
	};
}

curCSS = getComputedStyle || currentStyle;

function getWH( elem, name, extra ) {
	var which = name === "width" ? cssWidth : cssHeight,
		val = name === "width" ? elem.offsetWidth : elem.offsetHeight;

	if ( extra === "border" ) {
		return val;
	}

	jQuery.each( which, function() {
		if ( !extra ) {
			val -= parseFloat(jQuery.css( elem, "padding" + this )) || 0;
		}

		if ( extra === "margin" ) {
			val += parseFloat(jQuery.css( elem, "margin" + this )) || 0;

		} else {
			val -= parseFloat(jQuery.css( elem, "border" + this + "Width" )) || 0;
		}
	});

	return val;
}

if ( jQuery.expr && jQuery.expr.filters ) {
	jQuery.expr.filters.hidden = function( elem ) {
		var width = elem.offsetWidth,
			height = elem.offsetHeight;

		return (width === 0 && height === 0) || (!jQuery.support.reliableHiddenOffsets && (elem.style.display || jQuery.css( elem, "display" )) === "none");
	};

	jQuery.expr.filters.visible = function( elem ) {
		return !jQuery.expr.filters.hidden( elem );
	};
}

})( jQuery );
<|endoftext|>


<commit_before>#!/usr/bin/env node

import path from "path";
import fs from "fs";
import meow from "meow";
import resolveFrom from "resolve-from";
import standalone from "./standalone";

const cli = meow(
  `
    Usage: webfont [input] [options]

    Input: File(s) or glob(s).

        If an input argument is wrapped in quotation marks, it will be passed to "fast-glob"
        for cross-platform glob support.

    Options:

        --config

            Path to a specific configuration file (JSON, YAML, or CommonJS)
            or the name of a module in \`node_modules\` that points to one.
            If no \`--config\` argument is provided, webfont will search for
            configuration  files in the following places, in this order:
               - a \`webfont\` property in \`package.json\`
               - a \`.webfontrc\` file (with or without filename extension:
                   \`.json\`, \`.yaml\`, and \`.js\` are available)
               - a \`webfont.config.js\` file exporting a JS object
            The search will begin in the working directory and move up the
            directory tree until a configuration file is found.

        -f, --font-name

            The font family name you want, default: "webfont".

        -h, --help

            Output usage information.

        -v, --version

            Output the version number.

        -r, --formats

            Only this formats generate.

        -d, --dest

            Destination for generated fonts.

        -t, --template

            Type of template ('css', 'scss', 'styl') or path to custom template.

        -s, --dest-template

            Destination for generated template. If not passed used \`dest\` argument value.

        -c, --template-class-name

            Class name in css template.

        -p, --template-font-path

            Font path in css template.

        -n, --template-font-name

            Font name in css template.

        --no-sort

            Keeps the files in the same order of entry

        --verbose

            Tell me everything!.

    For "svgicons2svgfont":

        --font-id

            The font id you want, default as "--font-name".

        --font-style

            The font style you want.

        --font-weight

            The font weight you want.

        --fixed-width

            Creates a monospace font of the width of the largest input icon.

        --center-horizontally

            Calculate the bounds of a glyph and center it horizontally.

        --normalize

            Normalize icons by scaling them to the height of the highest icon.

        --font-height

            The outputted font height [MAX(icons.height)].

        --round

            Setup the SVG path rounding [10e12].

        --descent

            The font descent [0].

        --ascent

            The font ascent [height - descent].

        --start-unicode

            The start unicode codepoint for files without prefix [0xEA01].

        --prepend-unicode

            Prefix files with their automatically allocated unicode codepoint.

        --metadata

            Content of the metadata tag.
`,
  {
    autoHelp: false,
    autoVersion: false,
    flags: {
      ascent: {
        type: "string"
      },
      "center-horizontally": {
        type: "boolean"
      },
      config: {
        default: null
      },
      descent: {
        type: "string"
      },
      dest: {
        alias: "d",
        default: process.cwd(),
        type: "string"
      },
      "dest-template": {
        alias: "s",
        type: "string"
      },
      "fixed-width": {
        type: "boolean"
      },
      "font-height": {
        type: "string"
      },
      "font-id": {
        type: "string"
      },
      "font-name": {
        alias: "u",
        type: "string"
      },
      "font-style": {
        type: "string"
      },
      "font-weight": {
        type: "string"
      },
      formats: {
        alias: "f"
      },
      help: {
        alias: "h",
        type: "boolean"
      },
      normalize: {
        type: "boolean"
      },
      "prepend-unicode": {
        type: "boolean"
      },
      round: {
        type: "string"
      },
      sort: {
        default: true,
        type: "boolean"
      },
      "start-unicode": {
        type: "string"
      },
      template: {
        alias: "t",
        type: "string"
      },
      "template-class-name": {
        alias: "c",
        type: "string"
      },
      "template-font-name": {
        alias: "n",
        type: "string"
      },
      "template-font-path": {
        alias: "p",
        type: "string"
      },
      verbose: {
        default: false,
        type: "boolean"
      },
      version: {
        alias: "v",
        type: "boolean"
      }
    }
  }
);

const optionsBase = {};

if (cli.flags.config) {
  // Should check these possibilities:
  //   a. name of a node_module
  //   b. absolute path
  //   c. relative path relative to `process.cwd()`.
  // If none of the above work, we'll try a relative path starting
  // in `process.cwd()`.
  optionsBase.configFile =
    resolveFrom(process.cwd(), cli.flags.config) ||
    path.join(process.cwd(), cli.flags.config);
}

if (cli.flags.fontName) {
  optionsBase.fontName = cli.flags.fontName;
}

if (cli.flags.formats) {
  optionsBase.formats = cli.flags.formats;
}

if (cli.flags.dest) {
  optionsBase.dest = cli.flags.dest;
}

if (cli.flags.template) {
  optionsBase.template = cli.flags.template;
}

if (cli.flags.templateClassName) {
  optionsBase.templateClassName = cli.flags.templateClassName;
}

if (cli.flags.templateFontPath) {
  optionsBase.templateFontPath = cli.flags.templateFontPath;
}

if (cli.flags.templateFontName) {
  optionsBase.templateFontName = cli.flags.templateFontName;
}

if (cli.flags.destTemplate) {
  optionsBase.destTemplate = cli.flags.destTemplate;
}

if (cli.flags.verbose) {
  optionsBase.verbose = cli.flags.verbose;
}

if (cli.flags.fontId) {
  optionsBase.fontId = cli.flags.fontId;
}

if (cli.flags.fontStyle) {
  optionsBase.fontStyle = cli.flags.fontStyle;
}

if (cli.flags.fontWeight) {
  optionsBase.fontWeight = cli.flags.fontWeight;
}

if (cli.flags.fixedWidth) {
  optionsBase.fixedWidth = cli.flags.fixedWidth;
}

if (cli.flags.centerHorizontally) {
  optionsBase.centerHorizontally = cli.flags.centerHorizontally;
}

if (cli.flags.normalize) {
  optionsBase.normalize = cli.flags.normalize;
}

if (cli.flags.fontHeight) {
  optionsBase.fontHeight = cli.flags.fontHeight;
}

if (cli.flags.round) {
  optionsBase.round = cli.flags.round;
}

if (cli.flags.descent) {
  optionsBase.descent = cli.flags.descent;
}

if (cli.flags.ascent) {
  optionsBase.ascent = cli.flags.ascent;
}

if (cli.flags.startUnicode) {
  optionsBase.startUnicode = cli.flags.startUnicode;
}

if (cli.flags.prependUnicode) {
  optionsBase.prependUnicode = cli.flags.prependUnicode;
}

if (cli.flags.metadata) {
  optionsBase.metadata = cli.flags.metadata;
}

if (cli.flags.sort === false) {
  optionsBase.sort = cli.flags.sort;
}

if (cli.flags.help || cli.flags.h) {
  cli.showHelp();
}

if (cli.flags.version || cli.flags.v) {
  cli.showVersion();
}

Promise.resolve()
  .then(() => {
    const options = Object.assign({}, optionsBase, {
      files: cli.input
    });

    if (options.files.length === 0) {
      cli.showHelp();
    }

    return standalone(options).then(result => {
      result.config = Object.assign(
        {},
        {
          dest: options.dest,
          destTemplate: options.destTemplate
        },
        result.config
      );

      return result;
    });
  })
  .then(result => {
    const { fontName, dest } = result.config;

    let destTemplate = null;

    if (result.template) {
      ({ destTemplate } = result.config);

      if (!destTemplate) {
        destTemplate = dest;
      }

      if (result.usedBuildInTemplate) {
        destTemplate = path.join(
          destTemplate,
          `${result.config.fontName}.${result.config.template}`
        );
      } else {
        destTemplate = path.join(
          destTemplate,
          path.basename(result.config.template).replace(".njk", "")
        );
      }
    }

    return Promise.resolve()
      .then(() =>
        Promise.all(
          Object.keys(result).map(type => {
            if (
              type === "config" ||
              type === "usedBuildInTemplate" ||
              type === "glyphsData"
            ) {
              return null;
            }

            const content = result[type];
            // eslint-disable-next-line init-declarations
            let file;

            if (type !== "template") {
              file = path.resolve(path.join(dest, `${fontName}.${type}`));
            } else {
              file = path.resolve(destTemplate);
            }

            return fs.writeFile(file, content, () => {
              Function.prototype();
            });
          })
        )
      )
      .then(() => Promise.resolve(result));
  })
  .catch(error => {
    // eslint-disable-next-line no-console
    console.log(error.stack);

    const exitCode = typeof error.code === "number" ? error.code : 1;

    process.exit(exitCode);
  });
<commit_msg>style(cli): remove unneeded eslint-disable-next-line for init-declarations<commit_after>#!/usr/bin/env node

import path from "path";
import fs from "fs";
import meow from "meow";
import resolveFrom from "resolve-from";
import standalone from "./standalone";

const cli = meow(
  `
    Usage: webfont [input] [options]

    Input: File(s) or glob(s).

        If an input argument is wrapped in quotation marks, it will be passed to "fast-glob"
        for cross-platform glob support.

    Options:

        --config

            Path to a specific configuration file (JSON, YAML, or CommonJS)
            or the name of a module in \`node_modules\` that points to one.
            If no \`--config\` argument is provided, webfont will search for
            configuration  files in the following places, in this order:
               - a \`webfont\` property in \`package.json\`
               - a \`.webfontrc\` file (with or without filename extension:
                   \`.json\`, \`.yaml\`, and \`.js\` are available)
               - a \`webfont.config.js\` file exporting a JS object
            The search will begin in the working directory and move up the
            directory tree until a configuration file is found.

        -f, --font-name

            The font family name you want, default: "webfont".

        -h, --help

            Output usage information.

        -v, --version

            Output the version number.

        -r, --formats

            Only this formats generate.

        -d, --dest

            Destination for generated fonts.

        -t, --template

            Type of template ('css', 'scss', 'styl') or path to custom template.

        -s, --dest-template

            Destination for generated template. If not passed used \`dest\` argument value.

        -c, --template-class-name

            Class name in css template.

        -p, --template-font-path

            Font path in css template.

        -n, --template-font-name

            Font name in css template.

        --no-sort

            Keeps the files in the same order of entry

        --verbose

            Tell me everything!.

    For "svgicons2svgfont":

        --font-id

            The font id you want, default as "--font-name".

        --font-style

            The font style you want.

        --font-weight

            The font weight you want.

        --fixed-width

            Creates a monospace font of the width of the largest input icon.

        --center-horizontally

            Calculate the bounds of a glyph and center it horizontally.

        --normalize

            Normalize icons by scaling them to the height of the highest icon.

        --font-height

            The outputted font height [MAX(icons.height)].

        --round

            Setup the SVG path rounding [10e12].

        --descent

            The font descent [0].

        --ascent

            The font ascent [height - descent].

        --start-unicode

            The start unicode codepoint for files without prefix [0xEA01].

        --prepend-unicode

            Prefix files with their automatically allocated unicode codepoint.

        --metadata

            Content of the metadata tag.
`,
  {
    autoHelp: false,
    autoVersion: false,
    flags: {
      ascent: {
        type: "string"
      },
      "center-horizontally": {
        type: "boolean"
      },
      config: {
        default: null
      },
      descent: {
        type: "string"
      },
      dest: {
        alias: "d",
        default: process.cwd(),
        type: "string"
      },
      "dest-template": {
        alias: "s",
        type: "string"
      },
      "fixed-width": {
        type: "boolean"
      },
      "font-height": {
        type: "string"
      },
      "font-id": {
        type: "string"
      },
      "font-name": {
        alias: "u",
        type: "string"
      },
      "font-style": {
        type: "string"
      },
      "font-weight": {
        type: "string"
      },
      formats: {
        alias: "f"
      },
      help: {
        alias: "h",
        type: "boolean"
      },
      normalize: {
        type: "boolean"
      },
      "prepend-unicode": {
        type: "boolean"
      },
      round: {
        type: "string"
      },
      sort: {
        default: true,
        type: "boolean"
      },
      "start-unicode": {
        type: "string"
      },
      template: {
        alias: "t",
        type: "string"
      },
      "template-class-name": {
        alias: "c",
        type: "string"
      },
      "template-font-name": {
        alias: "n",
        type: "string"
      },
      "template-font-path": {
        alias: "p",
        type: "string"
      },
      verbose: {
        default: false,
        type: "boolean"
      },
      version: {
        alias: "v",
        type: "boolean"
      }
    }
  }
);

const optionsBase = {};

if (cli.flags.config) {
  // Should check these possibilities:
  //   a. name of a node_module
  //   b. absolute path
  //   c. relative path relative to `process.cwd()`.
  // If none of the above work, we'll try a relative path starting
  // in `process.cwd()`.
  optionsBase.configFile =
    resolveFrom(process.cwd(), cli.flags.config) ||
    path.join(process.cwd(), cli.flags.config);
}

if (cli.flags.fontName) {
  optionsBase.fontName = cli.flags.fontName;
}

if (cli.flags.formats) {
  optionsBase.formats = cli.flags.formats;
}

if (cli.flags.dest) {
  optionsBase.dest = cli.flags.dest;
}

if (cli.flags.template) {
  optionsBase.template = cli.flags.template;
}

if (cli.flags.templateClassName) {
  optionsBase.templateClassName = cli.flags.templateClassName;
}

if (cli.flags.templateFontPath) {
  optionsBase.templateFontPath = cli.flags.templateFontPath;
}

if (cli.flags.templateFontName) {
  optionsBase.templateFontName = cli.flags.templateFontName;
}

if (cli.flags.destTemplate) {
  optionsBase.destTemplate = cli.flags.destTemplate;
}

if (cli.flags.verbose) {
  optionsBase.verbose = cli.flags.verbose;
}

if (cli.flags.fontId) {
  optionsBase.fontId = cli.flags.fontId;
}

if (cli.flags.fontStyle) {
  optionsBase.fontStyle = cli.flags.fontStyle;
}

if (cli.flags.fontWeight) {
  optionsBase.fontWeight = cli.flags.fontWeight;
}

if (cli.flags.fixedWidth) {
  optionsBase.fixedWidth = cli.flags.fixedWidth;
}

if (cli.flags.centerHorizontally) {
  optionsBase.centerHorizontally = cli.flags.centerHorizontally;
}

if (cli.flags.normalize) {
  optionsBase.normalize = cli.flags.normalize;
}

if (cli.flags.fontHeight) {
  optionsBase.fontHeight = cli.flags.fontHeight;
}

if (cli.flags.round) {
  optionsBase.round = cli.flags.round;
}

if (cli.flags.descent) {
  optionsBase.descent = cli.flags.descent;
}

if (cli.flags.ascent) {
  optionsBase.ascent = cli.flags.ascent;
}

if (cli.flags.startUnicode) {
  optionsBase.startUnicode = cli.flags.startUnicode;
}

if (cli.flags.prependUnicode) {
  optionsBase.prependUnicode = cli.flags.prependUnicode;
}

if (cli.flags.metadata) {
  optionsBase.metadata = cli.flags.metadata;
}

if (cli.flags.sort === false) {
  optionsBase.sort = cli.flags.sort;
}

if (cli.flags.help || cli.flags.h) {
  cli.showHelp();
}

if (cli.flags.version || cli.flags.v) {
  cli.showVersion();
}

Promise.resolve()
  .then(() => {
    const options = Object.assign({}, optionsBase, {
      files: cli.input
    });

    if (options.files.length === 0) {
      cli.showHelp();
    }

    return standalone(options).then(result => {
      result.config = Object.assign(
        {},
        {
          dest: options.dest,
          destTemplate: options.destTemplate
        },
        result.config
      );

      return result;
    });
  })
  .then(result => {
    const { fontName, dest } = result.config;

    let destTemplate = null;

    if (result.template) {
      ({ destTemplate } = result.config);

      if (!destTemplate) {
        destTemplate = dest;
      }

      if (result.usedBuildInTemplate) {
        destTemplate = path.join(
          destTemplate,
          `${result.config.fontName}.${result.config.template}`
        );
      } else {
        destTemplate = path.join(
          destTemplate,
          path.basename(result.config.template).replace(".njk", "")
        );
      }
    }

    return Promise.resolve()
      .then(() =>
        Promise.all(
          Object.keys(result).map(type => {
            if (
              type === "config" ||
              type === "usedBuildInTemplate" ||
              type === "glyphsData"
            ) {
              return null;
            }

            const content = result[type];

            let file;

            if (type !== "template") {
              file = path.resolve(path.join(dest, `${fontName}.${type}`));
            } else {
              file = path.resolve(destTemplate);
            }

            return fs.writeFile(file, content, () => {
              Function.prototype();
            });
          })
        )
      )
      .then(() => Promise.resolve(result));
  })
  .catch(error => {
    // eslint-disable-next-line no-console
    console.log(error.stack);

    const exitCode = typeof error.code === "number" ? error.code : 1;

    process.exit(exitCode);
  });
<|endoftext|>


<commit_before>'use strict';

module.exports = function(grunt) {

  grunt.initConfig({
    json_merge: {
      options: {
        replacer: null,
        space: ''
      },
      tours: {
        files: {
          '.tmp/tours.json': ['tours/**/*.json']
        },
      }
    },
    clean: {
      dist: {
        src: ['dist/*']
      },
      tmp: {
        src: ['.tmp']
      }
    },
    concat: {
      tours: {
        options: {
          banner: 'var __tours = ',
          footer: ';',
        },
        files: {
          '.tmp/tours.js': ['.tmp/tours.json'],
        },
      },
      dist: {
        options: {
          banner: 'define([\'introjs\', \'jquery\', \'underscore\', \'moment\', \'polyglot\'], function (introjs, $, _, moment, P) {\n',
          footer: '});',
        },
        files: {
          'dist/tour.js': ['actions.js', '.tmp/tours.js', 'tour.js']
        }
      }
    },
    sass: {
      dist: {
        options: {
          style: 'compressed',
          sourcemap: 'none'
        },
        files: {
          'dist/tour.css': 'tour.scss'
        }
      }
    },
    autoprefixer: {
      single_file: {
        src: 'dist/tour.css'
      },
    }
  });

  grunt.loadNpmTasks('grunt-json-merge');
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-sass');
  grunt.loadNpmTasks('grunt-autoprefixer');

  grunt.registerTask('default', ['clean:dist', 'json_merge', 'concat', 'sass', 'autoprefixer']);

};
<commit_msg>unused sass flag<commit_after>'use strict';

module.exports = function(grunt) {

  grunt.initConfig({
    json_merge: {
      options: {
        replacer: null,
        space: ''
      },
      tours: {
        files: {
          '.tmp/tours.json': ['tours/**/*.json']
        },
      }
    },
    clean: {
      dist: {
        src: ['dist/*']
      },
      tmp: {
        src: ['.tmp']
      }
    },
    concat: {
      tours: {
        options: {
          banner: 'var __tours = ',
          footer: ';',
        },
        files: {
          '.tmp/tours.js': ['.tmp/tours.json'],
        },
      },
      dist: {
        options: {
          banner: 'define([\'introjs\', \'jquery\', \'underscore\', \'moment\', \'polyglot\'], function (introjs, $, _, moment, P) {\n',
          footer: '});',
        },
        files: {
          'dist/tour.js': ['actions.js', '.tmp/tours.js', 'tour.js']
        }
      }
    },
    sass: {
      dist: {
        options: {
          style: 'compressed'
        },
        files: {
          'dist/tour.css': 'tour.scss'
        }
      }
    },
    autoprefixer: {
      single_file: {
        src: 'dist/tour.css'
      },
    }
  });

  grunt.loadNpmTasks('grunt-json-merge');
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-sass');
  grunt.loadNpmTasks('grunt-autoprefixer');

  grunt.registerTask('default', ['clean:dist', 'json_merge', 'concat', 'sass', 'autoprefixer']);

};
<|endoftext|>