在git仓库中更改文件名

jar*_*ryd 68 git

git如何处理文件名更改?

是否会将文件名更改检测为修改,或者是否存在需要删除的"丢失"文件,然后需要添加新文件git add

ral*_*nja 90

它会自动被检测为修改,"new"文件将被添加到索引中,因此您只需要一个命令:

$ git mv application.py newApplication.py
$ git status
# On branch buildServer
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#       renamed:    application.py -> newApplication.py
Run Code Online (Sandbox Code Playgroud)

并且承诺当然..


Mar*_*air 28

在每次提交时,git都会记录源树的状态,而不是是否存在生成该状态的重命名(或其他).所以,如果你只是正常地重命名文件(而不是用git mv),输出git status将是这样的:

# On branch master
# Changed but not updated:
#   (use "git add/rm <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#   deleted:    foo.txt
#
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#   bar.txt
no changes added to commit (use "git add" and/or "git commit -a")
Run Code Online (Sandbox Code Playgroud)

如果您随后决定要记录重命名该文件的树的状态,则可以使用以下命令进行更改:

 git rm foo.txt
 git add bar.txt
Run Code Online (Sandbox Code Playgroud)

......然后git status会告诉你:

# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#   renamed:    foo.txt -> bar.txt
Run Code Online (Sandbox Code Playgroud)

......你可以git commit像往常一样承诺:

git commit -m "Renamed foo.txt to bar.txt"
Run Code Online (Sandbox Code Playgroud)

重要的是要记住,当git告诉你在查看历史记录时已经重命名了一个文件,那是因为它已经确定通过比较从一个版本到另一个版本的树的状态必须发生重命名 - 它并不意味着历史记录中记录了重命名操作.


Der*_*har 9

正如先前的答案所解释的那样,Git从源树中的内容更改派生文件重命名操作.要记录重命名操作,Git既存储删除操作又添加添加操作,而不存储重命名操作本身.

正如Magnus Skog 指出的那样 git mv <filename1> <filename2>告诉Git将内容添加<filename1>到文件树中<filename2><filename1>从中删除.

正如Mark Longair所 解释的那样,如果不git mv使用shell命令mv <filename1> <filename2>,Git将不会检测重命名操作,直到你调用git rm <filename1>git add <filename2>.

但是,另一种告诉Git重命名操作的方法mv是使用git add --all.此命令指示Git检测并准备提交工作区中与存储库中的文件不同的所有文件,包括您重命名的文件:

$ ls
a  b  c  d
$ mv d e
$ git status
# On branch master
# Changed but not updated:
#   (use "git add/rm <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#   deleted:    d
#
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#   e
no changes added to commit (use "git add" and/or "git commit -a")
$ git add --all
$ git status
# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#   renamed:    d -> e
#
Run Code Online (Sandbox Code Playgroud)

git add --all 例如,使用脚本或批量重命名工具提交您在工作区中重命名的大量文件是一种非常方便的方法.