gate-cache 0.5.0__tar.gz → 0.7.0__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: gate-cache
3
- Version: 0.5.0
3
+ Version: 0.7.0
4
4
  Summary: Skip lint and test gates that already passed on the exact same git tree.
5
5
  Author: Nate Landau
6
6
  Author-email: Nate Landau <github@natenate.org>
@@ -29,9 +29,8 @@ Classifier: Programming Language :: Python :: 3.11
29
29
  Classifier: Programming Language :: Python :: 3.12
30
30
  Classifier: Programming Language :: Python :: 3.13
31
31
  Classifier: Programming Language :: Python :: 3.14
32
- Requires-Dist: cyclopts>=5.2.0,<6.0.0
33
- Requires-Dist: nclutils>=3.4.4,<4.0.0
34
- Requires-Dist: platformdirs>=4.13.0,<5.0.0
32
+ Classifier: Programming Language :: Python :: 3.15
33
+ Requires-Dist: platformdirs>=4.14.5,<5.0.0
35
34
  Requires-Python: >=3.11
36
35
  Description-Content-Type: text/markdown
37
36
 
@@ -48,10 +47,12 @@ $ gate-cache -- uv run pytest
48
47
  ============================= 412 passed in 94.20s =============================
49
48
 
50
49
  $ gate-cache -- uv run pytest
51
- gate-cache: uv run pytest already passed on tree aaff74984ccc, skipping
50
+ gate-cache: uv run pytest already passed on tree aaff74984ccc, skipping (saved 1m 34s)
52
51
  ```
53
52
 
54
- A change to any file that git does not ignore changes the content, so no marker matches and the command runs again. A CI runner that starts from a fresh clone has no markers, so it runs every command.
53
+ The time in parentheses is how long the command ran when it passed, so the time that the skip saves is approximate.
54
+
55
+ A change to any file that git does not ignore changes the content, so no marker matches and the command runs again. To make a gate match only the files that its command reads, [scope the gate to its paths](#scope-a-gate-to-its-paths). A CI runner that starts from a fresh clone has no markers, so it runs every command.
55
56
 
56
57
  ## Install
57
58
 
@@ -86,6 +87,28 @@ gate-cache exits with the exit code of the command, or with 0 when it skips the
86
87
 
87
88
  The tree includes uncommitted edits and untracked files that git does not ignore. A gate that passes on uncommitted work therefore skips in the commit hook when you commit the same content. gate-cache computes the tree from a private copy of the index, so it never stages files or changes your index.
88
89
 
90
+ ## Scope a gate to its paths
91
+
92
+ In a repository with several parts, a change to the docs or to one part does not change the result of the tests of another part. A gate that has `--path` options matches only the content under those paths:
93
+
94
+ ```sh
95
+ gate-cache --name api-test --path api/ --path uv.lock -- uv run pytest api/tests
96
+ ```
97
+
98
+ After this gate passes, a change to `README.md` or to `web/` lets it skip, and so does a rebase that brings in only those changes. A change under `api/` or to `uv.lock` makes it run again.
99
+
100
+ Each `--path` is a git pathspec. gate-cache reads it from the top of the repository, so a recipe that runs in a subdirectory and a hook that runs at the top give the same paths. A directory covers every file under it. The order of the paths has no effect. Wildcards and `:(exclude)` work:
101
+
102
+ ```sh
103
+ gate-cache --name scripts-test --path scripts/ --path ':(exclude)scripts/fixtures/' -- uv run pytest scripts
104
+ ```
105
+
106
+ In a pathspec, `*` also matches `/`, so `*.just` matches a `.just` file in every directory. `**/justfile` matches only a `justfile` inside a directory. To also match the `justfile` at the top, use `:(glob)**/justfile`.
107
+
108
+ > **Warning:** List every file and directory that the command reads, including lock files and shared config. The gate skips when nothing under its paths changed. A change to a file outside the paths does not make the gate run again.
109
+
110
+ If a path matches no file, gate-cache runs the command without the cache and prints that path. A typo in a path therefore never makes a gate skip.
111
+
89
112
  ## Run it as a hook
90
113
 
91
114
  gate-cache works with [prek](https://github.com/j178/prek) and with [pre-commit](https://pre-commit.com) 3.2 or later. Each `gate-cache` hook takes the same arguments as the command line:
@@ -227,9 +250,24 @@ $ gate-cache status --name "uv run ruff check ."
227
250
  last run: exit code 1
228
251
  ```
229
252
 
230
- The `last run` line shows only when the name ran on this content without a pass.
253
+ The `last run` line shows only when the name ran on this content without a pass. The `duration` line shows how long the command ran when it passed.
254
+
255
+ For a scoped gate, give the same `--path` options with `--name`. The report adds a `paths` line and a `scope` line, and the `tree` line shows the whole tree:
256
+
257
+ ```console
258
+ $ gate-cache status --name api-test --path api/ --path uv.lock
259
+ name: api-test
260
+ paths: api/ uv.lock
261
+ scope: paths:7c462ce94adead1b7ab99f8e4212ffac194c562e0d178151207c1f01e0073615
262
+ tree: aaff74984cccd156a469afa7d9ab10e4777beb24
263
+ marker: /path/to/repo/.git/gate-cache/4156a896efe2ed16204b6d2525acbfbd9c4dd808dbfc135571e4f631b7d7754a
264
+ result: hit
265
+ duration: 1m 34s
266
+ ```
267
+
268
+ Without `--name`, `status` also lists the scoped gates that passed or missed on the current content of their paths.
231
269
 
232
- `status` runs nothing. With `--name`, it exits 0 when a marker matches and 1 when none does. Without `--name`, it exits 0 when at least one name passed. When gate-cache cannot match the content, for example during a merge conflict, the `tree` line gives the reason.
270
+ `status` runs nothing. With `--name`, it exits 0 when a marker matches and 1 when none does. Without `--name`, it exits 0 when at least one name passed. When gate-cache cannot match the content, for example during a merge conflict, the `tree` line gives the reason. For a scoped gate whose paths match no file, the `scope` line gives it.
233
271
 
234
272
  With `--json`, `status` writes one JSON object to stdout instead of text. The exit codes do not change:
235
273
 
@@ -246,7 +284,7 @@ $ gate-cache status --json
246
284
  }
247
285
  ```
248
286
 
249
- `reason` tells why gate-cache cannot match the content, and is `null` when it can. When caching is off, `enabled` is `false`, `reason` names the variable, and the other keys are empty or `null`. With `--name`, the object has the `name`, `marker`, `result`, and `last_run` keys in place of `passed` and `missed`.
287
+ `reason` tells why gate-cache cannot match the content, and is `null` when it can. When caching is off, `enabled` is `false`, `reason` names the variable, and the other keys are empty or `null`. With `--name`, the object has the `name`, `marker`, `result`, `last_run`, and `duration` keys in place of `passed` and `missed`. `duration` is the run time in seconds of the matching pass, or `null`. With `--path`, `tree` holds the scope value, and the object adds the `paths` and `full_tree` keys.
250
288
 
251
289
  ## Start fresh
252
290
 
@@ -11,10 +11,12 @@ $ gate-cache -- uv run pytest
11
11
  ============================= 412 passed in 94.20s =============================
12
12
 
13
13
  $ gate-cache -- uv run pytest
14
- gate-cache: uv run pytest already passed on tree aaff74984ccc, skipping
14
+ gate-cache: uv run pytest already passed on tree aaff74984ccc, skipping (saved 1m 34s)
15
15
  ```
16
16
 
