홈 › Git › 04 / 8

원격 저장소

섹션 7진행 0 / 8

3. 코드 예제

예제 1: 원격 등록과 clone — 01_remote.sh 발췌

bash
git init -q --bare -b main "$ORIGIN"
git clone -q "$ORIGIN" "$WORK/A"
cd "$WORK/A"
git remote -v
git remote add upstream "$UPSTREAM"
git remote -v
git remote rename upstream up2
git remote remove up2
text
origin  WORK/origin.git (fetch)
origin  WORK/origin.git (push)
origin  WORK/origin.git (fetch)
origin  WORK/origin.git (push)
upstream  WORK/upstream.git (fetch)
upstream  WORK/upstream.git (push)

빈 저장소를 clone 하면 "cloned an empty repository" 경고가 뜹니다. remote add 뒤에는 두 원격이 같이 보이고, rename·remove 뒤에는 다시 origin 만 남습니다.

예제 2: push, fetch, log, pull — 01_remote.sh 발췌

bash
git add README.md
git commit -q -m "커밋1: README 초기 작성"
git push -u origin main

# (다른 작업 폴더 B 에서)
git clone -q "$ORIGIN" "$WORK/B"
cd "$WORK/B"
git branch -vv
text
* main ff1fc34 [origin/main] 커밋1: README 초기 작성

branch -vv 의 [origin/main] 표시가 추적 브랜치입니다. B 는 clone 하면서 자동으로 추적이 설정됩니다.

이어서 A 가 두 번째 커밋을 push 한 뒤 B 가 받는 과정입니다.

bash
git fetch origin
git log --oneline main..origin/main
git pull
text
-- log main..origin/main (아직 받지 않은 커밋) --
675aeaf 커밋2: 설치 방법 추가
Updating ff1fc34..675aeaf
Fast-forward
 README.md | 1 +
 1 file changed, 1 insertion(+)

fetch 직후에는 origin/main 만 앞서 있고 로컬 main 은 그대로입니다. main..origin/main 로그가 그 차이를 보여줍니다. pull 을 해야 로컬 main 도 빨리 감기로 따라갑니다.

예제 3: push 거부와 pull --rebase — 01_remote.sh 발췌

B 가 먼저 커밋하고 push 한 뒤, A 가 그 사실을 모른 채 커밋하고 push 를 시도합니다.

bash
# A 에서
git commit -q -m "커밋4: 라이선스 추가 (A)"
git push
text
 ! [rejected]        main -> main (fetch first)
error: failed to push some refs to 'WORK/origin.git'
hint: Updates were rejected because the remote contains work that you do not
hint: have locally. This is usually caused by another repository pushing to
hint: the same ref. If you want to integrate the remote changes, use
hint: 'git pull' before pushing again.

git pull 도 pull.ff only 설정 때문에 그냥은 거부됩니다. fetch 로 받은 뒤 pull --rebase 로 내 커밋을 원격 위에 재배치해야 합니다.

bash
git fetch
git pull --rebase
git log --oneline
git push
text
Rebasing (1/1)Successfully rebased and updated refs/heads/main.
238dc37 커밋4: 라이선스 추가 (A)
2bf0644 커밋3: 사용법 예제 추가 (B)
675aeaf 커밋2: 설치 방법 추가
ff1fc34 커밋1: README 초기 작성
-- git push (재시도, 성공) --
To WORK/origin.git
   2bf0644..238dc37  main -> main

rebase 로 커밋4 의 해시(238dc37)가 바뀌었습니다. 부모가 커밋2 에서 커밋3 으로 바뀌었기 때문입니다. 이제는 원격보다 앞서 있으므로 push 가 성공합니다.

예제 4: bundle 로 폐쇄망 반입 — 01_remote.sh 발췌

bash
git bundle create "$WORK/repo.bundle" --all
git bundle verify "$WORK/repo.bundle"
git clone -q "$WORK/repo.bundle" "$WORK/C"
text
The bundle records a complete history.
The bundle uses this hash algorithm: sha1
WORK/repo.bundle is okay

--all 을 빼면 현재 브랜치만 담깁니다. verify 로 필요한 커밋이 모두 들어 있는지 확인한 뒤에 반입합니다. 이제 C 는 네트워크 없이도 repo.bundle 파일 하나로 완성된 저장소를 갖습니다.