git add - 使用difftool的补丁

时间:2012-01-26 19:19:18

标签: git

是否可以将Git配置为使用我配置的difftool git add --patch

我想通过我自己的difftool选择要添加到索引的更改。

5 个答案:

答案 0 :(得分:10)

不,不幸的是。

我想我可以看到工作--Git根据当前索引中的内容生成一个临时文件,将其与当前工作树版本的副本一起交给difftool(以防止您进行进一步的更改),让您使用difftool将一些更改移动到索引版本,然后一旦您保存并退出,将分析该修改后的索引版本中的任何内容。请注意,这将需要difftool也是一个编辑器,并不是所有有效的difftools;其中一些仅用于查看差异。另请注意,这基本上绕过了git add -p所有。你不会有任何正常的界面来在帅哥之间移动,分裂帅哥等等。 difftool将完全负责所有这些。

如果你的difftool功能齐全,可以做到这一点,那么我想你可以编写一个脚本来完成它。大纲,没有任何错误保护,处理特殊情况(二进制文件?),并且完全未经测试:

#!/bin/bash
tmpdir=$(mktemp -d)
git diff --name-only |
while read file; do
    cp "$file" $tmpdir
    # this has your changes in it
    work_tree_version="$tmpdir/$file"
    # this has the pristine version
    index_version=$(git checkout-index --temp "$file")
    # and now you bring changes from the work tree version into the index version,
    # within the difftool, and save the index version and quit when done
    my_difftool "$work_tree_version" "$index_version"

    # swap files around to run git add
    mv "$file" "$work_tree_version"
    mv "$index_version" "$file"
    git add "$file"
    mv "$work_tree_version" "$file"
    # you could also do this by calculating the diff and applying it directly to the index
    # git diff --no-index -- "$file" "$original_index_version" | git apply --cached

rm -r $tmpdir

可能有很多方法可以改善这种状况;抱歉,我现在没有时间小心谨慎。

答案 1 :(得分:3)

此处为my script,为您执行2个文件合并打开kdiff3。如果您不喜欢kdiff3,请为MERGETOOLMERGECMD提供您自己的值(但您不会喜欢kdiff3)。

为避免出现意外,此脚本会尝试模仿git add -p至参数和错误代码。 (它处理文件和目录列表。)

另外,它可以正确处理各种角落案例,包括:

  • 用户尝试在非git目录中运行脚本(中止并显示错误)
  • 用户在完成(提前退出)
  • 之前点击Ctrl+C
  • 用户拒绝在difftool中保存合并结果(然后不要使用它,而是转到下一个文件)
  • difftool出现意外错误(提前停止)

使用示例:

$ ## With kdiff3 (default):
$ add-with-mergetool myfile1.txt
$ add-with-mergetool some-directory

