Skip to content

Instantly share code, notes, and snippets.

@pablisco
Created August 14, 2014 15:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pablisco/bff04dd75ff770e97d07 to your computer and use it in GitHub Desktop.
Save pablisco/bff04dd75ff770e97d07 to your computer and use it in GitHub Desktop.
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
}
}
@pablisco
Copy link
Author

Usage:

def utils = new GitUtils(new File("/git/epo/"))
utils.tags.by('b')
utils.branches.current

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment