I have a project that now needs to know what branch it's currently operating under when it builds. The nature of our build process prevents us from using multibranch pipelines or similar freestyle jobs. I have discovered the related issue
JENKINS-43104 which describes the behaviour I'm experiencing. BRANCH_NAME is not set at all for non-multibranch jobs.
I have a sample Maven project that tries to commit changes from the build back to the repository but fails due to missing branch information. This can be found at https://github.com/kenrachynski/pipeline-branch-error.git
Running the maven build in a freestyle job exhibits the exact same behaviour. The error:
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-scm-plugin:1.9.5:checkin (04-commit) on project pipeline-branch-error: Cannot run checkin command : Exception while executing SCM command. Detecting the current branch failed: fatal: ref HEAD is not a symbolic ref -> [Help 1]