$ ## ...or with custom mergetool:
$ export MERGETOOL='opendiff'
$ export MERGECMD='$MERGETOOL $LOCAL $REMOTE -merge $MERGED'
$ add-with-mergetool some-directory/*.py
#!/bin/bash
#
# add-with-mergetool
# Author: Stuart Berg (http://github.com/stuarteberg)
# 
# This little script is like 'git add --patch', except that 
# it launches a merge-tool to perform the merge.

# TODO: For now, this script hard-codes MERGETOOL and MERGECMD for kdiff3.
#       Modify those variables for your own tool if you wish.
#       In the future, it would be nice if we could somehow read  
#       MERGETOOL and MERGECMD from the user's git-config.

# Configure for kdiff3
# (and hide warnings on about modalSession, from kdiff3 on OSX)
MERGETOOL=${MERGETOOL-kdiff3}
MERGECMD=${MERGECMD-'"${MERGETOOL}" "${LOCAL}" "${REMOTE}" -o "${MERGED}"'\
                    2>&1 | grep -iv modalSession}

main() {
    check_for_errors "$@"
    process_all "$@"
}

check_for_errors() {
    which "${MERGETOOL}" > /dev/null
    if [[ $? == 1 ]]; then
        echo "Error: Can't find mergetool: '${MERGETOOL}'" 1>&2
        exit 1
    fi

    if [[ "$1" == "-h" ]]; then
        echo "Usage: $(basename $0) [<pathspec>...]" 1>&2
        exit 0
    fi

    # Exit early if we're not in a git repo
    git status > /dev/null || exit $?
}

process_all() {
    repo_toplevel=$(git rev-parse --show-toplevel)

    # If no args given, add everything (like 'git add -p')
    if [[ $# == 0 ]]; then
        set -- "$repo_toplevel"
    fi

    # For each given file/directory...
    args=( "$@" )
    for arg in "${args[@]}"
    do
        # Find the modified file(s)
        changed_files=( $(git diff --name-only -- "$arg") )
        (
            # Switch to toplevel, to easily handle 'git diff' output
            cd "$repo_toplevel"

            # For each modified file...
            for f in "${changed_files[@]}"
            do
                if [[ $startmsg_shown != "yes" ]]; then
                    echo "Starting $(basename $0).  Use Ctrl+C to stop early."
                    echo "To skip a file, quit ${MERGETOOL} without saving."
                    echo
                    startmsg_shown="yes"
                fi

                # This is where the magic happens.            
                patch_file_and_add "$f"
            done
        ) || exit $? # exit early if loop body failed
    done
}

# This helper function launches the mergetool for a single file,
#  and then adds it to the git index (if the user saved the new file).
patch_file_and_add() {
    f="$1"
    git show :"$f" > "$f.from_index" # Copy from the index
    (
        set -e
        trap "echo && exit 130" INT # Ctrl+C should trigger abnormal exit

        # Execute 2-file merge
        echo "Launching ${MERGETOOL} for '$f'."
        LOCAL="$f.from_index"
        REMOTE="$f"
        MERGED="$f.to_add"
        eval "${MERGECMD}"

        if [[ -e "$f.to_add" ]]; then
            mv "$f" "$f.from_working" # Backup original from working-tree
            mv "$f.to_add" "$f"       # Replace with patched version
            git add "$f"              # Add to the index
            mv "$f.from_working" "$f" # Restore the working-tree version
        fi
    )
    status=$?
    rm "$f.from_index" # Discard the old index version
    if [ $status == 130 ]; then
        echo "User interrupted." 1>&2
        exit $status
    elif [ $status != 0 ]; then
        echo "Error: Interactive add-patch stopped early!" 1>&2
        exit $status
    fi
}

main "$@"

答案 2 :(得分:2)

如果vimdiff是.gitconfig中的difftool:

[diff]
    tool = vimdiff

您也可以站在文件屏幕上执行以下命令:

:!git add %

答案 3 :(得分:1)

我喜欢Cascabel和Stuart的答案,因为它们显示了如何编写完成所需任务的封面的脚本。他们使用git add代替了问题所陈述的git add --patch,但仍然本着问题的精神。另一种选择是使用git add --edit,它的优点是根本不需要修改工作树。从逻辑上来说,我的答案是对Stuart脚本的一个小改动。

我在git add --patch上遇到的问题是,它本质上是交互式的,因此很难覆盖脚本。 Stuart的方法是使用差异工具来确定所需的索引完整内容,然后使用git add来实现。我的方法的不同之处在于,在调用git add之前和之后,我没有修改工作树,而是获取了所需的完整内容,并将其变成可应用于索引的补丁。然后可以使用EDITOR="mv \"$PATCH\"" git add --edit来做到这一点。这样可以避免修改工作树。

要使用此方法,请从Stuart的脚本开始,并用以下内容替换patch_file_and_add的定义:

patch_file_and_add() {
    f="$1"
    base=$(basename "$f")
    dir=$(mktemp -d)
    mkdir "$dir/working"
    mkdir "$dir/index"
    mkdir "$dir/merged"
    LOCAL="$dir/working/$base"
    REMOTE="$dir/index/$base"
    MERGED="$dir/merged/$base"
    PATCH1="$dir/head.patch"
    PATCH="$dir/full.patch"
    git show :"$f" > "$REMOTE" # Copy from the index
    (
        set -e
        trap "echo && exit 130" INT # Ctrl+C should trigger abnormal exit

        # Execute 2-file merge
        echo "Launching ${MERGETOOL} for '$f'."
        cp "$f" "$LOCAL"
        eval "${MERGECMD}"

        if [[ -e "$MERGED" ]]; then
            git diff -- "$f" > "$PATCH1" 2> /dev/null
            git diff --staged -- "$f" >> "$PATCH1" 2> /dev/null
            # We need both of the above in case one is empty.
            head -4 "$PATCH1" > "$PATCH"
            diff --unified=7 "$REMOTE" "$MERGED" | tail -n +3 >> "$PATCH"
            # Now we have the patch we want to apply to the index.
            EDITOR="mv \"$PATCH\"" git add -e -- "$f"
        fi
        rm -rf "$dir"
    )
    status=$?
    if [ $status == 130 ]; then
        echo "User interrupted." 1>&2
        exit $status
    elif [ $status != 0 ]; then
        echo "Error: Interactive add-patch stopped early!" 1>&2
        exit $status
    fi
}

严格来说,可以将LOCAL设置为$f,而不必使用mv将其放在其他位置。但是我似乎记得,一些第三方差异程序允许隐藏路径的公共初始部分,因此这种方法可以利用该功能。

感谢Cascabel和Stuart的出色回答,以及HaxElit的出色问题。

答案 4 :(得分:-1)

不幸的是没有。

目前我所知道的唯一用户界面是git-gui的一部分,当被调用为

git gui citool

另一个UI是作为

调用时的交互式控制台UI
git add -i

git difftool允许一些不同的工具选项,但不允许添加接口。