Class: Wsv::CLI

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

Constant Summary collapse

DEFAULT_HOST =
"127.0.0.1"
DEFAULT_PORT =
8000

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(argv, out: $stdout, err: $stderr) ⇒ CLI

Returns a new instance of CLI.



13
14
15
16
17
# File 'lib/wsv/cli.rb', line 13

def initialize(argv, out: $stdout, err: $stderr)
  @argv = argv.dup
  @out = out
  @err = err
end

Instance Attribute Details

#argvObject (readonly)

Returns the value of attribute argv.



11
12
13
# File 'lib/wsv/cli.rb', line 11

def argv
  @argv
end

Instance Method Details

#parse_options(args) ⇒ Object

Raises:

  • (ArgumentError)


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
62
63
64
65
66
67
68
69
70
# File 'lib/wsv/cli.rb', line 36

def parse_options(args)
  options = {
    host: DEFAULT_HOST,
    port: DEFAULT_PORT,
    directory: Dir.pwd
  }

  parser = OptionParser.new do |opts|
    opts.banner = "Usage: wsv [options] [directory]"

    opts.on("-h", "--host HOST", "Bind host (default: #{DEFAULT_HOST})") do |host|
      options[:host] = host
    end

    opts.on("-p", "--port PORT", Integer, "Bind port (default: #{DEFAULT_PORT})") do |port|
      options[:port] = validate_port(port)
    end

    opts.on("--help", "Show help") do
      @out.puts opts
      options[:handled] = true
    end

    opts.on("--version", "Show version") do
      @out.puts Wsv::VERSION
      options[:handled] = true
    end
  end

  parser.parse!(args)
  raise ArgumentError, "too many directories" if args.length > 1

  options[:directory] = args.first if args.first
  options
end

#runObject



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/wsv/cli.rb', line 19

def run
  options = parse_options(argv)
  return 0 if options[:handled]

  root = resolve_root(options[:directory])
  server = Server.new(host: options[:host], port: options[:port], root: root, out: @out, err: @err)
  server.start
  0
rescue OptionParser::ParseError, ArgumentError => e
  @err.puts "wsv: #{e.message}"
  @err.puts "Try `wsv --help` for usage."
  1
rescue SystemCallError => e
  @err.puts "wsv: #{e.message}"
  1
end