manage_hooks-completion.bash 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #!/bin/bash
  2. #Not gonna lie, this is some magical stuff, but I will try to explain it
  3. #Automatic variables used by complete
  4. #COMPREPLY = An array of autocompletions to pass back to the shell
  5. #COMP_WORDS = The passed-in list of parameters
  6. #COMP_CWORD = The index of the current word as related to the count of
  7. #parameters
  8. #compgen = Generates an array of autocompletions to pass back to the shell
  9. #based on provided parameters
  10. function __completion() {
  11. COMPREPLY=()
  12. cur="${COMP_WORDS[COMP_CWORD]}"
  13. prev="${COMP_WORDS[COMP_CWORD-1]}"
  14. opts="list install remove"
  15. #Determine what "level" of autocomplete we are operating on
  16. #1 is no params
  17. #2 is 1 param, in this instance the command
  18. #3 etc
  19. case ${COMP_CWORD} in
  20. 1)
  21. #Generate a Word-list from opts from the current word
  22. COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
  23. ;;
  24. 2)
  25. case ${prev} in
  26. install)
  27. #Generate a list of filenames (and append "all") based on the current
  28. #directory and current word while ignoring select files
  29. COMPREPLY=( $(compgen -W "all $(ls --ignore='*.md' --ignore='*.sh' --ignore='*.bash')" -- ${cur}) )
  30. ;;
  31. remove)
  32. #Generate a list of filenames (and append "all") based on the
  33. #.git/hooks directory and current word while ignoring the sample
  34. #files
  35. COMPREPLY=( $(compgen -W "all $(ls ../.git/hooks --ignore='*.sample')" -- ${cur}) )
  36. ;;
  37. esac
  38. ;;
  39. 3)
  40. case "${COMP_WORDS[COMP_CWORD-2]}" in
  41. install)
  42. #When attempting to autocomplete for the third parameter ie copy
  43. #/symbolic AND the command is install
  44. #Generate a list of Words from the provded string
  45. COMPREPLY=( $(compgen -W "copy symbolic" -- ${cur}) )
  46. ;;
  47. esac
  48. ;;
  49. esac
  50. }
  51. #Use the function defined above, when an autocomplete event for
  52. #./manage_hooks.sh is fired. This is why you must be in the proper directory
  53. complete -F __completion ./manage_hooks.sh