Get configuration from NPM package or from resource files
335340
function getConfig(fpath, defaults) {
  var path = require('path');
  var dpath = path.dirname(path.resolve(fpath));

  function parentpath(fromdir, pattern) {
    var pp = require('parentpath'),
        cwd = process.cwd();
    try {
      process.chdir(fromdir);
      return pp.sync(pattern);
    } catch (e) {
      return null;
    } finally {
      process.chdir(cwd);
    }
  }

  function fromNpm() {
    var config;
    var dir = parentpath(dpath, 'package.json');
    if (dir) {
      try {
        config = require(dir + '/package.json')[MJS_NPM];
        config.__origin__ = dir + '/package.json';
      } catch (e) {
      }
    }
    return config;
  }

  function fromResourceFile() {
    var candidates = [
      parentpath(path, MJS_RC),
      process.env.HOME, process.env.USERPROFILE, process.env.HOMEPATH, process.env.HOMEDRIVE + process.env.HOMEPATH
    ];

    var config;
    for (var i = 0; i < candidates.length; i++) {
      var candidate = candidates[i] + '/' + MJS_RC;
      if (fs.existsSync(candidate)) {
        try {
          config = JSON.parse(fs.readFileSync(candidate));
          config.__origin__ = candidate;
          break;
        } catch (e) {
          showHelpAndExit('Unable to read config from "' + candidate + '": ' + e.message, 1);
        }
      }
    }
    return config;
  }

  var config = fromNpm() || fromResourceFile() || {};
  // Make sure we apply defaults to missing values
  Object.keys(defaults).filter(function (k) {
    return config[k] == null
  }).forEach(function (k) {
    config[k] = defaults[k];
  });
  return config;
}
874526
def get_config(config_file=None, config_values=None, load_project_conf=True):
    """"""
    config_values = config_values or {}
    config_settings = {}

    default_conf = _get_default_conf()
    user_conf = _get_user_conf(config_file) if config_file else {}
    # load project configuration only when user configuration was not specified
    project_conf = {} if user_conf or not load_project_conf else _get_project_conf()

    if not (user_conf or project_conf or config_values):
        if load_project_conf:
            raise Dump2PolarionException(
                "Failed to find configuration file for the project "
                "and no configuration file or values passed."
            )
        raise Dump2PolarionException("No configuration file or values passed.")

    # merge configuration
    config_settings.update(default_conf)
    config_settings.update(user_conf)
    config_settings.update(project_conf)
    config_settings.update(config_values)

    _populate_urls(config_settings)
    _set_legacy_project_id(config_settings)
    _set_legacy_custom_fields(config_settings)
    _check_config(config_settings)

    return config_settings
481082
def get_config(config_file):
    """"""
    config_path = os.path.abspath(config_file)

    try:
        with open(config_path, 'r') as data:
            config = yaml.safe_load(data)
    except IOError as exc:
        sys.exit(str(exc))

    return config
595438
function getTypingNamesFromNodeModuleFolder(nodeModulesPath) {
                // Todo: add support for ModuleResolutionHost too
                if (!host.directoryExists(nodeModulesPath)) {
                    return;
                }
                var typingNames = [];
                var fileNames = host.readDirectory(nodeModulesPath, [".json"], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2);
                for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) {
                    var fileName = fileNames_2[_i];
                    var normalizedFileName = ts.normalizePath(fileName);
                    if (ts.getBaseFileName(normalizedFileName) !== "package.json") {
                        continue;
                    }
                    var result = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); });
                    if (!result.config) {
                        continue;
                    }
                    var packageJson = result.config;
                    // npm 3's package.json contains a "_requiredBy" field
                    // we should include all the top level module names for npm 2, and only module names whose
                    // "_requiredBy" field starts with "#" or equals "/" for npm 3.
                    if (packageJson._requiredBy &&
                        ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) {
                        continue;
                    }
                    // If the package has its own d.ts typings, those will take precedence. Otherwise the package name will be used
                    // to download d.ts files from DefinitelyTyped
                    if (!packageJson.name) {
                        continue;
                    }
                    if (packageJson.typings) {
                        var absolutePath = ts.getNormalizedAbsolutePath(packageJson.typings, ts.getDirectoryPath(normalizedFileName));
                        inferredTypings[packageJson.name] = absolutePath;
                    }
                    else {
                        typingNames.push(packageJson.name);
                    }
                }
                mergeTypings(typingNames);
            }
