class Rexe::CommandLineParser
Attributes
lookups[R]
options[R]
Public Class Methods
new()
click to toggle source
# File exe/rexe, line 159 def initialize @lookups = Lookups.new @options = Options.new end
Public Instance Methods
parse()
click to toggle source
Using 'optparse', parses the command line. Settings go into this instance's properties (see Struct declaration).
# File exe/rexe, line 288 def parse prepend_environment_options OptionParser.new do |parser| parser.on('-c', '--clear_options', "Clear all previous command line options") do |v| options.clear end parser.on('-f', '--input_file FILESPEC', 'Use this file instead of stdin; autodetects YAML and JSON file extensions') do |v| unless File.exist?(v) raise "File #{v} does not exist." end options.input_filespec = v options.input_format = autodetect_file_format(v) if [:json, :yaml].include?(options.input_format) options.input_mode = :one_big_string end end parser.on('-g', '--log_format FORMAT', 'Log format, logs to stderr, defaults to none (see -o for format options)') do |v| options.log_format = lookups.output_formats[v] if options.log_format.nil? raise("Output mode was '#{v}' but must be one of #{lookups.output_formats.keys}.") end end parser.on("-h", "--help", "Show help") do |_help_requested| puts help_text exit end parser.on('-i', '--input_format FORMAT', 'Mode with which to parse input values (n = none (default), j = JSON, m = Marshal, y = YAML') do |v| options.input_format = lookups.input_formats[v] if options.input_format.nil? raise("Input mode was '#{v}' but must be one of #{lookups.input_formats.keys}.") end end parser.on('-l', '--load RUBY_FILE(S)', 'Ruby file(s) to load, comma separated, or ! to clear') do |v| if v == '!' options.loads.clear else loadfiles = v.split(',').map(&:strip).map { |s| File.expand_path(s) } removes, adds = loadfiles.partition { |filespec| filespec[0] == '-' } existent, nonexistent = adds.partition { |filespec| File.exists?(filespec) } if nonexistent.any? raise("\nDid not find the following files to load: #{nonexistent}\n\n") else existent.each { |filespec| options.loads << filespec } end removes.each { |filespec| options.loads -= [filespec[1..-1]] } end end parser.on('-m', '--input_mode MODE', 'Mode with which to handle input (-ml, -me, -mb, -mn (default)') do |v| options.input_mode = lookups.input_modes[v] if options.input_mode.nil? raise("Input mode was '#{v}' but must be one of #{lookups.input_modes.keys}.") end end # See https://stackoverflow.com/questions/54576873/ruby-optionparser-short-code-for-boolean-option # for an excellent explanation of this optparse incantation. # According to the answer, valid options are: # -n no, -n yes, -n false, -n true, -n n, -n y, -n +, but not -n -. parser.on('-n', '--[no-]noop [FLAG]', TrueClass, "Do not execute the code (useful with -g)") do |v| options.noop = (v.nil? ? true : v) end parser.on('-o', '--output_format FORMAT', 'Mode with which to format values for output (`-o` + [aijJmnpsy])') do |v| options.output_format_tty = lookups.output_formats[v[0]] options.output_format_block = lookups.output_formats[v[-1]] options.output_format = ($stdout.tty? ? options.output_format_tty : options.output_format_block) if [options.output_format_tty, options.output_format_block].include?(nil) raise("Bad output mode '#{v}'; each must be one of #{lookups.output_formats.keys}.") end end parser.on('-r', '--require REQUIRE(S)', 'Gems and built-in libraries (e.g. shellwords, yaml) to require, comma separated, or ! to clear') do |v| if v == '!' options.requires.clear else v.split(',').map(&:strip).each do |r| if r[0] == '-' options.requires -= [r[1..-1]] else options.requires << r end end end end parser.on('-v', '--version', 'Print version') do puts VERSION exit(0) end # Undocumented feature: open Github project with default web browser on a Mac parser.on('', '--open-project') do open_resource(PROJECT_URL) exit(0) end parser.on('', '--project-url') do puts PROJECT_URL exit(0) end end.parse! # We want to do this after all options have been processed because we don't want any clearing of the # options (by '-c', etc.) to result in exclusion of these needed requires. add_format_requires_to_requires_list options.requires = options.requires.sort.uniq options.loads.uniq! options end
Private Instance Methods
add_format_requires_to_requires_list()
click to toggle source
# File exe/rexe, line 175 def add_format_requires_to_requires_list formats = [options.input_format, options.output_format, options.log_format] requires = formats.map { |format| lookups.format_requires[format] }.uniq.compact requires.each { |r| options.requires << r } end
autodetect_file_format(filespec)
click to toggle source
File file input mode; detects the input mode (JSON, YAML, or None) from the extension.
# File exe/rexe, line 260 def autodetect_file_format(filespec) extension = File.extname(filespec).downcase if extension == '.json' :json elsif extension == '.yml' || extension == '.yaml' :yaml else :none end end
help_text()
click to toggle source
# File exe/rexe, line 182 def help_text unless @help_text @help_text ||= <<~HEREDOC rexe -- Ruby Command Line Executor/Filter -- v#{VERSION} -- #{PROJECT_URL} Executes Ruby code on the command line, optionally automating management of standard input and standard output, and optionally parsing input and formatting output with YAML, JSON, etc. rexe [options] [Ruby source code] Options: -c --clear_options Clear all previous command line options specified up to now -f --input_file Use this file instead of stdin for preprocessed input; if filespec has a YAML and JSON file extension, sets input format accordingly and sets input mode to -mb -g --log_format FORMAT Log format, logs to stderr, defaults to -gn (none) (see -o for format options) -h, --help Print help and exit -i, --input_format FORMAT Input format, defaults to -in (None) -ij JSON -im Marshal -in None (default) -iy YAML -l, --load RUBY_FILE(S) Ruby file(s) to load, comma separated; ! to clear all, or precede a name with '-' to remove -m, --input_mode MODE Input preprocessing mode (determines what `self` will be) defaults to -mn (none) -ml line; each line is ingested as a separate string -me enumerator (each_line on STDIN or File) -mb big string; all lines combined into one string -mn none (default); no input preprocessing; self is an Object.new -n, --[no-]noop Do not execute the code (useful with -g); For true: yes, true, y, +; for false: no, false, n -o, --output_format FORMAT Output format, defaults to -on (no output): -oa Amazing Print -oi Inspect -oj JSON -oJ Pretty JSON -om Marshal -on No Output (default) -op Puts -oP Pretty Print -os to_s -oy YAML If 2 letters are provided, 1st is for tty devices, 2nd for block --project-url Outputs project URL on Github, then exits -r, --require REQUIRE(S) Gems and built-in libraries to require, comma separated; ! to clear all, or precede a name with '-' to remove -v, --version Prints version and exits --------------------------------------------------------------------------------------- In many cases you will need to enclose your source code in single or double quotes. If source code is not specified, it will default to 'self', which is most likely useful only in a filter mode (-ml, -me, -mb). If there is a .rexerc file in your home directory, it will be run as Ruby code before processing the input. If there is a REXE_OPTIONS environment variable, its content will be prepended to the command line so that you can specify options implicitly (e.g. `export REXE_OPTIONS="-r amazing_print,yaml"`) HEREDOC @help_text.freeze end @help_text end
open_resource(resource_identifier)
click to toggle source
# File exe/rexe, line 272 def open_resource(resource_identifier) command = case (`uname`.chomp) when 'Darwin' 'open' when 'Linux' 'xdg-open' else 'start' end `#{command} #{resource_identifier}` end
prepend_environment_options()
click to toggle source
Inserts contents of REXE_OPTIONS environment variable at the beginning of ARGV.
# File exe/rexe, line 166 def prepend_environment_options env_opt_string = ENV['REXE_OPTIONS'] if env_opt_string args_to_prepend = Shellwords.shellsplit(env_opt_string) ARGV.unshift(args_to_prepend).flatten! end end