1"""The ``commit`` verb: a conventional commit on a proved tree.
3Stages the change, derives the scope from the packages it touches,
4runs the affected gate first so every commit sits on a proved tree,
5validates the subject the way ``submit`` validates a title, and
6commits. ``git commit`` keeps working; the verb is the spelling that
7never mistypes the scope the release train reads and never commits an
8unproved tree.
9"""
11from __future__ import annotations
13from pathlib import Path
14from typing import Annotated
16import livery.footman as footman
17from livery import git
18from livery.footman import Arg, doc, fail
19from livery.workshop._conventional import TITLE_RE, TYPES
20from livery.workshop._extensions import workspace_root
23def scope_of(root: Path, paths: list[str]) -> str:
24 """The scope of a change to *paths*: the packages it touches, by directory.
26 Empty when the change touches no package (root files, notes), and
27 the subject carries no scope then. Several packages join with a
28 comma, the spelling the release train reads. A package whose
29 changed paths are only the files the engine composes into it and
30 their receipt is left out: a template's change renders into every
31 package, and the change's scope is the template's owner, which the
32 same change touches. The receipt is read as it stands and as it was
33 at HEAD, so a composed file the change removes counts too.
34 """
35 from livery.workshop._fragment_engine import (
36 RENDERED_MANIFEST,
37 read_rendered,
38 receipts_from,
39 )
40 from livery.workshop._packages import discover_packages
42 names: set[str] = set()
43 for package in discover_packages(root):
44 prefix = package.path + "/"
45 touched = [path[len(prefix) :] for path in paths if path.startswith(prefix)]
46 if not touched:
47 continue
48 before = git.file_at(root, "HEAD", f"{package.path}/{RENDERED_MANIFEST}")
49 composed = {
50 RENDERED_MANIFEST,
51 *read_rendered(package.directory),
52 *receipts_from(before),
53 }
54 if all(name in composed for name in touched):
55 continue
56 names.add(package.member)
57 return ",".join(sorted(names))
60def _run_check() -> None:
61 """The reflex before a commit: the affected gate in its fix mode."""
62 from livery.workshop._quality import check
64 check(fix=True)
67def commit_flow(
68 root: Path,
69 type: str,
70 subject: str,
71 *,
72 body: str = "",
73 scope: str = "",
74 only: str = "",
75 breaking: bool = False,
76 check: bool = True,
77) -> str:
78 """Commit the change in *root* as ``type(scope): subject``; the subject written.
80 The verb's act after its argument refusals, which another verb
81 calls to commit through the same rules: the balancer's submit
82 ([livery.workshop._balance.submit][]) among them. Refuses on
83 ``main``, on a reserved branch, and with nothing to commit. With
84 *check* the affected gate runs first in its fix mode; a caller
85 whose next step is a gate of the same tree passes False. The
86 scope is the packages the staged change touches (`scope_of`)
87 unless *scope* gives it; *only* stages those comma-separated paths
88 alone; *breaking* marks the break.
90 Raises:
91 Failed: naming the refusal, or git's words when it refuses the
92 commit, the change left staged.
93 """
94 branch = git.current_branch(root)
95 if not branch:95 ↛ 96line 95 didn't jump to line 96 because the condition on line 95 was never true
96 fail("HEAD is detached: check out a branch first")
97 if branch == "main":
98 fail(
99 f"on main: start a branch first (`{footman.prog()} start"
100 " docs/the-plan`, or an issue)"
101 )
102 if branch.startswith("workflow/"):
103 fail(f"{branch} is a reserved branch; its commits are the workflow engine's")
104 if check:
105 _run_check()
106 if only:
107 git.run(root, "add", "--", *[p.strip() for p in only.split(",") if p.strip()])
108 else:
109 git.run(root, "add", "-A")
110 staged = [
111 line
112 for line in git.run(root, "diff", "--cached", "--name-only").splitlines()
113 if line
114 ]
115 if not staged:
116 fail(
117 "nothing to commit: the working tree matches HEAD"
118 + (" for the paths named" if only else "")
119 )
120 given = bool(scope)
121 scope = scope or scope_of(root, staged)
122 title = f"{type}({scope})" if scope else type
123 title += ("!" if breaking else "") + f": {subject.strip()}"
124 if not TITLE_RE.match(title):124 ↛ 125line 124 didn't jump to line 125 because the condition on line 124 was never true
125 fail(f"{title!r} is not a conventional subject: type(scope)!: subject")
126 args = ["commit", "-m", title]
127 if body.strip():
128 args += ["-m", body.strip()]
129 try:
130 git.run(root, *args)
131 except git.GitError as exc:
132 fail(
133 "git refused the commit; the change is still staged, so fix the"
134 f" cause and re-run:\n{exc}"
135 )
136 print(
137 f" scope: {scope or 'none'} ({'given' if given else 'from the changed paths'})"
138 )
139 print(f" committed {git.head_sha(root)[:8]}: {title}")
140 return title
143@footman.task(serial=True)
144def commit(
145 type: Arg[str] = "",
146 subject: Arg[str] = "",
147 body: Annotated[str, doc("the commit body, after the subject")] = "",
148 scope: Annotated[
149 str, doc("the scope; derived from the changed paths when absent")
150 ] = "",
151 only: Annotated[
152 str, doc("stage these paths alone, comma-separated; everything when absent")
153 ] = "",
154 breaking: Annotated[
155 bool, doc("mark the commit as a break (the ! before the colon)")
156 ] = False,
157 check: Annotated[
158 bool, doc("run the affected gate first, healing what is mechanical")
159 ] = True,
160) -> None:
161 """Commit the change as ``type(scope): subject`` on a proved tree.
163 TYPE is one of the conventional types the release train reads and
164 SUBJECT says what the change does. The scope is the packages the
165 staged change touches, by directory name, or none for a change
166 outside every package; ``--scope`` overrides it. A package whose
167 only changes are the files the engine composes into it is left
168 out. The affected gate runs first in its fix mode, so mechanical
169 findings heal into the commit and nothing unproved is committed;
170 ``--no-check`` skips it. Everything is staged unless ``--only``
171 names the paths. Refuses on ``main``, on a reserved branch, and
172 with nothing to commit.
173 """
174 if type not in TYPES:
175 fail(
176 f"the type is one of {', '.join(TYPES)}:"
177 f' `{footman.prog()} commit feat "the subject"`'
178 )
179 if not subject.strip():
180 fail("name the subject: what the change does, in the imperative")
181 root = workspace_root()
182 if root is None:182 ↛ 183line 182 didn't jump to line 183 because the condition on line 182 was never true
183 fail("no workspace: no workshop.toml above the working directory")
184 commit_flow(
185 root,
186 type,
187 subject,
188 body=body,
189 scope=scope,
190 only=only,
191 breaking=breaking,
192 check=check,
193 )