package io.freefair.gradle.plugins.git;

import org.codehaus.groovy.runtime.ProcessGroovyMethods;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.logging.Logger;

public class GitVersionPlugin implements Plugin<Project> {

    private Project project;
    private Logger logger;

    @Override
    public void apply(Project project) {
        this.project = project;
        this.logger = project.getLogger();
        project.setVersion(resolveVersion());

        project.allprojects(p -> p.setVersion(project.getVersion()));
    }

    private Object resolveVersion() {
        if (!"unspecified".equals(project.getVersion().toString())) {
            logger.lifecycle("Using explicit version {}", project.getVersion());
            return project.getVersion();
        }

        String travisTag = System.getenv("TRAVIS_TAG");
        if (travisTag != null && !travisTag.trim().isEmpty()) {
            logger.lifecycle("Using TRAVIS_TAG as version: {}", travisTag);
            return travisTag;
        }

        String travisBranch = System.getenv("TRAVIS_BRANCH");
        if (travisBranch != null) {
            travisBranch = travisBranch.replace("/", "-");
            String version = travisBranch + "-SNAPSHOT";
            logger.lifecycle("Using TRAVIS_BRANCH as version: {}", version);
            return version;
        }

        try {
            Process execute = ProcessGroovyMethods.execute("git symbolic-ref --short HEAD");
            String gitBranch = ProcessGroovyMethods.getText(execute).trim();

            if (!gitBranch.isEmpty()) {
                gitBranch = gitBranch.replace("/", "-");
                String version = gitBranch + "-SNAPSHOT";
                logger.lifecycle("Using git branch as version: {}", version);
                return version;
            }
        } catch (Exception ignored) {
        }

        return project.getVersion();
    }
}

@@ -1362,32 +1362,479 @@
 ion;%0A        %7D%0A%0A
+        try %7B%0A            Process execute = ProcessGroovyMethods.execute(%22git describe --tags --exact-match%22);%0A            String gitTag = ProcessGroovyMethods.getText(execute).trim();%0A%0A            if (!gitTag.isEmpty()) %7B%0A                logger.lifecycle(%22Using git tag as version: %7B%7D%22, gitTag);%0A                return gitTag;%0A            %7D%0A        %7D catch (Exception e) %7B%0A            logger.debug(%22Failed to get current git tag%22, e);%0A        %7D%0A%0A
         try %7B%0A  
@@ -1920,24 +1920,24 @@
 ort HEAD%22);%0A
-
             
@@ -2312,18 +2312,77 @@
 ion 
-ignored) %7B
+e) %7B%0A            logger.debug(%22Failed to get current git branch%22, e);
 %0A   

Use git tag as version when present