把各种 lint 的配置文件，移动到根目录

@param {string} presetModulePath preset module absolute path
@param {boolen} keep 是否保留旧配置文件
@returns {void}
768953
function link (presetModulePath, keep) {
  debug(`input ${presetModulePath}`)

  console.log('update config file:')

  findConfigFiles(presetModulePath)
    .forEach(configFilePath => {
      updateConfigFiles(configFilePath, keep)
    })
}
180905
function genModuleDeps(scriptPath) {
  var provideMap = new ProvideMap_();
  var requireMap = new RequireMap_();
  scanFiles([scriptPath], provideMap, requireMap);
  var dumpValues = function(map) {
    var results = [];
    map.forEach(function(value, key) {
      results = results.concat(value);
    });
    return results;
  };

  var relativePath = pathMod.join('../..', scriptPath);
  if (osMod.platform().indexOf('win') != -1) {
    relativePath = relativePath.replace(/\\/g, '\\\\');
  }

  var provide = provideMap.getAllProvides();
  var require = requireMap.getAllRequires();
  return 'goog.addDependency("' + relativePath + '", ' +
      JSON.stringify(dumpValues(provide)) + ', ' +
      JSON.stringify(dumpValues(require)) + ', true);';
}
1060866
function (filepath) {

            // console.log('processing: ' + filepath);

            // read file source, saved in RAM
            var content = grunt.file.read(filepath);

            /*
             * Reset pattern's last search index to 0
             * at the beginning for each file content.
             *
             * NOTE:
             *   Since the pattern is always the same regex instance,
             *   property 'lastIndex' changes each time when .exec() is performed.
             *   To avoid 'lastIndex' affected by recursive function call,
             *   its value MUST be cached for each file content.
             */
            var cacheLastIndex = 0;
            _.pattern.lastIndex = cacheLastIndex;
            var matches = _.pattern.exec(content);
            cacheLastIndex = _.pattern.lastIndex;

            // While there are matches (of import-links) in file content
            while (matches !== null) {

                /*
                 * Construct the imported file's absolute path
                 *   (doesn't matter whether or not a relative path),
                 * and recursively search in imported file. (dept-first)
                 *
                 * NOTE:
                 *    - the regex uses capture group, the first match is the fragment file path.
                 */
                var currentDir = path.dirname(filepath),
                    relativeFilepath = matches[1].trim(),
                    importedFilepath = path.resolve(currentDir, relativeFilepath);

                var returnContent = getReplacedFileContent(importedFilepath);


                /*
                 * For current file content,
                 * replace import-link tag with return value.
                 *
                 * NOTE:
                 *   Because of dept-first search,
                 *   should ONLY replace the first match in current content.
                 *   rather than search globally.
                 */
                content = content.replace(_.patternNonGlobal, returnContent);
                // console.log(content);
                // console.log(matches);
                // console.log('-----');


                /*
                 * Keep searching in current file.
                 *
                 * NOTE:
                 *   After replacing part of the content (the step above),
                 *   the content's length changes accordingly.
                 *   Thus the 'lastIndex' property should shift to
                 *   the proper position to ensure next search.
                 */
                var deltaLength = returnContent.length - matches[0].length;

                _.pattern.lastIndex = cacheLastIndex + deltaLength;
                matches = _.pattern.exec(content);
                cacheLastIndex = _.pattern.lastIndex;
            }

            // When searching and replacing is done, return the result.
            return content;
        }
219996
function (inPath) {
			var working, its = this.includeTrailingSlash, paths = this.paths;
			var fn = function(macro, name) {
				working = true;
				return its(paths[name]) || '';
			};
			var result = inPath;
			do {
				working = false;
				result = result.replace(this.rewritePattern, fn);
			} while (working);
			return result;
		}
