pjhyett-grit 0.9.11

Sign up to get free protection for your applications and to get access to all the features.
Files changed (47) hide show
  1. data/History.txt +13 -0
  2. data/Manifest.txt +71 -0
  3. data/README.txt +213 -0
  4. data/Rakefile +29 -0
  5. data/grit.gemspec +62 -0
  6. data/lib/grit.rb +54 -0
  7. data/lib/grit/actor.rb +36 -0
  8. data/lib/grit/blob.rb +117 -0
  9. data/lib/grit/commit.rb +229 -0
  10. data/lib/grit/commit_stats.rb +104 -0
  11. data/lib/grit/config.rb +44 -0
  12. data/lib/grit/diff.rb +70 -0
  13. data/lib/grit/errors.rb +7 -0
  14. data/lib/grit/git-ruby.rb +184 -0
  15. data/lib/grit/git-ruby/commit_db.rb +52 -0
  16. data/lib/grit/git-ruby/file_index.rb +186 -0
  17. data/lib/grit/git-ruby/git_object.rb +344 -0
  18. data/lib/grit/git-ruby/internal/loose.rb +137 -0
  19. data/lib/grit/git-ruby/internal/mmap.rb +58 -0
  20. data/lib/grit/git-ruby/internal/pack.rb +382 -0
  21. data/lib/grit/git-ruby/internal/raw_object.rb +37 -0
  22. data/lib/grit/git-ruby/object.rb +319 -0
  23. data/lib/grit/git-ruby/repository.rb +731 -0
  24. data/lib/grit/git.rb +122 -0
  25. data/lib/grit/head.rb +83 -0
  26. data/lib/grit/index.rb +121 -0
  27. data/lib/grit/lazy.rb +33 -0
  28. data/lib/grit/ref.rb +95 -0
  29. data/lib/grit/repo.rb +387 -0
  30. data/lib/grit/status.rb +151 -0
  31. data/lib/grit/tag.rb +71 -0
  32. data/lib/grit/tree.rb +104 -0
  33. data/test/test_actor.rb +35 -0
  34. data/test/test_blob.rb +79 -0
  35. data/test/test_commit.rb +184 -0
  36. data/test/test_config.rb +58 -0
  37. data/test/test_diff.rb +18 -0
  38. data/test/test_git.rb +70 -0
  39. data/test/test_grit.rb +32 -0
  40. data/test/test_head.rb +47 -0
  41. data/test/test_real.rb +19 -0
  42. data/test/test_reality.rb +17 -0
  43. data/test/test_remote.rb +14 -0
  44. data/test/test_repo.rb +277 -0
  45. data/test/test_tag.rb +25 -0
  46. data/test/test_tree.rb +96 -0
  47. metadata +128 -0
