gflags_reporting.cc 16.8 KB
Newer Older
1
// Copyright (c) 1999, Google Inc.
Craig Silverstein's avatar
Craig Silverstein committed
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
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

// ---
31
//
Craig Silverstein's avatar
Craig Silverstein committed
32 33 34 35 36 37 38 39
// Revamped and reorganized by Craig Silverstein
//
// This file contains code for handling the 'reporting' flags.  These
// are flags that, when present, cause the program to report some
// information and then exit.  --help and --version are the canonical
// reporting flags, but we also have flags like --helpxml, etc.
//
// There's only one function that's meant to be called externally:
40 41
// HandleCommandLineHelpFlags().  (Well, actually, ShowUsageWithFlags(),
// ShowUsageWithFlagsRestrict(), and DescribeOneFlag() can be called
Craig Silverstein's avatar
Craig Silverstein committed
42
// externally too, but there's little need for it.)  These are all
43
// declared in the main gflags.h header file.
Craig Silverstein's avatar
Craig Silverstein committed
44 45 46 47 48 49 50 51 52 53 54 55 56
//
// HandleCommandLineHelpFlags() will check what 'reporting' flags have
// been defined, if any -- the "help" part of the function name is a
// bit misleading -- and do the relevant reporting.  It should be
// called after all flag-values have been assigned, that is, after
// parsing the command-line.

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <assert.h>
#include <string>
#include <vector>
57

58
#include "config.h"
59 60
#include "gflags.h"
#include "gflags_completions.h"
61
#include "util.h"
Craig Silverstein's avatar
Craig Silverstein committed
62 63


64
// The 'reporting' flags.  They all call gflags_exitfunc().
65 66 67 68 69 70 71 72
DEFINE_bool  (help,        false, "show help on all flags [tip: all flags can have two dashes]");
DEFINE_bool  (helpfull,    false, "show help on all flags -- same as -help");
DEFINE_bool  (helpshort,   false, "show help on only the main module for this program");
DEFINE_string(helpon,      "",    "show help on the modules named by this flag value");
DEFINE_string(helpmatch,   "",    "show help on modules whose name contains the specified substr");
DEFINE_bool  (helppackage, false, "show help on all modules in the main package");
DEFINE_bool  (helpxml,     false, "produce an xml version of help");
DEFINE_bool  (version,     false, "show version and build info and exit");
Craig Silverstein's avatar
Craig Silverstein committed
73

74 75 76

