简体   繁体   中英

When do I commit when moving files in a git? (Jgit)

I am implementing a bot that performs scheduled backups. from a front-end a user will be able to change the folder names the backups are stored in.

according to: What's the purpose of git-mv?

mv oldname newname
git add newname
git rm oldname

is what I want to do when a folder or file name is to be changed. so I move the files using Java FileUtils, add the new file/folder and remove the old file/folder using:

git.add().addFilepattern(newName).call();
git.rm().addFilepattern(oldName).call();
git.commit().setAll(true).setMessage("Renamed group "+oldName+ " to " +newName).call();

The main goal being:

Should I commit after adding the 'new' file before removing the 'old'?

Is my current order of operations fine and committing after both operations should preserve the change history?

I am still new to Git and how the logging works, in TortoiseGit it shows files added and removed, would it show up as a move in the log if the process worked?

Thank you for your time.

Git does not actually record history of individual files in the repository; it records the history of the entire repository as a single unit. There's nothing in a commit that explicitly says that the foo.txt in revision 2 is a continuation of the bar.txt in revision 1. Instead, renames are inferred by tools that examine the repository — after the changes have been committed — using the heuristic that if a commit removes a file and also creates another file with similar contents, the old file was renamed to the new one.

This heuristic only recognizes a rename if both changes occur in the same commit. If you remove a file, commit, then add the file back with a different name and commit again, Git will see that as separate deletion and addition of unrelated files.

Note that rename detection is optional and tools may not do it by default. With git log you need to use the -M option, for example, or do git config --bool diff.renames true .

I'm not familiar with JGit, but your Java code should probably mirror what Git is actually doing beneath the interface when you run your command. Since you are already doing this, I don't see any problem. I would make sure that the entire renaming operation appears in a single commit. There are several reasons for wanting to do this. You may want to revert the renaming at some point. If you have a single commit, it would be easy to do this via git revert .

With regard to preserving the history, renaming a file makes it harder to track the history, but not impossible , eg

git log --follow ./path/to/file

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM