Turn webpack-config-plugin packages into installable .tgz files
182020
async function buildUnreleasedPackages() {
	const cwdBefore = process.cwd();
	const unreleasedPackagesSourceFolder = path.resolve(__dirname, '../../packages/');
	const unreleasedPackagesDistFolder = path.resolve(__dirname, '../packages');
	await rimrafAsync(unreleasedPackagesDistFolder);
	await mkdirAsync(unreleasedPackagesDistFolder);
	process.chdir(unreleasedPackagesDistFolder);
	console.log('🎁  Packing current packages');
	await Promise.all(
		fs
			.readdirSync(unreleasedPackagesSourceFolder)
			.filter((packageName) => fs.statSync(path.join(unreleasedPackagesSourceFolder, packageName)).isDirectory())
			.map((packageName) => execAsync(`npm pack "${path.resolve(__dirname, '../../packages/' + packageName)}"`))
	);
	// Remove version number from file name
	await Promise.all(
		fs
			.readdirSync(unreleasedPackagesDistFolder)
			.filter((tarPackageName) => /\.tgz/.test(tarPackageName))
			.map((tarPackageName) =>
				renameAsync(
					path.join(unreleasedPackagesDistFolder, tarPackageName),
					path.join(unreleasedPackagesDistFolder, tarPackageName.replace(/\-\d[^-]+$/, '.tgz'))
				)
			)
	);

	process.chdir(cwdBefore);
}
875161
def MakeDeployableBinary(self, template_path, output_path):
    """"""
    buildpackage_binary = "/usr/bin/dpkg-buildpackage"
    if not os.path.exists(buildpackage_binary):
      logging.error("dpkg-buildpackage not found, unable to repack client.")
      return

    with utils.TempDirectory() as tmp_dir:
      template_dir = os.path.join(tmp_dir, "dist")
      utils.EnsureDirExists(template_dir)

      zf = zipfile.ZipFile(template_path)
      for name in zf.namelist():
        dirname = os.path.dirname(name)
        utils.EnsureDirExists(os.path.join(template_dir, dirname))
        with open(os.path.join(template_dir, name), "wb") as fd:
          fd.write(zf.read(name))

      # Generate the dpkg files.
      self.GenerateDPKGFiles(tmp_dir)

      # Create a client config.
      client_context = ["Client Context"] + self.context
      client_config_content = self.GetClientConfig(client_context)

      # We need to strip leading /'s or .join will ignore everything that comes
      # before it.
      target_dir = config.CONFIG.Get(
          "ClientBuilder.target_dir", context=self.context).lstrip("/")
      agent_dir = os.path.join(
          template_dir, "debian",
          config.CONFIG.Get("ClientBuilder.package_name", context=self.context),
          target_dir)

      with open(
          os.path.join(
              agent_dir,
              config.CONFIG.Get(
                  "ClientBuilder.config_filename", context=self.context)),
          "wb") as fd:
        fd.write(client_config_content)

      # Set the daemon to executable.
      os.chmod(
          os.path.join(
              agent_dir,
              config.CONFIG.Get("Client.binary_name", context=self.context)),
          0o755)

      arch = config.CONFIG.Get("Template.arch", context=self.context)

      try:
        old_working_dir = os.getcwd()
      except OSError:
        old_working_dir = os.environ.get("HOME", "/tmp")

      try:
        os.chdir(template_dir)
        command = [buildpackage_binary, "-uc", "-d", "-b", "-a%s" % arch]

        try:
          subprocess.check_output(command, stderr=subprocess.STDOUT)
        except subprocess.CalledProcessError as e:
          if "Failed to sign" not in e.output:
            logging.error("Error calling %s.", command)
            logging.error(e.output)
            raise

        filename_base = config.CONFIG.Get(
            "ClientBuilder.debian_package_base", context=self.context)
        output_base = config.CONFIG.Get(
            "ClientRepacker.output_basename", context=self.context)
      finally:
        try:
          os.chdir(old_working_dir)
        except OSError:
          pass

      utils.EnsureDirExists(os.path.dirname(output_path))

      for extension in [
          ".changes",
          config.CONFIG.Get(
              "ClientBuilder.output_extension", context=self.context)
      ]:
        input_name = "%s%s" % (filename_base, extension)
        output_name = "%s%s" % (output_base, extension)

        # TODO(user):pytype: incorrect move() definition in typeshed.
        # pytype: disable=wrong-arg-types
        shutil.move(
            os.path.join(tmp_dir, input_name),
            os.path.join(os.path.dirname(output_path), output_name))
        # pytype: enable=wrong-arg-types

      logging.info("Created package %s", output_path)
      return output_path
