gabriel / muse public
mv.py python
608 lines 20.9 KB
Raw
sha256:9a3bb190de5a18742792038aa709072a582ada8b223d5dfa4f72c70831ec3ba3 docs: revert migrate hub-scoping/domain-integers rows from … Sonnet 5 23 hours ago
1 """``muse mv`` — move a tracked file or directory, staging the rename atomically.
2
3 Moves *source* to *dest* on disk and records the change in the stage.
4 For files: source tombstoned as ``"D"``, destination staged as ``"A"``
5 with the same object ID. For directories: all contained files are
6 restaged under the new path; empty-directory sentinels are relocated.
7
8 Special cases
9 -------------
10 - **Directory source**: detected automatically when the source path is a
11 tracked directory (has committed files under it, or is a committed empty
12 directory, or is a staged-as-new empty directory).
13 - **Move into directory**: if *dest* ends with ``/`` or is an existing
14 directory on disk, the source name is appended (``muse mv a.py lib/`` →
15 ``lib/a.py``; ``muse mv src/ lib/`` → ``lib/src/``).
16 - **Staged-only source**: a file staged as ``"A"`` but never committed is
17 moved by replacing its stage entry rather than creating a ``"D"`` tombstone.
18 - **``--force``**: bypasses the "destination exists on disk" safety check.
19
20 JSON schema (``--json``)::
21
22 {
23 "status": "moved" | "dry_run",
24 "source": "old/path.py" | "old/dir/",
25 "dest": "new/path.py" | "new/dir/",
26 "object_id": "sha256:<64-char hex>" | "",
27 "dry_run": true | false,
28 "duration_ms": 1.2,
29 "exit_code": 0
30 }
31
32 Exit codes::
33
34 0 — success (file/dir moved or would be moved in dry-run)
35 1 — user error: source not tracked, dest exists, path outside repo
36 2 — not a Muse repository
37 3 — I/O error during rename
38
39 Examples::
40
41 muse mv old.py new.py # rename file in-place
42 muse mv src/ lib/src/ # rename directory
43 muse mv utils.py lib/ # move file into existing directory
44 muse mv old.py new.py --dry-run --json # preview in JSON
45 """
46
47 import argparse
48 import json as _json
49 import logging
50 import pathlib
51 import shutil
52 import sys
53 from muse.core.errors import ExitCode
54 from muse.core.repo import require_repo
55 from muse.core.types import Manifest
56 from muse.core.refs import (
57 get_head_commit_id,
58 read_current_branch,
59 )
60 from muse.core.commits import read_commit
61 from muse.core.snapshots import read_snapshot
62 from muse.core.envelope import EnvelopeJson, make_envelope
63 from muse.core.validation import sanitize_display, assert_write_inside_repo
64 from muse.core.timing import start_timer
65 from muse.core.object_store import write_object
66 from muse.plugins.code.stage import EMPTY_DIR_OID, StagedFileMap, make_entry, read_stage, read_stage_dir_renames, write_stage
67
68 logger = logging.getLogger(__name__)
69
70 # ---------------------------------------------------------------------------
71 # Wire-format TypedDicts
72 # ---------------------------------------------------------------------------
73
74 class _MvResultJson(EnvelopeJson):
75 """Stable JSON envelope for a successful (or dry-run) mv operation."""
76 status: str # "moved" | "dry_run"
77 source: str
78 dest: str
79 object_id: str # sha256:… object ID
80 dry_run: bool
81
82 class _MvErrorJson(EnvelopeJson):
83 """Error payload for usage/internal errors in --json mode."""
84 status: str # "error"
85 error: str
86
87 # ---------------------------------------------------------------------------
88 # Helpers
89 # ---------------------------------------------------------------------------
90
91 def _emit_error(json_out: bool, msg: str, code: ExitCode, elapsed: float) -> None:
92 """Print an error and raise SystemExit. Never returns.
93
94 In ``--json`` mode the error goes to stdout as a JSON payload so agents
95 always get parseable output. In text mode it goes to stderr.
96 """
97 if json_out:
98 print(_json.dumps(_MvErrorJson(
99 **make_envelope(elapsed, exit_code=int(code)),
100 status="error",
101 error=msg,
102 )))
103 else:
104 print(f"❌ {msg}", file=sys.stderr)
105 raise SystemExit(code)
106
107 _DIR_SENTINEL = EMPTY_DIR_OID
108
109 def _head_manifest(root: pathlib.Path) -> Manifest:
110 """Return the manifest from HEAD, or ``{}`` on an empty repo."""
111 try:
112 branch = read_current_branch(root)
113 commit_id = get_head_commit_id(root, branch)
114 if not commit_id:
115 return {}
116 commit = read_commit(root, commit_id)
117 if commit is None:
118 return {}
119 snap = read_snapshot(root, commit.snapshot_id)
120 return dict(snap.manifest) if snap else {}
121 except Exception:
122 return {}
123
124 def _head_snapshot_dirs(root: pathlib.Path) -> list[str]:
125 """Return the ``directories`` list from the current HEAD snapshot."""
126 try:
127 branch = read_current_branch(root)
128 commit_id = get_head_commit_id(root, branch)
129 if not commit_id:
130 return []
131 commit = read_commit(root, commit_id)
132 if commit is None:
133 return []
134 snap = read_snapshot(root, commit.snapshot_id)
135 return list(snap.directories) if snap else []
136 except Exception:
137 return []
138
139 def _resolve_path(root: pathlib.Path, raw: str) -> str:
140 """Resolve *raw* to a repo-relative POSIX path.
141
142 Rejects anything that escapes the repository root (path traversal).
143
144 Args:
145 root: Absolute repository root.
146 raw: Raw path string from the user.
147
148 Returns:
149 POSIX-style path relative to *root* (e.g. ``"src/auth.py"``).
150
151 Raises:
152 SystemExit(USER_ERROR): path is outside the repository.
153 """
154 p = pathlib.Path(raw)
155 if not p.is_absolute():
156 cwd_candidate = (pathlib.Path.cwd() / p).resolve()
157 try:
158 cwd_candidate.relative_to(root.resolve())
159 abs_target = cwd_candidate
160 except ValueError:
161 abs_target = (root / p).resolve()
162 else:
163 abs_target = p.resolve()
164
165 try:
166 rel = abs_target.relative_to(root.resolve())
167 except ValueError:
168 print(
169 f"❌ fatal: '{sanitize_display(raw)}' is outside the repository root.",
170 file=sys.stderr,
171 )
172 raise SystemExit(ExitCode.USER_ERROR)
173
174 return rel.as_posix()
175
176 def _get_source_object_id(
177 src_rel: str,
178 head_manifest: Manifest,
179 stage: StagedFileMap,
180 ) -> str:
181 """Return the object_id for *src_rel*, preferring the stage over HEAD.
182
183 Args:
184 src_rel: Repo-relative POSIX path of the source file.
185 head_manifest: Manifest of the current HEAD commit.
186 stage: Current stage index.
187
188 Returns:
189 sha256:… object_id.
190 """
191 staged = stage.get(src_rel)
192 if staged is not None and staged["mode"] != "D":
193 return staged["object_id"]
194 return head_manifest[src_rel]
195
196 def _resolve_dest(
197 root: pathlib.Path,
198 raw_dest: str,
199 src_rel: str,
200 ) -> str:
201 """Compute the final destination relative path.
202
203 If *raw_dest* ends with ``/`` or is an existing directory, appends the
204 source filename to produce the full destination path.
205
206 Args:
207 root: Absolute repository root.
208 raw_dest: Destination argument as given by the user.
209 src_rel: Resolved source path (repo-relative POSIX).
210
211 Returns:
212 Repo-relative POSIX destination path.
213 """
214 # Strip trailing slash — purely cosmetic, no semantic meaning.
215 dest_path = pathlib.Path(raw_dest.rstrip("/"))
216
217 abs_dest: pathlib.Path
218 if not dest_path.is_absolute():
219 cwd_candidate = (pathlib.Path.cwd() / dest_path).resolve()
220 try:
221 cwd_candidate.relative_to(root.resolve())
222 abs_dest = cwd_candidate
223 except ValueError:
224 abs_dest = (root / dest_path).resolve()
225 else:
226 abs_dest = dest_path.resolve()
227
228 # If the destination exists as a directory on disk, move source inside it.
229 # Trailing slash is cosmetic — only actual directory existence matters.
230 # Matches git mv semantics: `muse mv a b/` where b doesn't exist → rename to b.
231 if abs_dest.is_dir():
232 src_filename = pathlib.Path(src_rel).name
233 abs_dest = abs_dest / src_filename
234
235 # Validate it stays inside the repo.
236 try:
237 rel = abs_dest.relative_to(root.resolve())
238 except ValueError:
239 print(
240 f"❌ fatal: destination '{sanitize_display(raw_dest)}' is outside "
241 f"the repository root.",
242 file=sys.stderr,
243 )
244 raise SystemExit(ExitCode.USER_ERROR)
245
246 return rel.as_posix()
247
248 # ---------------------------------------------------------------------------
249 # Public interface
250 # ---------------------------------------------------------------------------
251
252 def register(
253 subparsers: "argparse._SubParsersAction[argparse.ArgumentParser]",
254 ) -> None:
255 """Register the ``muse mv`` subcommand."""
256 parser = subparsers.add_parser(
257 "mv",
258 help="Move or rename a tracked file, staging the change.",
259 description=__doc__,
260 formatter_class=argparse.RawDescriptionHelpFormatter,
261 )
262 parser.add_argument(
263 "source",
264 metavar="SOURCE",
265 help="File to move (must be tracked).",
266 )
267 parser.add_argument(
268 "dest",
269 metavar="DEST",
270 help=(
271 "Destination path or directory. If DEST ends with '/' or is an "
272 "existing directory, SOURCE's filename is appended."
273 ),
274 )
275 parser.add_argument(
276 "-f", "--force",
277 action="store_true",
278 help=(
279 "Override safety checks — allow moving onto an already-tracked or "
280 "on-disk destination."
281 ),
282 )
283 parser.add_argument(
284 "-n", "--dry-run",
285 action="store_true",
286 dest="dry_run",
287 help="Preview what would be moved without writing anything.",
288 )
289 parser.add_argument(
290 "--json", "-j",
291 action="store_true",
292 dest="json_out",
293 help="Emit machine-readable JSON on stdout.",
294 )
295 parser.set_defaults(func=run)
296
297 def run(args: argparse.Namespace) -> None:
298 """Move a tracked file or directory, updating both the working tree and the stage.
299
300 Validates that the source is tracked and the destination is safe, then
301 performs the on-disk rename atomically and updates the stage.
302
303 For files: source is tombstoned as ``"D"``; destination staged as ``"A"``
304 with the same object ID — content is unchanged.
305
306 For directories: all contained files are restaged under the new path;
307 empty-directory sentinels are relocated.
308
309 Agent quickstart
310 ----------------
311 ::
312
313 muse mv src/old.py src/new.py --json
314 muse mv src/olddir/ src/newdir/ --json
315 muse mv src/old.py src/new.py --dry-run --json
316
317 Exit codes
318 ----------
319 0 Success (or would-succeed in dry-run).
320 1 User error — source not tracked, destination exists, path traversal.
321 2 Not inside a Muse repository.
322 3 I/O error during rename.
323 """
324 import os
325
326 elapsed = start_timer()
327
328 force: bool = args.force
329 dry_run: bool = args.dry_run
330 json_out: bool = args.json_out
331
332 root = require_repo()
333
334 # ------------------------------------------------------------------ #
335 # 1. Resolve source path
336 # ------------------------------------------------------------------ #
337 src_rel = _resolve_path(root, args.source)
338 src_abs = root / src_rel
339
340 head_manifest = _head_manifest(root)
341 stage = read_stage(root)
342
343 # ------------------------------------------------------------------ #
344 # 2. Detect whether source is a tracked directory
345 # ------------------------------------------------------------------ #
346 files_in_dir: dict[str, str] = {
347 p: oid for p, oid in head_manifest.items()
348 if p.startswith(src_rel + "/")
349 }
350 head_dirs = _head_snapshot_dirs(root)
351 is_committed_empty_dir = src_rel in head_dirs and not files_in_dir
352 staged_dir_entry = stage.get(src_rel)
353 is_staged_empty_dir = (
354 staged_dir_entry is not None
355 and staged_dir_entry.get("object_id") == _DIR_SENTINEL
356 and staged_dir_entry.get("mode") == "A"
357 and src_rel not in head_dirs
358 )
359 is_dir_source = bool(files_in_dir) or is_committed_empty_dir or is_staged_empty_dir
360
361 if is_dir_source:
362 # ---------------------------------------------------------------- #
363 # DIRECTORY BRANCH
364 # ---------------------------------------------------------------- #
365 if not src_abs.exists():
366 _emit_error(
367 json_out,
368 f"source directory '{sanitize_display(src_rel)}' does not exist on disk.",
369 ExitCode.USER_ERROR,
370 elapsed,
371 )
372
373 dest_rel = _resolve_dest(root, args.dest, src_rel)
374 dest_abs = root / dest_rel
375 assert_write_inside_repo(root, dest_abs)
376
377 if dest_abs.exists() and not force:
378 _emit_error(
379 json_out,
380 f"destination '{sanitize_display(dest_rel)}' already exists on disk. "
381 f"Use --force to overwrite.",
382 ExitCode.USER_ERROR,
383 elapsed,
384 )
385
386 if dry_run:
387 if json_out:
388 print(_json.dumps(_MvResultJson(
389 **make_envelope(elapsed),
390 status="dry_run",
391 source=src_rel + "/",
392 dest=dest_rel + "/",
393 object_id="",
394 dry_run=True,
395 )))
396 else:
397 print(f"[dry-run] Would rename: {sanitize_display(src_rel)}/ → {sanitize_display(dest_rel)}/")
398 return
399
400 try:
401 shutil.move(str(src_abs), str(dest_abs))
402 except OSError as exc:
403 _emit_error(
404 json_out,
405 f"could not rename '{sanitize_display(src_rel)}/' → "
406 f"'{sanitize_display(dest_rel)}/': {exc}",
407 ExitCode.INTERNAL_ERROR,
408 elapsed,
409 )
410
411 new_stage: StagedFileMap = dict(stage)
412 files_moved = 0
413
414 # Restage committed files under new path.
415 for old_path, oid in files_in_dir.items():
416 suffix = old_path[len(src_rel):] # "/sub/file.py"
417 new_path = dest_rel + suffix
418 new_stage[old_path] = make_entry(object_id=oid, mode="D")
419 new_stage[new_path] = make_entry(object_id=oid, mode="A")
420 files_moved += 1
421
422 # Restage staged-only files (not yet committed) under new path.
423 for old_path, entry in list(stage.items()):
424 if (old_path.startswith(src_rel + "/")
425 and entry.get("object_id") != _DIR_SENTINEL
426 and old_path not in head_manifest
427 and entry["mode"] == "A"):
428 suffix = old_path[len(src_rel):]
429 new_path = dest_rel + suffix
430 new_stage.pop(old_path, None)
431 new_stage[new_path] = make_entry(object_id=entry["object_id"], mode="A")
432 files_moved += 1
433
434 # Ensure zero-byte object exists in the store for all dir A entries.
435 write_object(root, EMPTY_DIR_OID, b"")
436
437 # Relocate empty-directory sentinel.
438 if is_committed_empty_dir:
439 new_stage.pop(src_rel, None)
440 new_stage[src_rel] = make_entry(object_id=_DIR_SENTINEL, mode="D")
441 new_stage[dest_rel] = make_entry(object_id=_DIR_SENTINEL, mode="A")
442 elif is_staged_empty_dir:
443 new_stage.pop(src_rel, None)
444 new_stage[dest_rel] = make_entry(object_id=_DIR_SENTINEL, mode="A")
445
446 # Record the rename so status/diff can display "renamed: old/ → new/"
447 # rather than separate delete + add entries.
448 existing_renames = read_stage_dir_renames(root)
449 # If src_rel was itself the destination of a previous rename, collapse
450 # the chain: old_orig → dest_rel (drop the intermediate src_rel step).
451 collapsed: dict[str, str] = {}
452 for old, new in existing_renames.items():
453 if new == src_rel:
454 collapsed[old] = dest_rel # A→B then B→C becomes A→C
455 elif old != src_rel:
456 collapsed[old] = new # unrelated rename — keep
457 collapsed[src_rel] = dest_rel
458 write_stage(root, new_stage, dir_renames=collapsed)
459
460 src_disp = sanitize_display(src_rel)
461 dst_disp = sanitize_display(dest_rel)
462 if json_out:
463 print(_json.dumps(_MvResultJson(
464 **make_envelope(elapsed),
465 status="moved",
466 source=src_rel + "/",
467 dest=dest_rel + "/",
468 object_id="",
469 dry_run=False,
470 )))
471 else:
472 suffix_msg = f" ({files_moved} file{'s' if files_moved != 1 else ''})" if files_moved else ""
473 print(f"mv: {src_disp}/ → {dst_disp}/{suffix_msg}")
474 return
475
476 # ------------------------------------------------------------------ #
477 # FILE BRANCH (original logic)
478 # ------------------------------------------------------------------ #
479 in_head = src_rel in head_manifest
480 staged_entry = stage.get(src_rel)
481 staged_only = (
482 staged_entry is not None
483 and staged_entry["mode"] == "A"
484 and not in_head
485 )
486 is_tracked = in_head or (
487 staged_entry is not None and staged_entry["mode"] != "D"
488 )
489
490 if not is_tracked:
491 _emit_error(
492 json_out,
493 f"'{sanitize_display(src_rel)}' is not tracked. "
494 f"Stage it with 'muse code add' first.",
495 ExitCode.USER_ERROR,
496 elapsed,
497 )
498
499 if not src_abs.exists():
500 _emit_error(
501 json_out,
502 f"source file '{sanitize_display(src_rel)}' does not exist on disk.",
503 ExitCode.USER_ERROR,
504 elapsed,
505 )
506
507 # ------------------------------------------------------------------ #
508 # Resolve destination path
509 # ------------------------------------------------------------------ #
510 dest_rel = _resolve_dest(root, args.dest, src_rel)
511 dest_abs = root / dest_rel
512
513 assert_write_inside_repo(root, dest_abs)
514
515 dest_in_head = dest_rel in head_manifest
516 dest_staged = stage.get(dest_rel)
517 dest_is_tracked = dest_in_head or (
518 dest_staged is not None and dest_staged["mode"] != "D"
519 )
520
521 if dest_is_tracked and not force:
522 _emit_error(
523 json_out,
524 f"destination '{sanitize_display(dest_rel)}' is already tracked. "
525 f"Use --force to overwrite.",
526 ExitCode.USER_ERROR,
527 elapsed,
528 )
529
530 if dest_abs.exists() and not force:
531 _emit_error(
532 json_out,
533 f"destination '{sanitize_display(dest_rel)}' already exists on disk. "
534 f"Use --force to overwrite.",
535 ExitCode.USER_ERROR,
536 elapsed,
537 )
538
539 # ------------------------------------------------------------------ #
540 # Resolve object_id (stays the same — content is unchanged)
541 # ------------------------------------------------------------------ #
542 object_id = _get_source_object_id(src_rel, head_manifest, stage)
543
544 # ------------------------------------------------------------------ #
545 # Dry-run — report and exit
546 # ------------------------------------------------------------------ #
547 if dry_run:
548 if json_out:
549 print(_json.dumps(_MvResultJson(
550 **make_envelope(elapsed),
551 status="dry_run",
552 source=src_rel,
553 dest=dest_rel,
554 object_id=object_id,
555 dry_run=True,
556 )))
557 else:
558 src_disp = sanitize_display(src_rel)
559 dst_disp = sanitize_display(dest_rel)
560 print(f"[dry-run] Would rename: {src_disp} → {dst_disp}")
561 return
562
563 # ------------------------------------------------------------------ #
564 # On-disk rename
565 # ------------------------------------------------------------------ #
566 dest_abs.parent.mkdir(parents=True, exist_ok=True)
567 try:
568 os.replace(src_abs, dest_abs)
569 except OSError as exc:
570 _emit_error(
571 json_out,
572 f"could not rename '{sanitize_display(src_rel)}' → "
573 f"'{sanitize_display(dest_rel)}': {exc}",
574 ExitCode.INTERNAL_ERROR,
575 elapsed,
576 )
577
578 # ------------------------------------------------------------------ #
579 # Update the stage
580 # ------------------------------------------------------------------ #
581 new_stage_f: StagedFileMap = dict(stage)
582
583 if staged_only:
584 new_stage_f.pop(src_rel, None)
585 else:
586 new_stage_f[src_rel] = make_entry(object_id="", mode="D")
587
588 new_stage_f[dest_rel] = make_entry(object_id=object_id, mode="A")
589
590 write_stage(root, new_stage_f)
591
592 # ------------------------------------------------------------------ #
593 # Output
594 # ------------------------------------------------------------------ #
595 src_disp = sanitize_display(src_rel)
596 dst_disp = sanitize_display(dest_rel)
597
598 if json_out:
599 print(_json.dumps(_MvResultJson(
600 **make_envelope(elapsed),
601 status="moved",
602 source=src_rel,
603 dest=dest_rel,
604 object_id=object_id,
605 dry_run=False,
606 )))
607 else:
608 print(f"mv: {src_disp} → {dst_disp}")
File History 1 commit
sha256:9a3bb190de5a18742792038aa709072a582ada8b223d5dfa4f72c70831ec3ba3 docs: revert migrate hub-scoping/domain-integers rows from … Sonnet 5 23 hours ago