Add 'add' command

This commit is contained in:
Nathan McRae 2024-07-08 21:46:18 -07:00
parent 11198aaf41
commit dbe3bca439

View File

@ -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)