Raw
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 https://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 # Like test_set_editor but sets GIT_SEQUENCE_EDITOR instead of EDITOR
36 test_set_sequence_editor () {
37 FAKE_SEQUENCE_EDITOR="$1"
38 export FAKE_SEQUENCE_EDITOR
39 GIT_SEQUENCE_EDITOR='"$FAKE_SEQUENCE_EDITOR"'
40 export GIT_SEQUENCE_EDITOR
41 }
42
43 test_decode_color () {
44 awk '
45 function name(n) {
46 if (n == 0) return "RESET";
47 if (n == 1) return "BOLD";
48 if (n == 2) return "FAINT";
49 if (n == 3) return "ITALIC";
50 if (n == 7) return "REVERSE";
51 if (n == 22) return "NORMAL_INTENSITY";
52 if (n == 23) return "NOITALIC";
53 if (n == 27) return "NOREVERSE";
54 if (n == 30) return "BLACK";
55 if (n == 31) return "RED";
56 if (n == 32) return "GREEN";
57 if (n == 33) return "YELLOW";
58 if (n == 34) return "BLUE";
59 if (n == 35) return "MAGENTA";
60 if (n == 36) return "CYAN";
61 if (n == 37) return "WHITE";
62 if (n == 40) return "BLACK";
63 if (n == 41) return "BRED";
64 if (n == 42) return "BGREEN";
65 if (n == 43) return "BYELLOW";
66 if (n == 44) return "BBLUE";
67 if (n == 45) return "BMAGENTA";
68 if (n == 46) return "BCYAN";
69 if (n == 47) return "BWHITE";
70 }
71 {
72 while (match($0, /\033\[[0-9;]*m/) != 0) {
73 printf "%s<", substr($0, 1, RSTART-1);
74 codes = substr($0, RSTART+2, RLENGTH-3);
75 if (length(codes) == 0)
76 printf "%s", name(0)
77 else {
78 n = split(codes, ary, ";");
79 sep = "";
80 for (i = 1; i <= n; i++) {
81 printf "%s%s", sep, name(ary[i]);
82 sep = ";"
83 }
84 }
85 printf ">";
86 $0 = substr($0, RSTART + RLENGTH, length($0) - RSTART - RLENGTH + 1);
87 }
88 print
89 }
90 '
91 }
92
93 lf_to_nul () {
94 tr '\012' '\000'
95 }
96
97 nul_to_q () {
98 tr '\000' 'Q'
99 }
100
101 q_to_nul () {
102 tr 'Q' '\000'
103 }
104
105 q_to_cr () {
106 tr Q '\015'
107 }
108
109 q_to_tab () {
110 tr Q '\011'
111 }
112
113 qz_to_tab_space () {
114 tr QZ '\011\040'
115 }
116
117 append_cr () {
118 sed -e 's/$/Q/' | tr Q '\015'
119 }
120
121 remove_cr () {
122 tr '\015' Q | sed -e 's/Q$//'
123 }
124
125 # In some bourne shell implementations, the "unset" builtin returns
126 # nonzero status when a variable to be unset was not set in the first
127 # place.
128 #
129 # Use sane_unset when that should not be considered an error.
130
131 sane_unset () {
132 unset "$@"
133 return 0
134 }
135
136 test_tick () {
137 if test -z "${test_tick+set}"
138 then
139 test_tick=1112911993
140 else
141 test_tick=$(($test_tick + 60))
142 fi
143 GIT_COMMITTER_DATE="$test_tick -0700"
144 GIT_AUTHOR_DATE="$test_tick -0700"
145 export GIT_COMMITTER_DATE GIT_AUTHOR_DATE
146 }
147
148 # Stop execution and start a shell. This is useful for debugging tests.
149 #
150 # Be sure to remove all invocations of this command before submitting.
151 # WARNING: the shell invoked by this helper does not have the same environment
152 # as the one running the tests (shell variables and functions are not
153 # available, and the options below further modify the environment). As such,
154 # commands copied from a test script might behave differently than when
155 # running the test.
156 #
157 # Usage: test_pause [options]
158 # -t
159 # Use your original TERM instead of test-lib.sh's "dumb".
160 # This usually restores color output in the invoked shell.
161 # -s
162 # Invoke $SHELL instead of $TEST_SHELL_PATH.
163 # -h
164 # Use your original HOME instead of test-lib.sh's "$TRASH_DIRECTORY".
165 # This allows you to use your regular shell environment and Git aliases.
166 # CAUTION: running commands copied from a test script into the paused shell
167 # might result in files in your HOME being overwritten.
168 # -a
169 # Shortcut for -t -s -h
170
171 test_pause () {
172 PAUSE_TERM=$TERM &&
173 PAUSE_SHELL=$TEST_SHELL_PATH &&
174 PAUSE_HOME=$HOME &&
175 while test $# != 0
176 do
177 case "$1" in
178 -t)
179 PAUSE_TERM="$USER_TERM"
180 ;;
181 -s)
182 PAUSE_SHELL="$SHELL"
183 ;;
184 -h)
185 PAUSE_HOME="$USER_HOME"
186 ;;
187 -a)
188 PAUSE_TERM="$USER_TERM"
189 PAUSE_SHELL="$SHELL"
190 PAUSE_HOME="$USER_HOME"
191 ;;
192 *)
193 break
194 ;;
195 esac
196 shift
197 done &&
198 TERM="$PAUSE_TERM" HOME="$PAUSE_HOME" "$PAUSE_SHELL" <&6 >&5 2>&7
199 }
200
201 # Wrap git with a debugger. Adding this to a command can make it easier
202 # to understand what is going on in a failing test.
203 #
204 # Usage: debug [options] <git command>
205 # -d <debugger>
206 # --debugger=<debugger>
207 # Use <debugger> instead of GDB
208 # -t
209 # Use your original TERM instead of test-lib.sh's "dumb".
210 # This usually restores color output in the debugger.
211 # WARNING: the command being debugged might behave differently than when
212 # running the test.
213 #
214 # Examples:
215 # debug git checkout master
216 # debug --debugger=nemiver git $ARGS
217 # debug -d "valgrind --tool=memcheck --track-origins=yes" git $ARGS
218 debug () {
219 GIT_DEBUGGER=1 &&
220 DEBUG_TERM=$TERM &&
221 while test $# != 0
222 do
223 case "$1" in
224 -t)
225 DEBUG_TERM="$USER_TERM"
226 ;;
227 -d)
228 GIT_DEBUGGER="$2" &&
229 shift
230 ;;
231 --debugger=*)
232 GIT_DEBUGGER="${1#*=}"
233 ;;
234 *)
235 break
236 ;;
237 esac
238 shift
239 done &&
240
241 dotfiles=".gdbinit .lldbinit"
242
243 for dotfile in $dotfiles
244 do
245 dotfile="$USER_HOME/$dotfile" &&
246 test -f "$dotfile" && cp "$dotfile" "$HOME" || :
247 done &&
248
249 TERM="$DEBUG_TERM" GIT_DEBUGGER="${GIT_DEBUGGER}" "$@" <&6 >&5 2>&7 &&
250
251 for dotfile in $dotfiles
252 do
253 rm -f "$HOME/$dotfile"
254 done
255 }
256
257 # Usage: test_ref_exists [options] <ref>
258 #
259 # -C <dir>:
260 # Run all git commands in directory <dir>
261 #
262 # This helper function checks whether a reference exists. Symrefs or object IDs
263 # will not be resolved. Can be used to check references with bad names.
264 test_ref_exists () {
265 local indir=
266
267 while test $# != 0
268 do
269 case "$1" in
270 -C)
271 indir="$2"
272 shift
273 ;;
274 *)
275 break
276 ;;
277 esac
278 shift
279 done &&
280
281 indir=${indir:+"$indir"/} &&
282
283 if test "$#" != 1
284 then
285 BUG "expected exactly one reference"
286 fi &&
287
288 git ${indir:+ -C "$indir"} show-ref --exists "$1"
289 }
290
291 # Behaves the same as test_ref_exists, except that it checks for the absence of
292 # a reference. This is preferable to `! test_ref_exists` as this function is
293 # able to distinguish actually-missing references from other, generic errors.
294 test_ref_missing () {
295 test_ref_exists "$@"
296 case "$?" in
297 2)
298 # This is the good case.
299 return 0
300 ;;
301 0)
302 echo >&4 "test_ref_missing: reference exists"
303 return 1
304 ;;
305 *)
306 echo >&4 "test_ref_missing: generic error"
307 return 1
308 ;;
309 esac
310 }
311
312 # Usage: test_commit [options] <message> [<file> [<contents> [<tag>]]]
313 # -C <dir>:
314 # Run all git commands in directory <dir>
315 # --notick
316 # Do not call test_tick before making a commit
317 # --append
318 # Use ">>" instead of ">" when writing "<contents>" to "<file>"
319 # --printf
320 # Use "printf" instead of "echo" when writing "<contents>" to
321 # "<file>", use this to write escape sequences such as "\0", a
322 # trailing "\n" won't be added automatically. This option
323 # supports nothing but the FORMAT of printf(1), i.e. no custom
324 # ARGUMENT(s).
325 # --signoff
326 # Invoke "git commit" with --signoff
327 # --author <author>
328 # Invoke "git commit" with --author <author>
329 # --no-tag
330 # Do not tag the resulting commit
331 # --annotate
332 # Create an annotated tag with "--annotate -m <message>". Calls
333 # test_tick between making the commit and tag, unless --notick
334 # is given.
335 #
336 # This will commit a file with the given contents and the given commit
337 # message, and tag the resulting commit with the given tag name.
338 #
339 # <file>, <contents>, and <tag> all default to <message>.
340
341 test_commit () {
342 local notick= &&
343 local echo=echo &&
344 local append= &&
345 local author= &&
346 local signoff= &&
347 local indir= &&
348 local tag=light &&
349 while test $# != 0
350 do
351 case "$1" in
352 --notick)
353 notick=yes
354 ;;
355 --printf)
356 echo=printf
357 ;;
358 --append)
359 append=yes
360 ;;
361 --author)
362 author="$2"
363 shift
364 ;;
365 --signoff)
366 signoff="$1"
367 ;;
368 --date)
369 notick=yes
370 GIT_COMMITTER_DATE="$2"
371 GIT_AUTHOR_DATE="$2"
372 shift
373 ;;
374 -C)
375 indir="$2"
376 shift
377 ;;
378 --no-tag)
379 tag=none
380 ;;
381 --annotate)
382 tag=annotate
383 ;;
384 *)
385 break
386 ;;
387 esac
388 shift
389 done &&
390 indir=${indir:+"$indir"/} &&
391 local file="${2:-"$1.t"}" &&
392 if test -n "$append"
393 then
394 $echo "${3-$1}" >>"$indir$file"
395 else
396 $echo "${3-$1}" >"$indir$file"
397 fi &&
398 git ${indir:+ -C "$indir"} add -- "$file" &&
399 if test -z "$notick"
400 then
401 test_tick
402 fi &&
403 git ${indir:+ -C "$indir"} commit \
404 ${author:+ --author "$author"} \
405 $signoff -m "$1" &&
406 case "$tag" in
407 none)
408 ;;
409 light)
410 git ${indir:+ -C "$indir"} tag "${4:-$1}"
411 ;;
412 annotate)
413 if test -z "$notick"
414 then
415 test_tick
416 fi &&
417 git ${indir:+ -C "$indir"} tag -a -m "$1" "${4:-$1}"
418 ;;
419 esac
420 }
421
422 # Call test_merge with the arguments "<message> <commit>", where <commit>
423 # can be a tag pointing to the commit-to-merge.
424
425 test_merge () {
426 label="$1" &&
427 shift &&
428 test_tick &&
429 git merge -m "$label" "$@" &&
430 git tag "$label"
431 }
432
433 # Efficiently create <nr> commits, each with a unique number (from 1 to <nr>
434 # by default) in the commit message.
435 #
436 # Usage: test_commit_bulk [options] <nr>
437 # -C <dir>:
438 # Run all git commands in directory <dir>
439 # --ref=<n>:
440 # ref on which to create commits (default: HEAD)
441 # --start=<n>:
442 # number commit messages from <n> (default: 1)
443 # --message=<msg>:
444 # use <msg> as the commit mesasge (default: "commit %s")
445 # --filename=<fn>:
446 # modify <fn> in each commit (default: %s.t)
447 # --contents=<string>:
448 # place <string> in each file (default: "content %s")
449 # --id=<string>:
450 # shorthand to use <string> and %s in message, filename, and contents
451 #
452 # The message, filename, and contents strings are evaluated by printf, with the
453 # first "%s" replaced by the current commit number. So you can do:
454 #
455 # test_commit_bulk --filename=file --contents="modification %s"
456 #
457 # to have every commit touch the same file, but with unique content.
458 #
459 test_commit_bulk () {
460 tmpfile=.bulk-commit.input
461 indir=.
462 ref=HEAD
463 n=1
464 notick=
465 message='commit %s'
466 filename='%s.t'
467 contents='content %s'
468 while test $# -gt 0
469 do
470 case "$1" in
471 -C)
472 indir=$2
473 shift
474 ;;
475 --ref=*)
476 ref=${1#--*=}
477 ;;
478 --start=*)
479 n=${1#--*=}
480 ;;
481 --message=*)
482 message=${1#--*=}
483 ;;
484 --filename=*)
485 filename=${1#--*=}
486 ;;
487 --contents=*)
488 contents=${1#--*=}
489 ;;
490 --id=*)
491 message="${1#--*=} %s"
492 filename="${1#--*=}-%s.t"
493 contents="${1#--*=} %s"
494 ;;
495 --notick)
496 notick=yes
497 ;;
498 -*)
499 BUG "invalid test_commit_bulk option: $1"
500 ;;
501 *)
502 break
503 ;;
504 esac
505 shift
506 done
507 total=$1
508
509 add_from=
510 if git -C "$indir" rev-parse --quiet --verify "$ref"
511 then
512 add_from=t
513 fi
514
515 while test "$total" -gt 0
516 do
517 if test -z "$notick"
518 then
519 test_tick
520 fi &&
521 echo "commit $ref"
522 printf 'author %s <%s> %s\n' \
523 "$GIT_AUTHOR_NAME" \
524 "$GIT_AUTHOR_EMAIL" \
525 "$GIT_AUTHOR_DATE"
526 printf 'committer %s <%s> %s\n' \
527 "$GIT_COMMITTER_NAME" \
528 "$GIT_COMMITTER_EMAIL" \
529 "$GIT_COMMITTER_DATE"
530 echo "data <<EOF"
531 printf "$message\n" $n
532 echo "EOF"
533 if test -n "$add_from"
534 then
535 echo "from $ref^0"
536 add_from=
537 fi
538 printf "M 644 inline $filename\n" $n
539 echo "data <<EOF"
540 printf "$contents\n" $n
541 echo "EOF"
542 echo
543 n=$((n + 1))
544 total=$((total - 1))
545 done >"$tmpfile"
546
547 git -C "$indir" \
548 -c fastimport.unpacklimit=0 \
549 fast-import <"$tmpfile" || return 1
550
551 # This will be left in place on failure, which may aid debugging.
552 rm -f "$tmpfile"
553
554 # If we updated HEAD, then be nice and update the index and working
555 # tree, too.
556 if test "$ref" = "HEAD"
557 then
558 git -C "$indir" checkout -f HEAD || return 1
559 fi
560
561 }
562
563 # This function helps systems where core.filemode=false is set.
564 # Use it instead of plain 'chmod +x' to set or unset the executable bit
565 # of a file in the working directory and add it to the index.
566
567 test_chmod () {
568 chmod "$@" &&
569 git update-index --add "--chmod=$@"
570 }
571
572 # Get the modebits from a file or directory, ignoring the setgid bit (g+s).
573 # This bit is inherited by subdirectories at their creation. So we remove it
574 # from the returning string to prevent callers from having to worry about the
575 # state of the bit in the test directory.
576 #
577 test_modebits () {
578 ls -ld "$1" | sed -e 's|^\(..........\).*|\1|' \
579 -e 's|^\(......\)S|\1-|' -e 's|^\(......\)s|\1x|'
580 }
581
582 # Unset a configuration variable, but don't fail if it doesn't exist.
583 test_unconfig () {
584 config_dir=
585 if test "$1" = -C
586 then
587 shift
588 config_dir=$1
589 shift
590 fi
591 git ${config_dir:+-C "$config_dir"} config --unset-all "$@"
592 config_status=$?
593 case "$config_status" in
594 5) # ok, nothing to unset
595 config_status=0
596 ;;
597 esac
598 return $config_status
599 }
600
601 # Set git config, automatically unsetting it after the test is over.
602 test_config () {
603 config_dir=
604 if test "$1" = -C
605 then
606 shift
607 config_dir=$1
608 shift
609 fi
610
611 # If --worktree is provided, use it to configure/unconfigure
612 is_worktree=
613 if test "$1" = --worktree
614 then
615 is_worktree=1
616 shift
617 fi
618
619 test_when_finished "test_unconfig ${config_dir:+-C '$config_dir'} ${is_worktree:+--worktree} '$1'" &&
620 git ${config_dir:+-C "$config_dir"} config ${is_worktree:+--worktree} "$@"
621 }
622
623 test_config_global () {
624 test_when_finished "test_unconfig --global '$1'" &&
625 git config --global "$@"
626 }
627
628 write_script () {
629 {
630 echo "#!${2-"$SHELL_PATH"}" &&
631 cat
632 } >"$1" &&
633 chmod +x "$1"
634 }
635
636 # Usage: test_hook [options] <hook-name> <<-\EOF
637 #
638 # -C <dir>:
639 # Run all git commands in directory <dir>
640 # --setup
641 # Setup a hook for subsequent tests, i.e. don't remove it in a
642 # "test_when_finished"
643 # --clobber
644 # Overwrite an existing <hook-name>, if it exists. Implies
645 # --setup (i.e. the "test_when_finished" is assumed to have been
646 # set up already).
647 # --disable
648 # Disable (chmod -x) an existing <hook-name>, which must exist.
649 # --remove
650 # Remove (rm -f) an existing <hook-name>, which must exist.
651 test_hook () {
652 setup= &&
653 clobber= &&
654 disable= &&
655 remove= &&
656 indir= &&
657 while test $# != 0
658 do
659 case "$1" in
660 -C)
661 indir="$2" &&
662 shift
663 ;;
664 --setup)
665 setup=t
666 ;;
667 --clobber)
668 clobber=t
669 ;;
670 --disable)
671 disable=t
672 ;;
673 --remove)
674 remove=t
675 ;;
676 -*)
677 BUG "invalid argument: $1"
678 ;;
679 *)
680 break
681 ;;
682 esac &&
683 shift
684 done &&
685
686 git_dir=$(git -C "$indir" rev-parse --absolute-git-dir) &&
687 hook_dir="$git_dir/hooks" &&
688 hook_file="$hook_dir/$1" &&
689 if test -n "$disable$remove"
690 then
691 test_path_is_file "$hook_file" &&
692 if test -n "$disable"
693 then
694 chmod -x "$hook_file"
695 elif test -n "$remove"
696 then
697 rm -f "$hook_file"
698 fi &&
699 return 0
700 fi &&
701 if test -z "$clobber"
702 then
703 test_path_is_missing "$hook_file"
704 fi &&
705 if test -z "$setup$clobber"
706 then
707 test_when_finished "rm \"$hook_file\""
708 fi &&
709 write_script "$hook_file"
710 }
711
712 # Use test_set_prereq to tell that a particular prerequisite is available.
713 # The prerequisite can later be checked for in two ways:
714 #
715 # - Explicitly using test_have_prereq.
716 #
717 # - Implicitly by specifying the prerequisite tag in the calls to
718 # test_expect_{success,failure}
719 #
720 # The single parameter is the prerequisite tag (a simple word, in all
721 # capital letters by convention).
722
723 test_unset_prereq () {
724 ! test_have_prereq "$1" ||
725 satisfied_prereq="${satisfied_prereq% $1 *} ${satisfied_prereq#* $1 }"
726 }
727
728 test_set_prereq () {
729 if test -n "$GIT_TEST_FAIL_PREREQS_INTERNAL"
730 then
731 case "$1" in
732 # The "!" case is handled below with
733 # test_unset_prereq()
734 !*)
735 ;;
736 # List of things we can't easily pretend to not support
737 SYMLINKS)
738 ;;
739 # Inspecting whether GIT_TEST_FAIL_PREREQS is on
740 # should be unaffected.
741 FAIL_PREREQS)
742 ;;
743 *)
744 return
745 esac
746 fi
747
748 case "$1" in
749 !*)
750 test_unset_prereq "${1#!}"
751 ;;
752 *)
753 satisfied_prereq="$satisfied_prereq$1 "
754 ;;
755 esac
756 }
757 satisfied_prereq=" "
758 lazily_testable_prereq= lazily_tested_prereq=
759
760 # Usage: test_lazy_prereq PREREQ 'script'
761 test_lazy_prereq () {
762 lazily_testable_prereq="$lazily_testable_prereq$1 "
763 eval test_prereq_lazily_$1=\$2
764 }
765
766 test_run_lazy_prereq_ () {
767 script='
768 mkdir -p "$TRASH_DIRECTORY/prereq-test-dir-'"$1"'" &&
769 (
770 cd "$TRASH_DIRECTORY/prereq-test-dir-'"$1"'" &&'"$2"'
771 )'
772 say >&3 "checking prerequisite: $1"
773 say >&3 "$script"
774 test_eval_ "$script"
775 eval_ret=$?
776 rm -rf "$TRASH_DIRECTORY/prereq-test-dir-$1"
777 if test "$eval_ret" = 0; then
778 say >&3 "prerequisite $1 ok"
779 elif test "$eval_ret" = 125; then
780 :;
781 else
782 say >&3 "prerequisite $1 not satisfied"
783 fi
784 return $eval_ret
785 }
786
787 test_have_prereq () {
788 # prerequisites can be concatenated with ','
789 save_IFS=$IFS
790 IFS=,
791 set -- $*
792 IFS=$save_IFS
793
794 total_prereq=0
795 ok_prereq=0
796 missing_prereq=
797
798 for prerequisite
799 do
800 case "$prerequisite" in
801 !*)
802 negative_prereq=t
803 prerequisite=${prerequisite#!}
804 ;;
805 *)
806 negative_prereq=
807 esac
808
809 case " $lazily_tested_prereq " in
810 *" $prerequisite "*)
811 ;;
812 *)
813 case " $lazily_testable_prereq " in
814 *" $prerequisite "*)
815 eval "script=\$test_prereq_lazily_$prerequisite" &&
816 if test_run_lazy_prereq_ "$prerequisite" "$script"
817 then
818 test_set_prereq $prerequisite
819 elif test $? = 125
820 then
821 BUG "Do not use $prerequisite"
822 fi
823 lazily_tested_prereq="$lazily_tested_prereq$prerequisite "
824 esac
825 ;;
826 esac
827
828 total_prereq=$(($total_prereq + 1))
829 case "$satisfied_prereq" in
830 *" $prerequisite "*)
831 satisfied_this_prereq=t
832 ;;
833 *)
834 satisfied_this_prereq=
835 esac
836
837 case "$satisfied_this_prereq,$negative_prereq" in
838 t,|,t)
839 ok_prereq=$(($ok_prereq + 1))
840 ;;
841 *)
842 # Keep a list of missing prerequisites; restore
843 # the negative marker if necessary.
844 prerequisite=${negative_prereq:+!}$prerequisite
845
846 # Abort if this prereq was marked as required
847 if test -n "$GIT_TEST_REQUIRE_PREREQ"
848 then
849 case " $GIT_TEST_REQUIRE_PREREQ " in
850 *" $prerequisite "*)
851 BAIL_OUT "required prereq $prerequisite failed"
852 ;;
853 esac
854 fi
855
856 if test -z "$missing_prereq"
857 then
858 missing_prereq=$prerequisite
859 else
860 missing_prereq="$prerequisite,$missing_prereq"
861 fi
862 esac
863 done
864
865 test $total_prereq = $ok_prereq
866 }
867
868 test_declared_prereq () {
869 case ",$test_prereq," in
870 *,$1,*)
871 return 0
872 ;;
873 esac
874 return 1
875 }
876
877 test_verify_prereq () {
878 test -z "$test_prereq" ||
879 expr >/dev/null "$test_prereq" : '[A-Z0-9_,!]*$' ||
880 BUG "'$test_prereq' does not look like a prereq"
881 }
882
883 # assign the variable named by "$1" with the contents of "$2";
884 # if "$2" is "-", then read stdin into "$1" instead
885 test_body_or_stdin () {
886 if test "$2" != "-"
887 then
888 eval "$1=\$2"
889 return
890 fi
891
892 # start with a newline, to match hanging newline from open-quote style
893 eval "$1=\$LF"
894 local test_line
895 while IFS= read -r test_line
896 do
897 eval "$1=\${$1}\${test_line}\${LF}"
898 done
899 }
900
901 test_expect_failure () {
902 test_start_ "$@"
903 test "$#" = 3 && { test_prereq=$1; shift; } || test_prereq=
904 test "$#" = 2 ||
905 BUG "not 2 or 3 parameters to test-expect-failure"
906 test_verify_prereq
907 export test_prereq
908 if ! test_skip "$@"
909 then
910 local test_body
911 test_body_or_stdin test_body "$2"
912 test -n "$test_skip_test_preamble" ||
913 say >&3 "checking known breakage of $TEST_NUMBER.$test_count '$1': $test_body"
914 if test_run_ "$test_body" expecting_failure
915 then
916 test_known_broken_ok_ "$1"
917 else
918 test_known_broken_failure_ "$1"
919 fi
920 fi
921 test_finish_
922 }
923
924 test_expect_success () {
925 test_start_ "$@"
926 test "$#" = 3 && { test_prereq=$1; shift; } || test_prereq=
927 test "$#" = 2 ||
928 BUG "not 2 or 3 parameters to test-expect-success"
929 test_verify_prereq
930 export test_prereq
931 if ! test_skip "$@"
932 then
933 local test_body
934 test_body_or_stdin test_body "$2"
935 test -n "$test_skip_test_preamble" ||
936 say >&3 "expecting success of $TEST_NUMBER.$test_count '$1': $test_body"
937 if test_run_ "$test_body" &&
938 ! check_test_results_san_file_has_entries_
939 then
940 test_ok_ "$1"
941 else
942 test_failure_ "$1" "$test_body"
943 fi
944 fi
945 test_finish_
946 }
947
948 # debugging-friendly alternatives to "test [-f|-d|-e]"
949 # The commands test the existence or non-existence of $1
950 test_path_is_file () {
951 test "$#" -ne 1 && BUG "1 param"
952 if ! test -f "$1"
953 then
954 echo "File $1 doesn't exist"
955 false
956 fi
957 }
958
959 test_path_is_file_not_symlink () {
960 test "$#" -ne 1 && BUG "1 param"
961 test_path_is_file "$1" &&
962 if test -h "$1"
963 then
964 echo "$1 shouldn't be a symbolic link"
965 false
966 fi
967 }
968
969 test_path_is_dir () {
970 test "$#" -ne 1 && BUG "1 param"
971 if ! test -d "$1"
972 then
973 echo "Directory $1 doesn't exist"
974 false
975 fi
976 }
977
978 test_path_is_dir_not_symlink () {
979 test "$#" -ne 1 && BUG "1 param"
980 test_path_is_dir "$1" &&
981 if test -h "$1"
982 then
983 echo "$1 shouldn't be a symbolic link"
984 false
985 fi
986 }
987
988 test_path_exists () {
989 test "$#" -ne 1 && BUG "1 param"
990 if ! test -e "$1"
991 then
992 echo "Path $1 doesn't exist"
993 false
994 fi
995 }
996
997 test_path_is_symlink () {
998 test "$#" -ne 1 && BUG "1 param"
999 if ! test -h "$1"
1000 then
1001 echo "Symbolic link $1 doesn't exist"
1002 false
1003 fi
1004 }
1005
1006 test_path_is_executable () {
1007 test "$#" -ne 1 && BUG "1 param"
1008 if ! test -x "$1"
1009 then
1010 echo "$1 is not executable"
1011 false
1012 fi
1013 }
1014
1015 # Check if the directory exists and is empty as expected, barf otherwise.
1016 test_dir_is_empty () {
1017 test "$#" -ne 1 && BUG "1 param"
1018 test_path_is_dir "$1" &&
1019 if test -n "$(ls -a1 "$1" | grep -E -v '^\.\.?$')"
1020 then
1021 echo "Directory '$1' is not empty, it contains:"
1022 ls -la "$1"
1023 return 1
1024 fi
1025 }
1026
1027 # Check if the file exists and has a size greater than zero
1028 test_file_not_empty () {
1029 test "$#" = 2 && BUG "2 param"
1030 if ! test -s "$1"
1031 then
1032 echo "'$1' is not a non-empty file."
1033 false
1034 fi
1035 }
1036
1037 test_path_is_missing () {
1038 test "$#" -ne 1 && BUG "1 param"
1039 if test -e "$1"
1040 then
1041 echo "Path exists:"
1042 ls -ld "$1"
1043 false
1044 fi
1045 }
1046
1047 # test_line_count checks that a file has the number of lines it
1048 # ought to. For example:
1049 #
1050 # test_expect_success 'produce exactly one line of output' '
1051 # do something >output &&
1052 # test_line_count = 1 output
1053 # '
1054 #
1055 # is like "test $(wc -l <output) = 1" except that it passes the
1056 # output through when the number of lines is wrong.
1057
1058 test_line_count () {
1059 if test $# != 3
1060 then
1061 BUG "not 3 parameters to test_line_count"
1062 elif ! test $(wc -l <"$3") "$1" "$2"
1063 then
1064 echo "test_line_count: line count for $3 !$1 $2"
1065 cat "$3"
1066 return 1
1067 fi
1068 }
1069
1070 # SYNOPSIS:
1071 # test_stdout_line_count <bin-ops> <value> <cmd> [<args>...]
1072 #
1073 # test_stdout_line_count checks that the output of a command has the number
1074 # of lines it ought to. For example:
1075 #
1076 # test_stdout_line_count = 3 git ls-files -u
1077 # test_stdout_line_count -gt 10 ls
1078 test_stdout_line_count () {
1079 local ops val trashdir &&
1080 if test "$#" -le 3
1081 then
1082 BUG "expect 3 or more arguments"
1083 fi &&
1084 ops="$1" &&
1085 val="$2" &&
1086 shift 2 &&
1087 if ! trashdir="$(git rev-parse --git-dir)/trash"; then
1088 BUG "expect to be run inside a worktree"
1089 fi &&
1090 mkdir -p "$trashdir" &&
1091 "$@" >"$trashdir/output" &&
1092 test_line_count "$ops" "$val" "$trashdir/output"
1093 }
1094
1095
1096 test_file_size () {
1097 test "$#" -ne 1 && BUG "1 param"
1098 test-tool path-utils file-size "$1"
1099 }
1100
1101 # Returns success if a comma separated string of keywords ($1) contains a
1102 # given keyword ($2).
1103 # Examples:
1104 # `list_contains "foo,bar" bar` returns 0
1105 # `list_contains "foo" bar` returns 1
1106
1107 list_contains () {
1108 case ",$1," in
1109 *,$2,*)
1110 return 0
1111 ;;
1112 esac
1113 return 1
1114 }
1115
1116 # Returns success if the arguments indicate that a command should be
1117 # accepted by test_must_fail(). If the command is run with env, the env
1118 # and its corresponding variable settings will be stripped before we
1119 # test the command being run.
1120 test_must_fail_acceptable () {
1121 if test "$1" = "env"
1122 then
1123 shift
1124 while test $# -gt 0
1125 do
1126 case "$1" in
1127 *?=*)
1128 shift
1129 ;;
1130 *)
1131 break
1132 ;;
1133 esac
1134 done
1135 fi
1136
1137 if test "$1" = "nongit"
1138 then
1139 shift
1140 fi
1141
1142 case "$1" in
1143 git|__git*|scalar|test-tool|test_terminal)
1144 return 0
1145 ;;
1146 *)
1147 return 1
1148 ;;
1149 esac
1150 }
1151
1152 # This is not among top-level (test_expect_success | test_expect_failure)
1153 # but is a prefix that can be used in the test script, like:
1154 #
1155 # test_expect_success 'complain and die' '
1156 # do something &&
1157 # do something else &&
1158 # test_must_fail git checkout ../outerspace
1159 # '
1160 #
1161 # Writing this as "! git checkout ../outerspace" is wrong, because
1162 # the failure could be due to a segv. We want a controlled failure.
1163 #
1164 # Accepts the following options:
1165 #
1166 # ok=<signal-name>[,<...>]:
1167 # Don't treat an exit caused by the given signal as error.
1168 # Multiple signals can be specified as a comma separated list.
1169 # Currently recognized signal names are: sigpipe, success.
1170 # (Don't use 'success', use 'test_might_fail' instead.)
1171 #
1172 # Do not use this to run anything but "git" and other specific testable
1173 # commands (see test_must_fail_acceptable()). We are not in the
1174 # business of vetting system supplied commands -- in other words, this
1175 # is wrong:
1176 #
1177 # test_must_fail grep pattern output
1178 #
1179 # Instead use '!':
1180 #
1181 # ! grep pattern output
1182
1183 test_must_fail () {
1184 case "$1" in
1185 ok=*)
1186 _test_ok=${1#ok=}
1187 shift
1188 ;;
1189 *)
1190 _test_ok=
1191 ;;
1192 esac
1193 if ! test_must_fail_acceptable "$@"
1194 then
1195 echo >&7 "test_must_fail: only 'git' is allowed: $*"
1196 return 1
1197 fi
1198
1199 exit_code=0; "$@" 2>&7 || exit_code=$?
1200
1201 if test $exit_code -eq 0 && ! list_contains "$_test_ok" success
1202 then
1203 echo >&4 "test_must_fail: command succeeded: $*"
1204 return 1
1205 elif test_match_signal 13 $exit_code && list_contains "$_test_ok" sigpipe
1206 then
1207 return 0
1208 elif test $exit_code -gt 129 && test $exit_code -le 192
1209 then
1210 echo >&4 "test_must_fail: died by signal $(($exit_code - 128)): $*"
1211 return 1
1212 elif test $exit_code -eq 127
1213 then
1214 echo >&4 "test_must_fail: command not found: $*"
1215 return 1
1216 elif test $exit_code -eq 126
1217 then
1218 echo >&4 "test_must_fail: valgrind error: $*"
1219 return 1
1220 fi
1221 return 0
1222 } 7>&2 2>&4
1223
1224 # Similar to test_must_fail, but tolerates success, too. This is
1225 # meant to be used in contexts like:
1226 #
1227 # test_expect_success 'some command works without configuration' '
1228 # test_might_fail git config --unset all.configuration &&
1229 # do something
1230 # '
1231 #
1232 # Writing "git config --unset all.configuration || :" would be wrong,
1233 # because we want to notice if it fails due to segv.
1234 #
1235 # Accepts the same options as test_must_fail.
1236
1237 test_might_fail () {
1238 test_must_fail ok=success "$@" 2>&7
1239 } 7>&2 2>&4
1240
1241 # Similar to test_must_fail and test_might_fail, but check that a
1242 # given command exited with a given exit code. Meant to be used as:
1243 #
1244 # test_expect_success 'Merge with d/f conflicts' '
1245 # test_expect_code 1 git merge "merge msg" B master
1246 # '
1247
1248 test_expect_code () {
1249 want_code=$1
1250 shift
1251 exit_code=0; "$@" 2>&7 || exit_code=$?
1252 if test $exit_code = $want_code
1253 then
1254 return 0
1255 fi
1256
1257 echo >&4 "test_expect_code: command exited with $exit_code, we wanted $want_code $*"
1258 return 1
1259 } 7>&2 2>&4
1260
1261 # test_cmp is a helper function to compare actual and expected output.
1262 # You can use it like:
1263 #
1264 # test_expect_success 'foo works' '
1265 # echo expected >expected &&
1266 # foo >actual &&
1267 # test_cmp expected actual
1268 # '
1269 #
1270 # This could be written as either "cmp" or "diff -u", but:
1271 # - cmp's output is not nearly as easy to read as diff -u
1272 # - not all diff versions understand "-u"
1273
1274 test_cmp () {
1275 test "$#" -ne 2 && BUG "2 param"
1276 eval "$GIT_TEST_CMP" '"$@"'
1277 }
1278
1279 # test_cmp_sorted runs test_cmp on sorted versions of the two
1280 # input files. Uses "$1.sorted" and "$2.sorted" as temp files.
1281
1282 test_cmp_sorted () {
1283 sort <"$1" >"$1.sorted" &&
1284 sort <"$2" >"$2.sorted" &&
1285 test_cmp "$1.sorted" "$2.sorted" &&
1286 rm "$1.sorted" "$2.sorted"
1287 }
1288
1289 # Check that the given config key has the expected value.
1290 #
1291 # test_cmp_config [-C <dir>] <expected-value>
1292 # [<git-config-options>...] <config-key>
1293 #
1294 # for example to check that the value of core.bar is foo
1295 #
1296 # test_cmp_config foo core.bar
1297 #
1298 test_cmp_config () {
1299 local GD &&
1300 if test "$1" = "-C"
1301 then
1302 shift &&
1303 GD="-C $1" &&
1304 shift
1305 fi &&
1306 printf "%s\n" "$1" >expect.config &&
1307 shift &&
1308 git $GD config "$@" >actual.config &&
1309 test_cmp expect.config actual.config
1310 }
1311
1312 # test_cmp_bin - helper to compare binary files
1313
1314 test_cmp_bin () {
1315 test "$#" -ne 2 && BUG "2 param"
1316 cmp "$@"
1317 }
1318
1319 test_i18ngrep () {
1320 BUG "do not use test_i18ngrep---use test_grep instead"
1321 }
1322
1323 test_grep () {
1324 eval "last_arg=\${$#}"
1325
1326 test -f "$last_arg" ||
1327 BUG "test_grep requires a file to read as the last parameter"
1328
1329 if test $# -lt 2 ||
1330 { test "x!" = "x$1" && test $# -lt 3 ; }
1331 then
1332 BUG "too few parameters to test_grep"
1333 fi
1334
1335 if test "x!" = "x$1"
1336 then
1337 shift
1338 ! grep "$@" && return 0
1339
1340 echo >&4 "error: '! grep $@' did find a match in:"
1341 else
1342 grep "$@" && return 0
1343
1344 echo >&4 "error: 'grep $@' didn't find a match in:"
1345 fi
1346
1347 if test -s "$last_arg"
1348 then
1349 cat >&4 "$last_arg"
1350 else
1351 echo >&4 "<File '$last_arg' is empty>"
1352 fi
1353
1354 return 1
1355 }
1356
1357 # Check if the file expected to be empty is indeed empty, and barfs
1358 # otherwise.
1359
1360 test_must_be_empty () {
1361 test "$#" -ne 1 && BUG "1 param"
1362 test_path_is_file "$1" &&
1363 if test -s "$1"
1364 then
1365 echo "'$1' is not empty, it contains:"
1366 cat "$1"
1367 return 1
1368 fi
1369 }
1370
1371 # Tests that its two parameters refer to the same revision, or if '!' is
1372 # provided first, that its other two parameters refer to different
1373 # revisions.
1374 test_cmp_rev () {
1375 local op='=' wrong_result=different
1376
1377 if test $# -ge 1 && test "x$1" = 'x!'
1378 then
1379 op='!='
1380 wrong_result='the same'
1381 shift
1382 fi
1383 if test $# != 2
1384 then
1385 BUG "test_cmp_rev requires two revisions, but got $#"
1386 else
1387 local r1 r2
1388 r1=$(git rev-parse --verify "$1") &&
1389 r2=$(git rev-parse --verify "$2") || return 1
1390
1391 if ! test "$r1" "$op" "$r2"
1392 then
1393 cat >&4 <<-EOF
1394 error: two revisions point to $wrong_result objects:
1395 '$1': $r1
1396 '$2': $r2
1397 EOF
1398 return 1
1399 fi
1400 fi
1401 }
1402
1403 # Tests that a commit message matches the expected text
1404 #
1405 # Usage: test_commit_message <rev> [-m <msg> | <file>]
1406 #
1407 # When using "-m" <msg> will have a line feed appended. If the second
1408 # argument is omitted then the expected message is read from stdin.
1409
1410 test_commit_message () {
1411 local msg_file=expect.msg
1412
1413 case $# in
1414 3)
1415 if test "$2" = "-m"
1416 then
1417 printf "%s\n" "$3" >"$msg_file"
1418 else
1419 BUG "Usage: test_commit_message <rev> [-m <message> | <file>]"
1420 fi
1421 ;;
1422 2)
1423 msg_file="$2"
1424 ;;
1425 1)
1426 cat >"$msg_file"
1427 ;;
1428 *)
1429 BUG "Usage: test_commit_message <rev> [-m <message> | <file>]"
1430 ;;
1431 esac
1432 git show --no-patch --pretty=format:%B "$1" -- >actual.msg &&
1433 test_cmp "$msg_file" actual.msg
1434 }
1435
1436 # Print the message body of a commit
1437 # Usage: commit_body <rev>
1438 commit_body () {
1439 git cat-file commit "$1" >.commit &&
1440 sed -e "1,/^$/d" .commit &&
1441 rm -f .commit
1442 }
1443
1444 # Compare paths respecting core.ignoreCase
1445 test_cmp_fspath () {
1446 if test "x$1" = "x$2"
1447 then
1448 return 0
1449 fi
1450
1451 if test true != "$(git config --get --type=bool core.ignorecase)"
1452 then
1453 return 1
1454 fi
1455
1456 test "x$(echo "$1" | tr A-Z a-z)" = "x$(echo "$2" | tr A-Z a-z)"
1457 }
1458
1459 # Print a sequence of integers in increasing order, either with
1460 # two arguments (start and end):
1461 #
1462 # test_seq 1 5 -- outputs 1 2 3 4 5 one line at a time
1463 #
1464 # or with one argument (end), in which case it starts counting
1465 # from 1. In addition to the start/end arguments, you can pass an optional
1466 # printf format. For example:
1467 #
1468 # test_seq -f "line %d" 1 5
1469 #
1470 # would print 5 lines, "line 1" through "line 5".
1471
1472 test_seq () {
1473 local fmt="%d"
1474 case "$1" in
1475 -f)
1476 fmt="$2"
1477 shift 2
1478 ;;
1479 esac
1480 case $# in
1481 1) set 1 "$@" ;;
1482 2) ;;
1483 *) BUG "not 1 or 2 parameters to test_seq" ;;
1484 esac
1485 test_seq_counter__=$1
1486 while test "$test_seq_counter__" -le "$2"
1487 do
1488 printf "$fmt\n" "$test_seq_counter__"
1489 test_seq_counter__=$(( $test_seq_counter__ + 1 ))
1490 done
1491 }
1492
1493 # This function can be used to schedule some commands to be run
1494 # unconditionally at the end of the test to restore sanity:
1495 #
1496 # test_expect_success 'test core.capslock' '
1497 # git config core.capslock true &&
1498 # test_when_finished "git config --unset core.capslock" &&
1499 # hello world
1500 # '
1501 #
1502 # That would be roughly equivalent to
1503 #
1504 # test_expect_success 'test core.capslock' '
1505 # git config core.capslock true &&
1506 # hello world
1507 # git config --unset core.capslock
1508 # '
1509 #
1510 # except that the greeting and config --unset must both succeed for
1511 # the test to pass.
1512 #
1513 # Note that under --immediate mode, no clean-up is done to help diagnose
1514 # what went wrong.
1515
1516 test_when_finished () {
1517 # We cannot detect when we are in a subshell in general, but by
1518 # doing so on Bash is better than nothing (the test will
1519 # silently pass on other shells).
1520 test "${BASH_SUBSHELL-0}" = 0 ||
1521 BUG "test_when_finished does nothing in a subshell"
1522 test_cleanup="{ $*
1523 } || eval_ret=\$?; $test_cleanup"
1524 }
1525
1526 # This function can be used to schedule some commands to be run
1527 # unconditionally at the end of the test script, e.g. to stop a daemon:
1528 #
1529 # test_expect_success 'test git daemon' '
1530 # git daemon &
1531 # daemon_pid=$! &&
1532 # test_atexit 'kill $daemon_pid' &&
1533 # hello world
1534 # '
1535 #
1536 # The commands will be executed before the trash directory is removed,
1537 # i.e. the atexit commands will still be able to access any pidfiles or
1538 # socket files.
1539 #
1540 # Note that these commands will be run even when a test script run
1541 # with '--immediate' fails. Be careful with your atexit commands to
1542 # minimize any changes to the failed state.
1543
1544 test_atexit () {
1545 # We cannot detect when we are in a subshell in general, but by
1546 # doing so on Bash is better than nothing (the test will
1547 # silently pass on other shells).
1548 test "${BASH_SUBSHELL-0}" = 0 ||
1549 BUG "test_atexit does nothing in a subshell"
1550 test_atexit_cleanup="{ $*
1551 } || eval_ret=\$?; $test_atexit_cleanup"
1552 }
1553
1554 # Deprecated wrapper for "git init", use "git init" directly instead
1555 # Usage: test_create_repo <directory>
1556 test_create_repo () {
1557 git init "$@"
1558 }
1559
1560 # This function helps on symlink challenged file systems when it is not
1561 # important that the file system entry is a symbolic link.
1562 # Use test_ln_s_add instead of "ln -s x y && git add y" to add a
1563 # symbolic link entry y to the index.
1564
1565 test_ln_s_add () {
1566 if test_have_prereq SYMLINKS
1567 then
1568 ln -s "$1" "$2" &&
1569 git update-index --add "$2"
1570 else
1571 printf '%s' "$1" >"$2" &&
1572 ln_s_obj=$(git hash-object -w "$2") &&
1573 git update-index --add --cacheinfo 120000 $ln_s_obj "$2" &&
1574 # pick up stat info from the file
1575 git update-index "$2"
1576 fi
1577 }
1578
1579 # This function writes out its parameters, one per line
1580 test_write_lines () {
1581 printf "%s\n" "$@"
1582 }
1583
1584 perl () {
1585 command "$PERL_PATH" "$@" 2>&7
1586 } 7>&2 2>&4
1587
1588 # Given the name of an environment variable with a bool value, normalize
1589 # its value to a 0 (true) or 1 (false or empty string) return code.
1590 #
1591 # test_bool_env GIT_TEST_HTTPD <default-value>
1592 #
1593 # Return with code corresponding to the given default value if the variable
1594 # is unset.
1595 # Abort the test script if either the value of the variable or the default
1596 # are not valid bool values.
1597
1598 test_bool_env () {
1599 if test $# != 2
1600 then
1601 BUG "test_bool_env requires two parameters (variable name and default value)"
1602 fi
1603
1604 test-tool env-helper --type=bool --default="$2" --exit-code "$1"
1605 ret=$?
1606 case $ret in
1607 0|1) # unset or valid bool value
1608 ;;
1609 *) # invalid bool value or something unexpected
1610 error >&7 "test_bool_env requires bool values both for \$$1 and for the default fallback"
1611 ;;
1612 esac
1613 return $ret
1614 }
1615
1616 # Exit the test suite, either by skipping all remaining tests or by
1617 # exiting with an error. If our prerequisite variable $1 falls back
1618 # on a default assume we were opportunistically trying to set up some
1619 # tests and we skip. If it is explicitly "true", then we report a failure.
1620 #
1621 # The error/skip message should be given by $2.
1622 #
1623 test_skip_or_die () {
1624 if ! test_bool_env "$1" false
1625 then
1626 skip_all=$2
1627 test_done
1628 fi
1629 error "$2"
1630 }
1631
1632 # Like "env FOO=BAR some-program", but run inside a subshell, which means
1633 # it also works for shell functions (though those functions cannot impact
1634 # the environment outside of the test_env invocation).
1635 test_env () {
1636 (
1637 while test $# -gt 0
1638 do
1639 case "$1" in
1640 *=*)
1641 eval "${1%%=*}=\${1#*=}"
1642 eval "export ${1%%=*}"
1643 shift
1644 ;;
1645 *)
1646 "$@" 2>&7
1647 exit
1648 ;;
1649 esac
1650 done
1651 )
1652 } 7>&2 2>&4
1653
1654 # Returns true if the numeric exit code in "$2" represents the expected signal
1655 # in "$1". Signals should be given numerically.
1656 test_match_signal () {
1657 if test "$2" = "$((128 + $1))"
1658 then
1659 # POSIX
1660 return 0
1661 elif test "$2" = "$((256 + $1))"
1662 then
1663 # ksh
1664 return 0
1665 fi
1666 return 1
1667 }
1668
1669 # Read up to "$1" bytes (or to EOF) from stdin and write them to stdout.
1670 test_copy_bytes () {
1671 dd ibs=1 count="$1" 2>/dev/null
1672 }
1673
1674 # run "$@" inside a non-git directory
1675 nongit () {
1676 test -d non-repo ||
1677 mkdir non-repo ||
1678 return 1
1679
1680 (
1681 GIT_CEILING_DIRECTORIES=$(pwd) &&
1682 export GIT_CEILING_DIRECTORIES &&
1683 cd non-repo &&
1684 "$@" 2>&7
1685 )
1686 } 7>&2 2>&4
1687
1688 # These functions are historical wrappers around "test-tool pkt-line"
1689 # for older tests. Use "test-tool pkt-line" itself in new tests.
1690 packetize () {
1691 if test $# -gt 0
1692 then
1693 packet="$*"
1694 printf '%04x%s' "$((4 + ${#packet}))" "$packet"
1695 else
1696 test-tool pkt-line pack
1697 fi
1698 }
1699
1700 packetize_raw () {
1701 test-tool pkt-line pack-raw-stdin
1702 }
1703
1704 depacketize () {
1705 test-tool pkt-line unpack
1706 }
1707
1708 # Converts base-16 data into base-8. The output is given as a sequence of
1709 # escaped octals, suitable for consumption by 'printf'.
1710 hex2oct () {
1711 perl -ne 'printf "\\%03o", hex for /../g'
1712 }
1713
1714 # Set the hash algorithm in use to $1. Only useful when testing the testsuite.
1715 test_set_hash () {
1716 test_hash_algo="$1"
1717 }
1718
1719 # Detect the hash algorithm in use.
1720 test_detect_hash () {
1721 case "${GIT_TEST_DEFAULT_HASH:-$GIT_TEST_BUILTIN_HASH}" in
1722 *:*)
1723 test_hash_algo="${GIT_TEST_DEFAULT_HASH%%:*}"
1724 test_compat_hash_algo="${GIT_TEST_DEFAULT_HASH##*:}"
1725 test_repo_compat_hash_algo="$test_compat_hash_algo"
1726 ;;
1727 sha256)
1728 test_hash_algo=sha256
1729 test_compat_hash_algo=sha1
1730 ;;
1731 sha1)
1732 test_hash_algo=sha1
1733 test_compat_hash_algo=sha256
1734 ;;
1735 esac
1736 }
1737
1738 # Detect the ref format in use.
1739 test_detect_ref_format () {
1740 echo "${GIT_TEST_DEFAULT_REF_FORMAT:-files}"
1741 }
1742
1743 # Load common hash metadata and common placeholder object IDs for use with
1744 # test_oid.
1745 test_oid_init () {
1746 test -n "$test_hash_algo" || test_detect_hash &&
1747 test_oid_cache <"$TEST_DIRECTORY/oid-info/hash-info" &&
1748 test_oid_cache <"$TEST_DIRECTORY/oid-info/oid"
1749 }
1750
1751 # Load key-value pairs from stdin suitable for use with test_oid. Blank lines
1752 # and lines starting with "#" are ignored. Keys must be shell identifier
1753 # characters.
1754 #
1755 # Examples:
1756 # rawsz sha1:20
1757 # rawsz sha256:32
1758 test_oid_cache () {
1759 local tag rest k v &&
1760
1761 { test -n "$test_hash_algo" || test_detect_hash; } &&
1762 while read tag rest
1763 do
1764 case $tag in
1765 \#*)
1766 continue;;
1767 ?*)
1768 # non-empty
1769 ;;
1770 *)
1771 # blank line
1772 continue;;
1773 esac &&
1774
1775 k="${rest%:*}" &&
1776 v="${rest#*:}" &&
1777
1778 if ! expr "$k" : '[a-z0-9][a-z0-9]*$' >/dev/null
1779 then
1780 BUG 'bad hash algorithm'
1781 fi &&
1782 eval "test_oid_${k}_$tag=\"\$v\""
1783 done
1784 }
1785
1786 # Look up a per-hash value based on a key ($1). The value must have been loaded
1787 # by test_oid_init or test_oid_cache.
1788 test_oid () {
1789 local algo="${test_hash_algo}" &&
1790
1791 case "$1" in
1792 --hash=storage)
1793 algo="$test_hash_algo" &&
1794 shift;;
1795 --hash=compat)
1796 algo="$test_compat_hash_algo" &&
1797 shift;;
1798 --hash=builtin)
1799 algo="$GIT_TEST_BUILTIN_HASH" &&
1800 shift;;
1801 --hash=*)
1802 algo="${1#--hash=}" &&
1803 shift;;
1804 *)
1805 ;;
1806 esac &&
1807
1808 local var="test_oid_${algo}_$1" &&
1809
1810 # If the variable is unset, we must be missing an entry for this
1811 # key-hash pair, so exit with an error.
1812 if eval "test -z \"\${$var+set}\""
1813 then
1814 BUG "undefined key '$1'"
1815 fi &&
1816 eval "printf '%s\n' \"\${$var}\""
1817 }
1818
1819 # Insert a slash into an object ID so it can be used to reference a location
1820 # under ".git/objects". For example, "deadbeef..." becomes "de/adbeef..".
1821 test_oid_to_path () {
1822 local basename="${1#??}"
1823 echo "${1%$basename}/$basename"
1824 }
1825
1826 # Parse oids from git ls-files --staged output
1827 test_parse_ls_files_stage_oids () {
1828 awk '{print $2}' -
1829 }
1830
1831 # Parse oids from git ls-tree output
1832 test_parse_ls_tree_oids () {
1833 awk '{print $3}' -
1834 }
1835
1836 # Choose a port number based on the test script's number and store it in
1837 # the given variable name, unless that variable already contains a number.
1838 test_set_port () {
1839 local var="$1" port
1840
1841 if test $# -ne 1 || test -z "$var"
1842 then
1843 BUG "test_set_port requires a variable name"
1844 fi
1845
1846 eval port=\$$var
1847 case "$port" in
1848 "")
1849 # No port is set in the given env var, use the test
1850 # number as port number instead.
1851 # Remove not only the leading 't', but all leading zeros
1852 # as well, so the arithmetic below won't (mis)interpret
1853 # a test number like '0123' as an octal value.
1854 port=${this_test#${this_test%%[1-9]*}}
1855 if test "${port:-0}" -lt 1024
1856 then
1857 # root-only port, use a larger one instead.
1858 port=$(($port + 10000))
1859 fi
1860 ;;
1861 *[!0-9]*|0*)
1862 error >&7 "invalid port number: $port"
1863 ;;
1864 *)
1865 # The user has specified the port.
1866 ;;
1867 esac
1868
1869 # Make sure that parallel '--stress' test jobs get different
1870 # ports.
1871 port=$(($port + ${GIT_TEST_STRESS_JOB_NR:-0}))
1872 eval $var=$port
1873 }
1874
1875 # Tests for the hidden file attribute on Windows
1876 test_path_is_hidden () {
1877 test_have_prereq MINGW ||
1878 BUG "test_path_is_hidden can only be used on Windows"
1879
1880 # Use the output of `attrib`, ignore the absolute path
1881 case "$("$SYSTEMROOT"/system32/attrib "$1")" in *H*?:*) return 0;; esac
1882 return 1
1883 }
1884
1885 # Poor man's URI escaping. Good enough for the test suite whose trash
1886 # directory has a space in it. See 93c3fcbe4d4 (git-svn: attempt to
1887 # mimic SVN 1.7 URL canonicalization, 2012-07-28) for prior art.
1888 test_uri_escape() {
1889 sed 's/ /%20/g'
1890 }
1891
1892 # Check that the given command was invoked as part of the
1893 # trace2-format trace on stdin.
1894 #
1895 # test_subcommand [!] <command> <args>... < <trace>
1896 #
1897 # For example, to look for an invocation of "git upload-pack
1898 # /path/to/repo"
1899 #
1900 # GIT_TRACE2_EVENT=event.log git fetch ... &&
1901 # test_subcommand git upload-pack "$PATH" <event.log
1902 #
1903 # If the first parameter passed is !, this instead checks that
1904 # the given command was not called.
1905 #
1906 test_subcommand () {
1907 local negate=
1908 if test "$1" = "!"
1909 then
1910 negate=t
1911 shift
1912 fi
1913
1914 local expr="$(printf '"%s",' "$@")"
1915 expr="${expr%,}"
1916
1917 if test -n "$negate"
1918 then
1919 ! grep "\[$expr\]"
1920 else
1921 grep "\[$expr\]"
1922 fi
1923 }
1924
1925 # Check that the given subcommand was run with the given set of
1926 # arguments in order (but with possible extra arguments).
1927 #
1928 # test_subcommand_flex [!] <command> <args>... < <trace>
1929 #
1930 # If the first parameter passed is !, this instead checks that
1931 # the given command was not called.
1932 #
1933 test_subcommand_flex () {
1934 local negate=
1935 if test "$1" = "!"
1936 then
1937 negate=t
1938 shift
1939 fi
1940
1941 local expr="$(printf '"%s".*' "$@")"
1942
1943 if test -n "$negate"
1944 then
1945 ! grep "\[$expr\]"
1946 else
1947 grep "\[$expr\]"
1948 fi
1949 }
1950
1951 # Check that the given command was invoked as part of the
1952 # trace2-format trace on stdin.
1953 #
1954 # test_region [!] <category> <label> git <command> <args>...
1955 #
1956 # For example, to look for trace2_region_enter("index", "do_read_index", repo)
1957 # in an invocation of "git checkout HEAD~1", run
1958 #
1959 # GIT_TRACE2_EVENT="$(pwd)/trace.txt" GIT_TRACE2_EVENT_NESTING=10 \
1960 # git checkout HEAD~1 &&
1961 # test_region index do_read_index <trace.txt
1962 #
1963 # If the first parameter passed is !, this instead checks that
1964 # the given region was not entered.
1965 #
1966 test_region () {
1967 local expect_exit=0
1968 if test "$1" = "!"
1969 then
1970 expect_exit=1
1971 shift
1972 fi
1973
1974 grep -e '"region_enter".*"category":"'"$1"'","label":"'"$2"\" "$3"
1975 exitcode=$?
1976
1977 if test $exitcode != $expect_exit
1978 then
1979 return 1
1980 fi
1981
1982 grep -e '"region_leave".*"category":"'"$1"'","label":"'"$2"\" "$3"
1983 exitcode=$?
1984
1985 if test $exitcode != $expect_exit
1986 then
1987 return 1
1988 fi
1989
1990 return 0
1991 }
1992
1993 # Check that the given data fragment was included as part of the
1994 # trace2-format trace on stdin.
1995 #
1996 # test_trace2_data <category> <key> <value>
1997 #
1998 # For example, to look for trace2_data_intmax("pack-objects", repo,
1999 # "reused", N) in an invocation of "git pack-objects", run:
2000 #
2001 # GIT_TRACE2_EVENT="$(pwd)/trace.txt" git pack-objects ... &&
2002 # test_trace2_data pack-objects reused N <trace2.txt
2003 test_trace2_data () {
2004 grep -e '"category":"'"$1"'","key":"'"$2"'","value":"'"$3"'"'
2005 }
2006
2007 # Given a GIT_TRACE2_EVENT log over stdin, writes to stdout a list of URLs
2008 # sent to git-remote-https child processes.
2009 test_remote_https_urls() {
2010 grep -e '"event":"child_start".*"argv":\["git-remote-https",".*"\]' |
2011 sed -e 's/{"event":"child_start".*"argv":\["git-remote-https","//g' \
2012 -e 's/"\]}//g'
2013 }
2014
2015 # Print the destination of symlink(s) provided as arguments. Basically
2016 # the same as the readlink command, but it's not available everywhere.
2017 test_readlink () {
2018 test-tool path-utils readlink "$@"
2019 }
2020
2021 # Set mtime to a fixed "magic" timestamp in mid February 2009, before we
2022 # run an operation that may or may not touch the file. If the file was
2023 # touched, its timestamp will not accidentally have such an old timestamp,
2024 # as long as your filesystem clock is reasonably correct. To verify the
2025 # timestamp, follow up with test_is_magic_mtime.
2026 #
2027 # An optional increment to the magic timestamp may be specified as second
2028 # argument.
2029 test_set_magic_mtime () {
2030 local inc="${2:-0}" &&
2031 local mtime=$((1234567890 + $inc)) &&
2032 test-tool chmtime =$mtime "$1" &&
2033 test_is_magic_mtime "$1" $inc
2034 }
2035
2036 # Test whether the given file has the "magic" mtime set. This is meant to
2037 # be used in combination with test_set_magic_mtime.
2038 #
2039 # An optional increment to the magic timestamp may be specified as second
2040 # argument. Usually, this should be the same increment which was used for
2041 # the associated test_set_magic_mtime.
2042 test_is_magic_mtime () {
2043 local inc="${2:-0}" &&
2044 local mtime=$((1234567890 + $inc)) &&
2045 echo $mtime >.git/test-mtime-expect &&
2046 test-tool chmtime --get "$1" >.git/test-mtime-actual &&
2047 test_cmp .git/test-mtime-expect .git/test-mtime-actual
2048 local ret=$?
2049 rm -f .git/test-mtime-expect
2050 rm -f .git/test-mtime-actual
2051 return $ret
2052 }
2053
2054 # Given two filenames, parse both using 'git config --list --file'
2055 # and compare the sorted output of those commands. Useful when
2056 # wanting to ignore whitespace differences and sorting concerns.
2057 test_cmp_config_output () {
2058 git config --list --file="$1" >config-expect &&
2059 git config --list --file="$2" >config-actual &&
2060 sort config-expect >sorted-expect &&
2061 sort config-actual >sorted-actual &&
2062 test_cmp sorted-expect sorted-actual
2063 }
2064
2065 # Given a filename, extract its trailing hash as a hex string
2066 test_trailing_hash () {
2067 local file="$1" &&
2068 tail -c $(test_oid rawsz) "$file" |
2069 test-tool hexdump |
2070 sed "s/ //g"
2071 }
2072
2073 # Trim and replace each character with ascii code below 32 or above
2074 # 127 (included) using a dot '.' character.
2075 # Octal intervals \001-\040 and \177-\377
2076 # correspond to decimal intervals 1-32 and 127-255
2077 test_redact_non_printables () {
2078 tr -d "\n\r" | tr "[\001-\040][\177-\377]" "."
2079 }
2080
2081 # Remove .gitconfig entries from a file in place. test-lib.sh may
2082 # create $HOME/.gitconfig (e.g. to set safe.bareRepository) which
2083 # can appear in ls-files or status output.
2084 test_filter_gitconfig () {
2085 sed "/\\.gitconfig/d" "$1" >"$1.filtered" &&
2086 mv "$1.filtered" "$1"
2087 }