【发布时间】:2011-06-28 20:19:12
【问题描述】:
我想在我的网站上显示 master 负责人的 git commit id(即 SHA)作为标识符。
如何从 git 中提取这些信息?
【问题讨论】:
标签: git
我想在我的网站上显示 master 负责人的 git commit id(即 SHA)作为标识符。
如何从 git 中提取这些信息?
【问题讨论】:
标签: git
此命令将为您获取最新提交的 SHA-1
git rev-parse HEAD
【讨论】:
git log ... ")。
git rev-parse master 会给你结果。
git rev-parse master 或 git rev-parse origin/master 或您想要提交 ID 的任何其他参考名称。
我宁愿使用 git describe 而不是 HEAD SHA1,作为获取“构建 ID”的更易读的方式。例如:
git describe --abbrev=4 HEAD
如果您不关心标签,并且考虑到 git describe 是一个 porcelain command,不应该在脚本中使用,那么,是的,git rev-parse(a plumbing command)更合适。
但同样,如果您要在您的网站上显示 SHA1 作为 id,我会选择:
git rev-parse --short HEAD
(为了只显示SHA1的前7位)
git rev-parse HEAD(表示所有 40 位数字)仍然有用,当您想检查您刚刚部署的内容是否确实是 HEAD 所指的内容时。
例如见deployment script:
它首先触发更新:
#If requested, perform update before gathering information from repos.
if $update; then
echo "Updating fred-official."
cd "$fredDir"
git_update
if ! [[ "$forceFredID" = "" ]]
then
checkGitID "$forceFredID"
fi
echo "Updating website repo."
cd "$websiteDir"
git_update
if ! [[ "$forceWebsiteID" = "" ]]
then
checkGitID "$forceWebsiteID"
fi
cd "$startingDir"
fi
更新本身会刷新网站内容:
# Discard any local changes, update remote branches and tags, and
# check out to the latest master branch.
git_update() {
#To update tags and branches.
git remote update
git clean -dfx
git reset --hard origin/master
}
然后它使用git rev-parse HEAD 来检查刚刚签出的内容:
function checkGitID {
checkID=$1
echo Checking git ID is "$checkID"
if ! git checkout "$checkID"
then
echo Failed to checkout "$checkID"
exit 4
fi
if ! actualID=$(git rev-parse --verify HEAD)
then
echo Failed to verify "$checkID"
git checkout master
exit 5
fi
if ! [[ "$actualID" = "$checkID" ]]
then
echo Git verification failed, something very bad is happening
exit 6
fi
echo Git ID verified: "$checkID"
}
【讨论】:
以下命令将返回 HEAD 的 SHA-1:
git log -1 --pretty="%H"
【讨论】:
只是稍微不那么优雅:
git log | head -1 | sed s/'commit '//
【讨论】:
你可以使用:
git describe --always --dirty
--dirty[=<mark>], --broken[=<mark>]
Describe the state of the working tree. When the working tree matches HEAD, the output is the same
as "git describe HEAD". If the working tree has local modification "-dirty" is appended to it. If a
repository is corrupt and Git cannot determine if there is local modification, Git will error out,
unless ‘--broken’ is given, which appends the suffix "-broken" instead.
--all
Instead of using only the annotated tags, use any ref found in refs/ namespace. This option enables
matching any known branch, remote-tracking branch, or lightweight tag.
【讨论】: