Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 25 additions & 2 deletions importlib_metadata/diagnose.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,29 @@
import sys

from . import Distribution
from . import Distribution, MetadataNotFound


def _locate(dist: Distribution) -> str:
"""
Indicate where the distribution's metadata was found.
"""
return str(getattr(dist, '_path', dist))


def describe(dist: Distribution) -> str:
"""
Describe the distribution by name, or by location when the
distribution is too invalid to name itself.

>>> describe(Distribution.at('missing-1.0.dist-info'))
'missing-1.0.dist-info (no metadata)'
"""
try:
return dist.name
except MetadataNotFound:
return f'{_locate(dist)} (no metadata)'
except KeyError:
return f'{_locate(dist)} (metadata without a name)'


def inspect(path):
Expand All @@ -9,7 +32,7 @@ def inspect(path):
if not dists:
return
print("Found", len(dists), "packages:", end=' ')
print(', '.join(dist.name for dist in dists))
print(', '.join(map(describe, dists)))


def run():
Expand Down
3 changes: 3 additions & 0 deletions newsfragments/548.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
``importlib_metadata.diagnose`` no longer crashes on a metadata directory
that has no metadata file or whose metadata declares no name. Such
distributions are now reported by their location.
19 changes: 19 additions & 0 deletions tests/test_main.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import contextlib
import importlib
import io
import pickle
import re
import unittest
Expand All @@ -13,6 +15,7 @@
MetadataNotFound,
PackageNotFoundError,
_unique,
diagnose,
distributions,
entry_points,
metadata,
Expand Down Expand Up @@ -169,6 +172,22 @@ def test_missing_metadata(self):
with self.assertRaises(MetadataNotFound):
metadata('foo')

def test_diagnose_reports_invalid(self):
"""
The diagnostic should report invalid dists by location
rather than crashing on them.

Ref python/importlib_metadata#548.
"""
fixtures.build_files(self.make_pkg('nameless-1.0'), self.site_dir)
fixtures.build_files(self.make_pkg('empty-1.0', files={}), self.site_dir)
out = io.StringIO()
with contextlib.redirect_stdout(out):
diagnose.inspect(str(self.site_dir))
report = out.getvalue()
assert 'empty-1.0.dist-info (no metadata)' in report
assert 'nameless-1.0.dist-info (metadata without a name)' in report


class NonASCIITests(fixtures.OnSysPath, fixtures.SiteDir, unittest.TestCase):
@staticmethod
Expand Down
Loading