How to add jenkins git branch build_number inside jar manifest

In maven , I could do it like this

<plugin>
			<groupId>org.apache.maven.plugins</groupId>
			<artifactId>maven-war-plugin</artifactId>
			<configuration>
				<manifest>
					<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
				</manifest>
				<archive>
					<manifestEntries>
						<Specification-Title>${project.name}</Specification-Title>
						<Specification-Version>${project.version}</Specification-Version>
		
						<GIT_BRANCH>${GIT_BRANCH}</GIT_BRANCH>
						<GIT_COMMIT>${GIT_COMMIT}</GIT_COMMIT>
		
						<BUILD_ID>${BUILD_ID}</BUILD_ID>
						<BUILD_NUMBER>${BUILD_NUMBER}</BUILD_NUMBER>
						<JOB_NAME>${JOB_NAME}</JOB_NAME>
		
						<BUILD_NUMBER>${BUILD_NUMBER}</BUILD_NUMBER>
						<BUILD_TAG>${BUILD_TAG}</BUILD_TAG>
					</manifestEntries>
				</archive>
			</configuration>
		</plugin>

I could build it in jenkins and local.

But with gradle, how should I do? Gradle throw error “No such property: BUILD_NUMBER for class:”

Jenkins exposes these to Gradle in the form of environment variables. Therefore you can access them in your Gradle build script as System.env.BUILD_NUMBER.

I got this error when I run in my local instead of jenkins.

"The value of a manifest attribute must not be null"

I got this error when I run in my local
"The value of a manifest attribute must not be null"

This is because the BUILD_NUMBER environment variable does not exist in your local environment. (see the System API)

If your Gradle build is executed in Jenkins and also locally, you have to be sure to

  • either create the BUILD_NUMBER environment variable in your local environment as well (if you plan to use it as well for a local build, which is questionable)
  • add custom logic to avoid putting this information in the manifest when executing a local build

How was it done before your transition to Gradle ?

Using my own experience, at work we have a boolean property (userIsCiServer) which is sets to true only if Gradle is executed from Jenkins. This allows to have two distincts behaviors, whether the build is executed locally or in jenkins.

A simple approach could be to simply check for the presence of the BUILD_NUMBER environment variable before using it, with something like

System.env.contains('BUILD_NUMBER')

or simply using Groovy String coercion

if(System.env.BUILD_NUMBER){
  // add the stuff you want in your manifest
}

I’m trying to this but it throws
Could not find method versionCode() for arguments [78] on ProductFlavor_Decorated when I try to compile