aboutsummaryrefslogtreecommitdiffstats
path: root/lib/cmdline.rb
blob: 9bbb0471d03504cc3827afd83d65d7bc2d6b02b4 (plain)
1
2
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
50
51
52
53
54
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
# Copyright (c) 2020 Bryan Frimin <bryan@frimin.fr>.
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
# REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
# AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
# LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
# OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
# PERFORMANCE OF THIS SOFTWARE.

module Cmdline
  Option = Struct.new(
    :short_name,
    :long_name,
    :value_string,
    :description,
    :default,
    :set,
    :value,
    keyword_init: true
  )

  class Option
    def initialize(*)
      super
      self.short_name ||= ""
      self.long_name ||= ""
      self.value_string ||= ""
      self.description ||= ""
      self.default ||= ""
      self.set ||= false
      self.value ||= ""
    end

    def sort_key
      return short_name unless short_name.empty?
      return long_name unless long_name.empty?
      ""
    end
  end

  Argument = Struct.new(
    :name,
    :description,
    :trailing,
    :value,
    :trailing_values,
    keyword_init: true
  )

  class Argument
    def initialize(*)
      super
      self.name ||= ""
      self.description ||= ""
      self.trailing ||= false
      self.value ||= ""
      self.trailing_values ||= []
    end
  end

  Command = Struct.new(
    :name,
    :description,
    keyword_init: true
  )

  class Command
    def initialize(*)
      super
      self.name ||= ""
      self.description ||= ""
    end
  end

  CmdLine = Struct.new(
    :options,
    :arguments,
    :commands,
    :command,
    :command_arguments,
    :program_name,
    keyword_init: true
  )

  class CmdLine
    def initialize(*)
      super
      self.options ||= {}
      self.commands ||= {}
      self.command ||= ""
      self.arguments ||= []
      self.command_arguments ||= []
      self.program_name ||= ""
    end

    # Add flag to the command line interface.
    #
    # @author Gearnode <bryan@frimin.fr>
    # @since 1.0.0
    #
    # @param [String] short the short name of the flag
    # @param [String] long the long name of the flag
    # @param [String] description the description of the flag
    #
    # @return [void]
    def add_flag(short, long, description)
      option = Option.new(
        short_name: short.to_s,
        long_name: long.to_s,
        value_string: "",
        description: description.to_s
      )

      addopt(option)
    end

    # Add option to the command line interface.
    #
    # @author Gearnode <bryan@frimin.fr>
    # @since 1.0.0
    #
    # @param [String] short the short name of the option
    # @param [String] long the long name of the option
    # @param [String] value the demo value of the option
    # @param [String] description the description of the option
    #
    # @return [void]
    def add_option(short, long, value, description)
      option = Option.new(
        short_name: short.to_s,
        long_name: long.to_s,
        value_string: value.to_s,
        description: description.to_s
      )

      addopt(option)
    end

    # A default value to an option.
    #
    # @author Gearnode <bryan@frimin.fr>
    # @since 1.0.0
    #
    # @param [String] name the name of the option
    # @param [Object] value the default value of the option
    #
    # @return [void]
    def set_option_default(name, value)
      option = self.options[name]
      raise(ArgumentError, "unknown option") if option.nil?
      raise(ArgumentError, "flags cannot have a default value") if option.value_string.empty?

      option.default = value
    end

    # Add argument to the command line interface.
    #
    # @author Gearnode <bryan@frimin.fr>
    # @since 1.0.0
    #
    # @param [String] name the argument name
    # @param [String] description the description of the argument
    #
    # @return [void]
    def add_argument(name, description)
      argument = Argument.new(
        name: name.to_s,
        description: description.to_s
      )

      addarg(argument)
    end

    # Add trailing argument to the command line interface.
    #
    # @author Gearnode <bryan@frimin.fr>
    # @since 1.0.0
    #
    # @param [String] name the name of the trailing arguments
    # @param [String] description the description of the trailing arguments
    #
    # @return [void]
    def add_trailing_arguments(name, description)
      argument = Argument.new(
        name: name.to_s,
        description: description.to_s,
        trailing: true
      )

      addarg(argument)
    end

    # Add command to the command line interface.
    #
    # @author Gearnode <bryan@frimin.fr>
    # @since 1.0.0
    #
    # @param [String] name the name of the command
    # @param [String] description the description of the command
    #
    # @raise [ArgumentError] when the command line has already argument
    #
    # @return [void]
    def add_command(name, description)
      if self.arguments.size.zero?
        add_argument("command", "the command to execute")
      elsif self.arguments.first.name != "command"
        raise(ArgumentError, "cannot have both arguments and commands")
      end

      cmd = Command.new(
        name: name.to_s,
        description: description.to_s
      )

      self.commands[cmd.name] = cmd
    end

    # Exit with error.
    #
    # @author Gearnode <bryan@frimin.fr>
    # @since 1.0.0
    #
    # @param (see Kernel#sprintf)
    #
    # @return [nil]
    def die(format, *args)
      msg = sprintf(format, *args)
      STDERR.puts("error: #{msg}")
      exit(1)
    end

    # Parse the argument values.
    #
    # @author Gearnode <bryan@frimin.fr>
    # @since 1.0.0
    #
    # @param [Array<String>] args
    #
    # @return [void]
    def parse(args)
      die("empty argument array") if args.size == 0

      self.program_name = args.shift

      while args.size > 0
        arg = args.first

        if arg == "--"
          args.shift
          break
        end

        is_short = arg.size == 2 && arg[0] == "-" && arg[1] != "-"
        is_long = arg.size > 2 && arg[0,2] == "--"

        if is_short || is_long
          key = if is_short
                  arg[1,2]
                else
                  arg[2..]
                end

          opt = self.options[key]
          die("unknown option \"%s\"", key) if opt.nil?

          opt.set = true

          if opt.value_string.empty?
            args = args[1..]
          else
            die("missing value for option \"%s\"", key) if args.size < 2
            opt.value = args[1]
            args = args[2..]
          end
        else
          break
        end
      end

      if self.arguments.size > 0 && !is_option_set("help")
        last = self.arguments.last

        min = self.arguments.size
        min -= 1 if last.trailing

        die("missing argument(s)") if args.size < min

        min.times do |i|
          self.arguments[i].value = args[i]
        end
        args = args[min..]

        if last.trailing
          last.trailing_values = args
          args = args[args.size..]
        end
      end

      if self.commands.size > 0
        self.command = self.arguments.first.value
        self.command_arguments = args
      end

      if !is_option_set("help")
        if self.commands.size > 0
          cmd = self.commands[self.command]
          if cmd.nil?
            die("unknown command \"%s\"", self.command)
          end
        elsif args.size > 0
          die("invalid extra argument(s)")
        end
      end

      if is_option_set("help")
        print_usage
        exit(0)
      end
    end

    # Print the usage of the command line interface.
    #
    # @author Gearnode <bryan@frimin.fr>
    # @since 1.0.0
    #
    # @return [void]
    def print_usage
      usage = sprintf("Usage: %s OPTIONS", self.program_name)
      if self.arguments.size > 0
        self.arguments.each do |arg|
          if arg.trailing
            usage << sprintf(" [<%s> ...]", arg.name)
          else
            usage << sprintf(" <%s>", arg.name)
          end
        end
      end

      usage << "\n\n"

      opt_strs = {}
      max_width = 0

      self.options.each do |_, opt|
        next if opt_strs[opt]

        buf = ""

        if opt.short_name != ""
          buf << sprintf("-%s", opt.short_name)
        end

        if opt.long_name != ""
          if opt.short_name != ""
            buf << ", "
          end

          buf << sprintf("--%s", opt.long_name)
        end

        if opt.value_string != ""
          buf << sprintf(" <%s>", opt.value_string)
        end

        opt_strs[opt] = buf

        if buf.size > max_width
          max_width = buf.size
        end
      end

      if self.commands.size > 0
        self.commands.each do |name, _|
          max_width = name.size if name.size > max_width
        end
      elsif self.arguments.size > 0
        self.arguments.each do |arg|
          max_width = arg.name.size if arg.name.size > max_width
        end
      end

      # Print options
      usage << "OPTIONS\n\n"

      opts = []
      opt_strs.each do |opt, _|
        opts << opt
      end

      # TODO: sort options

      opts.each do |opt|
        usage << sprintf("%-*s  %s", max_width, opt_strs[opt], opt.description)
        usage << sprintf(" (default: %s)", opt.default) unless opt.default.empty?
        usage << "\n"
      end

      if self.commands.size > 0
        usage << "\nCOMMANDS\n\n"
        names = []
        self.commands.each do |name, _|
          names << name
        end
        names.sort!

        names.each do |name|
          cmd = self.commands[name]
          usage << sprintf("%-*s  %s\n", max_width, cmd.name, cmd.description)
        end
      elsif self.arguments.size > 0
        usage << "\nARGUMENTS\n\n"

        self.arguments.each do |arg|
          usage << sprintf("%-*s  %s\n", max_width, arg.name, arg.description)
        end
      end

      printf(usage)
    end

    # Check if an option is set.
    #
    # @author Gearnode <bryan@frimin.fr>
    # @since 1.0.0
    #
    # @param [String] name the name of the option
    #
    # @raise [ArgumentError] when the option does not exist
    #
    # @return [Boolean]
    def is_option_set(name)
      opt = self.options[name]
      raise(ArgumentError, "unknown option") if opt.nil?
      opt.set
    end

    # Get the value of an option.
    #
    # @author Gearnode <bryan@frimin.fr>
    # @since 1.0.0
    #
    # @param [String] name the name of the option
    #
    # @raise [ArgumentError] when the option does not exist
    #
    # @return [String]
    def option_value(name)
      opt = self.options[name]
      raise(ArgumentError, "unknown option") if opt.nil?

      return opt.value if opt.set
      opt.default
    end

    # Get the value of an argument.
    #
    # @author Gearnode <bryan@frimin.fr>
    # @since 1.0.0
    #
    # @param [String] name the name of the argument
    #
    # @raise [ArgumentError] when the argument does not exist.
    #
    # @return [String]
    def argument_value(name)
      self.arguments.each do |arg|
        if arg.name == name
          return arg.value
        end
      end
      raise(ArgumentError, "unknown argument")
    end

    # Get the values of the trailing arguments.
    #
    # @author Gearnode <bryan@frimin.fr>
    # @since 1.0.0
    #
    # @param [String] name the name of the trailing arguments.
    #
    # @raise [ArgumentError] when the trailing arguments are empty.
    #
    # @return [Array<String>]
    def trailing_arguments_values(name)
      raise(ArgumentError, "empty argument array") if self.arguments.empty?
      last = self.arguments.last
      raise(ArgumentError, "no trailing arguments") unless last.trailing
      last.trailing_values
    end

    # Get the name of command to execute.
    #
    # @author Gearnode <bryan@frimin.fr>
    # @since 1.0.0
    #
    # @return [String]
    def command_name
      raise(RuntimeError, "no command defined") if self.commands.empty?
      self.command
    end

    # Get command arguments.
    #
    # @author Gearnode <bryan@frimin.fr>
    # @since 1.0.0
    #
    # @return [Array<String>]
    def command_arguments_values
      raise(RuntimeError, "no command defined") if self.commands.empty?
      self.command_arguments
    end

    # Get the command name and their arguments.
    #
    # @author Gearnode <bryan@frimin.fr>
    # @since 1.0.0
    #
    # @return [Array<String>]
    def command_name_and_arguments
      raise(RuntimeError, "no command defined") if self.commands.empty?
      [self.command, *self.command_arguments]
    end

    private

    def addopt(opt)
      if !opt.short_name.empty?
        if opt.short_name.size != 1
          raise(ArgumentError, "option short names must be one character long")
        end

        self.options[opt.short_name] = opt
      end

      if !opt.long_name.empty?
        if opt.long_name.size < 2
          raise(ArgumentError, "option long names must be at least two characters long")
        end

        self.options[opt.long_name] = opt
      end
    end

    def addarg(arg)
      raise(ArgumentError, "cannot have both arguments and commands") if self.commands.size > 0
      if self.arguments.size > 0
        last = self.arguments.last
        if last.trailing
          raise(ArgumentError, "cannot add argument after trailing argument")
        end
      end

      self.arguments << arg
    end
  end

  # Create new command line interface.
  #
  # @author Gearnode <bryan@frimin.fr>
  # @since 1.0.0
  #
  # @return [CmdLine]
  def self.new
    cmd = CmdLine.new
    cmd.add_flag("h", "help", "print help and exit")
    cmd
  end

  def self.argv
    ARGV.dup.unshift($0)
  end
end