2017-09-04 50 views
3

我想在2个字符串之间得到git diff。以下命令的工作原理如下:是否可以在Git目录之外创建Git哈希对象?

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目录外被执行?

+1

这似乎解决您的问题:https://stackoverflow.com/questions/7149984/how-do-i-execute-a-git-command-without-being-on-the-repository-folder?noredirect= 1 – jburtondev

+0

谢谢你的抬头...如果我的代码在无数其他机器上执行,有没有办法可靠地设置 - git-dir? – danday74

回答

4

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

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

有没有解决这个办法,以便它可以一个git 目录外被执行?

您所遇到的问题是因为你传递给git hash-object命令-w选项。该选项需要现有的存储库,因为它具有writing the object into the git database的副作用。

证明:

$ 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 hash-object 帮助做到这一点,你必须有一个Git仓库的git diff两者给出的字符串。为此,你可以生成一个临时的空库:

$ 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") "[email protected]" 
) 

使用

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

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

注意,您可以git diff两个字符串通过创建包含这些字符串,在这种情况下,你不需要一个Git仓库2个临时文件。

+0

优秀的东西,感谢莱昂,现在将所有这些功能添加到我的应用程序 - 非常感谢:D – danday74

1

@ danday74我无法根据您的反馈发表评论(由于StackOverflow的权限),所以这里是我的答案。您可以设置环境变量usingGIT_DIR。如果你在多台机器上这样做(你需要能够在这些机器上设置这个变量),那么你将能够可靠地设置--git-dir

希望这会有所帮助。