Class: Grit::Git
Defined Under Namespace
Classes: CommandFailed, GitTimeout
Class Attribute Summary collapse
- .git_binary ⇒ Object
-
.git_max_size ⇒ Object
Returns the value of attribute git_max_size.
-
.git_timeout ⇒ Object
Returns the value of attribute git_timeout.
Instance Attribute Summary collapse
-
#bytes_read ⇒ Object
Returns the value of attribute bytes_read.
-
#git_dir ⇒ Object
Returns the value of attribute git_dir.
-
#work_tree ⇒ Object
Returns the value of attribute work_tree.
Attributes included from GitRuby
#git_file_index, #ruby_git_repo
Class Method Summary collapse
Instance Method Summary collapse
-
#apply_patch(head_sha, patch) ⇒ Object
Applies the given patch against the given SHA of the current repo.
-
#check_applies(head_sha, applies_sha) ⇒ Object
Checks if the patch of a commit can be applied to the given head.
- #commit_from_sha(id) ⇒ Object
- #create_tempfile(seed, unlink = false) ⇒ Object
- #exist? ⇒ Boolean
-
#fs_chmod(mode, file = '/') ⇒ Object
Chmod the the file or dir and everything beneath
file
is the relative path from the Git dir. -
#fs_delete(file) ⇒ Object
Delete a normal file from the filesystem
file
is the relative path from the Git dir. -
#fs_exist?(file) ⇒ Boolean
Check if a normal file exists on the filesystem
file
is the relative path from the Git dir. -
#fs_mkdir(dir) ⇒ Object
Make a directory
dir
is the relative path to the directory to create. -
#fs_move(from, to) ⇒ Object
Move a normal file
from
is the relative path to the current fileto
is the relative path to the destination file. -
#fs_read(file) ⇒ Object
Read a normal file from the filesystem.
-
#fs_write(file, contents) ⇒ Object
Write a normal file to the filesystem.
-
#get_patch(applies_sha) ⇒ Object
Gets a patch for a given SHA using ‘git diff`.
-
#initialize(git_dir) ⇒ Git
constructor
A new instance of Git.
- #list_remotes ⇒ Object
-
#method_missing(cmd, options = {}, *args, &block) ⇒ Object
Methods not defined by a library implementation execute the git command using #native, passing the method name as the git command name.
-
#native(cmd, options = {}, *args, &block) ⇒ Object
Execute a git command, bypassing any library implementation.
- #object_exists?(object_id) ⇒ Boolean
-
#options_to_argv(options) ⇒ Object
Transform a ruby-style options hash to command-line arguments sutiable for use with Kernel::exec.
- #put_raw_object(content, type) ⇒ Object
-
#run(prefix, cmd, postfix, options, args, &block) ⇒ Object
DEPRECATED OPEN3-BASED COMMAND EXECUTION.
- #select_existing_objects(object_ids) ⇒ Object
- #sh(command, &block) ⇒ Object
- #shell_escape(str) ⇒ Object (also: #e)
-
#timeout_after(seconds) ⇒ Object
Simple wrapper around Timeout::timeout.
-
#transform_options(options) ⇒ Object
Transform Ruby style options into git command line options
options
is a hash of Ruby style options. - #wild_sh(command, &block) ⇒ Object
Methods included from GitRuby
#blame_tree, #cat_file, #cat_ref, #diff, #file_index, #file_size, #file_type, #init, #ls_tree, read_bytes_until, #refs, #rev_list, #rev_parse, #ruby_git, #tags
Constructor Details
#initialize(git_dir) ⇒ Git
Returns a new instance of Git.
85 86 87 88 89 |
# File 'lib/grit/git.rb', line 85 def initialize(git_dir) self.git_dir = git_dir self.work_tree = git_dir.gsub(/\/\.git$/,'') self.bytes_read = 0 end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(cmd, options = {}, *args, &block) ⇒ Object
Methods not defined by a library implementation execute the git command using #native, passing the method name as the git command name.
Examples:
git.rev_list({:max_count => 10, :header => true}, "master")
342 343 344 |
# File 'lib/grit/git.rb', line 342 def method_missing(cmd, ={}, *args, &block) native(cmd, , *args, &block) end |
Class Attribute Details
.git_binary ⇒ Object
64 65 66 67 68 69 |
# File 'lib/grit/git.rb', line 64 def git_binary @git_binary ||= ENV['PATH'].split(':'). map { |p| File.join(p, 'git') }. find { |p| File.exist?(p) } end |
.git_max_size ⇒ Object
Returns the value of attribute git_max_size.
63 64 65 |
# File 'lib/grit/git.rb', line 63 def git_max_size @git_max_size end |
.git_timeout ⇒ Object
Returns the value of attribute git_timeout.
63 64 65 |
# File 'lib/grit/git.rb', line 63 def git_timeout @git_timeout end |
Instance Attribute Details
#bytes_read ⇒ Object
Returns the value of attribute bytes_read.
83 84 85 |
# File 'lib/grit/git.rb', line 83 def bytes_read @bytes_read end |
#git_dir ⇒ Object
Returns the value of attribute git_dir.
83 84 85 |
# File 'lib/grit/git.rb', line 83 def git_dir @git_dir end |
#work_tree ⇒ Object
Returns the value of attribute work_tree.
83 84 85 |
# File 'lib/grit/git.rb', line 83 def work_tree @work_tree end |
Class Method Details
.with_timeout(timeout = 10.seconds) ⇒ Object
76 77 78 79 80 81 |
# File 'lib/grit/git.rb', line 76 def self.with_timeout(timeout = 10.seconds) old_timeout = Grit::Git.git_timeout Grit::Git.git_timeout = timeout yield Grit::Git.git_timeout = old_timeout end |
Instance Method Details
#apply_patch(head_sha, patch) ⇒ Object
Applies the given patch against the given SHA of the current repo.
head_sha - String SHA or ref to apply the patch to. patch - The String patch to apply. Get this from #get_patch.
Returns the String Tree SHA on a successful patch application, or false.
228 229 230 231 232 233 234 235 236 237 238 239 |
# File 'lib/grit/git.rb', line 228 def apply_patch(head_sha, patch) git_index = create_tempfile('index', true) = {:env => {'GIT_INDEX_FILE' => git_index}, :raise => true} begin native(:read_tree, .dup, head_sha) native(:apply, .merge(:cached => true, :input => patch)) rescue CommandFailed return false end native(:write_tree, :env => [:env]).to_s.chomp! end |
#check_applies(head_sha, applies_sha) ⇒ Object
Checks if the patch of a commit can be applied to the given head.
head_sha - String SHA or ref to check the patch against. applies_sha - String SHA of the patch. The patch itself is retrieved
with #get_patch.
Returns 0 if the patch applies cleanly (according to ‘git apply`), or an Integer that is the sum of the failed exit statuses.
195 196 197 198 199 200 201 202 203 204 205 206 207 |
# File 'lib/grit/git.rb', line 195 def check_applies(head_sha, applies_sha) git_index = create_tempfile('index', true) = {:env => {'GIT_INDEX_FILE' => git_index}, :raise => true} status = 0 begin native(:read_tree, .dup, head_sha) stdin = native(:diff, .dup, "#{applies_sha}^", applies_sha) native(:apply, .merge(:check => true, :cached => true, :input => stdin)) rescue CommandFailed => fail status += fail.exitstatus end status end |
#commit_from_sha(id) ⇒ Object
174 175 176 177 178 179 180 181 182 183 184 185 |
# File 'lib/grit/git.rb', line 174 def commit_from_sha(id) git_ruby_repo = GitRuby::Repository.new(self.git_dir) object = git_ruby_repo.get_object_by_sha1(id) if object.type == :commit id elsif object.type == :tag object.object else '' end end |
#create_tempfile(seed, unlink = false) ⇒ Object
168 169 170 171 172 |
# File 'lib/grit/git.rb', line 168 def create_tempfile(seed, unlink = false) path = Tempfile.new(seed).path File.unlink(path) if unlink return path end |
#exist? ⇒ Boolean
44 45 46 |
# File 'lib/grit/git.rb', line 44 def exist? File.exist?(self.git_dir) end |
#fs_chmod(mode, file = '/') ⇒ Object
Chmod the the file or dir and everything beneath
+file+ is the relative path from the Git dir
Returns nothing
154 155 156 |
# File 'lib/grit/git.rb', line 154 def fs_chmod(mode, file = '/') FileUtils.chmod_R(mode, File.join(self.git_dir, file)) end |
#fs_delete(file) ⇒ Object
Delete a normal file from the filesystem
+file+ is the relative path from the Git dir
Returns nothing
129 130 131 |
# File 'lib/grit/git.rb', line 129 def fs_delete(file) FileUtils.rm_rf(File.join(self.git_dir, file)) end |
#fs_exist?(file) ⇒ Boolean
Check if a normal file exists on the filesystem
+file+ is the relative path from the Git dir
Returns Boolean
100 101 102 |
# File 'lib/grit/git.rb', line 100 def fs_exist?(file) File.exist?(File.join(self.git_dir, file)) end |
#fs_mkdir(dir) ⇒ Object
Make a directory
+dir+ is the relative path to the directory to create
Returns nothing
146 147 148 |
# File 'lib/grit/git.rb', line 146 def fs_mkdir(dir) FileUtils.mkdir_p(File.join(self.git_dir, dir)) end |
#fs_move(from, to) ⇒ Object
Move a normal file
+from+ is the relative path to the current file
+to+ is the relative path to the destination file
Returns nothing
138 139 140 |
# File 'lib/grit/git.rb', line 138 def fs_move(from, to) FileUtils.mv(File.join(self.git_dir, from), File.join(self.git_dir, to)) end |
#fs_read(file) ⇒ Object
Read a normal file from the filesystem.
+file+ is the relative path from the Git dir
Returns the String contents of the file
108 109 110 |
# File 'lib/grit/git.rb', line 108 def fs_read(file) File.read(File.join(self.git_dir, file)) end |
#fs_write(file, contents) ⇒ Object
Write a normal file to the filesystem.
+file+ is the relative path from the Git dir
+contents+ is the String content to be written
Returns nothing
117 118 119 120 121 122 123 |
# File 'lib/grit/git.rb', line 117 def fs_write(file, contents) path = File.join(self.git_dir, file) FileUtils.mkdir_p(File.dirname(path)) File.open(path, 'w') do |f| f.write(contents) end end |
#get_patch(applies_sha) ⇒ Object
Gets a patch for a given SHA using ‘git diff`.
applies_sha - String SHA to get the patch from, using this command:
`git diff #{applies_sha}^ #{applies_sha}`
Returns the String patch from ‘git diff`.
215 216 217 218 219 220 |
# File 'lib/grit/git.rb', line 215 def get_patch(applies_sha) git_index = create_tempfile('index', true) native(:diff, { :env => {'GIT_INDEX_FILE' => git_index}}, "#{applies_sha}^", applies_sha) end |
#list_remotes ⇒ Object
158 159 160 161 162 163 164 165 166 |
# File 'lib/grit/git.rb', line 158 def list_remotes remotes = [] Dir.chdir(File.join(self.git_dir, 'refs/remotes')) do remotes = Dir.glob('*') end remotes rescue [] end |
#native(cmd, options = {}, *args, &block) ⇒ Object
Execute a git command, bypassing any library implementation.
cmd - The name of the git command as a Symbol. Underscores are
converted to dashes as in :rev_parse => 'rev-parse'.
options - Command line option arguments passed to the git command.
Single char keys are converted to short options (:a => -a).
Multi-char keys are converted to long options (:arg => '--arg').
Underscores in keys are converted to dashes. These special options
are used to control command execution and are not passed in command
invocation:
:timeout - Maximum amount of time the command can run for before
being aborted. When true, use Grit::Git.git_timeout; when numeric,
use that number of seconds; when false or 0, disable timeout.
:base - Set false to avoid passing the --git-dir argument when
invoking the git command.
:env - Hash of environment variable key/values that are set on the
child process.
:raise - When set true, commands that exit with a non-zero status
raise a CommandFailed exception. This option is available only on
platforms that support fork(2).
:process_info - By default, a single string with output written to
the process's stdout is returned. Setting this option to true
results in a [exitstatus, out, err] tuple being returned instead.
args - Non-option arguments passed on the command line.
Optionally yields to the block an IO object attached to the child process’s STDIN.
Examples
git.native(:rev_list, {:max_count => 10, :header => true}, "master")
Returns a String with all output written to the child process’s stdout
when the :process_info option is not set.
Returns a [exitstatus, out, err] tuple when the :process_info option is
set. The exitstatus is an small integer that was the process's exit
status. The out and err elements are the data written to stdout and
stderr as Strings.
Raises Grit::Git::GitTimeout when the timeout is exceeded or when more
than Grit::Git.git_max_size bytes are output.
Raises Grit::Git::CommandFailed when the :raise option is set true and the
git command exits with a non-zero exit status. The CommandFailed's #command,
#exitstatus, and #err attributes can be used to retrieve additional
detail about the error.
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 |
# File 'lib/grit/git.rb', line 284 def native(cmd, = {}, *args, &block) args = args.first if args.size == 1 && args[0].is_a?(Array) args.map! { |a| a.to_s.strip } args.reject! { |a| a.empty? } # special option arguments env = .delete(:env) || {} raise_errors = .delete(:raise) process_info = .delete(:process_info) # fall back to using a shell when the last argument looks like it wants to # start a pipeline for compatibility with previous versions of grit. return run(prefix, cmd, '', , args) if args[-1].to_s[0] == ?| # more options input = .delete(:input) timeout = .delete(:timeout); timeout = true if timeout.nil? base = .delete(:base); base = true if base.nil? chdir = .delete(:chdir) # build up the git process argv argv = [] argv << Git.git_binary argv << "--git-dir=#{git_dir}" if base argv << cmd.to_s.tr('_', '-') argv.concat(()) argv.concat(args) # run it and deal with fallout Grit.log(argv.join(' ')) if Grit.debug process = Grit::Process.new(argv, env, :input => input, :chdir => chdir, :timeout => (Grit::Git.git_timeout if timeout == true), :max => (Grit::Git.git_max_size if timeout == true) ) Grit.log(process.out) if Grit.debug Grit.log(process.err) if Grit.debug status = process.status if raise_errors && !status.success? raise CommandFailed.new(argv.join(' '), status.exitstatus, process.err) elsif process_info [status.exitstatus, process.out, process.err] else process.out end rescue Grit::Process::TimeoutExceeded, Grit::Process::MaximumOutputExceeded raise GitTimeout, argv.join(' ') end |
#object_exists?(object_id) ⇒ Boolean
52 53 54 |
# File 'lib/grit/git.rb', line 52 def object_exists?(object_id) ruby_git.object_exists?(object_id) end |
#options_to_argv(options) ⇒ Object
Transform a ruby-style options hash to command-line arguments sutiable for use with Kernel::exec. No shell escaping is performed.
Returns an Array of String option arguments.
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 |
# File 'lib/grit/git.rb', line 350 def () argv = [] .each do |key, val| if key.to_s.size == 1 if val == true argv << "-#{key}" elsif val == false # ignore else argv << "-#{key}" argv << val.to_s end else if val == true argv << "--#{key.to_s.tr('_', '-')}" elsif val == false # ignore else argv << "--#{key.to_s.tr('_', '-')}=#{val}" end end end argv end |
#put_raw_object(content, type) ⇒ Object
48 49 50 |
# File 'lib/grit/git.rb', line 48 def put_raw_object(content, type) ruby_git.put_raw_object(content, type) end |
#run(prefix, cmd, postfix, options, args, &block) ⇒ Object
DEPRECATED OPEN3-BASED COMMAND EXECUTION
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 |
# File 'lib/grit/git.rb', line 393 def run(prefix, cmd, postfix, , args, &block) timeout = .delete(:timeout) rescue nil timeout = true if timeout.nil? base = .delete(:base) rescue nil base = true if base.nil? if input = .delete(:input) block = lambda { |stdin| stdin.write(input) } end opt_args = () if RUBY_PLATFORM.downcase =~ /mswin(?!ce)|mingw|bccwin/ ext_args = args.reject { |a| a.empty? }.map { |a| (a == '--' || a[0].chr == '|' || Grit.no_quote) ? a : "\"#{e(a)}\"" } gitdir = base ? "--git-dir=\"#{self.git_dir}\"" : "" call = "#{prefix}#{Git.git_binary} #{gitdir} #{cmd.to_s.gsub(/_/, '-')} #{(opt_args + ext_args).join(' ')}#{e(postfix)}" else ext_args = args.reject { |a| a.empty? }.map { |a| (a == '--' || a[0].chr == '|' || Grit.no_quote) ? a : "'#{e(a)}'" } gitdir = base ? "--git-dir='#{self.git_dir}'" : "" call = "#{prefix}#{Git.git_binary} #{gitdir} #{cmd.to_s.gsub(/_/, '-')} #{(opt_args + ext_args).join(' ')}#{e(postfix)}" end Grit.log(call) if Grit.debug response, err = timeout ? sh(call, &block) : wild_sh(call, &block) Grit.log(response) if Grit.debug Grit.log(err) if Grit.debug response end |
#select_existing_objects(object_ids) ⇒ Object
56 57 58 59 60 |
# File 'lib/grit/git.rb', line 56 def select_existing_objects(object_ids) object_ids.select do |object_id| object_exists?(object_id) end end |
#sh(command, &block) ⇒ Object
423 424 425 426 427 428 429 430 431 432 433 |
# File 'lib/grit/git.rb', line 423 def sh(command, &block) process = Grit::Process.new( command, {}, :timeout => Git.git_timeout, :max => Git.git_max_size ) [process.out, process.err] rescue Grit::Process::TimeoutExceeded, Grit::Process::MaximumOutputExceeded raise GitTimeout, command end |
#shell_escape(str) ⇒ Object Also known as: e
91 92 93 |
# File 'lib/grit/git.rb', line 91 def shell_escape(str) str.to_s.gsub("'", "\\\\'").gsub(";", '\\;') end |
#timeout_after(seconds) ⇒ Object
Simple wrapper around Timeout::timeout.
seconds - Float number of seconds before a Timeout::Error is raised. When
true, the Grit::Git.git_timeout value is used. When the timeout is less
than or equal to 0, no timeout is established.
Raises Timeout::Error when the timeout has elapsed.
382 383 384 385 386 387 388 389 |
# File 'lib/grit/git.rb', line 382 def timeout_after(seconds) seconds = self.class.git_timeout if seconds == true if seconds && seconds > 0 Timeout.timeout(seconds) { yield } else yield end end |
#transform_options(options) ⇒ Object
Transform Ruby style options into git command line options
+options+ is a hash of Ruby style options
Returns String[]
e.g. ["--max-count=10", "--header"]
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 |
# File 'lib/grit/git.rb', line 445 def () args = [] .keys.each do |opt| if opt.to_s.size == 1 if [opt] == true args << "-#{opt}" elsif [opt] == false # ignore else val = .delete(opt) args << "-#{opt.to_s} '#{e(val)}'" end else if [opt] == true args << "--#{opt.to_s.gsub(/_/, '-')}" elsif [opt] == false # ignore else val = .delete(opt) args << "--#{opt.to_s.gsub(/_/, '-')}='#{e(val)}'" end end end args end |