Is it possible to call Git or other command line tools from inside a Thor script?
Asked Answered
F

2

5

I find that I'm often running a sequence of routine 'cleanup' tasks before and after I make a git commit for my Rails 3 app.

I was thinking about putting these things into a Thor script, but one thing I haven't been able to figure out is how to use Thor (or Rake) to call other tools on the system.

Is it possible to call a command like git log from a Thor or Rake script, and if so what does that look like?

Thanks!

Feme answered 26/1, 2011 at 6:33 Comment(0)
P
12

Just shell out:

result = %x(git log)
puts result

or

system('git log')

if you just want to pass the output to the terminal.

There is also the grit gem that abstracts the Git tools into a Ruby library:

require 'grit'
repo = Grit::Repo.new("/path/to/repo")
repo.commits.each do |commit|
  puts "#{commit.id}: #{commit.message}"
end
Pfeiffer answered 26/1, 2011 at 7:47 Comment(4)
Aha! Thanks. "shell out" is probably the keyword I was lacking in my google quest :)Feme
Hmm, I get nil returned using %x, system and back-ticks. Is there anything that I am missing? Do I need to cd into the proper directory?Catabolite
@Catabolite you need to be in or below the project directory (the one with the .git directory) and the git command must be in the path (i.e. you must make sure your script can actually find git).Pfeiffer
It should be noted that Grit doesn't currently work on Windows because of a problem with one of it's dependencies not being supported on the platform. github.com/rtomayko/posix-spawn/issues/9Angie
N
4

Don't forget that those are just Ruby files, so you can use everything in the Ruby arsenal there as well, so things like %x[rm -rf /], system("rm -rf /") and `rm -rf /` are accessible in those scripts too.

Nosography answered 26/1, 2011 at 6:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.