Add gflags for commandline flags processing.
gflags configuration files are fetched from webrtc: https://code.google.com/p/webrtc/source/browse/trunk/third_party/gflags gflags source is cloned from https://github.com/schuhschuh/gflags Change-Id: Ieb544990278b542decd2a25e6c24fc93cc5e3228
This commit is contained in:
parent
0f3056b551
commit
cde567c14c
|
@ -0,0 +1,28 @@
|
|||
Copyright (c) 2006, Google Inc.
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are
|
||||
met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above
|
||||
copyright notice, this list of conditions and the following disclaimer
|
||||
in the documentation and/or other materials provided with the
|
||||
distribution.
|
||||
* Neither the name of Google Inc. nor the names of its
|
||||
contributors may be used to endorse or promote products derived from
|
||||
this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
@ -0,0 +1,27 @@
|
|||
URL: http://code.google.com/p/gflags/
|
||||
Version: 2.0
|
||||
License: New BSD
|
||||
License File: LICENSE
|
||||
|
||||
Description:
|
||||
The gflags package contains a library that implements commandline
|
||||
flags processing. As such it's a replacement for getopt(). It has
|
||||
increased flexibility, including built-in support for C++ types like
|
||||
string, and the ability to define flags in the source file in which
|
||||
they're used.
|
||||
|
||||
Local Modifications: None
|
||||
|
||||
Refer to README.webrtc on how to update platform configuration files.
|
||||
|
||||
A brief description of the source files:
|
||||
|
||||
README.packager: this file.
|
||||
|
||||
Files under src/:
|
||||
Cloned from https://github.com/schuhschuh/gflags
|
||||
SHA eb92d6edceb2bfde33cb1b6e1c74a432b63017e7.
|
||||
|
||||
All other files:
|
||||
Fetched from webrtc:
|
||||
https://code.google.com/p/webrtc/source/browse/trunk/third_party/gflags r5342.
|
|
@ -0,0 +1,28 @@
|
|||
URL: http://code.google.com/p/gflags/
|
||||
Version: 2.0
|
||||
License: New BSD
|
||||
License File: LICENSE
|
||||
|
||||
Description:
|
||||
The gflags package contains a library that implements commandline
|
||||
flags processing. As such it's a replacement for getopt(). It has
|
||||
increased flexibility, including built-in support for C++ types like
|
||||
string, and the ability to define flags in the source file in which
|
||||
they're used.
|
||||
|
||||
Local Modifications: None
|
||||
|
||||
|
||||
How to update platform configuration files:
|
||||
The gen/ directory contains pre-generated configuration header files.
|
||||
Historically, all operating systems and architectures have generated
|
||||
similar configurations except for Windows. This is why there's only
|
||||
posix and win directories below gen/.
|
||||
When rolling gflags to a newer version, it's a good idea to check if
|
||||
new configuration files needs to be generated as well.
|
||||
Do this by running ./configure in the newly checked out version of
|
||||
gflags. Then diff the generated files with the ones below gen/.
|
||||
If you notice a diff, update the files with the updated ones.
|
||||
If you suspect platform dependend changes other than Windows, you'll
|
||||
have to checkout gflags on the other platforms as well and run
|
||||
./configure there too.
|
|
@ -0,0 +1,592 @@
|
|||
// Copyright (c) 2006, Google Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following disclaimer
|
||||
// in the documentation and/or other materials provided with the
|
||||
// distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from
|
||||
// this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
// ---
|
||||
// Author: Ray Sidney
|
||||
// Revamped and reorganized by Craig Silverstein
|
||||
//
|
||||
// This is the file that should be included by any file which declares
|
||||
// or defines a command line flag or wants to parse command line flags
|
||||
// or print a program usage message (which will include information about
|
||||
// flags). Executive summary, in the form of an example foo.cc file:
|
||||
//
|
||||
// #include "foo.h" // foo.h has a line "DECLARE_int32(start);"
|
||||
// #include "validators.h" // hypothetical file defining ValidateIsFile()
|
||||
//
|
||||
// DEFINE_int32(end, 1000, "The last record to read");
|
||||
//
|
||||
// DEFINE_string(filename, "my_file.txt", "The file to read");
|
||||
// // Crash if the specified file does not exist.
|
||||
// static bool dummy = RegisterFlagValidator(&FLAGS_filename,
|
||||
// &ValidateIsFile);
|
||||
//
|
||||
// DECLARE_bool(verbose); // some other file has a DEFINE_bool(verbose, ...)
|
||||
//
|
||||
// void MyFunc() {
|
||||
// if (FLAGS_verbose) printf("Records %d-%d\n", FLAGS_start, FLAGS_end);
|
||||
// }
|
||||
//
|
||||
// Then, at the command-line:
|
||||
// ./foo --noverbose --start=5 --end=100
|
||||
//
|
||||
// For more details, see
|
||||
// doc/gflags.html
|
||||
//
|
||||
// --- A note about thread-safety:
|
||||
//
|
||||
// We describe many functions in this routine as being thread-hostile,
|
||||
// thread-compatible, or thread-safe. Here are the meanings we use:
|
||||
//
|
||||
// thread-safe: it is safe for multiple threads to call this routine
|
||||
// (or, when referring to a class, methods of this class)
|
||||
// concurrently.
|
||||
// thread-hostile: it is not safe for multiple threads to call this
|
||||
// routine (or methods of this class) concurrently. In gflags,
|
||||
// most thread-hostile routines are intended to be called early in,
|
||||
// or even before, main() -- that is, before threads are spawned.
|
||||
// thread-compatible: it is safe for multiple threads to read from
|
||||
// this variable (when applied to variables), or to call const
|
||||
// methods of this class (when applied to classes), as long as no
|
||||
// other thread is writing to the variable or calling non-const
|
||||
// methods of this class.
|
||||
|
||||
#ifndef GOOGLE_GFLAGS_H_
|
||||
#define GOOGLE_GFLAGS_H_
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
// We care a lot about number of bits things take up. Unfortunately,
|
||||
// systems define their bit-specific ints in a lot of different ways.
|
||||
// We use our own way, and have a typedef to get there.
|
||||
// Note: these commands below may look like "#if 1" or "#if 0", but
|
||||
// that's because they were constructed that way at ./configure time.
|
||||
// Look at gflags.h.in to see how they're calculated (based on your config).
|
||||
#if 1
|
||||
#include <stdint.h> // the normal place uint16_t is defined
|
||||
#endif
|
||||
#if 1
|
||||
#include <sys/types.h> // the normal place u_int16_t is defined
|
||||
#endif
|
||||
#if 1
|
||||
#include <inttypes.h> // a third place for uint16_t or u_int16_t
|
||||
#endif
|
||||
|
||||
namespace google {
|
||||
|
||||
#if 1 // the C99 format
|
||||
typedef int32_t int32;
|
||||
typedef uint32_t uint32;
|
||||
typedef int64_t int64;
|
||||
typedef uint64_t uint64;
|
||||
#elif 1 // the BSD format
|
||||
typedef int32_t int32;
|
||||
typedef u_int32_t uint32;
|
||||
typedef int64_t int64;
|
||||
typedef u_int64_t uint64;
|
||||
#elif 0 // the windows (vc7) format
|
||||
typedef __int32 int32;
|
||||
typedef unsigned __int32 uint32;
|
||||
typedef __int64 int64;
|
||||
typedef unsigned __int64 uint64;
|
||||
#else
|
||||
#error Do not know how to define a 32-bit integer quantity on your system
|
||||
#endif
|
||||
|
||||
// TODO(kjellander): update generated .h's for new gflags.
|
||||
// https://code.google.com/p/webrtc/issues/detail?id=2251
|
||||
extern const char* VersionString();
|
||||
extern void SetVersionString(const std::string& version);
|
||||
|
||||
// --------------------------------------------------------------------
|
||||
// To actually define a flag in a file, use DEFINE_bool,
|
||||
// DEFINE_string, etc. at the bottom of this file. You may also find
|
||||
// it useful to register a validator with the flag. This ensures that
|
||||
// when the flag is parsed from the commandline, or is later set via
|
||||
// SetCommandLineOption, we call the validation function. It is _not_
|
||||
// called when you assign the value to the flag directly using the = operator.
|
||||
//
|
||||
// The validation function should return true if the flag value is valid, and
|
||||
// false otherwise. If the function returns false for the new setting of the
|
||||
// flag, the flag will retain its current value. If it returns false for the
|
||||
// default value, ParseCommandLineFlags() will die.
|
||||
//
|
||||
// This function is safe to call at global construct time (as in the
|
||||
// example below).
|
||||
//
|
||||
// Example use:
|
||||
// static bool ValidatePort(const char* flagname, int32 value) {
|
||||
// if (value > 0 && value < 32768) // value is ok
|
||||
// return true;
|
||||
// printf("Invalid value for --%s: %d\n", flagname, (int)value);
|
||||
// return false;
|
||||
// }
|
||||
// DEFINE_int32(port, 0, "What port to listen on");
|
||||
// static bool dummy = RegisterFlagValidator(&FLAGS_port, &ValidatePort);
|
||||
|
||||
// Returns true if successfully registered, false if not (because the
|
||||
// first argument doesn't point to a command-line flag, or because a
|
||||
// validator is already registered for this flag).
|
||||
bool RegisterFlagValidator(const bool* flag,
|
||||
bool (*validate_fn)(const char*, bool));
|
||||
bool RegisterFlagValidator(const int32* flag,
|
||||
bool (*validate_fn)(const char*, int32));
|
||||
bool RegisterFlagValidator(const int64* flag,
|
||||
bool (*validate_fn)(const char*, int64));
|
||||
bool RegisterFlagValidator(const uint64* flag,
|
||||
bool (*validate_fn)(const char*, uint64));
|
||||
bool RegisterFlagValidator(const double* flag,
|
||||
bool (*validate_fn)(const char*, double));
|
||||
bool RegisterFlagValidator(const std::string* flag,
|
||||
bool (*validate_fn)(const char*, const std::string&));
|
||||
|
||||
|
||||
// --------------------------------------------------------------------
|
||||
// These methods are the best way to get access to info about the
|
||||
// list of commandline flags. Note that these routines are pretty slow.
|
||||
// GetAllFlags: mostly-complete info about the list, sorted by file.
|
||||
// ShowUsageWithFlags: pretty-prints the list to stdout (what --help does)
|
||||
// ShowUsageWithFlagsRestrict: limit to filenames with restrict as a substr
|
||||
//
|
||||
// In addition to accessing flags, you can also access argv[0] (the program
|
||||
// name) and argv (the entire commandline), which we sock away a copy of.
|
||||
// These variables are static, so you should only set them once.
|
||||
|
||||
struct CommandLineFlagInfo {
|
||||
std::string name; // the name of the flag
|
||||
std::string type; // the type of the flag: int32, etc
|
||||
std::string description; // the "help text" associated with the flag
|
||||
std::string current_value; // the current value, as a string
|
||||
std::string default_value; // the default value, as a string
|
||||
std::string filename; // 'cleaned' version of filename holding the flag
|
||||
bool has_validator_fn; // true if RegisterFlagValidator called on flag
|
||||
bool is_default; // true if the flag has the default value and
|
||||
// has not been set explicitly from the cmdline
|
||||
// or via SetCommandLineOption
|
||||
const void* flag_ptr;
|
||||
|
||||
};
|
||||
|
||||
// Using this inside of a validator is a recipe for a deadlock.
|
||||
// TODO(wojtekm) Fix locking when validators are running, to make it safe to
|
||||
// call validators during ParseAllFlags.
|
||||
// Also make sure then to uncomment the corresponding unit test in
|
||||
// commandlineflags_unittest.sh
|
||||
extern void GetAllFlags(std::vector<CommandLineFlagInfo>* OUTPUT);
|
||||
// These two are actually defined in commandlineflags_reporting.cc.
|
||||
extern void ShowUsageWithFlags(const char *argv0); // what --help does
|
||||
extern void ShowUsageWithFlagsRestrict(const char *argv0, const char *restrict);
|
||||
|
||||
// Create a descriptive string for a flag.
|
||||
// Goes to some trouble to make pretty line breaks.
|
||||
extern std::string DescribeOneFlag(const CommandLineFlagInfo& flag);
|
||||
|
||||
// Thread-hostile; meant to be called before any threads are spawned.
|
||||
extern void SetArgv(int argc, const char** argv);
|
||||
// The following functions are thread-safe as long as SetArgv() is
|
||||
// only called before any threads start.
|
||||
extern const std::vector<std::string>& GetArgvs(); // all of argv as a vector
|
||||
extern const char* GetArgv(); // all of argv as a string
|
||||
extern const char* GetArgv0(); // only argv0
|
||||
extern uint32 GetArgvSum(); // simple checksum of argv
|
||||
extern const char* ProgramInvocationName(); // argv0, or "UNKNOWN" if not set
|
||||
extern const char* ProgramInvocationShortName(); // basename(argv0)
|
||||
// ProgramUsage() is thread-safe as long as SetUsageMessage() is only
|
||||
// called before any threads start.
|
||||
extern const char* ProgramUsage(); // string set by SetUsageMessage()
|
||||
|
||||
|
||||
// --------------------------------------------------------------------
|
||||
// Normally you access commandline flags by just saying "if (FLAGS_foo)"
|
||||
// or whatever, and set them by calling "FLAGS_foo = bar" (or, more
|
||||
// commonly, via the DEFINE_foo macro). But if you need a bit more
|
||||
// control, we have programmatic ways to get/set the flags as well.
|
||||
// These programmatic ways to access flags are thread-safe, but direct
|
||||
// access is only thread-compatible.
|
||||
|
||||
// Return true iff the flagname was found.
|
||||
// OUTPUT is set to the flag's value, or unchanged if we return false.
|
||||
extern bool GetCommandLineOption(const char* name, std::string* OUTPUT);
|
||||
|
||||
// Return true iff the flagname was found. OUTPUT is set to the flag's
|
||||
// CommandLineFlagInfo or unchanged if we return false.
|
||||
extern bool GetCommandLineFlagInfo(const char* name,
|
||||
CommandLineFlagInfo* OUTPUT);
|
||||
|
||||
// Return the CommandLineFlagInfo of the flagname. exit() if name not found.
|
||||
// Example usage, to check if a flag's value is currently the default value:
|
||||
// if (GetCommandLineFlagInfoOrDie("foo").is_default) ...
|
||||
extern CommandLineFlagInfo GetCommandLineFlagInfoOrDie(const char* name);
|
||||
|
||||
enum FlagSettingMode {
|
||||
// update the flag's value (can call this multiple times).
|
||||
SET_FLAGS_VALUE,
|
||||
// update the flag's value, but *only if* it has not yet been updated
|
||||
// with SET_FLAGS_VALUE, SET_FLAG_IF_DEFAULT, or "FLAGS_xxx = nondef".
|
||||
SET_FLAG_IF_DEFAULT,
|
||||
// set the flag's default value to this. If the flag has not yet updated
|
||||
// yet (via SET_FLAGS_VALUE, SET_FLAG_IF_DEFAULT, or "FLAGS_xxx = nondef")
|
||||
// change the flag's current value to the new default value as well.
|
||||
SET_FLAGS_DEFAULT
|
||||
};
|
||||
|
||||
// Set a particular flag ("command line option"). Returns a string
|
||||
// describing the new value that the option has been set to. The
|
||||
// return value API is not well-specified, so basically just depend on
|
||||
// it to be empty if the setting failed for some reason -- the name is
|
||||
// not a valid flag name, or the value is not a valid value -- and
|
||||
// non-empty else.
|
||||
|
||||
// SetCommandLineOption uses set_mode == SET_FLAGS_VALUE (the common case)
|
||||
extern std::string SetCommandLineOption(const char* name, const char* value);
|
||||
extern std::string SetCommandLineOptionWithMode(const char* name, const char* value,
|
||||
FlagSettingMode set_mode);
|
||||
|
||||
|
||||
// --------------------------------------------------------------------
|
||||
// Saves the states (value, default value, whether the user has set
|
||||
// the flag, registered validators, etc) of all flags, and restores
|
||||
// them when the FlagSaver is destroyed. This is very useful in
|
||||
// tests, say, when you want to let your tests change the flags, but
|
||||
// make sure that they get reverted to the original states when your
|
||||
// test is complete.
|
||||
//
|
||||
// Example usage:
|
||||
// void TestFoo() {
|
||||
// FlagSaver s1;
|
||||
// FLAG_foo = false;
|
||||
// FLAG_bar = "some value";
|
||||
//
|
||||
// // test happens here. You can return at any time
|
||||
// // without worrying about restoring the FLAG values.
|
||||
// }
|
||||
//
|
||||
// Note: This class is marked with __attribute__((unused)) because all the
|
||||
// work is done in the constructor and destructor, so in the standard
|
||||
// usage example above, the compiler would complain that it's an
|
||||
// unused variable.
|
||||
//
|
||||
// This class is thread-safe.
|
||||
|
||||
class FlagSaver {
|
||||
public:
|
||||
FlagSaver();
|
||||
~FlagSaver();
|
||||
|
||||
private:
|
||||
class FlagSaverImpl* impl_; // we use pimpl here to keep API steady
|
||||
|
||||
FlagSaver(const FlagSaver&); // no copying!
|
||||
void operator=(const FlagSaver&);
|
||||
} __attribute__ ((unused));
|
||||
|
||||
// --------------------------------------------------------------------
|
||||
// Some deprecated or hopefully-soon-to-be-deprecated functions.
|
||||
|
||||
// This is often used for logging. TODO(csilvers): figure out a better way
|
||||
extern std::string CommandlineFlagsIntoString();
|
||||
// Usually where this is used, a FlagSaver should be used instead.
|
||||
extern bool ReadFlagsFromString(const std::string& flagfilecontents,
|
||||
const char* prog_name,
|
||||
bool errors_are_fatal); // uses SET_FLAGS_VALUE
|
||||
|
||||
// These let you manually implement --flagfile functionality.
|
||||
// DEPRECATED.
|
||||
extern bool AppendFlagsIntoFile(const std::string& filename, const char* prog_name);
|
||||
extern bool SaveCommandFlags(); // actually defined in google.cc !
|
||||
extern bool ReadFromFlagsFile(const std::string& filename, const char* prog_name,
|
||||
bool errors_are_fatal); // uses SET_FLAGS_VALUE
|
||||
|
||||
|
||||
// --------------------------------------------------------------------
|
||||
// Useful routines for initializing flags from the environment.
|
||||
// In each case, if 'varname' does not exist in the environment
|
||||
// return defval. If 'varname' does exist but is not valid
|
||||
// (e.g., not a number for an int32 flag), abort with an error.
|
||||
// Otherwise, return the value. NOTE: for booleans, for true use
|
||||
// 't' or 'T' or 'true' or '1', for false 'f' or 'F' or 'false' or '0'.
|
||||
|
||||
extern bool BoolFromEnv(const char *varname, bool defval);
|
||||
extern int32 Int32FromEnv(const char *varname, int32 defval);
|
||||
extern int64 Int64FromEnv(const char *varname, int64 defval);
|
||||
extern uint64 Uint64FromEnv(const char *varname, uint64 defval);
|
||||
extern double DoubleFromEnv(const char *varname, double defval);
|
||||
extern const char *StringFromEnv(const char *varname, const char *defval);
|
||||
|
||||
|
||||
// --------------------------------------------------------------------
|
||||
// The next two functions parse commandlineflags from main():
|
||||
|
||||
// Set the "usage" message for this program. For example:
|
||||
// string usage("This program does nothing. Sample usage:\n");
|
||||
// usage += argv[0] + " <uselessarg1> <uselessarg2>";
|
||||
// SetUsageMessage(usage);
|
||||
// Do not include commandline flags in the usage: we do that for you!
|
||||
// Thread-hostile; meant to be called before any threads are spawned.
|
||||
extern void SetUsageMessage(const std::string& usage);
|
||||
|
||||
// Looks for flags in argv and parses them. Rearranges argv to put
|
||||
// flags first, or removes them entirely if remove_flags is true.
|
||||
// If a flag is defined more than once in the command line or flag
|
||||
// file, the last definition is used. Returns the index (into argv)
|
||||
// of the first non-flag argument.
|
||||
// See top-of-file for more details on this function.
|
||||
#ifndef SWIG // In swig, use ParseCommandLineFlagsScript() instead.
|
||||
extern uint32 ParseCommandLineFlags(int *argc, char*** argv,
|
||||
bool remove_flags);
|
||||
#endif
|
||||
|
||||
|
||||
// Calls to ParseCommandLineNonHelpFlags and then to
|
||||
// HandleCommandLineHelpFlags can be used instead of a call to
|
||||
// ParseCommandLineFlags during initialization, in order to allow for
|
||||
// changing default values for some FLAGS (via
|
||||
// e.g. SetCommandLineOptionWithMode calls) between the time of
|
||||
// command line parsing and the time of dumping help information for
|
||||
// the flags as a result of command line parsing. If a flag is
|
||||
// defined more than once in the command line or flag file, the last
|
||||
// definition is used. Returns the index (into argv) of the first
|
||||
// non-flag argument. (If remove_flags is true, will always return 1.)
|
||||
extern uint32 ParseCommandLineNonHelpFlags(int *argc, char*** argv,
|
||||
bool remove_flags);
|
||||
// This is actually defined in commandlineflags_reporting.cc.
|
||||
// This function is misnamed (it also handles --version, etc.), but
|
||||
// it's too late to change that now. :-(
|
||||
extern void HandleCommandLineHelpFlags(); // in commandlineflags_reporting.cc
|
||||
|
||||
// Allow command line reparsing. Disables the error normally
|
||||
// generated when an unknown flag is found, since it may be found in a
|
||||
// later parse. Thread-hostile; meant to be called before any threads
|
||||
// are spawned.
|
||||
extern void AllowCommandLineReparsing();
|
||||
|
||||
// Reparse the flags that have not yet been recognized. Only flags
|
||||
// registered since the last parse will be recognized. Any flag value
|
||||
// must be provided as part of the argument using "=", not as a
|
||||
// separate command line argument that follows the flag argument.
|
||||
// Intended for handling flags from dynamically loaded libraries,
|
||||
// since their flags are not registered until they are loaded.
|
||||
// Returns the index (into the original argv) of the first non-flag
|
||||
// argument. (If remove_flags is true, will always return 1.)
|
||||
extern void ReparseCommandLineNonHelpFlags();
|
||||
|
||||
// Clean up memory allocated by flags. This is only needed to reduce
|
||||
// the quantity of "potentially leaked" reports emitted by memory
|
||||
// debugging tools such as valgrind. It is not required for normal
|
||||
// operation, or for the perftools heap-checker. It must only be called
|
||||
// when the process is about to exit, and all threads that might
|
||||
// access flags are quiescent. Referencing flags after this is called
|
||||
// will have unexpected consequences. This is not safe to run when
|
||||
// multiple threads might be running: the function is thread-hostile.
|
||||
extern void ShutDownCommandLineFlags();
|
||||
|
||||
|
||||
// --------------------------------------------------------------------
|
||||
// Now come the command line flag declaration/definition macros that
|
||||
// will actually be used. They're kind of hairy. A major reason
|
||||
// for this is initialization: we want people to be able to access
|
||||
// variables in global constructors and have that not crash, even if
|
||||
// their global constructor runs before the global constructor here.
|
||||
// (Obviously, we can't guarantee the flags will have the correct
|
||||
// default value in that case, but at least accessing them is safe.)
|
||||
// The only way to do that is have flags point to a static buffer.
|
||||
// So we make one, using a union to ensure proper alignment, and
|
||||
// then use placement-new to actually set up the flag with the
|
||||
// correct default value. In the same vein, we have to worry about
|
||||
// flag access in global destructors, so FlagRegisterer has to be
|
||||
// careful never to destroy the flag-values it constructs.
|
||||
//
|
||||
// Note that when we define a flag variable FLAGS_<name>, we also
|
||||
// preemptively define a junk variable, FLAGS_no<name>. This is to
|
||||
// cause a link-time error if someone tries to define 2 flags with
|
||||
// names like "logging" and "nologging". We do this because a bool
|
||||
// flag FLAG can be set from the command line to true with a "-FLAG"
|
||||
// argument, and to false with a "-noFLAG" argument, and so this can
|
||||
// potentially avert confusion.
|
||||
//
|
||||
// We also put flags into their own namespace. It is purposefully
|
||||
// named in an opaque way that people should have trouble typing
|
||||
// directly. The idea is that DEFINE puts the flag in the weird
|
||||
// namespace, and DECLARE imports the flag from there into the current
|
||||
// namespace. The net result is to force people to use DECLARE to get
|
||||
// access to a flag, rather than saying "extern bool FLAGS_whatever;"
|
||||
// or some such instead. We want this so we can put extra
|
||||
// functionality (like sanity-checking) in DECLARE if we want, and
|
||||
// make sure it is picked up everywhere.
|
||||
//
|
||||
// We also put the type of the variable in the namespace, so that
|
||||
// people can't DECLARE_int32 something that they DEFINE_bool'd
|
||||
// elsewhere.
|
||||
|
||||
class FlagRegisterer {
|
||||
public:
|
||||
FlagRegisterer(const char* name, const char* type,
|
||||
const char* help, const char* filename,
|
||||
void* current_storage, void* defvalue_storage);
|
||||
};
|
||||
|
||||
extern bool FlagsTypeWarn(const char *name);
|
||||
|
||||
// If your application #defines STRIP_FLAG_HELP to a non-zero value
|
||||
// before #including this file, we remove the help message from the
|
||||
// binary file. This can reduce the size of the resulting binary
|
||||
// somewhat, and may also be useful for security reasons.
|
||||
|
||||
extern const char kStrippedFlagHelp[];
|
||||
|
||||
}
|
||||
|
||||
#ifndef SWIG // In swig, ignore the main flag declarations
|
||||
|
||||
#if defined(STRIP_FLAG_HELP) && STRIP_FLAG_HELP > 0
|
||||
// Need this construct to avoid the 'defined but not used' warning.
|
||||
#define MAYBE_STRIPPED_HELP(txt) (false ? (txt) : ::google::kStrippedFlagHelp)
|
||||
#else
|
||||
#define MAYBE_STRIPPED_HELP(txt) txt
|
||||
#endif
|
||||
|
||||
// Each command-line flag has two variables associated with it: one
|
||||
// with the current value, and one with the default value. However,
|
||||
// we have a third variable, which is where value is assigned; it's a
|
||||
// constant. This guarantees that FLAG_##value is initialized at
|
||||
// static initialization time (e.g. before program-start) rather than
|
||||
// than global construction time (which is after program-start but
|
||||
// before main), at least when 'value' is a compile-time constant. We
|
||||
// use a small trick for the "default value" variable, and call it
|
||||
// FLAGS_no<name>. This serves the second purpose of assuring a
|
||||
// compile error if someone tries to define a flag named no<name>
|
||||
// which is illegal (--foo and --nofoo both affect the "foo" flag).
|
||||
#define DEFINE_VARIABLE(type, shorttype, name, value, help) \
|
||||
namespace fL##shorttype { \
|
||||
static const type FLAGS_nono##name = value; \
|
||||
type FLAGS_##name = FLAGS_nono##name; \
|
||||
type FLAGS_no##name = FLAGS_nono##name; \
|
||||
static ::google::FlagRegisterer o_##name( \
|
||||
#name, #type, MAYBE_STRIPPED_HELP(help), __FILE__, \
|
||||
&FLAGS_##name, &FLAGS_no##name); \
|
||||
} \
|
||||
using fL##shorttype::FLAGS_##name
|
||||
|
||||
#define DECLARE_VARIABLE(type, shorttype, name) \
|
||||
namespace fL##shorttype { \
|
||||
extern type FLAGS_##name; \
|
||||
} \
|
||||
using fL##shorttype::FLAGS_##name
|
||||
|
||||
// For DEFINE_bool, we want to do the extra check that the passed-in
|
||||
// value is actually a bool, and not a string or something that can be
|
||||
// coerced to a bool. These declarations (no definition needed!) will
|
||||
// help us do that, and never evaluate From, which is important.
|
||||
// We'll use 'sizeof(IsBool(val))' to distinguish. This code requires
|
||||
// that the compiler have different sizes for bool & double. Since
|
||||
// this is not guaranteed by the standard, we check it with a
|
||||
// compile-time assert (msg[-1] will give a compile-time error).
|
||||
namespace fLB {
|
||||
struct CompileAssert {};
|
||||
typedef CompileAssert expected_sizeof_double_neq_sizeof_bool[
|
||||
(sizeof(double) != sizeof(bool)) ? 1 : -1];
|
||||
template<typename From> double IsBoolFlag(const From& from);
|
||||
bool IsBoolFlag(bool from);
|
||||
} // namespace fLB
|
||||
|
||||
#define DECLARE_bool(name) DECLARE_VARIABLE(bool, B, name)
|
||||
#define DEFINE_bool(name, val, txt) \
|
||||
namespace fLB { \
|
||||
typedef ::fLB::CompileAssert FLAG_##name##_value_is_not_a_bool[ \
|
||||
(sizeof(::fLB::IsBoolFlag(val)) != sizeof(double)) ? 1 : -1]; \
|
||||
} \
|
||||
DEFINE_VARIABLE(bool, B, name, val, txt)
|
||||
|
||||
#define DECLARE_int32(name) DECLARE_VARIABLE(::google::int32, I, name)
|
||||
#define DEFINE_int32(name,val,txt) DEFINE_VARIABLE(::google::int32, I, name, val, txt)
|
||||
|
||||
#define DECLARE_int64(name) DECLARE_VARIABLE(::google::int64, I64, name)
|
||||
#define DEFINE_int64(name,val,txt) DEFINE_VARIABLE(::google::int64, I64, name, val, txt)
|
||||
|
||||
#define DECLARE_uint64(name) DECLARE_VARIABLE(::google::uint64, U64, name)
|
||||
#define DEFINE_uint64(name,val,txt) DEFINE_VARIABLE(::google::uint64, U64, name, val, txt)
|
||||
|
||||
#define DECLARE_double(name) DECLARE_VARIABLE(double, D, name)
|
||||
#define DEFINE_double(name, val, txt) DEFINE_VARIABLE(double, D, name, val, txt)
|
||||
|
||||
// Strings are trickier, because they're not a POD, so we can't
|
||||
// construct them at static-initialization time (instead they get
|
||||
// constructed at global-constructor time, which is much later). To
|
||||
// try to avoid crashes in that case, we use a char buffer to store
|
||||
// the string, which we can static-initialize, and then placement-new
|
||||
// into it later. It's not perfect, but the best we can do.
|
||||
|
||||
namespace fLS {
|
||||
// The meaning of "string" might be different between now and when the
|
||||
// macros below get invoked (e.g., if someone is experimenting with
|
||||
// other string implementations that get defined after this file is
|
||||
// included). Save the current meaning now and use it in the macros.
|
||||
typedef std::string clstring;
|
||||
|
||||
inline clstring* dont_pass0toDEFINE_string(char *stringspot,
|
||||
const char *value) {
|
||||
return new(stringspot) clstring(value);
|
||||
}
|
||||
inline clstring* dont_pass0toDEFINE_string(char *stringspot,
|
||||
const clstring &value) {
|
||||
return new(stringspot) clstring(value);
|
||||
}
|
||||
inline clstring* dont_pass0toDEFINE_string(char *stringspot,
|
||||
int value);
|
||||
} // namespace fLS
|
||||
|
||||
#define DECLARE_string(name) namespace fLS { extern ::fLS::clstring& FLAGS_##name; } \
|
||||
using fLS::FLAGS_##name
|
||||
|
||||
// We need to define a var named FLAGS_no##name so people don't define
|
||||
// --string and --nostring. And we need a temporary place to put val
|
||||
// so we don't have to evaluate it twice. Two great needs that go
|
||||
// great together!
|
||||
// The weird 'using' + 'extern' inside the fLS namespace is to work around
|
||||
// an unknown compiler bug/issue with the gcc 4.2.1 on SUSE 10. See
|
||||
// http://code.google.com/p/google-gflags/issues/detail?id=20
|
||||
#define DEFINE_string(name, val, txt) \
|
||||
namespace fLS { \
|
||||
using ::fLS::clstring; \
|
||||
static union { void* align; char s[sizeof(clstring)]; } s_##name[2]; \
|
||||
clstring* const FLAGS_no##name = ::fLS:: \
|
||||
dont_pass0toDEFINE_string(s_##name[0].s, \
|
||||
val); \
|
||||
static ::google::FlagRegisterer o_##name( \
|
||||
#name, "string", MAYBE_STRIPPED_HELP(txt), __FILE__, \
|
||||
s_##name[0].s, new (s_##name[1].s) clstring(*FLAGS_no##name)); \
|
||||
extern clstring& FLAGS_##name; \
|
||||
using fLS::FLAGS_##name; \
|
||||
clstring& FLAGS_##name = *FLAGS_no##name; \
|
||||
} \
|
||||
using fLS::FLAGS_##name
|
||||
|
||||
#endif // SWIG
|
||||
|
||||
#endif // GOOGLE_GFLAGS_H_
|
|
@ -0,0 +1,121 @@
|
|||
// Copyright (c) 2008, Google Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following disclaimer
|
||||
// in the documentation and/or other materials provided with the
|
||||
// distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from
|
||||
// this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
//
|
||||
// ---
|
||||
// Author: Dave Nicponski
|
||||
//
|
||||
// Implement helpful bash-style command line flag completions
|
||||
//
|
||||
// ** Functional API:
|
||||
// HandleCommandLineCompletions() should be called early during
|
||||
// program startup, but after command line flag code has been
|
||||
// initialized, such as the beginning of HandleCommandLineHelpFlags().
|
||||
// It checks the value of the flag --tab_completion_word. If this
|
||||
// flag is empty, nothing happens here. If it contains a string,
|
||||
// however, then HandleCommandLineCompletions() will hijack the
|
||||
// process, attempting to identify the intention behind this
|
||||
// completion. Regardless of the outcome of this deduction, the
|
||||
// process will be terminated, similar to --helpshort flag
|
||||
// handling.
|
||||
//
|
||||
// ** Overview of Bash completions:
|
||||
// Bash can be told to programatically determine completions for the
|
||||
// current 'cursor word'. It does this by (in this case) invoking a
|
||||
// command with some additional arguments identifying the command
|
||||
// being executed, the word being completed, and the previous word
|
||||
// (if any). Bash then expects a sequence of output lines to be
|
||||
// printed to stdout. If these lines all contain a common prefix
|
||||
// longer than the cursor word, bash will replace the cursor word
|
||||
// with that common prefix, and display nothing. If there isn't such
|
||||
// a common prefix, bash will display the lines in pages using 'more'.
|
||||
//
|
||||
// ** Strategy taken for command line completions:
|
||||
// If we can deduce either the exact flag intended, or a common flag
|
||||
// prefix, we'll output exactly that. Otherwise, if information
|
||||
// must be displayed to the user, we'll take the opportunity to add
|
||||
// some helpful information beyond just the flag name (specifically,
|
||||
// we'll include the default flag value and as much of the flag's
|
||||
// description as can fit on a single terminal line width, as specified
|
||||
// by the flag --tab_completion_columns). Furthermore, we'll try to
|
||||
// make bash order the output such that the most useful or relevent
|
||||
// flags are the most likely to be shown at the top.
|
||||
//
|
||||
// ** Additional features:
|
||||
// To assist in finding that one really useful flag, substring matching
|
||||
// was implemented. Before pressing a <TAB> to get completion for the
|
||||
// current word, you can append one or more '?' to the flag to do
|
||||
// substring matching. Here's the semantics:
|
||||
// --foo<TAB> Show me all flags with names prefixed by 'foo'
|
||||
// --foo?<TAB> Show me all flags with 'foo' somewhere in the name
|
||||
// --foo??<TAB> Same as prior case, but also search in module
|
||||
// definition path for 'foo'
|
||||
// --foo???<TAB> Same as prior case, but also search in flag
|
||||
// descriptions for 'foo'
|
||||
// Finally, we'll trim the output to a relatively small number of
|
||||
// flags to keep bash quiet about the verbosity of output. If one
|
||||
// really wanted to see all possible matches, appending a '+' to the
|
||||
// search word will force the exhaustive list of matches to be printed.
|
||||
//
|
||||
// ** How to have bash accept completions from a binary:
|
||||
// Bash requires that it be informed about each command that programmatic
|
||||
// completion should be enabled for. Example addition to a .bashrc
|
||||
// file would be (your path to gflags_completions.sh file may differ):
|
||||
|
||||
/*
|
||||
$ complete -o bashdefault -o default -o nospace -C \
|
||||
'/usr/local/bin/gflags_completions.sh --tab_completion_columns $COLUMNS' \
|
||||
time env binary_name another_binary [...]
|
||||
*/
|
||||
|
||||
// This would allow the following to work:
|
||||
// $ /path/to/binary_name --vmodule<TAB>
|
||||
// Or:
|
||||
// $ ./bin/path/another_binary --gfs_u<TAB>
|
||||
// (etc)
|
||||
//
|
||||
// Sadly, it appears that bash gives no easy way to force this behavior for
|
||||
// all commands. That's where the "time" in the above example comes in.
|
||||
// If you haven't specifically added a command to the list of completion
|
||||
// supported commands, you can still get completions by prefixing the
|
||||
// entire command with "env".
|
||||
// $ env /some/brand/new/binary --vmod<TAB>
|
||||
// Assuming that "binary" is a newly compiled binary, this should still
|
||||
// produce the expected completion output.
|
||||
|
||||
|
||||
#ifndef GOOGLE_GFLAGS_COMPLETIONS_H_
|
||||
#define GOOGLE_GFLAGS_COMPLETIONS_H_
|
||||
|
||||
namespace google {
|
||||
|
||||
void HandleCommandLineCompletions(void);
|
||||
|
||||
}
|
||||
|
||||
#endif // GOOGLE_GFLAGS_COMPLETIONS_H_
|
|
@ -0,0 +1,110 @@
|
|||
/* src/config.h. Generated from config.h.in by configure. */
|
||||
/* src/config.h.in. Generated from configure.ac by autoheader. */
|
||||
|
||||
/* Always the empty-string on non-windows systems. On windows, should be
|
||||
"__declspec(dllexport)". This way, when we compile the dll, we export our
|
||||
functions/classes. It's safe to define this here because config.h is only
|
||||
used internally, to compile the DLL, and every DLL source file #includes
|
||||
"config.h" before anything else. */
|
||||
#define GFLAGS_DLL_DECL /**/
|
||||
|
||||
/* Namespace for Google classes */
|
||||
#define GOOGLE_NAMESPACE ::google
|
||||
|
||||
/* Define to 1 if you have the <dlfcn.h> header file. */
|
||||
#define HAVE_DLFCN_H 1
|
||||
|
||||
/* Define to 1 if you have the <fnmatch.h> header file. */
|
||||
#define HAVE_FNMATCH_H 1
|
||||
|
||||
/* Define to 1 if you have the <inttypes.h> header file. */
|
||||
#define HAVE_INTTYPES_H 1
|
||||
|
||||
/* Define to 1 if you have the <memory.h> header file. */
|
||||
#define HAVE_MEMORY_H 1
|
||||
|
||||
/* define if the compiler implements namespaces */
|
||||
#define HAVE_NAMESPACES 1
|
||||
|
||||
/* Define if you have POSIX threads libraries and header files. */
|
||||
#define HAVE_PTHREAD 1
|
||||
|
||||
/* Define to 1 if you have the `putenv' function. */
|
||||
#define HAVE_PUTENV 1
|
||||
|
||||
/* Define to 1 if you have the `setenv' function. */
|
||||
#define HAVE_SETENV 1
|
||||
|
||||
/* Define to 1 if you have the <stdint.h> header file. */
|
||||
#define HAVE_STDINT_H 1
|
||||
|
||||
/* Define to 1 if you have the <stdlib.h> header file. */
|
||||
#define HAVE_STDLIB_H 1
|
||||
|
||||
/* Define to 1 if you have the <strings.h> header file. */
|
||||
#define HAVE_STRINGS_H 1
|
||||
|
||||
/* Define to 1 if you have the <string.h> header file. */
|
||||
#define HAVE_STRING_H 1
|
||||
|
||||
/* Define to 1 if you have the `strtoll' function. */
|
||||
#define HAVE_STRTOLL 1
|
||||
|
||||
/* Define to 1 if you have the `strtoq' function. */
|
||||
#define HAVE_STRTOQ 1
|
||||
|
||||
/* Define to 1 if you have the <sys/stat.h> header file. */
|
||||
#define HAVE_SYS_STAT_H 1
|
||||
|
||||
/* Define to 1 if you have the <sys/types.h> header file. */
|
||||
#define HAVE_SYS_TYPES_H 1
|
||||
|
||||
/* Define to 1 if you have the <unistd.h> header file. */
|
||||
#define HAVE_UNISTD_H 1
|
||||
|
||||
/* define if your compiler has __attribute__ */
|
||||
#define HAVE___ATTRIBUTE__ 1
|
||||
|
||||
/* Define to the sub-directory in which libtool stores uninstalled libraries.
|
||||
*/
|
||||
#define LT_OBJDIR ".libs/"
|
||||
|
||||
/* Name of package */
|
||||
#define PACKAGE "gflags"
|
||||
|
||||
/* Define to the address where bug reports for this package should be sent. */
|
||||
#define PACKAGE_BUGREPORT "opensource@google.com"
|
||||
|
||||
/* Define to the full name of this package. */
|
||||
#define PACKAGE_NAME "gflags"
|
||||
|
||||
/* Define to the full name and version of this package. */
|
||||
#define PACKAGE_STRING "gflags 1.5"
|
||||
|
||||
/* Define to the one symbol short name of this package. */
|
||||
#define PACKAGE_TARNAME "gflags"
|
||||
|
||||
/* Define to the home page for this package. */
|
||||
#define PACKAGE_URL ""
|
||||
|
||||
/* Define to the version of this package. */
|
||||
#define PACKAGE_VERSION "1.5"
|
||||
|
||||
/* Define to necessary symbol if this constant uses a non-standard name on
|
||||
your system. */
|
||||
/* #undef PTHREAD_CREATE_JOINABLE */
|
||||
|
||||
/* Define to 1 if you have the ANSI C header files. */
|
||||
#define STDC_HEADERS 1
|
||||
|
||||
/* the namespace where STL code like vector<> is defined */
|
||||
#define STL_NAMESPACE std
|
||||
|
||||
/* Version number of package */
|
||||
#define VERSION "1.5"
|
||||
|
||||
/* Stops putting the code inside the Google namespace */
|
||||
#define _END_GOOGLE_NAMESPACE_ }
|
||||
|
||||
/* Puts following code inside the Google namespace */
|
||||
#define _START_GOOGLE_NAMESPACE_ namespace google {
|
|
@ -0,0 +1,607 @@
|
|||
// Copyright (c) 2006, Google Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following disclaimer
|
||||
// in the documentation and/or other materials provided with the
|
||||
// distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from
|
||||
// this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
// ---
|
||||
// Author: Ray Sidney
|
||||
// Revamped and reorganized by Craig Silverstein
|
||||
//
|
||||
// This is the file that should be included by any file which declares
|
||||
// or defines a command line flag or wants to parse command line flags
|
||||
// or print a program usage message (which will include information about
|
||||
// flags). Executive summary, in the form of an example foo.cc file:
|
||||
//
|
||||
// #include "foo.h" // foo.h has a line "DECLARE_int32(start);"
|
||||
// #include "validators.h" // hypothetical file defining ValidateIsFile()
|
||||
//
|
||||
// DEFINE_int32(end, 1000, "The last record to read");
|
||||
//
|
||||
// DEFINE_string(filename, "my_file.txt", "The file to read");
|
||||
// // Crash if the specified file does not exist.
|
||||
// static bool dummy = RegisterFlagValidator(&FLAGS_filename,
|
||||
// &ValidateIsFile);
|
||||
//
|
||||
// DECLARE_bool(verbose); // some other file has a DEFINE_bool(verbose, ...)
|
||||
//
|
||||
// void MyFunc() {
|
||||
// if (FLAGS_verbose) printf("Records %d-%d\n", FLAGS_start, FLAGS_end);
|
||||
// }
|
||||
//
|
||||
// Then, at the command-line:
|
||||
// ./foo --noverbose --start=5 --end=100
|
||||
//
|
||||
// For more details, see
|
||||
// doc/gflags.html
|
||||
//
|
||||
// --- A note about thread-safety:
|
||||
//
|
||||
// We describe many functions in this routine as being thread-hostile,
|
||||
// thread-compatible, or thread-safe. Here are the meanings we use:
|
||||
//
|
||||
// thread-safe: it is safe for multiple threads to call this routine
|
||||
// (or, when referring to a class, methods of this class)
|
||||
// concurrently.
|
||||
// thread-hostile: it is not safe for multiple threads to call this
|
||||
// routine (or methods of this class) concurrently. In gflags,
|
||||
// most thread-hostile routines are intended to be called early in,
|
||||
// or even before, main() -- that is, before threads are spawned.
|
||||
// thread-compatible: it is safe for multiple threads to read from
|
||||
// this variable (when applied to variables), or to call const
|
||||
// methods of this class (when applied to classes), as long as no
|
||||
// other thread is writing to the variable or calling non-const
|
||||
// methods of this class.
|
||||
|
||||
#ifndef GOOGLE_GFLAGS_H_
|
||||
#define GOOGLE_GFLAGS_H_
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
// We care a lot about number of bits things take up. Unfortunately,
|
||||
// systems define their bit-specific ints in a lot of different ways.
|
||||
// We use our own way, and have a typedef to get there.
|
||||
// Note: these commands below may look like "#if 1" or "#if 0", but
|
||||
// that's because they were constructed that way at ./configure time.
|
||||
// Look at gflags.h.in to see how they're calculated (based on your config).
|
||||
#if 0
|
||||
#include <stdint.h> // the normal place uint16_t is defined
|
||||
#endif
|
||||
#if 1
|
||||
#include <sys/types.h> // the normal place u_int16_t is defined
|
||||
#endif
|
||||
#if 0
|
||||
#include <inttypes.h> // a third place for uint16_t or u_int16_t
|
||||
#endif
|
||||
|
||||
// Annoying stuff for windows -- makes sure clients can import these functions
|
||||
#if defined(_WIN32)
|
||||
# ifndef GFLAGS_DLL_DECL
|
||||
# define GFLAGS_DLL_DECL __declspec(dllimport)
|
||||
# endif
|
||||
# ifndef GFLAGS_DLL_DECLARE_FLAG
|
||||
# define GFLAGS_DLL_DECLARE_FLAG __declspec(dllimport)
|
||||
# endif
|
||||
# ifndef GFLAGS_DLL_DEFINE_FLAG
|
||||
# define GFLAGS_DLL_DEFINE_FLAG __declspec(dllexport)
|
||||
# endif
|
||||
#else
|
||||
# ifndef GFLAGS_DLL_DECL
|
||||
# define GFLAGS_DLL_DECL
|
||||
# endif
|
||||
# ifndef GFLAGS_DLL_DECLARE_FLAG
|
||||
# define GFLAGS_DLL_DECLARE_FLAG
|
||||
# endif
|
||||
# ifndef GFLAGS_DLL_DEFINE_FLAG
|
||||
# define GFLAGS_DLL_DEFINE_FLAG
|
||||
# endif
|
||||
#endif
|
||||
|
||||
namespace google {
|
||||
|
||||
#if 0 // the C99 format
|
||||
typedef int32_t int32;
|
||||
typedef uint32_t uint32;
|
||||
typedef int64_t int64;
|
||||
typedef uint64_t uint64;
|
||||
#elif 0 // the BSD format
|
||||
typedef int32_t int32;
|
||||
typedef u_int32_t uint32;
|
||||
typedef int64_t int64;
|
||||
typedef u_int64_t uint64;
|
||||
#elif 1 // the windows (vc7) format
|
||||
typedef __int32 int32;
|
||||
typedef unsigned __int32 uint32;
|
||||
typedef __int64 int64;
|
||||
typedef unsigned __int64 uint64;
|
||||
#else
|
||||
#error Do not know how to define a 32-bit integer quantity on your system
|
||||
#endif
|
||||
|
||||
// TODO(kjellander): update generated .h's for new gflags.
|
||||
// https://code.google.com/p/webrtc/issues/detail?id=2251
|
||||
extern const char* VersionString();
|
||||
extern void SetVersionString(const std::string& version);
|
||||
|
||||
// --------------------------------------------------------------------
|
||||
// To actually define a flag in a file, use DEFINE_bool,
|
||||
// DEFINE_string, etc. at the bottom of this file. You may also find
|
||||
// it useful to register a validator with the flag. This ensures that
|
||||
// when the flag is parsed from the commandline, or is later set via
|
||||
// SetCommandLineOption, we call the validation function. It is _not_
|
||||
// called when you assign the value to the flag directly using the = operator.
|
||||
//
|
||||
// The validation function should return true if the flag value is valid, and
|
||||
// false otherwise. If the function returns false for the new setting of the
|
||||
// flag, the flag will retain its current value. If it returns false for the
|
||||
// default value, ParseCommandLineFlags() will die.
|
||||
//
|
||||
// This function is safe to call at global construct time (as in the
|
||||
// example below).
|
||||
//
|
||||
// Example use:
|
||||
// static bool ValidatePort(const char* flagname, int32 value) {
|
||||
// if (value > 0 && value < 32768) // value is ok
|
||||
// return true;
|
||||
// printf("Invalid value for --%s: %d\n", flagname, (int)value);
|
||||
// return false;
|
||||
// }
|
||||
// DEFINE_int32(port, 0, "What port to listen on");
|
||||
// static bool dummy = RegisterFlagValidator(&FLAGS_port, &ValidatePort);
|
||||
|
||||
// Returns true if successfully registered, false if not (because the
|
||||
// first argument doesn't point to a command-line flag, or because a
|
||||
// validator is already registered for this flag).
|
||||
GFLAGS_DLL_DECL bool RegisterFlagValidator(const bool* flag,
|
||||
bool (*validate_fn)(const char*, bool));
|
||||
GFLAGS_DLL_DECL bool RegisterFlagValidator(const int32* flag,
|
||||
bool (*validate_fn)(const char*, int32));
|
||||
GFLAGS_DLL_DECL bool RegisterFlagValidator(const int64* flag,
|
||||
bool (*validate_fn)(const char*, int64));
|
||||
GFLAGS_DLL_DECL bool RegisterFlagValidator(const uint64* flag,
|
||||
bool (*validate_fn)(const char*, uint64));
|
||||
GFLAGS_DLL_DECL bool RegisterFlagValidator(const double* flag,
|
||||
bool (*validate_fn)(const char*, double));
|
||||
GFLAGS_DLL_DECL bool RegisterFlagValidator(const std::string* flag,
|
||||
bool (*validate_fn)(const char*, const std::string&));
|
||||
|
||||
|
||||
// --------------------------------------------------------------------
|
||||
// These methods are the best way to get access to info about the
|
||||
// list of commandline flags. Note that these routines are pretty slow.
|
||||
// GetAllFlags: mostly-complete info about the list, sorted by file.
|
||||
// ShowUsageWithFlags: pretty-prints the list to stdout (what --help does)
|
||||
// ShowUsageWithFlagsRestrict: limit to filenames with restrict as a substr
|
||||
//
|
||||
// In addition to accessing flags, you can also access argv[0] (the program
|
||||
// name) and argv (the entire commandline), which we sock away a copy of.
|
||||
// These variables are static, so you should only set them once.
|
||||
|
||||
struct GFLAGS_DLL_DECL CommandLineFlagInfo {
|
||||
std::string name; // the name of the flag
|
||||
std::string type; // the type of the flag: int32, etc
|
||||
std::string description; // the "help text" associated with the flag
|
||||
std::string current_value; // the current value, as a string
|
||||
std::string default_value; // the default value, as a string
|
||||
std::string filename; // 'cleaned' version of filename holding the flag
|
||||
bool has_validator_fn; // true if RegisterFlagValidator called on flag
|
||||
bool is_default; // true if the flag has the default value and
|
||||
// has not been set explicitly from the cmdline
|
||||
// or via SetCommandLineOption
|
||||
const void* flag_ptr;
|
||||
};
|
||||
|
||||
// Using this inside of a validator is a recipe for a deadlock.
|
||||
// TODO(wojtekm) Fix locking when validators are running, to make it safe to
|
||||
// call validators during ParseAllFlags.
|
||||
// Also make sure then to uncomment the corresponding unit test in
|
||||
// commandlineflags_unittest.sh
|
||||
extern GFLAGS_DLL_DECL void GetAllFlags(std::vector<CommandLineFlagInfo>* OUTPUT);
|
||||
// These two are actually defined in commandlineflags_reporting.cc.
|
||||
extern GFLAGS_DLL_DECL void ShowUsageWithFlags(const char *argv0); // what --help does
|
||||
extern GFLAGS_DLL_DECL void ShowUsageWithFlagsRestrict(const char *argv0, const char *restrict);
|
||||
|
||||
// Create a descriptive string for a flag.
|
||||
// Goes to some trouble to make pretty line breaks.
|
||||
extern GFLAGS_DLL_DECL std::string DescribeOneFlag(const CommandLineFlagInfo& flag);
|
||||
|
||||
// Thread-hostile; meant to be called before any threads are spawned.
|
||||
extern GFLAGS_DLL_DECL void SetArgv(int argc, const char** argv);
|
||||
// The following functions are thread-safe as long as SetArgv() is
|
||||
// only called before any threads start.
|
||||
extern GFLAGS_DLL_DECL const std::vector<std::string>& GetArgvs(); // all of argv as a vector
|
||||
extern GFLAGS_DLL_DECL const char* GetArgv(); // all of argv as a string
|
||||
extern GFLAGS_DLL_DECL const char* GetArgv0(); // only argv0
|
||||
extern GFLAGS_DLL_DECL uint32 GetArgvSum(); // simple checksum of argv
|
||||
extern GFLAGS_DLL_DECL const char* ProgramInvocationName(); // argv0, or "UNKNOWN" if not set
|
||||
extern GFLAGS_DLL_DECL const char* ProgramInvocationShortName(); // basename(argv0)
|
||||
// ProgramUsage() is thread-safe as long as SetUsageMessage() is only
|
||||
// called before any threads start.
|
||||
extern GFLAGS_DLL_DECL const char* ProgramUsage(); // string set by SetUsageMessage()
|
||||
|
||||
|
||||
// --------------------------------------------------------------------
|
||||
// Normally you access commandline flags by just saying "if (FLAGS_foo)"
|
||||
// or whatever, and set them by calling "FLAGS_foo = bar" (or, more
|
||||
// commonly, via the DEFINE_foo macro). But if you need a bit more
|
||||
// control, we have programmatic ways to get/set the flags as well.
|
||||
// These programmatic ways to access flags are thread-safe, but direct
|
||||
// access is only thread-compatible.
|
||||
|
||||
// Return true iff the flagname was found.
|
||||
// OUTPUT is set to the flag's value, or unchanged if we return false.
|
||||
extern GFLAGS_DLL_DECL bool GetCommandLineOption(const char* name, std::string* OUTPUT);
|
||||
|
||||
// Return true iff the flagname was found. OUTPUT is set to the flag's
|
||||
// CommandLineFlagInfo or unchanged if we return false.
|
||||
extern GFLAGS_DLL_DECL bool GetCommandLineFlagInfo(const char* name,
|
||||
CommandLineFlagInfo* OUTPUT);
|
||||
|
||||
// Return the CommandLineFlagInfo of the flagname. exit() if name not found.
|
||||
// Example usage, to check if a flag's value is currently the default value:
|
||||
// if (GetCommandLineFlagInfoOrDie("foo").is_default) ...
|
||||
extern GFLAGS_DLL_DECL CommandLineFlagInfo GetCommandLineFlagInfoOrDie(const char* name);
|
||||
|
||||
enum GFLAGS_DLL_DECL FlagSettingMode {
|
||||
// update the flag's value (can call this multiple times).
|
||||
SET_FLAGS_VALUE,
|
||||
// update the flag's value, but *only if* it has not yet been updated
|
||||
// with SET_FLAGS_VALUE, SET_FLAG_IF_DEFAULT, or "FLAGS_xxx = nondef".
|
||||
SET_FLAG_IF_DEFAULT,
|
||||
// set the flag's default value to this. If the flag has not yet updated
|
||||
// yet (via SET_FLAGS_VALUE, SET_FLAG_IF_DEFAULT, or "FLAGS_xxx = nondef")
|
||||
// change the flag's current value to the new default value as well.
|
||||
SET_FLAGS_DEFAULT
|
||||
};
|
||||
|
||||
// Set a particular flag ("command line option"). Returns a string
|
||||
// describing the new value that the option has been set to. The
|
||||
// return value API is not well-specified, so basically just depend on
|
||||
// it to be empty if the setting failed for some reason -- the name is
|
||||
// not a valid flag name, or the value is not a valid value -- and
|
||||
// non-empty else.
|
||||
|
||||
// SetCommandLineOption uses set_mode == SET_FLAGS_VALUE (the common case)
|
||||
extern GFLAGS_DLL_DECL std::string SetCommandLineOption(const char* name, const char* value);
|
||||
extern GFLAGS_DLL_DECL std::string SetCommandLineOptionWithMode(const char* name, const char* value,
|
||||
FlagSettingMode set_mode);
|
||||
|
||||
|
||||
// --------------------------------------------------------------------
|
||||
// Saves the states (value, default value, whether the user has set
|
||||
// the flag, registered validators, etc) of all flags, and restores
|
||||
// them when the FlagSaver is destroyed. This is very useful in
|
||||
// tests, say, when you want to let your tests change the flags, but
|
||||
// make sure that they get reverted to the original states when your
|
||||
// test is complete.
|
||||
//
|
||||
// Example usage:
|
||||
// void TestFoo() {
|
||||
// FlagSaver s1;
|
||||
// FLAG_foo = false;
|
||||
// FLAG_bar = "some value";
|
||||
//
|
||||
// // test happens here. You can return at any time
|
||||
// // without worrying about restoring the FLAG values.
|
||||
// }
|
||||
//
|
||||
// Note: This class is marked with __attribute__((unused)) because all the
|
||||
// work is done in the constructor and destructor, so in the standard
|
||||
// usage example above, the compiler would complain that it's an
|
||||
// unused variable.
|
||||
//
|
||||
// This class is thread-safe.
|
||||
|
||||
class GFLAGS_DLL_DECL FlagSaver {
|
||||
public:
|
||||
FlagSaver();
|
||||
~FlagSaver();
|
||||
|
||||
private:
|
||||
class FlagSaverImpl* impl_; // we use pimpl here to keep API steady
|
||||
|
||||
FlagSaver(const FlagSaver&); // no copying!
|
||||
void operator=(const FlagSaver&);
|
||||
} ;
|
||||
|
||||
// --------------------------------------------------------------------
|
||||
// Some deprecated or hopefully-soon-to-be-deprecated functions.
|
||||
|
||||
// This is often used for logging. TODO(csilvers): figure out a better way
|
||||
extern GFLAGS_DLL_DECL std::string CommandlineFlagsIntoString();
|
||||
// Usually where this is used, a FlagSaver should be used instead.
|
||||
extern GFLAGS_DLL_DECL bool ReadFlagsFromString(const std::string& flagfilecontents,
|
||||
const char* prog_name,
|
||||
bool errors_are_fatal); // uses SET_FLAGS_VALUE
|
||||
|
||||
// These let you manually implement --flagfile functionality.
|
||||
// DEPRECATED.
|
||||
extern GFLAGS_DLL_DECL bool AppendFlagsIntoFile(const std::string& filename, const char* prog_name);
|
||||
extern GFLAGS_DLL_DECL bool SaveCommandFlags(); // actually defined in google.cc !
|
||||
extern GFLAGS_DLL_DECL bool ReadFromFlagsFile(const std::string& filename, const char* prog_name,
|
||||
bool errors_are_fatal); // uses SET_FLAGS_VALUE
|
||||
|
||||
|
||||
// --------------------------------------------------------------------
|
||||
// Useful routines for initializing flags from the environment.
|
||||
// In each case, if 'varname' does not exist in the environment
|
||||
// return defval. If 'varname' does exist but is not valid
|
||||
// (e.g., not a number for an int32 flag), abort with an error.
|
||||
// Otherwise, return the value. NOTE: for booleans, for true use
|
||||
// 't' or 'T' or 'true' or '1', for false 'f' or 'F' or 'false' or '0'.
|
||||
|
||||
extern GFLAGS_DLL_DECL bool BoolFromEnv(const char *varname, bool defval);
|
||||
extern GFLAGS_DLL_DECL int32 Int32FromEnv(const char *varname, int32 defval);
|
||||
extern GFLAGS_DLL_DECL int64 Int64FromEnv(const char *varname, int64 defval);
|
||||
extern GFLAGS_DLL_DECL uint64 Uint64FromEnv(const char *varname, uint64 defval);
|
||||
extern GFLAGS_DLL_DECL double DoubleFromEnv(const char *varname, double defval);
|
||||
extern GFLAGS_DLL_DECL const char *StringFromEnv(const char *varname, const char *defval);
|
||||
|
||||
|
||||
// --------------------------------------------------------------------
|
||||
// The next two functions parse commandlineflags from main():
|
||||
|
||||
// Set the "usage" message for this program. For example:
|
||||
// string usage("This program does nothing. Sample usage:\n");
|
||||
// usage += argv[0] + " <uselessarg1> <uselessarg2>";
|
||||
// SetUsageMessage(usage);
|
||||
// Do not include commandline flags in the usage: we do that for you!
|
||||
// Thread-hostile; meant to be called before any threads are spawned.
|
||||
extern GFLAGS_DLL_DECL void SetUsageMessage(const std::string& usage);
|
||||
|
||||
// Looks for flags in argv and parses them. Rearranges argv to put
|
||||
// flags first, or removes them entirely if remove_flags is true.
|
||||
// If a flag is defined more than once in the command line or flag
|
||||
// file, the last definition is used.
|
||||
// See top-of-file for more details on this function.
|
||||
#ifndef SWIG // In swig, use ParseCommandLineFlagsScript() instead.
|
||||
extern GFLAGS_DLL_DECL uint32 ParseCommandLineFlags(int *argc, char*** argv,
|
||||
bool remove_flags);
|
||||
#endif
|
||||
|
||||
|
||||
// Calls to ParseCommandLineNonHelpFlags and then to
|
||||
// HandleCommandLineHelpFlags can be used instead of a call to
|
||||
// ParseCommandLineFlags during initialization, in order to allow for
|
||||
// changing default values for some FLAGS (via
|
||||
// e.g. SetCommandLineOptionWithMode calls) between the time of
|
||||
// command line parsing and the time of dumping help information for
|
||||
// the flags as a result of command line parsing.
|
||||
// If a flag is defined more than once in the command line or flag
|
||||
// file, the last definition is used.
|
||||
extern GFLAGS_DLL_DECL uint32 ParseCommandLineNonHelpFlags(int *argc, char*** argv,
|
||||
bool remove_flags);
|
||||
// This is actually defined in commandlineflags_reporting.cc.
|
||||
// This function is misnamed (it also handles --version, etc.), but
|
||||
// it's too late to change that now. :-(
|
||||
extern GFLAGS_DLL_DECL void HandleCommandLineHelpFlags(); // in commandlineflags_reporting.cc
|
||||
|
||||
// Allow command line reparsing. Disables the error normally
|
||||
// generated when an unknown flag is found, since it may be found in a
|
||||
// later parse. Thread-hostile; meant to be called before any threads
|
||||
// are spawned.
|
||||
extern GFLAGS_DLL_DECL void AllowCommandLineReparsing();
|
||||
|
||||
// Reparse the flags that have not yet been recognized.
|
||||
// Only flags registered since the last parse will be recognized.
|
||||
// Any flag value must be provided as part of the argument using "=",
|
||||
// not as a separate command line argument that follows the flag argument.
|
||||
// Intended for handling flags from dynamically loaded libraries,
|
||||
// since their flags are not registered until they are loaded.
|
||||
extern GFLAGS_DLL_DECL void ReparseCommandLineNonHelpFlags();
|
||||
|
||||
// Clean up memory allocated by flags. This is only needed to reduce
|
||||
// the quantity of "potentially leaked" reports emitted by memory
|
||||
// debugging tools such as valgrind. It is not required for normal
|
||||
// operation, or for the perftools heap-checker. It must only be called
|
||||
// when the process is about to exit, and all threads that might
|
||||
// access flags are quiescent. Referencing flags after this is called
|
||||
// will have unexpected consequences. This is not safe to run when
|
||||
// multiple threads might be running: the function is thread-hostile.
|
||||
extern GFLAGS_DLL_DECL void ShutDownCommandLineFlags();
|
||||
|
||||
|
||||
// --------------------------------------------------------------------
|
||||
// Now come the command line flag declaration/definition macros that
|
||||
// will actually be used. They're kind of hairy. A major reason
|
||||
// for this is initialization: we want people to be able to access
|
||||
// variables in global constructors and have that not crash, even if
|
||||
// their global constructor runs before the global constructor here.
|
||||
// (Obviously, we can't guarantee the flags will have the correct
|
||||
// default value in that case, but at least accessing them is safe.)
|
||||
// The only way to do that is have flags point to a static buffer.
|
||||
// So we make one, using a union to ensure proper alignment, and
|
||||
// then use placement-new to actually set up the flag with the
|
||||
// correct default value. In the same vein, we have to worry about
|
||||
// flag access in global destructors, so FlagRegisterer has to be
|
||||
// careful never to destroy the flag-values it constructs.
|
||||
//
|
||||
// Note that when we define a flag variable FLAGS_<name>, we also
|
||||
// preemptively define a junk variable, FLAGS_no<name>. This is to
|
||||
// cause a link-time error if someone tries to define 2 flags with
|
||||
// names like "logging" and "nologging". We do this because a bool
|
||||
// flag FLAG can be set from the command line to true with a "-FLAG"
|
||||
// argument, and to false with a "-noFLAG" argument, and so this can
|
||||
// potentially avert confusion.
|
||||
//
|
||||
// We also put flags into their own namespace. It is purposefully
|
||||
// named in an opaque way that people should have trouble typing
|
||||
// directly. The idea is that DEFINE puts the flag in the weird
|
||||
// namespace, and DECLARE imports the flag from there into the current
|
||||
// namespace. The net result is to force people to use DECLARE to get
|
||||
// access to a flag, rather than saying "extern bool FLAGS_whatever;"
|
||||
// or some such instead. We want this so we can put extra
|
||||
// functionality (like sanity-checking) in DECLARE if we want, and
|
||||
// make sure it is picked up everywhere.
|
||||
//
|
||||
// We also put the type of the variable in the namespace, so that
|
||||
// people can't DECLARE_int32 something that they DEFINE_bool'd
|
||||
// elsewhere.
|
||||
|
||||
class GFLAGS_DLL_DECL FlagRegisterer {
|
||||
public:
|
||||
FlagRegisterer(const char* name, const char* type,
|
||||
const char* help, const char* filename,
|
||||
void* current_storage, void* defvalue_storage);
|
||||
};
|
||||
|
||||
extern bool FlagsTypeWarn(const char *name);
|
||||
|
||||
// If your application #defines STRIP_FLAG_HELP to a non-zero value
|
||||
// before #including this file, we remove the help message from the
|
||||
// binary file. This can reduce the size of the resulting binary
|
||||
// somewhat, and may also be useful for security reasons.
|
||||
|
||||
extern const char kStrippedFlagHelp[];
|
||||
|
||||
}
|
||||
|
||||
#ifndef SWIG // In swig, ignore the main flag declarations
|
||||
|
||||
#if defined(STRIP_FLAG_HELP) && STRIP_FLAG_HELP > 0
|
||||
// Need this construct to avoid the 'defined but not used' warning.
|
||||
#define MAYBE_STRIPPED_HELP(txt) (false ? (txt) : kStrippedFlagHelp)
|
||||
#else
|
||||
#define MAYBE_STRIPPED_HELP(txt) txt
|
||||
#endif
|
||||
|
||||
// Each command-line flag has two variables associated with it: one
|
||||
// with the current value, and one with the default value. However,
|
||||
// we have a third variable, which is where value is assigned; it's a
|
||||
// constant. This guarantees that FLAG_##value is initialized at
|
||||
// static initialization time (e.g. before program-start) rather than
|
||||
// than global construction time (which is after program-start but
|
||||
// before main), at least when 'value' is a compile-time constant. We
|
||||
// use a small trick for the "default value" variable, and call it
|
||||
// FLAGS_no<name>. This serves the second purpose of assuring a
|
||||
// compile error if someone tries to define a flag named no<name>
|
||||
// which is illegal (--foo and --nofoo both affect the "foo" flag).
|
||||
#define DEFINE_VARIABLE(type, shorttype, name, value, help) \
|
||||
namespace fL##shorttype { \
|
||||
static const type FLAGS_nono##name = value; \
|
||||
/* We always want to export defined variables, dll or no */ \
|
||||
GFLAGS_DLL_DEFINE_FLAG type FLAGS_##name = FLAGS_nono##name; \
|
||||
type FLAGS_no##name = FLAGS_nono##name; \
|
||||
static ::google::FlagRegisterer o_##name( \
|
||||
#name, #type, MAYBE_STRIPPED_HELP(help), __FILE__, \
|
||||
&FLAGS_##name, &FLAGS_no##name); \
|
||||
} \
|
||||
using fL##shorttype::FLAGS_##name
|
||||
|
||||
#define DECLARE_VARIABLE(type, shorttype, name) \
|
||||
namespace fL##shorttype { \
|
||||
/* We always want to import declared variables, dll or no */ \
|
||||
extern GFLAGS_DLL_DECLARE_FLAG type FLAGS_##name; \
|
||||
} \
|
||||
using fL##shorttype::FLAGS_##name
|
||||
|
||||
// For DEFINE_bool, we want to do the extra check that the passed-in
|
||||
// value is actually a bool, and not a string or something that can be
|
||||
// coerced to a bool. These declarations (no definition needed!) will
|
||||
// help us do that, and never evaluate From, which is important.
|
||||
// We'll use 'sizeof(IsBool(val))' to distinguish. This code requires
|
||||
// that the compiler have different sizes for bool & double. Since
|
||||
// this is not guaranteed by the standard, we check it with a
|
||||
// compile-time assert (msg[-1] will give a compile-time error).
|
||||
namespace fLB {
|
||||
struct CompileAssert {};
|
||||
typedef CompileAssert expected_sizeof_double_neq_sizeof_bool[
|
||||
(sizeof(double) != sizeof(bool)) ? 1 : -1];
|
||||
template<typename From> GFLAGS_DLL_DECL double IsBoolFlag(const From& from);
|
||||
GFLAGS_DLL_DECL bool IsBoolFlag(bool from);
|
||||
} // namespace fLB
|
||||
|
||||
#define DECLARE_bool(name) DECLARE_VARIABLE(bool, B, name)
|
||||
#define DEFINE_bool(name, val, txt) \
|
||||
namespace fLB { \
|
||||
typedef ::fLB::CompileAssert FLAG_##name##_value_is_not_a_bool[ \
|
||||
(sizeof(::fLB::IsBoolFlag(val)) != sizeof(double)) ? 1 : -1]; \
|
||||
} \
|
||||
DEFINE_VARIABLE(bool, B, name, val, txt)
|
||||
|
||||
#define DECLARE_int32(name) DECLARE_VARIABLE(::google::int32, I, name)
|
||||
#define DEFINE_int32(name,val,txt) DEFINE_VARIABLE(::google::int32, I, name, val, txt)
|
||||
|
||||
#define DECLARE_int64(name) DECLARE_VARIABLE(::google::int64, I64, name)
|
||||
#define DEFINE_int64(name,val,txt) DEFINE_VARIABLE(::google::int64, I64, name, val, txt)
|
||||
|
||||
#define DECLARE_uint64(name) DECLARE_VARIABLE(::google::uint64, U64, name)
|
||||
#define DEFINE_uint64(name,val,txt) DEFINE_VARIABLE(::google::uint64, U64, name, val, txt)
|
||||
|
||||
#define DECLARE_double(name) DECLARE_VARIABLE(double, D, name)
|
||||
#define DEFINE_double(name, val, txt) DEFINE_VARIABLE(double, D, name, val, txt)
|
||||
|
||||
// Strings are trickier, because they're not a POD, so we can't
|
||||
// construct them at static-initialization time (instead they get
|
||||
// constructed at global-constructor time, which is much later). To
|
||||
// try to avoid crashes in that case, we use a char buffer to store
|
||||
// the string, which we can static-initialize, and then placement-new
|
||||
// into it later. It's not perfect, but the best we can do.
|
||||
|
||||
namespace fLS {
|
||||
// The meaning of "string" might be different between now and when the
|
||||
// macros below get invoked (e.g., if someone is experimenting with
|
||||
// other string implementations that get defined after this file is
|
||||
// included). Save the current meaning now and use it in the macros.
|
||||
typedef std::string clstring;
|
||||
|
||||
inline clstring* dont_pass0toDEFINE_string(char *stringspot,
|
||||
const char *value) {
|
||||
return new(stringspot) clstring(value);
|
||||
}
|
||||
inline clstring* dont_pass0toDEFINE_string(char *stringspot,
|
||||
const clstring &value) {
|
||||
return new(stringspot) clstring(value);
|
||||
}
|
||||
inline clstring* dont_pass0toDEFINE_string(char *stringspot,
|
||||
int value);
|
||||
} // namespace fLS
|
||||
|
||||
#define DECLARE_string(name) namespace fLS { extern GFLAGS_DLL_DECLARE_FLAG ::fLS::clstring& FLAGS_##name; } \
|
||||
using fLS::FLAGS_##name
|
||||
|
||||
// We need to define a var named FLAGS_no##name so people don't define
|
||||
// --string and --nostring. And we need a temporary place to put val
|
||||
// so we don't have to evaluate it twice. Two great needs that go
|
||||
// great together!
|
||||
#define DEFINE_string(name, val, txt) \
|
||||
namespace fLS { \
|
||||
using ::fLS::clstring; \
|
||||
static union { void* align; char s[sizeof(clstring)]; } s_##name[2]; \
|
||||
clstring* const FLAGS_no##name = ::fLS:: \
|
||||
dont_pass0toDEFINE_string(s_##name[0].s, \
|
||||
val); \
|
||||
static ::google::FlagRegisterer o_##name( \
|
||||
#name, "string", MAYBE_STRIPPED_HELP(txt), __FILE__, \
|
||||
s_##name[0].s, new (s_##name[1].s) clstring(*FLAGS_no##name)); \
|
||||
GFLAGS_DLL_DEFINE_FLAG clstring& FLAGS_##name = *FLAGS_no##name; \
|
||||
} \
|
||||
using fLS::FLAGS_##name
|
||||
|
||||
#endif // SWIG
|
||||
|
||||
#endif // GOOGLE_GFLAGS_H_
|
|
@ -0,0 +1,130 @@
|
|||
// Copyright (c) 2008, Google Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following disclaimer
|
||||
// in the documentation and/or other materials provided with the
|
||||
// distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from
|
||||
// this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
//
|
||||
// ---
|
||||
// Author: Dave Nicponski
|
||||
//
|
||||
// Implement helpful bash-style command line flag completions
|
||||
//
|
||||
// ** Functional API:
|
||||
// HandleCommandLineCompletions() should be called early during
|
||||
// program startup, but after command line flag code has been
|
||||
// initialized, such as the beginning of HandleCommandLineHelpFlags().
|
||||
// It checks the value of the flag --tab_completion_word. If this
|
||||
// flag is empty, nothing happens here. If it contains a string,
|
||||
// however, then HandleCommandLineCompletions() will hijack the
|
||||
// process, attempting to identify the intention behind this
|
||||
// completion. Regardless of the outcome of this deduction, the
|
||||
// process will be terminated, similar to --helpshort flag
|
||||
// handling.
|
||||
//
|
||||
// ** Overview of Bash completions:
|
||||
// Bash can be told to programatically determine completions for the
|
||||
// current 'cursor word'. It does this by (in this case) invoking a
|
||||
// command with some additional arguments identifying the command
|
||||
// being executed, the word being completed, and the previous word
|
||||
// (if any). Bash then expects a sequence of output lines to be
|
||||
// printed to stdout. If these lines all contain a common prefix
|
||||
// longer than the cursor word, bash will replace the cursor word
|
||||
// with that common prefix, and display nothing. If there isn't such
|
||||
// a common prefix, bash will display the lines in pages using 'more'.
|
||||
//
|
||||
// ** Strategy taken for command line completions:
|
||||
// If we can deduce either the exact flag intended, or a common flag
|
||||
// prefix, we'll output exactly that. Otherwise, if information
|
||||
// must be displayed to the user, we'll take the opportunity to add
|
||||
// some helpful information beyond just the flag name (specifically,
|
||||
// we'll include the default flag value and as much of the flag's
|
||||
// description as can fit on a single terminal line width, as specified
|
||||
// by the flag --tab_completion_columns). Furthermore, we'll try to
|
||||
// make bash order the output such that the most useful or relevent
|
||||
// flags are the most likely to be shown at the top.
|
||||
//
|
||||
// ** Additional features:
|
||||
// To assist in finding that one really useful flag, substring matching
|
||||
// was implemented. Before pressing a <TAB> to get completion for the
|
||||
// current word, you can append one or more '?' to the flag to do
|
||||
// substring matching. Here's the semantics:
|
||||
// --foo<TAB> Show me all flags with names prefixed by 'foo'
|
||||
// --foo?<TAB> Show me all flags with 'foo' somewhere in the name
|
||||
// --foo??<TAB> Same as prior case, but also search in module
|
||||
// definition path for 'foo'
|
||||
// --foo???<TAB> Same as prior case, but also search in flag
|
||||
// descriptions for 'foo'
|
||||
// Finally, we'll trim the output to a relatively small number of
|
||||
// flags to keep bash quiet about the verbosity of output. If one
|
||||
// really wanted to see all possible matches, appending a '+' to the
|
||||
// search word will force the exhaustive list of matches to be printed.
|
||||
//
|
||||
// ** How to have bash accept completions from a binary:
|
||||
// Bash requires that it be informed about each command that programmatic
|
||||
// completion should be enabled for. Example addition to a .bashrc
|
||||
// file would be (your path to gflags_completions.sh file may differ):
|
||||
|
||||
/*
|
||||
$ complete -o bashdefault -o default -o nospace -C \
|
||||
'/usr/local/bin/gflags_completions.sh --tab_completion_columns $COLUMNS' \
|
||||
time env binary_name another_binary [...]
|
||||
*/
|
||||
|
||||
// This would allow the following to work:
|
||||
// $ /path/to/binary_name --vmodule<TAB>
|
||||
// Or:
|
||||
// $ ./bin/path/another_binary --gfs_u<TAB>
|
||||
// (etc)
|
||||
//
|
||||
// Sadly, it appears that bash gives no easy way to force this behavior for
|
||||
// all commands. That's where the "time" in the above example comes in.
|
||||
// If you haven't specifically added a command to the list of completion
|
||||
// supported commands, you can still get completions by prefixing the
|
||||
// entire command with "env".
|
||||
// $ env /some/brand/new/binary --vmod<TAB>
|
||||
// Assuming that "binary" is a newly compiled binary, this should still
|
||||
// produce the expected completion output.
|
||||
|
||||
|
||||
#ifndef GOOGLE_GFLAGS_COMPLETIONS_H_
|
||||
#define GOOGLE_GFLAGS_COMPLETIONS_H_
|
||||
|
||||
// Annoying stuff for windows -- makes sure clients can import these functions
|
||||
#ifndef GFLAGS_DLL_DECL
|
||||
# ifdef _WIN32
|
||||
# define GFLAGS_DLL_DECL __declspec(dllimport)
|
||||
# else
|
||||
# define GFLAGS_DLL_DECL
|
||||
# endif
|
||||
#endif
|
||||
|
||||
namespace google {
|
||||
|
||||
GFLAGS_DLL_DECL void HandleCommandLineCompletions(void);
|
||||
|
||||
}
|
||||
|
||||
#endif // GOOGLE_GFLAGS_COMPLETIONS_H_
|
|
@ -0,0 +1,139 @@
|
|||
/* src/config.h.in. Generated from configure.ac by autoheader. */
|
||||
|
||||
/* Sometimes we accidentally #include this config.h instead of the one
|
||||
in .. -- this is particularly true for msys/mingw, which uses the
|
||||
unix config.h but also runs code in the windows directory.
|
||||
*/
|
||||
#ifdef __MINGW32__
|
||||
#include "../config.h"
|
||||
#define GOOGLE_GFLAGS_WINDOWS_CONFIG_H_
|
||||
#endif
|
||||
|
||||
#ifndef GOOGLE_GFLAGS_WINDOWS_CONFIG_H_
|
||||
#define GOOGLE_GFLAGS_WINDOWS_CONFIG_H_
|
||||
|
||||
/* Always the empty-string on non-windows systems. On windows, should be
|
||||
"__declspec(dllexport)". This way, when we compile the dll, we export our
|
||||
functions/classes. It's safe to define this here because config.h is only
|
||||
used internally, to compile the DLL, and every DLL source file #includes
|
||||
"config.h" before anything else. */
|
||||
#ifndef GFLAGS_DLL_DECL
|
||||
# define GFLAGS_IS_A_DLL 1 /* not set if you're statically linking */
|
||||
# define GFLAGS_DLL_DECL __declspec(dllexport)
|
||||
# define GFLAGS_DLL_DECL_FOR_UNITTESTS __declspec(dllimport)
|
||||
#endif
|
||||
|
||||
/* Namespace for Google classes */
|
||||
#define GOOGLE_NAMESPACE ::google
|
||||
|
||||
/* Define to 1 if you have the <dlfcn.h> header file. */
|
||||
#undef HAVE_DLFCN_H
|
||||
|
||||
/* Define to 1 if you have the <fnmatch.h> header file. */
|
||||
#undef HAVE_FNMATCH_H
|
||||
|
||||
/* Define to 1 if you have the <inttypes.h> header file. */
|
||||
#undef HAVE_INTTYPES_H
|
||||
|
||||
/* Define to 1 if you have the <memory.h> header file. */
|
||||
#undef HAVE_MEMORY_H
|
||||
|
||||
/* define if the compiler implements namespaces */
|
||||
#define HAVE_NAMESPACES 1
|
||||
|
||||
/* Define if you have POSIX threads libraries and header files. */
|
||||
#undef HAVE_PTHREAD
|
||||
|
||||
/* Define to 1 if you have the `putenv' function. */
|
||||
#define HAVE_PUTENV 1
|
||||
|
||||
/* Define to 1 if you have the `setenv' function. */
|
||||
#undef HAVE_SETENV
|
||||
|
||||
/* Define to 1 if you have the <stdint.h> header file. */
|
||||
#undef HAVE_STDINT_H
|
||||
|
||||
/* Define to 1 if you have the <stdlib.h> header file. */
|
||||
#define HAVE_STDLIB_H 1
|
||||
|
||||
/* Define to 1 if you have the <strings.h> header file. */
|
||||
#undef HAVE_STRINGS_H
|
||||
|
||||
/* Define to 1 if you have the <string.h> header file. */
|
||||
#define HAVE_STRING_H 1
|
||||
|
||||
/* Define to 1 if you have the `strtoll' function. */
|
||||
#define HAVE_STRTOLL 1
|
||||
|
||||
/* Define to 1 if you have the `strtoq' function. */
|
||||
#define HAVE_STRTOQ 1
|
||||
|
||||
/* Define to 1 if you have the <sys/stat.h> header file. */
|
||||
#define HAVE_SYS_STAT_H 1
|
||||
|
||||
/* Define to 1 if you have the <sys/types.h> header file. */
|
||||
#define HAVE_SYS_TYPES_H 1
|
||||
|
||||
/* Define to 1 if you have the <unistd.h> header file. */
|
||||
#undef HAVE_UNISTD_H
|
||||
|
||||
/* define if your compiler has __attribute__ */
|
||||
#undef HAVE___ATTRIBUTE__
|
||||
|
||||
/* Define to the sub-directory in which libtool stores uninstalled libraries.
|
||||
*/
|
||||
#undef LT_OBJDIR
|
||||
|
||||
/* Name of package */
|
||||
#undef PACKAGE
|
||||
|
||||
/* Define to the address where bug reports for this package should be sent. */
|
||||
#undef PACKAGE_BUGREPORT
|
||||
|
||||
/* Define to the full name of this package. */
|
||||
#undef PACKAGE_NAME
|
||||
|
||||
/* Define to the full name and version of this package. */
|
||||
#undef PACKAGE_STRING
|
||||
|
||||
/* Define to the one symbol short name of this package. */
|
||||
#undef PACKAGE_TARNAME
|
||||
|
||||
/* Define to the home page for this package. */
|
||||
#undef PACKAGE_URL
|
||||
|
||||
/* Define to the version of this package. */
|
||||
#undef PACKAGE_VERSION
|
||||
|
||||
/* Define to necessary symbol if this constant uses a non-standard name on
|
||||
your system. */
|
||||
#undef PTHREAD_CREATE_JOINABLE
|
||||
|
||||
/* Define to 1 if you have the ANSI C header files. */
|
||||
#define STDC_HEADERS 1
|
||||
|
||||
/* the namespace where STL code like vector<> is defined */
|
||||
#define STL_NAMESPACE std
|
||||
|
||||
/* Version number of package */
|
||||
#undef VERSION
|
||||
|
||||
/* Stops putting the code inside the Google namespace */
|
||||
#define _END_GOOGLE_NAMESPACE_ }
|
||||
|
||||
/* Puts following code inside the Google namespace */
|
||||
#define _START_GOOGLE_NAMESPACE_ namespace google {
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// Extra stuff not found in config.h.in
|
||||
|
||||
// This must be defined before the windows.h is included. It's needed
|
||||
// for mutex.h, to give access to the TryLock method.
|
||||
#ifndef _WIN32_WINNT
|
||||
# define _WIN32_WINNT 0x0400
|
||||
#endif
|
||||
|
||||
// TODO(csilvers): include windows/port.h in every relevant source file instead?
|
||||
#include "windows/port.h"
|
||||
|
||||
#endif /* GOOGLE_GFLAGS_WINDOWS_CONFIG_H_ */
|
|
@ -0,0 +1,78 @@
|
|||
# Copyright 2011 Google Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
{
|
||||
'variables': {
|
||||
'gflags_root': '<(DEPTH)/third_party/gflags',
|
||||
'conditions': [
|
||||
['OS=="win"', {
|
||||
'gflags_gen_arch_root': '<(gflags_root)/gen/win',
|
||||
}, {
|
||||
'gflags_gen_arch_root': '<(gflags_root)/gen/posix',
|
||||
}],
|
||||
],
|
||||
},
|
||||
'targets': [
|
||||
{
|
||||
'target_name': 'gflags',
|
||||
'type': 'static_library',
|
||||
'include_dirs': [
|
||||
'<(gflags_gen_arch_root)/include/private', # For config.h
|
||||
'<(gflags_gen_arch_root)/include', # For configured files.
|
||||
'<(gflags_root)/src', # For everything else.
|
||||
],
|
||||
'defines': [
|
||||
# These macros exist so flags and symbols are properly
|
||||
# exported when building DLLs. Since we don't build DLLs, we
|
||||
# need to disable them.
|
||||
'GFLAGS_DLL_DECL=',
|
||||
'GFLAGS_DLL_DECLARE_FLAG=',
|
||||
'GFLAGS_DLL_DEFINE_FLAG=',
|
||||
],
|
||||
'direct_dependent_settings': {
|
||||
'include_dirs': [
|
||||
'<(gflags_gen_arch_root)/include', # For configured files.
|
||||
'<(gflags_root)/src', # For everything else.
|
||||
],
|
||||
'defines': [
|
||||
'GFLAGS_DLL_DECL=',
|
||||
'GFLAGS_DLL_DECLARE_FLAG=',
|
||||
'GFLAGS_DLL_DEFINE_FLAG=',
|
||||
],
|
||||
},
|
||||
'sources': [
|
||||
'src/gflags.cc',
|
||||
'src/gflags_completions.cc',
|
||||
'src/gflags_reporting.cc',
|
||||
],
|
||||
'conditions': [
|
||||
['OS=="win"', {
|
||||
'sources': [
|
||||
'src/windows/port.cc',
|
||||
],
|
||||
# Suppress warnings about WIN32_LEAN_AND_MEAN and size_t truncation.
|
||||
'msvs_disabled_warnings': [4005, 4267],
|
||||
}],
|
||||
# TODO(andrew): Look into fixing this warning upstream:
|
||||
# http://code.google.com/p/webrtc/issues/detail?id=760
|
||||
['clang==1', {
|
||||
'cflags!': ['-Wheader-hygiene',],
|
||||
'xcode_settings': {
|
||||
'WARNING_CFLAGS!': ['-Wheader-hygiene',],
|
||||
},
|
||||
}],
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
|
@ -0,0 +1,106 @@
|
|||
/* src/config.h.in. Generated from configure.ac by autoheader. */
|
||||
|
||||
/* Always the empty-string on non-windows systems. On windows, should be
|
||||
"__declspec(dllexport)". This way, when we compile the dll, we export our
|
||||
functions/classes. It's safe to define this here because config.h is only
|
||||
used internally, to compile the DLL, and every DLL source file #includes
|
||||
"config.h" before anything else. */
|
||||
#undef GFLAGS_DLL_DECL
|
||||
|
||||
/* Namespace for Google classes */
|
||||
#undef GOOGLE_NAMESPACE
|
||||
|
||||
/* Define to 1 if you have the <dlfcn.h> header file. */
|
||||
#undef HAVE_DLFCN_H
|
||||
|
||||
/* Define to 1 if you have the <fnmatch.h> header file. */
|
||||
#undef HAVE_FNMATCH_H
|
||||
|
||||
/* Define to 1 if you have the <inttypes.h> header file. */
|
||||
#undef HAVE_INTTYPES_H
|
||||
|
||||
/* Define to 1 if you have the <memory.h> header file. */
|
||||
#undef HAVE_MEMORY_H
|
||||
|
||||
/* define if the compiler implements namespaces */
|
||||
#undef HAVE_NAMESPACES
|
||||
|
||||
/* Define if you have POSIX threads libraries and header files. */
|
||||
#undef HAVE_PTHREAD
|
||||
|
||||
/* Define to 1 if you have the <stdint.h> header file. */
|
||||
#undef HAVE_STDINT_H
|
||||
|
||||
/* Define to 1 if you have the <stdlib.h> header file. */
|
||||
#undef HAVE_STDLIB_H
|
||||
|
||||
/* Define to 1 if you have the <strings.h> header file. */
|
||||
#undef HAVE_STRINGS_H
|
||||
|
||||
/* Define to 1 if you have the <string.h> header file. */
|
||||
#undef HAVE_STRING_H
|
||||
|
||||
/* Define to 1 if you have the `strtoll' function. */
|
||||
#undef HAVE_STRTOLL
|
||||
|
||||
/* Define to 1 if you have the `strtoq' function. */
|
||||
#undef HAVE_STRTOQ
|
||||
|
||||
/* Define to 1 if you have the <sys/stat.h> header file. */
|
||||
#undef HAVE_SYS_STAT_H
|
||||
|
||||
/* Define to 1 if you have the <sys/types.h> header file. */
|
||||
#undef HAVE_SYS_TYPES_H
|
||||
|
||||
/* Define to 1 if you have the <unistd.h> header file. */
|
||||
#undef HAVE_UNISTD_H
|
||||
|
||||
/* define if your compiler has __attribute__ */
|
||||
#undef HAVE___ATTRIBUTE__
|
||||
|
||||
/* Define to the sub-directory in which libtool stores uninstalled libraries.
|
||||
*/
|
||||
#undef LT_OBJDIR
|
||||
|
||||
/* Name of package */
|
||||
#undef PACKAGE
|
||||
|
||||
/* Define to the address where bug reports for this package should be sent. */
|
||||
#undef PACKAGE_BUGREPORT
|
||||
|
||||
/* Define to the full name of this package. */
|
||||
#undef PACKAGE_NAME
|
||||
|
||||
/* Define to the full name and version of this package. */
|
||||
#undef PACKAGE_STRING
|
||||
|
||||
/* Define to the one symbol short name of this package. */
|
||||
#undef PACKAGE_TARNAME
|
||||
|
||||
/* Define to the version of this package. */
|
||||
#undef PACKAGE_VERSION
|
||||
|
||||
/* Define to necessary symbol if this constant uses a non-standard name on
|
||||
your system. */
|
||||
#undef PTHREAD_CREATE_JOINABLE
|
||||
|
||||
/* Define to 1 if you have the ANSI C header files. */
|
||||
#undef STDC_HEADERS
|
||||
|
||||
/* the namespace where STL code like vector<> is defined */
|
||||
#undef STL_NAMESPACE
|
||||
|
||||
/* Version number of package */
|
||||
#undef VERSION
|
||||
|
||||
/* Stops putting the code inside the Google namespace */
|
||||
#undef _END_GOOGLE_NAMESPACE_
|
||||
|
||||
/* Puts following code inside the Google namespace */
|
||||
#undef _START_GOOGLE_NAMESPACE_
|
||||
|
||||
|
||||
#if defined( __MINGW32__) || defined(__MINGW64__)
|
||||
#include "windows/port.h"
|
||||
#endif
|
||||
|
|
@ -0,0 +1,63 @@
|
|||
// Copyright (c) 2007, Google Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following disclaimer
|
||||
// in the documentation and/or other materials provided with the
|
||||
// distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from
|
||||
// this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
// ---
|
||||
// All Rights Reserved.
|
||||
//
|
||||
//
|
||||
// This file is needed for windows -- unittests are not part of the
|
||||
// gflags dll, but still want to include config.h just like the
|
||||
// dll does, so they can use internal tools and APIs for testing.
|
||||
//
|
||||
// The problem is that config.h declares GFLAGS_DLL_DECL to be
|
||||
// for exporting symbols, but the unittest needs to *import* symbols
|
||||
// (since it's not the dll).
|
||||
//
|
||||
// The solution is to have this file, which is just like config.h but
|
||||
// sets GFLAGS_DLL_DECL to do a dllimport instead of a dllexport.
|
||||
//
|
||||
// The reason we need this extra GFLAGS_DLL_DECL_FOR_UNITTESTS
|
||||
// variable is in case people want to set GFLAGS_DLL_DECL explicitly
|
||||
// to something other than __declspec(dllexport). In that case, they
|
||||
// may want to use something other than __declspec(dllimport) for the
|
||||
// unittest case. For that, we allow folks to define both
|
||||
// GFLAGS_DLL_DECL and GFLAGS_DLL_DECL_FOR_UNITTESTS explicitly.
|
||||
//
|
||||
// NOTE: This file is equivalent to config.h on non-windows systems,
|
||||
// which never defined GFLAGS_DLL_DECL_FOR_UNITTESTS and always
|
||||
// define GFLAGS_DLL_DECL to the empty string.
|
||||
|
||||
#include "config.h"
|
||||
|
||||
#undef GFLAGS_DLL_DECL
|
||||
#ifdef GFLAGS_DLL_DECL_FOR_UNITTESTS
|
||||
# define GFLAGS_DLL_DECL GFLAGS_DLL_DECL_FOR_UNITTESTS
|
||||
#else
|
||||
# define GFLAGS_DLL_DECL // if DLL_DECL_FOR_UNITTESTS isn't defined, use ""
|
||||
#endif
|
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,570 @@
|
|||
// Copyright (c) 2006, Google Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following disclaimer
|
||||
// in the documentation and/or other materials provided with the
|
||||
// distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from
|
||||
// this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
// ---
|
||||
// Revamped and reorganized by Craig Silverstein
|
||||
//
|
||||
// This is the file that should be included by any file which declares
|
||||
// or defines a command line flag or wants to parse command line flags
|
||||
// or print a program usage message (which will include information about
|
||||
// flags). Executive summary, in the form of an example foo.cc file:
|
||||
//
|
||||
// #include "foo.h" // foo.h has a line "DECLARE_int32(start);"
|
||||
// #include "validators.h" // hypothetical file defining ValidateIsFile()
|
||||
//
|
||||
// DEFINE_int32(end, 1000, "The last record to read");
|
||||
//
|
||||
// DEFINE_string(filename, "my_file.txt", "The file to read");
|
||||
// // Crash if the specified file does not exist.
|
||||
// static bool dummy = RegisterFlagValidator(&FLAGS_filename,
|
||||
// &ValidateIsFile);
|
||||
//
|
||||
// DECLARE_bool(verbose); // some other file has a DEFINE_bool(verbose, ...)
|
||||
//
|
||||
// void MyFunc() {
|
||||
// if (FLAGS_verbose) printf("Records %d-%d\n", FLAGS_start, FLAGS_end);
|
||||
// }
|
||||
//
|
||||
// Then, at the command-line:
|
||||
// ./foo --noverbose --start=5 --end=100
|
||||
//
|
||||
// For more details, see
|
||||
// doc/gflags.html
|
||||
//
|
||||
// --- A note about thread-safety:
|
||||
//
|
||||
// We describe many functions in this routine as being thread-hostile,
|
||||
// thread-compatible, or thread-safe. Here are the meanings we use:
|
||||
//
|
||||
// thread-safe: it is safe for multiple threads to call this routine
|
||||
// (or, when referring to a class, methods of this class)
|
||||
// concurrently.
|
||||
// thread-hostile: it is not safe for multiple threads to call this
|
||||
// routine (or methods of this class) concurrently. In gflags,
|
||||
// most thread-hostile routines are intended to be called early in,
|
||||
// or even before, main() -- that is, before threads are spawned.
|
||||
// thread-compatible: it is safe for multiple threads to read from
|
||||
// this variable (when applied to variables), or to call const
|
||||
// methods of this class (when applied to classes), as long as no
|
||||
// other thread is writing to the variable or calling non-const
|
||||
// methods of this class.
|
||||
|
||||
#ifndef GFLAGS_GFLAGS_H_
|
||||
#define GFLAGS_GFLAGS_H_
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <gflags/gflags_declare.h> // IWYU pragma: export
|
||||
@ac_google_start_namespace@
|
||||
|
||||
//
|
||||
// NOTE: all functions below MUST have an explicit 'extern' before
|
||||
// them. Our automated opensourcing tools use this as a signal to do
|
||||
// appropriate munging for windows, which needs to add GFLAGS_DLL_DECL.
|
||||
//
|
||||
#define GFLAGS_DLL_DECL /* rewritten to be non-empty in windows dir */
|
||||
#define GFLAGS_DLL_DEFINE_FLAG /* rewritten to be non-empty in windows dir */
|
||||
|
||||
|
||||
// --------------------------------------------------------------------
|
||||
// To actually define a flag in a file, use DEFINE_bool,
|
||||
// DEFINE_string, etc. at the bottom of this file. You may also find
|
||||
// it useful to register a validator with the flag. This ensures that
|
||||
// when the flag is parsed from the commandline, or is later set via
|
||||
// SetCommandLineOption, we call the validation function. It is _not_
|
||||
// called when you assign the value to the flag directly using the = operator.
|
||||
//
|
||||
// The validation function should return true if the flag value is valid, and
|
||||
// false otherwise. If the function returns false for the new setting of the
|
||||
// flag, the flag will retain its current value. If it returns false for the
|
||||
// default value, ParseCommandLineFlags() will die.
|
||||
//
|
||||
// This function is safe to call at global construct time (as in the
|
||||
// example below).
|
||||
//
|
||||
// Example use:
|
||||
// static bool ValidatePort(const char* flagname, int32 value) {
|
||||
// if (value > 0 && value < 32768) // value is ok
|
||||
// return true;
|
||||
// printf("Invalid value for --%s: %d\n", flagname, (int)value);
|
||||
// return false;
|
||||
// }
|
||||
// DEFINE_int32(port, 0, "What port to listen on");
|
||||
// static bool dummy = RegisterFlagValidator(&FLAGS_port, &ValidatePort);
|
||||
|
||||
// Returns true if successfully registered, false if not (because the
|
||||
// first argument doesn't point to a command-line flag, or because a
|
||||
// validator is already registered for this flag).
|
||||
extern bool RegisterFlagValidator(const bool* flag,
|
||||
bool (*validate_fn)(const char*, bool));
|
||||
extern bool RegisterFlagValidator(const int32* flag,
|
||||
bool (*validate_fn)(const char*, int32));
|
||||
extern bool RegisterFlagValidator(const int64* flag,
|
||||
bool (*validate_fn)(const char*, int64));
|
||||
extern bool RegisterFlagValidator(const uint64* flag,
|
||||
bool (*validate_fn)(const char*, uint64));
|
||||
extern bool RegisterFlagValidator(const double* flag,
|
||||
bool (*validate_fn)(const char*, double));
|
||||
extern bool RegisterFlagValidator(const std::string* flag,
|
||||
bool (*validate_fn)(const char*,
|
||||
const std::string&));
|
||||
|
||||
// Convenience macro for the registration of a flag validator
|
||||
#define DEFINE_validator(name, validator) \
|
||||
static const bool name##_validator_registered = \
|
||||
@ac_google_namespace@::RegisterFlagValidator(&FLAGS_##name, validator)
|
||||
|
||||
|
||||
// --------------------------------------------------------------------
|
||||
// These methods are the best way to get access to info about the
|
||||
// list of commandline flags. Note that these routines are pretty slow.
|
||||
// GetAllFlags: mostly-complete info about the list, sorted by file.
|
||||
// ShowUsageWithFlags: pretty-prints the list to stdout (what --help does)
|
||||
// ShowUsageWithFlagsRestrict: limit to filenames with restrict as a substr
|
||||
//
|
||||
// In addition to accessing flags, you can also access argv[0] (the program
|
||||
// name) and argv (the entire commandline), which we sock away a copy of.
|
||||
// These variables are static, so you should only set them once.
|
||||
|
||||
struct GFLAGS_DLL_DECL CommandLineFlagInfo {
|
||||
std::string name; // the name of the flag
|
||||
std::string type; // the type of the flag: int32, etc
|
||||
std::string description; // the "help text" associated with the flag
|
||||
std::string current_value; // the current value, as a string
|
||||
std::string default_value; // the default value, as a string
|
||||
std::string filename; // 'cleaned' version of filename holding the flag
|
||||
bool has_validator_fn; // true if RegisterFlagValidator called on this flag
|
||||
bool is_default; // true if the flag has the default value and
|
||||
// has not been set explicitly from the cmdline
|
||||
// or via SetCommandLineOption
|
||||
const void* flag_ptr; // pointer to the flag's current value (i.e. FLAGS_foo)
|
||||
};
|
||||
|
||||
// Using this inside of a validator is a recipe for a deadlock.
|
||||
// TODO(user) Fix locking when validators are running, to make it safe to
|
||||
// call validators during ParseAllFlags.
|
||||
// Also make sure then to uncomment the corresponding unit test in
|
||||
// gflags_unittest.sh
|
||||
extern void GetAllFlags(std::vector<CommandLineFlagInfo>* OUTPUT);
|
||||
// These two are actually defined in gflags_reporting.cc.
|
||||
extern void ShowUsageWithFlags(const char *argv0); // what --help does
|
||||
extern void ShowUsageWithFlagsRestrict(const char *argv0, const char *restrict);
|
||||
|
||||
// Create a descriptive string for a flag.
|
||||
// Goes to some trouble to make pretty line breaks.
|
||||
extern std::string DescribeOneFlag(const CommandLineFlagInfo& flag);
|
||||
|
||||
// Thread-hostile; meant to be called before any threads are spawned.
|
||||
extern void SetArgv(int argc, const char** argv);
|
||||
|
||||
// The following functions are thread-safe as long as SetArgv() is
|
||||
// only called before any threads start.
|
||||
extern const std::vector<std::string>& GetArgvs();
|
||||
extern const char* GetArgv(); // all of argv as a string
|
||||
extern const char* GetArgv0(); // only argv0
|
||||
extern uint32 GetArgvSum(); // simple checksum of argv
|
||||
extern const char* ProgramInvocationName(); // argv0, or "UNKNOWN" if not set
|
||||
extern const char* ProgramInvocationShortName(); // basename(argv0)
|
||||
|
||||
// ProgramUsage() is thread-safe as long as SetUsageMessage() is only
|
||||
// called before any threads start.
|
||||
extern const char* ProgramUsage(); // string set by SetUsageMessage()
|
||||
|
||||
// VersionString() is thread-safe as long as SetVersionString() is only
|
||||
// called before any threads start.
|
||||
extern const char* VersionString(); // string set by SetVersionString()
|
||||
|
||||
|
||||
|
||||
// --------------------------------------------------------------------
|
||||
// Normally you access commandline flags by just saying "if (FLAGS_foo)"
|
||||
// or whatever, and set them by calling "FLAGS_foo = bar" (or, more
|
||||
// commonly, via the DEFINE_foo macro). But if you need a bit more
|
||||
// control, we have programmatic ways to get/set the flags as well.
|
||||
// These programmatic ways to access flags are thread-safe, but direct
|
||||
// access is only thread-compatible.
|
||||
|
||||
// Return true iff the flagname was found.
|
||||
// OUTPUT is set to the flag's value, or unchanged if we return false.
|
||||
extern bool GetCommandLineOption(const char* name, std::string* OUTPUT);
|
||||
|
||||
// Return true iff the flagname was found. OUTPUT is set to the flag's
|
||||
// CommandLineFlagInfo or unchanged if we return false.
|
||||
extern bool GetCommandLineFlagInfo(const char* name,
|
||||
CommandLineFlagInfo* OUTPUT);
|
||||
|
||||
// Return the CommandLineFlagInfo of the flagname. exit() if name not found.
|
||||
// Example usage, to check if a flag's value is currently the default value:
|
||||
// if (GetCommandLineFlagInfoOrDie("foo").is_default) ...
|
||||
extern CommandLineFlagInfo GetCommandLineFlagInfoOrDie(const char* name);
|
||||
|
||||
enum GFLAGS_DLL_DECL FlagSettingMode {
|
||||
// update the flag's value (can call this multiple times).
|
||||
SET_FLAGS_VALUE,
|
||||
// update the flag's value, but *only if* it has not yet been updated
|
||||
// with SET_FLAGS_VALUE, SET_FLAG_IF_DEFAULT, or "FLAGS_xxx = nondef".
|
||||
SET_FLAG_IF_DEFAULT,
|
||||
// set the flag's default value to this. If the flag has not yet updated
|
||||
// yet (via SET_FLAGS_VALUE, SET_FLAG_IF_DEFAULT, or "FLAGS_xxx = nondef")
|
||||
// change the flag's current value to the new default value as well.
|
||||
SET_FLAGS_DEFAULT
|
||||
};
|
||||
|
||||
// Set a particular flag ("command line option"). Returns a string
|
||||
// describing the new value that the option has been set to. The
|
||||
// return value API is not well-specified, so basically just depend on
|
||||
// it to be empty if the setting failed for some reason -- the name is
|
||||
// not a valid flag name, or the value is not a valid value -- and
|
||||
// non-empty else.
|
||||
|
||||
// SetCommandLineOption uses set_mode == SET_FLAGS_VALUE (the common case)
|
||||
extern std::string SetCommandLineOption(const char* name, const char* value);
|
||||
extern std::string SetCommandLineOptionWithMode(const char* name, const char* value,
|
||||
FlagSettingMode set_mode);
|
||||
|
||||
|
||||
// --------------------------------------------------------------------
|
||||
// Saves the states (value, default value, whether the user has set
|
||||
// the flag, registered validators, etc) of all flags, and restores
|
||||
// them when the FlagSaver is destroyed. This is very useful in
|
||||
// tests, say, when you want to let your tests change the flags, but
|
||||
// make sure that they get reverted to the original states when your
|
||||
// test is complete.
|
||||
//
|
||||
// Example usage:
|
||||
// void TestFoo() {
|
||||
// FlagSaver s1;
|
||||
// FLAG_foo = false;
|
||||
// FLAG_bar = "some value";
|
||||
//
|
||||
// // test happens here. You can return at any time
|
||||
// // without worrying about restoring the FLAG values.
|
||||
// }
|
||||
//
|
||||
// Note: This class is marked with ATTRIBUTE_UNUSED because all the
|
||||
// work is done in the constructor and destructor, so in the standard
|
||||
// usage example above, the compiler would complain that it's an
|
||||
// unused variable.
|
||||
//
|
||||
// This class is thread-safe. However, its destructor writes to
|
||||
// exactly the set of flags that have changed value during its
|
||||
// lifetime, so concurrent _direct_ access to those flags
|
||||
// (i.e. FLAGS_foo instead of {Get,Set}CommandLineOption()) is unsafe.
|
||||
|
||||
class GFLAGS_DLL_DECL FlagSaver {
|
||||
public:
|
||||
FlagSaver();
|
||||
~FlagSaver();
|
||||
|
||||
private:
|
||||
class FlagSaverImpl* impl_; // we use pimpl here to keep API steady
|
||||
|
||||
FlagSaver(const FlagSaver&); // no copying!
|
||||
void operator=(const FlagSaver&);
|
||||
}
|
||||
@ac_cv___attribute__unused@;
|
||||
|
||||
// --------------------------------------------------------------------
|
||||
// Some deprecated or hopefully-soon-to-be-deprecated functions.
|
||||
|
||||
// This is often used for logging. TODO(csilvers): figure out a better way
|
||||
extern std::string CommandlineFlagsIntoString();
|
||||
// Usually where this is used, a FlagSaver should be used instead.
|
||||
extern bool ReadFlagsFromString(const std::string& flagfilecontents,
|
||||
const char* prog_name,
|
||||
bool errors_are_fatal); // uses SET_FLAGS_VALUE
|
||||
|
||||
// These let you manually implement --flagfile functionality.
|
||||
// DEPRECATED.
|
||||
extern bool AppendFlagsIntoFile(const std::string& filename, const char* prog_name);
|
||||
extern bool ReadFromFlagsFile(const std::string& filename, const char* prog_name,
|
||||
bool errors_are_fatal); // uses SET_FLAGS_VALUE
|
||||
|
||||
|
||||
// --------------------------------------------------------------------
|
||||
// Useful routines for initializing flags from the environment.
|
||||
// In each case, if 'varname' does not exist in the environment
|
||||
// return defval. If 'varname' does exist but is not valid
|
||||
// (e.g., not a number for an int32 flag), abort with an error.
|
||||
// Otherwise, return the value. NOTE: for booleans, for true use
|
||||
// 't' or 'T' or 'true' or '1', for false 'f' or 'F' or 'false' or '0'.
|
||||
|
||||
extern bool BoolFromEnv(const char *varname, bool defval);
|
||||
extern int32 Int32FromEnv(const char *varname, int32 defval);
|
||||
extern int64 Int64FromEnv(const char *varname, int64 defval);
|
||||
extern uint64 Uint64FromEnv(const char *varname, uint64 defval);
|
||||
extern double DoubleFromEnv(const char *varname, double defval);
|
||||
extern const char *StringFromEnv(const char *varname, const char *defval);
|
||||
|
||||
|
||||
// --------------------------------------------------------------------
|
||||
// The next two functions parse gflags from main():
|
||||
|
||||
// Set the "usage" message for this program. For example:
|
||||
// string usage("This program does nothing. Sample usage:\n");
|
||||
// usage += argv[0] + " <uselessarg1> <uselessarg2>";
|
||||
// SetUsageMessage(usage);
|
||||
// Do not include commandline flags in the usage: we do that for you!
|
||||
// Thread-hostile; meant to be called before any threads are spawned.
|
||||
extern void SetUsageMessage(const std::string& usage);
|
||||
|
||||
// Sets the version string, which is emitted with --version.
|
||||
// For instance: SetVersionString("1.3");
|
||||
// Thread-hostile; meant to be called before any threads are spawned.
|
||||
extern void SetVersionString(const std::string& version);
|
||||
|
||||
|
||||
// Looks for flags in argv and parses them. Rearranges argv to put
|
||||
// flags first, or removes them entirely if remove_flags is true.
|
||||
// If a flag is defined more than once in the command line or flag
|
||||
// file, the last definition is used. Returns the index (into argv)
|
||||
// of the first non-flag argument.
|
||||
// See top-of-file for more details on this function.
|
||||
#ifndef SWIG // In swig, use ParseCommandLineFlagsScript() instead.
|
||||
extern uint32 ParseCommandLineFlags(int *argc, char*** argv, bool remove_flags);
|
||||
#endif
|
||||
|
||||
|
||||
// Calls to ParseCommandLineNonHelpFlags and then to
|
||||
// HandleCommandLineHelpFlags can be used instead of a call to
|
||||
// ParseCommandLineFlags during initialization, in order to allow for
|
||||
// changing default values for some FLAGS (via
|
||||
// e.g. SetCommandLineOptionWithMode calls) between the time of
|
||||
// command line parsing and the time of dumping help information for
|
||||
// the flags as a result of command line parsing. If a flag is
|
||||
// defined more than once in the command line or flag file, the last
|
||||
// definition is used. Returns the index (into argv) of the first
|
||||
// non-flag argument. (If remove_flags is true, will always return 1.)
|
||||
extern uint32 ParseCommandLineNonHelpFlags(int *argc, char*** argv,
|
||||
bool remove_flags);
|
||||
// This is actually defined in gflags_reporting.cc.
|
||||
// This function is misnamed (it also handles --version, etc.), but
|
||||
// it's too late to change that now. :-(
|
||||
extern void HandleCommandLineHelpFlags(); // in gflags_reporting.cc
|
||||
|
||||
// Allow command line reparsing. Disables the error normally
|
||||
// generated when an unknown flag is found, since it may be found in a
|
||||
// later parse. Thread-hostile; meant to be called before any threads
|
||||
// are spawned.
|
||||
extern void AllowCommandLineReparsing();
|
||||
|
||||
// Reparse the flags that have not yet been recognized. Only flags
|
||||
// registered since the last parse will be recognized. Any flag value
|
||||
// must be provided as part of the argument using "=", not as a
|
||||
// separate command line argument that follows the flag argument.
|
||||
// Intended for handling flags from dynamically loaded libraries,
|
||||
// since their flags are not registered until they are loaded.
|
||||
extern void ReparseCommandLineNonHelpFlags();
|
||||
|
||||
// Clean up memory allocated by flags. This is only needed to reduce
|
||||
// the quantity of "potentially leaked" reports emitted by memory
|
||||
// debugging tools such as valgrind. It is not required for normal
|
||||
// operation, or for the google perftools heap-checker. It must only
|
||||
// be called when the process is about to exit, and all threads that
|
||||
// might access flags are quiescent. Referencing flags after this is
|
||||
// called will have unexpected consequences. This is not safe to run
|
||||
// when multiple threads might be running: the function is
|
||||
// thread-hostile.
|
||||
extern void ShutDownCommandLineFlags();
|
||||
|
||||
|
||||
// --------------------------------------------------------------------
|
||||
// Now come the command line flag declaration/definition macros that
|
||||
// will actually be used. They're kind of hairy. A major reason
|
||||
// for this is initialization: we want people to be able to access
|
||||
// variables in global constructors and have that not crash, even if
|
||||
// their global constructor runs before the global constructor here.
|
||||
// (Obviously, we can't guarantee the flags will have the correct
|
||||
// default value in that case, but at least accessing them is safe.)
|
||||
// The only way to do that is have flags point to a static buffer.
|
||||
// So we make one, using a union to ensure proper alignment, and
|
||||
// then use placement-new to actually set up the flag with the
|
||||
// correct default value. In the same vein, we have to worry about
|
||||
// flag access in global destructors, so FlagRegisterer has to be
|
||||
// careful never to destroy the flag-values it constructs.
|
||||
//
|
||||
// Note that when we define a flag variable FLAGS_<name>, we also
|
||||
// preemptively define a junk variable, FLAGS_no<name>. This is to
|
||||
// cause a link-time error if someone tries to define 2 flags with
|
||||
// names like "logging" and "nologging". We do this because a bool
|
||||
// flag FLAG can be set from the command line to true with a "-FLAG"
|
||||
// argument, and to false with a "-noFLAG" argument, and so this can
|
||||
// potentially avert confusion.
|
||||
//
|
||||
// We also put flags into their own namespace. It is purposefully
|
||||
// named in an opaque way that people should have trouble typing
|
||||
// directly. The idea is that DEFINE puts the flag in the weird
|
||||
// namespace, and DECLARE imports the flag from there into the current
|
||||
// namespace. The net result is to force people to use DECLARE to get
|
||||
// access to a flag, rather than saying "extern bool FLAGS_whatever;"
|
||||
// or some such instead. We want this so we can put extra
|
||||
// functionality (like sanity-checking) in DECLARE if we want, and
|
||||
// make sure it is picked up everywhere.
|
||||
//
|
||||
// We also put the type of the variable in the namespace, so that
|
||||
// people can't DECLARE_int32 something that they DEFINE_bool'd
|
||||
// elsewhere.
|
||||
|
||||
class GFLAGS_DLL_DECL FlagRegisterer {
|
||||
public:
|
||||
FlagRegisterer(const char* name, const char* type,
|
||||
const char* help, const char* filename,
|
||||
void* current_storage, void* defvalue_storage);
|
||||
};
|
||||
|
||||
// If your application #defines STRIP_FLAG_HELP to a non-zero value
|
||||
// before #including this file, we remove the help message from the
|
||||
// binary file. This can reduce the size of the resulting binary
|
||||
// somewhat, and may also be useful for security reasons.
|
||||
|
||||
extern const char kStrippedFlagHelp[];
|
||||
|
||||
@ac_google_end_namespace@
|
||||
|
||||
#ifndef SWIG // In swig, ignore the main flag declarations
|
||||
|
||||
#if defined(STRIP_FLAG_HELP) && STRIP_FLAG_HELP > 0
|
||||
// Need this construct to avoid the 'defined but not used' warning.
|
||||
#define MAYBE_STRIPPED_HELP(txt) \
|
||||
(false ? (txt) : @ac_google_namespace@::kStrippedFlagHelp)
|
||||
#else
|
||||
#define MAYBE_STRIPPED_HELP(txt) txt
|
||||
#endif
|
||||
|
||||
// Each command-line flag has two variables associated with it: one
|
||||
// with the current value, and one with the default value. However,
|
||||
// we have a third variable, which is where value is assigned; it's a
|
||||
// constant. This guarantees that FLAG_##value is initialized at
|
||||
// static initialization time (e.g. before program-start) rather than
|
||||
// than global construction time (which is after program-start but
|
||||
// before main), at least when 'value' is a compile-time constant. We
|
||||
// use a small trick for the "default value" variable, and call it
|
||||
// FLAGS_no<name>. This serves the second purpose of assuring a
|
||||
// compile error if someone tries to define a flag named no<name>
|
||||
// which is illegal (--foo and --nofoo both affect the "foo" flag).
|
||||
#define DEFINE_VARIABLE(type, shorttype, name, value, help) \
|
||||
namespace fL##shorttype { \
|
||||
static const type FLAGS_nono##name = value; \
|
||||
/* We always want to export defined variables, dll or no */ \
|
||||
GFLAGS_DLL_DEFINE_FLAG type FLAGS_##name = FLAGS_nono##name; \
|
||||
type FLAGS_no##name = FLAGS_nono##name; \
|
||||
static @ac_google_namespace@::FlagRegisterer o_##name( \
|
||||
#name, #type, MAYBE_STRIPPED_HELP(help), __FILE__, \
|
||||
&FLAGS_##name, &FLAGS_no##name); \
|
||||
} \
|
||||
using fL##shorttype::FLAGS_##name
|
||||
|
||||
// For DEFINE_bool, we want to do the extra check that the passed-in
|
||||
// value is actually a bool, and not a string or something that can be
|
||||
// coerced to a bool. These declarations (no definition needed!) will
|
||||
// help us do that, and never evaluate From, which is important.
|
||||
// We'll use 'sizeof(IsBool(val))' to distinguish. This code requires
|
||||
// that the compiler have different sizes for bool & double. Since
|
||||
// this is not guaranteed by the standard, we check it with a
|
||||
// COMPILE_ASSERT.
|
||||
namespace fLB {
|
||||
struct CompileAssert {};
|
||||
typedef CompileAssert expected_sizeof_double_neq_sizeof_bool[
|
||||
(sizeof(double) != sizeof(bool)) ? 1 : -1];
|
||||
template<typename From> double GFLAGS_DLL_DECL IsBoolFlag(const From& from);
|
||||
GFLAGS_DLL_DECL bool IsBoolFlag(bool from);
|
||||
} // namespace fLB
|
||||
|
||||
// Here are the actual DEFINE_*-macros. The respective DECLARE_*-macros
|
||||
// are in a separate include, gflags_declare.h, for reducing
|
||||
// the physical transitive size for DECLARE use.
|
||||
#define DEFINE_bool(name, val, txt) \
|
||||
namespace fLB { \
|
||||
typedef ::fLB::CompileAssert FLAG_##name##_value_is_not_a_bool[ \
|
||||
(sizeof(::fLB::IsBoolFlag(val)) != sizeof(double)) ? 1 : -1]; \
|
||||
} \
|
||||
DEFINE_VARIABLE(bool, B, name, val, txt)
|
||||
|
||||
#define DEFINE_int32(name, val, txt) \
|
||||
DEFINE_VARIABLE(@ac_google_namespace@::int32, I, \
|
||||
name, val, txt)
|
||||
|
||||
#define DEFINE_int64(name, val, txt) \
|
||||
DEFINE_VARIABLE(@ac_google_namespace@::int64, I64, \
|
||||
name, val, txt)
|
||||
|
||||
#define DEFINE_uint64(name,val, txt) \
|
||||
DEFINE_VARIABLE(@ac_google_namespace@::uint64, U64, \
|
||||
name, val, txt)
|
||||
|
||||
#define DEFINE_double(name, val, txt) \
|
||||
DEFINE_VARIABLE(double, D, name, val, txt)
|
||||
|
||||
// Strings are trickier, because they're not a POD, so we can't
|
||||
// construct them at static-initialization time (instead they get
|
||||
// constructed at global-constructor time, which is much later). To
|
||||
// try to avoid crashes in that case, we use a char buffer to store
|
||||
// the string, which we can static-initialize, and then placement-new
|
||||
// into it later. It's not perfect, but the best we can do.
|
||||
|
||||
namespace fLS {
|
||||
|
||||
inline clstring* dont_pass0toDEFINE_string(char *stringspot,
|
||||
const char *value) {
|
||||
return new(stringspot) clstring(value);
|
||||
}
|
||||
inline clstring* dont_pass0toDEFINE_string(char *stringspot,
|
||||
const clstring &value) {
|
||||
return new(stringspot) clstring(value);
|
||||
}
|
||||
inline clstring* dont_pass0toDEFINE_string(char *stringspot,
|
||||
int value);
|
||||
} // namespace fLS
|
||||
|
||||
// We need to define a var named FLAGS_no##name so people don't define
|
||||
// --string and --nostring. And we need a temporary place to put val
|
||||
// so we don't have to evaluate it twice. Two great needs that go
|
||||
// great together!
|
||||
// The weird 'using' + 'extern' inside the fLS namespace is to work around
|
||||
// an unknown compiler bug/issue with the gcc 4.2.1 on SUSE 10. See
|
||||
// http://code.google.com/p/google-gflags/issues/detail?id=20
|
||||
#define DEFINE_string(name, val, txt) \
|
||||
namespace fLS { \
|
||||
using ::fLS::clstring; \
|
||||
static union { void* align; char s[sizeof(clstring)]; } s_##name[2]; \
|
||||
clstring* const FLAGS_no##name = ::fLS:: \
|
||||
dont_pass0toDEFINE_string(s_##name[0].s, \
|
||||
val); \
|
||||
static @ac_google_namespace@::FlagRegisterer o_##name( \
|
||||
#name, "string", MAYBE_STRIPPED_HELP(txt), __FILE__, \
|
||||
s_##name[0].s, new (s_##name[1].s) clstring(*FLAGS_no##name)); \
|
||||
extern GFLAGS_DLL_DEFINE_FLAG clstring& FLAGS_##name; \
|
||||
using fLS::FLAGS_##name; \
|
||||
clstring& FLAGS_##name = *FLAGS_no##name; \
|
||||
} \
|
||||
using fLS::FLAGS_##name
|
||||
|
||||
#endif // SWIG
|
||||
|
||||
#endif // GFLAGS_GFLAGS_H_
|
|
@ -0,0 +1,130 @@
|
|||
// Copyright (c) 2008, Google Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following disclaimer
|
||||
// in the documentation and/or other materials provided with the
|
||||
// distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from
|
||||
// this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
//
|
||||
// ---
|
||||
|
||||
//
|
||||
// Implement helpful bash-style command line flag completions
|
||||
//
|
||||
// ** Functional API:
|
||||
// HandleCommandLineCompletions() should be called early during
|
||||
// program startup, but after command line flag code has been
|
||||
// initialized, such as the beginning of HandleCommandLineHelpFlags().
|
||||
// It checks the value of the flag --tab_completion_word. If this
|
||||
// flag is empty, nothing happens here. If it contains a string,
|
||||
// however, then HandleCommandLineCompletions() will hijack the
|
||||
// process, attempting to identify the intention behind this
|
||||
// completion. Regardless of the outcome of this deduction, the
|
||||
// process will be terminated, similar to --helpshort flag
|
||||
// handling.
|
||||
//
|
||||
// ** Overview of Bash completions:
|
||||
// Bash can be told to programatically determine completions for the
|
||||
// current 'cursor word'. It does this by (in this case) invoking a
|
||||
// command with some additional arguments identifying the command
|
||||
// being executed, the word being completed, and the previous word
|
||||
// (if any). Bash then expects a sequence of output lines to be
|
||||
// printed to stdout. If these lines all contain a common prefix
|
||||
// longer than the cursor word, bash will replace the cursor word
|
||||
// with that common prefix, and display nothing. If there isn't such
|
||||
// a common prefix, bash will display the lines in pages using 'more'.
|
||||
//
|
||||
// ** Strategy taken for command line completions:
|
||||
// If we can deduce either the exact flag intended, or a common flag
|
||||
// prefix, we'll output exactly that. Otherwise, if information
|
||||
// must be displayed to the user, we'll take the opportunity to add
|
||||
// some helpful information beyond just the flag name (specifically,
|
||||
// we'll include the default flag value and as much of the flag's
|
||||
// description as can fit on a single terminal line width, as specified
|
||||
// by the flag --tab_completion_columns). Furthermore, we'll try to
|
||||
// make bash order the output such that the most useful or relevent
|
||||
// flags are the most likely to be shown at the top.
|
||||
//
|
||||
// ** Additional features:
|
||||
// To assist in finding that one really useful flag, substring matching
|
||||
// was implemented. Before pressing a <TAB> to get completion for the
|
||||
// current word, you can append one or more '?' to the flag to do
|
||||
// substring matching. Here's the semantics:
|
||||
// --foo<TAB> Show me all flags with names prefixed by 'foo'
|
||||
// --foo?<TAB> Show me all flags with 'foo' somewhere in the name
|
||||
// --foo??<TAB> Same as prior case, but also search in module
|
||||
// definition path for 'foo'
|
||||
// --foo???<TAB> Same as prior case, but also search in flag
|
||||
// descriptions for 'foo'
|
||||
// Finally, we'll trim the output to a relatively small number of
|
||||
// flags to keep bash quiet about the verbosity of output. If one
|
||||
// really wanted to see all possible matches, appending a '+' to the
|
||||
// search word will force the exhaustive list of matches to be printed.
|
||||
//
|
||||
// ** How to have bash accept completions from a binary:
|
||||
// Bash requires that it be informed about each command that programmatic
|
||||
// completion should be enabled for. Example addition to a .bashrc
|
||||
// file would be (your path to gflags_completions.sh file may differ):
|
||||
|
||||
/*
|
||||
$ complete -o bashdefault -o default -o nospace -C \
|
||||
'/home/build/eng/bash/bash_completions.sh --tab_completion_columns $COLUMNS' \
|
||||
time env binary_name another_binary [...]
|
||||
*/
|
||||
|
||||
// This would allow the following to work:
|
||||
// $ /path/to/binary_name --vmodule<TAB>
|
||||
// Or:
|
||||
// $ ./bin/path/another_binary --gfs_u<TAB>
|
||||
// (etc)
|
||||
//
|
||||
// Sadly, it appears that bash gives no easy way to force this behavior for
|
||||
// all commands. That's where the "time" in the above example comes in.
|
||||
// If you haven't specifically added a command to the list of completion
|
||||
// supported commands, you can still get completions by prefixing the
|
||||
// entire command with "env".
|
||||
// $ env /some/brand/new/binary --vmod<TAB>
|
||||
// Assuming that "binary" is a newly compiled binary, this should still
|
||||
// produce the expected completion output.
|
||||
|
||||
|
||||
#ifndef GFLAGS_COMPLETIONS_H_
|
||||
#define GFLAGS_COMPLETIONS_H_
|
||||
|
||||
// Annoying stuff for windows -- makes sure clients can import these functions
|
||||
//
|
||||
// NOTE: all functions below MUST have an explicit 'extern' before
|
||||
// them. Our automated opensourcing tools use this as a signal to do
|
||||
// appropriate munging for windows, which needs to add GFLAGS_DLL_DECL.
|
||||
//
|
||||
#define GFLAGS_DLL_DECL /* rewritten to be non-empty in windows dir */
|
||||
|
||||
|
||||
@ac_google_start_namespace@
|
||||
|
||||
extern void HandleCommandLineCompletions(void);
|
||||
|
||||
@ac_google_end_namespace@
|
||||
|
||||
#endif // GFLAGS_COMPLETIONS_H_
|
|
@ -0,0 +1,112 @@
|
|||
// Copyright (c) 1999, Google Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following disclaimer
|
||||
// in the documentation and/or other materials provided with the
|
||||
// distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from
|
||||
// this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
// ---
|
||||
//
|
||||
// Revamped and reorganized by Craig Silverstein
|
||||
//
|
||||
// This is the file that should be included by any file which declares
|
||||
// command line flag.
|
||||
|
||||
#ifndef GFLAGS_DECLARE_H_
|
||||
#define GFLAGS_DECLARE_H_
|
||||
|
||||
#include <string>
|
||||
#if @ac_cv_have_stdint_h@
|
||||
#include <stdint.h> // the normal place uint16_t is defined
|
||||
#endif
|
||||
#if @ac_cv_have_systypes_h@
|
||||
#include <sys/types.h> // the normal place u_int16_t is defined
|
||||
#endif
|
||||
#if @ac_cv_have_inttypes_h@
|
||||
#include <inttypes.h> // a third place for uint16_t or u_int16_t
|
||||
#endif
|
||||
|
||||
@ac_google_start_namespace@
|
||||
#if @ac_cv_have_uint16_t@ // the C99 format
|
||||
typedef int32_t int32;
|
||||
typedef uint32_t uint32;
|
||||
typedef int64_t int64;
|
||||
typedef uint64_t uint64;
|
||||
#elif @ac_cv_have_u_int16_t@ // the BSD format
|
||||
typedef int32_t int32;
|
||||
typedef u_int32_t uint32;
|
||||
typedef int64_t int64;
|
||||
typedef u_int64_t uint64;
|
||||
#elif @ac_cv_have___int16@ // the windows (vc7) format
|
||||
typedef __int32 int32;
|
||||
typedef unsigned __int32 uint32;
|
||||
typedef __int64 int64;
|
||||
typedef unsigned __int64 uint64;
|
||||
#else
|
||||
#error Do not know how to define a 32-bit integer quantity on your system
|
||||
#endif
|
||||
@ac_google_end_namespace@
|
||||
|
||||
|
||||
#define GFLAGS_DLL_DECLARE_FLAG /* rewritten to be non-empty in windows dir */
|
||||
|
||||
namespace fLS {
|
||||
|
||||
// The meaning of "string" might be different between now and when the
|
||||
// macros below get invoked (e.g., if someone is experimenting with
|
||||
// other string implementations that get defined after this file is
|
||||
// included). Save the current meaning now and use it in the macros.
|
||||
typedef std::string clstring;
|
||||
|
||||
}
|
||||
|
||||
#define DECLARE_VARIABLE(type, shorttype, name) \
|
||||
/* We always want to import declared variables, dll or no */ \
|
||||
namespace fL##shorttype { extern GFLAGS_DLL_DECLARE_FLAG type FLAGS_##name; } \
|
||||
using fL##shorttype::FLAGS_##name
|
||||
|
||||
#define DECLARE_bool(name) \
|
||||
DECLARE_VARIABLE(bool, B, name)
|
||||
|
||||
#define DECLARE_int32(name) \
|
||||
DECLARE_VARIABLE(@ac_google_namespace@::int32, I, name)
|
||||
|
||||
#define DECLARE_int64(name) \
|
||||
DECLARE_VARIABLE(@ac_google_namespace@::int64, I64, name)
|
||||
|
||||
#define DECLARE_uint64(name) \
|
||||
DECLARE_VARIABLE(@ac_google_namespace@::uint64, U64, name)
|
||||
|
||||
#define DECLARE_double(name) \
|
||||
DECLARE_VARIABLE(double, D, name)
|
||||
|
||||
#define DECLARE_string(name) \
|
||||
namespace fLS { \
|
||||
using ::fLS::clstring; \
|
||||
extern GFLAGS_DLL_DECLARE_FLAG ::fLS::clstring& FLAGS_##name; \
|
||||
} \
|
||||
using fLS::FLAGS_##name
|
||||
|
||||
#endif // GFLAGS_DECLARE_H_
|
|
@ -0,0 +1,768 @@
|
|||
// Copyright (c) 2008, Google Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following disclaimer
|
||||
// in the documentation and/or other materials provided with the
|
||||
// distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from
|
||||
// this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
//
|
||||
// ---
|
||||
|
||||
// Bash-style command line flag completion for C++ binaries
|
||||
//
|
||||
// This module implements bash-style completions. It achieves this
|
||||
// goal in the following broad chunks:
|
||||
//
|
||||
// 1) Take a to-be-completed word, and examine it for search hints
|
||||
// 2) Identify all potentially matching flags
|
||||
// 2a) If there are no matching flags, do nothing.
|
||||
// 2b) If all matching flags share a common prefix longer than the
|
||||
// completion word, output just that matching prefix
|
||||
// 3) Categorize those flags to produce a rough ordering of relevence.
|
||||
// 4) Potentially trim the set of flags returned to a smaller number
|
||||
// that bash is happier with
|
||||
// 5) Output the matching flags in groups ordered by relevence.
|
||||
// 5a) Force bash to place most-relevent groups at the top of the list
|
||||
// 5b) Trim most flag's descriptions to fit on a single terminal line
|
||||
|
||||
|
||||
#include <config.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h> // for strlen
|
||||
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include <gflags/gflags.h>
|
||||
#include "util.h"
|
||||
|
||||
using std::set;
|
||||
using std::string;
|
||||
using std::vector;
|
||||
|
||||
#ifndef PATH_SEPARATOR
|
||||
#define PATH_SEPARATOR '/'
|
||||
#endif
|
||||
|
||||
DEFINE_string(tab_completion_word, "",
|
||||
"If non-empty, HandleCommandLineCompletions() will hijack the "
|
||||
"process and attempt to do bash-style command line flag "
|
||||
"completion on this value.");
|
||||
DEFINE_int32(tab_completion_columns, 80,
|
||||
"Number of columns to use in output for tab completion");
|
||||
|
||||
_START_GOOGLE_NAMESPACE_
|
||||
|
||||
namespace {
|
||||
// Function prototypes and Type forward declarations. Code may be
|
||||
// more easily understood if it is roughly ordered according to
|
||||
// control flow, rather than by C's "declare before use" ordering
|
||||
struct CompletionOptions;
|
||||
struct NotableFlags;
|
||||
|
||||
// The entry point if flag completion is to be used.
|
||||
static void PrintFlagCompletionInfo(void);
|
||||
|
||||
|
||||
// 1) Examine search word
|
||||
static void CanonicalizeCursorWordAndSearchOptions(
|
||||
const string &cursor_word,
|
||||
string *canonical_search_token,
|
||||
CompletionOptions *options);
|
||||
|
||||
static bool RemoveTrailingChar(string *str, char c);
|
||||
|
||||
|
||||
// 2) Find all matches
|
||||
static void FindMatchingFlags(
|
||||
const vector<CommandLineFlagInfo> &all_flags,
|
||||
const CompletionOptions &options,
|
||||
const string &match_token,
|
||||
set<const CommandLineFlagInfo *> *all_matches,
|
||||
string *longest_common_prefix);
|
||||
|
||||
static bool DoesSingleFlagMatch(
|
||||
const CommandLineFlagInfo &flag,
|
||||
const CompletionOptions &options,
|
||||
const string &match_token);
|
||||
|
||||
|
||||
// 3) Categorize matches
|
||||
static void CategorizeAllMatchingFlags(
|
||||
const set<const CommandLineFlagInfo *> &all_matches,
|
||||
const string &search_token,
|
||||
const string &module,
|
||||
const string &package_dir,
|
||||
NotableFlags *notable_flags);
|
||||
|
||||
static void TryFindModuleAndPackageDir(
|
||||
const vector<CommandLineFlagInfo> all_flags,
|
||||
string *module,
|
||||
string *package_dir);
|
||||
|
||||
|
||||
// 4) Decide which flags to use
|
||||
static void FinalizeCompletionOutput(
|
||||
const set<const CommandLineFlagInfo *> &matching_flags,
|
||||
CompletionOptions *options,
|
||||
NotableFlags *notable_flags,
|
||||
vector<string> *completions);
|
||||
|
||||
static void RetrieveUnusedFlags(
|
||||
const set<const CommandLineFlagInfo *> &matching_flags,
|
||||
const NotableFlags ¬able_flags,
|
||||
set<const CommandLineFlagInfo *> *unused_flags);
|
||||
|
||||
|
||||
// 5) Output matches
|
||||
static void OutputSingleGroupWithLimit(
|
||||
const set<const CommandLineFlagInfo *> &group,
|
||||
const string &line_indentation,
|
||||
const string &header,
|
||||
const string &footer,
|
||||
bool long_output_format,
|
||||
int *remaining_line_limit,
|
||||
size_t *completion_elements_added,
|
||||
vector<string> *completions);
|
||||
|
||||
// (helpers for #5)
|
||||
static string GetShortFlagLine(
|
||||
const string &line_indentation,
|
||||
const CommandLineFlagInfo &info);
|
||||
|
||||
static string GetLongFlagLine(
|
||||
const string &line_indentation,
|
||||
const CommandLineFlagInfo &info);
|
||||
|
||||
|
||||
//
|
||||
// Useful types
|
||||
|
||||
// Try to deduce the intentions behind this completion attempt. Return the
|
||||
// canonical search term in 'canonical_search_token'. Binary search options
|
||||
// are returned in the various booleans, which should all have intuitive
|
||||
// semantics, possibly except:
|
||||
// - return_all_matching_flags: Generally, we'll trim the number of
|
||||
// returned candidates to some small number, showing those that are
|
||||
// most likely to be useful first. If this is set, however, the user
|
||||
// really does want us to return every single flag as an option.
|
||||
// - force_no_update: Any time we output lines, all of which share a
|
||||
// common prefix, bash will 'helpfully' not even bother to show the
|
||||
// output, instead changing the current word to be that common prefix.
|
||||
// If it's clear this shouldn't happen, we'll set this boolean
|
||||
struct CompletionOptions {
|
||||
bool flag_name_substring_search;
|
||||
bool flag_location_substring_search;
|
||||
bool flag_description_substring_search;
|
||||
bool return_all_matching_flags;
|
||||
bool force_no_update;
|
||||
};
|
||||
|
||||
// Notable flags are flags that are special or preferred for some
|
||||
// reason. For example, flags that are defined in the binary's module
|
||||
// are expected to be much more relevent than flags defined in some
|
||||
// other random location. These sets are specified roughly in precedence
|
||||
// order. Once a flag is placed in one of these 'higher' sets, it won't
|
||||
// be placed in any of the 'lower' sets.
|
||||
struct NotableFlags {
|
||||
typedef set<const CommandLineFlagInfo *> FlagSet;
|
||||
FlagSet perfect_match_flag;
|
||||
FlagSet module_flags; // Found in module file
|
||||
FlagSet package_flags; // Found in same directory as module file
|
||||
FlagSet most_common_flags; // One of the XXX most commonly supplied flags
|
||||
FlagSet subpackage_flags; // Found in subdirectories of package
|
||||
};
|
||||
|
||||
|
||||
//
|
||||
// Tab completion implementation - entry point
|
||||
static void PrintFlagCompletionInfo(void) {
|
||||
string cursor_word = FLAGS_tab_completion_word;
|
||||
string canonical_token;
|
||||
CompletionOptions options = { };
|
||||
CanonicalizeCursorWordAndSearchOptions(
|
||||
cursor_word,
|
||||
&canonical_token,
|
||||
&options);
|
||||
|
||||
DVLOG(1) << "Identified canonical_token: '" << canonical_token << "'";
|
||||
|
||||
vector<CommandLineFlagInfo> all_flags;
|
||||
set<const CommandLineFlagInfo *> matching_flags;
|
||||
GetAllFlags(&all_flags);
|
||||
DVLOG(2) << "Found " << all_flags.size() << " flags overall";
|
||||
|
||||
string longest_common_prefix;
|
||||
FindMatchingFlags(
|
||||
all_flags,
|
||||
options,
|
||||
canonical_token,
|
||||
&matching_flags,
|
||||
&longest_common_prefix);
|
||||
DVLOG(1) << "Identified " << matching_flags.size() << " matching flags";
|
||||
DVLOG(1) << "Identified " << longest_common_prefix
|
||||
<< " as longest common prefix.";
|
||||
if (longest_common_prefix.size() > canonical_token.size()) {
|
||||
// There's actually a shared common prefix to all matching flags,
|
||||
// so may as well output that and quit quickly.
|
||||
DVLOG(1) << "The common prefix '" << longest_common_prefix
|
||||
<< "' was longer than the token '" << canonical_token
|
||||
<< "'. Returning just this prefix for completion.";
|
||||
fprintf(stdout, "--%s", longest_common_prefix.c_str());
|
||||
return;
|
||||
}
|
||||
if (matching_flags.empty()) {
|
||||
VLOG(1) << "There were no matching flags, returning nothing.";
|
||||
return;
|
||||
}
|
||||
|
||||
string module;
|
||||
string package_dir;
|
||||
TryFindModuleAndPackageDir(all_flags, &module, &package_dir);
|
||||
DVLOG(1) << "Identified module: '" << module << "'";
|
||||
DVLOG(1) << "Identified package_dir: '" << package_dir << "'";
|
||||
|
||||
NotableFlags notable_flags;
|
||||
CategorizeAllMatchingFlags(
|
||||
matching_flags,
|
||||
canonical_token,
|
||||
module,
|
||||
package_dir,
|
||||
¬able_flags);
|
||||
DVLOG(2) << "Categorized matching flags:";
|
||||
DVLOG(2) << " perfect_match: " << notable_flags.perfect_match_flag.size();
|
||||
DVLOG(2) << " module: " << notable_flags.module_flags.size();
|
||||
DVLOG(2) << " package: " << notable_flags.package_flags.size();
|
||||
DVLOG(2) << " most common: " << notable_flags.most_common_flags.size();
|
||||
DVLOG(2) << " subpackage: " << notable_flags.subpackage_flags.size();
|
||||
|
||||
vector<string> completions;
|
||||
FinalizeCompletionOutput(
|
||||
matching_flags,
|
||||
&options,
|
||||
¬able_flags,
|
||||
&completions);
|
||||
|
||||
if (options.force_no_update)
|
||||
completions.push_back("~");
|
||||
|
||||
DVLOG(1) << "Finalized with " << completions.size()
|
||||
<< " chosen completions";
|
||||
|
||||
for (vector<string>::const_iterator it = completions.begin();
|
||||
it != completions.end();
|
||||
++it) {
|
||||
DVLOG(9) << " Completion entry: '" << *it << "'";
|
||||
fprintf(stdout, "%s\n", it->c_str());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 1) Examine search word (and helper method)
|
||||
static void CanonicalizeCursorWordAndSearchOptions(
|
||||
const string &cursor_word,
|
||||
string *canonical_search_token,
|
||||
CompletionOptions *options) {
|
||||
*canonical_search_token = cursor_word;
|
||||
if (canonical_search_token->empty()) return;
|
||||
|
||||
// Get rid of leading quotes and dashes in the search term
|
||||
if ((*canonical_search_token)[0] == '"')
|
||||
*canonical_search_token = canonical_search_token->substr(1);
|
||||
while ((*canonical_search_token)[0] == '-')
|
||||
*canonical_search_token = canonical_search_token->substr(1);
|
||||
|
||||
options->flag_name_substring_search = false;
|
||||
options->flag_location_substring_search = false;
|
||||
options->flag_description_substring_search = false;
|
||||
options->return_all_matching_flags = false;
|
||||
options->force_no_update = false;
|
||||
|
||||
// Look for all search options we can deduce now. Do this by walking
|
||||
// backwards through the term, looking for up to three '?' and up to
|
||||
// one '+' as suffixed characters. Consume them if found, and remove
|
||||
// them from the canonical search token.
|
||||
int found_question_marks = 0;
|
||||
int found_plusses = 0;
|
||||
while (true) {
|
||||
if (found_question_marks < 3 &&
|
||||
RemoveTrailingChar(canonical_search_token, '?')) {
|
||||
++found_question_marks;
|
||||
continue;
|
||||
}
|
||||
if (found_plusses < 1 &&
|
||||
RemoveTrailingChar(canonical_search_token, '+')) {
|
||||
++found_plusses;
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
switch (found_question_marks) { // all fallthroughs
|
||||
case 3: options->flag_description_substring_search = true;
|
||||
case 2: options->flag_location_substring_search = true;
|
||||
case 1: options->flag_name_substring_search = true;
|
||||
};
|
||||
|
||||
options->return_all_matching_flags = (found_plusses > 0);
|
||||
}
|
||||
|
||||
// Returns true if a char was removed
|
||||
static bool RemoveTrailingChar(string *str, char c) {
|
||||
if (str->empty()) return false;
|
||||
if ((*str)[str->size() - 1] == c) {
|
||||
*str = str->substr(0, str->size() - 1);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
// 2) Find all matches (and helper methods)
|
||||
static void FindMatchingFlags(
|
||||
const vector<CommandLineFlagInfo> &all_flags,
|
||||
const CompletionOptions &options,
|
||||
const string &match_token,
|
||||
set<const CommandLineFlagInfo *> *all_matches,
|
||||
string *longest_common_prefix) {
|
||||
all_matches->clear();
|
||||
bool first_match = true;
|
||||
for (vector<CommandLineFlagInfo>::const_iterator it = all_flags.begin();
|
||||
it != all_flags.end();
|
||||
++it) {
|
||||
if (DoesSingleFlagMatch(*it, options, match_token)) {
|
||||
all_matches->insert(&*it);
|
||||
if (first_match) {
|
||||
first_match = false;
|
||||
*longest_common_prefix = it->name;
|
||||
} else {
|
||||
if (longest_common_prefix->empty() || it->name.empty()) {
|
||||
longest_common_prefix->clear();
|
||||
continue;
|
||||
}
|
||||
string::size_type pos = 0;
|
||||
while (pos < longest_common_prefix->size() &&
|
||||
pos < it->name.size() &&
|
||||
(*longest_common_prefix)[pos] == it->name[pos])
|
||||
++pos;
|
||||
longest_common_prefix->erase(pos);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Given the set of all flags, the parsed match options, and the
|
||||
// canonical search token, produce the set of all candidate matching
|
||||
// flags for subsequent analysis or filtering.
|
||||
static bool DoesSingleFlagMatch(
|
||||
const CommandLineFlagInfo &flag,
|
||||
const CompletionOptions &options,
|
||||
const string &match_token) {
|
||||
// Is there a prefix match?
|
||||
string::size_type pos = flag.name.find(match_token);
|
||||
if (pos == 0) return true;
|
||||
|
||||
// Is there a substring match if we want it?
|
||||
if (options.flag_name_substring_search &&
|
||||
pos != string::npos)
|
||||
return true;
|
||||
|
||||
// Is there a location match if we want it?
|
||||
if (options.flag_location_substring_search &&
|
||||
flag.filename.find(match_token) != string::npos)
|
||||
return true;
|
||||
|
||||
// TODO(user): All searches should probably be case-insensitive
|
||||
// (especially this one...)
|
||||
if (options.flag_description_substring_search &&
|
||||
flag.description.find(match_token) != string::npos)
|
||||
return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// 3) Categorize matches (and helper method)
|
||||
|
||||
// Given a set of matching flags, categorize them by
|
||||
// likely relevence to this specific binary
|
||||
static void CategorizeAllMatchingFlags(
|
||||
const set<const CommandLineFlagInfo *> &all_matches,
|
||||
const string &search_token,
|
||||
const string &module, // empty if we couldn't find any
|
||||
const string &package_dir, // empty if we couldn't find any
|
||||
NotableFlags *notable_flags) {
|
||||
notable_flags->perfect_match_flag.clear();
|
||||
notable_flags->module_flags.clear();
|
||||
notable_flags->package_flags.clear();
|
||||
notable_flags->most_common_flags.clear();
|
||||
notable_flags->subpackage_flags.clear();
|
||||
|
||||
for (set<const CommandLineFlagInfo *>::const_iterator it =
|
||||
all_matches.begin();
|
||||
it != all_matches.end();
|
||||
++it) {
|
||||
DVLOG(2) << "Examining match '" << (*it)->name << "'";
|
||||
DVLOG(7) << " filename: '" << (*it)->filename << "'";
|
||||
string::size_type pos = string::npos;
|
||||
if (!package_dir.empty())
|
||||
pos = (*it)->filename.find(package_dir);
|
||||
string::size_type slash = string::npos;
|
||||
if (pos != string::npos) // candidate for package or subpackage match
|
||||
slash = (*it)->filename.find(
|
||||
PATH_SEPARATOR,
|
||||
pos + package_dir.size() + 1);
|
||||
|
||||
if ((*it)->name == search_token) {
|
||||
// Exact match on some flag's name
|
||||
notable_flags->perfect_match_flag.insert(*it);
|
||||
DVLOG(3) << "Result: perfect match";
|
||||
} else if (!module.empty() && (*it)->filename == module) {
|
||||
// Exact match on module filename
|
||||
notable_flags->module_flags.insert(*it);
|
||||
DVLOG(3) << "Result: module match";
|
||||
} else if (!package_dir.empty() &&
|
||||
pos != string::npos && slash == string::npos) {
|
||||
// In the package, since there was no slash after the package portion
|
||||
notable_flags->package_flags.insert(*it);
|
||||
DVLOG(3) << "Result: package match";
|
||||
} else if (false) {
|
||||
// In the list of the XXX most commonly supplied flags overall
|
||||
// TODO(user): Compile this list.
|
||||
DVLOG(3) << "Result: most-common match";
|
||||
} else if (!package_dir.empty() &&
|
||||
pos != string::npos && slash != string::npos) {
|
||||
// In a subdirectory of the package
|
||||
notable_flags->subpackage_flags.insert(*it);
|
||||
DVLOG(3) << "Result: subpackage match";
|
||||
}
|
||||
|
||||
DVLOG(3) << "Result: not special match";
|
||||
}
|
||||
}
|
||||
|
||||
static void PushNameWithSuffix(vector<string>* suffixes, const char* suffix) {
|
||||
suffixes->push_back(
|
||||
StringPrintf("/%s%s", ProgramInvocationShortName(), suffix));
|
||||
}
|
||||
|
||||
static void TryFindModuleAndPackageDir(
|
||||
const vector<CommandLineFlagInfo> all_flags,
|
||||
string *module,
|
||||
string *package_dir) {
|
||||
module->clear();
|
||||
package_dir->clear();
|
||||
|
||||
vector<string> suffixes;
|
||||
// TODO(user): There's some inherant ambiguity here - multiple directories
|
||||
// could share the same trailing folder and file structure (and even worse,
|
||||
// same file names), causing us to be unsure as to which of the two is the
|
||||
// actual package for this binary. In this case, we'll arbitrarily choose.
|
||||
PushNameWithSuffix(&suffixes, ".");
|
||||
PushNameWithSuffix(&suffixes, "-main.");
|
||||
PushNameWithSuffix(&suffixes, "_main.");
|
||||
// These four are new but probably merited?
|
||||
PushNameWithSuffix(&suffixes, "-test.");
|
||||
PushNameWithSuffix(&suffixes, "_test.");
|
||||
PushNameWithSuffix(&suffixes, "-unittest.");
|
||||
PushNameWithSuffix(&suffixes, "_unittest.");
|
||||
|
||||
for (vector<CommandLineFlagInfo>::const_iterator it = all_flags.begin();
|
||||
it != all_flags.end();
|
||||
++it) {
|
||||
for (vector<string>::const_iterator suffix = suffixes.begin();
|
||||
suffix != suffixes.end();
|
||||
++suffix) {
|
||||
// TODO(user): Make sure the match is near the end of the string
|
||||
if (it->filename.find(*suffix) != string::npos) {
|
||||
*module = it->filename;
|
||||
string::size_type sep = it->filename.rfind(PATH_SEPARATOR);
|
||||
*package_dir = it->filename.substr(0, (sep == string::npos) ? 0 : sep);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Can't specialize template type on a locally defined type. Silly C++...
|
||||
struct DisplayInfoGroup {
|
||||
const char* header;
|
||||
const char* footer;
|
||||
set<const CommandLineFlagInfo *> *group;
|
||||
|
||||
int SizeInLines() const {
|
||||
int size_in_lines = static_cast<int>(group->size()) + 1;
|
||||
if (strlen(header) > 0) {
|
||||
size_in_lines++;
|
||||
}
|
||||
if (strlen(footer) > 0) {
|
||||
size_in_lines++;
|
||||
}
|
||||
return size_in_lines;
|
||||
}
|
||||
};
|
||||
|
||||
// 4) Finalize and trim output flag set
|
||||
static void FinalizeCompletionOutput(
|
||||
const set<const CommandLineFlagInfo *> &matching_flags,
|
||||
CompletionOptions *options,
|
||||
NotableFlags *notable_flags,
|
||||
vector<string> *completions) {
|
||||
|
||||
// We want to output lines in groups. Each group needs to be indented
|
||||
// the same to keep its lines together. Unless otherwise required,
|
||||
// only 99 lines should be output to prevent bash from harassing the
|
||||
// user.
|
||||
|
||||
// First, figure out which output groups we'll actually use. For each
|
||||
// nonempty group, there will be ~3 lines of header & footer, plus all
|
||||
// output lines themselves.
|
||||
int max_desired_lines = // "999999 flags should be enough for anyone. -dave"
|
||||
(options->return_all_matching_flags ? 999999 : 98);
|
||||
int lines_so_far = 0;
|
||||
|
||||
vector<DisplayInfoGroup> output_groups;
|
||||
bool perfect_match_found = false;
|
||||
if (lines_so_far < max_desired_lines &&
|
||||
!notable_flags->perfect_match_flag.empty()) {
|
||||
perfect_match_found = true;
|
||||
DisplayInfoGroup group =
|
||||
{ "",
|
||||
"==========",
|
||||
¬able_flags->perfect_match_flag };
|
||||
lines_so_far += group.SizeInLines();
|
||||
output_groups.push_back(group);
|
||||
}
|
||||
if (lines_so_far < max_desired_lines &&
|
||||
!notable_flags->module_flags.empty()) {
|
||||
DisplayInfoGroup group = {
|
||||
"-* Matching module flags *-",
|
||||
"===========================",
|
||||
¬able_flags->module_flags };
|
||||
lines_so_far += group.SizeInLines();
|
||||
output_groups.push_back(group);
|
||||
}
|
||||
if (lines_so_far < max_desired_lines &&
|
||||
!notable_flags->package_flags.empty()) {
|
||||
DisplayInfoGroup group = {
|
||||
"-* Matching package flags *-",
|
||||
"============================",
|
||||
¬able_flags->package_flags };
|
||||
lines_so_far += group.SizeInLines();
|
||||
output_groups.push_back(group);
|
||||
}
|
||||
if (lines_so_far < max_desired_lines &&
|
||||
!notable_flags->most_common_flags.empty()) {
|
||||
DisplayInfoGroup group = {
|
||||
"-* Commonly used flags *-",
|
||||
"=========================",
|
||||
¬able_flags->most_common_flags };
|
||||
lines_so_far += group.SizeInLines();
|
||||
output_groups.push_back(group);
|
||||
}
|
||||
if (lines_so_far < max_desired_lines &&
|
||||
!notable_flags->subpackage_flags.empty()) {
|
||||
DisplayInfoGroup group = {
|
||||
"-* Matching sub-package flags *-",
|
||||
"================================",
|
||||
¬able_flags->subpackage_flags };
|
||||
lines_so_far += group.SizeInLines();
|
||||
output_groups.push_back(group);
|
||||
}
|
||||
|
||||
set<const CommandLineFlagInfo *> obscure_flags; // flags not notable
|
||||
if (lines_so_far < max_desired_lines) {
|
||||
RetrieveUnusedFlags(matching_flags, *notable_flags, &obscure_flags);
|
||||
if (!obscure_flags.empty()) {
|
||||
DisplayInfoGroup group = {
|
||||
"-* Other flags *-",
|
||||
"",
|
||||
&obscure_flags };
|
||||
lines_so_far += group.SizeInLines();
|
||||
output_groups.push_back(group);
|
||||
}
|
||||
}
|
||||
|
||||
// Second, go through each of the chosen output groups and output
|
||||
// as many of those flags as we can, while remaining below our limit
|
||||
int remaining_lines = max_desired_lines;
|
||||
size_t completions_output = 0;
|
||||
int indent = static_cast<int>(output_groups.size()) - 1;
|
||||
for (vector<DisplayInfoGroup>::const_iterator it =
|
||||
output_groups.begin();
|
||||
it != output_groups.end();
|
||||
++it, --indent) {
|
||||
OutputSingleGroupWithLimit(
|
||||
*it->group, // group
|
||||
string(indent, ' '), // line indentation
|
||||
string(it->header), // header
|
||||
string(it->footer), // footer
|
||||
perfect_match_found, // long format
|
||||
&remaining_lines, // line limit - reduces this by number printed
|
||||
&completions_output, // completions (not lines) added
|
||||
completions); // produced completions
|
||||
perfect_match_found = false;
|
||||
}
|
||||
|
||||
if (completions_output != matching_flags.size()) {
|
||||
options->force_no_update = false;
|
||||
completions->push_back("~ (Remaining flags hidden) ~");
|
||||
} else {
|
||||
options->force_no_update = true;
|
||||
}
|
||||
}
|
||||
|
||||
static void RetrieveUnusedFlags(
|
||||
const set<const CommandLineFlagInfo *> &matching_flags,
|
||||
const NotableFlags ¬able_flags,
|
||||
set<const CommandLineFlagInfo *> *unused_flags) {
|
||||
// Remove from 'matching_flags' set all members of the sets of
|
||||
// flags we've already printed (specifically, those in notable_flags)
|
||||
for (set<const CommandLineFlagInfo *>::const_iterator it =
|
||||
matching_flags.begin();
|
||||
it != matching_flags.end();
|
||||
++it) {
|
||||
if (notable_flags.perfect_match_flag.count(*it) ||
|
||||
notable_flags.module_flags.count(*it) ||
|
||||
notable_flags.package_flags.count(*it) ||
|
||||
notable_flags.most_common_flags.count(*it) ||
|
||||
notable_flags.subpackage_flags.count(*it))
|
||||
continue;
|
||||
unused_flags->insert(*it);
|
||||
}
|
||||
}
|
||||
|
||||
// 5) Output matches (and helper methods)
|
||||
|
||||
static void OutputSingleGroupWithLimit(
|
||||
const set<const CommandLineFlagInfo *> &group,
|
||||
const string &line_indentation,
|
||||
const string &header,
|
||||
const string &footer,
|
||||
bool long_output_format,
|
||||
int *remaining_line_limit,
|
||||
size_t *completion_elements_output,
|
||||
vector<string> *completions) {
|
||||
if (group.empty()) return;
|
||||
if (!header.empty()) {
|
||||
if (*remaining_line_limit < 2) return;
|
||||
*remaining_line_limit -= 2;
|
||||
completions->push_back(line_indentation + header);
|
||||
completions->push_back(line_indentation + string(header.size(), '-'));
|
||||
}
|
||||
for (set<const CommandLineFlagInfo *>::const_iterator it = group.begin();
|
||||
it != group.end() && *remaining_line_limit > 0;
|
||||
++it) {
|
||||
--*remaining_line_limit;
|
||||
++*completion_elements_output;
|
||||
completions->push_back(
|
||||
(long_output_format
|
||||
? GetLongFlagLine(line_indentation, **it)
|
||||
: GetShortFlagLine(line_indentation, **it)));
|
||||
}
|
||||
if (!footer.empty()) {
|
||||
if (*remaining_line_limit < 1) return;
|
||||
--*remaining_line_limit;
|
||||
completions->push_back(line_indentation + footer);
|
||||
}
|
||||
}
|
||||
|
||||
static string GetShortFlagLine(
|
||||
const string &line_indentation,
|
||||
const CommandLineFlagInfo &info) {
|
||||
string prefix;
|
||||
bool is_string = (info.type == "string");
|
||||
SStringPrintf(&prefix, "%s--%s [%s%s%s] ",
|
||||
line_indentation.c_str(),
|
||||
info.name.c_str(),
|
||||
(is_string ? "'" : ""),
|
||||
info.default_value.c_str(),
|
||||
(is_string ? "'" : ""));
|
||||
int remainder =
|
||||
FLAGS_tab_completion_columns - static_cast<int>(prefix.size());
|
||||
string suffix;
|
||||
if (remainder > 0)
|
||||
suffix =
|
||||
(static_cast<int>(info.description.size()) > remainder ?
|
||||
(info.description.substr(0, remainder - 3) + "...").c_str() :
|
||||
info.description.c_str());
|
||||
return prefix + suffix;
|
||||
}
|
||||
|
||||
static string GetLongFlagLine(
|
||||
const string &line_indentation,
|
||||
const CommandLineFlagInfo &info) {
|
||||
|
||||
string output = DescribeOneFlag(info);
|
||||
|
||||
// Replace '-' with '--', and remove trailing newline before appending
|
||||
// the module definition location.
|
||||
string old_flagname = "-" + info.name;
|
||||
output.replace(
|
||||
output.find(old_flagname),
|
||||
old_flagname.size(),
|
||||
"-" + old_flagname);
|
||||
// Stick a newline and indentation in front of the type and default
|
||||
// portions of DescribeOneFlag()s description
|
||||
static const char kNewlineWithIndent[] = "\n ";
|
||||
output.replace(output.find(" type:"), 1, string(kNewlineWithIndent));
|
||||
output.replace(output.find(" default:"), 1, string(kNewlineWithIndent));
|
||||
output = StringPrintf("%s Details for '--%s':\n"
|
||||
"%s defined: %s",
|
||||
line_indentation.c_str(),
|
||||
info.name.c_str(),
|
||||
output.c_str(),
|
||||
info.filename.c_str());
|
||||
|
||||
// Eliminate any doubled newlines that crept in. Specifically, if
|
||||
// DescribeOneFlag() decided to break the line just before "type"
|
||||
// or "default", we don't want to introduce an extra blank line
|
||||
static const string line_of_spaces(FLAGS_tab_completion_columns, ' ');
|
||||
static const char kDoubledNewlines[] = "\n \n";
|
||||
for (string::size_type newlines = output.find(kDoubledNewlines);
|
||||
newlines != string::npos;
|
||||
newlines = output.find(kDoubledNewlines))
|
||||
// Replace each 'doubled newline' with a single newline
|
||||
output.replace(newlines, sizeof(kDoubledNewlines) - 1, string("\n"));
|
||||
|
||||
for (string::size_type newline = output.find('\n');
|
||||
newline != string::npos;
|
||||
newline = output.find('\n')) {
|
||||
int newline_pos = static_cast<int>(newline) % FLAGS_tab_completion_columns;
|
||||
int missing_spaces = FLAGS_tab_completion_columns - newline_pos;
|
||||
output.replace(newline, 1, line_of_spaces, 1, missing_spaces);
|
||||
}
|
||||
return output;
|
||||
}
|
||||
} // anonymous
|
||||
|
||||
void HandleCommandLineCompletions(void) {
|
||||
if (FLAGS_tab_completion_word.empty()) return;
|
||||
PrintFlagCompletionInfo();
|
||||
gflags_exitfunc(0);
|
||||
}
|
||||
|
||||
_END_GOOGLE_NAMESPACE_
|
|
@ -0,0 +1,117 @@
|
|||
#!/bin/bash
|
||||
|
||||
# Copyright (c) 2008, Google Inc.
|
||||
# All rights reserved.
|
||||
#
|
||||
# Redistribution and use in source and binary forms, with or without
|
||||
# modification, are permitted provided that the following conditions are
|
||||
# met:
|
||||
#
|
||||
# * Redistributions of source code must retain the above copyright
|
||||
# notice, this list of conditions and the following disclaimer.
|
||||
# * Redistributions in binary form must reproduce the above
|
||||
# copyright notice, this list of conditions and the following disclaimer
|
||||
# in the documentation and/or other materials provided with the
|
||||
# distribution.
|
||||
# * Neither the name of Google Inc. nor the names of its
|
||||
# contributors may be used to endorse or promote products derived from
|
||||
# this software without specific prior written permission.
|
||||
#
|
||||
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
#
|
||||
# ---
|
||||
# Author: Dave Nicponski
|
||||
#
|
||||
# This script is invoked by bash in response to a matching compspec. When
|
||||
# this happens, bash calls this script using the command shown in the -C
|
||||
# block of the complete entry, but also appends 3 arguments. They are:
|
||||
# - The command being used for completion
|
||||
# - The word being completed
|
||||
# - The word preceding the completion word.
|
||||
#
|
||||
# Here's an example of how you might use this script:
|
||||
# $ complete -o bashdefault -o default -o nospace -C \
|
||||
# '/usr/local/bin/gflags_completions.sh --tab_completion_columns $COLUMNS' \
|
||||
# time env binary_name another_binary [...]
|
||||
|
||||
# completion_word_index gets the index of the (N-1)th argument for
|
||||
# this command line. completion_word gets the actual argument from
|
||||
# this command line at the (N-1)th position
|
||||
completion_word_index="$(($# - 1))"
|
||||
completion_word="${!completion_word_index}"
|
||||
|
||||
# TODO(user): Replace this once gflags_completions.cc has
|
||||
# a bool parameter indicating unambiguously to hijack the process for
|
||||
# completion purposes.
|
||||
if [ -z "$completion_word" ]; then
|
||||
# Until an empty value for the completion word stops being misunderstood
|
||||
# by binaries, don't actually execute the binary or the process
|
||||
# won't be hijacked!
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# binary_index gets the index of the command being completed (which bash
|
||||
# places in the (N-2)nd position. binary gets the actual command from
|
||||
# this command line at that (N-2)nd position
|
||||
binary_index="$(($# - 2))"
|
||||
binary="${!binary_index}"
|
||||
|
||||
# For completions to be universal, we may have setup the compspec to
|
||||
# trigger on 'harmless pass-through' commands, like 'time' or 'env'.
|
||||
# If the command being completed is one of those two, we'll need to
|
||||
# identify the actual command being executed. To do this, we need
|
||||
# the actual command line that the <TAB> was pressed on. Bash helpfully
|
||||
# places this in the $COMP_LINE variable.
|
||||
if [ "$binary" == "time" ] || [ "$binary" == "env" ]; then
|
||||
# we'll assume that the first 'argument' is actually the
|
||||
# binary
|
||||
|
||||
|
||||
# TODO(user): This is not perfect - the 'env' command, for instance,
|
||||
# is allowed to have options between the 'env' and 'the command to
|
||||
# be executed'. For example, consider:
|
||||
# $ env FOO="bar" bin/do_something --help<TAB>
|
||||
# In this case, we'll mistake the FOO="bar" portion as the binary.
|
||||
# Perhaps we should continuing consuming leading words until we
|
||||
# either run out of words, or find a word that is a valid file
|
||||
# marked as executable. I can't think of any reason this wouldn't
|
||||
# work.
|
||||
|
||||
# Break up the 'original command line' (not this script's command line,
|
||||
# rather the one the <TAB> was pressed on) and find the second word.
|
||||
parts=( ${COMP_LINE} )
|
||||
binary=${parts[1]}
|
||||
fi
|
||||
|
||||
# Build the command line to use for completion. Basically it involves
|
||||
# passing through all the arguments given to this script (except the 3
|
||||
# that bash added), and appending a '--tab_completion_word "WORD"' to
|
||||
# the arguments.
|
||||
params=""
|
||||
for ((i=1; i<=$(($# - 3)); ++i)); do
|
||||
params="$params \"${!i}\"";
|
||||
done
|
||||
params="$params --tab_completion_word \"$completion_word\""
|
||||
|
||||
# TODO(user): Perhaps stash the output in a temporary file somewhere
|
||||
# in /tmp, and only cat it to stdout if the command returned a success
|
||||
# code, to prevent false positives
|
||||
|
||||
# If we think we have a reasonable command to execute, then execute it
|
||||
# and hope for the best.
|
||||
candidate=$(type -p "$binary")
|
||||
if [ ! -z "$candidate" ]; then
|
||||
eval "$candidate 2>/dev/null $params"
|
||||
elif [ -f "$binary" ] && [ -x "$binary" ]; then
|
||||
eval "$binary 2>/dev/null $params"
|
||||
fi
|
|
@ -0,0 +1,68 @@
|
|||
// Copyright (c) 2009, Google Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following disclaimer
|
||||
// in the documentation and/or other materials provided with the
|
||||
// distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from
|
||||
// this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
// ---
|
||||
//
|
||||
// A negative comiple test for gflags.
|
||||
|
||||
#include <gflags/gflags.h>
|
||||
|
||||
#if defined(TEST_SWAPPED_ARGS)
|
||||
|
||||
DEFINE_bool(some_bool_flag,
|
||||
"the default value should go here, not the description",
|
||||
false);
|
||||
|
||||
|
||||
#elif defined(TEST_INT_INSTEAD_OF_BOOL)
|
||||
|
||||
DEFINE_bool(some_bool_flag_2,
|
||||
0,
|
||||
"should have been an int32 flag but mistakenly used bool instead");
|
||||
|
||||
#elif defined(TEST_BOOL_IN_QUOTES)
|
||||
|
||||
|
||||
DEFINE_bool(some_bool_flag_3,
|
||||
"false",
|
||||
"false in in quotes, which is wrong");
|
||||
|
||||
#elif defined(TEST_SANITY)
|
||||
|
||||
DEFINE_bool(some_bool_flag_4,
|
||||
true,
|
||||
"this is the correct usage of DEFINE_bool");
|
||||
|
||||
#elif defined(TEST_DEFINE_STRING_WITH_0)
|
||||
|
||||
DEFINE_string(some_string_flag,
|
||||
0,
|
||||
"Trying to construct a string by passing 0 would cause a crash.");
|
||||
|
||||
#endif
|
|
@ -0,0 +1,447 @@
|
|||
// Copyright (c) 1999, Google Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following disclaimer
|
||||
// in the documentation and/or other materials provided with the
|
||||
// distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from
|
||||
// this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
// ---
|
||||
//
|
||||
// Revamped and reorganized by Craig Silverstein
|
||||
//
|
||||
// This file contains code for handling the 'reporting' flags. These
|
||||
// are flags that, when present, cause the program to report some
|
||||
// information and then exit. --help and --version are the canonical
|
||||
// reporting flags, but we also have flags like --helpxml, etc.
|
||||
//
|
||||
// There's only one function that's meant to be called externally:
|
||||
// HandleCommandLineHelpFlags(). (Well, actually, ShowUsageWithFlags(),
|
||||
// ShowUsageWithFlagsRestrict(), and DescribeOneFlag() can be called
|
||||
// externally too, but there's little need for it.) These are all
|
||||
// declared in the main gflags.h header file.
|
||||
//
|
||||
// HandleCommandLineHelpFlags() will check what 'reporting' flags have
|
||||
// been defined, if any -- the "help" part of the function name is a
|
||||
// bit misleading -- and do the relevant reporting. It should be
|
||||
// called after all flag-values have been assigned, that is, after
|
||||
// parsing the command-line.
|
||||
|
||||
#include <config.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <ctype.h>
|
||||
#include <assert.h>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <gflags/gflags.h>
|
||||
#include <gflags/gflags_completions.h>
|
||||
#include "util.h"
|
||||
|
||||
#ifndef PATH_SEPARATOR
|
||||
#define PATH_SEPARATOR '/'
|
||||
#endif
|
||||
|
||||
// The 'reporting' flags. They all call gflags_exitfunc().
|
||||
DEFINE_bool(help, false,
|
||||
"show help on all flags [tip: all flags can have two dashes]");
|
||||
DEFINE_bool(helpfull, false,
|
||||
"show help on all flags -- same as -help");
|
||||
DEFINE_bool(helpshort, false,
|
||||
"show help on only the main module for this program");
|
||||
DEFINE_string(helpon, "",
|
||||
"show help on the modules named by this flag value");
|
||||
DEFINE_string(helpmatch, "",
|
||||
"show help on modules whose name contains the specified substr");
|
||||
DEFINE_bool(helppackage, false,
|
||||
"show help on all modules in the main package");
|
||||
DEFINE_bool(helpxml, false,
|
||||
"produce an xml version of help");
|
||||
DEFINE_bool(version, false,
|
||||
"show version and build info and exit");
|
||||
|
||||
_START_GOOGLE_NAMESPACE_
|
||||
|
||||
using std::string;
|
||||
using std::vector;
|
||||
|
||||
|
||||
// --------------------------------------------------------------------
|
||||
// DescribeOneFlag()
|
||||
// DescribeOneFlagInXML()
|
||||
// Routines that pretty-print info about a flag. These use
|
||||
// a CommandLineFlagInfo, which is the way the gflags
|
||||
// API exposes static info about a flag.
|
||||
// --------------------------------------------------------------------
|
||||
|
||||
static const int kLineLength = 80;
|
||||
|
||||
static void AddString(const string& s,
|
||||
string* final_string, int* chars_in_line) {
|
||||
const int slen = static_cast<int>(s.length());
|
||||
if (*chars_in_line + 1 + slen >= kLineLength) { // < 80 chars/line
|
||||
*final_string += "\n ";
|
||||
*chars_in_line = 6;
|
||||
} else {
|
||||
*final_string += " ";
|
||||
*chars_in_line += 1;
|
||||
}
|
||||
*final_string += s;
|
||||
*chars_in_line += slen;
|
||||
}
|
||||
|
||||
static string PrintStringFlagsWithQuotes(const CommandLineFlagInfo& flag,
|
||||
const string& text, bool current) {
|
||||
const char* c_string = (current ? flag.current_value.c_str() :
|
||||
flag.default_value.c_str());
|
||||
if (strcmp(flag.type.c_str(), "string") == 0) { // add quotes for strings
|
||||
return StringPrintf("%s: \"%s\"", text.c_str(), c_string);
|
||||
} else {
|
||||
return StringPrintf("%s: %s", text.c_str(), c_string);
|
||||
}
|
||||
}
|
||||
|
||||
// Create a descriptive string for a flag.
|
||||
// Goes to some trouble to make pretty line breaks.
|
||||
string DescribeOneFlag(const CommandLineFlagInfo& flag) {
|
||||
string main_part;
|
||||
SStringPrintf(&main_part, " -%s (%s)",
|
||||
flag.name.c_str(),
|
||||
flag.description.c_str());
|
||||
const char* c_string = main_part.c_str();
|
||||
int chars_left = static_cast<int>(main_part.length());
|
||||
string final_string = "";
|
||||
int chars_in_line = 0; // how many chars in current line so far?
|
||||
while (1) {
|
||||
assert(chars_left == strlen(c_string)); // Unless there's a \0 in there?
|
||||
const char* newline = strchr(c_string, '\n');
|
||||
if (newline == NULL && chars_in_line+chars_left < kLineLength) {
|
||||
// The whole remainder of the string fits on this line
|
||||
final_string += c_string;
|
||||
chars_in_line += chars_left;
|
||||
break;
|
||||
}
|
||||
if (newline != NULL && newline - c_string < kLineLength - chars_in_line) {
|
||||
int n = static_cast<int>(newline - c_string);
|
||||
final_string.append(c_string, n);
|
||||
chars_left -= n + 1;
|
||||
c_string += n + 1;
|
||||
} else {
|
||||
// Find the last whitespace on this 80-char line
|
||||
int whitespace = kLineLength-chars_in_line-1; // < 80 chars/line
|
||||
while ( whitespace > 0 && !isspace(c_string[whitespace]) ) {
|
||||
--whitespace;
|
||||
}
|
||||
if (whitespace <= 0) {
|
||||
// Couldn't find any whitespace to make a line break. Just dump the
|
||||
// rest out!
|
||||
final_string += c_string;
|
||||
chars_in_line = kLineLength; // next part gets its own line for sure!
|
||||
break;
|
||||
}
|
||||
final_string += string(c_string, whitespace);
|
||||
chars_in_line += whitespace;
|
||||
while (isspace(c_string[whitespace])) ++whitespace;
|
||||
c_string += whitespace;
|
||||
chars_left -= whitespace;
|
||||
}
|
||||
if (*c_string == '\0')
|
||||
break;
|
||||
StringAppendF(&final_string, "\n ");
|
||||
chars_in_line = 6;
|
||||
}
|
||||
|
||||
// Append data type
|
||||
AddString(string("type: ") + flag.type, &final_string, &chars_in_line);
|
||||
// The listed default value will be the actual default from the flag
|
||||
// definition in the originating source file, unless the value has
|
||||
// subsequently been modified using SetCommandLineOptionWithMode() with mode
|
||||
// SET_FLAGS_DEFAULT, or by setting FLAGS_foo = bar before ParseCommandLineFlags().
|
||||
AddString(PrintStringFlagsWithQuotes(flag, "default", false), &final_string,
|
||||
&chars_in_line);
|
||||
if (!flag.is_default) {
|
||||
AddString(PrintStringFlagsWithQuotes(flag, "currently", true),
|
||||
&final_string, &chars_in_line);
|
||||
}
|
||||
|
||||
StringAppendF(&final_string, "\n");
|
||||
return final_string;
|
||||
}
|
||||
|
||||
// Simple routine to xml-escape a string: escape & and < only.
|
||||
static string XMLText(const string& txt) {
|
||||
string ans = txt;
|
||||
for (string::size_type pos = 0; (pos = ans.find("&", pos)) != string::npos; )
|
||||
ans.replace(pos++, 1, "&");
|
||||
for (string::size_type pos = 0; (pos = ans.find("<", pos)) != string::npos; )
|
||||
ans.replace(pos++, 1, "<");
|
||||
return ans;
|
||||
}
|
||||
|
||||
static void AddXMLTag(string* r, const char* tag, const string& txt) {
|
||||
StringAppendF(r, "<%s>%s</%s>", tag, XMLText(txt).c_str(), tag);
|
||||
}
|
||||
|
||||
|
||||
static string DescribeOneFlagInXML(const CommandLineFlagInfo& flag) {
|
||||
// The file and flagname could have been attributes, but default
|
||||
// and meaning need to avoid attribute normalization. This way it
|
||||
// can be parsed by simple programs, in addition to xml parsers.
|
||||
string r("<flag>");
|
||||
AddXMLTag(&r, "file", flag.filename);
|
||||
AddXMLTag(&r, "name", flag.name);
|
||||
AddXMLTag(&r, "meaning", flag.description);
|
||||
AddXMLTag(&r, "default", flag.default_value);
|
||||
AddXMLTag(&r, "current", flag.current_value);
|
||||
AddXMLTag(&r, "type", flag.type);
|
||||
r += "</flag>";
|
||||
return r;
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------
|
||||
// ShowUsageWithFlags()
|
||||
// ShowUsageWithFlagsRestrict()
|
||||
// ShowXMLOfFlags()
|
||||
// These routines variously expose the registry's list of flag
|
||||
// values. ShowUsage*() prints the flag-value information
|
||||
// to stdout in a user-readable format (that's what --help uses).
|
||||
// The Restrict() version limits what flags are shown.
|
||||
// ShowXMLOfFlags() prints the flag-value information to stdout
|
||||
// in a machine-readable format. In all cases, the flags are
|
||||
// sorted: first by filename they are defined in, then by flagname.
|
||||
// --------------------------------------------------------------------
|
||||
|
||||
static const char* Basename(const char* filename) {
|
||||
const char* sep = strrchr(filename, PATH_SEPARATOR);
|
||||
return sep ? sep + 1 : filename;
|
||||
}
|
||||
|
||||
static string Dirname(const string& filename) {
|
||||
string::size_type sep = filename.rfind(PATH_SEPARATOR);
|
||||
return filename.substr(0, (sep == string::npos) ? 0 : sep);
|
||||
}
|
||||
|
||||
// Test whether a filename contains at least one of the substrings.
|
||||
static bool FileMatchesSubstring(const string& filename,
|
||||
const vector<string>& substrings) {
|
||||
for (vector<string>::const_iterator target = substrings.begin();
|
||||
target != substrings.end();
|
||||
++target) {
|
||||
if (strstr(filename.c_str(), target->c_str()) != NULL)
|
||||
return true;
|
||||
// If the substring starts with a '/', that means that we want
|
||||
// the string to be at the beginning of a directory component.
|
||||
// That should match the first directory component as well, so
|
||||
// we allow '/foo' to match a filename of 'foo'.
|
||||
if (!target->empty() && (*target)[0] == '/' &&
|
||||
strncmp(filename.c_str(), target->c_str() + 1,
|
||||
strlen(target->c_str() + 1)) == 0)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Show help for every filename which matches any of the target substrings.
|
||||
// If substrings is empty, shows help for every file. If a flag's help message
|
||||
// has been stripped (e.g. by adding '#define STRIP_FLAG_HELP 1'
|
||||
// before including gflags/gflags.h), then this flag will not be displayed
|
||||
// by '--help' and its variants.
|
||||
static void ShowUsageWithFlagsMatching(const char *argv0,
|
||||
const vector<string> &substrings) {
|
||||
fprintf(stdout, "%s: %s\n", Basename(argv0), ProgramUsage());
|
||||
|
||||
vector<CommandLineFlagInfo> flags;
|
||||
GetAllFlags(&flags); // flags are sorted by filename, then flagname
|
||||
|
||||
string last_filename; // so we know when we're at a new file
|
||||
bool first_directory = true; // controls blank lines between dirs
|
||||
bool found_match = false; // stays false iff no dir matches restrict
|
||||
for (vector<CommandLineFlagInfo>::const_iterator flag = flags.begin();
|
||||
flag != flags.end();
|
||||
++flag) {
|
||||
if (substrings.empty() ||
|
||||
FileMatchesSubstring(flag->filename, substrings)) {
|
||||
// If the flag has been stripped, pretend that it doesn't exist.
|
||||
if (flag->description == kStrippedFlagHelp) continue;
|
||||
found_match = true; // this flag passed the match!
|
||||
if (flag->filename != last_filename) { // new file
|
||||
if (Dirname(flag->filename) != Dirname(last_filename)) { // new dir!
|
||||
if (!first_directory)
|
||||
fprintf(stdout, "\n\n"); // put blank lines between directories
|
||||
first_directory = false;
|
||||
}
|
||||
fprintf(stdout, "\n Flags from %s:\n", flag->filename.c_str());
|
||||
last_filename = flag->filename;
|
||||
}
|
||||
// Now print this flag
|
||||
fprintf(stdout, "%s", DescribeOneFlag(*flag).c_str());
|
||||
}
|
||||
}
|
||||
if (!found_match && !substrings.empty()) {
|
||||
fprintf(stdout, "\n No modules matched: use -help\n");
|
||||
}
|
||||
}
|
||||
|
||||
void ShowUsageWithFlagsRestrict(const char *argv0, const char *restrict) {
|
||||
vector<string> substrings;
|
||||
if (restrict != NULL && *restrict != '\0') {
|
||||
substrings.push_back(restrict);
|
||||
}
|
||||
ShowUsageWithFlagsMatching(argv0, substrings);
|
||||
}
|
||||
|
||||
void ShowUsageWithFlags(const char *argv0) {
|
||||
ShowUsageWithFlagsRestrict(argv0, "");
|
||||
}
|
||||
|
||||
// Convert the help, program, and usage to xml.
|
||||
static void ShowXMLOfFlags(const char *prog_name) {
|
||||
vector<CommandLineFlagInfo> flags;
|
||||
GetAllFlags(&flags); // flags are sorted: by filename, then flagname
|
||||
|
||||
// XML. There is no corresponding schema yet
|
||||
fprintf(stdout, "<?xml version=\"1.0\"?>\n");
|
||||
// The document
|
||||
fprintf(stdout, "<AllFlags>\n");
|
||||
// the program name and usage
|
||||
fprintf(stdout, "<program>%s</program>\n",
|
||||
XMLText(Basename(prog_name)).c_str());
|
||||
fprintf(stdout, "<usage>%s</usage>\n",
|
||||
XMLText(ProgramUsage()).c_str());
|
||||
// All the flags
|
||||
for (vector<CommandLineFlagInfo>::const_iterator flag = flags.begin();
|
||||
flag != flags.end();
|
||||
++flag) {
|
||||
if (flag->description != kStrippedFlagHelp)
|
||||
fprintf(stdout, "%s\n", DescribeOneFlagInXML(*flag).c_str());
|
||||
}
|
||||
// The end of the document
|
||||
fprintf(stdout, "</AllFlags>\n");
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------
|
||||
// ShowVersion()
|
||||
// Called upon --version. Prints build-related info.
|
||||
// --------------------------------------------------------------------
|
||||
|
||||
static void ShowVersion() {
|
||||
const char* version_string = VersionString();
|
||||
if (version_string && *version_string) {
|
||||
fprintf(stdout, "%s version %s\n",
|
||||
ProgramInvocationShortName(), version_string);
|
||||
} else {
|
||||
fprintf(stdout, "%s\n", ProgramInvocationShortName());
|
||||
}
|
||||
# if !defined(NDEBUG)
|
||||
fprintf(stdout, "Debug build (NDEBUG not #defined)\n");
|
||||
# endif
|
||||
}
|
||||
|
||||
static void AppendPrognameStrings(vector<string>* substrings,
|
||||
const char* progname) {
|
||||
string r("/");
|
||||
r += progname;
|
||||
substrings->push_back(r + ".");
|
||||
substrings->push_back(r + "-main.");
|
||||
substrings->push_back(r + "_main.");
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------
|
||||
// HandleCommandLineHelpFlags()
|
||||
// Checks all the 'reporting' commandline flags to see if any
|
||||
// have been set. If so, handles them appropriately. Note
|
||||
// that all of them, by definition, cause the program to exit
|
||||
// if they trigger.
|
||||
// --------------------------------------------------------------------
|
||||
|
||||
void HandleCommandLineHelpFlags() {
|
||||
const char* progname = ProgramInvocationShortName();
|
||||
|
||||
HandleCommandLineCompletions();
|
||||
|
||||
vector<string> substrings;
|
||||
AppendPrognameStrings(&substrings, progname);
|
||||
|
||||
if (FLAGS_helpshort) {
|
||||
// show only flags related to this binary:
|
||||
// E.g. for fileutil.cc, want flags containing ... "/fileutil." cc
|
||||
ShowUsageWithFlagsMatching(progname, substrings);
|
||||
gflags_exitfunc(1);
|
||||
|
||||
} else if (FLAGS_help || FLAGS_helpfull) {
|
||||
// show all options
|
||||
ShowUsageWithFlagsRestrict(progname, ""); // empty restrict
|
||||
gflags_exitfunc(1);
|
||||
|
||||
} else if (!FLAGS_helpon.empty()) {
|
||||
string restrict = "/" + FLAGS_helpon + ".";
|
||||
ShowUsageWithFlagsRestrict(progname, restrict.c_str());
|
||||
gflags_exitfunc(1);
|
||||
|
||||
} else if (!FLAGS_helpmatch.empty()) {
|
||||
ShowUsageWithFlagsRestrict(progname, FLAGS_helpmatch.c_str());
|
||||
gflags_exitfunc(1);
|
||||
|
||||
} else if (FLAGS_helppackage) {
|
||||
// Shows help for all files in the same directory as main(). We
|
||||
// don't want to resort to looking at dirname(progname), because
|
||||
// the user can pick progname, and it may not relate to the file
|
||||
// where main() resides. So instead, we search the flags for a
|
||||
// filename like "/progname.cc", and take the dirname of that.
|
||||
vector<CommandLineFlagInfo> flags;
|
||||
GetAllFlags(&flags);
|
||||
string last_package;
|
||||
for (vector<CommandLineFlagInfo>::const_iterator flag = flags.begin();
|
||||
flag != flags.end();
|
||||
++flag) {
|
||||
if (!FileMatchesSubstring(flag->filename, substrings))
|
||||
continue;
|
||||
const string package = Dirname(flag->filename) + "/";
|
||||
if (package != last_package) {
|
||||
ShowUsageWithFlagsRestrict(progname, package.c_str());
|
||||
VLOG(7) << "Found package: " << package;
|
||||
if (!last_package.empty()) { // means this isn't our first pkg
|
||||
LOG(WARNING) << "Multiple packages contain a file=" << progname;
|
||||
}
|
||||
last_package = package;
|
||||
}
|
||||
}
|
||||
if (last_package.empty()) { // never found a package to print
|
||||
LOG(WARNING) << "Unable to find a package for file=" << progname;
|
||||
}
|
||||
gflags_exitfunc(1);
|
||||
|
||||
} else if (FLAGS_helpxml) {
|
||||
ShowXMLOfFlags(progname);
|
||||
gflags_exitfunc(1);
|
||||
|
||||
} else if (FLAGS_version) {
|
||||
ShowVersion();
|
||||
// Unlike help, we may be asking for version in a script, so return 0
|
||||
gflags_exitfunc(0);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
_END_GOOGLE_NAMESPACE_
|
|
@ -0,0 +1,61 @@
|
|||
// Copyright (c) 2011, Google Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following disclaimer
|
||||
// in the documentation and/or other materials provided with the
|
||||
// distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from
|
||||
// this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
//
|
||||
// ---
|
||||
// Author: csilvers@google.com (Craig Silverstein)
|
||||
//
|
||||
// A simple program that uses STRIP_FLAG_HELP. We'll have a shell
|
||||
// script that runs 'strings' over this program and makes sure
|
||||
// that the help string is not in there.
|
||||
|
||||
#include "config_for_unittests.h"
|
||||
#define STRIP_FLAG_HELP 1
|
||||
#include <gflags/gflags.h>
|
||||
|
||||
#include <stdio.h>
|
||||
|
||||
using GOOGLE_NAMESPACE::SetUsageMessage;
|
||||
using GOOGLE_NAMESPACE::ParseCommandLineFlags;
|
||||
|
||||
|
||||
DEFINE_bool(test, true, "This text should be stripped out");
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
SetUsageMessage("Usage message");
|
||||
ParseCommandLineFlags(&argc, &argv, false);
|
||||
|
||||
// Unfortunately, for us, libtool can replace executables with a shell
|
||||
// script that does some work before calling the 'real' executable
|
||||
// under a different name. We need the 'real' executable name to run
|
||||
// 'strings' on it, so we construct this binary to print the real
|
||||
// name (argv[0]) on stdout when run.
|
||||
puts(argv[0]);
|
||||
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,80 @@
|
|||
#!/bin/sh
|
||||
#
|
||||
# Copyright (c) 2011, Google Inc.
|
||||
# All rights reserved.
|
||||
#
|
||||
# Redistribution and use in source and binary forms, with or without
|
||||
# modification, are permitted provided that the following conditions are
|
||||
# met:
|
||||
#
|
||||
# * Redistributions of source code must retain the above copyright
|
||||
# notice, this list of conditions and the following disclaimer.
|
||||
# * Redistributions in binary form must reproduce the above
|
||||
# copyright notice, this list of conditions and the following disclaimer
|
||||
# in the documentation and/or other materials provided with the
|
||||
# distribution.
|
||||
# * Neither the name of Google Inc. nor the names of its
|
||||
# contributors may be used to endorse or promote products derived from
|
||||
# this software without specific prior written permission.
|
||||
#
|
||||
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
#
|
||||
# ---
|
||||
# Author: csilvers@google.com (Craig Silverstein)
|
||||
|
||||
if [ -z "$1" ]; then
|
||||
echo "USAGE: $0 <unittest exe>"
|
||||
exit 1
|
||||
fi
|
||||
BINARY="$1"
|
||||
|
||||
# Make sure the binary exists...
|
||||
if ! "$BINARY" >/dev/null 2>/dev/null
|
||||
then
|
||||
echo "Cannot run binary $BINARY"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Make sure the --help output doesn't print the stripped text.
|
||||
if "$BINARY" --help | grep "This text should be stripped out" >/dev/null 2>&1
|
||||
then
|
||||
echo "Text not stripped from --help like it should be: $BINARY"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Make sure the stripped text isn't in the binary at all.
|
||||
if strings --help >/dev/null 2>&1 # make sure the binary exists
|
||||
then
|
||||
# Unfortunately, for us, libtool can replace executables with a
|
||||
# shell script that does some work before calling the 'real'
|
||||
# executable under a different name. We need the 'real'
|
||||
# executable name to run 'strings' on it, so we construct this
|
||||
# binary to print the real name (argv[0]) on stdout when run.
|
||||
REAL_BINARY=`"$BINARY"`
|
||||
# On cygwin, we may need to add a '.exe' extension by hand.
|
||||
[ -f "$REAL_BINARY.exe" ] && REAL_BINARY="$REAL_BINARY.exe"
|
||||
if strings "$REAL_BINARY" | grep "This text should be stripped" >/dev/null 2>&1
|
||||
then
|
||||
echo "Text not stripped from binary like it should be: $BINARY"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Let's also do a sanity check to make sure strings is working properly
|
||||
if ! strings "$REAL_BINARY" | grep "Usage message" >/dev/null 2>&1
|
||||
then
|
||||
echo "Usage text not found in binary like it should be: $BINARY"
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
echo "PASS"
|
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,237 @@
|
|||
#!/bin/bash
|
||||
|
||||
# Copyright (c) 2006, Google Inc.
|
||||
# All rights reserved.
|
||||
#
|
||||
# Redistribution and use in source and binary forms, with or without
|
||||
# modification, are permitted provided that the following conditions are
|
||||
# met:
|
||||
#
|
||||
# * Redistributions of source code must retain the above copyright
|
||||
# notice, this list of conditions and the following disclaimer.
|
||||
# * Redistributions in binary form must reproduce the above
|
||||
# copyright notice, this list of conditions and the following disclaimer
|
||||
# in the documentation and/or other materials provided with the
|
||||
# distribution.
|
||||
# * Neither the name of Google Inc. nor the names of its
|
||||
# contributors may be used to endorse or promote products derived from
|
||||
# this software without specific prior written permission.
|
||||
#
|
||||
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
# ---
|
||||
# Author: Craig Silverstein
|
||||
#
|
||||
# Just tries to run the gflags_unittest with various flags
|
||||
# defined in gflags.cc, and make sure they give the
|
||||
# appropriate exit status and appropriate error message.
|
||||
|
||||
if [ -z "$1" ]; then
|
||||
echo "USAGE: $0 <unittest exe> [top_srcdir] [tmpdir]"
|
||||
exit 1
|
||||
fi
|
||||
EXE="$1"
|
||||
SRCDIR="${2:-./}"
|
||||
TMPDIR="${3:-/tmp/gflags}"
|
||||
EXE2="${EXE}2" # eg, gflags_unittest2
|
||||
EXE3="${EXE}3" # eg, gflags_unittest3
|
||||
|
||||
# $1: executable
|
||||
# $2: line-number $3: expected return code. $4: substring of expected output.
|
||||
# $5: a substring you *don't* expect to find in the output. $6+ flags
|
||||
ExpectExe() {
|
||||
local executable="$1"
|
||||
shift
|
||||
local line_number="$1"
|
||||
shift
|
||||
local expected_rc="$1"
|
||||
shift
|
||||
local expected_output="$1"
|
||||
shift
|
||||
local unexpected_output="$1"
|
||||
shift
|
||||
|
||||
# We always add --srcdir because it's needed for correctness
|
||||
"$executable" --srcdir="$SRCDIR" "$@" > "$TMPDIR/test.$line_number" 2>&1
|
||||
|
||||
local actual_rc=$?
|
||||
if [ $actual_rc != $expected_rc ]; then
|
||||
echo "Test on line $line_number failed:" \
|
||||
"expected rc $expected_rc, got $actual_rc"
|
||||
exit 1;
|
||||
fi
|
||||
if [ -n "$expected_output" ] &&
|
||||
! fgrep -e "$expected_output" "$TMPDIR/test.$line_number" >/dev/null; then
|
||||
echo "Test on line $line_number failed:" \
|
||||
"did not find expected substring '$expected_output'"
|
||||
exit 1;
|
||||
fi
|
||||
if [ -n "$unexpected_output" ] &&
|
||||
fgrep -e "$unexpected_output" "$TMPDIR/test.$line_number" >/dev/null; then
|
||||
echo "Test line $line_number failed:" \
|
||||
"found unexpected substring '$unexpected_output'"
|
||||
exit 1;
|
||||
fi
|
||||
}
|
||||
|
||||
# $1: line-number $2: expected return code. $3: substring of expected output.
|
||||
# $4: a substring you *don't* expect to find in the output. $5+ flags
|
||||
Expect() {
|
||||
ExpectExe "$EXE" "$@"
|
||||
}
|
||||
|
||||
rm -rf "$TMPDIR"
|
||||
mkdir "$TMPDIR" || exit 2
|
||||
|
||||
# Create a few flagfiles we can use later
|
||||
echo "--version" > "$TMPDIR/flagfile.1"
|
||||
echo "--foo=bar" > "$TMPDIR/flagfile.2"
|
||||
echo "--nounused_bool" >> "$TMPDIR/flagfile.2"
|
||||
echo "--flagfile=$TMPDIR/flagfile.2" > "$TMPDIR/flagfile.3"
|
||||
|
||||
# Set a few environment variables (useful for --tryfromenv)
|
||||
export FLAGS_undefok=foo,bar
|
||||
export FLAGS_weirdo=
|
||||
export FLAGS_version=true
|
||||
export FLAGS_help=false
|
||||
|
||||
# First, just make sure the unittest works as-is
|
||||
Expect $LINENO 0 "PASS" ""
|
||||
|
||||
# --help should show all flags, including flags from gflags_reporting
|
||||
Expect $LINENO 1 "/gflags_reporting.cc" "" --help
|
||||
|
||||
# Make sure that --help prints even very long helpstrings.
|
||||
Expect $LINENO 1 "end of a long helpstring" "" --help
|
||||
|
||||
# Make sure --help reflects flag changes made before flag-parsing
|
||||
Expect $LINENO 1 \
|
||||
"-changed_bool1 (changed) type: bool default: true" "" --help
|
||||
Expect $LINENO 1 \
|
||||
"-changed_bool2 (changed) type: bool default: false currently: true" "" \
|
||||
--help
|
||||
# And on the command-line, too
|
||||
Expect $LINENO 1 \
|
||||
"-changeable_string_var () type: string default: \"1\" currently: \"2\"" \
|
||||
"" --changeable_string_var 2 --help
|
||||
|
||||
# --nohelp and --help=false should be as if we didn't say anything
|
||||
Expect $LINENO 0 "PASS" "" --nohelp
|
||||
Expect $LINENO 0 "PASS" "" --help=false
|
||||
|
||||
# --helpfull is the same as help
|
||||
Expect $LINENO 1 "/gflags_reporting.cc" "" -helpfull
|
||||
|
||||
# --helpshort should show only flags from the unittest itself
|
||||
Expect $LINENO 1 "/gflags_unittest.cc" \
|
||||
"/gflags_reporting.cc" --helpshort
|
||||
|
||||
# --helpshort should show the tldflag we created in the unittest dir
|
||||
Expect $LINENO 1 "tldflag1" "/google.cc" --helpshort
|
||||
Expect $LINENO 1 "tldflag2" "/google.cc" --helpshort
|
||||
|
||||
# --helpshort should work if the main source file is suffixed with [_-]main
|
||||
ExpectExe "$EXE2" $LINENO 1 "/gflags_unittest-main.cc" \
|
||||
"/gflags_reporting.cc" --helpshort
|
||||
ExpectExe "$EXE3" $LINENO 1 "/gflags_unittest_main.cc" \
|
||||
"/gflags_reporting.cc" --helpshort
|
||||
|
||||
# --helpon needs an argument
|
||||
Expect $LINENO 1 \
|
||||
"'--helpon' is missing its argument; flag description: show help on" \
|
||||
"" --helpon
|
||||
|
||||
# --helpon argument indicates what file we'll show args from
|
||||
Expect $LINENO 1 "/gflags.cc" "/gflags_unittest.cc" \
|
||||
--helpon=gflags
|
||||
|
||||
# another way of specifying the argument
|
||||
Expect $LINENO 1 "/gflags.cc" "/gflags_unittest.cc" \
|
||||
--helpon gflags
|
||||
|
||||
# test another argument
|
||||
Expect $LINENO 1 "/gflags_unittest.cc" "/gflags.cc" \
|
||||
--helpon=gflags_unittest
|
||||
|
||||
# helpmatch is like helpon but takes substrings
|
||||
Expect $LINENO 1 "/gflags_reporting.cc" \
|
||||
"/gflags_unittest.cc" -helpmatch reporting
|
||||
Expect $LINENO 1 "/gflags_unittest.cc" \
|
||||
"/gflags.cc" -helpmatch=unittest
|
||||
|
||||
# if no flags are found with helpmatch or helpon, suggest --help
|
||||
Expect $LINENO 1 "No modules matched" "/gflags_unittest.cc" \
|
||||
-helpmatch=nosuchsubstring
|
||||
Expect $LINENO 1 "No modules matched" "/gflags_unittest.cc" \
|
||||
-helpon=nosuchmodule
|
||||
|
||||
# helppackage shows all the flags in the same dir as this unittest
|
||||
# --help should show all flags, including flags from google.cc
|
||||
Expect $LINENO 1 "/gflags_reporting.cc" "" --helppackage
|
||||
|
||||
# xml!
|
||||
Expect $LINENO 1 "/gflags_unittest.cc</file>" \
|
||||
"/gflags_unittest.cc:" --helpxml
|
||||
|
||||
# just print the version info and exit
|
||||
Expect $LINENO 0 "gflags_unittest" "gflags_unittest.cc" --version
|
||||
Expect $LINENO 0 "version test_version" "gflags_unittest.cc" --version
|
||||
|
||||
# --undefok is a fun flag...
|
||||
Expect $LINENO 1 "unknown command line flag 'foo'" "" --undefok= --foo --unused_bool
|
||||
Expect $LINENO 0 "PASS" "" --undefok=foo --foo --unused_bool
|
||||
# If you say foo is ok to be undefined, we'll accept --nofoo as well
|
||||
Expect $LINENO 0 "PASS" "" --undefok=foo --nofoo --unused_bool
|
||||
# It's ok if the foo is in the middle
|
||||
Expect $LINENO 0 "PASS" "" --undefok=fee,fi,foo,fum --foo --unused_bool
|
||||
# But the spelling has to be just right...
|
||||
Expect $LINENO 1 "unknown command line flag 'foo'" "" --undefok=fo --foo --unused_bool
|
||||
Expect $LINENO 1 "unknown command line flag 'foo'" "" --undefok=foot --foo --unused_bool
|
||||
|
||||
# See if we can successfully load our flags from the flagfile
|
||||
Expect $LINENO 0 "gflags_unittest" "gflags_unittest.cc" \
|
||||
--flagfile="$TMPDIR/flagfile.1"
|
||||
Expect $LINENO 0 "PASS" "" --flagfile="$TMPDIR/flagfile.2"
|
||||
Expect $LINENO 0 "PASS" "" --flagfile="$TMPDIR/flagfile.3"
|
||||
|
||||
# Also try to load flags from the environment
|
||||
Expect $LINENO 0 "gflags_unittest" "gflags_unittest.cc" \
|
||||
--fromenv=version
|
||||
Expect $LINENO 0 "gflags_unittest" "gflags_unittest.cc" \
|
||||
--tryfromenv=version
|
||||
Expect $LINENO 0 "PASS" "" --fromenv=help
|
||||
Expect $LINENO 0 "PASS" "" --tryfromenv=help
|
||||
Expect $LINENO 1 "helpfull not found in environment" "" --fromenv=helpfull
|
||||
Expect $LINENO 0 "PASS" "" --tryfromenv=helpfull
|
||||
Expect $LINENO 0 "PASS" "" --tryfromenv=undefok --foo
|
||||
Expect $LINENO 1 "unknown command line flag" "" --tryfromenv=weirdo
|
||||
Expect $LINENO 0 "gflags_unittest" "gflags_unittest.cc" \
|
||||
--tryfromenv=test_bool,version,unused_bool
|
||||
Expect $LINENO 1 "not found in environment" "" --fromenv=test_bool
|
||||
Expect $LINENO 1 "unknown command line flag" "" --fromenv=test_bool,ok
|
||||
# Here, the --version overrides the fromenv
|
||||
Expect $LINENO 0 "gflags_unittest" "gflags_unittest.cc" \
|
||||
--fromenv=test_bool,version,ok
|
||||
|
||||
# Make sure -- by itself stops argv processing
|
||||
Expect $LINENO 0 "PASS" "" -- --help
|
||||
|
||||
|
||||
# And we should die if the flag value doesn't pass the validator
|
||||
Expect $LINENO 1 "ERROR: failed validation of new value 'true' for flag 'always_fail'" "" --always_fail
|
||||
|
||||
# TODO(user) And if locking in validators fails.
|
||||
# Expect $LINENO 0 "PASS" "" --deadlock_if_cant_lock
|
||||
|
||||
echo "PASS"
|
||||
exit 0
|
|
@ -0,0 +1,2 @@
|
|||
--test_flag=1
|
||||
--test_flag=2
|
|
@ -0,0 +1,34 @@
|
|||
// Copyright (c) 2006, Google Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following disclaimer
|
||||
// in the documentation and/or other materials provided with the
|
||||
// distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from
|
||||
// this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
// Header files have moved from the google directory to the gflags
|
||||
// directory. This forwarding file is provided only for backwards
|
||||
// compatibility. Use gflags/gflags.h in all new code.
|
||||
|
||||
#include <gflags/gflags.h>
|
|
@ -0,0 +1,34 @@
|
|||
// Copyright (c) 2008, Google Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following disclaimer
|
||||
// in the documentation and/or other materials provided with the
|
||||
// distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from
|
||||
// this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
// Header files have moved from the google directory to the gflags
|
||||
// directory. This forwarding file is provided only for backwards
|
||||
// compatibility. Use gflags/gflags_completions.h in all new code.
|
||||
|
||||
#include <gflags/gflags_completions.h>
|
|
@ -0,0 +1,356 @@
|
|||
// Copyright (c) 2007, Google Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following disclaimer
|
||||
// in the documentation and/or other materials provided with the
|
||||
// distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from
|
||||
// this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
//
|
||||
// ---
|
||||
//
|
||||
// A simple mutex wrapper, supporting locks and read-write locks.
|
||||
// You should assume the locks are *not* re-entrant.
|
||||
//
|
||||
// To use: you should define the following macros in your configure.ac:
|
||||
// ACX_PTHREAD
|
||||
// AC_RWLOCK
|
||||
// The latter is defined in ../autoconf.
|
||||
//
|
||||
// This class is meant to be internal-only and should be wrapped by an
|
||||
// internal namespace. Before you use this module, please give the
|
||||
// name of your internal namespace for this module. Or, if you want
|
||||
// to expose it, you'll want to move it to the Google namespace. We
|
||||
// cannot put this class in global namespace because there can be some
|
||||
// problems when we have multiple versions of Mutex in each shared object.
|
||||
//
|
||||
// NOTE: by default, we have #ifdef'ed out the TryLock() method.
|
||||
// This is for two reasons:
|
||||
// 1) TryLock() under Windows is a bit annoying (it requires a
|
||||
// #define to be defined very early).
|
||||
// 2) TryLock() is broken for NO_THREADS mode, at least in NDEBUG
|
||||
// mode.
|
||||
// If you need TryLock(), and either these two caveats are not a
|
||||
// problem for you, or you're willing to work around them, then
|
||||
// feel free to #define GMUTEX_TRYLOCK, or to remove the #ifdefs
|
||||
// in the code below.
|
||||
//
|
||||
// CYGWIN NOTE: Cygwin support for rwlock seems to be buggy:
|
||||
// http://www.cygwin.com/ml/cygwin/2008-12/msg00017.html
|
||||
// Because of that, we might as well use windows locks for
|
||||
// cygwin. They seem to be more reliable than the cygwin pthreads layer.
|
||||
//
|
||||
// TRICKY IMPLEMENTATION NOTE:
|
||||
// This class is designed to be safe to use during
|
||||
// dynamic-initialization -- that is, by global constructors that are
|
||||
// run before main() starts. The issue in this case is that
|
||||
// dynamic-initialization happens in an unpredictable order, and it
|
||||
// could be that someone else's dynamic initializer could call a
|
||||
// function that tries to acquire this mutex -- but that all happens
|
||||
// before this mutex's constructor has run. (This can happen even if
|
||||
// the mutex and the function that uses the mutex are in the same .cc
|
||||
// file.) Basically, because Mutex does non-trivial work in its
|
||||
// constructor, it's not, in the naive implementation, safe to use
|
||||
// before dynamic initialization has run on it.
|
||||
//
|
||||
// The solution used here is to pair the actual mutex primitive with a
|
||||
// bool that is set to true when the mutex is dynamically initialized.
|
||||
// (Before that it's false.) Then we modify all mutex routines to
|
||||
// look at the bool, and not try to lock/unlock until the bool makes
|
||||
// it to true (which happens after the Mutex constructor has run.)
|
||||
//
|
||||
// This works because before main() starts -- particularly, during
|
||||
// dynamic initialization -- there are no threads, so a) it's ok that
|
||||
// the mutex operations are a no-op, since we don't need locking then
|
||||
// anyway; and b) we can be quite confident our bool won't change
|
||||
// state between a call to Lock() and a call to Unlock() (that would
|
||||
// require a global constructor in one translation unit to call Lock()
|
||||
// and another global constructor in another translation unit to call
|
||||
// Unlock() later, which is pretty perverse).
|
||||
//
|
||||
// That said, it's tricky, and can conceivably fail; it's safest to
|
||||
// avoid trying to acquire a mutex in a global constructor, if you
|
||||
// can. One way it can fail is that a really smart compiler might
|
||||
// initialize the bool to true at static-initialization time (too
|
||||
// early) rather than at dynamic-initialization time. To discourage
|
||||
// that, we set is_safe_ to true in code (not the constructor
|
||||
// colon-initializer) and set it to true via a function that always
|
||||
// evaluates to true, but that the compiler can't know always
|
||||
// evaluates to true. This should be good enough.
|
||||
//
|
||||
// A related issue is code that could try to access the mutex
|
||||
// after it's been destroyed in the global destructors (because
|
||||
// the Mutex global destructor runs before some other global
|
||||
// destructor, that tries to acquire the mutex). The way we
|
||||
// deal with this is by taking a constructor arg that global
|
||||
// mutexes should pass in, that causes the destructor to do no
|
||||
// work. We still depend on the compiler not doing anything
|
||||
// weird to a Mutex's memory after it is destroyed, but for a
|
||||
// static global variable, that's pretty safe.
|
||||
|
||||
#ifndef GOOGLE_MUTEX_H_
|
||||
#define GOOGLE_MUTEX_H_
|
||||
|
||||
#include "config.h" // to figure out pthreads support
|
||||
|
||||
#if defined(NO_THREADS)
|
||||
typedef int MutexType; // to keep a lock-count
|
||||
#elif defined(_WIN32) || defined(__CYGWIN32__) || defined(__CYGWIN64__)
|
||||
# ifndef WIN32_LEAN_AND_MEAN
|
||||
# define WIN32_LEAN_AND_MEAN // We only need minimal includes
|
||||
# endif
|
||||
# ifndef NOMINMAX
|
||||
# define NOMINMAX // Don't want windows to override min()/max()
|
||||
# endif
|
||||
# ifdef GMUTEX_TRYLOCK
|
||||
// We need Windows NT or later for TryEnterCriticalSection(). If you
|
||||
// don't need that functionality, you can remove these _WIN32_WINNT
|
||||
// lines, and change TryLock() to assert(0) or something.
|
||||
# ifndef _WIN32_WINNT
|
||||
# define _WIN32_WINNT 0x0400
|
||||
# endif
|
||||
# endif
|
||||
# include <windows.h>
|
||||
typedef CRITICAL_SECTION MutexType;
|
||||
#elif defined(HAVE_PTHREAD) && defined(HAVE_RWLOCK)
|
||||
// Needed for pthread_rwlock_*. If it causes problems, you could take it
|
||||
// out, but then you'd have to unset HAVE_RWLOCK (at least on linux -- it
|
||||
// *does* cause problems for FreeBSD, or MacOSX, but isn't needed
|
||||
// for locking there.)
|
||||
# ifdef __linux__
|
||||
# if _XOPEN_SOURCE < 500 // including not being defined at all
|
||||
# undef _XOPEN_SOURCE
|
||||
# define _XOPEN_SOURCE 500 // may be needed to get the rwlock calls
|
||||
# endif
|
||||
# endif
|
||||
# include <pthread.h>
|
||||
typedef pthread_rwlock_t MutexType;
|
||||
#elif defined(HAVE_PTHREAD)
|
||||
# include <pthread.h>
|
||||
typedef pthread_mutex_t MutexType;
|
||||
#else
|
||||
# error Need to implement mutex.h for your architecture, or #define NO_THREADS
|
||||
#endif
|
||||
|
||||
#include <assert.h>
|
||||
#include <stdlib.h> // for abort()
|
||||
|
||||
#define MUTEX_NAMESPACE gflags_mutex_namespace
|
||||
|
||||
namespace MUTEX_NAMESPACE {
|
||||
|
||||
class Mutex {
|
||||
public:
|
||||
// This is used for the single-arg constructor
|
||||
enum LinkerInitialized { LINKER_INITIALIZED };
|
||||
|
||||
// Create a Mutex that is not held by anybody. This constructor is
|
||||
// typically used for Mutexes allocated on the heap or the stack.
|
||||
inline Mutex();
|
||||
// This constructor should be used for global, static Mutex objects.
|
||||
// It inhibits work being done by the destructor, which makes it
|
||||
// safer for code that tries to acqiure this mutex in their global
|
||||
// destructor.
|
||||
inline Mutex(LinkerInitialized);
|
||||
|
||||
// Destructor
|
||||
inline ~Mutex();
|
||||
|
||||
inline void Lock(); // Block if needed until free then acquire exclusively
|
||||
inline void Unlock(); // Release a lock acquired via Lock()
|
||||
#ifdef GMUTEX_TRYLOCK
|
||||
inline bool TryLock(); // If free, Lock() and return true, else return false
|
||||
#endif
|
||||
// Note that on systems that don't support read-write locks, these may
|
||||
// be implemented as synonyms to Lock() and Unlock(). So you can use
|
||||
// these for efficiency, but don't use them anyplace where being able
|
||||
// to do shared reads is necessary to avoid deadlock.
|
||||
inline void ReaderLock(); // Block until free or shared then acquire a share
|
||||
inline void ReaderUnlock(); // Release a read share of this Mutex
|
||||
inline void WriterLock() { Lock(); } // Acquire an exclusive lock
|
||||
inline void WriterUnlock() { Unlock(); } // Release a lock from WriterLock()
|
||||
|
||||
private:
|
||||
MutexType mutex_;
|
||||
// We want to make sure that the compiler sets is_safe_ to true only
|
||||
// when we tell it to, and never makes assumptions is_safe_ is
|
||||
// always true. volatile is the most reliable way to do that.
|
||||
volatile bool is_safe_;
|
||||
// This indicates which constructor was called.
|
||||
bool destroy_;
|
||||
|
||||
inline void SetIsSafe() { is_safe_ = true; }
|
||||
|
||||
// Catch the error of writing Mutex when intending MutexLock.
|
||||
Mutex(Mutex* /*ignored*/) {}
|
||||
// Disallow "evil" constructors
|
||||
Mutex(const Mutex&);
|
||||
void operator=(const Mutex&);
|
||||
};
|
||||
|
||||
// Now the implementation of Mutex for various systems
|
||||
#if defined(NO_THREADS)
|
||||
|
||||
// When we don't have threads, we can be either reading or writing,
|
||||
// but not both. We can have lots of readers at once (in no-threads
|
||||
// mode, that's most likely to happen in recursive function calls),
|
||||
// but only one writer. We represent this by having mutex_ be -1 when
|
||||
// writing and a number > 0 when reading (and 0 when no lock is held).
|
||||
//
|
||||
// In debug mode, we assert these invariants, while in non-debug mode
|
||||
// we do nothing, for efficiency. That's why everything is in an
|
||||
// assert.
|
||||
|
||||
Mutex::Mutex() : mutex_(0) { }
|
||||
Mutex::Mutex(Mutex::LinkerInitialized) : mutex_(0) { }
|
||||
Mutex::~Mutex() { assert(mutex_ == 0); }
|
||||
void Mutex::Lock() { assert(--mutex_ == -1); }
|
||||
void Mutex::Unlock() { assert(mutex_++ == -1); }
|
||||
#ifdef GMUTEX_TRYLOCK
|
||||
bool Mutex::TryLock() { if (mutex_) return false; Lock(); return true; }
|
||||
#endif
|
||||
void Mutex::ReaderLock() { assert(++mutex_ > 0); }
|
||||
void Mutex::ReaderUnlock() { assert(mutex_-- > 0); }
|
||||
|
||||
#elif defined(_WIN32) || defined(__CYGWIN32__) || defined(__CYGWIN64__)
|
||||
|
||||
Mutex::Mutex() : destroy_(true) {
|
||||
InitializeCriticalSection(&mutex_);
|
||||
SetIsSafe();
|
||||
}
|
||||
Mutex::Mutex(LinkerInitialized) : destroy_(false) {
|
||||
InitializeCriticalSection(&mutex_);
|
||||
SetIsSafe();
|
||||
}
|
||||
Mutex::~Mutex() { if (destroy_) DeleteCriticalSection(&mutex_); }
|
||||
void Mutex::Lock() { if (is_safe_) EnterCriticalSection(&mutex_); }
|
||||
void Mutex::Unlock() { if (is_safe_) LeaveCriticalSection(&mutex_); }
|
||||
#ifdef GMUTEX_TRYLOCK
|
||||
bool Mutex::TryLock() { return is_safe_ ?
|
||||
TryEnterCriticalSection(&mutex_) != 0 : true; }
|
||||
#endif
|
||||
void Mutex::ReaderLock() { Lock(); } // we don't have read-write locks
|
||||
void Mutex::ReaderUnlock() { Unlock(); }
|
||||
|
||||
#elif defined(HAVE_PTHREAD) && defined(HAVE_RWLOCK)
|
||||
|
||||
#define SAFE_PTHREAD(fncall) do { /* run fncall if is_safe_ is true */ \
|
||||
if (is_safe_ && fncall(&mutex_) != 0) abort(); \
|
||||
} while (0)
|
||||
|
||||
Mutex::Mutex() : destroy_(true) {
|
||||
SetIsSafe();
|
||||
if (is_safe_ && pthread_rwlock_init(&mutex_, NULL) != 0) abort();
|
||||
}
|
||||
Mutex::Mutex(Mutex::LinkerInitialized) : destroy_(false) {
|
||||
SetIsSafe();
|
||||
if (is_safe_ && pthread_rwlock_init(&mutex_, NULL) != 0) abort();
|
||||
}
|
||||
Mutex::~Mutex() { if (destroy_) SAFE_PTHREAD(pthread_rwlock_destroy); }
|
||||
void Mutex::Lock() { SAFE_PTHREAD(pthread_rwlock_wrlock); }
|
||||
void Mutex::Unlock() { SAFE_PTHREAD(pthread_rwlock_unlock); }
|
||||
#ifdef GMUTEX_TRYLOCK
|
||||
bool Mutex::TryLock() { return is_safe_ ?
|
||||
pthread_rwlock_trywrlock(&mutex_) == 0 : true; }
|
||||
#endif
|
||||
void Mutex::ReaderLock() { SAFE_PTHREAD(pthread_rwlock_rdlock); }
|
||||
void Mutex::ReaderUnlock() { SAFE_PTHREAD(pthread_rwlock_unlock); }
|
||||
#undef SAFE_PTHREAD
|
||||
|
||||
#elif defined(HAVE_PTHREAD)
|
||||
|
||||
#define SAFE_PTHREAD(fncall) do { /* run fncall if is_safe_ is true */ \
|
||||
if (is_safe_ && fncall(&mutex_) != 0) abort(); \
|
||||
} while (0)
|
||||
|
||||
Mutex::Mutex() : destroy_(true) {
|
||||
SetIsSafe();
|
||||
if (is_safe_ && pthread_mutex_init(&mutex_, NULL) != 0) abort();
|
||||
}
|
||||
Mutex::Mutex(Mutex::LinkerInitialized) : destroy_(false) {
|
||||
SetIsSafe();
|
||||
if (is_safe_ && pthread_mutex_init(&mutex_, NULL) != 0) abort();
|
||||
}
|
||||
Mutex::~Mutex() { if (destroy_) SAFE_PTHREAD(pthread_mutex_destroy); }
|
||||
void Mutex::Lock() { SAFE_PTHREAD(pthread_mutex_lock); }
|
||||
void Mutex::Unlock() { SAFE_PTHREAD(pthread_mutex_unlock); }
|
||||
#ifdef GMUTEX_TRYLOCK
|
||||
bool Mutex::TryLock() { return is_safe_ ?
|
||||
pthread_mutex_trylock(&mutex_) == 0 : true; }
|
||||
#endif
|
||||
void Mutex::ReaderLock() { Lock(); }
|
||||
void Mutex::ReaderUnlock() { Unlock(); }
|
||||
#undef SAFE_PTHREAD
|
||||
|
||||
#endif
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// Some helper classes
|
||||
|
||||
// MutexLock(mu) acquires mu when constructed and releases it when destroyed.
|
||||
class MutexLock {
|
||||
public:
|
||||
explicit MutexLock(Mutex *mu) : mu_(mu) { mu_->Lock(); }
|
||||
~MutexLock() { mu_->Unlock(); }
|
||||
private:
|
||||
Mutex * const mu_;
|
||||
// Disallow "evil" constructors
|
||||
MutexLock(const MutexLock&);
|
||||
void operator=(const MutexLock&);
|
||||
};
|
||||
|
||||
// ReaderMutexLock and WriterMutexLock do the same, for rwlocks
|
||||
class ReaderMutexLock {
|
||||
public:
|
||||
explicit ReaderMutexLock(Mutex *mu) : mu_(mu) { mu_->ReaderLock(); }
|
||||
~ReaderMutexLock() { mu_->ReaderUnlock(); }
|
||||
private:
|
||||
Mutex * const mu_;
|
||||
// Disallow "evil" constructors
|
||||
ReaderMutexLock(const ReaderMutexLock&);
|
||||
void operator=(const ReaderMutexLock&);
|
||||
};
|
||||
|
||||
class WriterMutexLock {
|
||||
public:
|
||||
explicit WriterMutexLock(Mutex *mu) : mu_(mu) { mu_->WriterLock(); }
|
||||
~WriterMutexLock() { mu_->WriterUnlock(); }
|
||||
private:
|
||||
Mutex * const mu_;
|
||||
// Disallow "evil" constructors
|
||||
WriterMutexLock(const WriterMutexLock&);
|
||||
void operator=(const WriterMutexLock&);
|
||||
};
|
||||
|
||||
// Catch bug where variable name is omitted, e.g. MutexLock (&mu);
|
||||
#define MutexLock(x) COMPILE_ASSERT(0, mutex_lock_decl_missing_var_name)
|
||||
#define ReaderMutexLock(x) COMPILE_ASSERT(0, rmutex_lock_decl_missing_var_name)
|
||||
#define WriterMutexLock(x) COMPILE_ASSERT(0, wmutex_lock_decl_missing_var_name)
|
||||
|
||||
} // namespace MUTEX_NAMESPACE
|
||||
|
||||
using namespace MUTEX_NAMESPACE;
|
||||
|
||||
#undef MUTEX_NAMESPACE
|
||||
|
||||
#endif /* #define GOOGLE_MUTEX_H__ */
|
|
@ -0,0 +1,51 @@
|
|||
# libstdc++.la - a libtool library file
|
||||
# Generated by ltmain.sh - GNU libtool 1.4a-GCC3.0 (1.641.2.256 2001/05/28 20:09:07 with GCC-local changes)
|
||||
#
|
||||
# Please DO NOT delete this file!
|
||||
# It is necessary for linking the library.
|
||||
|
||||
# ---
|
||||
# NOTE: This file lives in /usr/sfw/lib on Solaris 10. Unfortunately,
|
||||
# due to an apparent bug in the Solaris 10 6/06 release,
|
||||
# /usr/sfw/lib/libstdc++.la is empty. Below is the correct content,
|
||||
# according to
|
||||
# http://forum.java.sun.com/thread.jspa?threadID=5073150
|
||||
# By passing LDFLAGS='-Lsrc/solaris' to configure, make will pick up
|
||||
# this copy of the file rather than the empty copy in /usr/sfw/lib.
|
||||
#
|
||||
# Also see
|
||||
# http://www.technicalarticles.org/index.php/Compiling_MySQL_5.0_on_Solaris_10
|
||||
#
|
||||
# Note: this is for 32-bit systems. If you have a 64-bit system,
|
||||
# uncomment the appropriate dependency_libs line below.
|
||||
# ----
|
||||
|
||||
# The name that we can dlopen(3).
|
||||
dlname='libstdc++.so.6'
|
||||
|
||||
# Names of this library.
|
||||
library_names='libstdc++.so.6.0.3 libstdc++.so.6 libstdc++.so'
|
||||
|
||||
# The name of the static archive.
|
||||
old_library='libstdc++.a'
|
||||
|
||||
# Libraries that this one depends upon.
|
||||
# 32-bit version:
|
||||
dependency_libs='-lc -lm -L/usr/sfw/lib -lgcc_s'
|
||||
# 64-bit version:
|
||||
#dependency_libs='-L/lib/64 -lc -lm -L/usr/sfw/lib/64 -lgcc_s'
|
||||
|
||||
# Version information for libstdc++.
|
||||
current=6
|
||||
age=0
|
||||
revision=3
|
||||
|
||||
# Is this an already installed library?
|
||||
installed=yes
|
||||
|
||||
# Files to dlopen/dlpreopen
|
||||
dlopen=''
|
||||
dlpreopen=''
|
||||
|
||||
# Directory that this library needs to be installed in:
|
||||
libdir='/usr/sfw/lib'
|
|
@ -0,0 +1,325 @@
|
|||
// Copyright (c) 2011, Google Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following disclaimer
|
||||
// in the documentation and/or other materials provided with the
|
||||
// distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from
|
||||
// this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
// ---
|
||||
//
|
||||
// Some generically useful utility routines that in google-land would
|
||||
// be their own projects. We make a shortened version here.
|
||||
|
||||
#ifndef GFLAGS_UTIL_H_
|
||||
#define GFLAGS_UTIL_H_
|
||||
|
||||
#include <assert.h>
|
||||
#include <config.h>
|
||||
#ifdef HAVE_INTTYPES_H
|
||||
# include <inttypes.h>
|
||||
#endif
|
||||
#include <stdarg.h> // for va_*
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#ifdef HAVE_SYS_STAT_H
|
||||
# include <sys/stat.h>
|
||||
#endif // for mkdir()
|
||||
|
||||
_START_GOOGLE_NAMESPACE_
|
||||
|
||||
// This is used for unittests for death-testing. It is defined in gflags.cc.
|
||||
extern GFLAGS_DLL_DECL void (*gflags_exitfunc)(int);
|
||||
|
||||
// Work properly if either strtoll or strtoq is on this system
|
||||
#ifdef HAVE_STRTOLL
|
||||
# define strto64 strtoll
|
||||
# define strtou64 strtoull
|
||||
#elif HAVE_STRTOQ
|
||||
# define strto64 strtoq
|
||||
# define strtou64 strtouq
|
||||
#else
|
||||
// Neither strtoll nor strtoq are defined. I hope strtol works!
|
||||
# define strto64 strtol
|
||||
# define strtou64 strtoul
|
||||
#endif
|
||||
|
||||
// If we have inttypes.h, it will have defined PRId32/etc for us. If
|
||||
// not, take our best guess.
|
||||
#ifndef PRId32
|
||||
# define PRId32 "d"
|
||||
#endif
|
||||
#ifndef PRId64
|
||||
# define PRId64 "lld"
|
||||
#endif
|
||||
#ifndef PRIu64
|
||||
# define PRIu64 "llu"
|
||||
#endif
|
||||
|
||||
typedef signed char int8;
|
||||
typedef unsigned char uint8;
|
||||
|
||||
// -- utility macros ---------------------------------------------------------
|
||||
|
||||
template <bool> struct CompileAssert {};
|
||||
#define COMPILE_ASSERT(expr, msg) \
|
||||
typedef CompileAssert<(bool(expr))> msg[bool(expr) ? 1 : -1]
|
||||
|
||||
// Returns the number of elements in an array.
|
||||
#define arraysize(arr) (sizeof(arr)/sizeof(*(arr)))
|
||||
|
||||
|
||||
// -- logging and testing ---------------------------------------------------
|
||||
|
||||
// For now, we ignore the level for logging, and don't show *VLOG's at
|
||||
// all, except by hand-editing the lines below
|
||||
#define LOG(level) std::cerr
|
||||
#define VLOG(level) if (true) {} else std::cerr
|
||||
#define DVLOG(level) if (true) {} else std::cerr
|
||||
|
||||
// CHECK dies with a fatal error if condition is not true. It is *not*
|
||||
// controlled by NDEBUG, so the check will be executed regardless of
|
||||
// compilation mode. Therefore, it is safe to do things like:
|
||||
// CHECK(fp->Write(x) == 4)
|
||||
// We allow stream-like objects after this for debugging, but they're ignored.
|
||||
#define EXPECT_TRUE(condition) \
|
||||
if (true) { \
|
||||
if (!(condition)) { \
|
||||
fprintf(stderr, "Check failed: %s\n", #condition); \
|
||||
exit(1); \
|
||||
} \
|
||||
} else std::cerr << ""
|
||||
|
||||
#define EXPECT_OP(op, val1, val2) \
|
||||
if (true) { \
|
||||
if (!((val1) op (val2))) { \
|
||||
fprintf(stderr, "Check failed: %s %s %s\n", #val1, #op, #val2); \
|
||||
exit(1); \
|
||||
} \
|
||||
} else std::cerr << ""
|
||||
|
||||
#define EXPECT_EQ(val1, val2) EXPECT_OP(==, val1, val2)
|
||||
#define EXPECT_NE(val1, val2) EXPECT_OP(!=, val1, val2)
|
||||
#define EXPECT_LE(val1, val2) EXPECT_OP(<=, val1, val2)
|
||||
#define EXPECT_LT(val1, val2) EXPECT_OP(< , val1, val2)
|
||||
#define EXPECT_GE(val1, val2) EXPECT_OP(>=, val1, val2)
|
||||
#define EXPECT_GT(val1, val2) EXPECT_OP(> , val1, val2)
|
||||
#define EXPECT_FALSE(cond) EXPECT_TRUE(!(cond))
|
||||
|
||||
// C99 declares isnan and isinf should be macros, so the #ifdef test
|
||||
// should be reliable everywhere. Of course, it's not, but these
|
||||
// are testing pertty marginal functionality anyway, so it's ok to
|
||||
// not-run them even in situations they might, with effort, be made to work.
|
||||
#ifdef isnan // Some compilers, like sun's for Solaris 10, don't define this
|
||||
#define EXPECT_NAN(arg) \
|
||||
do { \
|
||||
if (!isnan(arg)) { \
|
||||
fprintf(stderr, "Check failed: isnan(%s)\n", #arg); \
|
||||
exit(1); \
|
||||
} \
|
||||
} while (0)
|
||||
#else
|
||||
#define EXPECT_NAN(arg)
|
||||
#endif
|
||||
|
||||
#ifdef isinf // Some compilers, like sun's for Solaris 10, don't define this
|
||||
#define EXPECT_INF(arg) \
|
||||
do { \
|
||||
if (!isinf(arg)) { \
|
||||
fprintf(stderr, "Check failed: isinf(%s)\n", #arg); \
|
||||
exit(1); \
|
||||
} \
|
||||
} while (0)
|
||||
#else
|
||||
#define EXPECT_INF(arg)
|
||||
#endif
|
||||
|
||||
#define EXPECT_DOUBLE_EQ(val1, val2) \
|
||||
do { \
|
||||
if (((val1) < (val2) - 0.001 || (val1) > (val2) + 0.001)) { \
|
||||
fprintf(stderr, "Check failed: %s == %s\n", #val1, #val2); \
|
||||
exit(1); \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
#define EXPECT_STREQ(val1, val2) \
|
||||
do { \
|
||||
if (strcmp((val1), (val2)) != 0) { \
|
||||
fprintf(stderr, "Check failed: streq(%s, %s)\n", #val1, #val2); \
|
||||
exit(1); \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
// Call this in a .cc file where you will later call RUN_ALL_TESTS in main().
|
||||
#define TEST_INIT \
|
||||
static std::vector<void (*)()> g_testlist; /* the tests to run */ \
|
||||
static int RUN_ALL_TESTS() { \
|
||||
std::vector<void (*)()>::const_iterator it; \
|
||||
for (it = g_testlist.begin(); it != g_testlist.end(); ++it) { \
|
||||
(*it)(); /* The test will error-exit if there's a problem. */ \
|
||||
} \
|
||||
fprintf(stderr, "\nPassed %d tests\n\nPASS\n", \
|
||||
static_cast<int>(g_testlist.size())); \
|
||||
return 0; \
|
||||
}
|
||||
|
||||
// Note that this macro uses a FlagSaver to keep tests isolated.
|
||||
#define TEST(a, b) \
|
||||
struct Test_##a##_##b { \
|
||||
Test_##a##_##b() { g_testlist.push_back(&Run); } \
|
||||
static void Run() { \
|
||||
FlagSaver fs; \
|
||||
fprintf(stderr, "Running test %s/%s\n", #a, #b); \
|
||||
RunTest(); \
|
||||
} \
|
||||
static void RunTest(); \
|
||||
}; \
|
||||
static Test_##a##_##b g_test_##a##_##b; \
|
||||
void Test_##a##_##b::RunTest()
|
||||
|
||||
// This is a dummy class that eases the google->opensource transition.
|
||||
namespace testing {
|
||||
class Test {};
|
||||
}
|
||||
|
||||
// Call this in a .cc file where you will later call EXPECT_DEATH
|
||||
#define EXPECT_DEATH_INIT \
|
||||
static bool g_called_exit; \
|
||||
static void CalledExit(int) { g_called_exit = true; }
|
||||
|
||||
#define EXPECT_DEATH(fn, msg) \
|
||||
do { \
|
||||
g_called_exit = false; \
|
||||
gflags_exitfunc = &CalledExit; \
|
||||
fn; \
|
||||
gflags_exitfunc = &exit; /* set back to its default */ \
|
||||
if (!g_called_exit) { \
|
||||
fprintf(stderr, "Function didn't die (%s): %s\n", msg, #fn); \
|
||||
exit(1); \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
#define GTEST_HAS_DEATH_TEST 1
|
||||
|
||||
// -- path routines ----------------------------------------------------------
|
||||
|
||||
// Tries to create the directory path as a temp-dir. If it fails,
|
||||
// changes path to some directory it *can* create.
|
||||
#if defined(__MINGW32__)
|
||||
#include <io.h>
|
||||
inline void MakeTmpdir(std::string* path) {
|
||||
// I had trouble creating a directory in /tmp from mingw
|
||||
*path = "./gflags_unittest_testdir";
|
||||
mkdir(path->c_str()); // mingw has a weird one-arg mkdir
|
||||
}
|
||||
#elif defined(_MSC_VER)
|
||||
#include <direct.h>
|
||||
inline void MakeTmpdir(std::string* path) {
|
||||
char tmppath_buffer[1024];
|
||||
int tmppath_len = GetTempPathA(sizeof(tmppath_buffer), tmppath_buffer);
|
||||
assert(tmppath_len > 0 && tmppath_len < sizeof(tmppath_buffer));
|
||||
assert(tmppath_buffer[tmppath_len - 1] == '\\'); // API guarantees it
|
||||
*path = std::string(tmppath_buffer) + "gflags_unittest_testdir";
|
||||
_mkdir(path->c_str());
|
||||
}
|
||||
#else
|
||||
inline void MakeTmpdir(std::string* path) {
|
||||
mkdir(path->c_str(), 0755);
|
||||
}
|
||||
#endif
|
||||
|
||||
// -- string routines --------------------------------------------------------
|
||||
|
||||
inline void InternalStringPrintf(std::string* output, const char* format,
|
||||
va_list ap) {
|
||||
char space[128]; // try a small buffer and hope it fits
|
||||
|
||||
// It's possible for methods that use a va_list to invalidate
|
||||
// the data in it upon use. The fix is to make a copy
|
||||
// of the structure before using it and use that copy instead.
|
||||
va_list backup_ap;
|
||||
va_copy(backup_ap, ap);
|
||||
int bytes_written = vsnprintf(space, sizeof(space), format, backup_ap);
|
||||
va_end(backup_ap);
|
||||
|
||||
if ((bytes_written >= 0) && (static_cast<size_t>(bytes_written) < sizeof(space))) {
|
||||
output->append(space, bytes_written);
|
||||
return;
|
||||
}
|
||||
|
||||
// Repeatedly increase buffer size until it fits.
|
||||
int length = sizeof(space);
|
||||
while (true) {
|
||||
if (bytes_written < 0) {
|
||||
// Older snprintf() behavior. :-( Just try doubling the buffer size
|
||||
length *= 2;
|
||||
} else {
|
||||
// We need exactly "bytes_written+1" characters
|
||||
length = bytes_written+1;
|
||||
}
|
||||
char* buf = new char[length];
|
||||
|
||||
// Restore the va_list before we use it again
|
||||
va_copy(backup_ap, ap);
|
||||
bytes_written = vsnprintf(buf, length, format, backup_ap);
|
||||
va_end(backup_ap);
|
||||
|
||||
if ((bytes_written >= 0) && (bytes_written < length)) {
|
||||
output->append(buf, bytes_written);
|
||||
delete[] buf;
|
||||
return;
|
||||
}
|
||||
delete[] buf;
|
||||
}
|
||||
}
|
||||
|
||||
// Clears output before writing to it.
|
||||
inline void SStringPrintf(std::string* output, const char* format, ...) {
|
||||
va_list ap;
|
||||
va_start(ap, format);
|
||||
output->clear();
|
||||
InternalStringPrintf(output, format, ap);
|
||||
va_end(ap);
|
||||
}
|
||||
|
||||
inline void StringAppendF(std::string* output, const char* format, ...) {
|
||||
va_list ap;
|
||||
va_start(ap, format);
|
||||
InternalStringPrintf(output, format, ap);
|
||||
va_end(ap);
|
||||
}
|
||||
|
||||
inline std::string StringPrintf(const char* format, ...) {
|
||||
va_list ap;
|
||||
va_start(ap, format);
|
||||
std::string output;
|
||||
InternalStringPrintf(&output, format, ap);
|
||||
va_end(ap);
|
||||
return output;
|
||||
}
|
||||
|
||||
_END_GOOGLE_NAMESPACE_
|
||||
|
||||
#endif // GFLAGS_UTIL_H_
|
|
@ -0,0 +1,139 @@
|
|||
/* src/config.h.in. Generated from configure.ac by autoheader. */
|
||||
|
||||
/* Sometimes we accidentally #include this config.h instead of the one
|
||||
in .. -- this is particularly true for msys/mingw, which uses the
|
||||
unix config.h but also runs code in the windows directory.
|
||||
*/
|
||||
#ifdef __MINGW32__
|
||||
#include "../config.h"
|
||||
#define GOOGLE_GFLAGS_WINDOWS_CONFIG_H_
|
||||
#endif
|
||||
|
||||
#ifndef GOOGLE_GFLAGS_WINDOWS_CONFIG_H_
|
||||
#define GOOGLE_GFLAGS_WINDOWS_CONFIG_H_
|
||||
|
||||
/* Always the empty-string on non-windows systems. On windows, should be
|
||||
"__declspec(dllexport)". This way, when we compile the dll, we export our
|
||||
functions/classes. It's safe to define this here because config.h is only
|
||||
used internally, to compile the DLL, and every DLL source file #includes
|
||||
"config.h" before anything else. */
|
||||
#ifndef GFLAGS_DLL_DECL
|
||||
# define GFLAGS_IS_A_DLL 1 /* not set if you're statically linking */
|
||||
# define GFLAGS_DLL_DECL __declspec(dllexport)
|
||||
# define GFLAGS_DLL_DECL_FOR_UNITTESTS __declspec(dllimport)
|
||||
#endif
|
||||
|
||||
/* Namespace for Google classes */
|
||||
#define GOOGLE_NAMESPACE ::google
|
||||
|
||||
/* Define to 1 if you have the <dlfcn.h> header file. */
|
||||
#undef HAVE_DLFCN_H
|
||||
|
||||
/* Define to 1 if you have the <fnmatch.h> header file. */
|
||||
#undef HAVE_FNMATCH_H
|
||||
|
||||
/* Define to 1 if you have the <inttypes.h> header file. */
|
||||
#undef HAVE_INTTYPES_H
|
||||
|
||||
/* Define to 1 if you have the <memory.h> header file. */
|
||||
#undef HAVE_MEMORY_H
|
||||
|
||||
/* define if the compiler implements namespaces */
|
||||
#define HAVE_NAMESPACES 1
|
||||
|
||||
/* Define if you have POSIX threads libraries and header files. */
|
||||
#undef HAVE_PTHREAD
|
||||
|
||||
/* Define to 1 if you have the `putenv' function. */
|
||||
#define HAVE_PUTENV 1
|
||||
|
||||
/* Define to 1 if you have the `setenv' function. */
|
||||
#undef HAVE_SETENV
|
||||
|
||||
/* Define to 1 if you have the <stdint.h> header file. */
|
||||
#undef HAVE_STDINT_H
|
||||
|
||||
/* Define to 1 if you have the <stdlib.h> header file. */
|
||||
#define HAVE_STDLIB_H 1
|
||||
|
||||
/* Define to 1 if you have the <strings.h> header file. */
|
||||
#undef HAVE_STRINGS_H
|
||||
|
||||
/* Define to 1 if you have the <string.h> header file. */
|
||||
#define HAVE_STRING_H 1
|
||||
|
||||
/* Define to 1 if you have the `strtoll' function. */
|
||||
#define HAVE_STRTOLL 1
|
||||
|
||||
/* Define to 1 if you have the `strtoq' function. */
|
||||
#define HAVE_STRTOQ 1
|
||||
|
||||
/* Define to 1 if you have the <sys/stat.h> header file. */
|
||||
#define HAVE_SYS_STAT_H 1
|
||||
|
||||
/* Define to 1 if you have the <sys/types.h> header file. */
|
||||
#define HAVE_SYS_TYPES_H 1
|
||||
|
||||
/* Define to 1 if you have the <unistd.h> header file. */
|
||||
#undef HAVE_UNISTD_H
|
||||
|
||||
/* define if your compiler has __attribute__ */
|
||||
#undef HAVE___ATTRIBUTE__
|
||||
|
||||
/* Define to the sub-directory in which libtool stores uninstalled libraries.
|
||||
*/
|
||||
#undef LT_OBJDIR
|
||||
|
||||
/* Name of package */
|
||||
#undef PACKAGE
|
||||
|
||||
/* Define to the address where bug reports for this package should be sent. */
|
||||
#undef PACKAGE_BUGREPORT
|
||||
|
||||
/* Define to the full name of this package. */
|
||||
#undef PACKAGE_NAME
|
||||
|
||||
/* Define to the full name and version of this package. */
|
||||
#undef PACKAGE_STRING
|
||||
|
||||
/* Define to the one symbol short name of this package. */
|
||||
#undef PACKAGE_TARNAME
|
||||
|
||||
/* Define to the home page for this package. */
|
||||
#undef PACKAGE_URL
|
||||
|
||||
/* Define to the version of this package. */
|
||||
#undef PACKAGE_VERSION
|
||||
|
||||
/* Define to necessary symbol if this constant uses a non-standard name on
|
||||
your system. */
|
||||
#undef PTHREAD_CREATE_JOINABLE
|
||||
|
||||
/* Define to 1 if you have the ANSI C header files. */
|
||||
#define STDC_HEADERS 1
|
||||
|
||||
/* the namespace where STL code like vector<> is defined */
|
||||
#define STL_NAMESPACE std
|
||||
|
||||
/* Version number of package */
|
||||
#undef VERSION
|
||||
|
||||
/* Stops putting the code inside the Google namespace */
|
||||
#define _END_GOOGLE_NAMESPACE_ }
|
||||
|
||||
/* Puts following code inside the Google namespace */
|
||||
#define _START_GOOGLE_NAMESPACE_ namespace google {
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// Extra stuff not found in config.h.in
|
||||
|
||||
// This must be defined before the windows.h is included. It's needed
|
||||
// for mutex.h, to give access to the TryLock method.
|
||||
#ifndef _WIN32_WINNT
|
||||
# define _WIN32_WINNT 0x0400
|
||||
#endif
|
||||
|
||||
// TODO(csilvers): include windows/port.h in every relevant source file instead?
|
||||
#include "windows/port.h"
|
||||
|
||||
#endif /* GOOGLE_GFLAGS_WINDOWS_CONFIG_H_ */
|
|
@ -0,0 +1,569 @@
|
|||
// Copyright (c) 2006, Google Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following disclaimer
|
||||
// in the documentation and/or other materials provided with the
|
||||
// distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from
|
||||
// this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
// ---
|
||||
// Revamped and reorganized by Craig Silverstein
|
||||
//
|
||||
// This is the file that should be included by any file which declares
|
||||
// or defines a command line flag or wants to parse command line flags
|
||||
// or print a program usage message (which will include information about
|
||||
// flags). Executive summary, in the form of an example foo.cc file:
|
||||
//
|
||||
// #include "foo.h" // foo.h has a line "DECLARE_int32(start);"
|
||||
// #include "validators.h" // hypothetical file defining ValidateIsFile()
|
||||
//
|
||||
// DEFINE_int32(end, 1000, "The last record to read");
|
||||
//
|
||||
// DEFINE_string(filename, "my_file.txt", "The file to read");
|
||||
// // Crash if the specified file does not exist.
|
||||
// static bool dummy = RegisterFlagValidator(&FLAGS_filename,
|
||||
// &ValidateIsFile);
|
||||
//
|
||||
// DECLARE_bool(verbose); // some other file has a DEFINE_bool(verbose, ...)
|
||||
//
|
||||
// void MyFunc() {
|
||||
// if (FLAGS_verbose) printf("Records %d-%d\n", FLAGS_start, FLAGS_end);
|
||||
// }
|
||||
//
|
||||
// Then, at the command-line:
|
||||
// ./foo --noverbose --start=5 --end=100
|
||||
//
|
||||
// For more details, see
|
||||
// doc/gflags.html
|
||||
//
|
||||
// --- A note about thread-safety:
|
||||
//
|
||||
// We describe many functions in this routine as being thread-hostile,
|
||||
// thread-compatible, or thread-safe. Here are the meanings we use:
|
||||
//
|
||||
// thread-safe: it is safe for multiple threads to call this routine
|
||||
// (or, when referring to a class, methods of this class)
|
||||
// concurrently.
|
||||
// thread-hostile: it is not safe for multiple threads to call this
|
||||
// routine (or methods of this class) concurrently. In gflags,
|
||||
// most thread-hostile routines are intended to be called early in,
|
||||
// or even before, main() -- that is, before threads are spawned.
|
||||
// thread-compatible: it is safe for multiple threads to read from
|
||||
// this variable (when applied to variables), or to call const
|
||||
// methods of this class (when applied to classes), as long as no
|
||||
// other thread is writing to the variable or calling non-const
|
||||
// methods of this class.
|
||||
|
||||
#ifndef BASE_COMMANDLINEFLAGS_H_
|
||||
#define BASE_COMMANDLINEFLAGS_H_
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <gflags/gflags_declare.h> // IWYU pragma: export
|
||||
namespace google {
|
||||
|
||||
//
|
||||
// NOTE: all functions below MUST have an explicit 'extern' before
|
||||
// them. Our automated opensourcing tools use this as a signal to do
|
||||
// appropriate munging for windows, which needs to add GFLAGS_DLL_DECL.
|
||||
//
|
||||
#if defined(_MSC_VER) && !defined(GFLAGS_DLL_DECL)
|
||||
# define GFLAGS_DLL_DECL __declspec(dllimport)
|
||||
#endif
|
||||
#if defined(_MSC_VER) && !defined(GFLAGS_DLL_DEFINE_FLAG)
|
||||
# define GFLAGS_DLL_DEFINE_FLAG __declspec(dllexport)
|
||||
#endif
|
||||
|
||||
|
||||
// --------------------------------------------------------------------
|
||||
// To actually define a flag in a file, use DEFINE_bool,
|
||||
// DEFINE_string, etc. at the bottom of this file. You may also find
|
||||
// it useful to register a validator with the flag. This ensures that
|
||||
// when the flag is parsed from the commandline, or is later set via
|
||||
// SetCommandLineOption, we call the validation function. It is _not_
|
||||
// called when you assign the value to the flag directly using the = operator.
|
||||
//
|
||||
// The validation function should return true if the flag value is valid, and
|
||||
// false otherwise. If the function returns false for the new setting of the
|
||||
// flag, the flag will retain its current value. If it returns false for the
|
||||
// default value, ParseCommandLineFlags() will die.
|
||||
//
|
||||
// This function is safe to call at global construct time (as in the
|
||||
// example below).
|
||||
//
|
||||
// Example use:
|
||||
// static bool ValidatePort(const char* flagname, int32 value) {
|
||||
// if (value > 0 && value < 32768) // value is ok
|
||||
// return true;
|
||||
// printf("Invalid value for --%s: %d\n", flagname, (int)value);
|
||||
// return false;
|
||||
// }
|
||||
// DEFINE_int32(port, 0, "What port to listen on");
|
||||
// static bool dummy = RegisterFlagValidator(&FLAGS_port, &ValidatePort);
|
||||
|
||||
// Returns true if successfully registered, false if not (because the
|
||||
// first argument doesn't point to a command-line flag, or because a
|
||||
// validator is already registered for this flag).
|
||||
extern GFLAGS_DLL_DECL bool RegisterFlagValidator(const bool* flag,
|
||||
bool (*validate_fn)(const char*, bool));
|
||||
extern GFLAGS_DLL_DECL bool RegisterFlagValidator(const int32* flag,
|
||||
bool (*validate_fn)(const char*, int32));
|
||||
extern GFLAGS_DLL_DECL bool RegisterFlagValidator(const int64* flag,
|
||||
bool (*validate_fn)(const char*, int64));
|
||||
extern GFLAGS_DLL_DECL bool RegisterFlagValidator(const uint64* flag,
|
||||
bool (*validate_fn)(const char*, uint64));
|
||||
extern GFLAGS_DLL_DECL bool RegisterFlagValidator(const double* flag,
|
||||
bool (*validate_fn)(const char*, double));
|
||||
extern GFLAGS_DLL_DECL bool RegisterFlagValidator(const std::string* flag,
|
||||
bool (*validate_fn)(const char*,
|
||||
const std::string&));
|
||||
|
||||
|
||||
// --------------------------------------------------------------------
|
||||
// These methods are the best way to get access to info about the
|
||||
// list of commandline flags. Note that these routines are pretty slow.
|
||||
// GetAllFlags: mostly-complete info about the list, sorted by file.
|
||||
// ShowUsageWithFlags: pretty-prints the list to stdout (what --help does)
|
||||
// ShowUsageWithFlagsRestrict: limit to filenames with restrict as a substr
|
||||
//
|
||||
// In addition to accessing flags, you can also access argv[0] (the program
|
||||
// name) and argv (the entire commandline), which we sock away a copy of.
|
||||
// These variables are static, so you should only set them once.
|
||||
|
||||
struct GFLAGS_DLL_DECL CommandLineFlagInfo {
|
||||
std::string name; // the name of the flag
|
||||
std::string type; // the type of the flag: int32, etc
|
||||
std::string description; // the "help text" associated with the flag
|
||||
std::string current_value; // the current value, as a string
|
||||
std::string default_value; // the default value, as a string
|
||||
std::string filename; // 'cleaned' version of filename holding the flag
|
||||
bool has_validator_fn; // true if RegisterFlagValidator called on this flag
|
||||
bool is_default; // true if the flag has the default value and
|
||||
// has not been set explicitly from the cmdline
|
||||
// or via SetCommandLineOption
|
||||
const void* flag_ptr; // pointer to the flag's current value (i.e. FLAGS_foo)
|
||||
};
|
||||
|
||||
// Using this inside of a validator is a recipe for a deadlock.
|
||||
// TODO(user) Fix locking when validators are running, to make it safe to
|
||||
// call validators during ParseAllFlags.
|
||||
// Also make sure then to uncomment the corresponding unit test in
|
||||
// gflags_unittest.sh
|
||||
extern GFLAGS_DLL_DECL void GetAllFlags(std::vector<CommandLineFlagInfo>* OUTPUT);
|
||||
// These two are actually defined in gflags_reporting.cc.
|
||||
extern GFLAGS_DLL_DECL void ShowUsageWithFlags(const char *argv0); // what --help does
|
||||
extern GFLAGS_DLL_DECL void ShowUsageWithFlagsRestrict(const char *argv0, const char *restrict);
|
||||
|
||||
// Create a descriptive string for a flag.
|
||||
// Goes to some trouble to make pretty line breaks.
|
||||
extern GFLAGS_DLL_DECL std::string DescribeOneFlag(const CommandLineFlagInfo& flag);
|
||||
|
||||
// Thread-hostile; meant to be called before any threads are spawned.
|
||||
extern GFLAGS_DLL_DECL void SetArgv(int argc, const char** argv);
|
||||
|
||||
// The following functions are thread-safe as long as SetArgv() is
|
||||
// only called before any threads start.
|
||||
extern GFLAGS_DLL_DECL const std::vector<std::string>& GetArgvs();
|
||||
extern GFLAGS_DLL_DECL const char* GetArgv(); // all of argv as a string
|
||||
extern GFLAGS_DLL_DECL const char* GetArgv0(); // only argv0
|
||||
extern GFLAGS_DLL_DECL uint32 GetArgvSum(); // simple checksum of argv
|
||||
extern GFLAGS_DLL_DECL const char* ProgramInvocationName(); // argv0, or "UNKNOWN" if not set
|
||||
extern GFLAGS_DLL_DECL const char* ProgramInvocationShortName(); // basename(argv0)
|
||||
|
||||
// ProgramUsage() is thread-safe as long as SetUsageMessage() is only
|
||||
// called before any threads start.
|
||||
extern GFLAGS_DLL_DECL const char* ProgramUsage(); // string set by SetUsageMessage()
|
||||
|
||||
// VersionString() is thread-safe as long as SetVersionString() is only
|
||||
// called before any threads start.
|
||||
extern GFLAGS_DLL_DECL const char* VersionString(); // string set by SetVersionString()
|
||||
|
||||
|
||||
|
||||
// --------------------------------------------------------------------
|
||||
// Normally you access commandline flags by just saying "if (FLAGS_foo)"
|
||||
// or whatever, and set them by calling "FLAGS_foo = bar" (or, more
|
||||
// commonly, via the DEFINE_foo macro). But if you need a bit more
|
||||
// control, we have programmatic ways to get/set the flags as well.
|
||||
// These programmatic ways to access flags are thread-safe, but direct
|
||||
// access is only thread-compatible.
|
||||
|
||||
// Return true iff the flagname was found.
|
||||
// OUTPUT is set to the flag's value, or unchanged if we return false.
|
||||
extern GFLAGS_DLL_DECL bool GetCommandLineOption(const char* name, std::string* OUTPUT);
|
||||
|
||||
// Return true iff the flagname was found. OUTPUT is set to the flag's
|
||||
// CommandLineFlagInfo or unchanged if we return false.
|
||||
extern GFLAGS_DLL_DECL bool GetCommandLineFlagInfo(const char* name,
|
||||
CommandLineFlagInfo* OUTPUT);
|
||||
|
||||
// Return the CommandLineFlagInfo of the flagname. exit() if name not found.
|
||||
// Example usage, to check if a flag's value is currently the default value:
|
||||
// if (GetCommandLineFlagInfoOrDie("foo").is_default) ...
|
||||
extern GFLAGS_DLL_DECL CommandLineFlagInfo GetCommandLineFlagInfoOrDie(const char* name);
|
||||
|
||||
enum GFLAGS_DLL_DECL FlagSettingMode {
|
||||
// update the flag's value (can call this multiple times).
|
||||
SET_FLAGS_VALUE,
|
||||
// update the flag's value, but *only if* it has not yet been updated
|
||||
// with SET_FLAGS_VALUE, SET_FLAG_IF_DEFAULT, or "FLAGS_xxx = nondef".
|
||||
SET_FLAG_IF_DEFAULT,
|
||||
// set the flag's default value to this. If the flag has not yet updated
|
||||
// yet (via SET_FLAGS_VALUE, SET_FLAG_IF_DEFAULT, or "FLAGS_xxx = nondef")
|
||||
// change the flag's current value to the new default value as well.
|
||||
SET_FLAGS_DEFAULT
|
||||
};
|
||||
|
||||
// Set a particular flag ("command line option"). Returns a string
|
||||
// describing the new value that the option has been set to. The
|
||||
// return value API is not well-specified, so basically just depend on
|
||||
// it to be empty if the setting failed for some reason -- the name is
|
||||
// not a valid flag name, or the value is not a valid value -- and
|
||||
// non-empty else.
|
||||
|
||||
// SetCommandLineOption uses set_mode == SET_FLAGS_VALUE (the common case)
|
||||
extern GFLAGS_DLL_DECL std::string SetCommandLineOption(const char* name, const char* value);
|
||||
extern GFLAGS_DLL_DECL std::string SetCommandLineOptionWithMode(const char* name, const char* value,
|
||||
FlagSettingMode set_mode);
|
||||
|
||||
|
||||
// --------------------------------------------------------------------
|
||||
// Saves the states (value, default value, whether the user has set
|
||||
// the flag, registered validators, etc) of all flags, and restores
|
||||
// them when the FlagSaver is destroyed. This is very useful in
|
||||
// tests, say, when you want to let your tests change the flags, but
|
||||
// make sure that they get reverted to the original states when your
|
||||
// test is complete.
|
||||
//
|
||||
// Example usage:
|
||||
// void TestFoo() {
|
||||
// FlagSaver s1;
|
||||
// FLAG_foo = false;
|
||||
// FLAG_bar = "some value";
|
||||
//
|
||||
// // test happens here. You can return at any time
|
||||
// // without worrying about restoring the FLAG values.
|
||||
// }
|
||||
//
|
||||
// Note: This class is marked with ATTRIBUTE_UNUSED because all the
|
||||
// work is done in the constructor and destructor, so in the standard
|
||||
// usage example above, the compiler would complain that it's an
|
||||
// unused variable.
|
||||
//
|
||||
// This class is thread-safe. However, its destructor writes to
|
||||
// exactly the set of flags that have changed value during its
|
||||
// lifetime, so concurrent _direct_ access to those flags
|
||||
// (i.e. FLAGS_foo instead of {Get,Set}CommandLineOption()) is unsafe.
|
||||
|
||||
class GFLAGS_DLL_DECL FlagSaver {
|
||||
public:
|
||||
FlagSaver();
|
||||
~FlagSaver();
|
||||
|
||||
private:
|
||||
class FlagSaverImpl* impl_; // we use pimpl here to keep API steady
|
||||
|
||||
FlagSaver(const FlagSaver&); // no copying!
|
||||
void operator=(const FlagSaver&);
|
||||
}
|
||||
;
|
||||
|
||||
// --------------------------------------------------------------------
|
||||
// Some deprecated or hopefully-soon-to-be-deprecated functions.
|
||||
|
||||
// This is often used for logging. TODO(csilvers): figure out a better way
|
||||
extern GFLAGS_DLL_DECL std::string CommandlineFlagsIntoString();
|
||||
// Usually where this is used, a FlagSaver should be used instead.
|
||||
extern GFLAGS_DLL_DECL bool ReadFlagsFromString(const std::string& flagfilecontents,
|
||||
const char* prog_name,
|
||||
bool errors_are_fatal); // uses SET_FLAGS_VALUE
|
||||
|
||||
// These let you manually implement --flagfile functionality.
|
||||
// DEPRECATED.
|
||||
extern GFLAGS_DLL_DECL bool AppendFlagsIntoFile(const std::string& filename, const char* prog_name);
|
||||
extern GFLAGS_DLL_DECL bool ReadFromFlagsFile(const std::string& filename, const char* prog_name,
|
||||
bool errors_are_fatal); // uses SET_FLAGS_VALUE
|
||||
|
||||
|
||||
// --------------------------------------------------------------------
|
||||
// Useful routines for initializing flags from the environment.
|
||||
// In each case, if 'varname' does not exist in the environment
|
||||
// return defval. If 'varname' does exist but is not valid
|
||||
// (e.g., not a number for an int32 flag), abort with an error.
|
||||
// Otherwise, return the value. NOTE: for booleans, for true use
|
||||
// 't' or 'T' or 'true' or '1', for false 'f' or 'F' or 'false' or '0'.
|
||||
|
||||
extern GFLAGS_DLL_DECL bool BoolFromEnv(const char *varname, bool defval);
|
||||
extern GFLAGS_DLL_DECL int32 Int32FromEnv(const char *varname, int32 defval);
|
||||
extern GFLAGS_DLL_DECL int64 Int64FromEnv(const char *varname, int64 defval);
|
||||
extern GFLAGS_DLL_DECL uint64 Uint64FromEnv(const char *varname, uint64 defval);
|
||||
extern GFLAGS_DLL_DECL double DoubleFromEnv(const char *varname, double defval);
|
||||
extern GFLAGS_DLL_DECL const char *StringFromEnv(const char *varname, const char *defval);
|
||||
|
||||
|
||||
// --------------------------------------------------------------------
|
||||
// The next two functions parse gflags from main():
|
||||
|
||||
// Set the "usage" message for this program. For example:
|
||||
// string usage("This program does nothing. Sample usage:\n");
|
||||
// usage += argv[0] + " <uselessarg1> <uselessarg2>";
|
||||
// SetUsageMessage(usage);
|
||||
// Do not include commandline flags in the usage: we do that for you!
|
||||
// Thread-hostile; meant to be called before any threads are spawned.
|
||||
extern GFLAGS_DLL_DECL void SetUsageMessage(const std::string& usage);
|
||||
|
||||
// Sets the version string, which is emitted with --version.
|
||||
// For instance: SetVersionString("1.3");
|
||||
// Thread-hostile; meant to be called before any threads are spawned.
|
||||
extern GFLAGS_DLL_DECL void SetVersionString(const std::string& version);
|
||||
|
||||
|
||||
// Looks for flags in argv and parses them. Rearranges argv to put
|
||||
// flags first, or removes them entirely if remove_flags is true.
|
||||
// If a flag is defined more than once in the command line or flag
|
||||
// file, the last definition is used. Returns the index (into argv)
|
||||
// of the first non-flag argument.
|
||||
// See top-of-file for more details on this function.
|
||||
#ifndef SWIG // In swig, use ParseCommandLineFlagsScript() instead.
|
||||
extern GFLAGS_DLL_DECL uint32 ParseCommandLineFlags(int *argc, char*** argv, bool remove_flags);
|
||||
#endif
|
||||
|
||||
|
||||
// Calls to ParseCommandLineNonHelpFlags and then to
|
||||
// HandleCommandLineHelpFlags can be used instead of a call to
|
||||
// ParseCommandLineFlags during initialization, in order to allow for
|
||||
// changing default values for some FLAGS (via
|
||||
// e.g. SetCommandLineOptionWithMode calls) between the time of
|
||||
// command line parsing and the time of dumping help information for
|
||||
// the flags as a result of command line parsing. If a flag is
|
||||
// defined more than once in the command line or flag file, the last
|
||||
// definition is used. Returns the index (into argv) of the first
|
||||
// non-flag argument. (If remove_flags is true, will always return 1.)
|
||||
extern GFLAGS_DLL_DECL uint32 ParseCommandLineNonHelpFlags(int *argc, char*** argv,
|
||||
bool remove_flags);
|
||||
// This is actually defined in gflags_reporting.cc.
|
||||
// This function is misnamed (it also handles --version, etc.), but
|
||||
// it's too late to change that now. :-(
|
||||
extern GFLAGS_DLL_DECL void HandleCommandLineHelpFlags(); // in gflags_reporting.cc
|
||||
|
||||
// Allow command line reparsing. Disables the error normally
|
||||
// generated when an unknown flag is found, since it may be found in a
|
||||
// later parse. Thread-hostile; meant to be called before any threads
|
||||
// are spawned.
|
||||
extern GFLAGS_DLL_DECL void AllowCommandLineReparsing();
|
||||
|
||||
// Reparse the flags that have not yet been recognized. Only flags
|
||||
// registered since the last parse will be recognized. Any flag value
|
||||
// must be provided as part of the argument using "=", not as a
|
||||
// separate command line argument that follows the flag argument.
|
||||
// Intended for handling flags from dynamically loaded libraries,
|
||||
// since their flags are not registered until they are loaded.
|
||||
extern GFLAGS_DLL_DECL void ReparseCommandLineNonHelpFlags();
|
||||
|
||||
// Clean up memory allocated by flags. This is only needed to reduce
|
||||
// the quantity of "potentially leaked" reports emitted by memory
|
||||
// debugging tools such as valgrind. It is not required for normal
|
||||
// operation, or for the google perftools heap-checker. It must only
|
||||
// be called when the process is about to exit, and all threads that
|
||||
// might access flags are quiescent. Referencing flags after this is
|
||||
// called will have unexpected consequences. This is not safe to run
|
||||
// when multiple threads might be running: the function is
|
||||
// thread-hostile.
|
||||
extern GFLAGS_DLL_DECL void ShutDownCommandLineFlags();
|
||||
|
||||
|
||||
// --------------------------------------------------------------------
|
||||
// Now come the command line flag declaration/definition macros that
|
||||
// will actually be used. They're kind of hairy. A major reason
|
||||
// for this is initialization: we want people to be able to access
|
||||
// variables in global constructors and have that not crash, even if
|
||||
// their global constructor runs before the global constructor here.
|
||||
// (Obviously, we can't guarantee the flags will have the correct
|
||||
// default value in that case, but at least accessing them is safe.)
|
||||
// The only way to do that is have flags point to a static buffer.
|
||||
// So we make one, using a union to ensure proper alignment, and
|
||||
// then use placement-new to actually set up the flag with the
|
||||
// correct default value. In the same vein, we have to worry about
|
||||
// flag access in global destructors, so FlagRegisterer has to be
|
||||
// careful never to destroy the flag-values it constructs.
|
||||
//
|
||||
// Note that when we define a flag variable FLAGS_<name>, we also
|
||||
// preemptively define a junk variable, FLAGS_no<name>. This is to
|
||||
// cause a link-time error if someone tries to define 2 flags with
|
||||
// names like "logging" and "nologging". We do this because a bool
|
||||
// flag FLAG can be set from the command line to true with a "-FLAG"
|
||||
// argument, and to false with a "-noFLAG" argument, and so this can
|
||||
// potentially avert confusion.
|
||||
//
|
||||
// We also put flags into their own namespace. It is purposefully
|
||||
// named in an opaque way that people should have trouble typing
|
||||
// directly. The idea is that DEFINE puts the flag in the weird
|
||||
// namespace, and DECLARE imports the flag from there into the current
|
||||
// namespace. The net result is to force people to use DECLARE to get
|
||||
// access to a flag, rather than saying "extern bool FLAGS_whatever;"
|
||||
// or some such instead. We want this so we can put extra
|
||||
// functionality (like sanity-checking) in DECLARE if we want, and
|
||||
// make sure it is picked up everywhere.
|
||||
//
|
||||
// We also put the type of the variable in the namespace, so that
|
||||
// people can't DECLARE_int32 something that they DEFINE_bool'd
|
||||
// elsewhere.
|
||||
|
||||
class GFLAGS_DLL_DECL FlagRegisterer {
|
||||
public:
|
||||
FlagRegisterer(const char* name, const char* type,
|
||||
const char* help, const char* filename,
|
||||
void* current_storage, void* defvalue_storage);
|
||||
};
|
||||
|
||||
// If your application #defines STRIP_FLAG_HELP to a non-zero value
|
||||
// before #including this file, we remove the help message from the
|
||||
// binary file. This can reduce the size of the resulting binary
|
||||
// somewhat, and may also be useful for security reasons.
|
||||
|
||||
extern GFLAGS_DLL_DECL const char kStrippedFlagHelp[];
|
||||
|
||||
}
|
||||
|
||||
#ifndef SWIG // In swig, ignore the main flag declarations
|
||||
|
||||
#if defined(STRIP_FLAG_HELP) && STRIP_FLAG_HELP > 0
|
||||
// Need this construct to avoid the 'defined but not used' warning.
|
||||
#define MAYBE_STRIPPED_HELP(txt) \
|
||||
(false ? (txt) : ::google::kStrippedFlagHelp)
|
||||
#else
|
||||
#define MAYBE_STRIPPED_HELP(txt) txt
|
||||
#endif
|
||||
|
||||
// Each command-line flag has two variables associated with it: one
|
||||
// with the current value, and one with the default value. However,
|
||||
// we have a third variable, which is where value is assigned; it's a
|
||||
// constant. This guarantees that FLAG_##value is initialized at
|
||||
// static initialization time (e.g. before program-start) rather than
|
||||
// than global construction time (which is after program-start but
|
||||
// before main), at least when 'value' is a compile-time constant. We
|
||||
// use a small trick for the "default value" variable, and call it
|
||||
// FLAGS_no<name>. This serves the second purpose of assuring a
|
||||
// compile error if someone tries to define a flag named no<name>
|
||||
// which is illegal (--foo and --nofoo both affect the "foo" flag).
|
||||
#define DEFINE_VARIABLE(type, shorttype, name, value, help) \
|
||||
namespace fL##shorttype { \
|
||||
static const type FLAGS_nono##name = value; \
|
||||
/* We always want to export defined variables, dll or no */ \
|
||||
GFLAGS_DLL_DEFINE_FLAG type FLAGS_##name = FLAGS_nono##name; \
|
||||
type FLAGS_no##name = FLAGS_nono##name; \
|
||||
static ::google::FlagRegisterer o_##name( \
|
||||
#name, #type, MAYBE_STRIPPED_HELP(help), __FILE__, \
|
||||
&FLAGS_##name, &FLAGS_no##name); \
|
||||
} \
|
||||
using fL##shorttype::FLAGS_##name
|
||||
|
||||
// For DEFINE_bool, we want to do the extra check that the passed-in
|
||||
// value is actually a bool, and not a string or something that can be
|
||||
// coerced to a bool. These declarations (no definition needed!) will
|
||||
// help us do that, and never evaluate From, which is important.
|
||||
// We'll use 'sizeof(IsBool(val))' to distinguish. This code requires
|
||||
// that the compiler have different sizes for bool & double. Since
|
||||
// this is not guaranteed by the standard, we check it with a
|
||||
// COMPILE_ASSERT.
|
||||
namespace fLB {
|
||||
struct CompileAssert {};
|
||||
typedef CompileAssert expected_sizeof_double_neq_sizeof_bool[
|
||||
(sizeof(double) != sizeof(bool)) ? 1 : -1];
|
||||
template<typename From> double GFLAGS_DLL_DECL IsBoolFlag(const From& from);
|
||||
GFLAGS_DLL_DECL bool IsBoolFlag(bool from);
|
||||
} // namespace fLB
|
||||
|
||||
// Here are the actual DEFINE_*-macros. The respective DECLARE_*-macros
|
||||
// are in a separate include, gflags_declare.h, for reducing
|
||||
// the physical transitive size for DECLARE use.
|
||||
#define DEFINE_bool(name, val, txt) \
|
||||
namespace fLB { \
|
||||
typedef ::fLB::CompileAssert FLAG_##name##_value_is_not_a_bool[ \
|
||||
(sizeof(::fLB::IsBoolFlag(val)) != sizeof(double)) ? 1 : -1]; \
|
||||
} \
|
||||
DEFINE_VARIABLE(bool, B, name, val, txt)
|
||||
|
||||
#define DEFINE_int32(name, val, txt) \
|
||||
DEFINE_VARIABLE(::google::int32, I, \
|
||||
name, val, txt)
|
||||
|
||||
#define DEFINE_int64(name, val, txt) \
|
||||
DEFINE_VARIABLE(::google::int64, I64, \
|
||||
name, val, txt)
|
||||
|
||||
#define DEFINE_uint64(name,val, txt) \
|
||||
DEFINE_VARIABLE(::google::uint64, U64, \
|
||||
name, val, txt)
|
||||
|
||||
#define DEFINE_double(name, val, txt) \
|
||||
DEFINE_VARIABLE(double, D, name, val, txt)
|
||||
|
||||
// Strings are trickier, because they're not a POD, so we can't
|
||||
// construct them at static-initialization time (instead they get
|
||||
// constructed at global-constructor time, which is much later). To
|
||||
// try to avoid crashes in that case, we use a char buffer to store
|
||||
// the string, which we can static-initialize, and then placement-new
|
||||
// into it later. It's not perfect, but the best we can do.
|
||||
|
||||
namespace fLS {
|
||||
|
||||
inline clstring* dont_pass0toDEFINE_string(char *stringspot,
|
||||
const char *value) {
|
||||
return new(stringspot) clstring(value);
|
||||
}
|
||||
inline clstring* dont_pass0toDEFINE_string(char *stringspot,
|
||||
const clstring &value) {
|
||||
return new(stringspot) clstring(value);
|
||||
}
|
||||
inline clstring* dont_pass0toDEFINE_string(char *stringspot,
|
||||
int value);
|
||||
} // namespace fLS
|
||||
|
||||
// We need to define a var named FLAGS_no##name so people don't define
|
||||
// --string and --nostring. And we need a temporary place to put val
|
||||
// so we don't have to evaluate it twice. Two great needs that go
|
||||
// great together!
|
||||
// The weird 'using' + 'extern' inside the fLS namespace is to work around
|
||||
// an unknown compiler bug/issue with the gcc 4.2.1 on SUSE 10. See
|
||||
// http://code.google.com/p/google-gflags/issues/detail?id=20
|
||||
#define DEFINE_string(name, val, txt) \
|
||||
namespace fLS { \
|
||||
using ::fLS::clstring; \
|
||||
static union { void* align; char s[sizeof(clstring)]; } s_##name[2]; \
|
||||
clstring* const FLAGS_no##name = ::fLS:: \
|
||||
dont_pass0toDEFINE_string(s_##name[0].s, \
|
||||
val); \
|
||||
static ::google::FlagRegisterer o_##name( \
|
||||
#name, "string", MAYBE_STRIPPED_HELP(txt), __FILE__, \
|
||||
s_##name[0].s, new (s_##name[1].s) clstring(*FLAGS_no##name)); \
|
||||
extern GFLAGS_DLL_DEFINE_FLAG clstring& FLAGS_##name; \
|
||||
using fLS::FLAGS_##name; \
|
||||
clstring& FLAGS_##name = *FLAGS_no##name; \
|
||||
} \
|
||||
using fLS::FLAGS_##name
|
||||
|
||||
#endif // SWIG
|
||||
|
||||
#endif // BASE_COMMANDLINEFLAGS_H_
|
|
@ -0,0 +1,132 @@
|
|||
// Copyright (c) 2008, Google Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following disclaimer
|
||||
// in the documentation and/or other materials provided with the
|
||||
// distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from
|
||||
// this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
//
|
||||
// ---
|
||||
|
||||
//
|
||||
// Implement helpful bash-style command line flag completions
|
||||
//
|
||||
// ** Functional API:
|
||||
// HandleCommandLineCompletions() should be called early during
|
||||
// program startup, but after command line flag code has been
|
||||
// initialized, such as the beginning of HandleCommandLineHelpFlags().
|
||||
// It checks the value of the flag --tab_completion_word. If this
|
||||
// flag is empty, nothing happens here. If it contains a string,
|
||||
// however, then HandleCommandLineCompletions() will hijack the
|
||||
// process, attempting to identify the intention behind this
|
||||
// completion. Regardless of the outcome of this deduction, the
|
||||
// process will be terminated, similar to --helpshort flag
|
||||
// handling.
|
||||
//
|
||||
// ** Overview of Bash completions:
|
||||
// Bash can be told to programatically determine completions for the
|
||||
// current 'cursor word'. It does this by (in this case) invoking a
|
||||
// command with some additional arguments identifying the command
|
||||
// being executed, the word being completed, and the previous word
|
||||
// (if any). Bash then expects a sequence of output lines to be
|
||||
// printed to stdout. If these lines all contain a common prefix
|
||||
// longer than the cursor word, bash will replace the cursor word
|
||||
// with that common prefix, and display nothing. If there isn't such
|
||||
// a common prefix, bash will display the lines in pages using 'more'.
|
||||
//
|
||||
// ** Strategy taken for command line completions:
|
||||
// If we can deduce either the exact flag intended, or a common flag
|
||||
// prefix, we'll output exactly that. Otherwise, if information
|
||||
// must be displayed to the user, we'll take the opportunity to add
|
||||
// some helpful information beyond just the flag name (specifically,
|
||||
// we'll include the default flag value and as much of the flag's
|
||||
// description as can fit on a single terminal line width, as specified
|
||||
// by the flag --tab_completion_columns). Furthermore, we'll try to
|
||||
// make bash order the output such that the most useful or relevent
|
||||
// flags are the most likely to be shown at the top.
|
||||
//
|
||||
// ** Additional features:
|
||||
// To assist in finding that one really useful flag, substring matching
|
||||
// was implemented. Before pressing a <TAB> to get completion for the
|
||||
// current word, you can append one or more '?' to the flag to do
|
||||
// substring matching. Here's the semantics:
|
||||
// --foo<TAB> Show me all flags with names prefixed by 'foo'
|
||||
// --foo?<TAB> Show me all flags with 'foo' somewhere in the name
|
||||
// --foo??<TAB> Same as prior case, but also search in module
|
||||
// definition path for 'foo'
|
||||
// --foo???<TAB> Same as prior case, but also search in flag
|
||||
// descriptions for 'foo'
|
||||
// Finally, we'll trim the output to a relatively small number of
|
||||
// flags to keep bash quiet about the verbosity of output. If one
|
||||
// really wanted to see all possible matches, appending a '+' to the
|
||||
// search word will force the exhaustive list of matches to be printed.
|
||||
//
|
||||
// ** How to have bash accept completions from a binary:
|
||||
// Bash requires that it be informed about each command that programmatic
|
||||
// completion should be enabled for. Example addition to a .bashrc
|
||||
// file would be (your path to gflags_completions.sh file may differ):
|
||||
|
||||
/*
|
||||
$ complete -o bashdefault -o default -o nospace -C \
|
||||
'/home/build/eng/bash/bash_completions.sh --tab_completion_columns $COLUMNS' \
|
||||
time env binary_name another_binary [...]
|
||||
*/
|
||||
|
||||
// This would allow the following to work:
|
||||
// $ /path/to/binary_name --vmodule<TAB>
|
||||
// Or:
|
||||
// $ ./bin/path/another_binary --gfs_u<TAB>
|
||||
// (etc)
|
||||
//
|
||||
// Sadly, it appears that bash gives no easy way to force this behavior for
|
||||
// all commands. That's where the "time" in the above example comes in.
|
||||
// If you haven't specifically added a command to the list of completion
|
||||
// supported commands, you can still get completions by prefixing the
|
||||
// entire command with "env".
|
||||
// $ env /some/brand/new/binary --vmod<TAB>
|
||||
// Assuming that "binary" is a newly compiled binary, this should still
|
||||
// produce the expected completion output.
|
||||
|
||||
|
||||
#ifndef BASE_COMMANDLINEFLAGS_COMPLETIONS_H_
|
||||
#define BASE_COMMANDLINEFLAGS_COMPLETIONS_H_
|
||||
|
||||
// Annoying stuff for windows -- makes sure clients can import these functions
|
||||
//
|
||||
// NOTE: all functions below MUST have an explicit 'extern' before
|
||||
// them. Our automated opensourcing tools use this as a signal to do
|
||||
// appropriate munging for windows, which needs to add GFLAGS_DLL_DECL.
|
||||
//
|
||||
#if defined(_MSC_VER) && !defined(GFLAGS_DLL_DECL)
|
||||
# define GFLAGS_DLL_DECL __declspec(dllimport)
|
||||
#endif
|
||||
|
||||
|
||||
namespace google {
|
||||
|
||||
extern GFLAGS_DLL_DECL void HandleCommandLineCompletions(void);
|
||||
|
||||
}
|
||||
|
||||
#endif // BASE_COMMANDLINEFLAGS_COMPLETIONS_H_
|
|
@ -0,0 +1,114 @@
|
|||
// Copyright (c) 1999, Google Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following disclaimer
|
||||
// in the documentation and/or other materials provided with the
|
||||
// distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from
|
||||
// this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
// ---
|
||||
//
|
||||
// Revamped and reorganized by Craig Silverstein
|
||||
//
|
||||
// This is the file that should be included by any file which declares
|
||||
// command line flag.
|
||||
|
||||
#ifndef BASE_COMMANDLINEFLAGS_DECLARE_H_
|
||||
#define BASE_COMMANDLINEFLAGS_DECLARE_H_
|
||||
|
||||
#include <string>
|
||||
#if 0
|
||||
#include <stdint.h> // the normal place uint16_t is defined
|
||||
#endif
|
||||
#if 1
|
||||
#include <sys/types.h> // the normal place u_int16_t is defined
|
||||
#endif
|
||||
#if 0
|
||||
#include <inttypes.h> // a third place for uint16_t or u_int16_t
|
||||
#endif
|
||||
|
||||
namespace google {
|
||||
#if 0 // the C99 format
|
||||
typedef int32_t int32;
|
||||
typedef uint32_t uint32;
|
||||
typedef int64_t int64;
|
||||
typedef uint64_t uint64;
|
||||
#elif 0 // the BSD format
|
||||
typedef int32_t int32;
|
||||
typedef u_int32_t uint32;
|
||||
typedef int64_t int64;
|
||||
typedef u_int64_t uint64;
|
||||
#elif 1 // the windows (vc7) format
|
||||
typedef __int32 int32;
|
||||
typedef unsigned __int32 uint32;
|
||||
typedef __int64 int64;
|
||||
typedef unsigned __int64 uint64;
|
||||
#else
|
||||
#error Do not know how to define a 32-bit integer quantity on your system
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
#if defined(_MSC_VER) && !defined(GFLAGS_DLL_DECLARE_FLAG)
|
||||
# define GFLAGS_DLL_DECLARE_FLAG __declspec(dllimport)
|
||||
#endif
|
||||
|
||||
namespace fLS {
|
||||
|
||||
// The meaning of "string" might be different between now and when the
|
||||
// macros below get invoked (e.g., if someone is experimenting with
|
||||
// other string implementations that get defined after this file is
|
||||
// included). Save the current meaning now and use it in the macros.
|
||||
typedef std::string clstring;
|
||||
|
||||
}
|
||||
|
||||
#define DECLARE_VARIABLE(type, shorttype, name) \
|
||||
/* We always want to import declared variables, dll or no */ \
|
||||
namespace fL##shorttype { extern GFLAGS_DLL_DECLARE_FLAG type FLAGS_##name; } \
|
||||
using fL##shorttype::FLAGS_##name
|
||||
|
||||
#define DECLARE_bool(name) \
|
||||
DECLARE_VARIABLE(bool, B, name)
|
||||
|
||||
#define DECLARE_int32(name) \
|
||||
DECLARE_VARIABLE(::google::int32, I, name)
|
||||
|
||||
#define DECLARE_int64(name) \
|
||||
DECLARE_VARIABLE(::google::int64, I64, name)
|
||||
|
||||
#define DECLARE_uint64(name) \
|
||||
DECLARE_VARIABLE(::google::uint64, U64, name)
|
||||
|
||||
#define DECLARE_double(name) \
|
||||
DECLARE_VARIABLE(double, D, name)
|
||||
|
||||
#define DECLARE_string(name) \
|
||||
namespace fLS { \
|
||||
using ::fLS::clstring; \
|
||||
extern GFLAGS_DLL_DECLARE_FLAG ::fLS::clstring& FLAGS_##name; \
|
||||
} \
|
||||
using fLS::FLAGS_##name
|
||||
|
||||
#endif // BASE_COMMANDLINEFLAGS_DECLARE_H_
|
|
@ -0,0 +1,62 @@
|
|||
/* Copyright (c) 2009, Google Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are
|
||||
* met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above
|
||||
* copyright notice, this list of conditions and the following disclaimer
|
||||
* in the documentation and/or other materials provided with the
|
||||
* distribution.
|
||||
* * Neither the name of Google Inc. nor the names of its
|
||||
* contributors may be used to endorse or promote products derived from
|
||||
* this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* ---
|
||||
* Author: Craig Silverstein
|
||||
*/
|
||||
|
||||
#ifndef _WIN32
|
||||
# error You should only be including windows/port.cc in a windows environment!
|
||||
#endif
|
||||
|
||||
#include <config.h>
|
||||
#include <string.h> // for strlen(), memset(), memcmp()
|
||||
#include <assert.h>
|
||||
#include <stdarg.h> // for va_list, va_start, va_end
|
||||
#include <windows.h>
|
||||
#include "port.h"
|
||||
|
||||
// These call the windows _vsnprintf, but always NUL-terminate.
|
||||
#if !defined(__MINGW32__) && !defined(__MINGW64__) /* mingw already defines */
|
||||
int safe_vsnprintf(char *str, size_t size, const char *format, va_list ap) {
|
||||
if (size == 0) // not even room for a \0?
|
||||
return -1; // not what C99 says to do, but what windows does
|
||||
str[size-1] = '\0';
|
||||
return _vsnprintf(str, size-1, format, ap);
|
||||
}
|
||||
|
||||
int snprintf(char *str, size_t size, const char *format, ...) {
|
||||
int r;
|
||||
va_list ap;
|
||||
va_start(ap, format);
|
||||
r = vsnprintf(str, size, format, ap);
|
||||
va_end(ap);
|
||||
return r;
|
||||
}
|
||||
#endif /* #if !defined(__MINGW32__) && !defined(__MINGW64__) */
|
|
@ -0,0 +1,116 @@
|
|||
/* Copyright (c) 2009, Google Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are
|
||||
* met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above
|
||||
* copyright notice, this list of conditions and the following disclaimer
|
||||
* in the documentation and/or other materials provided with the
|
||||
* distribution.
|
||||
* * Neither the name of Google Inc. nor the names of its
|
||||
* contributors may be used to endorse or promote products derived from
|
||||
* this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* ---
|
||||
* Author: Craig Silverstein
|
||||
*
|
||||
* These are some portability typedefs and defines to make it a bit
|
||||
* easier to compile this code under VC++.
|
||||
*
|
||||
* Several of these are taken from glib:
|
||||
* http://developer.gnome.org/doc/API/glib/glib-windows-compatability-functions.html
|
||||
*/
|
||||
|
||||
#ifndef GOOGLE_GFLAGS_WINDOWS_PORT_H_
|
||||
#define GOOGLE_GFLAGS_WINDOWS_PORT_H_
|
||||
|
||||
#ifdef _WIN32
|
||||
|
||||
#ifndef WIN32_LEAN_AND_MEAN
|
||||
#define WIN32_LEAN_AND_MEAN /* We always want minimal includes */
|
||||
#endif
|
||||
#include <windows.h>
|
||||
#include <direct.h> /* for mkdir */
|
||||
#include <stdlib.h> /* for _putenv, getenv */
|
||||
#include <stdio.h> /* need this to override stdio's snprintf, also defines _unlink used by unit tests */
|
||||
#include <stdarg.h> /* util.h uses va_copy */
|
||||
#include <string.h> /* for _stricmp and _strdup */
|
||||
|
||||
/* We can't just use _vsnprintf and _snprintf as drop-in-replacements,
|
||||
* because they don't always NUL-terminate. :-( We also can't use the
|
||||
* name vsnprintf, since windows defines that (but not snprintf (!)).
|
||||
*/
|
||||
#if !defined(__MINGW32__) && !defined(__MINGW64__) /* mingw already defines */
|
||||
extern GFLAGS_DLL_DECL int snprintf(char *str, size_t size,
|
||||
const char *format, ...);
|
||||
extern int GFLAGS_DLL_DECL safe_vsnprintf(char *str, size_t size,
|
||||
const char *format, va_list ap);
|
||||
#define vsnprintf(str, size, format, ap) safe_vsnprintf(str, size, format, ap)
|
||||
#define va_copy(dst, src) (dst) = (src)
|
||||
#endif /* #if !defined(__MINGW32__) && !defined(__MINGW64__) */
|
||||
|
||||
inline void setenv(const char* name, const char* value, int) {
|
||||
// In windows, it's impossible to set a variable to the empty string.
|
||||
// We handle this by setting it to "0" and the NUL-ing out the \0.
|
||||
// That is, we putenv("FOO=0") and then find out where in memory the
|
||||
// putenv wrote "FOO=0", and change it in-place to "FOO=\0".
|
||||
// c.f. http://svn.apache.org/viewvc/stdcxx/trunk/tests/src/environ.cpp?r1=611451&r2=637508&pathrev=637508
|
||||
static const char* const kFakeZero = "0";
|
||||
if (*value == '\0')
|
||||
value = kFakeZero;
|
||||
// Apparently the semantics of putenv() is that the input
|
||||
// must live forever, so we leak memory here. :-(
|
||||
const int nameval_len = strlen(name) + 1 + strlen(value) + 1;
|
||||
char* nameval = reinterpret_cast<char*>(malloc(nameval_len));
|
||||
snprintf(nameval, nameval_len, "%s=%s", name, value);
|
||||
_putenv(nameval);
|
||||
if (value == kFakeZero) {
|
||||
nameval[nameval_len - 2] = '\0'; // works when putenv() makes no copy
|
||||
if (*getenv(name) != '\0')
|
||||
*getenv(name) = '\0'; // works when putenv() copies nameval
|
||||
}
|
||||
}
|
||||
|
||||
#define strcasecmp _stricmp
|
||||
|
||||
#if defined(_MSC_VER) && _MSC_VER >= 1400
|
||||
#define strdup _strdup
|
||||
#define unlink _unlink
|
||||
#endif
|
||||
|
||||
#define PRId32 "d"
|
||||
#define PRIu32 "u"
|
||||
#define PRId64 "I64d"
|
||||
#define PRIu64 "I64u"
|
||||
|
||||
#ifndef __MINGW32__
|
||||
#define strtoq _strtoi64
|
||||
#define strtouq _strtoui64
|
||||
#define strtoll _strtoi64
|
||||
#define strtoull _strtoui64
|
||||
#define atoll _atoi64
|
||||
#endif
|
||||
|
||||
#ifndef PATH_MAX
|
||||
#define PATH_MAX 1024
|
||||
#endif
|
||||
|
||||
#endif /* _WIN32 */
|
||||
|
||||
#endif /* GOOGLE_GFLAGS_WINDOWS_PORT_H_ */
|
Loading…
Reference in New Issue