547832
function View_setModulesViewsPath(dir) {
            var list, name, moduleToLoad, LoadedModule, moduleInstance;
            if (this.isDir(dir)) {
                list = this.readDir(dir);
                while (true) {
                    name = list.shift();

                    if (!name) {
                        break;
                    }

                    moduleToLoad = dir + '/' + name;

                    try {
                        LoadedModule = di.load(moduleToLoad);
                    } catch (e) {
                        throw new error.HttpError(500, {path: moduleToLoad}, 'Missing module', e);
                    }

                    if (!Type.assert(Type.FUNCTION, LoadedModule)) {
                        throw new error.HttpError(500, {path: moduleToLoad}, 'Module must be function type');
                    }

                    moduleInstance = new LoadedModule(name);

                    if (!(moduleInstance instanceof ModuleInterface)) {
                        throw new error.HttpError(500, moduleInstance, 'Module must be instance of ModuleInterface "core/module"');
                    }

                    this.normalizers.push(moduleInstance.getViewsPath());

                    this.config.themes.forEach(function (name) {
                        this.paths.push(moduleInstance.getViewsPath() + name + '/');
                    }.bind(this));
                }

            }
        }
468946
function lint(applyFixes) {
    logInfo("Lint TypeScript source files");

    const tsDir = path.resolve(TS_TARGETDIR);
    const cwdLength = tsDir.length - TS_TARGETDIR.length;
    const tsSuffix = ".ts";
    const dtsSuffix = ".d.ts";
    const lintConfigFile = path.resolve("./build/tslint.json");
    const lintOptions = {
        formatter: "verbose",
        fix: applyFixes
    };

    lintFolders(tsDir);

    function lintFolders(parent) {
        fse.readdirSync(parent).forEach((file, index) => {
            let curPath = path.join(parent, file);
            if (!fse.lstatSync(curPath).isDirectory()) {
                if ((file.substr(-tsSuffix.length) === tsSuffix) &&
                    !(file.substr(-dtsSuffix.length) === dtsSuffix)) {
                    lintFile(curPath.substr(cwdLength));
                }
            } else {
                lintFolders(curPath);
            }
        });
    }

    function lintFile(file) {
        const contents = fse.readFileSync(file, "utf-8");
        const linter = new tslint.Linter(lintOptions);
        const configuration = tslint.Configuration.findConfiguration(lintConfigFile).results;
        linter.lint(file, contents, configuration);
        const result = linter.getResult();

        // For debugging, use console.log(result);
        result.errorCount > 0 && console.log(result.output);
    }
}
639455
function parseStringPropertyPath(propertyPath) {
            //jshint maxcomplexity:13
            //jshint maxdepth:3
            //REASON: taken from https://github.com/marklagendijk/lodash-deep/blob/master/lodash-deep.js
            //        Need to look at refactoring it.
            var character = '';
            var parsedPropertyPath = [];
            var parsedPropertyPathPart = '';
            var escapeNextCharacter = false;
            var isSpecialCharacter = false;
            var insideBrackets = false;

            // Walk through the path and find backslashes that escape periods or other backslashes, and split on unescaped
            // periods and brackets.
            for (var i = 0; i < propertyPath.length; i++) {
                character = propertyPath[i];
                isSpecialCharacter = (character === '\\' || character === '[' || character === ']' || character === '.');

                if (isSpecialCharacter && !escapeNextCharacter) {
                    if (insideBrackets && character !== ']') {
                        throw new SyntaxError('unexpected "' + character + '" within brackets at character ' + i + ' in property path ' + propertyPath);
                    }

                    switch (character) {
                        case '\\':
                            escapeNextCharacter = true;
                            break;
                        case ']':
                            insideBrackets = false;
                            break;
                        case '[':
                            insideBrackets = true;
                            /* falls through */
                        case '.':
                            parsedPropertyPath.push(parsedPropertyPathPart);
                            parsedPropertyPathPart = '';
                            break;
                    }
                } else {
                    parsedPropertyPathPart += character;
                    escapeNextCharacter = false;
                }
            }

            if (parsedPropertyPath[0] === '') {
                //allow '[0]', or '.0'
                parsedPropertyPath.splice(0, 1);
            }

            // capture the final part
            parsedPropertyPath.push(parsedPropertyPathPart);
            return parsedPropertyPath;
        }
