Return a search function for searching a directory of packages, which has an index.json file
        created by the `mp install file` command.

        This will only search the issued index; it will not return results for the source index
358517
def search_json_indexed_directory(directory):
        

        from metapack.index import SearchIndex, search_index_file

        idx = SearchIndex(search_index_file())

        def _search_function(url):

            packages = idx.search(url, format='issued')

            if not packages:
                return None

            package = packages.pop(0)

            try:
                resource_str = '#' + url.target_file if url.fragment[0] else ''

                return parse_app_url(package['url'] + resource_str, downloader=url.downloader)
            except KeyError as e:
                return None

        return _search_function
844799
def search_for(self, dependency):  # type: (Dependency) -> List[Package]
        
        if dependency.is_root:
            return PackageCollection(dependency, [self._package])

        for constraint in self._search_for.keys():
            if (
                constraint.name == dependency.name
                and constraint.constraint.intersect(dependency.constraint)
                == dependency.constraint
            ):
                packages = [
                    p
                    for p in self._search_for[constraint]
                    if dependency.constraint.allows(p.version)
                ]

                packages.sort(
                    key=lambda p: (
                        not p.is_prerelease() and not dependency.allows_prereleases(),
                        p.version,
                    ),
                    reverse=True,
                )

                return PackageCollection(dependency, packages)

        if dependency.is_vcs():
            packages = self.search_for_vcs(dependency)
        elif dependency.is_file():
            packages = self.search_for_file(dependency)
        elif dependency.is_directory():
            packages = self.search_for_directory(dependency)
        else:
            constraint = dependency.constraint

            packages = self._pool.find_packages(
                dependency.name,
                constraint,
                extras=dependency.extras,
                allow_prereleases=dependency.allows_prereleases(),
            )

            packages.sort(
                key=lambda p: (
                    not p.is_prerelease() and not dependency.allows_prereleases(),
                    p.version,
                ),
                reverse=True,
            )

        self._search_for[dependency] = packages

        return PackageCollection(dependency, packages)
503197
def execute_finder(self, manager, package_name):
        
        filename = '{env_path}/results.json'.format(env_path=manager.env_path)
        subprocess.call([
            manager.venv_python, self._finder_path, package_name, filename
        ])

        # Load results into this context
        json_str = open(filename, 'r').read()
        return json.loads(json_str)
547694
def read_package_directives(dirname, filename)
      package = JSON.parse(File.read(filename), create_additions: false)

      case package['main']
      when String
        yield File.expand_path(package['main'], dirname)
      when nil
        yield File.expand_path('index.js', dirname)
      end

      yield File.expand_path(package['style'], dirname) if package['style']
    end
207214
function find(deleted, file) {
    var meta = bundle[file].meta
      , match = files.some(function some (file) {
          return file === meta.location || ~meta.location.indexOf(file)
            || (meta.compiler && ~meta.compiler.imported.join(',').indexOf(file));
        });

    if (!match) return;

    // If we check previous for deleted files, don't read content.
    if (!deleted) {
      self.hold(meta.location); // Temporary freeze of the event loop.
      self.package.bundle[file].meta.content = fs.readFileSync(meta.location, 'utf8');
    }

    // Add the file extension to the extensions list so we can create
    // a dedicated rebuild.
    extensions.push(meta.output);
    changes.push(file);
  }
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;
}
852324
function findProjectFiles({projectNotRequired}) {
    assert_internal([true, false].includes(projectNotRequired));

    const userDir = getUserDir();
 // console.log(require.resolve('@brillout/get-user-dir'));
    assert_internal(userDir);

    const packageJsonFile = find_up.sync('package.json', {cwd: userDir});
    assert_internal(packageJsonFile===null || pathModule.isAbsolute(packageJsonFile));

    const reframeConfigFile = find_up.sync('reframe.config.js', {cwd: userDir});
    assert_internal(reframeConfigFile===null || pathModule.isAbsolute(reframeConfigFile));

    if( projectNotRequired && (!packageJsonFile || !reframeConfigFile) ) {
        return {};
    }

    assert_usage(
        packageJsonFile,
        "Can't find project because no `package.json` file has been found between `"+userDir+"` and `/`."
    );
    assert_usage(
        reframeConfigFile,
        "Can't find project because no `reframe.config.js` file has been found between `"+userDir+"` and `/`."
    );

    assert_usage(
        pathModule.dirname(packageJsonFile)===pathModule.dirname(reframeConfigFile),
        "Your `reframe.config.js` and `package.json` should be located in the same directory.",
        "This is not the case: `"+packageJsonFile+"`, `"+reframeConfigFile+"`."
    );

    const projectRootDir = pathModule.dirname(packageJsonFile);

    const pagesDir = find('pages/', {anchorFiles: ['package.json'], canBeMissing: true, cwd: userDir});
    assert_internal(pagesDir===null || pathModule.isAbsolute(pagesDir));

    return {packageJsonFile, reframeConfigFile, pagesDir, projectRootDir};
}
1109446
function getPackageSet(index, callback) {
	var page = {
		limit  : 100,
		offset : index*100
	}

	ckan.exec('current_package_list_with_resources', page, function(err, resp){
		checkError(err, resp);
		
		for( var i = 0; i < resp.result.length; i++ ) {
			data.packages[resp.result[i].id] = resp.result[i];
		}

		if( resp.result.length == 0 ) {
			if( callback ) callback();
		} else {
			if( options.debug ) console.log("CKAN EXPORT: Package data loaded ("+(index*100)+" to "+((index+1)*100)+")");
			index++;
			getPackageSet(index, callback);
		}
	});
}
1280683
def search_pkg(name, repo):
    
    PACKAGES_TXT = Utils().read_file(_meta_.lib_path + "{0}_repo/"
                                     "PACKAGES.TXT".format(repo))
    names = Utils().package_name(PACKAGES_TXT)
    blacklist = BlackList().packages(pkgs=names, repo=repo)
    for line in PACKAGES_TXT.splitlines():
        status(0)
        if line.startswith("PACKAGE NAME:  ") and len(line) > 16:
            pkg_name = split_package(line[15:])[0].strip()
            if name == pkg_name and name not in blacklist:
                return pkg_name
