first stab at save-file command

currently supports:
* -i, -m, -c, -f, -l (specify lines to restrict to)

TODO:
* -a (append to file flag)
* --insert (insert at a certain point in a file)
* --indent (ensure inserted code is indented properly, using pry's indent mechanism)
This commit is contained in:
John Mair 2012-01-22 02:59:42 +13:00
parent 239c0fa14a
commit 943ec28fed
1 changed files with 67 additions and 0 deletions

View File

@ -30,6 +30,73 @@ class Pry
end
alias_command "file-mode", "shell-mode"
command_class "save-file", "Export to a file using content from the REPL." do
attr_accessor :content
attr_accessor :file_name
def setup
self.content = ""
end
def options(opt)
opt.banner unindent <<-USAGE
Usage: save-file [OPTIONS] [METH]
Save REPL content to a file.
e.g: save-file -m my_method -m my_method2 ./hello.rb
e.g: save-file -i 1..10 ./hello.rb
e.g: save-file -c show-method ./my_command.rb
e.g: save-file -f sample_file --lines 2..10 ./output_file.rb
USAGE
opt.on :m, :method, "Save a method's source.", true do |meth_name|
meth = get_method_or_raise(meth_name, target, {})
self.content << meth.source
end
opt.on :c, :command, "Save a command's source.", true do |command_name|
command = find_command(command_name)
self.content << command.block.source
end
opt.on :f, :file, "Save a file.", true do |file|
self.content << File.read(File.expand_path(file))
end
opt.on :l, :lines, "Only gist a subset of lines (only works with -m and -f)", :optional => true, :as => Range, :default => 1..-1
opt.on :i, :in, "Gist entries from Pry's input expression history. Takes an index or range.", :optional => true,
:as => Range, :default => -5..-1 do |range|
input_expressions = _pry_.input_array[range] || []
Array(input_expressions).each { |v| self.content << v }
end
end
def process
if args.empty?
raise CommandError, "Must specify a file name."
end
self.file_name = File.expand_path(args.first)
save_file
end
def save_file
if self.content.empty?
raise CommandError, "Found no code to save."
end
File.open(file_name, "w") do |f|
if opts.present?(:lines)
f.puts restrict_to_lines(content, opts[:l])
else
f.puts content
end
end
end
def restrict_to_lines(content, lines)
line_range = one_index_range(lines)
content.lines.to_a[line_range].join
end
end
create_command "cat", "Show code from a file, Pry's input buffer, or the last exception." do
banner <<-USAGE
Usage: cat FILE