987050
function createWebpack ({ alias = {}, context, name = 'index' }) {
  const pkgJson = require(path.join(context, 'package.json'));
  const ENV = process.env.NODE_ENV || 'development';
  const isProd = ENV === 'production';
  const hasPublic = fs.existsSync(path.join(context, 'public'));
  const plugins = hasPublic
    ? [new CopyWebpackPlugin([{ from: 'public' }])]
    : [];

  return {
    context,
    devtool: isProd ? 'source-map' : 'cheap-eval-source-map',
    entry: [
      `./src/${name}.tsx`,
      isProd
        ? null
        : 'webpack-plugin-serve/client'
    ].filter((entry) => entry),
    mode: ENV,
    output: {
      chunkFilename: `[name].[chunkhash:8].js`,
      filename: `[name].[hash:8].js`,
      globalObject: `(typeof self !== 'undefined' ? self : this)`,
      path: path.join(context, 'build')
    },
    resolve: {
      alias,
      extensions: ['.js', '.jsx', '.ts', '.tsx']
    },
    module: {
      rules: [
        {
          test: /\.css$/,
          exclude: /(node_modules)/,
          use: [
            isProd
              ? MiniCssExtractPlugin.loader
              : require.resolve('style-loader'),
            {
              loader: require.resolve('css-loader'),
              options: {
                importLoaders: 1
              }
            },
            {
              loader: require.resolve('postcss-loader'),
              options: {
                ident: 'postcss',
                plugins: () => [
                  require('precss'),
                  require('autoprefixer'),
                  require('postcss-simple-vars'),
                  require('postcss-nested'),
                  require('postcss-import'),
                  require('postcss-clean')(),
                  require('postcss-flexbugs-fixes')
                ]
              }
            }
          ]
        },
        {
          test: /\.css$/,
          include: /node_modules/,
          use: [
            isProd
              ? MiniCssExtractPlugin.loader
              : require.resolve('style-loader'),
            require.resolve('css-loader')
          ]
        },
        {
          test: /\.(js|ts|tsx)$/,
          exclude: /(node_modules)/,
          use: [
            require.resolve('thread-loader'),
            {
              loader: require.resolve('babel-loader'),
              options: require('@polkadot/dev-react/config/babel')
            }
          ]
        },
        {
          test: /\.md$/,
          use: [
            require.resolve('html-loader'),
            require.resolve('markdown-loader')
          ]
        },
        {
          test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
          use: [
            {
              loader: require.resolve('url-loader'),
              options: {
                limit: 10000,
                name: 'static/[name].[hash:8].[ext]'
              }
            }
          ]
        },
        {
          test: [/\.eot$/, /\.ttf$/, /\.svg$/, /\.woff$/, /\.woff2$/],
          use: [
            {
              loader: require.resolve('file-loader'),
              options: {
                name: 'static/[name].[hash:8].[ext]'
              }
            }
          ]
        }
      ]
    },
    node: {
      child_process: 'empty',
      dgram: 'empty',
      fs: 'empty',
      net: 'empty',
      tls: 'empty'
    },
    optimization: {
      runtimeChunk: 'single',
      splitChunks: {
        cacheGroups: {
          vendorOther: {
            chunks: 'initial',
            enforce: true,
            name: 'vendor',
            test: /node_modules\/(asn1|bn\.js|buffer|cuint|elliptic|lodash|moment|readable-stream|rxjs)/
          },
          vendorReact: {
            chunks: 'initial',
            enforce: true,
            name: 'react',
            test: /node_modules\/(chart|i18next|react|semantic-ui)/
          },
          polkadotJs: {
            chunks: 'initial',
            enforce: true,
            name: 'polkadotjs',
            test: /node_modules\/(@polkadot\/wasm-(crypto|dalek-ed25519|schnorrkel))/
          }
        }
      }
    },
    performance: {
      hints: false
    },
    plugins: plugins.concat([
      new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
      new webpack.DefinePlugin({
        'process.env': {
          NODE_ENV: JSON.stringify(ENV),
          VERSION: JSON.stringify(pkgJson.version),
          WS_URL: JSON.stringify(process.env.WS_URL)
        }
      }),
      new HtmlWebpackPlugin({
        inject: true,
        template: path.join(context, `${hasPublic ? 'public/' : ''}${name}.html`),
        PAGE_TITLE: 'Polkadot/Substrate Portal'
      }),
      new webpack.optimize.SplitChunksPlugin(),
      new MiniCssExtractPlugin({
        filename: `[name].[contenthash:8].css`
      }),
      isProd
        ? null
        : new WebpackPluginServe({
          port: 3000,
          static: path.join(process.cwd(), '/build')
        })
    ]).filter((plugin) => plugin),
    watch: !isProd
  };
}
816310
function createWebpackLessPlugin(loaderContext) {
  const { fs } = loaderContext;
  const resolve = pify(loaderContext.resolve.bind(loaderContext));
  const loadModule = pify(loaderContext.loadModule.bind(loaderContext));
  const readFile = pify(fs.readFile.bind(fs));

  class WebpackFileManager extends less.FileManager {
    supports() {
      // Our WebpackFileManager handles all the files
      return true;
    }

    // Sync resolving is used at least by the `data-uri` function.
    // This file manager doesn't know how to do it, so let's delegate it
    // to the default file manager of Less.
    // We could probably use loaderContext.resolveSync, but it's deprecated,
    // see https://webpack.js.org/api/loaders/#this-resolvesync
    supportsSync() {
      return false;
    }

    loadFile(filename, currentDirectory, options) {
      let url;
      if (less.version[0] >= 3) {
        if (options.ext && !isModuleName.test(filename)) {
          url = this.tryAppendExtension(filename, options.ext);
        } else {
          url = filename;
        }
      } else {
        url = filename.replace(matchMalformedModuleFilename, '$1');
      }
      const moduleRequest = loaderUtils.urlToRequest(
        url,
        url.charAt(0) === '/' ? '' : null
      );
      // Less is giving us trailing slashes, but the context should have no trailing slash
      const context = currentDirectory.replace(trailingSlash, '');
      let resolvedFilename;

      return resolve(context, moduleRequest)
        .then((f) => {
          resolvedFilename = f;
          loaderContext.addDependency(resolvedFilename);

          if (isLessCompatible.test(resolvedFilename)) {
            return readFile(resolvedFilename).then((contents) =>
              contents.toString('utf8')
            );
          }

          return loadModule([stringifyLoader, resolvedFilename].join('!')).then(
            JSON.parse
          );
        })
        .then((contents) => {
          return {
            contents,
            filename: resolvedFilename,
          };
        });
    }
  }

  return {
    install(lessInstance, pluginManager) {
      pluginManager.addFileManager(new WebpackFileManager());
    },
    minVersion: [2, 1, 1],
  };
}
433855
def package(options):
    
    import pkg_resources
    import tarfile
    import geonode

    version = geonode.get_version()
    # Use GeoNode's version for the package name.
    pkgname = 'GeoNode-%s-all' % version

    # Create the output directory.
    out_pkg = path(pkgname)
    out_pkg_tar = path("%s.tar.gz" % pkgname)

    # Create a distribution in zip format for the geonode python package.
    dist_dir = path('dist')
    dist_dir.rmtree()
    sh('python setup.py sdist --formats=zip')

    with pushd('package'):

        #Delete old tar files in that directory
        for f in glob.glob('GeoNode*.tar.gz'):
            old_package = path(f)
            if old_package != out_pkg_tar:
                old_package.remove()

        if out_pkg_tar.exists():
            info('There is already a package for version %s' % version)
            return

        # Clean anything that is in the oupout package tree.
        out_pkg.rmtree()
        out_pkg.makedirs()

        support_folder = path('support')
        install_file = path('install.sh')

        # And copy the default files from the package folder.
        justcopy(support_folder, out_pkg / 'support')
        justcopy(install_file, out_pkg)

        geonode_dist = path('..') / 'dist' / 'GeoNode-%s.zip' % version
        justcopy(geonode_dist, out_pkg)

        rogue_dist = path('../..') / 'dist' / 'geoshape-0.1.zip'
        justcopy(rogue_dist, out_pkg)

        # Create a tar file with all files in the output package folder.
        tar = tarfile.open(out_pkg_tar, "w:gz")
        for file in out_pkg.walkfiles():
            tar.add(file)

        # Add the README with the license and important links to documentation.
        tar.add('README', arcname=('%s/README.md' % out_pkg))
        tar.close()

        # Remove all the files in the temporary output package directory.
        out_pkg.rmtree()

    # Report the info about the new package.
    info("%s created" % out_pkg_tar.abspath())