272552
function getConfig() {
    var fs = require('fs');
    if (fs.existsSync(controllerDir + '/conf/' + appName + '.json')) {
        return JSON.parse(fs.readFileSync(controllerDir + '/conf/' + appName + '.json'));
    } else if (fs.existsSync(controllerDir + '/conf/' + appName.toLowerCase() + '.json')) {
        return JSON.parse(fs.readFileSync(controllerDir + '/conf/' + appName.toLowerCase() + '.json'));
    } else {
        throw new Error('Cannot find ' + controllerDir + '/conf/' + appName + '.json');
    }
}
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;
}
229016
function () {
  var shrinkWrapPath = path.resolve(process.cwd(), 'npm-shrinkwrap.json');
  if (fs.existsSync(shrinkWrapPath)) {
    logger.logInfo('[npm] using npm-shrinkwrap.json instead of package.json');
    return shrinkWrapPath;
  }

  if (getNpmMajorVersion() >= 5) {
      var packageLockPath = path.resolve(process.cwd(), 'package-lock.json');
      if (fs.existsSync(packageLockPath)) {
          logger.logInfo('[npm] using package-lock.json instead of package.json');
          return packageLockPath;
      }
  }

  var packagePath = path.resolve(process.cwd(), 'package.json');
  return packagePath;
}
468896
function loadConfig(done) {
  fs.stat('package.json', function(err) {
    if (err) return done(undefined, {});
    fs.readFile('package.json', function(err, contents) {
      if (err) return done(err);
      try {
        done(undefined, JSON.parse(contents).config || {});
      } catch(err) {
        done(err);
      }
    });
  });
}
259678
function config(opts) {
  if (!opts) return;
  if (opts.baseUrl) _baseUrl = parse(opts.baseUrl).bareId + '/';

  if (opts.paths) {
    Object.keys(opts.paths).forEach(path => {
      let alias = opts.paths[path];
      _paths[cleanPath(path)] = cleanPath(alias);
    });
  }

  if (opts.bundles) {
    Object.keys(opts.bundles).forEach(bundleName => {
      const spaces = opts.bundles[bundleName];
      if (Array.isArray(spaces)) {
        _bundles[bundleName] = {
          user: arrayToHash(spaces),
          package: arrayToHash([])
        };
      } else {
        _bundles[bundleName] = {
          nameSpace: spaces.nameSpace || null,
          user: arrayToHash(spaces.user || []),
          package: arrayToHash(spaces.package || [])
        };
      }
    });
  }
}
759499
def read_config(path=None, final=False):
    """"""
    try:
        with open(config_path(path, final=final), 'r') as configfile:
            return yaml.safe_load(configfile) or {}
    except FileNotFoundError:
        return {}
