Call 'pkg.install' API.

@param refresh refresh repos before installation
@param pkgs list of packages
@return the call
486708
public static LocalCall<Map<String, Object>> install(boolean refresh,
            List<String> pkgs) {
        LinkedHashMap<String, Object> kwargs = new LinkedHashMap<>();
        kwargs.put("refresh", refresh);
        kwargs.put("pkgs", pkgs);
        return new LocalCall<>("pkg.install", Optional.empty(), Optional.of(kwargs),
                new TypeToken<Map<String, Object>>(){});
    }
1297319
function (pkg, cb) {
  var auto = npm.config.get("auto-activate")
  if (!auto) {
    autoActivate = function (_, cb) { return cb() }
    return log.verbose("auto-activate", "disabled by config", cb)
  }
  pkg = pkg && pkg._data || pkg
  // get the list of versions of this package.
  readInstalled(pkg.name, function (er, inst) {
    if (er) return cb(er)
    var versions = Object.keys(inst)
    if (auto !== "always" && versions.indexOf("active") !== -1) {
      log("another version already active", "auto-activate")
      log("to activate, do:   npm activate "+
        pkg.name+"@"+pkg.version, "auto-activate")
      return cb()
    }
    var u = pkg.name+"@"+pkg.version
    log.verbose(u, "auto-activate")
    npm.commands.activate([u], function (er) {
      // don't rollback the whole install if the activate fails.
      if (er) log.error(er, "Failed to update "+u)
      cb()
    })
  })
}
290829
def install_build_requires(pkg_targets):
    """"""

    def pip_install(pkg_name, pkg_vers=None):
        pkg_name_version = '%s==%s' % (pkg_name, pkg_vers) if pkg_vers else pkg_name
        print '[WARNING] %s not found, attempting to install using a raw "pip install" call!' % pkg_name_version
        subprocess.Popen('pip install %s' % pkg_name_version, shell=True).communicate()

    def get_pkg_info(pkg):
        """Get package name and version given a build_requires element"""
        pkg_name, pkg_vers = None, None
        if '==' in pkg:
            pkg_name, pkg_vers = pkg.split('==')
        else:
            pkg_name = pkg.replace('>', '').replace('<', '').split('=')[0]
        return pkg_name, pkg_vers

    for pkg in pkg_targets:
        pkg_name, pkg_vers = get_pkg_info(pkg)
        try:
            pkg_name_version = '%s==%s' % (pkg_name, pkg_vers) if pkg_vers else pkg_name
            if pkg_vers:
                version = getattr(importlib.import_module(pkg_name), '__version__')
                if version != pkg_vers:
                    pip_install(pkg_name, pkg_vers)
            else:
                importlib.import_module(pkg_name)
        except ImportError:
            pip_install(pkg_name, pkg_vers)
163266
def fetch_package_version(dist_name):
    
    try:
        # Importing pkg_resources can be slow, so only import it
        # if we need it.
        import pkg_resources
    except ImportError:
        # pkg_resource is not available on Google App Engine
        raise NotImplementedError('pkg_resources is not available '
                                  'on this Python install')
    dist = pkg_resources.get_distribution(dist_name)
    return dist.version
999884
public void installFile(PackageFile packageFile) {
    File file = packageFile.getFile();
    if (!file.exists()) {
      throw new PackageManagerException("File does not exist: " + file.getAbsolutePath());
    }

    try (CloseableHttpClient httpClient = pkgmgr.getHttpClient()) {

      // before install: if bundles are still stopping/starting, wait for completion
      pkgmgr.waitForBundlesActivation(httpClient);

      if (packageFile.isInstall()) {
        log.info("Upload and install " + (packageFile.isForce() ? "(force) " : "") + file.getName() + " to " + props.getPackageManagerUrl());
      }
      else {
        log.info("Upload " + file.getName() + " to " + props.getPackageManagerUrl());
      }

      VendorPackageInstaller installer = VendorInstallerFactory.getPackageInstaller(props.getPackageManagerUrl());
      if (installer != null) {
        installer.installPackage(packageFile, pkgmgr, httpClient, props, log);
      }
    }
    catch (IOException ex) {
      throw new PackageManagerException("Install operation failed.", ex);
    }
  }
