Checks for package.json or npm-shrinkwrap.json inside a list of files and
expands the list of files to include package dependencies if so.
354607
function expandFiles(files, workingDirectory) {
  const promises = [];
  files.forEach((file) => {
    if (
      file.path !== './package.json' && file.path !== './npm-shrinkwrap.json'
    ) {
      promises.push(Promise.resolve(file));
      return;
    }
    findPackageDependencies(workingDirectory, true).forEach((dep) => {
      let resolvedPath;
      try {
        resolvedPath = forwardSlashes(path.relative(
          workingDirectory,
          requireRelative.resolve(dep, workingDirectory),
        ));
        if (!resolvedPath.startsWith('.')) {
          // path.relative won't add "./", but we need it further down the line
          resolvedPath = `./${resolvedPath}`;
        }
      } catch (e) {
        winston.error(`Failed to resolve "${dep}" relative to ${workingDirectory}`);
        return;
      }

      promises.push(lastUpdate.failSafe(resolvedPath, workingDirectory)
        .then(({ mtime }) =>
          Promise.resolve({
            path: resolvedPath,
            mtime,
            packageName: dep,
          })));
    });
  });
  return Promise.all(promises);
}
62616
function requirePackage(pkg, mainjs) {
			var processed = {};
			var pkgName = path.basename(pkg);
			var code = grunt.file.read(mainjs);
			while (true) {
				var requires = detective(code);
				if (!requires.length) break;
				for (var requireIdx in requires) {
					var name = requires[requireIdx];
					var requiredCode = '';
					if (!processed[name]) {
						var filepath = path.join(pkg, 'lib', name.replace(pkgName + '/', '') + '.js');
						requiredCode = grunt.file.read(filepath);
						processed[name] = true;
					}
					code = code.replace(new RegExp('require\\([\\\'\"]' + name + '[\\\'\"]\\);?'), requiredCode);
				}
			}
			return code;
		}
831859
function dependencyLink (pkg, cb) {
  var dependencies = path.join(npm.dir, pkg.name, pkg.version, "node_modules")
    , depBin = path.join(npm.dir, pkg.name, pkg.version, "dep-bin")
  asyncMap(pkg._resolvedDeps, function (dep, cb) {
    log.silly(dep, "dependency")
    var fromRoot = path.join(npm.dir, dep.name, dep.version)
      , dependsOn = path.join( npm.dir, pkg.name, pkg.version
                             , "dependson", dep.name + "@" + dep.version
                             )
    link(fromRoot, dependsOn, cb)
  }, function (dep, cb) {
    var depDir = path.join(npm.dir, dep.name, dep.version, "package")
    readJson(path.join(depDir, "package.json"), function (er, dep) {
      if (er) return cb(er)
      loadPackageDefaults(dep, function (er, dep) {
        if (er) return cb(er)
        asyncMap([dep], function (dep) {
          var toLib = path.join(dependencies, dep.name)
          linkModules(dep, toLib, cb)
        }, function (dep, cb) {
          // link the bins to this pkg's "dep-bin" folder.
          linkBins(dep, depBin, false, cb)
        }, cb)
      })
    })
  }, cb)
}
548160
function requireDependencies(dependencies) {
    var callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;

    var promise = new _es6Promise.Promise(function (succeed, fail) {
        var requirements = {};

        // no requirements
        if (!(dependencies instanceof Array)) {
            return succeed(requirements);
        }

        // check if succeeded
        function checkStatus() {
            if (Object.keys(requirements).length === dependencies.length) {
                succeed(requirements);
            }
        }

        dependencies.forEach(function (dependency) {
            if (packages.has(dependency)) {
                requirements[dependency] = packages.get(dependency);
            } else {
                events.once("load:" + dependency, function (requirement) {
                    requirements[dependency] = requirement;
                    checkStatus();
                });
            }
        });

        // First check
        checkStatus();
    });

    return typeof callback === "function" ? promise.then(callback) : promise;
}
1206512
function forcedByDependencies(filename) {
	if (!/\.ts$/.test(filename)) return null;
	var fs = require('fs');
	var fsp = require('path');
	function loadPackage(dir) {
		var path = fsp.join(dir, 'package.json');
		if (fs.existsSync(path)) return require(path);
		var ndir = fsp.join(dir, '..');
		if (ndir.length < dir.length && !/[\\\/]node_modules$/.test(ndir)) return loadPackage(ndir);
		else return null;
	}
	var pkg = loadPackage(fsp.resolve(fsp.dirname(filename)));
	if (!pkg) return false;
	return Object.keys(pkg.dependencies || {}).indexOf('streamline-runtime') >= 0 ||
		Object.keys(pkg.devDependencies || {}).indexOf('streamline-runtime') >= 0;
}
559486
function createPackageJson (name) {
  const { version, devDependencies } = require('../package.json')
  return {
    name,
    private: true,
    main: 'index.js',
    scripts: {
      start: 'node ./index.js',
      test: 'jest'
    },
    dependencies: {
      'actions-toolkit': `^${version}`
    },
    devDependencies: {
      jest: devDependencies.jest
    }
  }
}
77548
function findPackages(packagesPath) {
  return fs.readdirSync(packagesPath).reduce((acc, d) => {
    const fullpath = path.resolve(packagesPath, d);

    if (fs.statSync(fullpath).isDirectory()) {
      try {
        fs.statSync(path.resolve(fullpath, 'package.json'));
        acc.push(fullpath);
      }
      catch (err) {
        if (err.code === 'ENOENT') {
          return acc.concat(findPackages(fullpath));
        }
        throw err;
      }
    }

    return acc;
  }, []);
}
365961
function getPackageRoot (dir) {
    let lastDir = null;
    while (lastDir !== dir && !fs.existsSync(path.resolve(dir, "./package.json"))) {
        lastDir = dir;
        dir = path.dirname(dir);
    }
    return (lastDir === dir ? null : dir);
}
1123011
function findPackage(dir, packageName) {
    let d = dir || '.';
    do {
        let f = path.join(d, 'package.json');
        if ( fs.existsSync(f) ) {
            // require(f) would look for paths relative to this module,
            // but we need it to be relative to process.cwd()
            if ( !path.isAbsolute(f) ) {
                f = fs.realpathSync(f);
            }
            const p = requireJSON(f);
            // Look for a specific project name
            if ( packageName ) {
                if ( p ) {
                    if ( p.name == packageName ) {
                        return f;
                    }
                }
            }
            // Look for any project except this one (verup)
            else {
                if ( p ) {
                    if ( (p.extra && p.extra.verup || p.verup) && p.name != 'verup' ) {
                        return f;
                    }
                }
            }
        }
        dir = d;
        d = path.join(d, '..');
    } while (d != dir && dir.slice(0,2) != '..');
    return false;
}
133047
function (done) {
      var p = clone(pkg);
      delete p.devDependencies;
      var content = JSON.stringify(p, null, 2);
      write_if_not_exists('package.json', content, done);
    }
