uv-release-manager 1.0.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.
@@ -0,0 +1 @@
1
+ """Release uv projects that pin git dependencies during development"""
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
@@ -0,0 +1,336 @@
1
+ """Command line: ``uv-release-manager check | bump | update | gh-release``"""
2
+
3
+ import argparse
4
+ import os
5
+ import shlex
6
+ import subprocess
7
+ import sys
8
+ import tempfile
9
+ from pathlib import Path
10
+
11
+ from packaging.version import InvalidVersion, Version
12
+
13
+ from . import repo
14
+ from .git import GitError, git, tag_version
15
+ from . import update
16
+ from .pypi import PackageIndexError
17
+ from .sources import Project, bump, check_sources
18
+
19
+
20
+ def say(*parts: str):
21
+ sys.stdout.write(" ".join(parts) + "\n")
22
+
23
+
24
+ def report_sources(statuses) -> int:
25
+ """Prints the status of the sources; returns the number of errors"""
26
+ errors = 0
27
+ for status in statuses:
28
+ if status.error:
29
+ say("✗", f"{status.name}: {status.error}")
30
+ errors += 1
31
+ continue
32
+ where = "uv.lock" if status.locked else "remote"
33
+ for dep in status.ok:
34
+ say(
35
+ "✓",
36
+ f"{status.name}: {status.tag} ({status.commit[:12]}, {where}),"
37
+ f" {dep.where} require {dep.requirement.specifier}",
38
+ )
39
+ for dep in status.ahead:
40
+ say(
41
+ "✗",
42
+ f"{status.name}: the source is {status.version}"
43
+ f" ({status.commit[:12]}, {where}) but {dep.where} require a"
44
+ f" newer, untested version ({dep.requirement}): run bump or update",
45
+ )
46
+ errors += 1
47
+ for dep in status.outdated:
48
+ say(
49
+ "✗",
50
+ f"{status.name}: the source is {status.version}"
51
+ f" ({status.commit[:12]}, {where}) but {dep.where} allow older"
52
+ " versions"
53
+ f" ({dep.requirement}): run bump",
54
+ )
55
+ errors += 1
56
+ if not statuses:
57
+ say("✓", "no git or path source")
58
+ return errors
59
+
60
+
61
+ def run_checks(root: Path, args) -> int:
62
+ """All the release checks; returns the number of failures"""
63
+ project = Project(root / "pyproject.toml")
64
+ errors = report_sources(check_sources(project))
65
+ checks = [repo.clean_tree(root), repo.lock_up_to_date(root)]
66
+ if not args.no_push_check:
67
+ checks.append(repo.pushed(root, fetch=not args.no_fetch))
68
+ if args.test:
69
+ checks.append(
70
+ repo.released_dependencies_test(
71
+ root, shlex.split(args.test), shlex.split(args.uv_args)
72
+ )
73
+ )
74
+ for check in checks:
75
+ say("✓" if check.ok else "✗", f"{check.name}: {check.message}")
76
+ errors += not check.ok
77
+ return errors
78
+
79
+
80
+ def cmd_check(root: Path, args) -> int:
81
+ errors = run_checks(root, args)
82
+ say("Ready to release" if not errors else f"{errors} problem(s): cannot release")
83
+ return 1 if errors else 0
84
+
85
+
86
+ def cmd_bump(root: Path, args) -> int:
87
+ project = Project(root / "pyproject.toml")
88
+ statuses = check_sources(project)
89
+ unreleased = [s for s in statuses if s.error]
90
+ for status in unreleased:
91
+ say("✗", f"{status.name}: {status.error}")
92
+ changes = bump(project, statuses)
93
+ for old, new in changes:
94
+ say("↑", f"{old} -> {new}")
95
+ if changes and not args.dry_run:
96
+ project.save()
97
+ if (root / "uv.lock").exists():
98
+ subprocess.run(["uv", "lock"], cwd=root, check=True)
99
+ if not changes:
100
+ say("✓", "the lower bounds are up to date")
101
+ return 1 if unreleased else 0
102
+
103
+
104
+ #: Version of the first release (no version tag yet)
105
+ INITIAL_VERSION = "0.1.0"
106
+
107
+
108
+ def cliff(root: Path, *args: str) -> subprocess.CompletedProcess:
109
+ return subprocess.run(
110
+ ["git-cliff", *args],
111
+ cwd=root,
112
+ capture_output=True,
113
+ text=True,
114
+ env={**os.environ, "NO_COLOR": "1"},
115
+ )
116
+
117
+
118
+ def choose(c: "update.Candidates", to: str | None) -> tuple | None:
119
+ """The release to move the source to (asks the user if ``to`` is None)"""
120
+ options = {}
121
+ if c.next is not None:
122
+ options["n"] = ("next release containing it", c.next)
123
+ if c.latest is not None and c.latest != c.next:
124
+ options["l"] = ("latest release containing it", c.latest)
125
+ if not options:
126
+ say("✗", f"{c.name}: no release on PyPI contains {c.commit[:12]} yet")
127
+ return None
128
+ if to is not None:
129
+ return c.next if to == "next" else c.latest
130
+ if not sys.stdin.isatty():
131
+ raise RuntimeError("not interactive: use --to next or --to latest")
132
+
133
+ for key, (label, (_, tag)) in options.items():
134
+ say(f" [{key}] {label}: {tag}")
135
+ say(" [s] skip")
136
+ default = next(iter(options))
137
+ while True:
138
+ answer = input(f" Choice [{default}]: ").strip().lower() or default
139
+ if answer == "s":
140
+ return None
141
+ if answer in options:
142
+ return options[answer][1]
143
+
144
+
145
+ def cmd_update(root: Path, args) -> int:
146
+ project = Project(root / "pyproject.toml")
147
+ locked = update.locked(project)
148
+ changes = []
149
+ for name, source, deps in update.git_sources(project):
150
+ if args.packages and name not in args.packages:
151
+ continue
152
+ try:
153
+ c = update.candidates(name, dict(source), locked.get(name))
154
+ except (GitError, PackageIndexError) as e:
155
+ say("✗", str(e))
156
+ continue
157
+ at = f"{c.commit[:12]} ({'uv.lock' if name in locked else 'remote'})"
158
+ if c.current is not None and (
159
+ not args.all or c.latest is None or c.latest <= c.current
160
+ ):
161
+ say("✓", f"{name}: {at} is release {c.current[1]}")
162
+ continue
163
+ state = (
164
+ f"is release {c.current[1]}" if c.current else "is not a released version"
165
+ )
166
+ say("?", f"{name}: {at} {state}")
167
+ if (release := choose(c, args.to)) is None:
168
+ continue
169
+ for change in update.set_release(
170
+ project, name, deps, release, args.drop_source
171
+ ):
172
+ say("↑", change)
173
+ changes.append(change)
174
+
175
+ if changes and not args.dry_run:
176
+ project.save()
177
+ if (root / "uv.lock").exists():
178
+ subprocess.run(["uv", "lock"], cwd=root, check=True)
179
+ return 0
180
+
181
+
182
+ def next_version(root: Path) -> str:
183
+ """Next version tag from the conventional commits (git-cliff)"""
184
+ tags = git("tag", "--list", cwd=root).split()
185
+ if not any(tag_version(t) is not None for t in tags):
186
+ # git-cliff proposes 0.1.0, which may not match its tag pattern
187
+ return INITIAL_VERSION
188
+ result = cliff(root, "--bumped-version")
189
+ if result.returncode != 0:
190
+ raise RuntimeError(f"git-cliff --bumped-version: {result.stderr.strip()}")
191
+ return result.stdout.strip().splitlines()[-1]
192
+
193
+
194
+ def normalize_tag(version: str, root: Path) -> str:
195
+ """``1.2.0`` / ``v1.2.0`` -> the tag (``v`` prefix, as the existing tags)"""
196
+ if tag_version(version) is None:
197
+ raise ValueError(f"{version} is not a version")
198
+ try:
199
+ Version(version.removeprefix("v"))
200
+ except InvalidVersion as e:
201
+ raise ValueError(str(e)) from None
202
+ tags = git("tag", "--list", cwd=root).split()
203
+ prefix = "v" if not tags or any(t.startswith("v") for t in tags) else ""
204
+ return prefix + version.removeprefix("v")
205
+
206
+
207
+ def release_notes(root: Path, tag: str) -> str:
208
+ result = cliff(root, "--unreleased", "--tag", tag, "--strip", "header")
209
+ return result.stdout if result.returncode == 0 else ""
210
+
211
+
212
+ def cmd_gh_release(root: Path, args) -> int:
213
+ tag = normalize_tag(args.version or next_version(root), root)
214
+ if repo.tag_exists(root, tag):
215
+ say("✗", f"tag {tag} already exists")
216
+ return 1
217
+ say("Release", tag, "(from the commit log)" if not args.version else "")
218
+
219
+ if errors := run_checks(root, args):
220
+ say(f"{errors} problem(s): not releasing")
221
+ return 1
222
+
223
+ commit = repo.head(root)
224
+ notes = release_notes(root, tag)
225
+ command = ["gh", "release", "create", tag, "--target", commit, "--title", tag]
226
+ say("\n" + (notes.strip() or "(no release notes)") + "\n")
227
+ if args.dry_run:
228
+ say("Dry run:", shlex.join([*command, "--notes-file", "<notes>"]))
229
+ return 0
230
+ if not args.yes:
231
+ answer = input(f"Create the GitHub release {tag} at {commit[:12]}? [y/N] ")
232
+ if answer.strip().lower() not in ("y", "yes"):
233
+ say("Aborted")
234
+ return 1
235
+ with tempfile.NamedTemporaryFile("wt", suffix=".md") as fp:
236
+ fp.write(notes)
237
+ fp.flush()
238
+ subprocess.run([*command, "--notes-file", fp.name], cwd=root, check=True)
239
+ return 0
240
+
241
+
242
+ def add_check_options(parser):
243
+ parser.add_argument(
244
+ "--test",
245
+ metavar="COMMAND",
246
+ help="also run COMMAND (e.g. pytest) with the released dependencies"
247
+ " (uv run --isolated --no-sources)",
248
+ )
249
+ parser.add_argument(
250
+ "--uv-args",
251
+ default="",
252
+ metavar="OPTIONS",
253
+ help="uv run options for --test (e.g. '--all-extras --group test')",
254
+ )
255
+ parser.add_argument(
256
+ "--no-fetch", action="store_true", help="do not fetch the upstream branch"
257
+ )
258
+ parser.add_argument(
259
+ "--no-push-check", action="store_true", help="do not check that HEAD is pushed"
260
+ )
261
+
262
+
263
+ def main(argv=None):
264
+ parser = argparse.ArgumentParser(
265
+ prog="uv-release-manager",
266
+ description="Release uv projects that pin git dependencies during development",
267
+ )
268
+ parser.add_argument(
269
+ "-C", dest="root", type=Path, default=Path("."), help="project directory"
270
+ )
271
+ sub = parser.add_subparsers(dest="command", required=True)
272
+
273
+ check = sub.add_parser("check", help="check that the project can be released")
274
+ add_check_options(check)
275
+ check.set_defaults(func=cmd_check)
276
+
277
+ bump_parser = sub.add_parser(
278
+ "bump",
279
+ help="raise the dependency lower bounds to the released versions of"
280
+ " their git sources",
281
+ )
282
+ bump_parser.add_argument("--dry-run", action="store_true")
283
+ bump_parser.set_defaults(func=cmd_bump)
284
+
285
+ update_parser = sub.add_parser(
286
+ "update",
287
+ help="move git sources to releases (the next or the latest release"
288
+ " containing the pinned commit)",
289
+ )
290
+ update_parser.add_argument(
291
+ "packages", nargs="*", help="sources to update (default: all)"
292
+ )
293
+ update_parser.add_argument(
294
+ "--to",
295
+ choices=["next", "latest"],
296
+ help="do not ask: the next or the latest release containing the commit",
297
+ )
298
+ update_parser.add_argument(
299
+ "--all",
300
+ action="store_true",
301
+ help="also propose the latest release for sources already at a release",
302
+ )
303
+ update_parser.add_argument(
304
+ "--drop-source",
305
+ action="store_true",
306
+ help="remove the git source (the release is on PyPI) instead of pointing"
307
+ " it to the release tag",
308
+ )
309
+ update_parser.add_argument("--dry-run", action="store_true")
310
+ update_parser.set_defaults(func=cmd_update)
311
+
312
+ release = sub.add_parser(
313
+ "gh-release",
314
+ help="check, then create a GitHub release (which triggers the publish"
315
+ " workflow)",
316
+ )
317
+ release.add_argument(
318
+ "version",
319
+ nargs="?",
320
+ help="version to release (default: from the commit log, with git-cliff)",
321
+ )
322
+ release.add_argument("--dry-run", action="store_true")
323
+ release.add_argument("-y", "--yes", action="store_true", help="do not confirm")
324
+ add_check_options(release)
325
+ release.set_defaults(func=cmd_gh_release)
326
+
327
+ args = parser.parse_args(argv)
328
+ try:
329
+ return args.func(args.root.resolve(), args)
330
+ except (GitError, PackageIndexError, RuntimeError, ValueError) as e:
331
+ say("✗", str(e))
332
+ return 1
333
+
334
+
335
+ if __name__ == "__main__":
336
+ sys.exit(main())
@@ -0,0 +1,80 @@
1
+ """Git helpers (local repository and remotes)"""
2
+
3
+ import re
4
+ import subprocess
5
+ from pathlib import Path
6
+
7
+ from packaging.version import InvalidVersion, Version
8
+
9
+ #: Release tags: ``v1.2.3`` or ``1.2.3`` (PEP 440 pre / post / dev suffixes)
10
+ TAG = re.compile(r"^v?(\d+(?:\.\d+)*(?:[.-]?(?:a|b|rc|post|dev)\d+)*)$")
11
+
12
+
13
+ class GitError(RuntimeError):
14
+ pass
15
+
16
+
17
+ def git(*args: str, cwd: Path | None = None) -> str:
18
+ """Runs git and returns its (stripped) standard output"""
19
+ result = subprocess.run(
20
+ ["git", *args], cwd=cwd, capture_output=True, text=True, check=False
21
+ )
22
+ if result.returncode != 0:
23
+ raise GitError(f"git {' '.join(args)}: {result.stderr.strip()}")
24
+ return result.stdout.strip()
25
+
26
+
27
+ def tag_version(tag: str) -> Version | None:
28
+ """Version of a release tag (None if the tag is not a version)"""
29
+ if m := TAG.match(tag):
30
+ try:
31
+ return Version(m.group(1))
32
+ except InvalidVersion:
33
+ return None
34
+ return None
35
+
36
+
37
+ class RemoteRefs:
38
+ """The branches and tags of a remote repository (``git ls-remote``)"""
39
+
40
+ def __init__(self, url: str):
41
+ self.url = url
42
+ self.refs: dict[str, str] = {}
43
+ for line in git("ls-remote", "--tags", "--heads", url).splitlines():
44
+ sha, ref = line.split("\t")
45
+ if ref.endswith("^{}"): # peeled annotated tag: the commit
46
+ self.refs[ref[:-3]] = sha
47
+ else:
48
+ self.refs.setdefault(ref, sha)
49
+ self.head = git("ls-remote", "--symref", url, "HEAD").splitlines()
50
+
51
+ def default_branch(self) -> str | None:
52
+ for line in self.head:
53
+ if line.startswith("ref: "):
54
+ return line.split()[1].removeprefix("refs/heads/")
55
+ return None
56
+
57
+ def commit(self, *, rev=None, tag=None, branch=None) -> str:
58
+ """Commit of a uv git source (``rev``, ``tag``, ``branch`` or the
59
+ default branch)"""
60
+ if rev:
61
+ return rev
62
+ if tag:
63
+ ref = f"refs/tags/{tag}"
64
+ else:
65
+ branch = branch or self.default_branch()
66
+ ref = f"refs/heads/{branch}"
67
+ if ref not in self.refs:
68
+ raise GitError(f"{self.url}: no {ref}")
69
+ return self.refs[ref]
70
+
71
+ def versions(self, commit: str) -> list[tuple[Version, str, str]]:
72
+ """Release versions tagged on ``commit`` (full or abbreviated):
73
+ (version, tag, full commit), highest first"""
74
+ found = []
75
+ for ref, sha in self.refs.items():
76
+ if ref.startswith("refs/tags/") and sha.startswith(commit):
77
+ tag = ref.removeprefix("refs/tags/")
78
+ if (version := tag_version(tag)) is not None:
79
+ found.append((version, tag, sha))
80
+ return sorted(found, reverse=True)
@@ -0,0 +1,46 @@
1
+ """Released versions on the package index (PyPI JSON API)"""
2
+
3
+ import json
4
+ import os
5
+ import urllib.error
6
+ import urllib.request
7
+ from functools import cache
8
+
9
+ from packaging.utils import canonicalize_name
10
+ from packaging.version import InvalidVersion, Version
11
+
12
+ #: Base URL of the JSON API (``UV_RELEASE_MANAGER_PYPI`` overrides it, e.g. for
13
+ #: a test index)
14
+ PYPI = os.environ.get("UV_RELEASE_MANAGER_PYPI", "https://pypi.org/pypi")
15
+
16
+
17
+ class PackageIndexError(RuntimeError):
18
+ pass
19
+
20
+
21
+ @cache
22
+ def published_versions(name: str) -> frozenset[Version]:
23
+ """Versions of ``name`` with at least one (non yanked) file on the index"""
24
+ url = f"{PYPI}/{canonicalize_name(name)}/json"
25
+ try:
26
+ with urllib.request.urlopen(url, timeout=30) as response:
27
+ data = json.load(response)
28
+ except urllib.error.HTTPError as e:
29
+ if e.code == 404:
30
+ return frozenset()
31
+ raise PackageIndexError(f"{url}: {e}") from None
32
+ except urllib.error.URLError as e:
33
+ raise PackageIndexError(f"{url}: {e.reason}") from None
34
+
35
+ versions = set()
36
+ for version, files in data.get("releases", {}).items():
37
+ if files and not all(f.get("yanked") for f in files):
38
+ try:
39
+ versions.add(Version(version))
40
+ except InvalidVersion:
41
+ pass
42
+ return frozenset(versions)
43
+
44
+
45
+ def is_published(name: str, version: Version) -> bool:
46
+ return version in published_versions(name)
@@ -0,0 +1,87 @@
1
+ """State of the local repository before a release"""
2
+
3
+ import subprocess
4
+ from dataclasses import dataclass
5
+ from pathlib import Path
6
+
7
+ from .git import GitError, git
8
+
9
+
10
+ @dataclass
11
+ class Check:
12
+ name: str
13
+ ok: bool
14
+ message: str
15
+
16
+
17
+ def clean_tree(root: Path) -> Check:
18
+ """No uncommitted changes to tracked files"""
19
+ # Staged and unstaged changes to tracked files
20
+ changes = git("diff", "--name-only", "HEAD", cwd=root)
21
+ if changes:
22
+ files = ", ".join(changes.splitlines()[:5])
23
+ return Check("clean", False, f"uncommitted changes ({files})")
24
+ return Check("clean", True, "no uncommitted changes")
25
+
26
+
27
+ def pushed(root: Path, fetch: bool = True) -> Check:
28
+ """HEAD is on the upstream branch (what is released is what is pushed)"""
29
+ try:
30
+ upstream = git("rev-parse", "--abbrev-ref", "@{upstream}", cwd=root)
31
+ except GitError:
32
+ return Check("pushed", False, "the current branch has no upstream")
33
+ if fetch:
34
+ remote = upstream.split("/", 1)[0]
35
+ git("fetch", "--quiet", remote, cwd=root)
36
+ try:
37
+ git("merge-base", "--is-ancestor", "HEAD", upstream, cwd=root)
38
+ except GitError:
39
+ return Check("pushed", False, f"HEAD is not pushed to {upstream}")
40
+ return Check("pushed", True, f"HEAD is on {upstream}")
41
+
42
+
43
+ def lock_up_to_date(root: Path) -> Check:
44
+ """``uv.lock`` matches ``pyproject.toml``"""
45
+ if not (root / "uv.lock").exists():
46
+ return Check("lock", True, "no uv.lock")
47
+ result = subprocess.run(
48
+ ["uv", "lock", "--check"], cwd=root, capture_output=True, text=True
49
+ )
50
+ if result.returncode != 0:
51
+ return Check("lock", False, "uv.lock is outdated (run uv lock)")
52
+ return Check("lock", True, "uv.lock is up to date")
53
+
54
+
55
+ def released_dependencies_test(
56
+ root: Path, command: list[str], uv_args: list[str] = ()
57
+ ) -> Check:
58
+ """Runs ``command`` in an isolated environment resolved without the uv
59
+ sources, i.e. with the released versions of the dependencies
60
+
61
+ :param uv_args: extra ``uv run`` options (e.g. ``--all-extras``)
62
+ """
63
+ args = ["uv", "run", "--isolated", "--no-sources", *uv_args, "--", *command]
64
+ result = subprocess.run(args, cwd=root)
65
+ if result.returncode != 0:
66
+ return Check(
67
+ "released dependencies",
68
+ False,
69
+ f"{' '.join(command)} failed without the uv sources",
70
+ )
71
+ return Check(
72
+ "released dependencies", True, f"{' '.join(command)} passed without sources"
73
+ )
74
+
75
+
76
+ def head(root: Path) -> str:
77
+ return git("rev-parse", "HEAD", cwd=root)
78
+
79
+
80
+ def tag_exists(root: Path, tag: str) -> bool:
81
+ if git("tag", "--list", tag, cwd=root):
82
+ return True
83
+ try:
84
+ remote = git("ls-remote", "--tags", "origin", f"refs/tags/{tag}", cwd=root)
85
+ except GitError:
86
+ return False
87
+ return bool(remote)
@@ -0,0 +1,224 @@
1
+ """Git sources of a uv project and the dependencies they pin
2
+
3
+ During development, ``[tool.uv.sources]`` can pin dependencies to git commits.
4
+ Sources only matter for the local lock: the published metadata contains the
5
+ ``[project]`` dependencies only. Before a release, each git source must point
6
+ to a released (tagged) version, and the dependency must require at least that
7
+ version -- otherwise the published package could be installed with an older,
8
+ incompatible release.
9
+ """
10
+
11
+ import tomllib
12
+ from dataclasses import dataclass, field
13
+ from pathlib import Path
14
+
15
+ import tomlkit
16
+ from packaging.requirements import Requirement
17
+ from packaging.utils import canonicalize_name
18
+ from packaging.version import Version
19
+
20
+ from .git import GitError, RemoteRefs
21
+ from .pypi import PackageIndexError, is_published
22
+
23
+
24
+ @dataclass
25
+ class Dependency:
26
+ """A requirement of the project (``[project]`` dependencies or extras)"""
27
+
28
+ requirement: Requirement
29
+ #: The tomlkit array holding it, and its index (to rewrite it in place)
30
+ array: list
31
+ index: int
32
+ #: None for the main dependencies, the extra name otherwise
33
+ extra: str | None = None
34
+
35
+ @property
36
+ def where(self) -> str:
37
+ return "dependencies" if self.extra is None else f"extra {self.extra}"
38
+
39
+ def lower_bound(self) -> Version | None:
40
+ bounds = [
41
+ Version(s.version)
42
+ for s in self.requirement.specifier
43
+ if s.operator in (">=", ">", "==", "~=", "===") and "*" not in s.version
44
+ ]
45
+ return max(bounds, default=None)
46
+
47
+ def with_lower_bound(self, version: Version) -> str:
48
+ """The requirement with ``>=version`` (other bounds kept)"""
49
+ req = self.requirement
50
+ others = [str(s) for s in req.specifier if s.operator not in (">=", ">")]
51
+ extras = f"[{','.join(sorted(req.extras))}]" if req.extras else ""
52
+ # Single quotes in markers: no escaping in the TOML string
53
+ marker = f"; {str(req.marker).replace(chr(34), chr(39))}" if req.marker else ""
54
+ return f"{req.name}{extras}{','.join([f'>={version}', *others])}{marker}"
55
+
56
+
57
+ @dataclass
58
+ class SourceStatus:
59
+ """Status of a git (or path) source"""
60
+
61
+ name: str
62
+ source: dict
63
+ #: Released version of the source commit (None if not released)
64
+ version: Version | None = None
65
+ tag: str | None = None
66
+ commit: str | None = None
67
+ #: Problem with the source itself (not released, path source...)
68
+ error: str | None = None
69
+ #: Whether the commit comes from uv.lock (otherwise, from the remote)
70
+ locked: bool = False
71
+ #: Dependencies whose lower bound is below the released version
72
+ outdated: list[Dependency] = field(default_factory=list)
73
+ #: Dependencies whose lower bound is above the released version (the
74
+ #: published package would require a version that was not tested)
75
+ ahead: list[Dependency] = field(default_factory=list)
76
+ #: Dependencies that are fine
77
+ ok: list[Dependency] = field(default_factory=list)
78
+
79
+
80
+ class Project:
81
+ """A ``pyproject.toml`` (edited in place, formatting preserved)"""
82
+
83
+ def __init__(self, path: Path):
84
+ self.path = path
85
+ self.document = tomlkit.parse(path.read_text())
86
+
87
+ @property
88
+ def project(self):
89
+ return self.document.get("project", {})
90
+
91
+ @property
92
+ def sources(self) -> dict:
93
+ return self.document.get("tool", {}).get("uv", {}).get("sources", {})
94
+
95
+ def dependencies(self) -> dict[str, list[Dependency]]:
96
+ """Canonical name -> requirements (main dependencies and extras)"""
97
+ arrays = [(None, self.project.get("dependencies", []))]
98
+ arrays += list(self.project.get("optional-dependencies", {}).items())
99
+ deps: dict[str, list[Dependency]] = {}
100
+ for extra, array in arrays:
101
+ for i, spec in enumerate(array):
102
+ req = Requirement(str(spec))
103
+ deps.setdefault(canonicalize_name(req.name), []).append(
104
+ Dependency(req, array, i, extra)
105
+ )
106
+ return deps
107
+
108
+ def save(self):
109
+ self.path.write_text(tomlkit.dumps(self.document))
110
+
111
+
112
+ def locked_commits(lock: Path) -> dict[str, str]:
113
+ """Canonical package name -> commit of its git source in ``uv.lock``"""
114
+ if not lock.exists():
115
+ return {}
116
+ commits = {}
117
+ for package in tomllib.loads(lock.read_text()).get("package", []):
118
+ git_url = package.get("source", {}).get("git")
119
+ if git_url and "#" in git_url:
120
+ commits[canonicalize_name(package["name"])] = git_url.rsplit("#", 1)[1]
121
+ return commits
122
+
123
+
124
+ def source_status(
125
+ name: str,
126
+ source: dict,
127
+ deps: list[Dependency],
128
+ remotes: dict,
129
+ locked: str | None = None,
130
+ ) -> SourceStatus | None:
131
+ """Checks one source (None for sources that are not git / path, e.g.
132
+ package indexes or workspace members)
133
+
134
+ :param locked: the commit of the source in ``uv.lock`` (what was used
135
+ during development); if not given, the commit the source points to
136
+ on the remote (e.g. the tip of its branch)
137
+ """
138
+ status = SourceStatus(name, source)
139
+ if "path" in source:
140
+ status.error = f"path source {source['path']} (cannot be released)"
141
+ return status
142
+ if "git" not in source:
143
+ return None
144
+
145
+ url = source["git"]
146
+ try:
147
+ if url not in remotes:
148
+ remotes[url] = RemoteRefs(url)
149
+ refs = remotes[url]
150
+ status.locked = locked is not None
151
+ commit = locked or refs.commit(
152
+ rev=source.get("rev"), tag=source.get("tag"), branch=source.get("branch")
153
+ )
154
+ except GitError as e:
155
+ status.error = str(e)
156
+ return status
157
+
158
+ versions = refs.versions(commit)
159
+ if not versions:
160
+ status.commit = commit
161
+ status.error = f"{url} @ {commit[:12]} is not a released (tagged) version"
162
+ return status
163
+ status.version, status.tag, status.commit = versions[0]
164
+ try:
165
+ if not is_published(name, status.version):
166
+ status.error = (
167
+ f"{status.tag} ({status.commit[:12]}) is tagged but {name}"
168
+ f" {status.version} is not on PyPI"
169
+ )
170
+ return status
171
+ except PackageIndexError as e:
172
+ status.error = str(e)
173
+ return status
174
+
175
+ for dep in deps:
176
+ bound = dep.lower_bound()
177
+ if bound is None or bound < status.version:
178
+ status.outdated.append(dep)
179
+ elif bound > status.version:
180
+ status.ahead.append(dep)
181
+ else:
182
+ status.ok.append(dep)
183
+ return status
184
+
185
+
186
+ def check_sources(project: Project) -> list[SourceStatus]:
187
+ """Status of the git and path sources of the project's dependencies
188
+ (sources of development-only dependencies are ignored: they are not
189
+ published)"""
190
+ deps = project.dependencies()
191
+ locked = locked_commits(project.path.parent / "uv.lock")
192
+ remotes: dict[str, RemoteRefs] = {}
193
+ statuses = []
194
+ for name, source in project.sources.items():
195
+ if isinstance(source, list): # e.g. per-platform indexes
196
+ continue
197
+ cname = canonicalize_name(name)
198
+ if cname not in deps:
199
+ continue
200
+ if (
201
+ status := source_status(
202
+ name, dict(source), deps[cname], remotes, locked.get(cname)
203
+ )
204
+ ) is not None:
205
+ statuses.append(status)
206
+ return statuses
207
+
208
+
209
+ def bump(project: Project, statuses: list[SourceStatus]) -> list[tuple[str, str]]:
210
+ """Sets the lower bounds of the dependencies to the released versions of
211
+ their sources, when they are below (outdated) or above (untested) -- in
212
+ the document: call :meth:`Project.save`
213
+
214
+ :returns: the (old, new) requirements
215
+ """
216
+ changes = []
217
+ for status in statuses:
218
+ for dep in [*status.outdated, *status.ahead]:
219
+ new = dep.with_lower_bound(status.version)
220
+ changes.append((str(dep.array[dep.index]), new))
221
+ dep.array[dep.index] = new
222
+ status.ok.extend([*status.outdated, *status.ahead])
223
+ status.outdated, status.ahead = [], []
224
+ return changes
@@ -0,0 +1,133 @@
1
+ """Moving git sources to releases
2
+
3
+ For a git source pinned to a commit, two releases are candidates:
4
+
5
+ - the *next* release: the first release whose tag contains the commit (the
6
+ smallest change that keeps what was developed against)
7
+ - the *latest* release containing the commit
8
+
9
+ Older releases are never proposed (they would drop what the commit brings),
10
+ and only versions published on PyPI (and not pre-releases) are.
11
+ """
12
+
13
+ import hashlib
14
+ import os
15
+ from dataclasses import dataclass
16
+ from pathlib import Path
17
+
18
+ from packaging.utils import canonicalize_name
19
+ from packaging.version import Version
20
+
21
+ from .git import GitError, RemoteRefs, git, tag_version
22
+ from . import pypi
23
+ from .sources import Dependency, Project, locked_commits
24
+
25
+
26
+ def cache_dir() -> Path:
27
+ base = os.environ.get("XDG_CACHE_HOME") or Path.home() / ".cache"
28
+ return Path(base) / "uv-release-manager" / "repos"
29
+
30
+
31
+ def mirror(url: str) -> Path:
32
+ """A bare, tree-less clone of ``url`` (cached, fetched on each call) to
33
+ find the tags containing a commit"""
34
+ path = cache_dir() / hashlib.sha1(url.encode()).hexdigest()[:16]
35
+ if path.exists():
36
+ heads = "+refs/heads/*:refs/heads/*"
37
+ git("fetch", "--quiet", "--force", "--tags", "--prune", url, heads, cwd=path)
38
+ else:
39
+ path.parent.mkdir(parents=True, exist_ok=True)
40
+ git("clone", "--quiet", "--bare", "--filter=tree:0", url, str(path))
41
+ return path
42
+
43
+
44
+ @dataclass
45
+ class Candidates:
46
+ name: str
47
+ url: str
48
+ commit: str
49
+ #: Released version of the commit itself (None if not released)
50
+ current: tuple[Version, str] | None
51
+ #: First release containing the commit
52
+ next: tuple[Version, str] | None
53
+ #: Latest release containing the commit
54
+ latest: tuple[Version, str] | None
55
+
56
+
57
+ def release_tags(tags, published) -> list[tuple[Version, str]]:
58
+ """(version, tag) of the tags that are published, non pre-release
59
+ versions (ascending)"""
60
+ found = []
61
+ for tag in tags:
62
+ version = tag_version(tag)
63
+ if version is not None and not version.is_prerelease and version in published:
64
+ found.append((version, tag))
65
+ return sorted(found)
66
+
67
+
68
+ def candidates(name: str, source: dict, locked: str | None) -> Candidates:
69
+ url = source["git"]
70
+ refs = RemoteRefs(url)
71
+ commit = locked or refs.commit(
72
+ rev=source.get("rev"), tag=source.get("tag"), branch=source.get("branch")
73
+ )
74
+ published = pypi.published_versions(name)
75
+ current = refs.versions(commit)
76
+ current = (current[0][0], current[0][1]) if current else None
77
+
78
+ repo = mirror(url)
79
+ try:
80
+ containing = git("tag", "--contains", commit, cwd=repo).split()
81
+ except GitError:
82
+ raise GitError(f"{name}: commit {commit[:12]} is not in {url}") from None
83
+ after = release_tags(containing, published)
84
+ return Candidates(
85
+ name,
86
+ url,
87
+ commit,
88
+ current,
89
+ after[0] if after else None,
90
+ after[-1] if after else None,
91
+ )
92
+
93
+
94
+ def git_sources(project: Project) -> list[tuple[str, dict, list[Dependency]]]:
95
+ """Git sources of the published dependencies"""
96
+ deps = project.dependencies()
97
+ found = []
98
+ for name, source in project.sources.items():
99
+ if isinstance(source, list) or "git" not in source:
100
+ continue
101
+ if (cname := canonicalize_name(name)) in deps:
102
+ found.append((name, source, deps[cname]))
103
+ return found
104
+
105
+
106
+ def set_release(
107
+ project: Project, name: str, deps: list[Dependency], release, drop: bool
108
+ ) -> list[str]:
109
+ """Points the source of ``name`` to the release tag (or removes it), and
110
+ sets the lower bounds of its dependencies to the release version"""
111
+ version, tag = release
112
+ changes = []
113
+ sources = project.sources
114
+ if drop:
115
+ del sources[name]
116
+ changes.append(f"{name}: git source removed (released on PyPI)")
117
+ else:
118
+ source = sources[name]
119
+ for key in ("rev", "branch"):
120
+ if key in source:
121
+ del source[key]
122
+ source["tag"] = tag
123
+ changes.append(f"{name}: source -> tag {tag}")
124
+ for dep in deps:
125
+ new = dep.with_lower_bound(version)
126
+ if str(dep.array[dep.index]) != new:
127
+ changes.append(f"{dep.array[dep.index]} -> {new}")
128
+ dep.array[dep.index] = new
129
+ return changes
130
+
131
+
132
+ def locked(project: Project) -> dict[str, str]:
133
+ return locked_commits(project.path.parent / "uv.lock")
@@ -0,0 +1,120 @@
1
+ Metadata-Version: 2.5
2
+ Name: uv-release-manager
3
+ Version: 1.0.0
4
+ Summary: Release uv projects that pin git dependencies during development
5
+ Project-URL: Repository, https://github.com/experimaestro/uv-release-manager
6
+ License-Expression: GPL-3.0-or-later
7
+ Keywords: dependencies,git,pypi,release,uv
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Environment :: Console
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.11
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: Programming Language :: Python :: 3.13
14
+ Classifier: Programming Language :: Python :: 3.14
15
+ Classifier: Programming Language :: Python :: 3.15
16
+ Classifier: Topic :: Software Development :: Build Tools
17
+ Requires-Python: >=3.11
18
+ Requires-Dist: git-cliff>=2.6
19
+ Requires-Dist: packaging>=24
20
+ Requires-Dist: tomlkit>=0.13
21
+ Description-Content-Type: text/markdown
22
+
23
+ # uv-release-manager
24
+
25
+ Release [uv](https://docs.astral.sh/uv/) projects that pin git dependencies
26
+ during development.
27
+
28
+ While several libraries evolve together, it is convenient to pin a dependency
29
+ to a git commit in `[tool.uv.sources]`:
30
+
31
+ ```toml
32
+ [project]
33
+ dependencies = ["mylib>=0.3"]
34
+
35
+ [tool.uv.sources]
36
+ mylib = { git = "https://github.com/org/mylib", rev = "c4580cb" }
37
+ ```
38
+
39
+ Sources are only used for the local lock: the published package requires
40
+ `mylib>=0.3`. If the code needs the pinned commit, the release is broken as
41
+ soon as `mylib` 0.3 (or any version without that commit) is installed.
42
+ `uv-release-manager` checks, before releasing, that every git source points to
43
+ a released (tagged) version and that the dependency requires at least that
44
+ version.
45
+
46
+ ## Commands
47
+
48
+ ```sh
49
+ # Can we release? (fails fast, exit code 1 otherwise)
50
+ uv-release-manager check
51
+ uv-release-manager check --test pytest # also test with the released deps
52
+ uv-release-manager check --test pytest --uv-args "--all-extras --group test"
53
+
54
+ # Move git sources to releases: for each source, choose between the next
55
+ # release containing the pinned commit and the latest one containing it
56
+ uv-release-manager update
57
+ uv-release-manager update --to next # without asking
58
+ uv-release-manager update --drop-source # remove the source (use PyPI)
59
+
60
+ # Set the lower bounds to the released versions of the git sources
61
+ uv-release-manager bump
62
+
63
+ # Check, then create the GitHub release (the publish workflow does the rest);
64
+ # without a version, the next one is computed from the conventional commits
65
+ uv-release-manager gh-release # e.g. v0.5.0 after a feat: commit
66
+ uv-release-manager gh-release 1.0.0 --dry-run
67
+ ```
68
+
69
+ ### check
70
+
71
+ `check` (also run by `gh-release`) verifies that:
72
+
73
+ - each git source points to a commit tagged with a version (`v1.2.3` or
74
+ `1.2.3`) that is published on PyPI; the commit is the one locked in
75
+ `uv.lock` (what was developed against), or the one the source points to on
76
+ the remote when the package is not locked
77
+ - the lower bound of the dependency (main dependencies and extras) is this
78
+ version: a lower bound below allows older, incompatible releases, and one
79
+ above requires a version that was not tested
80
+ - there is no `path` source
81
+ - there are no uncommitted changes, `uv.lock` is up to date, and `HEAD` is
82
+ pushed to the upstream branch
83
+ - optionally (`--test COMMAND`), `COMMAND` passes in an isolated environment
84
+ resolved without the sources (`uv run --isolated --no-sources`)
85
+
86
+ Sources of development-only dependencies (`[dependency-groups]`) and index
87
+ sources are ignored, since they are not part of the published metadata.
88
+
89
+ ### update
90
+
91
+ For each git source (or the ones given on the command line) that is not a
92
+ release, `update` proposes the *next* release (the first release whose tag
93
+ contains the pinned commit) and the *latest* release containing it. Older
94
+ releases are never proposed, since they would drop what the commit brings;
95
+ only non pre-release versions published on PyPI are. The source is then
96
+ pointed to the release tag (or removed with `--drop-source`), the lower bounds
97
+ are set to the release version, and `uv.lock` is updated. With `--all`, sources
98
+ already at a release are moved to the latest release containing them.
99
+
100
+ The tags containing a commit are found in tree-less clones of the
101
+ dependencies, cached in `~/.cache/uv-release-manager`.
102
+
103
+ ### gh-release
104
+
105
+ `gh-release` uses [git-cliff](https://git-cliff.org) to compute the next
106
+ version (`--bumped-version`; v0.1.0 for the first release) and the release
107
+ notes, then runs `gh release create <tag> --target <HEAD>`. The publish
108
+ workflow (triggered by the release) builds and uploads the package.
109
+
110
+ ## Release
111
+
112
+ This project is released with itself:
113
+
114
+ ```sh
115
+ uv run uv-release-manager gh-release --dry-run # version and release notes
116
+ uv run uv-release-manager gh-release
117
+ ```
118
+
119
+ The GitHub release triggers `.github/workflows/python-publish.yml`, which runs
120
+ `uv-release-manager check` again and publishes to PyPI (trusted publishing).
@@ -0,0 +1,12 @@
1
+ uv_release_manager/__init__.py,sha256=keSUjFV8sywCUI0_LTButyaRaqXlIqwF-y6dgGyMpVI,71
2
+ uv_release_manager/__main__.py,sha256=E6Gls0DNz8GQK2K-kOUIx8cYhgANW_CH54VKrfCfs14,52
3
+ uv_release_manager/cli.py,sha256=f4bM10QgYvzHyrTTeIh44-qfzC2bEpKgAlpLVAL4S6g,11591
4
+ uv_release_manager/git.py,sha256=wgKBOsbwE4wRQV5xIufZv3hp06H8nO2H_8X1_3zCe3M,2777
5
+ uv_release_manager/pypi.py,sha256=ibeJH8A8UoUXxlIn5MfO3oIBRPcZk4tVFhpWakRUw9Y,1444
6
+ uv_release_manager/repo.py,sha256=G1UCbzalDoxiaAyBON2d9Ptyd2gBBFQmUJmRPTrXAck,2831
7
+ uv_release_manager/sources.py,sha256=DJNMfbzcSuLVKCHPjmVCokB4fnZqC1BnQhzxvj3xVws,8047
8
+ uv_release_manager/update.py,sha256=iXeUFTSeFR-4hn4DZCjgcbHhxH2JdnPeR96z9Z8pbpM,4410
9
+ uv_release_manager-1.0.0.dist-info/METADATA,sha256=ji00uR8yTl2N09uY6I3I_2T-shXwArqTFR2EUZWL8qc,4893
10
+ uv_release_manager-1.0.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
11
+ uv_release_manager-1.0.0.dist-info/entry_points.txt,sha256=zgu94HDLUVcDVC7INIo5AdrEEsYnS0FD2QnLw92CfGI,67
12
+ uv_release_manager-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ uv-release-manager = uv_release_manager.cli:main