直接提交到裸存储库

时间:2012-03-12 15:50:51

标签: git

一些上下文

这适合

以协作为中心的Web应用程序,提供git托管(作为bare repos)

我们想做什么

允许用户将一组文件直接添加到其现有存储库。

我的问题

是否有工具或方法手动创建仅涉及将新文件添加到git仓库的提交?

我们现在可以使用临时服务器端稀疏检出来执行此操作,但我们希望优化此过程。

3 个答案:

答案 0 :(得分:7)

plumbing and porcelain页面有一个例子,但我会尝试简化它。

似乎裸repos仍​​然有一个索引,可以操作并将其作为提交。它也可能从头开始创建树对象,但我并不知道具体如何。

如果存在其他人可能同时访问存储库的风险,则可能必须锁定存储库。我只是在这里使用lockfile包中的procmail

#!/bin/bash
cd myrepo.git

MY_BRANCH=master
MY_FILE_CONTENTS=$'Hello, world!\n'

# Note this is just a lock for this script. It's not honored by other tools.
lockfile -1 -r 10 lock || exit 1

PARENT_COMMIT="$(git show-ref -s "$MY_BRANCH")"

# Empty the index, not sure if this step is necessary
git read-tree --empty

# Load the current tree. A commit ref is fine, it'll figure it out.
git read-tree "${PARENT_COMMIT}"

# Create a blob object. Some systems have "shasum" instead of "sha1sum"
# Might want to check if it already exists. Left as an excercise. :)
BLOB_ID=$(printf "blob %d\0%s" $(echo -n "$MY_FILE_CONTENTS" | wc -c) "$MY_FILE_CONTENTS" | sha1sum | cut -d ' ' -f 1)
mkdir -p "objects/${BLOB_ID:0:2}"
printf "blob %d\0%s" $(echo -n "$MY_FILE_CONTENTS" | wc -c) "$MY_FILE_CONTENTS" | perl -MCompress::Zlib -e 'undef $/; print compress(<>)' > "objects/${BLOB_ID:0:2}/${BLOB_ID:2}"

# Now add it to the index.
git update-index --add --cacheinfo 100644 "$BLOB_ID" "myfile.txt"

# Create a tree from your new index
TREE_ID=$(git write-tree)

# Commit it.
NEW_COMMIT=$(echo "My commit message" | git commit-tree "$TREE_ID" -p "$PARENT_COMMIT")

# Update the branch
git update-ref "refs/heads/$MY_BRANCH" "$NEW_COMMIT" "$PARENT_COMMIT"

# Done
rm -f lock

如果有git命令来创建blob,那就好了,但我找不到。 perl命令取自another question

答案 1 :(得分:4)

Pro Git的"Plumbing and Porcelain"章节提供了对Git内部的一些见解,您可以利用这种方式创建提交,同时绕过一些正常的Git进程。

答案 2 :(得分:2)

我使用JGit将git add / rm文件的示例创建为裸仓库。 查看https://github.com/junoyoon/git-online-commit-sample。在测试代​​码中,您可以了解如何使用JGit API进行裸仓库操作。