ynh_handle_getopts_args 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. #!/bin/bash
  2. # Redisgn of ynh_handle_getopts_args for flohmarkt to be tested as `flohmarkt_ynh_handle_getopts_args`
  3. # https://github.com/YunoHost/yunohost/pull/1856
  4. # Internal helper design to allow helpers to use getopts to manage their arguments
  5. #
  6. # [internal]
  7. #
  8. # example: function my_helper()
  9. # {
  10. # local -A args_array=( [a]=arg1= [b]=arg2= [c]=arg3 )
  11. # local arg1
  12. # local arg2
  13. # local arg3
  14. # ynh_handle_getopts_args "$@"
  15. #
  16. # [...]
  17. # }
  18. # my_helper --arg1 "val1" -b val2 -c
  19. #
  20. # usage: ynh_handle_getopts_args "$@"
  21. # | arg: $@ - Simply "$@" to tranfert all the positionnal arguments to the function
  22. #
  23. # This helper need an array, named "args_array" with all the arguments used by the helper
  24. # that want to use ynh_handle_getopts_args
  25. # Be carreful, this array has to be an associative array, as the following example:
  26. # local -A args_array=( [a]=arg1 [b]=arg2= [c]=arg3 )
  27. # Let's explain this array:
  28. # a, b and c are short options, -a, -b and -c
  29. # arg1, arg2 and arg3 are the long options associated to the previous short ones. --arg1, --arg2 and --arg3
  30. # For each option, a short and long version has to be defined.
  31. # Let's see something more significant
  32. # local -A args_array=( [u]=user [f]=finalpath= [d]=database )
  33. #
  34. # NB: Because we're using 'declare' without -g, the array will be declared as a local variable.
  35. #
  36. # Please keep in mind that the long option will be used as a variable to store the values for this option.
  37. # For the previous example, that means that $finalpath will be fill with the value given as argument for this option.
  38. #
  39. # Also, in the previous example, finalpath has a '=' at the end. That means this option need a value.
  40. # So, the helper has to be call with --finalpath /final/path, --finalpath=/final/path or -f /final/path,
  41. # the variable $finalpath will get the value /final/path
  42. # If there's many values for an option, -f /final /path, the value will be separated by a ';' $finalpath=/final;/path
  43. # For an option without value, like --user in the example, the helper can be called only with --user or -u. $user
  44. # will then get the value 1.
  45. #
  46. # To keep a retrocompatibility, a package can still call a helper, using getopts, with positional arguments.
  47. # The "legacy mode" will manage the positional arguments and fill the variable in the same order than they are given
  48. # in $args_array. e.g. for `my_helper "val1" val2`, arg1 will be filled with val1, and arg2 with val2.
  49. # Positional parameters (used to be the only way to use ynh_handle_getopts_args once upon a time) can be
  50. # used also:
  51. #
  52. # '--' start processing the rest of the arguments as positional parameters
  53. # $legacy_args The arguments positional parameters will be assign to
  54. # Needs to be composed of array keys of args_array. If a key for a predefined variable
  55. # is used multiple times the assigned values will be concatenated delimited by ';'.
  56. # If the long option variable to contain the data is predefined as an array (e.g. using
  57. # `local -a arg1` then multiple values will be assigned to its cells.
  58. # If the last positional parameter defined in legacy_args is defined as an array all
  59. # the leftover positional parameters will be assigned to its cells.
  60. # (it is named legacy_args, because the use of positional parameters was about to be
  61. # deprecated before the last re-design of this sub)
  62. #
  63. # Requires YunoHost version 3.2.2 or higher.
  64. # flohmarkt_ynh_handle_getopts_args() {
  65. ynh_handle_getopts_args() {
  66. # Manage arguments only if there's some provided
  67. set +o xtrace # set +x
  68. if [ $# -eq 0 ]; then
  69. ynh_print_warn --message="ynh_handle_getopts_args called without arguments"
  70. return
  71. fi
  72. # Store arguments in an array to keep each argument separated
  73. local arguments=("$@")
  74. # For each option in the array, reduce to short options for getopts (e.g. for [u]=user, --user will be -u)
  75. # And built parameters string for getopts
  76. # ${!args_array[@]} is the list of all option_flags in the array (An option_flag is 'u' in [u]=user, user is a value)
  77. local getopts_parameters=""
  78. local option_flag=""
  79. ## go through all possible options and replace arguments with short versions
  80. flohmarkt_print_debug "arguments = '${arguments[@]}"
  81. flohmarkt_print_debug "args_array = (${!args_array[@]})"
  82. for option_flag in "${!args_array[@]}"; do
  83. # TODO refactor: Now I'm not sure anymore this part belongs here. To make the
  84. # this all less hard to read and understand I'm thinking at the moment that it
  85. # would be good to split the different things done here into their own loops:
  86. #
  87. # 1. build the option string $getopts_parameters
  88. # 2. go through the arguments and add empty arguments where needed to
  89. # allow for cases like '--arg= --value' where 'value' is a valid option, too
  90. # 3. replace long option names by short once
  91. # 4. (possibly add empty parameters for '-a -v' in cases where -a expects a value
  92. # and -v is a valid option, too - but I dearly hope this will not be necessary)
  93. flohmarkt_print_debug "option_flag = $option_flag"
  94. # Concatenate each option_flags of the array to build the string of arguments for getopts
  95. # Will looks like 'abcd' for -a -b -c -d
  96. # If the value of an option_flag finish by =, it's an option with additionnal values.
  97. # (e.g. --user bob or -u bob)
  98. # Check the last character of the value associate to the option_flag
  99. flohmarkt_print_debug "compare to '${args_array[$option_flag]: -1}'"
  100. if [ "${args_array[$option_flag]: -1}" = "=" ]; then
  101. # For an option with additionnal values, add a ':' after the letter for getopts.
  102. getopts_parameters="${getopts_parameters}${option_flag}:"
  103. else
  104. getopts_parameters="${getopts_parameters}${option_flag}"
  105. fi
  106. flohmarkt_print_debug "getopts_parameters = ${getopts_parameters}"
  107. # Check each argument given to the function
  108. local arg=""
  109. # ${#arguments[@]} is the size of the array
  110. ## for one possible option: look at each argument supplied:
  111. for arg in $(seq 0 $((${#arguments[@]} - 1))); do
  112. flohmarkt_print_debug "option_flag='$option_flag', arg = '$arg', argument = '${arguments[arg]}'"
  113. # the following cases need to be taken care of
  114. # '--arg=value' → works
  115. # '--arg= value' → works
  116. # '--arg=-value' → works
  117. # '--arg= -v' or
  118. # '--arg= --value' → works if not exists arg '[v]=value='
  119. # → $arg will be set to '-v' or '--value'
  120. # but if exists '[v]=value=' this is not the expected behavior:
  121. # → then $arg is expected to contain an empty value and '-v' or '--value'
  122. # is expected to be interpreted as its own valid argument
  123. # (found in use of ynh_replace_string called by ynh_add_config)
  124. # solution:
  125. # insert an empty arg into array arguments to be later interpreted by
  126. # getopts as the missing value to --arg=
  127. if [[ -v arguments[arg+1] ]] && [[ ${arguments[arg]: -1} == '=' ]]; then
  128. # arg ends with a '='
  129. local this_argument=${arguments[arg]}
  130. local next_argument=${arguments[arg+1]}
  131. # for looking up next_argument in args_array remove optionally trailing '='
  132. next_argument=$( printf '%s' "$next_argument" | cut -d'=' -f1 )
  133. flohmarkt_print_debug "MISSING PARAMETER: this_argument='$this_argument', next_argument='$next_argument'"
  134. # check if next_argument is a value in args_array
  135. # → starts with '--' and the rest of the argument excluding optional trailing '='
  136. # of the string is a value in associative array args_array
  137. # → or starts with '-' and the rest of the argument is a valid key in args_array
  138. # (long argument could already have been replaced by short version before)
  139. flohmarkt_print_debug "args_array values='${args_array[@]}'"
  140. flohmarkt_print_debug "args_array keys='${!args_array[@]}'"
  141. flohmarkt_print_debug "{next_argument:2}='${next_argument:2}'"
  142. flohmarkt_print_debug "{next_argument:0:2}='${next_argument:0:2}'"
  143. if ( [[ "${next_argument:0:2}" == '--' ]] \
  144. && printf '%s ' "${args_array[@]}" | fgrep -w "${next_argument:2}" > /dev/null ) \
  145. || ( [[ "${next_argument:0:1}" == '-' ]] \
  146. && printf '%s ' "${!args_array[@]}" | fgrep -w "${next_argument:1:1}" > /dev/null )
  147. then
  148. # insert an empty value to array arguments to be interpreted as the value
  149. # for argument[arg]
  150. arguments=( ${arguments[@]:0:arg+1} '' ${arguments[@]:arg+1})
  151. flohmarkt_print_debug "now arguments='${arguments[@]}'"
  152. fi
  153. fi
  154. # Replace long option with = (match the beginning of the argument)
  155. arguments[arg]="$(printf '%s\n' "${arguments[arg]}" \
  156. | sed "s/^--${args_array[$option_flag]}/-${option_flag}/")"
  157. # And long option without = (match the whole line)
  158. arguments[arg]="$(printf '%s\n' "${arguments[arg]}" \
  159. | sed "s/^--${args_array[$option_flag]%=}$/-${option_flag}/")"
  160. flohmarkt_print_debug " arg = '$arg', argument = '${arguments[arg]}'"
  161. done
  162. flohmarkt_print_debug "====> end loop: arguments = '${arguments[@]}'"
  163. done
  164. flohmarkt_print_debug '================= end first loop ================='
  165. # Parse the first argument, return the number of arguments to be shifted off the arguments array
  166. # The function call is necessary here to allow `getopts` to use $@
  167. parse_arg() {
  168. flohmarkt_print_debug "========= parse_arg started ======== , arguments='$@', getopts_parameters: '$getopts_parameters'"
  169. # Initialize the index of getopts
  170. OPTIND=1
  171. # getopts will fill $parameter with the letter of the option it has read.
  172. local parameter=""
  173. getopts ":$getopts_parameters" parameter || true
  174. flohmarkt_print_debug "after getopts - parameter='$parameter', OPTIND='${OPTIND:-none}', OPTARG='${OPTARG:-none}'"
  175. if [ "$parameter" = "?" ]; then
  176. ynh_die --message="Invalid argument: -${OPTARG:-}"
  177. flohmarkt_print_debug "Invalid argument: -${OPTARG:-}"
  178. exit 255
  179. elif [ "$parameter" = ":" ]; then
  180. ynh_die --message="-$OPTARG parameter requires an argument."
  181. echo "-$OPTARG parameter requires an argument."
  182. exit 255
  183. else
  184. # Use the long option, corresponding to the short option read by getopts, as a variable
  185. # (e.g. for [u]=user, 'user' will be used as a variable)
  186. # Also, remove '=' at the end of the long option
  187. # The variable name will be stored in 'option_var' as a nameref
  188. option_var="${args_array[$parameter]%=}"
  189. flohmarkt_print_debug "option_var='$option_var'"
  190. # if there's a '=' at the end of the long option name, this option takes values
  191. if [ "${args_array[$parameter]: -1}" != "=" ]; then
  192. # no argument expected for option - set option variable to '1'
  193. option_value=1
  194. else
  195. # remove leading and trailing spaces from OPTARG
  196. OPTARG="$( printf '%s' "${OPTARG}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"
  197. option_value="${OPTARG}"
  198. fi
  199. flohmarkt_print_debug "option_value='$option_value'"
  200. # set shift_value according to the number of options interpreted by getopts
  201. shift_value=$(( $OPTIND - 1 ))
  202. flohmarkt_print_debug "shift_value='$shift_value'"
  203. fi
  204. }
  205. # iterate over the arguments: if first argument starts with a '-' feed arguments to getopts
  206. # if first argument doesn't start with a '-' enter mode to read positional parameters
  207. local argument
  208. local positional_mode=0 # state is getopts mode at the beginning, not positional parameters
  209. local positional_count=0 # counter for positional parameters
  210. local option_var='' # the variable name to be filled
  211. # Try to use legacy_args as a list of option_flag of the array args_array
  212. # Otherwise, fill it with getopts_parameters to get the option_flag.
  213. # (But an associative arrays isn't always sorted in the correct order...)
  214. # Remove all ':' in getopts_parameters, if used.
  215. legacy_args=${legacy_args:-${getopts_parameters//:/}}
  216. while [[ -v 'arguments' ]] && [[ ${#arguments} -ne 0 ]]; do
  217. flohmarkt_print_debug '======= start while loop ======='
  218. local shift_value=0
  219. local option_value='' # the value to be filled into ${!option_var}
  220. argument=${arguments[0]}
  221. flohmarkt_print_debug "argument='$argument'"
  222. # if state once changed to positional parameter mode, all the rest of the arguments will
  223. # be interpreted in positional parameter mode even if they start with a '-'
  224. if [ $positional_mode == 0 ] && [ "${argument}" == '--' ];then
  225. flohmarkt_print_debug "found '--', start positional parameter mode"
  226. positional_mode=1
  227. shift_value=1
  228. elif [ $positional_mode == 0 ] && [ "${argument:0:1}" == '-' ]; then
  229. flohmarkt_print_debug "getopts, arguments='${arguments[@]}', starting parse_arg"
  230. parse_arg "${arguments[@]}"
  231. else
  232. positional_mode=1 # set state to positional parameter mode
  233. flohmarkt_print_debug "positional parameter, argument='$argument'"
  234. # Get the option_flag from getopts_parameters by using the option_flag according to the
  235. # position of the argument.
  236. option_flag=${legacy_args:$positional_count:1}
  237. # increment counter for legacy_args if still args left. If no args left check if the
  238. # last arg is a predefined array and let it cells be filled. Otherwise complain and
  239. # return.
  240. flohmarkt_print_debug "positional_counter='$positional_count', max positional_counter='$(( ${#legacy_args} -1 ))'"
  241. if [[ $positional_count -le $((${#legacy_args} - 1)) ]]; then
  242. # set counter to for next option_flag to fill
  243. positional_count=$((positional_count+1))
  244. flohmarkt_print_debug "incremented positional_counter to '$positional_count'"
  245. # Use the long option, corresponding to the option_flag, as a variable
  246. # (e.g. for [u]=user, 'user' will be used as a variable)
  247. # Also, remove '=' at the end of the long option
  248. # The variable name will be stored in 'option_var'
  249. option_var="${args_array[$option_flag]%=}"
  250. elif [[ $positional_count -ge $((${#legacy_args} - 1)) ]] &&
  251. ! declare -p ${option_var} | grep '^declare -a'
  252. then
  253. # no more legacy_args to fill - legacy behaviour: complain and return
  254. ynh_print_warn --message="Too many arguments ! \"${arguments[$i]}\" will be ignored."
  255. return
  256. else
  257. flohmarkt_print_debug "array found - keep going"
  258. fi
  259. # value to be assigned to ${!option_var}
  260. option_value=$argument
  261. # shift off one positional parameter
  262. shift_value=1
  263. fi
  264. # fill option_var with value found
  265. # if ${!option_var} is an array, fill mutiple values as array cells
  266. # otherwise concatenate them seperated by ';'
  267. # nameref is used to access the variable that is named $option_var
  268. local -n option_ref=$option_var
  269. # this defines option_ref as a reference to the variable named "$option_var"
  270. # any operation on option_ref will be written to the variable named "$option_var"
  271. # 'option_ref="hello world"' will work like as if '${!option_var}="hello world"'
  272. # would be a valid syntax
  273. # see also: `man bash` part about commands 'declare' option '-n'
  274. flohmarkt_print_debug "option_ref declare: '$(declare -p option_ref)'"
  275. flohmarkt_print_debug "'$option_var' declare: '$(declare -p $option_var)'"
  276. flohmarkt_print_debug "option_value='$option_value'"
  277. if declare -p $option_var | grep '^declare -a ' > /dev/null; then
  278. # hurray it's an array
  279. flohmarkt_print_debug "hurray! '$option_var' is an array."
  280. option_ref+=( "${option_value}" )
  281. elif ! [[ -v "$option_var" ]] || [[ -z "$option_ref" ]]; then
  282. flohmarkt_print_debug "'$option_var' is unset or empty"
  283. option_ref=${option_value}
  284. else
  285. flohmarkt_print_debug "appending to string '$option_ref'"
  286. option_ref+=";${option_value}"
  287. fi
  288. flohmarkt_print_debug "now declared $option_var: '$(declare -p $option_var)'"
  289. # shift value off arguments array
  290. flohmarkt_print_debug "shifting '$shift_value' off arguments='${arguments[@]}'"
  291. arguments=("${arguments[@]:${shift_value}}")
  292. done
  293. # the former subroutine did this - no idea if it is expected somewhere
  294. unset legacy_args
  295. # re-enable trace
  296. set -o xtrace # set -x
  297. }