854001
function getConfigSettings(packageJsonFile) {
  // Locate and read package.json
  const pkg = JSON.parse(fs.readFileSync(packageJsonFile));

  return {
    searchDir:
      getConfigSetting(pkg, 'searchDir', true) || getDefaultValue('searchDir'),
    outputFile:
      getConfigSetting(pkg, 'outputFile') || getDefaultValue('outputFile'),
    pattern: getConfigSetting(pkg, 'pattern') || getDefaultValue('pattern'),
  };
}
329712
def _find_packages_iter(cls, where, exclude, include):
        
        for root, dirs, files in os.walk(where, followlinks=True):
            # Copy dirs to iterate over it, then empty dirs.
            all_dirs = dirs[:]
            dirs[:] = []

            for dir in all_dirs:
                full_path = os.path.join(root, dir)
                rel_path = os.path.relpath(full_path, where)
                package = rel_path.replace(os.path.sep, '.')

                # Skip directory trees that are not valid packages
                if ('.' in dir or not cls._looks_like_package(full_path)):
                    continue

                # Should this package be included?
                if include(package) and not exclude(package):
                    yield package

                # Keep searching subdirectories, as there may be more packages
                # down there, even if the parent was excluded.
                dirs.append(dir)
121802
function getPackageMetaFile(answers) {
    const packageFields = ['name', 'version', 'license', 'category'];
    const packageObject = merge(pick(packageFields, answers),
        { dependencies: { 'rung-cli': '1.0.0' } });

    return {
        filename: path.join(answers.name, 'package.json'),
        content: JSON.stringify(packageObject, null, 2)
    };
}
627478
function getInfo(d) {
  var p = path.join(d, 'package.json')
  return exists(p) ? require(p) : false
}
227585
function findProjectRoot(currentPath) {
  var result = undefined;

  try {
    var packageStats = lstatSync(path.join(currentPath, 'package.json'));

    if (packageStats.isFile()) {
      result = currentPath;
    }
  } catch (error) {
    if (currentPath !== path.resolve('/')) {
      result = findProjectRoot(path.join(currentPath, '..'));
    }
  }

  return result;
}
1206286
def search(query, team=None):
    
    if team is None:
        team = _find_logged_in_team()

    if team is not None:
        session = _get_session(team)
        response = session.get("%s/api/search/" % get_registry_url(team), params=dict(q=query))
        print("* Packages in team %s" % team)
        packages = response.json()['packages']
        for pkg in packages:
            print(("%s:" % team) + ("%(owner)s/%(name)s" % pkg))
        if len(packages) == 0:
            print("(No results)")
        print("* Packages in public cloud")

    public_session = _get_session(None)
    response = public_session.get("%s/api/search/" % get_registry_url(None), params=dict(q=query))
    packages = response.json()['packages']
    for pkg in packages:
        print("%(owner)s/%(name)s" % pkg)
    if len(packages) == 0:
        print("(No results)")
58905
def search_packages_info(query):
    
    installed = {}
    for p in pkg_resources.working_set:
        installed[canonicalize_name(p.project_name)] = p

    query_names = [canonicalize_name(name) for name in query]

    for dist in [installed[pkg] for pkg in query_names if pkg in installed]:
        package = {
            'name': dist.project_name,
            'version': dist.version,
            'location': dist.location,
            'requires': [dep.project_name for dep in dist.requires()],
        }
        file_list = None
        if isinstance(dist, pkg_resources.DistInfoDistribution):
            # RECORDs should be part of .dist-info metadatas
            if dist.has_metadata('RECORD'):
                lines = dist.get_metadata_lines('RECORD')
                paths = [l.split(',')[0] for l in lines]
                paths = [os.path.join(dist.location, p) for p in paths]
                file_list = [os.path.relpath(p, dist.location) for p in paths]
        else:
            # Otherwise use pip's log for .egg-info's
            if dist.has_metadata('installed-files.txt'):
                paths = dist.get_metadata_lines('installed-files.txt')
                paths = [os.path.join(dist.egg_info, p) for p in paths]
                file_list = [os.path.relpath(p, dist.location) for p in paths]

        if file_list:
            package['files'] = sorted(file_list)
        yield package
413962
def locate_resource(name, lang, filter=None):
  
  task_dir = resource_dir.get(name, name)
  package_id = u"{}.{}".format(task_dir, lang)
  p = path.join(polyglot_path, task_dir, lang)
  if not path.isdir(p):
    if downloader.status(package_id) != downloader.INSTALLED:
      raise ValueError("This resource is available in the index "
                       "but not downloaded, yet. Try to run\n\n"
                       "polyglot download {}".format(package_id))
  return path.join(p, os.listdir(p)[0])