Skip to content

Instantly share code, notes, and snippets.

@sehe
Created September 10, 2011 14:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sehe/1208393 to your computer and use it in GitHub Desktop.
Save sehe/1208393 to your computer and use it in GitHub Desktop.
Git is_submodule function
#!/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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment