claude-migrate 0.0.0-stage → 1.0.0

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.
package/cm_ui.py ADDED
@@ -0,0 +1,354 @@
1
+ """Small terminal UI in the style of modern installers (intro, arrow-key menus, spinners, notes).
2
+
3
+ Stdlib only. With a real terminal it is interactive (cbreak mode + ANSI); with pipes it falls back
4
+ to plain numbered prompts, which is also what the tests drive."""
5
+ import contextlib
6
+ import os
7
+ import re
8
+ import select as _select
9
+ import sys
10
+ import threading
11
+
12
+ BAR, START, END = "│", "┌", "└"
13
+ STEP_ACTIVE, STEP_DONE = "◆", "◇"
14
+ RADIO_ON, RADIO_OFF, CHECK_ON, CHECK_OFF = "●", "○", "◼", "◻"
15
+ INFO, OK, WARN, ERR = "●", "✔", "▲", "■"
16
+ _ANSI_RE = re.compile(r"\x1b\[[0-9;?]*[A-Za-z]")
17
+
18
+
19
+ class Cancelled(Exception):
20
+ pass
21
+
22
+
23
+ def _norm(options):
24
+ out = []
25
+ for o in options:
26
+ out.append((o[0], o[1], o[2] if len(o) > 2 else ""))
27
+ return out
28
+
29
+
30
+ def _isatty(f):
31
+ return hasattr(f, "isatty") and f.isatty()
32
+
33
+
34
+ class UI:
35
+ def __init__(self, inp=None, out=None, color=None, interactive=None):
36
+ self.inp = inp or sys.stdin
37
+ self.out = out or sys.stdout
38
+ self.interactive = (_isatty(self.inp) and _isatty(self.out)) if interactive is None else interactive
39
+ if color is None:
40
+ color = _isatty(self.out) and not os.environ.get("NO_COLOR")
41
+ self.color = color
42
+
43
+ # ------------------------------------------------------------ output
44
+ def _w(self, text):
45
+ self.out.write(text)
46
+ self.out.flush()
47
+
48
+ def _c(self, code, s):
49
+ return "\x1b[%sm%s\x1b[0m" % (code, s) if self.color else s
50
+
51
+ def bold(self, s): return self._c("1", s)
52
+ def dim(self, s): return self._c("2", s)
53
+ def cyan(self, s): return self._c("36", s)
54
+ def green(self, s): return self._c("32", s)
55
+ def yellow(self, s): return self._c("33", s)
56
+ def red(self, s): return self._c("31", s)
57
+
58
+ def intro(self, title):
59
+ self._w("\n%s %s\n%s\n" % (self.dim(START), self.bold(title), self.dim(BAR)))
60
+
61
+ def outro(self, msg):
62
+ self._w("%s\n%s %s\n\n" % (self.dim(BAR), self.dim(END), msg))
63
+
64
+ def cancel(self, msg="Cancelled."):
65
+ self._w("%s\n%s %s\n\n" % (self.dim(BAR), self.dim(END), self.red(msg)))
66
+
67
+ def _log(self, sym, msg):
68
+ self._w("%s %s %s\n" % (self.dim(BAR), sym, msg))
69
+
70
+ def info(self, msg): self._log(self.cyan(INFO), msg)
71
+ def success(self, msg): self._log(self.green(OK), msg)
72
+ def warn(self, msg): self._log(self.yellow(WARN), msg)
73
+ def error(self, msg): self._log(self.red(ERR), msg)
74
+
75
+ def note(self, title, lines):
76
+ width = max([len(_ANSI_RE.sub("", l)) for l in lines] + [len(title)]) + 2
77
+ top = "%s %s %s%s" % (self.green(STEP_DONE), self.bold(title), self.dim("─" * (width - len(title) - 1)), self.dim("╮"))
78
+ self._w(top + "\n")
79
+ self._w("%s %s%s\n" % (self.dim(BAR), " " * width, self.dim(BAR)))
80
+ for l in lines:
81
+ pad = width - len(_ANSI_RE.sub("", l))
82
+ self._w("%s %s%s%s\n" % (self.dim(BAR), l, " " * pad, self.dim(BAR)))
83
+ self._w("%s %s%s\n" % (self.dim(BAR), " " * width, self.dim(BAR)))
84
+ self._w(self.dim("├" + "─" * (width + 2) + "╯") + "\n")
85
+
86
+ def _collapsed(self, message, answer):
87
+ self._w("%s %s\n%s %s\n%s\n" % (self.green(STEP_DONE), message, self.dim(BAR), self.dim(answer), self.dim(BAR)))
88
+
89
+ # ------------------------------------------------------------ input plumbing
90
+ def _read_line(self):
91
+ line = self.inp.readline()
92
+ if line == "":
93
+ raise Cancelled()
94
+ return line.rstrip("\n")
95
+
96
+ @contextlib.contextmanager
97
+ def _raw(self):
98
+ import termios
99
+ import tty
100
+ fd = self.inp.fileno()
101
+ old = termios.tcgetattr(fd)
102
+ tty.setcbreak(fd)
103
+ # cbreak keeps ISIG, which would turn Ctrl-C into SIGINT; read it as a key so we can cancel cleanly
104
+ mode = termios.tcgetattr(fd)
105
+ mode[3] &= ~termios.ISIG
106
+ termios.tcsetattr(fd, termios.TCSADRAIN, mode)
107
+ self._w("\x1b[?25l")
108
+ try:
109
+ yield fd
110
+ finally:
111
+ termios.tcsetattr(fd, termios.TCSADRAIN, old)
112
+ self._w("\x1b[?25h")
113
+
114
+ def _key(self, fd):
115
+ b = os.read(fd, 1)
116
+ if b == b"":
117
+ raise Cancelled()
118
+ if b == b"\x1b":
119
+ if _select.select([fd], [], [], 0.05)[0]:
120
+ seq = os.read(fd, 2)
121
+ if seq[:1] in (b"[", b"O"):
122
+ return {b"A": "UP", b"B": "DOWN", b"C": "RIGHT", b"D": "LEFT"}.get(seq[1:2], "ESC")
123
+ return "ESC"
124
+ if b in (b"\r", b"\n"):
125
+ return "ENTER"
126
+ if b in (b"\x03", b"\x04"):
127
+ raise Cancelled()
128
+ if b in (b"\x7f", b"\x08"):
129
+ return "BACKSPACE"
130
+ if b == b" ":
131
+ return "SPACE"
132
+ lead = b[0]
133
+ extra = 3 if lead >= 0xF0 else 2 if lead >= 0xE0 else 1 if lead >= 0xC0 else 0
134
+ if extra:
135
+ b += os.read(fd, extra)
136
+ return b.decode("utf-8", "replace")
137
+
138
+ def _redraw(self, nlines, lines):
139
+ self._w("\x1b[%dA\r\x1b[J" % nlines + "\n".join(lines) + "\n")
140
+
141
+ # ------------------------------------------------------------ prompts
142
+ def select(self, message, options, initial=0):
143
+ opts = _norm(options)
144
+ if not self.interactive:
145
+ return self._select_plain(message, opts, initial)
146
+ cur = initial
147
+ def render():
148
+ ls = ["%s %s" % (self.cyan(STEP_ACTIVE), self.bold(message))]
149
+ for i, (_v, label, hint) in enumerate(opts):
150
+ h = " " + self.dim(hint) if hint else ""
151
+ if i == cur:
152
+ ls.append("%s %s %s%s" % (self.cyan(BAR), self.green(RADIO_ON), label, h))
153
+ else:
154
+ ls.append("%s %s %s" % (self.cyan(BAR), self.dim(RADIO_OFF), self.dim(label)))
155
+ ls.append(self.cyan(END))
156
+ return ls
157
+ with self._raw() as fd:
158
+ lines = render()
159
+ self._w("\n".join(lines) + "\n")
160
+ while True:
161
+ k = self._key(fd)
162
+ if k in ("UP", "k"):
163
+ cur = (cur - 1) % len(opts)
164
+ elif k in ("DOWN", "j"):
165
+ cur = (cur + 1) % len(opts)
166
+ elif k == "ENTER":
167
+ break
168
+ else:
169
+ continue
170
+ new = render()
171
+ self._redraw(len(lines), new)
172
+ lines = new
173
+ self._w("\x1b[%dA\r\x1b[J" % len(lines))
174
+ self._collapsed(message, opts[cur][1])
175
+ return opts[cur][0]
176
+
177
+ def _select_plain(self, message, opts, initial):
178
+ self._w("%s %s\n" % (STEP_ACTIVE, message))
179
+ for i, (_v, label, hint) in enumerate(opts, 1):
180
+ self._w("%s %d) %s%s\n" % (BAR, i, label, " (%s)" % hint if hint else ""))
181
+ while True:
182
+ self._w("%s Choose [%d]: " % (END, initial + 1))
183
+ line = self._read_line().strip()
184
+ if not line:
185
+ return opts[initial][0]
186
+ if line.isdigit() and 1 <= int(line) <= len(opts):
187
+ return opts[int(line) - 1][0]
188
+ self._w("%s Enter a number between 1 and %d.\n" % (BAR, len(opts)))
189
+
190
+ def multiselect(self, message, options, initial=()):
191
+ opts = _norm(options)
192
+ chosen = {o[0] for o in opts if o[0] in set(initial)}
193
+ if not self.interactive:
194
+ return self._multiselect_plain(message, opts, chosen)
195
+ cur = 0
196
+ def render():
197
+ ls = ["%s %s" % (self.cyan(STEP_ACTIVE), self.bold(message))]
198
+ for i, (v, label, hint) in enumerate(opts):
199
+ on = v in chosen
200
+ box = self.green(CHECK_ON) if on else self.dim(CHECK_OFF)
201
+ h = " " + self.dim(hint) if hint else ""
202
+ text = label if i == cur else (label if on else self.dim(label))
203
+ pointer = self.cyan("›") if i == cur else " "
204
+ ls.append("%s %s %s %s%s" % (self.cyan(BAR), pointer, box, text, h))
205
+ ls.append("%s %s" % (self.cyan(BAR), self.dim("space: toggle · a: all · enter: confirm")))
206
+ ls.append(self.cyan(END))
207
+ return ls
208
+ with self._raw() as fd:
209
+ lines = render()
210
+ self._w("\n".join(lines) + "\n")
211
+ while True:
212
+ k = self._key(fd)
213
+ if k in ("UP", "k"):
214
+ cur = (cur - 1) % len(opts)
215
+ elif k in ("DOWN", "j"):
216
+ cur = (cur + 1) % len(opts)
217
+ elif k == "SPACE":
218
+ chosen.symmetric_difference_update({opts[cur][0]})
219
+ elif k == "a":
220
+ chosen = set() if len(chosen) == len(opts) else {o[0] for o in opts}
221
+ elif k == "ENTER":
222
+ break
223
+ else:
224
+ continue
225
+ new = render()
226
+ self._redraw(len(lines), new)
227
+ lines = new
228
+ self._w("\x1b[%dA\r\x1b[J" % len(lines))
229
+ result = [o[0] for o in opts if o[0] in chosen]
230
+ self._collapsed(message, ", ".join(o[1] for o in opts if o[0] in chosen) or "none")
231
+ return result
232
+
233
+ def _multiselect_plain(self, message, opts, chosen):
234
+ self._w("%s %s\n" % (STEP_ACTIVE, message))
235
+ for i, (v, label, hint) in enumerate(opts, 1):
236
+ self._w("%s %d) [%s] %s%s\n" % (BAR, i, "x" if v in chosen else " ", label, " (%s)" % hint if hint else ""))
237
+ while True:
238
+ self._w("%s Numbers separated by commas, 'none', or Enter to keep the [x] ones: " % END)
239
+ line = self._read_line().strip().lower()
240
+ if not line:
241
+ return [o[0] for o in opts if o[0] in chosen]
242
+ if line == "none":
243
+ return []
244
+ try:
245
+ idx = {int(p) for p in line.replace(" ", "").split(",") if p}
246
+ except ValueError:
247
+ idx = set()
248
+ if idx and all(1 <= i <= len(opts) for i in idx):
249
+ return [o[0] for n, o in enumerate(opts, 1) if n in idx]
250
+ self._w("%s Enter numbers between 1 and %d.\n" % (BAR, len(opts)))
251
+
252
+ def confirm(self, message, default=True):
253
+ if self.interactive:
254
+ return self.select(message, [(True, "Yes"), (False, "No")], initial=0 if default else 1)
255
+ self._w("%s %s\n" % (STEP_ACTIVE, message))
256
+ while True:
257
+ self._w("%s %s: " % (END, "[Y/n]" if default else "[y/N]"))
258
+ line = self._read_line().strip().lower()
259
+ if not line:
260
+ return default
261
+ if line in ("y", "yes"):
262
+ return True
263
+ if line in ("n", "no"):
264
+ return False
265
+ self._w("%s Please answer y or n.\n" % BAR)
266
+
267
+ def text(self, message, default="", validate=None):
268
+ while True:
269
+ value = self._text_once(message, default)
270
+ problem = validate(value) if validate else None
271
+ if not problem:
272
+ return value
273
+ self.warn(problem)
274
+
275
+ def _text_once(self, message, default):
276
+ if not self.interactive:
277
+ self._w("%s %s\n" % (STEP_ACTIVE, message))
278
+ self._w("%s %s" % (END, "[%s]: " % default if default else ": "))
279
+ line = self._read_line()
280
+ return line.strip() or default
281
+ buf = []
282
+ def line():
283
+ shown = "".join(buf) or self.dim(default)
284
+ return "\r\x1b[2K%s %s" % (self.cyan(BAR), shown)
285
+ with self._raw() as fd:
286
+ # raw mode first: anything typed once the prompt is visible must not be flushed
287
+ self._w("%s %s\n" % (self.cyan(STEP_ACTIVE), self.bold(message)))
288
+ self._w("\x1b[?25h" + line())
289
+ while True:
290
+ k = self._key(fd)
291
+ if k == "ENTER":
292
+ break
293
+ if k == "BACKSPACE":
294
+ if buf:
295
+ buf.pop()
296
+ elif len(k) >= 1 and k not in ("UP", "DOWN", "LEFT", "RIGHT", "ESC", "SPACE") and k.isprintable():
297
+ buf.append(k)
298
+ elif k == "SPACE":
299
+ buf.append(" ")
300
+ else:
301
+ continue
302
+ self._w(line())
303
+ value = ("".join(buf)).strip() or default
304
+ self._w("\x1b[1A\r\x1b[J")
305
+ self._collapsed(message, value)
306
+ return value
307
+
308
+ # ------------------------------------------------------------ spinner
309
+ def spinner(self, message):
310
+ return _Spinner(self, message)
311
+
312
+
313
+ class _Spinner:
314
+ FRAMES = "◒◐◓◑"
315
+
316
+ def __init__(self, ui, message):
317
+ self.ui, self.message, self._stopped = ui, message, False
318
+ self._thread = None
319
+ self._halt = threading.Event()
320
+
321
+ def __enter__(self):
322
+ if self.ui.interactive:
323
+ self._thread = threading.Thread(target=self._spin, daemon=True)
324
+ self._thread.start()
325
+ else:
326
+ self.ui._w("%s … %s\n" % (BAR, self.message))
327
+ return self
328
+
329
+ def _spin(self):
330
+ i = 0
331
+ while not self._halt.wait(0.1):
332
+ self.ui._w("\r\x1b[2K%s %s" % (self.ui.cyan(self.FRAMES[i % 4]), self.message))
333
+ i += 1
334
+
335
+ def update(self, message):
336
+ self.message = message
337
+
338
+ def stop(self, message=None, ok=True):
339
+ if self._stopped:
340
+ return
341
+ self._stopped = True
342
+ self._halt.set()
343
+ if self._thread:
344
+ self._thread.join()
345
+ sym = self.ui.green(OK) if ok else self.ui.red(ERR)
346
+ self.ui._w("\r\x1b[2K%s %s\n" % (sym, message or self.message) if self.ui.interactive
347
+ else "%s %s %s\n" % (BAR, sym, message or self.message))
348
+
349
+ def __exit__(self, exc_type, exc, tb):
350
+ if exc_type is not None:
351
+ self.stop("%s: Failed" % self.message, ok=False)
352
+ else:
353
+ self.stop()
354
+ return False
package/cm_wizard.py ADDED
@@ -0,0 +1,314 @@
1
+ """Guided, installer-style flow around export and import."""
2
+ import datetime
3
+ import glob
4
+ import json
5
+ import os
6
+ import subprocess
7
+ import textwrap
8
+
9
+ import cm_import
10
+ from cm_bundle import export_bundle, scan_components
11
+ from cm_layout import Layout, discover
12
+ from cm_import import (BundleError, PlanError, RunningError, apply_import, build_plan, default_mapping_path,
13
+ propose_mapping, verify_bundle, zsh_lines_from_bundle, MAPPING_HELP)
14
+ from cm_paths import PathMapper
15
+ from cm_ui import Cancelled
16
+
17
+ MAX_ROWS = 12
18
+ # Start unticked in the export checklist: machine- or account-specific extras you opt into.
19
+ # Everything that is not part of the Claude Code setup itself starts unticked; discovered tools are added to it.
20
+ OPT_IN_COMPONENTS = {"shell", "work_account", "other"}
21
+
22
+
23
+ def human(n):
24
+ n = float(n)
25
+ for unit in ("B", "KB", "MB", "GB"):
26
+ if n < 1024 or unit == "GB":
27
+ return ("%d %s" % (n, unit)) if unit == "B" else ("%.1f %s" % (n, unit))
28
+ n /= 1024.0
29
+
30
+
31
+ def _dir_size(path):
32
+ total = 0
33
+ for dp, _dn, fn in os.walk(path):
34
+ for f in fn:
35
+ try:
36
+ total += os.lstat(os.path.join(dp, f)).st_size
37
+ except OSError:
38
+ pass
39
+ return total
40
+
41
+
42
+ def validate_out_path(p):
43
+ p = os.path.abspath(os.path.expanduser(p))
44
+ if os.path.isdir(p):
45
+ return "That is a directory; give a file name, e.g. %s" % os.path.join(p, "claude-migrate.tar.gz")
46
+ parent = os.path.dirname(p)
47
+ if not os.path.isdir(parent):
48
+ return "Folder does not exist: %s" % parent
49
+ if not os.access(parent, os.W_OK):
50
+ return "Folder is not writable: %s" % parent
51
+ return None
52
+
53
+
54
+ def validate_bundle_path(p):
55
+ p = os.path.expanduser(p)
56
+ return None if os.path.isfile(p) else "File not found: %s" % p
57
+
58
+
59
+ def find_default_bundle(dirs):
60
+ found = []
61
+ for d in dirs:
62
+ found += glob.glob(os.path.join(d, "claude-migrate-*.tar.gz"))
63
+ return max(found, key=os.path.getmtime) if found else None
64
+
65
+
66
+ def common_prefix(paths, fallback):
67
+ split = [[c for c in p.split("/") if c] for p in paths]
68
+ if not split:
69
+ return fallback
70
+ common = []
71
+ for parts in zip(*split):
72
+ if len(set(parts)) != 1:
73
+ break
74
+ common.append(parts[0])
75
+ return "/" + "/".join(common) if common else fallback
76
+
77
+
78
+ def _abs(p, cwd):
79
+ p = os.path.expanduser(p)
80
+ return p if os.path.isabs(p) else os.path.join(cwd, p)
81
+
82
+
83
+ # ---------------------------------------------------------------- export
84
+
85
+ def _component_options(scan, layout):
86
+ opts = []
87
+ for cid, label, hint in layout.components():
88
+ info = scan[cid]
89
+ if not info["files"]:
90
+ continue # nothing there on this Mac, so nothing to choose
91
+ detail = ", ".join(x for x in (hint, human(info["bytes"])) if x)
92
+ opts.append((cid, label, detail))
93
+ return opts
94
+
95
+
96
+ def _export(ui, home, cwd, now):
97
+ layout = discover(home)
98
+ options = _component_options(scan_components(home, layout), layout)
99
+ if not options:
100
+ ui.error("Found nothing to export under %s (no ~/.claude, ~/.claude.json and so on)." % home)
101
+ return 1
102
+ ui.info("Logins and credential files are never exported, and secrets found in settings are masked.")
103
+ include = ui.multiselect("What do you want to export?", options,
104
+ initial=[o[0] for o in options if o[0] not in OPT_IN_COMPONENTS | set(layout.tool_dirs.values())])
105
+ if not include:
106
+ ui.cancel("Nothing selected, so nothing was exported.")
107
+ return 1
108
+ default = os.path.join(cwd, "claude-migrate-%s.tar.gz" % now.date().isoformat())
109
+ out = _abs(ui.text("Where should the bundle be saved?", default=default, validate=validate_out_path), cwd)
110
+ if os.path.exists(out) and not ui.confirm("%s already exists. Overwrite it?" % os.path.basename(out), default=False):
111
+ ui.cancel("Nothing was written.")
112
+ return 1
113
+ with ui.spinner("Collecting your Claude Code setup") as sp:
114
+ rep = export_bundle(home, out, components=include, layout=layout)
115
+ sp.stop("Bundle created")
116
+ ui.note("Bundle", [
117
+ "File %s" % out,
118
+ "Size %s" % human(rep["bytes"]),
119
+ "Files %d" % rep["files"],
120
+ "Projects %d" % rep["projects"],
121
+ "Included %d of %d components" % (len(rep["components"]), len(options)),
122
+ ])
123
+ if rep["masked"]:
124
+ ui.warn("%d secret value(s) were masked. Re-enter them on the new Mac:" % len(rep["masked"]))
125
+ rows = rep["masked"][:MAX_ROWS]
126
+ if len(rep["masked"]) > MAX_ROWS:
127
+ rows.append("... and %d more" % (len(rep["masked"]) - MAX_ROWS))
128
+ ui.note("Masked values", rows)
129
+ for rel in rep["excluded_sensitive"]:
130
+ ui.warn("Left out (credential file): %s" % rel)
131
+ for w in rep["warnings"][:MAX_ROWS]:
132
+ ui.warn(w)
133
+ ui.outro("Copy %s to your other Mac and run: claude-migrate" % os.path.basename(out))
134
+ return 0
135
+
136
+
137
+ # ---------------------------------------------------------------- import
138
+
139
+ def _plan_lines(plan):
140
+ lines = []
141
+ for p in plan["projects"][:MAX_ROWS]:
142
+ lines.append("%s %s -> %s" % ("ok " if p["exists"] else "warn", p["old"], p["new"]))
143
+ if len(plan["projects"]) > MAX_ROWS:
144
+ lines.append("... and %d more projects" % (len(plan["projects"]) - MAX_ROWS))
145
+ renamed = sum(1 for f in plan["folders"] if f["old_folder"] != f["new_folder"])
146
+ lines.append("History folders: %d (%d renamed)" % (len(plan["folders"]), renamed))
147
+ return lines
148
+
149
+
150
+ def _save_mapping(path, manifest, mapper, home):
151
+ preview = {p: mapper.map(p) for p in manifest.get("projects", [])}
152
+ data = {"_help": MAPPING_HELP, "default": mapper.default, "projects": mapper.projects, "_preview": preview}
153
+ with open(path, "w") as f:
154
+ json.dump(data, f, indent=2)
155
+
156
+
157
+ def _edit_project(ui, plan, overrides):
158
+ rows = [(p["old"], "%s -> %s" % (p["old"], p["new"])) for p in plan["projects"]]
159
+ old = ui.select("Which project do you want to move?", rows)
160
+ new = ui.text("New location for %s" % old,
161
+ default=overrides.get(old, next(p["new"] for p in plan["projects"] if p["old"] == old)),
162
+ validate=lambda s: None if s.startswith("/") else "Use an absolute path starting with /")
163
+ overrides[old] = new
164
+
165
+
166
+ def _contents(manifest):
167
+ comps = manifest.get("components")
168
+ if comps is None: # bundles from before components existed
169
+ return "everything except history" if manifest.get("options", {}).get("no_history") else "everything"
170
+ labels = {c[0]: c[1] for c in Layout.from_manifest(manifest).components()}
171
+ return ", ".join(labels.get(c, c) for c in comps) or "nothing"
172
+
173
+
174
+ def _import(ui, home, cwd):
175
+ dl = [cwd, os.path.expanduser("~/Downloads"), os.path.expanduser("~/Desktop")]
176
+ bundle = _abs(ui.text("Path to the bundle file", default=find_default_bundle(dl) or "",
177
+ validate=lambda p: validate_bundle_path(_abs(p, cwd))), cwd)
178
+ try:
179
+ with ui.spinner("Verifying bundle") as sp:
180
+ manifest = verify_bundle(bundle)
181
+ sp.stop("Bundle verified")
182
+ except BundleError as e:
183
+ ui.error(str(e))
184
+ return 1
185
+ contents = textwrap.wrap(_contents(manifest), 58) or ["nothing"]
186
+ ui.note("Bundle", [
187
+ "Created %s" % manifest.get("created", "?"),
188
+ "From %s (%s)" % (manifest["source_home"], manifest.get("username", "?")),
189
+ "To %s" % home,
190
+ "Files %d" % len(manifest.get("files", {})),
191
+ "Projects %d" % len(manifest.get("projects", [])),
192
+ "Contains %s" % contents[0],
193
+ ] + [" %s" % c for c in contents[1:]])
194
+ ui.warn("Only import bundles you made yourself. A bundle carries hooks, slash commands and MCP server "
195
+ "commands, and those run code on this Mac.")
196
+ src_home = manifest["source_home"]
197
+ if os.path.normpath(src_home) != os.path.normpath(home):
198
+ ui.info("Home folder changes %s -> %s; everything inside it is re-pointed automatically." % (src_home, home))
199
+
200
+ layout = ui.select("Where do your projects live on this Mac?", [
201
+ ("same", "In the same places as before", "relative to this Mac's home folder"),
202
+ ("prefix", "Moved under a different folder", "e.g. ~/workspace -> ~/dev"),
203
+ ])
204
+ default = propose_mapping(manifest, home)["default"]
205
+ if layout == "prefix":
206
+ old_prefix = ui.text("Old folder (on the previous Mac)",
207
+ default=common_prefix(manifest.get("projects", []), src_home),
208
+ validate=lambda s: None if s.startswith("/") else "Use an absolute path starting with /")
209
+ mapped = PathMapper(default, {}).map(old_prefix)
210
+ new_prefix = ui.text("New folder (on this Mac)", default=mapped,
211
+ validate=lambda s: None if s.startswith("/") else "Use an absolute path starting with /")
212
+ default = dict(default)
213
+ default[old_prefix] = new_prefix
214
+ overrides = {}
215
+ mapping_path = default_mapping_path(bundle)
216
+
217
+ while True:
218
+ mapper = PathMapper(default, overrides)
219
+ plan = build_plan(manifest, mapper, home)
220
+ ui.note("Plan", _plan_lines(plan))
221
+ for e in plan["errors"]:
222
+ ui.error(e)
223
+ menu = [("edit", "Change one project's location")]
224
+ if not plan["errors"]:
225
+ menu.insert(0, ("go", "Looks good, continue"))
226
+ menu += [("file", "Edit the whole mapping file in my editor"), ("cancel", "Cancel")]
227
+ choice = ui.select("Does this look right?", menu)
228
+ if choice == "go":
229
+ break
230
+ if choice == "cancel":
231
+ ui.cancel("Nothing was changed.")
232
+ return 1
233
+ if choice == "edit":
234
+ _edit_project(ui, plan, overrides)
235
+ else:
236
+ _save_mapping(mapping_path, manifest, mapper, home)
237
+ subprocess.call([os.environ.get("VISUAL") or os.environ.get("EDITOR") or "vi", mapping_path])
238
+ edited = PathMapper.from_file(mapping_path)
239
+ default, overrides = edited.default, edited.projects
240
+ _save_mapping(mapping_path, manifest, mapper, home)
241
+ missing = [p for p in plan["projects"] if not p["exists"]]
242
+ if missing:
243
+ ui.warn("%d project folder(s) don't exist on this Mac yet. Their history is still imported." % len(missing))
244
+
245
+ extras = ui.multiselect("Extras", [("zsh", "Add the Claude aliases to ~/.zshrc", "off unless you tick it")],
246
+ initial=[])
247
+ if "zsh" in extras:
248
+ safe_lines, rejected = zsh_lines_from_bundle(bundle)
249
+ if safe_lines:
250
+ ui.note("Lines that will be added to ~/.zshrc", safe_lines)
251
+ else:
252
+ ui.info("The bundle has no shell lines to add.")
253
+ for l in rejected:
254
+ ui.warn("Will not add this line (not a plain alias/export/source): %r" % l[:80])
255
+ force = False
256
+ while cm_import.is_claude_running():
257
+ action = ui.select("Claude Code is running", [
258
+ ("retry", "I've quit it, check again"), ("force", "Continue anyway"), ("cancel", "Cancel")])
259
+ if action == "cancel":
260
+ ui.cancel("Nothing was changed.")
261
+ return 1
262
+ if action == "force":
263
+ force = True
264
+ break
265
+ ui.note("Ready to import", [
266
+ "%d projects, %d history folders" % (len(plan["projects"]), len(plan["folders"])),
267
+ "Target %s" % home,
268
+ "Existing files that differ are backed up first.",
269
+ ])
270
+ if not ui.confirm("Import now?", default=True):
271
+ ui.cancel("Nothing was changed.")
272
+ return 1
273
+ try:
274
+ with ui.spinner("Importing") as sp:
275
+ rep = apply_import(bundle, mapper, home, force=force, zsh="zsh" in extras)
276
+ sp.stop("Import finished")
277
+ except (PlanError, RunningError, BundleError) as e:
278
+ ui.error(str(e))
279
+ return 1
280
+ ui.success("%d file(s) written" % rep["written"])
281
+ if rep["backup"]:
282
+ ui.info("Replaced files were backed up to %s" % rep["backup"])
283
+ for w in rep["warnings"][:6]:
284
+ ui.warn(w)
285
+ if len(rep["warnings"]) > 6:
286
+ ui.warn("... and %d more warnings" % (len(rep["warnings"]) - 6))
287
+ for p in rep["problems"]:
288
+ ui.error(p)
289
+ if rep["zsh_lines"] and not rep["zsh_installed"]:
290
+ ui.note("Shell aliases (not installed)", rep["zsh_lines"])
291
+ ui.note("Next steps", [
292
+ "1. Run `claude` and sign in with /login (logins are never copied).",
293
+ "2. Re-enter any masked API keys.",
294
+ "3. Open a project and use /resume to check your history.",
295
+ ])
296
+ ui.outro("Problems found, see above." if rep["problems"] else "Your Claude Code setup is ready.")
297
+ return 1 if rep["problems"] else 0
298
+
299
+
300
+ # ---------------------------------------------------------------- entry
301
+
302
+ def run(ui, home, now=None, cwd=None):
303
+ now = now or datetime.datetime.now()
304
+ cwd = cwd or os.getcwd()
305
+ ui.intro("Claude Migrate")
306
+ try:
307
+ mode = ui.select("What do you want to do?", [
308
+ ("export", "Export this Mac's Claude Code setup", "creates a bundle to carry over"),
309
+ ("import", "Import a bundle onto this Mac", "from a previous export"),
310
+ ])
311
+ return _export(ui, home, cwd, now) if mode == "export" else _import(ui, home, cwd)
312
+ except Cancelled:
313
+ ui.cancel("Cancelled. Nothing further was changed.")
314
+ return 130