Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
713 views
in Technique[技术] by (71.8m points)

git - Move file and directory into a sub-directory along with commit history

How can I move a directory and files to a sub-directory along with commit history?

For example:

  • Source directory structure: [project]/x/[files & sub-dirs]

  • Target directory structure: [project]/x/p/q/[files & sub-dirs]

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To add to bmargulies's comment, the complete sequence is:

mkdir -p x/p/q      # make sure the parent directories exist first
git mv x/* x/p/q    # move folder, with history preserved
git commit -m "changed the foldername x into x/p/q"

Try it first to see a preview of the move:

git mv -n x/* x/p/q

Wolfgang comments:

If you're using bash, you can avoid the issue of trying to move a folder into itself by using an extended glob like so (using the shopt built-in):

shopt -s extglob; git mv !(folder) folder

Captain Man reports in the comments having to do:

mkdir temp 
git mv x/* temp
mkdir -p x/p/q
git mv temp x/p/q
rmdir temp;

Context:

I am on Windows with Cygwin.
I just realized I did the shopt -s extglob example wrong so my way may not have be necessary, but I typically do use zsh instead of bash, and it didn't have the command shopt -s extglob (though I'm sure there is an alternative), so this approach should work across shells (subbing in your shell's mkdir and rmdir if it's especially foreign)


As an alternative, spanky mentions in the comments the -k option of git mv:

Skip move or rename actions which would lead to an error condition.

git mv -k * target/

That would avoid the "can not move directory into itself" error.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...