install package via npm

@param {String} [name] published package name
@param {String} [ver] install version
@param {String} [dir] install directory
@public
350962
function installVer(name, ver, dir) {
        var _child$spawnSync2 = _child_process2['default'].spawnSync(npmCommand, ['install', name + '@' + ver], { cwd: dir });

        var error = _child$spawnSync2.error;

        if (error) throw error;
    }
1101124
function updateManifests() {
      function updateVersion( name ) {
        var _ = grunt.util._;
        var manifest = grunt.file.readJSON(name);

        manifest = JSON.stringify(_.extend(manifest, {version: grunt.option('version')}), null, 2);
        grunt.file.write(name, manifest);
      }
      return Q.fcall(function() {
        var files = [
          path.join('./', 'package.json'),
          path.join('./', 'bower.json')
        ];
        files.forEach(function(item){
          //grunt.log.ok(item);
          if ( existsFilePath(item) ) {
            updateVersion(item);
          }
        });
      });
    }
856689
function push() {
		Release.chdir( Release.dir.dist );

		console.log( "Pushing release to dist repo..." );
		Release.exec( "git push " + distRemote + " master --tags",
			"Error pushing master and tags to git repo." );

		// Set repo for npm publish
		Release.dir.origRepo = Release.dir.repo;
		Release.dir.repo = Release.dir.dist;
	}
108320
async function commitVersionBump (version) {
  const gitDir = path.resolve(__dirname, '..')
  const gitArgs = ['commit', '-a', '-m', `Bump v${version}`, '-n']
  await GitProcess.exec(gitArgs, gitDir)
}
408033
function isPackageAlreadyInstalled(packageInstallFolder) {
    try {
        const flagFilePath = path.join(packageInstallFolder, INSTALLED_FLAG_FILENAME);
        if (!fs.existsSync(flagFilePath)) {
            return false;
        }
        const fileContents = fs.readFileSync(flagFilePath).toString();
        return fileContents.trim() === process.version;
    }
    catch (e) {
        return false;
    }
}
906796
function outputVersion () {
  fs.readFile(path.join(__dirname, '/../package.json'), function (err, data) {
    if (err) {
      console.log(err.toString())
    } else {
      const pkg = JSON.parse(data)
      const version = pkg && pkg.version ? pkg.version : 'unknown'
      console.log(version)
    }
    process.exit(0)
  })
}
12810
private void install() {
        File directory = getNPMDirectory();
        if (directory.isDirectory()) {
            // Check the version
            String version = getVersionFromNPM(directory, log);
            // Are we looking for a specific version ?
            if (npmVersion != null) {
                // Yes
                if (!npmVersion.equals(version)) {
                    log.info("The NPM " + npmName + " is already installed but not in the requested version" +
                            " (requested: " + npmVersion + " - current: " + version + ") - uninstall it");
                    try {
                        FileUtils.deleteDirectory(directory);
                    } catch (IOException e) { //NOSONAR
                        // ignore it.
                    }
                } else {
                    log.debug("NPM " + npmName + " already installed in " + directory.getAbsolutePath() +
                            " (" + version + ")");
                    return;
                }
            } else {
                // No
                log.debug("NPM " + npmName + " already installed in " + directory.getAbsolutePath() + " " +
                        "(" + version + ")");
                return;
            }
        }

        StringBuilder command = new StringBuilder();
        command.append("install ");
        if (installArguments != null) {
            for (String s : installArguments) {
                command.append(s);
                command.append(" ");
            }
        }

        if (npmVersion != null) {
            command.append(npmName).append("@").append(npmVersion);
        } else {
            command.append(npmName);
        }

        try {
            node.factoryForNPMInstallation().getNpmRunner(node.proxy()).execute(command.toString());
        } catch (TaskRunnerException e) {
            log.error("Error during the installation of the NPM " + npmName + " - check log", e);
        }
    }
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)
    }
  })
}
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;
  }
61457
def npm(package_json, output_file, pinned_file):
    """"""
    amd_build_deprecation_warning()
    try:
        version = get_distribution(current_app.name).version
    except DistributionNotFound:
        version = ''

    output = {
        'name': current_app.name,
        'version': make_semver(version) if version else version,
        'dependencies': {},
    }

    # Load base file
    if package_json:
        output = dict(output, **json.load(package_json))

    # Iterate over bundles
    deps = extract_deps(current_app.extensions['invenio-assets'].env,
                        click.echo)
    output['dependencies'].update(deps)

    # Load pinned dependencies
    if pinned_file:
        output['dependencies'].update(
            json.load(pinned_file).get('dependencies', {}))

    # Write to static folder if output file is not specified
    if output_file is None:
        if not os.path.exists(current_app.static_folder):
            os.makedirs(current_app.static_folder)
        output_file = open(
            os.path.join(current_app.static_folder, 'package.json'),
            'w')

    click.echo('Writing {0}'.format(output_file.name))
    json.dump(output, output_file, indent=4)
    output_file.close()