928308
async function getAdditionalFiles(config, packageFiles) {
  logger.trace({ config }, 'getAdditionalFiles');
  const artifactErrors = [];
  const updatedArtifacts = [];
  if (!(packageFiles.npm && packageFiles.npm.length)) {
    return { artifactErrors, updatedArtifacts };
  }
  if (!config.updateLockFiles) {
    logger.info('Skipping lock file generation');
    return { artifactErrors, updatedArtifacts };
  }
  logger.debug('Getting updated lock files');
  if (
    config.updateType === 'lockFileMaintenance' &&
    config.parentBranch &&
    (await platform.branchExists(config.branchName))
  ) {
    logger.debug('Skipping lockFileMaintenance update');
    return { artifactErrors, updatedArtifacts };
  }
  const dirs = module.exports.determineLockFileDirs(config, packageFiles);
  logger.debug({ dirs }, 'lock file dirs');
  await module.exports.writeExistingFiles(config, packageFiles);
  await module.exports.writeUpdatedPackageFiles(config, packageFiles);

  process.env.NPM_CONFIG_CACHE =
    process.env.NPM_CONFIG_CACHE || upath.join(config.cacheDir, './others/npm');
  await fs.ensureDir(process.env.NPM_CONFIG_CACHE);
  process.env.YARN_CACHE_FOLDER =
    process.env.YARN_CACHE_FOLDER ||
    upath.join(config.cacheDir, './others/yarn');
  await fs.ensureDir(process.env.YARN_CACHE_FOLDER);
  process.env.npm_config_store =
    process.env.npm_config_store ||
    upath.join(config.cacheDir, './others/pnpm');
  await fs.ensureDir(process.env.npm_config_store);

  const env =
    global.trustLevel === 'high'
      ? process.env
      : {
          HOME: process.env.HOME,
          PATH: process.env.PATH,
          NPM_CONFIG_CACHE: process.env.NPM_CONFIG_CACHE,
          YARN_CACHE_FOLDER: process.env.YARN_CACHE_FOLDER,
          npm_config_store: process.env.npm_config_store,
        };
  env.NODE_ENV = 'dev';

  let token = '';
  try {
    ({ token } = hostRules.find({ platform: config.platform }));
    token += '@';
  } catch (err) {
    logger.warn({ err }, 'Error getting token for packageFile');
  }
  for (const lockFile of dirs.npmLockDirs) {
    const lockFileDir = path.dirname(lockFile);
    const fileName = path.basename(lockFile);
    logger.debug(`Generating ${fileName} for ${lockFileDir}`);
    const upgrades = config.upgrades.filter(
      upgrade => upgrade.npmLock === lockFile
    );
    const res = await npm.generateLockFile(
      upath.join(config.localDir, lockFileDir),
      env,
      fileName,
      config,
      upgrades
    );
    if (res.error) {
      // istanbul ignore if
      if (res.stderr && res.stderr.includes('No matching version found for')) {
        for (const upgrade of config.upgrades) {
          if (
            res.stderr.includes(
              `No matching version found for ${upgrade.depName}`
            )
          ) {
            logger.info(
              { dependency: upgrade.depName, type: 'npm' },
              'lock file failed for the dependency being updated - skipping branch creation'
            );
            throw new Error('registry-failure');
          }
        }
      }
      artifactErrors.push({
        lockFile,
        stderr: res.stderr,
      });
    } else {
      const existingContent = await platform.getFile(
        lockFile,
        config.parentBranch
      );
      if (res.lockFile !== existingContent) {
        logger.debug(`${lockFile} needs updating`);
        updatedArtifacts.push({
          name: lockFile,
          contents: res.lockFile.replace(new RegExp(`${token}`, 'g'), ''),
        });
      } else {
        logger.debug(`${lockFile} hasn't changed`);
      }
    }
  }

  for (const lockFile of dirs.yarnLockDirs) {
    const lockFileDir = path.dirname(lockFile);
    logger.debug(`Generating yarn.lock for ${lockFileDir}`);
    const lockFileName = upath.join(lockFileDir, 'yarn.lock');
    const upgrades = config.upgrades.filter(
      upgrade => upgrade.yarnLock === lockFile
    );
    const res = await yarn.generateLockFile(
      upath.join(config.localDir, lockFileDir),
      env,
      config,
      upgrades
    );
    if (res.error) {
      // istanbul ignore if
      if (res.stderr && res.stderr.includes(`Couldn't find any versions for`)) {
        for (const upgrade of config.upgrades) {
          /* eslint-disable no-useless-escape */
          if (
            res.stderr.includes(
              `Couldn't find any versions for \\\"${upgrade.depName}\\\"`
            )
          ) {
            logger.info(
              { dependency: upgrade.depName, type: 'yarn' },
              'lock file failed for the dependency being updated - skipping branch creation'
            );
            throw new Error('registry-failure');
          }
          /* eslint-enable no-useless-escape */
        }
      }
      artifactErrors.push({
        lockFile,
        stderr: res.stderr,
      });
    } else {
      const existingContent = await platform.getFile(
        lockFileName,
        config.parentBranch
      );
      if (res.lockFile !== existingContent) {
        logger.debug('yarn.lock needs updating');
        updatedArtifacts.push({
          name: lockFileName,
          contents: res.lockFile,
        });
      } else {
        logger.debug("yarn.lock hasn't changed");
      }
    }
  }

  for (const lockFile of dirs.pnpmShrinkwrapDirs) {
    const lockFileDir = path.dirname(lockFile);
    logger.debug(`Generating pnpm-lock.yaml for ${lockFileDir}`);
    const res = await pnpm.generateLockFile(
      upath.join(config.localDir, lockFileDir),
      env,
      config.binarySource
    );
    if (res.error) {
      // istanbul ignore if
      if (res.stdout && res.stdout.includes(`No compatible version found:`)) {
        for (const upgrade of config.upgrades) {
          if (
            res.stdout.includes(
              `No compatible version found: ${upgrade.depName}`
            )
          ) {
            logger.info(
              { dependency: upgrade.depName, type: 'pnpm' },
              'lock file failed for the dependency being updated - skipping branch creation'
            );
            throw new Error('registry-failure');
          }
        }
      }
      artifactErrors.push({
        lockFile,
        stderr: res.stderr,
      });
    } else {
      const existingContent = await platform.getFile(
        lockFile,
        config.parentBranch
      );
      if (res.lockFile !== existingContent) {
        logger.debug('pnpm-lock.yaml needs updating');
        updatedArtifacts.push({
          name: lockFile,
          contents: res.lockFile,
        });
      } else {
        logger.debug("pnpm-lock.yaml hasn't changed");
      }
    }
  }

  for (const lernaDir of dirs.lernaDirs) {
    let lockFile;
    logger.debug(`Finding package.json for lerna directory "${lernaDir}"`);
    const lernaPackageFile = packageFiles.npm.find(
      p => path.dirname(p.packageFile) === lernaDir
    );
    if (!lernaPackageFile) {
      logger.debug('No matching package.json found');
      throw new Error('lerna-no-lockfile');
    }
    if (lernaPackageFile.lernaClient === 'npm') {
      lockFile = config.npmLock || 'package-lock.json';
    } else {
      lockFile = config.yarnLock || 'yarn.lock';
    }
    const skipInstalls =
      lockFile === 'npm-shrinkwrap.json' ? false : config.skipInstalls;
    const res = await lerna.generateLockFiles(
      lernaPackageFile.lernaClient,
      upath.join(config.localDir, lernaDir),
      env,
      skipInstalls,
      config.binarySource
    );
    // istanbul ignore else
    if (res.error) {
      // istanbul ignore if
      if (
        res.stderr &&
        res.stderr.includes('ENOSPC: no space left on device')
      ) {
        throw new Error('disk-space');
      }
      for (const upgrade of config.upgrades) {
        /* eslint-disable no-useless-escape */
        if (
          res.stderr.includes(
            `Couldn't find any versions for \\\"${upgrade.depName}\\\"`
          )
        ) {
          logger.info(
            { dependency: upgrade.depName, type: 'yarn' },
            'lock file failed for the dependency being updated - skipping branch creation'
          );
          throw new Error('registry-failure');
        }
        /* eslint-enable no-useless-escape */
        if (
          res.stderr.includes(
            `No matching version found for ${upgrade.depName}`
          )
        ) {
          logger.info(
            { dependency: upgrade.depName, type: 'npm' },
            'lock file failed for the dependency being updated - skipping branch creation'
          );
          throw new Error('registry-failure');
        }
      }
      artifactErrors.push({
        lockFile,
        stderr: res.stderr,
      });
    } else {
      for (const packageFile of packageFiles.npm) {
        const filename = packageFile.npmLock || packageFile.yarnLock;
        logger.trace('Checking for ' + filename);
        const existingContent = await platform.getFile(
          filename,
          config.parentBranch
        );
        if (existingContent) {
          logger.trace('Found lock file');
          const lockFilePath = upath.join(config.localDir, filename);
          logger.trace('Checking against ' + lockFilePath);
          try {
            let newContent;
            try {
              newContent = await fs.readFile(lockFilePath, 'utf8');
            } catch (err) {
              newContent = await fs.readFile(
                lockFilePath.replace('npm-shrinkwrap.json', 'package-lock.json')
              );
            }
            if (newContent !== existingContent) {
              logger.debug('File is updated: ' + lockFilePath);
              updatedArtifacts.push({
                name: filename,
                contents: newContent,
              });
            } else {
              logger.trace('File is unchanged');
            }
          } catch (err) {
            if (config.updateType === 'lockFileMaintenance') {
              logger.info(
                { packageFile, lockFilePath },
                'No lock file found after lerna lockFileMaintenance'
              );
            } else {
              logger.warn(
                { packageFile, lockFilePath },
                'No lock file found after lerna bootstrap'
              );
            }
          }
        } else {
          logger.trace('No lock file found');
        }
      }
    }
  }

  return { artifactErrors, updatedArtifacts };
}
202856
function getNPM() {
    Object.keys(require.cache).forEach(function (key) {
        delete require.cache[key];
    });
    var NPM = require('npm');
    return NPM;
}
1237662
function readConfig() {
  let options = {}
  let cFile = ''

  if (program.config) {
    cFile = path.resolve(cwd, program.config)
    if (fs.existsSync(cFile)) {
      Object.assign(config, require(cFile))
    } else {
      console.warn(`Cannot find configuration file ${program.config}`)
      process.exit()
    }
  } else {
    cFile = path.resolve(cwd, 'deploy.js')
  }

  if (fs.existsSync(cFile)) {
    options = require(cFile)
  }

  ;['server', 'ignore'].forEach(function(name) {
    if (typeof program[name] !== 'undefined') {
      options[name] = program[name]
    }
  })

  if (program.args[0]) {
    options.workspace = path.resolve(cwd, program.args[0])
  }

  if (program.args[1]) {
    options.deployTo = program.args[1]
  }

  return options
}
989058
def config_(name: str, local: bool, package: str, section: str,
            key: Optional[str]):
    """"""
    cfg = config.read_configs(package, name, local=local)
    if key:
        with suppress(NoOptionError, NoSectionError):
            echo(cfg.get(section, key))
    else:
        with suppress(NoSectionError):
            for opt in cfg.options(section):
                colourise.pinfo(opt)
                echo('    {}'.format(cfg.get(section, opt)))
779041
function (options, callback) {
  var withAsar = path.join(options.src, 'resources/app.asar')
  var withoutAsar = path.join(options.src, 'resources/app/package.json')

  try {
    fs.accessSync(withAsar)
    options.logger('Reading package metadata from ' + withAsar)
    callback(null, JSON.parse(asar.extractFile(withAsar, 'package.json')))
    return
  } catch (err) {
  }

  try {
    options.logger('Reading package metadata from ' + withoutAsar)
    callback(null, fs.readJsonSync(withoutAsar))
  } catch (err) {
    callback(new Error('Error reading package metadata: ' + (err.message || err)))
  }
}
404986
def get_build_configuration(id=None, name=None):
    
    data = get_build_configuration_raw(id, name)
    if data:
        return utils.format_json(data)
537967
function getConfig(api /*: any */) /*: BabelCoreOptions */ {
  api.cache.never();

  return {
    babelrc: false,
    presets: presets.map(preset => require.resolve(preset)),
    plugins: plugins.map(plugin => require.resolve(plugin)),
  };
}