config: Declare local config variables earlier.
[gsu.git] / config
1 #!/bin/bash
2 # Copyright (C) 2006 Andre Noll
3 # Licensed under the LGPL, version 3. See COPYING and COPYING.LESSER.
4
5 # Syntactically check the gsu_options array for errors and parse the config
6 # file.
7 gsu_check_options()
8 {
9 local i conf="${gsu_config_file:=${HOME:-}/.$gsu_name.rc}" val orig_val
10 local name option_type default_value required description help_text
11
12 for ((i=0; i < ${#gsu_options[@]}; i++)); do
13 eval "${gsu_options[$i]}"
14 eval val='"'\${${name}:-}'"'
15 eval orig_${gsu_config_var_prefix}_$name='"'${val}'"'
16 done
17
18 [[ -r "$conf" ]] && source "$conf"
19
20 for ((i=0; i < ${#gsu_options[@]}; i++)); do
21 name=
22 option_type=
23 default_value=
24 required=
25 description=
26 help_text=
27
28 eval "${gsu_options[$i]}"
29
30 # Check name. It must be non-empty and consist of [a-zA-Z_0-9]
31 # only. Moreover it must start with [a-zA-Z].
32 ret=-$E_GSU_BAD_CONFIG_VAR
33 result="name: '$name'"
34 # bash's =~ works only for 3.2 and newer, so use grep
35 echo "$name" | grep '^[a-zA-Z][a-zA-Z_0123456789]*$' &> /dev/null;
36 (($? != 0)) && return
37
38 eval orig_val='"'\$orig_${gsu_config_var_prefix}_$name'"'
39 if [[ -z "$orig_val" ]]; then
40 eval val='"'\${$name:-}'"'
41 else
42 val="$orig_val"
43 fi
44 case "$required" in
45 true|yes)
46 ret=-$E_GSU_NEED_VALUE
47 result="$name"
48 [[ -z "$val" ]] && return
49 ;;
50 false|no)
51 ;;
52 *)
53 ret=-$E_GSU_BAD_BOOL
54 result="required: $required, name: $name, val: $val"
55 return
56 esac
57
58 eval ${gsu_config_var_prefix}_$name='"'\${val:="$default_value"}'"'
59 # Check option type. ATM, only num and string are supported
60 # Other types may be added without breaking compatibility
61 case "$option_type" in
62 string)
63 ;;
64 num)
65 gsu_is_a_number "$val"
66 (($ret < 0)) && return
67 ;;
68 *)
69 ret=-$E_GSU_BAD_OPTION_TYPE
70 result="$name/$option_type"
71 return
72 esac
73 done
74 ret=$GSU_SUCCESS
75 }
76
77 # Call gsu_check_options(), die on errors.
78 gsu_check_options_or_die()
79 {
80 gsu_check_options
81 if (($ret < 0)); then
82 gsu_err_msg
83 exit 1
84 fi
85 }
86
87 if [[ "$(type -t _gsu_setup)" != "function" ]]; then
88 gsu_dir=${gsu_dir:-${BASH_SOURCE[0]%/*}}
89 . $gsu_dir/common || exit 1
90 _gsu_setup
91 fi