Skip to content

Instantly share code, notes, and snippets.

@brianoflan
Created December 22, 2017 15:08
Show Gist options
  • Save brianoflan/4d70bd310bf90b64acc0a632b82e7659 to your computer and use it in GitHub Desktop.
Save brianoflan/4d70bd310bf90b64acc0a632b82e7659 to your computer and use it in GitHub Desktop.
~/bin/swgit to switch .git folders in your current folder
#!/bin/bash
main() {
local switch_to=$1
local what_repo=$(basename "$(pwd)")
local topd=$(pwd)
local top=true
[[ -d .git ]] || top=false
while [[ $top == false ]] ; do
cd .. || die "ERROR: Failed to find a top git repo root (a parent folder with a .git subfolder, stopped at $tmp)."
local tmp=$(pwd)
[[ $tmp != $topd ]] || die "ERROR: Failed to find a top git repo root (a parent folder with a .git subfolder, stopped at $tmp)."
topd=$tmp
[[ -d .git ]] || top=false
done ;
local current=$(cat ../.swgit-current-$what_repo 2>/dev/null || true)
if [[ -z $current ]] ; then
if [[ $switch_to ]] ; then
if [[ $switch_to -gt 1 ]] ; then
current=$(($switch_to - 1))
else
current=$(($switch_to + 1))
fi ;
else
current=1
switch_to=2
fi ;
fi ;
if [[ -z $switch_to ]] ; then
if [[ $current -gt 1 ]] ; then
switch_to=$(($current - 1))
else
switch_to=$(($current + 1))
fi ;
fi ;
echo "$0: Switching $topd from $current to $switch_to."
if confirm ; then
switch_dot_git "$current" "$switch_to" || die "ERROR: Failed to switch $topd from $current to $switch_to: $?."
echo "$switch_to" > ../.swgit-current-$what_repo || die "ERROR: Failed to record current git number ($switch_to): $?."
fi ;
}
confirm() {
local result=1 # default = no
local answer
local sets=$-
set +ex
local keep_prompting=true
echo -n "Confirm [Y/n]: " ;
while [[ $keep_prompting == true ]] ; do
keep_prompting=false
stty -echo
read answer
stty echo
echo
if [[ $answer == Y ]] ; then
result=0
else
if echo "$answer" | egrep -i '^(go|ok|sure|true|y|yeppers|yes)$' >/dev/null ; then
echo -n "You answered '$answer' but I only accept 'Y'. Did you mean 'Y' [Y/n]: "
keep_prompting=true
fi ;
fi ;
done ;
set $sets
return $result
}
die() {
echo "$1"
exit 1
}
switch_dot_git() {
local current=$1
local switch_to=$2
local cur_d="../.swgit$current-$what_repo"
local swto_d="../.swgit$switch_to-$what_repo"
[[ -d $cur_d ]] || mkdir $cur_d || return 1
[[ -d $swto_d ]] || mkdir $swto_d || return 1
[[ -e .git ]] || git init || return 1
mv .git $cur_d/ || return 1
[[ -e $swto_d/.git ]] && mv $swto_d/.git ./ || git init || return 1
[[ ! -e $swto_d/.gitignore ]] || {
[[ ! -e .gitignore ]] || mv -f .gitignore $cur_d/ || return 1
mv $swto_d/.gitignore ./ || return 1
}
return 0
}
main "$@"
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment