/*
collect the data for a single package
517296
function getPackageReportData(package, versionRangeOrCallback, callback) {
	var versionRange = versionRangeOrCallback

	if (arguments.length === 2) {
		var split = package.split('@')
		
		if (split.length !== 2) {
			throw new Error('invalid package: ' + package)
		}

		callback = versionRangeOrCallback
		package = split[0]
		versionRange = split[1]
	}

	if (typeof callback !== 'function') {
		throw new Error('missing callback argument')
	}
	
	versionRange = semver.validRange(versionRange)

	if (!versionRange) {
		var message = util.format('skipping %s (invalid semversion)', package)
		
		return callback(null, { name: package, comment: message })
	}

	getPackageJson(package, function(err, json) {
		if (err) return callback(err)

		// dont think it is possible but just to make sure.
		if (!json.versions) {
			return callback(new Error('no versions in registry for package ' + package))
		}

		// find the right version for this package
		var versions = _.keys(json.versions)

		var version = semver.maxSatisfying(versions, versionRange)

		if (!version) {
			return callback(new Error('cannot find a version that satisfies range ' + versionRange + ' in the registry'))
		}

		getPackageJson(package, version, function(err, json) {
			if (err) return callback(err)

			/*
				finally, callback with all the data
			*/
			callback(null, { 
				name: package,
				licenseType: extractLicense(json),
				link: extractLink(json),
				comment: version.toString()
			})
		})
	})
}
1094525
def check_package_data(dist, attr, value):
    """"""
    if isinstance(value, dict):
        for k, v in value.items():
            if not isinstance(k, str):
                break
            try:
                iter(v)
            except TypeError:
                break
        else:
            return
    raise DistutilsSetupError(
        attr + " must be a dictionary mapping package names to lists of "
        "wildcard patterns"
    )
1364372
function getFiles(packageName,files,bundledFile){
	    	if(!traversed_bundles[packageName]){
	    		traversed_bundles[packageName] = true;
	    		var bundle = resourcesJs.bundles[packageName];
	    		if(bundle){
		    		bundle.bundled = bundledFile;
	    			for(var i in bundle.on){
	    				files = getFiles(bundle.on[i],files);
	    			}
	    			for(var i in bundle.js){
	    				var file = dir+ "/" + bundle.js[i];
	    				if(!traversed_files[file]){
	    					files.push(file);
	    					traversed_files[file] = true;
	    				}
	    			}
	    		}
	    	}
	    	return files;
	    }
48398
def repo_data(PACKAGES_TXT, repo, flag):
    
    (name, location, size, unsize,
     rname, rlocation, rsize, runsize) = ([] for i in range(8))
    for line in PACKAGES_TXT.splitlines():
        if _meta_.rsl_deps in ["on", "ON"] and "--resolve-off" not in flag:
            status(0.000005)
        if line.startswith("PACKAGE NAME:"):
            name.append(line[15:].strip())
        if line.startswith("PACKAGE LOCATION:"):
            location.append(line[21:].strip())
        if line.startswith("PACKAGE SIZE (compressed):"):
            size.append(line[28:-2].strip())
        if line.startswith("PACKAGE SIZE (uncompressed):"):
            unsize.append(line[30:-2].strip())
    if repo == "rlw":
        (rname,
         rlocation,
         rsize,
         runsize
         ) = rlw_filter(name, location, size, unsize)
    elif repo == "alien":
        (rname,
         rlocation,
         rsize,
         runsize
         ) = alien_filter(name, location, size, unsize)
    elif repo == "rested":
        (rname,
         rlocation,
         rsize,
         runsize
         ) = rested_filter(name, location, size, unsize)
    elif repo == "ktown":
        (rname,
         rlocation,
         rsize,
         runsize
         ) = ktown_filter(name, location, size, unsize)
    else:
        rname, rlocation, rsize, runsize = name, location, size, unsize
    return [rname, rlocation, rsize, runsize]
298240
function fetchDependentPackages( $dependencyType, &$failedList )
    {
        $packages = array();
        $provides = $this->Parameters['dependencies'][$dependencyType];

        if ( $provides != null )
        {
            foreach ( $provides as $provide )
            {
                // fetch only dependent packages, not package items.
                if ( $provide['type'] == 'ezpackage' )
                {
                    // TODO: Add fetching from URL (not here ?)
                    $package = $this->fetch( $provide['name'] );

                    if ( !$package )
                    {
                        $failedList[] = $provide['name'];
                        continue;
                    }
                    $packages[] =& $package;
                }
            }
        }
        return $packages;
    }
1340894
def getPackages(self, distribution = "rawhide"):
		
		if self._packages == {}:
			file_location = "%s/data/distribution_packages.json" % getScriptDir(__file__)
			with open(file_location, "r") as f:
				packages = json.load(f)
			for pkg in packages:
				for distro in pkg["distributions"]:
					try:
						self._packages[distro].append(pkg["package"])
					except KeyError:
						self._packages[distro] = [pkg["package"]]

		return self._packages[distribution]
1282114
function packResult(args, proto, ObjName) {
    debug && logger.trace("Package Data To Client [ %s ]", JSON.stringify(args));
    if (null == proto) {
        logger.error('No proto File Configured！');
        return "";
    } else if (typeof proto == "string") {
        if (fs.existsSync(proto)) {
            proto = ProtoBuf.loadProtoFile(proto);
        } else if (fs.existsSync(proto + ".proto")) {
            proto = ProtoBuf.loadProtoFile(proto + ".proto");
        } else {
            return "";
        }
    }

    var RetMessage = proto.build("Ret" + ObjName);
    try {
        var ret_msg = new RetMessage();
    } catch (e) {
        console.log(RetMessage, e);
    }

    for (var index in args) {
        if (args.hasOwnProperty(index)) {
            ret_msg[index] = args[index];
        }
    }

    return ret_msg.toBase64();
}
71255
def build_package_data(self):
        """"""
        for package, src_dir, build_dir, filenames in self.data_files:
            for filename in filenames:
                target = os.path.join(build_dir, filename)
                self.mkpath(os.path.dirname(target))
                srcfile = os.path.join(src_dir, filename)
                outf, copied = self.copy_file(srcfile, target)
                srcfile = os.path.abspath(srcfile)
                if (copied and
                        srcfile in self.distribution.convert_2to3_doctests):
                    self.__doctests_2to3.append(outf)
879178
function getBin(packageName, binName = packageName) {
  const packagePath = require.resolve(`${packageName}/package.json`)
  const concurrentlyDir = path.dirname(packagePath)
  let {bin: binRelativeToPackage} = require(packagePath)
  if (typeof binRelativeToPackage === 'object') {
    binRelativeToPackage = binRelativeToPackage[binName]
  }
  const fullBinPath = path.join(concurrentlyDir, binRelativeToPackage)
  return path.relative(process.cwd(), fullBinPath)
}
1118457
protected function collect_packs() {
		$iterator = new DirectoryIterator( $this->dir );

		foreach ( $iterator as $pack_dir ) {
			if ( $pack_dir->isDot() || ! $pack_dir->isDir() || ! $pack_dir->isReadable() ) {
				continue;
			}

			$pack_dirname = $pack_dir->getFilename();
			$pack_data    = $this->get_pack_data( $pack_dir );

			if ( ! empty( $pack_data ) ) {
				$this->packs[ $pack_dirname ] = $pack_data;
			}
		}
	}
572385
private static void extractAndAddPackageInfo(ClassInfo classInfo, Set<String> packages, IndexView indexView) {
        if (classInfo == null) {
            return;
        }

        // Check if we were given an abstract class / interface, in which case we need to check the IndexView to see if there
        // is an implementation or not.
        String className = classInfo.name().toString();
        if (indexView != null) {
            DotName dotName = DotName.createSimple(className);
            if (Modifier.isInterface(classInfo.flags())) {
                indexView.getAllKnownImplementors(dotName).forEach(ci -> extractAndAddPackageInfo(ci, packages, indexView));
            } else if (Modifier.isAbstract(classInfo.flags())) {
                indexView.getAllKnownSubclasses(dotName).forEach(ci -> extractAndAddPackageInfo(ci, packages, indexView));
            }
        }
        StringBuilder builder = new StringBuilder(className).reverse();
        int idx = builder.indexOf(".");
        if (idx != -1) {
            builder.delete(0, idx + 1);
        }
        packages.add(builder.reverse().toString());
    }
