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/__init__.py +3 -0
- depdelta_cli/__main__.py +3 -0
- depdelta_cli/api.py +142 -0
- depdelta_cli/check.py +48 -0
- depdelta_cli/env.py +116 -0
- depdelta_cli/gerrit.py +40 -0
- depdelta_cli/git.py +110 -0
- depdelta_cli/gitlab.py +74 -0
- depdelta_cli/main.py +184 -0
- depdelta_cli/manifests.py +94 -0
- depdelta_cli/usage.py +391 -0
- depdelta_cli/web.py +68 -0
- depdelta_cli-0.1.0.dist-info/METADATA +166 -0
- depdelta_cli-0.1.0.dist-info/RECORD +17 -0
- depdelta_cli-0.1.0.dist-info/WHEEL +4 -0
- depdelta_cli-0.1.0.dist-info/entry_points.txt +2 -0
- depdelta_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
depdelta_cli/__init__.py
ADDED
depdelta_cli/__main__.py
ADDED
depdelta_cli/api.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
# src/depdelta_cli/api.py
|
|
2
|
+
#
|
|
3
|
+
# DepDelta's POST /ci/reviews: the change's manifests in, the review out.
|
|
4
|
+
# While release notes are read the review says `indexing`; it is asked again
|
|
5
|
+
# after `retry_after` seconds until it is ready or the wait runs out.
|
|
6
|
+
|
|
7
|
+
import time
|
|
8
|
+
import uuid
|
|
9
|
+
from collections.abc import Callable
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
|
|
12
|
+
from depdelta_cli import web
|
|
13
|
+
from depdelta_cli.git import ChangedFile
|
|
14
|
+
|
|
15
|
+
DEFAULT_API_URL = "https://api.depdelta.com/api/v1"
|
|
16
|
+
#: Server errors and network failures are tried this many times in all.
|
|
17
|
+
ATTEMPTS = 3
|
|
18
|
+
RETRY_SECONDS = 5
|
|
19
|
+
#: When the API gives no retry_after.
|
|
20
|
+
POLL_SECONDS = 15
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class ApiError(Exception):
|
|
24
|
+
"""DepDelta refused the review (bad key, spent budget, bad request)."""
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass(frozen=True)
|
|
28
|
+
class Review:
|
|
29
|
+
status: str
|
|
30
|
+
label: str
|
|
31
|
+
body: str
|
|
32
|
+
retry_after: int | None
|
|
33
|
+
verdict: str | None
|
|
34
|
+
updates: list[dict]
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _message(body: object) -> str:
|
|
38
|
+
"""The error envelope's message: `{"detail": {"message": …}}`, a bare
|
|
39
|
+
envelope, or FastAPI's validation list."""
|
|
40
|
+
if isinstance(body, dict):
|
|
41
|
+
detail = body.get("detail", body)
|
|
42
|
+
if isinstance(detail, dict) and detail.get("message"):
|
|
43
|
+
return str(detail["message"])
|
|
44
|
+
if isinstance(detail, list) and detail and isinstance(detail[0], dict):
|
|
45
|
+
first = detail[0]
|
|
46
|
+
where = ".".join(str(p) for p in first.get("loc", ()))
|
|
47
|
+
return f"{where}: {first.get('msg', 'invalid')}"
|
|
48
|
+
if isinstance(detail, str):
|
|
49
|
+
return detail
|
|
50
|
+
if isinstance(body, str) and body:
|
|
51
|
+
return body[:300]
|
|
52
|
+
return "no details"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _review(data: dict) -> Review:
|
|
56
|
+
return Review(
|
|
57
|
+
status=str(data["status"]),
|
|
58
|
+
label=str(data["label"]),
|
|
59
|
+
body=str(data["body"]),
|
|
60
|
+
retry_after=data.get("retry_after"),
|
|
61
|
+
verdict=data.get("verdict"),
|
|
62
|
+
updates=list(data.get("updates") or []),
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class DepDelta:
|
|
67
|
+
def __init__(
|
|
68
|
+
self,
|
|
69
|
+
key: str,
|
|
70
|
+
api_url: str = DEFAULT_API_URL,
|
|
71
|
+
*,
|
|
72
|
+
sleep: Callable[[float], None] = time.sleep,
|
|
73
|
+
clock: Callable[[], float] = time.monotonic,
|
|
74
|
+
) -> None:
|
|
75
|
+
self.key = key
|
|
76
|
+
self.url = f"{api_url.rstrip('/')}/ci/reviews"
|
|
77
|
+
self.sleep = sleep
|
|
78
|
+
self.clock = clock
|
|
79
|
+
|
|
80
|
+
def ask(
|
|
81
|
+
self,
|
|
82
|
+
files: list[ChangedFile],
|
|
83
|
+
*,
|
|
84
|
+
usage: list[dict] | None = None,
|
|
85
|
+
fmt: str = "markdown",
|
|
86
|
+
source_url: str | None = None,
|
|
87
|
+
) -> Review:
|
|
88
|
+
"""One ask; server errors and network failures are tried again."""
|
|
89
|
+
payload: dict = {
|
|
90
|
+
"files": [{"path": f.path, "base": f.base, "head": f.head} for f in files],
|
|
91
|
+
"usage": usage or [],
|
|
92
|
+
"format": fmt,
|
|
93
|
+
}
|
|
94
|
+
if source_url:
|
|
95
|
+
payload["source_url"] = source_url
|
|
96
|
+
for attempt in range(1, ATTEMPTS + 1):
|
|
97
|
+
try:
|
|
98
|
+
reply = web.request(
|
|
99
|
+
"POST",
|
|
100
|
+
self.url,
|
|
101
|
+
body=payload,
|
|
102
|
+
headers={
|
|
103
|
+
"Authorization": f"Bearer {self.key}",
|
|
104
|
+
# New for every ask: a repeat must see fresh notes.
|
|
105
|
+
"Idempotency-Key": str(uuid.uuid4()),
|
|
106
|
+
},
|
|
107
|
+
)
|
|
108
|
+
except web.HttpError as error:
|
|
109
|
+
if attempt == ATTEMPTS:
|
|
110
|
+
raise ApiError(str(error)) from error
|
|
111
|
+
self.sleep(RETRY_SECONDS * attempt)
|
|
112
|
+
continue
|
|
113
|
+
if reply.status >= 500 and attempt < ATTEMPTS:
|
|
114
|
+
self.sleep(RETRY_SECONDS * attempt)
|
|
115
|
+
continue
|
|
116
|
+
if reply.status != 200 or not isinstance(reply.body, dict):
|
|
117
|
+
raise ApiError(
|
|
118
|
+
f"DepDelta answered {reply.status}: {_message(reply.body)}"
|
|
119
|
+
)
|
|
120
|
+
return _review(reply.body["data"])
|
|
121
|
+
raise AssertionError("unreachable") # pragma: no cover
|
|
122
|
+
|
|
123
|
+
def review(
|
|
124
|
+
self,
|
|
125
|
+
files: list[ChangedFile],
|
|
126
|
+
*,
|
|
127
|
+
usage: list[dict] | None = None,
|
|
128
|
+
fmt: str = "markdown",
|
|
129
|
+
source_url: str | None = None,
|
|
130
|
+
wait: float = 300,
|
|
131
|
+
) -> Review:
|
|
132
|
+
"""Ask until the review is ready or ``wait`` seconds pass; then the
|
|
133
|
+
last answer (still `indexing`) is the review."""
|
|
134
|
+
deadline = self.clock() + wait
|
|
135
|
+
while True:
|
|
136
|
+
review = self.ask(files, usage=usage, fmt=fmt, source_url=source_url)
|
|
137
|
+
if review.status != "indexing":
|
|
138
|
+
return review
|
|
139
|
+
pause = review.retry_after or POLL_SECONDS
|
|
140
|
+
if self.clock() + pause > deadline:
|
|
141
|
+
return review
|
|
142
|
+
self.sleep(pause)
|
depdelta_cli/check.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
# src/depdelta_cli/check.py
|
|
2
|
+
#
|
|
3
|
+
# The usage check: for each update with removed or changed declarations,
|
|
4
|
+
# where this checkout uses them. Runs in CI on CI's copy of the code; only
|
|
5
|
+
# the hits (path, line, symbol) are sent back.
|
|
6
|
+
|
|
7
|
+
from depdelta_cli.git import SourceFiles
|
|
8
|
+
from depdelta_cli.usage import ApiSymbol, find_usages
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def ecosystems(updates: list[dict]) -> set[str]:
|
|
12
|
+
"""Ecosystems of the updates that have declarations to look for."""
|
|
13
|
+
return {u["ecosystem"] for u in updates if u.get("symbols")}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def usage(updates: list[dict], sources: SourceFiles) -> list[dict]:
|
|
17
|
+
"""CiUsage for each update with symbols, as POST /ci/reviews takes it."""
|
|
18
|
+
found: list[dict] = []
|
|
19
|
+
for update in updates:
|
|
20
|
+
if not update.get("symbols"):
|
|
21
|
+
continue
|
|
22
|
+
wanted = [
|
|
23
|
+
ApiSymbol(
|
|
24
|
+
kind=s["kind"], name=s["name"], module=s["module"], change=s["change"]
|
|
25
|
+
)
|
|
26
|
+
for s in update["symbols"]
|
|
27
|
+
]
|
|
28
|
+
report = find_usages(update["ecosystem"], update["name"], wanted, sources.files)
|
|
29
|
+
found.append(
|
|
30
|
+
{
|
|
31
|
+
"ecosystem": update["ecosystem"],
|
|
32
|
+
"name": update["name"],
|
|
33
|
+
"from_version": update["from_version"],
|
|
34
|
+
"to_version": update["to_version"],
|
|
35
|
+
"hits": [
|
|
36
|
+
{
|
|
37
|
+
"path": h.path,
|
|
38
|
+
"line": h.line,
|
|
39
|
+
"symbol": h.symbol,
|
|
40
|
+
"change": h.change,
|
|
41
|
+
}
|
|
42
|
+
for h in report.hits
|
|
43
|
+
],
|
|
44
|
+
"total": report.total,
|
|
45
|
+
"too_large": sources.too_large,
|
|
46
|
+
}
|
|
47
|
+
)
|
|
48
|
+
return found
|
depdelta_cli/env.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
# src/depdelta_cli/env.py
|
|
2
|
+
#
|
|
3
|
+
# Which change this CI job is for, read from the variables the CI sets:
|
|
4
|
+
# Jenkins with the Gerrit Trigger plugin, or a GitLab merge request pipeline.
|
|
5
|
+
|
|
6
|
+
from collections.abc import Mapping
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from typing import Literal
|
|
9
|
+
from urllib.parse import quote, urlsplit
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class EnvError(Exception):
|
|
13
|
+
"""The job isn't for a change, or a variable it needs is missing."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True)
|
|
17
|
+
class GerritChange:
|
|
18
|
+
#: Gerrit's web root: https://gerrit.example.com (or …/r).
|
|
19
|
+
url: str
|
|
20
|
+
#: REST id: `project~number`, URL-encoded.
|
|
21
|
+
change_id: str
|
|
22
|
+
revision: str
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True)
|
|
26
|
+
class GitLabMergeRequest:
|
|
27
|
+
#: https://gitlab.example.com/api/v4
|
|
28
|
+
api_url: str
|
|
29
|
+
project_id: str
|
|
30
|
+
iid: str
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass(frozen=True)
|
|
34
|
+
class Change:
|
|
35
|
+
platform: Literal["gerrit", "gitlab"]
|
|
36
|
+
base: str
|
|
37
|
+
head: str
|
|
38
|
+
#: Files' page at the head commit; uses link into it.
|
|
39
|
+
source_url: str | None
|
|
40
|
+
target: GerritChange | GitLabMergeRequest
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _need(env: Mapping[str, str], name: str) -> str:
|
|
44
|
+
value = env.get(name, "").strip()
|
|
45
|
+
if not value:
|
|
46
|
+
raise EnvError(f"{name} is not set.")
|
|
47
|
+
return value
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _gerrit_root(change_url: str) -> str:
|
|
51
|
+
"""Gerrit's web root from a change's URL: `…/c/project/+/123` (Gerrit
|
|
52
|
+
3) or `…/123` (older)."""
|
|
53
|
+
parts = urlsplit(change_url)
|
|
54
|
+
path = parts.path.rstrip("/")
|
|
55
|
+
if "/c/" in f"{path}/":
|
|
56
|
+
path = path[: f"{path}/".index("/c/")]
|
|
57
|
+
else:
|
|
58
|
+
path = path.rsplit("/", 1)[0]
|
|
59
|
+
return f"{parts.scheme}://{parts.netloc}{path}"
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def gerrit(env: Mapping[str, str]) -> Change:
|
|
63
|
+
"""A Jenkins job started by the Gerrit Trigger plugin."""
|
|
64
|
+
project = _need(env, "GERRIT_PROJECT")
|
|
65
|
+
number = _need(env, "GERRIT_CHANGE_NUMBER")
|
|
66
|
+
revision = _need(env, "GERRIT_PATCHSET_REVISION")
|
|
67
|
+
url = env.get("DEPDELTA_GERRIT_URL", "").strip().rstrip("/")
|
|
68
|
+
if not url:
|
|
69
|
+
url = _gerrit_root(_need(env, "GERRIT_CHANGE_URL"))
|
|
70
|
+
return Change(
|
|
71
|
+
platform="gerrit",
|
|
72
|
+
# A Gerrit change is one commit: its parent is what it changes.
|
|
73
|
+
base=f"{revision}^",
|
|
74
|
+
head=revision,
|
|
75
|
+
source_url=None,
|
|
76
|
+
target=GerritChange(
|
|
77
|
+
url=url,
|
|
78
|
+
change_id=f"{quote(project, safe='')}~{number}",
|
|
79
|
+
revision=revision,
|
|
80
|
+
),
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def gitlab(env: Mapping[str, str]) -> Change:
|
|
85
|
+
"""A GitLab merge request pipeline."""
|
|
86
|
+
iid = env.get("CI_MERGE_REQUEST_IID", "").strip()
|
|
87
|
+
if not iid:
|
|
88
|
+
raise EnvError(
|
|
89
|
+
"Not a merge request pipeline: run the job on merge requests "
|
|
90
|
+
"(rules: - if: $CI_PIPELINE_SOURCE == 'merge_request_event')."
|
|
91
|
+
)
|
|
92
|
+
head = _need(env, "CI_COMMIT_SHA")
|
|
93
|
+
project_url = env.get("CI_PROJECT_URL", "").strip().rstrip("/")
|
|
94
|
+
return Change(
|
|
95
|
+
platform="gitlab",
|
|
96
|
+
base=_need(env, "CI_MERGE_REQUEST_DIFF_BASE_SHA"),
|
|
97
|
+
head=head,
|
|
98
|
+
source_url=f"{project_url}/-/blob/{head}" if project_url else None,
|
|
99
|
+
target=GitLabMergeRequest(
|
|
100
|
+
api_url=_need(env, "CI_API_V4_URL").rstrip("/"),
|
|
101
|
+
project_id=_need(env, "CI_PROJECT_ID"),
|
|
102
|
+
iid=iid,
|
|
103
|
+
),
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def detect(env: Mapping[str, str]) -> Change:
|
|
108
|
+
"""The change from the CI's variables."""
|
|
109
|
+
if env.get("GERRIT_CHANGE_NUMBER"):
|
|
110
|
+
return gerrit(env)
|
|
111
|
+
if env.get("GITLAB_CI"):
|
|
112
|
+
return gitlab(env)
|
|
113
|
+
raise EnvError(
|
|
114
|
+
"No change found: run in Jenkins with the Gerrit Trigger plugin or in "
|
|
115
|
+
"a GitLab merge request pipeline, or pass --base and --head."
|
|
116
|
+
)
|
depdelta_cli/gerrit.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
# src/depdelta_cli/gerrit.py
|
|
2
|
+
#
|
|
3
|
+
# The review as a Gerrit change message on the patch set, with no vote. The
|
|
4
|
+
# `autogenerated:` tag lets Gerrit's UI fold earlier patch sets' reviews
|
|
5
|
+
# away behind "Show all comments" ("Only comments" hides them).
|
|
6
|
+
|
|
7
|
+
from depdelta_cli import web
|
|
8
|
+
from depdelta_cli.env import GerritChange
|
|
9
|
+
|
|
10
|
+
TAG = "autogenerated:depdelta"
|
|
11
|
+
#: Gerrit's default change.commentSizeLimit is 16 KiB.
|
|
12
|
+
MAX_MESSAGE = 16_000
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class GerritError(Exception):
|
|
16
|
+
"""Gerrit refused the message."""
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def fit(message: str, link: str | None = None) -> str:
|
|
20
|
+
"""``message`` cut to Gerrit's size limit, ending with ``link``."""
|
|
21
|
+
if len(message) <= MAX_MESSAGE:
|
|
22
|
+
return message
|
|
23
|
+
tail = f"\n\n… cut to fit. The full review: {link}" if link else "\n\n…"
|
|
24
|
+
return message[: MAX_MESSAGE - len(tail)].rstrip() + tail
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def post(change: GerritChange, message: str, user: str, password: str) -> None:
|
|
28
|
+
"""Post ``message`` on the change's patch set (HTTP password auth)."""
|
|
29
|
+
url = (
|
|
30
|
+
f"{change.url}/a/changes/{change.change_id}/revisions/{change.revision}/review"
|
|
31
|
+
)
|
|
32
|
+
reply = web.request(
|
|
33
|
+
"POST",
|
|
34
|
+
url,
|
|
35
|
+
body={"message": message, "tag": TAG, "notify": "OWNER"},
|
|
36
|
+
headers={"Authorization": web.basic(user, password)},
|
|
37
|
+
)
|
|
38
|
+
if reply.status != 200:
|
|
39
|
+
detail = reply.body if isinstance(reply.body, str) else ""
|
|
40
|
+
raise GerritError(f"Gerrit answered {reply.status}: {detail[:300]}".strip())
|
depdelta_cli/git.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
# src/depdelta_cli/git.py
|
|
2
|
+
#
|
|
3
|
+
# What the change touched, read from the CI checkout with git: the changed
|
|
4
|
+
# manifests at both ends, and the source files at the change's head (the
|
|
5
|
+
# working tree, which CI has checked out).
|
|
6
|
+
|
|
7
|
+
import os
|
|
8
|
+
import subprocess
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
|
|
11
|
+
from depdelta_cli.manifests import is_manifest, skipped
|
|
12
|
+
from depdelta_cli.usage import SOURCE_EXTENSIONS
|
|
13
|
+
|
|
14
|
+
#: Source files read for the usage check, the size of each, and in all.
|
|
15
|
+
MAX_SOURCE_FILES = 5000
|
|
16
|
+
MAX_SOURCE_FILE_BYTES = 1024 * 1024
|
|
17
|
+
MAX_SOURCE_BYTES = 64 * 1024 * 1024
|
|
18
|
+
#: A line this long is generated or minified code: the file is skipped.
|
|
19
|
+
MAX_LINE_LENGTH = 5000
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class GitError(Exception):
|
|
23
|
+
"""git failed (not a repository, an unknown revision)."""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass(frozen=True)
|
|
27
|
+
class ChangedFile:
|
|
28
|
+
path: str
|
|
29
|
+
#: None when the change adds it.
|
|
30
|
+
base: str | None
|
|
31
|
+
#: None when the change deletes it.
|
|
32
|
+
head: str | None
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _git(repo: str, *args: str) -> subprocess.CompletedProcess[bytes]:
|
|
36
|
+
return subprocess.run(["git", "-C", repo, *args], capture_output=True, check=False)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _out(repo: str, *args: str) -> str:
|
|
40
|
+
result = _git(repo, *args)
|
|
41
|
+
if result.returncode != 0:
|
|
42
|
+
message = result.stderr.decode("utf-8", "replace").strip()
|
|
43
|
+
raise GitError(f"git {' '.join(args)}: {message}")
|
|
44
|
+
return result.stdout.decode("utf-8", "replace")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _show(repo: str, rev: str, path: str) -> str | None:
|
|
48
|
+
"""The file at ``rev``, or None when it isn't there."""
|
|
49
|
+
result = _git(repo, "show", f"{rev}:{path}")
|
|
50
|
+
if result.returncode != 0:
|
|
51
|
+
return None
|
|
52
|
+
return result.stdout.decode("utf-8", "replace")
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def changed_manifests(repo: str, base: str, head: str) -> list[ChangedFile]:
|
|
56
|
+
"""The manifests and lockfiles the change touched, at both ends."""
|
|
57
|
+
names = _out(repo, "diff", "--name-only", "--no-renames", base, head, "--")
|
|
58
|
+
paths = [p for p in names.splitlines() if p and is_manifest(p)]
|
|
59
|
+
return [
|
|
60
|
+
ChangedFile(path, _show(repo, base, path), _show(repo, head, path))
|
|
61
|
+
for path in paths
|
|
62
|
+
]
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@dataclass(frozen=True)
|
|
66
|
+
class SourceFiles:
|
|
67
|
+
#: (path, text) of each file read.
|
|
68
|
+
files: list[tuple[str, str]]
|
|
69
|
+
#: More files than the limits: the usage check saw only some.
|
|
70
|
+
too_large: bool
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def ensure_commit(repo: str, rev: str) -> None:
|
|
74
|
+
"""Fetch ``rev`` when a shallow clone doesn't have it."""
|
|
75
|
+
if _git(repo, "cat-file", "-e", f"{rev}^{{commit}}").returncode == 0:
|
|
76
|
+
return
|
|
77
|
+
_out(repo, "fetch", "--quiet", "--depth=1", "origin", rev)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def source_files(repo: str, ecosystems: set[str]) -> SourceFiles:
|
|
81
|
+
"""The checkout's tracked source files for ``ecosystems``. Vendored and
|
|
82
|
+
build directories, type declarations, oversized and minified files are
|
|
83
|
+
left out."""
|
|
84
|
+
extensions = tuple(
|
|
85
|
+
ext for eco in sorted(ecosystems) for ext in SOURCE_EXTENSIONS.get(eco, ())
|
|
86
|
+
)
|
|
87
|
+
if not extensions:
|
|
88
|
+
return SourceFiles([], False)
|
|
89
|
+
files: list[tuple[str, str]] = []
|
|
90
|
+
size = 0
|
|
91
|
+
for path in _out(repo, "ls-files", "-z").split("\0"):
|
|
92
|
+
if not path.endswith(extensions) or path.endswith(".d.ts") or skipped(path):
|
|
93
|
+
continue
|
|
94
|
+
if len(files) >= MAX_SOURCE_FILES or size >= MAX_SOURCE_BYTES:
|
|
95
|
+
return SourceFiles(files, True)
|
|
96
|
+
full = os.path.join(repo, path)
|
|
97
|
+
try:
|
|
98
|
+
if os.path.getsize(full) > MAX_SOURCE_FILE_BYTES:
|
|
99
|
+
continue
|
|
100
|
+
with open(full, "rb") as handle:
|
|
101
|
+
raw = handle.read()
|
|
102
|
+
except OSError:
|
|
103
|
+
# Listed but not checked out (a sparse checkout, a submodule).
|
|
104
|
+
continue
|
|
105
|
+
size += len(raw)
|
|
106
|
+
text = raw.decode("utf-8", "replace")
|
|
107
|
+
if any(len(line) > MAX_LINE_LENGTH for line in text.splitlines()):
|
|
108
|
+
continue
|
|
109
|
+
files.append((path, text))
|
|
110
|
+
return SourceFiles(files, False)
|
depdelta_cli/gitlab.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
# src/depdelta_cli/gitlab.py
|
|
2
|
+
#
|
|
3
|
+
# The review as one merge request note, found by its marker and edited in
|
|
4
|
+
# place on later pipelines, as the GitHub App does with its PR comment.
|
|
5
|
+
|
|
6
|
+
from urllib.parse import quote
|
|
7
|
+
|
|
8
|
+
from depdelta_cli import web
|
|
9
|
+
from depdelta_cli.env import GitLabMergeRequest
|
|
10
|
+
|
|
11
|
+
#: depdelta-api `app/updates/utils/render.py` MARKER.
|
|
12
|
+
MARKER = "<!-- depdelta:review -->"
|
|
13
|
+
PER_PAGE = 100
|
|
14
|
+
#: Notes searched for the marker (newest first).
|
|
15
|
+
MAX_PAGES = 10
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class GitLabError(Exception):
|
|
19
|
+
"""GitLab refused to list, add or edit the note."""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _notes_url(mr: GitLabMergeRequest) -> str:
|
|
23
|
+
project = quote(mr.project_id, safe="")
|
|
24
|
+
return f"{mr.api_url}/projects/{project}/merge_requests/{mr.iid}/notes"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _check(reply: web.Response, doing: str) -> None:
|
|
28
|
+
if reply.status not in (200, 201):
|
|
29
|
+
raise GitLabError(
|
|
30
|
+
f"GitLab answered {reply.status} {doing}: {_detail(reply.body)}"
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _detail(body: object) -> str:
|
|
35
|
+
if isinstance(body, dict):
|
|
36
|
+
return str(body.get("message") or body.get("error") or body)[:300]
|
|
37
|
+
return str(body or "")[:300]
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def find_note(mr: GitLabMergeRequest, token: str) -> int | None:
|
|
41
|
+
"""The id of the note carrying the marker, if one was posted."""
|
|
42
|
+
headers = {"PRIVATE-TOKEN": token}
|
|
43
|
+
for page in range(1, MAX_PAGES + 1):
|
|
44
|
+
reply = web.request(
|
|
45
|
+
"GET",
|
|
46
|
+
f"{_notes_url(mr)}?sort=desc&order_by=created_at"
|
|
47
|
+
f"&per_page={PER_PAGE}&page={page}",
|
|
48
|
+
headers=headers,
|
|
49
|
+
)
|
|
50
|
+
_check(reply, "listing notes")
|
|
51
|
+
notes = reply.body if isinstance(reply.body, list) else []
|
|
52
|
+
for note in notes:
|
|
53
|
+
if MARKER in str(note.get("body", "")):
|
|
54
|
+
return int(note["id"])
|
|
55
|
+
if len(notes) < PER_PAGE:
|
|
56
|
+
return None
|
|
57
|
+
return None
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def post(mr: GitLabMergeRequest, body: str, token: str) -> str:
|
|
61
|
+
"""Edit the earlier note, or add one. Says which."""
|
|
62
|
+
headers = {"PRIVATE-TOKEN": token}
|
|
63
|
+
existing = find_note(mr, token)
|
|
64
|
+
if existing is None:
|
|
65
|
+
reply = web.request(
|
|
66
|
+
"POST", _notes_url(mr), body={"body": body}, headers=headers
|
|
67
|
+
)
|
|
68
|
+
_check(reply, "adding the note")
|
|
69
|
+
return "added"
|
|
70
|
+
reply = web.request(
|
|
71
|
+
"PUT", f"{_notes_url(mr)}/{existing}", body={"body": body}, headers=headers
|
|
72
|
+
)
|
|
73
|
+
_check(reply, "editing the note")
|
|
74
|
+
return "updated"
|