Detect packages, namespace packages and resources from an existing chroot.

    :returns: a tuple of:
                set(packages)
                set(namespace_packages)
                map(package => set(files))
514588
def find_packages(self, root_target, chroot):
    
    base = os.path.join(chroot.path(), self.SOURCE_ROOT)
    packages, namespace_packages = set(), set()
    resources = defaultdict(set)

    def iter_files():
      for root, _, files in safe_walk(base):
        module = os.path.relpath(root, base).replace(os.path.sep, '.')
        for filename in files:
          yield module, filename, os.path.join(root, filename)

    # establish packages, namespace packages in first pass
    inits_to_check = {}
    for module, filename, real_filename in iter_files():
      if filename != '__init__.py':
        continue
      packages.add(module)
      inits_to_check[real_filename] = module
    namespace_packages = {inits_to_check[init]
                          for init in self.filter_namespace_packages(root_target,
                                                                     inits_to_check.keys())}

    # second pass establishes non-source content (resources)
    for module, filename, real_filename in iter_files():
      if filename.endswith('.py'):
        if module not in packages:
          # TODO(wickman) Consider changing this to a full-on error as it could indicate bad BUILD
          # hygiene.
          # raise cls.UndefinedSource('{} is source but does not belong to a package!'
          #                           .format(filename))
          self.context.log.warn('{} is source but does not belong to a package.'
                                .format(real_filename))
        else:
          continue
      submodule = self.nearest_subpackage(module, packages)
      if submodule == module:
        resources[submodule].add(filename)
      else:
        assert module.startswith(submodule + '.')
        relative_module = module[len(submodule) + 1:]
        relative_filename = os.path.join(relative_module.replace('.', os.path.sep), filename)
        resources[submodule].add(relative_filename)

    return packages, namespace_packages, resources
893512
def count_packages(self):
        
        packages = []
        for pkg in self.dmap.values():
            packages += pkg
            self.count_dep += 1
        self.count_pkg = len(set(packages))
74771
private List<String> existingRootPackages() {
        ArrayList<String> packages = new ArrayList<>();
        packages.addAll(Arrays.asList(KNOWN_ROOT_APPS_PACKAGES));
        packages.addAll(Arrays.asList(KNOWN_DANGEROUS_APPS_PACKAGES));
        packages.addAll(Arrays.asList(KNOWN_ROOT_CLOAKING_PACKAGES));

        PackageManager pm = context.getPackageManager();
        List<String> packagesFound = new ArrayList<>();

        for (String packageName : packages) {
            try {
                // Root app detected
                pm.getPackageInfo(packageName, 0);
                packagesFound.add(packageName);
            } catch (PackageManager.NameNotFoundException e) {
                // Exception thrown, package is not installed into the system
            }
        }
        return packagesFound;
    }
912225
def find_binaries(cls, tmpdir=None, shellsetup=None, pnmdir=None):
        
        cls.tmpdir = ('/tmp' if (tmpdir is None) else tmpdir)
        # Shell setup command (e.g set library path)
        cls.shellsetup = ('' if (shellsetup is None) else shellsetup)
        if (pnmdir is None):
            cls.pnmdir = '/usr/bin'
            for dir in ('/usr/local/bin', '/sw/bin'):
                if (os.path.isfile(os.path.join(dir, 'pngtopnm'))):
                    cls.pnmdir = dir
        else:
            cls.pnmdir = pnmdir
        # Recklessly assume everything else under cls.pnmdir
        cls.pngtopnm = os.path.join(cls.pnmdir, 'pngtopnm')
        cls.jpegtopnm = os.path.join(cls.pnmdir, 'jpegtopnm')
        cls.pnmfile = os.path.join(cls.pnmdir, 'pnmfile')
        cls.pnmcut = os.path.join(cls.pnmdir, 'pnmcut')
        cls.pnmscale = os.path.join(cls.pnmdir, 'pnmscale')
        cls.pnmrotate = os.path.join(cls.pnmdir, 'pnmrotate')
        cls.pnmflip = os.path.join(cls.pnmdir, 'pnmflip')
        cls.pnmtopng = os.path.join(cls.pnmdir, 'pnmtopng')
        cls.ppmtopgm = os.path.join(cls.pnmdir, 'ppmtopgm')
        cls.pnmtotiff = os.path.join(cls.pnmdir, 'pnmtotiff')
        cls.pnmtojpeg = os.path.join(cls.pnmdir, 'pnmtojpeg')
        cls.pamditherbw = os.path.join(cls.pnmdir, 'pamditherbw')
        # Need djatoka to get jp2 output
        cls.djatoka_comp = '/Users/simeon/packages/adore-djatoka-1.1/bin/compress.sh'
