init.sh: don't use $(...) just yet
[gnulib.git] / tests / init.sh
1 # source this file; set up for tests
2
3 # Copyright (C) 2009, 2010 Free Software Foundation, Inc.
4
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14
15 # You should have received a copy of the GNU General Public License
16 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
18 # Using this file in a test
19 # =========================
20 #
21 # The typical skeleton of a test looks like this:
22 #
23 #   #!/bin/sh
24 #   : ${srcdir=.}
25 #   . "$srcdir/init.sh"; path_prepend_ .
26 #   Execute some commands.
27 #   Note that these commands are executed in a subdirectory, therefore you
28 #   need to prepend "../" to relative filenames in the build directory.
29 #   Set the exit code 0 for success, 77 for skipped, or 1 or other for failure.
30 #   Use the skip_ and fail_ functions to print a diagnostic and then exit
31 #   with the corresponding exit code.
32 #   Exit $?
33
34 # Executing a test that uses this file
35 # ====================================
36 #
37 # Running a single test:
38 #   $ make check TESTS=test-foo.sh
39 #
40 # Running a single test, with verbose output:
41 #   $ make check TESTS=test-foo.sh VERBOSE=yes
42 #
43 # Running a single test, with single-stepping:
44 #   1. Go into a sub-shell:
45 #   $ bash
46 #   2. Set relevant environment variables from TESTS_ENVIRONMENT in the
47 #      Makefile:
48 #   $ export srcdir=../../tests # this is an example
49 #   3. Execute the commands from the test, copy&pasting them one by one:
50 #   $ . "$srcdir/init.sh"; path_prepend_ .
51 #   ...
52 #   4. Finally
53 #   $ exit
54
55 # We use a trap below for cleanup.  This requires us to go through
56 # hoops to get the right exit status transported through the handler.
57 # So use `Exit STATUS' instead of `exit STATUS' inside of the tests.
58 # Turn off errexit here so that we don't trip the bug with OSF1/Tru64
59 # sh inside this function.
60 Exit () { set +e; (exit $1); exit $1; }
61
62 fail_() { echo "$ME_: failed test: $@" 1>&2; Exit 1; }
63 skip_() { echo "$ME_: skipped test: $@" 1>&2; Exit 77; }
64
65 # This is a stub function that is run upon trap (upon regular exit and
66 # interrupt).  Override it with a per-test function, e.g., to unmount
67 # a partition, or to undo any other global state changes.
68 cleanup_() { :; }
69
70 if ( diff --version < /dev/null 2>&1 | grep GNU ) 2>&1 > /dev/null; then
71   compare() { diff -u "$@"; }
72 elif ( cmp --version < /dev/null 2>&1 | grep GNU ) 2>&1 > /dev/null; then
73   compare() { cmp -s "$@"; }
74 else
75   compare() { cmp "$@"; }
76 fi
77
78 # An arbitrary prefix to help distinguish test directories.
79 testdir_prefix_() { printf gt; }
80
81 # Run the user-overridable cleanup_ function, remove the temporary
82 # directory and exit with the incoming value of $?.
83 remove_tmp_()
84 {
85   __st=$?
86   cleanup_
87   # cd out of the directory we're about to remove
88   cd "$initial_cwd_" || cd / || cd /tmp
89   chmod -R u+rwx "$test_dir_"
90   # If removal fails and exit status was to be 0, then change it to 1.
91   rm -rf "$test_dir_" || { test $__st = 0 && __st=1; }
92   exit $__st
93 }
94
95 # Given a directory name, DIR, if every entry in it that matches *.exe
96 # contains only the specified bytes (see the case stmt below), then print
97 # a space-separated list of those names and return 0.  Otherwise, don't
98 # print anything and return 1.  Naming constraints apply also to DIR.
99 find_exe_basenames_()
100 {
101   feb_dir_=$1
102   feb_fail_=0
103   feb_result_=
104   feb_sp_=
105   for feb_file_ in $feb_dir_/*.exe; do
106     case $feb_file_ in
107       *[!-a-zA-Z/0-9_.+]*) feb_fail_=1; break;;
108       *) # Remove leading file name components as well as the .exe suffix.
109          feb_file_=${feb_file_##*/}
110          feb_file_=${feb_file_%.exe}
111          feb_result_="$feb_result_$feb_sp_$feb_file_";;
112     esac
113     feb_sp_=' '
114   done
115   test $feb_fail_ = 0 && printf %s "$feb_result_"
116   return $feb_fail_
117 }
118
119 # Consider the files in directory, $1.
120 # For each file name of the form PROG.exe, create a shim function named
121 # PROG that simply invokes PROG.exe, then return 0.  If any selected
122 # file name or the directory name, $1, contains an unexpected character,
123 # define no function and return 1.
124 create_exe_shim_functions_()
125 {
126   case $EXEEXT in
127     '') return 0 ;;
128     .exe) ;;
129     *) echo "$0: unexpected \$EXEEXT value: $EXEEXT" 1>&2; return 1 ;;
130   esac
131
132   base_names_=`find_exe_basenames_ $1` \
133     || { echo "$0 (exe_shim): skipping directory: $1" 1>&2; return 1; }
134
135   if test -n "$base_names_"; then
136     for base_ in $base_names_; do
137       # Create a function named $base whose sole job is to invoke
138       # $base_$EXEEXT, assuming its containing dir is already in PATH.
139       eval "$base_() { $base_$EXEEXT"' "$@"; }'
140     done
141   fi
142
143   return 0
144 }
145
146 # Use this function to prepend to PATH an absolute name for each
147 # specified, possibly-$initial_cwd_-relative, directory.
148 path_prepend_()
149 {
150   while test $# != 0; do
151     path_dir_=$1
152     case $path_dir_ in
153       '') fail_ "invalid path dir: '$1'";;
154       /*) abs_path_dir_=$path_dir_;;
155       *) abs_path_dir_=`cd "$initial_cwd_/$path_dir_" && echo "$PWD"` \
156            || fail_ "invalid path dir: $path_dir_";;
157     esac
158     case $abs_path_dir_ in
159       *:*) fail_ "invalid path dir: '$abs_path_dir_'";;
160     esac
161     PATH="$abs_path_dir_:$PATH"
162
163     # Create a function FOO for each FOO.exe in this directory.
164     create_exe_shim_functions_ "$abs_path_dir_"
165     shift
166   done
167   export PATH
168 }
169
170 setup_()
171 {
172   test "$VERBOSE" = yes && set -x
173
174   initial_cwd_=$PWD
175   ME_=`expr "./$0" : '.*/\(.*\)$'`
176
177   pfx_=`testdir_prefix_`
178   test_dir_=`mktempd_ "$initial_cwd_" "$pfx_-$ME_.XXXX"` \
179     || fail_ "failed to create temporary directory in $initial_cwd_"
180   cd "$test_dir_"
181
182   # This pair of trap statements ensures that the temporary directory,
183   # $test_dir_, is removed upon exit as well as upon catchable signal.
184   trap remove_tmp_ 0
185   trap 'Exit $?' 1 2 13 15
186 }
187
188 # Create a temporary directory, much like mktemp -d does.
189 # Written by Jim Meyering.
190 #
191 # Usage: mktempd_ /tmp phoey.XXXXXXXXXX
192 #
193 # First, try to use the mktemp program.
194 # Failing that, we'll roll our own mktemp-like function:
195 #  - try to get random bytes from /dev/urandom
196 #  - failing that, generate output from a combination of quickly-varying
197 #      sources and gzip.  Ignore non-varying gzip header, and extract
198 #      "random" bits from there.
199 #  - given those bits, map to file-name bytes using tr, and try to create
200 #      the desired directory.
201 #  - make only $MAX_TRIES_ attempts
202
203 # Helper function.  Print $N pseudo-random bytes from a-zA-Z0-9.
204 rand_bytes_()
205 {
206   n_=$1
207
208   # Maybe try openssl rand -base64 $n_prime_|tr '+/=\012' abcd first?
209   # But if they have openssl, they probably have mktemp, too.
210
211   chars_=abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
212   dev_rand_=/dev/urandom
213   if test -r "$dev_rand_"; then
214     # Note: 256-length($chars_) == 194; 3 copies of $chars_ is 186 + 8 = 194.
215     dd ibs=$n_ count=1 if=$dev_rand_ 2>/dev/null \
216       | tr -c $chars_ 01234567$chars_$chars_$chars_
217     return
218   fi
219
220   n_plus_50_=`expr $n_ + 50`
221   cmds_='date; date +%N; free; who -a; w; ps auxww; ps ef; netstat -n'
222   data_=` (eval "$cmds_") 2>&1 | gzip `
223
224   # Ensure that $data_ has length at least 50+$n_
225   while :; do
226     len_=`echo "$data_"|wc -c`
227     test $n_plus_50_ -le $len_ && break;
228     data_=` (echo "$data_"; eval "$cmds_") 2>&1 | gzip `
229   done
230
231   echo "$data_" \
232     | dd bs=1 skip=50 count=$n_ 2>/dev/null \
233     | tr -c $chars_ 01234567$chars_$chars_$chars_
234 }
235
236 mktempd_()
237 {
238   case $# in
239   2);;
240   *) fail_ "Usage: $ME DIR TEMPLATE";;
241   esac
242
243   destdir_=$1
244   template_=$2
245
246   MAX_TRIES_=4
247
248   # Disallow any trailing slash on specified destdir:
249   # it would subvert the post-mktemp "case"-based destdir test.
250   case $destdir_ in
251   /) ;;
252   */) fail_ "invalid destination dir: remove trailing slash(es)";;
253   esac
254
255   case $template_ in
256   *XXXX) ;;
257   *) fail_ "invalid template: $template_ (must have a suffix of at least 4 X's)";;
258   esac
259
260   fail=0
261
262   # First, try to use mktemp.
263   d=`env -u TMPDIR mktemp -d -t -p "$destdir_" "$template_" 2>/dev/null` \
264     || fail=1
265
266   # The resulting name must be in the specified directory.
267   case $d in "$destdir_"*);; *) fail=1;; esac
268
269   # It must have created the directory.
270   test -d "$d" || fail=1
271
272   # It must have 0700 permissions.  Handle sticky "S" bits.
273   perms=`ls -dgo "$d" 2>/dev/null|tr S -` || fail=1
274   case $perms in drwx------*) ;; *) fail=1;; esac
275
276   test $fail = 0 && {
277     echo "$d"
278     return
279   }
280
281   # If we reach this point, we'll have to create a directory manually.
282
283   # Get a copy of the template without its suffix of X's.
284   base_template_=`echo "$template_"|sed 's/XX*$//'`
285
286   # Calculate how many X's we've just removed.
287   template_length_=`echo "$template_" | wc -c`
288   nx_=`echo "$base_template_" | wc -c`
289   nx_=`expr $template_length_ - $nx_`
290
291   err_=
292   i_=1
293   while :; do
294     X_=`rand_bytes_ $nx_`
295     candidate_dir_="$destdir_/$base_template_$X_"
296     err_=`mkdir -m 0700 "$candidate_dir_" 2>&1` \
297       && { echo "$candidate_dir_"; return; }
298     test $MAX_TRIES_ -le $i_ && break;
299     i_=`expr $i_ + 1`
300   done
301   fail_ "$err_"
302 }
303
304 # If you want to override the testdir_prefix_ function,
305 # or to add more utility functions, use this file.
306 test -f "$srcdir/init.cfg" \
307   && . "$srcdir/init.cfg"
308
309 setup_ "$@"