Class: Black::Git::Repository

Inherits:
Object
  • Object
show all
Defined in:
lib/black/git.rb

Instance Method Summary collapse

Constructor Details

#initialize(path) ⇒ Repository

Returns a new instance of Repository.



14
15
16
17
18
19
20
# File 'lib/black/git.rb', line 14

def initialize(path)
  unless File.directory?(path)
    raise "#{ path } is not a valid directory"
  end

  @path = path
end

Instance Method Details

#commit_at(index_or_sha) ⇒ Object

Return a diff object for each file in the given commit



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
# File 'lib/black/git.rb', line 31

def commit_at(index_or_sha)
  if index_or_sha.is_a?(Integer)
    index = index_or_sha
    sha = commits_dict[index_or_sha]
  else
    index = commits_dict.key(index_or_sha)
    sha = index_or_sha
  end
  sha_prev = commits_dict[index-1]
  output = diff_output(sha)

  commands = %w(diff-tree --no-commit-id --name-status -r)
  commands.push('--root') if index.zero?
  commands.push(sha)

  Black::Git
    .execute(@path, commands)
    .lines
    .map
    .with_index do |line, i|
      status, filename = line.split(/\s+/)
      status = status.chomp
      filename = filename.chomp

      Black::Git::Diff.new(@path, sha, sha_prev, output[i], filename, status)
    end
end

#commitsObject



22
23
24
25
26
27
28
# File 'lib/black/git.rb', line 22

def commits
  Enumerator.new do |y|
    commits_dict.each_key do |index|
      y.yield commit_at(index)
    end
  end
end

#commits_dictObject

Store a lookup dictionary for all commits



60
61
62
63
64
65
66
67
68
69
70
# File 'lib/black/git.rb', line 60

def commits_dict
  return @commits_dict if @commits_dict

  @commits_dict = {}
  Black::Git
    .execute(@path, %w(rev-list HEAD --reverse))
    .each_line
    .with_index{ |a, i| @commits_dict[i] = a.chomp }

  @commits_dict
end

#diff_output(sha) ⇒ Object

Get diff output on all files in each commit rather than one file at a time.



73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/black/git.rb', line 73

def diff_output(sha)
  output = []
  marker = 0

  Black::Git
    .execute(@path, %w(show --format='%b' --no-prefix -U1000).push(sha))
    .each_line do |line|
      if line.start_with?('diff --git')
        marker += 1
      else
        if output[marker]
          output[marker] += line
        else
          output[marker] = line
        end
      end
    end

  # there are two empty lines at the top of the git show output
  output.shift
  output
end