Debian Codegraph @

packages/seacas/libraries/ioss/src/Ioss_GetLongOpt.C

raw
1 // Copyright(C) 1999-2025 National Technology & Engineering Solutions
2 // of Sandia, LLC (NTESS). Under the terms of Contract DE-NA0003525 with
3 // NTESS, the U.S. Government retains certain rights in this software.
4 //
5 // See packages/seacas/LICENSE for details
6
7 /* S Manoharan. Advanced Computer Research Institute. Lyon. France */
8 #include "Ioss_GetLongOpt.h"
9 #include <cstdio>
10 #include <cstring>
11 #include <fmt/color.h>
12 #include <fmt/core.h>
13 #include <fmt/ostream.h>
14 #include <sstream>
15
16 namespace Ioss {
17 /** \brief Create an empty options database.
18 *
19 * \param optmark The command line symbol designating options.
20 */
21 GetLongOption::GetLongOption(const char optmark) : optmarker(optmark) {}
22
23 /** \brief Frees dynamically allocated memory.
24 *
25 * Frees memory for the private struct variables representing the options.
26 */
27 GetLongOption::~GetLongOption()
28 {
29 Cell *t = table;
30
31 while (t != nullptr) {
32 Cell *tmp = t;
33 t = t->next;
34 delete tmp;
35 }
36 }
37
38 /** \brief Extract the base file name from a full path.
39 *
40 * Finds the last instance of the '/' character and
41 * extracts the part of the string that follows.
42 *
43 * \param[in] pathname The full path.
44 * \return The base file name.
45 */
46 char *GetLongOption::basename(char *const pathname)
47 {
48 char *s = strrchr(pathname, '/');
49 if (s == nullptr) {
50 s = pathname;
51 }
52 else {
53 ++s;
54 }
55 return s;
56 }
57
58 /** \brief Enroll a command line option into the database.
59 *
60 * Dynamically allocates memory for the option, sets its name
61 * type, description, value, and default value, and links it
62 * to the preceding option.
63 *
64 * \param[in] opt The long option name.
65 * \param[in] t The option type.
66 * \param[in] desc A short description of the option.
67 * \param[in] val The option value.
68 * \param[in] optval The default value.
69 * \param[in] extra_line If true, add a blank line after this description output.
70 * \returns 1 if successful, 0 if unsuccessful.
71 */
72 bool GetLongOption::enroll(const char *const opt, const OptType t, const char *const desc,
73 const char *const val, const char *const optval, bool extra_line)
74 {
75 if (options_parsed) {
76 return false;
77 }
78
79 auto *c = new Cell;
80 c->option = opt;
81 c->type = t;
82 c->description = desc != nullptr ? desc : "no description available";
83 c->value = val;
84 c->opt_value = optval;
85 c->next = nullptr;
86 c->extra_line = extra_line;
87
88 if (last == nullptr) {
89 table = last = c;
90 }
91 else {
92 last->next = c;
93 last = c;
94 }
95
96 return true;
97 }
98
99 const char *GetLongOption::program_name() const { return pname == nullptr ? "[UNSET]" : pname; }
100
101 /** \brief Get a command line option object.
102 *
103 * \param[in] opt The option name.
104 * \returns The option object.
105 */
106 const char *GetLongOption::retrieve(const char *const opt) const
107 {
108 for (Cell *t = table; t != nullptr; t = t->next) {
109 if (strcmp(opt, t->option) == 0) {
110 return t->value;
111 }
112 }
113 fmt::print(stderr, "GetLongOption::retrieve - unenrolled option {}{}\n", optmarker, opt);
114 return nullptr;
115 }
116
117 /** \brief parse command line arguments
118 *
119 * Set the values of options in the option table based on
120 * the given command line arguments.
121 *
122 * \param[in] argc Number of command line arguments passed in from main(int argc, char *argv[]).
123 * \param[in] argv Command line arguments passed in from main(int argc, char *argv[]).
124 * \returns Number of options processed, or -1 on failure.
125 *
126 */
127 int GetLongOption::parse(int argc, char *const *argv)
128 {
129 int my_optind = 1;
130
131 std::ostringstream multiple_match;
132
133 pname = basename(*argv);
134 options_parsed = true;
135 if (argc-- <= 1) {
136 return my_optind;
137 }
138
139 while (argc >= 1) {
140 char *token = *++argv;
141 --argc;
142
143 // '--' signifies end of options if followed by space
144 if (token[0] != optmarker || (token[1] == optmarker && strlen(token) == 2)) {
145 break; /* end of options */
146 }
147
148 ++my_optind;
149 char *tmptoken = ++token;
150 if (token[0] == optmarker) { // Handle a double '--'
151 tmptoken = ++token;
152 }
153
154 while (*tmptoken != '\0' && *tmptoken != '=') {
155 ++tmptoken;
156 }
157 /* (tmptoken - token) is now equal to the command line option
158 length. */
159
160 Cell *t;
161 enum { NoMatch, ExactMatch, PartialMatch, MultipleMatch } matchStatus = NoMatch;
162
163 Cell *pc = nullptr; // pointer to the partially-matched cell
164 for (t = table; t != nullptr; t = t->next) {
165 if (strncmp(t->option, token, (tmptoken - token)) == 0) {
166 if (static_cast<int>(strlen(t->option)) == (tmptoken - token)) {
167 /* an exact match found */
168 int stat = setcell(t, tmptoken, *(argv + 1), pname);
169 if (stat == -1) {
170 return -1;
171 }
172 if (stat == 1) {
173 ++argv;
174 --argc;
175 ++my_optind;
176 }
177 matchStatus = ExactMatch;
178 break;
179 }
180 else {
181 /* partial match found */
182 if (pc == nullptr) {
183 matchStatus = PartialMatch;
184 pc = t;
185 }
186 else {
187 // Multiple partial matches...Print warning
188 if (matchStatus == PartialMatch) {
189 // First time, print the message header and the first
190 // matched duplicate...
191 fmt::print(multiple_match, "ERROR: {}: Multiple matches found for option '{}{}'.\n",
192 pname, optmarker, strtok(token, "= "));
193 fmt::print(multiple_match, "\t{}{}: {}\n", optmarker, pc->option, pc->description);
194 }
195 fmt::print(multiple_match, "\t{}{}:{}\n", optmarker, t->option, t->description);
196 matchStatus = MultipleMatch;
197 }
198 }
199 } /* end if */
200 } /* end for */
201
202 if (matchStatus == PartialMatch) {
203 int stat = setcell(pc, tmptoken, *(argv + 1), pname);
204 if (stat == -1) {
205 return -1;
206 }
207 if (stat == 1) {
208 ++argv;
209 --argc;
210 ++my_optind;
211 }
212 }
213 else if (matchStatus == NoMatch) {
214 fmt::print(stderr, "{}: unrecognized option {}{}\n", pname, optmarker, strtok(token, "= "));
215 return -1; /* no match */
216 }
217 else if (matchStatus == MultipleMatch) {
218 std::cerr << multiple_match.str();
219 return -1; /* no match */
220 }
221
222 } /* end while */
223 return my_optind;
224 }
225
226 /** \brief parse an argument string.
227 *
228 * Set the values of options in the option table based on
229 * the given option string.
230 *
231 * \param[in] str The option string.
232 * \param[in] p A string to be used in error reporting
233 * \returns 1 if successful, or -1 otherwise.
234 *
235 */
236 int GetLongOption::parse(char *const str, char *const p)
237 {
238 options_parsed = true;
239 char *token = strtok(str, " \t");
240 const char *name = p != nullptr ? p : "GetLongOption";
241
242 while (token != nullptr) {
243 if (token[0] != optmarker || (token[1] == optmarker && strlen(token) == 2)) {
244 fmt::print(stderr, "{}: nonoptions not allowed\n", name);
245 return -1; /* end of options */
246 }
247
248 char *ladtoken = nullptr; /* lookahead token */
249 char *tmptoken = ++token;
250 while (*tmptoken != '\0' && *tmptoken != '=') {
251 ++tmptoken;
252 }
253 /* (tmptoken - token) is now equal to the command line option
254 length. */
255
256 Cell *t;
257 enum { NoMatch, ExactMatch, PartialMatch } matchStatus = NoMatch;
258 Cell *pc = nullptr; // pointer to the partially-matched cell
259 for (t = table; t != nullptr; t = t->next) {
260 if (strncmp(t->option, token, (tmptoken - token)) == 0) {
261 if (static_cast<int>(strlen(t->option)) == (tmptoken - token)) {
262 /* an exact match found */
263 ladtoken = strtok(nullptr, " \t");
264 int stat = setcell(t, tmptoken, ladtoken, name);
265 if (stat == -1) {
266 return -1;
267 }
268 if (stat == 1) {
269 ladtoken = nullptr;
270 }
271 matchStatus = ExactMatch;
272 break;
273 }
274 else {
275 /* partial match found */
276 matchStatus = PartialMatch;
277 pc = t;
278 }
279 } /* end if */
280 } /* end for */
281
282 if (matchStatus == PartialMatch) {
283 ladtoken = strtok(nullptr, " \t");
284 int stat = setcell(pc, tmptoken, ladtoken, name);
285 if (stat == -1) {
286 return -1;
287 }
288 if (stat == 1) {
289 ladtoken = nullptr;
290 }
291 }
292 else if (matchStatus == NoMatch) {
293 fmt::print(stderr, "{}: unrecognized option {}{}\n", name, optmarker, strtok(token, "= "));
294 return -1; /* no match */
295 }
296
297 token = ladtoken != nullptr ? ladtoken : strtok(nullptr, " \t");
298 } /* end while */
299
300 return 1;
301 }
302
303 /* ----------------------------------------------------------------
304 GetLongOption::setcell returns
305 -1 if there was an error
306 0 if the nexttoken was not consumed
307 1 if the nexttoken was consumed
308 ------------------------------------------------------------------- */
309
310 int GetLongOption::setcell(Cell *c, char *valtoken, char *nexttoken, const char *name)
311 {
312 if (c == nullptr) {
313 return -1;
314 }
315
316 switch (c->type) {
317 case GetLongOption::OptType::NoValue:
318 if (*valtoken == '=') {
319 fmt::print(stderr, "{}: unsolicited value for flag {}{}\n", name, optmarker, c->option);
320 return -1; /* unsolicited value specification */
321 }
322 // Set to a non-zero value. Used to be "(char*) ~0", but that
323 // gives out-of-range warnings on some systems...
324 c->value = (char *)1;
325 return 0;
326 case GetLongOption::OptType::OptionalValue:
327 if (*valtoken == '=') {
328 c->value = ++valtoken;
329 return 0;
330 }
331 else {
332 if (nexttoken != nullptr && nexttoken[0] != optmarker) {
333 c->value = nexttoken;
334 return 1;
335 }
336 c->value = c->opt_value;
337 return 0;
338 }
339 case GetLongOption::OptType::MandatoryValue:
340 if (*valtoken == '=') {
341 c->value = ++valtoken;
342 return 0;
343 }
344 else {
345 if (nexttoken != nullptr) {
346 c->value = nexttoken;
347 return 1;
348 }
349 fmt::print(stderr, "{}: mandatory value for {}{} not specified\n", name, optmarker,
350 c->option);
351 return -1; /* mandatory value not specified */
352 }
353 default: break;
354 }
355 return -1;
356 }
357
358 /** \brief Print the program usage string.
359 *
360 * \param[in] outfile The output stream to which the usage string is printed.
361 */
362 void GetLongOption::usage(std::ostream &outfile) const
363 {
364 // The API of `usage` specifies an `ostream` for the output location. However,
365 // the fmt::print color options do not work with an ostream and instead
366 // want a FILE*. To give formatting in the usage message, we convert the
367 // ostream to a FILE* if it is std::cout or std::cerr; otherwise use the old
368 // non-formatted version...
369 FILE *out = nullptr;
370 if (&outfile == &std::cout) {
371 out = stdout;
372 }
373 else if (&outfile == &std::cerr) {
374 out = stderr;
375 }
376
377 if (out != nullptr) {
378 fmt::print(out, fmt::emphasis::bold, "\nusage: {} {}\n", pname, ustring);
379 for (Cell *t = table; t != nullptr; t = t->next) {
380 fmt::print(out, fmt::emphasis::bold, "\t{}{}", optmarker, t->option);
381 if (t->type == GetLongOption::OptType::MandatoryValue) {
382 fmt::print(out, fmt::emphasis::italic | fmt::emphasis::bold, " <$val>");
383 }
384 else if (t->type == GetLongOption::OptType::OptionalValue) {
385 fmt::print(out, fmt::emphasis::italic | fmt::emphasis::bold, " [$val]");
386 }
387 fmt::print(out, " ({})\n", t->description);
388 if (t->extra_line) {
389 fmt::print(out, "\n");
390 }
391 }
392 }
393 else {
394 fmt::print(outfile, "\nusage: {} {}\n", pname, ustring);
395 for (Cell *t = table; t != nullptr; t = t->next) {
396 fmt::print(outfile, "\t{}{}", optmarker, t->option);
397 if (t->type == GetLongOption::OptType::MandatoryValue) {
398 fmt::print(outfile, " <$val>");
399 }
400 else if (t->type == GetLongOption::OptType::OptionalValue) {
401 fmt::print(outfile, " [$val]");
402 }
403 fmt::print(outfile, " ({})\n", t->description);
404 if (t->extra_line) {
405 fmt::print(outfile, "\n");
406 }
407 }
408 outfile.flush();
409 }
410 }
411 } // namespace Ioss