File: Flags.cpp

package info (click to toggle)
ola 0.10.8.nojsmin-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 16,656 kB
  • sloc: cpp: 132,274; python: 14,082; javascript: 6,774; sh: 4,616; ansic: 2,189; java: 518; xml: 253; makefile: 183
file content (445 lines) | stat: -rw-r--r-- 11,440 bytes parent folder | download | duplicates (4)
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
/*
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 *
 * Flags.cpp
 * Handle command line flags.
 * Copyright (C) 2013 Simon Newton
 */

/**
 * @addtogroup flags
 * @{
 * @file common/base/Flags.cpp
 * @}
 */
#include <time.h>

#include <algorithm>
#include <iostream>
#include <string>
#include <vector>

#include "ola/base/Array.h"
#include "ola/base/Flags.h"
#include "ola/base/SysExits.h"
#include "ola/base/Version.h"
#include "ola/file/Util.h"
#include "ola/stl/STLUtils.h"

/**
 * @private
 * @brief Define the help flag
 */
DEFINE_s_default_bool(help, h, false, "Display the help message");
DEFINE_s_default_bool(version, v, false, "Display version information");
DEFINE_default_bool(gen_manpage, false, "Generate a man page snippet");

namespace ola {

/**
 * @addtogroup flags
 * @{
 */

using std::cerr;
using std::cout;
using std::endl;
using std::string;
using std::vector;

/**
 * The prefix used on inverted bool flags
 * @examplepara
 *   @code
 *   DEFINE_s_default_bool(noMaster, d, false, "Dummy flag to show NO_PREFIX")
 *   @endcode
 *
 *   Then if you called your application with that flag:
 *   @code
 *   bash$myapplication -d
 *   @endcode
 *   Then the noMaster flag would be true.
 */
const char Flag<bool>::NO_PREFIX[] = "no-";

void SetHelpString(const string &first_line, const string &description) {
  GetRegistry()->SetFirstLine(first_line);
  GetRegistry()->SetDescription(description);
}

void DisplayUsage() {
  GetRegistry()->DisplayUsage();
}

void DisplayUsageAndExit() {
  GetRegistry()->DisplayUsage();
  exit(ola::EXIT_USAGE);
}

void DisplayVersion() {
  GetRegistry()->DisplayVersion();
}

void GenManPage() {
  GetRegistry()->GenManPage();
}

void ParseFlags(int *argc, char **argv) {
  GetRegistry()->ParseFlags(argc, argv);
}

/**
 * @}
 * @cond HIDDEN_SYMBOLS
 */

static FlagRegistry *registry = NULL;

/*
 * Registered as an atexit function by the FlagRegistry constructor.
 */
void DeleteFlagRegistry() {
  FlagRegistry *old_registry = registry;
  registry = NULL;
  delete old_registry;
}

/*
 * Change the input to s/_/-/g
 */
void BaseFlag::ReplaceUnderscoreWithHyphen(char *input) {
  for (char *c = input; *c; c++) {
    if (*c == '_')
      *c = '-';
  }
}

/*
 * Convert a flag name to the canonical representation.
 */
const char *BaseFlag::NewCanonicalName(const char *name) {
  unsigned int total_size = strlen(name) + 1;
  char *output = new char[total_size];
  char *o = output;
  for (const char *i = name; *i; i++, o++) {
    if (*i == '_')
      *o = '-';
    else
      *o = *i;
  }
  output[total_size - 1] = 0;
  return output;
}

/**
 * @private
 * Get the global FlagRegistry object.
 */
FlagRegistry *GetRegistry() {
  if (!registry) {
    registry = new FlagRegistry();
    atexit(DeleteFlagRegistry);
  }
  return registry;
}

/**
 * Register a flag.
 */
void FlagRegistry::RegisterFlag(FlagInterface *flag) {
  STLInsertOrDie(&m_long_opts, flag->name(), flag);
  if (flag->short_opt()) {
    STLInsertOrDie(&m_short_opts, flag->short_opt(), flag);
  }
}

/**
 * @brief Parse the command line flags. This re-arranges argv so that only the
 * non-flag options remain.
 */
void FlagRegistry::ParseFlags(int *argc, char **argv) {
  const string long_option_prefix("--");
  const string short_option_prefix("-");

  m_argv0 = argv[0];

  int c;
  int option_index = 0;
  const string short_opts = GetShortOptsString();
  FlagMap flags;
  const struct option *long_options = GetLongOpts(&flags);

  optind = 0;  // reset each time
  while (1) {
    c = getopt_long(*argc, argv, short_opts.c_str(),
                    long_options, &option_index);

    if (c == -1) {
      break;
    } else if (c == '?') {
      exit(EXIT_USAGE);
    }


    FlagInterface *flag = STLFindOrNull(flags, c);
    if (!flag) {
      cerr << "Missing flag " << c << endl;
    } else {
      if (flag->has_arg()) {
        if (!flag->SetValue(optarg)) {
          cerr << "Invalid arg value " << optarg << " for flag "
               << flag->name() << endl;
          exit(EXIT_USAGE);
        }
      } else {
        if (!flag->SetValue("1")) {
          cerr << "Failed to set value of 1 for flag " << flag->name() << endl;
          exit(EXIT_USAGE);
        }
      }
    }
  }

  if (FLAGS_help) {
    DisplayUsage();
    exit(EXIT_OK);
  }

  if (FLAGS_version) {
    DisplayVersion();
    exit(EXIT_OK);
  }

  if (FLAGS_gen_manpage) {
    GenManPage();
    exit(EXIT_OK);
  }

  delete[] long_options;

  // Remove flags so only non-flag arguments remain.
  for (int i = 0; i < *argc - optind; i++) {
    argv[1 + i] = argv[optind + i];
  }
  *argc = 1 + *argc - optind;
}


void FlagRegistry::SetFirstLine(const string &first_line) {
  m_first_line = first_line;
}


void FlagRegistry::SetDescription(const string &description) {
  m_description = description;
}

/*
 * @brief Print the usage text to stdout
 */
void FlagRegistry::DisplayUsage() {
  cout << "Usage: " << m_argv0 << " " << m_first_line << endl << endl;
  if (!m_description.empty()) {
    cout << m_description << endl << endl;
  }

  // - comes before a-z which means flags without long options appear first. To
  // avoid this we keep two lists.
  vector<string> short_flag_lines, long_flag_lines;
  LongOpts::const_iterator iter = m_long_opts.begin();
  for (; iter != m_long_opts.end(); ++iter) {
    std::ostringstream str;
    const FlagInterface *flag = iter->second;
    if (flag->name() == FLAGS_gen_manpage.name()) {
      continue;
    }

    str << "  ";
    if (flag->short_opt()) {
      str << "-" << flag->short_opt() << ", ";
    }
    str << "--" << flag->name();

    if (flag->has_arg()) {
      str << " <" << flag->arg_type() << ">";
    }
    str << endl << "    " << iter->second->help() << endl;
    if (flag->short_opt())
      short_flag_lines.push_back(str.str());
    else
      long_flag_lines.push_back(str.str());
  }

  PrintFlags(&short_flag_lines);
  PrintFlags(&long_flag_lines);
}

/*
 * @brief Print the version text to stdout
 */
void FlagRegistry::DisplayVersion() {
  cout << "OLA " << m_argv0 << " version: " << ola::base::Version::GetVersion()
       << endl;
}

void FlagRegistry::GenManPage() {
  char date_str[100];
  time_t curtime;
  curtime = time(NULL);
  struct tm loctime;
#ifdef _WIN32
  loctime = *gmtime(&curtime);  // NOLINT(runtime/threadsafe_fn)
#else
  gmtime_r(&curtime, &loctime);
#endif  // _WIN32
  strftime(date_str, arraysize(date_str), "%B %Y", &loctime);

  string exe_name = ola::file::FilenameFromPathOrPath(m_argv0);

  if (0 != exe_name.compare(m_argv0)) {
    // Strip lt- off the start if present, in case we're generating the man
    // page from a libtool wrapper script for the exe
    ola::StripPrefix(&exe_name, "lt-");
  }

  // Convert newlines to a suitable format for man pages
  string man_description = m_description;
  ReplaceAll(&man_description, "\n", "\n.PP\n");

  // Guess at a single line synopsis, match ". " so we don't get standards
  string synopsis = "";
  std::size_t pos = man_description.find(". ");
  if (pos != string::npos) {
    synopsis = man_description.substr(0, pos + 1);
  } else {
    synopsis = man_description;
  }

  cout << ".TH " << exe_name << " 1 \"" << date_str << "\"" << endl;
  cout << ".SH NAME" << endl;
  cout << exe_name << " \\- " << synopsis << endl;
  cout << ".SH SYNOPSIS" << endl;
  cout << ".B " << exe_name << endl;
  cout << m_first_line << endl;
  cout << ".SH DESCRIPTION" << endl;
  cout << ".B " << exe_name << endl;
  cout << man_description << endl;
  cout << ".SH OPTIONS" << endl;

  // - comes before a-z which means flags without long options appear first. To
  // avoid this we keep two lists.
  vector<OptionPair> short_flag_lines, long_flag_lines;
  LongOpts::const_iterator iter = m_long_opts.begin();
  for (; iter != m_long_opts.end(); ++iter) {
    const FlagInterface *flag = iter->second;
    if (flag->name() == FLAGS_gen_manpage.name()) {
      continue;
    }

    std::ostringstream str;
    if (flag->short_opt()) {
      str << "-" << flag->short_opt() << ", ";
    }
    str << "--" << flag->name();

    if (flag->has_arg()) {
      str << " <" << flag->arg_type() << ">";
    }
    if (flag->short_opt()) {
      short_flag_lines.push_back(
          OptionPair(str.str(), iter->second->help()));
    } else {
      long_flag_lines.push_back(
          OptionPair(str.str(), iter->second->help()));
    }
  }

  PrintManPageFlags(&short_flag_lines);
  PrintManPageFlags(&long_flag_lines);
}

/**
 * @brief Generate the short opts string for getopt. See `man 3 getopt` for the
 * format.
 */
string FlagRegistry::GetShortOptsString() const {
  string short_opts;
  ShortOpts::const_iterator iter = m_short_opts.begin();
  for (; iter != m_short_opts.end(); ++iter) {
    char short_opt = iter->second->short_opt();
    if (!short_opt)
      continue;

    short_opts.push_back(iter->second->short_opt());
    if (iter->second->has_arg()) {
      short_opts.push_back(':');
    }
  }
  return short_opts;
}

/**
 * @brief Allocate & populate the array of option structs for the call to
 * getopt_long. The caller is responsible for deleting the array.
 *
 * The flag_map is populated with the option identifier (int) to FlagInterface*
 * mappings. The ownership of the pointers to FlagInterfaces is not transferred
 * to the caller.
 */
struct option *FlagRegistry::GetLongOpts(FlagMap *flag_map) {
  unsigned int flag_count = m_long_opts.size() + 1;
  struct option *long_options = new struct option[flag_count];
  memset(long_options, 0, sizeof(struct option) * flag_count);

