Class: Phaad::CLI

Inherits:
Object
  • Object
show all
Defined in:
lib/phaad/cli.rb

Instance Method Summary collapse

Constructor Details

#initialize(argv) ⇒ CLI

Returns a new instance of CLI.



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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
# File 'lib/phaad/cli.rb', line 3

def initialize(argv)
  @options = Slop.parse! argv, :help => true  do
    banner "Usage: phaad [options] [file]"
    on :c, :compile,      "Compile to PHP, and save as .php files"
    on :i, :interactive,  "Run an interactive Phaad REPL"
    on :s, :stdio,        "Fetch, compile, and print a Phaad script over stdio"
    on :e, :eval,         "Compile a string from command line", true
    on :w, :watch,        "Watch a Phaad file for changes, and autocompile"
    on :v, :version,      "Print Phaad version" do
      puts Phaad::VERSION
      exit
    end
  end

  if @options.interactive?
    repl
  elsif @options.eval?
    puts compile(@options[:eval])
  elsif @options.stdio?
    puts "<?php\n"
    puts compile(STDIN.readlines.join("\n"))
  elsif @options.compile?
    input_file = argv.shift
    output_file = input_file.sub(/\..*?$/, '.php')
    File.open(output_file, 'w') do |f|
      f << "<?php\n"
      f << compile(File.read(input_file))
    end
  elsif @options.watch?
    require 'fssm'

    input_file = argv.shift
    output_file = input_file.sub(/\..*?$/, '.php')
    FSSM.monitor(File.dirname(input_file), File.basename(input_file)) do
      update do
        puts ">>> Detected changes in #{input_file}"
        File.open(output_file, 'w') do |f|
          f << "<?php\n"
          f << Phaad::Generator.new(File.read(input_file)).emitted
        end
        puts ">>> Compiled!"
      end
    end
  else
    repl
  end
end

Instance Method Details

#compile(input) ⇒ Object



51
52
53
# File 'lib/phaad/cli.rb', line 51

def compile(input)
  Phaad::Generator.new(input).emitted
end

#replObject



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/phaad/cli.rb', line 55

def repl
  require 'readline'

  puts "Type exit or press Ctrl-D to exit."
  lines = ""
  loop do
    prompt = lines.size == 0 ? '> ' : '>> '
    line = Readline::readline(prompt)

    exit if line.nil? || line == "exit" && lines.size == 0

    lines << line + "\n"
    Readline::HISTORY.push line

    if valid_expression?(lines)
      begin
        puts Phaad::Generator.new(lines).emitted
      rescue Exception => e
        puts e
        p e.message
        puts e.backtrace
      ensure
        lines = ""
      end
    end
  end
end

#valid_expression?(lines) ⇒ Boolean

Returns:

  • (Boolean)


83
84
85
# File 'lib/phaad/cli.rb', line 83

def valid_expression?(lines)
  !!Ripper.sexp(lines)
end