rhomobile-grit 2.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/lib/grit/git.rb ADDED
@@ -0,0 +1,472 @@
1
+ require 'tempfile'
2
+ module Grit
3
+
4
+ class Git
5
+ class GitTimeout < RuntimeError
6
+ attr_accessor :command
7
+ attr_accessor :bytes_read
8
+
9
+ def initialize(command = nil, bytes_read = nil)
10
+ @command = command
11
+ @bytes_read = bytes_read
12
+ end
13
+ end
14
+
15
+ # Raised when a native git command exits with non-zero.
16
+ class CommandFailed < StandardError
17
+ # The full git command that failed as a String.
18
+ attr_reader :command
19
+
20
+ # The integer exit status.
21
+ attr_reader :exitstatus
22
+
23
+ # Everything output on the command's stderr as a String.
24
+ attr_reader :err
25
+
26
+ def initialize(command, exitstatus=nil, err='')
27
+ if exitstatus
28
+ @command = command
29
+ @exitstatus = exitstatus
30
+ @err = err
31
+ message = "Command failed [#{exitstatus}]: #{command}"
32
+ message << "\n\n" << err unless err.nil? || err.empty?
33
+ super message
34
+ else
35
+ super command
36
+ end
37
+ end
38
+ end
39
+
40
+ undef_method :clone
41
+
42
+ include GitRuby
43
+
44
+ def exist?
45
+ File.exist?(self.git_dir)
46
+ end
47
+
48
+ def put_raw_object(content, type)
49
+ ruby_git.put_raw_object(content, type)
50
+ end
51
+
52
+ def object_exists?(object_id)
53
+ ruby_git.object_exists?(object_id)
54
+ end
55
+
56
+ def select_existing_objects(object_ids)
57
+ object_ids.select do |object_id|
58
+ object_exists?(object_id)
59
+ end
60
+ end
61
+
62
+ class << self
63
+ attr_accessor :git_timeout, :git_max_size
64
+ def git_binary
65
+ @git_binary ||=
66
+ ENV['PATH'].split(':').
67
+ map { |p| File.join(p, 'git') }.
68
+ find { |p| File.exist?(p) }
69
+ end
70
+ attr_writer :git_binary
71
+ end
72
+
73
+ self.git_timeout = 10
74
+ self.git_max_size = 5242880 # 5.megabytes
75
+
76
+ def self.with_timeout(timeout = 10.seconds)
77
+ old_timeout = Grit::Git.git_timeout
78
+ Grit::Git.git_timeout = timeout
79
+ yield
80
+ Grit::Git.git_timeout = old_timeout
81
+ end
82
+
83
+ attr_accessor :git_dir, :bytes_read, :work_tree
84
+
85
+ def initialize(git_dir)
86
+ self.git_dir = git_dir
87
+ self.work_tree = git_dir.gsub(/\/\.git$/,'')
88
+ self.bytes_read = 0
89
+ end
90
+
91
+ def shell_escape(str)
92
+ str.to_s.gsub("'", "\\\\'").gsub(";", '\\;')
93
+ end
94
+ alias_method :e, :shell_escape
95
+
96
+ # Check if a normal file exists on the filesystem
97
+ # +file+ is the relative path from the Git dir
98
+ #
99
+ # Returns Boolean
100
+ def fs_exist?(file)
101
+ File.exist?(File.join(self.git_dir, file))
102
+ end
103
+
104
+ # Read a normal file from the filesystem.
105
+ # +file+ is the relative path from the Git dir
106
+ #
107
+ # Returns the String contents of the file
108
+ def fs_read(file)
109
+ File.read(File.join(self.git_dir, file))
110
+ end
111
+
112
+ # Write a normal file to the filesystem.
113
+ # +file+ is the relative path from the Git dir
114
+ # +contents+ is the String content to be written
115
+ #
116
+ # Returns nothing
117
+ def fs_write(file, contents)
118
+ path = File.join(self.git_dir, file)
119
+ FileUtils.mkdir_p(File.dirname(path))
120
+ File.open(path, 'w') do |f|
121
+ f.write(contents)
122
+ end
123
+ end
124
+
125
+ # Delete a normal file from the filesystem
126
+ # +file+ is the relative path from the Git dir
127
+ #
128
+ # Returns nothing
129
+ def fs_delete(file)
130
+ FileUtils.rm_rf(File.join(self.git_dir, file))
131
+ end
132
+
133
+ # Move a normal file
134
+ # +from+ is the relative path to the current file
135
+ # +to+ is the relative path to the destination file
136
+ #
137
+ # Returns nothing
138
+ def fs_move(from, to)
139
+ FileUtils.mv(File.join(self.git_dir, from), File.join(self.git_dir, to))
140
+ end
141
+
142
+ # Make a directory
143
+ # +dir+ is the relative path to the directory to create
144
+ #
145
+ # Returns nothing
146
+ def fs_mkdir(dir)
147
+ FileUtils.mkdir_p(File.join(self.git_dir, dir))
148
+ end
149
+
150
+ # Chmod the the file or dir and everything beneath
151
+ # +file+ is the relative path from the Git dir
152
+ #
153
+ # Returns nothing
154
+ def fs_chmod(mode, file = '/')
155
+ FileUtils.chmod_R(mode, File.join(self.git_dir, file))
156
+ end
157
+
158
+ def list_remotes
159
+ remotes = []
160
+ Dir.chdir(File.join(self.git_dir, 'refs/remotes')) do
161
+ remotes = Dir.glob('*')
162
+ end
163
+ remotes
164
+ rescue
165
+ []
166
+ end
167
+
168
+ def create_tempfile(seed, unlink = false)
169
+ path = Tempfile.new(seed).path
170
+ File.unlink(path) if unlink
171
+ return path
172
+ end
173
+
174
+ def commit_from_sha(id)
175
+ git_ruby_repo = GitRuby::Repository.new(self.git_dir)
176
+ object = git_ruby_repo.get_object_by_sha1(id)
177
+
178
+ if object.type == :commit
179
+ id
180
+ elsif object.type == :tag
181
+ object.object
182
+ else
183
+ ''
184
+ end
185
+ end
186
+
187
+ # Checks if the patch of a commit can be applied to the given head.
188
+ #
189
+ # head_sha - String SHA or ref to check the patch against.
190
+ # applies_sha - String SHA of the patch. The patch itself is retrieved
191
+ # with #get_patch.
192
+ #
193
+ # Returns 0 if the patch applies cleanly (according to `git apply`), or
194
+ # an Integer that is the sum of the failed exit statuses.
195
+ def check_applies(head_sha, applies_sha)
196
+ git_index = create_tempfile('index', true)
197
+ options = {:env => {'GIT_INDEX_FILE' => git_index}, :raise => true}
198
+ status = 0
199
+ begin
200
+ native(:read_tree, options.dup, head_sha)
201
+ stdin = native(:diff, options.dup, "#{applies_sha}^", applies_sha)
202
+ native(:apply, options.merge(:check => true, :cached => true, :input => stdin))
203
+ rescue CommandFailed => fail
204
+ status += fail.exitstatus
205
+ end
206
+ status
207
+ end
208
+
209
+ # Gets a patch for a given SHA using `git diff`.
210
+ #
211
+ # applies_sha - String SHA to get the patch from, using this command:
212
+ # `git diff #{applies_sha}^ #{applies_sha}`
213
+ #
214
+ # Returns the String patch from `git diff`.
215
+ def get_patch(applies_sha)
216
+ git_index = create_tempfile('index', true)
217
+ native(:diff, {
218
+ :env => {'GIT_INDEX_FILE' => git_index}},
219
+ "#{applies_sha}^", applies_sha)
220
+ end
221
+
222
+ # Applies the given patch against the given SHA of the current repo.
223
+ #
224
+ # head_sha - String SHA or ref to apply the patch to.
225
+ # patch - The String patch to apply. Get this from #get_patch.
226
+ #
227
+ # Returns the String Tree SHA on a successful patch application, or false.
228
+ def apply_patch(head_sha, patch)
229
+ git_index = create_tempfile('index', true)
230
+
231
+ options = {:env => {'GIT_INDEX_FILE' => git_index}, :raise => true}
232
+ begin
233
+ native(:read_tree, options.dup, head_sha)
234
+ native(:apply, options.merge(:cached => true, :input => patch))
235
+ rescue CommandFailed
236
+ return false
237
+ end
238
+ native(:write_tree, :env => options[:env]).to_s.chomp!
239
+ end
240
+
241
+ # Execute a git command, bypassing any library implementation.
242
+ #
243
+ # cmd - The name of the git command as a Symbol. Underscores are
244
+ # converted to dashes as in :rev_parse => 'rev-parse'.
245
+ # options - Command line option arguments passed to the git command.
246
+ # Single char keys are converted to short options (:a => -a).
247
+ # Multi-char keys are converted to long options (:arg => '--arg').
248
+ # Underscores in keys are converted to dashes. These special options
249
+ # are used to control command execution and are not passed in command
250
+ # invocation:
251
+ # :timeout - Maximum amount of time the command can run for before
252
+ # being aborted. When true, use Grit::Git.git_timeout; when numeric,
253
+ # use that number of seconds; when false or 0, disable timeout.
254
+ # :base - Set false to avoid passing the --git-dir argument when
255
+ # invoking the git command.
256
+ # :env - Hash of environment variable key/values that are set on the
257
+ # child process.
258
+ # :raise - When set true, commands that exit with a non-zero status
259
+ # raise a CommandFailed exception. This option is available only on
260
+ # platforms that support fork(2).
261
+ # :process_info - By default, a single string with output written to
262
+ # the process's stdout is returned. Setting this option to true
263
+ # results in a [exitstatus, out, err] tuple being returned instead.
264
+ # args - Non-option arguments passed on the command line.
265
+ #
266
+ # Optionally yields to the block an IO object attached to the child
267
+ # process's STDIN.
268
+ #
269
+ # Examples
270
+ # git.native(:rev_list, {:max_count => 10, :header => true}, "master")
271
+ #
272
+ # Returns a String with all output written to the child process's stdout
273
+ # when the :process_info option is not set.
274
+ # Returns a [exitstatus, out, err] tuple when the :process_info option is
275
+ # set. The exitstatus is an small integer that was the process's exit
276
+ # status. The out and err elements are the data written to stdout and
277
+ # stderr as Strings.
278
+ # Raises Grit::Git::GitTimeout when the timeout is exceeded or when more
279
+ # than Grit::Git.git_max_size bytes are output.
280
+ # Raises Grit::Git::CommandFailed when the :raise option is set true and the
281
+ # git command exits with a non-zero exit status. The CommandFailed's #command,
282
+ # #exitstatus, and #err attributes can be used to retrieve additional
283
+ # detail about the error.
284
+ def native(cmd, options = {}, *args, &block)
285
+ args = args.first if args.size == 1 && args[0].is_a?(Array)
286
+ args.map! { |a| a.to_s.strip }
287
+ args.reject! { |a| a.empty? }
288
+
289
+ # special option arguments
290
+ env = options.delete(:env) || {}
291
+ raise_errors = options.delete(:raise)
292
+ process_info = options.delete(:process_info)
293
+
294
+ # fall back to using a shell when the last argument looks like it wants to
295
+ # start a pipeline for compatibility with previous versions of grit.
296
+ return run(prefix, cmd, '', options, args) if args[-1].to_s[0] == ?|
297
+
298
+ # more options
299
+ input = options.delete(:input)
300
+ timeout = options.delete(:timeout); timeout = true if timeout.nil?
301
+ base = options.delete(:base); base = true if base.nil?
302
+ chdir = options.delete(:chdir)
303
+
304
+ # build up the git process argv
305
+ argv = []
306
+ argv << Git.git_binary
307
+ argv << "--git-dir=#{git_dir}" if base
308
+ argv << cmd.to_s.tr('_', '-')
309
+ argv.concat(options_to_argv(options))
310
+ argv.concat(args)
311
+
312
+ # run it and deal with fallout
313
+ Grit.log(argv.join(' ')) if Grit.debug
314
+
315
+ process =
316
+ Grit::Process.new(argv, env,
317
+ :input => input,
318
+ :chdir => chdir,
319
+ :timeout => (Grit::Git.git_timeout if timeout == true),
320
+ :max => (Grit::Git.git_max_size if timeout == true)
321
+ )
322
+ Grit.log(process.out) if Grit.debug
323
+ Grit.log(process.err) if Grit.debug
324
+
325
+ status = process.status
326
+ if raise_errors && !status.success?
327
+ raise CommandFailed.new(argv.join(' '), status.exitstatus, process.err)
328
+ elsif process_info
329
+ [status.exitstatus, process.out, process.err]
330
+ else
331
+ process.out
332
+ end
333
+ rescue Grit::Process::TimeoutExceeded, Grit::Process::MaximumOutputExceeded
334
+ raise GitTimeout, argv.join(' ')
335
+ end
336
+
337
+ # Methods not defined by a library implementation execute the git command
338
+ # using #native, passing the method name as the git command name.
339
+ #
340
+ # Examples:
341
+ # git.rev_list({:max_count => 10, :header => true}, "master")
342
+ def method_missing(cmd, options={}, *args, &block)
343
+ native(cmd, options, *args, &block)
344
+ end
345
+
346
+ # Transform a ruby-style options hash to command-line arguments sutiable for
347
+ # use with Kernel::exec. No shell escaping is performed.
348
+ #
349
+ # Returns an Array of String option arguments.
350
+ def options_to_argv(options)
351
+ argv = []
352
+ options.each do |key, val|
353
+ if key.to_s.size == 1
354
+ if val == true
355
+ argv << "-#{key}"
356
+ elsif val == false
357
+ # ignore
358
+ else
359
+ argv << "-#{key}"
360
+ argv << val.to_s
361
+ end
362
+ else
363
+ if val == true
364
+ argv << "--#{key.to_s.tr('_', '-')}"
365
+ elsif val == false
366
+ # ignore
367
+ else
368
+ argv << "--#{key.to_s.tr('_', '-')}=#{val}"
369
+ end
370
+ end
371
+ end
372
+ argv
373
+ end
374
+
375
+ # Simple wrapper around Timeout::timeout.
376
+ #
377
+ # seconds - Float number of seconds before a Timeout::Error is raised. When
378
+ # true, the Grit::Git.git_timeout value is used. When the timeout is less
379
+ # than or equal to 0, no timeout is established.
380
+ #
381
+ # Raises Timeout::Error when the timeout has elapsed.
382
+ def timeout_after(seconds)
383
+ seconds = self.class.git_timeout if seconds == true
384
+ if seconds && seconds > 0
385
+ Timeout.timeout(seconds) { yield }
386
+ else
387
+ yield
388
+ end
389
+ end
390
+
391
+ # DEPRECATED OPEN3-BASED COMMAND EXECUTION
392
+
393
+ def run(prefix, cmd, postfix, options, args, &block)
394
+ timeout = options.delete(:timeout) rescue nil
395
+ timeout = true if timeout.nil?
396
+
397
+ base = options.delete(:base) rescue nil
398
+ base = true if base.nil?
399
+
400
+ if input = options.delete(:input)
401
+ block = lambda { |stdin| stdin.write(input) }
402
+ end
403
+
404
+ opt_args = transform_options(options)
405
+
406
+ if RUBY_PLATFORM.downcase =~ /mswin(?!ce)|mingw|bccwin/
407
+ ext_args = args.reject { |a| a.empty? }.map { |a| (a == '--' || a[0].chr == '|' || Grit.no_quote) ? a : "\"#{e(a)}\"" }
408
+ gitdir = base ? "--git-dir=\"#{self.git_dir}\"" : ""
409
+ call = "#{prefix}#{Git.git_binary} #{gitdir} #{cmd.to_s.gsub(/_/, '-')} #{(opt_args + ext_args).join(' ')}#{e(postfix)}"
410
+ else
411
+ ext_args = args.reject { |a| a.empty? }.map { |a| (a == '--' || a[0].chr == '|' || Grit.no_quote) ? a : "'#{e(a)}'" }
412
+ gitdir = base ? "--git-dir='#{self.git_dir}'" : ""
413
+ call = "#{prefix}#{Git.git_binary} #{gitdir} #{cmd.to_s.gsub(/_/, '-')} #{(opt_args + ext_args).join(' ')}#{e(postfix)}"
414
+ end
415
+
416
+ Grit.log(call) if Grit.debug
417
+ response, err = timeout ? sh(call, &block) : wild_sh(call, &block)
418
+ Grit.log(response) if Grit.debug
419
+ Grit.log(err) if Grit.debug
420
+ response
421
+ end
422
+
423
+ def sh(command, &block)
424
+ process =
425
+ Grit::Process.new(
426
+ command, {},
427
+ :timeout => Git.git_timeout,
428
+ :max => Git.git_max_size
429
+ )
430
+ [process.out, process.err]
431
+ rescue Grit::Process::TimeoutExceeded, Grit::Process::MaximumOutputExceeded
432
+ raise GitTimeout, command
433
+ end
434
+
435
+ def wild_sh(command, &block)
436
+ process = Grit::Process.new(command)
437
+ [process.out, process.err]
438
+ end
439
+
440
+ # Transform Ruby style options into git command line options
441
+ # +options+ is a hash of Ruby style options
442
+ #
443
+ # Returns String[]
444
+ # e.g. ["--max-count=10", "--header"]
445
+ def transform_options(options)
446
+ args = []
447
+ options.keys.each do |opt|
448
+ if opt.to_s.size == 1
449
+ if options[opt] == true
450
+ args << "-#{opt}"
451
+ elsif options[opt] == false
452
+ # ignore
453
+ else
454
+ val = options.delete(opt)
455
+ args << "-#{opt.to_s} '#{e(val)}'"
456
+ end
457
+ else
458
+ if options[opt] == true
459
+ args << "--#{opt.to_s.gsub(/_/, '-')}"
460
+ elsif options[opt] == false
461
+ # ignore
462
+ else
463
+ val = options.delete(opt)
464
+ args << "--#{opt.to_s.gsub(/_/, '-')}='#{e(val)}'"
465
+ end
466
+ end
467
+ end
468
+ args
469
+ end
470
+ end # Git
471
+
472
+ end # Grit