#!/bin/sh

# This script is obsolete.  Use `ci-org-and-branch` and `git-changes` instead.
#
# This script duplicates what `set-ci-org-and-branch` and `set-git-range` do.
# The duplication is deliberate:  this script is frozen except for bug fixes,
# so extracting the shared code into a file that both it and the "set-" scripts
# source would constrain those scripts for the sake of a script that no one
# should be using.  Keep a bug fix in step across the copies, and prefer the
# "set-" scripts' behavior where they differ, as they do in one place:
#  * When the GitHub API request for an Azure Pipelines pull request fails,
#    this script gives up; `set-ci-org-and-branch` falls back to
#    $SYSTEM_PULLREQUEST_SOURCEREPOSITORYURI.

# Determines the start and end commits for a CI job.
# Works under Azure Pipelines, CircleCI, GitHub Actions, and Travis CI.

# Typical use:
#
#   PLUME_SCRIPTS="/tmp/${USER:-$(id -un)}/plume-scripts"
#   if [ -d "$PLUME_SCRIPTS" ] ; then
#     git -C "$PLUME_SCRIPTS" pull -q > /dev/null 2>&1
#   else
#     git clone --depth=1 -q https://github.com/plume-lib/plume-scripts.git "$PLUME_SCRIPTS"
#   fi
#   eval "$("$PLUME_SCRIPTS"/ci-info DEFAULT-ORGANIZATION)"
#
# Alternatively, to use a specific version of this script rather than the latest:
#
#   PLUME_SCRIPTS="/tmp/${USER:-$(id -un)}/plume-scripts"
#   if [ ! -d "$PLUME_SCRIPTS" ] ; then
#     git clone --revision=e768754ffafad4a9f1e26c5305591d4061d890b4 --depth=1 -q https://github.com/plume-lib/plume-scripts.git "$PLUME_SCRIPTS"
#   fi
#   eval "$("$PLUME_SCRIPTS"/ci-info DEFAULT-ORGANIZATION)"

# Either snippet of code sets these variables:
# CI_COMMIT_RANGE: An argument to `git diff` with the range of commit IDs.
#    (Don't use it with `git log`, which interprets its argument differently.)
# CI_COMMIT_RANGE_START: The start element of CI_COMMIT_RANGE, a commit ID/SHA.
# CI_COMMIT_RANGE_END: The end element of CI_COMMIT_RANGE, a commit ID/SHA.
#    For an Azure Pipelines pull request, it is the merge commit that Azure
#    checks out, which is on no branch of the repository.
#
# If called not under CI, or under CI but not in the main or toplevel
# clone, then gets information from the local repository.

# Requires the `jq` program and either `curl` or `wget`.
#
# If environment variable GITHUB_PAT or GH_TOKEN is set when this script is
# called, it is used as GitHub Personal Access Token when making GitHub API
# calls.  This can avoid "403 rate limit exceeded" failures.

# PROBLEM: A CI job may itself call "git clone" and then later call git-changes
# from that clone, so the environment and the current directory can describe
# different repositories.  Which one should win depends on what is being
# computed.  For a commit ID, the directory wins, because a commit that the
# environment names need not exist in this clone; `set-git-range` therefore
# verifies $GITHUB_SHA before using it.  For the organization, the environment
# wins, because the job's own repository is what the client is asking about,
# and a sibling clone's origin names some other organization.  Idea: check the
# directory name.

# SCRIPT_DIR="$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd -P)"
SCRIPT_NAME="$(basename -- "$0")"

# Writes its argument, quoted so that the client's `eval` reads it back as one
# word.  A value may contain a shell metacharacter:  a git branch name may
# contain any of `$`, backquote, `;`, `&`, `|`, and `'`.
shell_quote() {
  printf "'%s'" "$(printf '%s' "$1" | sed "s/'/'\\\\''/g")"
}

# emit_echo TEXT: writes a command that prints TEXT when the client `eval`s
# this script's output.  TEXT is quoted, so a value interpolated into it is
# printed rather than executed.  Much of what this script reports -- a branch
# name, a GitHub API response -- is chosen by whoever opened the pull request
# being tested, so an unquoted value would be a command injection into the
# client.
emit_echo() {
  echo "echo $(shell_quote "$1");"
}

# Copies standard input to standard output, turning each line into a command
# that prints that line when the client `eval`s this script's output.  The
# quoting is as in `emit_echo`, and for the same reason.
emit_echo_lines() {
  sed -e "s/'/'\\\\''/g" -e "s/^/echo '/" -e "s/\$/';/"
}

# emit_exit STATUS: writes a command that makes the client's `eval` exit with
# STATUS, then exits with STATUS.  The client's `eval` reports the status of
# the text it evaluated rather than this script's, so exiting without writing
# that command would leave the client with status 0 and with no value (or a
# stale value) for each variable.  The client would then act on the silent
# success -- running, say, `git diff ${CI_COMMIT_RANGE}` with CI_COMMIT_RANGE
# unset, which diffs the working tree rather than the pull request.
emit_exit() {
  echo "exit $1"
  exit "$1"
}

DEBUG=""
DEFAULT_ORGANIZATION=""
while [ "$#" -gt 0 ]; do
  case $1 in
    --verbose)
      VERBOSE="--verbose"
      ;;
    --debug)
      DEBUG="--debug"
      VERBOSE="--verbose"
      ;;
    *)
      if [ -n "${DEFAULT_ORGANIZATION}" ]; then
        usage="Usage: ${SCRIPT_NAME} [--verbose] [--debug] [DEFAULT-ORGANIZATION]"
        emit_echo "$usage"
        echo "$usage" >&2
        emit_exit 2
      else
        DEFAULT_ORGANIZATION="$1"
      fi
      ;;
  esac
  shift
done

