Class: Toys::Cli

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

Constant Summary collapse

BUILTINS_PATH =
File.join(__dir__, "builtins")
DEFAULT_DIR_NAME =
".toys"
DEFAULT_FILE_NAME =
".toys.rb"
DEFAULT_BINARY_NAME =
"toys"
ETC_PATH =
"/etc"

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(binary_name: nil, logger: nil, config_dir_name: nil, config_file_name: nil, index_file_name: nil) ⇒ Cli

Returns a new instance of Cli.



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/toys/cli.rb', line 9

def initialize(
  binary_name: nil,
  logger: nil,
  config_dir_name: nil,
  config_file_name: nil,
  index_file_name: nil
)
  @lookup = Toys::Lookup.new(
    config_dir_name: config_dir_name,
    config_file_name: config_file_name,
    index_file_name: index_file_name)
  @context = Context.new(
    @lookup,
    logger: logger || self.class.default_logger,
    binary_name: binary_name)
end

Class Method Details

.create_standardObject



55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/toys/cli.rb', line 55

def create_standard
  cli = new(
    binary_name: DEFAULT_BINARY_NAME,
    config_dir_name: DEFAULT_DIR_NAME,
    config_file_name: DEFAULT_FILE_NAME,
    index_file_name: DEFAULT_FILE_NAME
  )
  cli.add_config_path_hierarchy
  if !File.directory?(ETC_PATH) || !File.readable?(ETC_PATH)
    cli.add_config_paths(ETC_PATH)
  end
  cli.add_paths(BUILTINS_PATH)
  cli
end

.default_loggerObject



70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/toys/cli.rb', line 70

def default_logger
  logger = Logger.new(STDERR)
  logger.formatter = ->(severity, time, progname, msg) {
    msg_str =
      case msg
      when String
        msg
      when Exception
        "#{msg.message} (#{msg.class})\n" << (msg.backtrace || []).join("\n")
      else
        msg.inspect
      end
    timestr = time.strftime("%Y-%m-%d %H:%M:%S")
    "[%s %5s]  %s\n" % [timestr, severity, msg_str]
  }
  logger.level = Logger::WARN
  logger
end

Instance Method Details

#add_config_path_hierarchy(path = nil, base = "/") ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/toys/cli.rb', line 36

def add_config_path_hierarchy(path=nil, base="/")
  path ||= Dir.pwd
  paths = []
  loop do
    paths << path
    break if !base || path == base
    next_path = File.dirname(path)
    break if next_path == path
    path = next_path
  end
  @lookup.add_config_paths(paths)
  self
end

#add_config_paths(paths) ⇒ Object



31
32
33
34
# File 'lib/toys/cli.rb', line 31

def add_config_paths(paths)
  @lookup.add_config_paths(paths)
  self
end

#add_paths(paths) ⇒ Object



26
27
28
29
# File 'lib/toys/cli.rb', line 26

def add_paths(paths)
  @lookup.add_paths(paths)
  self
end

#run(*args) ⇒ Object



50
51
52
# File 'lib/toys/cli.rb', line 50

def run(*args)
  @context.run(*args)
end