def has_dist(dist): try: distribution(dist) return True except PackageNotFoundError: pass return False
def _get_version(): """ @return: Version Number """ try: from sys import version_info if version_info[0] < 3 or (version_info[0] and version_info[1] < 8): from importlib_metadata import PackageNotFoundError, distribution try: dist = distribution("splunk_eventgen") return dist.version except PackageNotFoundError: return "dev" else: # module change in python 3.8 from importlib.metadata import PackageNotFoundError, distribution try: dist = distribution("splunk_eventgen") return dist.version except PackageNotFoundError: return "dev" except ImportError: return "Unknown" except ModuleNotFoundError: return "Unknown" except Exception: return "Unknown"
def uncached_distribution_perf(): "uncached distribution" import importlib import importlib_metadata # end warmup importlib.invalidate_caches() importlib_metadata.distribution('ipython')
def _first_available_package(*package_list): for package in package_list: try: importlib_metadata.distribution(package) except importlib_metadata.PackageNotFoundError: continue return package return None
def from_name(cls, name: str) -> Package: """ Return a package instance from its distribution name. A factory class method that returns a package with its name and version, as well as requirements. Args: name: A package's distribution name. Returns: A package instance with its version and requirements if it is installed in the current environment; otherwise only the name is set whereas the version and requirements are empty. """ name = cls._normalize_name(name) try: dist = distribution(name) except PackageNotFoundError: result = cls(name=name, version=None, requirements=[]) else: result = cls( name=name, version=dist.version, requirements=[] if dist.requires is None else [cls._normalize_name(cls._get_name(req)) for req in dist.requires], ) return result
def element_factory(session): element_factory = session.get_service("element_factory") dist = importlib_metadata.distribution("gaphor") path = dist.locate_file("test-diagrams/issue_53.gaphor") load(path, element_factory) yield element_factory element_factory.shutdown()
def test_load_save(self): """Test loading and saving models""" dist = importlib_metadata.distribution("gaphor") path = dist.locate_file("test-diagrams/simple-items.gaphor") with open(path, "r") as ifile: storage.load(ifile, factory=self.element_factory) pf = PseudoFile() storage.save(XMLWriter(pf), factory=self.element_factory) with open(path, "r") as ifile: orig = ifile.read() copy = pf.data with open("tmp.gaphor", "w") as ofile: ofile.write(copy) expr = re.compile('gaphor-version="[^"]*"') orig = expr.sub("%VER%", orig) copy = expr.sub("%VER%", copy) self.maxDiff = None assert copy == orig, "Saved model does not match copy"
class Config: encoding = encoding format = 'text' excludes = ['pip', 'setuptools', 'wheel', 'pkg-resources', project_name] includes = list( map(lambda r: REQUIREMENT.parseString(r)[0], im.distribution(project_name).requires)) verbose = False graph = False outfile = cwd.joinpath(NOTICE_FILE).as_posix() def __init__(self, **kwargs): for key, val in kwargs.items(): setattr(self, key, val) if self.graph: self.includes.clear() def exclude_package(self, name: str): return self.excludes is not None and name in self.excludes def include_package(self, name: str): return not self.exclude_package(name) \ and self.includes is not None and name in self.includes def keep_dist(self, dist: im.Distribution): return self.include_package(dist.metadata['Name'])
def _describe_metadata_elements(group): infos = {} from datalad.support.entrypoints import iter_entrypoints from importlib import import_module if sys.version_info < (3, 10): # 3.10 is when it was no longer provisional from importlib_metadata import distribution else: from importlib.metadata import distribution for ename, emod, eload in iter_entrypoints(group): info = {} infos[f'{ename}'] = info try: info['module'] = emod dist = distribution(emod.split('.', maxsplit=1)[0]) info['distribution'] = f'{dist.name} {dist.version}' mod = import_module(emod, package='datalad') version = getattr(mod, '__version__', None) if version: # no not clutter the report with no version info['version'] = version eload() info['load_error'] = None except Exception as e: ce = CapturedException(e) info['load_error'] = ce.format_short() continue return infos
def get_package_version_without_import(name): """For given package name, try to find the version without importing it Import and package.__version__ is still the backup here, so an import *might* happen. Returns either the version string, or None if the package or the version was not readily found. """ if name in sys.modules: mod = sys.modules[name] if hasattr(mod, "__version__"): return mod.__version__ if sys.version_info >= (3, 8): try: import importlib.metadata return importlib.metadata.distribution(name).version except: # noqa: E722 pass else: try: import importlib_metadata return importlib_metadata.distribution(name).version except: # noqa: E722 pass try: import importlib mod = importlib.import_module(name) return mod.__version__ except (ImportError, AttributeError): return None
def about(self): logo_file = importlib_metadata.distribution("gaphor").locate_file( "gaphor/ui/pixmaps/gaphor-96x96.png" ) logo = GdkPixbuf.Pixbuf.new_from_file(str(logo_file)) about = Gtk.AboutDialog.new() about.set_logo(logo) about.set_title("About Gaphor") about.set_program_name("Gaphor") about.set_comments("Gaphor is the simple modeling tool written in Python") about.set_version(str(__version__)) about.set_copyright("Copyright (c) 2001-2019 Arjan J. Molenaar and Dan Yeaw") about.set_license( "This software is published under the terms of the\n" "Apache Software License, version 2.0.\n" "See the LICENSE.txt file for details." ) about.set_website("https://github.com/gaphor/gaphor") about.set_website_label("Fork me on GitHub") about.set_authors( [ "Arjan Molenaar, Artur Wroblewski,", "Jeroen Vloothuis, Dan Yeaw, ", "Enno Groeper, Adam Boduch, ", "Alexis Howells, Melis Doğan", ] ) about.set_translator_credits( "Jordi Mallach (ca), " "Antonin Delpeuch (fr), " "Ygor Mutti (pt_BR)" ) about.set_transient_for(self.main_window.window) about.show_all() about.run() about.destroy()
def load(self) -> "Porcupine": """Load Porcupine object.""" dist = importlib_metadata.distribution("pvporcupine") porcupine_paths = [ f for f in cast(List[importlib_metadata.PackagePath], dist.files) if f.name == "porcupine.py" ] if not porcupine_paths: raise RuntimeError("Unable to find porcupine.py in pvporcupine package") porcupine_path = porcupine_paths[0].locate().parent lib_path = porcupine_path.parent.parent sys.path.append(str(porcupine_path)) if not TYPE_CHECKING: # pylint: disable=import-outside-toplevel, import-error from porcupine import Porcupine return Porcupine( library_path=str(self._library_path(lib_path)), model_file_path=str(self._model_file_path(lib_path)), keyword_file_path=str(self._keyword_file_path(lib_path)), sensitivity=0.5, )
def get_importname_from_package(package_name: str) -> str: """ Try to fetch the name of the top-level import name for the given package. For some reason, this isn't straightforward. For now, we do not support distribution packages that contains multiple top-level packages. """ try: dist = importlib_metadata.distribution(package_name) except importlib_metadata.PackageNotFoundError: raise DiscoveryFailed("Package {p} not found ".format(p=package_name)) try: packages = dist.top_level except FileNotFoundError: raise DiscoveryFailed( "failed to load package {p} metadata. " "Was the package installed properly?".format(p=package_name)) if len(packages) > 1: raise DiscoveryFailed( "Package {p} contains multiple top-level packages. " "Unable to discover from multiple packages.".format( p=package_name)) return packages[0]
def handler(): try: dist = importlib_metadata.distribution("gaphor") path = dist.locate_file("test-diagrams/diagram-#4.gaphor") load(path, self.element_factory) finally: Gtk.main_quit()
def test_loading(): dist = importlib_metadata.distribution("gaphor") model_file = dist.locate_file("tests/test-model.gaphor") outfile = PseudoFile() generate(model_file, outfile) assert outfile.data == GENERATED, '"""%s"""' % outfile.data
def _get_version(): fallback = '0.0.0.dev0' try: dist = distribution(__package__) except PackageNotFoundError: return fallback inst_loc = str(dist.locate_file(join(__package__, '__version__.py'))) return dist.version if inst_loc == __file__ else fallback
def inflate(req: Dict[str, str], licenses: Dict[str, str]): pkg = req['name'] dist = distribution(pkg) record = dict(package=pkg) record["version"] = f"{dist.metadata['Version']}" record["url"] = f"{dist.metadata['Home-page']}" record["license"] = f"{dist.metadata['License']}" record["license_text"] = licenses.get(pkg, "") return record
def element_factory(): Application.init() element_factory = Application.get_service("element_factory") dist = importlib_metadata.distribution("gaphor") path = dist.locate_file("test-diagrams/issue_53.gaphor") load(path, element_factory) yield element_factory Application.get_service("element_factory").shutdown() Application.shutdown()
def test_bug(self): """ Load file. This does not nearly resemble the error, since the model should be loaded from within the mainloop (which will delay all updates). """ dist = importlib_metadata.distribution("gaphor") path = dist.locate_file("test-diagrams/diagram-#4.gaphor") load(path, self.element_factory)
def test_load_uml_metamodel(self): """ Test if the meta model can be loaded. """ dist = importlib_metadata.distribution("gaphor") path = dist.locate_file("gaphor/UML/uml2.gaphor") with open(path) as ifile: storage.load(ifile, factory=self.element_factory)
def test_loading_an_old_version(self): """Test loading and saving models""" dist = importlib_metadata.distribution("gaphor") path = dist.locate_file("test-diagrams/old-gaphor-version.gaphor") def load_old_model(): with io.open(path, "r") as ifile: storage.load(ifile, factory=self.element_factory) self.assertRaises(ValueError, load_old_model)
def _get_importlib_metadata_entry_points(package_name): # type: (str) -> None """Retrieve information about entry-points for the given package.""" import sys import importlib_metadata import json entry_points = importlib_metadata.distribution(package_name).entry_points print( json.dumps([{ "name": ep.name, "value": ep.value, "group": ep.group } for ep in entry_points])) sys.exit(0)
def get_extension_status(self) -> Optional[ExtensionStatus]: ext_name = self.name.split(".")[0] source_package_name = self.__class__.__module__.split(".")[0] # workaround for #2586 package_name = "inmanta-core" if source_package_name == "inmanta" else source_package_name try: distribution = importlib_metadata.distribution(package_name) return ExtensionStatus(name=ext_name, package=ext_name, version=distribution.version) except importlib_metadata.PackageNotFoundError: LOGGER.info( "Package %s of slice %s is not packaged in a distribution. Unable to determine its extension.", package_name, self.name, ) return None
def test_entry_points_by_index(self): """ Prior versions of Distribution.entry_points would return a tuple that allowed access by index. Capture this now deprecated use-case See python/importlib_metadata#300 and bpo-44246. """ eps = distribution('distinfo-pkg').entry_points with suppress_known_deprecation() as caught: eps[0] # check warning expected = next(iter(caught)) assert expected.category is DeprecationWarning assert "Accessing entry points by index is deprecated" in str(expected)
def version_info(parser): versions = OrderedDict() to_visit = {"tox"} while to_visit: current = to_visit.pop() current_dist = importlib_metadata.distribution(current) current_name = canonicalize_name(current_dist.metadata["name"]) versions[current_name] = current_dist.version if current_dist.requires is not None: for require in current_dist.requires: pkg = Requirement(require) pkg_name = canonicalize_name(pkg.name) if (pkg.marker is None or pkg.marker.evaluate( {"extra": ""})) and pkg_name not in versions: to_visit.add(pkg_name) set_section(parser, "tox:versions", versions)
def main(package, template, output): """recursive dependency pinning for package""" pinned_dep_graph = [] deps = [] package_deps(package, deps) for d in sorted(deps): pinned_dep_graph.append('%s==%s' % (d, pkgmd.distribution(d).version)) if not template and output: print('\n'.join(pinned_dep_graph)) return with open(template) as fh: t = jinja2.Template(fh.read(), trim_blocks=True, lstrip_blocks=True) with open(output, 'w') as fh: fh.write(t.render(pinned_packages=pinned_dep_graph))
def main(): parser = argparse.ArgumentParser() parser.add_argument('pkg') parser.add_argument('--include-extras', action='store_true') args = parser.parse_args() pkgname, *_ = args.pkg.partition('==') with tempfile.TemporaryDirectory() as tmp: cmd = ('pip', 'wheel', '--no-deps', args.pkg, '-w', tmp) subprocess.check_call(cmd, stdout=subprocess.DEVNULL) filename, = os.listdir(tmp) filename = os.path.join(tmp, filename) with onpath(filename): print('*' * 79) print(f'{args.pkg}:') dist = importlib_metadata.distribution(pkgname) for req in dist.metadata.get_all('requires-dist'): if not args.include_extras and 'extra == ' in req: continue print(f'- {req}')
def test_message_item_upgrade(element_factory): """ """ dist = importlib_metadata.distribution("gaphor") path = dist.locate_file("test-diagrams/multiple-messages.gaphor") elements = parse(path) load_elements(elements, element_factory) diagram = element_factory.lselect(lambda e: e.isKindOf(UML.Diagram))[0] items = diagram.canvas.get_root_items() message_items = [ i for i in items if isinstance(i, diagramitems.MessageItem) ] subjects = [m.subject for m in message_items] messages = element_factory.lselect(lambda e: e.isKindOf(UML.Message)) presentations = [m.presentation for m in messages] assert len(messages) == 10 assert all(subjects), subjects assert len(message_items) == 10 assert all(presentations), presentations
def get_version_using_importlib_metadata(module # type: ModuleType ): # type: (...) -> str """ Uses the importlib_metadata backport to read the version. See https://importlib-metadata.readthedocs.io/en/latest/using.html#overview Note: unfortunately this provides very bad answers in some cases (e.g. when the module is built-in) so we have to protect against them :param module: :return: """ # CAN RETURN SOMETHING CRAZY (the version of another distribution!) # return version(module.__name__) # WORKAROUND: proceed carefully and protect against crazy answers from importlib_metadata import distribution dist = distribution(module.__name__) # we have to do this sanity check if dist.metadata['Name'] == module.__name__: return dist.version
def get_pkg_info( package_name: str, additional: Iterable[str] = ("pip", "flit", "pbr", "poetry", "setuptools", "wheel"), ) -> Dict[str, str]: """Return build and package dependencies as a dict.""" dist = distribution(package_name) dependencies = {package_name: dist.version} for requirement in dist.requires: try: pkg, ver = _get_package_version(requirement) except PackageNotFoundError: dependencies[requirement] = "not installed" else: dependencies[pkg] = ver for name in additional: try: pkg, ver = _get_package_version(name) except PackageNotFoundError: continue else: dependencies[pkg] = ver return dependencies
def test_missing_metadata(self): distribution = importlib_metadata.distribution('example') self.assertIsNone(distribution.read_text('does not exist'))
def test_for_name_does_not_exist(self): with self.assertRaises(importlib_metadata.PackageNotFoundError): importlib_metadata.distribution('does-not-exist')
def test_for_top_level(self): distribution = importlib_metadata.distribution('importlib_metadata') self.assertEqual( distribution.read_text('top_level.txt').strip(), 'importlib_metadata')