scripts/update-third-party-notices-pr.sh
#!/bin/bash

# This script is used to update the THIRD_PARTY_NOTICES.txt file in the repository with the latest third party notices
# report generated by FOSSA, using `make generate-third-party-notices`.
# If you are a Confluent engineer running this script locally, ensure you have logged into Vault before running this script.

# IMPORTANT: The script will raise a GitHub pull request against the branch checked out locally, so make sure to
#            checkout to the desired branch and pull the latest changes from remote before running this script.

GIT_REMOTE_NAME="origin"
BASE_BRANCH=$(git rev-parse --abbrev-ref HEAD)
PR_BRANCH="update-third-party-notices-${BASE_BRANCH}"

# Don't use [ci skip] for branches other than main, since branch protection rules* will require CI
# checks to pass before merging. If [ci skip] is used, we will need to manually push an empty commit
# without [ci skip] to cause the CI checks to run.
# (*This only applies to release branches, which is really the only other path since we don't create
# third party notice PRs for normal development branches.)
CI_SKIP_SUFFIX=""
if [[ "${BASE_BRANCH}" == "main" ]]; then
  CI_SKIP_SUFFIX=" [ci skip]"
fi
COMMIT_MESSAGE="[${BASE_BRANCH}] chore: update third party notices${CI_SKIP_SUFFIX}"

push_local_changes() {
  git commit -q -m "${COMMIT_MESSAGE}"
  git push -q -f -u "${GIT_REMOTE_NAME}" "${PR_BRANCH}"
  gh pr create \
    --base "${BASE_BRANCH}" \
    --head "${PR_BRANCH}" \
    --title "${COMMIT_MESSAGE}" \
    --body "${COMMIT_MESSAGE}"
}

main() {
  # Generate third party notices
  make generate-third-party-notices

  # Update NOTICE-vsix.txt
  make collect-notices-vsix

  # Add, commit, push and create PR
  echo "Checking if there is already a PR opened"
  if gh pr list -B "${BASE_BRANCH}" | grep "${COMMIT_MESSAGE}" ; then
    echo "there is already a update third party notices PR opened; close or merge it before running this script"
  else
    # delete local update branch if it exists
    git branch -D "${PR_BRANCH}" &>/dev/null || true
    git checkout -b "${PR_BRANCH}" ${BASE_BRANCH}

    if git add THIRD_PARTY_NOTICES.txt NOTICE-vsix.txt && \
     git diff --cached --exit-code --quiet; then
      echo "No changes detected. Not creating PR.";
    else
      push_local_changes || true
    fi
  fi
}

main
