1 // Copyright (c) 1999, Google Inc.
2 // All rights reserved.
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
8 // * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 // * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
14 // * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 // Revamped and reorganized by Craig Silverstein
34 // This file contains code for handling the 'reporting' flags. These
35 // are flags that, when present, cause the program to report some
36 // information and then exit. --help and --version are the canonical
37 // reporting flags, but we also have flags like --helpxml, etc.
39 // There's only one function that's meant to be called externally:
40 // HandleCommandLineHelpFlags(). (Well, actually, ShowUsageWithFlags(),
41 // ShowUsageWithFlagsRestrict(), and DescribeOneFlag() can be called
42 // externally too, but there's little need for it.) These are all
43 // declared in the main gflags.h header file.
45 // HandleCommandLineHelpFlags() will check what 'reporting' flags have
46 // been defined, if any -- the "help" part of the function name is a
47 // bit misleading -- and do the relevant reporting. It should be
48 // called after all flag-values have been assigned, that is, after
49 // parsing the command-line.
60 #include "gflags_completions.h"
64 // The 'reporting' flags. They all call gflags_exitfunc().
65 DEFINE_bool (help, false, "show help on all flags [tip: all flags can have two dashes]");
66 DEFINE_bool (helpfull, false, "show help on all flags -- same as -help");
67 DEFINE_bool (helpshort, false, "show help on only the main module for this program");
68 DEFINE_string(helpon, "", "show help on the modules named by this flag value");
69 DEFINE_string(helpmatch, "", "show help on modules whose name contains the specified substr");
70 DEFINE_bool (helppackage, false, "show help on all modules in the main package");
71 DEFINE_bool (helpxml, false, "produce an xml version of help");
72 DEFINE_bool (version, false, "show version and build info and exit");
75 namespace GFLAGS_NAMESPACE {
82 // --------------------------------------------------------------------
84 // DescribeOneFlagInXML()
85 // Routines that pretty-print info about a flag. These use
86 // a CommandLineFlagInfo, which is the way the gflags
87 // API exposes static info about a flag.
88 // --------------------------------------------------------------------
90 static const int kLineLength = 80;
92 static void AddString(const string& s,
93 string* final_string, int* chars_in_line) {
94 const int slen = static_cast<int>(s.length());
95 if (*chars_in_line + 1 + slen >= kLineLength) { // < 80 chars/line
96 *final_string += "\n ";
103 *chars_in_line += slen;
106 static string PrintStringFlagsWithQuotes(const CommandLineFlagInfo& flag,
107 const string& text, bool current) {
108 const char* c_string = (current ? flag.current_value.c_str() :
109 flag.default_value.c_str());
110 if (strcmp(flag.type.c_str(), "string") == 0) { // add quotes for strings
111 return StringPrintf("%s: \"%s\"", text.c_str(), c_string);
113 return StringPrintf("%s: %s", text.c_str(), c_string);
117 // Create a descriptive string for a flag.
118 // Goes to some trouble to make pretty line breaks.
119 string DescribeOneFlag(const CommandLineFlagInfo& flag) {
121 SStringPrintf(&main_part, " -%s (%s)",
123 flag.description.c_str());
124 const char* c_string = main_part.c_str();
125 int chars_left = static_cast<int>(main_part.length());
126 string final_string = "";
127 int chars_in_line = 0; // how many chars in current line so far?
129 assert(chars_left == strlen(c_string)); // Unless there's a \0 in there?
130 const char* newline = strchr(c_string, '\n');
131 if (newline == NULL && chars_in_line+chars_left < kLineLength) {
132 // The whole remainder of the string fits on this line
133 final_string += c_string;
134 chars_in_line += chars_left;
137 if (newline != NULL && newline - c_string < kLineLength - chars_in_line) {
138 int n = static_cast<int>(newline - c_string);
139 final_string.append(c_string, n);
143 // Find the last whitespace on this 80-char line
144 int whitespace = kLineLength-chars_in_line-1; // < 80 chars/line
145 while ( whitespace > 0 && !isspace(c_string[whitespace]) ) {
148 if (whitespace <= 0) {
149 // Couldn't find any whitespace to make a line break. Just dump the
151 final_string += c_string;
152 chars_in_line = kLineLength; // next part gets its own line for sure!
155 final_string += string(c_string, whitespace);
156 chars_in_line += whitespace;
157 while (isspace(c_string[whitespace])) ++whitespace;
158 c_string += whitespace;
159 chars_left -= whitespace;
161 if (*c_string == '\0')
163 StringAppendF(&final_string, "\n ");
168 AddString(string("type: ") + flag.type, &final_string, &chars_in_line);
169 // The listed default value will be the actual default from the flag
170 // definition in the originating source file, unless the value has
171 // subsequently been modified using SetCommandLineOptionWithMode() with mode
172 // SET_FLAGS_DEFAULT, or by setting FLAGS_foo = bar before ParseCommandLineFlags().
173 AddString(PrintStringFlagsWithQuotes(flag, "default", false), &final_string,
175 if (!flag.is_default) {
176 AddString(PrintStringFlagsWithQuotes(flag, "currently", true),
177 &final_string, &chars_in_line);
180 StringAppendF(&final_string, "\n");
184 // Simple routine to xml-escape a string: escape & and < only.
185 static string XMLText(const string& txt) {
187 for (string::size_type pos = 0; (pos = ans.find("&", pos)) != string::npos; )
188 ans.replace(pos++, 1, "&");
189 for (string::size_type pos = 0; (pos = ans.find("<", pos)) != string::npos; )
190 ans.replace(pos++, 1, "<");
194 static void AddXMLTag(string* r, const char* tag, const string& txt) {
195 StringAppendF(r, "<%s>%s</%s>", tag, XMLText(txt).c_str(), tag);
199 static string DescribeOneFlagInXML(const CommandLineFlagInfo& flag) {
200 // The file and flagname could have been attributes, but default
201 // and meaning need to avoid attribute normalization. This way it
202 // can be parsed by simple programs, in addition to xml parsers.
204 AddXMLTag(&r, "file", flag.filename);
205 AddXMLTag(&r, "name", flag.name);
206 AddXMLTag(&r, "meaning", flag.description);
207 AddXMLTag(&r, "default", flag.default_value);
208 AddXMLTag(&r, "current", flag.current_value);
209 AddXMLTag(&r, "type", flag.type);
214 // --------------------------------------------------------------------
215 // ShowUsageWithFlags()
216 // ShowUsageWithFlagsRestrict()
218 // These routines variously expose the registry's list of flag
219 // values. ShowUsage*() prints the flag-value information
220 // to stdout in a user-readable format (that's what --help uses).
221 // The Restrict() version limits what flags are shown.
222 // ShowXMLOfFlags() prints the flag-value information to stdout
223 // in a machine-readable format. In all cases, the flags are
224 // sorted: first by filename they are defined in, then by flagname.
225 // --------------------------------------------------------------------
227 static const char* Basename(const char* filename) {
228 const char* sep = strrchr(filename, PATH_SEPARATOR);
229 return sep ? sep + 1 : filename;
232 static string Dirname(const string& filename) {
233 string::size_type sep = filename.rfind(PATH_SEPARATOR);
234 return filename.substr(0, (sep == string::npos) ? 0 : sep);
237 // Test whether a filename contains at least one of the substrings.
238 static bool FileMatchesSubstring(const string& filename,
239 const vector<string>& substrings) {
240 for (vector<string>::const_iterator target = substrings.begin();
241 target != substrings.end();
243 if (strstr(filename.c_str(), target->c_str()) != NULL)
245 // If the substring starts with a '/', that means that we want
246 // the string to be at the beginning of a directory component.
247 // That should match the first directory component as well, so
248 // we allow '/foo' to match a filename of 'foo'.
249 if (!target->empty() && (*target)[0] == PATH_SEPARATOR &&
250 strncmp(filename.c_str(), target->c_str() + 1,
251 strlen(target->c_str() + 1)) == 0)
257 // Show help for every filename which matches any of the target substrings.
258 // If substrings is empty, shows help for every file. If a flag's help message
259 // has been stripped (e.g. by adding '#define STRIP_FLAG_HELP 1'
260 // before including gflags/gflags.h), then this flag will not be displayed
261 // by '--help' and its variants.
262 static void ShowUsageWithFlagsMatching(const char *argv0,
263 const vector<string> &substrings) {
264 fprintf(stdout, "%s: %s\n", Basename(argv0), ProgramUsage());
266 vector<CommandLineFlagInfo> flags;
267 GetAllFlags(&flags); // flags are sorted by filename, then flagname
269 string last_filename; // so we know when we're at a new file
270 bool first_directory = true; // controls blank lines between dirs
271 bool found_match = false; // stays false iff no dir matches restrict
272 for (vector<CommandLineFlagInfo>::const_iterator flag = flags.begin();
275 if (substrings.empty() ||
276 FileMatchesSubstring(flag->filename, substrings)) {
277 // If the flag has been stripped, pretend that it doesn't exist.
278 if (flag->description == kStrippedFlagHelp) continue;
279 found_match = true; // this flag passed the match!
280 if (flag->filename != last_filename) { // new file
281 if (Dirname(flag->filename) != Dirname(last_filename)) { // new dir!
282 if (!first_directory)
283 fprintf(stdout, "\n\n"); // put blank lines between directories
284 first_directory = false;
286 fprintf(stdout, "\n Flags from %s:\n", flag->filename.c_str());
287 last_filename = flag->filename;
289 // Now print this flag
290 fprintf(stdout, "%s", DescribeOneFlag(*flag).c_str());
293 if (!found_match && !substrings.empty()) {
294 fprintf(stdout, "\n No modules matched: use -help\n");
298 void ShowUsageWithFlagsRestrict(const char *argv0, const char *restrict) {
299 vector<string> substrings;
300 if (restrict != NULL && *restrict != '\0') {
301 substrings.push_back(restrict);
303 ShowUsageWithFlagsMatching(argv0, substrings);
306 void ShowUsageWithFlags(const char *argv0) {
307 ShowUsageWithFlagsRestrict(argv0, "");
310 // Convert the help, program, and usage to xml.
311 static void ShowXMLOfFlags(const char *prog_name) {
312 vector<CommandLineFlagInfo> flags;
313 GetAllFlags(&flags); // flags are sorted: by filename, then flagname
315 // XML. There is no corresponding schema yet
316 fprintf(stdout, "<?xml version=\"1.0\"?>\n");
318 fprintf(stdout, "<AllFlags>\n");
319 // the program name and usage
320 fprintf(stdout, "<program>%s</program>\n",
321 XMLText(Basename(prog_name)).c_str());
322 fprintf(stdout, "<usage>%s</usage>\n",
323 XMLText(ProgramUsage()).c_str());
325 for (vector<CommandLineFlagInfo>::const_iterator flag = flags.begin();
328 if (flag->description != kStrippedFlagHelp)
329 fprintf(stdout, "%s\n", DescribeOneFlagInXML(*flag).c_str());
331 // The end of the document
332 fprintf(stdout, "</AllFlags>\n");
335 // --------------------------------------------------------------------
337 // Called upon --version. Prints build-related info.
338 // --------------------------------------------------------------------
340 static void ShowVersion() {
341 const char* version_string = VersionString();
342 if (version_string && *version_string) {
343 fprintf(stdout, "%s version %s\n",
344 ProgramInvocationShortName(), version_string);
346 fprintf(stdout, "%s\n", ProgramInvocationShortName());
348 # if !defined(NDEBUG)
349 fprintf(stdout, "Debug build (NDEBUG not #defined)\n");
353 static void AppendPrognameStrings(vector<string>* substrings,
354 const char* progname) {
358 substrings->push_back(r + ".");
359 substrings->push_back(r + "-main.");
360 substrings->push_back(r + "_main.");
363 // --------------------------------------------------------------------
364 // HandleCommandLineHelpFlags()
365 // Checks all the 'reporting' commandline flags to see if any
366 // have been set. If so, handles them appropriately. Note
367 // that all of them, by definition, cause the program to exit
369 // --------------------------------------------------------------------
371 void HandleCommandLineHelpFlags() {
372 const char* progname = ProgramInvocationShortName();
374 HandleCommandLineCompletions();
376 vector<string> substrings;
377 AppendPrognameStrings(&substrings, progname);
379 if (FLAGS_helpshort) {
380 // show only flags related to this binary:
381 // E.g. for fileutil.cc, want flags containing ... "/fileutil." cc
382 ShowUsageWithFlagsMatching(progname, substrings);
385 } else if (FLAGS_help || FLAGS_helpfull) {
387 ShowUsageWithFlagsRestrict(progname, ""); // empty restrict
390 } else if (!FLAGS_helpon.empty()) {
391 string restrict = PATH_SEPARATOR + FLAGS_helpon + ".";
392 ShowUsageWithFlagsRestrict(progname, restrict.c_str());
395 } else if (!FLAGS_helpmatch.empty()) {
396 ShowUsageWithFlagsRestrict(progname, FLAGS_helpmatch.c_str());
399 } else if (FLAGS_helppackage) {
400 // Shows help for all files in the same directory as main(). We
401 // don't want to resort to looking at dirname(progname), because
402 // the user can pick progname, and it may not relate to the file
403 // where main() resides. So instead, we search the flags for a
404 // filename like "/progname.cc", and take the dirname of that.
405 vector<CommandLineFlagInfo> flags;
408 for (vector<CommandLineFlagInfo>::const_iterator flag = flags.begin();
411 if (!FileMatchesSubstring(flag->filename, substrings))
413 const string package = Dirname(flag->filename) + PATH_SEPARATOR;
414 if (package != last_package) {
415 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;
420 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;
428 } else if (FLAGS_helpxml) {
429 ShowXMLOfFlags(progname);
432 } else if (FLAGS_version) {
434 // Unlike help, we may be asking for version in a script, so return 0
441 } // namespace GFLAGS_NAMESPACE