1 // Copyright (c) 1999, Google Inc.
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
6 // met:
7 //
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
13 // distribution.
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.
17 //
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.
29 
30 // ---
31 //
32 // Revamped and reorganized by Craig Silverstein
33 //
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.
38 //
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.
44 //
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.
50 
51 #include <stdio.h>
52 #include <string.h>
53 #include <ctype.h>
54 #include <assert.h>
55 #include <string>
56 #include <vector>
57 
58 #include "config.h"
59 #include "gflags/gflags.h"
60 #include "gflags/gflags_completions.h"
61 #include "util.h"
62 
63 
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");
73 
74 
75 namespace GFLAGS_NAMESPACE {
76 
77 
78 using std::string;
79 using std::vector;
80 
81 
82 // --------------------------------------------------------------------
83 // DescribeOneFlag()
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 // --------------------------------------------------------------------
89 
90 static const int kLineLength = 80;
91 
AddString(const string & s,string * final_string,int * chars_in_line)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      ";
97     *chars_in_line = 6;
98   } else {
99     *final_string += " ";
100     *chars_in_line += 1;
101   }
102   *final_string += s;
103   *chars_in_line += slen;
104 }
105 
PrintStringFlagsWithQuotes(const CommandLineFlagInfo & flag,const string & text,bool current)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);
112   } else {
113     return StringPrintf("%s: %s", text.c_str(), c_string);
114   }
115 }
116 
117 // Create a descriptive string for a flag.
118 // Goes to some trouble to make pretty line breaks.
DescribeOneFlag(const CommandLineFlagInfo & flag)119 string DescribeOneFlag(const CommandLineFlagInfo& flag) {
120   string main_part;
121   SStringPrintf(&main_part, "    -%s (%s)",
122                 flag.name.c_str(),
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?
128   while (1) {
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;
136       break;
137     }
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);
141       chars_left -= n + 1;
142       c_string += n + 1;
143     } else {
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]) ) {
147         --whitespace;
148       }
149       if (whitespace <= 0) {
150         // Couldn't find any whitespace to make a line break.  Just dump the
151         // rest out!
152         final_string += c_string;
153         chars_in_line = kLineLength;  // next part gets its own line for sure!
154         break;
155       }
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;
161     }
162     if (*c_string == '\0')
163       break;
164     StringAppendF(&final_string, "\n      ");
165     chars_in_line = 6;
166   }
167 
168   // Append data type
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,
175             &chars_in_line);
176   if (!flag.is_default) {
177     AddString(PrintStringFlagsWithQuotes(flag, "currently", true),
178               &final_string, &chars_in_line);
179   }
180 
181   StringAppendF(&final_string, "\n");
182   return final_string;
183 }
184 
185 // Simple routine to xml-escape a string: escape & and < only.
XMLText(const string & txt)186 static string XMLText(const string& txt) {
187   string ans = txt;
188   for (string::size_type pos = 0; (pos = ans.find("&", pos)) != string::npos; )
189     ans.replace(pos++, 1, "&amp;");
190   for (string::size_type pos = 0; (pos = ans.find("<", pos)) != string::npos; )
191     ans.replace(pos++, 1, "&lt;");
192   return ans;
193 }
194 
AddXMLTag(string * r,const char * tag,const string & txt)195 static void AddXMLTag(string* r, const char* tag, const string& txt) {
196   StringAppendF(r, "<%s>%s</%s>", tag, XMLText(txt).c_str(), tag);
197 }
198 
199 
DescribeOneFlagInXML(const CommandLineFlagInfo & flag)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.
204   string r("<flag>");
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);
211   r += "</flag>";
212   return r;
213 }
214 
215 // --------------------------------------------------------------------
216 // ShowUsageWithFlags()
217 // ShowUsageWithFlagsRestrict()
218 // ShowXMLOfFlags()
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 // --------------------------------------------------------------------
227 
Basename(const char * filename)228 static const char* Basename(const char* filename) {
229   const char* sep = strrchr(filename, PATH_SEPARATOR);
230   return sep ? sep + 1 : filename;
231 }
232 
Dirname(const string & 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);
236 }
237 
238 // Test whether a filename contains at least one of the substrings.
FileMatchesSubstring(const string & filename,const vector<string> & 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();
243        ++target) {
244     if (strstr(filename.c_str(), target->c_str()) != NULL)
245       return true;
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)
253       return true;
254   }
255   return false;
256 }
257 
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.
ShowUsageWithFlagsMatching(const char * argv0,const vector<string> & substrings)263 static void ShowUsageWithFlagsMatching(const char *argv0,
264                                        const vector<string> &substrings) {
265   fprintf(stdout, "%s: %s\n", Basename(argv0), ProgramUsage());
266 
267   vector<CommandLineFlagInfo> flags;
268   GetAllFlags(&flags);           // flags are sorted by filename, then flagname
269 
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();
274        flag != flags.end();
275        ++flag) {
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;
286         }
287         fprintf(stdout, "\n  Flags from %s:\n", flag->filename.c_str());
288         last_filename = flag->filename;
289       }
290       // Now print this flag
291       fprintf(stdout, "%s", DescribeOneFlag(*flag).c_str());
292     }
293   }
294   if (!found_match && !substrings.empty()) {
295     fprintf(stdout, "\n  No modules matched: use -help\n");
296   }
297 }
298 
ShowUsageWithFlagsRestrict(const char * argv0,const char * restrict_)299 void ShowUsageWithFlagsRestrict(const char *argv0, const char *restrict_) {
300   vector<string> substrings;
301   if (restrict_ != NULL && *restrict_ != '\0') {
302     substrings.push_back(restrict_);
303   }
304   ShowUsageWithFlagsMatching(argv0, substrings);
305 }
306 
ShowUsageWithFlags(const char * argv0)307 void ShowUsageWithFlags(const char *argv0) {
308   ShowUsageWithFlagsRestrict(argv0, "");
309 }
310 
311 // Convert the help, program, and usage to xml.
ShowXMLOfFlags(const char * prog_name)312 static void ShowXMLOfFlags(const char *prog_name) {
313   vector<CommandLineFlagInfo> flags;
314   GetAllFlags(&flags);   // flags are sorted: by filename, then flagname
315 
316   // XML.  There is no corresponding schema yet
317   fprintf(stdout, "<?xml version=\"1.0\"?>\n");
318   // The document
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());
325   // All the flags
326   for (vector<CommandLineFlagInfo>::const_iterator flag = flags.begin();
327        flag != flags.end();
328        ++flag) {
329     if (flag->description != kStrippedFlagHelp)
330       fprintf(stdout, "%s\n", DescribeOneFlagInXML(*flag).c_str());
331   }
332   // The end of the document
333   fprintf(stdout, "</AllFlags>\n");
334 }
335 
336 // --------------------------------------------------------------------
337 // ShowVersion()
338 //    Called upon --version.  Prints build-related info.
339 // --------------------------------------------------------------------
340 
ShowVersion()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);
346   } else {
347     fprintf(stdout, "%s\n", ProgramInvocationShortName());
348   }
349 # if !defined(NDEBUG)
350   fprintf(stdout, "Debug build (NDEBUG not #defined)\n");
351 # endif
352 }
353 
AppendPrognameStrings(vector<string> * substrings,const char * progname)354 static void AppendPrognameStrings(vector<string>* substrings,
355                                   const char* progname) {
356   string r("");
357   r += PATH_SEPARATOR;
358   r += progname;
359   substrings->push_back(r + ".");
360   substrings->push_back(r + "-main.");
361   substrings->push_back(r + "_main.");
362 }
363 
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
369 //    if they trigger.
370 // --------------------------------------------------------------------
371 
HandleCommandLineHelpFlags()372 void HandleCommandLineHelpFlags() {
373   const char* progname = ProgramInvocationShortName();
374 
375   HandleCommandLineCompletions();
376 
377   vector<string> substrings;
378   AppendPrognameStrings(&substrings, progname);
379 
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);
384     gflags_exitfunc(1);
385 
386   } else if (FLAGS_help || FLAGS_helpfull) {
387     // show all options
388     ShowUsageWithFlagsRestrict(progname, "");   // empty restrict
389     gflags_exitfunc(1);
390 
391   } else if (!FLAGS_helpon.empty()) {
392     string restrict_ = PATH_SEPARATOR + FLAGS_helpon + ".";
393     ShowUsageWithFlagsRestrict(progname, restrict_.c_str());
394     gflags_exitfunc(1);
395 
396   } else if (!FLAGS_helpmatch.empty()) {
397     ShowUsageWithFlagsRestrict(progname, FLAGS_helpmatch.c_str());
398     gflags_exitfunc(1);
399 
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;
407     GetAllFlags(&flags);
408     string last_package;
409     for (vector<CommandLineFlagInfo>::const_iterator flag = flags.begin();
410          flag != flags.end();
411          ++flag) {
412       if (!FileMatchesSubstring(flag->filename, substrings))
413         continue;
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;
420         }
421         last_package = package;
422       }
423     }
424     if (last_package.empty()) {   // never found a package to print
425       LOG(WARNING) << "Unable to find a package for file=" << progname;
426     }
427     gflags_exitfunc(1);
428 
429   } else if (FLAGS_helpxml) {
430     ShowXMLOfFlags(progname);
431     gflags_exitfunc(1);
432 
433   } else if (FLAGS_version) {
434     ShowVersion();
435     // Unlike help, we may be asking for version in a script, so return 0
436     gflags_exitfunc(0);
437 
438   }
439 }
440 
441 
442 } // namespace GFLAGS_NAMESPACE
443