Use setuptools to search for a package's URI

    @returns: URI string
773267
def get_download_uri(package_name, version, source, index_url=None):

    
    tmpdir = None
    force_scan = True
    develop_ok = False
    if not index_url:
        index_url = 'http://cheeseshop.python.org/pypi'

    if version:
        pkg_spec = "%s==%s" % (package_name, version)
    else:
        pkg_spec = package_name
    req = pkg_resources.Requirement.parse(pkg_spec)
    pkg_index = MyPackageIndex(index_url)
    try:
        pkg_index.fetch_distribution(req, tmpdir, force_scan, source,
                develop_ok)
    except DownloadURI as url:
        #Remove #egg=pkg-dev
        clean_url = url.value.split("#")[0]
        #If setuptools is asked for an egg and there isn't one, it will
        #return source if available, which we don't want.
        if not source and not clean_url.endswith(".egg") and \
                not clean_url.endswith(".EGG"):
            return
        else:
            return clean_url
977387
function () {
            var self = this,
                t,
                fullPathUri,
                packageBaseUri,
                packageInfo,
                packageName,
                path;
            if (!self.fullPathUri) {
                if (self.fullpath) {
                    fullPathUri = new S.Uri(self.fullpath);
                } else {
                    packageInfo = self.getPackage();
                    packageBaseUri = packageInfo.getBaseUri();
                    path = self.getPath();
                    // #262
                    if (packageInfo.isIgnorePackageNameInUri() &&
                        // native mod does not allow ignore package name
                        (packageName = packageInfo.getName())) {
                        path = Path.relative(packageName, path);
                    }
                    fullPathUri = packageBaseUri.resolve(path);
                    if (t = self.getTag()) {
                        t += '.' + self.getType();
                        fullPathUri.query.set('t', t);
                    }
                }
                self.fullPathUri = fullPathUri;
            }
            return self.fullPathUri;
        }
104344
def find_packages(recursive=True, maxdepth=None):
    
    import utool
    if utool.VERBOSE:
        print('[util_setup] find_packages(recursive=%r, maxdepth=%r)' % (recursive, maxdepth))
    from os.path import relpath
    cwd = os.getcwd()
    init_files = utool.glob(cwd, '__init__.py', recursive=recursive, maxdepth=maxdepth)
    package_paths = list(map(dirname, init_files))
    package_relpaths = [relpath(path, cwd) for path in package_paths]

    packages = []
    for path in package_relpaths:
        base = utool.dirsplit(path)[0]
        if exists(join(base, '__init__.py')):
            package = path.replace('/', '.').replace('\\', '.')
            packages.append(package)
    return packages
1043347
def yum_install_from_url(pkg_name, url):
    
    if is_package_installed(distribution='el', pkg=pkg_name) is False:
        log_green(
            "installing %s from %s" % (pkg_name, url))
        with settings(hide('warnings', 'running', 'stdout', 'stderr'),
                      warn_only=True, capture=True):

            result = sudo("rpm -i %s" % url)
            if result.return_code == 0:
                return True
            elif result.return_code == 1:
                return False
            else:  # print error to user
                print(result)
                raise SystemExit()
1225624
def _get_repos(self):
        
        result = {}
        for xmlpath in self.installed:
            repo = RepositorySettings(self, xmlpath)
            result[repo.name.lower()] = repo

        return result
604280
def find_packages(root_directory: str = '.') -> t.List[str]:
    """"""
    exclude = ['test*', 'test.*'] if ('bdist_wheel' in sys.argv or 'bdist' in sys.argv) else []
    packages_list = setuptools.find_packages(root_directory, exclude=exclude)
    return packages_list
478821
def package_url(self):
        """"""

        if self.resource_file == DEFAULT_METATAB_FILE or self.target_format in ('txt','ipynb'):
            u = self.inner.clone().clear_fragment()
            u.path = dirname(self.path) + '/'
            u.scheme_extension = 'metapack'
        else:
            u = self

        return MetapackPackageUrl(str(u.clear_fragment()), downloader=self._downloader)
357165
def via_find_packages(self):  # type: () -> List[str]
        
        packages = []  # type: List[str]
        source = self.setup_py_source()
        if not source:
            return packages
        find_package_args = ""
        for row in source.split("\n"):
            if "find_packages" in row:
                logger.debug(row)
                if "find_packages()" in row:
                    packages = find_packages()
                else:
                    try:

                        find_package_args_source = row.split("(")[1].split(")")[0]
                        find_package_args = ast.literal_eval(find_package_args_source)
                        logger.debug(packages)
                    except:
                        logger.debug(source)
                        # raise
        if not find_package_args:
            packages = find_packages()
        else:
            try:
                # signature find(cls, where='.', exclude=(), include=('*',)):
                packages = find_packages(find_package_args)
            except:
                packages = find_packages()

        return packages
431296
def _build_package_finder(options, index_urls, session):
        
        return PackageFinder(
            find_links=options.get('find_links'),
            index_urls=index_urls,
            allow_all_prereleases=options.get('pre'),
            trusted_hosts=options.get('trusted_hosts'),
            session=session,
        )
