Search code examples
gitgit-submodules

Commit .git folder from subfolder in git repository


Below is structure of git repository which has another git repository initialized using git init in subfolder dir.

$ tree -a -L 2 . 
.
├── .git
│   ├── HEAD
│   ├── config
│   ├── description
│   ├── hooks
│   ├── info
│   ├── objects
│   └── refs
└── dir
    └── .git

How to commit and push .git folder from the subfolder?

I tried running git add dir/.git and git commit .., but nothing was commited as far as git log is concerned.

Repository inside dir is used in deployment by some tool which needs to clone/checkout changes from local git repository in dir.


Solution

  • Using git submodules according to tutorial helped.

    Below sequence of commands illustrates the required test flow:

    $ mkdir git_repo
    $ cd git_repo/
    $:git_repo  git init
    Initialized empty Git repository in /private/tmp/git_repo/.git/
    $:git_repo  mkdir inner_repo
    $:git_repo  cd inner_repo
    $:inner_repo  git init
    Initialized empty Git repository in /private/tmp/git_repo/inner_repo/.git/
    $:inner_repo  touch file
    $:inner_repo  git add file
    $:inner_repo  git commit -m 'initial'
    [master (root-commit) 2b13943] initial
     1 file changed, 0 insertions(+), 0 deletions(-)
     create mode 100644 file
    $:inner_repo  cd ..
    $:git_repo  git submodule add ./inner_repo
    Adding existing repo at 'inner_repo' to the index
    $:git_repo  cd ..
    $ git clone git_repo/inner_repo inner
    Cloning into 'inner'...
    done.
    

    Below flow achieved the desired result in existing local repository which had remote in Bitbucket:

    • create folder for inner repository in parent repository
    • copy some files to inner_repo
    • initialize inner repository and commit the files (inside inner_repo run git init and git commit -am 'initial')
    • go to parent repo: cd ...
    • critical step: git submodule add ./inner_repo ./inner_repo

    After that .gitmodules and inner_repo were staged.

    Explanation according to docs:

    git submodule add [-b <branch>] [-f|--force] [--name <name>] [--reference <repository>] [--depth <depth>] [--] <repository> [<path>]

    Add the given repository as a submodule at the given path to the changeset to be committed next to the current project: the current project is termed the "superproject".

    The optional argument <path> is the relative location for the cloned submodule to exist in the superproject. If <path> exists and is already a valid Git repository, then it is staged for commit without cloning.