【问题标题】:Is it possible to replace the tree of a git branch without first checking it out?是否可以在不先检查的情况下替换 git 分支的树?
【发布时间】:2016-12-13 03:34:09
【问题描述】:

对于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 questionthis question,但它们似乎无法解决这个问题。

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

【问题讨论】:

  • 我原本以为我的问题与另一个问题重复,但我意识到我正在尝试进行整个树的替换,这感觉不同,足以保证一个新的答案,我会当这个问题被重新打开时发布自己。
  • This answer,展示了如果您 正在 将树提交给 master 时该怎么做。将其扩展到您尚未提交的树的提交意味着学习如何使用git write-treegit read-tree
  • @jthill,过去几天我在学习使用git write-treegit read-tree。 :)
  • @jthill,但我认为我的脚本还没有你的那么安全,因为我不确定同一棵树没有双重提交。

标签: git github doxygen


【解决方案1】:

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

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

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

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

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

【讨论】:

  • 你也可以使用git worktree:github.com/blog/…
  • @TavianBarnes 确实如此。将想法发展为答案。比我的好。
【解决方案2】:

我编写了以下脚本以避免使用额外的工作目录,尽管@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="$1"
branch="$2"
msg="$3"

# 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 $2}') \
    "$commithash"

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

我还决定稍微升级一下,并将其放在GitHub 上并举例说明。

【讨论】:

  • 与其拒绝继续,你可以只 save=$(git write-tree) 然后在最后读取树而不是 HEAD。
  • @jthill,感谢您的建议。我正在添加它以及重复树检查。
猜你喜欢
  • 2015-07-05
  • 2010-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-01
  • 2021-11-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多