Example #1
0
jsFiles.forEach(function(filename) {
  assert(path.isAbsolute(filename));
});
Example #2
0
 browser: function(requirePath, opts) {
   opts = opts || {};
   opts.browser = true;
   requirePath = path.isAbsolute(requirePath) ? requirePath : path.join(baseDir, requirePath);
   addToApp(requirePath, opts);
 },
Example #3
0
const getDataLocation = (dataDir, projectLocation) => (
  dataDir && path.isAbsolute(dataDir)
    ? path.resolve(dataDir)
    : path.resolve(projectLocation, dataDir || 'data')
)
Example #4
0
 .filter(folder => !path.isAbsolute(folder))
Example #5
0
const checkIfResolveChangedRootFolder = (resolved, initial) => {
  return path.isAbsolute(resolved) &&
  path.isAbsolute(initial) &&
  !resolved.startsWith(initial)
}
Example #6
0
function resolve(filename) {
    if(path.isAbsolute(filename)) return filename;
    if(process.env.PWD) return path.resolve(process.env.PWD, filename);
    return path.resolve(filename);
}
        Report stylelint-disable comments that are not blocking a lint warning.
        If you provide the argument "error", the process will exit with code 2
        if needless disables are found.

      --version, -v

        Show the currently installed version of stylelint.
  `,
  pkg: "../package.json"
};

const cli /*: cliType*/ = meow(meowOptions, minimistOptions);

let formatter = cli.flags.formatter;
if (cli.flags.customFormatter) {
  const customFormatter = path.isAbsolute(cli.flags.customFormatter)
    ? cli.flags.customFormatter
    : path.join(process.cwd(), cli.flags.customFormatter);
  formatter = dynamicRequire(customFormatter);
}

const optionsBase /*: optionBaseType*/ = {
  formatter,
  configOverrides: {}
};

if (cli.flags.quiet) {
  optionsBase.configOverrides.quiet = cli.flags.quiet;
}

if (cli.flags.syntax) {
'use strict';
const _=require('lodash');
const fs=require('fs');
const path=require('path');
const pandoc=require('../services/pandoc');
const template=fs.readFileSync(__dirname+'/download.md','utf8');
const compiled=_.template(template,null,{variable: 'data', imports: {_: _}});
const send=require('koa-send');
const download=require('config').get('download');
let cwd=download.cwd;
let dest=download.dest;
if(!path.isAbsolute(download.cwd)){
  cwd=path.join(process.cwd(),download.cwd);
}
if(!path.isAbsolute(download.dest)){
  dest=path.join(process.cwd(),download.dest);
}
const binary=['docx','epub'];
const $=module.exports={};

$.getToken=function *getToken(next){
  if(!this.query.token){
    this.throw('no token found');
  }
  else{
    this.request.headers.authorization='bearer '+this.query.token;
    yield next;
  }
};

$.getUnits=function *getUnits(next){
Example #9
0
        .catch(() => {
          return os.release()
        })
      }

      return os.release()

    })
  },

  // attention:
  // when passing relative path to NPM post install hook, the current working
  // directory is set to the `node_modules/cypress` folder
  // the user is probably passing relative path with respect to root package folder
  formAbsolutePath (filename) {
    if (path.isAbsolute(filename)) {
      return filename
    }

    return path.join(process.cwd(), '..', '..', filename)
  },

  getEnv (varName) {
    const envVar = process.env[varName]
    const configVar = process.env[`npm_config_${varName}`]
    const packageConfigVar = process.env[`npm_package_config_${varName}`]

    if (envVar) {
      debug(`Using ${varName} from environment variable`)

      return envVar
Example #10
0
 getModulePath(from: Path, moduleName: string) {
   if (moduleName[0] !== '.' || path.isAbsolute(moduleName)) {
     return moduleName;
   }
   return path.normalize(path.dirname(from) + '/' + moduleName);
 }
Example #11
0
var _ME = function(argv, force) {
    if (_OPTIONS && !force) return _OPTIONS;

    if (_OPTIONS) {
        // 清空对象,但保留句柄。
        for (var i in _OPTIONS) delete _OPTIONS[i];
    }
    else {
        _OPTIONS = {};
    }

    // 如果未提供参数,则使用命令行参数。
    if (!argv) {
        argv = minimist(process.argv.slice(2));
        _OPTIONS.isCLI = true;
    }
    else {
        _OPTIONS.isCLI = false;
        _OPTIONS.callback = argv.callback;
        _OPTIONS.ceased = false;
    }

    // -------------------------------------------------------------------------
    // 排他性、指示独立任务的命令行参数处理。
    // API 模式下忽略此环节。

    if (_OPTIONS.isCLI) {

        if (argv.help || argv.h) {
            help();
            process.exit(0);
        }

        if (argv.version || argv.v) {
            yuancon.print
                .line('Moles Packer')
                .em(require('../package').version)
                .br()
                ;
            process.exit(0);
        }

    }

    // -------------------------------------------------------------------------
    // 非耦合参数处理。

    // 由 run.js 间接调用的时候,需要指定基础目录。
    _OPTIONS.base = path.resolve(argv.base || '.');

    // --common-modules
    // default react,react-native
    if (argv['common-modules']) {
        _OPTIONS.commonModules = argv['common-modules'].split(',');
    }

    // --dev
    // default FALSE
    _OPTIONS.dev = !!argv.dev;

    // --execOnRequired
    // default FALSE
    _OPTIONS.execOnRequired = !!argv['exec-on-required'];

    // 默认以当前目录作为待编译项目根目录。
    _OPTIONS.input = path.resolve(_OPTIONS.base,
        (typeof argv.input == 'string') ? argv.input : '.');

	// 尝试获取待编译项目的 react-native 版本。

    // --minify
    // default FALSE
    _OPTIONS.minify = !!argv.minify;

    // 默认以 [当前目录]/build 作为输出根目录。
    _OPTIONS.output = path.resolve(_OPTIONS.base,
        typeof argv.output == 'string' ? argv.output : './build');
    yuancon.fs.mkdirp(_OPTIONS.output);
    _OPTIONS.metaOutput = path.join(_OPTIONS.output, 'moles.meta.json');

    // --platform
    // default 'ios'
    _OPTIONS.platform = yuan.ifEmpty(argv['platform'], 'cross');
    if (['cross', 'ios', 'android'].indexOf(_OPTIONS.platform) < 0) {
        _exit(`Invalid platform "${_OPTIONS.platform}".`);
    }

    // --single
    // default FALSE
    _OPTIONS.single = !!argv.single;

    // --standalone
    // default FALSE
    _OPTIONS.standalone = !!argv.standalone;

    // --verbose
    // default FALSE
    _OPTIONS.verbose = !!argv.verbose;

    // -------------------------------------------------------------------------
    // 耦合参数处理。

    // --entry
    // 默认以 [项目根目录]/index.js 作为入口文件。
    _OPTIONS.entry = path.resolve(_OPTIONS.input,
        typeof argv.entry == 'string' ? argv.entry : CONFIG.path.entry);

    if (!fs.existsSync(_OPTIONS.entry)) {
        // 自动检测入口文 件。

        let pathname = path.join(_OPTIONS.input, `index.${_OPTIONS.platform}.js`);
        if (fs.existsSync(pathname)) {
            _OPTIONS.entry = pathname;
        }
    }
    if (!fs.existsSync(_OPTIONS.entry)) {
        _exit(`Entry file "${_OPTIONS.entry}" not exists or not accessible.`);
    }

    // --common
    if (argv['common-input']) {
        let realpath = _find_real_path(argv['common-input'], 'common directory');

        // STEP 0. By default, Moles Packer will create a sub directory named with
        // CONFIG.path.common in the output directory. So, supposing that the output
        // directory is used as --common-input next time, Moles Packer will guess
        // that the sub directory named with CONFIG.path.common is the real directory
        // in which common meta file and common bundle file(s) stored.
        let realpathGuessed = path.join(realpath, CONFIG.path.common);
        if (fs.existsSync(realpathGuessed)) {
            realpath = realpathGuessed;
        }

        // STEP 1. Firstly, we should find the meta file.

        let commonMetas;
        commonMetas = [ path.join(realpath, CONFIG.path.commonMeta[_OPTIONS.platform]) ];

        // If you wanna create os-specified bundle(s) and corresponding meta
        // file is not found in the directory specified by --common option,
        // Moles Packer will try the cross-platform one as a replacement if
        // it exists.
        if (_OPTIONS.platform != 'cross') {
            commonMetas.push(path.join(realpath, CONFIG.path.commonMeta['cross']));
        }
        _OPTIONS.commonMeta = _check_exist(commonMetas, 'meta file');

        // STEP 2. Secondly, while option --standalone set, we should find the
        // corresponding common bundle(s).
        // If --platform not specified, both ios and android common bundle are
        // required.

        if (_OPTIONS.standalone) {
            let commonBundle = {};
            if (_OPTIONS.platform == 'cross') {
                for (let platform in CONFIG.path.commonBundle) {
                    commonBundle[platform] = path.join(realpath, CONFIG.path.commonBundle[platform]);
                }
            }
            else {
                commonBundle[_OPTIONS.platform] = path.join(realpath, CONFIG.path.commonBundle[_OPTIONS.platform]);
            }
            _OPTIONS.commonBundle = _check_exist(commonBundle, 'common bundle(s)', true);
        }
    }

    // --common-output
    if (argv['common-output']) {
        if (path.isAbsolute(argv['common-output'])) {
            _OPTIONS.commonOutput = argv['common-output'];
        }
        else if (argv['common-output'].charAt(0) == '.') {
            _OPTIONS.commonOutput = path.resolve(argv['common-output']);
        }
        else {
            _OPTIONS.commonOutput = path.join(_OPTIONS.output , argv['common-output']);
        }
    }
    else {
        _OPTIONS.commonOutput = path.join(_OPTIONS.output, CONFIG.path.common);
    }

    // --bundle
    // default false
    if (argv.bundle) {
        _OPTIONS.bundle = !!argv.bundle;
    }
	else if (_OPTIONS.standalone) {
		_OPTIONS.bundle = true;
	}

    // ---------------------------


    if (_OPTIONS.verbose) {
        let rows = [];
        let keys = Object.keys(_OPTIONS).sort();
        let reducePathname = (/*String*/ value) => {
            if (value.startsWith(_OPTIONS.base)) {
                value = colors.gray('BASE') + path.sep + path.relative(_OPTIONS.base, value);
            }
            return value;
        };
        keys.forEach((key) => {
            let value = _OPTIONS[key];
            if (typeof value == 'string') {
                if (key != 'base') value = reducePathname(value);
                value = colors.italic(`"${value}"`);
            }
            else if (typeof value == 'boolean') {
                value = colors.italic.green(value);
            }
            else if (value instanceof Array) {
                let rows = [];
                value.forEach((item) => {
                    rows.push(colors.italic(`"${value}"`));
                });
                value = rows.join(os.EOL);
            }
            else if (typeof value == 'function') {
                value = 'Function() [ ... ]';
            }
            else if (typeof value == 'object') {
                for (let subkey in value) {
                    let subvalue = reducePathname(value[subkey]);
                    rows.push({
                        name: key + '.' + subkey,
                        value: `"${colors.italic(subvalue)}"`
                    });
                }
                return;
            }

            rows.push({ name: key, value: value });
        });
        yuancon.print.em(`[${CONFIG.title}] -- options parsed --`).br();
        yuancon.print.table(rows);
    }

    return _OPTIONS;
};
Example #12
0
function parseOpts(options, resolvedTarget) {
    // Backwards-compatibility: Allow a single string argument
    if (typeof options == 'string') options = [options];

    var ret = {
        buildType: 'debug',
        buildMethod: process.env['ANDROID_BUILD'] || 'gradle',
        arch: null,
        extraArgs: []
    };

    var multiValueArgs = {
      'versionCode': true,
      'minSdkVersion': true,
      'gradleArg': true,
      'keystore' : true,
      'alias' : true,
      'password' : true,
      'storePassword' : true,
      'keystoreType' : true,
      'buildConfig' : true
    };
    var packageArgs = {};
    var buildConfig;
    // Iterate through command line options
    for (var i=0; options && (i < options.length); ++i) {
        if (/^--/.exec(options[i])) {
            var keyValue = options[i].substring(2).split('=');
            var flagName = keyValue.shift();
            var flagValue = keyValue.join('=');
            if (multiValueArgs[flagName] && !flagValue) {
                flagValue = options[i + 1];
                ++i;
            }
            switch(flagName) {
                case 'debug':
                case 'release':
                    ret.buildType = flagName;
                    break;
                case 'ant':
                case 'gradle':
                    ret.buildMethod = flagName;
                    break;
                case 'device':
                case 'emulator':
                    // Don't need to do anything special to when building for device vs emulator.
                    // iOS uses this flag to switch on architecture.
                    break;
                case 'prepenv' :
                    ret.prepEnv = true;
                    break;
                case 'nobuild' :
                    ret.buildMethod = 'none';
                    break;
                case 'versionCode':
                    ret.extraArgs.push('-PcdvVersionCode=' + flagValue);
                    break;
                case 'minSdkVersion':
                    ret.extraArgs.push('-PcdvMinSdkVersion=' + flagValue);
                    break;
                case 'gradleArg':
                    ret.extraArgs.push(flagValue);
                    break;
                case 'keystore':
                    packageArgs.keystore = path.relative(ROOT, path.resolve(flagValue));
                    break;
                case 'alias':
                case 'storePassword':
                case 'password':
                case 'keystoreType':
                    packageArgs[flagName] = flagValue;
                    break;
                case 'buildConfig':
                    buildConfig = flagValue;
                    break;
                default :
                    console.warn('Build option --\'' + flagName + '\' not recognized (ignoring).');
            }
        } else {
            console.warn('Build option \'' + options[i] + '\' not recognized (ignoring).');
        }
    }

    // If some values are not specified as command line arguments - use build config to supplement them.
    // Command line arguemnts have precedence over build config.
    if (buildConfig) {
        if (!fs.existsSync(buildConfig)) {
            throw new Error('Specified build config file does not exist: ' + buildConfig);
        }
        console.log('Reading build config file: '+ path.resolve(buildConfig));
        var config = JSON.parse(fs.readFileSync(buildConfig, 'utf8'));
        if (config.android && config.android[ret.buildType]) {
            var androidInfo = config.android[ret.buildType];
            if(androidInfo.keystore && !packageArgs.keystore) {
                if(path.isAbsolute(androidInfo.keystore)) {
                    packageArgs.keystore = androidInfo.keystore;
                } else {
                    packageArgs.keystore = path.relative(ROOT, path.join(path.dirname(buildConfig), androidInfo.keystore));
                }
            }

            ['alias', 'storePassword', 'password','keystoreType'].forEach(function (key){
                packageArgs[key] = packageArgs[key] || androidInfo[key];
            });
        }
    }
    if (packageArgs.keystore && packageArgs.alias) {
        ret.packageInfo = new PackageInfo(packageArgs.keystore, packageArgs.alias, packageArgs.storePassword,
            packageArgs.password, packageArgs.keystoreType);
    }

    if(!ret.packageInfo) {
        if(Object.keys(packageArgs).length > 0) {
            console.warn('\'keystore\' and \'alias\' need to be specified to generate a signed archive.');
        }
    }
    ret.arch = resolvedTarget && resolvedTarget.arch;

    return ret;
}
Example #13
0
function makeConfig (argv) {
  var config = {};

  //We don't need to load a config if the user is *generating* a config.
  var CMD_REQUIRES_CONFIG = !/genConfig/.test(argv['_'][0]);

  config.args = argv;

  // BACKSTOP MODULE PATH
  config.backstop = path.join(__dirname, '../..'); // backstop module
  config.customBackstop = process.cwd(); // running instance

  // Legacy mode, if the cwd is the backstop module
  if (config.backstop === config.customBackstop) {
    config.customBackstop = path.join(__dirname, '../../../..');
    console.log('BackstopJS is running in legacy mode.');
  }

  // BACKSTOP CONFIG PATH
  var configPathArg = argv.backstopConfigFilePath || argv.configPath || argv.config || null;
  if (configPathArg) {
    if (path.isAbsolute(configPathArg)) {
      config.backstopConfigFileName = configPathArg;
    } else {
      config.backstopConfigFileName = path.join(config.customBackstop, configPathArg);
    }
  } else {
    config.backstopConfigFileName = path.join(config.customBackstop, 'backstop.json');
  }

  console.log('\nBackstopJS CWD: ', config.customBackstop);

  // LOAD CONFIG
  var userConfig = {};
  if (CMD_REQUIRES_CONFIG && config.backstopConfigFileName) {
    try {
      console.log('BackstopJS loading config: ', config.backstopConfigFileName, '\n');
      userConfig = require(config.backstopConfigFileName);
    } catch (e) {
      console.error('Error ' + e);
      process.exit(1);
    }
  }

  // BITMAPS PATHS -- note: this path is overwritten if config files exist.  see below.
  config.bitmaps_reference = path.join(config.customBackstop, 'backstop_data', 'bitmaps_reference');
  config.bitmaps_test = path.join(config.customBackstop, 'backstop_data', 'bitmaps_test');

  // Continuous Integration (CI) report
  config.ci_report = path.join(config.customBackstop, 'backstop_data', 'ci_report');
  config.ci = {
    format: 'junit',
    testReportFileName: 'xunit',
    testSuiteName: 'BackstopJS'
  };

  // HTML Report
  config.html_report = path.join(config.customBackstop, 'backstop_data', 'html_report');
  config.openReport = true;
  if ('openReport' in userConfig) {
    config.openReport = userConfig.openReport;
  }

  // COMPARE PATHS -- note: compareConfigFileName is overwritten if config files exist.  see below.
  config.comparePath = path.join(config.backstop, 'compare');
  config.tempCompareConfigFileName = temp.path({suffix: '.json'});

  // CAPTURE CONFIG PATHS
  config.captureConfigFileName = path.join(config.backstop, 'capture', 'config.json');
  config.captureConfigFileNameDefault = path.join(config.backstop, 'capture', 'config.default.json');

  // SCRIPTS PATHS -- note: scripts is overwritten if config file exists.
  config.casper_scripts = path.join(config.customBackstop, 'backstop_data', 'casper_scripts');
  config.casper_scripts_default = path.join(config.backstop, 'capture', 'casper_scripts');

  config.casperFlags = userConfig.casperFlags || null;
  config.engine = userConfig.engine || null;
  config.report = userConfig.report || [ 'browser' ];
  config.ciReport = userConfig.ci ? {
    format: userConfig.ci.format || config.ci.format,
    testReportFileName: userConfig.ci.testReportFileName || config.ci.testReportFileName,
    testSuiteName: userConfig.ci.testSuiteName || config.ci.testSuiteName
  } : config.ci;

  // overwrite default filepaths if config files exist
  if (userConfig.paths) {
    config.bitmaps_reference = userConfig.paths.bitmaps_reference || config.bitmaps_reference;
    config.bitmaps_test = userConfig.paths.bitmaps_test || config.bitmaps_test;
    config.html_report = userConfig.paths.html_report || config.html_report;
    config.casper_scripts = userConfig.paths.casper_scripts || config.casper_scripts;
    config.ci_report = userConfig.paths.ci_report || config.ci_report;
  }

  config.compareConfigFileName = path.join(config.html_report, 'config.js');
  config.compareReportURL = path.join(config.html_report, 'index.html');

  config.defaultMisMatchThreshold = 0.1;
  config.debug = userConfig.debug || false;

  return config;
}
Example #14
0
excludes.forEach(function(exclude) {
  assert(path.isAbsolute(exclude));
  fs.statSync(exclude);
});
Example #15
0
 patternList.concat(excludedPatternList).forEach(pattern => {
     if (path.isAbsolute(pattern) || pattern.includes("..")) {
         throw new Error(`Invalid override pattern (expected relative path not containing '..'): ${pattern}`);
     }
 });
'use strict';

/* eslint
  comma-dangle: [1, always-multiline],
  prefer-object-spread/prefer-object-spread: 0,
  nuclide-internal/no-commonjs: 0,
  */

const assert = require('assert');
const Module = require('module');
const path = require('path');

const _real_ModuleLoad = Module._load;

const basedir = path.join(require.resolve('../../package.json'), '../');
assert(path.isAbsolute(basedir));
assert(basedir.endsWith(path.sep));

let running = false;
let data = null;
let order = null;
let startTime = null;
let stopTime = null;

// This function shows up in stack traces - make the name distinct.
function profile_require_time(request, parent, isMain) {
  // https://github.com/nodejs/node/blob/v4.1.1/lib/module.js#L276
  if (request === 'internal/repl' || request === 'repl') {
    return _real_ModuleLoad.call(Module, request, parent, isMain);
  }
Example #17
0
		}).map(function (p) {
			return path.isAbsolute(p) ? p : path.resolve(root, p);
		});
/**
 * Attempts to detect whether the string is a local path regardless of its
 * existence by checking its format. The point is to distinguish between
 * paths and modules on the npm registry. This will fail for non-existent
 * local Windows paths that begin with a drive letter, e.g. C:..\generator.js,
 * but will succeed for any existing files and any absolute paths.
 *
 * @param {String} str - string to check
 * @returns {Boolean} whether the string could be a path to a local file or directory
 */
function default_1(str) {
    return path.isAbsolute(str) || /^\./.test(str) || fs.existsSync(str);
}
module.exports = ctx => function multiConfigPath(base, configPaths, outputDir) {
  const log = ctx.log;

  const defaultPath = pathFn.join(base, '_config.yml');
  let paths;

  if (!configPaths) {
    log.w('No config file entered.');
    return pathFn.join(base, '_config.yml');
  }

  // determine if comma or space separated
  if (configPaths.includes(',')) {
    paths = configPaths.replace(' ', '').split(',');
  } else {
    // only one config
    let configPath = pathFn.isAbsolute(configPaths) ? configPaths : pathFn.resolve(base, configPaths);

    if (!fs.existsSync(configPath)) {
      log.w(`Config file ${configPaths} not found, using default.`);
      configPath = defaultPath;
    }

    return configPath;
  }

  const numPaths = paths.length;

  // combine files
  const combinedConfig = {};
  let count = 0;
  for (let i = 0; i < numPaths; i++) {
    let configPath = '';

    if (pathFn.isAbsolute(paths[i])) {
      configPath = paths[i];
    } else {
      configPath = pathFn.join(base, paths[i]);
    }

    if (!fs.existsSync(configPath)) {
      log.w(`Config file ${paths[i]} not found.`);
      continue;
    }

    // files read synchronously to ensure proper overwrite order
    const file = fs.readFileSync(configPath);
    const ext = pathFn.extname(paths[i]).toLowerCase();

    if (ext === '.yml') {
      merge(combinedConfig, yml.load(file));
      count++;
    } else if (ext === '.json') {
      merge(combinedConfig, yml.safeLoad(file, {json: true}));
      count++;
    } else {
      log.w(`Config file ${paths[i]} not supported type.`);
    }
  }

  if (count === 0) {
    log.e('No config files found. Using _config.yml.');
    return defaultPath;
  }

  log.i('Config based on', count, 'files');

  const multiconfigRoot = outputDir || base;
  const outputPath = pathFn.join(multiconfigRoot, '_multiconfig.yml');

  log.d(`Writing _multiconfig.yml to ${outputPath}`);

  fs.writeFileSync(outputPath, yml.dump(combinedConfig));

  // write file and return path
  return outputPath;
};
Example #20
0
router.post('/:type', (req, res) => {
  let type =  req.params.type === 'move' ? 'createMove'
                  : req.params.type === 'copy' ? 'createCopy' : undefined
  if(type){
    let src = req.body.src
    let dst = req.body.dst
    if(typeof src.path !== 'string' || typeof dst.path !== 'string')
      return res.error(new Error('path type error'), 400)
    if(!((src.type === 'fruitmix' && isUUID(src.path)) || (src.type === 'ext' && path.isAbsolute(src.path))))
      return res.error(new Error('src error'), 400)
    if(!((dst.type === 'fruitmix' && isUUID(dst.path)) || (dst.type === 'ext' && path.isAbsolute(dst.path))))
      return res.error(new Error('dst error'), 400)
      
    config.ipc.call(type, { src, dst, userUUID: req.user.uuid }, (e, data) => {
      if(e){ 
        console.log(e)
        return res.error(e, 500)
      }
      return res.success(data, 200)
    })
  }else{
    res.error(null, 404)
  }
})
Example #21
0
/**
 * Whether or not the path is absolute.
 *
 * @private
 * @param  {String}  p
 * @return {Boolean}
 */
function isAbsolute(p) {
  return path.isAbsolute ? path.isAbsolute(p) : path.resolve(p) === p;
}
Example #22
0
File: index.js Project: bondden/but
		var aP=function(p){
			if(!path.isAbsolute(p)){
				p=path.resolve(__dirname+'/../../'+p).replace(/\\/ig,'/');
			}
			return p;
		};
Example #23
0
/**
 * Returns "golden" matchers for use with the specified `testFile`.
 *
 * Golden tests read a collection of input files, process them with a
 * function, and compare the results against a collection of ("golden") output
 * files. Discrepancies are reported as textual diffs, and the golden files
 * can be updated by running the tests with an environment variable set.
 *
 * A directory containing input and output fixtures can be specified using a
 * path relative to the directory containing the current test file (passed in
 * via the `testFile` parameter):
 *
 *    beforeEach(() => {
 *      expect.extend(getGoldenMatchers(__filename));
 *    });
 *
 * If you don't initialize in this way, either absolute paths, or paths
 * relative to the current working directory, may be used, but this is not
 * recommended.
 *
 * Additionally, an optional options object can be supplied to fine-tune the
 * comparison between actual and expected outputs:
 *
 *    getGoldenMatchers(
 *      __filename,
 *      {trimWhitespace: false}
 *    );
 *
 * Supported options:
 *
 *  - `trimWhitespace`: If `true` (the default), trailing whitespace is
 *    stripped before comparing actual and expected output.
 *
 */
function getGoldenMatchers(...args) {
  const [testFile, options] = args;
  const trimWhitespace = options && options.hasOwnProperty('trimWhitespace')
    ? options.trimWhitespace
    : true;

  return {
    /**
    * Implements the "golden" test pattern. Takes a path to a folder of input
    * and output fixtures, and a function to operate on the contents of each
    * input file.
    *
    * Input files have the form "$BASENAME.input.$EXT" and output files have
    * the form "$BASENAME.golden.$EXT". Input and output files are matched up
    * according to their basenames (ie. file extensions are ignored). This
    * enables viewing and editing input and output files with arbitrary syntax
    * highlighting in your editor.
    *
    * To run the tests:
    *
    *    expect('fixtures/parser').toMatchGolden(text => parse(text));
    *
    * To update the golden files, re-run the tests with the
    * `GOLDEN_ACCEPT` environment variable set:
    *
    *    GOLDEN_ACCEPT=1 jest MyTestModule
    *
    * Additionally, note that adding a new input file and running the tests
    * will cause the corresponding golden file to be created with a default
    * ".txt" extension.
    */
    toMatchGolden(fixtures, operation) {
      const fs = require('fs');
      const path = require('path');
      const base = testFile ? path.dirname(testFile) : process.cwd();

      const absoluteFixtures = path.isAbsolute(fixtures)
        ? fixtures
        : path.join(base, fixtures);
      invariant(
        fs.statSync(absoluteFixtures).isDirectory(),
        `toMatchGolden: "${fixtures}" is not a directory`,
      );
      const fixtureInfo = fs.readdirSync(absoluteFixtures).map(file => {
        const {ext, name: nameWithType} = path.parse(file);
        const {ext: type, name} = path.parse(nameWithType);
        const fixture = path.join(absoluteFixtures, file);
        invariant(
          ext !== '' && (type === '.input' || type === '.golden'),
          `toMatchGolden: "${file}" must be named ` +
            '"*.input.$EXTENSION" or "*.golden.$EXTENSION".',
        );
        invariant(
          fs.statSync(fixture).isFile(),
          `toMatchGolden: "${file}" must be a regular file.`,
        );
        return {
          ext: ext.slice(1),
          fixture,
          name,
          type: type.slice(1),
        };
      });
      const inputFilesSet = new Set();
      const outputFilesMap = new Map();
      const [inputFiles, outputFiles] = partitionArray(fixtureInfo, info => {
        const {name, type} = info;
        if (type === 'input') {
          inputFilesSet.add(name);
          return true;
        } else {
          outputFilesMap.set(name, info);
        }
      });
      outputFiles.forEach(({ext, name, type}) => {
        invariant(
          inputFilesSet.has(name),
          `toMatchGolden: golden file "${name}.${type}.${ext}" does ` +
            'not have a corresponding input file.',
        );
      });
      const failures = [];
      inputFiles.forEach(({ext, fixture, name, type}) => {
        const inputFile = `${name}.${type}.${ext}`;
        const input = fs.readFileSync(fixture).toString();
        let output;

        try {
          output = operation(input, inputFile);
        } catch (e) {
          throw new Error(
            'Failure applying function to input from file ' +
              `"${inputFile}":\n` +
              `${e.message}\n${e.stack}`,
          );
        }

        if (outputFilesMap.has(name)) {
          const expectedFileInfo = outputFilesMap.get(name);
          const expectedFile = expectedFileInfo.fixture;
          const expected = fs.readFileSync(expectedFile).toString();
          const trimmedOutput = trimWhitespace ? output.trim() : output;
          const trimmedExpected = trimWhitespace ? expected.trim() : expected;
          if (trimmedOutput !== trimmedExpected) {
            if (process.env.GOLDEN_ACCEPT) {
              log(COLOR.green(' ACK  ') + ' ' + name);
              fs.writeFileSync(expectedFile, normalize(output));
            } else {
              log(COLOR.red(' FAIL ') + ' ' + name);
              failures.push({
                name,
                expectedFile,
                expected,
                output,
              });
              printDiff(trimmedExpected, trimmedOutput, expectedFileInfo);
            }
          } else {
            log(COLOR.green('  OK  ') + ' ' + name);
          }
        } else {
          log(COLOR.yellow(' NEW  ') + ' ' + name);
          const golden = path.join(absoluteFixtures, `${name}.golden.txt`);
          fs.writeFileSync(golden, normalize(output));
        }
      });
      return {
        pass: failures.length === 0,
        message: 'actual output did not match expected for files: ' +
          failures.map(failure => failure.name).join(', ') +
          ' (if these changes are intended, re-run the tests with the ' +
          'environment variable GOLDEN_ACCEPT=1 to update the ' +
          'fixtures)',
      };
    },
  };
}
Example #24
0
        return code.replace(/require\(['"]([\w\d_\-\.\/@]+)['"]\)/ig, (match, lib) => {
            if (lib === './_wepylogs.js') {
                return match;
            }
            let resolved = lib;


            let target = '', source = '', ext = '', needCopy = false;

            if (config.output === 'ant' && lib === 'wepy') {
                lib = 'wepy-ant';
            }
            lib = resolve.resolveAlias(lib);
            if (path.isAbsolute(lib)) {
                source = lib;
                target = util.getDistPath(source);
            } else if (lib[0] === '.') { // require('./something'');
                source = path.join(opath.dir, lib);  // e:/src/util
                if (type === 'npm') {
                    target = path.join(npmPath, path.relative(npmInfo.modulePath, source));
                    needCopy = true;
                } else {
                    // e:/dist/util
                    target = util.getDistPath(source);
                    needCopy = false;
                }
            } else if (lib.indexOf('/') === -1 || // require('asset');
                lib.indexOf('/') === lib.length - 1 || // reqiore('a/b/something/')
                (lib[0] === '@' && lib.indexOf('/') !== -1 && lib.lastIndexOf('/') === lib.indexOf('/')) // require('@abc/something')
            ) {  

                let mainFile = resolve.getMainFile(lib);

                if (!mainFile) {
                    throw Error('找不到模块: ' + lib + '\n被依赖于: ' + path.join(opath.dir, opath.base) + '。\n请尝试手动执行 npm install ' + lib + ' 进行安装。');
                }
                npmInfo = {
                    lib: lib,
                    dir: mainFile.dir,
                    modulePath: mainFile.modulePath,
                    file: mainFile.file
                };
                source = path.join(mainFile.dir, mainFile.file);
                target = path.join(npmPath, lib, mainFile.file);

                lib += path.sep + mainFile.file;
                ext = '';
                needCopy = true;
            } else { // require('babel-runtime/regenerator')
                let requieInfo = lib.split('/');
                let mainFile = resolve.getMainFile(requieInfo[0]);

                if (!mainFile) {
                    throw Error('找不到模块: ' + lib + '\n被依赖于: ' + path.join(opath.dir, opath.base) + '。\n请尝试手动执行 npm install ' + lib + ' 进行安装。');
                }
                npmInfo = {
                    lib: requieInfo[0],
                    dir: mainFile.dir,
                    modulePath: mainFile.modulePath,
                    file: mainFile.file
                };
                requieInfo.shift();

                source = path.join(mainFile.dir, requieInfo.join('/'));
                target = path.join(npmPath, npmInfo.lib, requieInfo.join('/'));
                ext = '';
                needCopy = true;
            }

            if (util.isFile(source + wpyExt)) {
                ext = '.js';
            } else if (util.isFile(source + '.js')) {
                ext = '.js';
            } else if (util.isDir(source) && util.isFile(source + path.sep + 'index.js')) {
                ext = path.sep + 'index.js';
            }else if (util.isFile(source)) {
                ext = '';
            } else {
                throw ('找不到文件: ' + source);
            }
            source += ext;
            target += ext;
            lib += ext;
            resolved = lib;

            // 第三方组件
            if (/\.wpy$/.test(resolved)) {
                target = target.replace(/\.wpy$/, '') + '.js';
                resolved = resolved.replace(/\.wpy$/, '') + '.js';
                lib = resolved;
            }

            if (needCopy) {
                if (!cache.checkBuildCache(source)) {
                    cache.setBuildCache(source);
                    util.log('依赖: ' + path.relative(process.cwd(), target), '拷贝');
                    let newOpath = path.parse(source);
                    newOpath.npm = npmInfo;
                    this.compile('js', null, 'npm', newOpath);

                }
            }
            if (type === 'npm') {
                if (lib[0] !== '.') {
                    resolved = path.join('..' + path.sep, path.relative(opath.dir, npmInfo.modulePath), lib);
                } else {
                    if (lib[0] === '.' && lib[1] === '.')
                        resolved = './' + resolved;
                }

            } else {
                resolved = path.relative(util.getDistPath(opath, opath.ext, src, dist), target);
            }
            resolved = resolved.replace(/\\/g, '/').replace(/^\.\.\//, './');
            return `require('${resolved}')`;
        });
Example #25
0
module.exports = function create (opts) {
  if (typeof opts === 'undefined') opts = {dir: app.getAppPath()}
  if (typeof opts === 'string') opts = {dir: opts}
  if (!opts.dir) opts.dir = app.getAppPath()
  if (!(path.isAbsolute(opts.dir))) opts.dir = path.resolve(opts.dir)
  if (!opts.index) opts.index = 'file://' + path.join(opts.dir, 'index.html')
  if (!opts['windowPosition']) opts['windowPosition'] = (process.platform === 'win32') ? 'trayBottomCenter' : 'trayCenter'
  if (typeof opts['showDockIcon'] === 'undefined') opts['showDockIcon'] = false

  // set width/height on opts to be usable before the window is created
  opts.width = opts.width || 400
  opts.height = opts.height || 400
  opts.tooltip = opts.tooltip || ''

  app.on('ready', appReady)

  var menubar = new events.EventEmitter()
  menubar.app = app

  // Set / get options
  menubar.setOption = function (opt, val) {
    opts[opt] = val
  }

  menubar.getOption = function (opt) {
    return opts[opt]
  }

  return menubar

  function appReady () {
    if (app.dock && !opts['showDockIcon']) app.dock.hide()

    var iconPath = opts.icon || path.join(opts.dir, 'IconTemplate.png')
    if (!fs.existsSync(iconPath)) iconPath = path.join(__dirname, 'example', 'IconTemplate.png') // default cat icon

    var cachedBounds // cachedBounds are needed for double-clicked event
    var defaultClickEvent = opts['show-on-right-click'] ? 'right-click' : 'click'

    menubar.tray = opts.tray || new Tray(iconPath)
    menubar.tray.on(defaultClickEvent, clicked)
    menubar.tray.on('double-click', clicked)
    menubar.tray.setToolTip(opts.tooltip)

    if (opts.preloadWindow || opts['preload-window']) {
      createWindow()
    }

    menubar.showWindow = showWindow
    menubar.hideWindow = hideWindow
    menubar.emit('ready')

    function clicked (e, bounds) {
      if (e.altKey || e.shiftKey || e.ctrlKey || e.metaKey) return hideWindow()
      if (menubar.window && menubar.window.isVisible()) return hideWindow()
      cachedBounds = bounds || cachedBounds
      showWindow(cachedBounds)
    }

    function createWindow () {
      menubar.emit('create-window')
      var defaults = {
        show: false,
        frame: false
      }

      var winOpts = extend(defaults, opts)
      menubar.window = new BrowserWindow(winOpts)

      menubar.positioner = new Positioner(menubar.window)

      if (!opts['always-on-top']) {
        menubar.window.on('blur', hideWindow)
      } else {
        menubar.window.on('blur', emitBlur)
      }

      if (opts['show-on-all-workspaces'] !== false) {
        menubar.window.setVisibleOnAllWorkspaces(true)
      }

      menubar.window.on('close', windowClear)
      menubar.window.loadURL(opts.index)
      menubar.emit('after-create-window')
    }

    function showWindow (trayPos) {
      if (!menubar.window) {
        createWindow()
      }

      menubar.emit('show')

      if (trayPos && trayPos.x !== 0) {
        // Cache the bounds
        cachedBounds = trayPos
      } else if (cachedBounds) {
        // Cached value will be used if showWindow is called without bounds data
        trayPos = cachedBounds
      }

      // Default the window to the right if `trayPos` bounds are undefined or null.
      var noBoundsPosition = null
      if ((trayPos === undefined || trayPos.x === 0) && opts['windowPosition'].substr(0, 4) === 'tray') {
        noBoundsPosition = (process.platform === 'win32') ? 'bottomRight' : 'topRight'
      }

      var position = menubar.positioner.calculate(noBoundsPosition || opts['windowPosition'], trayPos)

      var x = (opts.x !== undefined) ? opts.x : position.x
      var y = (opts.y !== undefined) ? opts.y : position.y

      menubar.window.setPosition(x, y)
      menubar.window.show()
      menubar.emit('after-show')
      return
    }

    function hideWindow () {
      if (!menubar.window) return
      menubar.emit('hide')
      menubar.window.hide()
      menubar.emit('after-hide')
    }

    function windowClear () {
      delete menubar.window
      menubar.emit('after-close')
    }

    function emitBlur () {
      menubar.emit('focus-lost')
    }
  }
}
Example #26
0
module.exports = function lintSource(
  stylelint/*: stylelint$internalApi*/,
  options/*: {
    code?: string,
    codeFilename?: string, // Must be an absolute file path
    filePath?: string, // Must be an absolute file path
    existingPostcssResult?: Object,
  }*/
)/*: Promise<Object>*/ {
  options = options || {}

  if (!options.filePath && options.code === undefined && !options.existingPostcssResult) {
    return Promise.reject(new Error("You must provide filePath, code, or existingPostcssResult"))
  }

  const isCodeNotFile = options.code !== undefined

  const inputFilePath = isCodeNotFile ? options.codeFilename : options.filePath
  if (inputFilePath !== undefined && !path.isAbsolute(inputFilePath)) {
    if (isCodeNotFile) {
      return Promise.reject(new Error("codeFilename must be an absolute path"))
    } else {
      return Promise.reject(new Error("filePath must be an absolute path"))
    }
  }

  const getIsIgnored = stylelint.isPathIgnored(inputFilePath).catch(err => {
    if (isCodeNotFile && err.code === "ENOENT") return false
    throw err
  })

  return getIsIgnored.then(isIgnored => {
    if (isIgnored) {
      const postcssResult = options.existingPostcssResult || createEmptyPostcssResult(inputFilePath)
      postcssResult.stylelint = postcssResult.stylelint || {}
      postcssResult.stylelint.ignored = true
      postcssResult.standaloneIgnored = true // TODO: remove need for this
      return postcssResult
    }

    const configSearchPath = stylelint._options.configFile || inputFilePath

    const getConfig = stylelint.getConfigForFile(configSearchPath).catch(err => {
      if (isCodeNotFile && err.code === "ENOENT") return stylelint.getConfigForFile(process.cwd())
      throw err
    })

    return getConfig.then((result) => {
      const config = result.config
      const existingPostcssResult = options.existingPostcssResult

      if (existingPostcssResult) {
        return lintPostcssResult(stylelint, existingPostcssResult, config).then(() => existingPostcssResult)
      }

      return stylelint._getPostcssResult({
        code: options.code,
        codeFilename: options.codeFilename,
        filePath: inputFilePath,
        codeProcessors: config.codeProcessors,
      }).then(postcssResult => {
        return lintPostcssResult(stylelint, postcssResult, config).then(() => postcssResult)
      })
    })
  })
}
Example #27
0
StoryBook.load = async function load( path , options ) {
	var regex , script ;

	if ( ! options || typeof options !== 'object' ) { options = {} ; }

	options.type = 'story' ;

	if ( ! options.cwd ) {
		// Set the CWD for commands, summonings, and persistent
		if ( pathModule.isAbsolute( path ) ) {
			options.cwd = pathModule.dirname( path ) ;
		}
		else {
			options.cwd = process.cwd() + '/' + pathModule.dirname( path ) ;
		}
	}

	if ( ! options.data ) { options.data = {} ; }

	if ( ! options.data.__babel ) {
		regex = /(\^)/g ;
		regex.substitution = '$1$1' ;
		Object.defineProperty( options.data , '__babel' , { value: new Babel( regex ) , writable: true } ) ;
	}

	if ( ! options.locales ) { options.locales = {} ; }


	script = await kungFig.loadAsync( path , {
		kfgFiles: {
			basename: [ 'spellbook' , 'book' ]
		} ,
		noKfgCache: true ,
		modulePath: KFG_MODULE_PATH ,
		doctype: 'spellcast/book' ,
		metaHook: ( meta , parseOptions ) => {
			var localesMeta , assetsMeta , locale ;

			localesMeta = meta.getFirstTag( 'locales' ) ;
			assetsMeta = meta.getFirstTag( 'assets' ) ;

			if ( localesMeta ) {
				pathSecurityCheck( localesMeta.attributes , true ) ;
				glob.sync( pathModule.dirname( parseOptions.file ) + '/' + localesMeta.attributes , { absolute: true } ).forEach( e => {
					locale = pathModule.basename( e , '.kfg' ) ;
					if ( ! Array.isArray( options.locales[ locale ] ) ) { options.locales[ locale ] = [] ; }
					options.locales[ locale ].push( e ) ;
				} ) ;
			}

			if ( assetsMeta ) {
				pathSecurityCheck( assetsMeta.attributes ) ;
				options.assetBaseUrl = fs.realpathSync( pathModule.dirname( path ) + '/' + assetsMeta.attributes ) ;
				//console.log( "options.assetBaseUrl: " , options.assetBaseUrl ) ;
			}
		} ,
		operators: require( './operators.js' ) ,
		classes: require( './kfgClasses.js' ) ,
		tags: availableTags
	} ) ;

	var book = new StoryBook( script , options ) ;

	return book ;
} ;
Example #28
0
module.exports = function fileInput( options , callback ) {
	if ( typeof options === 'function' ) { callback = options ; options = {} ; }
	if ( ! options || typeof options !== 'object' ) { options = {} ; }

	var baseDir ;

	var promise = new Promise() ;

	if ( options.baseDir ) {
		baseDir = path.resolve( options.baseDir ) ;

		if ( ! path.isAbsolute( baseDir ) ) {
			fs.realpath( options.baseDir , ( error , resolvedPath ) => {
				if ( error ) {
					if ( callback ) { callback( error ) ; }
					else { promise.reject( error ) ; }
					return ;
				}

				options.baseDir = resolvedPath ;

				this.fileInput( options ).then(
					input => {
						if ( callback ) { callback( input ) ; }
						else { promise.resolve( input ) ; }
					} ,
					error_ => {
						if ( callback ) { callback( error_ ) ; }
						else { promise.reject( error_ ) ; }
					}
				) ;
			} ) ;

			return promise ;
		}
	}
	else {
		baseDir = process.cwd() ;
	}

	if ( baseDir[ baseDir.length - 1 ] !== '/' ) { baseDir += '/' ; }

	var autoCompleter = async function autoCompleter( inputString ) {
		var inputDir , inputFile , currentDir , files , completion ;

		if ( inputString[ inputString.length - 1 ] === '/' ) {
			inputDir = inputString ;
			inputFile = '' ;
		}
		else {
			inputDir = path.dirname( inputString ) ;
			inputDir = inputDir === '.' ? '' : inputDir + '/' ;
			inputFile = path.basename( inputString ) ;
		}


		// If the input start with a '/', then forget about the baseDir
		if ( path.isAbsolute( inputString ) ) { currentDir = inputDir ; }
		else { currentDir = baseDir + inputDir ; }


		//console.error( "### '" + inputDir +"' '"+ inputFile +"' '"+ currentDir + "'" ) ;
		try {
			files = await readdir( currentDir ) ;
		}
		catch ( error ) {
			return inputString ;
		}

		if ( ! Array.isArray( files ) || ! files.length ) { return inputString ; }

		completion = autoComplete( files , inputFile , true ) ;

		// force inputField() to prefix that *AFTER* singleLineMenu()
		if ( Array.isArray( completion ) ) { completion.prefix = inputDir ;	}
		else { completion = path.normalize( inputDir + completion ) ; }

		return completion ;
	} ;

	// Transmit options to inputField()
	options = Object.assign( {} , options , { autoComplete: autoCompleter , autoCompleteMenu: true , minLength: 1 } ) ;

	this.inputField( options ).promise.then(
		input => {
			if ( ! input && typeof input !== 'string' ) {
				input = undefined ;
			}
			else {
				input = path.resolve( path.isAbsolute( input ) ? input : baseDir + input ) ;
			}

			if ( callback ) { callback( undefined , input ) ; }
			else { promise.resolve( input ) ; }
		} ,
		error => {
			if ( callback ) { callback( error ) ; }
			else { promise.reject( error ) ; }
		}
	) ;

	return promise ;
} ;
Example #29
0
 dir = (function () {
     if (path.isAbsolute(config.dir)) {
         return config.dir;
     }
     return path.join(configure.rootDir, config.dir);
 })();
Example #30
0
File: config.js Project: YMFE/yicon
import path from 'path';
import fs from 'fs';

const { CONFIG } = process.env;

let file = path.join(__dirname, '../../config.json');

if (CONFIG) {
  if (path.isAbsolute(CONFIG)) {
    file = CONFIG;
  } else {
    file = path.join(process.cwd(), CONFIG);
  }
}

const data = fs.readFileSync(file);

let config = {};

try {
  config = JSON.parse(data);
} catch (e) {
  throw new Error(e);
}

const common = {
  path: {
    caches: path.join(__dirname, '../../caches'),
    font: 'download/font',
    svg: 'download/svg',
    png: 'download/png',