# Copies standard input to standard output, with the value of each variable
# whose name suggests a credential replaced.  A debug dump would otherwise
# write secrets into the CI log, which is often readable by anyone who can see
# the job.  Matching by name pattern rather than by an allowlist of names also
# covers secrets that this script does not know about; GitHub Actions, for
# example, defines $ACTIONS_RUNTIME_TOKEN in every job and does not mask it.
# A credential can also hide in the userinfo of a URL, under a variable whose
# name suggests nothing -- $URL holds `remote.origin.url`, which a job that
# cloned with a token spells "https://USER:TOKEN@github.com/org/repo" -- so
# strip that too, wherever in a line it appears.
# The placeholder contains no shell metacharacters, because the client `eval`s
# this script's output.
# This function is defined here rather than with the other functions below,
# because the debug dump just after it uses it.
redact_tokens() {
  awk '
    /^[A-Za-z_][A-Za-z0-9_]*=/ {
      name = $0
      sub(/=.*/, "", name)
      if (toupper(name) ~ /TOKEN|SECRET|PASSWORD|PASSWD|PASSPHRASE|CREDENTIAL|APIKEY|API_KEY|PRIVATE_KEY|_PAT$|^PAT$/) {
        print name "=REDACTED"
        next
      }
    }
    # Excluding whitespace and quotes from the userinfo keeps a match from
    # spanning a URL and a later "@" in unrelated text, which would delete
    # everything between them.  The userinfo also ends at the first "/", "?",
    # or "#", so an "@" in a path, query, or fragment is not a credential.
    { gsub(/:\/\/[^\/?#[:space:]"'\'']*@/, "://REDACTED@"); print }
  '
}

if [ "$DEBUG" = "--debug" ]; then
  # `env` only prints EXPORTED variables, so `set` is usually more useful.
  emit_echo "${SCRIPT_NAME} is running in $(pwd)"
  echo
  emit_echo '---------------- start of env'
  env -0 | sort -z | tr '\0' '\n' | redact_tokens | emit_echo_lines
  emit_echo '---------------- end of env'
  echo
  emit_echo '---------------- start of set'
  set | redact_tokens | emit_echo_lines
  emit_echo '---------------- end of set'
  echo
  emit_echo '---------------- start of git status'
  git --no-pager status | emit_echo_lines
  emit_echo '---------------- end of git status'
  echo
  emit_echo '---------------- start of all branches'
  git --no-pager branch -a | emit_echo_lines
  emit_echo '---------------- end of all branches'
  echo
  emit_echo '---------------- start of all remote branches'
  git --no-pager branch -r | emit_echo_lines
  emit_echo '---------------- end of all branches'
  echo
  emit_echo '---------------- start of 1000 lines of git log'
  git --no-pager log --graph | head --lines=1000 | emit_echo_lines
  emit_echo '---------------- end of 1000 lines of git log'
  echo
fi

### Variables

# "GITHUB_PAT" is a GitHub Personal Access Token.
# TODO: Should this be "Authorization: Bearer <YOUR-TOKEN>" instead?  See https://docs.github.com/en/rest/pulls/pulls#get-a-pull-request
if [ -n "$GITHUB_PAT" ]; then
  auth_token="$GITHUB_PAT"
elif [ -n "$GH_TOKEN" ]; then
  auth_token="$GH_TOKEN"
else
  auth_token=""
fi

### Prerequisites

# TODO: Try to not access the GitHub REST API, because it can get throttled.
if [ -n "$(command -v curl 2> /dev/null)" ]; then
  http_get_tool="curl"
elif [ -n "$(command -v wget 2> /dev/null)" ]; then
  http_get_tool="wget"
else
  emit_echo "Neither curl nor wget is installed"
  emit_exit 2
fi

# get_url URL: fetch URL to standard output, sending an Authorization header
# if $auth_token is set.  The header is passed as a single argument rather than
# being word-split out of a command string; that avoids mangling the header and
# leaking the token into stray connection attempts.
get_url() {
  if [ "$http_get_tool" = "curl" ]; then
    if [ -n "$auth_token" ]; then
      curl -s --header "Authorization: token $auth_token" "$1"
    else
      curl -s "$1"
    fi
  else
    if [ -n "$auth_token" ]; then
      wget -q -O - --header="Authorization: token $auth_token" "$1"
    else
      wget -q -O - "$1"
    fi
  fi
}

if [ -z "$(command -v jq 2> /dev/null)" ]; then
  emit_echo "jq is not installed"
  emit_exit 2
fi

### Functions

# Returns either `git rev-parse HEAD^1` if HEAD^1 exists, or `git rev-parse HEAD`.
# HEAD^1 does not exist if the clone was created with `git clone --depth=1`.
head1() {
  if git rev-parse --verify --quiet HEAD^1 > /dev/null 2>&1; then
    git rev-parse HEAD^1
  else
    git rev-parse HEAD
  fi
}

# Returns true if commit $1 is a merge commit, that is, has two or more
# parents.  This reads the commit itself, because in a shallow clone, `git show`
# and `git rev-list` show no parents for a commit at the clone's depth limit,
# such as HEAD in a clone created with `git clone --depth=1`.
is_merge() {
  # Only the header precedes the first empty line; the message could contain a
  # line that starts with "parent ".
  [ "$(git cat-file commit "$1" | sed '/^$/q' | grep -c '^parent ')" -ge 2 ]
}

# Converts a shallow clone into a complete one.
unshallow() {
  if [ "$(git rev-parse --is-shallow-repository)" = "true" ]; then
    git fetch --unshallow origin
  fi
}

# Prints the merge base of commits $1 and $2, or nothing if they have none.
# A shallow clone can lack the merge base, as when a merge commit's second
# parent brings in more commits than the clone's depth; in that case, this
# completes the clone.
merge_base() {
  # Hide the first try's errors, which a shallow clone can cause.  Show the
  # second try's, which explain a failure that completing the clone did not fix.
  git merge-base "$1" "$2" 2> /dev/null && return
  unshallow > /dev/null
  git merge-base "$1" "$2"
}

# Fetches $base_branch, the branch that a pull request is against, and sets
# $base_tip to its commit.  Does nothing on a second call, because fetching a
# branch fetches its complete history, so once is enough.
base_branch=""
base_branch_fetched=""
base_tip=""
fetch_base_branch() {
  if [ -z "$base_branch_fetched" ] && [ -n "$base_branch" ]; then
    base_branch_fetched="true"
    # Test the fetch's status rather than reading FETCH_HEAD unconditionally:  a
    # fetch that fails before writing FETCH_HEAD (as when the network is down)
    # leaves the previous fetch's commit there, which would silently yield a
    # commit range computed from an unrelated branch.
    if git fetch -q origin "$base_branch"; then
      # Remember the tip, because a later fetch overwrites FETCH_HEAD.
      base_tip=$(git rev-parse --verify -q FETCH_HEAD)
    else
      emit_echo "${SCRIPT_NAME}: cannot fetch ${base_branch} from origin."
    fi
  fi
}

# Returns true if `git diff ${CI_COMMIT_RANGE_START}...${CI_COMMIT_RANGE_END}`
# would work.  That command diffs from the merge base of the two commits, so it
# is not enough for both commits to be in the clone; their common ancestor must
# be as well, which is not the case in a clone that is too shallow.
commit_range_is_usable() {
  git merge-base "$CI_COMMIT_RANGE_START" "$CI_COMMIT_RANGE_END" > /dev/null 2>&1
}

# to_lower TEXT: prints TEXT with every uppercase letter made lowercase.
to_lower() {
  printf '%s' "$1" | tr '[:upper:]' '[:lower:]'
}

# org_from_url URL: prints the GitHub organization of a repository URL, or
# nothing if the argument is not a GitHub repository URL.  The caller treats no
# output as "unknown" and falls back to $DEFAULT_ORGANIZATION, so it is better
# to print nothing than to print a guess.
# These are the forms that git accepts and that can name GitHub:
#   https://github.com/mernst/annotation-tools[.git]
#   https://USER[:TOKEN]@github.com/mernst/annotation-tools[.git]
#   http://github.com/mernst/annotation-tools[.git]
#   git://github.com/mernst/annotation-tools[.git]
#   ssh://git@github.com[:PORT]/mernst/annotation-tools[.git]
#   git@github.com:mernst/annotation-tools[.git]   (git's scp-like syntax)
# A local path such as "../plume-scripts" is not one of them; neither is a URL
# for some other forge.  Printing the leading component of those would yield an
# organization that does not exist -- and, for a URL that embeds a credential,
# would copy the credential into $CI_ORGANIZATION and thence into the log.
org_from_url() {
  ofu_rest="$1"

  case $ofu_rest in
    ssh://* | git://* | http://* | https://*)
      ofu_rest=${ofu_rest#*://}
      # The host is everything before the first "/", which must be present:
      # these forms have no path-less spelling.
      case $ofu_rest in
        */*)
          ofu_host=${ofu_rest%%/*}
          ofu_path=${ofu_rest#*/}
          ;;
        *) return 0 ;;
      esac
      ;;
    *://*)
      # Some other scheme, such as git's file://.
      return 0
      ;;
    *:*)
      # The scp-like syntax, [USER@]HOST:PATH.  It has no "//", so the case
      # above has already ruled out every URL with a scheme.  A Windows path
      # such as "C:/repo" also matches, but git treats that as scp-like syntax
      # too, so this function is no more wrong about it than git is.
      ofu_host=${ofu_rest%%:*}
      ofu_path=${ofu_rest#*:}
      ;;
    *)
      # A local path, or a bare name.
      return 0
      ;;
  esac

  # Discard any userinfo ("git@", "USER:TOKEN@") and any port.
  ofu_host=${ofu_host##*@}
  ofu_host=${ofu_host%%:*}
  # Hostnames are case-insensitive, and git accepts them in any case.
  ofu_host=$(to_lower "${ofu_host}")
  case $ofu_host in
    github.com | www.github.com) : ;;
    *) return 0 ;;
  esac

  # The organization is the first component of the path.  Requiring a second
  # component rejects a URL that names no repository.
  ofu_path=${ofu_path#/}
  case $ofu_path in
    */*) printf '%s\n' "${ofu_path%%/*}" ;;
  esac
}

# redact_url URL: prints URL with any embedded credential replaced by a
# placeholder.  git accepts "https://USER:TOKEN@github.com/org/repo", and the
# --debug output goes to the CI log, which is often readable by anyone who can
# see the job.
redact_url() {
  ru_scheme=""
  ru_rest="$1"
  case $ru_rest in
    *://*)
      ru_scheme="${ru_rest%%://*}://"
      ru_rest="${ru_rest#*://}"
      ;;
  esac
  # The userinfo, if any, precedes the first "/", "?", or "#":  the start of
  # the path, query, or fragment.  Testing only that prefix avoids mangling a
  # URL whose path, query, or fragment contains an "@".
  ru_authority="${ru_rest%%/*}"
  ru_authority="${ru_authority%%\?*}"
  ru_authority="${ru_authority%%#*}"
  case $ru_authority in
    # "git@github.com:org/repo" is a convention, not a credential.
    git@*) ;;
    *@*) ru_rest="REDACTED@${ru_rest#*@}" ;;
  esac
  printf '%s\n' "${ru_scheme}${ru_rest}"
}

### Organization

# The origin of the clone that the client called this script from.  Set here,
# not where it is first used, because three places want it:  the fallback for
# the organization, the cross-check of the organization that the CI service
# reports, and the --debug output.
URL=$(git config --get remote.origin.url)

## Continuous integration services
if [ "$TRAVIS" = "true" ]; then
  CI_ORGANIZATION=${TRAVIS_PULL_REQUEST_SLUG%/*}
  if [ -z "$CI_ORGANIZATION" ]; then
    CI_ORGANIZATION=${TRAVIS_REPO_SLUG%/*}
  fi
elif [ -n "$AZURE_HTTP_USER_AGENT" ]; then
  # TODO: Can I implement this without a GitHub API request?
  if [ "$BUILD_REASON" = "PullRequest" ]; then
    url="https://api.github.com/repos/${BUILD_REPOSITORY_NAME}/pulls/${SYSTEM_PULLREQUEST_PULLREQUESTNUMBER}"
    pull_json="$(get_url "${url}" 2>&1 | tr -d '[:cntrl:]')"
    SLUG=$(printf '%s' "${pull_json}" | jq -r '.head.label // empty' 2> /dev/null)
    if [ -z "$SLUG" ]; then
      emit_echo "${SCRIPT_NAME} error: bad output for ${url}"
      if [ -n "$auth_token" ]; then
        emit_echo "auth_token is set."
      fi
      emit_echo "---- start of ${http_get_tool} output ----"
      printf '%s\n' "${pull_json}" | emit_echo_lines
      emit_echo "---- end of ${http_get_tool} output ----"
      emit_exit 2
    fi
    CI_ORGANIZATION=${SLUG%:*}
  else
    CI_ORGANIZATION=${BUILD_REPOSITORY_NAME%/*}
    # CI_REPO=${BUILD_REPOSITORY_NAME##*/}
  fi
elif [ -n "$CIRCLE_PR_USERNAME" ]; then
  CI_ORGANIZATION="$CIRCLE_PR_USERNAME"
elif [ -n "$GITHUB_HEAD_REF" ]; then
  # GitHub Actions pull request

  # TODO: Can I implement this without a GitHub API request?
  # Is GITHUB_ACTOR equal to CI_ORGANIZATION, maybe??  (Need to observe beyond mernst.)
  GITHUB_PR_NUMBER=${GITHUB_REF_NAME%/merge}
  url="https://api.github.com/repos/${GITHUB_REPOSITORY}/pulls/${GITHUB_PR_NUMBER}"
  pull_json="$(get_url "${url}" 2>&1 | tr -d '[:cntrl:]')"
  # "// empty" maps JSON null to the empty string, to avoid yielding "null".
  CI_ORGANIZATION=$(printf '%s' "${pull_json}" | jq -r '.head.repo.owner.login // empty' 2> /dev/null)
  if [ -z "$CI_ORGANIZATION" ]; then
    # Warn and fall back, rather than failing:  a throttled request should not
    # fail the whole job.
    emit_echo "${SCRIPT_NAME} warning: bad output for ${url}"
    if [ -n "$auth_token" ]; then
      emit_echo "auth_token is set."
    fi
    emit_echo "---- start of ${http_get_tool} output ----"
    printf '%s\n' "${pull_json}" | emit_echo_lines
    emit_echo "---- end of ${http_get_tool} output ----"
    # GitHub Actions writes the event payload to the file named by
    # $GITHUB_EVENT_PATH, and for a pull request event that payload describes
    # the same pull request that the API request asked about -- including the
    # head repository, which is the fork if the pull request is from one.
    # Prefer it to the fallbacks below, which yield this clone's origin -- the
    # base repository, a wrong answer that a client cloning a companion
    # repository would act on without noticing.
    if [ -r "${GITHUB_EVENT_PATH}" ]; then
      CI_ORGANIZATION=$(jq -r '.pull_request.head.repo.owner.login // empty' "${GITHUB_EVENT_PATH}" 2> /dev/null)
    fi
    if [ -n "$CI_ORGANIZATION" ]; then
      emit_echo "${SCRIPT_NAME}: using organization ${CI_ORGANIZATION} from ${GITHUB_EVENT_PATH}."
    else
      emit_echo "${SCRIPT_NAME}: using the organization of this clone's origin instead,"
      emit_echo "which is the base repository if this is a pull request from a fork."
    fi
  fi
  if [ "$DEBUG" = "--debug" ]; then
    emit_echo "GitHub Actions pull request, GITHUB_HEAD_REF=${GITHUB_HEAD_REF}"
    emit_echo "GITHUB_PR_NUMBER=${GITHUB_PR_NUMBER}"
    emit_echo "CI_ORGANIZATION=${CI_ORGANIZATION}"
  fi
elif [ -n "$GITHUB_ACTIONS" ] && [ -n "$GITHUB_REPOSITORY" ]; then
  # GitHub Actions, non-pull-request.  $GITHUB_REPOSITORY is the repository the
  # job is running for.  Prefer it to the fallback below, which reads the origin
  # of whatever directory the client called this script from:  a client that
  # clones a companion repository may call from a sibling clone of a different
  # repository, whose origin names the wrong organization.
  # GitHub Actions always sets $GITHUB_REPOSITORY, but a self-hosted runner, a
  # container, or a tool such as `act` may pass on only $GITHUB_ACTIONS.  The
  # condition above tests for it, so that such a job falls through to the clone
  # below rather than getting an empty organization.
  CI_ORGANIZATION=${GITHUB_REPOSITORY%%/*}
  # Report the disagreement, as every other preference for the environment over
  # this clone does.  A job that runs in a sibling clone of another
  # organization's repository would otherwise silently get companion clones
  # from an organization that appears nowhere in its log.  GitHub owner names
  # are case-insensitive, so compare them that way:  a clone of this very
  # repository whose origin spells the owner differently is no disagreement.
  clone_organization=$(org_from_url "$URL")
  clone_organization_lower=$(to_lower "$clone_organization")
  ci_organization_lower=$(to_lower "$CI_ORGANIZATION")
  if [ -n "$clone_organization" ] && [ "$clone_organization_lower" != "$ci_organization_lower" ]; then
    emit_echo "${SCRIPT_NAME}: using organization ${CI_ORGANIZATION} from GITHUB_REPOSITORY=${GITHUB_REPOSITORY},"
    emit_echo "not ${clone_organization} from the origin of this clone."
  fi
  if [ "$DEBUG" = "--debug" ]; then
    emit_echo "GitHub Actions, not a pull request, GITHUB_REPOSITORY=${GITHUB_REPOSITORY}"
    emit_echo "CI_ORGANIZATION=${CI_ORGANIZATION}"
  fi
fi

## Git clone
if [ -z "$CI_ORGANIZATION" ]; then
  CI_ORGANIZATION=$(org_from_url "$URL")
  # TODO: Maybe add a sanity check here.
fi

## Default
if [ -z "$CI_ORGANIZATION" ]; then
  CI_ORGANIZATION="${DEFAULT_ORGANIZATION}"
fi

if [ "$DEBUG" = "--debug" ]; then
  emit_echo "CI_ORGANIZATION=${CI_ORGANIZATION}"
fi

### Other information (besides organization)

## `git remote show origin | grep 'HEAD branch' | cut -d' ' -f5` also works,
## but only in an English locale:  `git remote show` is porcelain, so git
## translates its output.  `git ls-remote` is plumbing, so its output is stable.
## The output is kept rather than piped straight into awk, so that the --debug
## block below can print it without asking origin a second time.  The
## redirection is inside the substitution, so that git's diagnostics are
## captured rather than written to this script's stderr:  an old git names the
## URL, credential and all, in them, hence `redact_tokens` at each use below.
ORIGIN_HEAD=$(git ls-remote --symref origin HEAD 2>&1)
DEFAULT_BRANCH_NAME=$(printf '%s\n' "${ORIGIN_HEAD}" | awk '/^ref:/ {sub(/refs\/heads\//, "", $2); print $2}')
if [ -z "$DEFAULT_BRANCH_NAME" ]; then
  # `git ls-remote` failed, or origin's HEAD is not a symbolic ref.  The
  # network may be down, or origin may require credentials that this checkout
  # does not have (a GitHub Actions job that uses `persist-credentials: false`
  # has none, for example).  Fall back to the remote-tracking HEAD that
  # `git clone` recorded locally.  Warn either way:  a client that silently
  # gets an empty default branch name computes something other than what it
  # asked for, and the resulting diagnostics blame the wrong thing.  Print
  # what git said, too:  it was captured above, so nothing else would report
  # it, and without it an authentication failure, an unreachable host, and a
  # deleted remote all look alike.
  local_head_ref=$(git symbolic-ref --quiet --short refs/remotes/origin/HEAD 2> /dev/null)
  DEFAULT_BRANCH_NAME=${local_head_ref#origin/}
  if [ -n "$DEFAULT_BRANCH_NAME" ]; then
    emit_echo "${SCRIPT_NAME}: cannot ask origin for its default branch; using ${DEFAULT_BRANCH_NAME} from refs/remotes/origin/HEAD instead:"
  else
    emit_echo "${SCRIPT_NAME}: WARNING: cannot determine the default branch name, from origin or from refs/remotes/origin/HEAD:"
  fi
  printf '%s\n' "${ORIGIN_HEAD}" | redact_tokens | emit_echo_lines
fi
if [ "$DEBUG" = "--debug" ]; then
  emit_echo "remote's DEFAULT_BRANCH_NAME=$DEFAULT_BRANCH_NAME"
  if [ -n "${URL}" ]; then
    echo "HEAD of $(redact_url "${URL}") = ${ORIGIN_HEAD}" | redact_tokens | emit_echo_lines
  else
    emit_echo "URL is empty (no remote named origin, or this directory is not a git clone)"
  fi
  emit_echo "current branch: $(git branch --show-current)"
fi

if [ -n "$SYSTEM_PULLREQUEST_TARGETBRANCH" ]; then
  ## Azure Pipelines pull request
  if [ "$DEBUG" = "--debug" ]; then
    emit_echo "Azure Pipelines pull request $SYSTEM_PULLREQUEST_TARGETBRANCH"
  fi
  # WARNING!  $BUILD_SOURCEBRANCHNAME is just a name, not a full ref path.  For example,
  # $BUILD_SOURCEBRANCHNAME may be "merge" when $BUILD_SOURCEBRANCH is "refs/pull/2971/merge".
  CI_BRANCH=$SYSTEM_PULLREQUEST_SOURCEBRANCH
  # HEAD = $BUILD_SOURCEVERSION is the merge commit refs/pull/N/merge, which
  # Azure checks out.  Its first parent HEAD^1 is the target branch (e.g.,
  # master), and its second parent is the pull request's head.  The range
  # HEAD^1...HEAD is the pull request's changes, as merged into the target
  # branch.  Its line numbers are those of the checked-out files, which are the
  # files that a client's tools examine.  Its merge base is HEAD^1, which is in
  # every clone except one made with `fetchDepth: 1`.  By contrast, the fork
  # point of the pull request's branch is absent from a shallow clone when the
  # branch lags its target branch by more commits than the clone's depth.
  if ! git rev-parse --verify --quiet HEAD^1 > /dev/null 2>&1; then
    # This clone has only HEAD, as `fetchDepth: 1` makes.
    unshallow
  fi
  CI_COMMIT_RANGE_START=$(head1)
  CI_COMMIT_RANGE_END=$(git rev-parse HEAD)
  CI_COMMIT_RANGE=${CI_COMMIT_RANGE_START}...${CI_COMMIT_RANGE_END}
elif [ -n "$BUILD_SOURCEBRANCH" ]; then
  # Azure Pipelines build for a branch (possibly master).
  if [ "$DEBUG" = "--debug" ]; then
    emit_echo "Azure Pipelines build for a branch $BUILD_SOURCEBRANCH"
    emit_echo "SYSTEM_PULLREQUEST_TARGETBRANCH=$SYSTEM_PULLREQUEST_TARGETBRANCH is not set but BUILD_SOURCEBRANCH=$BUILD_SOURCEBRANCH"
  fi
  # In Azure Pipelines:  BUILD_SOURCEBRANCH is a full ref path like "refs/heads/mybranch";
  # BUILD_SOURCEBRANCHNAME is a short name like "mybranch"; $BUILD_SOURCEVERSION is a commit ID.
  # Some clients such as `git-clone-related` MUST be given a branch name, not a commit ID.
  CI_BRANCH=$BUILD_SOURCEBRANCHNAME
  if [ "$BUILD_SOURCEBRANCHNAME" = "$DEFAULT_BRANCH_NAME" ]; then
    DEFAULT_CI_COMMIT_RANGE_START=$(head1)

    # If a build fails, we would like to continue failing subsequent
    # builds until the problem is fixed.  Using `git rev-parse HEAD^1`
    # does not do that, because there could have been multiple pushes
    # since the last successful CI job.
    # Pass argument to ci-last-success.py, because in a pull request
    # we are only interested in the last success on the master branch,
    # not on the feature branch!  The feature branch might have many
    # succeeding jobs and then ci-last-success.py will return just
    # part of the pull request's diffs.

    ## # ci-last-success.py is disabled here because it makes at least one
    ## # unauthenticated GitHub API request per commit -- two when the commit's
    ## # check runs do not show that CI failed, and more when they span several
    ## # pages -- so walking back far exhausts the 60-requests-per-hour limit.
    # # TODO: wrap all this in a ci-last-commit.sh shell script.
    # if pip3 list --format columns | tail -n +1 | grep -q '^requests ' ; then
    #   # echo "echo \"Python requests package is already installed\";"
    #   :
    # else
    #   (sudo pip3 install requests || pip3 install --user requests || true) > /dev/null 2>&1
    # fi
    # if pip3 list --format columns | tail -n +1 | grep -q '^requests ' ; then
    #   CI_COMMIT_RANGE_START=$(${SCRIPT_DIR}/ci-last-success.py ${CI_ORGANIZATION} ${CI_REPO} ${DEFAULT_CI_COMMIT_RANGE_START})
    #   if [ -z "$CI_COMMIT_RANGE_START" ] ; then
    #     echo "echo \"WARNING: ci-last-success.py script failed; just considering last commit.\";"
    #     CI_COMMIT_RANGE_START=${DEFAULT_CI_COMMIT_RANGE_START}
    #   elif ! git cat-file -e ${CI_COMMIT_RANGE_START}^{commit}; then
    #     # The commit is not in the repository.  Maybe it is older than the
    #     # commits pulled into this repository.
    #     echo "echo \"WARNING: ci-last-success.py script returned commit not in repository; using last commit.\";"
    #     CI_COMMIT_RANGE_START=${DEFAULT_CI_COMMIT_RANGE_START}
    #   else
    #     echo "echo \"ci-last-success.py ${CI_ORGANIZATION} ${CI_REPO} succeeded with $CI_COMMIT_RANGE_START.\";"
    #   fi
    # else
    #   echo "echo \"WARNING: Could not run ci-last-success.py script; just considering last commit.\";"
    #   CI_COMMIT_RANGE_START=${DEFAULT_CI_COMMIT_RANGE_START}
    # fi

    ## Use this because the ci-last-success.py call above is disabled.
    CI_COMMIT_RANGE_START=${DEFAULT_CI_COMMIT_RANGE_START}
  else
    git fetch origin "$DEFAULT_BRANCH_NAME"
    CI_COMMIT_RANGE_START=$(git rev-parse "origin/$DEFAULT_BRANCH_NAME")
  fi
  CI_COMMIT_RANGE_END=$BUILD_SOURCEVERSION
  CI_COMMIT_RANGE=${CI_COMMIT_RANGE_START}...${CI_COMMIT_RANGE_END}
elif [ "$TRAVIS" = "true" ]; then
  ## Travis CI
  if [ "$DEBUG" = "--debug" ]; then
    emit_echo "Travis CI $TRAVIS"
  fi
  CI_BRANCH=${TRAVIS_PULL_REQUEST_BRANCH:-$TRAVIS_BRANCH}
  if [ "$VERBOSE" = "--verbose" ]; then
    emit_echo "TRAVIS_PULL_REQUEST_BRANCH=$TRAVIS_PULL_REQUEST_BRANCH"
    emit_echo "TRAVIS_BRANCH=$TRAVIS_BRANCH"
    emit_echo "CI_BRANCH=$CI_BRANCH"
  fi
  # $TRAVIS_COMMIT_RANGE is empty for builds triggered by the initial commit of a new branch.
  CI_COMMIT_RANGE=$TRAVIS_COMMIT_RANGE

elif [ -n "$CIRCLECI" ]; then
  if [ "$DEBUG" = "--debug" ]; then
    emit_echo "CircleCI, CIRCLE_PULL_REQUEST=$CIRCLE_PULL_REQUEST"
  fi
  if [ -n "$CIRCLE_PR_NUMBER" ]; then
    # TODO: Can I implement this without a GitHub API request?
    # The request is unauthenticated, so it is subject to throttling; every
    # value it provides has a fallback that is computed locally.
    url="https://api.github.com/repos/${CIRCLE_PROJECT_USERNAME}/${CIRCLE_PROJECT_REPONAME}/pulls/${CIRCLE_PR_NUMBER}"
    pull_json="$(get_url "${url}" | tr -d '[:cntrl:]')"
    # "// empty" maps JSON null to the empty string; the redirection discards
    # jq's complaint if the response is not JSON at all (as when throttling
    # yields an HTML error page).
    CI_BRANCH=$(printf '%s' "${pull_json}" | jq -r '.head.ref // empty' 2> /dev/null)
    CI_COMMIT_RANGE_START=$(printf '%s' "${pull_json}" | jq -r '.base.sha // empty' 2> /dev/null)
    CI_COMMIT_RANGE_END=$(printf '%s' "${pull_json}" | jq -r '.head.sha // empty' 2> /dev/null)
    # The branch that the pull request is against.  It is usually the default
    # branch, but a pull request may be against any branch.
    base_branch=$(printf '%s' "${pull_json}" | jq -r '.base.ref // empty' 2> /dev/null)
    if [ -z "$base_branch" ]; then
      base_branch=$DEFAULT_BRANCH_NAME
    fi
    if [ -z "$CI_BRANCH" ]; then
      # For a pull request, this is like "pull/1234" rather than a branch name.
      CI_BRANCH=$CIRCLE_BRANCH
    fi
    if [ -z "$CI_COMMIT_RANGE_END" ] \
      || ! git rev-parse --verify -q "${CI_COMMIT_RANGE_END}^{commit}" > /dev/null; then
      # Either the GitHub API request supplied no head commit, or it supplied
      # one that is not in this clone (as happens when the pull request branch
      # was pushed to after this job checked it out).  Use the commit that this
      # job is actually testing.
      CI_COMMIT_RANGE_END=${CIRCLE_SHA1:-$(git rev-parse HEAD)}
    fi

    if [ -n "$CI_COMMIT_RANGE_START" ] && ! commit_range_is_usable; then
      # Fetch the branch that the commit is on.  Fetching by commit ID would be
      # cheaper, but not every server permits it; `git fetch --depth` would be
      # futile, because the commit is on a branch that this clone may not track
      # at all, and it would shorten a complete clone's history.
      fetch_base_branch
      if ! commit_range_is_usable; then
        if git rev-parse --verify -q "${CI_COMMIT_RANGE_START}^{commit}" > /dev/null; then
          # The commit is here, but this clone's history stops after the fork
          # point.  Completing the clone is the only way to reach it.
          unshallow
        fi
        if ! commit_range_is_usable; then
          # The commit is unreachable in origin, as after a force-push, so no
          # amount of fetching will produce it.
          emit_echo "${SCRIPT_NAME}: cannot use commit range start ${CI_COMMIT_RANGE_START} from the GitHub API."
          CI_COMMIT_RANGE_START=""
        fi
      fi
    fi

    if [ -z "$CI_COMMIT_RANGE_START" ]; then
      # Either the GitHub API request failed, or its answer is unusable.  Use
      # the fork point from the base branch instead.  Say so, because otherwise
      # the log gives no way to tell which of the two was used.
      emit_echo "${SCRIPT_NAME}: computing commit range start locally, as the fork point from ${base_branch:-the default branch}."
      fetch_base_branch
      if [ -n "$base_tip" ]; then
        # `merge_base` completes the clone if needed.  The base branch need not
        # be fetched again, because only this clone's own history can be
        # missing.
        CI_COMMIT_RANGE_START=$(merge_base "$base_tip" "$CI_COMMIT_RANGE_END")
      fi
      if [ -z "$CI_COMMIT_RANGE_START" ]; then
        # Last resort.  Under CircleCI, HEAD is the pull request's head branch,
        # so HEAD^1 is the pull request's next-to-last commit and the range
        # omits every earlier commit of the pull request.  Warn, because the
        # range is valid and non-empty, so no client will complain about it.
        CI_COMMIT_RANGE_START=$(head1)
        emit_echo "${SCRIPT_NAME}: WARNING: cannot find the fork point from ${base_branch:-the default branch}, so the commit range covers only the last commit."
      fi
    fi
    CI_COMMIT_RANGE="${CI_COMMIT_RANGE_START}...${CI_COMMIT_RANGE_END}"
  else
    CI_BRANCH=$CIRCLE_BRANCH
  fi

elif [ -n "${GITHUB_HEAD_REF}" ]; then
  # GitHub Actions pull request (no special handling is required for non-PR GitHub Actions jobs).
  if [ "$DEBUG" = "--debug" ]; then
    emit_echo "GitHub Actions pull request https://github.com/${GITHUB_REPOSITORY}/pull/${GITHUB_PR_NUMBER}"
    emit_echo "  GITHUB_BASE_REF=${GITHUB_BASE_REF}"
    emit_echo "  GITHUB_REF_NAME=${GITHUB_REF_NAME}"
    emit_echo "  GITHUB_SHA=${GITHUB_SHA}"
    # GITHUB_HEAD_REF is in the PR fork which is not available.
    emit_echo "  GITHUB_HEAD_REF=${GITHUB_HEAD_REF}"
  fi
  # At this point, these two are the same:
  # git rev-parse HEAD
  # git rev-parse remotes/pull/"${GITHUB_REF_NAME}"

  GITHUB_PR_NUMBER=${GITHUB_REF_NAME%/merge}

  CI_BRANCH="${GITHUB_HEAD_REF}"
  if ! CI_COMMIT_RANGE_START=$(git rev-parse "${GITHUB_BASE_REF}" 2> /dev/null); then
    if ! CI_COMMIT_RANGE_START=$(git rev-parse remotes/origin/"${GITHUB_BASE_REF}" 2> /dev/null); then
      if ! CI_COMMIT_RANGE_START=$(git rev-parse refs/remotes/origin/"${GITHUB_BASE_REF}" 2> /dev/null); then
        if ! CI_COMMIT_RANGE_START=$(git rev-parse refs/remotes/origin/"${DEFAULT_BRANCH_NAME}" 2> /dev/null); then
          pull_json="$(get_url "https://api.github.com/repos/${GITHUB_REPOSITORY}/pulls/${GITHUB_PR_NUMBER}" | tr -d '[:cntrl:]')"
          if ! CI_COMMIT_RANGE_START=$(printf '%s' "${pull_json}" | jq -e -r '.base.sha // empty'); then
            emit_echo "${SCRIPT_NAME} in $(pwd): cannot find commit range start, tried ${GITHUB_BASE_REF} and remotes/origin/${GITHUB_BASE_REF} and refs/remotes/origin/${GITHUB_BASE_REF} and refs/remotes/origin/${DEFAULT_BRANCH_NAME}"
            # This is a routine failure in a shallow single-branch checkout,
            # so dump the state only when asked.  `set` prints the whole
            # environment, and CI logs are often readable by anyone who can
            # see the job.
            if [ "$DEBUG" = "--debug" ]; then
              emit_echo '---------------- start of set'
              set | redact_tokens | emit_echo_lines
              emit_echo '---------------- end of set'
              # emit_echo "git branch:"
              # git --no-pager branch -a | cut -c 3- | emit_echo_lines
              emit_echo "git log --graph:"
              git log --graph | head --lines=1000 | emit_echo_lines
              emit_echo "git show:"
              git --no-pager show | head --lines=1000 | emit_echo_lines
            fi
            CI_COMMIT_RANGE_START=$(git rev-parse "${GITHUB_SHA}"^)
            # emit_echo "exiting"
            # # exit 2
            # exit
          fi
        fi
      fi
    fi
  fi
  # These are the same: `sha`=`echo $GITHUB_SHA`=`git rev-parse remotes/pull/"${GITHUB_REF_NAME}"`.
  CI_COMMIT_RANGE_END=${GITHUB_SHA}
  CI_COMMIT_RANGE="${CI_COMMIT_RANGE_START}...${CI_COMMIT_RANGE_END}"

  # If this elif is reached, it's not a pull request (except maybe a re-run Azure Pipelines pull request).
elif [ -n "$GITHUB_ACTIONS" ]; then
  # GitHub Actions, non-pull-request.
  if [ "$DEBUG" = "--debug" ]; then
    emit_echo "GitHub Actions, not a pull request, GITHUB_REF_NAME=${GITHUB_REF_NAME}, GITHUB_SHA=${GITHUB_SHA}, head=$(git rev-parse HEAD)"
  fi

  if [ "${GITHUB_EVENT_NAME}" = "pull_request" ]; then
    emit_echo "GITHUB_EVENT_NAME=${GITHUB_EVENT_NAME}"
    emit_exit 2
  fi

  # GITHUB_REF_NAME is the name of the branch or tag being built, except in a
  # pull request, where it is like "40/merge" and names no branch.  Tell the
  # two apart by the ref name's syntax.  Don't instead ask `git branch --list`
  # whether the name is a local branch:  a job that checked out a detached HEAD
  # or a different `ref` has no local branch of that name either, and then a
  # branch or tag name would be used as a pull request number, giving a 404 and
  # an empty CI_BRANCH.
  pr_number=""
  case "${GITHUB_REF_NAME}" in
    */merge)
      # A pull request number is a nonempty string of digits.  A branch may be
      # named "release/merge", which is not a pull request.
      case "${GITHUB_REF_NAME%/merge}" in
        '' | *[!0-9]*) ;;
        *) pr_number="${GITHUB_REF_NAME%/merge}" ;;
      esac
      ;;
  esac
  if [ -z "$pr_number" ]; then
    CI_BRANCH="${GITHUB_REF_NAME}"
  else
    # TODO: Can I implement this without a GitHub API request?
    url="https://api.github.com/repos/${GITHUB_REPOSITORY}/pulls/${pr_number}"
    pull_json="$(get_url "${url}" | tr -d '[:cntrl:]')"
    # "// empty" maps JSON null to the empty string, to avoid yielding "null".
    CI_BRANCH=$(printf '%s' "${pull_json}" | jq -r '.head.ref // empty' 2> /dev/null)
    if [ -z "$CI_BRANCH" ]; then
      emit_echo "${SCRIPT_NAME} warning: bad output for ${url}"
      if [ -n "$auth_token" ]; then
        emit_echo "auth_token is set."
      fi
      emit_echo "---- start of ${http_get_tool} output ----"
      printf '%s\n' "${pull_json}" | emit_echo_lines
      emit_echo "---- end of ${http_get_tool} output ----"
      # GitHub Actions writes the event payload to the file named by
      # $GITHUB_EVENT_PATH, and if this job was triggered by a pull request
      # event that payload names the same head branch that the API request
      # asked about.
      if [ -r "${GITHUB_EVENT_PATH}" ]; then
        CI_BRANCH=$(jq -r '.pull_request.head.ref // empty' "${GITHUB_EVENT_PATH}" 2> /dev/null)
      fi
      if [ -n "$CI_BRANCH" ]; then
        emit_echo "${SCRIPT_NAME}: using branch ${CI_BRANCH} from ${GITHUB_EVENT_PATH}."
      else
        # Unlike the organization, the branch has no fallback here:
        # GITHUB_REF_NAME is like "42/merge", which names no branch, and this
        # clone's HEAD is the merge commit, which is on no branch either.
        # Report failure rather than printing an empty CI_BRANCH, which a
        # client would use as if it were a branch name.
        emit_echo "${SCRIPT_NAME}: cannot determine the branch of ${url}"
        emit_exit 2
      fi
    fi
  fi
  CI_COMMIT_RANGE_END="${GITHUB_SHA}"

else

  if [ "$DEBUG" = "--debug" ]; then
    emit_echo "Else clause: no CI environment detected"
  fi
  # git 2.22 and later has `git branch --show-current`; CircleCI doesn't have that version yet.
  CI_BRANCH=$(git rev-parse --abbrev-ref HEAD)
  # In an Azure Pipelines pull request, `git branch` yields "(HEAD detached at pull/4/merge)".
  # If you re-run a pull request via "Queue" rather than "Rebuild",
  # variables SYSTEM_PULLREQUEST_TARGETBRANCH and SYSTEM_PULLREQUEST_SOURCEBRANCH are not set.
  if [ "$CI_BRANCH" = '(HEAD' ]; then
    CI_BRANCH=$DEFAULT_BRANCH_NAME
  fi
fi

if [ "$DEBUG" = "--debug" ]; then
  emit_echo "CI_BRANCH=${CI_BRANCH}"
  emit_echo "CI_COMMIT_RANGE_START=${CI_COMMIT_RANGE_START}"
  emit_echo "CI_COMMIT_RANGE_END=${CI_COMMIT_RANGE_END}"
  emit_echo "CI_COMMIT_RANGE=${CI_COMMIT_RANGE}"
fi

## The above may not have set CI_COMMIT_RANGE.  Set it.

