]> Sergey Matveev's repositories - zsh-autoenv.git/blob - lib/varstash
Usage examples
[zsh-autoenv.git] / lib / varstash
1 ################################################################################
2 # Stash/unstash support for per-directory variables
3 #
4 # Adopted for zsh-autoenv.
5 #
6 #   Copyright (c) 2009,2012 Dave Olszewski <cxreg@pobox.com>
7 #   http://github.com/cxreg/smartcd
8 #
9 #   This code is released under GPL v2 and the Artistic License, and
10 #   may be redistributed under the terms of either.
11 #
12 #
13 #   This library allows you to save the current value of a given environment
14 #   variable in a temporary location, so that you can modify it, and then
15 #   later restore its original value.
16 #
17 #   Note that you will need to be in the same directory you were in when you
18 #   stashed in order to successfully unstash.  This is because the temporary
19 #   variable is derived from your current working directory's path.
20 #
21 #   Usage:
22 #       stash PATH
23 #       export PATH=/something/else
24 #       [...]
25 #       unstash PATH
26 #
27 #   Note that this was written for use with, and works very well with,
28 #   smartcd.  See the documentation there for examples.
29 #
30 #   An alternate usage is `autostash' which will trigger autounstash when
31 #   leaving the directory, if combined with smartcd.  This reduces the amount
32 #   of explicit configuration you need to provide:
33 #
34 #       autostash PATH
35 #       export PATH=/something/else
36 #
37 #   You may also do both operations in one line, resulting in the very succinct
38 #
39 #       autostash PATH=/something/else
40 #
41 #   If you attempt to stash the same value twice, a warning will be displayed
42 #   and the second stash will not occur.  To make it happen anyway, pass -f
43 #   as the first argument to stash.
44 #
45 #       $ stash FOO
46 #       $ stash FOO
47 #       You have already stashed FOO, please specify "-f" if you want to overwrite another stashed value.
48 #       $ stash -f FOO
49 #       $
50 #
51 #   This rule is a bit different if you are assigning a value and the variable
52 #   has already been stashed.  In that case, the new value will be assigned, but
53 #   the stash will not be overwritten.  This allows for non-conflicting chained
54 #   stash-assign rules.
55 #
56 ################################################################################
57
58 function stash() {
59     if [[ $1 == "-f" ]]; then
60         local force=1; shift
61     fi
62
63     while [[ -n $1 ]]; do
64         if [[ $1 == "alias" && $2 == *=* ]]; then
65             shift
66             local _stashing_alias_assign=1
67             continue
68         fi
69
70         local stash_expression=$1
71         local stash_which=${stash_expression%%'='*}
72         local stash_name=$(_mangle_var $stash_which)
73
74         # Extract the value and make it double-quote safe
75         local stash_value=${stash_expression#*'='}
76         stash_value=${stash_value//\\/\\\\}
77         stash_value=${stash_value//\"/\\\"}
78         stash_value=${stash_value//\`/\\\`}
79         stash_value=${stash_value//\$/\\\$}
80
81         if [[ ( -n "$(eval echo '$__varstash_alias__'$stash_name)"    ||
82                 -n "$(eval echo '$__varstash_function__'$stash_name)" ||
83                 -n "$(eval echo '$__varstash_array__'$stash_name)"    ||
84                 -n "$(eval echo '$__varstash_export__'$stash_name)"   ||
85                 -n "$(eval echo '$__varstash_variable__'$stash_name)" ||
86                 -n "$(eval echo '$__varstash_nostash__'$stash_name)" )
87                 && -z $force ]]; then
88
89             if [[ -z $already_stashed && ${already_stashed-_} == "_" ]]; then
90                 local already_stashed=1
91             else
92                 already_stashed=1
93             fi
94
95             if [[ $stash_which == $stash_expression ]]; then
96                 if [[ -z $run_from_smartcd ]]; then
97                     echo "You have already stashed $stash_which, please specify \"-f\" if you want to overwrite another stashed value."
98                 fi
99
100                 # Skip remaining work if we're not doing an assignment
101                 shift
102                 continue
103             fi
104         fi
105
106         # Handle any alias that may exist under this name
107         if [[ -z $already_stashed ]]; then
108             local alias_def="$(eval alias $stash_which 2>/dev/null)"
109             if [[ -n $alias_def ]]; then
110                 alias_def=${alias_def#alias }
111                 eval "__varstash_alias__$stash_name=\"$alias_def\""
112                 local stashed=1
113             fi
114         fi
115         if [[ $stash_which != $stash_expression && -n $_stashing_alias_assign ]]; then
116             eval "alias $stash_which=\"$stash_value\""
117         fi
118
119         # Handle any function that may exist under this name
120         if [[ -z $already_stashed ]]; then
121             local function_def="$(declare -f $stash_which)"
122             if [[ -n $function_def ]]; then
123                 # make function definition quote-safe.  because we are going to evaluate the
124                 # source with "echo -e", we need to double-escape the backslashes (so 1 -> 4)
125                 function_def=${function_def//\\/\\\\\\\\}
126                 function_def=${function_def//\"/\\\"}
127                 function_def=${function_def//\`/\\\`}
128                 function_def=${function_def//\$/\\\$}
129                 eval "__varstash_function__$stash_name=\"$function_def\""
130                 local stashed=1
131             fi
132         fi
133
134         # Handle any variable that may exist under this name
135         local vartype="$(declare -p $stash_which 2>/dev/null)"
136         if [[ -n $vartype ]]; then
137             if [[ $vartype == 'typeset -a'* ]]; then
138                 # varible is an array
139                 if [[ -z $already_stashed ]]; then
140                     eval "__varstash_array__$stash_name=(\"\${$stash_which""[@]}\")"
141                 fi
142
143             elif [[ $vartype == "export "* || $vartype == 'typeset -x'* ]]; then
144                 # variable is exported
145                 if [[ -z $already_stashed ]]; then
146                     eval "export __varstash_export__$stash_name=\"\$$stash_which\""
147                 fi
148                 if [[ $stash_which != $stash_expression && -z $_stashing_alias_assign ]]; then
149                     eval "export $stash_which=\"$stash_value\""
150                 fi
151             else
152                 # regular variable
153                 if [[ -z $already_stashed ]]; then
154                     eval "__varstash_variable__$stash_name=\"\$$stash_which\""
155                 fi
156                 if [[ $stash_which != $stash_expression && -z $_stashing_alias_assign ]]; then
157                     eval "$stash_which=\"$stash_value\""
158                 fi
159
160             fi
161             local stashed=1
162         fi
163
164         if [[ -z $stashed ]]; then
165             # Nothing in the variable we're stashing, but make a note that we stashed so we
166             # do the right thing when unstashing.  Without this, we take no action on unstash
167
168             # Zsh bug sometimes caues
169             # (eval):1: command not found: __varstash_nostash___tmp__home_dolszewski_src_smartcd_RANDOM_VARIABLE=1
170             # fixed in zsh commit 724fd07a67f, version 4.3.14
171             if [[ -z $already_stashed ]]; then
172                 eval "export __varstash_nostash__$stash_name=1"
173             fi
174
175             # In the case of a previously unset variable that we're assigning too, export it
176             if [[ $stash_which != $stash_expression && -z $_stashing_alias_assign ]]; then
177                 eval "export $stash_which=\"$stash_value\""
178             fi
179         fi
180
181         shift
182         unset -v _stashing_alias_assign
183     done
184 }
185
186 function get_autostash_array_name() {
187     local autostash_name=$(_mangle_var AUTOSTASH)
188     # Create a scalar variable linked to an array (for exporting).
189     local autostash_array_name=${(L)autostash_name}
190     if ! (( ${(P)+autostash_array_name} )); then
191         # Conditionally set it, to prevent error with Zsh 4.3:
192         # can't tie already tied scalar: ...
193         typeset -xT $autostash_name $autostash_array_name
194     fi
195     ret=$autostash_array_name
196 }
197
198 function autostash() {
199     local run_from_autostash=1
200     local ret varname
201     local already_stashed=
202     while [[ -n $1 ]]; do
203         if [[ $1 == "alias" && $2 == *=* ]]; then
204             shift
205             local _stashing_alias_assign=1
206         fi
207
208         already_stashed=
209         stash "$1"
210         if [[ -z $already_stashed ]]; then
211             varname=${1%%'='*}
212             get_autostash_array_name
213             eval "$ret=(\$$ret \$varname)"
214         fi
215         shift
216         unset -v _stashing_alias_assign
217     done
218 }
219
220 function unstash() {
221     while [[ -n $1 ]]; do
222         local unstash_which=$1
223         if [[ -z $unstash_which ]]; then
224             continue
225         fi
226
227         local unstash_name=$(_mangle_var $unstash_which)
228
229         # This bit is a little tricky.  Here are the rules:
230         #   1) unstash any alias, function, or variable which matches
231         #   2) if one or more matches, but not all, delete any that did not
232         #   3) if none match but nostash is found, delete all
233         #   4) if none match and nostash not found, do nothing
234
235         # Unstash any alias
236         if [[ -n "$(eval echo \$__varstash_alias__$unstash_name)" ]]; then
237             eval "alias $(eval echo \$__varstash_alias__$unstash_name)"
238             unset __varstash_alias__$unstash_name
239             local unstashed=1
240             local unstashed_alias=1
241         fi
242
243         # Unstash any function
244         if [[ -n "$(eval echo \$__varstash_function__$unstash_name)" ]]; then
245             eval "function $(eval echo -e \"\$__varstash_function__$unstash_name\")"
246             unset __varstash_function__$unstash_name
247             local unstashed=1
248             local unstashed_function=1
249         fi
250
251         # Unstash any variable
252         if [[ -n "$(declare -p __varstash_array__$unstash_name 2>/dev/null)" ]]; then
253             eval "$unstash_which=(\"\${__varstash_array__$unstash_name""[@]}\")"
254             unset __varstash_array__$unstash_name
255             local unstashed=1
256             local unstashed_variable=1
257         elif [[ -n "$(declare -p __varstash_export__$unstash_name 2>/dev/null)" ]]; then
258             eval "export $unstash_which=\"\$__varstash_export__$unstash_name\""
259             unset __varstash_export__$unstash_name
260             local unstashed=1
261             local unstashed_variable=1
262         elif [[ -n "$(declare -p __varstash_variable__$unstash_name 2>/dev/null)" ]]; then
263             # Unset variable first to reset export
264             unset -v $unstash_which
265             eval "$unstash_which=\"\$__varstash_variable__$unstash_name\""
266             unset __varstash_variable__$unstash_name
267             local unstashed=1
268             local unstashed_variable=1
269         fi
270
271         # Unset any values which did not exist at time of stash
272         local nostash="$(eval echo \$__varstash_nostash__$unstash_name)"
273         unset __varstash_nostash__$unstash_name
274         if [[ ( -n "$nostash" && -z "$unstashed" ) || ( -n "$unstashed" && -z "$unstashed_alias" ) ]]; then
275             unalias $unstash_which 2>/dev/null
276         fi
277         if [[ ( -n "$nostash" && -z "$unstashed" ) || ( -n "$unstashed" && -z "$unstashed_function" ) ]]; then
278             unset -f $unstash_which 2>/dev/null
279         fi
280         if [[ ( -n "$nostash" && -z "$unstashed" ) || ( -n "$unstashed" && -z "$unstashed_variable" ) ]]; then
281             # Don't try to unset illegal variable names
282             # Using substitution to avoid using regex, which might fail to load on Zsh (minimal system).
283             if [[ ${unstash_which//[^a-zA-Z0-9_]/} == $unstash_which && $unstash_which != [0-9]* ]]; then
284                 unset -v $unstash_which
285             fi
286         fi
287
288         shift
289     done
290 }
291
292 function autounstash() {
293     # If there is anything in (mangled) variable AUTOSTASH, then unstash it
294     local ret
295     get_autostash_array_name
296     if (( ${#${(P)ret}} > 0 )); then
297         local run_from_autounstash=1
298         for autounstash_var in ${(P)ret}; do
299             unstash $autounstash_var
300         done
301         unset $ret
302     fi
303 }
304
305 function _mangle_var() {
306     local mangle_var_where="${varstash_dir:-$PWD}"
307     mangle_var_where=${mangle_var_where//[^A-Za-z0-9]/_}
308     local mangled_name=${1//[^A-Za-z0-9]/_}
309     echo "_tmp_${mangle_var_where}_${mangled_name}"
310 }
311
312 # vim: filetype=zsh autoindent expandtab shiftwidth=4 softtabstop=4