Git & Tips




1. 일반 #

1.1. 알아두면 좋은 기능 #

1.1.1. alias g='git' #
예) .bashrc 에 alias 기록
alias gs='git status -s'
alias gp='git pull'
1.1.2. stashing #
현재 브랜치에서 작업중인 내용을 임시로 저장하고 다른 브랜치로 이동할 때 사용한다.
1.1.3. blame #
파일 라인 단위로 누가 마지막으로 수정했는지 보여준다.
http://git-scm.com/docs/git-blame

2. commit #

2.1. commit 메시지 수정 #

2.1.1. 마지막 커밋을 수정하기 #
$ git commit --amend
마지막 커밋을 수정하는 방법은 매우 간단하다. 이 명령으로 텍스트 편집기가 열리고 메시지를 수정하면 된다.

2.1.2. 커밋 메시지를 여러 개 수정하기 #
예를 들어 마지막 세 번째에 있는 커밋 로그를 수정하고 싶다면 rebase -i를 사용해서 수정한다. 주의할 점은 이미 서버에 push된 커밋은 SHA-1 값이 바뀌기 때문에 가능하면 수정하지 말아야 한다. 만약 rebase에 익숙하지 않다면 다음을 주의 깊게 봐야 한다. https://git-scm.com/book/ko/v1/Git-도구-히스토리-단장하기

$ git rebase -i HEAD~3

텍스트 편집기가 열리면 다음 같은 커밋 목록이 첨부되어 있다.

pick ...
pick ...
pick ...

여기서 커밋 목록 순서는 위쪽이 오래된 것이다. 마지막 세 번째 커밋 메시지를 수정하려면 pick을 edit로 변경하고 저장 및 종료한다.

edit ...
pick ...
pick ...

저장하고 편집기를 종료하면 Git은 목록에 있는 커밋 중에서 가장 오래된 커밋으로 이동하고, 아래와 같이 다음은 어떻게 해야 하는지 메시지를 보여준다.

$ git rebase -i HEAD~3
Stopped at 7482e0d... updated the gemspec to hopefully work better
You can amend the commit now, with

       git commit --amend

Once you’re satisfied with your changes, run

       git rebase --continue

마지막 커밋 메시지를 변경했을 때와 같이 git commit --amend 으로 메시지를 변경하고 git rebase --continue로 rebase를 계속한다. 이것을 반복하면 어떤 위치의 커밋 메시지도 수정할 수 있다. 다시 말하지만 주의할 점은 이미 서버에 push된 커밋은 rebase를 하면 SHA-1 값이 바뀌기 때문에 동료 개발자들을 혼란스럽게 할 가능성이 있다. 될 수 있으면 수정하지 말아야 한다.

3. log #

3.1. log .. 커밋 범위 지정하여 로그 보기 #

$ git log START_COMMIT..END_COMMIT
ex) git log ea87e9..60a6da

3.2. log --since= 특정 날짜 이전/이후 commit만 출력 #

$ git log --sinceafter,until,before
ex) git log --before="2018-07-15"

3.3. log -N 개수 출력 #

$ git log -2
2개만 출력

3.4. log --pretty= commit 메시지의 첫 번째 줄만 출력 #

$ git log --pretty=short

3.5. log -p 특정 브랜치 변경된 내용을 출력 #

$ git log -p <브랜치이름>

$ git log -p <브랜치이름> -- <파일/경로/이름.cpp>
특정 브랜치의 특정 파일 변경된 내용을 출력

3.6. log --graph 브랜치를 시각적으로 출력 #

$ git log --graph

4. show #

4.1. 기본 사용법 #

$ git show
현재 브랜치의 가장 최근 커밋 정보를 확인

$ git show 커밋해시값
특정 커밋 정보를 확인

$ git show HEAD
HEAD 포인터가 가리키는 커밋정보를 확인

$ git show HEAD:/파일/경로/파일이름.cpp
HEAD 포인터의 파일 내용을 확인

5. branch #

5.1. 브랜치 확인 #

현재 브랜치
$ git branch
모든 브랜치
$ git branch -a

5.2. 브랜치를 만들고 변경 #

예) <new-branch> 브랜치로 변경
$ git checkout -b <new-branch>

checkout -bgit branch <new-branch> 브랜치를 만들고, git checkout <new-branch> <new-branch> 브랜치로 이동하는 것과 동일함.

5.3. 브랜치 제거 #

$ git branch -D <branch-name>

6. merge #

6.1. 브랜치, commit id 머지 #

예)
머지 대상 브랜치: develop
머지 브랜치: <branch-name>
또는 머지 commit id: <commit-id>

git checkout develop
git merge --no-ff <branch-name>
git merge --no-ff <commit-id>

The --no-ff flag prevents git merge from executing a "fast-forward" if it detects that your current HEAD is an ancestor of the commit you're trying to merge.

6.2. 머지 conflict 해결 #

머지할 때 conflict가 발생해도 간단히 해결할 수 있기 때문에 당황할 필요가 없다.
Merge conflict를 해결할 때 IDE의 도움을 받을 수도 있지만 수동으로 해결하는 과정을 알아두면 도움이 된다.

예)
1. 충돌 발생
<<<<<<< HEAD
...
=======
...
>>>>>>> <this-branch> changes

2. 충돌이 발생한 코드에서 <<< (upstream change), >>> (작업 중인 change) 코드를 직접 확인하며 적절한 코드를 선택하거나 병합하여 충돌을 해결한 다음 저장한다.

3. 병합한 코드에 문제가 없으면 commit 한다.
$ git add <conflict-files>
$ git commit -m 'Fix conflict'

4. 다시 merge 한다.

6.3. prevents the MERGE COMMIT to occur #

$ git merge --no-commit