266924
function addNotPackPluginRes(target, resFiles) {
    resFiles.forEach(function (item) {
        if (target.indexOf(item) === -1) {
            target.push(item);
        }
    });
}
812356
function(files, options) {
    verbose.writeln('Using srcPrefix: ' + options.srcPrefix)
    verbose.writeln('Using destPrefix: ' + options.destPrefix)

    // Build the file list
    files = convert(files)

    // Copy files
    if (!copy(files, options)) {
      fail.warn('Nothing was copied for the "' + this.target + '" target')
    }

    // Report if any dependencies have not been copied
    ensure(files, options)
  }
1190150
function(next) {
            core.allowPackages.forEach(function(pkg) {
                try {
                    var mod = path.dirname(require.resolve(pkg)).replace(/\/lib$/, "");
                    core.packages[pkg] = { path: mod };
                    if (lib.statSync(mod + "/etc").isDirectory()) {
                        core.packages[pkg].etc = 1;
                        var cfg = lib.readFileSync(mod + "/etc/config");
                        if (cfg) {
                            config = cfg + "\n" + config;
                            core.packages[pkg].config = 1;
                            core.parseConfig(cfg, 1);
                        }
                    }
                    ["modules","locales","views","web"].forEach(function(x) {
                        if (lib.statSync(mod + "/" + x).isDirectory()) {
                            core.path[x].unshift(mod + "/" + x);
                            core.packages[pkg][x] = 1;
                        }
                    });
                    logger.debug("init:", "npm package:", pkg, core.packages[pkg]);
                } catch(e) {
                    logger.error("init:", "npm package:", pkg, e);
                }
            });
            next();
        }
15340
function addModulesToPackageJson(externalModules, packageJson, pathToPackageRoot) {
  _.forEach(externalModules, externalModule => {
    const splitModule = _.split(externalModule, '@');
    // If we have a scoped module we have to re-add the @
    if (_.startsWith(externalModule, '@')) {
      splitModule.splice(0, 1);
      splitModule[0] = '@' + splitModule[0];
    }
    let moduleVersion = _.join(_.tail(splitModule), '@');
    // We have to rebase file references to the target package.json
    moduleVersion = rebaseFileReferences(pathToPackageRoot, moduleVersion);
    packageJson.dependencies = packageJson.dependencies || {};
    packageJson.dependencies[_.first(splitModule)] = moduleVersion;
  });
}
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 };
}
236354
def verify(package_json)
      inspect(package_json).each do |suspicious|
        warn(
          "`#{suspicious[:package]}` doesn't specify fixed version number",
          file: package_json,
          line: suspicious[:line]
        )
      end
    end
1146377
function(context, pkg, isRoot) {
		var deps = crawl.getDependencies(context.loader, pkg, isRoot);

		return Promise.all(utils.filter(utils.map(deps, function(childPkg){
			return crawl.fetchDep(context, pkg, childPkg, isRoot);
		}), truthy)).then(function(packages){
 			// at this point all dependencies of pkg have been loaded, it's ok to get their children

			return Promise.all(utils.map(packages, function(childPkg){
				// Also load 'steal' so that the builtins will be configured
				if(childPkg && childPkg.name === 'steal') {
					return crawl.deps(context, childPkg);
				}
			})).then(function(){
				return packages;
			});
		});
	}