llmswap-cli 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.
- claude_swap/__init__.py +24 -0
- claude_swap/__main__.py +6 -0
- claude_swap/app_bundle.py +330 -0
- claude_swap/appearance.py +219 -0
- claude_swap/autoswitch.py +3065 -0
- claude_swap/cache.py +44 -0
- claude_swap/claude_locks.py +279 -0
- claude_swap/cli.py +2265 -0
- claude_swap/credentials.py +2156 -0
- claude_swap/exceptions.py +102 -0
- claude_swap/fsutil.py +409 -0
- claude_swap/json_output.py +455 -0
- claude_swap/launch_agent.py +862 -0
- claude_swap/lines.py +153 -0
- claude_swap/list_view.py +371 -0
- claude_swap/locking.py +87 -0
- claude_swap/logging_config.py +64 -0
- claude_swap/macos_keychain.py +240 -0
- claude_swap/mappings.py +127 -0
- claude_swap/menubar.py +1433 -0
- claude_swap/migrations.py +360 -0
- claude_swap/models.py +329 -0
- claude_swap/oauth.py +1628 -0
- claude_swap/pace.py +161 -0
- claude_swap/paths.py +250 -0
- claude_swap/poll_policy.py +337 -0
- claude_swap/printer.py +252 -0
- claude_swap/process_detection.py +370 -0
- claude_swap/session.py +2696 -0
- claude_swap/settings.py +827 -0
- claude_swap/signin.py +238 -0
- claude_swap/snapshot_source.py +121 -0
- claude_swap/spawn.py +135 -0
- claude_swap/subscription.py +349 -0
- claude_swap/switcher.py +9807 -0
- claude_swap/transfer.py +807 -0
- claude_swap/tui/__init__.py +43 -0
- claude_swap/tui/app.py +482 -0
- claude_swap/tui/autoview.py +381 -0
- claude_swap/tui/cswap.tcss +205 -0
- claude_swap/tui/dashboard.py +434 -0
- claude_swap/tui/data.py +194 -0
- claude_swap/tui/modals.py +159 -0
- claude_swap/tui/theme.py +88 -0
- claude_swap/tui/widgets.py +544 -0
- claude_swap/update_check.py +509 -0
- claude_swap/usage_bars.py +208 -0
- claude_swap/usage_rows.py +160 -0
- claude_swap/usage_store.py +1429 -0
- llmswap/AGENTS.md +11 -0
- llmswap/__init__.py +3 -0
- llmswap/__main__.py +4 -0
- llmswap/cli.py +535 -0
- llmswap/config.py +101 -0
- llmswap/httpjson.py +50 -0
- llmswap/jwt.py +20 -0
- llmswap/menubar.py +218 -0
- llmswap/model.py +172 -0
- llmswap/paths.py +41 -0
- llmswap/providers/AGENTS.md +12 -0
- llmswap/providers/base.py +619 -0
- llmswap/providers/claude.py +187 -0
- llmswap/providers/codex.py +274 -0
- llmswap/providers/gemini.py +80 -0
- llmswap/providers/registry.py +30 -0
- llmswap/render.py +127 -0
- llmswap/rotate.py +102 -0
- llmswap/store.py +138 -0
- llmswap/tui.py +182 -0
- llmswap/usage_cache.py +72 -0
- llmswap/warm/plan.py +118 -0
- llmswap/warm/runner.py +175 -0
- llmswap/warm/schedule.py +264 -0
- llmswap_cli-1.0.0.dist-info/METADATA +181 -0
- llmswap_cli-1.0.0.dist-info/RECORD +78 -0
- llmswap_cli-1.0.0.dist-info/WHEEL +4 -0
- llmswap_cli-1.0.0.dist-info/entry_points.txt +5 -0
- llmswap_cli-1.0.0.dist-info/licenses/LICENSE +22 -0
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""Custom exceptions for Claude Switch."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class ClaudeSwitchError(Exception):
|
|
5
|
+
"""Base exception for Claude Switch errors."""
|
|
6
|
+
|
|
7
|
+
pass
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class CredentialError(ClaudeSwitchError):
|
|
11
|
+
"""Error related to credential operations."""
|
|
12
|
+
|
|
13
|
+
pass
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class CredentialReadError(CredentialError):
|
|
17
|
+
"""Failed to read credentials."""
|
|
18
|
+
|
|
19
|
+
pass
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class CredentialWriteError(CredentialError):
|
|
23
|
+
"""Failed to write credentials."""
|
|
24
|
+
|
|
25
|
+
pass
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class ConfigError(ClaudeSwitchError):
|
|
29
|
+
"""Error related to configuration operations."""
|
|
30
|
+
|
|
31
|
+
pass
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class SwitchError(ClaudeSwitchError):
|
|
35
|
+
"""Error during account switch operation."""
|
|
36
|
+
|
|
37
|
+
pass
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class SessionError(ClaudeSwitchError):
|
|
41
|
+
"""Error setting up or launching a session-mode profile."""
|
|
42
|
+
|
|
43
|
+
pass
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class SignInError(ClaudeSwitchError):
|
|
47
|
+
"""A sign-in run through Claude Code did not produce a usable login."""
|
|
48
|
+
|
|
49
|
+
pass
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class LockError(ClaudeSwitchError):
|
|
53
|
+
"""Error acquiring lock."""
|
|
54
|
+
|
|
55
|
+
pass
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class ClaudeCodeLockTimeout(LockError):
|
|
59
|
+
"""Timed out acquiring one of Claude Code's own advisory locks.
|
|
60
|
+
|
|
61
|
+
Raised when ``~/.claude.lock`` / ``~/.claude.json.lock`` stays held past
|
|
62
|
+
our bounded wait — usually Claude Code mid-token-refresh. Nothing has been
|
|
63
|
+
mutated when this raises; the operation is safe to retry.
|
|
64
|
+
"""
|
|
65
|
+
|
|
66
|
+
pass
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class AccountNotFoundError(ClaudeSwitchError):
|
|
70
|
+
"""Account not found."""
|
|
71
|
+
|
|
72
|
+
pass
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class ValidationError(ClaudeSwitchError):
|
|
76
|
+
"""Validation error."""
|
|
77
|
+
|
|
78
|
+
pass
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class TransferError(ClaudeSwitchError):
|
|
82
|
+
"""Error during account export or import."""
|
|
83
|
+
|
|
84
|
+
pass
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class MigrationError(ClaudeSwitchError):
|
|
88
|
+
"""Error migrating the backup directory between layouts (e.g. legacy → XDG)."""
|
|
89
|
+
|
|
90
|
+
pass
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class MigrationIncomplete(ClaudeSwitchError):
|
|
94
|
+
"""A one-time data migration could not finish for every record.
|
|
95
|
+
|
|
96
|
+
Raised by run-once migrations (see ``migrations.py``) when some entries
|
|
97
|
+
failed or the source backend was inaccessible. The migration runner treats
|
|
98
|
+
this as "not applied" so the migration is retried on the next run rather
|
|
99
|
+
than being recorded as done with records left behind.
|
|
100
|
+
"""
|
|
101
|
+
|
|
102
|
+
pass
|
claude_swap/fsutil.py
ADDED
|
@@ -0,0 +1,409 @@
|
|
|
1
|
+
"""Filesystem primitives with no claude_swap dependencies.
|
|
2
|
+
|
|
3
|
+
Deliberately a leaf module: the atomic-write helpers here are needed by
|
|
4
|
+
settings, credentials, mappings and session, which sit on both sides of
|
|
5
|
+
the paths/models/usage_store import cycle.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import errno
|
|
11
|
+
import os
|
|
12
|
+
import sys
|
|
13
|
+
import tempfile
|
|
14
|
+
import time
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
# Windows error codes that usually mean "someone else has the file open right
|
|
18
|
+
# now": ERROR_ACCESS_DENIED, ERROR_SHARING_VIOLATION and ERROR_LOCK_VIOLATION.
|
|
19
|
+
# AV/indexer contention clears within milliseconds; ERROR_ACCESS_DENIED can
|
|
20
|
+
# also be a persistent condition (ACLs, read-only attribute), which still
|
|
21
|
+
# surfaces once the bounded retries are exhausted.
|
|
22
|
+
_TRANSIENT_WIN_ERRORS = frozenset({5, 32, 33})
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def read_text_with_retry(
|
|
26
|
+
path: os.PathLike | str,
|
|
27
|
+
*,
|
|
28
|
+
attempts: int = 10,
|
|
29
|
+
initial_delay: float = 0.002,
|
|
30
|
+
) -> str:
|
|
31
|
+
"""``Path.read_text``, retried past the same transient Windows failures.
|
|
32
|
+
|
|
33
|
+
The read side of :func:`replace_with_retry`, and it needs the same
|
|
34
|
+
treatment for the same reason: ``_write_json`` publishes the roster by
|
|
35
|
+
renaming onto ``sequence.json``, so the file is freshly-modified exactly
|
|
36
|
+
when AV/the indexer opens it opportunistically, and a reader arriving in
|
|
37
|
+
that window gets ERROR_SHARING_VIOLATION as a ``PermissionError``.
|
|
38
|
+
|
|
39
|
+
That window matters more on the read side than the write side, because a
|
|
40
|
+
strict roster read raises ``ConfigError`` at ~59 call sites — including
|
|
41
|
+
read-only ones (``list_accounts``, ``_account_kind``) and
|
|
42
|
+
``SwitchTransaction.rollback``, where turning a recoverable switch failure
|
|
43
|
+
into a failed ROLLBACK is the worst outcome available.
|
|
44
|
+
|
|
45
|
+
POSIX is untouched: there is no such window, and an ``EACCES`` there is a
|
|
46
|
+
genuine, persistent permission problem that must surface at once rather
|
|
47
|
+
than after a ~0.75 s stall.
|
|
48
|
+
"""
|
|
49
|
+
if attempts < 1:
|
|
50
|
+
raise ValueError("attempts must be >= 1")
|
|
51
|
+
delay = initial_delay
|
|
52
|
+
for attempt in range(attempts):
|
|
53
|
+
try:
|
|
54
|
+
return Path(path).read_text(encoding="utf-8")
|
|
55
|
+
except OSError as e:
|
|
56
|
+
transient = (
|
|
57
|
+
sys.platform == "win32"
|
|
58
|
+
and getattr(e, "winerror", None) in _TRANSIENT_WIN_ERRORS
|
|
59
|
+
)
|
|
60
|
+
if not transient or attempt == attempts - 1:
|
|
61
|
+
raise
|
|
62
|
+
time.sleep(delay)
|
|
63
|
+
delay = min(delay * 2, 0.25)
|
|
64
|
+
raise AssertionError("unreachable") # pragma: no cover - loop always exits
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def replace_with_retry(
|
|
68
|
+
src: os.PathLike | str,
|
|
69
|
+
dst: os.PathLike | str,
|
|
70
|
+
*,
|
|
71
|
+
attempts: int = 10,
|
|
72
|
+
initial_delay: float = 0.002,
|
|
73
|
+
) -> None:
|
|
74
|
+
"""``os.replace``, retried past transient Windows sharing failures.
|
|
75
|
+
|
|
76
|
+
POSIX ``rename`` is genuinely atomic and never fails this way, but on
|
|
77
|
+
Windows antivirus (Defender) and the search indexer open freshly-created
|
|
78
|
+
files opportunistically. A replace onto a just-written target then fails
|
|
79
|
+
with ERROR_ACCESS_DENIED or ERROR_SHARING_VIOLATION for a few milliseconds
|
|
80
|
+
— measured at ~44% of replaces into a scanned temp directory, which made
|
|
81
|
+
credential and usage-store writes fail intermittently for real users.
|
|
82
|
+
|
|
83
|
+
Only the contention codes are retried; other errors (missing source,
|
|
84
|
+
cross-device link) surface on the first attempt. A *persistent* access
|
|
85
|
+
denial (ACLs, read-only target) matches the retried codes and so raises
|
|
86
|
+
only after the attempt budget — a ~0.75 s delay in the worst case.
|
|
87
|
+
"""
|
|
88
|
+
if attempts < 1:
|
|
89
|
+
raise ValueError("attempts must be >= 1")
|
|
90
|
+
delay = initial_delay
|
|
91
|
+
for attempt in range(attempts):
|
|
92
|
+
try:
|
|
93
|
+
os.replace(src, dst)
|
|
94
|
+
return
|
|
95
|
+
except OSError as e:
|
|
96
|
+
transient = (
|
|
97
|
+
sys.platform == "win32"
|
|
98
|
+
and getattr(e, "winerror", None) in _TRANSIENT_WIN_ERRORS
|
|
99
|
+
)
|
|
100
|
+
if not transient or attempt == attempts - 1:
|
|
101
|
+
raise
|
|
102
|
+
time.sleep(delay)
|
|
103
|
+
delay = min(delay * 2, 0.25)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
# Filesystems that do not implement fsync answer one of these; the write goes
|
|
107
|
+
# ahead without the durability it would otherwise buy (Claude Code's own
|
|
108
|
+
# writer tolerates the same set). Anything else -- EIO above all -- raises.
|
|
109
|
+
_FSYNC_UNSUPPORTED = frozenset(
|
|
110
|
+
code
|
|
111
|
+
for code in (
|
|
112
|
+
getattr(errno, name, None)
|
|
113
|
+
for name in ("EINVAL", "ENOTSUP", "EOPNOTSUPP", "ENOSYS")
|
|
114
|
+
)
|
|
115
|
+
if code is not None
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
# ``os.path.ALLOW_MISSING`` (3.12.11 / 3.13.4 and later) resolves a symlink
|
|
120
|
+
# chain strictly -- a loop or any other resolution error raises -- while
|
|
121
|
+
# allowing the final referent to be missing. Older patch releases fall back to
|
|
122
|
+
# fully strict resolution, which refuses a dangling link rather than guess.
|
|
123
|
+
# Module-level so a test can pin the fallback without touching ``os.path``.
|
|
124
|
+
_RESOLVE_STRICT = getattr(os.path, "ALLOW_MISSING", True)
|
|
125
|
+
|
|
126
|
+
# NAME_MAX is 255 bytes on every filesystem cswap meets, and ``mkstemp`` adds
|
|
127
|
+
# eight random characters plus ``.tmp`` to the prefix. A prefix carrying the
|
|
128
|
+
# whole destination name would push a legal 243+ character destination over
|
|
129
|
+
# the limit -- ENAMETOOLONG at the temp, for a file that itself fits. Keep
|
|
130
|
+
# the association readable for ordinary names and bounded for long ones.
|
|
131
|
+
_TEMP_PREFIX_CHARS = 40
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def publish_target(path: os.PathLike | str) -> Path:
|
|
135
|
+
"""Where a publish to ``path`` lands: ``path`` itself or, for a symlink,
|
|
136
|
+
the end of its chain.
|
|
137
|
+
|
|
138
|
+
Written THROUGH a link rather than over it: a rename swaps a directory
|
|
139
|
+
entry and never follows links, so renaming onto a symlinked path detaches
|
|
140
|
+
it -- the write succeeds, the content is right, and the link's target
|
|
141
|
+
silently stops receiving updates (#192). Claude Code's own config writer
|
|
142
|
+
writes through a symlinked ``~/.claude.json`` for the same reason.
|
|
143
|
+
|
|
144
|
+
Resolution is ``os.path.realpath`` with ``strict=os.path.ALLOW_MISSING``:
|
|
145
|
+
the whole chain (not one hop), a missing final referent allowed (a
|
|
146
|
+
dangling link writes where it points), a loop or any other resolution
|
|
147
|
+
error raised. Not the non-strict default: that collapses
|
|
148
|
+
``loop/../victim.json`` lexically into ``victim.json`` and would aim the
|
|
149
|
+
write at a different file than ``open`` reaches (which fails with ELOOP).
|
|
150
|
+
"""
|
|
151
|
+
target = Path(path)
|
|
152
|
+
if not target.is_symlink():
|
|
153
|
+
return target
|
|
154
|
+
return Path(os.path.realpath(target, strict=_RESOLVE_STRICT))
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def atomic_write_bytes(
|
|
158
|
+
path: os.PathLike | str,
|
|
159
|
+
data: bytes,
|
|
160
|
+
*,
|
|
161
|
+
mode: int = 0o600,
|
|
162
|
+
follow_symlinks: bool = True,
|
|
163
|
+
) -> None:
|
|
164
|
+
"""Publish ``data`` at ``path`` by temp file + rename.
|
|
165
|
+
|
|
166
|
+
``mkstemp`` creates the temp beside the target (0600 from creation, same
|
|
167
|
+
filesystem, so the rename is atomic); the bytes are written, ``mode`` is
|
|
168
|
+
set on the open descriptor, the content is fsynced, and the temp is
|
|
169
|
+
renamed over the target. A reader sees the old file or the new one, never
|
|
170
|
+
a truncated or partial one -- which is what ``Path.write_text`` (O_TRUNC,
|
|
171
|
+
then write) cannot promise, and why the switch rollback must not use it:
|
|
172
|
+
Claude Code watches ``~/.claude.json`` and treats a torn read as a
|
|
173
|
+
corrupted config (#419).
|
|
174
|
+
|
|
175
|
+
``follow_symlinks`` (the default) publishes onto the end of a symlink
|
|
176
|
+
chain so the link survives -- see :func:`publish_target`. Pass ``False``
|
|
177
|
+
for a destination the user typed, such as an export file under ``/tmp``,
|
|
178
|
+
where a link planted by someone else must not redirect the write: the
|
|
179
|
+
rename then replaces the link itself.
|
|
180
|
+
|
|
181
|
+
Precisely what is promised: a failure before the rename leaves the
|
|
182
|
+
destination exactly as it was and removes the temp; no further ordinary
|
|
183
|
+
fallible operation follows the rename (a signal can still interrupt the
|
|
184
|
+
caller once the file is published). The content is fsynced before it is
|
|
185
|
+
published, so a crash cannot leave an empty new file where an old one was.
|
|
186
|
+
The durability of the rename itself is the directory's business and is
|
|
187
|
+
not promised: a crash right after it can lose a newly created file or
|
|
188
|
+
show the previous version of an existing one. Where the filesystem
|
|
189
|
+
reports fsync as unsupported, the write proceeds without that guarantee.
|
|
190
|
+
One cleanup gap is accepted: a signal landing inside ``mkstemp`` between
|
|
191
|
+
the create and the return of its name strands one 0600 temp.
|
|
192
|
+
|
|
193
|
+
Not done here on purpose: no ``mkdir`` of parents (callers that need it do
|
|
194
|
+
it first), and no in-place fallback when the rename is refused -- a
|
|
195
|
+
bind-mounted target answers EBUSY, the write fails, the destination is
|
|
196
|
+
untouched. Claude Code's own writer does fall back to an in-place rewrite
|
|
197
|
+
there (keeping its temp until the rewrite lands); that is the shape to copy
|
|
198
|
+
if anyone ever asks for it, in this one place.
|
|
199
|
+
"""
|
|
200
|
+
target = publish_target(path) if follow_symlinks else Path(path)
|
|
201
|
+
fd, tmp = tempfile.mkstemp(
|
|
202
|
+
dir=str(target.parent),
|
|
203
|
+
prefix=f"{target.name[:_TEMP_PREFIX_CHARS]}.",
|
|
204
|
+
suffix=".tmp",
|
|
205
|
+
)
|
|
206
|
+
try:
|
|
207
|
+
view = memoryview(data)
|
|
208
|
+
while view:
|
|
209
|
+
written = os.write(fd, view)
|
|
210
|
+
if written == 0:
|
|
211
|
+
raise OSError(errno.EIO, "write made no progress", tmp)
|
|
212
|
+
view = view[written:]
|
|
213
|
+
# Windows before 3.13 has no fchmod; the attribute check (not only the
|
|
214
|
+
# platform string) keeps this safe under tests that patch sys.platform
|
|
215
|
+
# to darwin process-wide, as the launch agent tests do.
|
|
216
|
+
if sys.platform != "win32" and hasattr(os, "fchmod"):
|
|
217
|
+
os.fchmod(fd, mode)
|
|
218
|
+
try:
|
|
219
|
+
os.fsync(fd)
|
|
220
|
+
except OSError as e:
|
|
221
|
+
if e.errno not in _FSYNC_UNSUPPORTED:
|
|
222
|
+
raise
|
|
223
|
+
os.close(fd)
|
|
224
|
+
fd = -1
|
|
225
|
+
replace_with_retry(tmp, target)
|
|
226
|
+
except BaseException:
|
|
227
|
+
if fd >= 0:
|
|
228
|
+
try:
|
|
229
|
+
os.close(fd)
|
|
230
|
+
except OSError:
|
|
231
|
+
pass
|
|
232
|
+
try:
|
|
233
|
+
os.unlink(tmp)
|
|
234
|
+
except OSError:
|
|
235
|
+
pass
|
|
236
|
+
raise
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def atomic_write_text(
|
|
240
|
+
path: os.PathLike | str,
|
|
241
|
+
text: str,
|
|
242
|
+
*,
|
|
243
|
+
mode: int = 0o600,
|
|
244
|
+
follow_symlinks: bool = True,
|
|
245
|
+
) -> None:
|
|
246
|
+
""":func:`atomic_write_bytes` for UTF-8 text."""
|
|
247
|
+
atomic_write_bytes(
|
|
248
|
+
path, text.encode("utf-8"), mode=mode, follow_symlinks=follow_symlinks
|
|
249
|
+
)
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
# ---------------------------------------------------------------------------
|
|
253
|
+
# Links
|
|
254
|
+
# ---------------------------------------------------------------------------
|
|
255
|
+
#
|
|
256
|
+
# A link, here, is a directory entry that leads somewhere else and holds no
|
|
257
|
+
# data of its own: a symlink on any platform, or a directory junction on
|
|
258
|
+
# Windows. Junctions matter because they are the one directory link an
|
|
259
|
+
# ordinary Windows user can create (a symlink needs Developer Mode or an
|
|
260
|
+
# elevated token), and because the stdlib does not count them as links:
|
|
261
|
+
# ``Path.is_symlink()`` is False for one, ``is_dir()`` follows it, and
|
|
262
|
+
# ``rglob`` and ``os.walk`` descend into it as into a plain directory. Code
|
|
263
|
+
# that must tell a cswap-made link from real user data goes through
|
|
264
|
+
# ``is_link``, never ``is_symlink``.
|
|
265
|
+
|
|
266
|
+
# Windows stores a link target with the extended-length prefix in front:
|
|
267
|
+
# ``\\?\C:\...``, or ``\\?\UNC\server\share\...`` for a network path.
|
|
268
|
+
_EXTENDED_PREFIX = "\\\\?\\"
|
|
269
|
+
_EXTENDED_UNC_PREFIX = _EXTENDED_PREFIX + "UNC\\"
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def is_link(path: os.PathLike | str) -> bool:
|
|
273
|
+
"""Whether ``path`` is a symlink or a Windows junction, dangling or not."""
|
|
274
|
+
target = Path(path)
|
|
275
|
+
try:
|
|
276
|
+
return target.is_symlink() or target.is_junction()
|
|
277
|
+
except OSError:
|
|
278
|
+
return False
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def _without_extended_prefix(path: str) -> str:
|
|
282
|
+
"""Drop the extended-length prefix Windows puts on a stored link target."""
|
|
283
|
+
if path.startswith(_EXTENDED_UNC_PREFIX):
|
|
284
|
+
return "\\\\" + path[len(_EXTENDED_UNC_PREFIX):]
|
|
285
|
+
if path.startswith(_EXTENDED_PREFIX):
|
|
286
|
+
return path[len(_EXTENDED_PREFIX):]
|
|
287
|
+
return path
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def link_points_at(link: os.PathLike | str, target: os.PathLike | str) -> bool:
|
|
291
|
+
"""Whether the link at ``link`` stores ``target`` as its destination.
|
|
292
|
+
|
|
293
|
+
Compares the stored path, not where it leads: a link to an intermediate
|
|
294
|
+
symlink is a different (and worse) link than one to the resolved file
|
|
295
|
+
even though both end at the same place -- see the note on dotfiles
|
|
296
|
+
setups in ``session.SessionManager._sync_items``. Windows hands a stored
|
|
297
|
+
path back with its extended-length prefix, which is stripped first.
|
|
298
|
+
False for anything that is not a link.
|
|
299
|
+
"""
|
|
300
|
+
try:
|
|
301
|
+
stored = os.readlink(link)
|
|
302
|
+
except OSError:
|
|
303
|
+
return False
|
|
304
|
+
return Path(_without_extended_prefix(os.fspath(stored))) == Path(target)
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def remove_link(link: os.PathLike | str) -> None:
|
|
308
|
+
"""Remove a symlink or junction itself, never what it leads to.
|
|
309
|
+
|
|
310
|
+
``os.unlink`` takes a file symlink anywhere, a directory symlink on
|
|
311
|
+
POSIX, and on Windows a directory symlink and a junction alike (CPython
|
|
312
|
+
removes a directory reparse point with ``RemoveDirectoryW``). ``rmdir``
|
|
313
|
+
is the fallback for a build that answers EISDIR or EPERM instead.
|
|
314
|
+
"""
|
|
315
|
+
try:
|
|
316
|
+
os.unlink(link)
|
|
317
|
+
except (IsADirectoryError, PermissionError):
|
|
318
|
+
os.rmdir(link)
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def make_dir_link(target: os.PathLike | str, link: os.PathLike | str) -> None:
|
|
322
|
+
"""Put a directory link at ``link`` leading to ``target``.
|
|
323
|
+
|
|
324
|
+
A symlink on POSIX. On Windows a junction: it needs no privilege, stores
|
|
325
|
+
an absolute path, and Claude Code reads and writes through it exactly as
|
|
326
|
+
through a symlink (issue #292). ``target`` must be absolute and on a
|
|
327
|
+
local volume; a filesystem without reparse points (FAT, a network
|
|
328
|
+
share) refuses with OSError -- ``can_junction`` says so in advance.
|
|
329
|
+
"""
|
|
330
|
+
if sys.platform == "win32":
|
|
331
|
+
import _winapi # Windows-only stdlib module; private but stable since 3.5
|
|
332
|
+
|
|
333
|
+
_winapi.CreateJunction(os.fspath(target), os.fspath(link))
|
|
334
|
+
else:
|
|
335
|
+
os.symlink(target, link, target_is_directory=True)
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def make_file_link(target: os.PathLike | str, link: os.PathLike | str) -> None:
|
|
339
|
+
"""Put a symlink at ``link`` leading to the file ``target``.
|
|
340
|
+
|
|
341
|
+
The one link cswap makes that needs a privilege on Windows: Developer
|
|
342
|
+
Mode, or an elevated token. ``can_symlink`` says so in advance.
|
|
343
|
+
"""
|
|
344
|
+
os.symlink(target, link)
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
# ``(directory, kind) -> bool``: each probe runs once per process. Module-level
|
|
348
|
+
# so a test can reset it.
|
|
349
|
+
_LINK_PROBES: dict[tuple[str, str], bool] = {}
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def _probe_link(directory: os.PathLike | str, kind: str, make) -> bool:
|
|
353
|
+
key = (os.path.normcase(os.path.abspath(directory)), kind)
|
|
354
|
+
if key not in _LINK_PROBES:
|
|
355
|
+
probe = Path(directory) / f".cswap-link-probe-{os.getpid()}"
|
|
356
|
+
try:
|
|
357
|
+
try:
|
|
358
|
+
os.unlink(probe) # left by a probe that was interrupted
|
|
359
|
+
except OSError:
|
|
360
|
+
pass
|
|
361
|
+
make(probe)
|
|
362
|
+
os.unlink(probe)
|
|
363
|
+
_LINK_PROBES[key] = True
|
|
364
|
+
except OSError:
|
|
365
|
+
try:
|
|
366
|
+
os.unlink(probe)
|
|
367
|
+
except OSError:
|
|
368
|
+
pass
|
|
369
|
+
_LINK_PROBES[key] = False
|
|
370
|
+
return _LINK_PROBES[key]
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
def can_symlink(directory: os.PathLike | str) -> bool:
|
|
374
|
+
"""Whether this process may create a file symlink in ``directory``.
|
|
375
|
+
|
|
376
|
+
Always true off Windows, where trying is the check. On Windows only a
|
|
377
|
+
process with Developer Mode on or an elevated token may, so one dangling
|
|
378
|
+
probe link is made and removed, once per directory per process (the
|
|
379
|
+
answer cannot change within one). Probed in the directory the real link
|
|
380
|
+
goes in, so a filesystem or permission difference cannot say yes here
|
|
381
|
+
and no there.
|
|
382
|
+
"""
|
|
383
|
+
if sys.platform != "win32":
|
|
384
|
+
return True
|
|
385
|
+
return _probe_link(
|
|
386
|
+
directory, "symlink", lambda probe: os.symlink("cswap-link-probe", probe)
|
|
387
|
+
)
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def can_junction(
|
|
391
|
+
directory: os.PathLike | str, target: os.PathLike | str | None = None
|
|
392
|
+
) -> bool:
|
|
393
|
+
"""Whether a directory link from ``directory`` to ``target`` can be made.
|
|
394
|
+
|
|
395
|
+
Always true off Windows (a symlink). A junction needs no privilege but
|
|
396
|
+
does need a volume with reparse points -- NTFS or ReFS; FAT and network
|
|
397
|
+
shares refuse -- and a target Windows accepts, so one is made from
|
|
398
|
+
``directory`` to ``target`` (``directory`` itself when none is given)
|
|
399
|
+
and removed, once per directory and target per process. Pass the parent
|
|
400
|
+
of the real targets, so the probe fails where the real link would.
|
|
401
|
+
"""
|
|
402
|
+
if sys.platform != "win32":
|
|
403
|
+
return True
|
|
404
|
+
to = os.path.abspath(target if target is not None else directory)
|
|
405
|
+
return _probe_link(
|
|
406
|
+
directory,
|
|
407
|
+
f"junction:{os.path.normcase(to)}",
|
|
408
|
+
lambda probe: make_dir_link(to, probe),
|
|
409
|
+
)
|