2

I'm working with a ruby script that execute the following git command on a given git repository.

  branches = `git branch -a --contains #{tag_name}`

This approach has some drawbacks with command output (that may change in different git versions) and is subject to git binary version on the hosting machine, so I was trying to see if it's possible to replace that command using rugged but I wasn't able to find anything similar to that.

Maybe in rugged there's no way to implement --contains flag, but I think it should be pretty easy to implement this behavior:

Given any git commit-ish (a tag, a commit sha, etc.) how to get (with rugged) the list of branches (both local and remote) that contains that commit-ish?

I need to implement something like github commit show page, i.e. tag xyz is contained in master, develop, branch_xx

Fabio
  • 18,856
  • 9
  • 82
  • 114
  • want to exactly this thing. Did you ever figure this out?? – quinn Aug 30 '19 at 20:26
  • 1
    @quinn yes I did it, here's the code: https://github.com/uala/drone-rancher-deploy/blob/master/lib/rancher_deployer/tag_checker.rb#L33-L45 – Fabio Sep 02 '19 at 16:41

1 Answers1

1

Finally solved with this code:

def branches_for_tag(tag_name, repo_path = Dir.pwd)
  @branches ||= begin
    repo = Rugged::Repository.new(repo_path)
    # Convert tag to sha1 if matching tag found
    full_sha = repo.tags[tag_name] ? repo.tags[tag_name].target_id : tag_name
    logger.debug "Inspecting repo at #{repo.path}, branches are #{repo.branches.map(&:name)}"
    # descendant_of? does not return true for it self, i.e. repo.descendant_of?(x, x) will return false for every commit
    # @see https://github.com/libgit2/libgit2/pull/4362
    repo.branches.select { |branch| repo.descendant_of?(branch.target_id, full_sha) || full_sha == branch.target_id }
  end
end
Fabio
  • 18,856
  • 9
  • 82
  • 114