Skip to content

Instantly share code, notes, and snippets.

@varesa
Created June 30, 2023 13:46
Show Gist options
  • Save varesa/77a31c1339b1500bfee6702cefe1f085 to your computer and use it in GitHub Desktop.
Save varesa/77a31c1339b1500bfee6702cefe1f085 to your computer and use it in GitHub Desktop.
_execute_multiple_choice() {
local cmd
local prefix
local choices
if [[ "$#" -eq "2" ]]; then
cmd="$1"
prefix=""
choices="$2"
elif [[ "$#" -eq "3" ]]; then
cmd="$1"
prefix="$2"
choices="$3"
else
echo "_execute_multiple_choice: invalid args" > /dev/stderr
return 1
fi
local choice
# Prompt if multiple choices
if [[ "$(echo $choices | wc -l)" -gt 1 ]]
then
choice="$(echo $choices | fzf)"
if [[ "$choice" == "" ]]
then
echo "Selection canceled"
return 0
fi
else
choice="$choices"
fi
local args
if [[ -n "$ZSH_VERSION" ]]; then
IFS=' ' read -A args <<< "$prefix$choice"
else
IFS=' ' read -a args <<< "$prefix$choice"
fi
"$cmd" "${args[@]}"
}
rrepo() {
cd ~/workspace/
if [[ "$#" -eq "0" ]]; then
return 0
fi
# List remote repos
local pages
local query
local repos
pages="$(curl -Ssv -H "PRIVATE-TOKEN: $(secret-tool lookup gitlab read_token)" "https://gitlab/api/v4/projects?simple=true&per_page=100" 2>&1 | grep 'x-total-pages' | cut -d ':' -f 2 | tr -d ' \r')"
query=""
for page in $(seq $pages); do
query="$query\ncurl -Ss -H \"PRIVATE-TOKEN: $(secret-tool lookup gitlab read_token)\" \"https://gitlab/api/v4/projects?simple=true&per_page=100&page=$page\" | jq -r '.[].ssh_url_to_repo' | cut -d ':' -f 2"
done
repos="$(echo "$query" | parallel)"
# Filter while search terms remain
while [[ "$#" -gt 0 ]]
do
repos="$(echo $repos | grep $1)"
shift
done
if [[ "$(echo $repos | grep -v '^$' | wc -l)" -gt 0 ]]; then
_execute_multiple_choice "git" "clone git@gitlab:" "$repos"
else
echo "remote repo not found" >/dev/stderr
fi
}
repo() {
local original_args
local repos
original_args=("$@")
cd ~/workspace/
if [[ "$#" -eq "0" ]]; then
return 0
fi
# List local repos
repos="$(ls -1)"
# Filter while search terms remain
while [[ "$#" -gt 0 ]]
do
repos="$(echo $repos | grep $1)"
shift
done
if [[ "$(echo $repos | grep -v '^$' | wc -l)" -gt 0 ]]; then
_execute_multiple_choice "cd" "$repos"
else
echo "repo not found locally, searching git" > /dev/stderr
rrepo "${original_args[@]}"
repo "${original_args[@]}"
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment