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
claude_swap/pace.py
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
"""Weekly usage pace (issue #125).
|
|
2
|
+
|
|
3
|
+
A weekly window is "ahead of pace" when the account has used more of it than
|
|
4
|
+
the fraction of the weekly reset cycle that has elapsed so far — e.g. 40% used
|
|
5
|
+
at the 20%-through-the-week mark. Applies only to weekly windows (``seven_day``
|
|
6
|
+
and every ``scoped`` per-model window); the 5h window is excluded because it
|
|
7
|
+
resets too fast for pace to mean anything (it starts "ahead of pace" almost by
|
|
8
|
+
definition early in the window, and the store's poll floor of ~3 minutes,
|
|
9
|
+
drifting to ~10 minutes when idle, is a large fraction of a 5h window but
|
|
10
|
+
negligible against a week — see issue #125 discussion).
|
|
11
|
+
|
|
12
|
+
``compute_pace`` is a pure function: it consumes an already-fetched window
|
|
13
|
+
dict and the snapshot's ``fetched_at``, never fetches anything itself, and has
|
|
14
|
+
no influence on poll cadence (that stays entirely in ``poll_policy``). Elapsed
|
|
15
|
+
time is measured against ``fetched_at`` rather than wall-clock ``now()``, so a
|
|
16
|
+
snapshot served stale (last-good data re-served after a failed refetch) is
|
|
17
|
+
evaluated against the clock it was actually measured at.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
from dataclasses import dataclass
|
|
23
|
+
from datetime import datetime
|
|
24
|
+
|
|
25
|
+
# Weekly windows reset on a fixed 7-day cadence.
|
|
26
|
+
WEEKLY_PERIOD_S = 7 * 86400.0
|
|
27
|
+
|
|
28
|
+
# Suppress the marker for this long after a weekly reset. Right after reset,
|
|
29
|
+
# elapsed is tiny so `expected_pct` is near zero and almost any usage reads as
|
|
30
|
+
# "far ahead" — a false positive, not a genuine pace warning. A plain
|
|
31
|
+
# `elapsed == 0` guard isn't enough since a snapshot fetched shortly after
|
|
32
|
+
# reset already has nonzero (if small) elapsed time.
|
|
33
|
+
SUPPRESS_AFTER_RESET_S = 24 * 3600.0
|
|
34
|
+
|
|
35
|
+
# Minimum (actual - expected) percentage-point gap before showing a marker.
|
|
36
|
+
# Below this, "ahead of pace" is within normal usage variance and would just
|
|
37
|
+
# add noise to already-dense usage rows. A flat gap also means the marker
|
|
38
|
+
# cannot fire once expected passes (100 - threshold) — the last ~day of the
|
|
39
|
+
# week — since pct tops out at 100. Deliberate: by then the percentage itself
|
|
40
|
+
# tells the story, and a maxed window is the switcher's job anyway.
|
|
41
|
+
AHEAD_THRESHOLD_PCT = 15.0
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass(frozen=True)
|
|
45
|
+
class PaceResult:
|
|
46
|
+
"""One weekly window's pace at the moment its snapshot was fetched."""
|
|
47
|
+
|
|
48
|
+
expected_pct: float # % of the week's budget "on schedule" usage would be at
|
|
49
|
+
actual_pct: float # the window's actual pct
|
|
50
|
+
elapsed_s: float # time since this window's current cycle started
|
|
51
|
+
period_s: float # the window's full cycle length (e.g. 7 days)
|
|
52
|
+
ahead: bool # actual_pct - expected_pct >= the "meaningfully ahead" threshold
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _resets_at_ts(resets_at: object) -> float | None:
|
|
56
|
+
"""POSIX timestamp of a ``resets_at`` ISO string, or None if missing/unparseable."""
|
|
57
|
+
if not isinstance(resets_at, str):
|
|
58
|
+
return None
|
|
59
|
+
try:
|
|
60
|
+
return datetime.fromisoformat(resets_at).timestamp()
|
|
61
|
+
except ValueError:
|
|
62
|
+
return None
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def compute_pace(
|
|
66
|
+
window: dict | None,
|
|
67
|
+
*,
|
|
68
|
+
fetched_at: float | None,
|
|
69
|
+
period_s: float = WEEKLY_PERIOD_S,
|
|
70
|
+
suppress_after_reset_s: float = SUPPRESS_AFTER_RESET_S,
|
|
71
|
+
ahead_threshold_pct: float = AHEAD_THRESHOLD_PCT,
|
|
72
|
+
) -> PaceResult | None:
|
|
73
|
+
"""Pace for one weekly usage window, or None when pace isn't computable/meaningful.
|
|
74
|
+
|
|
75
|
+
``window`` is a raw window dict (``{"pct": ..., "resets_at": ...}``) as
|
|
76
|
+
stored in ``UsageEntry.last_good`` — the *next* reset, not the current
|
|
77
|
+
window's start, since that's the only timestamp the usage API provides.
|
|
78
|
+
The current window's start is derived by rolling ``resets_at`` by whole
|
|
79
|
+
``period_s`` increments until it lands at or before ``fetched_at``; this
|
|
80
|
+
is correct however many cycles old ``resets_at`` is, including a
|
|
81
|
+
not-yet-rolled-forward stale value.
|
|
82
|
+
|
|
83
|
+
Returns None when: the window is missing/unparseable, ``pct``/``resets_at``
|
|
84
|
+
aren't usable, or elapsed time since the window's start is inside
|
|
85
|
+
``suppress_after_reset_s``.
|
|
86
|
+
"""
|
|
87
|
+
if not isinstance(window, dict) or fetched_at is None:
|
|
88
|
+
return None
|
|
89
|
+
pct = window.get("pct")
|
|
90
|
+
if not isinstance(pct, (int, float)):
|
|
91
|
+
return None
|
|
92
|
+
next_reset = _resets_at_ts(window.get("resets_at"))
|
|
93
|
+
if next_reset is None:
|
|
94
|
+
return None
|
|
95
|
+
|
|
96
|
+
# (next_reset - fetched_at) mod period_s == time remaining until the next
|
|
97
|
+
# reset, folded into [0, period_s). period_s minus that is elapsed time
|
|
98
|
+
# since the current window started — works regardless of how many whole
|
|
99
|
+
# cycles next_reset is ahead of or behind fetched_at.
|
|
100
|
+
remaining = (next_reset - fetched_at) % period_s
|
|
101
|
+
elapsed = 0.0 if remaining == 0 else period_s - remaining
|
|
102
|
+
|
|
103
|
+
if elapsed < suppress_after_reset_s:
|
|
104
|
+
return None
|
|
105
|
+
|
|
106
|
+
expected_pct = min(100.0, (elapsed / period_s) * 100.0)
|
|
107
|
+
ahead = (float(pct) - expected_pct) >= ahead_threshold_pct
|
|
108
|
+
return PaceResult(
|
|
109
|
+
expected_pct=expected_pct,
|
|
110
|
+
actual_pct=float(pct),
|
|
111
|
+
elapsed_s=elapsed,
|
|
112
|
+
period_s=period_s,
|
|
113
|
+
ahead=ahead,
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def projected_exhaustion_ts(pace: PaceResult, *, fetched_at: float) -> float | None:
|
|
118
|
+
"""Linear-projection ETA (POSIX timestamp) for when usage would hit 100%.
|
|
119
|
+
|
|
120
|
+
JSON-only per issue #125: the projection assumes a constant burn rate,
|
|
121
|
+
which has wide error bars against real, bursty usage, and would look
|
|
122
|
+
falsely precise if surfaced in the UI. Returns None when there's no
|
|
123
|
+
measurable rate (no elapsed time, or usage isn't climbing).
|
|
124
|
+
"""
|
|
125
|
+
if pace.elapsed_s <= 0 or pace.actual_pct <= 0:
|
|
126
|
+
return None
|
|
127
|
+
rate_pct_per_s = pace.actual_pct / pace.elapsed_s
|
|
128
|
+
if rate_pct_per_s <= 0:
|
|
129
|
+
return None
|
|
130
|
+
remaining_pct = 100.0 - pace.actual_pct
|
|
131
|
+
if remaining_pct <= 0:
|
|
132
|
+
return fetched_at
|
|
133
|
+
return fetched_at + remaining_pct / rate_pct_per_s
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def will_last_to_reset(pace: PaceResult) -> bool | None:
|
|
137
|
+
"""Whether, at the current burn rate, usage stays under 100% through reset.
|
|
138
|
+
|
|
139
|
+
JSON-only (like ``projected_exhaustion_ts``): a boolean answer to "should I
|
|
140
|
+
worry" is safe to expose even though it's built from the same linear-rate
|
|
141
|
+
assumption, but it's still a projection with the same wide error bars
|
|
142
|
+
against bursty real usage, so it stays out of every human-facing surface.
|
|
143
|
+
Returns None when there's no measurable rate to extrapolate from.
|
|
144
|
+
|
|
145
|
+
Relationship to the ``(ahead)`` marker: at a constant rate the projected
|
|
146
|
+
total is ``100 × actual/expected``, so this is False exactly when the
|
|
147
|
+
window is over expected *at all* — the marker's signal with no threshold.
|
|
148
|
+
A window can therefore report ``willLastToReset: false`` while showing no
|
|
149
|
+
marker: the marker additionally requires being ``AHEAD_THRESHOLD_PCT``
|
|
150
|
+
over expected. Deliberate — scripts get the sensitive signal, the UI gets
|
|
151
|
+
the noise-gated one.
|
|
152
|
+
"""
|
|
153
|
+
if pace.actual_pct <= 0:
|
|
154
|
+
return True # no usage yet — nothing to run out of before reset
|
|
155
|
+
if pace.elapsed_s <= 0:
|
|
156
|
+
return None
|
|
157
|
+
rate_pct_per_s = pace.actual_pct / pace.elapsed_s
|
|
158
|
+
if rate_pct_per_s <= 0:
|
|
159
|
+
return None
|
|
160
|
+
projected_total_pct = pace.actual_pct + rate_pct_per_s * (pace.period_s - pace.elapsed_s)
|
|
161
|
+
return projected_total_pct <= 100.0
|
claude_swap/paths.py
ADDED
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
"""Path resolution for Claude Code config and credential files.
|
|
2
|
+
|
|
3
|
+
Mirrors claude-code's own resolution so cswap reads and writes the same files
|
|
4
|
+
claude-code does. Key rules (from claude-code source):
|
|
5
|
+
|
|
6
|
+
- Config home: ``CLAUDE_CONFIG_DIR`` if set, else ``~/.claude``.
|
|
7
|
+
- Global config: ``<config_home>/.config.json`` (legacy) if it is a regular
|
|
8
|
+
file that is non-empty, or empty and writable with no ``.claude.json`` (the
|
|
9
|
+
rule of claude-code 2.1.299), otherwise
|
|
10
|
+
``(CLAUDE_CONFIG_DIR || $HOME)/.claude.json``. Note the asymmetry:
|
|
11
|
+
``.claude.json`` sits at homedir by default, not inside ``.claude/``.
|
|
12
|
+
- Credentials: ``.credentials.json`` in the secure-storage directory, which is
|
|
13
|
+
``CLAUDE_SECURESTORAGE_CONFIG_DIR`` when that is defined (empty means
|
|
14
|
+
``~/.claude``) and the config home otherwise.
|
|
15
|
+
|
|
16
|
+
Also resolves the cswap backup root, which on Linux/WSL follows the XDG Base
|
|
17
|
+
Directory Specification (``$XDG_DATA_HOME/claude-swap``) and falls back to the
|
|
18
|
+
legacy ``~/.claude-swap-backup`` on macOS/Windows.
|
|
19
|
+
|
|
20
|
+
References:
|
|
21
|
+
- claude-code utils/env.ts getGlobalClaudeFile
|
|
22
|
+
- claude-code utils/secureStorage/plainTextStorage.ts getStoragePath
|
|
23
|
+
- XDG Base Directory Specification: https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
from __future__ import annotations
|
|
27
|
+
|
|
28
|
+
import os
|
|
29
|
+
import shutil
|
|
30
|
+
import stat
|
|
31
|
+
from pathlib import Path
|
|
32
|
+
|
|
33
|
+
from claude_swap.exceptions import MigrationError
|
|
34
|
+
from claude_swap.models import Platform
|
|
35
|
+
|
|
36
|
+
LEGACY_BACKUP_DIRNAME = ".claude-swap-backup"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def get_claude_config_home() -> Path:
|
|
40
|
+
"""Return the Claude config home directory (CLAUDE_CONFIG_DIR or ~/.claude)."""
|
|
41
|
+
env = os.environ.get("CLAUDE_CONFIG_DIR")
|
|
42
|
+
if env:
|
|
43
|
+
return Path(env)
|
|
44
|
+
return Path.home() / ".claude"
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _pick_global_config(legacy: Path, global_cfg: Path) -> Path:
|
|
48
|
+
"""Claude Code 2.1.299's choice between ``.config.json`` and ``.claude.json``."""
|
|
49
|
+
try:
|
|
50
|
+
st = legacy.stat() # follows symlinks; an error makes the global file win
|
|
51
|
+
except OSError:
|
|
52
|
+
return global_cfg
|
|
53
|
+
if stat.S_ISREG(st.st_mode) and (
|
|
54
|
+
st.st_size > 0 or (st.st_mode & 0o222 and not os.path.exists(global_cfg))
|
|
55
|
+
):
|
|
56
|
+
return legacy
|
|
57
|
+
return global_cfg
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def get_global_config_path() -> Path:
|
|
61
|
+
"""Return the path to the global Claude config file.
|
|
62
|
+
|
|
63
|
+
Returns the legacy ``<config_home>/.config.json`` if Claude Code would use
|
|
64
|
+
it (see :func:`_pick_global_config`), else
|
|
65
|
+
``(CLAUDE_CONFIG_DIR || $HOME)/.claude.json``.
|
|
66
|
+
"""
|
|
67
|
+
env = os.environ.get("CLAUDE_CONFIG_DIR")
|
|
68
|
+
base = Path(env) if env else Path.home()
|
|
69
|
+
return _pick_global_config(
|
|
70
|
+
get_claude_config_home() / ".config.json", base / ".claude.json"
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def get_default_claude_config_home() -> Path:
|
|
75
|
+
"""Return the *default* profile's config home, ignoring ``CLAUDE_CONFIG_DIR``.
|
|
76
|
+
|
|
77
|
+
``_read_capture_credentials`` has to tell an env var that names the default
|
|
78
|
+
profile from one that names another, since only the former's credential is
|
|
79
|
+
the active store's.
|
|
80
|
+
"""
|
|
81
|
+
return Path.home() / ".claude"
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def get_default_global_config_path() -> Path:
|
|
85
|
+
"""Return the global config path of the *default* profile.
|
|
86
|
+
|
|
87
|
+
Same legacy fallback as :func:`get_global_config_path`, but deliberately
|
|
88
|
+
ignores ``CLAUDE_CONFIG_DIR``: callers that mirror the user's real profile
|
|
89
|
+
(session sharing) must not source from another session when invoked from
|
|
90
|
+
inside one.
|
|
91
|
+
"""
|
|
92
|
+
return _pick_global_config(
|
|
93
|
+
get_default_claude_config_home() / ".config.json", Path.home() / ".claude.json"
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def get_credentials_path() -> Path:
|
|
98
|
+
"""Return the path to the Claude credentials file.
|
|
99
|
+
|
|
100
|
+
Claude Code (2.1.322) keeps the file in its secure-storage directory:
|
|
101
|
+
``CLAUDE_SECURESTORAGE_CONFIG_DIR`` when that is defined, where an empty
|
|
102
|
+
value selects the default profile's ``~/.claude``, and the config home
|
|
103
|
+
otherwise. Its Keychain item is named from the same variable (see
|
|
104
|
+
``credentials._active_oauth_keychain_services``), so the file and the item
|
|
105
|
+
always belong to one profile.
|
|
106
|
+
"""
|
|
107
|
+
secure_env = os.environ.get("CLAUDE_SECURESTORAGE_CONFIG_DIR")
|
|
108
|
+
if secure_env is None:
|
|
109
|
+
return get_claude_config_home() / ".credentials.json"
|
|
110
|
+
secure_home = Path(secure_env) if secure_env else get_default_claude_config_home()
|
|
111
|
+
return secure_home / ".credentials.json"
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def get_legacy_backup_root() -> Path:
|
|
115
|
+
"""Return the legacy (pre-XDG) backup root: ``~/.claude-swap-backup``."""
|
|
116
|
+
return Path.home() / LEGACY_BACKUP_DIRNAME
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def get_backup_root() -> Path:
|
|
120
|
+
"""Return the cswap backup root for the current platform.
|
|
121
|
+
|
|
122
|
+
Linux/WSL: ``$XDG_DATA_HOME/claude-swap`` (default ``~/.local/share/claude-swap``).
|
|
123
|
+
macOS/Windows/unknown: ``~/.claude-swap-backup`` (legacy layout).
|
|
124
|
+
|
|
125
|
+
Per the XDG spec, ``$XDG_DATA_HOME`` is ignored when unset, empty, or
|
|
126
|
+
non-absolute. A leading ``~`` is expanded so values like ``~/data`` set
|
|
127
|
+
via systemd unit files or Dockerfiles (which don't get shell expansion)
|
|
128
|
+
still work.
|
|
129
|
+
"""
|
|
130
|
+
if Platform.detect() in (Platform.LINUX, Platform.WSL):
|
|
131
|
+
xdg = os.environ.get("XDG_DATA_HOME", "")
|
|
132
|
+
if xdg:
|
|
133
|
+
xdg_path = Path(os.path.expanduser(xdg))
|
|
134
|
+
if xdg_path.is_absolute():
|
|
135
|
+
return xdg_path / "claude-swap"
|
|
136
|
+
return Path.home() / ".local" / "share" / "claude-swap"
|
|
137
|
+
return get_legacy_backup_root()
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
# Names that any prior cswap run may have created in the backup root without
|
|
141
|
+
# user data being present (logger output, update-check + usage cache). The
|
|
142
|
+
# migration treats a target containing only these as effectively empty, since
|
|
143
|
+
# wiping them loses no real state.
|
|
144
|
+
_THROWAWAY_NAMES = {"cache"}
|
|
145
|
+
_THROWAWAY_PREFIXES = ("claude-swap.log",)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _target_has_meaningful_data(target: Path) -> bool:
|
|
149
|
+
"""Return True if target contains anything beyond throwaway artifacts."""
|
|
150
|
+
try:
|
|
151
|
+
entries = list(target.iterdir())
|
|
152
|
+
except (FileNotFoundError, NotADirectoryError):
|
|
153
|
+
return False
|
|
154
|
+
for entry in entries:
|
|
155
|
+
if entry.name in _THROWAWAY_NAMES:
|
|
156
|
+
continue
|
|
157
|
+
if any(entry.name.startswith(p) for p in _THROWAWAY_PREFIXES):
|
|
158
|
+
continue
|
|
159
|
+
return True
|
|
160
|
+
return False
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _wipe_throwaway_artifacts(target: Path) -> None:
|
|
164
|
+
"""Remove cache dir / log files so shutil.move can land on target."""
|
|
165
|
+
try:
|
|
166
|
+
entries = list(target.iterdir())
|
|
167
|
+
except (FileNotFoundError, NotADirectoryError):
|
|
168
|
+
return
|
|
169
|
+
for entry in entries:
|
|
170
|
+
if entry.is_dir() and not entry.is_symlink():
|
|
171
|
+
shutil.rmtree(entry)
|
|
172
|
+
else:
|
|
173
|
+
entry.unlink()
|
|
174
|
+
target.rmdir()
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def migration_flag_for(target: Path) -> Path:
|
|
178
|
+
"""The interrupted-migration flag for ``target``: a SIBLING of the
|
|
179
|
+
backup root, not a child.
|
|
180
|
+
|
|
181
|
+
Spell it here only -- this flag is what turns the collision refusal
|
|
182
|
+
below into an rmtree of the destination, and a second copy drifts.
|
|
183
|
+
"""
|
|
184
|
+
return target.parent / f".{target.name}.migrating"
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def migrate_legacy_backup_dir(target: Path) -> bool:
|
|
188
|
+
"""Move the legacy backup directory to ``target`` if needed.
|
|
189
|
+
|
|
190
|
+
Uses ``shutil.move`` (atomic ``rename`` on same FS; copy + unlink across
|
|
191
|
+
FS) guarded by a ``<target>.migrating`` flag file. Touching the flag
|
|
192
|
+
*before* the move and removing it *after* lets us tell an interrupted
|
|
193
|
+
migration apart from a foreign collision on the next run:
|
|
194
|
+
|
|
195
|
+
* Flag present, legacy still there → resume (discard any partial target
|
|
196
|
+
and retry).
|
|
197
|
+
* Flag present, legacy gone → previous run completed but didn't get to
|
|
198
|
+
clean the flag; just unlink it.
|
|
199
|
+
* No flag, both paths exist → genuine collision, refuse — *unless* the
|
|
200
|
+
target only holds throwaway artifacts (cache/, log files) that any
|
|
201
|
+
prior cswap run may have laid down before legacy reappeared (e.g.
|
|
202
|
+
first run on a fresh box, then legacy synced in from another machine).
|
|
203
|
+
In that case wipe the artifacts and migrate normally.
|
|
204
|
+
|
|
205
|
+
Returns:
|
|
206
|
+
True if the move ran in this call, False if it was a no-op.
|
|
207
|
+
|
|
208
|
+
Raises:
|
|
209
|
+
MigrationError: on a genuine collision, or when ``shutil.move`` fails.
|
|
210
|
+
"""
|
|
211
|
+
legacy = get_legacy_backup_root()
|
|
212
|
+
try:
|
|
213
|
+
same_path = legacy.resolve() == target.resolve()
|
|
214
|
+
except OSError:
|
|
215
|
+
same_path = legacy == target
|
|
216
|
+
if same_path:
|
|
217
|
+
return False
|
|
218
|
+
|
|
219
|
+
flag = migration_flag_for(target)
|
|
220
|
+
|
|
221
|
+
if not legacy.exists():
|
|
222
|
+
# Successful prior run that died before unlinking the flag.
|
|
223
|
+
flag.unlink(missing_ok=True)
|
|
224
|
+
return False
|
|
225
|
+
|
|
226
|
+
try:
|
|
227
|
+
if flag.exists():
|
|
228
|
+
# Prior run was interrupted before completion. Discard any
|
|
229
|
+
# (potentially partial) target and retry the move from legacy.
|
|
230
|
+
if target.exists():
|
|
231
|
+
shutil.rmtree(target)
|
|
232
|
+
elif target.exists():
|
|
233
|
+
if _target_has_meaningful_data(target):
|
|
234
|
+
raise MigrationError(
|
|
235
|
+
f"Both legacy ({legacy}) and new ({target}) backup paths exist. "
|
|
236
|
+
f"Refusing to merge or overwrite — inspect both and remove the "
|
|
237
|
+
f"stale one manually before re-running."
|
|
238
|
+
)
|
|
239
|
+
_wipe_throwaway_artifacts(target)
|
|
240
|
+
|
|
241
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
242
|
+
flag.touch()
|
|
243
|
+
shutil.move(legacy, target)
|
|
244
|
+
flag.unlink()
|
|
245
|
+
except OSError as exc:
|
|
246
|
+
raise MigrationError(
|
|
247
|
+
f"Migration of {legacy} → {target} failed: {exc}"
|
|
248
|
+
) from exc
|
|
249
|
+
|
|
250
|
+
return True
|