579360
function buildJSONSource() {

  var data = getModularSource();

  addCorePackage();
  prepareData();
  outputJSON('source.json', data);

  function addCorePackage() {
    data.modules.unshift({
      name: 'Core'
    });
    data.packages.unshift({
      name: 'Sugar',
      type: 'core',
      module: 'Core',
      dependencies: [],
      bodyWithComments: readFile('lib/core.js').trim()
    });
  }

  function bundleSetPackages() {
    var packages = [], handledSets = {}, p;

    for (var i = 0; i < data.packages.length; i++) {
      p = data.packages[i];
      if (p.set) {
        // If the package has been handled already then just skip.
        if (!handledSets[p.namespace + p.setName]) {
          packages.push({
            setName: p.setName,
            name: p.setName.replace(/[\[\]]/g, ''),
            sample: p.set.slice(0, 3).concat('...').join(', '),
            type: p.type,
            alias: p.alias,
            module: p.module,
            namespace: p.namespace,
            dependencies: p.dependencies,
            bodyWithComments: p.bodyWithComments
          });
          handledSets[p.namespace + p.setName] = true;
        }
      } else {
        packages.push(p);
      }
    }

    return packages;
  }

  function prepareData() {
    var bundledPackages = bundleSetPackages();
    data.modules.forEach(function(m) {
      indentField(m, 'comment');
    });
    bundledPackages.forEach(function(p) {

      // Pre-indenting all packages rather than doing it on compile to
      // save some cycles and also correctly calculate the package size.
      indentField(p, 'blockStart');
      indentField(p, 'blockEnd');
      indentField(p, 'bodyWithComments');

      cleanSourcePackage(p);
    });
    data.packages = bundledPackages;
  }

  function indentField(p, field) {
    if (p[field]) {
      p[field] = p[field].replace(/^(?=.)/gm, '  ');
    }
  }

  function cleanSourcePackage(p) {
    if (sourcePackageIsDependency(p)) {
      delete p.type;
    }
    delete p.vars;
    delete p.target;
    delete p.body;
    delete p.path;
    delete p.assigns;
    delete p.comments;
    delete p.defineMethod;
    delete p.varDependencies;
    compactField(p, 'bodyWithComments');
    compactField(p, 'dependencies');
  }

  function compactField(p, field) {
    var val = p[field];
    if (!val || (Array.isArray(val) && !val.length)) {
      delete p[field];
    }
  }

}
319202
function collectImports(items, children) {
	const result = Promise.map(items, (item) => {
		const name = item.name;
		const parent = cbuild.path2url(item.path);
		const pos = name.indexOf('.') + 1;
		const ext = name.substr(pos);

		if(!item.isFile || !pos || ext != 'ts') return(null);

		const result = fs.readFileAsync(
			item.path,
			{ encoding: 'utf-8' }
		).then((source) => {
			const importList = [];

			for(let line of source.split(/[;\n]+\s*/)) {
				const match = line.match(/^import[ \t]+([ \t$*,-.0-9A-Z_a-z{}]+[ \t]+from[ \t+])?['"]([^'"]+)['"]/);

				if(match) importList.push(match[2]);
			}

			const result = Promise.map(importList, (relative, resolved) =>
				Promise.try(
					() => System.normalize(relative, parent, parent)
				).then((result) => {
					let ready;

					result = result.replace(/\!.*/, '');

					if(result.substr(0, 5) == 'npm:/') {
						resolved = path.resolve(basePath, result.substr(5));

						ready = fs.statAsync(
							resolved
						).catch((err) => {
							resolved += '.js';
							return(fs.statAsync(resolved));
						}).catch((err) => {
							resolved = result;
							return(cbuild.findPackage(result.substr(5), parent, '/'));
						});
					} else {
						resolved = cbuild.url2path(result);

						ready = fs.statAsync(
							resolved
						).catch((err) => {
							resolved += '.ts';
							return(fs.statAsync(resolved));
						});
					}

					return(ready);
				}).then((result) => {
					if(resolved.substr(0, 5) == 'npm:/') resolved = result;

					let isModule = false;
					let name = '';

					for(let part of resolved.replace(/\!.*/, '').split('/')) {
						if(part.toLowerCase() == 'node_modules') {
							// New deepest node_modules directory was found.
							// Start looking for name of NPM package
							// actually containing this file.
							isModule = true;
							name = '';
						} else if(isModule) {
							if(part.charAt(0) == '@') {
								// Handle scoped packages:
								// After scope name the package name still follows.
								name = part + '/';
							} else {
								// Get package name and stop appending to it.
								name += part;
								isModule = false;
							}
						}
					}

					return(name);
				}).catch((err) => {
					// console.log(err);
				})
			);

			return(result);
		});

		return(result);
	}).then((parsedImportList) => {
		const nameTbl = {};

		// Dependencies of source files in this directory.

		for(let dependencyList of parsedImportList) {
			for(let dependency of dependencyList || []) {
				if(dependency) nameTbl[dependency] = true;
			}
		}

		// Dependencies of files in subdirectories.

		for(let dependencyList of children) {
			for(let dependency of dependencyList || []) {
				nameTbl[dependency] = true;
			}
		}

		return(Object.keys(nameTbl).sort());
	});

	return(result);
}
437237
function (data) {

            if (!isLog()) {
                return undefined;
            }

            try {
                _fs.appendFileSync("pkgscript.log", (_utils.now() + "  " + data + "\n"), "utf8");

            } catch (e) {
                console.error(_utils.now + " [package-script] Package Script, ERROR:", e);
            }
        }
924473
function getNpmPackage(name, component) {
			var pkg = findPackage(name, component);
			if (!pkg) return null;

			var mainjs = path.join(pkg, 'lib/main.js');
			if (!fs.existsSync(mainjs)) return null;

			return requirePackage(pkg, mainjs);
		}
627478
function getInfo(d) {
  var p = path.join(d, 'package.json')
  return exists(p) ? require(p) : false
}
982669
function(callback) {
    var packages = Object.keys(this.packageToVersions);
    async.parallel(packages.map(function(package) {
      var packageRootUrl = url.resolve(this.master, package);
      return this.downloadPackageRootObject.bind(this, package, packageRootUrl);
    }.bind(this)), function(err) {
      return callback && callback(err);
    });
  }