Class: Git::Git

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

Constant Summary collapse

GIT_PATH =
'/usr/bin/git'.freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(repository_name, git_cache_path: '/tmp/git') ⇒ Git

Returns a new instance of Git.



18
19
20
21
22
# File 'lib/git/git.rb', line 18

def initialize(repository_name, git_cache_path: '/tmp/git')
  @repository_name = repository_name
  @repository_url = "[email protected]:#{repository_name}.git"
  @repository_path = File.join(git_cache_path, repository_name).to_s
end

Instance Attribute Details

#repository_nameObject (readonly)

Returns the value of attribute repository_name.



16
17
18
# File 'lib/git/git.rb', line 16

def repository_name
  @repository_name
end

#repository_pathObject (readonly)

Returns the value of attribute repository_path.



16
17
18
# File 'lib/git/git.rb', line 16

def repository_path
  @repository_path
end

#repository_urlObject (readonly)

Returns the value of attribute repository_url.



16
17
18
# File 'lib/git/git.rb', line 16

def repository_url
  @repository_url
end

Class Method Details

.get_conflict_list_from_failed_merge_output(failed_merged_output) ⇒ Object



179
180
181
182
183
# File 'lib/git/git.rb', line 179

def get_conflict_list_from_failed_merge_output(failed_merged_output)
  failed_merged_output.split("\n").grep(/CONFLICT/).collect! do |conflict|
    conflict.sub(/CONFLICT \(.*\): /, '').sub(/Merge conflict in /, '').sub(/ deleted in .*/, '')
  end
end

.is_git_sha?(str) ⇒ Boolean

rubocop:disable Style/PredicateName

Returns:

  • (Boolean)


175
176
177
# File 'lib/git/git.rb', line 175

def is_git_sha?(str) # rubocop:disable Style/PredicateName
  (str =~ /[0-9a-f]{40}/) == 0
end

Instance Method Details

#branch_listObject



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/git/git.rb', line 38

def branch_list
  raw_output = execute(
    'for-each-ref refs/remotes/ --format=\'%(refname:short)~%(authordate:iso8601)~%(authorname)~%(authoremail)\''
  )

  raw_output.split("\n").collect! do |raw_branch_data|
    branch_data = raw_branch_data.split('~')
    GitBranch.new(
      @repository_name,
      branch_data[0].sub!('origin/', ''),
      DateTime.parse(branch_data[1]),
      branch_data[2],
      branch_data[3].gsub!(/[<>]/, '')
    )
  end
end

#checkout_branch(branch_name) ⇒ Object



126
127
128
129
130
# File 'lib/git/git.rb', line 126

def checkout_branch(branch_name)
  reset
  execute("checkout #{Shellwords.escape(branch_name)}")
  reset
end

#clone_repository(default_branch_name) ⇒ Object



98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/git/git.rb', line 98

def clone_repository(default_branch_name)
  if Dir.exist?(@repository_path)
    # cleanup any changes that might have been left over if we crashed while running
    reset
    execute('clean -f -d')

    # move to the master branch
    checkout_branch(default_branch_name)

    # remove branches that no longer exist on origin and update all branches that do
    execute('fetch --prune --all')

    # pull all of the branches
    execute('pull --all')
  else
    execute("clone #{@repository_url} #{@repository_path}", false)
  end
end

#commit_diff_refs(ref, ancestor_ref, fetch: false) ⇒ Object



153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
# File 'lib/git/git.rb', line 153

def commit_diff_refs(ref, ancestor_ref, fetch: false)
  if fetch
    fetch_all
  end
  ref_prefix = 'origin/' unless self.class.is_git_sha?(ref)
  ancestor_ref_prefix = 'origin/' unless self.class.is_git_sha?(ancestor_ref)

  raw_output = execute(
    "log --format=%H\t%an\t%ae\t%aI\t%s " \
    "--no-color #{ancestor_ref_prefix}#{Shellwords.escape(ancestor_ref)}..#{ref_prefix}#{Shellwords.escape(ref)}"
  )
  raw_output.split("\n").map do |row|
    commit_data = row.split("\t")
    GitCommit.new(commit_data[0], commit_data[4], DateTime.iso8601(commit_data[3]), commit_data[1], commit_data[2], repository_name: @repository_name)
  end
end

#current_branch_nameObject



170
171
172
# File 'lib/git/git.rb', line 170

def current_branch_name
  execute('rev-parse --abbrev-ref HEAD').strip
end

#execute(command, run_in_repository_path = true) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/git/git.rb', line 24

def execute(command, run_in_repository_path = true)
  options = if run_in_repository_path
              { chdir: @repository_path }
            else
              {}
            end
  stdout_andstderr_str, status = Open3.capture2e(GIT_PATH, *command.split(/ /), options)
  unless status.success?
    raise GitError.new("#{GIT_PATH} #{command}", status, stdout_andstderr_str)
  end

  stdout_andstderr_str
end

#fetch_allObject



140
141
142
# File 'lib/git/git.rb', line 140

def fetch_all
  execute('fetch --all')
end

#file_diff_branch_with_ancestor(branch_name, ancestor_branch_name) ⇒ Object



144
145
146
147
148
149
150
151
# File 'lib/git/git.rb', line 144

def file_diff_branch_with_ancestor(branch_name, ancestor_branch_name)
  # gets the merge base of the branch and its ancestor, then gets a list of files changed since the merge base
  raw_output = execute(
    "diff --name-only $(git merge-base origin/#{Shellwords.escape(ancestor_branch_name)} " \
    "origin/#{Shellwords.escape(branch_name)})..origin/#{Shellwords.escape(branch_name)}"
  )
  raw_output.split("\n")
end

#lookup_tag(tag) ⇒ Object



136
137
138
# File 'lib/git/git.rb', line 136

def lookup_tag(tag)
  execute("describe --abbrev=0 --match #{tag}").strip
end

#merge_branches(target_branch_name, source_branch_name, source_tag_name: nil, keep_changes: true, commit_message: nil) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/git/git.rb', line 55

def merge_branches(target_branch_name,
                   source_branch_name,
                   source_tag_name: nil,
                   keep_changes: true,
                   commit_message: nil)
  if current_branch_name != target_branch_name
    checkout_branch(target_branch_name)
  end

  commit_message_argument = "-m \"#{commit_message.gsub('"', '\\"')}\"" if commit_message
  source = if source_tag_name.present?
             Shellwords.escape(source_tag_name)
           else
             "origin/#{Shellwords.escape(source_branch_name)}"
           end

  raw_output = execute("merge --no-edit #{commit_message_argument} #{source}")

  if raw_output =~ /.*Already up-to-date.\n/
    [false, nil]
  else
    [true, nil]
  end
rescue GitError => ex
  conflicting_files = Git.get_conflict_list_from_failed_merge_output(ex.error_message)
  if conflicting_files.empty?
    raise
  else
    [
      false,
      GitConflict.new(
        @repository_name,
        target_branch_name,
        source_branch_name,
        conflicting_files
      )
    ]
  end
ensure
  # cleanup our "mess"
  keep_changes || reset
end

#push(dry_run: false) ⇒ Object



117
118
119
120
121
122
123
124
# File 'lib/git/git.rb', line 117

def push(dry_run: false)
  dry_run_argument = ''
  if dry_run
    dry_run_argument = '--dry-run'
  end
  raw_output = execute("push #{dry_run_argument} origin")
  raw_output != "Everything up-to-date\n"
end

#resetObject



132
133
134
# File 'lib/git/git.rb', line 132

def reset
  execute("reset --hard origin/#{Shellwords.escape(current_branch_name)}")
end