@@ -0,0 +1,319 @@
1
+ #
2
+ # converted from the gitrb project
3
+ #
4
+ # authors:
5
+ # Matthias Lederhofer <matled@gmx.net>
6
+ # Simon 'corecode' Schubert <corecode@fs.ei.tum.de>
7
+ # Scott Chacon <schacon@gmail.com>
8
+ #
9
+ # provides native ruby access to git objects and pack files
10
+ #
11
+
12
+ # These classes translate the raw binary data kept in the sha encoded files
13
+ # into parsed data that can then be used in another fashion
14
+ require 'stringio'
15
+
16
+ module Grit
17
+ module GitRuby
18
+
19
+ # class for author/committer/tagger lines
20
+ class UserInfo
21
+ attr_accessor :name, :email, :date, :offset
22
+
23
+ def initialize(str)
24
+ m = /^(.*?) <(.*)> (\d+) ([+-])0*(\d+?)$/.match(str)
25
+ if !m
26
+ raise RuntimeError, "invalid header '%s' in commit" % str
27
+ end
28
+ @name = m[1]
29
+ @email = m[2]
30
+ @date = Time.at(Integer(m[3]))
31
+ @offset = (m[4] == "-" ? -1 : 1)*Integer(m[5])
32
+ end
33
+
34
+ def to_s
35
+ "%s <%s> %s %+05d" % [@name, @email, @date.to_i, @offset]
36
+ end
37
+ end
38
+
39
+ # base class for all git objects (blob, tree, commit, tag)
40
+ class Object
41
+ attr_accessor :repository
42
+
43
+ def Object.from_raw(rawobject, repository = nil)
44
+ case rawobject.type
45
+ when :blob
46
+ return Blob.from_raw(rawobject, repository)
47
+ when :tree
48
+ return Tree.from_raw(rawobject, repository)
49
+ when :commit
50
+ return Commit.from_raw(rawobject, repository)
51
+ when :tag
52
+ return Tag.from_raw(rawobject, repository)
53
+ else
54
+ raise RuntimeError, "got invalid object-type"
55
+ end
56
+ end
57
+
58
+ def initialize
59
+ raise NotImplemented, "abstract class"
60
+ end
61
+
62
+ def type
63
+ raise NotImplemented, "abstract class"
64
+ end
65
+
66
+ def raw_content
67
+ raise NotImplemented, "abstract class"
68
+ end
69
+
70
+ def sha1
71
+ Digest::SHA1.hexdigest("%s %d\0" % \
72
+ [self.type, self.raw_content.length] + \
73
+ self.raw_content)
74
+ end
75
+ end
76
+
77
+ class Blob < Object
78
+ attr_accessor :content
79
+
80
+ def self.from_raw(rawobject, repository)
81
+ new(rawobject.content)
82
+ end
83
+
84
+ def initialize(content, repository=nil)
85
+ @content = content
86
+ @repository = repository
87
+ end
88
+
89
+ def type
90
+ :blob
91
+ end
92
+
93
+ def raw_content
94
+ @content
95
+ end
96
+ end
97
+
98
+ class DirectoryEntry
99
+ S_IFMT = 00170000
100
+ S_IFLNK = 0120000
101
+ S_IFREG = 0100000
102
+ S_IFDIR = 0040000
103
+
104
+ attr_accessor :mode, :name, :sha1
105
+ def initialize(mode, filename, sha1o)
106
+ @mode = 0
107
+ mode.each_byte do |i|
108
+ @mode = (@mode << 3) | (i-'0'[0])
109
+ end
110
+ @name = filename
111
+ @sha1 = sha1o
112
+ if ![S_IFLNK, S_IFDIR, S_IFREG].include?(@mode & S_IFMT)
113
+ raise RuntimeError, "unknown type for directory entry"
114
+ end
115
+ end
116
+
117
+ def type
118
+ case @mode & S_IFMT
119
+ when S_IFLNK
120
+ @type = :link
121
+ when S_IFDIR
122
+ @type = :directory
123
+ when S_IFREG
124
+ @type = :file
125
+ else
126
+ raise RuntimeError, "unknown type for directory entry"
127
+ end
128
+ end
129
+
130
+ def type=(type)
131
+ case @type
132
+ when :link
133
+ @mode = (@mode & ~S_IFMT) | S_IFLNK
134
+ when :directory
135
+ @mode = (@mode & ~S_IFMT) | S_IFDIR
136
+ when :file
137
+ @mode = (@mode & ~S_IFMT) | S_IFREG
138
+ else
139
+ raise RuntimeError, "invalid type"
140
+ end
141
+ end
142
+
143
+ def format_type
144
+ case type
145
+ when :link
146
+ 'link'
147
+ when :directory
148
+ 'tree'
149
+ when :file
150
+ 'blob'
151
+ end
152
+ end
153
+
154
+ def format_mode
155
+ "%06o" % @mode
156
+ end
157
+
158
+ def raw
159
+ "%o %s\0%s" % [@mode, @name, [@sha1].pack("H*")]
160
+ end
161
+ end
162
+
163
+
164
+ def self.read_bytes_until(io, char)
165
+ string = ''
166
+ while ((next_char = io.getc.chr) != char) && !io.eof
167
+ string += next_char
168
+ end
169
+ string
170
+ end
171
+
172
+
173
+ class Tree < Object
174
+ attr_accessor :entry
175
+
176
+ def self.from_raw(rawobject, repository=nil)
177
+ raw = StringIO.new(rawobject.content)
178
+
179
+ entries = []
180
+ while !raw.eof?
181
+ mode = Grit::GitRuby.read_bytes_until(raw, ' ')
182
+ file_name = Grit::GitRuby.read_bytes_until(raw, "\0")
183
+ raw_sha = raw.read(20)
184
+ sha = raw_sha.unpack("H*").first
185
+
186
+ entries << DirectoryEntry.new(mode, file_name, sha)
187
+ end
188
+ new(entries, repository)
189
+ end
190
+
191
+ def initialize(entries=[], repository = nil)
192
+ @entry = entries
193
+ @repository = repository
194
+ end
195
+
196
+ def type
197
+ :tree
198
+ end
199
+
200
+ def raw_content
201
+ # TODO: sort correctly
202
+ #@entry.sort { |a,b| a.name <=> b.name }.
203
+ @entry.collect { |e| [[e.format_mode, e.format_type, e.sha1].join(' '), e.name].join("\t") }.join("\n")
204
+ end
205
+
206
+ def actual_raw
207
+ #@entry.collect { |e| e.raw.join(' '), e.name].join("\t") }.join("\n")
208
+ end
209
+ end
210
+
211
+ class Commit < Object
212
+ attr_accessor :author, :committer, :tree, :parent, :message, :headers
213
+
214
+ def self.from_raw(rawobject, repository=nil)
215
+ parent = []
216
+ tree = author = committer = nil
217
+
218
+ headers, message = rawobject.content.split(/\n\n/, 2)
219
+ all_headers = headers.split(/\n/).map { |header| header.split(/ /, 2) }
220
+ all_headers.each do |key, value|
221
+ case key
222
+ when "tree"
223
+ tree = value
224
+ when "parent"
225
+ parent.push(value)
226
+ when "author"
227
+ author = UserInfo.new(value)
228
+ when "committer"
229
+ committer = UserInfo.new(value)
230
+ else
231
+ warn "unknown header '%s' in commit %s" % \
232
+ [key, rawobject.sha1.unpack("H*")[0]]
233
+ end
234
+ end
235
+ if not tree && author && committer
236
+ raise RuntimeError, "incomplete raw commit object"
237
+ end
238
+ new(tree, parent, author, committer, message, headers, repository)
239
+ end
240
+
241
+ def initialize(tree, parent, author, committer, message, headers, repository=nil)
242
+ @tree = tree
243
+ @author = author
244
+ @parent = parent
245
+ @committer = committer
246
+ @message = message
247
+ @headers = headers
248
+ @repository = repository
249
+ end
250
+
251
+ def type
252
+ :commit
253
+ end
254
+
255
+ def raw_content
256
+ "tree %s\n%sauthor %s\ncommitter %s\n\n" % [
257
+ @tree,
258
+ @parent.collect { |i| "parent %s\n" % i }.join,
259
+ @author, @committer] + @message
260
+ end
261
+
262
+ def raw_log(sha)
263
+ output = "commit #{sha}\n"
264
+ output += @headers + "\n\n"
265
+ output += @message.split("\n").map { |l| ' ' + l }.join("\n") + "\n\n"
266
+ end
267
+
268
+ end
269
+
270
+ class Tag < Object
271
+ attr_accessor :object, :type, :tag, :tagger, :message
272
+
273
+ def self.from_raw(rawobject, repository=nil)
274
+ headers, message = rawobject.content.split(/\n\n/, 2)
275
+ headers = headers.split(/\n/).map { |header| header.split(/ /, 2) }
276
+ headers.each do |key, value|
277
+ case key
278
+ when "object"
279
+ object = value
280
+ when "type"
281
+ if !["blob", "tree", "commit", "tag"].include?(value)
282
+ raise RuntimeError, "invalid type in tag"
283
+ end
284
+ type = value.to_sym
285
+ when "tag"
286
+ tag = value
287
+ when "tagger"
288
+ tagger = UserInfo.new(value)
289
+ else
290
+ warn "unknown header '%s' in tag" % \
291
+ [key, rawobject.sha1.unpack("H*")[0]]
292
+ end
293
+ if not object && type && tag && tagger
294
+ raise RuntimeError, "incomplete raw tag object"
295
+ end
296
+ end
297
+ new(object, type, tag, tagger, repository)
298
+ end
299
+
300
+ def initialize(object, type, tag, tagger, repository=nil)
301
+ @object = object
302
+ @type = type
303
+ @tag = tag
304
+ @tagger = tagger
305
+ @repository = repository
306
+ end
307
+
308
+ def raw_content
309
+ "object %s\ntype %s\ntag %s\ntagger %s\n\n" % \
310
+ [@object, @type, @tag, @tagger] + @message
311
+ end
312
+
313
+ def type
314
+ :tag
315
+ end
316
+ end
317
+
318
+ end
319
+ end
@@ -0,0 +1,731 @@
1
+ #
2
+ # converted from the gitrb project
3
+ #
4
+ # authors:
5
+ # Matthias Lederhofer <matled@gmx.net>
6
+ # Simon 'corecode' Schubert <corecode@fs.ei.tum.de>
7
+ # Scott Chacon <schacon@gmail.com>
8
+ #
9
+ # provides native ruby access to git objects and pack files
10
+ #
11
+ require 'grit/git-ruby/internal/raw_object'
12
+ require 'grit/git-ruby/internal/pack'
13
+ require 'grit/git-ruby/internal/loose'
14
+ require 'grit/git-ruby/git_object'
15
+
16
+ require 'rubygems'
17
+ require 'diff/lcs'
18
+ require 'diff/lcs/hunk'
19
+
20
+ # have to do this so it doesn't interfere with Grit::Diff
21
+ module Difference
22
+ include Diff
23
+ end
24
+
25
+ module Grit
26
+ module GitRuby
27
+ class Repository
28
+
29
+ class NoSuchShaFound < StandardError
30
+ end
31
+
32
+ class NoSuchPath < StandardError
33
+ end
34
+
35
+ attr_accessor :git_dir, :options
36
+
37
+ def initialize(git_dir, options = {})
38
+ @git_dir = git_dir
39
+ @options = options
40
+ @packs = []
41
+ end
42
+
43
+ # returns the loose objects object lazily
44
+ def loose
45
+ @loose ||= initloose
46
+ end
47
+
48
+ # returns the array of pack list objects
49
+ def packs
50
+ @packs ||= initpacks
51
+ end
52
+
53
+
54
+ # prints out the type, shas and content of all of the pack files
55
+ def show
56
+ packs.each do |p|
57
+ puts p.name
58
+ puts
59
+ p.each_sha1 do |s|
60
+ puts "**#{p[s].type}**"
61
+ if p[s].type.to_s == 'commit'
62
+ puts s.unpack('H*')
63
+ puts p[s].content
64
+ end
65
+ end
66
+ puts
67
+ end
68
+ end
69
+
70
+
71
+ # returns a raw object given a SHA1
72
+ def get_raw_object_by_sha1(sha1o)
73
+ raise NoSuchShaFound if sha1o.nil? || sha1o.empty? || !sha1o.is_a?(String)
74
+
75
+ sha1 = [sha1o.chomp].pack("H*")
76
+ # try packs
77
+ packs.each do |pack|
78
+ o = pack[sha1]
79
+ return pack[sha1] if o
80
+ end
81
+
82
+ # try loose storage
83
+ loose.each do |lsobj|
84
+ o = lsobj[sha1]
85
+ return o if o
86
+ end
87
+
88
+ # try packs again, maybe the object got packed in the meantime
89
+ initpacks
90
+ packs.each do |pack|
91
+ o = pack[sha1]
92
+ return o if o
93
+ end
94
+
95
+ # puts "*#{sha1o}*"
96
+ raise NoSuchShaFound
97
+ end
98
+
99
+ def cached(key, object, do_cache = true)
100
+ object
101
+ end
102
+
103
+ # returns GitRuby object of any type given a SHA1
104
+ def get_object_by_sha1(sha1)
105
+ r = get_raw_object_by_sha1(sha1)
106
+ return nil if !r
107
+ GitObject.from_raw(r)
108
+ end
109
+
110
+ # writes a raw object into the git repo
111
+ def put_raw_object(content, type)
112
+ loose.first.put_raw_object(content, type)
113
+ end
114
+
115
+ # returns true or false if that sha exists in the db
116
+ def object_exists?(sha1)
117
+ sha_hex = [sha1].pack("H*")
118
+ return true if in_packs?(sha_hex)
119
+ return true if in_loose?(sha_hex)
120
+ initpacks
121
+ return true if in_packs?(sha_hex) #maybe the object got packed in the meantime
122
+ false
123
+ end
124
+
125
+ # returns true if the hex-packed sha is in the packfiles
126
+ def in_packs?(sha_hex)
127
+ # try packs
128
+ packs.each do |pack|
129
+ return true if pack[sha_hex]
130
+ end
131
+ false
132
+ end
133
+
134
+ # returns true if the hex-packed sha is in the loose objects
135
+ def in_loose?(sha_hex)
136
+ loose.each do |lsobj|
137
+ return true if lsobj[sha_hex]
138
+ end
139
+ false
140
+ end
141
+
142
+
143
+ # returns the file type (as a symbol) of this sha
144
+ def cat_file_type(sha)
145
+ get_raw_object_by_sha1(sha).type
146
+ end
147
+
148
+ # returns the file size (as an int) of this sha
149
+ def cat_file_size(sha)
150
+ get_raw_object_by_sha1(sha).content.size
151
+ end
152
+
153
+ # returns the raw file contents of this sha
154
+ def cat_file(sha)
155
+ get_object_by_sha1(sha).raw_content
156
+ end
157
+
158
+ # returns a 2-d hash of the tree
159
+ # ['blob']['FILENAME'] = {:mode => '100644', :sha => SHA}
160
+ # ['tree']['DIRNAME'] = {:mode => '040000', :sha => SHA}
161
+ def list_tree(sha)
162
+ data = {'blob' => {}, 'tree' => {}, 'link' => {}, 'commit' => {}}
163
+ get_object_by_sha1(sha).entry.each do |e|
164
+ data[e.format_type][e.name] = {:mode => e.format_mode, :sha => e.sha1}
165
+ end
166
+ data
167
+ end
168
+
169
+ # returns the raw (cat-file) output for a tree
170
+ # if given a commit sha, it will print the tree of that commit
171
+ # if given a path limiter array, it will limit the output to those
172
+ def ls_tree(sha, paths = [])
173
+ if paths.size > 0
174
+ # pathing
175
+ part = []
176
+ paths.each do |path|
177
+ part += ls_tree_path(sha, path)
178
+ end
179
+ return part.join("\n")
180
+ else
181
+ get_raw_tree(sha)
182
+ end
183
+ end
184
+
185
+ def get_raw_tree(sha)
186
+ o = get_raw_object_by_sha1(sha)
187
+ if o.type == :commit
188
+ tree = cat_file(get_object_by_sha1(sha).tree)
189
+ elsif o.type == :tag
190
+ commit_sha = get_object_by_sha1(sha).object
191
+ tree = cat_file(get_object_by_sha1(commit_sha).tree)
192
+ else
193
+ tree = cat_file(sha)
194
+ end
195
+ return tree
196
+ end
197
+
198
+ # return array of tree entries
199
+ ## TODO : refactor this to remove the fugly
200
+ def ls_tree_path(sha, path, append = nil)
201
+ tree = get_raw_tree(sha)
202
+ if path =~ /\//
203
+ paths = path.split('/')
204
+ last = path[path.size - 1, 1]
205
+ if (last == '/') && (paths.size == 1)
206
+ append = append ? File.join(append, paths.first) : paths.first
207
+ dir_name = tree.split("\n").select { |p| p.split("\t")[1] == paths.first }.first
208
+ raise NoSuchPath if !dir_name
209
+ next_sha = dir_name.split(' ')[2]
210
+ tree = get_raw_tree(next_sha)
211
+ tree = tree.split("\n")
212
+ if append
213
+ mod_tree = []
214
+ tree.each do |ent|
215
+ (info, fpath) = ent.split("\t")
216
+ mod_tree << [info, File.join(append, fpath)].join("\t")
217
+ end
218
+ mod_tree
219
+ else
220
+ tree
221
+ end
222
+ else
223
+ next_path = paths.shift
224
+ dir_name = tree.split("\n").select { |p| p.split("\t")[1] == next_path }.first
225
+ raise NoSuchPath if !dir_name
226
+ next_sha = dir_name.split(' ')[2]
227
+ next_path = append ? File.join(append, next_path) : next_path
228
+ if (last == '/')
229
+ ls_tree_path(next_sha, paths.join("/") + '/', next_path)
230
+ else
231
+ ls_tree_path(next_sha, paths.join("/"), next_path)
232
+ end
233
+ end
234
+ else
235
+ tree = tree.split("\n")
236
+ tree = tree.select { |p| p.split("\t")[1] == path }
237
+ if append
238
+ mod_tree = []
239
+ tree.each do |ent|
240
+ (info, fpath) = ent.split("\t")
241
+ mod_tree << [info, File.join(append, fpath)].join("\t")
242
+ end
243
+ mod_tree
244
+ else
245
+ tree
246
+ end
247
+ end
248
+ end
249
+
250
+ # returns an array of GitRuby Commit objects
251
+ # [ [sha, raw_output], [sha, raw_output], [sha, raw_output] ... ]
252
+ #
253
+ # takes the following options:
254
+ # :since - Time object specifying that you don't want commits BEFORE this
255
+ # :until - Time object specifying that you don't want commit AFTER this
256
+ # :first_parent - tells log to only walk first parent
257
+ # :path_limiter - string or array of strings to limit path
258
+ # :max_count - number to limit the output
259
+ def log(sha, options = {})
260
+ @already_searched = {}
261
+ walk_log(sha, options)
262
+ end
263
+
264
+ def truncate_arr(arr, sha)
265
+ new_arr = []
266
+ arr.each do |a|
267
+ if a[0] == sha
268
+ return new_arr
269
+ end
270
+ new_arr << a
271
+ end
272
+ return new_arr
273
+ end
274
+
275
+ def rev_list(sha, options)
276
+ if sha.is_a? Array
277
+ (end_sha, sha) = sha
278
+ end
279
+
280
+ log = log(sha, options)
281
+ log = log.sort { |a, b| a[2] <=> b[2] }.reverse
282
+
283
+ if end_sha
284
+ log = truncate_arr(log, end_sha)
285
+ end
286
+
287
+ # shorten the list if it's longer than max_count (had to get everything in branches)
288
+ if options[:max_count]
289
+ if (opt_len = options[:max_count].to_i) < log.size
290
+ log = log[0, opt_len]
291
+ end
292
+ end
293
+
294
+ if options[:pretty] == 'raw'
295
+ log.map {|k, v| v }.join('')
296
+ else
297
+ log.map {|k, v| k }.join("\n")
298
+ end
299
+ end
300
+
301
+ # called by log() to recursively walk the tree
302
+ def walk_log(sha, opts, total_size = 0)
303
+ return [] if @already_searched[sha] # to prevent rechecking branches
304
+ @already_searched[sha] = true
305
+
306
+ array = []
307
+ if (sha)
308
+ o = get_raw_object_by_sha1(sha)
309
+ if o.type == :tag
310
+ commit_sha = get_object_by_sha1(sha).object
311
+ c = get_object_by_sha1(commit_sha)
312
+ else
313
+ c = GitObject.from_raw(o)
314
+ end
315
+
316
+ return [] if c.type != :commit
317
+
318
+ add_sha = true
319
+
320
+ if opts[:since] && opts[:since].is_a?(Time) && (opts[:since] > c.committer.date)
321
+ add_sha = false
322
+ end
323
+ if opts[:until] && opts[:until].is_a?(Time) && (opts[:until] < c.committer.date)
324
+ add_sha = false
325
+ end
326
+
327
+ # follow all parents unless '--first-parent' is specified #
328
+ subarray = []
329
+
330
+ if !c.parent.first && opts[:path_limiter] # check for the last commit
331
+ add_sha = false
332
+ end
333
+
334
+ if (!opts[:max_count] || ((array.size + total_size) < opts[:max_count]))
335
+
336
+ if !opts[:path_limiter]
337
+ output = c.raw_log(sha)
338
+ array << [sha, output, c.committer.date]
339
+ end
340
+
341
+ if (opts[:max_count] && (array.size + total_size) >= opts[:max_count])
342
+ return array
343
+ end
344
+
345
+ c.parent.each do |psha|
346
+ if psha && !files_changed?(c.tree, get_object_by_sha1(psha).tree,
347
+ opts[:path_limiter])
348
+ add_sha = false
349
+ end
350
+ subarray += walk_log(psha, opts, (array.size + total_size))
351
+ next if opts[:first_parent]
352
+ end
353
+
354
+ if opts[:path_limiter] && add_sha
355
+ output = c.raw_log(sha)
356
+ array << [sha, output, c.committer.date]
357
+ end
358
+
359
+ if add_sha
360
+ array += subarray
361
+ end
362
+ end
363
+
364
+ end
365
+
366
+ array
367
+ end
368
+
369
+ def diff(commit1, commit2, options = {})
370
+ patch = ''
371
+
372
+ commit_obj1 = get_object_by_sha1(commit1)
373
+ tree1 = commit_obj1.tree
374
+ if commit2
375
+ tree2 = get_object_by_sha1(commit2).tree
376
+ else
377
+ tree2 = get_object_by_sha1(commit_obj1.parent.first).tree
378
+ end
379
+
380
+ qdiff = quick_diff(tree1, tree2)
381
+
382
+ qdiff.sort.each do |diff_arr|
383
+ format, lines, output = :unified, 3, ''
384
+ file_length_difference = 0
385
+
386
+ fileA = (diff_arr[2]) ? cat_file(diff_arr[2]) : ''
387
+ fileB = (diff_arr[3]) ? cat_file(diff_arr[3]) : ''
388
+
389
+ sha1 = (diff_arr[2]) ? diff_arr[2] : '0000000000000000000000000000000000000000'
390
+ sha2 = (diff_arr[3]) ? diff_arr[3] : '0000000000000000000000000000000000000000'
391
+
392
+ data_old = fileA.split(/\n/).map! { |e| e.chomp }
393
+ data_new = fileB.split(/\n/).map! { |e| e.chomp }
394
+
395
+ diffs = Difference::LCS.diff(data_old, data_new)
396
+ next if diffs.empty?
397
+
398
+ header = 'diff --git a/' + diff_arr[0].gsub('./', '') + ' b/' + diff_arr[0].gsub('./', '')
399
+ if options[:full_index]
400
+ header << "\n" + 'index ' + sha1 + '..' + sha2
401
+ header << ' 100644' if diff_arr[3] # hard coding this because i don't think we use it
402
+ else
403
+ header << "\n" + 'index ' + sha1[0,7] + '..' + sha2[0,7]
404
+ header << ' 100644' if diff_arr[3] # hard coding this because i don't think we use it
405
+ end
406
+ header << "\n--- " + 'a/' + diff_arr[0].gsub('./', '')
407
+ header << "\n+++ " + 'b/' + diff_arr[0].gsub('./', '')
408
+ header += "\n"
409
+
410
+ oldhunk = hunk = nil
411
+
412
+ diffs.each do |piece|
413
+ begin
414
+ hunk = Difference::LCS::Hunk.new(data_old, data_new, piece, lines, file_length_difference)
415
+ file_length_difference = hunk.file_length_difference
416
+
417
+ next unless oldhunk
418
+
419
+ if lines > 0 && hunk.overlaps?(oldhunk)
420
+ hunk.unshift(oldhunk)
421
+ else
422
+ output << oldhunk.diff(format)
423
+ end
424
+ ensure
425
+ oldhunk = hunk
426
+ output << "\n"
427
+ end
428
+ end
429
+
430
+ output << oldhunk.diff(format)
431
+ output << "\n"
432
+
433
+ patch << header + output.lstrip
434
+ end
435
+ patch
436
+ rescue
437
+ '' # one of the trees was bad or lcs isn't there - no diff
438
+ end
439
+
440
+ # takes 2 tree shas and recursively walks them to find out what
441
+ # files or directories have been modified in them and returns an
442
+ # array of changes
443
+ # [ [full_path, 'added', tree1_hash, nil],
444
+ # [full_path, 'removed', nil, tree2_hash],
445
+ # [full_path, 'modified', tree1_hash, tree2_hash]
446
+ # ]
447
+ def quick_diff(tree1, tree2, path = '.', recurse = true)
448
+ # handle empty trees
449
+ changed = []
450
+ return changed if tree1 == tree2
451
+
452
+ t1 = list_tree(tree1) if tree1
453
+ t2 = list_tree(tree2) if tree2
454
+
455
+ # finding files that are different
456
+ t1['blob'].each do |file, hsh|
457
+ t2_file = t2['blob'][file] rescue nil
458
+ full = File.join(path, file)
459
+ if !t2_file
460
+ changed << [full, 'added', hsh[:sha], nil] # not in parent
461
+ elsif (hsh[:sha] != t2_file[:sha])
462
+ changed << [full, 'modified', hsh[:sha], t2_file[:sha]] # file changed
463
+ end
464
+ end if t1
465
+ t2['blob'].each do |file, hsh|
466
+ if !t1 || !t1['blob'][file]
467
+ changed << [File.join(path, file), 'removed', nil, hsh[:sha]]
468
+ end
469
+ end if t2
470
+
471
+ t1['tree'].each do |dir, hsh|
472
+ t2_tree = t2['tree'][dir] rescue nil
473
+ full = File.join(path, dir)
474
+ if !t2_tree
475
+ if recurse
476
+ changed += quick_diff(hsh[:sha], nil, full, true)
477
+ else
478
+ changed << [full, 'added', hsh[:sha], nil] # not in parent
479
+ end
480
+ elsif (hsh[:sha] != t2_tree[:sha])
481
+ if recurse
482
+ changed += quick_diff(hsh[:sha], t2_tree[:sha], full, true)
483
+ else
484
+ changed << [full, 'modified', hsh[:sha], t2_tree[:sha]] # file changed
485
+ end
486
+ end
487
+ end if t1
488
+ t2['tree'].each do |dir, hsh|
489
+ t1_tree = t1['tree'][dir] rescue nil
490
+ full = File.join(path, dir)
491
+ if !t1_tree
492
+ if recurse
493
+ changed += quick_diff(nil, hsh[:sha], full, true)
494
+ else
495
+ changed << [full, 'removed', nil, hsh[:sha]]
496
+ end
497
+ end
498
+ end if t2
499
+
500
+ changed
501
+ end
502
+
503
+ # returns true if the files in path_limiter were changed, or no path limiter
504
+ # used by the log() function when passed with a path_limiter
505
+ def files_changed?(tree_sha1, tree_sha2, path_limiter = nil)
506
+ if path_limiter
507
+ mod = quick_diff(tree_sha1, tree_sha2)
508
+ files = mod.map { |c| c.first }
509
+ path_limiter.to_a.each do |filepath|
510
+ if files.include?(filepath)
511
+ return true
512
+ end
513
+ end
514
+ return false
515
+ end
516
+ true
517
+ end
518
+
519
+ def get_subtree(commit_sha, path)
520
+ tree_sha = get_object_by_sha1(commit_sha).tree
521
+
522
+ if path && !(path == '' || path == '.' || path == './')
523
+ paths = path.split('/')
524
+ paths.each do |path|
525
+ tree = get_object_by_sha1(tree_sha)
526
+ if entry = tree.entry.select { |e| e.name == path }.first
527
+ tree_sha = entry.sha1 rescue nil
528
+ else
529
+ return false
530
+ end
531
+ end
532
+ end
533
+
534
+ tree_sha
535
+ end
536
+
537
+ def blame_tree(commit_sha, path)
538
+ # find subtree
539
+ tree_sha = get_subtree(commit_sha, path)
540
+ return {} if !tree_sha
541
+
542
+ looking_for = []
543
+ get_object_by_sha1(tree_sha).entry.each do |e|
544
+ looking_for << File.join('.', e.name)
545
+ end
546
+
547
+ @already_searched = {}
548
+ commits = look_for_commits(commit_sha, path, looking_for)
549
+
550
+ # cleaning up array
551
+ arr = {}
552
+ commits.each do |commit_array|
553
+ key = commit_array[0].gsub('./', '')
554
+ arr[key] = commit_array[1]
555
+ end
556
+ arr
557
+ end
558
+
559
+ def look_for_commits(commit_sha, path, looking_for, options = {})
560
+ return [] if @already_searched[commit_sha] # to prevent rechecking branches
561
+
562
+ @already_searched[commit_sha] = true
563
+
564
+ commit = get_object_by_sha1(commit_sha)
565
+ tree_sha = get_subtree(commit_sha, path)
566
+
567
+ found_data = []
568
+
569
+ # at the beginning of the branch
570
+ if commit.parent.size == 0
571
+ looking_for.each do |search|
572
+ # prevents the rare case of multiple branch starting points with
573
+ # files that have never changed
574
+ if found_data.assoc(search)
575
+ found_data << [search, commit_sha]
576
+ end
577
+ end
578
+ return found_data
579
+ end
580
+
581
+ # go through the parents recursively, looking for somewhere this has been changed
582
+ commit.parent.each do |pc|
583
+ diff = quick_diff(tree_sha, get_subtree(pc, path), '.', false)
584
+
585
+ # remove anything found
586
+ looking_for.each do |search|
587
+ if match = diff.assoc(search)
588
+ found_data << [search, commit_sha, match]
589
+ looking_for.delete(search)
590
+ end
591
+ end
592
+
593
+ if looking_for.size <= 0 # we're done
594
+ return found_data
595
+ end
596
+
597
+ found_data += look_for_commits(pc, path, looking_for) # recurse into parent
598
+ return found_data if options[:first_parent]
599
+ end
600
+
601
+ ## TODO : find most recent commit with change in any parent
602
+ found_data
603
+ end
604
+
605
+ # initialize a git repository
606
+ def self.init(dir, bare = false)
607
+
608
+ FileUtils.mkdir_p(dir) if !File.exists?(dir)
609
+
610
+ FileUtils.cd(dir) do
611
+ if(File.exists?('objects'))
612
+ return false # already initialized
613
+ else
614
+ # initialize directory
615
+ create_initial_config(bare)
616
+ FileUtils.mkdir_p('refs/heads')
617
+ FileUtils.mkdir_p('refs/tags')
618
+ FileUtils.mkdir_p('objects/info')
619
+ FileUtils.mkdir_p('objects/pack')
620
+ FileUtils.mkdir_p('branches')
621
+ add_file('description', 'Unnamed repository; edit this file to name it for gitweb.')
622
+ add_file('HEAD', "ref: refs/heads/master\n")
623
+ FileUtils.mkdir_p('hooks')
624
+ FileUtils.cd('hooks') do
625
+ add_file('applypatch-msg', '# add shell script and make executable to enable')
626
+ add_file('post-commit', '# add shell script and make executable to enable')
627
+ add_file('post-receive', '# add shell script and make executable to enable')
628
+ add_file('post-update', '# add shell script and make executable to enable')
629
+ add_file('pre-applypatch', '# add shell script and make executable to enable')
630
+ add_file('pre-commit', '# add shell script and make executable to enable')
631
+ add_file('pre-rebase', '# add shell script and make executable to enable')
632
+ add_file('update', '# add shell script and make executable to enable')
633
+ end
634
+ FileUtils.mkdir_p('info')
635
+ add_file('info/exclude', "# *.[oa]\n# *~")
636
+ end
637
+ end
638
+ end
639
+
640
+ def self.create_initial_config(bare = false)
641
+ bare ? bare_status = 'true' : bare_status = 'false'
642
+ config = "[core]\n\trepositoryformatversion = 0\n\tfilemode = true\n\tbare = #{bare_status}\n\tlogallrefupdates = true"
643
+ add_file('config', config)
644
+ end
645
+
646
+ def self.add_file(name, contents)
647
+ File.open(name, 'w') do |f|
648
+ f.write contents
649
+ end
650
+ end
651
+
652
+ def close
653
+ @packs.each do |pack|
654
+ pack.close
655
+ end if @packs
656
+ end
657
+
658
+ protected
659
+
660
+ def git_path(path)
661
+ return "#@git_dir/#{path}"
662
+ end
663
+
664
+ private
665
+
666
+ def initloose
667
+ @loose = []
668
+ load_loose(git_path('objects'))
669
+ load_alternate_loose(git_path('objects'))
670
+ @loose
671
+ end
672
+
673
+ def load_alternate_loose(path)
674
+ # load alternate loose, too
675
+ alt = File.join(path, 'info/alternates')
676
+ if File.exists?(alt)
677
+ File.readlines(alt).each do |line|
678
+ if line[0, 2] == '..'
679
+ line = File.expand_path(File.join(@git_dir, line))
680
+ end
681
+ load_loose(line.chomp)
682
+ load_alternate_loose(line.chomp)
683
+ end
684
+ end
685
+ end
686
+
687
+ def load_loose(path)
688
+ return if !File.exists?(path)
689
+ @loose << Grit::GitRuby::Internal::LooseStorage.new(path)
690
+ end
691
+
692
+ def initpacks
693
+ close
694
+ @packs = []
695
+ load_packs(git_path("objects/pack"))
696
+ load_alternate_packs(git_path('objects'))
697
+ @packs
698
+ end
699
+
700
+ def load_alternate_packs(path)
701
+ alt = File.join(path, 'info/alternates')
702
+ if File.exists?(alt)
703
+ File.readlines(alt).each do |line|
704
+ if line[0, 2] == '..'
705
+ line = File.expand_path(File.join(@git_dir, line))
706
+ end
707
+ full_pack = File.join(line.chomp, 'pack')
708
+ load_packs(full_pack)
709
+ load_alternate_packs(File.join(line.chomp))
710
+ end
711
+ end
712
+ end
713
+
714
+ def load_packs(path)
715
+ return if !File.exists?(path)
716
+ Dir.open(path) do |dir|
717
+ dir.each do |entry|
718
+ next if !(entry =~ /\.pack$/i)
719
+ pack = Grit::GitRuby::Internal::PackStorage.new(File.join(path,entry))
720
+ if @options[:map_packfile]
721
+ pack.cache_objects
722
+ end
723
+ @packs << pack
724
+ end
725
+ end
726
+ end
727
+
728
+ end
729
+
730
+ end
731
+ end