1 module eph.args.err;
2 
3 import std.string: format;
4 
5 import eph.args.arg: Argument;
6 import eph.args.param: Parameter;
7 
8 public class ConflictingOptionsException: Exception {
9   private const Argument opt1;
10   private const Argument opt2;
11 
12   this(const Argument a, const Argument b) {
13     super(format("Conflicting options:
14       %s
15       %s"));
16     this.opt1 = a;
17     this.opt2 = b;
18   }
19 
20   public const(Argument) getOption1() const {
21     return opt1;
22   }
23 
24   public const(Argument) getOption2() const {
25     return opt2;
26   }
27 }
28 
29 public class UnknownFlagException: Exception {
30   private const bool wasShort;
31   private const char shortFlag;
32   private const string longFlag;
33 
34   this(const char c) {
35     super(format("Unrecognized option -%s", c));
36     wasShort = true;
37     shortFlag = c;
38     longFlag = "";
39   }
40 
41   this(string s) {
42     super(format("Unrecognized option --%s", s));
43     wasShort = false;
44     shortFlag = 0;
45     longFlag = s;
46   }
47 
48   public const(bool) wasShortFlag() const {
49     return wasShort;
50   }
51 
52   public const(char) getShortFlag() const {
53     return shortFlag;
54   }
55 
56   public const(string) getLongFlag() const {
57     return longFlag;
58   }
59 }
60 
61 public class MissingParameterException: Exception {
62   private const Argument opt;
63   private const Parameter param;
64 
65   this(const Argument opt) {
66     super(format("argument %s requires a value", optName(opt)));
67     this.opt = opt;
68     this.param = null;
69   }
70 
71   this(const Parameter param) {
72     super(format("missing required parameter %s", param.name()));
73     this.opt   = null;
74     this.param = param;
75   }
76 
77   public const(Argument) getArgument() const {
78     return opt;
79   }
80 
81   public const(Parameter) getParameter() const {
82     return param;
83   }
84 }
85 
86 public class UnexpectedParameterException: Exception {
87   private const Argument arg;
88   private const string value;
89 
90   this(const Argument opt, const string val) {
91     super(format("argument %s does not take a value", optName(opt)));
92     arg = opt;
93     value = val;
94   }
95 
96   public const(Argument) getArgument() const {
97     return arg;
98   }
99 
100   public const(string) getValue() const {
101     return value;
102   }
103 }
104 
105 private string optName(const Argument opt) {
106   const bool l = opt.hasLongFlag();
107   const bool s = opt.hasShortFlag();
108 
109   if(l && s) {
110     return format("-%s/--%s", opt.shortFlag(), opt.longFlag());
111   }
112 
113   if(l) {
114     return format("--%s", opt.longFlag());
115   }
116 
117   return format("-%s", opt.shortFlag());
118 }