interplane.Get Omega
Read in your language

git

[Ported from github.com/git/git] Sync with Git 2.56.1

Brought by drakestapleton

branch master Branches Tags History

git / t / test-lib-functions.sh

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