File: branches.rb

package info (click to toggle)
ruby-git 1.13.1-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 4,124 kB
  • sloc: ruby: 5,385; sh: 507; perl: 64; makefile: 6
file content (71 lines) | stat: -rw-r--r-- 1,657 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
module Git
  
  # object that holds all the available branches
  class Branches

    include Enumerable
    
    def initialize(base)
      @branches = {}
      
      @base = base
            
      @base.lib.branches_all.each do |b|
        @branches[b[0]] = Git::Branch.new(@base, b[0])
      end
    end

    def local
      self.select { |b| !b.remote }
    end
    
    def remote
      self.select { |b| b.remote }
    end
    
    # array like methods

    def size
      @branches.size
    end    
    
    def each(&block)
      @branches.values.each(&block)
    end
    
    # Returns the target branch
    #
    # Example:
    #   Given (git branch -a):
    #    master
    #    remotes/working/master
    #
    #   g.branches['master'].full #=> 'master'
    #   g.branches['working/master'].full => 'remotes/working/master'
    #   g.branches['remotes/working/master'].full => 'remotes/working/master'
    #
    # @param [#to_s] branch_name the target branch name.
    # @return [Git::Branch] the target branch.
    def [](branch_name)
      @branches.values.inject(@branches) do |branches, branch|
        branches[branch.full] ||= branch

        # This is how Git (version 1.7.9.5) works. 
        # Lets you ignore the 'remotes' if its at the beginning of the branch full name (even if is not a real remote branch). 
        branches[branch.full.sub('remotes/', '')] ||= branch if branch.full =~ /^remotes\/.+/
        
        branches
      end[branch_name.to_s]
    end
    
    def to_s
      out = ''
      @branches.each do |k, b|
        out << (b.current ? '* ' : '  ') << b.to_s << "\n"
      end
      out
    end
    
  end

end