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.
59 #include "gflags/gflags.h"
60 #include "gflags/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(static_cast<size_t>(chars_left)
130 == strlen(c_string)); // Unless there's a \0 in there?
131 const char* newline = strchr(c_string, '\n');
132 if (newline == NULL && chars_in_line+chars_left < kLineLength) {
133 // The whole remainder of the string fits on this line
134 final_string += c_string;
135 chars_in_line += chars_left;
138 if (newline != NULL && newline - c_string < kLineLength - chars_in_line) {
139 int n = static_cast<int>(newline - c_string);
140 final_string.append(c_string, n);
144 // Find the last whitespace on this 80-char line
145 int whitespace = kLineLength-chars_in_line-1; // < 80 chars/line
146 while ( whitespace > 0 && !isspace(c_string[whitespace]) ) {
149 if (whitespace <= 0) {
150 // Couldn't find any whitespace to make a line break. Just dump the
152 final_string += c_string;
153 chars_in_line = kLineLength; // next part gets its own line for sure!
156 final_string += string(c_string, whitespace);
157 chars_in_line += whitespace;
158 while (isspace(c_string[whitespace])) ++whitespace;
159 c_string += whitespace;
160 chars_left -= whitespace;
162 if (*c_string == '\0')
164 StringAppendF(&final_string, "\n ");
169 AddString(string("type: ") + flag.type, &final_string, &chars_in_line);
170 // The listed default value will be the actual default from the flag
171 // definition in the originating source file, unless the value has
172 // subsequently been modified using SetCommandLineOptionWithMode() with mode
173 // SET_FLAGS_DEFAULT, or by setting FLAGS_foo = bar before ParseCommandLineFlags().
174 AddString(PrintStringFlagsWithQuotes(flag, "default", false), &final_string,
176 if (!flag.is_default) {
177 AddString(PrintStringFlagsWithQuotes(flag, "currently", true),
178 &final_string, &chars_in_line);
181 StringAppendF(&final_string, "\n");
185 // Simple routine to xml-escape a string: escape & and < only.
186 static string XMLText(const string& txt) {
188 for (string::size_type pos = 0; (pos = ans.find("&", pos)) != string::npos; )
189 ans.replace(pos++, 1, "&");
190 for (string::size_type pos = 0; (pos = ans.find("<", pos)) != string::npos; )
191 ans.replace(pos++, 1, "<");
195 static void AddXMLTag(string* r, const char* tag, const string& txt) {
196 StringAppendF(r, "<%s>%s</%s>", tag, XMLText(txt).c_str(), tag);
200 static string DescribeOneFlagInXML(const CommandLineFlagInfo& flag) {
201 // The file and flagname could have been attributes, but default
202 // and meaning need to avoid attribute normalization. This way it
203 // can be parsed by simple programs, in addition to xml parsers.
205 AddXMLTag(&r, "file", flag.filename);
206 AddXMLTag(&r, "name", flag.name);
207 AddXMLTag(&r, "meaning", flag.description);
208 AddXMLTag(&r, "default", flag.default_value);
209 AddXMLTag(&r, "current", flag.current_value);
210 AddXMLTag(&r, "type", flag.type);
215 // --------------------------------------------------------------------
216 // ShowUsageWithFlags()
217 // ShowUsageWithFlagsRestrict()
219 // These routines variously expose the registry's list of flag
220 // values. ShowUsage*() prints the flag-value information
221 // to stdout in a user-readable format (that's what --help uses).
222 // The Restrict() version limits what flags are shown.
223 // ShowXMLOfFlags() prints the flag-value information to stdout
224 // in a machine-readable format. In all cases, the flags are
225 // sorted: first by filename they are defined in, then by flagname.
226 // --------------------------------------------------------------------
228 static const char* Basename(const char* filename) {
229 const char* sep = strrchr(filename, PATH_SEPARATOR);
230 return sep ? sep + 1 : filename;
233 static string Dirname(const string& filename) {
234 string::size_type sep = filename.rfind(PATH_SEPARATOR);
235 return filename.substr(0, (sep == string::npos) ? 0 : sep);
238 // Test whether a filename contains at least one of the substrings.
239 static bool FileMatchesSubstring(const string& filename,
240 const vector<string>& substrings) {
241 for (vector<string>::const_iterator target = substrings.begin();
242 target != substrings.end();
244 if (strstr(filename.c_str(), target->c_str()) != NULL)
246 // If the substring starts with a '/', that means that we want
247 // the string to be at the beginning of a directory component.
248 // That should match the first directory component as well, so
249 // we allow '/foo' to match a filename of 'foo'.
250 if (!target->empty() && (*target)[0] == PATH_SEPARATOR &&
251 strncmp(filename.c_str(), target->c_str() + 1,
252 strlen(target->c_str() + 1)) == 0)
258 // Show help for every filename which matches any of the target substrings.
259 // If substrings is empty, shows help for every file. If a flag's help message
260 // has been stripped (e.g. by adding '#define STRIP_FLAG_HELP 1'
261 // before including gflags/gflags.h), then this flag will not be displayed
262 // by '--help' and its variants.
263 static void ShowUsageWithFlagsMatching(const char *argv0,
264 const vector<string> &substrings) {
265 fprintf(stdout, "%s: %s\n", Basename(argv0), ProgramUsage());
267 vector<CommandLineFlagInfo> flags;
268 GetAllFlags(&flags); // flags are sorted by filename, then flagname
270 string last_filename; // so we know when we're at a new file
271 bool first_directory = true; // controls blank lines between dirs
272 bool found_match = false; // stays false iff no dir matches restrict
273 for (vector<CommandLineFlagInfo>::const_iterator flag = flags.begin();
276 if (substrings.empty() ||
277 FileMatchesSubstring(flag->filename, substrings)) {
278 // If the flag has been stripped, pretend that it doesn't exist.
279 if (flag->description == kStrippedFlagHelp) continue;
280 found_match = true; // this flag passed the match!
281 if (flag->filename != last_filename) { // new file
282 if (Dirname(flag->filename) != Dirname(last_filename)) { // new dir!
283 if (!first_directory)
284 fprintf(stdout, "\n\n"); // put blank lines between directories
285 first_directory = false;
287 fprintf(stdout, "\n Flags from %s:\n", flag->filename.c_str());
288 last_filename = flag->filename;
290 // Now print this flag
291 fprintf(stdout, "%s", DescribeOneFlag(*flag).c_str());
294 if (!found_match && !substrings.empty()) {
295 fprintf(stdout, "\n No modules matched: use -help\n");
299 void ShowUsageWithFlagsRestrict(const char *argv0, const char *restrict) {
300 vector<string> substrings;
301 if (restrict != NULL && *restrict != '\0') {
302 substrings.push_back(restrict);
304 ShowUsageWithFlagsMatching(argv0, substrings);
307 void ShowUsageWithFlags(const char *argv0) {
308 ShowUsageWithFlagsRestrict(argv0, "");
311 // Convert the help, program, and usage to xml.
312 static void ShowXMLOfFlags(const char *prog_name) {
313 vector<CommandLineFlagInfo> flags;
314 GetAllFlags(&flags); // flags are sorted: by filename, then flagname
316 // XML. There is no corresponding schema yet
317 fprintf(stdout, "<?xml version=\"1.0\"?>\n");
319 fprintf(stdout, "<AllFlags>\n");
320 // the program name and usage
321 fprintf(stdout, "<program>%s</program>\n",
322 XMLText(Basename(prog_name)).c_str());
323 fprintf(stdout, "<usage>%s</usage>\n",
324 XMLText(ProgramUsage()).c_str());
326 for (vector<CommandLineFlagInfo>::const_iterator flag = flags.begin();
329 if (flag->description != kStrippedFlagHelp)
330 fprintf(stdout, "%s\n", DescribeOneFlagInXML(*flag).c_str());
332 // The end of the document
333 fprintf(stdout, "</AllFlags>\n");
336 // --------------------------------------------------------------------
338 // Called upon --version. Prints build-related info.
339 // --------------------------------------------------------------------
341 static void ShowVersion() {
342 const char* version_string = VersionString();
343 if (version_string && *version_string) {
344 fprintf(stdout, "%s version %s\n",
345 ProgramInvocationShortName(), version_string);
347 fprintf(stdout, "%s\n", ProgramInvocationShortName());
349 # if !defined(NDEBUG)
350 fprintf(stdout, "Debug build (NDEBUG not #defined)\n");
354 static void AppendPrognameStrings(vector<string>* substrings,
355 const char* progname) {
359 substrings->push_back(r + ".");
360 substrings->push_back(r + "-main.");
361 substrings->push_back(r + "_main.");
364 // --------------------------------------------------------------------
365 // HandleCommandLineHelpFlags()
366 // Checks all the 'reporting' commandline flags to see if any
367 // have been set. If so, handles them appropriately. Note
368 // that all of them, by definition, cause the program to exit
370 // --------------------------------------------------------------------
372 void HandleCommandLineHelpFlags() {
373 const char* progname = ProgramInvocationShortName();
375 HandleCommandLineCompletions();
377 vector<string> substrings;
378 AppendPrognameStrings(&substrings, progname);
380 if (FLAGS_helpshort) {
381 // show only flags related to this binary:
382 // E.g. for fileutil.cc, want flags containing ... "/fileutil." cc
383 ShowUsageWithFlagsMatching(progname, substrings);
386 } else if (FLAGS_help || FLAGS_helpfull) {
388 ShowUsageWithFlagsRestrict(progname, ""); // empty restrict
391 } else if (!FLAGS_helpon.empty()) {
392 string restrict = PATH_SEPARATOR + FLAGS_helpon + ".";
393 ShowUsageWithFlagsRestrict(progname, restrict.c_str());
396 } else if (!FLAGS_helpmatch.empty()) {
397 ShowUsageWithFlagsRestrict(progname, FLAGS_helpmatch.c_str());
400 } else if (FLAGS_helppackage) {
401 // Shows help for all files in the same directory as main(). We
402 // don't want to resort to looking at dirname(progname), because
403 // the user can pick progname, and it may not relate to the file
404 // where main() resides. So instead, we search the flags for a
405 // filename like "/progname.cc", and take the dirname of that.
406 vector<CommandLineFlagInfo> flags;
409 for (vector<CommandLineFlagInfo>::const_iterator flag = flags.begin();
412 if (!FileMatchesSubstring(flag->filename, substrings))
414 const string package = Dirname(flag->filename) + PATH_SEPARATOR;
415 if (package != last_package) {
416 ShowUsageWithFlagsRestrict(progname, package.c_str());
417 VLOG(7) << "Found package: " << package;
418 if (!last_package.empty()) { // means this isn't our first pkg
419 LOG(WARNING) << "Multiple packages contain a file=" << progname;
421 last_package = package;
424 if (last_package.empty()) { // never found a package to print
425 LOG(WARNING) << "Unable to find a package for file=" << progname;
429 } else if (FLAGS_helpxml) {
430 ShowXMLOfFlags(progname);
433 } else if (FLAGS_version) {
435 // Unlike help, we may be asking for version in a script, so return 0
442 } // namespace GFLAGS_NAMESPACE