How to add a git repo as a submodule of itself? (Or: How to generate GitHub Pages programmatically?)

后端 未结 2 681
故里飘歌
故里飘歌 2020-12-14 02:13

I want to start using GitHub Pages for my project\'s website. This simply requires a branch (subtree) named gh-pages in the repo, and serves up its content. The

2条回答
  •  眼角桃花
    2020-12-14 02:36

    In this case, the behaviour seems to be that git is trying to set the origin of the original repository to be the origin of the submodule. This is confirmed by the git submodule man page, which says [my emphasis]:

    is the URL of the new submodule’s origin repository. This may be either an absolute URL, or (if it begins with ./ or ../), the location relative to the superproject’s origin repository.

    A workaround that seems fine for me is to do the following:

    # Define origin to be the absolute path to this repository - we'll remove
    # this later:
    $ cd /tmp/main/
    $ git remote add origin /tmp/main/
    
    # Now add the submodule:
    $ git submodule add -b gh-pages ./ gh-pages
    Initialized empty Git repository in /tmp/main/gh-pages/.git/
    Branch gh-pages set up to track remote branch gh-pages from origin.
    
    # Now .gitmodules looks sensible:
    $ cat .gitmodules 
    [submodule "gh-pages"]
        path = gh-pages
        url = ./
    
    # However, the origin for the submodule isn't what we want:
    $ cd gh-pages
    $ git remote -v
    origin  /tmp/main/ (fetch)
    origin  /tmp/main/ (push)
    
    # So remove it and add the right origin (just ".."):
    $ git remote rm origin
    $ git remote add origin ..
    
    # Change back to the main repository and commit:
    $ cd ..
    $ git commit -m "Added the gh-pages branch as a submodule of this repository"
    [master 6849d53] Added the gh-pages branch as a submodule of this repository
     2 files changed, 4 insertions(+), 0 deletions(-)
     create mode 100644 .gitmodules
     create mode 160000 gh-pages
    

    This seems to work OK - if I change into another directory and do:

    $ cd /var/tmp
    $ git clone --recursive /tmp/main/
    

    ... the submodule is updated and initialized correctly. (Update: although as you point out in a comment below, origin in the submodule will be set to the URL you cloned from rather than ..)

    As for whether this is a good idea or not: I've worked on a project which used a similar setup in the past and which subsequently abandoned it. The reasons for this, however, were (a) that the alternative branches in the main repository were huge and bloated the repository even for people who didn't need the submodule and (b) that it caused confusion for people who weren't sure what was going on.

    For your use case, however, I think it's a rather neat solution :)

提交回复
热议问题