Home > Back-end >  How can I determine the action that originated a commit within Gitlab?
How can I determine the action that originated a commit within Gitlab?

Time:07-07

In Github there are environment variables like GITHUB_VIA that expose the action that originated a git commit. In the example below, taken from here, this is used to protect default branches.

Is there something similar for Gitlab? I'm coding a pre-receive hook and I can't find this documented anywhere on Gitlab's doc.

#!/bin/bash
#
# This hook restricts changes on the default branch to those made with the GUI Pull Request Merge button, or the Pull Request Merge API.
#
DEFAULT_BRANCH=$(git symbolic-ref HEAD)
while read -r oldrev newrev refname; do
  if [[ "${refname}" != "${DEFAULT_BRANCH:=refs/heads/master}" ]]; then
    continue
  else
    if [[ "${GITHUB_VIA}" != 'pull request merge button' && \
          "${GITHUB_VIA}" != 'pull request merge api' ]]; then
      echo "Changes to the default branch must be made by Pull Request. Direct pushes, edits, or merges are not allowed."
      exit 1
    else
      continue
    fi
  fi
done

I'm looking for environment variables I could use within the context of a pre-receive on Gitlab, such as these ones on GHE.

CodePudding user response:

Besides the information that is normally exposed in git pre-receive hooks, GitLab does provide some additional environment variables. The closest thing to GITHUB_VIA would be GL_PROTOCOL, which can tell you some information like if a push was made using http/ssh or the web UI. The value of this variable will be either http ssh or web accordingly.

So, in your case you might do something like:

if [[ "$GL_PROTOCOL" != "web" ]]; then
  echo "Changes to the default branch must be made by Pull Request. Direct pushes, edits, or merges are not allowed."
  exit 1
fi   

It is worth mentioning, however, that GitLab has controls for this use case directly in the project settings in protected branches. For example, you can create a protected branch rule that prohibits pushes to the branch and only allows changes via an MR. So you should be able to achieve the same effect in GitLab without a pre-receive hook.

CodePudding user response:

Yea. Gitlab also has a list of pre-defined environment variables that you can use within your gitlab-ci.yml file.

You can find a list of them on gitlabs documentation website - here’s a link https://docs.gitlab.com/ee/ci/variables/predefined_variables.html

  • Related