getopt.net
A port of getopt in pure C#.
Loading...
Searching...
No Matches
Extensions.cs
Go to the documentation of this file.
1using System;
2
3namespace getopt.net {
4
5 using System.Linq;
6 using System.Text;
7
11 public enum OptStringPrefix {
15 None,
16
20 Plus = '+',
21
25 Minus = '-'
26 }
27
32 public static class Extensions {
33
40 public static Option? FindOptionOrDefault(this Option[] list, string optName) {
41 if (string.IsNullOrEmpty(optName)) { throw new ArgumentNullException(nameof(optName), "optName must not be null!"); }
42
43 return Array.Find(list, o => o.Name?.Equals(optName, StringComparison.InvariantCulture) == true);
44 }
45
52 public static Option? FindOptionOrDefault(this Option[]? list, char optVal) => list?.ToList().Find(o => o.Value == optVal);
53
59 public static string ToShortOptString(this Option[] list) {
60 if (list is null || list.Length == 0) { return string.Empty; }
61
62 var sBuilder = new StringBuilder();
63
64 foreach (var opt in list) {
65 sBuilder.Append((char)opt.Value);
66 switch (opt.ArgumentType) {
67 case ArgumentType.Required:
68 sBuilder.Append(':');
69 break;
70 case ArgumentType.Optional:
71 sBuilder.Append(';');
72 break;
73 default: break;
74 }
75 }
76
77 return sBuilder.ToString();
78 }
79
86 public static string ToShortOptString(this Option[] list, OptStringPrefix prefix) {
87 if (list is null || list.Length == 0) { return string.Empty; }
88
89 var sBuilder = new StringBuilder();
90 if (prefix != OptStringPrefix.None) {
91 sBuilder.Append((char)prefix);
92 }
93
94 sBuilder.Append(list.ToShortOptString());
95
96 return sBuilder.ToString();
97 }
98
136 public static string GenerateHelpText(this GetOpt getopt, HelpTextConfig? generatorOptions = null) {
137 const string Tab = " ";
138 if (getopt is null) { throw new ArgumentNullException(nameof(getopt), "getopt must not be null!"); }
139
140 var options = getopt.Options;
141 if (options is null || options.Length == 0) { return string.Empty; }
142
143 var config = generatorOptions ?? HelpTextConfig.Default;
144
145 var sBuilder = new StringBuilder();
146
147 if (!string.IsNullOrEmpty(config.ApplicationName) && !string.IsNullOrEmpty(config.ApplicationVersion)) {
148 sBuilder.Append($"{config.ApplicationName} {config.ApplicationVersion}");
149 if (config.CopyrightDate is not null && !string.IsNullOrEmpty(config.CopyrightHolder)) {
150 sBuilder.Append($" © {config.CopyrightDate.Value.Year} {config.CopyrightHolder}");
151 }
152 sBuilder.AppendLine()
153 .AppendLine();
154 }
155
156 string shortOptPrefix = config.OptionConvention == OptionConvention.Windows ? "/" : "-";
157 string longOptPrefix = config.OptionConvention == OptionConvention.Windows ? "/" : config.OptionConvention == OptionConvention.GnuPosix ? "--" : "-";
158
159 sBuilder.AppendLine("Usage:");
160 sBuilder.AppendLine($"{Tab}{config.ApplicationName ?? GetApplicationName()} [options]");
161 if (config.ShowSupportedConventions) {
162 sBuilder.AppendLine(
163 $"""
164
165 Supported option conventions:
166 Windows (/): {(getopt.AllowWindowsConventions ? "yes" : "no")}
167 Powershell (-): {(getopt.AllowPowershellConventions ? "yes" : "no")}
168 Gnu/Posix (-, --): yes
169 """
170 );
171 }
172 sBuilder.AppendLine();
173
174 var longestName = options.Max(o => o.Name?.Length ?? 0);
175 // Align longestName to the next multiple of 4
176 longestName = (longestName + 3) / 4 * 4;
177
178 sBuilder.AppendLine("Switches:");
179 foreach (var opt in options.Where(o => o.ArgumentType == ArgumentType.None)) {
180 sBuilder.AppendLine(string.Format("{0}{1}{2}, {3}{4}{5}", Tab, shortOptPrefix, (char)opt.Value, longOptPrefix, opt.Name?.PadRight(longestName), opt.Description ?? string.Empty));
181 }
182 sBuilder.AppendLine();
183
184 sBuilder.AppendLine("Options:");
185 foreach (var opt in options.Where(o => o.ArgumentType != ArgumentType.None)) {
186 var line = string.Format("{0}{1}{2}, {3}{4}{5}", Tab, shortOptPrefix, (char)opt.Value, longOptPrefix, opt.Name?.PadRight(longestName), opt.Description ?? string.Empty);
187
188 // If line is > config.MaxWidth, split it into multiple lines and align the description
189 if (line.Length > config.MaxWidth) {
190 var desc = opt.Description ?? string.Empty;
191 var beginWhitespace = new string(
192 ' ',
193 Tab.Length +
194 shortOptPrefix.Length +
195 1 +
196 longOptPrefix.Length +
197 (opt.Name?.PadRight(longestName).Length ?? 0) +
198 2 // these last two are the missing space and comma between the long and short opt
199 );
200
201 while (desc.Length > config.MaxWidth - longestName - 10) {
202 var split = desc.Substring(0, config.MaxWidth - longestName - 10);
203 var splitIndex = split.LastIndexOf(' ');
204
205 sBuilder.AppendLine(string.Format("{0}{1}", beginWhitespace, split.Substring(0, splitIndex)));
206 desc = desc.Substring(splitIndex + 1);
207 }
208
209 sBuilder.AppendLine(string.Format("{0}{1}{2}, {3}{4}{5}", Tab, shortOptPrefix, (char)opt.Value, longOptPrefix, opt.Name?.PadRight(longestName), desc));
210 } else {
211 sBuilder.AppendLine(line);
212 }
213
214 sBuilder.AppendLine();
215 }
216 sBuilder.AppendLine();
217
218 if (!string.IsNullOrEmpty(config.FooterText)) {
219 sBuilder.AppendLine(config.FooterText);
220 }
221
222 return sBuilder.ToString();
223 }
224
228 public static string GetApplicationName() {
229 return System.Reflection.Assembly.GetEntryAssembly()?.GetName().Name ?? "Unknown";
230 }
231
232 }
233}
234
static string ToShortOptString(this Option[] list)
Creates a short opt string from an array of Option objects.
Definition Extensions.cs:59
static string GenerateHelpText(this GetOpt getopt, HelpTextConfig? generatorOptions=null)
Generates a help text from the arguments contained in getopt . See GetOpt.Options for more informatio...
static string ToShortOptString(this Option[] list, OptStringPrefix prefix)
Creates a short opt string from an array of Option objects.
Definition Extensions.cs:86
static ? Option FindOptionOrDefault(this Option[]? list, char optVal)
Finds an option in the list list with the Option.Value optVal .
static ? Option FindOptionOrDefault(this Option[] list, string optName)
Finds an option with the name optName
Definition Extensions.cs:40
static string GetApplicationName()
Gets the name of the application.
GetOpt-like class for handling getopt-like command-line arguments in .net.
Definition GetOpt.cs:15
A class that contains configuration options for the help text generator.
static HelpTextConfig Default
Gets a default configuration.
OptStringPrefix
This enumeration contains different prefixes for the generation of shortopt strings.
Definition Extensions.cs:11
@ Plus
If the first character of optstring is '+' or the environment variable POSIXLY_CORRECT is set,...
@ Minus
If the first character of optstring is '-', then each nonoption argv-element is handled as if it were...
ArgumentType
Enumeration containing the argument types possible for getopt.
@ None
No argument is required for the option.
Represents a single long option for getopt.
Definition Option.cs:8
string? Name
The name of the (long) option.
Definition Option.cs:47