public
Created

Git is_submodule function

  • Download Gist
submodule.sh
Shell
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
#!/bin/bash
 
cat >> /dev/null <<"HERE"
Looking good. There is a bug in
 
for line in $submodules; do cd "$parent_git/$line"; \
if [[ `pwd` = $_git_dir ]]; then return 0; fi; \
done
 
because it won't cd back (so it would only work if the first submodule
is a match). I'd check without changing directories, or do the `cd` in a
subshell.
 
I don't know where you get $_git_dir from - I used basename(1) to get that
information (see below).
 
I also suggest you trap errors (either with 'set -e', 'trap "return 1"
ERR' or similar)
 
There was also a problem with submodules containing a space in the name. There
is still a problem with newlines in submodule names left, but I don't care
enough to fix that :)
 
finally declaring all the vars local fixes potential problems when using this
inside other scripts
HERE
 
function is_submodule() {
local git_dir parent_git module_name path
# Find the root of this git repo, then check if its parent dir is also a repo
git_dir="$(git rev-parse --show-toplevel)"
module_name="$(basename "$git_dir")"
parent_git="$(cd "$git_dir/.." && git rev-parse --show-toplevel 2> /dev/null)"
if [[ -n $parent_git ]]; then
# List all the submodule paths for the parent repo
while read path
do
if [[ "$path" != "$module_name" ]]; then continue; fi
if [[ -d "$git_dir/../$path" ]]; then return 0; fi
done < <(cd $parent_git && git submodule --quiet foreach 'echo $path' 2> /dev/null)
#return 1
fi
return 1
}
 
# Usage
if is_submodule; then
echo "In a submodule!"
else
echo "Not in a submodule"
fi

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.