# Separate from "It's not a pull request" because sometimes this is not set for Travis.
if [ -z "$CI_COMMIT_RANGE" ]; then
  if [ "$DEBUG" = "--debug" ]; then
    emit_echo "Setting CI_COMMIT_RANGE from CI_BRANCH=$CI_BRANCH"
  fi
  if [ "$CI_BRANCH" = "$DEFAULT_BRANCH_NAME" ]; then
    if is_merge HEAD; then
      CI_COMMIT_RANGE_START=$(merge_base HEAD^1 HEAD^2)
    else
      CI_COMMIT_RANGE_START=$(head1)
    fi
    CI_COMMIT_RANGE_END=$(git rev-parse HEAD)
  else
    # "origin/$DEFAULT_BRANCH_NAME" is accurate when the pull request was
    # created, but it doesn't change when force-push occurs (as Renovate does),
    # making it out of date.
    CI_COMMIT_RANGE_END=$(git rev-parse "$CI_BRANCH")
    case $CI_BRANCH in
      renovate/*) CI_COMMIT_RANGE_START=$(head1) ;;
      *)
        # Fetch the default branch rather than trusting "origin/$DEFAULT_BRANCH_NAME",
        # which can be arbitrarily out of date.  For example, when CircleCI restores a
        # clone from its cache, its checkout step fetches only the branch being built.
        CI_COMMIT_RANGE_START=""
        base_branch=${base_branch:-$DEFAULT_BRANCH_NAME}
        fetch_base_branch
        if [ -n "$base_tip" ]; then
          # If the end has no merge base with the fetched tip, as for an orphan
          # branch such as "gh-pages", leave the start empty for the code below.
          # Do not fall back to "origin/$DEFAULT_BRANCH_NAME":  the fetch has
          # just updated it, so it has no merge base with the end either, and
          # `git diff` would reject the range.
          CI_COMMIT_RANGE_START=$(merge_base "$base_tip" "$CI_COMMIT_RANGE_END")
          if [ -n "$CI_COMMIT_RANGE_START" ] && [ "$DEBUG" = "--debug" ]; then
            emit_echo "Set CI_COMMIT_RANGE_START=$CI_COMMIT_RANGE_START as the fork point from ${base_branch}"
          fi
        elif git rev-parse --verify --quiet "origin/$DEFAULT_BRANCH_NAME" > /dev/null 2>&1; then
          CI_COMMIT_RANGE_START=$(git rev-parse "origin/$DEFAULT_BRANCH_NAME")
          if [ "$DEBUG" = "--debug" ]; then
            emit_echo "Set CI_COMMIT_RANGE_START=$CI_COMMIT_RANGE_START from git rev-parse origin/$DEFAULT_BRANCH_NAME"
          fi
        fi
        if [ -z "$CI_COMMIT_RANGE_START" ]; then
          if is_merge HEAD; then
            CI_COMMIT_RANGE_START=$(merge_base HEAD^1 HEAD^2)
          else
            CI_COMMIT_RANGE_START=$(head1)
          fi
        fi
        ;;
    esac
  fi
  CI_COMMIT_RANGE=${CI_COMMIT_RANGE_START}...${CI_COMMIT_RANGE_END}
  if [ "$DEBUG" = "--debug" ]; then
    emit_echo "CI_BRANCH=${CI_BRANCH}"
    emit_echo "CI_COMMIT_RANGE_START=${CI_COMMIT_RANGE_START}"
    emit_echo "CI_COMMIT_RANGE_END=${CI_COMMIT_RANGE_END}"
    emit_echo "CI_COMMIT_RANGE=${CI_COMMIT_RANGE}"
  fi
fi

if [ -z "$CI_COMMIT_RANGE_START" ]; then
  if [ "$DEBUG" = "--debug" ]; then
    emit_echo "Setting CI_COMMIT_RANGE_START from CI_COMMIT_RANGE=$CI_COMMIT_RANGE"
  fi
  CI_COMMIT_RANGE_START=${CI_COMMIT_RANGE%%.*}
  CI_COMMIT_RANGE_END=${CI_COMMIT_RANGE##*.}
  if [ -z "$CI_COMMIT_RANGE_START" ]; then
    CI_COMMIT_RANGE_START=${CI_COMMIT_RANGE_END}
  fi
fi

# Avoid errors regarding empty range
if [ "$CI_COMMIT_RANGE_START" = "$CI_COMMIT_RANGE_END" ]; then
  if [ "$VERBOSE" = "--verbose" ]; then
    emit_echo "Resetting CI_COMMIT_RANGE_START because CI_COMMIT_RANGE=$CI_COMMIT_RANGE"
  fi
  if is_merge "$CI_COMMIT_RANGE_END"; then
    CI_COMMIT_RANGE_START=$(merge_base "$CI_COMMIT_RANGE_END^1" "$CI_COMMIT_RANGE_END^2")
  else
    if git rev-parse --verify --quiet "$CI_COMMIT_RANGE_END^1" > /dev/null 2>&1; then
      CI_COMMIT_RANGE_START=$(git rev-parse "$CI_COMMIT_RANGE_END^1")
    fi
  fi
  # The start and end commits could still be the same, if the current branch was cloned with
  # --depth=1.
  CI_COMMIT_RANGE="${CI_COMMIT_RANGE_START}...${CI_COMMIT_RANGE_END}"
fi

if [ "$VERBOSE" = "--verbose" ]; then
  # A throttled or otherwise failed request also has a non-empty response body,
  # so test whether the response really does describe a pull request.
  if [ -n "${pull_json}" ] \
    && printf '%s' "${pull_json}" | jq -e -r '.head.sha // empty' > /dev/null 2>&1; then
    emit_echo "CI_ACCESSED_GITHUB_API=true"
  else
    emit_echo "CI_ACCESSED_GITHUB_API=false"
  fi
fi

if [ "$VERBOSE" = "--verbose" ]; then
  emit_echo '---------------- start of first 10000 lines of diff:'
  git --no-pager diff "${CI_COMMIT_RANGE}" | head --lines=10000 | emit_echo_lines
  emit_echo '---------------- end of first 10000 lines of diff.'
fi

# The diff might be empty if the last commit is the revert of the one before it.

### Print it out

if [ "$VERBOSE" = "--verbose" ]; then
  emit_echo "CI_ORGANIZATION=$CI_ORGANIZATION"
fi
echo "CI_ORGANIZATION=$(shell_quote "$CI_ORGANIZATION"); export CI_ORGANIZATION;"
if [ "$VERBOSE" = "--verbose" ]; then
  emit_echo "CI_BRANCH=$CI_BRANCH"
fi
echo "CI_BRANCH=$(shell_quote "$CI_BRANCH"); export CI_BRANCH;"
if [ "$VERBOSE" = "--verbose" ]; then
  emit_echo "CI_COMMIT_RANGE_START=$CI_COMMIT_RANGE_START"
fi
echo "CI_COMMIT_RANGE_START=$(shell_quote "$CI_COMMIT_RANGE_START"); export CI_COMMIT_RANGE_START;"
if [ "$VERBOSE" = "--verbose" ]; then
  emit_echo "CI_COMMIT_RANGE_END=$CI_COMMIT_RANGE_END"
fi
echo "CI_COMMIT_RANGE_END=$(shell_quote "$CI_COMMIT_RANGE_END"); export CI_COMMIT_RANGE_END;"
if [ "$VERBOSE" = "--verbose" ]; then
  emit_echo "CI_COMMIT_RANGE=$CI_COMMIT_RANGE"
fi
echo "CI_COMMIT_RANGE=$(shell_quote "$CI_COMMIT_RANGE"); export CI_COMMIT_RANGE;"
