如何将git分支上的标签移动到另一个提交节点?

1173

我在主分支上创建了一个叫做v0.1的标签,就像这样:

git tag -a v0.1

但后来我发现仍然有一些更改需要合并到主分支以发布0.1版本,因此我做了这个。但现在我的v0.1标签(用便利贴笔记的类比来说)被固定在了错误的提交上。我想让它固定在主分支上最新的提交上,但它却被固定在次新的提交上。

我该如何将它移动到主分支上最新的提交?

13个回答

1
如果您想移动一个已注释的标签,仅更改目标提交但保留注释消息和其他元数据,请使用以下命令:
moveTag() {
  local tagName=$1
  # Support passing branch/tag names (not just full commit hashes)
  local newTarget=$(git rev-parse $2^{commit})

  git cat-file -p refs/tags/$tagName | 
    sed "1 s/^object .*$/object $newTarget/g" | 
    git hash-object -w --stdin -t tag | 
    xargs -I {} git update-ref refs/tags/$tagName {}
}

用法:moveTag <要移动的标签> <目标>

上述函数是参考teerapap/git-move-annotated-tag.sh开发的。


2
似乎不再需要这样做:git tag -f -a my_tag 已经保留了先前消息的消息(使用 git 版本 2.11.0)。 - Matthijs Kooijman

1
如果期望的最终结果是更新远程已有标签的内容:
  1. git checkout <tag_name>
  2. 提交您的更改
  3. git tag -f <tag_name>
  4. git push -f origin <tag_name>

0

如果需要将所有标签更新到当前分支的最新提交:

for i in $(git tag); do
  git push origin ":refs/tags/$i"
  git tag -fa $i
done
git push origin --tags

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接