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 <config.h>
52 #include <stdio.h>
53 #include <string.h>
54 #include <ctype.h>
55 #include <assert.h>
56 #include <string>
57 #include <vector>
58 #include <gflags/gflags.h>
59 #include <gflags/gflags_completions.h>
60 #include "util.h"
61 
62 #ifndef PATH_SEPARATOR
63 #define PATH_SEPARATOR  '/'
64 #endif
65 
66 // The 'reporting' flags.  They all call gflags_exitfunc().
67 DEFINE_bool(help, false,
68             "show help on all flags [tip: all flags can have two dashes]");
69 DEFINE_bool(helpfull, false,
70             "show help on all flags -- same as -help");
71 DEFINE_bool(helpshort, false,
72             "show help on only the main module for this program");
73 DEFINE_string(helpon, "",
74               "show help on the modules named by this flag value");
75 DEFINE_string(helpmatch, "",
76               "show help on modules whose name contains the specified substr");
77 DEFINE_bool(helppackage, false,
78             "show help on all modules in the main package");
79 DEFINE_bool(helpxml, false,
80             "produce an xml version of help");
81 DEFINE_bool(version, false,
82             "show version and build info and exit");
83 
84 _START_GOOGLE_NAMESPACE_
85 
86 using std::string;
87 using std::vector;
88 
89 
90 // --------------------------------------------------------------------
91 // DescribeOneFlag()
92 // DescribeOneFlagInXML()
93 //    Routines that pretty-print info about a flag.  These use
94 //    a CommandLineFlagInfo, which is the way the gflags
95 //    API exposes static info about a flag.
96 // --------------------------------------------------------------------
97 
98 static const int kLineLength = 80;
99 
AddString(const string & s,string * final_string,int * chars_in_line)100 static void AddString(const string& s,
101                       string* final_string, int* chars_in_line) {
102   const int slen = static_cast<int>(s.length());
103   if (*chars_in_line + 1 + slen >= kLineLength) {  // < 80 chars/line
104     *final_string += "\n      ";
105     *chars_in_line = 6;
106   } else {
107     *final_string += " ";
108     *chars_in_line += 1;
109   }
110   *final_string += s;
111   *chars_in_line += slen;
112 }
113 
PrintStringFlagsWithQuotes(const CommandLineFlagInfo & flag,const string & text,bool current)114 static string PrintStringFlagsWithQuotes(const CommandLineFlagInfo& flag,
115                                          const string& text, bool current) {
116   const char* c_string = (current ? flag.current_value.c_str() :
117                           flag.default_value.c_str());
118   if (strcmp(flag.type.c_str(), "string") == 0) {  // add quotes for strings
119     return StringPrintf("%s: \"%s\"", text.c_str(), c_string);
120   } else {
121     return StringPrintf("%s: %s", text.c_str(), c_string);
122   }
123 }
124 
125 // Create a descriptive string for a flag.
126 // Goes to some trouble to make pretty line breaks.
DescribeOneFlag(const CommandLineFlagInfo & flag)127 string DescribeOneFlag(const CommandLineFlagInfo& flag) {
128   string main_part;
129   SStringPrintf(&main_part, "    -%s (%s)",
130                 flag.name.c_str(),
131                 flag.description.c_str());
132   const char* c_string = main_part.c_str();
133   int chars_left = static_cast<int>(main_part.length());
134   string final_string = "";
135   int chars_in_line = 0;  // how many chars in current line so far?
136   while (1) {
137     assert(chars_left == strlen(c_string));  // Unless there's a \0 in there?
138     const char* newline = strchr(c_string, '\n');
139     if (newline == NULL && chars_in_line+chars_left < kLineLength) {
140       // The whole remainder of the string fits on this line
141       final_string += c_string;
142       chars_in_line += chars_left;
143       break;
144     }
145     if (newline != NULL && newline - c_string < kLineLength - chars_in_line) {
146       int n = static_cast<int>(newline - c_string);
147       final_string.append(c_string, n);
148       chars_left -= n + 1;
149       c_string += n + 1;
150     } else {
151       // Find the last whitespace on this 80-char line
152       int whitespace = kLineLength-chars_in_line-1;  // < 80 chars/line
153       while ( whitespace > 0 && !isspace(c_string[whitespace]) ) {
154         --whitespace;
155       }
156       if (whitespace <= 0) {
157         // Couldn't find any whitespace to make a line break.  Just dump the
158         // rest out!
159         final_string += c_string;
160         chars_in_line = kLineLength;  // next part gets its own line for sure!
161         break;
162       }
163       final_string += string(c_string, whitespace);
164       chars_in_line += whitespace;
165       while (isspace(c_string[whitespace]))  ++whitespace;
166       c_string += whitespace;
167       chars_left -= whitespace;
168     }
169     if (*c_string == '\0')
170       break;
171     StringAppendF(&final_string, "\n      ");
172     chars_in_line = 6;
173   }
174 
175   // Append data type
176   AddString(string("type: ") + flag.type, &final_string, &chars_in_line);
177   // The listed default value will be the actual default from the flag
178   // definition in the originating source file, unless the value has
179   // subsequently been modified using SetCommandLineOptionWithMode() with mode
180   // SET_FLAGS_DEFAULT, or by setting FLAGS_foo = bar before ParseCommandLineFlags().
181   AddString(PrintStringFlagsWithQuotes(flag, "default", false), &final_string,
182             &chars_in_line);
183   if (!flag.is_default) {
184     AddString(PrintStringFlagsWithQuotes(flag, "currently", true),
185               &final_string, &chars_in_line);
186   }
187 
188   StringAppendF(&final_string, "\n");
189   return final_string;
190 }
191 
192 // Simple routine to xml-escape a string: escape & and < only.
XMLText(const string & txt)193 static string XMLText(const string& txt) {
194   string ans = txt;
195   for (string::size_type pos = 0; (pos = ans.find("&", pos)) != string::npos; )
196     ans.replace(pos++, 1, "&amp;");
197   for (string::size_type pos = 0; (pos = ans.find("<", pos)) != string::npos; )
198     ans.replace(pos++, 1, "&lt;");
199   return ans;
200 }
201 
AddXMLTag(string * r,const char * tag,const string & txt)202 static void AddXMLTag(string* r, const char* tag, const string& txt) {
203   StringAppendF(r, "<%s>%s</%s>", tag, XMLText(txt).c_str(), tag);
204 }
205 
206 
DescribeOneFlagInXML(const CommandLineFlagInfo & flag)207 static string DescribeOneFlagInXML(const CommandLineFlagInfo& flag) {
208   // The file and flagname could have been attributes, but default
209   // and meaning need to avoid attribute normalization.  This way it
210   // can be parsed by simple programs, in addition to xml parsers.
211   string r("<flag>");
212   AddXMLTag(&r, "file", flag.filename);
213   AddXMLTag(&r, "name", flag.name);
214   AddXMLTag(&r, "meaning", flag.description);
215   AddXMLTag(&r, "default", flag.default_value);
216   AddXMLTag(&r, "current", flag.current_value);
217   AddXMLTag(&r, "type", flag.type);
218   r += "</flag>";
219   return r;
220 }
221 
222 // --------------------------------------------------------------------
223 // ShowUsageWithFlags()
224 // ShowUsageWithFlagsRestrict()
225 // ShowXMLOfFlags()
226 //    These routines variously expose the registry's list of flag
227 //    values.  ShowUsage*() prints the flag-value information
228 //    to stdout in a user-readable format (that's what --help uses).
229 //    The Restrict() version limits what flags are shown.
230 //    ShowXMLOfFlags() prints the flag-value information to stdout
231 //    in a machine-readable format.  In all cases, the flags are
232 //    sorted: first by filename they are defined in, then by flagname.
233 // --------------------------------------------------------------------
234 
Basename(const char * filename)235 static const char* Basename(const char* filename) {
236   const char* sep = strrchr(filename, PATH_SEPARATOR);
237   return sep ? sep + 1 : filename;
238 }
239 
Dirname(const string & filename)240 static string Dirname(const string& filename) {
241   string::size_type sep = filename.rfind(PATH_SEPARATOR);
242   return filename.substr(0, (sep == string::npos) ? 0 : sep);
243 }
244 
245 // Test whether a filename contains at least one of the substrings.
FileMatchesSubstring(const string & filename,const vector<string> & substrings)246 static bool FileMatchesSubstring(const string& filename,
247                                  const vector<string>& substrings) {
248   for (vector<string>::const_iterator target = substrings.begin();
249        target != substrings.end();
250        ++target) {
251     if (strstr(filename.c_str(), target->c_str()) != NULL)
252       return true;
253     // If the substring starts with a '/', that means that we want
254     // the string to be at the beginning of a directory component.
255     // That should match the first directory component as well, so
256     // we allow '/foo' to match a filename of 'foo'.
257     if (!target->empty() && (*target)[0] == '/' &&
258         strncmp(filename.c_str(), target->c_str() + 1,
259                 strlen(target->c_str() + 1)) == 0)
260       return true;
261   }
262   return false;
263 }
264 
265 // Show help for every filename which matches any of the target substrings.
266 // If substrings is empty, shows help for every file. If a flag's help message
267 // has been stripped (e.g. by adding '#define STRIP_FLAG_HELP 1'
268 // before including gflags/gflags.h), then this flag will not be displayed
269 // by '--help' and its variants.
ShowUsageWithFlagsMatching(const char * argv0,const vector<string> & substrings)270 static void ShowUsageWithFlagsMatching(const char *argv0,
271                                        const vector<string> &substrings) {
272   fprintf(stdout, "%s: %s\n", Basename(argv0), ProgramUsage());
273 
274   vector<CommandLineFlagInfo> flags;
275   GetAllFlags(&flags);           // flags are sorted by filename, then flagname
276 
277   string last_filename;          // so we know when we're at a new file
278   bool first_directory = true;   // controls blank lines between dirs
279   bool found_match = false;      // stays false iff no dir matches restrict
280   for (vector<CommandLineFlagInfo>::const_iterator flag = flags.begin();
281        flag != flags.end();
282        ++flag) {
283     if (substrings.empty() ||
284         FileMatchesSubstring(flag->filename, substrings)) {
285       // If the flag has been stripped, pretend that it doesn't exist.
286       if (flag->description == kStrippedFlagHelp) continue;
287       found_match = true;     // this flag passed the match!
288       if (flag->filename != last_filename) {                      // new file
289         if (Dirname(flag->filename) != Dirname(last_filename)) {  // new dir!
290           if (!first_directory)
291             fprintf(stdout, "\n\n");   // put blank lines between directories
292           first_directory = false;
293         }
294         fprintf(stdout, "\n  Flags from %s:\n", flag->filename.c_str());
295         last_filename = flag->filename;
296       }
297       // Now print this flag
298       fprintf(stdout, "%s", DescribeOneFlag(*flag).c_str());
299     }
300   }
301   if (!found_match && !substrings.empty()) {
302     fprintf(stdout, "\n  No modules matched: use -help\n");
303   }
304 }
305 
ShowUsageWithFlagsRestrict(const char * argv0,const char * restrict)306 void ShowUsageWithFlagsRestrict(const char *argv0, const char *restrict) {
307   vector<string> substrings;
308   if (restrict != NULL && *restrict != '\0') {
309     substrings.push_back(restrict);
310   }
311   ShowUsageWithFlagsMatching(argv0, substrings);
312 }
313 
ShowUsageWithFlags(const char * argv0)314 void ShowUsageWithFlags(const char *argv0) {
315   ShowUsageWithFlagsRestrict(argv0, "");
316 }
317 
318 // Convert the help, program, and usage to xml.
ShowXMLOfFlags(const char * prog_name)319 static void ShowXMLOfFlags(const char *prog_name) {
320   vector<CommandLineFlagInfo> flags;
321   GetAllFlags(&flags);   // flags are sorted: by filename, then flagname
322 
323   // XML.  There is no corresponding schema yet
324   fprintf(stdout, "<?xml version=\"1.0\"?>\n");
325   // The document
326   fprintf(stdout, "<AllFlags>\n");
327   // the program name and usage
328   fprintf(stdout, "<program>%s</program>\n",
329           XMLText(Basename(prog_name)).c_str());
330   fprintf(stdout, "<usage>%s</usage>\n",
331           XMLText(ProgramUsage()).c_str());
332   // All the flags
333   for (vector<CommandLineFlagInfo>::const_iterator flag = flags.begin();
334        flag != flags.end();
335        ++flag) {
336     if (flag->description != kStrippedFlagHelp)
337       fprintf(stdout, "%s\n", DescribeOneFlagInXML(*flag).c_str());
338   }
339   // The end of the document
340   fprintf(stdout, "</AllFlags>\n");
341 }
342 
343 // --------------------------------------------------------------------
344 // ShowVersion()
345 //    Called upon --version.  Prints build-related info.
346 // --------------------------------------------------------------------
347 
ShowVersion()348 static void ShowVersion() {
349   const char* version_string = VersionString();
350   if (version_string && *version_string) {
351     fprintf(stdout, "%s version %s\n",
352             ProgramInvocationShortName(), version_string);
353   } else {
354     fprintf(stdout, "%s\n", ProgramInvocationShortName());
355   }
356 # if !defined(NDEBUG)
357   fprintf(stdout, "Debug build (NDEBUG not #defined)\n");
358 # endif
359 }
360 
AppendPrognameStrings(vector<string> * substrings,const char * progname)361 static void AppendPrognameStrings(vector<string>* substrings,
362                                   const char* progname) {
363   string r("/");
364   r += progname;
365   substrings->push_back(r + ".");
366   substrings->push_back(r + "-main.");
367   substrings->push_back(r + "_main.");
368 }
369 
370 // --------------------------------------------------------------------
371 // HandleCommandLineHelpFlags()
372 //    Checks all the 'reporting' commandline flags to see if any
373 //    have been set.  If so, handles them appropriately.  Note
374 //    that all of them, by definition, cause the program to exit
375 //    if they trigger.
376 // --------------------------------------------------------------------
377 
HandleCommandLineHelpFlags()378 void HandleCommandLineHelpFlags() {
379   const char* progname = ProgramInvocationShortName();
380 
381   HandleCommandLineCompletions();
382 
383   vector<string> substrings;
384   AppendPrognameStrings(&substrings, progname);
385 
386   if (FLAGS_helpshort) {
387     // show only flags related to this binary:
388     // E.g. for fileutil.cc, want flags containing   ... "/fileutil." cc
389     ShowUsageWithFlagsMatching(progname, substrings);
390     gflags_exitfunc(1);
391 
392   } else if (FLAGS_help || FLAGS_helpfull) {
393     // show all options
394     ShowUsageWithFlagsRestrict(progname, "");   // empty restrict
395     gflags_exitfunc(1);
396 
397   } else if (!FLAGS_helpon.empty()) {
398     string restrict = "/" + FLAGS_helpon + ".";
399     ShowUsageWithFlagsRestrict(progname, restrict.c_str());
400     gflags_exitfunc(1);
401 
402   } else if (!FLAGS_helpmatch.empty()) {
403     ShowUsageWithFlagsRestrict(progname, FLAGS_helpmatch.c_str());
404     gflags_exitfunc(1);
405 
406   } else if (FLAGS_helppackage) {
407     // Shows help for all files in the same directory as main().  We
408     // don't want to resort to looking at dirname(progname), because
409     // the user can pick progname, and it may not relate to the file
410     // where main() resides.  So instead, we search the flags for a
411     // filename like "/progname.cc", and take the dirname of that.
412     vector<CommandLineFlagInfo> flags;
413     GetAllFlags(&flags);
414     string last_package;
415     for (vector<CommandLineFlagInfo>::const_iterator flag = flags.begin();
416          flag != flags.end();
417          ++flag) {
418       if (!FileMatchesSubstring(flag->filename, substrings))
419         continue;
420       const string package = Dirname(flag->filename) + "/";
421       if (package != last_package) {
422         ShowUsageWithFlagsRestrict(progname, package.c_str());
423         VLOG(7) << "Found package: " << package;
424         if (!last_package.empty()) {      // means this isn't our first pkg
425           LOG(WARNING) << "Multiple packages contain a file=" << progname;
426         }
427         last_package = package;
428       }
429     }
430     if (last_package.empty()) {   // never found a package to print
431       LOG(WARNING) << "Unable to find a package for file=" << progname;
432     }
433     gflags_exitfunc(1);
434 
435   } else if (FLAGS_helpxml) {
436     ShowXMLOfFlags(progname);
437     gflags_exitfunc(1);
438 
439   } else if (FLAGS_version) {
440     ShowVersion();
441     // Unlike help, we may be asking for version in a script, so return 0
442     gflags_exitfunc(0);
443 
444   }
445 }
446 
447 _END_GOOGLE_NAMESPACE_
448