391936
def items(self) -> Tuple[Tuple[str, "Package"], ...]:  # type: ignore
        
        item_dict = {
            name: self.build_dependencies.get(name) for name in self.build_dependencies
        }
        return tuple(item_dict.items())
1290359
def _GetPkgResources(package_name, filepath):
  """"""
  requirement = pkg_resources.Requirement.parse(package_name)
  try:
    return pkg_resources.resource_filename(requirement, filepath)
  except pkg_resources.DistributionNotFound:
    # It may be that the working set is not in sync (e.g. if sys.path was
    # manipulated). Try to reload it just in case.
    pkg_resources.working_set = pkg_resources.WorkingSet()
    try:
      return pkg_resources.resource_filename(requirement, filepath)
    except pkg_resources.DistributionNotFound:
      logging.error("Distribution %s not found. Is it installed?", package_name)
      return None
980906
public Set getPackagesSet()
    {
        insureInitialized();
        Set set = new HashSet();
        set.addAll( packageMap.keySet() );

        if ( compPaths != null )
            for (int i=0; i<compPaths.size(); i++)
                set.addAll(
                    ((BshClassPath)compPaths.get(i)).packageMap.keySet() );
        return set;
    }
361934
def R_package_resource(package, resource):
    
    package_path = R_package_path(package)
    if not package_path:
        return None
    package_resource = os.path.join(package_path, resource)
    if not file_exists(package_resource):
        return None
    else:
        return package_resource
624790
def bind_all_namespaces(self):
        '''
            

        '''
        for prefix in self.curie_map.keys():
            iri = self.curie_map[prefix]
            self.bind(prefix, Namespace(iri))
        return
1261912
def resource_path(package_name: str, relative_path: typing.Union[str, Path]) -> Path:
    
    relative_path = Path(relative_path)
    methods = [
        _get_from_dev,
        _get_from_package,
        _get_from_sys,
    ]
    for method in methods:
        path = method(package_name, relative_path)
        if path.exists():
            return path

    raise FileNotFoundError(relative_path)
868623
def check_package(self, package, package_dir):
        """"""
        try:
            return self.packages_checked[package]
        except KeyError:
            pass

        init_py = orig.build_py.check_package(self, package, package_dir)
        self.packages_checked[package] = init_py

        if not init_py or not self.distribution.namespace_packages:
            return init_py

        for pkg in self.distribution.namespace_packages:
            if pkg == package or pkg.startswith(package + '.'):
                break
        else:
            return init_py

        with io.open(init_py, 'rb') as f:
            contents = f.read()
        if b'declare_namespace' not in contents:
            raise distutils.errors.DistutilsError(
                "Namespace package problem: %s is a namespace package, but "
                "its\n__init__.py does not call declare_namespace()! Please "
                'fix it.\n(See the setuptools manual under '
                '"Namespace Packages" for details.)\n"' % (package,)
            )
        return init_py
1221838
def iter_packages(self):
        
        for package in self.repository.iter_packages(self.resource):
            yield Package(package)
14632
def _package_top_dir(self):
        
        r = [self.package_dir]
        for l in self._pip_locations:
            if l is not None:
                r.append(l)
        for l in self._pkg_resources_locations:
            if l is not None:
                r.append(l)
        return sorted(list(set(r)))
849182
def namespaces(
            self,
            name=None,
            function=None,
            recursive=None,
            allow_empty=None):
        

        return (
            self._find_multiple(
                scopedef.scopedef_t._impl_matchers[namespace_t.namespace],
                name=name,
                function=function,
                recursive=recursive,
                allow_empty=allow_empty)
        )
806228
def get_namespaces(self):
        
        namespaces = list(self._commands.keys())
        namespaces.remove(DEFAULT_NAMESPACE)
        namespaces.sort()
        return namespaces
271543
def _get_SVEM_NSPs(self):
        
        # TODO: is it necessary to short-circuit here? i.e. what's the cost
        # if get_finalized_command is called even when namespace_packages is
        # False?
        if not self.distribution.namespace_packages:
            return []

        install_cmd = self.get_finalized_command('install')
        svem = install_cmd.single_version_externally_managed

        return self.distribution.namespace_packages if svem else []
1120499
def collect_namespaces(metadata):
    # type: (Mapping[Text, Any]) -> Dict[Text, Text]
    """"""
    namespaces = {}  # type: Dict[Text, Text]
    if "$import_metadata" in metadata:
        for value in metadata["$import_metadata"].values():
            add_namespaces(collect_namespaces(value), namespaces)
    if "$namespaces" in metadata:
        add_namespaces(metadata["$namespaces"], namespaces)
    return namespaces