Sha256: 08508b74ee51458cdf500c26b5a0e213e63b236eda7007245c19cd197c34db03

Contents?: true

Size: 1.68 KB

Versions: 1

Compression:

Stored size: 1.68 KB

Contents

#!/usr/bin/env ruby

require 'tempfile'
require 'optparse'

iprefix = ''
oprefix = '# => '

parser = OptionParser.new(nil, 20) do |o|
  o.banner = 'Usage: rubyx [options] <file> -- [arguments]'

  o.separator ''
  o.separator 'Options:'

  o.on('-i PREFIX', %{Set prefix for source code (default: "#{iprefix}")}) do |value|
    iprefix = value
  end

  o.on('-o PREFIX', %{Set prefix for standard output (default: "#{oprefix}")}) do |value|
    oprefix = value
  end

  o.on_tail('-h', 'Show this message') do
    puts o
    exit
  end
end

begin
  parser.parse!
rescue OptionParser::InvalidOption
  puts parser
  exit 1
end

def abort(message)
  puts message
  exit 1
end

def capture(stream)
  original = stream.dup
  surrogate = Tempfile.new('rubyx')
  stream.reopen(surrogate)

  yield

  stream.rewind
  surrogate.readlines
ensure
  surrogate.close
  surrogate.unlink
  stream.reopen(original)
end

def trace(handler)
  set_trace_func(handler)
  yield
ensure
  set_trace_func(nil)
end

filename = ARGV.shift || ''
abort(parser) if filename.empty?

filename = File.absolute_path(filename)
abort('The file does not exist.') unless File.exist?(filename)

tag = Random.new_seed
last_position = 0

handler = Proc.new do |event, source, position|
  if event == 'line' && source == filename && position > last_position
    (last_position..(position - 1)).each { |i| puts "#{tag}#{i}" }
    last_position = position
  end
end

source = File.readlines(filename)
output = capture($stdout) { trace(handler) { load(filename) } }

output.map! do |line|
  if line =~ /^#{tag}(?<position>\d+)$/
    line = source[Regexp.last_match(:position).to_i]
    "#{iprefix}#{line}"
  else
    "#{oprefix}#{line}"
  end
end

puts output.join

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
rubyx-0.0.2 bin/rubyx