625560
function install(context) {
    // set properties
    const q = context.requireCordovaModule("q");
    var async = new q.defer(); // eslint-disable-line
    const installFlagLocation = path.join(
      context.opts.projectRoot,
      "plugins",
      context.opts.plugin.id,
      INSTALLFLAGNAME
    );
    const dependencies = require(path.join(
      context.opts.projectRoot,
      "plugins",
      context.opts.plugin.id,
      "package.json"
    )).dependencies;

    // only run once
    if (getPackageInstalled(installFlagLocation)) return;

    // install node modules
    const modules = getNodeModulesToInstall(dependencies);
    if (modules.length === 0) return async.promise;

    installNodeModules(modules, () => {
      // only run once
      setPackageInstalled(installFlagLocation);
      removeEtcDirectory();
      async.resolve();
    });

    // wait until callbacks from the all the npm install complete
    return async.promise;
  }
897611
def __unpack_tgz(self, filename):
        """"""
        if isinstance(filename, string_types) and self.__isValidTGZ(filename) and tarfile.is_tarfile(filename):
            with tarfile.open(filename, mode='r:gz') as t:
                for name in t.getnames():
                    t.extract(name, self.plugin_abspath)
        else:
            raise TarError("Invalid Plugin Compressed File")
1309816
function overrideWebpack({ plugin, options }, cracoConfig, webpackConfig, context) {
    if (isFunction(plugin.overrideWebpackConfig)) {
        const resultingConfig = plugin.overrideWebpackConfig({
            cracoConfig: cracoConfig,
            webpackConfig: webpackConfig,
            pluginOptions: options,
            context: context
        });

        if (!resultingConfig) {
            throw new Error("craco: Plugin returned an undefined webpack config.");
        }
    }

    log("Overrided webpack config with plugin.");

    return webpackConfig;
}
383517
function getPackageName(installPackage) {
  if (installPackage.match(/^.+\.(tgz|tar\.gz)$/)) {
    return getTemporaryDirectory()
      .then(obj => {
        let stream;
        if (/^http/.test(installPackage)) {
          stream = hyperquest(installPackage);
        } else {
          stream = fs.createReadStream(installPackage);
        }
        return extractStream(stream, obj.tmpdir).then(() => obj);
      })
      .then(obj => {
        const packageName = require(path.join(obj.tmpdir, 'package.json')).name;
        obj.cleanup();
        return packageName;
      })
      .catch(err => {
        // The package name could be with or without semver version, e.g. tscomp-0.2.0-alpha.1.tgz
        // However, this function returns package name only without semver version.
        console.log(
          `Could not extract the package name from the archive: ${err.message}`
        );
        const assumedProjectName = installPackage.match(
          /^.+\/(.+?)(?:-\d+.+)?\.(tgz|tar\.gz)$/
        )[1];
        console.log(
          `Based on the filename, assuming it is "${chalk.cyan(
            assumedProjectName
          )}"`
        );
        return Promise.resolve(assumedProjectName);
      });
  } else if (installPackage.indexOf('git+') === 0) {
    // Pull package name out of git urls e.g:
    // git+https://github.com/mycompany/tscomp.git
    // git+ssh://github.com/mycompany/tscomp.git#v1.2.3
    return Promise.resolve(installPackage.match(/([^/]+)\.git(#.*)?$/)[1]);
  } else if (installPackage.match(/.+@/)) {
    // Do not match @scope/ when stripping off @version or @tag
    return Promise.resolve(
      installPackage.charAt(0) + installPackage.substr(1).split('@')[0]
    );
  } else if (installPackage.match(/^file:/)) {
    const installPackagePath = installPackage.match(/^file:(.*)?$/)[1];
    const installPackageJson = require(path.join(
      installPackagePath,
      'package.json'
    ));
    return Promise.resolve(installPackageJson.name);
  }
  return Promise.resolve(installPackage);
}
496264
function getHtmlWebpackPluginHooks (compilation) {
  let hooks = htmlWebpackPluginHooksMap.get(compilation);
  // Setup the hooks only once
  if (hooks === undefined) {
    hooks = createHtmlWebpackPluginHooks();
    htmlWebpackPluginHooksMap.set(compilation, hooks);
  }
  return hooks;
}
453805
function loadPaths (pkg) {
  const name = pkg.name
  const file = pkg.path
  return resolveFile(tmp, path.join(name, file)).then(entry => ({
    entry: entry,
    package: path.join(tmp, 'node_modules', name, 'package.json')
  }))
}
339968
function (mods) {
            var i, l = mods.length,
                tmpMods, mod, packageInfo, type,
                tag, charset, packageBase,
                packageName, group, modUrl;
            var groups = {
                /*
                 js: {
                 'groupA-gbk':{
                 'http://x.com':[m1,m2]
                 }
                 }
                 */
            };
            var normals = {
                /*
                 js:{
                 'http://x.com':[m1,m2]
                 }
                 */
            };
            for (i = 0; i < l; ++i) {
                mod = mods[i];
                type = mod.getType();
                modUrl = mod.getUrl();
                packageInfo = mod.getPackage();

                if (packageInfo) {
                    packageBase = packageInfo.getBase();
                    packageName = packageInfo.name;
                    charset = packageInfo.getCharset();
                    tag = packageInfo.getTag();
                    group = packageInfo.getGroup();
                } else {
                    packageBase = mod.name;
                }

                if (packageInfo && packageInfo.isCombine() && group) {
                    var typeGroups = groups[type] || (groups[type] = {});
                    group = group + '-' + charset;
                    var typeGroup = typeGroups[group] || (typeGroups[group] = {});
                    var find = 0;
                    /*jshint loopfunc:true*/
                    Utils.each(typeGroup, function (tmpMods, prefix) {
                        if (Utils.isSameOriginAs(prefix, packageBase)) {
                            var newPrefix = getCommonPathPrefix(prefix, packageBase);
                            tmpMods.push(mod);
                            if (tag && tag !== tmpMods.tag) {
                                tmpMods.tag = getHash(tmpMods.tag + tag);
                            }
                            delete typeGroup[prefix];
                            typeGroup[newPrefix] = tmpMods;
                            find = 1;
                        }
                    });
                    if (!find) {
                        tmpMods = typeGroup[packageBase] = [mod];
                        tmpMods.charset = charset;
                        tmpMods.tag = tag || '';
                    }
                } else {
                    var normalTypes = normals[type] || (normals[type] = {});
                    if (!(tmpMods = normalTypes[packageBase])) {
                        tmpMods = normalTypes[packageBase] = [];
                        tmpMods.charset = charset;
                        tmpMods.tag = tag || '';
                    } else {
                        if (tag && tag !== tmpMods.tag) {
                            tmpMods.tag = getHash(tmpMods.tag + tag);
                        }
                    }
                    tmpMods.push(mod);
                }
            }

            return {
                groups: groups,
                normals: normals
            };
        }
1307187
function configure() {
      var pkg = this.square.package
        , configuration = pkg.configuration
        , type = this.type || Plugin.modifier
        , self = this
        , load = [];

      // Check for the distribution and if it should accept the given extension,
      // extend self with the context of the plugin.
      if (!~type.indexOf('once') && (!this.distributable() || !this.accepted())) {
        this.logger.debug(
            'disregarding this plugin for extension: '+ this.extension
          +', distribution: '+ this.distribution
        );
        return this.emit('disregard');
      }

      // Check if there are any configuration options in the package.
      if (_.isObject(pkg.plugins) && this.id in pkg.plugins) {
        this.merge(this, pkg.plugins[this.id]);
      }

      // Merge in the plugin configuration.
      if (
           configuration
        && _.isObject(configuration.plugins)
        && this.id in configuration.plugins
      ) {
        this.merge(this, configuration.plugins[this.id]);
      }

      // Check if the bundle it self also had specific configurations for this
      // plugin.
      if (this.id in this && _.isObject(this[this.id])) {
        this.merge(this, this[this.id]);
      }

      // Ensure that our requires is an array, before we continue
      if (!Array.isArray(this.requires)) this.requires = [this.requires];

      // Check if we need to lazy load any dependencies
      if (this.requires && this.requires.length) {
        load = this.requires.map(function (file) {
          if (typeof file !== 'object') return file;
          if (!('extension' in file)) return file.name || file;
          if (file.extension === self.extension) return file.name || file;

          return undefined;
        }).filter(Boolean); // Only get existing files

        // Only fetch shizzle when we actually have shizzle to fetch here
        if (load.length) return canihaz.apply(canihaz, load.concat(function canihaz(err) {
          if (err) return self.emit('error', err);

          // Add all the libraries to the context, the `canihaz#all` returns an
          // error first, and then all libraries it installed or required in the
          // order as given to it, which is in our case the `this.requires` order.
          Array.prototype.slice.call(arguments, 1).forEach(function (lib, index) {
            self[load[index]] = lib;
          });

          // We are now fully initialized.
          if (self.initialize) self.initialize();
        }));
      }

      // We are now fully initialized.
      if (self.initialize) self.initialize();
    }
332455
function readWebpackConfig( server ) {

  const devConfig = server.webpackConfig && server.webpackConfig.dev;
  const configFile = paths.resolveApp( devConfig ) || appWebpackDevConfig;

  try {

    assert(
      existsSync( configFile ),
      `File ${devConfig || WEBPACK_DEV_CONFIG} is not exsit.`
    );

    const wpConfig = getConfig( configFile );

    // plugins: function
    if ( is.Function( wpConfig.plugins )) {
      wpConfig.plugins = wpConfig.plugins( wpConfig );
    }

    // plugins: not array
    if ( !is.Array( wpConfig.plugins )) {
      wpConfig.plugins = [wpConfig.plugins];
    }

    // plugins: array in array
    wpConfig.plugins = flatten( wpConfig.plugins.map(( plugin ) => {
      return is.Function( plugin ) ? plugin( wpConfig ) : plugin;
    }));

    server.webpackDevConfig = wpConfig;
    watchFiles.push( configFile );

    return Right( server );
  } catch ( e ) {
    print(
      chalk.red( `Failed to read ${devConfig || WEBPACK_DEV_CONFIG}.` ),
      e.message
    );
    print();
    return Left( null );
  }
}
312971
function getHtmlTemplates(dirName) {
  const html_conf = [];
  // create the array of HTML plugins.
  const template = path.join(dirName, '_template.html');
  getExamples(dirName, (entryName, filename) => {
    html_conf.push(
      new HtmlWebpackPlugin({
        title: entryName,
        // ensure each output has a unique filename
        filename: entryName + '.html',
        template,
        // without specifying chunks, all chunks are
        //  included with the file.
        chunks: ['common', entryName]
      })
    );
  });
  return html_conf;
}
933731
function createBundle(skyPagesConfig, webpack) {
  const webpackConfig = require('../config/webpack/build-public-library.webpack.config');
  const config = webpackConfig.getWebpackConfig(skyPagesConfig);
  return runCompiler(webpack, config);
}
306589
function install_ (pkg, reg, seen, mustHave, pkglist, bundles, cb) {
  log.verbose(pkg, "install_")
  if (seen[pkg]) return cb() // repeat, skip it
  seen[pkg] = true

  // it's a local thing or a url if it has a / in it.
  if (pkg.indexOf("/") !== -1 || pkg === ".") {
    log.silly(pkg, "install local")
    return cache.add(pkg, finisher(pkg, reg, pkglist, bundles, cb))
  }

  // now we know it's not a URL or file,
  // so handle it like a tag, version, or range.
  pkg = pkg.split("@")
  var name = pkg[0]
    , defTag = npm.config.get("tag")
    , ver = pkg.slice(1).join("@").trim() || defTag
    , range = semver.validRange(ver)
    , exact = semver.valid(ver)
    , tag = !exact && !range && range !== "" && ver
  log.verbose([pkg, mustHave], "must install?")
  pkg = pkg.join("@")
  seen[name+"@"+ver] = true

  // if there is a satisfying version already, then simply move on.
  if (!tag && findSatisfying(pkg, name, range, mustHave, reg)) {
    return cb()
  }

  // at this point, assume that it has to be installed.
  if (exact) {
    log.verbose("exact", pkg)
    // just pull the data out of the cache to ensure it's there
    return cache.read(name, exact, finisher(pkg, reg, pkglist, bundles, cb))
  }

  getData(name, function (er, data) {
    if (er) return cb(er)
    log.silly(data, pkg)
    if (tag) {
      log.verbose(tag, pkg+" tag")
      var tags = data["dist-tags"]
      if (!tags[tag]) cb(new Error(
        "Tag not found: "+data.name+"@"+tag
        +"\nValid install targets for "+data.name+": "
        +installTargets(data)))
      install_(data.name+"@"+tags[tag], reg, seen, mustHave
              , pkglist, bundles, cb)
    } else {
      log(pkg, "range")
      // prefer the default tag version.
      var defTag = npm.config.get("tag")
        , satis
      defTag = defTag && data["dist-tags"] && data["dist-tags"][defTag]
      if (semver.satisfies(defTag, range)) satis = defTag
      else satis = semver.maxSatisfying(Object.keys(data.versions), range)

      if (!satis) return cb(new Error(
        "No satisfying version found for '"+data.name+"'@'"+range+"'"
        +"\nValid install targets for "+data.name+": "
        +installTargets(data)))
      install_(data.name+"@"+satis, reg, seen, mustHave
              , pkglist, bundles, cb)
    }
  })
}