Skip to content

Instantly share code, notes, and snippets.

@davidgf
Last active June 28, 2018 13:41
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save davidgf/5bd76141aa70f9ed4d8f716851e68830 to your computer and use it in GitHub Desktop.
Save davidgf/5bd76141aa70f9ed4d8f716851e68830 to your computer and use it in GitHub Desktop.
Bash completion for Serverless
_sls()
{
local cur prev words cword
COMPREPLY=()
cur="${COMP_WORDS[COMP_CWORD]}"
prev="${COMP_WORDS[COMP_CWORD-1]}"
words="${COMP_WORDS}"
local COMMANDS=(
"project"
"function"
"endpoint"
"event"
"dash"
"stage"
"region"
"resources"
"plugin"
"variables"
)
local FCOMMANDS=(
"run"
"deploy"
"create"
"logs"
"remove"
"rollback"
)
local command
if [[ ${COMP_CWORD} -gt 1 && ${COMMANDS[@]} =~ ${COMP_WORDS[1]} ]]; then
command=${COMP_WORDS[1]}
fi
# command is function, showing subcommands
if [[ "$command" = "function" && ${COMP_CWORD} -eq 2 ]]; then
COMPREPLY=( $( compgen -W '${FCOMMANDS[@]}' ${cur} ) )
return 0
fi
# command is function and has subcommand, showing function names
if [[ "$command" = "function" && ${COMP_CWORD} -eq 3 ]]; then
local fnames=`find . -type f -name "s-function.json" |sed "s#\(.*\)/.*#\1#" | rev |cut -d"/" -f1 | rev`
COMPREPLY=( $( compgen -W '${fnames}' ${cur} ) )
return 0
fi
# no command yet, show what commands we have
if [ "$command" = "" ]; then
COMPREPLY=( $( compgen -W '${COMMANDS[@]}' ${cur} ) )
fi
return 0
} &&
complete -F _sls serverless
complete -F _sls sls
@danielesegato
Copy link

danielesegato commented Jun 29, 2016

Thanks.

to Avoid the find . you can do something like this:

upsearch () {
  slashes=${PWD//[^\/]/}
  directory="$PWD"
  for (( n=${#slashes}; n>0; --n ))
  do
    test -e "$directory/$1" && echo `readlink -m "$directory/$1"` && return 0
    directory="$directory/.."
  done
  return 1
}

projectDir=`upsearch s-project.json`
if [ $? -eq 0 ]; then
  echo "Found = $projectDir";
fi

The upsearch function search for a specifical file name starting from current directory recursively up.
If it find it it echo it and return 0, if not return 1.
you can get the result, check if it found it and then use that for the find command. This assure you do not run find on root directory (unless someone place the s-project.json file in the root directory).

@danielesegato
Copy link

danielesegato commented Jun 30, 2016

@davidgf
Copy link
Author

davidgf commented Jul 5, 2016

Awesome @danielesegato, thank you very much! Only one thing prevents me from using your script: I'm using OS X and the readlink command is apparently different from the Linux version. Do you know any workaround for this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment