Merge pull request #143 from schuhschuh/fix-bazel-bulid-osx
[platform/upstream/gflags.git] / src / gflags_reporting.cc
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.h"
60 #include "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
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
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.
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(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;
135       break;
136     }
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);
140       chars_left -= n + 1;
141       c_string += n + 1;
142     } else {
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]) ) {
146         --whitespace;
147       }
148       if (whitespace <= 0) {
149         // Couldn't find any whitespace to make a line break.  Just dump the
150         // rest out!
151         final_string += c_string;
152         chars_in_line = kLineLength;  // next part gets its own line for sure!
153         break;
154       }
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;
160     }
161     if (*c_string == '\0')
162       break;
163     StringAppendF(&final_string, "\n      ");
164     chars_in_line = 6;
165   }
166
167   // Append data type
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,
174             &chars_in_line);
175   if (!flag.is_default) {
176     AddString(PrintStringFlagsWithQuotes(flag, "currently", true),
177               &final_string, &chars_in_line);
178   }
179
180   StringAppendF(&final_string, "\n");
181   return final_string;
182 }
183
184 // Simple routine to xml-escape a string: escape & and < only.
185 static string XMLText(const string& txt) {
186   string ans = txt;
187   for (string::size_type pos = 0; (pos = ans.find("&", pos)) != string::npos; )
188     ans.replace(pos++, 1, "&amp;");
189   for (string::size_type pos = 0; (pos = ans.find("<", pos)) != string::npos; )
190     ans.replace(pos++, 1, "&lt;");
191   return ans;
192 }
193
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
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.
203   string r("<flag>");
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);
210   r += "</flag>";
211   return r;
212 }
213
214 // --------------------------------------------------------------------
215 // ShowUsageWithFlags()
216 // ShowUsageWithFlagsRestrict()
217 // ShowXMLOfFlags()
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 // --------------------------------------------------------------------
226
227 static const char* Basename(const char* filename) {
228   const char* sep = strrchr(filename, PATH_SEPARATOR);
229   return sep ? sep + 1 : filename;
230 }
231
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);
235 }
236
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();
242        ++target) {
243     if (strstr(filename.c_str(), target->c_str()) != NULL)
244       return true;
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)
252       return true;
253   }
254   return false;
255 }
256
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());
265
266   vector<CommandLineFlagInfo> flags;
267   GetAllFlags(&flags);           // flags are sorted by filename, then flagname
268
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();
273        flag != flags.end();
274        ++flag) {
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;
285         }
286         fprintf(stdout, "\n  Flags from %s:\n", flag->filename.c_str());
287         last_filename = flag->filename;
288       }
289       // Now print this flag
290       fprintf(stdout, "%s", DescribeOneFlag(*flag).c_str());
291     }
292   }
293   if (!found_match && !substrings.empty()) {
294     fprintf(stdout, "\n  No modules matched: use -help\n");
295   }
296 }
297
298 void ShowUsageWithFlagsRestrict(const char *argv0, const char *restrict) {
299   vector<string> substrings;
300   if (restrict != NULL && *restrict != '\0') {
301     substrings.push_back(restrict);
302   }
303   ShowUsageWithFlagsMatching(argv0, substrings);
304 }
305
306 void ShowUsageWithFlags(const char *argv0) {
307   ShowUsageWithFlagsRestrict(argv0, "");
308 }
309
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
314
315   // XML.  There is no corresponding schema yet
316   fprintf(stdout, "<?xml version=\"1.0\"?>\n");
317   // The document
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());
324   // All the flags
325   for (vector<CommandLineFlagInfo>::const_iterator flag = flags.begin();
326        flag != flags.end();
327        ++flag) {
328     if (flag->description != kStrippedFlagHelp)
329       fprintf(stdout, "%s\n", DescribeOneFlagInXML(*flag).c_str());
330   }
331   // The end of the document
332   fprintf(stdout, "</AllFlags>\n");
333 }
334
335 // --------------------------------------------------------------------
336 // ShowVersion()
337 //    Called upon --version.  Prints build-related info.
338 // --------------------------------------------------------------------
339
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);
345   } else {
346     fprintf(stdout, "%s\n", ProgramInvocationShortName());
347   }
348 # if !defined(NDEBUG)
349   fprintf(stdout, "Debug build (NDEBUG not #defined)\n");
350 # endif
351 }
352
353 static void AppendPrognameStrings(vector<string>* substrings,
354                                   const char* progname) {
355   string r("");
356   r += PATH_SEPARATOR;
357   r += progname;
358   substrings->push_back(r + ".");
359   substrings->push_back(r + "-main.");
360   substrings->push_back(r + "_main.");
361 }
362
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
368 //    if they trigger.
369 // --------------------------------------------------------------------
370
371 void HandleCommandLineHelpFlags() {
372   const char* progname = ProgramInvocationShortName();
373
374   HandleCommandLineCompletions();
375
376   vector<string> substrings;
377   AppendPrognameStrings(&substrings, progname);
378
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);
383     gflags_exitfunc(1);
384
385   } else if (FLAGS_help || FLAGS_helpfull) {
386     // show all options
387     ShowUsageWithFlagsRestrict(progname, "");   // empty restrict
388     gflags_exitfunc(1);
389
390   } else if (!FLAGS_helpon.empty()) {
391     string restrict = PATH_SEPARATOR + FLAGS_helpon + ".";
392     ShowUsageWithFlagsRestrict(progname, restrict.c_str());
393     gflags_exitfunc(1);
394
395   } else if (!FLAGS_helpmatch.empty()) {
396     ShowUsageWithFlagsRestrict(progname, FLAGS_helpmatch.c_str());
397     gflags_exitfunc(1);
398
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;
406     GetAllFlags(&flags);
407     string last_package;
408     for (vector<CommandLineFlagInfo>::const_iterator flag = flags.begin();
409          flag != flags.end();
410          ++flag) {
411       if (!FileMatchesSubstring(flag->filename, substrings))
412         continue;
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;
419         }
420         last_package = package;
421       }
422     }
423     if (last_package.empty()) {   // never found a package to print
424       LOG(WARNING) << "Unable to find a package for file=" << progname;
425     }
426     gflags_exitfunc(1);
427
428   } else if (FLAGS_helpxml) {
429     ShowXMLOfFlags(progname);
430     gflags_exitfunc(1);
431
432   } else if (FLAGS_version) {
433     ShowVersion();
434     // Unlike help, we may be asking for version in a script, so return 0
435     gflags_exitfunc(0);
436
437   }
438 }
439
440
441 } // namespace GFLAGS_NAMESPACE