110106
def get_install_paths(name):
    
    paths = {}

    i = get_install_command(name)

    for key in install.SCHEME_KEYS:
        paths[key] = getattr(i, 'install_' + key)

    # pip uses a similar path as an alternative to the system's (read-only)
    # include directory:
    if hasattr(sys, 'real_prefix'):  # virtualenv
        paths['headers'] = os.path.join(sys.prefix,
                                        'include',
                                        'site',
                                        'python' + sys.version[:3],
                                        name)

    return paths
944382
def parse_package_name(self):  # type: () -> Optional[str]
        
        if not self.setup_source:
            return None
        for row in self.setup_source.split("\n"):
            simplified_row = row.replace(" ", "").replace("'", '"').strip(" \t\n")
            if "name=" in simplified_row:
                if '"' in simplified_row:
                    return simplified_row.split('"')[1]

        name = self.execute_setup_name()
        if name:
            return name

        return ""
680565
function getPackageConfigMatch(loader, normalized) {
    var pkgName, exactMatch = false, configPath;
    for (var i = 0; i < loader.packageConfigPaths.length; i++) {
      var packageConfigPath = loader.packageConfigPaths[i];
      var p = packageConfigPaths[packageConfigPath] || (packageConfigPaths[packageConfigPath] = createPkgConfigPathObj(packageConfigPath));
      if (normalized.length < p.length)
        continue;
      var match = normalized.match(p.regEx);
      if (match && (!pkgName || (!(exactMatch && p.wildcard) && pkgName.length < match[1].length))) {
        pkgName = match[1];
        exactMatch = !p.wildcard;
        configPath = pkgName + packageConfigPath.substr(p.length);
      }
    }

    if (!pkgName)
      return;

    return {
      packageName: pkgName,
      configPath: configPath
    };
  }
767390
def _find_pip_info(self):
        
        res = {}
        dist = None
        dist_name = self.package_name.replace('_', '-')
        logger.debug('Checking for pip distribution named: %s', dist_name)
        for d in pip.get_installed_distributions():
            if d.project_name == dist_name:
                dist = d
        if dist is None:
            logger.debug('could not find dist matching package_name')
            return res
        logger.debug('found dist: %s', dist)
        self._pip_locations = [dist.location]
        ver, url = self._dist_version_url(dist)
        res['version'] = ver
        res['url'] = url
        # this is a bit of an ugly, lazy hack...
        req = pip.FrozenRequirement.from_dist(dist, [])
        logger.debug('pip FrozenRequirement: %s', req)
        res['requirement'] = str(req.req)
        return res
353649
def print_download_uri(self, version, source):
        

        if version == "dev":
            pkg_type = "subversion"
            source = True
        elif source:
            pkg_type = "source"
        else:
            pkg_type = "egg"

        #Use setuptools monkey-patch to grab url
        url = get_download_uri(self.project_name, version, source,
                self.options.pypi_index)
        if url:
            print("%s" % url)
        else:
            self.logger.info("No download URL found for %s" % pkg_type)
1106194
def setup!
      return self if @app_is_setup
      puts "Hatchet setup: #{name.inspect} for #{repo_name.inspect}"
      create_git_repo! unless is_git_repo?
      create_app
      set_labs!
      buildpack_list = @buildpacks.map { |pack| { buildpack: pack } }
      api_rate_limit.call.buildpack_installation.update(name, updates: buildpack_list)
      set_config @app_config

      call_before_deploy
      @app_is_setup = true
      self
    end
894406
def dependency_context(package_names, aggressively_remove=False):
	
	installed_packages = []
	log = logging.getLogger(__name__)
	try:
		if not package_names:
			logging.debug('No packages requested')
		if package_names:
			lock = yg.lockfile.FileLock(
				'/tmp/.pkg-context-lock',
				timeout=30 * 60)
			log.info('Acquiring lock to perform install')
			lock.acquire()
			log.info('Installing ' + ', '.join(package_names))
			output = subprocess.check_output(
				['sudo', 'aptitude', 'install', '-y'] + package_names,
				stderr=subprocess.STDOUT,
			)
			log.debug('Aptitude output:\n%s', output)
			installed_packages = jaraco.apt.parse_new_packages(
				output,
				include_automatic=aggressively_remove)
			if not installed_packages:
				lock.release()
			log.info('Installed ' + ', '.join(installed_packages))
		yield installed_packages
	except subprocess.CalledProcessError:
		log.error("Error occurred installing packages")
		raise
	finally:
		if installed_packages:
			log.info('Removing ' + ','.join(installed_packages))
			subprocess.check_call(
				['sudo', 'aptitude', 'remove', '-y'] + installed_packages,
				stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
			)
			lock.release()
1076860
def _build_package_finder(self, options, index_urls, session):
        
        return PackageFinder(
            find_links=options.find_links,
            index_urls=index_urls,
            allow_all_prereleases=options.pre,
            trusted_hosts=options.trusted_hosts,
            session=session,
        )