From 943ec28fed6965573fb81518eea39b29355d3ac9 Mon Sep 17 00:00:00 2001 From: John Mair Date: Sun, 22 Jan 2012 02:59:42 +1300 Subject: [PATCH] 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) --- lib/pry/default_commands/shell.rb | 67 +++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) diff --git a/lib/pry/default_commands/shell.rb b/lib/pry/default_commands/shell.rb index 48c95cee..d42cf8d7 100644 --- a/lib/pry/default_commands/shell.rb +++ b/lib/pry/default_commands/shell.rb @@ -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