balupton
balupton

Reputation: 48650

Check if a git branch exists in the local repository with ruby?

What would be the best way of checking if git branch exists in the local git repository with ruby? My ruby skills are not that good, so would like to know the best way of going about it :) Thanks.

Upvotes: 0

Views: 1801

Answers (2)

balupton
balupton

Reputation: 48650

I ended up coming up with this:

# Check if a Branch Exists
def branch_exists(branch)
    branches = run("git branch",false)
    regex = Regexp.new('[\\n\\s\\*]+' + Regexp.escape(branch.to_s) + '\\n')
    result = ((branches =~ regex) ? true : false)
    return result
end

Where run is a backtick expression. The reasoning is that the code is to be highly portable and is not allowed any other dependencies. Whereas git is installed in the environment.

Upvotes: 0

miku
miku

Reputation: 188014

There are ruby libraries for accessing git repositories, one being grit.

To install use [sudo] gem install grit.

$ irb
>> require 'grit'
=> true
>> repo = Grit::Repo.new('/path/to/your/repo/')
=> #<Grit::Repo "/path/to/your/repo/.git">
>> repo.branches
=> [#<Grit::Head "master">, #<Grit::Head "some-topic-branch">, ...]

Upvotes: 5

Related Questions