Programing

중간에 커밋하지 않고 두 커밋 사이의 변경 사항을 보는 방법은 무엇입니까?

lottogame 2020. 10. 3. 09:44
반응형

중간에 커밋하지 않고 두 커밋 사이의 변경 사항을 보는 방법은 무엇입니까?


git diff중간에있는 다른 커밋을 제외하고 두 커밋의 차이점 만 보여 주려면 어떻게해야 합니까?


다음과 같이 2 개의 커밋을 git diff에 간단히 전달할 수 있습니다.

-> git diff 0da94be  59ff30c > my.patch
-> git apply my.patch

두 커밋 사이에 커밋을 포함하지 않고 차이 / between /을 요청하는 것은 거의 의미가 없습니다. 커밋은 저장소 콘텐츠의 스냅 샷일뿐입니다. 둘 사이의 차이를 요구하는 것은 반드시 그들을 포함합니다. 그래서 질문은, 당신은 정말로 무엇을 찾고 있습니까?

William이 제안했듯이 체리 피킹은 다른 커밋 위에 리베이스 된 단일 커밋의 델타를 제공 할 수 있습니다. 그건:

$ git checkout 012345
$ git cherry-pick -n abcdef
$ git diff --cached

이것은 커밋 'abcdef'를 취하고 직계 조상과 비교 한 다음 그 차이 를 '012345'위에 적용 합니다 . 이 새로운 차이점이 표시됩니다. 유일한 변경 사항은 'abcdef'의 직계 조상이 아닌 '012345'에서 나온 컨텍스트입니다. 물론 충돌 등이 발생할 수 있으므로 대부분의 경우 매우 유용한 프로세스는 아닙니다.

abcdef 자체에만 관심이 있다면 다음을 수행 할 수 있습니다.

$ git log -u -1 abcdef

이것은 abcdef를 직계 조상과 단독으로 비교하며 일반적으로 원하는 것입니다.

그리고 물론

$ git diff 012345..abcdef

이 두 커밋 사이의 모든 차이점을 제공합니다.

달성하려는 것이 무엇인지에 대한 더 나은 아이디어를 얻는 데 도움이 될 것입니다. 앞서 언급했듯이 두 커밋 사이의 차이를 요청하는 것은 실제로 의미가 없습니다.


두 개의 git 커밋 12345와 abcdef를 패치로 비교하려면 diff 명령을 다음과 같이 사용할 수 있습니다.

diff <(git show 123456) <(git show abcdef)

git diff <a-commit> <another-commit> path

예:

git diff commit1 commit2 config/routes.rb

해당 커밋 간의 해당 파일의 차이점을 보여줍니다.


이것을 가지고 있다고 가정 해 봅시다.

A
|
B    A0
|    |
C    D
\   /
  |
 ...

그리고 당신은 A 동일하다 A0.

이것은 트릭을 할 것입니다.

$ git diff B A > B-A.diff
$ git diff D A0 > D-A0.diff
$ diff B-A.diff D-A0.diff

전체 변경 사항을 확인하려면 :

  git diff <commit_Id_1> <commit_Id_2>

변경 / 추가 / 삭제 된 파일 만 확인하려면 :

  git diff <commit_Id_1> <commit_Id_2> --name-only

노트 : 커밋하지 않고 diff를 확인하기 위해 커밋 ID를 넣을 필요가 없습니다.


커밋 012345와 abcdef의 차이를보고 싶다고 가정합니다. 다음은 원하는 작업을 수행해야합니다.

$ git checkout 012345
$ git cherry-pick -n abcdef
$ git diff --cached

이것에 대해 :

git diff abcdef 123456 | less

즉석에서 많은 다른 diff를 비교하려면 더 적은 수로 파이프하는 것이 편리합니다.


대한 파일의 alias설정 :~/.bashrcgit diff

alias gdca='git diff --cached' # diff between your staged file and the last commit
alias gdcc='git diff HEAD{,^}' # diff between your recent tow commits

영어가 제 모국어가 아닙니다. 입력 오류를 용서해주십시오.


Git 2.19부터 다음을 간단히 사용할 수 있습니다.

git range-diff rev1...rev2 -공통 조상으로 시작하여 두 개의 커밋 트리 비교

또는 git range-diff rev1~..rev1 rev2~..rev2-주어진 커밋 2 개에 의해 도입 된 변경 사항 비교


두 커밋 간의 차이를 표시하는 스크립트를 작성했으며 Ubuntu에서 잘 작동합니다.

https://gist.github.com/jacobabrahamb4/a60624d6274ece7a0bd2d141b53407bc

#!/usr/bin/env python
import sys, subprocess, os

TOOLS = ['bcompare', 'meld']

def getTool():
    for tool in TOOLS:
        try:
            out = subprocess.check_output(['which', tool]).strip()
            if tool in out:
                return tool
        except subprocess.CalledProcessError:
            pass
    return None

def printUsageAndExit():
    print 'Usage: python bdiff.py <project> <commit_one> <commit_two>'
    print 'Example: python bdiff.py <project> 0 1'
    print 'Example: python bdiff.py <project> fhejk7fe d78ewg9we'
    print 'Example: python bdiff.py <project> 0 d78ewg9we'
    sys.exit(0)

def getCommitIds(name, first, second):
    commit1 = None
    commit2 = None
    try:
        first_index = int(first) - 1
        second_index = int(second) - 1
        if int(first) < 0 or int(second) < 0:
            print "Cannot handle negative values: "
            sys.exit(0)
        logs = subprocess.check_output(['git', '-C', name, 'log', '--oneline', '--reverse']).split('\n')
        if first_index >= 0:
            commit1 = logs[first_index].split(' ')[0]
        if second_index >= 0:
            commit2 = logs[second_index].split(' ')[0]
    except ValueError:
        if first != '0':
            commit1 = first
        if second != '0':
            commit2 = second
    return commit1, commit2

def validateCommitIds(name, commit1, commit2):
    if commit1 == None and commit2 == None:
        print "Nothing to do, exit!"
        return False
    try:
        if commit1 != None:
            subprocess.check_output(['git', '-C', name, 'cat-file', '-t', commit1]).strip()
        if commit2 != None:
            subprocess.check_output(['git', '-C', name, 'cat-file', '-t', commit2]).strip()
    except subprocess.CalledProcessError:
        return False
    return True

def cleanup(commit1, commit2):
        subprocess.check_output(['rm', '-rf', '/tmp/'+(commit1 if commit1 != None else '0'), '/tmp/'+(commit2 if commit2 != None else '0')])

def checkoutCommit(name, commit):
    if commit != None:
        subprocess.check_output(['git', 'clone', name, '/tmp/'+commit])
        subprocess.check_output(['git', '-C', '/tmp/'+commit, 'checkout', commit])
    else:
        subprocess.check_output(['mkdir', '/tmp/0'])

def compare(tool, commit1, commit2):
        subprocess.check_output([tool, '/tmp/'+(commit1 if commit1 != None else '0'), '/tmp/'+(commit2 if commit2 != None else '0')])

if __name__=='__main__':
    tool = getTool()
    if tool == None:
        print "No GUI diff tools"
        sys.exit(0)
    if len(sys.argv) != 4:
        printUsageAndExit()

    name, first, second = None, 0, 0
    try:
        name, first, second = sys.argv[1], sys.argv[2], sys.argv[3]
    except IndexError:
        printUsageAndExit()

    commit1, commit2 = getCommitIds(name, first, second)

    if not validateCommitIds(name, commit1, commit2):
        sys.exit(0)

    cleanup(commit1, commit2)
    checkoutCommit(name, commit1)
    checkoutCommit(name, commit2)

    try:
        compare(tool, commit1, commit2)
    except KeyboardInterrupt:
        pass
    finally:
        cleanup(commit1, commit2)
    sys.exit(0)

My alias settings in ~/.zshrc file for git diff:

alias gdf='git diff HEAD{'^',}' # diff between your recent tow commits

Thanks @Jinmiao Luo

참고URL : https://stackoverflow.com/questions/1191282/how-to-see-the-changes-between-two-commits-without-commits-in-between

반응형