Gentoo Archives: gentoo-dev

From: Mike Frysinger <vapier@g.o>
To: gentoo-dev@l.g.o
Subject: [gentoo-dev] new eshopts_{push,pop} functions
Date: Wed, 09 Dec 2009 10:02:45
Message-Id: 200912090341.38018.vapier@gentoo.org
1 i got tired of copying & pasting the shell option save/restore code, so i
2 created two helper functions. am i missing anything before i add to
3 eutils.eclass ? i could extend eshopts_pop to take a numeric argument for
4 number of stack entries to pop, but i dont see much value/use.
5
6 # @FUNCTION: eshopts_push
7 # @USAGE: [options to `set`]
8 # @DESCRIPTION:
9 # Often times code will want to enable a shell option to change code behavior.
10 # Since changing shell options can easily break other pieces of code (which
11 # assume the default state), eshopts_push is used to (1) push the current shell
12 # options onto a stack and (2) pass the specified arguments to set.
13 #
14 # A common example is to disable shell globbing so that special meaning/care
15 # may be used with variables/arguments to custom functions. That would be:
16 # @CODE
17 # eshopts_push -o noglob
18 # for x in ${foo} ; do
19 # if ...some check... ; then
20 # eshopts_pop
21 # return 0
22 # fi
23 # done
24 # eshopts_pop
25 # @CODE
26 eshopts_push() {
27 # have to assume __ESHOPTS_SAVE__ isn't screwed with
28 # as a `declare -a` here will reset its value
29 local i=${#__ESHOPTS_SAVE__[@]}
30 __ESHOPTS_SAVE__[$i]=$-
31 [[ $# -eq 0 ]] && return 0
32 set "$@" || die "eshopts_push: bad options to set"
33 }
34
35 # @FUNCTION: eshopts_pop
36 # @USAGE:
37 # @DESCRIPTION:
38 # Restore the shell options to the state saved with the corresponding
39 # eshopts_push call. See that function for more details.
40 eshopts_pop() {
41 [[ $# -ne 0 ]] && die "eshopts_pop takes no arguments"
42 local i=$(( ${#__ESHOPTS_SAVE__[@]} - 1 ))
43 [[ ${i} -eq -1 ]] && die "eshopts_{push,pop}: unbalanced pair"
44 local s=${__ESHOPTS_SAVE__[$i]}
45 unset __ESHOPTS_SAVE__[$i]
46 set +$- || die "eshopts_pop: sanity: invalid shell settings !?"
47 set -${s} || die "eshopts_pop: sanity: unable to restore saved shell settings"
48 }
49
50 and an example of new usage in eutils.eclass:
51
52 @@ -1343,16 +1363,15 @@ check_license() {
53
54 # here is where we check for the licenses the user already
55 # accepted ... if we don't find a match, we make the user accept
56 - local shopts=$-
57 local alic
58 - set -o noglob #so that bash doesn't expand "*"
59 + eshopts_push -o noglob # so that bash doesn't expand "*"
60 for alic in ${ACCEPT_LICENSE} ; do
61 if [[ ${alic} == ${l} ]]; then
62 - set +o noglob; set -${shopts} #reset old shell opts
63 + eshopts_pop
64 return 0
65 fi
66 done
67 - set +o noglob; set -$shopts #reset old shell opts
68 + eshopts_pop
69
70 local licmsg=$(emktemp)
71 cat <<-EOF > ${licmsg}
72
73 -mike

Attachments

File name MIME type
signature.asc application/pgp-signature