ynh_handle_getopts_args 17 KB

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