1107333
function downloadUpdateRepo(config, callback) {

  console.log('Downloading repo...'.magenta);

  // Keep track if the request fails to prevent the continuation of the install
  var requestFailed = false;

  // TODO: have this hit different templating repos
  var repoRequest = request(config.baseGit + '/generate-repo.zip');

  repoRequest
    .on('response', function (response) {
      // If we fail, set it as failing and remove zip file
      if (response.statusCode !== 200) {
        requestFailed = true;
        fs.unlinkSync('.generate-repo.zip');
        callback(true);
      }
    })
    .pipe(fs.createWriteStream('.generate-repo.zip'))
    .on('close', function () {
      if (requestFailed) return;

      callback(null, '.generate-repo.zip');
    });
}
1040786
def list_upgrades(refresh=True, **kwargs):
    '''
    
    '''
    pkgs = {}
    for pkg in sorted(list_pkgs(refresh=refresh).keys()):
        # NOTE: we already optionally refreshed in de list_pkg call
        pkg_upgrade = latest_version(pkg, refresh=False)
        if pkg_upgrade:
            pkgs[pkg] = pkg_upgrade
    return pkgs
136711
def _verify_install(desired, new_pkgs, ignore_epoch=False, new_caps=None):
    '''
    
    '''
    ok = []
    failed = []
    if not new_caps:
        new_caps = dict()
    for pkgname, pkgver in desired.items():
        # FreeBSD pkg supports `openjdk` and `java/openjdk7` package names.
        # Homebrew for Mac OSX does something similar with tap names
        # prefixing package names, separated with a slash.
        has_origin = '/' in pkgname

        if __grains__['os'] == 'FreeBSD' and has_origin:
            cver = [k for k, v in six.iteritems(new_pkgs) if v['origin'] == pkgname]
        elif __grains__['os'] == 'MacOS' and has_origin:
            cver = new_pkgs.get(pkgname, new_pkgs.get(pkgname.split('/')[-1]))
        elif __grains__['os'] == 'OpenBSD':
            cver = new_pkgs.get(pkgname.split('%')[0])
        elif __grains__['os_family'] == 'Debian':
            cver = new_pkgs.get(pkgname.split('=')[0])
        else:
            cver = new_pkgs.get(pkgname)
            if not cver and pkgname in new_caps:
                cver = new_pkgs.get(new_caps.get(pkgname)[0])

        if not cver:
            failed.append(pkgname)
            continue
        elif pkgver == 'latest':
            ok.append(pkgname)
            continue
        elif not __salt__['pkg_resource.version_clean'](pkgver):
            ok.append(pkgname)
            continue
        elif pkgver.endswith("*") and cver[0].startswith(pkgver[:-1]):
            ok.append(pkgname)
            continue
        if _fulfills_version_string(cver, pkgver, ignore_epoch=ignore_epoch):
            ok.append(pkgname)
        else:
            failed.append(pkgname)
    return ok, failed
387821
def _repo(self, args):
        '''
        
        '''
        args.pop(0)
        command = args[0]
        if command == 'list':
            self._repo_list(args)
        elif command == 'packages':
            self._repo_packages(args)
        elif command == 'search':
            self._repo_packages(args, search=True)
        elif command == 'update':
            self._download_repo_metadata(args)
        elif command == 'create':
            self._create_repo(args)
        else:
            raise SPMInvocationError('Invalid repo command \'{0}\''.format(command))
1088224
def upgrade_all(self):
        
        for pkg in self.installed_package_names:
            self.install(pkg, upgrade=True)
810989
def install(args, console, env, ciprcfg, opts):
    
    if len(args) == 0:
        # Is this a cipr project?
        if ciprcfg.exists:
            # Install all the packages for this project
            console.quiet('Installing current project packages...')
            for name, source in ciprcfg.packages.items():
                if opts.upgrade:
                    app.command.run(['install', '--upgrade', source])
                else:
                    app.command.run(['install', source])
        else:
            console.error('No cipr project or package found.')
        return
    else:
        for source in args:
            package, name, version, type = _package_info(source)

            if not path.exists(env.package_dir):
                os.makedirs(env.package_dir)

            package_dir = path.join(env.package_dir, name)

            if path.exists(package_dir):
                if opts.upgrade:
                    app.command.run(['uninstall', name])
                else:
                    console.quiet('Package %s already exists. Use --upgrade to force a re-install.' % name)
                    return

            console.quiet('Installing %s...' % name)


            if type == 'git':
                tmpdir = tempfile.mkdtemp(prefix='cipr')
                clom.git.clone(package, tmpdir).shell.execute()

                if version:
                    cmd = AND(clom.cd(tmpdir), clom.git.checkout(version))
                    cmd.shell.execute()

                package_json = path.join(tmpdir, 'package.json')
                if path.exists(package_json):
                    # Looks like a cipr package, copy directly
                    shutil.move(tmpdir, package_dir)
                else:
                    # Not a cipr package, sandbox in sub-directory
                    shutil.move(tmpdir, path.join(package_dir, name))

                console.quiet('`%s` installed from git repo to `%s`' % (name, package_dir))

            elif path.exists(package):
                # Local
                os.symlink(package, package_dir)
            else:
                console.error('Package `%s` type not recognized' % package)
                return

            pkg = Package(package_dir, source)
            ciprcfg.add_package(pkg)

            if pkg.dependencies:
                console.quiet('Installing dependancies...')
                for name, require in pkg.dependencies.items():
                    if opts.upgrade:
                        app.command.run(['install', '--upgrade', require])
                    else:
                        app.command.run(['install', require])
866687
def upgrade_available(name, **kwargs):
    '''
    
    '''
    version = None
    cmd = ['pkg', 'list', '-Huv', name]
    lines = __salt__['cmd.run_stdout'](cmd).splitlines()
    if not lines:
        return {}
    ret = {}
    for line in lines:
        ret[_ips_get_pkgname(line)] = _ips_get_pkgversion(line)
    return ret
901711
def apt_upgrade(options=None, fatal=False, dist=False):
    """"""
    if options is None:
        options = ['--option=Dpkg::Options::=--force-confold']

    cmd = ['apt-get', '--assume-yes']
    cmd.extend(options)
    if dist:
        cmd.append('dist-upgrade')
    else:
        cmd.append('upgrade')
    log("Upgrading with options: {}".format(options))
    _run_apt_command(cmd, fatal)
1363118
function install(runtime, abi, platform, arch, cb) {
  const essential = runtime + '-v' + abi + '-' + platform + '-' + arch;
  const pkgVersion = pkg.version;
  const currentPlatform = pkg.name + '-v' + pkgVersion + '-' + essential;

  console.log('Downloading prebuild for platform:', currentPlatform);
  let downloadUrl = 'https://github.com/WilixLead/iohook/releases/download/v' + pkgVersion + '/' + currentPlatform + '.tar.gz';

  let reqOpts = {url: downloadUrl};
  let tempFile = path.join(os.tmpdir(), 'prebuild.tar.gz');
  let req = get(reqOpts, function(err, res) {
    if (err) {
      return onerror(err);
    }
    if (res.statusCode !== 200) {
      if (res.statusCode === 404) {
        console.error('Prebuild for current platform (' + currentPlatform + ') not found!');
        console.error('Try to compile for your platform:');
        console.error('# cd node_modules/iohook;');
        console.error('# npm run compile');
        console.error('');
        return onerror('Prebuild for current platform (' + currentPlatform + ') not found!');
      }
      return onerror('Bad response from prebuild server. Code: ' + res.statusCode);
    }
    pump(res, fs.createWriteStream(tempFile), function(err) {
      if (err) {
        throw err;
      }
      let options = {
        readable: true,
        writable: true,
        hardlinkAsFilesFallback: true
      };
      let binaryName;
      let updateName = function(entry) {
        if (/\.node$/i.test(entry.name)) binaryName = entry.name
      };
      let targetFile = path.join(__dirname, 'builds', essential);
      let extract = tfs.extract(targetFile, options)
        .on('entry', updateName);
      pump(fs.createReadStream(tempFile), zlib.createGunzip(), extract, function(err) {
        if (err) {
          return onerror(err);
        }
        cb()
      })
    })
  });

  req.setTimeout(30 * 1000, function() {
    req.abort()
  })
}
854842
def refresh_db(**kwargs):
    '''
    
    '''
    # Remove rtag file to keep multiple refreshes from happening in pkg states
    salt.utils.pkg.clear_rtag(__opts__)
    cmd = 'update'
    if _call_brew(cmd)['retcode']:
        log.error('Failed to update')
        return False

    return True
271109
def _repo_packages(self, args, search=False):
        '''
        
        '''
        packages = []
        repo_metadata = self._get_repo_metadata()
        for repo in repo_metadata:
            for pkg in repo_metadata[repo]['packages']:
                if args[1] in pkg:
                    version = repo_metadata[repo]['packages'][pkg]['info']['version']
                    release = repo_metadata[repo]['packages'][pkg]['info']['release']
                    packages.append((pkg, version, release, repo))
        for pkg in sorted(packages):
            self.ui.status(
                '{0}\t{1}-{2}\t{3}'.format(pkg[0], pkg[1], pkg[2], pkg[3])
            )
        return packages
93226
@CheckForNull
    /*package*/ JSONArray getPlatformPluginList() {
        Jenkins.get().checkPermission(Jenkins.ADMINISTER);
        JSONArray initialPluginList = null;
        updateSiteList: for (UpdateSite updateSite : Jenkins.get().getUpdateCenter().getSiteList()) {
            String updateCenterJsonUrl = updateSite.getUrl();
            String suggestedPluginUrl = updateCenterJsonUrl.replace("/update-center.json", "/platform-plugins.json");
            try {
                URLConnection connection = ProxyConfiguration.open(new URL(suggestedPluginUrl));
                
                try {
                    if(connection instanceof HttpURLConnection) {
                        int responseCode = ((HttpURLConnection)connection).getResponseCode();
                        if(HttpURLConnection.HTTP_OK != responseCode) {
                            throw new HttpRetryException("Invalid response code (" + responseCode + ") from URL: " + suggestedPluginUrl, responseCode);
                        }
                    }
                    
                    String initialPluginJson = IOUtils.toString(connection.getInputStream(), "utf-8");
                    initialPluginList = JSONArray.fromObject(initialPluginJson);
                    break updateSiteList;
                } catch(Exception e) {
                    // not found or otherwise unavailable
                    LOGGER.log(Level.FINE, e.getMessage(), e);
                    continue updateSiteList;
                }
            } catch(Exception e) {
                LOGGER.log(Level.FINE, e.getMessage(), e);
            }
        }
        if (initialPluginList == null) {
            // fall back to local file
            try {
                ClassLoader cl = getClass().getClassLoader();
                URL localPluginData = cl.getResource("jenkins/install/platform-plugins.json");
                String initialPluginJson = IOUtils.toString(localPluginData.openStream(), "utf-8");
                initialPluginList =  JSONArray.fromObject(initialPluginJson);
            } catch (Exception e) {
                LOGGER.log(Level.SEVERE, e.getMessage(), e);
            }
        }
        return initialPluginList;
    }