是否可以在不首先检查的情况下替换 git 分支的树?

Is it possible to replace the tree of a git branch without first checking it out?

对于 github.io 上的页面,通常使用主存储库上名为 gh-pages 的分支来发布与特定存储库关联的网站。

在我当前的项目中,我执行以下步骤来更新托管在 github.io 上的文档。

  1. 使用 Doxygen 在主分支上构建 API 文档。
  2. html 目录移动到临时目录。
  3. 检查 gh-pages 分支。
  4. 将临时目录的内容复制到项目目录。
  5. git commitgit push gh-pages 分支。
  6. 再次检查 master 分支。

是否可以一步将html目录的内容提交到gh-pages分支?

请注意,我不希望将 html 目录的内容添加到 master 分支,因为它是生成的内容而不是源代码。

我已经看过 this question and this question 但他们似乎没有解决这个问题。

这实际上不是 this question 的重复,因为这个问题涉及整个树替换而不是添加单个文件,我相信前一个操作可以比后者更干净的方式完成。

在新的本地存储库中再次克隆您的远程存储库。 检出这个新存储库中的分支 gh_pages

使用您已有的 repo 进行开发,就像您现在使用它一样。

像现在一样使用 Doxygen 在开发存储库的主分支上构建 API 文档。如果可能,将进程配置为在存储第二个本地存储库的目录中生成输出。否则在创建后将生成的文档移动到第二个本地仓库。

运行 git add .; git commit; git push 在第二个存储库(文档存储库)中。

每次需要时重复最后两个步骤。

我编写了以下脚本来避免使用额外的工作目录,尽管@axiac 的回答是解决此问题的有效方法。

#!/bin/bash

# This script will take a directory and replace the contents of a non-current
# branch with it.
if [ "$#" -ne 3 ]; then
    echo \
    "Usage:  replace-branch <top level directory> <branchname> <commit message>"
    exit
fi

root=""
branch=""
msg=""

# First check if the index is polluted, since we will be using it.
save=HEAD
indexDiverges=$(git diff-index --cached  $(git rev-parse HEAD))
if [[ -n "$indexDiverges" ]]; then
    save=$(git write-tree)
fi

# Create a new index
git read-tree --empty
GIT_WORK_TREE=$root git add .

# Check whether the index is actually different from the target.
isDuplicateCommit=$(git diff-index --cached  $(git rev-parse $branch))
if [[ ! -n "$isDuplicateCommit" ]]; then
    echo "The branch already matches the state we are trying to commit!"
    git read-tree $save
    exit
fi

# Write the index out to a new tree
tree=$(git write-tree)

# Commit with the given commit message to the other branch
commithash=$(echo "$msg" | git commit-tree $tree -p $(git rev-parse $branch))

# Move the branch pointer.
git update-ref $(git show-ref --heads "$branch"  | awk '{print }') \
    "$commithash"

# Restore the index to its previous state
git read-tree $save

我还决定稍微升级一下并将其放在 GitHub 上并附上示例用法。