File: cli_parsing.rb

package info (click to toggle)
ruby-puppetserver-ca-cli 2.7.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 696 kB
  • sloc: ruby: 6,970; sh: 4; makefile: 3
file content (67 lines) | stat: -rw-r--r-- 1,896 bytes parent folder | download | duplicates (2)
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
module Puppetserver
  module Ca
    module Utils
      module CliParsing
        def self.parse_without_raising(parser, args)
          all, not_flags, malformed_flags, unknown_flags = [], [], [], []

          begin
            # OptionParser calls this block when it finds a value that doesn't
            # start with one or two dashes and doesn't follow a flag that
            # consumes a value.
            parser.order!(args) do |not_flag|
              not_flags << not_flag
              all << not_flag
            end
          rescue OptionParser::MissingArgument => e
            malformed_flags += e.args
            all += e.args

            retry
          rescue OptionParser::ParseError => e
            flag = e.args.first
            unknown_flags << flag
            all << flag

            if does_not_contain_argument(flag) &&
                args.first &&
                next_arg_is_not_another_flag(args.first)

              value = args.shift
              unknown_flags << value
              all << value
            end

            retry
          end

          return all, not_flags, malformed_flags, unknown_flags
        end

        def self.parse_with_errors(parser, args)
          errors = []

          _, non_flags, malformed_flags, unknown_flags = parse_without_raising(parser, args)

          malformed_flags.each {|f| errors << "    Missing argument to flag `#{f}`" }
          unknown_flags.each   {|f| errors << "    Unknown flag or argument `#{f}`" }
          non_flags.each       {|f| errors << "    Unknown input `#{f}`" }

          errors
        end


      private

        # eg. --flag=argument-to-flag
        def self.does_not_contain_argument(flag)
          !flag.include?('=')
        end

        def self.next_arg_is_not_another_flag(maybe_an_arg)
          !maybe_an_arg.start_with?('-')
        end
      end
    end
  end
end