1083499
function subModulePath(subModule, node_modules) {
  var index = subModule.indexOf("/");
  var length = subModule.length;
  if (index <= 0 || index + 1 == length) {
    return null;
  }
  var module = subModule.substring(0, index);
  var relative = subModule.substring(index + 1, length);

  var moduleDirectory = path.join(node_modules, module);
  var filePath = path.join(moduleDirectory, relative);
  return realRequirPath(filePath);
}
399629
function ConfigFromPath (superConfig, project, version) {
  ConfigFromPath.super_.call(this, superConfig, project, version);

  var strictNS = simpleWrapNS(this.ns);
  strictNS.env = simpleWrapNS(createNamespace(superConfig.getEnvConfig()));

  var files = superConfig._resolvePaths(project, version);
  var loaded = {};

  var generateLoad = function (f) {
    return function (otherVersion) {
      debug('load(%s) in %s', otherVersion, f);
      var dir = path.dirname(f);
      var otherFile = path.resolve(dir, otherVersion + '.js');
      if (loaded[otherFile]) {
        throw new Error('load(' + version + ') conflict in file ' + f);
      }
      try {
        require(otherFile)(strictNS, generateLoad(otherFile));
      } catch (err) {
        if (err.code === 'MODULE_NOT_FOUND') {
          throw new Error('load(' + version + ') fail in file ' + f);
        } else {
          throw err;
        }
      }
    };
  };
  files.forEach(function (f) {
    debug('load %s', f);
    var init = require(f);
    loaded[f] = true;
    if (typeof init !== 'function') {
      throw new Error('bad config file format, `module.exports` must be a function: ' + f);
    }
    init(strictNS, generateLoad(f));
  });

  var loadedFiles = Object.keys(loaded);
  if (loadedFiles.length < 1) {
    throw new Error('cannot find any config files for ' + project + '.' + version);
  } else {
    loadedFiles.forEach(function (f) {
      delete require.cache[f];
    });
  }

  this._loadFinish();
  debug('done');
}
948062
function assurePathSync (modulePath, resolveSync) {
  if (resolveCache[modulePath] === false) {
    return false
  } else if (!(modulePath in resolveCache)) {
    if (typeof resolveSync === 'function') {
      try {
        resolveCache[modulePath] = !!resolveSync(modulePath)
      } catch (e) {
        resolveCache[modulePath] = false
      }
    }
  }

  return resolveCache[modulePath]
}
460315
function parseModule(fileInfo) {

    var moduleName = file2modulename(fileInfo.relativePath);
    var sourceFile = new SourceFile(moduleName, fileInfo.content);
    var comments = [];
    var moduleTree;
    var parser = new Parser(sourceFile);

    // Configure the parser
    parser.handleComment = function(range) {
      comments.push({ range: range });
    };
    traceurOptions.setFromObject(service.traceurOptions);

    try {
      // Parse the file as a module, attaching the comments
      moduleTree = parser.parseModule();
      attachComments(moduleTree, comments);
    } catch(ex) {
      // HACK: sometime traceur crashes for various reasons including
      // Not Yet Implemented (NYI)!
      log.error(ex.stack);
      moduleTree = {};
    }
    log.debug(moduleName);
    moduleTree.moduleName = moduleName;

    // We return the module AST but also a collection of all the comments
    // since it can be helpful to iterate through them without having to
    // traverse the AST again
    return {
      moduleTree: moduleTree,
      comments: comments
    };
  }
