我正在尝试获取 2 个字符串之间的 git diff
。以下命令有效:
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 目录外执行吗?
最佳答案
I believe this portion of the command is failing:
echo "my first string" | git hash-object -w --stdin
Is there any way around this so that it can be executed outside a git directory?
您遇到的问题是因为您传递给 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 diff
,如果您想在 git hash-object 的帮助下完成此操作,则必须拥有一个 git 存储库
1。为此,您可以生成一个临时的空存储库:
$ 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 请注意,您可以通过创建 2 个包含这些字符串的临时文件来git diff
两个字符串,在这种情况下您不需要 git 存储库。
关于git - 是否可以在 Git 目录之外创建 Git 哈希对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46035862/