1
def generateVersion() {
    def commitCount = sh(script: "git rev-list --count HEAD", returnStdout: true).trim() as Integer
    echo "this is commitcount------------->>>>>>>>>>>>>>>> ${commitCount}";
    def metadata = readJSON file: 'package.json'
    def (major, minor) = metadata.version.tokenize('.')
    def patch = commitCount
    def prerelease = env.BRANCH_NAME == 'master' ? '' : "-${env.BRANCH_NAME}"
    return "${major}.${minor}.${patch}${prerelease}"
}

This is a groovy code that I have written in my Jenkinsfile. It is supposed to return me a unique version of the build. This function gets called in a stage Publish Libraries.

....
stage('Publish Libraries') {
            dir('External') {
                libVersion = generateVersion()
...
...

I am not able to get the correct value of commitCount and therefore wrong value of patch. It stays consistent at value 5 no matter how many commits I make in my branch. I have created a branch off of another feature branch that initally had 56 commits. So when i created a branch it initally had those 56 commits. I added 11 commits of my own in the newly created branch so a total of 67 commits are there in the branch but it shows the count as only 5. What should I do?

I even tried:

def commitCount = sh(script: "git rev-list --count ${env.BRANCH_NAME}", returnStdout: true).trim() as Integer

thinking that maybe my HEAD gets set to some other branch without my knowledge. But still commitCount is 5.

1 Answers1

-1

You're almost certainly using a shallow clone with --depth=5 (and the corresponding implied --single-branch). In this case, the revisions counted by git rev-list HEAD will never exceed five. To fix the problem, tell Jenkins to use a non-shallow clone (see git clone without history using SCM).

Note that --count is not a reliable way to get a unique revision specifier even if you make a full (non-shallow) clone. The reason is simple enough: the number of commits reachable from some branch tip does not necessarily increase (e.g., git reset removes commits from the branch tip), and the number of commits reachable from, e.g., feature/a and from feature/b may be the same:

          o--o   <-- feature/1
         /
...--o--o   <-- main
         \
          o--o   <-- feature/b

Here, let's say that the revision count found by starting from main and working backwards is 200. There are two commits on each feature branch that are not on main, plus the 200 commits that are on main, so the count on both branches will be 202. Yet the commits on feature/a differ from the commits on feature/b.

If you want a unique descriptive name for a commit that's at least marginally less ugly than a raw hash ID, consider using git describe (perhaps with --always and/or --dirty). To make it work well, be sure to use tags (preferably annotated tags for releases) and maybe add the --tags option.

torek
  • 448,244
  • 59
  • 642
  • 775