3

我正在尝试获取git diff2 个字符串之间的值。以下命令有效:

git diff $(echo "my first string" | git hash-object -w --stdin) $(echo "my second string" | git hash-object -w --stdin)  --word-diff

但是,如果不在 Git 目录中执行,它会失败。

我相信这部分命令失败了:

echo "my first string" | git hash-object -w --stdin

有没有办法解决这个问题,以便它可以在 Git 目录之外执行?

4

2 回答 2

4

我相信这部分命令失败了:

echo "my first string" | git hash-object -w --stdin

有没有办法解决这个问题,以便它可以在 git 目录之外执行?

您遇到的问题是因为-w您传递给git hash-object命令的选项。该选项需要一个现有的存储库,因为它具有将对象写入 git 数据库的副作用。

证明:

$ echo "my first string" | git hash-object -w --stdin
fatal: Not a git repository (or any parent up to mount point /home)
Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set).

$ echo "my first string" | git hash-object --stdin
3616fdee3ac48e5db02fbf9d5e1c2941cfa3e165

但是,由于您的最终目标是获取git diff两个给定字符串之间的值,因此如果您想在git hash-object1的帮助下完成此操作,则必须拥有一个 git 存储库。为此,您可以生成一个临时的空存储库:

$ tmpgitrepo="$(mktemp -d)"

$ git init "$tmpgitrepo"
Initialized empty Git repository in /tmp/tmp.MqBqDI1ytM/.git/

$ (export GIT_DIR="$tmpgitrepo"/.git; git diff $(echo "my first string" | git hash-object -w --stdin) $(echo "my second string" | git hash-object -w --stdin)  --word-diff)
diff --git a/3616fdee3ac48e5db02fbf9d5e1c2941cfa3e165 b/2ab8560d75d92363c8cb128fb70b615129c63371
index 3616fde..2ab8560 100644
--- a/3616fdee3ac48e5db02fbf9d5e1c2941cfa3e165
+++ b/2ab8560d75d92363c8cb128fb70b615129c63371
@@ -1 +1 @@
my [-first-]{+second+} string

$ rm -rf "$tmpgitrepo"

这种方法可以打包成一个 bash 函数:

git-diff-strings()
(
    local tmpgitrepo="$(mktemp -d)"
    trap "rm -rf $tmpgitrepo" EXIT
    git init "$tmpgitrepo" &> /dev/null
    export GIT_DIR="$tmpgitrepo"/.git
    local s1="$1"
    local s2="$2"
    shift 2
    git diff $(git hash-object -w --stdin <<< "$s1") $(git hash-object -w --stdin <<< "$s2") "$@"
)

用法

git-diff-strings <string1> <string2> [git-diff-options]

示例

git-diff-strings "first string" "second string" --word-diff

1请注意,您可以git diff通过创建 2 个包含这些字符串的临时文件来创建两个字符串,在这种情况下,您不需要 git 存储库。

于 2017-09-04T11:50:18.087 回答
1

@danday74 我无法根据您的反馈写评论(由于 StackOverflow 的权限),所以这是我的答案。您可以使用 设置环境变量GIT_DIR。如果您在多台机器上执行此操作(您需要能够在此类机器上设置此变量),那么您将能够可靠地设置--git-dir.

希望这可以帮助。

于 2017-09-04T12:17:08.500 回答