0 votes
1 view
in Devops and Agile by (20k points)
edited by

I'd read that when renaming files in git, you should commit any changes, perform your rename and then stage your renamed file. Git will recognize the file from the contents, rather than seeing it as a new untracked file, and keep the change history.

However, doing just this tonight I ended up reverting to git mv.

> $ git status

# On branch master

# Changes to be committed:

#   (use "git reset HEAD <file>..." to unstage)

#

#   modified:   index.html

#

Rename my stylesheet in Finder from iphone.css to mobile.css

> $ git status

# On branch master

# Changes to be committed:

#   (use "git reset HEAD <file>..." to unstage)

#

#   modified:   index.html

#

# 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:    css/iphone.css

#

# Untracked files:

#   (use "git add <file>..." to include in what will be committed)

#

#   css/mobile.css

So git now thinks I've deleted one CSS file, and added a new one. Not what I want, lets undo the rename and let git do the work.

> $ git reset HEAD .

Unstaged changes after reset:

M   css/iphone.css

M   index.html

Back to where I began.

> $ git status

# On branch master

# Changes to be committed:

#   (use "git reset HEAD <file>..." to unstage)

#

#   modified:   index.html

#

Let's use git mv instead.

> $ git mv css/iphone.css css/mobile.css

> $ git status

# On branch master

# Changes to be committed:

#   (use "git reset HEAD <file>..." to unstage)

#

#   renamed:    css/iphone.css -> css/mobile.css

#

# Changed but not updated:

#   (use "git add <file>..." to update what will be committed)

#   (use "git checkout -- <file>..." to discard changes in working directory)

#

#   modified:   index.html

#

Looks like we're good. So why didn't git recognize the rename the first time around when I used Finder?

2 Answers

0 votes
by (28.4k points)

Before git will recognize it as a move you have to add the two modified files to the index. You have to notice that the difference between mv old new and git mv old new is that the git mv also adds the files to the index.

mv old new then git add -A would have worked, too.

Keep in mind that you can't just use git add . because that doesn't add removals to the index.

0 votes
by (63.4k points)

Follow the below steps:

Step1: rename the file from oldfile to new file

git mv #oldfile #newfile

Step2: git commit and add comments

 git commit -m "rename oldfile to newfile"

Step3: push this change to the remote server

 git push origin #localbranch:#remotebranch

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...