Add conflict for replacing owned empty directory
[pacman-ng.git] / scripts / library / parse_options.sh
blob039eef92be33858115dd1d2120c01c3a420a55b8
1 # getopt like parser
2 parse_options() {
3 local short_options=$1; shift;
4 local long_options=$1; shift;
5 local ret=0;
6 local unused_options=""
7 local i
9 while [[ -n $1 ]]; do
10 if [[ ${1:0:2} = '--' ]]; then
11 if [[ -n ${1:2} ]]; then
12 local match=""
13 for i in ${long_options//,/ }; do
14 if [[ ${1:2} = ${i//:} ]]; then
15 match=$i
16 break
18 done
19 if [[ -n $match ]]; then
20 local needsargument=0
22 [[ ${match} = ${1:2}: ]] && needsargument=1
23 [[ ${match} = ${1:2}:: && -n $2 && ${2:0:1} != "-" ]] && needsargument=1
25 if (( ! needsargument )); then
26 printf ' %s' "$1"
27 else
28 if [[ -n $2 ]]; then
29 printf ' %s ' "$1"
30 shift
31 printf "'%q" "$1"
32 while [[ -n $2 && ${2:0:1} != "-" ]]; do
33 shift
34 printf " %q" "$1"
35 done
36 printf "'"
37 else
38 printf "@SCRIPTNAME@: $(gettext "option %s requires an argument\n")" "'$1'" >&2
39 ret=1
42 else
43 echo "@SCRIPTNAME@: $(gettext "unrecognized option") '$1'" >&2
44 ret=1
46 else
47 shift
48 break
50 elif [[ ${1:0:1} = '-' ]]; then
51 for ((i=1; i<${#1}; i++)); do
52 if [[ $short_options =~ ${1:i:1} ]]; then
53 local needsargument=0
55 [[ $short_options =~ ${1:i:1}: && ! $short_options =~ ${1:i:1}:: ]] && needsargument=1
56 [[ $short_options =~ ${1:i:1}:: && \
57 ( -n ${1:$i+1} || ( -n $2 && ${2:0:1} != "-" ) ) ]] && needsargument=1
59 if (( ! needsargument )); then
60 printf ' -%s' "${1:i:1}"
61 else
62 if [[ -n ${1:$i+1} ]]; then
63 printf ' -%s ' "${1:i:1}"
64 printf "'%q" "${1:$i+1}"
65 while [[ -n $2 && ${2:0:1} != "-" ]]; do
66 shift
67 printf " %q" "$1"
68 done
69 printf "'"
70 else
71 if [[ -n $2 ]]; then
72 printf ' -%s ' "${1:i:1}"
73 shift
74 printf "'%q" "$1"
75 while [[ -n $2 && ${2:0:1} != "-" ]]; do
76 shift
77 printf " %q" "$1"
78 done
79 printf "'"
81 else
82 printf "@SCRIPTNAME@: $(gettext "option %s requires an argument\n")" "'-${1:i:1}'" >&2
83 ret=1
86 break
88 else
89 echo "@SCRIPTNAME@: $(gettext "unrecognized option") '-${1:i:1}'" >&2
90 ret=1
92 done
93 else
94 unused_options="${unused_options} '$1'"
96 shift
97 done
99 printf " --"
100 [[ $unused_options ]] && printf ' %s' "${unused_options[@]}"
101 [[ $1 ]] && printf " '%s'" "$@"
102 printf "\n"
104 return $ret