【问题标题】:commit certain files to new branch将某些文件提交到新分支
【发布时间】:2016-11-13 16:51:54
【问题描述】:

假设我的 master 分支上有以下 4 个文件

$ ls
README.txt documentation.html main.py docs/main.html

$ git branch -a
* master
  remotes/origin/gh-pages
  remotes/origin/master

问。我应该运行哪些命令集以仅将 html 文件 documentation.htmldocs/main.html 提交到单独的分支 gh-pages 以破坏现有分支并创建包含这些文件的单个提交?我还想将它们推送到远程机器。是否可以在不运行git checkout gh-pages 的情况下执行此操作?

我目前的解决方案是使用以下命令

git branch -D gh-pages || echo "Delete local branch failed. It is possible that local branch exists"
git checkout --orphan gh-pages
git rm --cached $(git ls-files) # unstage existing files

# Currently using python add_files.py to do this instead
# subprocess.call('git add {}'.format(html_file)')
find . -name '*.html' | xargs git add 

git commit -m "Commit all html files. This commit message does not matter"

git reset $(git commit-tree HEAD^{tree} -m "Generate Sphinx Documentation") # Creates a single commit from current branch
git push --set-upstream origin gh-pages --force
git clean -fxd # Since I unstaged existing files, they will cause conflicts on running the next command if not removed
git checkout master

git pull # Just to make sure master and origin/master are in sync

在我看来这并不优雅,但它确实有效。我想知道是否有更好的方法来做到这一点?此“脚本”的目的是在 ContinuousIntegration 服务器上生成文档并将文档推送到远程存储库上的 gh-pages 分支,以利​​用 GitHub 页面或 GitLab 页面。我不关心 gh-pages 分支的历史。

想法?

【问题讨论】:

  • git push -f origin gh-pages 创建本地分支后。或者,如果您不想要 -f 标志,您可以只 git push origin :gh-pages 先删除远程分支。
  • 您可以使用git rebase -i将所有现有提交压缩到一个分支上
  • 如果我使用 Travis-CI 或 Jenkins,git rebase -i 将不起作用。等效的git rebase --root 只会将除根提交之外的所有提交合并为一个,在分支上留下两个提交。
  • 实际上,如果您执行EDITOR=touch git rebase -i 之类的操作,它会。对于较新的版本,请使用 GIT_SEQUENCE_EDITOR 而不是 EDITOR
  • 那还不需要交互吗?你仍然需要告诉 git 哪些提交需要被压缩到之前的提交上,对吧?

标签: git


【解决方案1】:

对于仅添加 html 文件,您可以简单地运行 git add *.html

以某种方式破坏现有分支并创建包含这些文件的单个提交?

我猜你只关心文件的当前状态,但我不建议这样做。维护历史总是有帮助的。但是,您始终可以在本地修改 gh-pages 分支后执行git push -f origin gh-pages。这样,您的分支将始终包含一个带有您最近更改的提交。

是否可以在不运行git checkout gh-pages 的情况下执行此操作?

嗯,您目前正在这样做,但它非常冗长。给this answer看看。虽然签出到分支也会使您免于像当前方法那样执行git resetgit clean

【讨论】:

  • 感谢您的回答。有一个看似做同样事情的工具 - ghp_import。但是,它似乎没有将文件列表作为输入,而是似乎在整个文件夹上工作。
猜你喜欢
  • 2012-09-22
  • 1970-01-01
  • 2018-08-01
  • 2021-12-24
  • 2020-10-08
  • 1970-01-01
  • 2011-03-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多