简体   繁体   中英

How do I get the git revision of my project assuming there are no committed changes?

I want a way to be able to return "unknown" as my git revision if I have uncommitted changes locally. If not, it should return the correct git revision.

String getGitRevision() {
    String gitRevision = "unknown"
    try {
        def cmd = "git rev-parse HEAD"
        def proc = cmd.execute()
        gitRevision = proc.text.trim()
    }
    catch (IOException ioe) {
        println "Fetch revision failed."
    }
    return gitRevision;
}

I expect that when I have uncommitted changes locally, getGitRevision() returns unknown.

But even when I have uncommitted changes, it grabs the correct revision id. I'm not really sure how to add that logic in.

HEAD is parseable as a commit as long as there is a current commit, and there is almost always a current commit. "Uncommitted changes" is not relevant to whether there is a current commit.

To compare the index and work-tree to the current commit, use git status . To do this reliably, in your own software, consider using git --no-optional-locks status --porcelain=v2 , perhaps with -z as well, and reading its output, which is shown in the git status documentation . Your code can then choose what to consider "uncommitted changes" (including untracked files, and, if you add --ignored , ignored files).

For this particular case, you can just use git describe --always --dirty and check for the -dirty suffix. Or—since this is what git describe itself does—run git diff-index --quiet HEAD and check its exit status: 0 means "not dirty", 1 means "dirty", anything else means "unable to tell, something went wrong". The method using git status --porcelain... is the most flexible, as it lets you define what you mean by "dirty", but the other two are much simpler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM