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 # Compare paths respecting core.ignoreCase
1437 test_cmp_fspath () {
1438 if test "x$1" = "x$2"
1439 then
1440 return 0
1441 fi
1442
1443 if test true != "$(git config --get --type=bool core.ignorecase)"
1444 then
1445 return 1
1446 fi
1447
1448 test "x$(echo "$1" | tr A-Z a-z)" = "x$(echo "$2" | tr A-Z a-z)"
1449 }
1450
1451 # Print a sequence of integers in increasing order, either with
1452 # two arguments (start and end):
1453 #
1454 # test_seq 1 5 -- outputs 1 2 3 4 5 one line at a time
1455 #
1456 # or with one argument (end), in which case it starts counting
1457 # from 1. In addition to the start/end arguments, you can pass an optional
1458 # printf format. For example:
1459 #
1460 # test_seq -f "line %d" 1 5
1461 #
1462 # would print 5 lines, "line 1" through "line 5".
1463
1464 test_seq () {
1465 local fmt="%d"
1466 case "$1" in
1467 -f)
1468 fmt="$2"
1469 shift 2
1470 ;;
1471 esac
1472 case $# in
1473 1) set 1 "$@" ;;
1474 2) ;;
1475 *) BUG "not 1 or 2 parameters to test_seq" ;;
1476 esac
1477 test_seq_counter__=$1
1478 while test "$test_seq_counter__" -le "$2"
1479 do
1480 printf "$fmt\n" "$test_seq_counter__"
1481 test_seq_counter__=$(( $test_seq_counter__ + 1 ))
1482 done
1483 }
1484
1485 # This function can be used to schedule some commands to be run
1486 # unconditionally at the end of the test to restore sanity:
1487 #
1488 # test_expect_success 'test core.capslock' '
1489 # git config core.capslock true &&
1490 # test_when_finished "git config --unset core.capslock" &&
1491 # hello world
1492 # '
1493 #
1494 # That would be roughly equivalent to
1495 #
1496 # test_expect_success 'test core.capslock' '
1497 # git config core.capslock true &&
1498 # hello world
1499 # git config --unset core.capslock
1500 # '
1501 #
1502 # except that the greeting and config --unset must both succeed for
1503 # the test to pass.
1504 #
1505 # Note that under --immediate mode, no clean-up is done to help diagnose
1506 # what went wrong.
1507
1508 test_when_finished () {
1509 # We cannot detect when we are in a subshell in general, but by
1510 # doing so on Bash is better than nothing (the test will
1511 # silently pass on other shells).
1512 test "${BASH_SUBSHELL-0}" = 0 ||
1513 BUG "test_when_finished does nothing in a subshell"
1514 test_cleanup="{ $*
1515 } || eval_ret=\$?; $test_cleanup"
1516 }
1517
1518 # This function can be used to schedule some commands to be run
1519 # unconditionally at the end of the test script, e.g. to stop a daemon:
1520 #
1521 # test_expect_success 'test git daemon' '
1522 # git daemon &
1523 # daemon_pid=$! &&
1524 # test_atexit 'kill $daemon_pid' &&
1525 # hello world
1526 # '
1527 #
1528 # The commands will be executed before the trash directory is removed,
1529 # i.e. the atexit commands will still be able to access any pidfiles or
1530 # socket files.
1531 #
1532 # Note that these commands will be run even when a test script run
1533 # with '--immediate' fails. Be careful with your atexit commands to
1534 # minimize any changes to the failed state.
1535
1536 test_atexit () {
1537 # We cannot detect when we are in a subshell in general, but by
1538 # doing so on Bash is better than nothing (the test will
1539 # silently pass on other shells).
1540 test "${BASH_SUBSHELL-0}" = 0 ||
1541 BUG "test_atexit does nothing in a subshell"
1542 test_atexit_cleanup="{ $*
1543 } || eval_ret=\$?; $test_atexit_cleanup"
1544 }
1545
1546 # Deprecated wrapper for "git init", use "git init" directly instead
1547 # Usage: test_create_repo <directory>
1548 test_create_repo () {
1549 git init "$@"
1550 }
1551
1552 # This function helps on symlink challenged file systems when it is not
1553 # important that the file system entry is a symbolic link.
1554 # Use test_ln_s_add instead of "ln -s x y && git add y" to add a
1555 # symbolic link entry y to the index.
1556
1557 test_ln_s_add () {
1558 if test_have_prereq SYMLINKS
1559 then
1560 ln -s "$1" "$2" &&
1561 git update-index --add "$2"
1562 else
1563 printf '%s' "$1" >"$2" &&
1564 ln_s_obj=$(git hash-object -w "$2") &&
1565 git update-index --add --cacheinfo 120000 $ln_s_obj "$2" &&
1566 # pick up stat info from the file
1567 git update-index "$2"
1568 fi
1569 }
1570
1571 # This function writes out its parameters, one per line
1572 test_write_lines () {
1573 printf "%s\n" "$@"
1574 }
1575
1576 perl () {
1577 command "$PERL_PATH" "$@" 2>&7
1578 } 7>&2 2>&4
1579
1580 # Given the name of an environment variable with a bool value, normalize
1581 # its value to a 0 (true) or 1 (false or empty string) return code.
1582 #
1583 # test_bool_env GIT_TEST_HTTPD <default-value>
1584 #
1585 # Return with code corresponding to the given default value if the variable
1586 # is unset.
1587 # Abort the test script if either the value of the variable or the default
1588 # are not valid bool values.
1589
1590 test_bool_env () {
1591 if test $# != 2
1592 then
1593 BUG "test_bool_env requires two parameters (variable name and default value)"
1594 fi
1595
1596 test-tool env-helper --type=bool --default="$2" --exit-code "$1"
1597 ret=$?
1598 case $ret in
1599 0|1) # unset or valid bool value
1600 ;;
1601 *) # invalid bool value or something unexpected
1602 error >&7 "test_bool_env requires bool values both for \$$1 and for the default fallback"
1603 ;;
1604 esac
1605 return $ret
1606 }
1607
1608 # Exit the test suite, either by skipping all remaining tests or by
1609 # exiting with an error. If our prerequisite variable $1 falls back
1610 # on a default assume we were opportunistically trying to set up some
1611 # tests and we skip. If it is explicitly "true", then we report a failure.
1612 #
1613 # The error/skip message should be given by $2.
1614 #
1615 test_skip_or_die () {
1616 if ! test_bool_env "$1" false
1617 then
1618 skip_all=$2
1619 test_done
1620 fi
1621 error "$2"
1622 }
1623
1624 # Like "env FOO=BAR some-program", but run inside a subshell, which means
1625 # it also works for shell functions (though those functions cannot impact
1626 # the environment outside of the test_env invocation).
1627 test_env () {
1628 (
1629 while test $# -gt 0
1630 do
1631 case "$1" in
1632 *=*)
1633 eval "${1%%=*}=\${1#*=}"
1634 eval "export ${1%%=*}"
1635 shift
1636 ;;
1637 *)
1638 "$@" 2>&7
1639 exit
1640 ;;
1641 esac
1642 done
1643 )
1644 } 7>&2 2>&4
1645
1646 # Returns true if the numeric exit code in "$2" represents the expected signal
1647 # in "$1". Signals should be given numerically.
1648 test_match_signal () {
1649 if test "$2" = "$((128 + $1))"
1650 then
1651 # POSIX
1652 return 0
1653 elif test "$2" = "$((256 + $1))"
1654 then
1655 # ksh
1656 return 0
1657 fi
1658 return 1
1659 }
1660
1661 # Read up to "$1" bytes (or to EOF) from stdin and write them to stdout.
1662 test_copy_bytes () {
1663 dd ibs=1 count="$1" 2>/dev/null
1664 }
1665
1666 # run "$@" inside a non-git directory
1667 nongit () {
1668 test -d non-repo ||
1669 mkdir non-repo ||
1670 return 1
1671
1672 (
1673 GIT_CEILING_DIRECTORIES=$(pwd) &&
1674 export GIT_CEILING_DIRECTORIES &&
1675 cd non-repo &&
1676 "$@" 2>&7
1677 )
1678 } 7>&2 2>&4
1679
1680 # These functions are historical wrappers around "test-tool pkt-line"
1681 # for older tests. Use "test-tool pkt-line" itself in new tests.
1682 packetize () {
1683 if test $# -gt 0
1684 then
1685 packet="$*"
1686 printf '%04x%s' "$((4 + ${#packet}))" "$packet"
1687 else
1688 test-tool pkt-line pack
1689 fi
1690 }
1691
1692 packetize_raw () {
1693 test-tool pkt-line pack-raw-stdin
1694 }
1695
1696 depacketize () {
1697 test-tool pkt-line unpack
1698 }
1699
1700 # Converts base-16 data into base-8. The output is given as a sequence of
1701 # escaped octals, suitable for consumption by 'printf'.
1702 hex2oct () {
1703 perl -ne 'printf "\\%03o", hex for /../g'
1704 }
1705
1706 # Set the hash algorithm in use to $1. Only useful when testing the testsuite.
1707 test_set_hash () {
1708 test_hash_algo="$1"
1709 }
1710
1711 # Detect the hash algorithm in use.
1712 test_detect_hash () {
1713 case "${GIT_TEST_DEFAULT_HASH:-$GIT_TEST_BUILTIN_HASH}" in
1714 *:*)
1715 test_hash_algo="${GIT_TEST_DEFAULT_HASH%%:*}"
1716 test_compat_hash_algo="${GIT_TEST_DEFAULT_HASH##*:}"
1717 test_repo_compat_hash_algo="$test_compat_hash_algo"
1718 ;;
1719 sha256)
1720 test_hash_algo=sha256
1721 test_compat_hash_algo=sha1
1722 ;;
1723 sha1)
1724 test_hash_algo=sha1
1725 test_compat_hash_algo=sha256
1726 ;;
1727 esac
1728 }
1729
1730 # Detect the ref format in use.
1731 test_detect_ref_format () {
1732 echo "${GIT_TEST_DEFAULT_REF_FORMAT:-files}"
1733 }
1734
1735 # Load common hash metadata and common placeholder object IDs for use with
1736 # test_oid.
1737 test_oid_init () {
1738 test -n "$test_hash_algo" || test_detect_hash &&
1739 test_oid_cache <"$TEST_DIRECTORY/oid-info/hash-info" &&
1740 test_oid_cache <"$TEST_DIRECTORY/oid-info/oid"
1741 }
1742
1743 # Load key-value pairs from stdin suitable for use with test_oid. Blank lines
1744 # and lines starting with "#" are ignored. Keys must be shell identifier
1745 # characters.
1746 #
1747 # Examples:
1748 # rawsz sha1:20
1749 # rawsz sha256:32
1750 test_oid_cache () {
1751 local tag rest k v &&
1752
1753 { test -n "$test_hash_algo" || test_detect_hash; } &&
1754 while read tag rest
1755 do
1756 case $tag in
1757 \#*)
1758 continue;;
1759 ?*)
1760 # non-empty
1761 ;;
1762 *)
1763 # blank line
1764 continue;;
1765 esac &&
1766
1767 k="${rest%:*}" &&
1768 v="${rest#*:}" &&
1769
1770 if ! expr "$k" : '[a-z0-9][a-z0-9]*$' >/dev/null
1771 then
1772 BUG 'bad hash algorithm'
1773 fi &&
1774 eval "test_oid_${k}_$tag=\"\$v\""
1775 done
1776 }
1777
1778 # Look up a per-hash value based on a key ($1). The value must have been loaded
1779 # by test_oid_init or test_oid_cache.
1780 test_oid () {
1781 local algo="${test_hash_algo}" &&
1782
1783 case "$1" in
1784 --hash=storage)
1785 algo="$test_hash_algo" &&
1786 shift;;
1787 --hash=compat)
1788 algo="$test_compat_hash_algo" &&
1789 shift;;
1790 --hash=builtin)
1791 algo="$GIT_TEST_BUILTIN_HASH" &&
1792 shift;;
1793 --hash=*)
1794 algo="${1#--hash=}" &&
1795 shift;;
1796 *)
1797 ;;
1798 esac &&
1799
1800 local var="test_oid_${algo}_$1" &&
1801
1802 # If the variable is unset, we must be missing an entry for this
1803 # key-hash pair, so exit with an error.
1804 if eval "test -z \"\${$var+set}\""
1805 then
1806 BUG "undefined key '$1'"
1807 fi &&
1808 eval "printf '%s\n' \"\${$var}\""
1809 }
1810
1811 # Insert a slash into an object ID so it can be used to reference a location
1812 # under ".git/objects". For example, "deadbeef..." becomes "de/adbeef..".
1813 test_oid_to_path () {
1814 local basename="${1#??}"
1815 echo "${1%$basename}/$basename"
1816 }
1817
1818 # Parse oids from git ls-files --staged output
1819 test_parse_ls_files_stage_oids () {
1820 awk '{print $2}' -
1821 }
1822
1823 # Parse oids from git ls-tree output
1824 test_parse_ls_tree_oids () {
1825 awk '{print $3}' -
1826 }
1827
1828 # Choose a port number based on the test script's number and store it in
1829 # the given variable name, unless that variable already contains a number.
1830 test_set_port () {
1831 local var="$1" port
1832
1833 if test $# -ne 1 || test -z "$var"
1834 then
1835 BUG "test_set_port requires a variable name"
1836 fi
1837
1838 eval port=\$$var
1839 case "$port" in
1840 "")
1841 # No port is set in the given env var, use the test
1842 # number as port number instead.
1843 # Remove not only the leading 't', but all leading zeros
1844 # as well, so the arithmetic below won't (mis)interpret
1845 # a test number like '0123' as an octal value.
1846 port=${this_test#${this_test%%[1-9]*}}
1847 if test "${port:-0}" -lt 1024
1848 then
1849 # root-only port, use a larger one instead.
1850 port=$(($port + 10000))
1851 fi
1852 ;;
1853 *[!0-9]*|0*)
1854 error >&7 "invalid port number: $port"
1855 ;;
1856 *)
1857 # The user has specified the port.
1858 ;;
1859 esac
1860
1861 # Make sure that parallel '--stress' test jobs get different
1862 # ports.
1863 port=$(($port + ${GIT_TEST_STRESS_JOB_NR:-0}))
1864 eval $var=$port
1865 }
1866
1867 # Tests for the hidden file attribute on Windows
1868 test_path_is_hidden () {
1869 test_have_prereq MINGW ||
1870 BUG "test_path_is_hidden can only be used on Windows"
1871
1872 # Use the output of `attrib`, ignore the absolute path
1873 case "$("$SYSTEMROOT"/system32/attrib "$1")" in *H*?:*) return 0;; esac
1874 return 1
1875 }
1876
1877 # Poor man's URI escaping. Good enough for the test suite whose trash
1878 # directory has a space in it. See 93c3fcbe4d4 (git-svn: attempt to
1879 # mimic SVN 1.7 URL canonicalization, 2012-07-28) for prior art.
1880 test_uri_escape() {
1881 sed 's/ /%20/g'
1882 }
1883
1884 # Check that the given command was invoked as part of the
1885 # trace2-format trace on stdin.
1886 #
1887 # test_subcommand [!] <command> <args>... < <trace>
1888 #
1889 # For example, to look for an invocation of "git upload-pack
1890 # /path/to/repo"
1891 #
1892 # GIT_TRACE2_EVENT=event.log git fetch ... &&
1893 # test_subcommand git upload-pack "$PATH" <event.log
1894 #
1895 # If the first parameter passed is !, this instead checks that
1896 # the given command was not called.
1897 #
1898 test_subcommand () {
1899 local negate=
1900 if test "$1" = "!"
1901 then
1902 negate=t
1903 shift
1904 fi
1905
1906 local expr="$(printf '"%s",' "$@")"
1907 expr="${expr%,}"
1908
1909 if test -n "$negate"
1910 then
1911 ! grep "\[$expr\]"
1912 else
1913 grep "\[$expr\]"
1914 fi
1915 }
1916
1917 # Check that the given subcommand was run with the given set of
1918 # arguments in order (but with possible extra arguments).
1919 #
1920 # test_subcommand_flex [!] <command> <args>... < <trace>
1921 #
1922 # If the first parameter passed is !, this instead checks that
1923 # the given command was not called.
1924 #
1925 test_subcommand_flex () {
1926 local negate=
1927 if test "$1" = "!"
1928 then
1929 negate=t
1930 shift
1931 fi
1932
1933 local expr="$(printf '"%s".*' "$@")"
1934
1935 if test -n "$negate"
1936 then
1937 ! grep "\[$expr\]"
1938 else
1939 grep "\[$expr\]"
1940 fi
1941 }
1942
1943 # Check that the given command was invoked as part of the
1944 # trace2-format trace on stdin.
1945 #
1946 # test_region [!] <category> <label> git <command> <args>...
1947 #
1948 # For example, to look for trace2_region_enter("index", "do_read_index", repo)
1949 # in an invocation of "git checkout HEAD~1", run
1950 #
1951 # GIT_TRACE2_EVENT="$(pwd)/trace.txt" GIT_TRACE2_EVENT_NESTING=10 \
1952 # git checkout HEAD~1 &&
1953 # test_region index do_read_index <trace.txt
1954 #
1955 # If the first parameter passed is !, this instead checks that
1956 # the given region was not entered.
1957 #
1958 test_region () {
1959 local expect_exit=0
1960 if test "$1" = "!"
1961 then
1962 expect_exit=1
1963 shift
1964 fi
1965
1966 grep -e '"region_enter".*"category":"'"$1"'","label":"'"$2"\" "$3"
1967 exitcode=$?
1968
1969 if test $exitcode != $expect_exit
1970 then
1971 return 1
1972 fi
1973
1974 grep -e '"region_leave".*"category":"'"$1"'","label":"'"$2"\" "$3"
1975 exitcode=$?
1976
1977 if test $exitcode != $expect_exit
1978 then
1979 return 1
1980 fi
1981
1982 return 0
1983 }
1984
1985 # Check that the given data fragment was included as part of the
1986 # trace2-format trace on stdin.
1987 #
1988 # test_trace2_data <category> <key> <value>
1989 #
1990 # For example, to look for trace2_data_intmax("pack-objects", repo,
1991 # "reused", N) in an invocation of "git pack-objects", run:
1992 #
1993 # GIT_TRACE2_EVENT="$(pwd)/trace.txt" git pack-objects ... &&
1994 # test_trace2_data pack-objects reused N <trace2.txt
1995 test_trace2_data () {
1996 grep -e '"category":"'"$1"'","key":"'"$2"'","value":"'"$3"'"'
1997 }
1998
1999 # Check that the given trace2 data event has the expected value and
2000 # appears exactly once. Produces a diagnostic on failure.
2001 #
2002 # test_trace2_data_singular <category> <key> <value> [<label>]
2003 test_trace2_data_singular () {
2004 local category="$1" key="$2" expect_val="$3"
2005 local label_suffix="${4:+ [$4]}"
2006 local kv_pattern='"category":"'"$category"'","key":"'"$key"'","value":"\([^"]*\)"'
2007 local actual
2008
2009 actual=$(sed -n "s|.*${kv_pattern}.*|\1|p") &&
2010
2011 if test -z "$actual"
2012 then
2013 echo >&4 "error: trace2 data '$category/$key'$label_suffix not found"
2014 return 1
2015 fi &&
2016
2017 case "$actual" in
2018 *"
2019 "*)
2020 echo >&4 "error: trace2 data '$category/$key'$label_suffix has multiple entries, expected 1"
2021 printf '%s\n' "$actual" | sed 's/^/ actual: /' >&4
2022 return 1
2023 ;;
2024 esac &&
2025
2026 if test "$actual" != "$expect_val"
2027 then
2028 echo >&4 "error: trace2 data '$category/$key'$label_suffix"
2029 echo >&4 " expected: $expect_val"
2030 echo >&4 " actual: $actual"
2031 return 1
2032 fi
2033 }
2034
2035 # Given a GIT_TRACE2_EVENT log over stdin, writes to stdout a list of URLs
2036 # sent to git-remote-https child processes.
2037 test_remote_https_urls() {
2038 grep -e '"event":"child_start".*"argv":\["git-remote-https",".*"\]' |
2039 sed -e 's/{"event":"child_start".*"argv":\["git-remote-https","//g' \
2040 -e 's/"\]}//g'
2041 }
2042
2043 # Print the destination of symlink(s) provided as arguments. Basically
2044 # the same as the readlink command, but it's not available everywhere.
2045 test_readlink () {
2046 test-tool path-utils readlink "$@"
2047 }
2048
2049 # Set mtime to a fixed "magic" timestamp in mid February 2009, before we
2050 # run an operation that may or may not touch the file. If the file was
2051 # touched, its timestamp will not accidentally have such an old timestamp,
2052 # as long as your filesystem clock is reasonably correct. To verify the
2053 # timestamp, follow up with test_is_magic_mtime.
2054 #
2055 # An optional increment to the magic timestamp may be specified as second
2056 # argument.
2057 test_set_magic_mtime () {
2058 local inc="${2:-0}" &&
2059 local mtime=$((1234567890 + $inc)) &&
2060 test-tool chmtime =$mtime "$1" &&
2061 test_is_magic_mtime "$1" $inc
2062 }
2063
2064 # Test whether the given file has the "magic" mtime set. This is meant to
2065 # be used in combination with test_set_magic_mtime.
2066 #
2067 # An optional increment to the magic timestamp may be specified as second
2068 # argument. Usually, this should be the same increment which was used for
2069 # the associated test_set_magic_mtime.
2070 test_is_magic_mtime () {
2071 local inc="${2:-0}" &&
2072 local mtime=$((1234567890 + $inc)) &&
2073 echo $mtime >.git/test-mtime-expect &&
2074 test-tool chmtime --get "$1" >.git/test-mtime-actual &&
2075 test_cmp .git/test-mtime-expect .git/test-mtime-actual
2076 local ret=$?
2077 rm -f .git/test-mtime-expect
2078 rm -f .git/test-mtime-actual
2079 return $ret
2080 }
2081
2082 # Given two filenames, parse both using 'git config --list --file'
2083 # and compare the sorted output of those commands. Useful when
2084 # wanting to ignore whitespace differences and sorting concerns.
2085 test_cmp_config_output () {
2086 git config --list --file="$1" >config-expect &&
2087 git config --list --file="$2" >config-actual &&
2088 sort config-expect >sorted-expect &&
2089 sort config-actual >sorted-actual &&
2090 test_cmp sorted-expect sorted-actual
2091 }
2092
2093 # Given a filename, extract its trailing hash as a hex string
2094 test_trailing_hash () {
2095 local file="$1" &&
2096 tail -c $(test_oid rawsz) "$file" |
2097 test-tool hexdump |
2098 sed "s/ //g"
2099 }
2100
2101 # Trim and replace each character with ascii code below 32 or above
2102 # 127 (included) using a dot '.' character.
2103 # Octal intervals \001-\040 and \177-\377
2104 # correspond to decimal intervals 1-32 and 127-255
2105 test_redact_non_printables () {
2106 tr -d "\n\r" | tr "[\001-\040][\177-\377]" "."
2107 }
2108
2109 # Remove .gitconfig entries from a file in place. test-lib.sh may
2110 # create $HOME/.gitconfig (e.g. to set safe.bareRepository) which
2111 # can appear in ls-files or status output.
2112 test_filter_gitconfig () {
2113 sed "/\\.gitconfig/d" "$1" >"$1.filtered" &&
2114 mv "$1.filtered" "$1"
2115 }