Merge branch 'ab/test-lib'
[git] / t / test-lib-functions.sh
1 # Library of functions shared by all tests scripts, included by
2 # test-lib.sh.
3 #
4 # Copyright (c) 2005 Junio C Hamano
5 #
6 # This program is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 2 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program.  If not, see http://www.gnu.org/licenses/ .
18
19 # The semantics of the editor variables are that of invoking
20 # sh -c "$EDITOR \"$@\"" files ...
21 #
22 # If our trash directory contains shell metacharacters, they will be
23 # interpreted if we just set $EDITOR directly, so do a little dance with
24 # environment variables to work around this.
25 #
26 # In particular, quoting isn't enough, as the path may contain the same quote
27 # that we're using.
28 test_set_editor () {
29         FAKE_EDITOR="$1"
30         export FAKE_EDITOR
31         EDITOR='"$FAKE_EDITOR"'
32         export EDITOR
33 }
34
35 test_decode_color () {
36         awk '
37                 function name(n) {
38                         if (n == 0) return "RESET";
39                         if (n == 1) return "BOLD";
40                         if (n == 2) return "FAINT";
41                         if (n == 3) return "ITALIC";
42                         if (n == 7) return "REVERSE";
43                         if (n == 30) return "BLACK";
44                         if (n == 31) return "RED";
45                         if (n == 32) return "GREEN";
46                         if (n == 33) return "YELLOW";
47                         if (n == 34) return "BLUE";
48                         if (n == 35) return "MAGENTA";
49                         if (n == 36) return "CYAN";
50                         if (n == 37) return "WHITE";
51                         if (n == 40) return "BLACK";
52                         if (n == 41) return "BRED";
53                         if (n == 42) return "BGREEN";
54                         if (n == 43) return "BYELLOW";
55                         if (n == 44) return "BBLUE";
56                         if (n == 45) return "BMAGENTA";
57                         if (n == 46) return "BCYAN";
58                         if (n == 47) return "BWHITE";
59                 }
60                 {
61                         while (match($0, /\033\[[0-9;]*m/) != 0) {
62                                 printf "%s<", substr($0, 1, RSTART-1);
63                                 codes = substr($0, RSTART+2, RLENGTH-3);
64                                 if (length(codes) == 0)
65                                         printf "%s", name(0)
66                                 else {
67                                         n = split(codes, ary, ";");
68                                         sep = "";
69                                         for (i = 1; i <= n; i++) {
70                                                 printf "%s%s", sep, name(ary[i]);
71                                                 sep = ";"
72                                         }
73                                 }
74                                 printf ">";
75                                 $0 = substr($0, RSTART + RLENGTH, length($0) - RSTART - RLENGTH + 1);
76                         }
77                         print
78                 }
79         '
80 }
81
82 lf_to_nul () {
83         perl -pe 'y/\012/\000/'
84 }
85
86 nul_to_q () {
87         perl -pe 'y/\000/Q/'
88 }
89
90 q_to_nul () {
91         perl -pe 'y/Q/\000/'
92 }
93
94 q_to_cr () {
95         tr Q '\015'
96 }
97
98 q_to_tab () {
99         tr Q '\011'
100 }
101
102 qz_to_tab_space () {
103         tr QZ '\011\040'
104 }
105
106 append_cr () {
107         sed -e 's/$/Q/' | tr Q '\015'
108 }
109
110 remove_cr () {
111         tr '\015' Q | sed -e 's/Q$//'
112 }
113
114 # In some bourne shell implementations, the "unset" builtin returns
115 # nonzero status when a variable to be unset was not set in the first
116 # place.
117 #
118 # Use sane_unset when that should not be considered an error.
119
120 sane_unset () {
121         unset "$@"
122         return 0
123 }
124
125 test_tick () {
126         if test -z "${test_tick+set}"
127         then
128                 test_tick=1112911993
129         else
130                 test_tick=$(($test_tick + 60))
131         fi
132         GIT_COMMITTER_DATE="$test_tick -0700"
133         GIT_AUTHOR_DATE="$test_tick -0700"
134         export GIT_COMMITTER_DATE GIT_AUTHOR_DATE
135 }
136
137 # Stop execution and start a shell. This is useful for debugging tests.
138 #
139 # Be sure to remove all invocations of this command before submitting.
140
141 test_pause () {
142         "$SHELL_PATH" <&6 >&5 2>&7
143 }
144
145 # Wrap git with a debugger. Adding this to a command can make it easier
146 # to understand what is going on in a failing test.
147 #
148 # Examples:
149 #     debug git checkout master
150 #     debug --debugger=nemiver git $ARGS
151 #     debug -d "valgrind --tool=memcheck --track-origins=yes" git $ARGS
152 debug () {
153         case "$1" in
154         -d)
155                 GIT_DEBUGGER="$2" &&
156                 shift 2
157                 ;;
158         --debugger=*)
159                 GIT_DEBUGGER="${1#*=}" &&
160                 shift 1
161                 ;;
162         *)
163                 GIT_DEBUGGER=1
164                 ;;
165         esac &&
166         GIT_DEBUGGER="${GIT_DEBUGGER}" "$@" <&6 >&5 2>&7
167 }
168
169 # Usage: test_commit [options] <message> [<file> [<contents> [<tag>]]]
170 #   -C <dir>:
171 #       Run all git commands in directory <dir>
172 #   --notick
173 #       Do not call test_tick before making a commit
174 #   --append
175 #       Use "echo >>" instead of "echo >" when writing "<contents>" to
176 #       "<file>"
177 #   --signoff
178 #       Invoke "git commit" with --signoff
179 #   --author <author>
180 #       Invoke "git commit" with --author <author>
181 #
182 # This will commit a file with the given contents and the given commit
183 # message, and tag the resulting commit with the given tag name.
184 #
185 # <file>, <contents>, and <tag> all default to <message>.
186
187 test_commit () {
188         notick= &&
189         append= &&
190         author= &&
191         signoff= &&
192         indir= &&
193         while test $# != 0
194         do
195                 case "$1" in
196                 --notick)
197                         notick=yes
198                         ;;
199                 --append)
200                         append=yes
201                         ;;
202                 --author)
203                         author="$2"
204                         shift
205                         ;;
206                 --signoff)
207                         signoff="$1"
208                         ;;
209                 --date)
210                         notick=yes
211                         GIT_COMMITTER_DATE="$2"
212                         GIT_AUTHOR_DATE="$2"
213                         shift
214                         ;;
215                 -C)
216                         indir="$2"
217                         shift
218                         ;;
219                 *)
220                         break
221                         ;;
222                 esac
223                 shift
224         done &&
225         indir=${indir:+"$indir"/} &&
226         file=${2:-"$1.t"} &&
227         if test -n "$append"
228         then
229                 echo "${3-$1}" >>"$indir$file"
230         else
231                 echo "${3-$1}" >"$indir$file"
232         fi &&
233         git ${indir:+ -C "$indir"} add "$file" &&
234         if test -z "$notick"
235         then
236                 test_tick
237         fi &&
238         git ${indir:+ -C "$indir"} commit \
239             ${author:+ --author "$author"} \
240             $signoff -m "$1" &&
241         git ${indir:+ -C "$indir"} tag "${4:-$1}"
242 }
243
244 # Call test_merge with the arguments "<message> <commit>", where <commit>
245 # can be a tag pointing to the commit-to-merge.
246
247 test_merge () {
248         label="$1" &&
249         shift &&
250         test_tick &&
251         git merge -m "$label" "$@" &&
252         git tag "$label"
253 }
254
255 # Efficiently create <nr> commits, each with a unique number (from 1 to <nr>
256 # by default) in the commit message.
257 #
258 # Usage: test_commit_bulk [options] <nr>
259 #   -C <dir>:
260 #       Run all git commands in directory <dir>
261 #   --ref=<n>:
262 #       ref on which to create commits (default: HEAD)
263 #   --start=<n>:
264 #       number commit messages from <n> (default: 1)
265 #   --message=<msg>:
266 #       use <msg> as the commit mesasge (default: "commit %s")
267 #   --filename=<fn>:
268 #       modify <fn> in each commit (default: %s.t)
269 #   --contents=<string>:
270 #       place <string> in each file (default: "content %s")
271 #   --id=<string>:
272 #       shorthand to use <string> and %s in message, filename, and contents
273 #
274 # The message, filename, and contents strings are evaluated by printf, with the
275 # first "%s" replaced by the current commit number. So you can do:
276 #
277 #   test_commit_bulk --filename=file --contents="modification %s"
278 #
279 # to have every commit touch the same file, but with unique content.
280 #
281 test_commit_bulk () {
282         tmpfile=.bulk-commit.input
283         indir=.
284         ref=HEAD
285         n=1
286         message='commit %s'
287         filename='%s.t'
288         contents='content %s'
289         while test $# -gt 0
290         do
291                 case "$1" in
292                 -C)
293                         indir=$2
294                         shift
295                         ;;
296                 --ref=*)
297                         ref=${1#--*=}
298                         ;;
299                 --start=*)
300                         n=${1#--*=}
301                         ;;
302                 --message=*)
303                         message=${1#--*=}
304                         ;;
305                 --filename=*)
306                         filename=${1#--*=}
307                         ;;
308                 --contents=*)
309                         contents=${1#--*=}
310                         ;;
311                 --id=*)
312                         message="${1#--*=} %s"
313                         filename="${1#--*=}-%s.t"
314                         contents="${1#--*=} %s"
315                         ;;
316                 -*)
317                         BUG "invalid test_commit_bulk option: $1"
318                         ;;
319                 *)
320                         break
321                         ;;
322                 esac
323                 shift
324         done
325         total=$1
326
327         add_from=
328         if git -C "$indir" rev-parse --quiet --verify "$ref"
329         then
330                 add_from=t
331         fi
332
333         while test "$total" -gt 0
334         do
335                 test_tick &&
336                 echo "commit $ref"
337                 printf 'author %s <%s> %s\n' \
338                         "$GIT_AUTHOR_NAME" \
339                         "$GIT_AUTHOR_EMAIL" \
340                         "$GIT_AUTHOR_DATE"
341                 printf 'committer %s <%s> %s\n' \
342                         "$GIT_COMMITTER_NAME" \
343                         "$GIT_COMMITTER_EMAIL" \
344                         "$GIT_COMMITTER_DATE"
345                 echo "data <<EOF"
346                 printf "$message\n" $n
347                 echo "EOF"
348                 if test -n "$add_from"
349                 then
350                         echo "from $ref^0"
351                         add_from=
352                 fi
353                 printf "M 644 inline $filename\n" $n
354                 echo "data <<EOF"
355                 printf "$contents\n" $n
356                 echo "EOF"
357                 echo
358                 n=$((n + 1))
359                 total=$((total - 1))
360         done >"$tmpfile"
361
362         git -C "$indir" \
363             -c fastimport.unpacklimit=0 \
364             fast-import <"$tmpfile" || return 1
365
366         # This will be left in place on failure, which may aid debugging.
367         rm -f "$tmpfile"
368
369         # If we updated HEAD, then be nice and update the index and working
370         # tree, too.
371         if test "$ref" = "HEAD"
372         then
373                 git -C "$indir" checkout -f HEAD || return 1
374         fi
375
376 }
377
378 # This function helps systems where core.filemode=false is set.
379 # Use it instead of plain 'chmod +x' to set or unset the executable bit
380 # of a file in the working directory and add it to the index.
381
382 test_chmod () {
383         chmod "$@" &&
384         git update-index --add "--chmod=$@"
385 }
386
387 # Get the modebits from a file or directory, ignoring the setgid bit (g+s).
388 # This bit is inherited by subdirectories at their creation. So we remove it
389 # from the returning string to prevent callers from having to worry about the
390 # state of the bit in the test directory.
391 #
392 test_modebits () {
393         ls -ld "$1" | sed -e 's|^\(..........\).*|\1|' \
394                           -e 's|^\(......\)S|\1-|' -e 's|^\(......\)s|\1x|'
395 }
396
397 # Unset a configuration variable, but don't fail if it doesn't exist.
398 test_unconfig () {
399         config_dir=
400         if test "$1" = -C
401         then
402                 shift
403                 config_dir=$1
404                 shift
405         fi
406         git ${config_dir:+-C "$config_dir"} config --unset-all "$@"
407         config_status=$?
408         case "$config_status" in
409         5) # ok, nothing to unset
410                 config_status=0
411                 ;;
412         esac
413         return $config_status
414 }
415
416 # Set git config, automatically unsetting it after the test is over.
417 test_config () {
418         config_dir=
419         if test "$1" = -C
420         then
421                 shift
422                 config_dir=$1
423                 shift
424         fi
425         test_when_finished "test_unconfig ${config_dir:+-C '$config_dir'} '$1'" &&
426         git ${config_dir:+-C "$config_dir"} config "$@"
427 }
428
429 test_config_global () {
430         test_when_finished "test_unconfig --global '$1'" &&
431         git config --global "$@"
432 }
433
434 write_script () {
435         {
436                 echo "#!${2-"$SHELL_PATH"}" &&
437                 cat
438         } >"$1" &&
439         chmod +x "$1"
440 }
441
442 # Use test_set_prereq to tell that a particular prerequisite is available.
443 # The prerequisite can later be checked for in two ways:
444 #
445 # - Explicitly using test_have_prereq.
446 #
447 # - Implicitly by specifying the prerequisite tag in the calls to
448 #   test_expect_{success,failure} and test_external{,_without_stderr}.
449 #
450 # The single parameter is the prerequisite tag (a simple word, in all
451 # capital letters by convention).
452
453 test_unset_prereq () {
454         ! test_have_prereq "$1" ||
455         satisfied_prereq="${satisfied_prereq% $1 *} ${satisfied_prereq#* $1 }"
456 }
457
458 test_set_prereq () {
459         if test -n "$GIT_TEST_FAIL_PREREQS_INTERNAL"
460         then
461                 case "$1" in
462                 # The "!" case is handled below with
463                 # test_unset_prereq()
464                 !*)
465                         ;;
466                 # (Temporary?) whitelist of things we can't easily
467                 # pretend not to support
468                 SYMLINKS)
469                         ;;
470                 # Inspecting whether GIT_TEST_FAIL_PREREQS is on
471                 # should be unaffected.
472                 FAIL_PREREQS)
473                         ;;
474                 *)
475                         return
476                 esac
477         fi
478
479         case "$1" in
480         !*)
481                 test_unset_prereq "${1#!}"
482                 ;;
483         *)
484                 satisfied_prereq="$satisfied_prereq$1 "
485                 ;;
486         esac
487 }
488 satisfied_prereq=" "
489 lazily_testable_prereq= lazily_tested_prereq=
490
491 # Usage: test_lazy_prereq PREREQ 'script'
492 test_lazy_prereq () {
493         lazily_testable_prereq="$lazily_testable_prereq$1 "
494         eval test_prereq_lazily_$1=\$2
495 }
496
497 test_run_lazy_prereq_ () {
498         script='
499 mkdir -p "$TRASH_DIRECTORY/prereq-test-dir-'"$1"'" &&
500 (
501         cd "$TRASH_DIRECTORY/prereq-test-dir-'"$1"'" &&'"$2"'
502 )'
503         say >&3 "checking prerequisite: $1"
504         say >&3 "$script"
505         test_eval_ "$script"
506         eval_ret=$?
507         rm -rf "$TRASH_DIRECTORY/prereq-test-dir-$1"
508         if test "$eval_ret" = 0; then
509                 say >&3 "prerequisite $1 ok"
510         else
511                 say >&3 "prerequisite $1 not satisfied"
512         fi
513         return $eval_ret
514 }
515
516 test_have_prereq () {
517         # prerequisites can be concatenated with ','
518         save_IFS=$IFS
519         IFS=,
520         set -- $*
521         IFS=$save_IFS
522
523         total_prereq=0
524         ok_prereq=0
525         missing_prereq=
526
527         for prerequisite
528         do
529                 case "$prerequisite" in
530                 !*)
531                         negative_prereq=t
532                         prerequisite=${prerequisite#!}
533                         ;;
534                 *)
535                         negative_prereq=
536                 esac
537
538                 case " $lazily_tested_prereq " in
539                 *" $prerequisite "*)
540                         ;;
541                 *)
542                         case " $lazily_testable_prereq " in
543                         *" $prerequisite "*)
544                                 eval "script=\$test_prereq_lazily_$prerequisite" &&
545                                 if test_run_lazy_prereq_ "$prerequisite" "$script"
546                                 then
547                                         test_set_prereq $prerequisite
548                                 fi
549                                 lazily_tested_prereq="$lazily_tested_prereq$prerequisite "
550                         esac
551                         ;;
552                 esac
553
554                 total_prereq=$(($total_prereq + 1))
555                 case "$satisfied_prereq" in
556                 *" $prerequisite "*)
557                         satisfied_this_prereq=t
558                         ;;
559                 *)
560                         satisfied_this_prereq=
561                 esac
562
563                 case "$satisfied_this_prereq,$negative_prereq" in
564                 t,|,t)
565                         ok_prereq=$(($ok_prereq + 1))
566                         ;;
567                 *)
568                         # Keep a list of missing prerequisites; restore
569                         # the negative marker if necessary.
570                         prerequisite=${negative_prereq:+!}$prerequisite
571                         if test -z "$missing_prereq"
572                         then
573                                 missing_prereq=$prerequisite
574                         else
575                                 missing_prereq="$prerequisite,$missing_prereq"
576                         fi
577                 esac
578         done
579
580         test $total_prereq = $ok_prereq
581 }
582
583 test_declared_prereq () {
584         case ",$test_prereq," in
585         *,$1,*)
586                 return 0
587                 ;;
588         esac
589         return 1
590 }
591
592 test_verify_prereq () {
593         test -z "$test_prereq" ||
594         expr >/dev/null "$test_prereq" : '[A-Z0-9_,!]*$' ||
595         BUG "'$test_prereq' does not look like a prereq"
596 }
597
598 test_expect_failure () {
599         test_start_
600         test "$#" = 3 && { test_prereq=$1; shift; } || test_prereq=
601         test "$#" = 2 ||
602         BUG "not 2 or 3 parameters to test-expect-failure"
603         test_verify_prereq
604         export test_prereq
605         if ! test_skip "$@"
606         then
607                 say >&3 "checking known breakage of $TEST_NUMBER.$test_count '$1': $2"
608                 if test_run_ "$2" expecting_failure
609                 then
610                         test_known_broken_ok_ "$1"
611                 else
612                         test_known_broken_failure_ "$1"
613                 fi
614         fi
615         test_finish_
616 }
617
618 test_expect_success () {
619         test_start_
620         test "$#" = 3 && { test_prereq=$1; shift; } || test_prereq=
621         test "$#" = 2 ||
622         BUG "not 2 or 3 parameters to test-expect-success"
623         test_verify_prereq
624         export test_prereq
625         if ! test_skip "$@"
626         then
627                 say >&3 "expecting success of $TEST_NUMBER.$test_count '$1': $2"
628                 if test_run_ "$2"
629                 then
630                         test_ok_ "$1"
631                 else
632                         test_failure_ "$@"
633                 fi
634         fi
635         test_finish_
636 }
637
638 # test_external runs external test scripts that provide continuous
639 # test output about their progress, and succeeds/fails on
640 # zero/non-zero exit code.  It outputs the test output on stdout even
641 # in non-verbose mode, and announces the external script with "# run
642 # <n>: ..." before running it.  When providing relative paths, keep in
643 # mind that all scripts run in "trash directory".
644 # Usage: test_external description command arguments...
645 # Example: test_external 'Perl API' perl ../path/to/test.pl
646 test_external () {
647         test "$#" = 4 && { test_prereq=$1; shift; } || test_prereq=
648         test "$#" = 3 ||
649         BUG "not 3 or 4 parameters to test_external"
650         descr="$1"
651         shift
652         test_verify_prereq
653         export test_prereq
654         if ! test_skip "$descr" "$@"
655         then
656                 # Announce the script to reduce confusion about the
657                 # test output that follows.
658                 say_color "" "# run $test_count: $descr ($*)"
659                 # Export TEST_DIRECTORY, TRASH_DIRECTORY and GIT_TEST_LONG
660                 # to be able to use them in script
661                 export TEST_DIRECTORY TRASH_DIRECTORY GIT_TEST_LONG
662                 # Run command; redirect its stderr to &4 as in
663                 # test_run_, but keep its stdout on our stdout even in
664                 # non-verbose mode.
665                 "$@" 2>&4
666                 if test "$?" = 0
667                 then
668                         if test $test_external_has_tap -eq 0; then
669                                 test_ok_ "$descr"
670                         else
671                                 say_color "" "# test_external test $descr was ok"
672                                 test_success=$(($test_success + 1))
673                         fi
674                 else
675                         if test $test_external_has_tap -eq 0; then
676                                 test_failure_ "$descr" "$@"
677                         else
678                                 say_color error "# test_external test $descr failed: $@"
679                                 test_failure=$(($test_failure + 1))
680                         fi
681                 fi
682         fi
683 }
684
685 # Like test_external, but in addition tests that the command generated
686 # no output on stderr.
687 test_external_without_stderr () {
688         # The temporary file has no (and must have no) security
689         # implications.
690         tmp=${TMPDIR:-/tmp}
691         stderr="$tmp/git-external-stderr.$$.tmp"
692         test_external "$@" 4> "$stderr"
693         test -f "$stderr" || error "Internal error: $stderr disappeared."
694         descr="no stderr: $1"
695         shift
696         say >&3 "# expecting no stderr from previous command"
697         if test ! -s "$stderr"
698         then
699                 rm "$stderr"
700
701                 if test $test_external_has_tap -eq 0; then
702                         test_ok_ "$descr"
703                 else
704                         say_color "" "# test_external_without_stderr test $descr was ok"
705                         test_success=$(($test_success + 1))
706                 fi
707         else
708                 if test "$verbose" = t
709                 then
710                         output=$(echo; echo "# Stderr is:"; cat "$stderr")
711                 else
712                         output=
713                 fi
714                 # rm first in case test_failure exits.
715                 rm "$stderr"
716                 if test $test_external_has_tap -eq 0; then
717                         test_failure_ "$descr" "$@" "$output"
718                 else
719                         say_color error "# test_external_without_stderr test $descr failed: $@: $output"
720                         test_failure=$(($test_failure + 1))
721                 fi
722         fi
723 }
724
725 # debugging-friendly alternatives to "test [-f|-d|-e]"
726 # The commands test the existence or non-existence of $1
727 test_path_is_file () {
728         test "$#" -ne 1 && BUG "1 param"
729         if ! test -f "$1"
730         then
731                 echo "File $1 doesn't exist"
732                 false
733         fi
734 }
735
736 test_path_is_dir () {
737         test "$#" -ne 1 && BUG "1 param"
738         if ! test -d "$1"
739         then
740                 echo "Directory $1 doesn't exist"
741                 false
742         fi
743 }
744
745 test_path_exists () {
746         test "$#" -ne 1 && BUG "1 param"
747         if ! test -e "$1"
748         then
749                 echo "Path $1 doesn't exist"
750                 false
751         fi
752 }
753
754 # Check if the directory exists and is empty as expected, barf otherwise.
755 test_dir_is_empty () {
756         test "$#" -ne 1 && BUG "1 param"
757         test_path_is_dir "$1" &&
758         if test -n "$(ls -a1 "$1" | egrep -v '^\.\.?$')"
759         then
760                 echo "Directory '$1' is not empty, it contains:"
761                 ls -la "$1"
762                 return 1
763         fi
764 }
765
766 # Check if the file exists and has a size greater than zero
767 test_file_not_empty () {
768         test "$#" = 2 && BUG "2 param"
769         if ! test -s "$1"
770         then
771                 echo "'$1' is not a non-empty file."
772                 false
773         fi
774 }
775
776 test_path_is_missing () {
777         test "$#" -ne 1 && BUG "1 param"
778         if test -e "$1"
779         then
780                 echo "Path exists:"
781                 ls -ld "$1"
782                 if test $# -ge 1
783                 then
784                         echo "$*"
785                 fi
786                 false
787         fi
788 }
789
790 # test_line_count checks that a file has the number of lines it
791 # ought to. For example:
792 #
793 #       test_expect_success 'produce exactly one line of output' '
794 #               do something >output &&
795 #               test_line_count = 1 output
796 #       '
797 #
798 # is like "test $(wc -l <output) = 1" except that it passes the
799 # output through when the number of lines is wrong.
800
801 test_line_count () {
802         if test $# != 3
803         then
804                 BUG "not 3 parameters to test_line_count"
805         elif ! test $(wc -l <"$3") "$1" "$2"
806         then
807                 echo "test_line_count: line count for $3 !$1 $2"
808                 cat "$3"
809                 return 1
810         fi
811 }
812
813 test_file_size () {
814         test "$#" -ne 1 && BUG "1 param"
815         test-tool path-utils file-size "$1"
816 }
817
818 # Returns success if a comma separated string of keywords ($1) contains a
819 # given keyword ($2).
820 # Examples:
821 # `list_contains "foo,bar" bar` returns 0
822 # `list_contains "foo" bar` returns 1
823
824 list_contains () {
825         case ",$1," in
826         *,$2,*)
827                 return 0
828                 ;;
829         esac
830         return 1
831 }
832
833 # Returns success if the arguments indicate that a command should be
834 # accepted by test_must_fail(). If the command is run with env, the env
835 # and its corresponding variable settings will be stripped before we
836 # test the command being run.
837 test_must_fail_acceptable () {
838         if test "$1" = "env"
839         then
840                 shift
841                 while test $# -gt 0
842                 do
843                         case "$1" in
844                         *?=*)
845                                 shift
846                                 ;;
847                         *)
848                                 break
849                                 ;;
850                         esac
851                 done
852         fi
853
854         case "$1" in
855         git|__git*|test-tool|test_terminal)
856                 return 0
857                 ;;
858         *)
859                 return 1
860                 ;;
861         esac
862 }
863
864 # This is not among top-level (test_expect_success | test_expect_failure)
865 # but is a prefix that can be used in the test script, like:
866 #
867 #       test_expect_success 'complain and die' '
868 #           do something &&
869 #           do something else &&
870 #           test_must_fail git checkout ../outerspace
871 #       '
872 #
873 # Writing this as "! git checkout ../outerspace" is wrong, because
874 # the failure could be due to a segv.  We want a controlled failure.
875 #
876 # Accepts the following options:
877 #
878 #   ok=<signal-name>[,<...>]:
879 #     Don't treat an exit caused by the given signal as error.
880 #     Multiple signals can be specified as a comma separated list.
881 #     Currently recognized signal names are: sigpipe, success.
882 #     (Don't use 'success', use 'test_might_fail' instead.)
883 #
884 # Do not use this to run anything but "git" and other specific testable
885 # commands (see test_must_fail_acceptable()).  We are not in the
886 # business of vetting system supplied commands -- in other words, this
887 # is wrong:
888 #
889 #    test_must_fail grep pattern output
890 #
891 # Instead use '!':
892 #
893 #    ! grep pattern output
894
895 test_must_fail () {
896         case "$1" in
897         ok=*)
898                 _test_ok=${1#ok=}
899                 shift
900                 ;;
901         *)
902                 _test_ok=
903                 ;;
904         esac
905         if ! test_must_fail_acceptable "$@"
906         then
907                 echo >&7 "test_must_fail: only 'git' is allowed: $*"
908                 return 1
909         fi
910         "$@" 2>&7
911         exit_code=$?
912         if test $exit_code -eq 0 && ! list_contains "$_test_ok" success
913         then
914                 echo >&4 "test_must_fail: command succeeded: $*"
915                 return 1
916         elif test_match_signal 13 $exit_code && list_contains "$_test_ok" sigpipe
917         then
918                 return 0
919         elif test $exit_code -gt 129 && test $exit_code -le 192
920         then
921                 echo >&4 "test_must_fail: died by signal $(($exit_code - 128)): $*"
922                 return 1
923         elif test $exit_code -eq 127
924         then
925                 echo >&4 "test_must_fail: command not found: $*"
926                 return 1
927         elif test $exit_code -eq 126
928         then
929                 echo >&4 "test_must_fail: valgrind error: $*"
930                 return 1
931         fi
932         return 0
933 } 7>&2 2>&4
934
935 # Similar to test_must_fail, but tolerates success, too.  This is
936 # meant to be used in contexts like:
937 #
938 #       test_expect_success 'some command works without configuration' '
939 #               test_might_fail git config --unset all.configuration &&
940 #               do something
941 #       '
942 #
943 # Writing "git config --unset all.configuration || :" would be wrong,
944 # because we want to notice if it fails due to segv.
945 #
946 # Accepts the same options as test_must_fail.
947
948 test_might_fail () {
949         test_must_fail ok=success "$@" 2>&7
950 } 7>&2 2>&4
951
952 # Similar to test_must_fail and test_might_fail, but check that a
953 # given command exited with a given exit code. Meant to be used as:
954 #
955 #       test_expect_success 'Merge with d/f conflicts' '
956 #               test_expect_code 1 git merge "merge msg" B master
957 #       '
958
959 test_expect_code () {
960         want_code=$1
961         shift
962         "$@" 2>&7
963         exit_code=$?
964         if test $exit_code = $want_code
965         then
966                 return 0
967         fi
968
969         echo >&4 "test_expect_code: command exited with $exit_code, we wanted $want_code $*"
970         return 1
971 } 7>&2 2>&4
972
973 # test_cmp is a helper function to compare actual and expected output.
974 # You can use it like:
975 #
976 #       test_expect_success 'foo works' '
977 #               echo expected >expected &&
978 #               foo >actual &&
979 #               test_cmp expected actual
980 #       '
981 #
982 # This could be written as either "cmp" or "diff -u", but:
983 # - cmp's output is not nearly as easy to read as diff -u
984 # - not all diff versions understand "-u"
985
986 test_cmp () {
987         test "$#" -ne 2 && BUG "2 param"
988         eval "$GIT_TEST_CMP" '"$@"'
989 }
990
991 # Check that the given config key has the expected value.
992 #
993 #    test_cmp_config [-C <dir>] <expected-value>
994 #                    [<git-config-options>...] <config-key>
995 #
996 # for example to check that the value of core.bar is foo
997 #
998 #    test_cmp_config foo core.bar
999 #
1000 test_cmp_config () {
1001         local GD &&
1002         if test "$1" = "-C"
1003         then
1004                 shift &&
1005                 GD="-C $1" &&
1006                 shift
1007         fi &&
1008         printf "%s\n" "$1" >expect.config &&
1009         shift &&
1010         git $GD config "$@" >actual.config &&
1011         test_cmp expect.config actual.config
1012 }
1013
1014 # test_cmp_bin - helper to compare binary files
1015
1016 test_cmp_bin () {
1017         test "$#" -ne 2 && BUG "2 param"
1018         cmp "$@"
1019 }
1020
1021 # Wrapper for test_cmp which used to be used for
1022 # GIT_TEST_GETTEXT_POISON=false. Only here as a shim for other
1023 # in-flight changes. Should not be used and will be removed soon.
1024 test_i18ncmp () {
1025         test_cmp "$@"
1026 }
1027
1028 # Wrapper for grep which used to be used for
1029 # GIT_TEST_GETTEXT_POISON=false. Only here as a shim for other
1030 # in-flight changes. Should not be used and will be removed soon.
1031 test_i18ngrep () {
1032         eval "last_arg=\${$#}"
1033
1034         test -f "$last_arg" ||
1035         BUG "test_i18ngrep requires a file to read as the last parameter"
1036
1037         if test $# -lt 2 ||
1038            { test "x!" = "x$1" && test $# -lt 3 ; }
1039         then
1040                 BUG "too few parameters to test_i18ngrep"
1041         fi
1042
1043         if test "x!" = "x$1"
1044         then
1045                 shift
1046                 ! grep "$@" && return 0
1047
1048                 echo >&4 "error: '! grep $@' did find a match in:"
1049         else
1050                 grep "$@" && return 0
1051
1052                 echo >&4 "error: 'grep $@' didn't find a match in:"
1053         fi
1054
1055         if test -s "$last_arg"
1056         then
1057                 cat >&4 "$last_arg"
1058         else
1059                 echo >&4 "<File '$last_arg' is empty>"
1060         fi
1061
1062         return 1
1063 }
1064
1065 # Call any command "$@" but be more verbose about its
1066 # failure. This is handy for commands like "test" which do
1067 # not output anything when they fail.
1068 verbose () {
1069         "$@" && return 0
1070         echo >&4 "command failed: $(git rev-parse --sq-quote "$@")"
1071         return 1
1072 }
1073
1074 # Check if the file expected to be empty is indeed empty, and barfs
1075 # otherwise.
1076
1077 test_must_be_empty () {
1078         test "$#" -ne 1 && BUG "1 param"
1079         test_path_is_file "$1" &&
1080         if test -s "$1"
1081         then
1082                 echo "'$1' is not empty, it contains:"
1083                 cat "$1"
1084                 return 1
1085         fi
1086 }
1087
1088 # Tests that its two parameters refer to the same revision, or if '!' is
1089 # provided first, that its other two parameters refer to different
1090 # revisions.
1091 test_cmp_rev () {
1092         local op='=' wrong_result=different
1093
1094         if test $# -ge 1 && test "x$1" = 'x!'
1095         then
1096             op='!='
1097             wrong_result='the same'
1098             shift
1099         fi
1100         if test $# != 2
1101         then
1102                 BUG "test_cmp_rev requires two revisions, but got $#"
1103         else
1104                 local r1 r2
1105                 r1=$(git rev-parse --verify "$1") &&
1106                 r2=$(git rev-parse --verify "$2") || return 1
1107
1108                 if ! test "$r1" "$op" "$r2"
1109                 then
1110                         cat >&4 <<-EOF
1111                         error: two revisions point to $wrong_result objects:
1112                           '$1': $r1
1113                           '$2': $r2
1114                         EOF
1115                         return 1
1116                 fi
1117         fi
1118 }
1119
1120 # Compare paths respecting core.ignoreCase
1121 test_cmp_fspath () {
1122         if test "x$1" = "x$2"
1123         then
1124                 return 0
1125         fi
1126
1127         if test true != "$(git config --get --type=bool core.ignorecase)"
1128         then
1129                 return 1
1130         fi
1131
1132         test "x$(echo "$1" | tr A-Z a-z)" =  "x$(echo "$2" | tr A-Z a-z)"
1133 }
1134
1135 # Print a sequence of integers in increasing order, either with
1136 # two arguments (start and end):
1137 #
1138 #     test_seq 1 5 -- outputs 1 2 3 4 5 one line at a time
1139 #
1140 # or with one argument (end), in which case it starts counting
1141 # from 1.
1142
1143 test_seq () {
1144         case $# in
1145         1)      set 1 "$@" ;;
1146         2)      ;;
1147         *)      BUG "not 1 or 2 parameters to test_seq" ;;
1148         esac
1149         test_seq_counter__=$1
1150         while test "$test_seq_counter__" -le "$2"
1151         do
1152                 echo "$test_seq_counter__"
1153                 test_seq_counter__=$(( $test_seq_counter__ + 1 ))
1154         done
1155 }
1156
1157 # This function can be used to schedule some commands to be run
1158 # unconditionally at the end of the test to restore sanity:
1159 #
1160 #       test_expect_success 'test core.capslock' '
1161 #               git config core.capslock true &&
1162 #               test_when_finished "git config --unset core.capslock" &&
1163 #               hello world
1164 #       '
1165 #
1166 # That would be roughly equivalent to
1167 #
1168 #       test_expect_success 'test core.capslock' '
1169 #               git config core.capslock true &&
1170 #               hello world
1171 #               git config --unset core.capslock
1172 #       '
1173 #
1174 # except that the greeting and config --unset must both succeed for
1175 # the test to pass.
1176 #
1177 # Note that under --immediate mode, no clean-up is done to help diagnose
1178 # what went wrong.
1179
1180 test_when_finished () {
1181         # We cannot detect when we are in a subshell in general, but by
1182         # doing so on Bash is better than nothing (the test will
1183         # silently pass on other shells).
1184         test "${BASH_SUBSHELL-0}" = 0 ||
1185         BUG "test_when_finished does nothing in a subshell"
1186         test_cleanup="{ $*
1187                 } && (exit \"\$eval_ret\"); eval_ret=\$?; $test_cleanup"
1188 }
1189
1190 # This function can be used to schedule some commands to be run
1191 # unconditionally at the end of the test script, e.g. to stop a daemon:
1192 #
1193 #       test_expect_success 'test git daemon' '
1194 #               git daemon &
1195 #               daemon_pid=$! &&
1196 #               test_atexit 'kill $daemon_pid' &&
1197 #               hello world
1198 #       '
1199 #
1200 # The commands will be executed before the trash directory is removed,
1201 # i.e. the atexit commands will still be able to access any pidfiles or
1202 # socket files.
1203 #
1204 # Note that these commands will be run even when a test script run
1205 # with '--immediate' fails.  Be careful with your atexit commands to
1206 # minimize any changes to the failed state.
1207
1208 test_atexit () {
1209         # We cannot detect when we are in a subshell in general, but by
1210         # doing so on Bash is better than nothing (the test will
1211         # silently pass on other shells).
1212         test "${BASH_SUBSHELL-0}" = 0 ||
1213         BUG "test_atexit does nothing in a subshell"
1214         test_atexit_cleanup="{ $*
1215                 } && (exit \"\$eval_ret\"); eval_ret=\$?; $test_atexit_cleanup"
1216 }
1217
1218 # Most tests can use the created repository, but some may need to create more.
1219 # Usage: test_create_repo <directory>
1220 test_create_repo () {
1221         test "$#" = 1 ||
1222         BUG "not 1 parameter to test-create-repo"
1223         repo="$1"
1224         mkdir -p "$repo"
1225         (
1226                 cd "$repo" || error "Cannot setup test environment"
1227                 "${GIT_TEST_INSTALLED:-$GIT_EXEC_PATH}/git$X" -c \
1228                         init.defaultBranch="${GIT_TEST_DEFAULT_INITIAL_BRANCH_NAME-master}" \
1229                         init \
1230                         "--template=$GIT_BUILD_DIR/templates/blt/" >&3 2>&4 ||
1231                 error "cannot run git init -- have you built things yet?"
1232                 mv .git/hooks .git/hooks-disabled
1233         ) || exit
1234 }
1235
1236 # This function helps on symlink challenged file systems when it is not
1237 # important that the file system entry is a symbolic link.
1238 # Use test_ln_s_add instead of "ln -s x y && git add y" to add a
1239 # symbolic link entry y to the index.
1240
1241 test_ln_s_add () {
1242         if test_have_prereq SYMLINKS
1243         then
1244                 ln -s "$1" "$2" &&
1245                 git update-index --add "$2"
1246         else
1247                 printf '%s' "$1" >"$2" &&
1248                 ln_s_obj=$(git hash-object -w "$2") &&
1249                 git update-index --add --cacheinfo 120000 $ln_s_obj "$2" &&
1250                 # pick up stat info from the file
1251                 git update-index "$2"
1252         fi
1253 }
1254
1255 # This function writes out its parameters, one per line
1256 test_write_lines () {
1257         printf "%s\n" "$@"
1258 }
1259
1260 perl () {
1261         command "$PERL_PATH" "$@" 2>&7
1262 } 7>&2 2>&4
1263
1264 # Given the name of an environment variable with a bool value, normalize
1265 # its value to a 0 (true) or 1 (false or empty string) return code.
1266 #
1267 #   test_bool_env GIT_TEST_HTTPD <default-value>
1268 #
1269 # Return with code corresponding to the given default value if the variable
1270 # is unset.
1271 # Abort the test script if either the value of the variable or the default
1272 # are not valid bool values.
1273
1274 test_bool_env () {
1275         if test $# != 2
1276         then
1277                 BUG "test_bool_env requires two parameters (variable name and default value)"
1278         fi
1279
1280         git env--helper --type=bool --default="$2" --exit-code "$1"
1281         ret=$?
1282         case $ret in
1283         0|1)    # unset or valid bool value
1284                 ;;
1285         *)      # invalid bool value or something unexpected
1286                 error >&7 "test_bool_env requires bool values both for \$$1 and for the default fallback"
1287                 ;;
1288         esac
1289         return $ret
1290 }
1291
1292 # Exit the test suite, either by skipping all remaining tests or by
1293 # exiting with an error. If our prerequisite variable $1 falls back
1294 # on a default assume we were opportunistically trying to set up some
1295 # tests and we skip. If it is explicitly "true", then we report a failure.
1296 #
1297 # The error/skip message should be given by $2.
1298 #
1299 test_skip_or_die () {
1300         if ! test_bool_env "$1" false
1301         then
1302                 skip_all=$2
1303                 test_done
1304         fi
1305         error "$2"
1306 }
1307
1308 # The following mingw_* functions obey POSIX shell syntax, but are actually
1309 # bash scripts, and are meant to be used only with bash on Windows.
1310
1311 # A test_cmp function that treats LF and CRLF equal and avoids to fork
1312 # diff when possible.
1313 mingw_test_cmp () {
1314         # Read text into shell variables and compare them. If the results
1315         # are different, use regular diff to report the difference.
1316         local test_cmp_a= test_cmp_b=
1317
1318         # When text came from stdin (one argument is '-') we must feed it
1319         # to diff.
1320         local stdin_for_diff=
1321
1322         # Since it is difficult to detect the difference between an
1323         # empty input file and a failure to read the files, we go straight
1324         # to diff if one of the inputs is empty.
1325         if test -s "$1" && test -s "$2"
1326         then
1327                 # regular case: both files non-empty
1328                 mingw_read_file_strip_cr_ test_cmp_a <"$1"
1329                 mingw_read_file_strip_cr_ test_cmp_b <"$2"
1330         elif test -s "$1" && test "$2" = -
1331         then
1332                 # read 2nd file from stdin
1333                 mingw_read_file_strip_cr_ test_cmp_a <"$1"
1334                 mingw_read_file_strip_cr_ test_cmp_b
1335                 stdin_for_diff='<<<"$test_cmp_b"'
1336         elif test "$1" = - && test -s "$2"
1337         then
1338                 # read 1st file from stdin
1339                 mingw_read_file_strip_cr_ test_cmp_a
1340                 mingw_read_file_strip_cr_ test_cmp_b <"$2"
1341                 stdin_for_diff='<<<"$test_cmp_a"'
1342         fi
1343         test -n "$test_cmp_a" &&
1344         test -n "$test_cmp_b" &&
1345         test "$test_cmp_a" = "$test_cmp_b" ||
1346         eval "diff -u \"\$@\" $stdin_for_diff"
1347 }
1348
1349 # $1 is the name of the shell variable to fill in
1350 mingw_read_file_strip_cr_ () {
1351         # Read line-wise using LF as the line separator
1352         # and use IFS to strip CR.
1353         local line
1354         while :
1355         do
1356                 if IFS=$'\r' read -r -d $'\n' line
1357                 then
1358                         # good
1359                         line=$line$'\n'
1360                 else
1361                         # we get here at EOF, but also if the last line
1362                         # was not terminated by LF; in the latter case,
1363                         # some text was read
1364                         if test -z "$line"
1365                         then
1366                                 # EOF, really
1367                                 break
1368                         fi
1369                 fi
1370                 eval "$1=\$$1\$line"
1371         done
1372 }
1373
1374 # Like "env FOO=BAR some-program", but run inside a subshell, which means
1375 # it also works for shell functions (though those functions cannot impact
1376 # the environment outside of the test_env invocation).
1377 test_env () {
1378         (
1379                 while test $# -gt 0
1380                 do
1381                         case "$1" in
1382                         *=*)
1383                                 eval "${1%%=*}=\${1#*=}"
1384                                 eval "export ${1%%=*}"
1385                                 shift
1386                                 ;;
1387                         *)
1388                                 "$@" 2>&7
1389                                 exit
1390                                 ;;
1391                         esac
1392                 done
1393         )
1394 } 7>&2 2>&4
1395
1396 # Returns true if the numeric exit code in "$2" represents the expected signal
1397 # in "$1". Signals should be given numerically.
1398 test_match_signal () {
1399         if test "$2" = "$((128 + $1))"
1400         then
1401                 # POSIX
1402                 return 0
1403         elif test "$2" = "$((256 + $1))"
1404         then
1405                 # ksh
1406                 return 0
1407         fi
1408         return 1
1409 }
1410
1411 # Read up to "$1" bytes (or to EOF) from stdin and write them to stdout.
1412 test_copy_bytes () {
1413         perl -e '
1414                 my $len = $ARGV[1];
1415                 while ($len > 0) {
1416                         my $s;
1417                         my $nread = sysread(STDIN, $s, $len);
1418                         die "cannot read: $!" unless defined($nread);
1419                         last unless $nread;
1420                         print $s;
1421                         $len -= $nread;
1422                 }
1423         ' - "$1"
1424 }
1425
1426 # run "$@" inside a non-git directory
1427 nongit () {
1428         test -d non-repo ||
1429         mkdir non-repo ||
1430         return 1
1431
1432         (
1433                 GIT_CEILING_DIRECTORIES=$(pwd) &&
1434                 export GIT_CEILING_DIRECTORIES &&
1435                 cd non-repo &&
1436                 "$@" 2>&7
1437         )
1438 } 7>&2 2>&4
1439
1440 # convert function arguments or stdin (if not arguments given) to pktline
1441 # representation. If multiple arguments are given, they are separated by
1442 # whitespace and put in a single packet. Note that data containing NULs must be
1443 # given on stdin, and that empty input becomes an empty packet, not a flush
1444 # packet (for that you can just print 0000 yourself).
1445 packetize () {
1446         if test $# -gt 0
1447         then
1448                 packet="$*"
1449                 printf '%04x%s' "$((4 + ${#packet}))" "$packet"
1450         else
1451                 perl -e '
1452                         my $packet = do { local $/; <STDIN> };
1453                         printf "%04x%s", 4 + length($packet), $packet;
1454                 '
1455         fi
1456 }
1457
1458 # Parse the input as a series of pktlines, writing the result to stdout.
1459 # Sideband markers are removed automatically, and the output is routed to
1460 # stderr if appropriate.
1461 #
1462 # NUL bytes are converted to "\\0" for ease of parsing with text tools.
1463 depacketize () {
1464         perl -e '
1465                 while (read(STDIN, $len, 4) == 4) {
1466                         if ($len eq "0000") {
1467                                 print "FLUSH\n";
1468                         } else {
1469                                 read(STDIN, $buf, hex($len) - 4);
1470                                 $buf =~ s/\0/\\0/g;
1471                                 if ($buf =~ s/^[\x2\x3]//) {
1472                                         print STDERR $buf;
1473                                 } else {
1474                                         $buf =~ s/^\x1//;
1475                                         print $buf;
1476                                 }
1477                         }
1478                 }
1479         '
1480 }
1481
1482 # Converts base-16 data into base-8. The output is given as a sequence of
1483 # escaped octals, suitable for consumption by 'printf'.
1484 hex2oct () {
1485         perl -ne 'printf "\\%03o", hex for /../g'
1486 }
1487
1488 # Set the hash algorithm in use to $1.  Only useful when testing the testsuite.
1489 test_set_hash () {
1490         test_hash_algo="$1"
1491 }
1492
1493 # Detect the hash algorithm in use.
1494 test_detect_hash () {
1495         test_hash_algo="${GIT_TEST_DEFAULT_HASH:-sha1}"
1496 }
1497
1498 # Load common hash metadata and common placeholder object IDs for use with
1499 # test_oid.
1500 test_oid_init () {
1501         test -n "$test_hash_algo" || test_detect_hash &&
1502         test_oid_cache <"$TEST_DIRECTORY/oid-info/hash-info" &&
1503         test_oid_cache <"$TEST_DIRECTORY/oid-info/oid"
1504 }
1505
1506 # Load key-value pairs from stdin suitable for use with test_oid.  Blank lines
1507 # and lines starting with "#" are ignored.  Keys must be shell identifier
1508 # characters.
1509 #
1510 # Examples:
1511 # rawsz sha1:20
1512 # rawsz sha256:32
1513 test_oid_cache () {
1514         local tag rest k v &&
1515
1516         { test -n "$test_hash_algo" || test_detect_hash; } &&
1517         while read tag rest
1518         do
1519                 case $tag in
1520                 \#*)
1521                         continue;;
1522                 ?*)
1523                         # non-empty
1524                         ;;
1525                 *)
1526                         # blank line
1527                         continue;;
1528                 esac &&
1529
1530                 k="${rest%:*}" &&
1531                 v="${rest#*:}" &&
1532
1533                 if ! expr "$k" : '[a-z0-9][a-z0-9]*$' >/dev/null
1534                 then
1535                         BUG 'bad hash algorithm'
1536                 fi &&
1537                 eval "test_oid_${k}_$tag=\"\$v\""
1538         done
1539 }
1540
1541 # Look up a per-hash value based on a key ($1).  The value must have been loaded
1542 # by test_oid_init or test_oid_cache.
1543 test_oid () {
1544         local algo="${test_hash_algo}" &&
1545
1546         case "$1" in
1547         --hash=*)
1548                 algo="${1#--hash=}" &&
1549                 shift;;
1550         *)
1551                 ;;
1552         esac &&
1553
1554         local var="test_oid_${algo}_$1" &&
1555
1556         # If the variable is unset, we must be missing an entry for this
1557         # key-hash pair, so exit with an error.
1558         if eval "test -z \"\${$var+set}\""
1559         then
1560                 BUG "undefined key '$1'"
1561         fi &&
1562         eval "printf '%s' \"\${$var}\""
1563 }
1564
1565 # Insert a slash into an object ID so it can be used to reference a location
1566 # under ".git/objects".  For example, "deadbeef..." becomes "de/adbeef..".
1567 test_oid_to_path () {
1568         local basename=${1#??}
1569         echo "${1%$basename}/$basename"
1570 }
1571
1572 # Choose a port number based on the test script's number and store it in
1573 # the given variable name, unless that variable already contains a number.
1574 test_set_port () {
1575         local var=$1 port
1576
1577         if test $# -ne 1 || test -z "$var"
1578         then
1579                 BUG "test_set_port requires a variable name"
1580         fi
1581
1582         eval port=\$$var
1583         case "$port" in
1584         "")
1585                 # No port is set in the given env var, use the test
1586                 # number as port number instead.
1587                 # Remove not only the leading 't', but all leading zeros
1588                 # as well, so the arithmetic below won't (mis)interpret
1589                 # a test number like '0123' as an octal value.
1590                 port=${this_test#${this_test%%[1-9]*}}
1591                 if test "${port:-0}" -lt 1024
1592                 then
1593                         # root-only port, use a larger one instead.
1594                         port=$(($port + 10000))
1595                 fi
1596                 ;;
1597         *[!0-9]*|0*)
1598                 error >&7 "invalid port number: $port"
1599                 ;;
1600         *)
1601                 # The user has specified the port.
1602                 ;;
1603         esac
1604
1605         # Make sure that parallel '--stress' test jobs get different
1606         # ports.
1607         port=$(($port + ${GIT_TEST_STRESS_JOB_NR:-0}))
1608         eval $var=$port
1609 }
1610
1611 # Tests for the hidden file attribute on Windows
1612 test_path_is_hidden () {
1613         test_have_prereq MINGW ||
1614         BUG "test_path_is_hidden can only be used on Windows"
1615
1616         # Use the output of `attrib`, ignore the absolute path
1617         case "$("$SYSTEMROOT"/system32/attrib "$1")" in *H*?:*) return 0;; esac
1618         return 1
1619 }
1620
1621 # Check that the given command was invoked as part of the
1622 # trace2-format trace on stdin.
1623 #
1624 #       test_subcommand [!] <command> <args>... < <trace>
1625 #
1626 # For example, to look for an invocation of "git upload-pack
1627 # /path/to/repo"
1628 #
1629 #       GIT_TRACE2_EVENT=event.log git fetch ... &&
1630 #       test_subcommand git upload-pack "$PATH" <event.log
1631 #
1632 # If the first parameter passed is !, this instead checks that
1633 # the given command was not called.
1634 #
1635 test_subcommand () {
1636         local negate=
1637         if test "$1" = "!"
1638         then
1639                 negate=t
1640                 shift
1641         fi
1642
1643         local expr=$(printf '"%s",' "$@")
1644         expr="${expr%,}"
1645
1646         if test -n "$negate"
1647         then
1648                 ! grep "\[$expr\]"
1649         else
1650                 grep "\[$expr\]"
1651         fi
1652 }
1653
1654 # Check that the given command was invoked as part of the
1655 # trace2-format trace on stdin.
1656 #
1657 #       test_region [!] <category> <label> git <command> <args>...
1658 #
1659 # For example, to look for trace2_region_enter("index", "do_read_index", repo)
1660 # in an invocation of "git checkout HEAD~1", run
1661 #
1662 #       GIT_TRACE2_EVENT="$(pwd)/trace.txt" GIT_TRACE2_EVENT_NESTING=10 \
1663 #               git checkout HEAD~1 &&
1664 #       test_region index do_read_index <trace.txt
1665 #
1666 # If the first parameter passed is !, this instead checks that
1667 # the given region was not entered.
1668 #
1669 test_region () {
1670         local expect_exit=0
1671         if test "$1" = "!"
1672         then
1673                 expect_exit=1
1674                 shift
1675         fi
1676
1677         grep -e '"region_enter".*"category":"'"$1"'","label":"'"$2"\" "$3"
1678         exitcode=$?
1679
1680         if test $exitcode != $expect_exit
1681         then
1682                 return 1
1683         fi
1684
1685         grep -e '"region_leave".*"category":"'"$1"'","label":"'"$2"\" "$3"
1686         exitcode=$?
1687
1688         if test $exitcode != $expect_exit
1689         then
1690                 return 1
1691         fi
1692
1693         return 0
1694 }