depdelta-cli 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
depdelta_cli/main.py ADDED
@@ -0,0 +1,184 @@
1
+ # src/depdelta_cli/main.py
2
+ #
3
+ # `depdelta`: review the change's dependency updates and post the review on
4
+ # the change (a Gerrit message, or a GitLab merge request note).
5
+ #
6
+ # 1. The manifests and lockfiles the change touched go to DepDelta.
7
+ # 2. DepDelta answers with each update's verdict and, for npm and Maven,
8
+ # the declarations it removes or changes.
9
+ # 3. The command looks for those in the checkout and sends what it found;
10
+ # the review then says where the code is hit.
11
+ #
12
+ # Exit status: 0 posted (or nothing to review), 1 the --fail-on verdict was
13
+ # met, 2 it couldn't review or post.
14
+
15
+ import argparse
16
+ import os
17
+ import sys
18
+ from collections.abc import Mapping, Sequence
19
+
20
+ from depdelta_cli import __version__, check, gerrit, gitlab, web
21
+ from depdelta_cli.api import DEFAULT_API_URL, ApiError, DepDelta, Review
22
+ from depdelta_cli.env import Change, EnvError, GerritChange, GitLabMergeRequest
23
+ from depdelta_cli.env import detect as detect_change
24
+ from depdelta_cli.git import GitError, changed_manifests, ensure_commit, source_files
25
+
26
+ #: depdelta-api pull_diff MAX_FILES: manifests reviewed per change.
27
+ MAX_FILES = 40
28
+ #: Verdicts from riskiest; --fail-on X fails on X and anything riskier.
29
+ VERDICTS = ("breaking", "review", "unknown", "safe")
30
+
31
+
32
+ class UsageError(Exception):
33
+ """A required option or variable is missing."""
34
+
35
+
36
+ def parser() -> argparse.ArgumentParser:
37
+ p = argparse.ArgumentParser(
38
+ prog="depdelta",
39
+ description="Review a change's dependency updates with DepDelta and "
40
+ "post the review on the Gerrit change or GitLab merge request.",
41
+ )
42
+ p.add_argument("--version", action="version", version=f"depdelta {__version__}")
43
+ p.add_argument("--repo", default=".", help="The checkout (default: .)")
44
+ p.add_argument("--base", help="Compare from this commit (default: from CI)")
45
+ p.add_argument("--head", help="Compare to this commit (default: from CI)")
46
+ p.add_argument(
47
+ "--print",
48
+ dest="print_only",
49
+ action="store_true",
50
+ help="Print the review instead of posting it",
51
+ )
52
+ p.add_argument(
53
+ "--format",
54
+ choices=("markdown", "text"),
55
+ help="Review format (default: text for Gerrit, markdown otherwise)",
56
+ )
57
+ p.add_argument(
58
+ "--wait",
59
+ type=int,
60
+ default=300,
61
+ help="Seconds to wait for release notes to be read (default: 300)",
62
+ )
63
+ p.add_argument(
64
+ "--fail-on",
65
+ choices=("never", *VERDICTS),
66
+ default="never",
67
+ help="Exit 1 when an update's verdict is this or riskier (default: never)",
68
+ )
69
+ p.add_argument(
70
+ "--api-url",
71
+ default=None,
72
+ help=f"DepDelta API (default: $DEPDELTA_API_URL or {DEFAULT_API_URL})",
73
+ )
74
+ return p
75
+
76
+
77
+ def _need(env: Mapping[str, str], name: str, why: str) -> str:
78
+ value = env.get(name, "").strip()
79
+ if not value:
80
+ raise UsageError(f"Set {name} {why}.")
81
+ return value
82
+
83
+
84
+ def _change(args: argparse.Namespace, env: Mapping[str, str]) -> Change | None:
85
+ """The CI's change, or None for --base/--head given by hand."""
86
+ if args.base or args.head:
87
+ if not (args.base and args.head):
88
+ raise UsageError("Pass both --base and --head.")
89
+ return None
90
+ return detect_change(env)
91
+
92
+
93
+ def _review(
94
+ client: DepDelta,
95
+ args: argparse.Namespace,
96
+ files: list,
97
+ fmt: str,
98
+ source_url: str | None,
99
+ ) -> Review:
100
+ review = client.review(files, fmt=fmt, source_url=source_url, wait=args.wait)
101
+ wanted = check.ecosystems(review.updates)
102
+ if not wanted:
103
+ return review
104
+ sources = source_files(args.repo, wanted)
105
+ usage = check.usage(review.updates, sources)
106
+ log(f"Usage check: {sum(u['total'] for u in usage)} uses found.")
107
+ return client.review(
108
+ files, usage=usage, fmt=fmt, source_url=source_url, wait=args.wait
109
+ )
110
+
111
+
112
+ def _post(change: Change, review: Review, env: Mapping[str, str]) -> None:
113
+ target = change.target
114
+ if isinstance(target, GerritChange):
115
+ user = _need(env, "GERRIT_HTTP_USER", "to the Gerrit account that posts")
116
+ password = _need(env, "GERRIT_HTTP_PASSWORD", "to that account's HTTP password")
117
+ link = next((u["url"] for u in review.updates if u.get("url")), None)
118
+ gerrit.post(target, gerrit.fit(review.body, link), user, password)
119
+ log("Posted the review on the Gerrit change.")
120
+ elif isinstance(target, GitLabMergeRequest):
121
+ token = _need(env, "GITLAB_TOKEN", "to a token with the api scope")
122
+ done = gitlab.post(target, review.body, token)
123
+ log(f"Review note {done} on the merge request.")
124
+
125
+
126
+ def failed(review: Review, fail_on: str) -> bool:
127
+ """An update's verdict is ``fail_on`` or riskier."""
128
+ if fail_on == "never":
129
+ return False
130
+ worst = VERDICTS.index(fail_on)
131
+ return any(
132
+ u.get("verdict") in VERDICTS and VERDICTS.index(u["verdict"]) <= worst
133
+ for u in review.updates
134
+ )
135
+
136
+
137
+ def log(message: str) -> None:
138
+ print(f"depdelta: {message}", file=sys.stderr)
139
+
140
+
141
+ def run(argv: Sequence[str] | None = None, env: Mapping[str, str] | None = None) -> int:
142
+ args = parser().parse_args(argv)
143
+ env = os.environ if env is None else env
144
+ try:
145
+ change = _change(args, env)
146
+ base = change.base if change else args.base
147
+ head = change.head if change else args.head
148
+ for rev in (head, base):
149
+ ensure_commit(args.repo, rev)
150
+ files = changed_manifests(args.repo, base, head)
151
+ if not files:
152
+ log("The change touches no manifests or lockfiles: nothing to review.")
153
+ return 0
154
+ if len(files) > MAX_FILES:
155
+ log(f"{len(files)} manifests changed; reviewing the first {MAX_FILES}.")
156
+ files = files[:MAX_FILES]
157
+ key = _need(env, "DEPDELTA_API_KEY", "to an API key from DepDelta Settings")
158
+ api_url = args.api_url or env.get("DEPDELTA_API_URL") or DEFAULT_API_URL
159
+ fmt = args.format or (
160
+ "text" if change and change.platform == "gerrit" else "markdown"
161
+ )
162
+ source_url = change.source_url if change else None
163
+ review = _review(DepDelta(key, api_url), args, files, fmt, source_url)
164
+ log(f"{review.label} ({len(review.updates)} updates).")
165
+ if change is None or args.print_only:
166
+ print(review.body)
167
+ else:
168
+ _post(change, review, env)
169
+ except (
170
+ UsageError,
171
+ EnvError,
172
+ GitError,
173
+ ApiError,
174
+ gerrit.GerritError,
175
+ gitlab.GitLabError,
176
+ web.HttpError,
177
+ ) as error:
178
+ log(str(error))
179
+ return 2
180
+ return 1 if failed(review, args.fail_on) else 0
181
+
182
+
183
+ def main() -> None: # pragma: no cover
184
+ sys.exit(run())
@@ -0,0 +1,94 @@
1
+ # src/depdelta_cli/manifests.py
2
+ #
3
+ # Which changed files are manifests and lockfiles: only those are sent to
4
+ # DepDelta, never source code. The names follow depdelta-api
5
+ # (`app/reports/utils/manifests.py` and `app/github/utils/repos.py`); change
6
+ # them there first, then here.
7
+
8
+ import re
9
+
10
+ #: Supported manifests and lockfiles, by lower-cased file name.
11
+ MANIFEST_NAMES = frozenset(
12
+ {
13
+ "build.gradle",
14
+ "build.gradle.kts",
15
+ "cargo.lock",
16
+ "cargo.toml",
17
+ "composer.json",
18
+ "composer.lock",
19
+ "directory.packages.props",
20
+ "gemfile",
21
+ "gemfile.lock",
22
+ "gems.locked",
23
+ "gems.rb",
24
+ "go.mod",
25
+ "go.sum",
26
+ "libs.versions.toml",
27
+ "npm-shrinkwrap.json",
28
+ "package-lock.json",
29
+ "package.json",
30
+ "packages.config",
31
+ "packages.lock.json",
32
+ "pipfile.lock",
33
+ "pnpm-lock.yaml",
34
+ "poetry.lock",
35
+ "pom.xml",
36
+ "pubspec.lock",
37
+ "pubspec.yaml",
38
+ "pyproject.toml",
39
+ "requirements.txt",
40
+ "uv.lock",
41
+ "yarn.lock",
42
+ }
43
+ )
44
+ #: requirements-dev.txt, requirements.in.txt …
45
+ _REQUIREMENTS = re.compile(r"^requirements[\w.-]*\.txt$")
46
+ #: MSBuild project files: C# (MyApp.csproj), F# and Visual Basic.
47
+ _MSBUILD_PROJECT = re.compile(r"^.+\.(?:cs|fs|vb)proj$")
48
+
49
+ #: Vendored, generated and build directories: never read.
50
+ SKIP_DIRS = frozenset(
51
+ {
52
+ ".bundle",
53
+ ".dart_tool",
54
+ ".git",
55
+ ".gradle",
56
+ ".next",
57
+ ".nuxt",
58
+ ".venv",
59
+ "__fixtures__",
60
+ "__pycache__",
61
+ "bin",
62
+ "bower_components",
63
+ "build",
64
+ "dist",
65
+ "fixtures",
66
+ "node_modules",
67
+ "obj",
68
+ "out",
69
+ "site-packages",
70
+ "target",
71
+ "testdata",
72
+ "vendor",
73
+ "venv",
74
+ }
75
+ )
76
+
77
+
78
+ def skipped(path: str) -> bool:
79
+ """Inside a vendored, generated or build directory."""
80
+ return any(part in SKIP_DIRS for part in path.split("/")[:-1])
81
+
82
+
83
+ def is_manifest(path: str) -> bool:
84
+ """A supported manifest or lockfile outside vendored and build folders."""
85
+ if skipped(path):
86
+ return False
87
+ base = path.rsplit("/", 1)[-1].lower()
88
+ return (
89
+ base in MANIFEST_NAMES
90
+ or bool(_REQUIREMENTS.match(base))
91
+ # gradle/libs.versions.toml variants: deps.versions.toml
92
+ or base.endswith(".versions.toml")
93
+ or bool(_MSBUILD_PROJECT.match(base))
94
+ )
depdelta_cli/usage.py ADDED
@@ -0,0 +1,391 @@
1
+ # src/depdelta_cli/usage.py
2
+ #
3
+ # Where the checkout uses the declarations an update removes or changes.
4
+ # Copied from depdelta-api `app/updates/utils/usage.py` (the matching, not its
5
+ # tarball reading), so CI finds exactly what the GitHub App finds; change it
6
+ # there first, then copy it here. The code is read in CI and never sent: only
7
+ # the hits (path, line, symbol) go to DepDelta.
8
+ #
9
+ # Matching is a heuristic, per language:
10
+ # TS/JS files that import the package; what they import (named imports,
11
+ # a default or namespace import, require) used as the removed or
12
+ # changed declaration, or one of its members.
13
+ # Java/Kt files that can see the class (an import of it or of its
14
+ # package, living in its package, or naming it fully qualified);
15
+ # the class, its constructor or its members used (a getter read
16
+ # as a Kotlin property included). Kotlin top-level functions and
17
+ # properties (static members of a `FileKt` class) are matched by
18
+ # their own name where Kotlin files import them.
19
+ # A file that imports a removed declaration but never uses it beyond the
20
+ # import still breaks the build: then the import line is the hit.
21
+
22
+ import re
23
+ from collections.abc import Iterator
24
+ from dataclasses import dataclass
25
+ from typing import Literal
26
+
27
+ #: Hits kept per update (all of them are counted).
28
+ MAX_HITS = 50
29
+
30
+ UsageChange = Literal["removed", "changed"]
31
+
32
+ SOURCE_EXTENSIONS: dict[str, tuple[str, ...]] = {
33
+ "npm": (".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs", ".vue"),
34
+ "maven": (".java", ".kt", ".kts"),
35
+ }
36
+
37
+ #: Kinds naming a member of the declaration before the last dot (`get` and
38
+ #: `set` are TS accessors, `member` an enum member).
39
+ _MEMBER_KINDS = frozenset({"method", "property", "field", "get", "set", "member"})
40
+ _CONSTRUCTOR_KINDS = frozenset({"ctor", "constructor"})
41
+ #: Kinds with no name of their own to look for: call, construct and index
42
+ #: signatures, `export default x` (x's own line is diffed too).
43
+ _UNMATCHED_KINDS = frozenset({"call", "new", "index", "default"})
44
+ #: Member names too common to look for without their owner (`.name`, `.get(`).
45
+ _COMMON_MEMBERS = frozenset(
46
+ {
47
+ "apply",
48
+ "bind",
49
+ "call",
50
+ "close",
51
+ "data",
52
+ "emit",
53
+ "find",
54
+ "init",
55
+ "keys",
56
+ "length",
57
+ "name",
58
+ "next",
59
+ "open",
60
+ "push",
61
+ "read",
62
+ "send",
63
+ "size",
64
+ "then",
65
+ "toString",
66
+ "type",
67
+ "value",
68
+ "values",
69
+ "write",
70
+ }
71
+ )
72
+ _NAME = re.compile(r"^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$")
73
+
74
+
75
+ @dataclass(frozen=True)
76
+ class ApiSymbol:
77
+ """A declaration the update removes or changes."""
78
+
79
+ kind: str
80
+ #: Dotted name as declared: `CLIEngine`, `Linter.verify`.
81
+ name: str
82
+ #: The module (npm) or Java package (Maven) it is declared in.
83
+ module: str
84
+ change: UsageChange
85
+
86
+ @property
87
+ def owner(self) -> str:
88
+ """The top-level declaration: `Linter` for `Linter.verify`."""
89
+ return self.name.split(".", 1)[0]
90
+
91
+ @property
92
+ def member(self) -> str | None:
93
+ """The member a member kind names (`verify`), else None."""
94
+ if self.kind in _MEMBER_KINDS and "." in self.name:
95
+ return self.name.rsplit(".", 1)[1]
96
+ return None
97
+
98
+
99
+ @dataclass(frozen=True)
100
+ class UsageHit:
101
+ path: str
102
+ line: int
103
+ #: The symbol's dotted name.
104
+ symbol: str
105
+ change: UsageChange
106
+
107
+
108
+ @dataclass(frozen=True)
109
+ class UsageReport:
110
+ """Where the checkout appears to use one update's removed or changed APIs."""
111
+
112
+ #: The first MAX_HITS, by path and line.
113
+ hits: tuple[UsageHit, ...] = ()
114
+ total: int = 0
115
+
116
+
117
+ def _line_of(text: str, position: int) -> int:
118
+ return text.count("\n", 0, position) + 1
119
+
120
+
121
+ def _span_lines(text: str, start: int, end: int) -> set[int]:
122
+ return set(range(_line_of(text, start), _line_of(text, end) + 1))
123
+
124
+
125
+ def _word(name: str) -> str:
126
+ """A regex for ``name`` as a whole identifier."""
127
+ return rf"(?<![\w$]){re.escape(name)}(?![\w$])"
128
+
129
+
130
+ def _distinctive(member: str) -> bool:
131
+ return len(member) >= 4 and member not in _COMMON_MEMBERS
132
+
133
+
134
+ def _hits(
135
+ path: str,
136
+ text: str,
137
+ symbol: ApiSymbol,
138
+ patterns: list[str],
139
+ imports: set[int],
140
+ ) -> Iterator[UsageHit]:
141
+ """Lines of ``text`` matching any of ``patterns``; import lines only
142
+ when nothing else matches."""
143
+ lines: set[int] = set()
144
+ for pattern in patterns:
145
+ lines.update(_line_of(text, m.start()) for m in re.finditer(pattern, text))
146
+ used = lines - imports
147
+ for line in sorted(used or lines):
148
+ yield UsageHit(path, line, symbol.name, symbol.change)
149
+
150
+
151
+ # ── TS/JS ────────────────────────────────────────────────────────────────────
152
+
153
+ _IMPORT = re.compile(
154
+ r"""\bimport\s+(?:type\s+)?(?P<clause>[\w$*{}\s,]{1,2000}?)\s*from\s*"""
155
+ r"""['"](?P<spec>[^'"\n]+)['"]"""
156
+ )
157
+ _REQUIRE = re.compile(
158
+ r"""\b(?:const|let|var)\s+(?P<binding>\{[^}]{0,2000}\}|[\w$]+)\s*=\s*"""
159
+ r"""require\(\s*['"](?P<spec>[^'"\n]+)['"]\s*\)"""
160
+ )
161
+
162
+
163
+ @dataclass
164
+ class _JsImports:
165
+ #: Local name → the name it's exported as.
166
+ named: dict[str, str]
167
+ #: Locals bound to the whole module (default, `* as`, require).
168
+ whole: set[str]
169
+ #: Lines the import statements take.
170
+ lines: set[int]
171
+
172
+
173
+ def _named(block: str, separator: str) -> dict[str, str]:
174
+ """`{ a, b as c }` (import) or `{ a, b: c }` (require) → local → exported."""
175
+ names: dict[str, str] = {}
176
+ for part in block.strip("{} \n").split(","):
177
+ part = part.strip().removeprefix("type ").strip()
178
+ exported, _, local = part.partition(separator)
179
+ exported, local = exported.strip(), local.strip() or exported.strip()
180
+ if _NAME.match(exported) and _NAME.match(local):
181
+ names[local] = exported
182
+ return names
183
+
184
+
185
+ def _js_imports(text: str, package: str) -> _JsImports | None:
186
+ """What a file imports from ``package`` (or a subpath); None for nothing."""
187
+
188
+ def ours(spec: str) -> bool:
189
+ return spec == package or spec.startswith(package + "/")
190
+
191
+ found = _JsImports({}, set(), set())
192
+ for match in _IMPORT.finditer(text):
193
+ if not ours(match["spec"]):
194
+ continue
195
+ found.lines |= _span_lines(text, match.start(), match.end())
196
+ clause = match["clause"]
197
+ if braces := re.search(r"\{[^}]*\}", clause):
198
+ found.named.update(_named(braces.group(0), " as "))
199
+ clause = clause.replace(braces.group(0), "")
200
+ for part in clause.split(","):
201
+ part = part.strip()
202
+ if part.startswith("*"):
203
+ part = part.partition(" as ")[2].strip()
204
+ if _NAME.match(part):
205
+ found.whole.add(part)
206
+ for match in _REQUIRE.finditer(text):
207
+ if not ours(match["spec"]):
208
+ continue
209
+ found.lines |= _span_lines(text, match.start(), match.end())
210
+ binding = match["binding"]
211
+ if binding.startswith("{"):
212
+ found.named.update(_named(binding, ":"))
213
+ else:
214
+ found.whole.add(binding)
215
+ return found if found.lines else None
216
+
217
+
218
+ def _js_patterns(symbol: ApiSymbol, imports: _JsImports) -> list[str]:
219
+ owner, member = symbol.owner, symbol.member
220
+ dot = r"\s*\??\.\s*"
221
+ # How the file names the owner: a named import, or a whole-module
222
+ # binding's property (`ns.Linter`).
223
+ names = [_word(local) for local, name in imports.named.items() if name == owner]
224
+ names += [_word(local) + dot + _word(owner) for local in imports.whole]
225
+ if member is None:
226
+ if symbol.kind in _CONSTRUCTOR_KINDS:
227
+ return [r"\bnew\s+" + name for name in names]
228
+ return names
229
+ patterns = [name + dot + _word(member) for name in names]
230
+ # The default export may be the owner itself (`axios.create`).
231
+ patterns += [_word(local) + dot + _word(member) for local in imports.whole]
232
+ if names and _distinctive(member):
233
+ # An instance of the owner: `linter.verifyAndFix`.
234
+ patterns.append(r"\??\.\s*" + _word(member))
235
+ return patterns
236
+
237
+
238
+ def _js_hits(
239
+ files: list[tuple[str, str]], package: str, wanted: list[ApiSymbol]
240
+ ) -> Iterator[UsageHit]:
241
+ for path, text in files:
242
+ imports = _js_imports(text, package)
243
+ if imports is None:
244
+ continue
245
+ for symbol in wanted:
246
+ yield from _hits(
247
+ path, text, symbol, _js_patterns(symbol, imports), imports.lines
248
+ )
249
+
250
+
251
+ # ── Java / Kotlin ────────────────────────────────────────────────────────────
252
+
253
+ _PACKAGE = re.compile(r"^[ \t]*package[ \t]+([\w.]+)", re.MULTILINE)
254
+ _JVM_IMPORT = re.compile(
255
+ r"^[ \t]*import[ \t]+(?:static[ \t]+)?([\w.]+?)(\.\*)?(?:[ \t]+as[ \t]+(\w+))?"
256
+ r"[ \t]*;?[ \t]*$",
257
+ re.MULTILINE,
258
+ )
259
+
260
+
261
+ def _jvm_view(text: str, symbol: ApiSymbol) -> tuple[str, set[int]] | None:
262
+ """The name ``symbol``'s class goes by in a file and the file's import
263
+ lines, or None when the file can't see it."""
264
+ owner = symbol.owner
265
+ qualified = f"{symbol.module}.{owner}" if symbol.module else owner
266
+ imports: set[int] = set()
267
+ local: str | None = None
268
+ for match in _JVM_IMPORT.finditer(text):
269
+ target, wildcard, alias = match.groups()
270
+ if wildcard and target == symbol.module:
271
+ local = local or owner
272
+ elif target == qualified:
273
+ local = alias or owner
274
+ elif target.startswith(qualified + ".") and not wildcard:
275
+ # A nested class imported by itself: `CarProgressBar.Builder`.
276
+ local = local or alias or target.rsplit(".", 1)[1]
277
+ else:
278
+ continue
279
+ imports.add(_line_of(text, match.start()))
280
+ if local is not None:
281
+ return local, imports
282
+ package = _PACKAGE.search(text)
283
+ if (package.group(1) if package else "") == symbol.module or (
284
+ symbol.module and re.search(_word(qualified), text)
285
+ ):
286
+ return owner, imports
287
+ return None
288
+
289
+
290
+ def _getter_property(member: str) -> str | None:
291
+ """Kotlin reads `getColor()` as `.color`."""
292
+ if member.startswith("get") and len(member) > 3 and member[3].isupper():
293
+ return member[3].lower() + member[4:]
294
+ return None
295
+
296
+
297
+ def _jvm_patterns(symbol: ApiSymbol, local: str) -> list[str]:
298
+ member = symbol.member
299
+ if member is None:
300
+ if symbol.kind in _CONSTRUCTOR_KINDS:
301
+ return [_word(local) + r"\s*(?:<[^<>()]*>)?\s*\("]
302
+ return [_word(local)]
303
+ patterns = [_word(local) + r"\s*\.\s*" + _word(member)]
304
+ if _distinctive(member):
305
+ patterns.append(r"\.\s*" + _word(member))
306
+ prop = _getter_property(member) if symbol.kind == "method" else None
307
+ if prop is not None and _distinctive(prop):
308
+ patterns.append(r"\.\s*" + _word(prop) + r"(?!\s*\()")
309
+ return patterns
310
+
311
+
312
+ def _kotlin_top_level(
313
+ text: str, symbol: ApiSymbol
314
+ ) -> tuple[list[str], set[int]] | None:
315
+ """Patterns for a Kotlin top-level function or property (compiled into a
316
+ `FileKt` class Kotlin code never names) and the file's import lines, or
317
+ None when the file can't see it.
318
+
319
+ Kotlin imports these by their own name (`import p.transaction`); a
320
+ wildcard import or the same package sees them too, and then only a
321
+ distinctive name is looked for.
322
+ """
323
+ member = symbol.member
324
+ assert member is not None
325
+ names = {member}
326
+ if (prop := _getter_property(member)) is not None:
327
+ names.add(prop)
328
+ found: set[str] = set()
329
+ imports: set[int] = set()
330
+ wildcard = False
331
+ for match in _JVM_IMPORT.finditer(text):
332
+ target, star, alias = match.groups()
333
+ package, _, name = target.rpartition(".")
334
+ if star and target == symbol.module:
335
+ wildcard = True
336
+ elif not star and package == symbol.module and name in names:
337
+ found.add(alias or name)
338
+ else:
339
+ continue
340
+ imports.add(_line_of(text, match.start()))
341
+ if not found:
342
+ same = _PACKAGE.search(text)
343
+ if wildcard or (same.group(1) if same else "") == symbol.module:
344
+ found = {name for name in names if _distinctive(name)}
345
+ if not found:
346
+ return None
347
+ return [_word(name) for name in sorted(found)], imports
348
+
349
+
350
+ def _jvm_hits(
351
+ files: list[tuple[str, str]], wanted: list[ApiSymbol]
352
+ ) -> Iterator[UsageHit]:
353
+ for path, text in files:
354
+ kotlin = path.endswith((".kt", ".kts"))
355
+ for symbol in wanted:
356
+ if kotlin and symbol.owner.endswith("Kt") and symbol.member is not None:
357
+ seen = _kotlin_top_level(text, symbol)
358
+ if seen is not None:
359
+ yield from _hits(path, text, symbol, *seen)
360
+ continue
361
+ view = _jvm_view(text, symbol)
362
+ if view is None:
363
+ continue
364
+ local, imports = view
365
+ yield from _hits(path, text, symbol, _jvm_patterns(symbol, local), imports)
366
+
367
+
368
+ def find_usages(
369
+ ecosystem: str,
370
+ package: str,
371
+ wanted: list[ApiSymbol],
372
+ files: list[tuple[str, str]],
373
+ ) -> UsageReport:
374
+ """Where ``files`` appear to use ``wanted`` declarations of ``package``.
375
+
376
+ Args:
377
+ ecosystem: "npm" or "maven" (no other has an API diff).
378
+ package: The package's name (npm files import it by name).
379
+ wanted: The update's removed and changed declarations.
380
+ files: (path, text) of the repository's source files.
381
+ """
382
+ extensions = SOURCE_EXTENSIONS.get(ecosystem, ())
383
+ mine = [(p, t) for p, t in files if extensions and p.endswith(extensions)]
384
+ if not wanted or not mine:
385
+ return UsageReport()
386
+ if ecosystem == "npm":
387
+ found = _js_hits(mine, package, wanted)
388
+ else:
389
+ found = _jvm_hits(mine, wanted)
390
+ hits = sorted(set(found), key=lambda h: (h.path, h.line, h.symbol))
391
+ return UsageReport(tuple(hits[:MAX_HITS]), len(hits))