Class: H8::Command

Inherits:
Object show all
Defined in:
lib/h8/command.rb

Defined Under Namespace

Classes: Console, FileProxy, Stream

Instance Method Summary collapse

Constructor Details

#initialize(*args, out: STDOUT, err: STDERR, dont_run: false) ⇒ Command

Returns a new instance of Command.



10
11
12
13
14
15
# File 'lib/h8/command.rb', line 10

def initialize *args, out: STDOUT, err: STDERR, dont_run: false
  @out = out
  @err = err

  run *args unless dont_run
end

Instance Method Details

#contextObject



63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/h8/command.rb', line 63

def context
  @context ||= begin
    cxt             = H8::Context.new
    console         = Console.new out: @out, err: @err
    cxt[:console]   = console
    print           = -> (*args) { console.debug *args }
    cxt[:print]     = print
    cxt[:puts]      = print
    cxt[:open]      = -> (name, mode='r', block=nil) { Stream.new(name, mode, block) }
    cxt['__FILE__'] = @file ? @file.to_s : '<inline>'
    cxt[:File]      = FileProxy.new
    cxt
  end
end

#run(*args) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/h8/command.rb', line 25

def run *args
  count = 0

  @parser = Pargser.new(args)

  @parser.key('-e', default: false, doc: 'inline coffee code to execute') { |script|
    if script
      @file = '-e'
      context.coffee (@script=script)
      count += 1
    end
  }
      .key('-x', default: nil, doc: 'inline js code to execute') { |script|
    if script
      @file = '-e'
      context.eval (@script=script)
      count += 1
    end
  }
      .key('-h', '--h') {
    usage
    count = -100000000
  }

  rest = @parser.parse { |file|
    count   += 1
    @script = open(file, 'r').read
    file.downcase.end_with?('.coffee') and @script = H8::Coffee.compile(@script)
    @file = file
    context.eval @script
  }

  unless count != 0
    STDERR.puts 'H8: error: provide at least one file (use -h for help)'
    exit 300
  end
end

#usageObject



17
18
19
20
21
22
23
# File 'lib/h8/command.rb', line 17

def usage
  puts "h8 #{H8::VERSION} CLI runner\n"
  puts "Usage:\n h8 [keys] file1..."
  puts
  puts "executes 1 or more javascript/coffeescript files connected with Ruby environment"
  puts @parser.keys_doc
end