642865
function installModule (module, modulesDir, callback) {

    let details = module.split('/');
    let devModulePath = resolve(modulesDir, module);

    fs.access(resolve(modulesDir, module), err => {

        // skip next steps if module already exists
        if (!err || err.code !== 'ENOENT') {
            return callback();
        }

        exec('git clone git@github.com:' + details[0] + '/' + details[1] + '.git ' + devModulePath, err => {

            if (err) {
                return callback(err);
            }

            exec('cd ' + devModulePath + '; npm i', err => {

                if (err) {
                    return callback(err);
                }

                // create a symlink to the babelify presets
                // it is required in order for babelify to work
                fs.symlink(resolve(__dirname, '../../', 'babel-preset-es2015'), resolve(devModulePath, 'node_modules/babel-preset-es2015'), err => {

                    if (err) {
                        return callback(err);
                    }

                    callback();
                });
            });
        });
    });
}
766785
function formatAsElegantPath(path, sep) {
    const chalk = require('chalk');
    const packages = path.split(sep);
    const lastIndex = packages.length - 1;

    // prettier-ignore
    const result = packages
        .map((item) => item.trim())
        .map((item, index) => {
            return index === lastIndex
                ? chalk.red.bold(item)
                : item;
        })
        .join(' -> ');
    return result;
}
299687
function copyFileSync(sourcePath, destPath) {
  var data = fs.readFileSync(sourcePath);
  var stat = fs.statSync(sourcePath);
  fs.writeFileSync(destPath, data);
  fs.chmodSync(destPath, stat.mode);
}
82908
function(filepath){
      filepath = filepath.replace(pathSepExp,'/'); // Use unix paths regardless. Makes these checks easier
      if(filepath &&
        (
          ( // If filepath has the jsIncludeDir, but does not include the node_modules directory under them
            filepath.match(expressions.jsIncludeDir)
            && !filepath.match(expressions.jsExcludeDir)
          )
          // Or the filepath has nothing to do with node_modules, app_modules/vendor
          || !filepath.match(expressions.jsAlwaysIncludeDir)
          || filepath.match(/node_modules(\\|\/)@polymer|node_modules(\\|\/)@webcomponents(\\|\/)shadycss/)
        )
      ) {
        // console.log('===================================')
        // console.log(filepath)
        // console.log('### Transpiling: '+filepath);
        return true;
      }
    }
1066202
function updateConfigFiles (filePath, keep) {
  debug(`file path: ${filePath}`)

  if (typeof filePath !== 'string' || !fs.existsSync(filePath)) {
    debug(`file not exists: ${filePath}`)
    return
  }

  const baseDir = getBaseDir()
  const fileParsedObj = path.parse(filePath)
  const fileName = `${fileParsedObj.name}${fileParsedObj.ext}`
  const destFilePath = path.join(baseDir, fileName)
  const oldFilePath = path.join(
    baseDir,
    `${fileParsedObj.name}.old${fileParsedObj.ext}`
  )

  debug(`file dest path: ${destFilePath}`)

  // 获取输出时使用的相对路径
  const getRelativePath = p => {
    if (p.startsWith(baseDir)) {
      return path.relative(baseDir, p)
    }

    return p
  }

  // 旧文件存在，rename
  if (keep === true && fs.existsSync(destFilePath)) {
    if (isSameFile(filePath, destFilePath)) {
      debug('file exists, file same, ignore')
      console.log(`  "${getRelativePath(destFilePath)}" is up to date`)
      return
    }

    debug('file exists, file different, move.')
    debug(`file old name: ${oldFilePath}`)
    fs.moveSync(destFilePath, oldFilePath, { overwrite: true })
    console.log(`  move: from "${getRelativePath(destFilePath)}"`)
    console.log(`          to "${getRelativePath(oldFilePath)}"`)
  }

  fs.copySync(filePath, destFilePath)
  console.log(`  copy: from "${getRelativePath(filePath)}"`)
  console.log(`          to "${getRelativePath(destFilePath)}"`)
}
186083
function getModuleConfig(nameOrPath,modules) {
    for (var i = 0; i < modules.length; i++) {
        var config = modules[i];
        if (config.options && (config.options.directory === nameOrPath || config.name === nameOrPath)) {
            return config;
        }
    }
    return null;
}