namespace GFLAGS_NAMESPACE {

Craig Silverstein's avatar
Craig Silverstein committed
77

78 79 80
using std::string;
using std::vector;

81

Craig Silverstein's avatar
Craig Silverstein committed
82 83 84 85
// --------------------------------------------------------------------
// DescribeOneFlag()
// DescribeOneFlagInXML()
//    Routines that pretty-print info about a flag.  These use
86
//    a CommandLineFlagInfo, which is the way the gflags
Craig Silverstein's avatar
Craig Silverstein committed
87 88 89 90 91 92 93
//    API exposes static info about a flag.
// --------------------------------------------------------------------

static const int kLineLength = 80;

static void AddString(const string& s,
                      string* final_string, int* chars_in_line) {
94
  const int slen = static_cast<int>(s.length());
Craig Silverstein's avatar
Craig Silverstein committed
95 96 97 98 99 100 101 102 103 104 105
  if (*chars_in_line + 1 + slen >= kLineLength) {  // < 80 chars/line
    *final_string += "\n      ";
    *chars_in_line = 6;
  } else {
    *final_string += " ";
    *chars_in_line += 1;
  }
  *final_string += s;
  *chars_in_line += slen;
}

106 107 108 109 110
static string PrintStringFlagsWithQuotes(const CommandLineFlagInfo& flag,
                                         const string& text, bool current) {
  const char* c_string = (current ? flag.current_value.c_str() :
                          flag.default_value.c_str());
  if (strcmp(flag.type.c_str(), "string") == 0) {  // add quotes for strings
111
    return StringPrintf("%s: \"%s\"", text.c_str(), c_string);
112
  } else {
113
    return StringPrintf("%s: %s", text.c_str(), c_string);
114 115 116
  }
}

Craig Silverstein's avatar
Craig Silverstein committed
117 118
// Create a descriptive string for a flag.
// Goes to some trouble to make pretty line breaks.
119
string DescribeOneFlag(const CommandLineFlagInfo& flag) {
120 121 122 123
  string main_part;
  SStringPrintf(&main_part, "    -%s (%s)",
                flag.name.c_str(),
                flag.description.c_str());
Craig Silverstein's avatar
Craig Silverstein committed
124
  const char* c_string = main_part.c_str();
125
  int chars_left = static_cast<int>(main_part.length());
Craig Silverstein's avatar
Craig Silverstein committed
126 127 128 129 130 131 132 133 134 135 136 137
  string final_string = "";
  int chars_in_line = 0;  // how many chars in current line so far?
  while (1) {
    assert(chars_left == strlen(c_string));  // Unless there's a \0 in there?
    const char* newline = strchr(c_string, '\n');
    if (newline == NULL && chars_in_line+chars_left < kLineLength) {
      // The whole remainder of the string fits on this line
      final_string += c_string;
      chars_in_line += chars_left;
      break;
    }
    if (newline != NULL && newline - c_string < kLineLength - chars_in_line) {
138
      int n = static_cast<int>(newline - c_string);
Craig Silverstein's avatar
Craig Silverstein committed
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
      final_string.append(c_string, n);
      chars_left -= n + 1;
      c_string += n + 1;
    } else {
      // Find the last whitespace on this 80-char line
      int whitespace = kLineLength-chars_in_line-1;  // < 80 chars/line
      while ( whitespace > 0 && !isspace(c_string[whitespace]) ) {
        --whitespace;
      }
      if (whitespace <= 0) {
        // Couldn't find any whitespace to make a line break.  Just dump the
        // rest out!
        final_string += c_string;
        chars_in_line = kLineLength;  // next part gets its own line for sure!
        break;
      }
      final_string += string(c_string, whitespace);
      chars_in_line += whitespace;
      while (isspace(c_string[whitespace]))  ++whitespace;
      c_string += whitespace;
      chars_left -= whitespace;
    }
    if (*c_string == '\0')
      break;
163
    StringAppendF(&final_string, "\n      ");
Craig Silverstein's avatar
Craig Silverstein committed
164 165 166 167 168
    chars_in_line = 6;
  }

  // Append data type
  AddString(string("type: ") + flag.type, &final_string, &chars_in_line);
169 170 171
  // The listed default value will be the actual default from the flag
  // definition in the originating source file, unless the value has
  // subsequently been modified using SetCommandLineOptionWithMode() with mode
172
  // SET_FLAGS_DEFAULT, or by setting FLAGS_foo = bar before ParseCommandLineFlags().
173 174 175 176
  AddString(PrintStringFlagsWithQuotes(flag, "default", false), &final_string,
            &chars_in_line);
  if (!flag.is_default) {
    AddString(PrintStringFlagsWithQuotes(flag, "currently", true),
Craig Silverstein's avatar
Craig Silverstein committed
177 178 179
              &final_string, &chars_in_line);
  }

180
  StringAppendF(&final_string, "\n");
Craig Silverstein's avatar
Craig Silverstein committed
181 182 183 184 185 186
  return final_string;
}

// Simple routine to xml-escape a string: escape & and < only.
static string XMLText(const string& txt) {
  string ans = txt;
187
  for (string::size_type pos = 0; (pos = ans.find("&", pos)) != string::npos; )
Craig Silverstein's avatar
Craig Silverstein committed
188
    ans.replace(pos++, 1, "&amp;");
189
  for (string::size_type pos = 0; (pos = ans.find("<", pos)) != string::npos; )
Craig Silverstein's avatar
Craig Silverstein committed
190 191 192 193
    ans.replace(pos++, 1, "&lt;");
  return ans;
}

194
static void AddXMLTag(string* r, const char* tag, const string& txt) {
195
  StringAppendF(r, "<%s>%s</%s>", tag, XMLText(txt).c_str(), tag);
196 197
}

198

Craig Silverstein's avatar
Craig Silverstein committed
199 200 201 202
static string DescribeOneFlagInXML(const CommandLineFlagInfo& flag) {
  // The file and flagname could have been attributes, but default
  // and meaning need to avoid attribute normalization.  This way it
  // can be parsed by simple programs, in addition to xml parsers.
203 204 205 206 207 208 209 210 211
  string r("<flag>");
  AddXMLTag(&r, "file", flag.filename);
  AddXMLTag(&r, "name", flag.name);
  AddXMLTag(&r, "meaning", flag.description);
  AddXMLTag(&r, "default", flag.default_value);
  AddXMLTag(&r, "current", flag.current_value);
  AddXMLTag(&r, "type", flag.type);
  r += "</flag>";
  return r;
Craig Silverstein's avatar
Craig Silverstein committed
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
}

// --------------------------------------------------------------------
// ShowUsageWithFlags()
// ShowUsageWithFlagsRestrict()
// ShowXMLOfFlags()
//    These routines variously expose the registry's list of flag
//    values.  ShowUsage*() prints the flag-value information
//    to stdout in a user-readable format (that's what --help uses).
//    The Restrict() version limits what flags are shown.
//    ShowXMLOfFlags() prints the flag-value information to stdout
//    in a machine-readable format.  In all cases, the flags are
//    sorted: first by filename they are defined in, then by flagname.
// --------------------------------------------------------------------

static const char* Basename(const char* filename) {
  const char* sep = strrchr(filename, PATH_SEPARATOR);
  return sep ? sep + 1 : filename;
}

static string Dirname(const string& filename) {
  string::size_type sep = filename.rfind(PATH_SEPARATOR);
  return filename.substr(0, (sep == string::npos) ? 0 : sep);
}

237 238 239 240 241 242
// Test whether a filename contains at least one of the substrings.
static bool FileMatchesSubstring(const string& filename,
                                 const vector<string>& substrings) {
  for (vector<string>::const_iterator target = substrings.begin();
       target != substrings.end();
       ++target) {
243 244 245 246 247 248
    if (strstr(filename.c_str(), target->c_str()) != NULL)
      return true;
    // If the substring starts with a '/', that means that we want
    // the string to be at the beginning of a directory component.
    // That should match the first directory component as well, so
    // we allow '/foo' to match a filename of 'foo'.
249
    if (!target->empty() && (*target)[0] == PATH_SEPARATOR &&
250 251
        strncmp(filename.c_str(), target->c_str() + 1,
                strlen(target->c_str() + 1)) == 0)
252 253 254 255 256 257 258
      return true;
  }
  return false;
}

// Show help for every filename which matches any of the target substrings.
// If substrings is empty, shows help for every file. If a flag's help message
259 260 261
// has been stripped (e.g. by adding '#define STRIP_FLAG_HELP 1'
// before including gflags/gflags.h), then this flag will not be displayed
// by '--help' and its variants.
262 263
static void ShowUsageWithFlagsMatching(const char *argv0,
                                       const vector<string> &substrings) {
Craig Silverstein's avatar
Craig Silverstein committed
264 265 266 267 268
  fprintf(stdout, "%s: %s\n", Basename(argv0), ProgramUsage());

  vector<CommandLineFlagInfo> flags;
  GetAllFlags(&flags);           // flags are sorted by filename, then flagname

269
  string last_filename;          // so we know when we're at a new file
Craig Silverstein's avatar
Craig Silverstein committed
270 271 272 273 274
  bool first_directory = true;   // controls blank lines between dirs
  bool found_match = false;      // stays false iff no dir matches restrict
  for (vector<CommandLineFlagInfo>::const_iterator flag = flags.begin();
       flag != flags.end();
       ++flag) {
275 276 277 278 279 280 281 282 283 284 285 286 287
    if (substrings.empty() ||
        FileMatchesSubstring(flag->filename, substrings)) {
      // If the flag has been stripped, pretend that it doesn't exist.
      if (flag->description == kStrippedFlagHelp) continue;
      found_match = true;     // this flag passed the match!
      if (flag->filename != last_filename) {                      // new file
        if (Dirname(flag->filename) != Dirname(last_filename)) {  // new dir!
          if (!first_directory)
            fprintf(stdout, "\n\n");   // put blank lines between directories
          first_directory = false;
        }
        fprintf(stdout, "\n  Flags from %s:\n", flag->filename.c_str());
        last_filename = flag->filename;
Craig Silverstein's avatar
Craig Silverstein committed
288
      }
289 290
      // Now print this flag
      fprintf(stdout, "%s", DescribeOneFlag(*flag).c_str());
Craig Silverstein's avatar
Craig Silverstein committed
291 292
    }
  }
293 294 295 296 297 298 299 300 301
  if (!found_match && !substrings.empty()) {
    fprintf(stdout, "\n  No modules matched: use -help\n");
  }
}

void ShowUsageWithFlagsRestrict(const char *argv0, const char *restrict) {
  vector<string> substrings;
  if (restrict != NULL && *restrict != '\0') {
    substrings.push_back(restrict);
Craig Silverstein's avatar
Craig Silverstein committed
302
  }
303
  ShowUsageWithFlagsMatching(argv0, substrings);
Craig Silverstein's avatar
Craig Silverstein committed
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
}

void ShowUsageWithFlags(const char *argv0) {
  ShowUsageWithFlagsRestrict(argv0, "");
}

// Convert the help, program, and usage to xml.
static void ShowXMLOfFlags(const char *prog_name) {
  vector<CommandLineFlagInfo> flags;
  GetAllFlags(&flags);   // flags are sorted: by filename, then flagname

  // XML.  There is no corresponding schema yet
  fprintf(stdout, "<?xml version=\"1.0\"?>\n");
  // The document
  fprintf(stdout, "<AllFlags>\n");
  // the program name and usage
  fprintf(stdout, "<program>%s</program>\n",
          XMLText(Basename(prog_name)).c_str());
  fprintf(stdout, "<usage>%s</usage>\n",
          XMLText(ProgramUsage()).c_str());
  // All the flags
  for (vector<CommandLineFlagInfo>::const_iterator flag = flags.begin();
       flag != flags.end();
       ++flag) {
328 329
    if (flag->description != kStrippedFlagHelp)
      fprintf(stdout, "%s\n", DescribeOneFlagInXML(*flag).c_str());
Craig Silverstein's avatar
Craig Silverstein committed
330 331 332 333 334 335 336 337 338 339 340
  }
  // The end of the document
  fprintf(stdout, "</AllFlags>\n");
}

// --------------------------------------------------------------------
// ShowVersion()
//    Called upon --version.  Prints build-related info.
// --------------------------------------------------------------------

static void ShowVersion() {
341 342 343 344 345 346 347
  const char* version_string = VersionString();
  if (version_string && *version_string) {
    fprintf(stdout, "%s version %s\n",
            ProgramInvocationShortName(), version_string);
  } else {
    fprintf(stdout, "%s\n", ProgramInvocationShortName());
  }
Craig Silverstein's avatar
Craig Silverstein committed
348 349 350 351 352
# if !defined(NDEBUG)
  fprintf(stdout, "Debug build (NDEBUG not #defined)\n");
# endif
}

353 354
static void AppendPrognameStrings(vector<string>* substrings,
                                  const char* progname) {
355 356
  string r("");
  r += PATH_SEPARATOR;
357 358 359 360 361 362
  r += progname;
  substrings->push_back(r + ".");
  substrings->push_back(r + "-main.");
  substrings->push_back(r + "_main.");
}

Craig Silverstein's avatar
Craig Silverstein committed
363 364 365 366 367 368 369 370 371 372 373
// --------------------------------------------------------------------
// HandleCommandLineHelpFlags()
//    Checks all the 'reporting' commandline flags to see if any
//    have been set.  If so, handles them appropriately.  Note
//    that all of them, by definition, cause the program to exit
//    if they trigger.
// --------------------------------------------------------------------

void HandleCommandLineHelpFlags() {
  const char* progname = ProgramInvocationShortName();

374 375
  HandleCommandLineCompletions();

376 377 378
  vector<string> substrings;
  AppendPrognameStrings(&substrings, progname);

Craig Silverstein's avatar
Craig Silverstein committed
379 380 381
  if (FLAGS_helpshort) {
    // show only flags related to this binary:
    // E.g. for fileutil.cc, want flags containing   ... "/fileutil." cc
382
    ShowUsageWithFlagsMatching(progname, substrings);
383
    gflags_exitfunc(1);
Craig Silverstein's avatar
Craig Silverstein committed
384 385 386 387

  } else if (FLAGS_help || FLAGS_helpfull) {
    // show all options
    ShowUsageWithFlagsRestrict(progname, "");   // empty restrict
388
    gflags_exitfunc(1);
Craig Silverstein's avatar
Craig Silverstein committed
389 390

  } else if (!FLAGS_helpon.empty()) {
391
    string restrict = PATH_SEPARATOR + FLAGS_helpon + ".";
Craig Silverstein's avatar
Craig Silverstein committed
392
    ShowUsageWithFlagsRestrict(progname, restrict.c_str());
393
    gflags_exitfunc(1);
Craig Silverstein's avatar
Craig Silverstein committed
394 395 396

  } else if (!FLAGS_helpmatch.empty()) {
    ShowUsageWithFlagsRestrict(progname, FLAGS_helpmatch.c_str());
397
    gflags_exitfunc(1);
Craig Silverstein's avatar
Craig Silverstein committed
398 399 400 401 402 403 404 405 406

  } else if (FLAGS_helppackage) {
    // Shows help for all files in the same directory as main().  We
    // don't want to resort to looking at dirname(progname), because
    // the user can pick progname, and it may not relate to the file
    // where main() resides.  So instead, we search the flags for a
    // filename like "/progname.cc", and take the dirname of that.
    vector<CommandLineFlagInfo> flags;
    GetAllFlags(&flags);
407
    string last_package;
Craig Silverstein's avatar
Craig Silverstein committed
408 409 410
    for (vector<CommandLineFlagInfo>::const_iterator flag = flags.begin();
         flag != flags.end();
         ++flag) {
411
      if (!FileMatchesSubstring(flag->filename, substrings))
Craig Silverstein's avatar
Craig Silverstein committed
412
        continue;
413
      const string package = Dirname(flag->filename) + PATH_SEPARATOR;
Craig Silverstein's avatar
Craig Silverstein committed
414 415
      if (package != last_package) {
        ShowUsageWithFlagsRestrict(progname, package.c_str());
416
        VLOG(7) << "Found package: " << package;
417
        if (!last_package.empty()) {      // means this isn't our first pkg
418
          LOG(WARNING) << "Multiple packages contain a file=" << progname;
Craig Silverstein's avatar
Craig Silverstein committed
419 420 421 422
        }
        last_package = package;
      }
    }
423
    if (last_package.empty()) {   // never found a package to print
424
      LOG(WARNING) << "Unable to find a package for file=" << progname;
Craig Silverstein's avatar
Craig Silverstein committed
425
    }
426
    gflags_exitfunc(1);
Craig Silverstein's avatar
Craig Silverstein committed
427 428 429

  } else if (FLAGS_helpxml) {
    ShowXMLOfFlags(progname);
430
    gflags_exitfunc(1);
Craig Silverstein's avatar
Craig Silverstein committed
431 432 433 434

  } else if (FLAGS_version) {
    ShowVersion();
    // Unlike help, we may be asking for version in a script, so return 0
435 436
    gflags_exitfunc(0);

Craig Silverstein's avatar
Craig Silverstein committed
437 438 439
  }
}

440 441

} // namespace GFLAGS_NAMESPACE