Ver3.0 버전 관리 시스템, 직접 만들어보는 미니 Git: 객체·브랜치·커밋까지 동작하는 실전 소스와 설계의 모든 것 🚀

버전 관리 시스템, 직접 만들어보는 미니 Git: 객체·브랜치·커밋까지 동작하는 실전 소스와 설계의 모든 것 🚀
깃을 쓰는 건 쉽지만, 깃이 왜 그렇게 동작하는지 이해하는 건 또 다른 재미죠. 오늘은 정말 동작하는 미니 Git을 파이썬으로 같이 만들어보며, 내부 구조와 핵심 개념을 통째로 체득해봅시다. 🧩🛠️
덧붙여, 지식 콘텐츠를 공유하는 분위기답게, 재능넷의 ‘지식인의 숲’에서도 읽기 편한 교양서 느낌으로 구성했어요. 코드 이면의 개념을 먼저 잡고, 천천히 구현을 쌓아올립니다. 🌲
- 파일 스테이징: add
- 커밋: commit
- 로그 보기: log
- 상태 확인: status
- 차이 보기: diff
- 브랜치: branch / 체크아웃 checkout
- 병합: merge (fast-forward 우선, 단순한 3-way는 안내만)
- 참조 조작: symbolic HEAD, refs/heads/*
- 가비지 컬렉션 개념과 팩파일은 개념만 설명 (코드는 단순 버전)
- OS 제약 없음 (Windows, macOS, Linux 테스트 가능)
- 터미널에서 실행하면 됩니다.
Git이 뭔데 이렇게 잘 나가? 내부 디자인 한 장 요약
Git은 콘텐츠 주소화(content-addressable storage)를 핵심으로 합니다. 파일 내용으로부터 해시(SHA)를 계산하고, 그 해시를 파일명 삼아 저장하죠. 덕분에 중복 저장이 자동으로 제거되고, 어떤 시점의 프로젝트 스냅샷을 영원히 참조할 수 있어요.
또한 commit은 tree를 가리키고, tree는 하위 디렉터리/파일(blob)을 가리키는 나무 구조를 가집니다. commit은 부모 커밋을 기록해 역사 그래프를 만들고, HEAD/refs는 해당 그래프에서 현재 바라보는 스냅샷을 가리키는 표지판 역할을 합니다.
미니 Git 설계 철학
우리는 다음 5가지 원칙을 지킵니다. 첫째, 디스크 구조는 실제 Git을 최대한 닮게 만든다. 둘째, 기능은 최소 핵심만 골라 구현한다. 셋째, 코드는 읽히도록 작성한다. 넷째, 플랫폼 독립성을 지킨다. 다섯째, 에러 메시지 친절화로 디버깅을 돕는다. 🧠
- .minigit/refs/heads/main: 브랜치 포인터
- .minigit/refs/tags/v1.0: 태그 포인터(옵션)
- .minigit/HEAD: 현재 브랜치를 나타내는 심볼릭 ref (예: ref: refs/heads/main)
- .minigit/index: 스테이징 파일 목록 및 blob 해시 기록
첫 시작: 저장소 초기화 코드
먼저 .minigit 디렉터리를 만들고, 기본 구조를 세팅합니다. HEAD를 main 브랜치로 가리키고, refs/heads/main은 비워둔 채 시작해요.
# minigit.py
import argparse, os, sys, hashlib, zlib, time, stat, json, difflib
from pathlib import Path
MINIGIT_DIR = ".minigit"
OBJECTS_DIR = "objects"
REFS_DIR = "refs"
HEADS_DIR = os.path.join(REFS_DIR, "heads")
TAGS_DIR = os.path.join(REFS_DIR, "tags")
INDEX_FILE = "index"
CONFIG_FILE = "config"
def repo_path(*parts):
return os.path.join(MINIGIT_DIR, *parts)
def ensure_dir(p):
Path(p).mkdir(parents=True, exist_ok=True)
def read_file(p, mode="rb"):
with open(p, mode) as f:
return f.read()
def write_file(p, data, mode="wb"):
ensure_dir(os.path.dirname(p))
with open(p, mode) as f:
f.write(data)
def exists(p):
return os.path.exists(p)
def repo_init():
if exists(MINIGIT_DIR):
print("이미 초기화된 저장소입니다: .minigit")
return
ensure_dir(repo_path())
ensure_dir(repo_path(OBJECTS_DIR))
ensure_dir(repo_path(HEADS_DIR))
ensure_dir(repo_path(TAGS_DIR))
write_file(repo_path("HEAD"), b"ref: refs/heads/main\n")
write_file(repo_path(HEADS_DIR, "main"), b"")
write_file(repo_path(INDEX_FILE), b"{}")
write_file(repo_path(CONFIG_FILE), b'{"user":{"name":"You","email":"you@example.com"}}')
print("Initialized empty MiniGit repository in .minigit/")
이제 python minigit.py init만 실행하면 준비 완료. ✨
콘텐츠 주소 스토리지: 객체 저장과 조회
객체는 헤더 + 널문자 + 콘텐츠를 합친 바이트 시퀀스를 SHA-1로 해시하고, 그 결과를 20바이트(40헥사)로 파일명에 사용합니다. 저장할 땐 zlib으로 압축해 디스크 절약을 노립니다.
def sha1(data: bytes) -> str:
return hashlib.sha1(data).hexdigest()
def object_path(oid):
return repo_path(OBJECTS_DIR, oid[:2], oid[2:])
def hash_object(obj_type: str, data: bytes, write=True) -> str:
# ex) b"blob 12\x00<content>"
header = f"{obj_type} {len(data)}".encode() + b"\x00"
store = header + data
oid = sha1(store)
if write:
p = object_path(oid)
if not exists(p):
write_file(p, zlib.compress(store))
return oid
def read_object(oid: str) -> tuple[str, bytes]:
try:
raw = zlib.decompress(read_file(object_path(oid)))
except FileNotFoundError:
raise SystemExit(f"객체를 찾을 수 없습니다: {oid}")
# 헤더 파싱
null_index = raw.index(b"\x00")
header = raw[:null_index].decode()
obj_type, size_str = header.split(" ", 1)
data = raw[null_index+1:]
size = int(size_str)
if size != len(data):
raise SystemExit("객체 크기 불일치")
return obj_type, data
Blob은 파일 내용을 그대로 저장해요. Tree는 디렉터리 스냅샷을 표현하고, Commit은 프로젝트 상태와 부모 커밋을 설명하는 메타 오브젝트입니다.
인덱스: 스테이징 영역의 단순화 모델
실제 Git 인덱스는 바이너리 포맷이지만, 우리 미니 Git은 학습 친화성을 위해 JSON으로 구성하겠습니다. 경로 → blob OID 매핑을 저장하죠.
def read_index() -> dict:
p = repo_path(INDEX_FILE)
if not exists(p):
return {}
return json.loads(read_file(p, "rb").decode() or "{}")
def write_index(idx: dict):
write_file(repo_path(INDEX_FILE), json.dumps(idx, ensure_ascii=False, indent=0).encode())
def add(paths):
idx = read_index()
for path in paths:
if os.path.isdir(path):
# 디렉터리면 재귀적으로 추가
for root, _, files in os.walk(path):
for f in files:
w = os.path.join(root, f)
if w.startswith(MINIGIT_DIR):
continue
data = read_file(w, "rb")
oid = hash_object("blob", data, write=True)
idx[w.replace("\\","/")] = {"oid": oid, "mode": "100644"}
print(f"add {w} ({oid[:10]})")
else:
data = read_file(path, "rb")
oid = hash_object("blob", data, write=True)
idx[path.replace("\\","/")] = {"oid": oid, "mode": "100644"}
print(f"add {path} ({oid[:10]})")
write_index(idx)
여기서 모드는 간단히 일반 파일 100644만 지원합니다. 실행 비트 등은 확장 사항으로 남겨 둡니다.
트리 객체 만들기: 디렉터리 스냅샷의 핵심
트리는 Git의 진짜 보물입니다. 인덱스에 담긴 파일 경로들을 디렉터리별로 묶어 재귀적으로 Tree를 만듭니다.
def build_tree_from_index(index: dict) -> str:
# index를 디렉터리 구조로 묶기
entries_by_dir = {}
for path, meta in index.items():
parts = path.split("/")
d = "/".join(parts[:-1])
name = parts[-1]
entries_by_dir.setdefault(d, []).append((name, meta))
def build_tree(dir_path: str) -> str:
files = []
dirs = {}
for (path, meta) in index.items():
if path.startswith(dir_path + "/" if dir_path else "") or path == dir_path:
# 해당 디렉터리 하위만 고려
pass
# 실제로는 entries_by_dir로 처리
for (name, meta) in entries_by_dir.get(dir_path, []):
files.append((meta["mode"], name, meta["oid"]))
# 하위 디렉터리 탐색
subdirs = set()
for p in index.keys():
if dir_path:
if p.startswith(dir_path + "/"):
rest = p[len(dir_path)+1:]
else:
continue
else:
rest = p
if "/" in rest:
subdirs.add(rest.split("/")[0])
tree_entries = []
# 파일부터
for mode, name, oid in sorted(files, key=lambda x: x[1]):
# tree 포맷: "{mode} {name}\x00<20-byte oid>"
ent = f"{mode} {name}".encode() + b"\x00" + bytes.fromhex(oid)
tree_entries.append(ent)
# 디렉터리(트리)
for sd in sorted(subdirs):
subdir_path = f"{dir_path}/{sd}" if dir_path else sd
child_oid = build_tree(subdir_path)
ent = f"40000 {sd}".encode() + b"\x00" + bytes.fromhex(child_oid)
tree_entries.append(ent)
tree_data = b"".join(tree_entries)
return hash_object("tree", tree_data, write=True)
return build_tree("") # 루트 기준 빌드
여기서 트리 엔트리는 mode name\0raw-oid 형태의 바이너리입니다. 오브젝트 내부 포맷까지 진짜 Git과 크게 다르지 않아요. 🌳
참조와 HEAD: 지금 우리가 어디에 있는지
HEAD는 보통 ref: refs/heads/main 같은 심볼릭 문자열입니다. 커밋이 생길 때 브랜치 ref가 커밋 OID를 가리키도록 갱신하죠.
def get_head_ref() -> tuple[bool, str]:
data = read_file(repo_path("HEAD")).decode().strip()
if data.startswith("ref: "):
return True, data[5:]
return False, data # detached HEAD (oid)
def read_ref(name: str) -> str|None:
p = repo_path(name)
if not exists(p):
return None
s = read_file(p).decode().strip()
return s if s else None
def update_ref(name: str, oid: str):
write_file(repo_path(name), (oid+"\n").encode())
def resolve_head() -> str|None:
is_sym, target = get_head_ref()
if is_sym:
return read_ref(target)
return target or None
def set_head_detached(oid: str):
write_file(repo_path("HEAD"), (oid+"\n").encode())
def set_head_symbolic(refname: str):
write_file(repo_path("HEAD"), f"ref: {refname}\n".encode())
커밋 만들기: 타임캡슐 찍기
커밋 객체는 tree, parent, author, committer, message를 담습니다. 간단한 텍스트 포맷을 그대로 사용하죠.
def get_config():
p = repo_path(CONFIG_FILE)
if exists(p):
return json.loads(read_file(p).decode() or "{}")
return {"user":{"name":"You","email":"you@example.com"}}
def commit_tree(tree_oid: str, parents: list[str], message: str) -> str:
cfg = get_config()
name = cfg.get("user",{}).get("name","You")
email = cfg.get("user",{}).get("email","you@example.com")
ts = int(time.time())
tz = time.strftime("%z", time.localtime())
lines = []
lines.append(f"tree {tree_oid}")
for p in parents:
lines.append(f"parent {p}")
who = f"{name} <{email}> {ts} {tz}"
lines.append(f"author {who}")
lines.append(f"committer {who}")
lines.append("") # blank line
lines.append(message)
data = ("\n".join(lines)).encode()
return hash_object("commit", data, write=True)
def commit(message: str):
idx = read_index()
if not idx:
print("커밋할 스테이징 내용이 없습니다.")
return
tree_oid = build_tree_from_index(idx)
head_oid = resolve_head()
parents = [head_oid] if head_oid else []
oid = commit_tree(tree_oid, parents, message)
# HEAD가 심볼릭이라면 브랜치 이동
is_sym, refname = get_head_ref()
if is_sym:
update_ref(refname, oid)
else:
set_head_detached(oid)
print(f"[commit {oid[:10]}] {message}")
한 문장이라도 메시지를 남기는 습관, 정말 중요합니다. 깃 히스토리를 미래의 자신에게 보내는 러브레터라고 생각해보세요. 💌
로그 탐색: 부모 링크를 거슬러 올라가기
커밋은 DAG(Graph) 구조이지만, 기본 로그는 부모를 따라 과거로 이동하는 단순한 루프입니다.
def parse_commit(oid: str) -> dict:
typ, data = read_object(oid)
assert typ == "commit"
text = data.decode("utf-8", errors="replace")
header, _, msg = text.partition("\n\n")
info = {"message":msg, "parents":[], "tree":None, "author":None, "committer":None}
for line in header.splitlines():
if line.startswith("tree "):
info["tree"] = line[5:]
elif line.startswith("parent "):
info["parents"].append(line[7:])
elif line.startswith("author "):
info["author"] = line[7:]
elif line.startswith("committer "):
info["committer"] = line[10:]
return info
def log():
oid = resolve_head()
if not oid:
print("로그가 없습니다. 아직 커밋이 없어요.")
return
seen = set()
while oid and oid not in seen:
seen.add(oid)
info = parse_commit(oid)
print(f"commit {oid}")
if info["author"]:
print(f"Author: {info['author']}")
print("")
for line in info["message"].splitlines():
print(f" {line}")
print("")
oid = info["parents"][0] if info["parents"] else None
체크아웃: 작업 디렉터리를 커밋 스냅샷과 동기화
트리를 워킹 디렉터리로 복원하는 과정입니다. 우선 간단히, 충돌이나 덮어쓰기 보호는 최소한으로 구현하고 경고 메시지로 대체합니다.
def read_tree(oid: str) -> list[tuple[str,str,str]]:
# returns list of (mode, name, oid) for this tree
typ, data = read_object(oid)
assert typ == "tree"
i = 0
out = []
while i < len(data):
# read "mode name\x00"
j = data.find(b"\x00", i)
header = data[i:j].decode()
mode, name = header.split(" ", 1)
raw_oid = data[j+1:j+21]
child = raw_oid.hex()
out.append((mode, name, child))
i = j + 21
return out
def restore_tree(oid: str, base=""):
for mode, name, child in read_tree(oid):
path = os.path.join(base, name) if base else name
if mode == "40000":
ensure_dir(path)
restore_tree(child, path)
else:
_, blob = read_object(child)
ensure_dir(os.path.dirname(path) or ".")
write_file(path, blob)
def find_tree_entry(oid: str, path: str) -> str|None:
# path like "a/b/c"
parts = [p for p in path.split("/") if p]
cur = oid
for i, part in enumerate(parts):
found = False
for mode, name, child in read_tree(cur):
if name == part:
if i == len(parts)-1:
return child if mode != "40000" else None
else:
if mode != "40000":
return None
cur = child
found = True
break
if not found:
return None
return None
def checkout(name_or_oid: str):
# 브랜치 또는 커밋 OID
target_oid = None
ref_candidate = f"refs/heads/{name_or_oid}"
if exists(repo_path(ref_candidate)):
target_oid = read_ref(ref_candidate)
if not target_oid:
print("빈 브랜치입니다. 커밋 없음.")
return
restore_tree(parse_commit(target_oid)["tree"])
set_head_symbolic(ref_candidate)
print(f"Switched to branch '{name_or_oid}'")
return
# OID로 시도
if exists(object_path(name_or_oid[:40])):
typ, _ = read_object(name_or_oid)
if typ != "commit":
raise SystemExit("커밋 OID를 지정하세요.")
restore_tree(parse_commit(name_or_oid)["tree"])
set_head_detached(name_or_oid)
print(f"Note: switching to detached HEAD at {name_or_oid[:7]}")
else:
raise SystemExit(f"대상 없음: {name_or_oid}")
브랜치와 병합: 함께 자라나는 히스토리
브랜치는 refs/heads/아래에 커밋 OID 한 줄이면 됩니다. 병합은 먼저 Fast-Forward부터 구현해 감을 잡습니다.
def branch_list():
heads = repo_path(HEADS_DIR)
if not exists(heads):
print("(no heads)")
return
_, headref = get_head_ref()
cur = read_ref(headref) if headref else None
for name in sorted(os.listdir(heads)):
refname = f"refs/heads/{name}"
oid = read_ref(refname)
star = "*" if ("refs/heads/"+name)==headref else " "
print(f"{star} {name} {oid[:10] if oid else ''}")
def branch_create(name: str, oid: str|None=None):
if exists(repo_path(HEADS_DIR, name)):
raise SystemExit("이미 존재하는 브랜치")
if not oid:
oid = resolve_head()
if not oid:
raise SystemExit("HEAD가 비어있습니다.")
update_ref(f"refs/heads/{name}", oid)
print(f"브랜치 생성: {name} -> {oid[:10]}")
def is_ancestor(base: str, target: str) -> bool:
# base가 target의 조상인지 검사
seen = set()
stack = [target]
while stack:
x = stack.pop()
if x in seen:
continue
seen.add(x)
if x == base:
return True
p = parse_commit(x)["parents"]
stack.extend(p)
return False
def merge_ff(branch: str):
# 머지 대상 브랜치의 OID
refname = f"refs/heads/{branch}"
other = read_ref(refname)
if not other:
raise SystemExit("대상 브랜치가 비어있음")
head = resolve_head()
if not head:
raise SystemExit("현재 브랜치가 비어있음")
# FF 조건: HEAD가 other의 조상이라면 ref만 이동
if is_ancestor(head, other):
is_sym, curref = get_head_ref()
if not is_sym:
raise SystemExit("detached HEAD 상태에서는 병합 불가(단순화)")
update_ref(curref, other)
restore_tree(parse_commit(other)["tree"])
print(f"Fast-forward: {curref.split('/')[-1]} -> {branch}")
else:
print("Fast-forward 불가. 3-way 머지가 필요합니다. (이 구현은 안내만)")
- 라인 충돌이 있으면 conflict 마커(<<<<<<<)를 남깁니다.
- 우리 미니 Git에선 3-way 알고리즘을 설명만 하고, FF만 실제 동작시킵니다.
status와 diff: 지금 무슨 일이?
status는 워킹 디렉터리, 인덱스, HEAD 커밋 간 상태를 요약합니다. diff는 라인 수준 차이를 보여주죠.
def list_working_files():
out = []
for root, dirs, files in os.walk("."):
# .minigit 제외
if MINIGIT_DIR in root:
continue
for f in files:
p = os.path.join(root, f)
if p.startswith(f"./{MINIGIT_DIR}") or p.startswith(MINIGIT_DIR):
continue
if p.startswith("./."):
# 숨김파일 포함 여부는 취향. 여기선 포함하되 .minigit만 제외
pass
out.append(p[2:] if p.startswith("./") else p)
return out
def tree_to_map(oid: str, base="") -> dict:
m = {}
for mode, name, child in read_tree(oid):
path = f"{base}/{name}" if base else name
if mode == "40000":
m.update(tree_to_map(child, path))
else:
m[path] = child
return m
def status():
idx = read_index()
head_oid = resolve_head()
head_map = {}
if head_oid:
head_map = tree_to_map(parse_commit(head_oid)["tree"])
work = list_working_files()
staged_new, staged_mod, staged_del = [], [], []
not_staged_mod, not_tracked = [], []
# 인덱스 기준
for path, meta in idx.items():
blob = meta["oid"]
head_blob = head_map.get(path)
if head_blob is None:
staged_new.append(path)
elif head_blob != blob:
staged_mod.append(path)
for path in head_map.keys():
if path not in idx:
staged_del.append(path)
# 워킹 디렉터리 비교
for w in work:
data = read_file(w, "rb")
cur_blob = sha1(f"blob {len(data)}".encode()+b"\x00"+data) # 계산만
if w in idx:
if idx[w]["oid"] != cur_blob:
not_staged_mod.append(w)
else:
if w not in head_map:
not_tracked.append(w)
print("Changes to be committed:")
for p in staged_new: print(f" (new) {p}")
for p in staged_mod: print(f" (modified) {p}")
for p in staged_del: print(f" (deleted) {p}")
print("")
print("Changes not staged for commit:")
for p in not_staged_mod: print(f" (modified) {p}")
print("")
print("Untracked files:")
for p in not_tracked: print(f" {p}")
def diff(path: str, staged=False):
idx = read_index()
head_oid = resolve_head()
head_map = {}
if head_oid:
head_map = tree_to_map(parse_commit(head_oid)["tree"])
a = ""
b = ""
if staged:
if path not in idx:
print("인덱스에 없는 파일입니다.")
return
_, a_bytes = read_object(idx[path]["oid"])
a = a_bytes.decode("utf-8", errors="replace")
cur = read_file(path, "rb").decode("utf-8", errors="replace") if exists(path) else ""
b = cur
else:
# HEAD vs 워킹
head_blob = head_map.get(path)
if head_blob:
_, a_bytes = read_object(head_blob)
a = a_bytes.decode("utf-8", errors="replace")
else:
a = ""
b = read_file(path, "rb").decode("utf-8", errors="replace") if exists(path) else ""
for line in difflib.unified_diff(a.splitlines(), b.splitlines(), lineterm="", fromfile="a/"+path, tofile="b/"+path):
print(line)
명령어 파서와 엔트리포인트
여러 명령을 묶는 깔끔한 CLI를 위해 argparse를 사용합니다. 실행 파일은 단일 minigit.py로 충분합니다.
def main():
p = argparse.ArgumentParser(prog="minigit", description="Mini Git implemented in Python")
sub = p.add_subparsers(dest="cmd")
sub.add_parser("init")
ap_add = sub.add_parser("add")
ap_add.add_argument("paths", nargs="+")
ap_commit = sub.add_parser("commit")
ap_commit.add_argument("-m", "--message", required=True)
sub.add_parser("log")
ap_co = sub.add_parser("checkout")
ap_co.add_argument("name")
ap_br = sub.add_parser("branch")
ap_br.add_argument("subcmd", nargs="?", default="list", choices=["list","create"])
ap_br.add_argument("name", nargs="?")
ap_merge = sub.add_parser("merge")
ap_merge.add_argument("branch")
ap_status = sub.add_parser("status")
ap_diff = sub.add_parser("diff")
ap_diff.add_argument("path")
ap_diff.add_argument("--staged", action="store_true")
args = p.parse_args()
if args.cmd == "init":
repo_init()
elif args.cmd == "add":
add(args.paths)
elif args.cmd == "commit":
commit(args.message)
elif args.cmd == "log":
log()
elif args.cmd == "checkout":
checkout(args.name)
elif args.cmd == "branch":
if args.subcmd == "list":
branch_list()
else:
branch_create(args.name)
elif args.cmd == "merge":
merge_ff(args.branch)
elif args.cmd == "status":
status()
elif args.cmd == "diff":
diff(args.path, staged=args.staged)
else:
p.print_help()
if __name__ == "__main__":
# 저장소 존재 확인은 일부 명령에서만 강제
if len(sys.argv) > 1 and sys.argv[1] == "init":
main()
else:
if not exists(MINIGIT_DIR):
print("여긴 미니Git 저장소가 아닙니다. 먼저 'minigit init'을 실행하세요.")
# 그래도 help는 보여주자
main()
한 번에 따라 하기: 손에 느낌 남기기 튜토리얼
터미널에서 다음 순서로 실행해보세요.
2. 파일 생성: echo "hello" > hello.txt
3. 스테이징: python minigit.py add hello.txt
4. 커밋: python minigit.py commit -m "first commit"
5. 로그: python minigit.py log
6. 브랜치 생성: python minigit.py branch create feature
7. 체인지: echo "world" >> hello.txt
8. 상태: python minigit.py status → not staged 확인
9. 스테이징: python minigit.py add hello.txt
10. 커밋: python minigit.py commit -m "update hello"
11. 브랜치 목록: python minigit.py branch list
12. Fast-Forward 병합 테스트: python minigit.py merge feature
파일 포맷을 더 깊게: 객체 내부를 까보자
Blob: "blob {size}\0{data}". Tree: "tree {size}\0" + entries, 엔트리는 "{mode} {name}\x00{20바이트 OID}" 바이너리.
Commit: 헤더에 tree/parent/author/committer 줄을 적고, 빈 줄 뒤 메시지가 이어집니다. 헤더만 보면 깔끔한 텍스트지만 사실은 모두 객체이며 zlib으로 압축돼 디스크에 저장돼요.
- 임의 검증: 헤더 길이와 데이터 길이가 같은지 항상 체크. 손상 감지를 빠르게 도와줍니다.
에러 처리와 안정성: 간단해도 품질은 챙기자
소프트웨어는 친절해야 합니다. 사용자가 실수하더라도 의미 있는 메시지를 제공해야 하죠. 예를 들어 존재하지 않는 브랜치로 체크아웃하면 명확히 알려주고, 덮어쓰기를 유발할 수 있는 경우 경고를 남깁니다.
또한 인덱스가 손상됐을 때 기본값으로 복구하거나, 잘못된 OID를 요청하면 즉시 종료하기 전에 어떤 OID가 문제인지 보여주는 식으로 피드백을 강화합니다.
성능과 구조적 고찰
우리 구현은 교육용이므로 팩파일과 델타 압축을 생략했습니다. 대규모 저장소에서는 pack과 delta가 필수입니다. 대신 지금 구조에서도 다음 최적화는 적용할 수 있어요.
- 인덱스 JSON을 pretty가 아닌 compact 모드로 저장해 I/O 줄이기
- 트리 빌더 캐싱으로 동일 디렉터리 조합 반복 계산 방지
- diff 시 바이너리 감지(널 바이트 존재 여부)로 텍스트 디코딩 스킵
2) GPG 서명 커밋 헤더 적용.
3) 인덱스 포맷을 실제 Git과 같게(바이너리) 구현해보기.
4) 간단한 3-way merge 작성과 충돌 표시/해결 플로우 도입.
테스트 전략: 고마운 실패들을 미리 모시기
TDD로 간다면 명령어별 시나리오 테스트가 좋습니다. 파일시스템을 건드리므로 임시 디렉터리에서 테스트를 돌리고, 스냅샷 기반 검증을 활용하세요.
# tests_sketched.py (개념 스케치)
import os, shutil, subprocess, tempfile, json
def run(*args):
return subprocess.run(["python","minigit.py",*args], check=False, capture_output=True, text=True)
def test_init_and_first_commit():
d = tempfile.mkdtemp()
cwd = os.getcwd()
try:
os.chdir(d)
out = run("init")
open("a.txt","w").write("A")
run("add","a.txt")
run("commit","-m","init")
log = run("log")
assert "commit " in log.stdout
finally:
os.chdir(cwd); shutil.rmtree(d)
실제 Git과 차이점 정리
우리 미니 Git은 다음을 과감히 단순화했습니다.
- 인덱스: JSON 기반, 충돌 상태(스테이지 1/2/3) 미지원
- 머지: Fast-Forward만 자동 처리, 3-way는 안내만
- 퍼미션/링크: 단일 모드 중심
- 네트워킹: fetch/push 없음 (로컬 스냅샷 학습 집중)
- 가비지 컬렉션: 참조되지 않은 객체 청소(gc) 생략
- 브랜치/HEAD/커밋의 관계를 손으로 조작하며 메커니즘 이해
- 코드 읽기 능력 향상과 디버깅 직감 강화
보너스: 태그(tag)와 라이트웨이트 릴리스
태그는 단순히 refs/tags/v1.0에 커밋 OID를 적는 것만으로도 충분히 라이트웨이트 태그가 됩니다. 주석 태그(annotated tag)는 tag 객체 타입을 따로 저장하지만, 여기서는 다음처럼 간단 도우미 함수를 더할 수 있어요.
def tag_create(name: str, oid: str|None=None):
if not oid:
oid = resolve_head()
if not oid:
raise SystemExit("태그할 커밋이 없습니다.")
refname = f"refs/tags/{name}"
if exists(repo_path(refname)):
raise SystemExit("이미 존재하는 태그")
update_ref(refname, oid)
print(f"tag {name} -> {oid[:10]}")
한눈정리: 자주 부딪히는 에지 케이스
- 빈 커밋: 인덱스가 비어 있으면 커밋 불가로 처리.
- 동일 파일 다른 대소문자: Windows/Mac에서는 충돌 가능. 경로 정규화 필요.
- 바이너리 파일 diff: 텍스트 디코드 실패 가능성. 우리 구현은 replace로 안전 디코딩.
- 긴 경로와 권한: OS별 파일 이름 제한 주의.
프로덕션으로 가려면?
진짜 서비스에 쓰려면 아래가 필요합니다.
- 패킹/델타/GC: 저장 효율과 속도 극대화
- 네트워크 프로토콜: fetch/push/clone/receive-pack
- 파일 잠금과 동시성: 인덱스/레프 원자적 업데이트
- 보안: 서명 검증, 해시 업그레이드, 필터(융합형 LFS) 등
자주 하는 질문 모음
Q. 왜 SHA-1인가요?
A. 교육 목적과 간결성 때문입니다. SHA-256로 바꾸는 것도 큰 일은 아니니 도전해보세요.
Q. 왜 인덱스를 JSON으로?
A. 읽기 쉬운 포맷으로 학습 속도를 올리기 위해서예요.
Q. 3-way 머지는 꼭 필요한가요?
A. 협업이 늘어나면 반드시 필요해요. fast-forward만으로는 히스토리 관리가 제한됩니다.
마무리: 직접 만들어본 사람의 자신감
한 번 구현해보면, Git을 더는 마법처럼 보지 않게 됩니다. 당신의 손에 객체가 있고, 트리가 있고, 커밋이 있습니다. 브랜치를 옮기고, 로그를 읽고, 병합을 시도하는 모든 경험이 버전 관리라는 큰 그림을 선명하게 합니다. 🚦
이 글을 읽고, 스스로 코드를 변형해보세요. 예를 들어 커밋에 서명을 추가하거나, 변경 감지를 위해 파일 mtime과 크기를 캐시해 성능을 높이는 것도 재밌습니다.
실전 코드와 설계를 담은 이런 콘텐츠를 더 보고 싶다면 ‘지식인의 숲’ 같은 공간—이를테면 재능넷—에서 서로의 실험을 나누는 것도 추천합니다. 공유는 지식을 증폭시키니까요. 🤝
작고 단단한 버전관리의 심장을 손끝으로 느껴보세요.
부록 A: 전체 파일 한 방에 복사본
아래 코드는 본문 조각을 하나로 모은 풀 소스입니다. 복붙해서 실행하면 됩니다.
# minigit.py (full)
import argparse, os, sys, hashlib, zlib, time, json, difflib
from pathlib import Path
MINIGIT_DIR=".minigit"; OBJECTS_DIR="objects"; REFS_DIR="refs"; HEADS_DIR=os.path.join(REFS_DIR,"heads"); TAGS_DIR=os.path.join(REFS_DIR,"tags"); INDEX_FILE="index"; CONFIG_FILE="config"
def repo_path(*parts): return os.path.join(MINIGIT_DIR,*parts)
def ensure_dir(p): Path(p).mkdir(parents=True, exist_ok=True)
def read_file(p, mode="rb"):
with open(p, mode) as f: return f.read()
def write_file(p,data,mode="wb"):
d=os.path.dirname(p);
if d: ensure_dir(d);
with open(p, mode) as f: f.write(data)
def exists(p): return os.path.exists(p)
def repo_init():
if exists(MINIGIT_DIR): print("이미 초기화된 저장소입니다: .minigit"); return
ensure_dir(repo_path()); ensure_dir(repo_path(OBJECTS_DIR)); ensure_dir(repo_path(HEADS_DIR)); ensure_dir(repo_path(TAGS_DIR))
write_file(repo_path("HEAD"), b"ref: refs/heads/main\n")
write_file(repo_path(HEADS_DIR,"main"), b"")
write_file(repo_path(INDEX_FILE), b"{}")
write_file(repo_path(CONFIG_FILE), b'{"user":{"name":"You","email":"you@example.com"}}')
print("Initialized empty MiniGit repository in .minigit/")
def sha1(b:bytes)->str: return hashlib.sha1(b).hexdigest()
def object_path(oid): return repo_path(OBJECTS_DIR, oid[:2], oid[2:])
def hash_object(obj_type:str,data:bytes,write=True)->str:
header=f"{obj_type} {len(data)}".encode()+b"\x00"; store=header+data; oid=sha1(store)
if write:
p=object_path(oid)
if not exists(p): write_file(p, zlib.compress(store))
return oid
def read_object(oid:str)->tuple[str,bytes]:
raw=zlib.decompress(read_file(object_path(oid)))
i=raw.index(b"\x00"); header=raw[:i].decode(); typ,size_str=header.split(" ",1); data=raw[i+1:]; size=int(size_str)
if size!=len(data): raise SystemExit("객체 크기 불일치")
return typ,data
def read_index()->dict:
p=repo_path(INDEX_FILE)
if not exists(p): return {}
return json.loads(read_file(p,"rb").decode() or "{}")
def write_index(idx:dict): write_file(repo_path(INDEX_FILE), json.dumps(idx, ensure_ascii=False, indent=0).encode())
def add(paths):
idx=read_index()
for path in paths:
if os.path.isdir(path):
for root,_,files in os.walk(path):
if MINIGIT_DIR in root: continue
for f in files:
w=os.path.join(root,f)
if w.startswith(MINIGIT_DIR): continue
data=read_file(w,"rb"); oid=hash_object("blob",data,True)
idx[w.replace("\\","/")]={"oid":oid,"mode":"100644"}; print(f"add {w} ({oid[:10]})")
else:
data=read_file(path,"rb"); oid=hash_object("blob",data,True)
idx[path.replace("\\","/")]={"oid":oid,"mode":"100644"}; print(f"add {path} ({oid[:10]})")
write_index(idx)
def build_tree_from_index(index:dict)->str:
entries_by_dir={}
for path,meta in index.items():
parts=path.split("/"); d="/".join(parts[:-1]); name=parts[-1]; entries_by_dir.setdefault(d,[]).append((name,meta))
def build_tree(dir_path:str)->str:
files=[]; subdirs=set()
for (name,meta) in entries_by_dir.get(dir_path,[]): files.append((meta["mode"],name,meta["oid"]))
for p in index.keys():
rest=p[len(dir_path)+1:] if dir_path and p.startswith(dir_path+"/") else (p if not dir_path else None)
if rest is None: continue
if "/" in rest: subdirs.add(rest.split("/")[0])
tree_entries=[]
for mode,name,oid in sorted(files,key=lambda x:x[1]):
ent=f"{mode} {name}".encode()+b"\x00"+bytes.fromhex(oid); tree_entries.append(ent)
for sd in sorted(subdirs):
subdir_path=f"{dir_path}/{sd}" if dir_path else sd
child_oid=build_tree(subdir_path)
ent=f"40000 {sd}".encode()+b"\x00"+bytes.fromhex(child_oid); tree_entries.append(ent)
return hash_object("tree", b"".join(tree_entries), True)
return build_tree("")
def get_config():
p=repo_path(CONFIG_FILE)
if exists(p): return json.loads(read_file(p).decode() or "{}")
return {"user":{"name":"You","email":"you@example.com"}}
def get_head_ref()->tuple[bool,str]:
data=read_file(repo_path("HEAD")).decode().strip()
if data.startswith("ref: "): return True,data[5:]
return False,data
def read_ref(name:str)->str|None:
p=repo_path(name)
if not exists(p): return None
s=read_file(p).decode().strip()
return s if s else None
def update_ref(name:str, oid:str): write_file(repo_path(name),(oid+"\n").encode())
def resolve_head()->str|None:
is_sym,target=get_head_ref()
return read_ref(target) if is_sym else (target or None)
def set_head_detached(oid:str): write_file(repo_path("HEAD"), (oid+"\n").encode())
def set_head_symbolic(refname:str): write_file(repo_path("HEAD"), f"ref: {refname}\n".encode())
def commit_tree(tree_oid:str, parents:list[str], message:str)->str:
cfg=get_config(); name=cfg.get("user",{}).get("name","You"); email=cfg.get("user",{}).get("email","you@example.com")
ts=int(time.time()); tz=time.strftime("%z", time.localtime())
who=f"{name} <{email}> {ts} {tz}"
lines=[f"tree {tree_oid}"]+[f"parent {p}" for p in parents]+[f"author {who}", f"committer {who}","",message]
return hash_object("commit","\n".join(lines).encode(),True)
def commit(message:str):
idx=read_index()
if not idx: print("커밋할 스테이징 내용이 없습니다."); return
tree_oid=build_tree_from_index(idx); head_oid=resolve_head(); parents=[head_oid] if head_oid else []
oid=commit_tree(tree_oid, parents, message); is_sym,refname=get_head_ref()
if is_sym: update_ref(refname, oid)
else: set_head_detached(oid)
print(f"[commit {oid[:10]}] {message}")
def parse_commit(oid:str)->dict:
typ,data=read_object(oid); assert typ=="commit"
text=data.decode("utf-8","replace"); header,_,msg=text.partition("\n\n")
info={"message":msg,"parents":[],"tree":None,"author":None,"committer":None}
for line in header.splitlines():
if line.startswith("tree "): info["tree"]=line[5:]
elif line.startswith("parent "): info["parents"].append(line[7:])
elif line.startswith("author "): info["author"]=line[7:]
elif line.startswith("committer "): info["committer"]=line[10:]
return info
def log():
oid=resolve_head()
if not oid: print("로그가 없습니다. 아직 커밋이 없어요."); return
seen=set()
while oid and oid not in seen:
seen.add(oid); info=parse_commit(oid)
print(f"commit {oid}")
if info["author"]: print(f"Author: {info['author']}")
print("")
for line in info["message"].splitlines(): print(f" {line}")
print("")
oid=info["parents"][0] if info["parents"] else None
def read_tree(oid:str)->list[tuple[str,str,str]]:
typ,data=read_object(oid); assert typ=="tree"; i=0; out=[]
while i<len(data):
j=data.find(b"\x00", i); header=data[i:j].decode(); mode,name=header.split(" ",1); raw_oid=data[j+1:j+21]; child=raw_oid.hex()
out.append((mode,name,child)); i=j+21
return out
def restore_tree(oid:str,base=""):
for mode,name,child in read_tree(oid):
path=os.path.join(base,name) if base else name
if mode=="40000":
ensure_dir(path); restore_tree(child,path)
else:
_,blob=read_object(child); ensure_dir(os.path.dirname(path) or "."); write_file(path, blob)
def tree_to_map(oid:str, base="")->dict:
m={}
for mode,name,child in read_tree(oid):
path=f"{base}/{name}" if base else name
if mode=="40000": m.update(tree_to_map(child, path))
else: m[path]=child
return m
def list_working_files():
out=[]
for root,dirs,files in os.walk("."):
if MINIGIT_DIR in root: continue
for f in files:
p=os.path.join(root,f)
if p.startswith(f"./{MINIGIT_DIR}") or p.startswith(MINIGIT_DIR): continue
out.append(p[2:] if p.startswith("./") else p)
return out
def status():
idx=read_index(); head_oid=resolve_head(); head_map={}
if head_oid: head_map=tree_to_map(parse_commit(head_oid)["tree"])
work=list_working_files()
staged_new,staged_mod,staged_del=[],[],[]
not_staged_mod,not_tracked=[],[]
for path,meta in idx.items():
blob=meta["oid"]; head_blob=head_map.get(path)
if head_blob is None: staged_new.append(path)
elif head_blob!=blob: staged_mod.append(path)
for path in head_map.keys():
if path not in idx: staged_del.append(path)
for w in work:
data=read_file(w,"rb"); cur_blob=sha1(f"blob {len(data)}".encode()+b"\x00"+data)
if w in idx:
if idx[w]["oid"]!=cur_blob: not_staged_mod.append(w)
else:
if w not in head_map: not_tracked.append(w)
print("Changes to be committed:")
for pth in staged_new: print(f" (new) {pth}")
for pth in staged_mod: print(f" (modified) {pth}")
for pth in staged_del: print(f" (deleted) {pth}")
print("\nChanges not staged for commit:")
for pth in not_staged_mod: print(f" (modified) {pth}")
print("\nUntracked files:")
for pth in not_tracked: print(f" {pth}")
def diff(path:str, staged=False):
idx=read_index(); head_oid=resolve_head(); head_map={}
if head_oid: head_map=tree_to_map(parse_commit(head_oid)["tree"])
a=""; b=""
if staged:
if path not in idx: print("인덱스에 없는 파일입니다."); return
_,a_bytes=read_object(idx[path]["oid"]); a=a_bytes.decode("utf-8","replace")
cur=read_file(path,"rb").decode("utf-8","replace") if exists(path) else ""; b=cur
else:
head_blob=head_map.get(path)
if head_blob:
_,a_bytes=read_object(head_blob); a=a_bytes.decode("utf-8","replace")
else: a=""
b=read_file(path,"rb").decode("utf-8","replace") if exists(path) else ""
for line in difflib.unified_diff(a.splitlines(), b.splitlines(), lineterm="", fromfile="a/"+path, tofile="b/"+path): print(line)
def get_head_ref()->tuple[bool,str]:
data=read_file(repo_path("HEAD")).decode().strip()
if data.startswith("ref: "): return True,data[5:]
return False,data
def read_ref(name:str)->str|None:
p=repo_path(name)
if not exists(p): return None
s=read_file(p).decode().strip(); return s if s else None
def update_ref(name:str, oid:str): write_file(repo_path(name),(oid+"\n").encode())
def resolve_head()->str|None:
is_sym,target=get_head_ref()
return read_ref(target) if is_sym else (target or None)
def set_head_detached(oid:str): write_file(repo_path("HEAD"), (oid+"\n").encode())
def set_head_symbolic(refname:str): write_file(repo_path("HEAD"), f"ref: {refname}\n".encode())
def checkout(name_or_oid:str):
ref_candidate=f"refs/heads/{name_or_oid}"
if exists(repo_path(ref_candidate)):
target=read_ref(ref_candidate)
if not target: print("빈 브랜치입니다. 커밋 없음."); return
restore_tree(parse_commit(target)["tree"]); set_head_symbolic(ref_candidate); print(f"Switched to branch '{name_or_oid}'"); return
if exists(object_path(name_or_oid[:40])):
typ,_=read_object(name_or_oid)
if typ!="commit": raise SystemExit("커밋 OID를 지정하세요.")
restore_tree(parse_commit(name_or_oid)["tree"]); set_head_detached(name_or_oid); print(f"Note: switching to detached HEAD at {name_or_oid[:7]}")
else: raise SystemExit(f"대상 없음: {name_or_oid}")
def branch_list():
heads=repo_path(HEADS_DIR)
if not exists(heads): print("(no heads)"); return
is_sym, headref=get_head_ref()
for name in sorted(os.listdir(heads)):
refname=f"refs/heads/{name}"; oid=read_ref(refname); star="*" if (is_sym and ("refs/heads/"+name)==headref) else " "
print(f"{star} {name} {oid[:10] if oid else ''}")
def branch_create(name:str, oid:str|None=None):
if exists(repo_path(HEADS_DIR,name)): raise SystemExit("이미 존재하는 브랜치")
if not oid:
oid=resolve_head()
if not oid: raise SystemExit("HEAD가 비어있습니다.")
update_ref(f"refs/heads/{name}", oid); print(f"브랜치 생성: {name} -> {oid[:10]}")
def is_ancestor(base:str, target:str)->bool:
seen=set(); stack=[target]
while stack:
x=stack.pop()
if x in seen: continue
seen.add(x)
if x==base: return True
stack.extend(parse_commit(x)["parents"])
return False
def merge_ff(branch:str):
refname=f"refs/heads/{branch}"; other=read_ref(refname)
if not other: raise SystemExit("대상 브랜치가 비어있음")
head=resolve_head()
if not head: raise SystemExit("현재 브랜치가 비어있음")
is_sym, curref=get_head_ref()
if not is_sym: raise SystemExit("detached HEAD 상태에서는 병합 불가(단순화)")
if is_ancestor(head, other):
update_ref(curref, other); restore_tree(parse_commit(other)["tree"]); print(f"Fast-forward: {curref.split('/')[-1]} -> {branch}")
else:
print("Fast-forward 불가. 3-way 머지가 필요합니다. (이 구현은 안내만)")
def tag_create(name:str, oid:str|None=None):
if not oid: oid=resolve_head()
if not oid: raise SystemExit("태그할 커밋이 없습니다.")
refname=f"refs/tags/{name}"
if exists(repo_path(refname)): raise SystemExit("이미 존재하는 태그")
update_ref(refname, oid); print(f"tag {name} -> {oid[:10]}")
def main():
p=argparse.ArgumentParser(prog="minigit", description="Mini Git implemented in Python")
sub=p.add_subparsers(dest="cmd")
sub.add_parser("init")
ap_add=sub.add_parser("add"); ap_add.add_argument("paths", nargs="+")
ap_commit=sub.add_parser("commit"); ap_commit.add_argument("-m","--message", required=True)
sub.add_parser("log")
ap_co=sub.add_parser("checkout"); ap_co.add_argument("name")
ap_br=sub.add_parser("branch"); ap_br.add_argument("subcmd", nargs="?", default="list", choices=["list","create"]); ap_br.add_argument("name", nargs="?")
ap_merge=sub.add_parser("merge"); ap_merge.add_argument("branch")
sub.add_parser("status")
ap_diff=sub.add_parser("diff"); ap_diff.add_argument("path"); ap_diff.add_argument("--staged", action="store_true")
ap_tag=sub.add_parser("tag"); ap_tag.add_argument("name"); ap_tag.add_argument("--oid")
args=p.parse_args()
if args.cmd=="init": repo_init()
elif args.cmd=="add": add(args.paths)
elif args.cmd=="commit": commit(args.message)
elif args.cmd=="log": log()
elif args.cmd=="checkout": checkout(args.name)
elif args.cmd=="branch":
if args.subcmd=="list": branch_list()
else:
if not args.name: print("브랜치 이름 필요"); return
branch_create(args.name)
elif args.cmd=="merge": merge_ff(args.branch)
elif args.cmd=="status": status()
elif args.cmd=="diff": diff(args.path, staged=args.staged)
elif args.cmd=="tag": tag_create(args.name, args.oid)
else: p.print_help()
if __name__=="__main__":
if len(sys.argv)>1 and sys.argv[1]=="init": main()
else:
if not exists(MINIGIT_DIR): print("여긴 미니Git 저장소가 아닙니다. 먼저 'minigit init'을 실행하세요.")
main()
부록 B: 디버깅 레시피
- 객체 손상 의심 시: 최근 생성된 OID로 파일을 찾아 zlib.decompress 후 헤더/길이 일치 확인.
- 잘못된 HEAD: .minigit/HEAD에 ref가 맞는지 체크, 필요한 경우 직접 OID/심볼릭 교정.
- 인덱스 정리: .minigit/index를 비우고 다시 add로 재구성.
댓글 작성
이 글에 대한 여러분의 생각을 들려주세요
로그인이 필요합니다
댓글을 작성하려면 먼저 로그인해주세요.
댓글 0
지식인의 숲 - 지적 재산권 보호 고지
지적 재산권 보호 고지
- 저작권 및 소유권: 본 컨텐츠는 재능넷의 독점 AI 기술로 생성되었으며, 대한민국 저작권법 및 국제 저작권 협약에 의해 보호됩니다.
- AI 생성 컨텐츠의 법적 지위: 본 AI 생성 컨텐츠는 재능넷의 지적 창작물로 인정되며, 관련 법규에 따라 저작권 보호를 받습니다.
- 사용 제한: 재능넷의 명시적 서면 동의 없이 본 컨텐츠를 복제, 수정, 배포, 또는 상업적으로 활용하는 행위는 엄격히 금지됩니다.
- 데이터 수집 금지: 본 컨텐츠에 대한 무단 스크래핑, 크롤링, 및 자동화된 데이터 수집은 법적 제재의 대상이 됩니다.
- AI 학습 제한: 재능넷의 AI 생성 컨텐츠를 타 AI 모델 학습에 무단 사용하는 행위는 금지되며, 이는 지적 재산권 침해로 간주됩니다.
아직 댓글이 없습니다.