740005
function package(cb) {
    const pkgjson = JSON.parse(fs.readFileSync('./package.json', 'utf8'));
    delete pkgjson.scripts;
    delete pkgjson.devDependencies;
    const filepath = './dist/package.json';
    fs.writeFileSync(filepath, JSON.stringify(pkgjson, null, 2), 'utf-8');
    console.log('package.json Copied to Dist Directory');
    cb();
}
106094
function updateInstalledPackage(updatedPackage) {
   var packageIndex = installedPackages.findIndex(function(element) { 
      return (element.packageName === updatedPackage.packageName); 
   });

   if (packageIndex < 0) {
      packageIndex = installedPackages.length;
      installedPackages.push(updatedPackage);
   } else {
      installedPackages[packageIndex] = updatedPackage;
   }

   fs.writeFileSync(installedPackagesDataFileName, JSON.stringify(installedPackages));
}
271760
def install_dir(pkgpath, install_path, register_func, delete_after_install=False):
    
    logger.debug("%s is a directory, attempting to validate", pkgpath)
    plugin = register_func(pkgpath)
    logger.debug("%s looks good, copying to %s", pkgpath, install_path)
    try:
        copy_tree(pkgpath, os.path.join(install_path, plugin.name))
        if delete_after_install:
            logger.debug("deleting %s", pkgpath)
            shutil.rmtree(pkgpath)
        pkgpath = os.path.join(install_path, plugin.name)
    except (OSError, CTError) as exc:
        # TODO: handle package name exists (upgrade? overwrite?)
        logger.debug(str(exc), exc_info=True)
        raise exceptions.PluginAlreadyInstalled(plugin.name)

    return install_deps(pkgpath)
120616
function install(items, callback) {

    var item = items[next],
        command = item.command,
        args = item.args,
        admin = item.admin,
        spawnopt = (item.spawnopt || {}),
        print;


    // set the spawn object according to the passed admin argument
    admin = setSpawnObject(admin);

    // run the command
    if (isLinux) {
        if (admin) {
            // use sudo
            args.unshift(command);
            print = args.join(" ");
            logger.console.log("[package-script] Running Installer command: " + print);

            sudoopt.spawnOptions = {};
            jsutils.Object.copy(spawnopt, sudoopt.spawnOptions);
            cprocess = spawn(args, sudoopt);
        } else {
            //use child_process
            print = args.join(" ");
            logger.console.log("[package-script] Running Installer command: " + command + " " + print);
            cprocess = spawn(command, args, spawnopt);
        }
    } else {
        args.unshift(command);
        args.unshift("/c");
        command = "cmd";
        print = [command, args.join(" ")].join(" ");
        logger.console.log("[package-script] Running Installer command: " + print);
        cprocess = spawn(command, args, spawnopt);

    }

    // -- Spawn Listeners
    cprocess.stdout.on('data', function (data) {
        var log = 'CAT Installer: ' + data;
        logger.logall(log);
    });

    cprocess.stderr.on('data', function (data) {
        if (data && (new String(data)).indexOf("npm ERR") != -1) {
            logger.logall('Package Script : ' + data);
        } else {
            logger.log2file('Package Script : ' + data);
        }
    });

    cprocess.on('close', function (code) {
        logger.log2file('Package Script Complete ' + code);
        next++;
        if (next < size) {
            install(items, callback);

        } else {
            // callback
            if (callback && _.isFunction(callback)) {
                callback.call(this, code);

            }
        }
    });
}
1114074
function packageVersion(repo) {
    var location = repo ? path.join(repo, 'package.json') : './package.json';
    var pack = require(location);
    return pack['version'];
}
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();
                });
            });
        });
    });
}
1314841
function publishNpm(pck) {
	var pkg = null, auth = [], npm = null;
	if (pck.commit.hasNpmToken && pck.commit.pkgPath) {
		try {
			npm = require('npm');
		} catch (e) {
			pck.rollCall.error('npm publish failed because npm module is not found (use "npm link npm")', e).resume();
			return;
		}
		rbot.log.info('Publishing to npm');
		go();
	} else {
		rbot.log.verbose('Skipping npm publish for ' + pck.commit.pkgPath + ' version ' + pck.commit.version);
	}
	function go() {
		var pd = pck.commit.versionPkg({
			replacer : pck.options.pkgJsonReplacer,
			space : pck.options.pkgJsonSpace,
			readOnly : true
		});
		pkg = pd.pkg;
		if (!pkg || !pkg.author || !pkg.author.email) {
			pck.rollCall.error('npm publish failed due to missing author.email in ' + pck.commit.pkgPath);
		} else {
			auth = (typeof pck.commit.npmToken === 'function' ? pck.commit.npmToken() : pck.commit.npmToken);
			auth = typeof auth === 'string' && (auth = new Buffer(auth, 'base64').toString()) ? auth.split(':') : [];
			if (auth.length !== 2) {
				pck.rollCall.error('npm NPM_TOKEN is missing or invalid');
			} else {
				pck.rollCall.pause(function() {
					npm.load({}, function(e) {
						if (e) {
							pck.rollCall.error('npm load failed', e).resume();
						} else {
							pck.rollCall.pause(adduser);
						}
					});
				});
			}
		}
	}
	function adduser() {
		npm.config.set('email', pkg.author.email, 'user');
		npm.registry.adduser(pck.options.npmRegistryURL, auth[0], auth[1], pkg.author.email, aucb);
		function aucb(e) {
			if (e) {
				pck.rollCall.error('npm publish failed to be authenticated', e).resume();
			} else {
				pck.rollCall.pause(pub);
			}
		}
	}
	function pub() {
		var pargs = [];
		if (pck.options.npmTag) {
			pargs.push('--tag ' + pck.options.npmTag);
		}
		rbot.log.info('npm publish ' + pargs.join(' '));
		// switch to the master branch so publish will pickup the right version
		pck.command.chkoutCmd(pck.commit.branch);
		npm.commands.publish(pargs, function(e) {
			if (e) {
				pck.rollCall.error('npm publish failed', e).resume();
			} else {
				pck.rollCall.pause(postPub);
			}
		});
		function postPub() {
			pck.command.chkoutRun(null, function() {
				rbot.log.verbose('npm publish complete');
				pck.rollCall.resume();
			});
		}
	}
}