Fix gsu_cword_is_option_parameter().
[gsu.git] / common
1 #!/bin/bash
2 # Copyright (C) 2006 Andre Noll
3 # Licensed under the LGPL, version 3. See COPYING and COPYING.LESSER.
4
5 _gsu_init_errors()
6 {
7 gsu_errors="
8 GSU_SUCCESS success
9 E_GSU_BAD_COMMAND invalid command
10 E_GSU_NOT_A_NUMBER not a number
11 E_GSU_BAD_CONFIG_VAR invalid config variable
12 E_GSU_NEED_VALUE value required but not given
13 E_GSU_BAD_BOOL bad value for boolian option
14 E_GSU_BAD_OPTION_TYPE invalid option type
15 E_GSU_BAD_ARG_COUNT invalid number of arguments
16 E_GSU_EDITOR failed to execute editor
17 E_GSU_MKDIR failed to create directory
18 E_GSU_GETOPTS getopts error
19 E_GSU_DIALOG dialog error
20 E_GSU_MKTEMP mktemp error
21 E_GSU_MENU_TREE invalid menu tree
22 ${gsu_errors:-}
23 "
24 local a b i=0
25 while read a b; do
26 if test -z "$a"; then
27 continue
28 fi
29 #echo "a:$a, b: $b"
30 gsu_error_txt[i]="$b"
31 eval $a=$i
32 i=$(($i + 1))
33 done << EOF
34 $gsu_errors
35 EOF
36 }
37
38 # check if $1 is a number
39 gsu_is_a_number()
40 {
41 result="$1"
42 if [ "$1" -eq "$1" ] &> /dev/null; then
43 ret=$GSU_SUCCESS
44 else
45 ret=-$E_GSU_NOT_A_NUMBER
46 fi
47 }
48
49 gsu_short_msg()
50 {
51 echo "$1" 1>&2
52 }
53
54 gsu_msg()
55 {
56 gsu_short_msg "$gsu_name: $1"
57 }
58
59 gsu_date_msg()
60 {
61 gsu_short_msg "$gsu_name $(date): $1"
62 }
63
64 gsu_err_msg()
65 {
66 local txt="$result" err
67
68 gsu_is_a_number "$ret"
69 if (($ret < 0)); then
70 gsu_msg "unknown error ($ret:$txt)"
71 exit 1
72 fi
73 if (($result >= 0)); then
74 gsu_msg "unknown error ($result:$txt)"
75 exit 1
76 fi
77 err=$((0 - $result))
78 if test -n "$txt"; then
79 txt="$txt: ${gsu_error_txt[$err]}"
80 else
81 txt="${gsu_error_txt[$err]}"
82 fi
83 gsu_msg "$txt"
84 }
85
86 _gsu_setup()
87 {
88 gsu_name="${gsu_name:-${0##*/}}"
89 gsu_config_var_prefix="${gsu_config_var_prefix:=$gsu_name}"
90 gsu_banner_txt="${gsu_banner_txt:-set \$gsu_banner_txt to customize this message}"
91 _gsu_init_errors
92 }
93
94 # We'd love to use mktemp -t here, but on Linux -t is deprecated in favor of
95 # --tempdir, which is not supported on *BSD. Hence we have to implement our own
96 # logic for -t.
97 #
98 # The second parameter to this function is optional. It is ignored if the
99 # template ($1) is an absolute path. Conversely, if the template is a relative
100 # path and a second parameter is given, $2 is assumed to be the directory in
101 # which the temporary file should be created.
102 gsu_make_tempfile()
103 {
104 local template="$1"
105 local dir
106
107 if [[ "${template:0:1}" != '/' ]]; then # relative path
108 if (($# > 1)); then
109 dir="$2"
110 elif [[ -n "${TMPDIR:-}" ]]; then
111 dir="$TMPDIR"
112 else
113 dir="/tmp"
114 fi
115 template="$dir/$template"
116 fi
117 result="$(mktemp "$template")"
118 if (($? != 0)); then
119 ret=-$E_GSU_MKTEMP
120 result="template: $template"
121 return
122 fi
123 ret=$GSU_SUCCESS
124 }