rubylibgit2rugged

"git branch --merged <sha>" via Rugged libgit2 bindings?


Is there any way to get the same information as the native git command

git branch --merged <sha>

via the Rugged libgit2 bindings for Ruby?


Solution

  • What that git commit is doing is looking at each branch and checking whether the merge-base between the branch and the commit you've given (or HEAD if none) corresponds to the one of the branch.

    If they match, it's merged; if they don't, it's not. You can do this loop in ruby fairly easily

    repo.branches.each(:local) # look only at local branches
    .map { |b|
      tgt = b.resolve.target # look at what the branch is pointing to
      # and check if the target commit is included in the history of HEAD
      merged = repo.merge_base(repo.head.target, tgt) == tgt.oid
      [b.name, merged]
    } # this will give a list with the name and whether the branch is merged
    .keep_if { |name, merged| merged } # keep only the ones which are merged
    .map(&:first) # get the name
    

    You could have an merged_list << b.name if merged in the first block and make it hang off of the each, but I like composing streams of data.

    You can also change whether to use :local, :remote or both for the branches depending on your need. And you can also change repo.head.target to whatever id you want to compare against.