Multiple working directories with Git?

后端 未结 4 653
礼貌的吻别
礼貌的吻别 2020-11-21 07:14

I\'m not sure if this is something supported by Git, but in theory it seems like it should work to me.

My workflow often involves my editing of files in multiple bra

4条回答
  •  旧时难觅i
    2020-11-21 08:03

    I came across this question hoping for a solution I didn't find here. So now that I did find what I needed, I decided to post it here for others.

    Caveat: This is probably not a good solution if you need to edit multiple branches simultaneously, like OP states. It is for having multiple branches checked out simultaneously that you don't intend to edit. (Multiple working directories backed by one .git folder.)

    There were a few things I've learned since I came to this question the first time:

    1. What a "bare repository" is. It is essentially the contents of the .git directory, without being located in a working tree.

    2. The fact that you can specify the location of the repo you are using (the location of your .git dir) on the command line with the git option --git-dir=

    3. The fact that you can specify the location of your working copy with --work-tree=

    4. What a "mirror repo" is.

    This last is a pretty important distinction. I don't actually want to work on the repo, I just need to have copies of different branches and/or tags checked out simultaneously. In actual fact, I need to guarantee that the branches don't end up different from my remote's branches. So a mirror is perfect for me.

    So for my use case, I got what I needed by doing:

    git clone --mirror   # Where localgitdir doesn't exist yet
    mkdir firstcopy
    mkdir secondcopy
    git --git-dir= --work-tree=firstcopy checkout -f branch1
    git --git-dir= --work-tree=secondcopy checkout -f branch2
    

    The big caveat about this is that there isn't a separate HEAD for the two copies. So after the above, running git --git-dir= --work-tree=firstcopy status will show all the differences from branch2 to branch1 as uncommitted changes - because HEAD is pointing at branch2. (That's why I use the -f option to checkout, because I'm not actually planning to make any changes locally at all. I can checkout any tag or branch for any work-tree, as long as I use the -f option.)

    For my use case of having multiple checkouts co-existing on the same computer without needing to edit them, this works perfectly. I don't know if there is any way to have multiple HEADs for the multiple work trees without a script such as is covered in the other answers, but I hope this is helpful to someone else anyway.

提交回复
热议问题