17
- A change to any file that git does not ignore changes the content, so no marker matches and the command runs again. A CI runner that starts from a fresh clone has no markers, so it runs every command.
17
+ The time in parentheses is how long the command ran when it passed, so the time that the skip saves is approximate.
18
+
19
+ A change to any file that git does not ignore changes the content, so no marker matches and the command runs again. To make a gate match only the files that its command reads, [scope the gate to its paths](#scope-a-gate-to-its-paths). A CI runner that starts from a fresh clone has no markers, so it runs every command.
18
20
 
19
21
  ## Install
20
22
 
@@ -49,6 +51,28 @@ gate-cache exits with the exit code of the command, or with 0 when it skips the
49
51
 
50
52
  The tree includes uncommitted edits and untracked files that git does not ignore. A gate that passes on uncommitted work therefore skips in the commit hook when you commit the same content. gate-cache computes the tree from a private copy of the index, so it never stages files or changes your index.
51
53
 
54
+ ## Scope a gate to its paths
55
+
56
+ In a repository with several parts, a change to the docs or to one part does not change the result of the tests of another part. A gate that has `--path` options matches only the content under those paths:
57
+
58
+ ```sh
59
+ gate-cache --name api-test --path api/ --path uv.lock -- uv run pytest api/tests
60
+ ```
61
+
62
+ After this gate passes, a change to `README.md` or to `web/` lets it skip, and so does a rebase that brings in only those changes. A change under `api/` or to `uv.lock` makes it run again.
63
+
64
+ Each `--path` is a git pathspec. gate-cache reads it from the top of the repository, so a recipe that runs in a subdirectory and a hook that runs at the top give the same paths. A directory covers every file under it. The order of the paths has no effect. Wildcards and `:(exclude)` work:
65
+
66
+ ```sh
67
+ gate-cache --name scripts-test --path scripts/ --path ':(exclude)scripts/fixtures/' -- uv run pytest scripts
68
+ ```
69
+
70
+ In a pathspec, `*` also matches `/`, so `*.just` matches a `.just` file in every directory. `**/justfile` matches only a `justfile` inside a directory. To also match the `justfile` at the top, use `:(glob)**/justfile`.
71
+
72
+ > **Warning:** List every file and directory that the command reads, including lock files and shared config. The gate skips when nothing under its paths changed. A change to a file outside the paths does not make the gate run again.
73
+
74
+ If a path matches no file, gate-cache runs the command without the cache and prints that path. A typo in a path therefore never makes a gate skip.
75
+
52
76
  ## Run it as a hook
53
77
 
54
78
  gate-cache works with [prek](https://github.com/j178/prek) and with [pre-commit](https://pre-commit.com) 3.2 or later. Each `gate-cache` hook takes the same arguments as the command line:
@@ -190,9 +214,24 @@ $ gate-cache status --name "uv run ruff check ."
190
214
  last run: exit code 1
191
215
  ```
192
216
 
193
- The `last run` line shows only when the name ran on this content without a pass.
217
+ The `last run` line shows only when the name ran on this content without a pass. The `duration` line shows how long the command ran when it passed.
218
+
219
+ For a scoped gate, give the same `--path` options with `--name`. The report adds a `paths` line and a `scope` line, and the `tree` line shows the whole tree:
220
+
221
+ ```console
222
+ $ gate-cache status --name api-test --path api/ --path uv.lock
223
+ name: api-test
224
+ paths: api/ uv.lock
225
+ scope: paths:7c462ce94adead1b7ab99f8e4212ffac194c562e0d178151207c1f01e0073615
226
+ tree: aaff74984cccd156a469afa7d9ab10e4777beb24
227
+ marker: /path/to/repo/.git/gate-cache/4156a896efe2ed16204b6d2525acbfbd9c4dd808dbfc135571e4f631b7d7754a
228
+ result: hit
229
+ duration: 1m 34s
230
+ ```
231
+
232
+ Without `--name`, `status` also lists the scoped gates that passed or missed on the current content of their paths.
194
233
 
195
- `status` runs nothing. With `--name`, it exits 0 when a marker matches and 1 when none does. Without `--name`, it exits 0 when at least one name passed. When gate-cache cannot match the content, for example during a merge conflict, the `tree` line gives the reason.
234
+ `status` runs nothing. With `--name`, it exits 0 when a marker matches and 1 when none does. Without `--name`, it exits 0 when at least one name passed. When gate-cache cannot match the content, for example during a merge conflict, the `tree` line gives the reason. For a scoped gate whose paths match no file, the `scope` line gives it.
196
235
 
197
236
  With `--json`, `status` writes one JSON object to stdout instead of text. The exit codes do not change:
198
237
 
@@ -209,7 +248,7 @@ $ gate-cache status --json
209
248
  }
210
249
  ```
211
250
 
212
- `reason` tells why gate-cache cannot match the content, and is `null` when it can. When caching is off, `enabled` is `false`, `reason` names the variable, and the other keys are empty or `null`. With `--name`, the object has the `name`, `marker`, `result`, and `last_run` keys in place of `passed` and `missed`.
251
+ `reason` tells why gate-cache cannot match the content, and is `null` when it can. When caching is off, `enabled` is `false`, `reason` names the variable, and the other keys are empty or `null`. With `--name`, the object has the `name`, `marker`, `result`, `last_run`, and `duration` keys in place of `passed` and `missed`. `duration` is the run time in seconds of the matching pass, or `null`. With `--path`, `tree` holds the scope value, and the object adds the `paths` and `full_tree` keys.
213
252
 
214
253
  ## Start fresh
215
254
 
@@ -4,17 +4,14 @@ classifiers = [
4
4
  "Programming Language :: Python :: 3.12",
5
5
  "Programming Language :: Python :: 3.13",
6
6
  "Programming Language :: Python :: 3.14",
7
+ "Programming Language :: Python :: 3.15",
7
8
  ]
8
- dependencies = [
9
- "cyclopts>=5.2.0,<6.0.0",
10
- "nclutils>=3.4.4,<4.0.0",
11
- "platformdirs>=4.13.0,<5.0.0",
12
- ]
9
+ dependencies = ["platformdirs>=4.14.5,<5.0.0"]
13
10
  description = "Skip lint and test gates that already passed on the exact same git tree."
14
11
  name = "gate-cache"
15
12
  readme = "README.md"
16
13
  requires-python = ">=3.11"
17
- version = "0.5.0"
14
+ version = "0.7.0"
18
15
 
19
16
  [[project.authors]]
20
17
  name = "Nate Landau"
@@ -28,7 +25,7 @@ gate-cache = "gate_cache.cli:main"
28
25
 
29
26
  [build-system]
30
27
  build-backend = "uv_build"
31
- requires = ["uv_build>=0.11.0,<0.12.0"]
28
+ requires = ["uv_build>=0.13.0,<0.14"]
32
29
 
33
30
  [tool.uv.build-backend]
34
31
  module-name = "gate_cache"
@@ -169,23 +166,23 @@ error-on-warning = true
169
166
 
170
167
  [dependency-groups]
171
168
  dev = [
172
- "commitizen>=4.19.0",
173
- "coverage>=7.16.2",
174
- "duty>=1.10.0",
175
- "pre-commit>=4.6.2",
176
- "prek>=0.5.4",
169
+ "commitizen>=4.19.3",
170
+ "coverage>=7.17.3",
171
+ "duty>=1.10.1",
172
+ "pre-commit>=4.7.0",
173
+ "prek>=0.5.11",
177
174
  "pytest-clarity>=1.0.1",
178
175
  "pytest-cov>=7.1.0",
179
176
  "pytest-devtools>=1.3.0",
180
- "pytest-mock>=3.16.0",
177
+ "pytest-mock>=3.17.0",
181
178
  "pytest-repeat>=0.9.4",
182
179
  "pytest-sugar>=1.1.1",
183
180
  "pytest-xdist>=3.8.0",
184
- "pytest>=9.1.1",
181
+ "pytest>=9.2.0",
185
182
  "rich>=15.0.0",
186
- "ruff>=0.16.9",
183
+ "ruff>=0.17.5",
187
184
  "shellcheck-py>=0.11.0.1",
188
- "ty>=0.0.84",
189
- "typos>=1.50.3",
185
+ "ty>=0.0.104",
186
+ "typos>=1.52.2",
190
187
  "yamllint>=1.38.0",
191
188
  ]
@@ -5,49 +5,48 @@
5
5
  "Programming Language :: Python :: 3.12",
6
6
  "Programming Language :: Python :: 3.13",
7
7
  "Programming Language :: Python :: 3.14",
8
+ "Programming Language :: Python :: 3.15",
8
9
  ]
9
10
  dependencies = [
10
- "cyclopts>=5.2.0,<6.0.0",
11
- "nclutils>=3.4.4,<4.0.0",
12
- "platformdirs>=4.13.0,<5.0.0",
13
- ]
11
+ "platformdirs>=4.14.5,<5.0.0",
12
+ ]
14
13
  description = "Skip lint and test gates that already passed on the exact same git tree."
15
14
  license = { file = "LICENSE" }
16
15
  name = "gate-cache"
17
16
  readme = "README.md"
18
17
  requires-python = ">=3.11"
19
- version = "0.5.0"
18
+ version = "0.7.0"
20
19
 
21
20
  [project.scripts]
22
21
  gate-cache = "gate_cache.cli:main"
23
22
 
24
23
  [build-system]
25
24
  build-backend = "uv_build"
26
- requires = ["uv_build>=0.11.0,<0.12.0"]
25
+ requires = ["uv_build>=0.13.0,<0.14"]
27
26
 
28
27
  [tool.uv.build-backend]
29
28
  module-name = "gate_cache"
30
29
 
31
30
  [dependency-groups]
32
31
  dev = [
33
- "commitizen>=4.19.0",
34
- "coverage>=7.16.2",
35
- "duty>=1.10.0",
36
- "pre-commit>=4.6.2",
37
- "prek>=0.5.4",
32
+ "commitizen>=4.19.3",
33
+ "coverage>=7.17.3",
34
+ "duty>=1.10.1",
35
+ "pre-commit>=4.7.0",
36
+ "prek>=0.5.11",
38
37
  "pytest-clarity>=1.0.1",
39
38
  "pytest-cov>=7.1.0",
40
39
  "pytest-devtools>=1.3.0",
41
- "pytest-mock>=3.16.0",
40
+ "pytest-mock>=3.17.0",
42
41
  "pytest-repeat>=0.9.4",
43
42
  "pytest-sugar>=1.1.1",
44
43
  "pytest-xdist>=3.8.0",
45
- "pytest>=9.1.1",
44
+ "pytest>=9.2.0",
46
45
  "rich>=15.0.0",
47
- "ruff>=0.16.9",
46
+ "ruff>=0.17.5",
48
47
  "shellcheck-py>=0.11.0.1",
49
- "ty>=0.0.84",
50
- "typos>=1.50.3",
48
+ "ty>=0.0.104",
49
+ "typos>=1.52.2",
51
50
  "yamllint>=1.38.0",
52
51
  ]
53
52
 
@@ -1,3 +1,3 @@
1
1
  """Skip lint and test gates that already passed on the exact same git tree."""
2
2
 
3
- __version__ = "0.5.0"
3
+ __version__ = "0.7.0"
@@ -0,0 +1,308 @@
1
+ """Command line interface for gate-cache."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import shlex
7
+ import sys
8
+ from dataclasses import dataclass
9
+ from typing import TYPE_CHECKING
10
+
11
+ from gate_cache import __version__
12
+ from gate_cache.console import say
13
+ from gate_cache.gate import clear_cache, gate_status, run_gate
14
+
15
+ if TYPE_CHECKING:
16
+ from collections.abc import Sequence
17
+
18
+ _USAGE_ERROR = 2
19
+ _INTERRUPTED = 130
20
+ _INFO_FLAGS = {"-h", "--help", "--version"}
21
+ _NAME_NEEDS_VALUE = "--name needs a value, e.g. gate-cache --name pytest -- uv run pytest"
22
+ _NEEDS_SEPARATOR = "put -- before the command, e.g. gate-cache -- uv run pytest"
23
+ _NEEDS_VALUE = {
24
+ "--name": _NAME_NEEDS_VALUE,
25
+ "--path": "--path needs a value, e.g. gate-cache --path src/ -- uv run pytest",
26
+ }
27
+ _NAME_REPEATED = "--name given more than once"
28
+ _NO_COMMAND = "no command given after --"
29
+
30
+ _USAGE = """\
31
+ gate-cache [--name NAME] [--path PATHSPEC]... -- COMMAND [ARGS...]
32
+ gate-cache status [--name NAME [--path PATHSPEC]...] [--json]
33
+ gate-cache clear"""
34
+
35
+ _HELP = """\
36
+ Skip a lint or test command that already passed on the same git tree. gate-cache
37
+ runs the command, records a pass keyed on the git tree of the working copy
38
+ (tracked and untracked, non-ignored files), and skips the command next time the
39
+ tree is identical. A pass on uncommitted work therefore skips when the same
40
+ content is committed.
41
+
42
+ -- is required, and only --name and --path may come before it. Everything after
43
+ -- is the command, verbatim. Without --name, the gate name is the command
44
+ itself, so each set of arguments has its own records. Give --name to share
45
+ records between commands that check the same thing, or to key on inputs that the
46
+ tree does not cover.
47
+
48
+ Exit codes:
49
+ run the command's own exit code, or 0 when a recorded pass lets it skip.
50
+ Usage errors exit 2.
51
+ status 0 when the named gate, or any gate without --name, passed on the
52
+ current tree. 1 otherwise. --json prints one JSON object instead.
53
+ clear 0 on success, 1 on failure.
54
+
55
+ GATE_CACHE_DISABLE and CI are on when the value is not empty, 0, or false (any
56
+ case). If GATE_CACHE_DISABLE is on, the command always runs without the cache.
57
+ If it is 0 or false, caching stays on. If it is empty or not set, CI decides the
58
+ same way.
59
+ Set GATE_CACHE_MAX_AGE_DAYS to a positive whole number to change how many days a
60
+ recorded pass lasts (default 30).
61
+
62
+ Only the name and the file content are keyed. The working directory is not, so
63
+ a command whose meaning depends on it needs a distinct --name. To also key on an
64
+ ignored file, an environment variable, or a tool version, put its value in
65
+ --name. A changed value gives a new name, so the command runs again. Never put a
66
+ secret in a name, because markers and status store it as plain text. Without
67
+ --name the command line is the name, so give --name to a command that takes a
68
+ secret argument. Never wrap checks that depend on the commit message or the
69
+ branch name.
70
+
71
+ --path scopes a gate to the files it reads, so a change elsewhere in the
72
+ repository does not run it again. Each --path is a git pathspec, read from the
73
+ top of the work tree whatever the current directory, and globs and :(exclude)
74
+ work. Repeat --path for each path. The gate skips when nothing under its paths changed,
75
+ so a path left out is a skip that should have run. A path that matches no file
76
+ runs the command without the cache.
77
+
78
+ Typical use:
79
+ gate-cache -- uv run pytest -x
80
+ gate-cache --name pytest -- uv run pytest -x
81
+ gate-cache --name "test-$(git hash-object .env)" -- uv run pytest
82
+ gate-cache --name api-test --path api/ -- uv run pytest
83
+ """
84
+
85
+ _RUN_HELP = """\
86
+ subcommands:
87
+ status Report whether gates would skip, without running anything.
88
+ clear Delete every recorded pass for this repository.
89
+
90
+ run:
91
+ gate-cache [--name NAME] [--path PATHSPEC]... -- COMMAND [ARGS...] runs COMMAND
92
+ unless it already passed on the current git tree, or on the same content under
93
+ its paths. On a skip, it prints one line to stderr and
94
+ exits 0 without running anything. Otherwise it runs the command and exits with
95
+ its exit code. The command runs without caching (and nothing is recorded) when
96
+ GATE_CACHE_DISABLE or CI turns caching off, the tree is unknown (for example an
97
+ unmerged index), or this is not a git repository. A pass is recorded only when
98
+ the command exits 0 and the run leaves the tree unchanged.
99
+
100
+ Run gate-cache SUBCOMMAND --help for the options of a subcommand.
101
+ """
102
+
103
+ _STATUS_HELP = """\
104
+ Report whether gates would skip, without running anything.
105
+
106
+ With --name, print the tree hash (or why it is unknown), the marker path,
107
+ hit or miss, and how the last run on this tree failed when it did. Exit 0 on a
108
+ hit, 1 otherwise. Repeat --path with --name to look up a gate scoped to those
109
+ paths.
110
+
111
+ Without --name, list the gates that passed on the current tree and the gates
112
+ that ran on it without passing. Scoped gates are listed when they passed or
113
+ missed on the current content of their paths. Exit 0 when at least one gate
114
+ passed, 1 otherwise.
115
+ """
116
+
117
+ _CLEAR_HELP = """\
118
+ Delete every recorded pass for this repository.
119
+
120
+ Use after something outside git changes, such as a tool upgrade. Exits 1 outside a
121
+ git repository.
122
+ """
123
+
124
+
125
+ class _UsageError(Exception):
126
+ """A malformed run invocation, reported as one line on stderr with exit code 2."""
127
+
128
+
129
+ class _StoreOnce(argparse.Action):
130
+ """Store an option's value, rejecting a second occurrence instead of overwriting the first."""
131
+
132
+ def __call__(
133
+ self,
134
+ parser: argparse.ArgumentParser,
135
+ namespace: argparse.Namespace,
136
+ values: str | Sequence[object] | None,
137
+ option_string: str | None = None,
138
+ ) -> None:
139
+ if getattr(namespace, self.dest) is not None:
140
+ parser.error(f"{option_string} given more than once")
141
+ setattr(namespace, self.dest, values)
142
+
143
+
144
+ def _main_parser() -> argparse.ArgumentParser:
145
+ """Build the top-level parser, which serves only --help and --version.
146
+
147
+ The run form is not parsed here because everything after -- must reach the wrapped
148
+ command verbatim. The parser still declares --name so that --help documents it.
149
+ """
150
+ parser = argparse.ArgumentParser(
151
+ prog="gate-cache",
152
+ usage=_USAGE,
153
+ description=_HELP,
154
+ epilog=_RUN_HELP,
155
+ formatter_class=argparse.RawDescriptionHelpFormatter,
156
+ allow_abbrev=False,
157
+ )
158
+ parser.add_argument("--version", action="version", version=__version__)
159
+ parser.add_argument(
160
+ "--name",
161
+ metavar="NAME",
162
+ help="Gate name. Records match only when the name and the tree both match. "
163
+ "Defaults to the command and its arguments, quoted as a shell would.",
164
+ )
165
+ parser.add_argument(
166
+ "--path",
167
+ metavar="PATHSPEC",
168
+ help="Key on only the files under this git pathspec, read from the top of the work "
169
+ "tree. Repeat for each path.",
170
+ )
171
+ return parser
172
+
173
+
174
+ def _status_parser() -> argparse.ArgumentParser:
175
+ """Build the parser for the status subcommand."""
176
+ parser = argparse.ArgumentParser(
177
+ prog="gate-cache status",
178
+ description=_STATUS_HELP,
179
+ formatter_class=argparse.RawDescriptionHelpFormatter,
180
+ allow_abbrev=False,
181
+ )
182
+ parser.add_argument(
183
+ "--name",
184
+ action=_StoreOnce,
185
+ help="Gate name to look up. Omit it to list every gate that ran on this tree.",
186
+ )
187
+ parser.add_argument(
188
+ "--path",
189
+ action="append",
190
+ default=[],
191
+ metavar="PATHSPEC",
192
+ help="Look up the gate scoped to these paths. Repeat for each path. Needs --name.",
193
+ )
194
+ parser.add_argument(
195
+ "--json",
196
+ dest="as_json",
197
+ action="store_true",
198
+ help="Print one JSON object to stdout instead of text. Exit codes are unchanged.",
199
+ )
200
+ return parser
201
+
202
+
203
+ def _clear_parser() -> argparse.ArgumentParser:
204
+ """Build the parser for the clear subcommand."""
205
+ return argparse.ArgumentParser(
206
+ prog="gate-cache clear",
207
+ description=_CLEAR_HELP,
208
+ formatter_class=argparse.RawDescriptionHelpFormatter,
209
+ allow_abbrev=False,
210
+ )
211
+
212
+
213
+ @dataclass(frozen=True)
214
+ class _RunArgs:
215
+ """The options before -- and the command after it."""
216
+
217
+ name: str | None
218
+ paths: list[str]
219
+ command: list[str]
220
+
221
+
222
+ def _option_value(tokens: list[str], index: int, option: str) -> tuple[str, int] | None:
223
+ """Read `option X` or `option=X` at index, returning the value and the next index.
224
+
225
+ Raises:
226
+ _UsageError: When the option has no value or an empty one, such as an unset shell
227
+ variable.
228
+ """
229
+ arg = tokens[index]
230
+ if arg == option:
231
+ if index + 1 == len(tokens) or tokens[index + 1] == "--":
232
+ raise _UsageError(_NEEDS_VALUE[option])
233
+ value, after = tokens[index + 1], index + 2
234
+ elif arg.startswith(f"{option}="):
235
+ value, after = arg.removeprefix(f"{option}="), index + 1
236
+ else:
237
+ return None
238
+ if not value:
239
+ raise _UsageError(_NEEDS_VALUE[option])
240
+ return value, after
241
+
242
+
243
+ def _split_run(tokens: list[str]) -> _RunArgs:
244
+ """Split a run invocation into its options and the command after the first --.
245
+
246
+ Only `--name` and `--path`, each as `--opt X` or `--opt=X`, may precede `--`, so a stray
247
+ option such as `--version` or the first word of the command can never be mistaken for
248
+ one of ours.
249
+
250
+ Raises:
251
+ _UsageError: When anything else precedes `--`, `--` is missing, an option is
252
+ missing its value, or `--name` is given twice.
253
+ """
254
+ name: str | None = None
255
+ paths: list[str] = []
256
+ index = 0
257
+ while index < len(tokens):
258
+ if tokens[index] == "--":
259
+ return _RunArgs(name=name, paths=paths, command=tokens[index + 1 :])
260
+ if (found := _option_value(tokens=tokens, index=index, option="--name")) is not None:
261
+ if name is not None:
262
+ raise _UsageError(_NAME_REPEATED)
263
+ name, index = found
264
+ elif (found := _option_value(tokens=tokens, index=index, option="--path")) is not None:
265
+ value, index = found
266
+ paths.append(value)
267
+ else:
268
+ break
269
+ raise _UsageError(_NEEDS_SEPARATOR)
270
+
271
+
272
+ def _dispatch(tokens: list[str]) -> int:
273
+ """Run the invocation in tokens and return its exit code.
274
+
275
+ Raises:
276
+ _UsageError: When a run invocation is malformed.
277
+ """
278
+ if tokens and tokens[0] in _INFO_FLAGS:
279
+ _main_parser().parse_args(tokens) # prints help or the version, then exits
280
+ if tokens and tokens[0] == "status":
281
+ parser = _status_parser()
282
+ args = parser.parse_args(tokens[1:])
283
+ if args.path and args.name is None:
284
+ parser.error("--path needs --name")
285
+ if "" in args.path:
286
+ parser.error(_NEEDS_VALUE["--path"])
287
+ return gate_status(args.name, as_json=args.as_json, paths=args.path)
288
+ if tokens and tokens[0] == "clear":
289
+ _clear_parser().parse_args(tokens[1:])
290
+ return clear_cache()
291
+
292
+ run = _split_run(tokens)
293
+ if not run.command:
294
+ raise _UsageError(_NO_COMMAND)
295
+ name = shlex.join(run.command) if run.name is None else run.name
296
+ return run_gate(name, run.command, paths=run.paths)
297
+
298
+
299
+ def main() -> None:
300
+ """Run the gate-cache command line interface and exit with its code."""
301
+ try:
302
+ code = _dispatch(sys.argv[1:])
303
+ except _UsageError as error:
304
+ say(str(error))
305
+ sys.exit(_USAGE_ERROR)
306
+ except KeyboardInterrupt:
307
+ sys.exit(_INTERRUPTED)
308
+ sys.exit(code)