thii / aws-codebuild-extras

Add extra information of your AWS CodeBuild build via environment variables.
150 stars 115 forks source link

CODEBUILD_GIT_BRANCH sometimes mis-identified #13

Closed dls314 closed 4 years ago

dls314 commented 4 years ago

I ran into a scenario where the CODEBUILD_GIT_BRANCH was mis-identified.

A commit to main triggered a build, and a very quick commit to another branch followed. When CodePipeline and CodeBuild ran and sourced the install script, the CODEBUILD_GIT_BRANCH identified was the branch of the subsequent commit.

I am not a git expert, please bear with the rest of the issue :-)

export CODEBUILD_GIT_BRANCH="$(git symbolic-ref HEAD --short 2>/dev/null)"
if [ "$CODEBUILD_GIT_BRANCH" = "" ] ; then
  CODEBUILD_GIT_BRANCH="$(git branch -a --contains HEAD | sed -n 2p | awk '{ printf $1 }')";
  export CODEBUILD_GIT_BRANCH=${CODEBUILD_GIT_BRANCH#remotes/origin/};
fi

In this pipeline run, I downloaded the output zip artifact (which has the .git directory) and ran some commands...

$ git symbolic-ref HEAD
fatal: ref HEAD is not a symbolic ref

So the second method is used

$ git branch -a --contains HEAD
* (no branch)
  bug/4762
  master
  remotes/origin/bug/4762
  remotes/origin/master

The commit was to master, and I think a command like the following (thank you, https://stackoverflow.com/a/52947601/1661089) might have worked better

$ git rev-parse HEAD | xargs git name-rev | cut -d' ' -f2 | sed 's/remotes\/origin\///g'
master