From 68c806e581d458fed87d90045672d3a183ce9df6 Mon Sep 17 00:00:00 2001 From: Mitchell Hashimoto Date: Tue, 28 Sep 2021 08:49:18 -0700 Subject: [PATCH 1/6] internal/config/funcs: git-commits-changes testdata --- .../funcs/testdata/git-commits-changes/A | 1 + .../git-commits-changes/DOTgit/COMMIT_EDITMSG | 8 + .../testdata/git-commits-changes/DOTgit/HEAD | 1 + .../git-commits-changes/DOTgit/config | 7 + .../git-commits-changes/DOTgit/description | 1 + .../DOTgit/hooks/applypatch-msg.sample | 15 ++ .../DOTgit/hooks/commit-msg.sample | 24 +++ .../DOTgit/hooks/fsmonitor-watchman.sample | 173 ++++++++++++++++++ .../DOTgit/hooks/post-update.sample | 8 + .../DOTgit/hooks/pre-applypatch.sample | 14 ++ .../DOTgit/hooks/pre-commit.sample | 49 +++++ .../DOTgit/hooks/pre-merge-commit.sample | 13 ++ .../DOTgit/hooks/pre-push.sample | 53 ++++++ .../DOTgit/hooks/pre-rebase.sample | 169 +++++++++++++++++ .../DOTgit/hooks/pre-receive.sample | 24 +++ .../DOTgit/hooks/prepare-commit-msg.sample | 42 +++++ .../DOTgit/hooks/update.sample | 128 +++++++++++++ .../testdata/git-commits-changes/DOTgit/index | Bin 0 -> 129 bytes .../git-commits-changes/DOTgit/info/exclude | 6 + .../git-commits-changes/DOTgit/logs/HEAD | 2 + .../DOTgit/logs/refs/heads/master | 2 + .../38/0afd697abe993b89bfa08d8dd8724d6a513ba1 | Bin 0 -> 825 bytes .../45/9023a450b8e8aa344d230839d41e2f115d3d28 | Bin 0 -> 46 bytes .../7c/178d1296d8b87e83382c324aeb32e2def2a5af | Bin 0 -> 46 bytes .../8b/137891791fe96927ad78e64b0aad7bded08bdc | Bin 0 -> 16 bytes .../b1/a2dcd337f590a185a20f013721e7410764bab4 | Bin 0 -> 791 bytes .../e6/9de29bb2d1d6434b8b29ae775ad8c2e48c5391 | Bin 0 -> 15 bytes .../DOTgit/refs/heads/master | 1 + .../git-commits-changes/untracked_file | 0 29 files changed, 741 insertions(+) create mode 100644 internal/config/funcs/testdata/git-commits-changes/A create mode 100644 internal/config/funcs/testdata/git-commits-changes/DOTgit/COMMIT_EDITMSG create mode 100644 internal/config/funcs/testdata/git-commits-changes/DOTgit/HEAD create mode 100644 internal/config/funcs/testdata/git-commits-changes/DOTgit/config create mode 100644 internal/config/funcs/testdata/git-commits-changes/DOTgit/description create mode 100755 internal/config/funcs/testdata/git-commits-changes/DOTgit/hooks/applypatch-msg.sample create mode 100755 internal/config/funcs/testdata/git-commits-changes/DOTgit/hooks/commit-msg.sample create mode 100755 internal/config/funcs/testdata/git-commits-changes/DOTgit/hooks/fsmonitor-watchman.sample create mode 100755 internal/config/funcs/testdata/git-commits-changes/DOTgit/hooks/post-update.sample create mode 100755 internal/config/funcs/testdata/git-commits-changes/DOTgit/hooks/pre-applypatch.sample create mode 100755 internal/config/funcs/testdata/git-commits-changes/DOTgit/hooks/pre-commit.sample create mode 100755 internal/config/funcs/testdata/git-commits-changes/DOTgit/hooks/pre-merge-commit.sample create mode 100755 internal/config/funcs/testdata/git-commits-changes/DOTgit/hooks/pre-push.sample create mode 100755 internal/config/funcs/testdata/git-commits-changes/DOTgit/hooks/pre-rebase.sample create mode 100755 internal/config/funcs/testdata/git-commits-changes/DOTgit/hooks/pre-receive.sample create mode 100755 internal/config/funcs/testdata/git-commits-changes/DOTgit/hooks/prepare-commit-msg.sample create mode 100755 internal/config/funcs/testdata/git-commits-changes/DOTgit/hooks/update.sample create mode 100644 internal/config/funcs/testdata/git-commits-changes/DOTgit/index create mode 100644 internal/config/funcs/testdata/git-commits-changes/DOTgit/info/exclude create mode 100644 internal/config/funcs/testdata/git-commits-changes/DOTgit/logs/HEAD create mode 100644 internal/config/funcs/testdata/git-commits-changes/DOTgit/logs/refs/heads/master create mode 100644 internal/config/funcs/testdata/git-commits-changes/DOTgit/objects/38/0afd697abe993b89bfa08d8dd8724d6a513ba1 create mode 100644 internal/config/funcs/testdata/git-commits-changes/DOTgit/objects/45/9023a450b8e8aa344d230839d41e2f115d3d28 create mode 100644 internal/config/funcs/testdata/git-commits-changes/DOTgit/objects/7c/178d1296d8b87e83382c324aeb32e2def2a5af create mode 100644 internal/config/funcs/testdata/git-commits-changes/DOTgit/objects/8b/137891791fe96927ad78e64b0aad7bded08bdc create mode 100644 internal/config/funcs/testdata/git-commits-changes/DOTgit/objects/b1/a2dcd337f590a185a20f013721e7410764bab4 create mode 100644 internal/config/funcs/testdata/git-commits-changes/DOTgit/objects/e6/9de29bb2d1d6434b8b29ae775ad8c2e48c5391 create mode 100644 internal/config/funcs/testdata/git-commits-changes/DOTgit/refs/heads/master create mode 100644 internal/config/funcs/testdata/git-commits-changes/untracked_file diff --git a/internal/config/funcs/testdata/git-commits-changes/A b/internal/config/funcs/testdata/git-commits-changes/A new file mode 100644 index 00000000000..8b137891791 --- /dev/null +++ b/internal/config/funcs/testdata/git-commits-changes/A @@ -0,0 +1 @@ + diff --git a/internal/config/funcs/testdata/git-commits-changes/DOTgit/COMMIT_EDITMSG b/internal/config/funcs/testdata/git-commits-changes/DOTgit/COMMIT_EDITMSG new file mode 100644 index 00000000000..994ef5e43a2 --- /dev/null +++ b/internal/config/funcs/testdata/git-commits-changes/DOTgit/COMMIT_EDITMSG @@ -0,0 +1,8 @@ +Commit two +# Please enter the commit message for your changes. Lines starting +# with '#' will be ignored, and an empty message aborts the commit. +# +# On branch master +# Changes to be committed: +# modified: A +# diff --git a/internal/config/funcs/testdata/git-commits-changes/DOTgit/HEAD b/internal/config/funcs/testdata/git-commits-changes/DOTgit/HEAD new file mode 100644 index 00000000000..cb089cd89a7 --- /dev/null +++ b/internal/config/funcs/testdata/git-commits-changes/DOTgit/HEAD @@ -0,0 +1 @@ +ref: refs/heads/master diff --git a/internal/config/funcs/testdata/git-commits-changes/DOTgit/config b/internal/config/funcs/testdata/git-commits-changes/DOTgit/config new file mode 100644 index 00000000000..6c9406b7d93 --- /dev/null +++ b/internal/config/funcs/testdata/git-commits-changes/DOTgit/config @@ -0,0 +1,7 @@ +[core] + repositoryformatversion = 0 + filemode = true + bare = false + logallrefupdates = true + ignorecase = true + precomposeunicode = true diff --git a/internal/config/funcs/testdata/git-commits-changes/DOTgit/description b/internal/config/funcs/testdata/git-commits-changes/DOTgit/description new file mode 100644 index 00000000000..498b267a8c7 --- /dev/null +++ b/internal/config/funcs/testdata/git-commits-changes/DOTgit/description @@ -0,0 +1 @@ +Unnamed repository; edit this file 'description' to name the repository. diff --git a/internal/config/funcs/testdata/git-commits-changes/DOTgit/hooks/applypatch-msg.sample b/internal/config/funcs/testdata/git-commits-changes/DOTgit/hooks/applypatch-msg.sample new file mode 100755 index 00000000000..098d30088df --- /dev/null +++ b/internal/config/funcs/testdata/git-commits-changes/DOTgit/hooks/applypatch-msg.sample @@ -0,0 +1,15 @@ +#!/nix/store/ilgf30winx4zw3acm5pk79cvhzkjch0f-bash-4.4-p23/bin/bash +# +# An example hook script to check the commit log message taken by +# applypatch from an e-mail message. +# +# The hook should exit with non-zero status after issuing an +# appropriate message if it wants to stop the commit. The hook is +# allowed to edit the commit message file. +# +# To enable this hook, rename this file to "applypatch-msg". + +. git-sh-setup +commitmsg="$(git rev-parse --git-path hooks/commit-msg)" +test -x "$commitmsg" && exec "$commitmsg" ${1+"$@"} +: diff --git a/internal/config/funcs/testdata/git-commits-changes/DOTgit/hooks/commit-msg.sample b/internal/config/funcs/testdata/git-commits-changes/DOTgit/hooks/commit-msg.sample new file mode 100755 index 00000000000..f6aef4380b6 --- /dev/null +++ b/internal/config/funcs/testdata/git-commits-changes/DOTgit/hooks/commit-msg.sample @@ -0,0 +1,24 @@ +#!/nix/store/ilgf30winx4zw3acm5pk79cvhzkjch0f-bash-4.4-p23/bin/bash +# +# An example hook script to check the commit log message. +# Called by "git commit" with one argument, the name of the file +# that has the commit message. The hook should exit with non-zero +# status after issuing an appropriate message if it wants to stop the +# commit. The hook is allowed to edit the commit message file. +# +# To enable this hook, rename this file to "commit-msg". + +# Uncomment the below to add a Signed-off-by line to the message. +# Doing this in a hook is a bad idea in general, but the prepare-commit-msg +# hook is more suited to it. +# +# SOB=$(git var GIT_AUTHOR_IDENT | sed -n 's/^\(.*>\).*$/Signed-off-by: \1/p') +# grep -qs "^$SOB" "$1" || echo "$SOB" >> "$1" + +# This example catches duplicate Signed-off-by lines. + +test "" = "$(grep '^Signed-off-by: ' "$1" | + sort | uniq -c | sed -e '/^[ ]*1[ ]/d')" || { + echo >&2 Duplicate Signed-off-by lines. + exit 1 +} diff --git a/internal/config/funcs/testdata/git-commits-changes/DOTgit/hooks/fsmonitor-watchman.sample b/internal/config/funcs/testdata/git-commits-changes/DOTgit/hooks/fsmonitor-watchman.sample new file mode 100755 index 00000000000..0053addb85b --- /dev/null +++ b/internal/config/funcs/testdata/git-commits-changes/DOTgit/hooks/fsmonitor-watchman.sample @@ -0,0 +1,173 @@ +#!/nix/store/5mkw2nn6ghpadr95hic5l84vfp5xyana-perl-5.30.2/bin/perl + +use strict; +use warnings; +use IPC::Open2; + +# An example hook script to integrate Watchman +# (https://facebook.github.io/watchman/) with git to speed up detecting +# new and modified files. +# +# The hook is passed a version (currently 2) and last update token +# formatted as a string and outputs to stdout a new update token and +# all files that have been modified since the update token. Paths must +# be relative to the root of the working tree and separated by a single NUL. +# +# To enable this hook, rename this file to "query-watchman" and set +# 'git config core.fsmonitor .git/hooks/query-watchman' +# +my ($version, $last_update_token) = @ARGV; + +# Uncomment for debugging +# print STDERR "$0 $version $last_update_token\n"; + +# Check the hook interface version +if ($version ne 2) { + die "Unsupported query-fsmonitor hook version '$version'.\n" . + "Falling back to scanning...\n"; +} + +my $git_work_tree = get_working_dir(); + +my $retry = 1; + +my $json_pkg; +eval { + require JSON::XS; + $json_pkg = "JSON::XS"; + 1; +} or do { + require JSON::PP; + $json_pkg = "JSON::PP"; +}; + +launch_watchman(); + +sub launch_watchman { + my $o = watchman_query(); + if (is_work_tree_watched($o)) { + output_result($o->{clock}, @{$o->{files}}); + } +} + +sub output_result { + my ($clockid, @files) = @_; + + # Uncomment for debugging watchman output + # open (my $fh, ">", ".git/watchman-output.out"); + # binmode $fh, ":utf8"; + # print $fh "$clockid\n@files\n"; + # close $fh; + + binmode STDOUT, ":utf8"; + print $clockid; + print "\0"; + local $, = "\0"; + print @files; +} + +sub watchman_clock { + my $response = qx/watchman clock "$git_work_tree"/; + die "Failed to get clock id on '$git_work_tree'.\n" . + "Falling back to scanning...\n" if $? != 0; + + return $json_pkg->new->utf8->decode($response); +} + +sub watchman_query { + my $pid = open2(\*CHLD_OUT, \*CHLD_IN, 'watchman -j --no-pretty') + or die "open2() failed: $!\n" . + "Falling back to scanning...\n"; + + # In the query expression below we're asking for names of files that + # changed since $last_update_token but not from the .git folder. + # + # To accomplish this, we're using the "since" generator to use the + # recency index to select candidate nodes and "fields" to limit the + # output to file names only. Then we're using the "expression" term to + # further constrain the results. + if (substr($last_update_token, 0, 1) eq "c") { + $last_update_token = "\"$last_update_token\""; + } + my $query = <<" END"; + ["query", "$git_work_tree", { + "since": $last_update_token, + "fields": ["name"], + "expression": ["not", ["dirname", ".git"]] + }] + END + + # Uncomment for debugging the watchman query + # open (my $fh, ">", ".git/watchman-query.json"); + # print $fh $query; + # close $fh; + + print CHLD_IN $query; + close CHLD_IN; + my $response = do {local $/; }; + + # Uncomment for debugging the watch response + # open ($fh, ">", ".git/watchman-response.json"); + # print $fh $response; + # close $fh; + + die "Watchman: command returned no output.\n" . + "Falling back to scanning...\n" if $response eq ""; + die "Watchman: command returned invalid output: $response\n" . + "Falling back to scanning...\n" unless $response =~ /^\{/; + + return $json_pkg->new->utf8->decode($response); +} + +sub is_work_tree_watched { + my ($output) = @_; + my $error = $output->{error}; + if ($retry > 0 and $error and $error =~ m/unable to resolve root .* directory (.*) is not watched/) { + $retry--; + my $response = qx/watchman watch "$git_work_tree"/; + die "Failed to make watchman watch '$git_work_tree'.\n" . + "Falling back to scanning...\n" if $? != 0; + $output = $json_pkg->new->utf8->decode($response); + $error = $output->{error}; + die "Watchman: $error.\n" . + "Falling back to scanning...\n" if $error; + + # Uncomment for debugging watchman output + # open (my $fh, ">", ".git/watchman-output.out"); + # close $fh; + + # Watchman will always return all files on the first query so + # return the fast "everything is dirty" flag to git and do the + # Watchman query just to get it over with now so we won't pay + # the cost in git to look up each individual file. + my $o = watchman_clock(); + $error = $output->{error}; + + die "Watchman: $error.\n" . + "Falling back to scanning...\n" if $error; + + output_result($o->{clock}, ("/")); + $last_update_token = $o->{clock}; + + eval { launch_watchman() }; + return 0; + } + + die "Watchman: $error.\n" . + "Falling back to scanning...\n" if $error; + + return 1; +} + +sub get_working_dir { + my $working_dir; + if ($^O =~ 'msys' || $^O =~ 'cygwin') { + $working_dir = Win32::GetCwd(); + $working_dir =~ tr/\\/\//; + } else { + require Cwd; + $working_dir = Cwd::cwd(); + } + + return $working_dir; +} diff --git a/internal/config/funcs/testdata/git-commits-changes/DOTgit/hooks/post-update.sample b/internal/config/funcs/testdata/git-commits-changes/DOTgit/hooks/post-update.sample new file mode 100755 index 00000000000..7e659999e01 --- /dev/null +++ b/internal/config/funcs/testdata/git-commits-changes/DOTgit/hooks/post-update.sample @@ -0,0 +1,8 @@ +#!/nix/store/ilgf30winx4zw3acm5pk79cvhzkjch0f-bash-4.4-p23/bin/bash +# +# An example hook script to prepare a packed repository for use over +# dumb transports. +# +# To enable this hook, rename this file to "post-update". + +exec git update-server-info diff --git a/internal/config/funcs/testdata/git-commits-changes/DOTgit/hooks/pre-applypatch.sample b/internal/config/funcs/testdata/git-commits-changes/DOTgit/hooks/pre-applypatch.sample new file mode 100755 index 00000000000..364fcc17a39 --- /dev/null +++ b/internal/config/funcs/testdata/git-commits-changes/DOTgit/hooks/pre-applypatch.sample @@ -0,0 +1,14 @@ +#!/nix/store/ilgf30winx4zw3acm5pk79cvhzkjch0f-bash-4.4-p23/bin/bash +# +# An example hook script to verify what is about to be committed +# by applypatch from an e-mail message. +# +# The hook should exit with non-zero status after issuing an +# appropriate message if it wants to stop the commit. +# +# To enable this hook, rename this file to "pre-applypatch". + +. git-sh-setup +precommit="$(git rev-parse --git-path hooks/pre-commit)" +test -x "$precommit" && exec "$precommit" ${1+"$@"} +: diff --git a/internal/config/funcs/testdata/git-commits-changes/DOTgit/hooks/pre-commit.sample b/internal/config/funcs/testdata/git-commits-changes/DOTgit/hooks/pre-commit.sample new file mode 100755 index 00000000000..69588be6d53 --- /dev/null +++ b/internal/config/funcs/testdata/git-commits-changes/DOTgit/hooks/pre-commit.sample @@ -0,0 +1,49 @@ +#!/nix/store/ilgf30winx4zw3acm5pk79cvhzkjch0f-bash-4.4-p23/bin/bash +# +# An example hook script to verify what is about to be committed. +# Called by "git commit" with no arguments. The hook should +# exit with non-zero status after issuing an appropriate message if +# it wants to stop the commit. +# +# To enable this hook, rename this file to "pre-commit". + +if git rev-parse --verify HEAD >/dev/null 2>&1 +then + against=HEAD +else + # Initial commit: diff against an empty tree object + against=$(git hash-object -t tree /dev/null) +fi + +# If you want to allow non-ASCII filenames set this variable to true. +allownonascii=$(git config --type=bool hooks.allownonascii) + +# Redirect output to stderr. +exec 1>&2 + +# Cross platform projects tend to avoid non-ASCII filenames; prevent +# them from being added to the repository. We exploit the fact that the +# printable range starts at the space character and ends with tilde. +if [ "$allownonascii" != "true" ] && + # Note that the use of brackets around a tr range is ok here, (it's + # even required, for portability to Solaris 10's /usr/bin/tr), since + # the square bracket bytes happen to fall in the designated range. + test $(git diff --cached --name-only --diff-filter=A -z $against | + LC_ALL=C tr -d '[ -~]\0' | wc -c) != 0 +then + cat <<\EOF +Error: Attempt to add a non-ASCII file name. + +This can cause problems if you want to work with people on other platforms. + +To be portable it is advisable to rename the file. + +If you know what you are doing you can disable this check using: + + git config hooks.allownonascii true +EOF + exit 1 +fi + +# If there are whitespace errors, print the offending file names and fail. +exec git diff-index --check --cached $against -- diff --git a/internal/config/funcs/testdata/git-commits-changes/DOTgit/hooks/pre-merge-commit.sample b/internal/config/funcs/testdata/git-commits-changes/DOTgit/hooks/pre-merge-commit.sample new file mode 100755 index 00000000000..8b8dfcdb8a8 --- /dev/null +++ b/internal/config/funcs/testdata/git-commits-changes/DOTgit/hooks/pre-merge-commit.sample @@ -0,0 +1,13 @@ +#!/nix/store/ilgf30winx4zw3acm5pk79cvhzkjch0f-bash-4.4-p23/bin/bash +# +# An example hook script to verify what is about to be committed. +# Called by "git merge" with no arguments. The hook should +# exit with non-zero status after issuing an appropriate message to +# stderr if it wants to stop the merge commit. +# +# To enable this hook, rename this file to "pre-merge-commit". + +. git-sh-setup +test -x "$GIT_DIR/hooks/pre-commit" && + exec "$GIT_DIR/hooks/pre-commit" +: diff --git a/internal/config/funcs/testdata/git-commits-changes/DOTgit/hooks/pre-push.sample b/internal/config/funcs/testdata/git-commits-changes/DOTgit/hooks/pre-push.sample new file mode 100755 index 00000000000..85d9662acf2 --- /dev/null +++ b/internal/config/funcs/testdata/git-commits-changes/DOTgit/hooks/pre-push.sample @@ -0,0 +1,53 @@ +#!/nix/store/ilgf30winx4zw3acm5pk79cvhzkjch0f-bash-4.4-p23/bin/bash + +# An example hook script to verify what is about to be pushed. Called by "git +# push" after it has checked the remote status, but before anything has been +# pushed. If this script exits with a non-zero status nothing will be pushed. +# +# This hook is called with the following parameters: +# +# $1 -- Name of the remote to which the push is being done +# $2 -- URL to which the push is being done +# +# If pushing without using a named remote those arguments will be equal. +# +# Information about the commits which are being pushed is supplied as lines to +# the standard input in the form: +# +# +# +# This sample shows how to prevent push of commits where the log message starts +# with "WIP" (work in progress). + +remote="$1" +url="$2" + +z40=0000000000000000000000000000000000000000 + +while read local_ref local_sha remote_ref remote_sha +do + if [ "$local_sha" = $z40 ] + then + # Handle delete + : + else + if [ "$remote_sha" = $z40 ] + then + # New branch, examine all commits + range="$local_sha" + else + # Update to existing branch, examine new commits + range="$remote_sha..$local_sha" + fi + + # Check for WIP commit + commit=`git rev-list -n 1 --grep '^WIP' "$range"` + if [ -n "$commit" ] + then + echo >&2 "Found WIP commit in $local_ref, not pushing" + exit 1 + fi + fi +done + +exit 0 diff --git a/internal/config/funcs/testdata/git-commits-changes/DOTgit/hooks/pre-rebase.sample b/internal/config/funcs/testdata/git-commits-changes/DOTgit/hooks/pre-rebase.sample new file mode 100755 index 00000000000..bf56307dcb5 --- /dev/null +++ b/internal/config/funcs/testdata/git-commits-changes/DOTgit/hooks/pre-rebase.sample @@ -0,0 +1,169 @@ +#!/nix/store/ilgf30winx4zw3acm5pk79cvhzkjch0f-bash-4.4-p23/bin/bash +# +# Copyright (c) 2006, 2008 Junio C Hamano +# +# The "pre-rebase" hook is run just before "git rebase" starts doing +# its job, and can prevent the command from running by exiting with +# non-zero status. +# +# The hook is called with the following parameters: +# +# $1 -- the upstream the series was forked from. +# $2 -- the branch being rebased (or empty when rebasing the current branch). +# +# This sample shows how to prevent topic branches that are already +# merged to 'next' branch from getting rebased, because allowing it +# would result in rebasing already published history. + +publish=next +basebranch="$1" +if test "$#" = 2 +then + topic="refs/heads/$2" +else + topic=`git symbolic-ref HEAD` || + exit 0 ;# we do not interrupt rebasing detached HEAD +fi + +case "$topic" in +refs/heads/??/*) + ;; +*) + exit 0 ;# we do not interrupt others. + ;; +esac + +# Now we are dealing with a topic branch being rebased +# on top of master. Is it OK to rebase it? + +# Does the topic really exist? +git show-ref -q "$topic" || { + echo >&2 "No such branch $topic" + exit 1 +} + +# Is topic fully merged to master? +not_in_master=`git rev-list --pretty=oneline ^master "$topic"` +if test -z "$not_in_master" +then + echo >&2 "$topic is fully merged to master; better remove it." + exit 1 ;# we could allow it, but there is no point. +fi + +# Is topic ever merged to next? If so you should not be rebasing it. +only_next_1=`git rev-list ^master "^$topic" ${publish} | sort` +only_next_2=`git rev-list ^master ${publish} | sort` +if test "$only_next_1" = "$only_next_2" +then + not_in_topic=`git rev-list "^$topic" master` + if test -z "$not_in_topic" + then + echo >&2 "$topic is already up to date with master" + exit 1 ;# we could allow it, but there is no point. + else + exit 0 + fi +else + not_in_next=`git rev-list --pretty=oneline ^${publish} "$topic"` + /nix/store/5mkw2nn6ghpadr95hic5l84vfp5xyana-perl-5.30.2/bin/perl -e ' + my $topic = $ARGV[0]; + my $msg = "* $topic has commits already merged to public branch:\n"; + my (%not_in_next) = map { + /^([0-9a-f]+) /; + ($1 => 1); + } split(/\n/, $ARGV[1]); + for my $elem (map { + /^([0-9a-f]+) (.*)$/; + [$1 => $2]; + } split(/\n/, $ARGV[2])) { + if (!exists $not_in_next{$elem->[0]}) { + if ($msg) { + print STDERR $msg; + undef $msg; + } + print STDERR " $elem->[1]\n"; + } + } + ' "$topic" "$not_in_next" "$not_in_master" + exit 1 +fi + +<<\DOC_END + +This sample hook safeguards topic branches that have been +published from being rewound. + +The workflow assumed here is: + + * Once a topic branch forks from "master", "master" is never + merged into it again (either directly or indirectly). + + * Once a topic branch is fully cooked and merged into "master", + it is deleted. If you need to build on top of it to correct + earlier mistakes, a new topic branch is created by forking at + the tip of the "master". This is not strictly necessary, but + it makes it easier to keep your history simple. + + * Whenever you need to test or publish your changes to topic + branches, merge them into "next" branch. + +The script, being an example, hardcodes the publish branch name +to be "next", but it is trivial to make it configurable via +$GIT_DIR/config mechanism. + +With this workflow, you would want to know: + +(1) ... if a topic branch has ever been merged to "next". Young + topic branches can have stupid mistakes you would rather + clean up before publishing, and things that have not been + merged into other branches can be easily rebased without + affecting other people. But once it is published, you would + not want to rewind it. + +(2) ... if a topic branch has been fully merged to "master". + Then you can delete it. More importantly, you should not + build on top of it -- other people may already want to + change things related to the topic as patches against your + "master", so if you need further changes, it is better to + fork the topic (perhaps with the same name) afresh from the + tip of "master". + +Let's look at this example: + + o---o---o---o---o---o---o---o---o---o "next" + / / / / + / a---a---b A / / + / / / / + / / c---c---c---c B / + / / / \ / + / / / b---b C \ / + / / / / \ / + ---o---o---o---o---o---o---o---o---o---o---o "master" + + +A, B and C are topic branches. + + * A has one fix since it was merged up to "next". + + * B has finished. It has been fully merged up to "master" and "next", + and is ready to be deleted. + + * C has not merged to "next" at all. + +We would want to allow C to be rebased, refuse A, and encourage +B to be deleted. + +To compute (1): + + git rev-list ^master ^topic next + git rev-list ^master next + + if these match, topic has not merged in next at all. + +To compute (2): + + git rev-list master..topic + + if this is empty, it is fully merged to "master". + +DOC_END diff --git a/internal/config/funcs/testdata/git-commits-changes/DOTgit/hooks/pre-receive.sample b/internal/config/funcs/testdata/git-commits-changes/DOTgit/hooks/pre-receive.sample new file mode 100755 index 00000000000..41e19422178 --- /dev/null +++ b/internal/config/funcs/testdata/git-commits-changes/DOTgit/hooks/pre-receive.sample @@ -0,0 +1,24 @@ +#!/nix/store/ilgf30winx4zw3acm5pk79cvhzkjch0f-bash-4.4-p23/bin/bash +# +# An example hook script to make use of push options. +# The example simply echoes all push options that start with 'echoback=' +# and rejects all pushes when the "reject" push option is used. +# +# To enable this hook, rename this file to "pre-receive". + +if test -n "$GIT_PUSH_OPTION_COUNT" +then + i=0 + while test "$i" -lt "$GIT_PUSH_OPTION_COUNT" + do + eval "value=\$GIT_PUSH_OPTION_$i" + case "$value" in + echoback=*) + echo "echo from the pre-receive-hook: ${value#*=}" >&2 + ;; + reject) + exit 1 + esac + i=$((i + 1)) + done +fi diff --git a/internal/config/funcs/testdata/git-commits-changes/DOTgit/hooks/prepare-commit-msg.sample b/internal/config/funcs/testdata/git-commits-changes/DOTgit/hooks/prepare-commit-msg.sample new file mode 100755 index 00000000000..ba3b38e6076 --- /dev/null +++ b/internal/config/funcs/testdata/git-commits-changes/DOTgit/hooks/prepare-commit-msg.sample @@ -0,0 +1,42 @@ +#!/nix/store/ilgf30winx4zw3acm5pk79cvhzkjch0f-bash-4.4-p23/bin/bash +# +# An example hook script to prepare the commit log message. +# Called by "git commit" with the name of the file that has the +# commit message, followed by the description of the commit +# message's source. The hook's purpose is to edit the commit +# message file. If the hook fails with a non-zero status, +# the commit is aborted. +# +# To enable this hook, rename this file to "prepare-commit-msg". + +# This hook includes three examples. The first one removes the +# "# Please enter the commit message..." help message. +# +# The second includes the output of "git diff --name-status -r" +# into the message, just before the "git status" output. It is +# commented because it doesn't cope with --amend or with squashed +# commits. +# +# The third example adds a Signed-off-by line to the message, that can +# still be edited. This is rarely a good idea. + +COMMIT_MSG_FILE=$1 +COMMIT_SOURCE=$2 +SHA1=$3 + +/nix/store/5mkw2nn6ghpadr95hic5l84vfp5xyana-perl-5.30.2/bin/perl -i.bak -ne 'print unless(m/^. Please enter the commit message/..m/^#$/)' "$COMMIT_MSG_FILE" + +# case "$COMMIT_SOURCE,$SHA1" in +# ,|template,) +# /nix/store/5mkw2nn6ghpadr95hic5l84vfp5xyana-perl-5.30.2/bin/perl -i.bak -pe ' +# print "\n" . `git diff --cached --name-status -r` +# if /^#/ && $first++ == 0' "$COMMIT_MSG_FILE" ;; +# *) ;; +# esac + +# SOB=$(git var GIT_COMMITTER_IDENT | sed -n 's/^\(.*>\).*$/Signed-off-by: \1/p') +# git interpret-trailers --in-place --trailer "$SOB" "$COMMIT_MSG_FILE" +# if test -z "$COMMIT_SOURCE" +# then +# /nix/store/5mkw2nn6ghpadr95hic5l84vfp5xyana-perl-5.30.2/bin/perl -i.bak -pe 'print "\n" if !$first_line++' "$COMMIT_MSG_FILE" +# fi diff --git a/internal/config/funcs/testdata/git-commits-changes/DOTgit/hooks/update.sample b/internal/config/funcs/testdata/git-commits-changes/DOTgit/hooks/update.sample new file mode 100755 index 00000000000..da23bbb35ae --- /dev/null +++ b/internal/config/funcs/testdata/git-commits-changes/DOTgit/hooks/update.sample @@ -0,0 +1,128 @@ +#!/nix/store/ilgf30winx4zw3acm5pk79cvhzkjch0f-bash-4.4-p23/bin/bash +# +# An example hook script to block unannotated tags from entering. +# Called by "git receive-pack" with arguments: refname sha1-old sha1-new +# +# To enable this hook, rename this file to "update". +# +# Config +# ------ +# hooks.allowunannotated +# This boolean sets whether unannotated tags will be allowed into the +# repository. By default they won't be. +# hooks.allowdeletetag +# This boolean sets whether deleting tags will be allowed in the +# repository. By default they won't be. +# hooks.allowmodifytag +# This boolean sets whether a tag may be modified after creation. By default +# it won't be. +# hooks.allowdeletebranch +# This boolean sets whether deleting branches will be allowed in the +# repository. By default they won't be. +# hooks.denycreatebranch +# This boolean sets whether remotely creating branches will be denied +# in the repository. By default this is allowed. +# + +# --- Command line +refname="$1" +oldrev="$2" +newrev="$3" + +# --- Safety check +if [ -z "$GIT_DIR" ]; then + echo "Don't run this script from the command line." >&2 + echo " (if you want, you could supply GIT_DIR then run" >&2 + echo " $0 )" >&2 + exit 1 +fi + +if [ -z "$refname" -o -z "$oldrev" -o -z "$newrev" ]; then + echo "usage: $0 " >&2 + exit 1 +fi + +# --- Config +allowunannotated=$(git config --type=bool hooks.allowunannotated) +allowdeletebranch=$(git config --type=bool hooks.allowdeletebranch) +denycreatebranch=$(git config --type=bool hooks.denycreatebranch) +allowdeletetag=$(git config --type=bool hooks.allowdeletetag) +allowmodifytag=$(git config --type=bool hooks.allowmodifytag) + +# check for no description +projectdesc=$(sed -e '1q' "$GIT_DIR/description") +case "$projectdesc" in +"Unnamed repository"* | "") + echo "*** Project description file hasn't been set" >&2 + exit 1 + ;; +esac + +# --- Check types +# if $newrev is 0000...0000, it's a commit to delete a ref. +zero="0000000000000000000000000000000000000000" +if [ "$newrev" = "$zero" ]; then + newrev_type=delete +else + newrev_type=$(git cat-file -t $newrev) +fi + +case "$refname","$newrev_type" in + refs/tags/*,commit) + # un-annotated tag + short_refname=${refname##refs/tags/} + if [ "$allowunannotated" != "true" ]; then + echo "*** The un-annotated tag, $short_refname, is not allowed in this repository" >&2 + echo "*** Use 'git tag [ -a | -s ]' for tags you want to propagate." >&2 + exit 1 + fi + ;; + refs/tags/*,delete) + # delete tag + if [ "$allowdeletetag" != "true" ]; then + echo "*** Deleting a tag is not allowed in this repository" >&2 + exit 1 + fi + ;; + refs/tags/*,tag) + # annotated tag + if [ "$allowmodifytag" != "true" ] && git rev-parse $refname > /dev/null 2>&1 + then + echo "*** Tag '$refname' already exists." >&2 + echo "*** Modifying a tag is not allowed in this repository." >&2 + exit 1 + fi + ;; + refs/heads/*,commit) + # branch + if [ "$oldrev" = "$zero" -a "$denycreatebranch" = "true" ]; then + echo "*** Creating a branch is not allowed in this repository" >&2 + exit 1 + fi + ;; + refs/heads/*,delete) + # delete branch + if [ "$allowdeletebranch" != "true" ]; then + echo "*** Deleting a branch is not allowed in this repository" >&2 + exit 1 + fi + ;; + refs/remotes/*,commit) + # tracking branch + ;; + refs/remotes/*,delete) + # delete tracking branch + if [ "$allowdeletebranch" != "true" ]; then + echo "*** Deleting a tracking branch is not allowed in this repository" >&2 + exit 1 + fi + ;; + *) + # Anything else (is there anything else?) + echo "*** Update hook: unknown type of update to ref $refname of type $newrev_type" >&2 + exit 1 + ;; +esac + +# --- Finished +exit 0 diff --git a/internal/config/funcs/testdata/git-commits-changes/DOTgit/index b/internal/config/funcs/testdata/git-commits-changes/DOTgit/index new file mode 100644 index 0000000000000000000000000000000000000000..f95362676ad1e2ca8aa3224d09da6f1796bf4abc GIT binary patch literal 129 zcmZ?q402{*U|<4b#>8MtYq^=O959-JfrF7j!XSi!p>YWV1M>@@niP<_ZsCfFmGUn$ z)z?-$^X6JxeeXi|9R@~6hL9jvSD?HkgQ0=}m+J)OB>_8LtTORc=CHgXr!N?5tFdO! X*38gP8b6PnZ{&B9tlGUyxZn=}@=GS# literal 0 HcmV?d00001 diff --git a/internal/config/funcs/testdata/git-commits-changes/DOTgit/info/exclude b/internal/config/funcs/testdata/git-commits-changes/DOTgit/info/exclude new file mode 100644 index 00000000000..a5196d1be8f --- /dev/null +++ b/internal/config/funcs/testdata/git-commits-changes/DOTgit/info/exclude @@ -0,0 +1,6 @@ +# git ls-files --others --exclude-from=.git/info/exclude +# Lines that start with '#' are comments. +# For a project mostly in C, the following would be a good set of +# exclude patterns (uncomment them if you want to use them): +# *.[oa] +# *~ diff --git a/internal/config/funcs/testdata/git-commits-changes/DOTgit/logs/HEAD b/internal/config/funcs/testdata/git-commits-changes/DOTgit/logs/HEAD new file mode 100644 index 00000000000..bfc8bc239a2 --- /dev/null +++ b/internal/config/funcs/testdata/git-commits-changes/DOTgit/logs/HEAD @@ -0,0 +1,2 @@ +0000000000000000000000000000000000000000 b1a2dcd337f590a185a20f013721e7410764bab4 Mitchell Hashimoto 1597446600 -0700 commit (initial): Commit one +b1a2dcd337f590a185a20f013721e7410764bab4 380afd697abe993b89bfa08d8dd8724d6a513ba1 Mitchell Hashimoto 1597446608 -0700 commit: Commit two diff --git a/internal/config/funcs/testdata/git-commits-changes/DOTgit/logs/refs/heads/master b/internal/config/funcs/testdata/git-commits-changes/DOTgit/logs/refs/heads/master new file mode 100644 index 00000000000..bfc8bc239a2 --- /dev/null +++ b/internal/config/funcs/testdata/git-commits-changes/DOTgit/logs/refs/heads/master @@ -0,0 +1,2 @@ +0000000000000000000000000000000000000000 b1a2dcd337f590a185a20f013721e7410764bab4 Mitchell Hashimoto 1597446600 -0700 commit (initial): Commit one +b1a2dcd337f590a185a20f013721e7410764bab4 380afd697abe993b89bfa08d8dd8724d6a513ba1 Mitchell Hashimoto 1597446608 -0700 commit: Commit two diff --git a/internal/config/funcs/testdata/git-commits-changes/DOTgit/objects/38/0afd697abe993b89bfa08d8dd8724d6a513ba1 b/internal/config/funcs/testdata/git-commits-changes/DOTgit/objects/38/0afd697abe993b89bfa08d8dd8724d6a513ba1 new file mode 100644 index 0000000000000000000000000000000000000000..da04713c08fad55368171ef577ca336249e594b8 GIT binary patch literal 825 zcmV-91IGM#0j-qD4x3mIMSIOxuty0z9;4KW8qAEr490+WOpn1##^CAe<0Q(im#O8E z>Zq!uTg5aC?TP~c=zrFws&IxCDH>)BOXWf(WEo_bl7^H3#gYLPjR0UvSkeMEXG=A% zcn&hUEJ_G@^y$oiz-BasC;)jHR6GMHo@4SXXRvHrn`yzFb}gE!?{Oo$HSI916aMdK zf?w=w^N0Oc4_VuPEvDf+4p@=U^{0qfX6!xK?jZH<5VS+c5|F7D|b z9-6u<9iu?~#W5ViTi<-kk|ghHsnl9kom4syxJgO}i>r!ZjXF?1m@zE)hbHv`)Js#^ z)ffK{$MAxG%B4?|akI!lVfY%MUbtpE#Jx9@2*{3@B4d%|&0cc(YQDI<;0Cb|Yu@Y3 z+M+R>Y2rw2G%e*r>ENEh9YqB!m}f2f&V9%454Y<+XIbG?>%jd+pXU?{*Qa z7lto|Lz|6dY;&>o>ATP_PasH~55t=jPMzr~@~X9ar=ea?C<+57j<1Z(Q3yuw&z$w<=V|XtR?NjRVJciGx zvcw%Ndv>VWmx@5fcs#T0m=UaPrp%K|D>48UpydZK$F_KR+lk>I+b8F$$@{1N)5VqjumU~Cvzkn%!o-HZs$|3<;Jxkruj*KNJ}U9aRmBg54%e2M^p Cwi1v4 literal 0 HcmV?d00001 diff --git a/internal/config/funcs/testdata/git-commits-changes/DOTgit/objects/7c/178d1296d8b87e83382c324aeb32e2def2a5af b/internal/config/funcs/testdata/git-commits-changes/DOTgit/objects/7c/178d1296d8b87e83382c324aeb32e2def2a5af new file mode 100644 index 0000000000000000000000000000000000000000..328b144031c4465153d391ccbb4a51ed054a3040 GIT binary patch literal 46 zcmb)5VqjumU~CvzkWyjx{o)&6@%5I~<=N}B`*#(-@bv%S!thIl{|W$u Cs1l$6 literal 0 HcmV?d00001 diff --git a/internal/config/funcs/testdata/git-commits-changes/DOTgit/objects/8b/137891791fe96927ad78e64b0aad7bded08bdc b/internal/config/funcs/testdata/git-commits-changes/DOTgit/objects/8b/137891791fe96927ad78e64b0aad7bded08bdc new file mode 100644 index 0000000000000000000000000000000000000000..9d8f60531ebc0489c29cf79c42b6fc0e3583f9d9 GIT binary patch literal 16 Xcmbfc8%y@T zh!tb;tP1e;-{AyFF@PzVz)>WFb?>(Dn?nEsm8BdU%W{0dreY-sgMisIIk1mTC9|Yk z?lqe3=iW)EU1VDtmy&_yi^lrPA&^kV8!q6J8p*;FSG8hWh;lcLt5-*5)DSUcX3QSoX0lsVL7MvRW!AFil+x!G}^_V@za3?GUg2B6?MI* zv~Pn@)i`dPM8B5^@o|Y#)`ozH=`&kv`hhadjTnw;mEjoYop zN%TbH;cFj}k`FE4PO~+H0G;0_tX37e&V9vL&xT&)0zwR-&k%vmw5g^C2H#Qla?m-E z&!pp_#tBCkh`F<@i$VZT_g&qTwrEh5tT`UO_f@TodF5HiF=sqwlclUZuHx}tmGE^_ z@JenITlE?g?uO8XfS)3tYa7xS^uw>``_>agD$l}%j#`5tj6q|%ue-YWcJV&(M$9~N zC035%?MLECxkF%L(pxGCnpiBnb%izDZg0Gd#ZN=CDup$ih|1ctw%$nFWzD!hlhbY+ zFRf)7#A+`m2-ryl&$zdAOvbw2%J~xUu+m2zCOw=jcX*;Va<1hy9<8zHu??428TVSp ze{Gf4r33^BH|W{K++b?-^wz%KY`NI4yAIb}BzDhu4(=PV1vg@o%2kBpi#cvHx)@IN zY>&onKbgD`a`@~AEh$RzkyW={^~Ok7GrNLS)|fFVgHd~)*gQB{C*S#)lh~6Qtu;Ga z<^_QOR)}0+$h4W)Tv1>|XT8S5Xba4ptXMXYH=A#zu+fq-y&2VJu7vOd0zYO0cc4F= V5sb@!H3s7UJc^;upkFxKRpIb!i?;v( literal 0 HcmV?d00001 diff --git a/internal/config/funcs/testdata/git-commits-changes/DOTgit/objects/e6/9de29bb2d1d6434b8b29ae775ad8c2e48c5391 b/internal/config/funcs/testdata/git-commits-changes/DOTgit/objects/e6/9de29bb2d1d6434b8b29ae775ad8c2e48c5391 new file mode 100644 index 0000000000000000000000000000000000000000..711223894375fe1186ac5bfffdc48fb1fa1e65cc GIT binary patch literal 15 Wcmb Date: Tue, 28 Sep 2021 08:53:41 -0700 Subject: [PATCH 2/6] internal/config/funcs: change a file in a test fixture --- .../config/funcs/testdata/git-commits-changes/A | 2 +- .../testdata/git-commits-changes/DOTgit/index | Bin 129 -> 110 bytes .../testdata/git-commits-changes/untracked_file | 0 3 files changed, 1 insertion(+), 1 deletion(-) delete mode 100644 internal/config/funcs/testdata/git-commits-changes/untracked_file diff --git a/internal/config/funcs/testdata/git-commits-changes/A b/internal/config/funcs/testdata/git-commits-changes/A index 8b137891791..5c56af15d47 100644 --- a/internal/config/funcs/testdata/git-commits-changes/A +++ b/internal/config/funcs/testdata/git-commits-changes/A @@ -1 +1 @@ - +changes diff --git a/internal/config/funcs/testdata/git-commits-changes/DOTgit/index b/internal/config/funcs/testdata/git-commits-changes/DOTgit/index index f95362676ad1e2ca8aa3224d09da6f1796bf4abc..d2d9a078064a0139b06833631ee5df732ab0807c 100644 GIT binary patch delta 33 pcmZo<%$pD_&BmZ>s9?Y)u=gTcS(;nq7v&|M+g6{yDZjU+767h@47LCO delta 52 zcmV-40L%YwfdP6L9?5HWYmT diff --git a/internal/config/funcs/testdata/git-commits-changes/untracked_file b/internal/config/funcs/testdata/git-commits-changes/untracked_file deleted file mode 100644 index e69de29bb2d..00000000000 From 9fa9bc7fc0afa73fe1385af73165f1af7f66c7b9 Mon Sep 17 00:00:00 2001 From: Mitchell Hashimoto Date: Tue, 28 Sep 2021 08:58:43 -0700 Subject: [PATCH 3/6] internal/config/funcs: test refpretty --- internal/config/funcs/vcs_git.go | 13 ++----- internal/config/funcs/vcs_git_test.go | 55 ++++++++++++++++++++++++++- 2 files changed, 58 insertions(+), 10 deletions(-) diff --git a/internal/config/funcs/vcs_git.go b/internal/config/funcs/vcs_git.go index afcc1d21447..2f92d6fbefa 100644 --- a/internal/config/funcs/vcs_git.go +++ b/internal/config/funcs/vcs_git.go @@ -88,10 +88,11 @@ func (s *VCSGit) refPrettyFunc(args []cty.Value, retType cty.Type) (cty.Value, e cmd := exec.Command("git", "diff", "--quiet") cmd.Stdout = ioutil.Discard cmd.Stderr = ioutil.Discard + cmd.Dir = s.Path if err := cmd.Run(); err != nil { - // If git isn't available, don't worry about trying to calculate changes. - // more than likely, if git isn't available, then we're running in an env - // where changes aren't even possible anyway. + // If git isn't available, we fall back to using go-git. This can + // take a very long time and that is sad but we want to give consistent + // results from this func. if errors.Is(err, exec.ErrNotFound) { return cty.StringVal(result), nil } @@ -228,12 +229,6 @@ func (s *VCSGit) init() error { return nil } - // Check if `git` is installed. We'll use this sometimes. - if _, err := exec.LookPath("git"); err != nil { - s.initErr = fmt.Errorf("git was not found on the system and is required") - return s.initErr - } - // Open the repo repo, err := git.PlainOpenWithOptions(s.Path, &git.PlainOpenOptions{ DetectDotGit: true, diff --git a/internal/config/funcs/vcs_git_test.go b/internal/config/funcs/vcs_git_test.go index 247070d3b14..dc7caa71f9f 100644 --- a/internal/config/funcs/vcs_git_test.go +++ b/internal/config/funcs/vcs_git_test.go @@ -1,11 +1,14 @@ package funcs import ( + "io/ioutil" "os" "os/exec" "path/filepath" + "strings" "testing" + "github.com/hashicorp/waypoint/internal/pkg/copy" "github.com/stretchr/testify/require" "github.com/zclconf/go-cty/cty" ) @@ -82,13 +85,52 @@ func TestVCSGit(t *testing.T) { cty.StringVal("https://github.com/hashicorp/example.git"), "", }, + + { + "refpretty with no changes", + "git-commits", + "", + (*VCSGit).refPrettyFunc, + nil, + cty.StringVal("380afd697abe993b89bfa08d8dd8724d6a513ba1"), + "", + }, + + { + "refpretty with changes", + "git-commits-changes", + "", + (*VCSGit).refPrettyFunc, + nil, + cty.StringVal("380afd697abe993b89bfa08d8dd8724d6a513ba1_CHANGES_*"), + "", + }, + + { + "refpretty with tags", + "git-tag", + "", + (*VCSGit).refPrettyFunc, + nil, + cty.StringVal("hello"), + "", + }, } for _, tt := range cases { t.Run(tt.Name, func(t *testing.T) { require := require.New(t) + td, err := ioutil.TempDir("", "git") + require.NoError(err) + defer os.RemoveAll(td) + + // Copy our test fixture so we don't have any side effects path := filepath.Join("testdata", tt.Fixture) + dstPath := filepath.Join(td, "fixture") + require.NoError(copy.CopyDir(path, dstPath)) + path = dstPath + testGitFixture(t, path) if tt.Subdir != "" { path = filepath.Join(path, tt.Subdir) @@ -101,8 +143,19 @@ func TestVCSGit(t *testing.T) { require.Contains(err.Error(), tt.Error) return } - require.NoError(err) + + // If our expected value ends in _* then we do a prefix check + // instead. This is so we can test the dynamic parts of the timestamp. + if tt.Expected.Type() == cty.String { + expected := tt.Expected.AsString() + if strings.HasSuffix(expected, "_*") { + require.True(strings.HasPrefix( + result.AsString(), expected[:len(expected)-1])) + return + } + } + require.True(tt.Expected.RawEquals(result), result.GoString()) }) } From f7d2f0ac9566ffed1fa0b3c85859623e93790029 Mon Sep 17 00:00:00 2001 From: Mitchell Hashimoto Date: Tue, 28 Sep 2021 09:32:16 -0700 Subject: [PATCH 4/6] internal/config/funcs: fallback to go-git if git not available --- internal/config/funcs/vcs_git.go | 46 ++++++++++++---- internal/config/funcs/vcs_git_test.go | 78 +++++++++++++++------------ 2 files changed, 79 insertions(+), 45 deletions(-) diff --git a/internal/config/funcs/vcs_git.go b/internal/config/funcs/vcs_git.go index 2f92d6fbefa..8c12905c53c 100644 --- a/internal/config/funcs/vcs_git.go +++ b/internal/config/funcs/vcs_git.go @@ -30,6 +30,10 @@ type VCSGit struct { // a ".git" folder automatically. Path string + // GoGitOnly forces go-git usage and disables all subprocessing to "git" + // even if it exists. + GoGitOnly bool + initErr error repo *git.Repository } @@ -85,24 +89,46 @@ func (s *VCSGit) refPrettyFunc(args []cty.Value, retType cty.Type) (cty.Value, e // To determine if there are changes we subprocess because go-git's Status // function is really, really slow sadly. On the waypoint repo at the time // of this commit, go-git took 12s on my machine vs. 50ms for `git`. - cmd := exec.Command("git", "diff", "--quiet") - cmd.Stdout = ioutil.Discard - cmd.Stderr = ioutil.Discard - cmd.Dir = s.Path - if err := cmd.Run(); err != nil { + goGitChanges := s.GoGitOnly + if !goGitChanges { + cmd := exec.Command("git", "diff", "--quiet") + cmd.Stdout = ioutil.Discard + cmd.Stderr = ioutil.Discard + cmd.Dir = s.Path + err := cmd.Run() + // If git isn't available, we fall back to using go-git. This can // take a very long time and that is sad but we want to give consistent // results from this func. if errors.Is(err, exec.ErrNotFound) { - return cty.StringVal(result), nil + goGitChanges = true + } + + if !goGitChanges && err != nil { + exitError, ok := err.(*exec.ExitError) + if !ok { + return cty.UnknownVal(cty.String), fmt.Errorf("error executing git: %s", err) + } + + if exitError.ExitCode() != 0 { + result += fmt.Sprintf("_CHANGES_%d", time.Now().Unix()) + } + } + } + + // If we want to use go-git for change detection, then do that now. + if goGitChanges { + wt, err := s.repo.Worktree() + if err != nil { + return cty.UnknownVal(cty.String), err } - exitError, ok := err.(*exec.ExitError) - if !ok { - return cty.UnknownVal(cty.String), fmt.Errorf("error executing git: %s", err) + st, err := wt.Status() + if err != nil { + return cty.UnknownVal(cty.String), err } - if exitError.ExitCode() != 0 { + if !st.IsClean() { result += fmt.Sprintf("_CHANGES_%d", time.Now().Unix()) } } diff --git a/internal/config/funcs/vcs_git_test.go b/internal/config/funcs/vcs_git_test.go index dc7caa71f9f..e2a783f944e 100644 --- a/internal/config/funcs/vcs_git_test.go +++ b/internal/config/funcs/vcs_git_test.go @@ -118,46 +118,54 @@ func TestVCSGit(t *testing.T) { } for _, tt := range cases { - t.Run(tt.Name, func(t *testing.T) { - require := require.New(t) - - td, err := ioutil.TempDir("", "git") - require.NoError(err) - defer os.RemoveAll(td) - - // Copy our test fixture so we don't have any side effects - path := filepath.Join("testdata", tt.Fixture) - dstPath := filepath.Join(td, "fixture") - require.NoError(copy.CopyDir(path, dstPath)) - path = dstPath - - testGitFixture(t, path) - if tt.Subdir != "" { - path = filepath.Join(path, tt.Subdir) + for i := 0; i < 2; i++ { + gogit := i == 1 + name := tt.Name + if gogit { + name += " (go-git)" } - s := &VCSGit{Path: path} - result, err := tt.Func(s, tt.Args, cty.String) - if tt.Error != "" { - require.Error(err) - require.Contains(err.Error(), tt.Error) - return - } - require.NoError(err) - - // If our expected value ends in _* then we do a prefix check - // instead. This is so we can test the dynamic parts of the timestamp. - if tt.Expected.Type() == cty.String { - expected := tt.Expected.AsString() - if strings.HasSuffix(expected, "_*") { - require.True(strings.HasPrefix( - result.AsString(), expected[:len(expected)-1])) + t.Run(name, func(t *testing.T) { + require := require.New(t) + + td, err := ioutil.TempDir("", "git") + require.NoError(err) + defer os.RemoveAll(td) + + // Copy our test fixture so we don't have any side effects + path := filepath.Join("testdata", tt.Fixture) + dstPath := filepath.Join(td, "fixture") + require.NoError(copy.CopyDir(path, dstPath)) + path = dstPath + + testGitFixture(t, path) + if tt.Subdir != "" { + path = filepath.Join(path, tt.Subdir) + } + + s := &VCSGit{Path: path, GoGitOnly: gogit} + result, err := tt.Func(s, tt.Args, cty.String) + if tt.Error != "" { + require.Error(err) + require.Contains(err.Error(), tt.Error) return } - } + require.NoError(err) + + // If our expected value ends in _* then we do a prefix check + // instead. This is so we can test the dynamic parts of the timestamp. + if tt.Expected.Type() == cty.String { + expected := tt.Expected.AsString() + if strings.HasSuffix(expected, "_*") { + require.True(strings.HasPrefix( + result.AsString(), expected[:len(expected)-1])) + return + } + } - require.True(tt.Expected.RawEquals(result), result.GoString()) - }) + require.True(tt.Expected.RawEquals(result), result.GoString()) + }) + } } } From 44b44c80303274ccaf0272b27b66425401d50f12 Mon Sep 17 00:00:00 2001 From: Mitchell Hashimoto Date: Tue, 28 Sep 2021 09:37:26 -0700 Subject: [PATCH 5/6] changelog --- .changelog/2371.txt | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 .changelog/2371.txt diff --git a/.changelog/2371.txt b/.changelog/2371.txt new file mode 100644 index 00000000000..2a51b07c808 --- /dev/null +++ b/.changelog/2371.txt @@ -0,0 +1,3 @@ +```release-note:improvement +config: `gitrefpretty` no longer requires `git` to be installed +``` From 715e15fcadb1d7f1ec510760110b92d98e21509c Mon Sep 17 00:00:00 2001 From: Mitchell Hashimoto Date: Tue, 28 Sep 2021 10:11:38 -0700 Subject: [PATCH 6/6] internal/config: fix unknown val deref --- internal/config/funcs/vcs_git_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/config/funcs/vcs_git_test.go b/internal/config/funcs/vcs_git_test.go index e2a783f944e..f50eb4be1d6 100644 --- a/internal/config/funcs/vcs_git_test.go +++ b/internal/config/funcs/vcs_git_test.go @@ -154,7 +154,7 @@ func TestVCSGit(t *testing.T) { // If our expected value ends in _* then we do a prefix check // instead. This is so we can test the dynamic parts of the timestamp. - if tt.Expected.Type() == cty.String { + if tt.Expected.Type() == cty.String && tt.Expected.IsKnown() { expected := tt.Expected.AsString() if strings.HasSuffix(expected, "_*") { require.True(strings.HasPrefix(