Skip to content

Commit 41feb68

Browse files
authored
Merge pull request #146 from bjester/sync-126
Add treefort sync for repository hooks and templates
2 parents 5c82016 + ded6748 commit 41feb68

20 files changed

Lines changed: 1259 additions & 68 deletions

‎README.md‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ A CLI tool that helps you manage Git worktrees. Built as a GitHub CLI (`gh`) ext
2727
- [switch](#commands-switch)
2828
- [remove](#commands-remove)
2929
- [prune](#commands-prune)
30+
- [sync](#commands-sync)
3031
- [install](#commands-install)
3132
- [shell-init](#commands-shell-init)
3233
- [version](#commands-version)
@@ -264,6 +265,29 @@ Finds worktrees whose local branch head matches a merged GitHub pull request. Un
264265

265266
</details>
266267

268+
<details>
269+
<summary><strong><a id="commands-sync">sync</a></strong> — Synchronize project hooks and templates</summary>
270+
271+
**Spec:** `sync [ref] [--no-fetch]`
272+
273+
Copies `.treefort/hooks/` and `.treefort/templates/` from the repository Git tree into the
274+
project's `.treefort/` directory. Use it to collect hooks and templates that your team added or
275+
changed after you ran `init`.
276+
277+
Files are copied byte for byte, so binary templates stay intact. Executable bits recorded in Git
278+
are preserved on both hooks and templates. Existing files are replaced. Files that exist only on
279+
your machine are kept.
280+
281+
The command reads `<default_remote>/<default_branch>` unless you pass a `ref`. It fetches first,
282+
from the remote the `ref` names when it names one, and from the default remote otherwise.
283+
284+
- `--no-fetch`: Skip the fetch and read the ref that is already in your local repository
285+
286+
Synced hooks are not approved automatically. The next time a synced hook runs, treefort prompts
287+
you to approve its new checksum.
288+
289+
</details>
290+
267291
<details>
268292
<summary><strong><a id="commands-install">install</a></strong> — Install treefort</summary>
269293

‎src/treefort/commands/init.py‎

Lines changed: 7 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,7 @@
66
from treefort.config import RepositoryConfig, TomlConfigIO
77
from treefort.errors import ProjectExistsError, RepositoryPathError
88
from treefort.git import GitUri
9-
from treefort.hooks import Hook, HookExists
10-
from treefort.templates import TemplateExists
9+
from treefort.hooks import Hook
1110

1211
JUST_PATH_RE = re.compile(r"^[\w\-_]+/[\w\-_]+$")
1312

@@ -146,29 +145,11 @@ def __call__(
146145
)
147146

148147
def _add_hooks(self, config):
149-
"""Checks whether the repo has hooks in the default branch and copies them"""
150-
for hook in Hook:
151-
# check to see if repo has a hook
152-
if not any(self._runtime.git.ls_tree(config.default_branch, hook.git_path)):
153-
continue
154-
155-
# copy it
156-
try:
157-
with self._runtime.hooks.add(hook) as f:
158-
for line in self._runtime.git.cat_file(config.default_branch, hook.git_path):
159-
f.write(f"{line}\n")
160-
except HookExists as e:
161-
self._logger.warning(f"Skipping due to error: {str(e)}")
148+
"""Copies any hooks tracked in the default branch, keeping hooks that already exist"""
149+
self._runtime.hooks.sync_from_git(self._runtime.git, config.default_branch, overwrite=False)
162150

163151
def _add_templates(self, config):
164-
"""Checks whether the repo has templates in the default branch and copies them"""
165-
# check to see if repo has templates
166-
for template_ls in self._runtime.git.ls_tree(config.default_branch, ".treefort/templates"):
167-
template_file = template_ls.split("\t")[1].strip('"')
168-
# copy it
169-
try:
170-
with self._runtime.templates.add(template_file) as f:
171-
for line in self._runtime.git.cat_file(config.default_branch, template_file):
172-
f.write(f"{line}\n")
173-
except TemplateExists as e:
174-
self._logger.warning(f"Skipping due to error: {str(e)}")
152+
"""Copies any templates tracked in the default branch, keeping existing templates"""
153+
self._runtime.templates.sync_from_git(
154+
self._runtime.git, config.default_branch, overwrite=False
155+
)

‎src/treefort/commands/sync.py‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
from typing import Annotated
2+
3+
from treefort import ui
4+
from treefort.command import Arg, Command, Completion, command
5+
6+
7+
@command("sync")
8+
class SyncCommand(Command):
9+
"""Synchronize project hooks and templates from the repository"""
10+
11+
def __call__(
12+
self,
13+
ref: Annotated[str | None, Arg(complete=Completion.BRANCH_REF)] = None,
14+
*,
15+
fetch: bool = True,
16+
) -> None:
17+
"""Synchronize project hooks and templates from a Git ref.
18+
19+
Copies `.treefort/hooks/` and `.treefort/templates/` out of the repository Git tree
20+
into the project configuration directory. Files are written byte for byte, so binary
21+
templates survive intact, and executable bits recorded in Git are preserved.
22+
23+
Modified hooks are not approved automatically; the next hook execution prompts for
24+
approval of the new checksum.
25+
26+
Examples:
27+
treefort sync
28+
treefort sync upstream/release
29+
treefort sync --no-fetch
30+
31+
:param ref: Git ref to sync from (defaults to `<default_remote>/<default_branch>`)
32+
:param fetch: Fetch before syncing, from the remote the ref names when it names one
33+
"""
34+
self._context.assert_within_project()
35+
config = self._context.get_config()
36+
remote = self._runtime.get_default_remote()
37+
remote_name = remote.name if remote else "origin"
38+
target_ref = ref or f"{remote_name}/{config.default_branch}"
39+
40+
with self._context.use(self._context.project_dir):
41+
if fetch:
42+
fetch_remote = self._resolve_fetch_remote(ref, remote_name)
43+
with ui.spinner(f"Fetching {fetch_remote}...", enabled=self._ui_enabled):
44+
self._runtime.git.fetch(fetch_remote)
45+
46+
hook_count = self._runtime.hooks.sync_from_git(
47+
self._runtime.git, target_ref, overwrite=True
48+
)
49+
template_count = self._runtime.templates.sync_from_git(
50+
self._runtime.git, target_ref, overwrite=True
51+
)
52+
53+
self._logger.info(
54+
ui.success(
55+
f"Synced {hook_count} hook(s) and {template_count} template(s) "
56+
f"from {ui.bold(target_ref)}"
57+
)
58+
)
59+
60+
def _resolve_fetch_remote(self, ref: str | None, default_remote: str) -> str:
61+
"""Return the remote to fetch, which is the one an explicit ref names when it has one.
62+
63+
A ref such as `upstream/release` is read from the remote-tracking namespace, so
64+
fetching the default remote would leave it stale. A ref that names no configured
65+
remote, such as `main` or `refs/pull/7/head`, falls back to the default remote.
66+
67+
:param ref: The ref the caller passed, or ``None`` for the default branch
68+
:param default_remote: The remote to fetch when the ref names none
69+
:return: The name of the remote to fetch
70+
"""
71+
if not ref:
72+
return default_remote
73+
prefix = ref.split("/", 1)[0]
74+
remote_names = {remote.name for remote in self._runtime.git.remote()}
75+
return prefix if prefix in remote_names else default_remote

‎src/treefort/git.py‎

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import re
22
import subprocess
33
from collections.abc import Iterator
4+
from dataclasses import dataclass
45
from pathlib import Path
56
from urllib import parse
67

@@ -11,6 +12,9 @@
1112
GIT_EXT_RE = re.compile(r"\.git$", re.IGNORECASE)
1213
# Git records checked-out local branches in worktree listings as this ref prefix.
1314
LOCAL_BRANCH_REF_PREFIX = "refs/heads/"
15+
# Tree modes that hold regular file content: 100644 is plain and 100755 is executable.
16+
# Symlinks are recorded as 120000 and subtrees as 040000, so neither carries file content.
17+
TREE_FILE_MODES = ("100644", "100755")
1418

1519

1620
class GitUri:
@@ -99,6 +103,46 @@ def matches(self, owner: str, name: str) -> bool:
99103
return self.git_uri.matches(owner, name)
100104

101105

106+
@dataclass(frozen=True)
107+
class GitTreeEntry:
108+
"""A single ``git ls-tree`` record describing one path in a Git tree."""
109+
110+
mode: str
111+
"""The tree mode, such as ``100644``, ``100755``, or ``120000`` for a symlink."""
112+
113+
obj_type: str
114+
"""The object type, which is ``blob`` for files and symlinks."""
115+
116+
sha: str
117+
"""The object name of the blob holding the file content."""
118+
119+
path: str
120+
"""The repository-relative POSIX path of the entry."""
121+
122+
@property
123+
def is_executable(self) -> bool:
124+
return self.mode == "100755"
125+
126+
127+
def _parse_tree_entries(output: str) -> list[GitTreeEntry]:
128+
"""Parse NUL-delimited ``git ls-tree`` records into tree entries.
129+
130+
:param output: The raw ``git ls-tree -r -z`` output
131+
:return: The parsed entries, in the order Git emitted them
132+
"""
133+
entries = []
134+
for record in output.split("\x00"):
135+
if not record:
136+
continue
137+
metadata, separator, path = record.partition("\t")
138+
fields = metadata.split(" ")
139+
if not separator or len(fields) != 3:
140+
raise CommandError(f"Unexpected git ls-tree record: {record!r}")
141+
mode, obj_type, sha = fields
142+
entries.append(GitTreeEntry(mode, obj_type, sha, path))
143+
return entries
144+
145+
102146
class GitCLI(SubprocessOperator):
103147
command_name = "git"
104148

@@ -126,6 +170,39 @@ def ls_tree(self, branch_name: str, file_path: str) -> Iterator[str]:
126170
def cat_file(self, branch_name: str, file_path: str) -> Iterator[str]:
127171
yield from self.iter_output(["cat-file", "-p", f"{branch_name}:{file_path}"])
128172

173+
def ls_tree_entries(self, ref: str, path_prefix: str) -> list[GitTreeEntry]:
174+
"""List the tree entries under a path in a Git ref.
175+
176+
:param ref: The ref whose tree to read, such as ``origin/main``
177+
:param path_prefix: The repository-relative path to list
178+
:return: The entries recorded in the tree, in Git's order
179+
"""
180+
if ref.startswith("-"):
181+
raise CommandError(f"Invalid ref: {ref}")
182+
183+
command = ["ls-tree", "-r", "-z", ref, "--", path_prefix]
184+
try:
185+
with self.run(command) as process:
186+
return _parse_tree_entries(process.stdout)
187+
except subprocess.CalledProcessError as e:
188+
raise CommandError(self._format_command_error(e.returncode, command)) from e
189+
190+
def read_blob(self, sha: str) -> bytes:
191+
"""Read the raw content of a blob object.
192+
193+
:param sha: The object name of the blob to read
194+
:return: The undecoded blob content, so binary files survive intact
195+
"""
196+
if sha.startswith("-"):
197+
raise CommandError(f"Invalid object name: {sha}")
198+
199+
command = ["cat-file", "blob", sha]
200+
try:
201+
with self.run(command, text=False) as process:
202+
return process.stdout
203+
except subprocess.CalledProcessError as e:
204+
raise CommandError(self._format_command_error(e.returncode, command)) from e
205+
129206
def fetch(self, remote: str = "origin", refspec: str | None = None):
130207
args = ["fetch", remote]
131208
if refspec is not None:

‎src/treefort/hooks.py‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,12 @@
99
from treefort import ui
1010
from treefort.context import Context
1111
from treefort.errors import HookError, HookExistsError
12+
from treefort.git import TREE_FILE_MODES, GitCLI
1213
from treefort.operator import ConfigOperator
1314
from treefort.subprocess import SubprocessOperator
15+
from treefort.utils import resolve_contained, write_bytes_atomically
16+
17+
GIT_HOOKS_DIR = ".treefort/hooks"
1418

1519

1620
class Hook(Enum):
@@ -138,3 +142,33 @@ def add(self, hook: Hook):
138142

139143
# allow exec
140144
hook_file.chmod(hook_file.stat().st_mode | stat.S_IEXEC)
145+
146+
def sync_from_git(self, git: GitCLI, ref: str, overwrite: bool = True) -> int:
147+
"""
148+
Synchronize the project hooks tracked in a Git ref into the configuration directory.
149+
:param git: The Git CLI used to read the tree entries and blobs
150+
:param ref: The Git ref to read the hooks from
151+
:param overwrite: Whether to replace hooks that already exist on disk
152+
:return: The number of hooks written
153+
"""
154+
hooks_dir = self.context.config_dir / self.dir_name
155+
synced = 0
156+
157+
for entry in git.ls_tree_entries(ref, GIT_HOOKS_DIR):
158+
if entry.obj_type != "blob" or entry.mode not in TREE_FILE_MODES:
159+
continue
160+
if not entry.path.startswith(f"{GIT_HOOKS_DIR}/"):
161+
continue
162+
163+
rel_path = entry.path.removeprefix(f"{GIT_HOOKS_DIR}/")
164+
dest = resolve_contained(hooks_dir, rel_path)
165+
if "/" in rel_path or rel_path not in Hook.__members__:
166+
continue
167+
if not overwrite and dest.exists():
168+
self.logger.warning(f"Hook {dest} already exists. Skipping.")
169+
continue
170+
171+
write_bytes_atomically(dest, git.read_blob(entry.sha), 0o755)
172+
synced += 1
173+
174+
return synced

‎src/treefort/main.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
from treefort.commands.remove import RemoveCommand
99
from treefort.commands.shell_init import ShellInitCommand
1010
from treefort.commands.switch import SwitchCommand
11+
from treefort.commands.sync import SyncCommand
1112
from treefort.runtime import Runtime
1213

1314

@@ -27,6 +28,7 @@ class WorktreeCommands(Command):
2728
PruneCommand,
2829
ShellInitCommand,
2930
SwitchCommand,
31+
SyncCommand,
3032
)
3133

3234
def __init__(self, verbose: bool = False):

‎src/treefort/subprocess.py‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -192,12 +192,13 @@ def stream_exec(
192192

193193
@contextmanager
194194
def run(
195-
self, command: list[str], cwd: str | Path | None = None
195+
self, command: list[str], cwd: str | Path | None = None, text: bool = True
196196
) -> Generator[CompletedProcess, Any, None]:
197197
"""
198198
Executes a command in a subprocess and returns the completed process
199199
:param command: The command to execute as a list of strings
200200
:param cwd: The working directory to execute the command in
201+
:param text: Whether to decode the output, which binary callers turn off
201202
"""
202203
logger = self._get_command_logger(command)
203204
# Only failure paths populate last_output for run() so successful queries do not
@@ -218,7 +219,7 @@ def run(
218219
process = subprocess.run(
219220
command,
220221
capture_output=True,
221-
text=True,
222+
text=text,
222223
check=True,
223224
timeout=self.wait_time,
224225
cwd=cwd or self.context.cwd,
@@ -230,6 +231,9 @@ def run(
230231
for stream_output in (e.stdout, e.stderr):
231232
if not stream_output:
232233
continue
234+
if isinstance(stream_output, bytes):
235+
# A binary caller still reports its failures as readable diagnostics
236+
stream_output = stream_output.decode("utf-8", errors="replace")
233237
for line in stream_output.splitlines():
234238
if stripped := self._record_output_line(line):
235239
logger.debug(

0 commit comments

Comments
 (0)