Created
August 14, 2014 15:01
-
-
Save pablisco/bff04dd75ff770e97d07 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class GitUtils { | |
def final static NO_BRANCH = new Branch(name: "NO_BRANCH") | |
def final static NO_TAG = new Tag(name: "NO_TAG") | |
static class Tag implements CharSequence { | |
private @Delegate CharSequence name | |
@Override | |
String toString() { name ? name.toString() : 'null' } | |
def hasPrefix = { name && name.startsWith(it) } | |
} | |
static class Branch implements CharSequence { | |
private @Delegate CharSequence name | |
@Lazy def isCurrent = name && length() > 0 && charAt(0) == '*' | |
@Override | |
public String toString() { isCurrent ? name.toString().substring(2) : name.toString().trim() } | |
} | |
private class TagList extends List<Tag> { | |
@Delegate List<Tag> tags = execute("tag").collect { new Tag(name: it) } ?: [NO_TAG] | |
def by = { prefix -> tags.findAll{ it.hasPrefix(prefix) } ?: [NO_TAG] } | |
} | |
private class BranchList extends List<Branch> { | |
@Delegate List<Branch> branches = execute("branch").collect { new Branch(name: it) } ?: [NO_BRANCH] | |
@Lazy def current = branches?.find { it.isCurrent } ?: NO_BRANCH | |
} | |
@Lazy def tags = new TagList(); | |
@Lazy def branches = new BranchList(); | |
/** | |
* Path in which to work on | |
*/ | |
def final path | |
GitUtils(File path) { | |
this.path = path | |
} | |
/** | |
* Executes the git command and returns an array with all the | |
*/ | |
def execute = { command -> | |
def proc = ("git " + command).execute(null, path) | |
proc.waitFor() | |
def out = proc.in.text.trim() | |
// return null if no output is provided to use the elvis format | |
out && out.length() > 0 ? out.split("\n") : null | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: