From dbe3bca439caf0c899af2e37f4dfd6fcdcc7c197 Mon Sep 17 00:00:00 2001 From: Nathan McRae Date: Mon, 8 Jul 2024 21:46:18 -0700 Subject: [PATCH] Add 'add' command --- libwyag.py | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/libwyag.py b/libwyag.py index bfa4031..51919a3 100644 --- a/libwyag.py +++ b/libwyag.py @@ -1291,3 +1291,51 @@ def rm(repo, paths, delete=True, skip_missing=False): index.entries = kept_entries index_write(repo, index) + +argsp = argsubparsers.add_parser("add", help="Add files' contents to the index.") +argsp.add_argument("path", nargs="+", help="Files to add") + +def cmd_add(args): + repo = repo_find() + add(repo, args.path) + +def add(repo, paths, delete=True, skip_missing=False): + rm(repo, paths, delete=False, skip_missing=True) + + worktree = repo.worktree + "/" + + # Convert the paths to pairs: (absolute, relative_to_worktree). + # Also dlete delete them from the index if they're present. + clean_paths = list() + for path in paths: + abspath = os.path.abspath(path).replace("\\", "/") + if not (abspath.startswith(worktree) and os.path.isfile(abspath)): + raise Exception(f"Not a file, or outside the worktree: {paths}") + relpath = os.path.relpath(abspath, repo.worktree).replace("\\", "/") + clean_paths.append((abspath, relpath)) + + # Find and read the index. It was modified by rm. (This isn't + # optimal, but good enough) + # + # FIXME: though: we could just move the index through commands instead + # of reading and writing it over agains + index = index_read(repo) + + for (abspath, relpath) in clean_paths: + with open(abspath, "rb") as fd: + sha = object_hash(fd, b"blob", repo) + + stat = os.stat(abspath) + + ctime_s = int(stat.st_ctime) + ctime_ns = stat.st_ctime_ns % 10**9 + mtime_s = int(stat.st_mtime) + mtime_ns = stat.st_mtime_ns % 10**9 + + entry = GitIndexEntry(ctime=(ctime_s, ctime_ns), mtime=(mtime_s, mtime_ns), ino=stat.st_ino, + mode_type=0b1000, mode_perms=0o644, uid=stat.st_uid, gid=stat.st_gid, + fsize=stat.st_size, sha=sha, flag_assume_valid=False, + flag_stage=False, name=relpath) + index.entries.append(entry) + + index_write(repo, index)