forked from ManageIQ/manageiq
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgit_worktree.rb
349 lines (302 loc) · 9.89 KB
/
git_worktree.rb
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
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
require 'rugged'
require_relative 'git_worktree_exception'
class GitWorktree
attr_accessor :name, :email, :base_name
ENTRY_KEYS = [:path, :dev, :ino, :mode, :gid, :uid, :ctime, :mtime]
DEFAULT_FILE_MODE = 0100644
LOCK_REFERENCE = 'refs/locks'
MASTER_REF = 'refs/heads/master'
def initialize(options = {})
raise ArgumentError, "Must specify path" unless options.key?(:path)
@path = options[:path]
@email = options[:email]
@username = options[:username]
@bare = options[:bare]
@commit_sha = options[:commit_sha]
@password = options[:password]
@fast_forward_merge = options[:ff] || true
@remote_name = 'origin'
@cred = Rugged::Credentials::UserPassword.new(:username => @username,
:password => @password)
@base_name = File.basename(@path)
@certificate_check_cb = options[:certificate_check]
process_repo(options)
end
def delete_repo
return false unless @repo
@repo.close
FileUtils.rm_rf(@path)
true
end
def branches(where = nil)
where.nil? ? @repo.branches.each_name.sort : @repo.branches.each_name(where).sort
end
def branch=(name)
branch = @repo.branches.each.detect { |b| b.name.casecmp(name) == 0 }
raise GitWorktreeException::BranchMissing, name unless branch
@commit_sha = branch.target.oid
end
def branch_info(name)
branch = @repo.branches.each.detect { |b| b.name.casecmp(name) == 0 }
raise GitWorktreeException::BranchMissing, name unless branch
{:time => branch.target.time, :message => branch.target.message, :commit_sha => branch.target.oid}
end
def tags
@repo.tags.each.collect(&:name)
end
def tag=(name)
tag = @repo.tags.each.detect { |t| t.name.casecmp(name) == 0 }
raise GitWorktreeException::TagMissing, name unless tag
@commit_sha = tag.target.oid
end
def tag_info(name)
tag = @repo.tags.each.detect { |t| t.name.casecmp(name) == 0 }
raise GitWorktreeException::TagMissing, name unless tag
{:time => tag.target.time, :message => tag.target.message, :commit_sha => tag.target.oid}
end
def add(path, data, default_entry_keys = {})
entry = {}
entry[:path] = path
ENTRY_KEYS.each { |key| entry[key] = default_entry_keys[key] if default_entry_keys.key?(key) }
entry[:oid] = @repo.write(data, :blob)
entry[:mode] ||= DEFAULT_FILE_MODE
entry[:mtime] ||= Time.now
current_index.add(entry)
end
def remove(path )
current_index.remove(path)
end
def remove_dir(path)
current_index.remove_dir(path)
end
def file_exists?(path)
!!find_entry(path)
end
def directory_exists?(path)
entry = find_entry(path)
entry && entry[:type] == :tree
end
def read_file(path)
read_entry(fetch_entry(path))
end
def read_entry(entry)
@repo.lookup(entry[:oid]).content
end
def entries(path)
tree = get_tree(path)
tree.find_all.collect { |e| e[:name] }
end
def nodes(path)
tree = path.empty? ? lookup_commit_tree : get_tree(path)
entries = tree.find_all
entries.each do |entry|
entry[:full_name] = File.join(@base_name, path, entry[:name])
entry[:rel_path] = File.join(path, entry[:name])
end
end
def save_changes(message, owner = :local)
cid = commit(message)
if owner == :local
lock { merge(cid) }
else
merge_and_push(cid)
end
true
end
def file_attributes(fname)
walker = Rugged::Walker.new(@repo)
walker.sorting(Rugged::SORT_DATE)
walker.push(@repo.ref(MASTER_REF).target)
commit = walker.find { |c| c.diff(:paths => [fname]).size > 0 }
return {} unless commit
{:updated_on => commit.time.gmtime, :updated_by => commit.author[:name]}
end
def file_list
tree = lookup_commit_tree
return [] unless tree
tree.walk(:preorder).collect { |root, entry| "#{root}#{entry[:name]}" }
end
def find_entry(path)
get_tree_entry(path)
end
def mv_file_with_new_contents(old_file, new_path, new_data, default_entry_keys = {})
add(new_path, new_data, default_entry_keys)
remove(old_file)
end
def mv_file(old_file, new_file)
entry = current_index[old_file]
return unless entry
entry[:path] = new_file
current_index.add(entry)
remove(old_file)
end
def mv_dir(old_dir, new_dir)
raise GitWorktreeException::DirectoryAlreadyExists, new_dir if find_entry(new_dir)
old_dir = fix_path_mv(old_dir)
new_dir = fix_path_mv(new_dir)
updates = current_index.entries.select { |entry| entry[:path].start_with?(old_dir) }
updates.each do |entry|
entry[:path] = entry[:path].sub(old_dir, new_dir)
current_index.add(entry)
end
current_index.remove_dir(old_dir)
end
private
def fetch_and_merge
fetch
commit = @repo.ref("refs/remotes/#{@remote_name}/master").target
merge(commit)
end
def fetch
options = {:credentials => @cred, :certificate_check => @certificate_check_cb}
@repo.fetch(@remote_name, options)
end
def pull
lock { fetch_and_merge }
end
def merge_and_push(commit)
rebase = false
push_lock do
@saved_cid = @repo.ref(MASTER_REF).target.oid
merge(commit, rebase)
rebase = true
@repo.push(@remote_name, [MASTER_REF], :credentials => @cred)
end
end
def merge(commit, rebase = false)
master_branch = @repo.ref(MASTER_REF)
merge_index = master_branch ? @repo.merge_commits(master_branch.target, commit) : nil
if merge_index && merge_index.conflicts?
result = differences_with_master(commit)
raise GitWorktreeException::GitConflicts, result
end
commit = rebase(commit, merge_index, master_branch.try(:target)) if rebase
@repo.reset(commit, :soft)
end
def rebase(commit, merge_index, parent)
commit_obj = commit if commit.class == Rugged::Commit
commit_obj ||= @repo.lookup(commit)
Rugged::Commit.create(@repo, :author => commit_obj.author,
:committer => commit_obj.author,
:message => commit_obj.message,
:parents => parent ? [parent] : [],
:tree => merge_index.write_tree(@repo))
end
def commit(message)
tree = @current_index.write_tree(@repo)
parents = @repo.empty? ? [] : [@repo.ref(MASTER_REF).target].compact
create_commit(message, tree, parents)
end
def process_repo(options)
if options[:url]
clone(options[:url])
elsif options[:new]
create_repo
else
open_repo
end
end
def create_repo
@repo = @bare ? Rugged::Repository.init_at(@path, :bare) : Rugged::Repository.init_at(@path)
@repo.config['user.name'] = @username if @username
@repo.config['user.email'] = @email if @email
@repo.config['merge.ff'] = 'only' if @fast_forward_merge
end
def open_repo
@repo = Rugged::Repository.new(@path)
end
def clone(url)
options = {:credentials => @cred, :bare => true, :remote => @remote_name, :certificate_check => @certificate_check_cb}
@repo = Rugged::Repository.clone_at(url, @path, options)
end
def fetch_entry(path)
find_entry(path).tap do |entry|
raise GitWorktreeException::GitEntryMissing, path unless entry
end
end
def fix_path_mv(dir_name)
dir_name = dir_name[1..-1] if dir_name[0] == '/'
dir_name += '/' if dir_name[-1] != '/'
dir_name
end
def get_tree(path)
return lookup_commit_tree if path.empty?
entry = get_tree_entry(path)
raise GitWorktreeException::GitEntryMissing, path unless entry
raise GitWorktreeException::GitEntryNotADirectory, path unless entry[:type] == :tree
@repo.lookup(entry[:oid])
end
def lookup_commit_tree
return nil unless @repo.branches['master']
ct = @commit_sha ? @repo.lookup(@commit_sha) : @repo.branches['master'].target
ct.tree if ct
end
def get_tree_entry(path)
path = path[1..-1] if path[0] == '/'
tree = lookup_commit_tree
begin
entry = tree.path(path)
entry[:full_name] = File.join(@base_name, path)
entry[:rel_path] = path
rescue
return nil
end
entry
end
def current_index
@current_index ||= Rugged::Index.new.tap do |index|
unless @repo.empty?
tree = lookup_commit_tree
raise ArgumentError, "Cannot locate commit tree" unless tree
@current_tree_oid = tree.oid
index.read_tree(tree)
end
end
end
def create_commit(message, tree, parents)
author = {:email => @email, :name => @username, :time => Time.now}
# Create the actual commit but dont update the reference
Rugged::Commit.create(@repo, :author => author, :committer => author,
:message => message, :parents => parents,
:tree => tree)
end
def lock
@repo.references.create(LOCK_REFERENCE, MASTER_REF)
yield
rescue Rugged::ReferenceError
sleep 0.1
retry
ensure
@repo.references.delete(LOCK_REFERENCE)
end
def push_lock
@repo.references.create(LOCK_REFERENCE, MASTER_REF)
begin
yield
rescue Rugged::ReferenceError => err
sleep 0.1
@repo.reset(@saved_cid, :soft)
fetch_and_merge
retry
rescue GitWorktreeException::GitConflicts => err
@repo.reset(@saved_cid, :soft)
raise GitWorktreeException::GitConflicts, err.conflicts
ensure
@repo.references.delete(LOCK_REFERENCE)
end
end
def differences_with_master(commit)
differences = {}
diffs = @repo.diff(commit, @repo.ref(MASTER_REF).target)
diffs.deltas.each do |delta|
result = []
delta.diff.each_line do |line|
next unless line.addition? || line.deletion?
result << "+ #{line.content.to_str}" if line.addition?
result << "- #{line.content.to_str}" if line.deletion?
end
differences[delta.old_file[:path]] = {:status => delta.status, :diffs => result}
end
differences
end
end