foresto 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.
- foresto/__init__.py +0 -0
- foresto/__main__.py +5 -0
- foresto/cli.py +68 -0
- foresto/config.py +133 -0
- foresto/core.py +928 -0
- foresto-1.0.0.dist-info/METADATA +180 -0
- foresto-1.0.0.dist-info/RECORD +10 -0
- foresto-1.0.0.dist-info/WHEEL +4 -0
- foresto-1.0.0.dist-info/entry_points.txt +2 -0
- foresto-1.0.0.dist-info/licenses/LICENSE +21 -0
foresto/__init__.py
ADDED
|
File without changes
|
foresto/__main__.py
ADDED
foresto/cli.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
from importlib.metadata import version
|
|
3
|
+
|
|
4
|
+
from .core import cmd_finish, cmd_list, cmd_start
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
8
|
+
"""Build and return the CLI argument parser for ``foresto``.
|
|
9
|
+
|
|
10
|
+
Defines three subcommands:
|
|
11
|
+
|
|
12
|
+
- ``start`` -- create an isolated working copy.
|
|
13
|
+
- ``finish`` -- remove a working copy and pull latest changes.
|
|
14
|
+
- ``list`` -- list active worktrees.
|
|
15
|
+
|
|
16
|
+
Returns:
|
|
17
|
+
The configured :class:`argparse.ArgumentParser` instance.
|
|
18
|
+
"""
|
|
19
|
+
parser = argparse.ArgumentParser(prog="foresto")
|
|
20
|
+
parser.add_argument(
|
|
21
|
+
"--version", action="version", version=f"%(prog)s {version('foresto')}"
|
|
22
|
+
)
|
|
23
|
+
sub = parser.add_subparsers(dest="command")
|
|
24
|
+
|
|
25
|
+
p_start = sub.add_parser("start", help="create an isolated working copy")
|
|
26
|
+
p_start.add_argument("base_path", help="path to the base project")
|
|
27
|
+
p_start.add_argument("name", help="kebab-case identifier (e.g. quick-silver-moon)")
|
|
28
|
+
|
|
29
|
+
p_finish = sub.add_parser("finish", help="remove a working copy")
|
|
30
|
+
p_finish.add_argument(
|
|
31
|
+
"name", help="kebab-case identifier of the worktree to remove"
|
|
32
|
+
)
|
|
33
|
+
p_finish.add_argument(
|
|
34
|
+
"--no-pull", action="store_true", help="skip automatic git pull"
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
sub.add_parser("list", help="list active worktrees")
|
|
38
|
+
|
|
39
|
+
return parser
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def main() -> int:
|
|
43
|
+
"""Entry point for the ``foresto`` CLI.
|
|
44
|
+
|
|
45
|
+
Parses command-line arguments and dispatches to the appropriate
|
|
46
|
+
:mod:`core` command function. Prints help text and returns ``1``
|
|
47
|
+
when no subcommand is provided.
|
|
48
|
+
|
|
49
|
+
Returns:
|
|
50
|
+
Exit code -- ``0`` on success, ``1`` when no subcommand is given.
|
|
51
|
+
"""
|
|
52
|
+
parser = build_parser()
|
|
53
|
+
args = parser.parse_args()
|
|
54
|
+
|
|
55
|
+
if args.command == "start":
|
|
56
|
+
result = cmd_start(args.base_path, args.name)
|
|
57
|
+
print(result)
|
|
58
|
+
return 0
|
|
59
|
+
elif args.command == "finish":
|
|
60
|
+
cmd_finish(args.name, no_pull=args.no_pull)
|
|
61
|
+
return 0
|
|
62
|
+
elif args.command == "list":
|
|
63
|
+
for name in cmd_list():
|
|
64
|
+
print(name)
|
|
65
|
+
return 0
|
|
66
|
+
else:
|
|
67
|
+
parser.print_help()
|
|
68
|
+
return 1
|
foresto/config.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import sys
|
|
2
|
+
import tomllib
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def _config_error(msg: str) -> None:
|
|
8
|
+
"""Report a configuration error and exit."""
|
|
9
|
+
print(f"error: .foresto.toml: {msg}", file=sys.stderr)
|
|
10
|
+
sys.exit(13)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass
|
|
14
|
+
class SharePatterns:
|
|
15
|
+
"""Validated list of share patterns for non-git-managed files.
|
|
16
|
+
|
|
17
|
+
Patterns are classified into two categories based on whether they
|
|
18
|
+
contain a path separator (``/``):
|
|
19
|
+
|
|
20
|
+
- **Basename patterns** (no ``/``): matched against directory and file
|
|
21
|
+
names at every depth (e.g. ``.env``, ``node_modules``).
|
|
22
|
+
- **Path patterns** (contains ``/``): matched as relative paths from
|
|
23
|
+
the project root (e.g. ``secrets/local.env``).
|
|
24
|
+
|
|
25
|
+
This follows the same semantics as ``.gitignore``: a pattern containing
|
|
26
|
+
a slash is anchored to the root, otherwise it matches anywhere.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
_basename_patterns: list[str] = field(default_factory=list)
|
|
30
|
+
_path_patterns: list[str] = field(default_factory=list)
|
|
31
|
+
|
|
32
|
+
def __init__(self, raw_patterns: list[str] | None = None) -> None:
|
|
33
|
+
basename: list[str] = []
|
|
34
|
+
path: list[str] = []
|
|
35
|
+
seen: set[str] = set()
|
|
36
|
+
|
|
37
|
+
for p in raw_patterns or []:
|
|
38
|
+
if not p:
|
|
39
|
+
_config_error("share pattern must not be empty")
|
|
40
|
+
if p.startswith("!"):
|
|
41
|
+
_config_error(f"share pattern must not start with '!': {p!r}")
|
|
42
|
+
|
|
43
|
+
normalized = p.replace("\\", "/").rstrip("/")
|
|
44
|
+
|
|
45
|
+
if not normalized:
|
|
46
|
+
_config_error("share pattern must not be empty")
|
|
47
|
+
|
|
48
|
+
if ".." in normalized.split("/"):
|
|
49
|
+
_config_error(f"share pattern must not contain '..': {p!r}")
|
|
50
|
+
|
|
51
|
+
if normalized in seen:
|
|
52
|
+
continue
|
|
53
|
+
seen.add(normalized)
|
|
54
|
+
|
|
55
|
+
if "/" in normalized:
|
|
56
|
+
path.append(normalized)
|
|
57
|
+
else:
|
|
58
|
+
basename.append(normalized)
|
|
59
|
+
|
|
60
|
+
self._basename_patterns = basename
|
|
61
|
+
self._path_patterns = path
|
|
62
|
+
|
|
63
|
+
@property
|
|
64
|
+
def basename_patterns(self) -> list[str]:
|
|
65
|
+
"""Basename-only patterns matched at any directory level."""
|
|
66
|
+
return list(self._basename_patterns)
|
|
67
|
+
|
|
68
|
+
@property
|
|
69
|
+
def path_patterns(self) -> list[str]:
|
|
70
|
+
"""Path patterns matched relative to the project root."""
|
|
71
|
+
return list(self._path_patterns)
|
|
72
|
+
|
|
73
|
+
@property
|
|
74
|
+
def patterns(self) -> list[str]:
|
|
75
|
+
"""All patterns combined (basename + path)."""
|
|
76
|
+
return self._basename_patterns + self._path_patterns
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@dataclass
|
|
80
|
+
class StepConfig:
|
|
81
|
+
"""Configuration for a single workflow step (``start`` or ``finish``).
|
|
82
|
+
|
|
83
|
+
Attributes:
|
|
84
|
+
commands: Shell commands to execute during the step.
|
|
85
|
+
share: Patterns for non-git-managed files to copy into the worktree.
|
|
86
|
+
"""
|
|
87
|
+
|
|
88
|
+
commands: list[str] = field(default_factory=list)
|
|
89
|
+
share: SharePatterns = field(default_factory=SharePatterns)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
@dataclass
|
|
93
|
+
class Config:
|
|
94
|
+
"""Top-level configuration loaded from ``.foresto.toml``.
|
|
95
|
+
|
|
96
|
+
Attributes:
|
|
97
|
+
start: Configuration applied when creating a new worktree.
|
|
98
|
+
finish: Configuration applied when removing a worktree.
|
|
99
|
+
"""
|
|
100
|
+
|
|
101
|
+
start: StepConfig = field(default_factory=StepConfig)
|
|
102
|
+
finish: StepConfig = field(default_factory=StepConfig)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def load_config(base_path: Path) -> Config:
|
|
106
|
+
"""Load project configuration from ``.foresto.toml``.
|
|
107
|
+
|
|
108
|
+
Reads the TOML file at ``base_path / .foresto.toml`` and returns a
|
|
109
|
+
validated :class:`Config` object. If the file does not exist, returns
|
|
110
|
+
a default (empty) configuration.
|
|
111
|
+
|
|
112
|
+
Args:
|
|
113
|
+
base_path: Project root directory.
|
|
114
|
+
|
|
115
|
+
Returns:
|
|
116
|
+
Parsed configuration, or defaults when the file is absent.
|
|
117
|
+
"""
|
|
118
|
+
config_path = base_path / ".foresto.toml"
|
|
119
|
+
if not config_path.is_file():
|
|
120
|
+
return Config()
|
|
121
|
+
with open(config_path, "rb") as f:
|
|
122
|
+
data = tomllib.load(f)
|
|
123
|
+
start_section = data.get("start", {})
|
|
124
|
+
finish_section = data.get("finish", {})
|
|
125
|
+
return Config(
|
|
126
|
+
start=StepConfig(
|
|
127
|
+
commands=start_section.get("commands", []),
|
|
128
|
+
share=SharePatterns(start_section.get("share", [])),
|
|
129
|
+
),
|
|
130
|
+
finish=StepConfig(
|
|
131
|
+
commands=finish_section.get("commands", []),
|
|
132
|
+
),
|
|
133
|
+
)
|
foresto/core.py
ADDED
|
@@ -0,0 +1,928 @@
|
|
|
1
|
+
"""Core business logic for the foresto CLI tool.
|
|
2
|
+
|
|
3
|
+
Provides functions to create, list, and remove git-worktree-backed working
|
|
4
|
+
copies used for parallel AI-assisted development. Each worktree is created
|
|
5
|
+
via ``git worktree add`` and may include non-git-managed files (e.g.
|
|
6
|
+
``.env``, ``node_modules``) shared from the main project via the
|
|
7
|
+
``[start].share`` configuration in ``.foresto.toml``.
|
|
8
|
+
|
|
9
|
+
Public API:
|
|
10
|
+
- :func:`cmd_start` -- create a new worktree and share files.
|
|
11
|
+
- :func:`cmd_finish` -- remove a worktree and pull latest changes.
|
|
12
|
+
- :func:`cmd_list` -- list existing worktree names.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
import fnmatch
|
|
16
|
+
import json
|
|
17
|
+
import os
|
|
18
|
+
import platform
|
|
19
|
+
import re
|
|
20
|
+
import shutil
|
|
21
|
+
import stat
|
|
22
|
+
import subprocess
|
|
23
|
+
import sys
|
|
24
|
+
import time
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
|
|
27
|
+
# Optional dependency used to detect processes locking a worktree on Windows.
|
|
28
|
+
# Imported defensively so the CLI still works (without lock detection) if the
|
|
29
|
+
# package is unavailable -- core commands must not hard-fail on import.
|
|
30
|
+
try:
|
|
31
|
+
import psutil
|
|
32
|
+
except ImportError: # pragma: no cover - exercised only when psutil is absent
|
|
33
|
+
psutil = None # type: ignore[assignment]
|
|
34
|
+
|
|
35
|
+
from .config import SharePatterns, load_config
|
|
36
|
+
|
|
37
|
+
# Pattern matching kebab-case identifiers: lowercase alphanumeric segments
|
|
38
|
+
# joined by hyphens (e.g. "quick-silver-moon").
|
|
39
|
+
KEBAB_RE = re.compile(r"^[a-z0-9]+(-[a-z0-9]+)*$")
|
|
40
|
+
|
|
41
|
+
# Directories to skip when scanning for share candidates.
|
|
42
|
+
_SKIP_DIRS = frozenset({".worktrees", ".git"})
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _error(msg: str, code: int) -> None:
|
|
46
|
+
"""Print an error message to stderr and terminate the process.
|
|
47
|
+
|
|
48
|
+
Args:
|
|
49
|
+
msg: Human-readable error description.
|
|
50
|
+
code: Exit status code returned to the shell.
|
|
51
|
+
"""
|
|
52
|
+
print(f"error: {msg}", file=sys.stderr)
|
|
53
|
+
sys.exit(code)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _resolve_base_path(base_path_str: str) -> Path:
|
|
57
|
+
"""Resolve and validate a base directory path.
|
|
58
|
+
|
|
59
|
+
Expands ``~`` and makes the path absolute, then verifies the
|
|
60
|
+
directory actually exists on disk.
|
|
61
|
+
|
|
62
|
+
Args:
|
|
63
|
+
base_path_str: Raw path string (may include ``~`` or relative
|
|
64
|
+
segments).
|
|
65
|
+
|
|
66
|
+
Returns:
|
|
67
|
+
The fully resolved ``Path`` object.
|
|
68
|
+
|
|
69
|
+
Raises:
|
|
70
|
+
SystemExit: If the resolved path is not an existing directory.
|
|
71
|
+
"""
|
|
72
|
+
p = Path(base_path_str).expanduser().resolve()
|
|
73
|
+
if not p.is_dir():
|
|
74
|
+
_error(f"path does not exist: {base_path_str}", 1)
|
|
75
|
+
return p
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _validate_name(name: str) -> None:
|
|
79
|
+
"""Ensure *name* follows kebab-case conventions.
|
|
80
|
+
|
|
81
|
+
Valid names contain only lowercase ASCII letters, digits, and hyphens,
|
|
82
|
+
and must not start or end with a hyphen.
|
|
83
|
+
|
|
84
|
+
Args:
|
|
85
|
+
name: The worktree name to validate.
|
|
86
|
+
|
|
87
|
+
Raises:
|
|
88
|
+
SystemExit: If *name* does not match the kebab-case pattern.
|
|
89
|
+
"""
|
|
90
|
+
if not KEBAB_RE.match(name):
|
|
91
|
+
_error(f"name must be kebab-case (a-z, 0-9, hyphens): {name}", 2)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _ensure_gitignore_entry(base_path: Path) -> None:
|
|
95
|
+
"""Ensure ``.worktrees/`` is listed in the project's ``.gitignore``.
|
|
96
|
+
|
|
97
|
+
Appends ``.worktrees/`` to ``.gitignore`` if it doesn't already contain
|
|
98
|
+
an entry for it. Creates ``.gitignore`` if it doesn't exist.
|
|
99
|
+
|
|
100
|
+
Args:
|
|
101
|
+
base_path: Project root directory.
|
|
102
|
+
"""
|
|
103
|
+
gitignore = base_path / ".gitignore"
|
|
104
|
+
entry = ".worktrees/"
|
|
105
|
+
|
|
106
|
+
if gitignore.is_file():
|
|
107
|
+
# Why: .gitignoreは非ASCII UTF-8(コメント内のem-dash等)を含むことがあるが、Windowsでは
|
|
108
|
+
# 暗黙codecがロケール既定(日本語環境はcp932)になり、デコードがUnicodeDecodeErrorを
|
|
109
|
+
# 投げて`foresto start`がクラッシュした(issue #27)
|
|
110
|
+
content = gitignore.read_text(encoding="utf-8")
|
|
111
|
+
for line in content.splitlines():
|
|
112
|
+
if line.strip() in (".worktrees", ".worktrees/"):
|
|
113
|
+
return
|
|
114
|
+
if not content.endswith("\n"):
|
|
115
|
+
content += "\n"
|
|
116
|
+
content += entry + "\n"
|
|
117
|
+
# Why: 書き込みもUTF-8固定。ロケール既定のままだとcp932へ暗黙再エンコードされ、
|
|
118
|
+
# gitがUTF-8として扱うバイト列が壊れる(issue #27)
|
|
119
|
+
gitignore.write_text(content, encoding="utf-8")
|
|
120
|
+
else:
|
|
121
|
+
gitignore.write_text(entry + "\n", encoding="utf-8")
|
|
122
|
+
|
|
123
|
+
print(f"added '{entry}' to .gitignore", file=sys.stderr)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _git_worktree_add(base_path: Path, worktree_path: Path, name: str) -> None:
|
|
127
|
+
"""Create a new git worktree with a new branch via ``git worktree add``.
|
|
128
|
+
|
|
129
|
+
Atomically creates the worktree directory, a new branch from HEAD,
|
|
130
|
+
checks out all git-tracked files, and registers the worktree.
|
|
131
|
+
|
|
132
|
+
Args:
|
|
133
|
+
base_path: The main project root directory.
|
|
134
|
+
worktree_path: Target directory for the new worktree.
|
|
135
|
+
name: Branch name and worktree identifier.
|
|
136
|
+
|
|
137
|
+
Raises:
|
|
138
|
+
SystemExit: If ``git worktree add`` fails (exit code 4).
|
|
139
|
+
"""
|
|
140
|
+
result = subprocess.run(
|
|
141
|
+
["git", "worktree", "add", "-b", name, str(worktree_path), "HEAD"],
|
|
142
|
+
capture_output=True,
|
|
143
|
+
text=True,
|
|
144
|
+
cwd=base_path,
|
|
145
|
+
check=False,
|
|
146
|
+
)
|
|
147
|
+
if result.returncode != 0:
|
|
148
|
+
_error(f"git worktree add failed: {result.stderr.strip()}", 4)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _handle_rmtree_error(func, path, exc_info):
|
|
152
|
+
"""Handle removal errors from shutil.rmtree by retrying with elevated permissions.
|
|
153
|
+
|
|
154
|
+
When a ``PermissionError`` occurs (e.g. read-only files), the handler
|
|
155
|
+
adds write permission to the target and retries the failed operation.
|
|
156
|
+
All other exceptions are re-raised unchanged.
|
|
157
|
+
|
|
158
|
+
Args:
|
|
159
|
+
func: The callable that failed (e.g. ``os.remove`` or ``os.rmdir``).
|
|
160
|
+
path: Path to the file or directory that caused the error.
|
|
161
|
+
exc_info: Triple of ``(type, value, traceback)`` from ``sys.exc_info()``.
|
|
162
|
+
"""
|
|
163
|
+
if isinstance(exc_info[1], PermissionError):
|
|
164
|
+
os.chmod(path, stat.S_IWUSR | stat.S_IRUSR)
|
|
165
|
+
func(path)
|
|
166
|
+
else:
|
|
167
|
+
raise exc_info[1]
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _find_processes_locking_path(path: Path) -> list:
|
|
171
|
+
"""Find processes whose current working directory is under *path*.
|
|
172
|
+
|
|
173
|
+
Used on Windows to detect processes (e.g. a terminal shell opened to the
|
|
174
|
+
worktree) that hold an OS-level lock preventing directory removal. Only
|
|
175
|
+
the *current working directory* is checked -- intentionally NOT open file
|
|
176
|
+
handles, so that editors (e.g. Code.exe) merely having files open under the
|
|
177
|
+
worktree are not offered for termination.
|
|
178
|
+
|
|
179
|
+
Returns an empty list when psutil is unavailable or *path* does not exist.
|
|
180
|
+
|
|
181
|
+
Args:
|
|
182
|
+
path: The directory path to check for locks.
|
|
183
|
+
|
|
184
|
+
Returns:
|
|
185
|
+
A list of psutil.Process objects whose cwd is *path* or beneath it.
|
|
186
|
+
"""
|
|
187
|
+
if psutil is None or not path.exists():
|
|
188
|
+
return []
|
|
189
|
+
|
|
190
|
+
# Normalize without a trailing separator, then require an exact match or a
|
|
191
|
+
# separator boundary so ".worktrees/test-wt" does NOT match a sibling
|
|
192
|
+
# worktree such as ".worktrees/test-wt-other".
|
|
193
|
+
target = str(path).rstrip("\\/").lower()
|
|
194
|
+
|
|
195
|
+
locking_processes: list = []
|
|
196
|
+
for proc in psutil.process_iter(["pid", "name"]):
|
|
197
|
+
try:
|
|
198
|
+
cwd = proc.cwd()
|
|
199
|
+
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
|
|
200
|
+
continue
|
|
201
|
+
if not cwd:
|
|
202
|
+
continue
|
|
203
|
+
norm = str(cwd).rstrip("\\/").lower()
|
|
204
|
+
if norm == target or norm.startswith((target + "\\", target + "/")):
|
|
205
|
+
locking_processes.append(proc)
|
|
206
|
+
|
|
207
|
+
return locking_processes
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _terminate_processes_with_confirmation(processes: list) -> bool:
|
|
211
|
+
"""Terminate processes after user confirmation.
|
|
212
|
+
|
|
213
|
+
Lists the processes locking the worktree, asks for confirmation, then
|
|
214
|
+
terminates them via ``taskkill /F /T`` on Windows (psutil.terminate on
|
|
215
|
+
others). A process that already exited between detection and termination
|
|
216
|
+
is treated as success -- the lock is gone either way.
|
|
217
|
+
|
|
218
|
+
Args:
|
|
219
|
+
processes: List of psutil.Process objects to terminate.
|
|
220
|
+
|
|
221
|
+
Returns:
|
|
222
|
+
``True`` if the user confirmed and termination was attempted, ``False``
|
|
223
|
+
if the user declined or termination of a still-running process failed.
|
|
224
|
+
"""
|
|
225
|
+
if not processes:
|
|
226
|
+
return True
|
|
227
|
+
|
|
228
|
+
print(
|
|
229
|
+
f"\nFound {len(processes)} process(es) locking the worktree:", file=sys.stderr
|
|
230
|
+
)
|
|
231
|
+
for proc in processes:
|
|
232
|
+
try:
|
|
233
|
+
pid = proc.pid
|
|
234
|
+
name = proc.name()
|
|
235
|
+
cwd = proc.cwd()
|
|
236
|
+
except (psutil.NoSuchProcess, psutil.AccessDenied):
|
|
237
|
+
print(
|
|
238
|
+
f" - PID {proc.pid}: (access denied or already exited)",
|
|
239
|
+
file=sys.stderr,
|
|
240
|
+
)
|
|
241
|
+
continue
|
|
242
|
+
print(f" - PID {pid} ({name})", file=sys.stderr)
|
|
243
|
+
print(f" cwd: {cwd}", file=sys.stderr)
|
|
244
|
+
|
|
245
|
+
print(
|
|
246
|
+
"\nThe worktree directory cannot be removed while these processes are running.",
|
|
247
|
+
file=sys.stderr,
|
|
248
|
+
)
|
|
249
|
+
|
|
250
|
+
try:
|
|
251
|
+
response = (
|
|
252
|
+
input("Terminate these processes to continue? (y/N): ").strip().lower()
|
|
253
|
+
)
|
|
254
|
+
except (EOFError, KeyboardInterrupt):
|
|
255
|
+
print(file=sys.stderr)
|
|
256
|
+
return False
|
|
257
|
+
if response != "y":
|
|
258
|
+
print("Aborted by user.", file=sys.stderr)
|
|
259
|
+
return False
|
|
260
|
+
|
|
261
|
+
any_failure = False
|
|
262
|
+
for proc in processes:
|
|
263
|
+
try:
|
|
264
|
+
pid = proc.pid
|
|
265
|
+
except (psutil.NoSuchProcess, psutil.AccessDenied):
|
|
266
|
+
# Process gone before we could terminate it -- lock released.
|
|
267
|
+
continue
|
|
268
|
+
|
|
269
|
+
if platform.system() == "Windows":
|
|
270
|
+
# /T kills the process tree (child shells, conhost, etc.).
|
|
271
|
+
result = subprocess.run(
|
|
272
|
+
["taskkill", "/F", "/T", "/PID", str(pid)],
|
|
273
|
+
capture_output=True,
|
|
274
|
+
text=True,
|
|
275
|
+
check=False,
|
|
276
|
+
)
|
|
277
|
+
# taskkill returns 128 when the process no longer exists; treat
|
|
278
|
+
# that as success since the lock is already released.
|
|
279
|
+
if result.returncode in (0, 128):
|
|
280
|
+
print(f" Terminated PID {pid}", file=sys.stderr)
|
|
281
|
+
else:
|
|
282
|
+
print(
|
|
283
|
+
f" Failed to terminate PID {pid}: {result.stderr.strip()}",
|
|
284
|
+
file=sys.stderr,
|
|
285
|
+
)
|
|
286
|
+
any_failure = True
|
|
287
|
+
else:
|
|
288
|
+
try:
|
|
289
|
+
proc.terminate()
|
|
290
|
+
proc.wait(timeout=5)
|
|
291
|
+
print(f" Terminated PID {pid}", file=sys.stderr)
|
|
292
|
+
except psutil.NoSuchProcess:
|
|
293
|
+
pass # already gone -- success
|
|
294
|
+
except psutil.TimeoutExpired:
|
|
295
|
+
proc.kill()
|
|
296
|
+
print(f" Killed PID {pid}", file=sys.stderr)
|
|
297
|
+
except psutil.AccessDenied as e:
|
|
298
|
+
print(f" Failed to terminate PID {pid}: {e}", file=sys.stderr)
|
|
299
|
+
any_failure = True
|
|
300
|
+
|
|
301
|
+
if any_failure:
|
|
302
|
+
return False
|
|
303
|
+
|
|
304
|
+
# Give the OS a moment to release directory handles after termination so
|
|
305
|
+
# the immediate rmtree retry does not hit a stale WinError 32.
|
|
306
|
+
time.sleep(1)
|
|
307
|
+
return True
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def _force_remove_worktree(worktree_path: Path, base_path: Path) -> bool:
|
|
311
|
+
"""Force-remove a worktree directory and clean up git metadata.
|
|
312
|
+
|
|
313
|
+
Falls back to shutil.rmtree when ``git worktree remove --force`` fails.
|
|
314
|
+
Handles permission errors via chmod retry. On Windows, attempts to
|
|
315
|
+
identify and terminate processes locking the directory. After physical
|
|
316
|
+
removal, runs ``git worktree prune`` to clean stale metadata.
|
|
317
|
+
|
|
318
|
+
Args:
|
|
319
|
+
worktree_path: The worktree directory to remove.
|
|
320
|
+
base_path: The main project root directory.
|
|
321
|
+
|
|
322
|
+
Returns:
|
|
323
|
+
``True`` if removal succeeded, ``False`` otherwise.
|
|
324
|
+
"""
|
|
325
|
+
print(
|
|
326
|
+
f"git worktree remove failed, force-removing {worktree_path}...",
|
|
327
|
+
file=sys.stderr,
|
|
328
|
+
)
|
|
329
|
+
|
|
330
|
+
# Try to find and terminate processes locking the path
|
|
331
|
+
locking_processes = _find_processes_locking_path(worktree_path)
|
|
332
|
+
if locking_processes:
|
|
333
|
+
terminated = _terminate_processes_with_confirmation(locking_processes)
|
|
334
|
+
if not terminated:
|
|
335
|
+
print(
|
|
336
|
+
"Failed to terminate locking processes. "
|
|
337
|
+
"Worktree directory will not be removed.",
|
|
338
|
+
file=sys.stderr,
|
|
339
|
+
)
|
|
340
|
+
return False
|
|
341
|
+
|
|
342
|
+
# Attempt removal with a short retry loop to tolerate transient locks:
|
|
343
|
+
# handles may be released a moment after a process is killed, and AV /
|
|
344
|
+
# indexer / Explorer can briefly hold the path.
|
|
345
|
+
for attempt in range(3):
|
|
346
|
+
try:
|
|
347
|
+
shutil.rmtree(worktree_path, onerror=_handle_rmtree_error)
|
|
348
|
+
break
|
|
349
|
+
except OSError as e:
|
|
350
|
+
if attempt < 2:
|
|
351
|
+
time.sleep(0.5)
|
|
352
|
+
continue
|
|
353
|
+
print(
|
|
354
|
+
f"failed to force-remove worktree directory: {e}",
|
|
355
|
+
file=sys.stderr,
|
|
356
|
+
)
|
|
357
|
+
return False
|
|
358
|
+
|
|
359
|
+
# Clean up git metadata
|
|
360
|
+
subprocess.run(
|
|
361
|
+
["git", "worktree", "prune"],
|
|
362
|
+
capture_output=True,
|
|
363
|
+
text=True,
|
|
364
|
+
cwd=base_path,
|
|
365
|
+
check=False,
|
|
366
|
+
)
|
|
367
|
+
|
|
368
|
+
return True
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
def _git_worktree_remove(base_path: Path, worktree_path: Path) -> bool:
|
|
372
|
+
"""Remove a git worktree via ``git worktree remove``.
|
|
373
|
+
|
|
374
|
+
Tries without ``--force`` first, then retries with ``--force`` to
|
|
375
|
+
handle untracked files (e.g. files added via ``share``). If both
|
|
376
|
+
fail, falls back to :func:`_force_remove_worktree` (shutil.rmtree
|
|
377
|
+
+ git worktree prune).
|
|
378
|
+
|
|
379
|
+
Args:
|
|
380
|
+
base_path: The main project root directory.
|
|
381
|
+
worktree_path: The worktree directory to remove.
|
|
382
|
+
|
|
383
|
+
Returns:
|
|
384
|
+
``True`` if removal succeeded, ``False`` otherwise.
|
|
385
|
+
"""
|
|
386
|
+
for force in (False, True):
|
|
387
|
+
args = ["git", "worktree", "remove"]
|
|
388
|
+
if force:
|
|
389
|
+
args.append("--force")
|
|
390
|
+
args.append(str(worktree_path))
|
|
391
|
+
result = subprocess.run(
|
|
392
|
+
args, capture_output=True, text=True, cwd=base_path, check=False
|
|
393
|
+
)
|
|
394
|
+
if result.returncode == 0:
|
|
395
|
+
return True
|
|
396
|
+
if force:
|
|
397
|
+
print(
|
|
398
|
+
f"warning: git worktree remove --force failed: {result.stderr.strip()}",
|
|
399
|
+
file=sys.stderr,
|
|
400
|
+
)
|
|
401
|
+
|
|
402
|
+
return _force_remove_worktree(worktree_path, base_path)
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
def _collect_share_sources(base_path: Path, share: SharePatterns) -> list[Path]:
|
|
406
|
+
"""Collect paths matching share patterns from the base project.
|
|
407
|
+
|
|
408
|
+
Scans the base project directory for files and directories that match
|
|
409
|
+
the configured share patterns:
|
|
410
|
+
|
|
411
|
+
- **Path patterns** (containing ``/``): resolved as relative paths
|
|
412
|
+
from the project root.
|
|
413
|
+
- **Basename patterns** (no ``/``): matched against names at every
|
|
414
|
+
directory depth using :mod:`fnmatch`.
|
|
415
|
+
|
|
416
|
+
Directories named ``.worktrees`` and ``.git`` are always skipped
|
|
417
|
+
during the scan. When a directory matches a basename pattern, it is
|
|
418
|
+
not descended into further (its entire contents are included).
|
|
419
|
+
|
|
420
|
+
Args:
|
|
421
|
+
base_path: The main project root directory.
|
|
422
|
+
share: Validated share patterns.
|
|
423
|
+
|
|
424
|
+
Returns:
|
|
425
|
+
A list of absolute ``Path`` objects to copy into the worktree.
|
|
426
|
+
"""
|
|
427
|
+
sources: list[Path] = []
|
|
428
|
+
|
|
429
|
+
# Path patterns: direct lookup from project root
|
|
430
|
+
for pattern in share.path_patterns:
|
|
431
|
+
target = base_path / pattern
|
|
432
|
+
if target.exists():
|
|
433
|
+
sources.append(target)
|
|
434
|
+
else:
|
|
435
|
+
print(
|
|
436
|
+
f" warning: share path not found, skipping: {pattern}",
|
|
437
|
+
file=sys.stderr,
|
|
438
|
+
)
|
|
439
|
+
|
|
440
|
+
# Basename patterns: walk the directory tree
|
|
441
|
+
if share.basename_patterns:
|
|
442
|
+
for root, dirs, files in os.walk(base_path):
|
|
443
|
+
# Skip .worktrees and .git
|
|
444
|
+
dirs[:] = [d for d in dirs if d not in _SKIP_DIRS]
|
|
445
|
+
|
|
446
|
+
matched_dirs: set[str] = set()
|
|
447
|
+
for pattern in share.basename_patterns:
|
|
448
|
+
matches = fnmatch.filter(list(dirs) + files, pattern)
|
|
449
|
+
for m in matches:
|
|
450
|
+
sources.append(Path(root) / m)
|
|
451
|
+
if m in dirs:
|
|
452
|
+
matched_dirs.add(m)
|
|
453
|
+
|
|
454
|
+
# Don't descend into already-matched directories
|
|
455
|
+
dirs[:] = [d for d in dirs if d not in matched_dirs]
|
|
456
|
+
|
|
457
|
+
return sources
|
|
458
|
+
|
|
459
|
+
|
|
460
|
+
def _copy_content(src: Path, dst: Path) -> bool:
|
|
461
|
+
"""Copy the *content* of *src* to *dst*, following any symbolic links.
|
|
462
|
+
|
|
463
|
+
Shared fallback for :func:`_copy_symlink` and :func:`_copy_dir` when a
|
|
464
|
+
link-preserving copy is not permitted by the platform. Failures are
|
|
465
|
+
reported as warnings and do not terminate the share.
|
|
466
|
+
|
|
467
|
+
Args:
|
|
468
|
+
src: Source file or directory (may be a symbolic link).
|
|
469
|
+
dst: Destination path.
|
|
470
|
+
|
|
471
|
+
Returns:
|
|
472
|
+
``True`` on success, ``False`` on failure.
|
|
473
|
+
"""
|
|
474
|
+
try:
|
|
475
|
+
if src.is_dir():
|
|
476
|
+
shutil.copytree(src, dst, dirs_exist_ok=True)
|
|
477
|
+
else:
|
|
478
|
+
shutil.copy2(src, dst)
|
|
479
|
+
return True
|
|
480
|
+
except OSError as e:
|
|
481
|
+
print(
|
|
482
|
+
f" warning: share copy failed for '{dst.name}': {e}",
|
|
483
|
+
file=sys.stderr,
|
|
484
|
+
)
|
|
485
|
+
return False
|
|
486
|
+
|
|
487
|
+
|
|
488
|
+
def _copy_symlink(src: Path, dst: Path) -> bool:
|
|
489
|
+
"""Copy *src* (a symbolic link) to *dst* as a symbolic link.
|
|
490
|
+
|
|
491
|
+
Preserves the link target verbatim, so relative links keep working as
|
|
492
|
+
long as the resolved path still exists from *dst*. On platforms that
|
|
493
|
+
forbid creating symlinks without elevated privileges (notably Windows
|
|
494
|
+
without Developer Mode / admin rights), falls back to copying the link
|
|
495
|
+
target's content and emits a warning, so the share still succeeds.
|
|
496
|
+
|
|
497
|
+
Args:
|
|
498
|
+
src: An existing symbolic link.
|
|
499
|
+
dst: Destination path for the new symbolic link.
|
|
500
|
+
|
|
501
|
+
Returns:
|
|
502
|
+
``True`` if the link (or fallback content copy) was created,
|
|
503
|
+
``False`` if even the fallback failed.
|
|
504
|
+
"""
|
|
505
|
+
try:
|
|
506
|
+
link_target = os.readlink(src)
|
|
507
|
+
# Caution: dst の種別で削除方法を切り分け。実ディレクトリは unlink 不可のため rmtree するが、
|
|
508
|
+
# シンボリックリンクに rmtree を使うとリンク先の実体が破壊される恐れがあるため
|
|
509
|
+
# not dst.is_symlink() で実ディレクトリのみに限定している(issue #9)。
|
|
510
|
+
if dst.is_dir() and not dst.is_symlink():
|
|
511
|
+
shutil.rmtree(dst)
|
|
512
|
+
elif dst.is_symlink() or dst.exists():
|
|
513
|
+
dst.unlink()
|
|
514
|
+
# Constraint: Windows の os.symlink は対象がディレクトリかを示す引数が必須。誤指定すると
|
|
515
|
+
# OS エラーになるため src.is_dir() で判定。非 Windows では無視される(issue #9、Python os.symlink 仕様)。
|
|
516
|
+
os.symlink(link_target, dst, target_is_directory=src.is_dir())
|
|
517
|
+
return True
|
|
518
|
+
except OSError as e:
|
|
519
|
+
print(
|
|
520
|
+
f" warning: could not create symlink for '{dst.name}' "
|
|
521
|
+
f"(copying content instead): {e}",
|
|
522
|
+
file=sys.stderr,
|
|
523
|
+
)
|
|
524
|
+
# Note: Windows でシンボリックリンク作成権限がない場合の実体コピーへのフォールバック(issue #9)。
|
|
525
|
+
return _copy_content(src, dst)
|
|
526
|
+
|
|
527
|
+
|
|
528
|
+
def _copy_dir(src: Path, dst: Path) -> bool:
|
|
529
|
+
"""Copy directory *src* to *dst*, preserving inner symbolic links.
|
|
530
|
+
|
|
531
|
+
Uses :func:`shutil.copytree` with ``symlinks=True`` so that symbolic
|
|
532
|
+
links nested inside the tree are reproduced as links. On platforms
|
|
533
|
+
that forbid symlink creation, retries with ``symlinks=False`` (content
|
|
534
|
+
copy) and emits a warning.
|
|
535
|
+
|
|
536
|
+
Args:
|
|
537
|
+
src: An existing directory (not a symlink itself).
|
|
538
|
+
dst: Destination directory path.
|
|
539
|
+
|
|
540
|
+
Returns:
|
|
541
|
+
``True`` if the copy (preserving or fallback) succeeded,
|
|
542
|
+
``False`` otherwise.
|
|
543
|
+
"""
|
|
544
|
+
try:
|
|
545
|
+
shutil.copytree(src, dst, dirs_exist_ok=True, symlinks=True)
|
|
546
|
+
return True
|
|
547
|
+
except OSError as e:
|
|
548
|
+
print(
|
|
549
|
+
f" warning: could not preserve symlinks in '{src.name}' "
|
|
550
|
+
f"(copying content instead): {e}",
|
|
551
|
+
file=sys.stderr,
|
|
552
|
+
)
|
|
553
|
+
return _copy_content(src, dst)
|
|
554
|
+
|
|
555
|
+
|
|
556
|
+
def _share_files(base_path: Path, worktree_path: Path, share: SharePatterns) -> None:
|
|
557
|
+
"""Copy non-git-managed files matching share patterns into the worktree.
|
|
558
|
+
|
|
559
|
+
Symbolic links in the share sources are preserved as links -- both when
|
|
560
|
+
a source *is* a symlink and when a directory contains nested symlinks
|
|
561
|
+
-- keeping structures such as pnpm-style ``node_modules`` intact across
|
|
562
|
+
platforms. On platforms that forbid symlink creation, the affected
|
|
563
|
+
entry falls back to a content copy with a warning. Share copy failures
|
|
564
|
+
are otherwise treated as warnings and do not terminate the process.
|
|
565
|
+
|
|
566
|
+
Args:
|
|
567
|
+
base_path: The main project root directory.
|
|
568
|
+
worktree_path: The worktree directory to copy into.
|
|
569
|
+
share: Validated share patterns.
|
|
570
|
+
"""
|
|
571
|
+
sources = _collect_share_sources(base_path, share)
|
|
572
|
+
if not sources:
|
|
573
|
+
return
|
|
574
|
+
|
|
575
|
+
for src in sources:
|
|
576
|
+
rel = src.relative_to(base_path)
|
|
577
|
+
dst = worktree_path / rel
|
|
578
|
+
dst.parent.mkdir(parents=True, exist_ok=True)
|
|
579
|
+
|
|
580
|
+
# Why: is_symlink() を is_dir() より先に判定している。Path.is_dir() はリンクを辿るため、
|
|
581
|
+
# ディレクトリへのリンクも True になり、先に弾かないと _copy_dir 経由でリンクが実体化し
|
|
582
|
+
# issue #9 の「リンクとして保持」要件を満たせなくなる。
|
|
583
|
+
if src.is_symlink():
|
|
584
|
+
ok = _copy_symlink(src, dst)
|
|
585
|
+
elif src.is_dir():
|
|
586
|
+
ok = _copy_dir(src, dst)
|
|
587
|
+
else:
|
|
588
|
+
ok = _copy_content(src, dst)
|
|
589
|
+
|
|
590
|
+
if ok:
|
|
591
|
+
print(f" shared: {rel}", file=sys.stderr)
|
|
592
|
+
|
|
593
|
+
|
|
594
|
+
def _has_unpushed_commits(worktree_path: Path) -> bool:
|
|
595
|
+
"""Check whether the worktree has commits not pushed to any remote.
|
|
596
|
+
|
|
597
|
+
A branch whose pull request was squash-merged counts as pushed: the
|
|
598
|
+
merge creates a different commit on the base branch and the PR branch
|
|
599
|
+
is typically auto-deleted, so no remote branch ever contains HEAD.
|
|
600
|
+
|
|
601
|
+
Args:
|
|
602
|
+
worktree_path: The worktree directory to check.
|
|
603
|
+
|
|
604
|
+
Returns:
|
|
605
|
+
``True`` if there are unpushed commits, ``False`` otherwise.
|
|
606
|
+
"""
|
|
607
|
+
upstream = subprocess.run(
|
|
608
|
+
["git", "rev-parse", "--abbrev-ref", "@{u}"],
|
|
609
|
+
capture_output=True,
|
|
610
|
+
text=True,
|
|
611
|
+
cwd=worktree_path,
|
|
612
|
+
check=False,
|
|
613
|
+
)
|
|
614
|
+
if upstream.returncode == 0:
|
|
615
|
+
count = subprocess.run(
|
|
616
|
+
["git", "rev-list", "@{u}..HEAD", "--count"],
|
|
617
|
+
capture_output=True,
|
|
618
|
+
text=True,
|
|
619
|
+
cwd=worktree_path,
|
|
620
|
+
check=False,
|
|
621
|
+
)
|
|
622
|
+
return count.returncode == 0 and int(count.stdout.strip()) > 0
|
|
623
|
+
|
|
624
|
+
remote_branches = subprocess.run(
|
|
625
|
+
["git", "branch", "-r", "--contains", "HEAD"],
|
|
626
|
+
capture_output=True,
|
|
627
|
+
text=True,
|
|
628
|
+
cwd=worktree_path,
|
|
629
|
+
check=False,
|
|
630
|
+
)
|
|
631
|
+
if remote_branches.stdout.strip():
|
|
632
|
+
return False
|
|
633
|
+
|
|
634
|
+
# Why: squashマージ後の自動削除でリモースブランチが消えると、HEADを含む
|
|
635
|
+
# リモートrefが存在しなくなりgitだけではマージ済みと証明できない。
|
|
636
|
+
# ghでPR状態を確認し、MERGEDかつマージ時点のHEAD SHAが一致する場合のみ
|
|
637
|
+
# ガードを解除する(マージ後の追加コミットは保護対象のまま)。
|
|
638
|
+
# ghなし・非GitHub・未マージは従来どおりunpushed扱いのまま保護する。
|
|
639
|
+
branch = subprocess.run(
|
|
640
|
+
["git", "rev-parse", "--abbrev-ref", "HEAD"],
|
|
641
|
+
capture_output=True,
|
|
642
|
+
text=True,
|
|
643
|
+
cwd=worktree_path,
|
|
644
|
+
check=False,
|
|
645
|
+
)
|
|
646
|
+
head = subprocess.run(
|
|
647
|
+
["git", "rev-parse", "HEAD"],
|
|
648
|
+
capture_output=True,
|
|
649
|
+
text=True,
|
|
650
|
+
cwd=worktree_path,
|
|
651
|
+
check=False,
|
|
652
|
+
)
|
|
653
|
+
pr = None
|
|
654
|
+
if branch.returncode == 0 and head.returncode == 0:
|
|
655
|
+
pr = subprocess.run(
|
|
656
|
+
[
|
|
657
|
+
"gh",
|
|
658
|
+
"pr",
|
|
659
|
+
"view",
|
|
660
|
+
branch.stdout.strip(),
|
|
661
|
+
"--json",
|
|
662
|
+
"state,headRefOid",
|
|
663
|
+
],
|
|
664
|
+
capture_output=True,
|
|
665
|
+
text=True,
|
|
666
|
+
cwd=worktree_path,
|
|
667
|
+
check=False,
|
|
668
|
+
)
|
|
669
|
+
if pr is not None and pr.returncode == 0:
|
|
670
|
+
try:
|
|
671
|
+
merged = json.loads(pr.stdout)
|
|
672
|
+
except ValueError:
|
|
673
|
+
merged = {}
|
|
674
|
+
if (
|
|
675
|
+
merged.get("state") == "MERGED"
|
|
676
|
+
and merged.get("headRefOid") == head.stdout.strip()
|
|
677
|
+
):
|
|
678
|
+
print(
|
|
679
|
+
f"note: PR for branch '{branch.stdout.strip()}' is merged, "
|
|
680
|
+
"continuing finish",
|
|
681
|
+
file=sys.stderr,
|
|
682
|
+
)
|
|
683
|
+
return False
|
|
684
|
+
|
|
685
|
+
return True
|
|
686
|
+
|
|
687
|
+
|
|
688
|
+
def _resolve_branch_name(name: str, cwd: Path) -> str | None:
|
|
689
|
+
"""Resolve *name* to an actual branch name, allowing prefix matches.
|
|
690
|
+
|
|
691
|
+
First checks for an exact match, then searches for branches ending
|
|
692
|
+
with ``/<name>`` (e.g. ``feature/<name>``).
|
|
693
|
+
|
|
694
|
+
Returns:
|
|
695
|
+
The resolved branch name, or ``None`` if ambiguous or not found.
|
|
696
|
+
"""
|
|
697
|
+
result = subprocess.run(
|
|
698
|
+
["git", "branch", "--format=%(refname:short)"],
|
|
699
|
+
capture_output=True,
|
|
700
|
+
text=True,
|
|
701
|
+
cwd=cwd,
|
|
702
|
+
check=False,
|
|
703
|
+
)
|
|
704
|
+
if result.returncode != 0:
|
|
705
|
+
return name
|
|
706
|
+
|
|
707
|
+
branches = [line.strip() for line in result.stdout.splitlines() if line.strip()]
|
|
708
|
+
|
|
709
|
+
if name in branches:
|
|
710
|
+
return name
|
|
711
|
+
|
|
712
|
+
suffix = "/" + name
|
|
713
|
+
candidates = [b for b in branches if b.endswith(suffix)]
|
|
714
|
+
|
|
715
|
+
if len(candidates) == 1:
|
|
716
|
+
return candidates[0]
|
|
717
|
+
|
|
718
|
+
if len(candidates) > 1:
|
|
719
|
+
print(
|
|
720
|
+
f"warning: multiple branches match '*{suffix}': "
|
|
721
|
+
f"{', '.join(sorted(candidates))}, skipping deletion",
|
|
722
|
+
file=sys.stderr,
|
|
723
|
+
)
|
|
724
|
+
|
|
725
|
+
return None
|
|
726
|
+
|
|
727
|
+
|
|
728
|
+
def _delete_branch(name: str, cwd: Path) -> None:
|
|
729
|
+
"""Delete a local git branch using ``git branch -D``.
|
|
730
|
+
|
|
731
|
+
A status message is printed to stderr on both success and failure.
|
|
732
|
+
Failures are treated as non-fatal warnings -- the function does not
|
|
733
|
+
raise or exit the process.
|
|
734
|
+
|
|
735
|
+
Args:
|
|
736
|
+
name: Branch name to delete.
|
|
737
|
+
cwd: Working directory where the git command is executed.
|
|
738
|
+
"""
|
|
739
|
+
result = subprocess.run(
|
|
740
|
+
["git", "branch", "-D", name],
|
|
741
|
+
capture_output=True,
|
|
742
|
+
text=True,
|
|
743
|
+
cwd=cwd,
|
|
744
|
+
check=False,
|
|
745
|
+
)
|
|
746
|
+
if result.returncode == 0:
|
|
747
|
+
print(f"deleted branch '{name}'", file=sys.stderr)
|
|
748
|
+
else:
|
|
749
|
+
print(
|
|
750
|
+
f"warning: could not delete branch '{name}': {result.stderr.strip()}",
|
|
751
|
+
file=sys.stderr,
|
|
752
|
+
)
|
|
753
|
+
|
|
754
|
+
|
|
755
|
+
def _run_commands(commands: list[str], cwd: Path, error_code: int = 5) -> None:
|
|
756
|
+
"""Execute a sequence of shell commands sequentially.
|
|
757
|
+
|
|
758
|
+
Each command is run via the shell (``shell=True``) in the specified
|
|
759
|
+
working directory. Execution stops at the first failure.
|
|
760
|
+
|
|
761
|
+
Args:
|
|
762
|
+
commands: List of shell command strings to execute.
|
|
763
|
+
cwd: Working directory for command execution.
|
|
764
|
+
error_code: Exit code to use when a command fails.
|
|
765
|
+
|
|
766
|
+
Raises:
|
|
767
|
+
SystemExit: If any command returns a non-zero exit code.
|
|
768
|
+
"""
|
|
769
|
+
for cmd in commands:
|
|
770
|
+
print(f" running: {cmd}", file=sys.stderr)
|
|
771
|
+
result = subprocess.run(cmd, shell=True, cwd=cwd, check=False)
|
|
772
|
+
if result.returncode != 0:
|
|
773
|
+
_error(f"command failed (exit {result.returncode}): {cmd}", error_code)
|
|
774
|
+
|
|
775
|
+
|
|
776
|
+
def cmd_start(base_path_str: str, name: str) -> str:
|
|
777
|
+
"""Create a new git worktree and share non-git-managed files.
|
|
778
|
+
|
|
779
|
+
Creates a linked git worktree at ``.worktrees/<name>`` with a new
|
|
780
|
+
branch from HEAD, then copies non-git-managed files matching the
|
|
781
|
+
``[start].share`` patterns into the worktree.
|
|
782
|
+
|
|
783
|
+
Args:
|
|
784
|
+
base_path_str: Path to the project root directory.
|
|
785
|
+
name: Worktree identifier in kebab-case.
|
|
786
|
+
|
|
787
|
+
Returns:
|
|
788
|
+
The relative path to the newly created worktree
|
|
789
|
+
(e.g. ``.worktrees/my-feature``).
|
|
790
|
+
|
|
791
|
+
Raises:
|
|
792
|
+
SystemExit: If the path is invalid, the name is malformed, a
|
|
793
|
+
worktree with the same name already exists, or any start
|
|
794
|
+
command fails.
|
|
795
|
+
"""
|
|
796
|
+
base_path = _resolve_base_path(base_path_str)
|
|
797
|
+
_validate_name(name)
|
|
798
|
+
|
|
799
|
+
worktrees_dir = base_path / ".worktrees"
|
|
800
|
+
worktree_path = worktrees_dir / name
|
|
801
|
+
|
|
802
|
+
if worktree_path.exists():
|
|
803
|
+
_error(f"worktree already exists: {name}", 3)
|
|
804
|
+
|
|
805
|
+
config = load_config(base_path)
|
|
806
|
+
|
|
807
|
+
print(f"creating git worktree .worktrees/{name}...", file=sys.stderr)
|
|
808
|
+
_git_worktree_add(base_path, worktree_path, name)
|
|
809
|
+
|
|
810
|
+
_ensure_gitignore_entry(worktree_path)
|
|
811
|
+
|
|
812
|
+
toml_path = worktree_path / ".foresto.toml"
|
|
813
|
+
if not toml_path.exists():
|
|
814
|
+
# Why: .gitignore修正(issue #27)と同じ方針で、ユーザープロジェクトファイルへの書き込みは
|
|
815
|
+
# UTF-8を明示する。テンプレートは現在ASCII-onlyだが、ロケール非依存を保つ
|
|
816
|
+
toml_path.write_text(
|
|
817
|
+
"[start]\n"
|
|
818
|
+
'# commands = ["npm install"]\n'
|
|
819
|
+
'# share = [".env", "node_modules"]\n'
|
|
820
|
+
"\n"
|
|
821
|
+
"[finish]\n"
|
|
822
|
+
'# commands = ["npm install"]\n',
|
|
823
|
+
encoding="utf-8",
|
|
824
|
+
)
|
|
825
|
+
print("created .foresto.toml", file=sys.stderr)
|
|
826
|
+
|
|
827
|
+
if config.start.share.patterns:
|
|
828
|
+
print("sharing non-git files...", file=sys.stderr)
|
|
829
|
+
_share_files(base_path, worktree_path, config.start.share)
|
|
830
|
+
|
|
831
|
+
if config.start.commands:
|
|
832
|
+
print("running start commands...", file=sys.stderr)
|
|
833
|
+
_run_commands(config.start.commands, worktree_path, error_code=5)
|
|
834
|
+
|
|
835
|
+
return f".worktrees/{name}"
|
|
836
|
+
|
|
837
|
+
|
|
838
|
+
def cmd_finish(name: str, *, no_pull: bool = False) -> None:
|
|
839
|
+
"""Remove a git worktree, pull latest changes, and delete the branch.
|
|
840
|
+
|
|
841
|
+
Removes the worktree at ``.worktrees/<name>``, runs ``git pull``
|
|
842
|
+
on the current branch (unless *no_pull* is ``True``), deletes the local
|
|
843
|
+
branch, then runs any finish commands defined in the project configuration.
|
|
844
|
+
|
|
845
|
+
Must be called from the project root directory.
|
|
846
|
+
|
|
847
|
+
Args:
|
|
848
|
+
name: Worktree identifier in kebab-case.
|
|
849
|
+
no_pull: If ``True``, skip the automatic ``git pull``.
|
|
850
|
+
|
|
851
|
+
Raises:
|
|
852
|
+
SystemExit: If the current directory is not a project root, the
|
|
853
|
+
worktree does not exist, ``git pull`` fails, or any finish
|
|
854
|
+
command fails.
|
|
855
|
+
"""
|
|
856
|
+
cwd = Path.cwd()
|
|
857
|
+
_validate_name(name)
|
|
858
|
+
|
|
859
|
+
worktrees_dir = cwd / ".worktrees"
|
|
860
|
+
if not worktrees_dir.is_dir():
|
|
861
|
+
_error("not in a project root (.worktrees/ not found)", 6)
|
|
862
|
+
|
|
863
|
+
worktree_path = worktrees_dir / name
|
|
864
|
+
|
|
865
|
+
if not worktree_path.is_dir():
|
|
866
|
+
_error(f"worktree not found: {name}", 7)
|
|
867
|
+
|
|
868
|
+
if not (worktree_path / ".git").exists():
|
|
869
|
+
_error(f"directory exists but is not a valid worktree: {name}", 7)
|
|
870
|
+
|
|
871
|
+
if _has_unpushed_commits(worktree_path):
|
|
872
|
+
_error(
|
|
873
|
+
f"unpushed commits found in '{name}'. Push your changes before finishing.",
|
|
874
|
+
12,
|
|
875
|
+
)
|
|
876
|
+
|
|
877
|
+
print(f"removing .worktrees/{name}...", file=sys.stderr)
|
|
878
|
+
removal_success = _git_worktree_remove(cwd, worktree_path)
|
|
879
|
+
|
|
880
|
+
if not removal_success:
|
|
881
|
+
print(
|
|
882
|
+
f"warning: failed to remove worktree directory '{name}'. "
|
|
883
|
+
"Continuing with branch deletion and finish commands.",
|
|
884
|
+
file=sys.stderr,
|
|
885
|
+
)
|
|
886
|
+
|
|
887
|
+
if not no_pull:
|
|
888
|
+
index_lock = cwd / ".git" / "index.lock"
|
|
889
|
+
if index_lock.exists():
|
|
890
|
+
print("removing stale .git/index.lock", file=sys.stderr)
|
|
891
|
+
index_lock.unlink()
|
|
892
|
+
|
|
893
|
+
print("running: git pull", file=sys.stderr)
|
|
894
|
+
result = subprocess.run(
|
|
895
|
+
["git", "pull"], cwd=cwd, capture_output=True, text=True, check=False
|
|
896
|
+
)
|
|
897
|
+
if result.returncode != 0:
|
|
898
|
+
_error(f"git pull failed: {result.stderr.strip()}", 10)
|
|
899
|
+
|
|
900
|
+
resolved = _resolve_branch_name(name, cwd)
|
|
901
|
+
if resolved is None:
|
|
902
|
+
print(
|
|
903
|
+
f"warning: branch '{name}' not found, skipping deletion",
|
|
904
|
+
file=sys.stderr,
|
|
905
|
+
)
|
|
906
|
+
else:
|
|
907
|
+
_delete_branch(resolved, cwd)
|
|
908
|
+
|
|
909
|
+
config = load_config(cwd)
|
|
910
|
+
if config.finish.commands:
|
|
911
|
+
print("running finish commands...", file=sys.stderr)
|
|
912
|
+
_run_commands(config.finish.commands, cwd, error_code=8)
|
|
913
|
+
|
|
914
|
+
|
|
915
|
+
def cmd_list() -> list[str]:
|
|
916
|
+
"""List all existing worktree names under the current project.
|
|
917
|
+
|
|
918
|
+
Scans the ``.worktrees/`` directory in the current working directory
|
|
919
|
+
and returns sorted directory names.
|
|
920
|
+
|
|
921
|
+
Returns:
|
|
922
|
+
A sorted list of worktree names. Returns an empty list if
|
|
923
|
+
``.worktrees/`` does not exist.
|
|
924
|
+
"""
|
|
925
|
+
worktrees_dir = Path.cwd() / ".worktrees"
|
|
926
|
+
if not worktrees_dir.is_dir():
|
|
927
|
+
return []
|
|
928
|
+
return sorted(entry.name for entry in worktrees_dir.iterdir() if entry.is_dir())
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: foresto
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: CLI tool for creating isolated working copies for parallel AI-assisted development
|
|
5
|
+
Project-URL: Repository, https://github.com/j4rviscmd/foresto
|
|
6
|
+
Project-URL: Issues, https://github.com/j4rviscmd/foresto/issues
|
|
7
|
+
Author: j4rviscmd
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: ai-agents,cli,developer-tools,git,worktree
|
|
11
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
12
|
+
Classifier: Environment :: Console
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
21
|
+
Classifier: Topic :: Software Development
|
|
22
|
+
Classifier: Topic :: Software Development :: Version Control :: Git
|
|
23
|
+
Requires-Python: >=3.11
|
|
24
|
+
Requires-Dist: psutil
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
|
|
27
|
+
# foresto
|
|
28
|
+
|
|
29
|
+
[](https://github.com/j4rviscmd/foresto/actions/workflows/ci.yml)
|
|
30
|
+
[](https://pypi.org/project/foresto/)
|
|
31
|
+
[](https://pypi.org/project/foresto/)
|
|
32
|
+
[](https://github.com/j4rviscmd/foresto/blob/main/LICENSE)
|
|
33
|
+
|
|
34
|
+
A CLI tool that creates isolated working copies of a project for parallel AI-assisted development.
|
|
35
|
+
|
|
36
|
+
`foresto start` checks out git-tracked files with `git worktree add` and copies non-git files (`.env`, `node_modules`, etc.) declared in the `share` setting of `.foresto.toml`. Each copy is registered as a git worktree, so you can switch between them with tools like `lazygit`.
|
|
37
|
+
|
|
38
|
+
## Installation
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
# uv (recommended)
|
|
42
|
+
uv tool install foresto
|
|
43
|
+
|
|
44
|
+
# pip
|
|
45
|
+
pip install foresto
|
|
46
|
+
|
|
47
|
+
# straight from GitHub
|
|
48
|
+
uv tool install git+https://github.com/j4rviscmd/foresto
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## Usage
|
|
52
|
+
|
|
53
|
+
| Command | Purpose | Example |
|
|
54
|
+
| --- | --- | --- |
|
|
55
|
+
| `foresto --version` | Show version | `foresto --version` |
|
|
56
|
+
| `foresto start <base_path> <name>` | Create a working copy | `foresto start ./my-app quick-silver-moon` |
|
|
57
|
+
| `foresto finish <name>` | Remove a working copy | `foresto finish quick-silver-moon` |
|
|
58
|
+
| `foresto list` | List working copies | Run from the base directory |
|
|
59
|
+
|
|
60
|
+
### Create a working copy
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
foresto start <base_path> <name>
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
- `base_path` — path to the source project (absolute or relative)
|
|
67
|
+
- `name` — identifier in kebab-case (e.g. `quick-silver-moon`)
|
|
68
|
+
|
|
69
|
+
Example:
|
|
70
|
+
|
|
71
|
+
```bash
|
|
72
|
+
foresto start ./my-app quick-silver-moon
|
|
73
|
+
# -> .worktrees/quick-silver-moon
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
After running:
|
|
77
|
+
|
|
78
|
+
- git-tracked files are checked out with `git worktree add`
|
|
79
|
+
- non-git files listed in `[start].share` of `.foresto.toml` are copied
|
|
80
|
+
- a git branch named `name` is created in the working copy
|
|
81
|
+
- the relative path is printed to stdout (so callers can capture it)
|
|
82
|
+
|
|
83
|
+
### Remove a working copy
|
|
84
|
+
|
|
85
|
+
```bash
|
|
86
|
+
foresto finish <name>
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
Run from the base project directory.
|
|
90
|
+
|
|
91
|
+
Example:
|
|
92
|
+
|
|
93
|
+
```bash
|
|
94
|
+
cd my-app
|
|
95
|
+
foresto finish quick-silver-moon
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
After running:
|
|
99
|
+
|
|
100
|
+
- Stops with a warning if unpushed commits exist. When the remote branch was deleted after a squash merge, `gh pr view` is consulted and the command proceeds only if the PR is MERGED and the head SHA at merge time matches the local HEAD.
|
|
101
|
+
- The working directory is removed with `git worktree remove`
|
|
102
|
+
- `git pull` runs on the current branch
|
|
103
|
+
- The local branch is deleted
|
|
104
|
+
- The `finish` commands in `.foresto.toml` run in the base directory
|
|
105
|
+
|
|
106
|
+
Use `--no-pull` to skip `git pull`:
|
|
107
|
+
|
|
108
|
+
```bash
|
|
109
|
+
foresto finish --no-pull quick-silver-moon
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
### List working copies
|
|
113
|
+
|
|
114
|
+
```bash
|
|
115
|
+
foresto list
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
Run from the base project directory.
|
|
119
|
+
|
|
120
|
+
## Configuration
|
|
121
|
+
|
|
122
|
+
Place `.foresto.toml` in the project root. The lookup location depends on the command.
|
|
123
|
+
|
|
124
|
+
| Command | Lookup location | Description |
|
|
125
|
+
| --- | --- | --- |
|
|
126
|
+
| `foresto start` | `{base_path}/.foresto.toml` | Directly under the project path you passed |
|
|
127
|
+
| `foresto finish` | `{cwd}/.foresto.toml` | Directly under the current directory |
|
|
128
|
+
|
|
129
|
+
```toml
|
|
130
|
+
[start]
|
|
131
|
+
commands = ["npm install"]
|
|
132
|
+
share = [".env", "node_modules"]
|
|
133
|
+
|
|
134
|
+
[finish]
|
|
135
|
+
commands = ["npm install"]
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
- `[start].commands` — run inside the working copy after the worktree is created
|
|
139
|
+
- `[start].share` — patterns of non-git files to copy into the working copy
|
|
140
|
+
- Basename pattern (no `/`): matches by name at any depth (e.g. `.env`, `node_modules`)
|
|
141
|
+
- Path pattern (contains `/`): matches a path relative to the project root (e.g. `secrets/local.env`)
|
|
142
|
+
- Symbolic links are preserved as links (keeps structures like pnpm's `node_modules`). On Windows, falls back to a real copy with a warning when symlink creation is not permitted
|
|
143
|
+
- `[finish].commands` — run in the base directory after removal
|
|
144
|
+
|
|
145
|
+
If the file does not exist, nothing is run.
|
|
146
|
+
|
|
147
|
+
## Typical workflow
|
|
148
|
+
|
|
149
|
+
```text
|
|
150
|
+
1. foresto start ./my-app add-auth-feature
|
|
151
|
+
2. cd .worktrees/add-auth-feature
|
|
152
|
+
(the add-auth-feature branch is already created)
|
|
153
|
+
3. (work, commit, push, open a PR, merge)
|
|
154
|
+
4. cd ../..
|
|
155
|
+
5. foresto finish add-auth-feature
|
|
156
|
+
-> git pull runs and the merged changes land in the base
|
|
157
|
+
-> the local branch is deleted
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
## Exit codes
|
|
161
|
+
|
|
162
|
+
| Code | Meaning |
|
|
163
|
+
| --- | --- |
|
|
164
|
+
| 0 | Success |
|
|
165
|
+
| 1 | `base_path` does not exist, or no subcommand was given |
|
|
166
|
+
| 2 | `name` is not kebab-case |
|
|
167
|
+
| 3 | The worktree already exists |
|
|
168
|
+
| 4 | `git worktree add` failed |
|
|
169
|
+
| 5 | A start command failed |
|
|
170
|
+
| 6 | `.worktrees/` not found (finish was run outside the base directory) |
|
|
171
|
+
| 7 | The worktree was not found |
|
|
172
|
+
| 8 | A finish command failed |
|
|
173
|
+
| 10 | `git pull` failed |
|
|
174
|
+
| 11 | `git worktree remove` failed |
|
|
175
|
+
| 12 | Unpushed commits were detected (during finish) |
|
|
176
|
+
| 13 | Invalid `share` pattern in `.foresto.toml` |
|
|
177
|
+
|
|
178
|
+
## License
|
|
179
|
+
|
|
180
|
+
MIT
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
foresto/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
2
|
+
foresto/__main__.py,sha256=E6Gls0DNz8GQK2K-kOUIx8cYhgANW_CH54VKrfCfs14,52
|
|
3
|
+
foresto/cli.py,sha256=iJrTEvm4dgE9RIu7qPEvjfOZM7EyDMI7xvg453luuho,2095
|
|
4
|
+
foresto/config.py,sha256=GziQ5GiwlsIc2O1ZAhZ7XF3Ib9chrRAuPpi3Jlj30YM,4228
|
|
5
|
+
foresto/core.py,sha256=A7BVExrkyLMiIApvUX0G6EbI4Paq_1urMaqDJz1woDc,32497
|
|
6
|
+
foresto-1.0.0.dist-info/METADATA,sha256=l90i48I16DiAgLbs_hQ0OKRFbnTpizF0IzkzhG9gxKo,5930
|
|
7
|
+
foresto-1.0.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
8
|
+
foresto-1.0.0.dist-info/entry_points.txt,sha256=Ke-sE9fHQ3Jp668l4-F_TFv_JigjukFJIhq7xUBFhQU,45
|
|
9
|
+
foresto-1.0.0.dist-info/licenses/LICENSE,sha256=iGUSy6auzaCbtVd5scZlth06DAmqziJx31KqBWDigN8,1066
|
|
10
|
+
foresto-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 j4rviscmd
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|