  LongOpts::iterator iter = m_long_opts.begin();
  struct option *opt = long_options;
  int flag_counter = 256;
  for (; iter != m_long_opts.end(); ++iter) {
    FlagInterface *flag = iter->second;
    opt->name = flag->name();
    opt->has_arg = flag->has_arg() ? required_argument : no_argument;
    opt->flag = 0;
    int flag_option = flag->short_opt() ? flag->short_opt() : flag_counter++;
    opt->val = flag_option;
    flag_map->insert(FlagMap::value_type(flag_option, flag));
    opt++;
  }
  return long_options;
}


/**
 * @brief Given a vector of flags lines, sort them and print to stdout.
 */
void FlagRegistry::PrintFlags(vector<string> *lines) {
  std::sort(lines->begin(), lines->end());
  vector<string>::const_iterator iter = lines->begin();
  for (; iter != lines->end(); ++iter)
    cout << *iter;
}

void FlagRegistry::PrintManPageFlags(vector<OptionPair> *lines) {
  std::sort(lines->begin(), lines->end());
  vector<OptionPair>::const_iterator iter = lines->begin();
  for (; iter != lines->end(); ++iter) {
    cout << ".IP \"" << iter->first << "\"" << endl;
    cout << iter->second << endl;
  }
}
/**
 * @endcond
 * End Hidden Symbols
 */
}  // namespace ola