Automatic versioning of Android build using git describe with Gradle

后端 未结 10 1968
醉酒成梦
醉酒成梦 2020-11-30 18:18

I have searched extensively, but likely due to the newness of Android Studio and Gradle. I haven\'t found any description of how to do this. I want to do basically exactly

10条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-30 19:10

    Based on Léo Lam's answer and my earlier explorations on the same solution for ant, I have devised a purely cross-platform solution using jgit:

    (original source)

    File: git-version.gradle

    buildscript {
        dependencies {
            //noinspection GradleDynamicVersion
            classpath "org.eclipse.jgit:org.eclipse.jgit:4.1.1.+"
        }
        repositories {
            jcenter()
        }
    }
    import org.eclipse.jgit.api.Git
    import org.eclipse.jgit.revwalk.RevWalk
    import org.eclipse.jgit.storage.file.FileRepositoryBuilder
    
    import static org.eclipse.jgit.lib.Constants.MASTER
    
    def git = Git.wrap(new FileRepositoryBuilder()
            .readEnvironment()
            .findGitDir()
            .build())
    
    ext.readVersionCode = {
        def repo = git.getRepository()
        def walk = new RevWalk(repo)
        walk.withCloseable {
            def head = walk.parseCommit(repo.getRef(MASTER).getObjectId())
            def count = 0
            while (head != null) {
                count++
                def parents = head.getParents()
                if (parents != null && parents.length > 0) {
                    head = walk.parseCommit(parents[0])
                } else {
                    head = null
                }
            }
            walk.dispose()
            println("using version name: $count")
            return count
        }
    }
    
    ext.readVersionName = {
        def tag = git.describe().setLong(false).call()
        def clean = git.status().call().isClean()
        def version = tag + (clean ? '' : '-dirty')
        println("using version code: $version")
        return version
    }
    

    The usage will be:

    apply from: 'git-version.gradle'
    
    android {
      ...
      defaultConfig {
        ...
        versionCode readVersionCode()
        versionName readVersionName()
        ...
      }
      ...
    }
    

提交回复
热议问题