【问题标题】:Is it possible to create a Git hash object outside a Git directory?是否可以在 Git 目录之外创建 Git 哈希对象?
【发布时间】:2017-09-04 11:16:06
【问题描述】:

我试图在两个字符串之间获取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 目录之外执行吗?

【问题讨论】:

标签: git git-diff git-hash


【解决方案1】:

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

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 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 两个字符串,在这种情况下,您不需要 git 存储库。

【讨论】:

  • 好东西,感谢 Leon,现在将所有这些功能添加到我的应用程序中 - 非常感谢:D
【解决方案2】:

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

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2011-08-26
    • 2021-12-12
    • 2019-06-23
    • 2012-04-19
    • 1970-01-01
    • 1970-01-01
    • 2015-05-08
    • 2011-06-16
    • 1970-01-01
    相关资源
    最近更新 更多