module CMess::CLI

Constants

SPLIT_ARG_LIST_RE

How to split list of arguments.

Public Instance Methods

arg_list(arg) click to toggle source
# File lib/cmess/cli.rb, line 48
def arg_list(arg)
  arg.split(SPLIT_ARG_LIST_RE)
end
cli() { || ... } click to toggle source
# File lib/cmess/cli.rb, line 112
def cli
  yield
rescue => err
  if $VERBOSE
    backtrace = err.backtrace
    fromtrace = backtrace[1..-1].map { |i| "\n        from #{i}" }

    abort "#{backtrace.first} #{err} (#{err.class})#{fromtrace}"
  else
    abort "#{err.to_s.capitalize_first} [#{err.backtrace.first}]"
  end
end
determine_system_encoding() click to toggle source
# File lib/cmess/cli.rb, line 103
  def determine_system_encoding
    ENV.user_encoding || lambda {
      abort <<-EOT
Your system's encoding couldn't be determined automatically -- please specify
it explicitly via the ENCODING environment variable or via the '-t' option.
      EOT
    }.tap { |dummy| def dummy.to_s; 'NOT FOUND'; end }
  end
ensure_directory(dir) click to toggle source
# File lib/cmess/cli.rb, line 56
def ensure_directory(dir)
  abort "Directory not found: #{dir}" unless File.directory?(dir)
end
ensure_readable(file) click to toggle source
# File lib/cmess/cli.rb, line 52
def ensure_readable(file)
  abort "Can't find input file: #{file}" unless File.readable?(file)
end
open_file_in_place(file) click to toggle source
# File lib/cmess/cli.rb, line 60
def open_file_in_place(file)
  [open_temporary_input(file), File.open(file, 'w')]
end
open_file_or_std(file, mode = 'r') click to toggle source
# File lib/cmess/cli.rb, line 64
def open_file_or_std(file, mode = 'r')
  if file == '-'
    case mode
      when 'r' then STDIN
      when 'w' then STDOUT
      when 'a' then STDERR
      else raise ArgumentError, "don't know how to handle mode `#{mode}'"
    end
  else
    ensure_readable(file) unless mode == 'w'
    File.open(file, mode)
  end
end
open_temporary_input(*files) click to toggle source
# File lib/cmess/cli.rb, line 78
def open_temporary_input(*files)
  temp = Tempfile.new('cmess_cli')

  files.each { |file|
    if file == '-'
      STDIN.each { |line| temp << line }
    else
      ensure_readable(file)
      File.foreach(file) { |line| temp << line }
    end
  }

  # return File, instead of Tempfile
  temp.close
  temp.open
end
parse_options(&block) click to toggle source
# File lib/cmess/cli.rb, line 44
def parse_options(&block)
  OptionParser.new(nil, 40, &block).parse!
end
trailing_args_as_input(options) click to toggle source
# File lib/cmess/cli.rb, line 95
def trailing_args_as_input(options)
  unless ARGV.empty? || options[:input_set]
    options[:input] = ARGV.size == 1 ?
      open_file_or_std(ARGV.first) :
      open_temporary_input(*ARGV)
  end
end