--no-ff 와 같이 사용할 수 있다.
$ git merge --no-ff --no-commit$

6.4. 머지 취소 #

$ git merge --abort
머지 수행 전 상태로 돌아간다.

7. stash #

7.1. 기본 명령 #

* 현재 작업 상태 stash 저장
$ git stash

* 저장된 stash 확인
$ git stash list

* 저장된 stash 적용하고 제거
$ git stash pop

* 저장된 stash 적용하고 제거하지 않음
$ git stash apply

* 특정 stash만 제거할 때
$ git stash list
stash@{0}: WIP on master: 049d078 added the index file
stash@{1}: WIP on master: c264051 Revert "added file_size"
stash@{2}: WIP on master: 21d80a5 added number to log
$ git stash drop stash@{0}
Dropped stash@{0} (364e91f3f268f0900bc3ee613f9f733e82aaed43)

7.2. How can I delete all of my Git stashes at once? #

It does what you need:
$ git stash clear
from git documentation

8. patch #

8.1. 생성 #

$ git diff > <patch-file>
$ git diff --no-prefix > <patch-file>

8.2. 적용 #

--no-prefix 옵션 없이 패치파일 생성한 경우 -p1 (diff의 a/ b/ path prefix 무시)
$ cd path/to/top                   # 패치하고자 하는 소스 위치
$ patch -p1 < patchfile            # 패치 적용
$ cd path/to/top                   # 패치하고자 하는 소스 위치
$ patch -p0 < patchfile            # 패치 적용

9. config #

9.1. git config 순서 및 위치 #

$ git config --system
## /etc/gitconfig

$ git config --global
## ~/.gitconfig

$ git config --local
## repo/.gitconfig
각 설정 파일에 중복된 설정이 있으면 system부터 순서대로 덮어 씌운다. 즉, git은 가장 먼저 /etc/gitconfig을 찾고, 다음으로 ~/.gitconfig 순서로 찾는다.

9.2. editor 변경 #

$ git config --global core.editor editor경로

ex)
$ git config --global core.editor vim

9.3. CRLF 문제 #


2줄 요약
  • CORE.EOL
    • core.eol = native 기본 설정. 시스템에서 line ending 을 처리하는 방법에 따른다. windows에서는 CRLF 를 사용하고 Linux, OS X 는 LF 만 사용한다.
    • core.eol = crlf CRLF 를 line ending 으로 사용한다.
    • core.eol = lf LF를 line ending 으로 사용한다.
  • CORE.AUTOCRLF
    • core.autocrlf = false 기본 설정이다. 파일에 CRLF 를 썼든 LF 를 썼든 git 은 상관하지 않고 파일 그대로 checkin, checkout 한다. 이 설정은 line ending 이 다른 OS 에서는 text file 이 변경되었다고 나오므로 위에서 언급한 여러 가지 문제가 발생할 수 있다.
    • core.autocrlf = true text file을 object database 에 넣기전에 CRLF 를 LF 로 변경한다.
    • core.autocrlf = input LF를 line ending 으로 사용한다.

## 설정
$  git config --global core.eol native
  
## 설정 확인
$  git config --global --list|grep core.eol

10. 기타 #

10.1. git 작업내역 완전 초기화 #

$ git reset --hard
$ git clean -fd
git clone 상태와 동일하게 바꿔주는 git 명령.

10.2. git 파일이나 폴더 이름 변경 #

$ git mv oldName newName

git 으로 버전 관리할 경우 파일이나 폴더의 이름 변경도 추적할 수 있어야 한다.
특히 리팩토링시 클래스나 패키지 폴더의 이름 변경은 자주 발생하는 작업이므로 변경 내역을 잘 관리해야 한다.

<!> 변경 사항을 추적하기 어려워지니 절대 삭제후 add 하지 마십시오.
-n( --dry-run) 옵션을 사용하면 적용전에 어떻게 변경되는지 테스트가 가능하다.

10.3. fixup #



10.4. cherry-pick 중 conflicts 해결 #

1. conflict 발생 파일 수정

2. Merge 상태 제거(reset) 후 add
stash 하는 방법도 있지만 이 방법이 가장 쉬운 방법이다.
$ git reset filename
$ git add filename

10.5. gerrit에 push 할 때 unpacker error 발생 시 #

unpacker error는 --no-thin 옵션으로 packing을 하지 않고 push 하면 진행될 수 있다.

$ git push origin HEAD:refs/for/master --no-thin

10.6. .gitignore #

10.6.1. Visual Studio #

(※ .gitignore는 확장자가 아니다. 오직 .gitignore 파일만 적용 된다.)

10.7. Passing ssh options to git clone #

* run git clone without checking the repository host's key
$ git config core.sshCommand 'ssh -o StrictHostKeyChecking=no'

10.8. Emoji for GitHub #

http://www.emoji-cheat-sheet.com/
Emoji emoticons listed on this page are supported on Campfire, GitHub, Basecamp, Redbooth, Trac, Flowdock, Sprint.ly, Kandan, Textbox.io, Kippt, Redmine, JabbR, Trello, Hall, Plug.dj, Qiita, Zendesk, Ruby China, Grove, Idobata, NodeBB Forums, Slack, Streamup, OrganisedMinds, Hackpad, Cryptbin, Kato, Reportedly, Cheerful Ghost, IRCCloud, Dashcube, MyVideoGameList, Subrosa, Sococo, Quip, And Bang, Bonusly, Discourse, Ello, Twemoji Awesome, Got Chosen, Flow, ReadMe.io, esa, DBook, Groups.io, TeamworkChat, Damn Bugs, Let's Chat, Buildkite, ChatGrape, Dokuwiki, Usersnap, Discord, Status Hero, Bitbucket, Gitter, and YouTube.

이 글에는 0 개의 댓글이 있습니다.