ChatGPT解决这个技术问题 Extra ChatGPT

是否可以在 Git 中只提取一个文件?

我正在处理一个有一些损坏测试的 Git 分支,我想从另一个已经修复的分支中提取(合并更改,而不仅仅是覆盖)这些测试。

我知道我能做到

git pull origin that_other_branch

但这将尝试合并许多其他文件,因为我还没有准备好。

是否可以从另一个分支中仅提取和合并指定的文件(而不是所有文件)?

这不是 Git pull request for just one file 的副本,因为该问题的所有答案都是如何在不更改任何分支的情况下将本地更改的文件还原为存储库版本。


P
Peter Mortensen

这是我在研究时想出的一个稍微简单的方法:

git fetch {remote}
git checkout FETCH_HEAD -- {file}

致命:无效参考:FETCH_HEAD
这个答案可能缺少一个工作示例。目前还不清楚是否需要下一个承诺。
@Chris 如果我们已经在分支中,我们需要 {remote} 吗?如果是,为什么?
与 pull 不同,它会尝试合并,这就是我们要使用 pull 的原因。
x
xpt

您可以通过这种方式获取然后仅签出一个文件:

git fetch
git checkout -m <revision> <yourfilepath>
git add <yourfilepath>
git commit

关于 git checkout 命令:

-- 分支名称,即 origin/master

不包括存储库名称(您可以通过单击 GitHub 上文件页面上的复制路径按钮获得),即 README.md


-m 开关所需的哈希码可以用 git branch -v 打印。惊人的!
出色的。这不止一次帮助了我。澄清一下, -m 标志似乎对您要从中提取单个文件的提交的哈希值感到满意。
这也对我有用。不过,我在我的远程分支上运行 git log 来查找版本:例如 $ git log remotes/origin/master
是否可以在不拉取其他文件的情况下拉取特定文件?
@aleroot 代表什么?
M
Mawardy
git checkout master -- myplugin.js

master = 分支名称 myplugin.js = 文件名


有没有办法恢复?
不要忘记之前'git pull';)
L
Luke Flournoy

@Mawardy 的回答对我有用,但我的更改是在遥控器上,所以我必须指定来源

git checkout origin/master -- {filename}

佚名

是的,流程如下:

# Navigate to a directory and initiate a local repository
git init        

# Add remote repository to be tracked for changes:   
git remote add origin https://github.com/username/repository_name.git

# Track all changes made on above remote repository
# This will show files on remote repository not available on local repository
git fetch

# Add file present in staging area for checkout
git check origin/master -m /path/to/file
# NOTE: /path/to/file is a relative path from repository_name
git add /path/to/file

# Verify track of file(s) being committed to local repository
git status

# Commit to local repository
git commit -m "commit message"

# You may perform a final check of the staging area again with git status

我错过了 git checkout 行,因为它隐藏在评论之间。此外,这表示“git check”而不是“git checkout”。
S
Shawn Ashton

为了用来自其他仓库或分支的文件覆盖本地文件,命令是......

git checkout remoteName/branchName filePath

这是我之前使用的一个示例...

git checkout origin/master package-lock.json