diff options
author | Andreas Schuh <andreas.schuh.84@gmail.com> | 2014-03-19 16:08:35 +0000 |
---|---|---|
committer | Andreas Schuh <andreas.schuh.84@gmail.com> | 2014-03-19 16:08:35 +0000 |
commit | dbc09f12db59bc0da056d1b2b6821fe56c6d76f2 (patch) | |
tree | 0abeb48ec6b3f95f3859c099d9a5e3a6ea243d60 /src | |
parent | 4328de857d7ed2f12a9c8162788e160dffaf097e (diff) | |
parent | 13025b119f788a776087cda7dc0b5213e24e7545 (diff) | |
download | gflags-dbc09f12db59bc0da056d1b2b6821fe56c6d76f2.tar.gz gflags-dbc09f12db59bc0da056d1b2b6821fe56c6d76f2.tar.bz2 gflags-dbc09f12db59bc0da056d1b2b6821fe56c6d76f2.zip |
Merge remote-tracking branch 'github/cmake-migration'
Diffstat (limited to 'src')
25 files changed, 403 insertions, 3445 deletions
diff --git a/src/config.h.in b/src/config.h.in index 5338b73..24b513e 100644 --- a/src/config.h.in +++ b/src/config.h.in @@ -1,106 +1,110 @@ -/* src/config.h.in. Generated from configure.ac by autoheader. */ +/* Generated from config.h.in during build configuration using CMake. */ -/* 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 +// Note: This header file is only used internally. It is not part of public interface! -/* Namespace for Google classes */ -#undef GOOGLE_NAMESPACE +// --------------------------------------------------------------------------- +// System checks -/* Define to 1 if you have the <dlfcn.h> header file. */ -#undef HAVE_DLFCN_H +// Define if you have the <stdint.h> header file. +#cmakedefine HAVE_STDINT_H -/* Define to 1 if you have the <fnmatch.h> header file. */ -#undef HAVE_FNMATCH_H +// Define if you have the <sys/types.h> header file. +#cmakedefine HAVE_SYS_TYPES_H -/* Define to 1 if you have the <inttypes.h> header file. */ -#undef HAVE_INTTYPES_H +// Define if you have the <inttypes.h> header file. +#cmakedefine HAVE_INTTYPES_H -/* Define to 1 if you have the <memory.h> header file. */ -#undef HAVE_MEMORY_H +// Define if you have the <sys/stat.h> header file. +#cmakedefine HAVE_SYS_STAT_H -/* define if the compiler implements namespaces */ -#undef HAVE_NAMESPACES +// Define if you have the <unistd.h> header file. +#cmakedefine HAVE_UNISTD_H -/* Define if you have POSIX threads libraries and header files. */ -#undef HAVE_PTHREAD +// Define if you have the <fnmatch.h> header file. +#cmakedefine HAVE_FNMATCH_H -/* Define to 1 if you have the <stdint.h> header file. */ -#undef HAVE_STDINT_H +// Define if you have the <shlwapi.h> header file (Windows 2000/XP). +#cmakedefine HAVE_SHLWAPI_H -/* Define to 1 if you have the <stdlib.h> header file. */ -#undef HAVE_STDLIB_H +// Define if you have the strtoll function. +#cmakedefine HAVE_STRTOLL -/* Define to 1 if you have the <strings.h> header file. */ -#undef HAVE_STRINGS_H +// Define if you have the strtoq function. +#cmakedefine HAVE_STRTOQ -/* Define to 1 if you have the <string.h> header file. */ -#undef HAVE_STRING_H +// Define if you have the <pthread.h> header file. +#cmakedefine HAVE_PTHREAD -/* Define to 1 if you have the `strtoll' function. */ -#undef HAVE_STRTOLL +// Define if your pthread library defines the type pthread_rwlock_t +#cmakedefine HAVE_RWLOCK -/* 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 +// gcc requires this to get PRId64, etc. +#if defined(HAVE_INTTYPES_H) && !defined(__STDC_FORMAT_MACROS) +# define __STDC_FORMAT_MACROS 1 +#endif -/* Define to the full name and version of this package. */ -#undef PACKAGE_STRING +// --------------------------------------------------------------------------- +// Package information -/* Define to the one symbol short name of this package. */ -#undef PACKAGE_TARNAME +// Name of package. +#define PACKAGE @PROJECT_NAME@ -/* Define to the version of this package. */ -#undef PACKAGE_VERSION +// Define to the full name of this package. +#define PACKAGE_NAME @PACKAGE_NAME@ -/* Define to necessary symbol if this constant uses a non-standard name on - your system. */ -#undef PTHREAD_CREATE_JOINABLE +// Define to the full name and version of this package. +#define PACKAGE_STRING @PACKAGE_STRING@ -/* Define to 1 if you have the ANSI C header files. */ -#undef STDC_HEADERS +// Define to the one symbol short name of this package. +#define PACKAGE_TARNAME @PACKAGE_TARNAME@ -/* the namespace where STL code like vector<> is defined */ -#undef STL_NAMESPACE +// Define to the version of this package. +#define PACKAGE_VERSION @PACKAGE_VERSION@ -/* Version number of package */ -#undef VERSION +// Version number of package. +#define VERSION PACKAGE_VERSION -/* Stops putting the code inside the Google namespace */ -#undef _END_GOOGLE_NAMESPACE_ +// Define to the address where bug reports for this package should be sent. +#define PACKAGE_BUGREPORT @PACKAGE_BUGREPORT@ -/* Puts following code inside the Google namespace */ -#undef _START_GOOGLE_NAMESPACE_ +// Namespace of gflags library symbols. +#define GFLAGS_NAMESPACE @GFLAGS_NAMESPACE@ +// --------------------------------------------------------------------------- +// Path separator +#ifndef PATH_SEPARATOR +# if _WIN32 +# define PATH_SEPARATOR '\\' +# else +# define PATH_SEPARATOR '/' +# endif +#endif -#if defined( __MINGW32__) || defined(__MINGW64__) -#include "windows/port.h" +// --------------------------------------------------------------------------- +// Windows + +// Whether gflags library is shared. +#define GFLAGS_IS_A_DLL @GFLAGS_IS_A_DLL@ + +// Always export symbols when compiling a shared library as this file is only +// included by internal modules when building the gflags library itself. +// The gflags_declare.h header file will set it to import these symbols otherwise. +#ifndef GFLAGS_DLL_DECL +# if GFLAGS_IS_A_DLL && defined(_MSC_VER) +# define GFLAGS_DLL_DECL __declspec(dllexport) +# else +# define GFLAGS_DLL_DECL +# endif +#endif +// Flags defined by the gflags library itself must be exported +#ifndef GFLAGS_DLL_DEFINE_FLAG +# define GFLAGS_DLL_DEFINE_FLAG GFLAGS_DLL_DECL #endif +#ifdef _WIN32 +// The unittests import the symbols of the shared gflags library +# if GFLAGS_IS_A_DLL && defined(_MSC_VER) +# define GFLAGS_DLL_DECL_FOR_UNITTESTS __declspec(dllimport) +# endif +# include "windows_port.h" +#endif diff --git a/src/config_for_unittests.h b/src/config_for_unittests.h deleted file mode 100644 index ac0df4c..0000000 --- a/src/config_for_unittests.h +++ /dev/null @@ -1,63 +0,0 @@ -// 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 diff --git a/src/gflags.cc b/src/gflags.cc index 01acd09..bd1b130 100644 --- a/src/gflags.cc +++ b/src/gflags.cc @@ -87,18 +87,17 @@ // other hand, hooks into CommandLineFlagParser. Other API functions // are, similarly, mostly hooks into the functionality described above. -// This comes first to ensure we define __STDC_FORMAT_MACROS in time. -#include <config.h> -#if defined(HAVE_INTTYPES_H) && !defined(__STDC_FORMAT_MACROS) -# define __STDC_FORMAT_MACROS 1 // gcc requires this to get PRId64, etc. -#endif +#include "config.h" +#include "gflags.h" -#include <gflags/gflags.h> #include <assert.h> #include <ctype.h> #include <errno.h> -#ifdef HAVE_FNMATCH_H -# include <fnmatch.h> +#if defined(HAVE_FNMATCH_H) +# include <fnmatch.h> +#elif defined(_MSC_VER) && defined(HAVE_SHLWAPI_H) +# include <shlwapi.h> +# pragma comment(lib, "shlwapi.lib") #endif #include <stdarg.h> // For va_list and related operations #include <stdio.h> @@ -109,31 +108,23 @@ #include <string> #include <utility> // for pair<> #include <vector> + #include "mutex.h" #include "util.h" -#ifndef PATH_SEPARATOR -#define PATH_SEPARATOR '/' -#endif - - // Special flags, type 1: the 'recursive' flags. They set another flag's val. -DEFINE_string(flagfile, "", - "load flags from file"); -DEFINE_string(fromenv, "", - "set flags from the environment" - " [use 'export FLAGS_flag1=value']"); -DEFINE_string(tryfromenv, "", - "set flags from the environment if present"); +DEFINE_string(flagfile, "", "load flags from file"); +DEFINE_string(fromenv, "", "set flags from the environment" + " [use 'export FLAGS_flag1=value']"); +DEFINE_string(tryfromenv, "", "set flags from the environment if present"); // Special flags, type 2: the 'parsing' flags. They modify how we parse. -DEFINE_string(undefok, "", - "comma-separated list of flag names that it is okay to specify " - "on the command line even if the program does not define a flag " - "with that name. IMPORTANT: flags in this list that have " - "arguments MUST use the flag=value format"); +DEFINE_string(undefok, "", "comma-separated list of flag names that it is okay to specify " + "on the command line even if the program does not define a flag " + "with that name. IMPORTANT: flags in this list that have " + "arguments MUST use the flag=value format"); -_START_GOOGLE_NAMESPACE_ +namespace GFLAGS_NAMESPACE { using std::map; using std::pair; @@ -206,7 +197,7 @@ class FlagValue { private: friend class CommandLineFlag; // for many things, including Validate() - friend class GOOGLE_NAMESPACE::FlagSaverImpl; // calls New() + friend class GFLAGS_NAMESPACE::FlagSaverImpl; // calls New() friend class FlagRegistry; // checks value_buffer_ for flags_by_ptr_ map template <typename T> friend T GetFromEnv(const char*, const char*, T); friend bool TryParseLocked(const CommandLineFlag*, FlagValue*, @@ -406,8 +397,7 @@ const char* FlagValue::TypeName() const { assert(false); return ""; } - // Directly indexing the strigns in the 'types' string, each of them - // is 7 bytes long. + // Directly indexing the strings in the 'types' string, each of them is 7 bytes long. return &types[type_ * 7]; } @@ -504,7 +494,7 @@ class CommandLineFlag { private: // for SetFlagLocked() and setting flags_by_ptr_ friend class FlagRegistry; - friend class GOOGLE_NAMESPACE::FlagSaverImpl; // for cloning the values + friend class GFLAGS_NAMESPACE::FlagSaverImpl; // for cloning the values // set validate_fn friend bool AddFlagValidator(const void*, ValidateFnProto); @@ -671,9 +661,9 @@ class FlagRegistry { static FlagRegistry* GlobalRegistry(); // returns a singleton registry private: - friend class GOOGLE_NAMESPACE::FlagSaverImpl; // reads all the flags in order to copy them + friend class GFLAGS_NAMESPACE::FlagSaverImpl; // reads all the flags in order to copy them friend class CommandLineFlagParser; // for ValidateAllFlags - friend void GOOGLE_NAMESPACE::GetAllFlags(vector<CommandLineFlagInfo>*); + friend void GFLAGS_NAMESPACE::GetAllFlags(vector<CommandLineFlagInfo>*); // The map from name to flag, for FindFlagLocked(). typedef map<const char*, CommandLineFlag*, StringCmp> FlagMap; @@ -1003,8 +993,8 @@ static string ReadFileIntoString(const char* filename) { const int kBufSize = 8092; char buffer[kBufSize]; string s; - FILE* fp = fopen(filename, "r"); - if (!fp) PFATAL(filename); + FILE* fp; + if ((errno = SafeFOpen(&fp, filename, "r")) != 0) PFATAL(filename); size_t n; while ( (n=fread(buffer, 1, kBufSize, fp)) > 0 ) { if (ferror(fp)) PFATAL(filename); @@ -1148,8 +1138,8 @@ string CommandLineFlagParser::ProcessFromenvLocked(const string& flagval, } const string envname = string("FLAGS_") + string(flagname); - const char* envval = getenv(envname.c_str()); - if (!envval) { + string envval; + if (!SafeGetEnv(envname.c_str(), envval)) { if (errors_are_fatal) { error_flags_[flagname] = (string(kError) + envname + " not found in environment\n"); @@ -1158,15 +1148,14 @@ string CommandLineFlagParser::ProcessFromenvLocked(const string& flagval, } // Avoid infinite recursion. - if ((strcmp(envval, "fromenv") == 0) || - (strcmp(envval, "tryfromenv") == 0)) { + if (envval == "fromenv" || envval == "tryfromenv") { error_flags_[flagname] = StringPrintf("%sinfinite recursion on environment flag '%s'\n", - kError, envval); + kError, envval.c_str()); continue; } - msg += ProcessSingleOptionLocked(flag, envval, set_mode); + msg += ProcessSingleOptionLocked(flag, envval.c_str(), set_mode); } return msg; } @@ -1318,13 +1307,12 @@ string CommandLineFlagParser::ProcessOptionsFromStringLocked( // We try matching both against the full argv0 and basename(argv0) if (glob == ProgramInvocationName() // small optimization || glob == ProgramInvocationShortName() -#ifdef HAVE_FNMATCH_H - || fnmatch(glob.c_str(), - ProgramInvocationName(), - FNM_PATHNAME) == 0 - || fnmatch(glob.c_str(), - ProgramInvocationShortName(), - FNM_PATHNAME) == 0 +#if defined(HAVE_FNMATCH_H) + || fnmatch(glob.c_str(), ProgramInvocationName(), FNM_PATHNAME) == 0 + || fnmatch(glob.c_str(), ProgramInvocationShortName(), FNM_PATHNAME) == 0 +#elif defined(_MSC_VER) && defined(HAVE_SHLWAPI_H) + || PathMatchSpec(glob.c_str(), ProgramInvocationName()) + || PathMatchSpec(glob.c_str(), ProgramInvocationShortName()) #endif ) { flags_are_relevant = true; @@ -1346,14 +1334,15 @@ string CommandLineFlagParser::ProcessOptionsFromStringLocked( template<typename T> T GetFromEnv(const char *varname, const char* type, T dflt) { - const char* const valstr = getenv(varname); - if (!valstr) - return dflt; - FlagValue ifv(new T, type, true); - if (!ifv.ParseFrom(valstr)) - ReportError(DIE, "ERROR: error parsing env variable '%s' with value '%s'\n", - varname, valstr); - return OTHER_VALUE_AS(ifv, T); + std::string valstr; + if (SafeGetEnv(varname, valstr)) { + FlagValue ifv(new T, type, true); + if (!ifv.ParseFrom(valstr.c_str())) { + ReportError(DIE, "ERROR: error parsing env variable '%s' with value '%s'\n", + varname, valstr.c_str()); + } + return OTHER_VALUE_AS(ifv, T); + } else return dflt; } bool AddFlagValidator(const void* flag_ptr, ValidateFnProto validate_fn_proto) { @@ -1505,7 +1494,7 @@ const char* ProgramInvocationName() { // like the GNU libc fn } const char* ProgramInvocationShortName() { // like the GNU libc fn const char* slash = strrchr(argv0, '/'); -#ifdef OS_WINDOWS +#ifdef _WINDOWS if (!slash) slash = strrchr(argv0, '\\'); #endif return slash ? slash + 1 : argv0; @@ -1765,8 +1754,8 @@ bool ReadFlagsFromString(const string& flagfilecontents, // TODO(csilvers): nix prog_name in favor of ProgramInvocationShortName() bool AppendFlagsIntoFile(const string& filename, const char *prog_name) { - FILE *fp = fopen(filename.c_str(), "a"); - if (!fp) { + FILE *fp; + if (SafeFOpen(&fp, filename.c_str(), "a") != 0) { return false; } @@ -1824,10 +1813,18 @@ uint64 Uint64FromEnv(const char *v, uint64 dflt) { double DoubleFromEnv(const char *v, double dflt) { return GetFromEnv(v, "double", dflt); } + +#ifdef _MSC_VER +# pragma warning(push) +# pragma warning(disable: 4996) // ignore getenv security warning +#endif const char *StringFromEnv(const char *varname, const char *dflt) { const char* const val = getenv(varname); return val ? val : dflt; } +#ifdef _MSC_VER +# pragma warning(pop) +#endif // -------------------------------------------------------------------- @@ -1957,4 +1954,5 @@ void ShutDownCommandLineFlags() { FlagRegistry::DeleteGlobalRegistry(); } -_END_GOOGLE_NAMESPACE_ + +} // namespace GFLAGS_NAMESPACE diff --git a/src/windows/gflags/gflags.h b/src/gflags.h.in index 8b70a37..852de48 100644 --- a/src/windows/gflags/gflags.h +++ b/src/gflags.h.in @@ -75,27 +75,28 @@ // other thread is writing to the variable or calling non-const // methods of this class. -#ifndef BASE_COMMANDLINEFLAGS_H_ -#define BASE_COMMANDLINEFLAGS_H_ +#ifndef GFLAGS_GFLAGS_H_ +#define GFLAGS_GFLAGS_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) +#include "gflags_declare.h" // IWYU pragma: export + + +// We always want to export variables defined in user code +#ifndef GFLAGS_DLL_DEFINE_FLAG +# ifdef _MSC_VER +# define GFLAGS_DLL_DEFINE_FLAG __declspec(dllexport) +# else +# define GFLAGS_DLL_DEFINE_FLAG +# endif #endif +namespace @GFLAGS_NAMESPACE@ { + + // -------------------------------------------------------------------- // To actually define a flag in a file, use DEFINE_bool, // DEFINE_string, etc. at the bottom of this file. You may also find @@ -125,19 +126,17 @@ namespace google { // 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&)); +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&)); + +// Convenience macro for the registration of a flag validator +#define DEFINE_validator(name, validator) \ + static const bool name##_validator_registered = \ + @GFLAGS_NAMESPACE@::RegisterFlagValidator(&FLAGS_##name, validator) // -------------------------------------------------------------------- @@ -150,19 +149,20 @@ extern GFLAGS_DLL_DECL bool RegisterFlagValidator(const std::string* flag, // 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 { +// +// No need to export this data only structure from DLL, avoiding VS warning 4251. +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 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) + 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. @@ -185,19 +185,19 @@ 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* 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() +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() +extern GFLAGS_DLL_DECL const char* VersionString(); // string set by SetVersionString() @@ -215,8 +215,7 @@ extern GFLAGS_DLL_DECL bool GetCommandLineOption(const char* name, std::string* // 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); +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: @@ -243,9 +242,8 @@ enum GFLAGS_DLL_DECL FlagSettingMode { // 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); +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); // -------------------------------------------------------------------- @@ -266,8 +264,8 @@ extern GFLAGS_DLL_DECL std::string SetCommandLineOptionWithMode(const char* name // // 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 +// Note: This class is marked with GFLAGS_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. // @@ -286,8 +284,7 @@ class GFLAGS_DLL_DECL FlagSaver { FlagSaver(const FlagSaver&); // no copying! void operator=(const FlagSaver&); -} -; +}@GFLAGS_ATTRIBUTE_UNUSED@; // -------------------------------------------------------------------- // Some deprecated or hopefully-soon-to-be-deprecated functions. @@ -295,15 +292,15 @@ class GFLAGS_DLL_DECL FlagSaver { // 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 +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 +extern GFLAGS_DLL_DECL bool ReadFromFlagsFile(const std::string& filename, const char* prog_name, bool errors_are_fatal); // uses SET_FLAGS_VALUE // -------------------------------------------------------------------- @@ -360,8 +357,8 @@ extern GFLAGS_DLL_DECL uint32 ParseCommandLineFlags(int *argc, char*** argv, boo // 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); +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. :-( @@ -421,7 +418,7 @@ extern GFLAGS_DLL_DECL void ShutDownCommandLineFlags(); // 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;" +// access to a flag, rather than saying "extern GFLAGS_DLL_DECL 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. @@ -444,14 +441,16 @@ class GFLAGS_DLL_DECL FlagRegisterer { extern GFLAGS_DLL_DECL const char kStrippedFlagHelp[]; -} + +} // namespace @GFLAGS_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) : ::google::kStrippedFlagHelp) + (false ? (txt) : @GFLAGS_NAMESPACE@::kStrippedFlagHelp) #else #define MAYBE_STRIPPED_HELP(txt) txt #endif @@ -473,7 +472,7 @@ extern GFLAGS_DLL_DECL const char kStrippedFlagHelp[]; /* 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( \ + static @GFLAGS_NAMESPACE@::FlagRegisterer o_##name( \ #name, #type, MAYBE_STRIPPED_HELP(help), __FILE__, \ &FLAGS_##name, &FLAGS_no##name); \ } \ @@ -506,15 +505,15 @@ GFLAGS_DLL_DECL bool IsBoolFlag(bool from); DEFINE_VARIABLE(bool, B, name, val, txt) #define DEFINE_int32(name, val, txt) \ - DEFINE_VARIABLE(::google::int32, I, \ + DEFINE_VARIABLE(@GFLAGS_NAMESPACE@::int32, I, \ name, val, txt) #define DEFINE_int64(name, val, txt) \ - DEFINE_VARIABLE(::google::int64, I64, \ + DEFINE_VARIABLE(@GFLAGS_NAMESPACE@::int64, I64, \ name, val, txt) #define DEFINE_uint64(name,val, txt) \ - DEFINE_VARIABLE(::google::uint64, U64, \ + DEFINE_VARIABLE(@GFLAGS_NAMESPACE@::uint64, U64, \ name, val, txt) #define DEFINE_double(name, val, txt) \ @@ -555,7 +554,7 @@ inline clstring* dont_pass0toDEFINE_string(char *stringspot, clstring* const FLAGS_no##name = ::fLS:: \ dont_pass0toDEFINE_string(s_##name[0].s, \ val); \ - static ::google::FlagRegisterer o_##name( \ + static @GFLAGS_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; \ @@ -566,4 +565,4 @@ inline clstring* dont_pass0toDEFINE_string(char *stringspot, #endif // SWIG -#endif // BASE_COMMANDLINEFLAGS_H_ +#endif // GFLAGS_GFLAGS_H_ diff --git a/src/gflags/gflags.h.in b/src/gflags/gflags.h.in deleted file mode 100644 index eb084f5..0000000 --- a/src/gflags/gflags.h.in +++ /dev/null @@ -1,570 +0,0 @@ -// 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_ diff --git a/src/gflags_completions.cc b/src/gflags_completions.cc index 17439dd..3a47623 100644 --- a/src/gflags_completions.cc +++ b/src/gflags_completions.cc @@ -47,7 +47,8 @@ // 5b) Trim most flag's descriptions to fit on a single terminal line -#include <config.h> +#include "config.h" + #include <stdio.h> #include <stdlib.h> #include <string.h> // for strlen @@ -57,16 +58,13 @@ #include <utility> #include <vector> -#include <gflags/gflags.h> +#include "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 " @@ -75,7 +73,9 @@ DEFINE_string(tab_completion_word, "", DEFINE_int32(tab_completion_columns, 80, "Number of columns to use in output for tab completion"); -_START_GOOGLE_NAMESPACE_ + +namespace GFLAGS_NAMESPACE { + namespace { // Function prototypes and Type forward declarations. Code may be @@ -765,4 +765,5 @@ void HandleCommandLineCompletions(void) { gflags_exitfunc(0); } -_END_GOOGLE_NAMESPACE_ + +} // namespace GFLAGS_NAMESPACE diff --git a/src/gflags/gflags_completions.h.in b/src/gflags_completions.h.in index 4e8c6dc..b27e5fd 100644 --- a/src/gflags/gflags_completions.h.in +++ b/src/gflags_completions.h.in @@ -112,19 +112,10 @@ $ complete -o bashdefault -o default -o nospace -C \ #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@ +namespace @GFLAGS_NAMESPACE@ { extern void HandleCommandLineCompletions(void); -@ac_google_end_namespace@ +} #endif // GFLAGS_COMPLETIONS_H_ diff --git a/src/gflags/gflags_declare.h.in b/src/gflags_declare.h.in index 7a09381..b0548fa 100644 --- a/src/gflags/gflags_declare.h.in +++ b/src/gflags_declare.h.in @@ -37,40 +37,61 @@ #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 +// --------------------------------------------------------------------------- +// Windows DLL import/export. + +// We always want to import the symbols of the gflags library +#ifndef GFLAGS_DLL_DECL +# if @GFLAGS_IS_A_DLL@ && defined(_MSC_VER) +# define GFLAGS_DLL_DECL __declspec(dllimport) +# else +# define GFLAGS_DLL_DECL +# endif #endif -#if @ac_cv_have_systypes_h@ -#include <sys/types.h> // the normal place u_int16_t is defined + +// We always want to import variables declared in user code +#ifndef GFLAGS_DLL_DECLARE_FLAG +# ifdef _MSC_VER +# define GFLAGS_DLL_DECLARE_FLAG __declspec(dllimport) +# else +# define GFLAGS_DLL_DECLARE_FLAG +# endif #endif -#if @ac_cv_have_inttypes_h@ -#include <inttypes.h> // a third place for uint16_t or u_int16_t + +// --------------------------------------------------------------------------- +// Flag types +#include <string> +#if @HAVE_STDINT_H@ +# include <stdint.h> // the normal place uint32_t is defined +#elif @HAVE_SYS_TYPES_H@ +# include <sys/types.h> // the normal place u_int32_t is defined +#elif @HAVE_INTTYPES_H@ +# include <inttypes.h> // a third place for uint32_t or u_int32_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; +namespace @GFLAGS_NAMESPACE@ { + +#if @GFLAGS_INTTYPES_FORMAT_C99@ // C99 +typedef int32_t int32; +typedef uint32_t uint32; +typedef int64_t int64; +typedef uint64_t uint64; +#elif @GFLAGS_INTTYPES_FORMAT_BSD@ // BSD +typedef int32_t int32; +typedef u_int32_t uint32; +typedef int64_t int64; +typedef u_int64_t uint64; +#elif @GFLAGS_INTTYPES_FORMAT_VC7@ // Windows +typedef __int32 int32; typedef unsigned __int32 uint32; -typedef __int64 int64; +typedef __int64 int64; typedef unsigned __int64 uint64; #else -#error Do not know how to define a 32-bit integer quantity on your system +# error Do not know how to define a 32-bit integer quantity on your system #endif -@ac_google_end_namespace@ +} // namespace @GFLAGS_NAMESPACE@ -#define GFLAGS_DLL_DECLARE_FLAG /* rewritten to be non-empty in windows dir */ namespace fLS { @@ -80,7 +101,8 @@ namespace fLS { // included). Save the current meaning now and use it in the macros. typedef std::string clstring; -} +} // namespace fLS + #define DECLARE_VARIABLE(type, shorttype, name) \ /* We always want to import declared variables, dll or no */ \ @@ -91,22 +113,24 @@ typedef std::string clstring; DECLARE_VARIABLE(bool, B, name) #define DECLARE_int32(name) \ - DECLARE_VARIABLE(@ac_google_namespace@::int32, I, name) + DECLARE_VARIABLE(GFLAGS_NAMESPACE::int32, I, name) #define DECLARE_int64(name) \ - DECLARE_VARIABLE(@ac_google_namespace@::int64, I64, name) + DECLARE_VARIABLE(GFLAGS_NAMESPACE::int64, I64, name) #define DECLARE_uint64(name) \ - DECLARE_VARIABLE(@ac_google_namespace@::uint64, U64, name) + DECLARE_VARIABLE(GFLAGS_NAMESPACE::uint64, U64, name) #define DECLARE_double(name) \ DECLARE_VARIABLE(double, D, name) #define DECLARE_string(name) \ - namespace fLS { \ - using ::fLS::clstring; \ + /* We always want to import declared variables, dll or no */ \ + namespace fLS { \ + using ::fLS::clstring; \ extern GFLAGS_DLL_DECLARE_FLAG ::fLS::clstring& FLAGS_##name; \ - } \ + } \ using fLS::FLAGS_##name + #endif // GFLAGS_DECLARE_H_ diff --git a/src/gflags_nc.cc b/src/gflags_nc.cc deleted file mode 100644 index c283612..0000000 --- a/src/gflags_nc.cc +++ /dev/null @@ -1,68 +0,0 @@ -// 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 diff --git a/src/gflags_reporting.cc b/src/gflags_reporting.cc index 8afcb95..9cc41a7 100644 --- a/src/gflags_reporting.cc +++ b/src/gflags_reporting.cc @@ -48,40 +48,32 @@ // 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 "config.h" +#include "gflags.h" +#include "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_ +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"); + + +namespace GFLAGS_NAMESPACE { + using std::string; using std::vector; @@ -254,7 +246,7 @@ static bool FileMatchesSubstring(const string& filename, // 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] == '/' && + if (!target->empty() && (*target)[0] == PATH_SEPARATOR && strncmp(filename.c_str(), target->c_str() + 1, strlen(target->c_str() + 1)) == 0) return true; @@ -360,7 +352,8 @@ static void ShowVersion() { static void AppendPrognameStrings(vector<string>* substrings, const char* progname) { - string r("/"); + string r(""); + r += PATH_SEPARATOR; r += progname; substrings->push_back(r + "."); substrings->push_back(r + "-main."); @@ -395,7 +388,7 @@ void HandleCommandLineHelpFlags() { gflags_exitfunc(1); } else if (!FLAGS_helpon.empty()) { - string restrict = "/" + FLAGS_helpon + "."; + string restrict = PATH_SEPARATOR + FLAGS_helpon + "."; ShowUsageWithFlagsRestrict(progname, restrict.c_str()); gflags_exitfunc(1); @@ -417,7 +410,7 @@ void HandleCommandLineHelpFlags() { ++flag) { if (!FileMatchesSubstring(flag->filename, substrings)) continue; - const string package = Dirname(flag->filename) + "/"; + const string package = Dirname(flag->filename) + PATH_SEPARATOR; if (package != last_package) { ShowUsageWithFlagsRestrict(progname, package.c_str()); VLOG(7) << "Found package: " << package; @@ -444,4 +437,5 @@ void HandleCommandLineHelpFlags() { } } -_END_GOOGLE_NAMESPACE_ + +} // namespace GFLAGS_NAMESPACE diff --git a/src/gflags_strip_flags_test.cc b/src/gflags_strip_flags_test.cc deleted file mode 100644 index 001ccd3..0000000 --- a/src/gflags_strip_flags_test.cc +++ /dev/null @@ -1,61 +0,0 @@ -// 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; -} diff --git a/src/gflags_strip_flags_test.sh b/src/gflags_strip_flags_test.sh deleted file mode 100755 index 9ebb457..0000000 --- a/src/gflags_strip_flags_test.sh +++ /dev/null @@ -1,80 +0,0 @@ -#!/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" diff --git a/src/gflags_unittest.cc b/src/gflags_unittest.cc deleted file mode 100644 index cce60d9..0000000 --- a/src/gflags_unittest.cc +++ /dev/null @@ -1,1534 +0,0 @@ -// Copyright (c) 2005, 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. - -// --- -// -// For now, this unit test does not cover all features of -// gflags.cc - -#include "config_for_unittests.h" -#include <gflags/gflags.h> - -#include <math.h> // for isinf() and isnan() -#include <stdio.h> -#include <stdlib.h> -#include <string.h> -#ifdef HAVE_UNISTD_H -# include <unistd.h> -#endif // for unlink() -#include <vector> -#include <string> -#include "util.h" -TEST_INIT -EXPECT_DEATH_INIT - -// I don't actually use this header file, but #include it under the -// old location to make sure that the include-header-forwarding -// works. But don't bother on windows; the windows port is so new -// it never had the old location-names. -#ifndef _MSC_VER -#include <google/gflags_completions.h> -void (*unused_fn)() = &GOOGLE_NAMESPACE::HandleCommandLineCompletions; -#endif - -using std::string; -using std::vector; -using GOOGLE_NAMESPACE::int32; -using GOOGLE_NAMESPACE::FlagRegisterer; -using GOOGLE_NAMESPACE::StringFromEnv; -using GOOGLE_NAMESPACE::RegisterFlagValidator; -using GOOGLE_NAMESPACE::CommandLineFlagInfo; -using GOOGLE_NAMESPACE::GetAllFlags; - -DEFINE_string(test_tmpdir, "/tmp/gflags_unittest", "Dir we use for temp files"); -#ifdef _MSC_VER // in MSVC, we run from the vsprojects directory -DEFINE_string(srcdir, "..\\..", - "Source-dir root, needed to find gflags_unittest_flagfile"); -#else -DEFINE_string(srcdir, StringFromEnv("SRCDIR", "."), - "Source-dir root, needed to find gflags_unittest_flagfile"); -#endif - -DECLARE_string(tryfromenv); // in gflags.cc - -DEFINE_bool(test_bool, false, "tests bool-ness"); -DEFINE_int32(test_int32, -1, ""); -DEFINE_int64(test_int64, -2, ""); -DEFINE_uint64(test_uint64, 2, ""); -DEFINE_double(test_double, -1.0, ""); -DEFINE_string(test_string, "initial", ""); - -// -// The below ugliness gets some additional code coverage in the -helpxml -// and -helpmatch test cases having to do with string lengths and formatting -// -DEFINE_bool(test_bool_with_quite_quite_quite_quite_quite_quite_quite_quite_quite_quite_quite_quite_quite_quite_long_name, - false, - "extremely_extremely_extremely_extremely_extremely_extremely_extremely_extremely_long_meaning"); - -DEFINE_string(test_str1, "initial", ""); -DEFINE_string(test_str2, "initial", ""); -DEFINE_string(test_str3, "initial", ""); - -// This is used to test setting tryfromenv manually -DEFINE_string(test_tryfromenv, "initial", ""); - -// Don't try this at home! -static int changeable_var = 12; -DEFINE_int32(changeable_var, ++changeable_var, ""); - -static int changeable_bool_var = 8008; -DEFINE_bool(changeable_bool_var, ++changeable_bool_var == 8009, ""); - -static int changeable_string_var = 0; -static string ChangeableString() { - char r[] = {static_cast<char>('0' + ++changeable_string_var), '\0'}; - return r; -} -DEFINE_string(changeable_string_var, ChangeableString(), ""); - -// These are never used in this unittest, but can be used by -// gflags_unittest.sh when it needs to specify flags -// that are legal for gflags_unittest but don't need to -// be a particular value. -DEFINE_bool(unused_bool, true, "unused bool-ness"); -DEFINE_int32(unused_int32, -1001, ""); -DEFINE_int64(unused_int64, -2001, ""); -DEFINE_uint64(unused_uint64, 2000, ""); -DEFINE_double(unused_double, -1000.0, ""); -DEFINE_string(unused_string, "unused", ""); - -// These flags are used by gflags_unittest.sh -DEFINE_bool(changed_bool1, false, "changed"); -DEFINE_bool(changed_bool2, false, "changed"); -DEFINE_bool(long_helpstring, false, - "This helpstring goes on forever and ever and ever and ever and " - "ever and ever and ever and ever and ever and ever and ever and " - "ever and ever and ever and ever and ever and ever and ever and " - "ever and ever and ever and ever and ever and ever and ever and " - "ever and ever and ever and ever and ever and ever and ever and " - "ever and ever and ever and ever and ever and ever and ever and " - "ever and ever and ever and ever and ever and ever and ever and " - "ever and ever and ever and ever and ever and ever and ever and " - "ever and ever and ever and ever and ever and ever and ever and " - "ever and ever and ever and ever and ever and ever and ever and " - "ever. This is the end of a long helpstring"); - - -static bool AlwaysFail(const char* flag, bool value) { return value == false; } -DEFINE_bool(always_fail, false, "will fail to validate when you set it"); -DEFINE_validator(always_fail, AlwaysFail); - -// See the comment by GetAllFlags in gflags.h -static bool DeadlockIfCantLockInValidators(const char* flag, bool value) { - if (!value) { - return true; - } - vector<CommandLineFlagInfo> dummy; - GetAllFlags(&dummy); - return true; -} -DEFINE_bool(deadlock_if_cant_lock, - false, - "will deadlock if set to true and " - "if locking of registry in validators fails."); -DEFINE_validator(deadlock_if_cant_lock, DeadlockIfCantLockInValidators); - -#define MAKEFLAG(x) DEFINE_int32(test_flag_num##x, x, "Test flag") - -// Define 10 flags -#define MAKEFLAG10(x) \ - MAKEFLAG(x##0); \ - MAKEFLAG(x##1); \ - MAKEFLAG(x##2); \ - MAKEFLAG(x##3); \ - MAKEFLAG(x##4); \ - MAKEFLAG(x##5); \ - MAKEFLAG(x##6); \ - MAKEFLAG(x##7); \ - MAKEFLAG(x##8); \ - MAKEFLAG(x##9) - -// Define 100 flags -#define MAKEFLAG100(x) \ - MAKEFLAG10(x##0); \ - MAKEFLAG10(x##1); \ - MAKEFLAG10(x##2); \ - MAKEFLAG10(x##3); \ - MAKEFLAG10(x##4); \ - MAKEFLAG10(x##5); \ - MAKEFLAG10(x##6); \ - MAKEFLAG10(x##7); \ - MAKEFLAG10(x##8); \ - MAKEFLAG10(x##9) - -// Define a bunch of command-line flags. Each occurrence of the MAKEFLAG100 -// macro defines 100 integer flags. This lets us test the effect of having -// many flags on startup time. -MAKEFLAG100(1); -MAKEFLAG100(2); -MAKEFLAG100(3); -MAKEFLAG100(4); -MAKEFLAG100(5); -MAKEFLAG100(6); -MAKEFLAG100(7); -MAKEFLAG100(8); -MAKEFLAG100(9); -MAKEFLAG100(10); -MAKEFLAG100(11); -MAKEFLAG100(12); -MAKEFLAG100(13); -MAKEFLAG100(14); -MAKEFLAG100(15); - -#undef MAKEFLAG100 -#undef MAKEFLAG10 -#undef MAKEFLAG - -// This is a pseudo-flag -- we want to register a flag with a filename -// at the top level, but there is no way to do this except by faking -// the filename. -namespace fLI { - static const int32 FLAGS_nonotldflag1 = 12; - int32 FLAGS_tldflag1 = FLAGS_nonotldflag1; - int32 FLAGS_notldflag1 = FLAGS_nonotldflag1; - static FlagRegisterer o_tldflag1( - "tldflag1", "int32", - "should show up in --helpshort", "gflags_unittest.cc", - &FLAGS_tldflag1, &FLAGS_notldflag1); -} -using fLI::FLAGS_tldflag1; - -namespace fLI { - static const int32 FLAGS_nonotldflag2 = 23; - int32 FLAGS_tldflag2 = FLAGS_nonotldflag2; - int32 FLAGS_notldflag2 = FLAGS_nonotldflag2; - static FlagRegisterer o_tldflag2( - "tldflag2", "int32", - "should show up in --helpshort", "gflags_unittest.", - &FLAGS_tldflag2, &FLAGS_notldflag2); -} -using fLI::FLAGS_tldflag2; - -_START_GOOGLE_NAMESPACE_ - -namespace { - - -static string TmpFile(const string& basename) { -#ifdef _MSC_VER - return FLAGS_test_tmpdir + "\\" + basename; -#else - return FLAGS_test_tmpdir + "/" + basename; -#endif -} - -// Returns the definition of the --flagfile flag to be used in the tests. -// Must be called after ParseCommandLineFlags(). -static const char* GetFlagFileFlag() { -#ifdef _MSC_VER - static const string flagfile = FLAGS_srcdir + "\\src\\gflags_unittest_flagfile"; -#else - static const string flagfile = FLAGS_srcdir + "/src/gflags_unittest_flagfile"; -#endif - static const string flagfile_flag = string("--flagfile=") + flagfile; - return flagfile_flag.c_str(); -} - - -// Defining a variable of type CompileAssertTypesEqual<T1, T2> will cause a -// compiler error iff T1 and T2 are different types. -template <typename T1, typename T2> -struct CompileAssertTypesEqual; - -template <typename T> -struct CompileAssertTypesEqual<T, T> { -}; - - -template <typename Expected, typename Actual> -void AssertIsType(Actual& x) { - CompileAssertTypesEqual<Expected, Actual>(); -} - -// Verify all the flags are the right type. -TEST(FlagTypes, FlagTypes) { - AssertIsType<bool>(FLAGS_test_bool); - AssertIsType<int32>(FLAGS_test_int32); - AssertIsType<int64>(FLAGS_test_int64); - AssertIsType<uint64>(FLAGS_test_uint64); - AssertIsType<double>(FLAGS_test_double); - AssertIsType<string>(FLAGS_test_string); -} - -#ifdef GTEST_HAS_DEATH_TEST -// Death tests for "help" options. -// -// The help system automatically calls gflags_exitfunc(1) when you specify any of -// the help-related flags ("-helpmatch", "-helpxml") so we can't test -// those mainline. - -// Tests that "-helpmatch" causes the process to die. -TEST(ReadFlagsFromStringDeathTest, HelpMatch) { - EXPECT_DEATH(ReadFlagsFromString("-helpmatch=base", GetArgv0(), true), - ""); -} - - -// Tests that "-helpxml" causes the process to die. -TEST(ReadFlagsFromStringDeathTest, HelpXml) { - EXPECT_DEATH(ReadFlagsFromString("-helpxml", GetArgv0(), true), - ""); -} -#endif - - -// A subroutine needed for testing reading flags from a string. -void TestFlagString(const string& flags, - const string& expected_string, - bool expected_bool, - int32 expected_int32, - double expected_double) { - EXPECT_TRUE(ReadFlagsFromString(flags, - GetArgv0(), - // errors are fatal - true)); - - EXPECT_EQ(expected_string, FLAGS_test_string); - EXPECT_EQ(expected_bool, FLAGS_test_bool); - EXPECT_EQ(expected_int32, FLAGS_test_int32); - EXPECT_DOUBLE_EQ(expected_double, FLAGS_test_double); -} - - -// Tests reading flags from a string. -TEST(FlagFileTest, ReadFlagsFromString) { - TestFlagString( - // Flag string - "-test_string=continued\n" - "# some comments are in order\n" - "# some\n" - " # comments\n" - "#are\n" - " #trickier\n" - "# than others\n" - "-test_bool=true\n" - " -test_int32=1\n" - "-test_double=0.0\n", - // Expected values - "continued", - true, - 1, - 0.0); - - TestFlagString( - // Flag string - "# let's make sure it can update values\n" - "-test_string=initial\n" - "-test_bool=false\n" - "-test_int32=123\n" - "-test_double=123.0\n", - // Expected values - "initial", - false, - 123, - 123.0); -} - -// Tests the filename part of the flagfile -TEST(FlagFileTest, FilenamesOurfileLast) { - FLAGS_test_string = "initial"; - FLAGS_test_bool = false; - FLAGS_test_int32 = -1; - FLAGS_test_double = -1.0; - TestFlagString( - // Flag string - "-test_string=continued\n" - "# some comments are in order\n" - "# some\n" - " # comments\n" - "#are\n" - " #trickier\n" - "# than others\n" - "not_our_filename\n" - "-test_bool=true\n" - " -test_int32=1\n" - "gflags_unittest\n" - "-test_double=1000.0\n", - // Expected values - "continued", - false, - -1, - 1000.0); -} - -TEST(FlagFileTest, FilenamesOurfileFirst) { - FLAGS_test_string = "initial"; - FLAGS_test_bool = false; - FLAGS_test_int32 = -1; - FLAGS_test_double = -1.0; - TestFlagString( - // Flag string - "-test_string=continued\n" - "# some comments are in order\n" - "# some\n" - " # comments\n" - "#are\n" - " #trickier\n" - "# than others\n" - "gflags_unittest\n" - "-test_bool=true\n" - " -test_int32=1\n" - "not_our_filename\n" - "-test_double=1000.0\n", - // Expected values - "continued", - true, - 1, - -1.0); -} - -#ifdef HAVE_FNMATCH_H // otherwise glob isn't supported -TEST(FlagFileTest, FilenamesOurfileGlob) { - FLAGS_test_string = "initial"; - FLAGS_test_bool = false; - FLAGS_test_int32 = -1; - FLAGS_test_double = -1.0; - TestFlagString( - // Flag string - "-test_string=continued\n" - "# some comments are in order\n" - "# some\n" - " # comments\n" - "#are\n" - " #trickier\n" - "# than others\n" - "*flags*\n" - "-test_bool=true\n" - " -test_int32=1\n" - "flags\n" - "-test_double=1000.0\n", - // Expected values - "continued", - true, - 1, - -1.0); -} - -TEST(FlagFileTest, FilenamesOurfileInBigList) { - FLAGS_test_string = "initial"; - FLAGS_test_bool = false; - FLAGS_test_int32 = -1; - FLAGS_test_double = -1.0; - TestFlagString( - // Flag string - "-test_string=continued\n" - "# some comments are in order\n" - "# some\n" - " # comments\n" - "#are\n" - " #trickier\n" - "# than others\n" - "*first* *flags* *third*\n" - "-test_bool=true\n" - " -test_int32=1\n" - "flags\n" - "-test_double=1000.0\n", - // Expected values - "continued", - true, - 1, - -1.0); -} -#endif // ifdef HAVE_FNMATCH_H - -// Tests that a failed flag-from-string read keeps flags at default values -TEST(FlagFileTest, FailReadFlagsFromString) { - FLAGS_test_int32 = 119; - string flags("# let's make sure it can update values\n" - "-test_string=non_initial\n" - "-test_bool=false\n" - "-test_int32=123\n" - "-test_double=illegal\n"); - - EXPECT_FALSE(ReadFlagsFromString(flags, - GetArgv0(), - // errors are fatal - false)); - - EXPECT_EQ(119, FLAGS_test_int32); - EXPECT_EQ("initial", FLAGS_test_string); -} - -// Tests that flags can be set to ordinary values. -TEST(SetFlagValueTest, OrdinaryValues) { - EXPECT_EQ("initial", FLAGS_test_str1); - - SetCommandLineOptionWithMode("test_str1", "second", SET_FLAG_IF_DEFAULT); - EXPECT_EQ("second", FLAGS_test_str1); // set; was default - - SetCommandLineOptionWithMode("test_str1", "third", SET_FLAG_IF_DEFAULT); - EXPECT_EQ("second", FLAGS_test_str1); // already set once - - FLAGS_test_str1 = "initial"; - SetCommandLineOptionWithMode("test_str1", "third", SET_FLAG_IF_DEFAULT); - EXPECT_EQ("initial", FLAGS_test_str1); // still already set before - - SetCommandLineOptionWithMode("test_str1", "third", SET_FLAGS_VALUE); - EXPECT_EQ("third", FLAGS_test_str1); // changed value - - SetCommandLineOptionWithMode("test_str1", "fourth", SET_FLAGS_DEFAULT); - EXPECT_EQ("third", FLAGS_test_str1); - // value not changed (already set before) - - EXPECT_EQ("initial", FLAGS_test_str2); - - SetCommandLineOptionWithMode("test_str2", "second", SET_FLAGS_DEFAULT); - EXPECT_EQ("second", FLAGS_test_str2); // changed (was default) - - FLAGS_test_str2 = "extra"; - EXPECT_EQ("extra", FLAGS_test_str2); - - FLAGS_test_str2 = "second"; - SetCommandLineOptionWithMode("test_str2", "third", SET_FLAGS_DEFAULT); - EXPECT_EQ("third", FLAGS_test_str2); // still changed (was equal to default) - - SetCommandLineOptionWithMode("test_str2", "fourth", SET_FLAG_IF_DEFAULT); - EXPECT_EQ("fourth", FLAGS_test_str2); // changed (was default) - - EXPECT_EQ("initial", FLAGS_test_str3); - - SetCommandLineOptionWithMode("test_str3", "second", SET_FLAGS_DEFAULT); - EXPECT_EQ("second", FLAGS_test_str3); // changed - - FLAGS_test_str3 = "third"; - SetCommandLineOptionWithMode("test_str3", "fourth", SET_FLAGS_DEFAULT); - EXPECT_EQ("third", FLAGS_test_str3); // not changed (was set) - - SetCommandLineOptionWithMode("test_str3", "fourth", SET_FLAG_IF_DEFAULT); - EXPECT_EQ("third", FLAGS_test_str3); // not changed (was set) - - SetCommandLineOptionWithMode("test_str3", "fourth", SET_FLAGS_VALUE); - EXPECT_EQ("fourth", FLAGS_test_str3); // changed value -} - - -// Tests that flags can be set to exceptional values. -// Note: apparently MINGW doesn't parse inf and nan correctly: -// http://www.mail-archive.com/bug-gnulib@gnu.org/msg09573.html -// This url says FreeBSD also has a problem, but I didn't see that. -TEST(SetFlagValueTest, ExceptionalValues) { -#if defined(isinf) && !defined(__MINGW32__) - EXPECT_EQ("test_double set to inf\n", - SetCommandLineOption("test_double", "inf")); - EXPECT_INF(FLAGS_test_double); - - EXPECT_EQ("test_double set to inf\n", - SetCommandLineOption("test_double", "INF")); - EXPECT_INF(FLAGS_test_double); -#endif - - // set some bad values - EXPECT_EQ("", - SetCommandLineOption("test_double", "0.1xxx")); - EXPECT_EQ("", - SetCommandLineOption("test_double", " ")); - EXPECT_EQ("", - SetCommandLineOption("test_double", "")); -#if defined(isinf) && !defined(__MINGW32__) - EXPECT_EQ("test_double set to -inf\n", - SetCommandLineOption("test_double", "-inf")); - EXPECT_INF(FLAGS_test_double); - EXPECT_GT(0, FLAGS_test_double); -#endif - -#if defined(isnan) && !defined(__MINGW32__) - EXPECT_EQ("test_double set to nan\n", - SetCommandLineOption("test_double", "NaN")); - EXPECT_NAN(FLAGS_test_double); -#endif -} - -// Tests that integer flags can be specified in many ways -TEST(SetFlagValueTest, DifferentRadices) { - EXPECT_EQ("test_int32 set to 12\n", - SetCommandLineOption("test_int32", "12")); - - EXPECT_EQ("test_int32 set to 16\n", - SetCommandLineOption("test_int32", "0x10")); - - EXPECT_EQ("test_int32 set to 34\n", - SetCommandLineOption("test_int32", "0X22")); - - // Leading 0 is *not* octal; it's still decimal - EXPECT_EQ("test_int32 set to 10\n", - SetCommandLineOption("test_int32", "010")); -} - -// Tests what happens when you try to set a flag to an illegal value -TEST(SetFlagValueTest, IllegalValues) { - FLAGS_test_bool = true; - FLAGS_test_int32 = 119; - FLAGS_test_int64 = 1191; - FLAGS_test_uint64 = 11911; - - EXPECT_EQ("", - SetCommandLineOption("test_bool", "12")); - - EXPECT_EQ("", - SetCommandLineOption("test_int32", "7000000000000")); - - // TODO(csilvers): uncomment this when we disallow negative numbers for uint64 -#if 0 - EXPECT_EQ("", - SetCommandLineOption("test_uint64", "-1")); -#endif - - EXPECT_EQ("", - SetCommandLineOption("test_int64", "not a number!")); - - // Test the empty string with each type of input - EXPECT_EQ("", SetCommandLineOption("test_bool", "")); - EXPECT_EQ("", SetCommandLineOption("test_int32", "")); - EXPECT_EQ("", SetCommandLineOption("test_int64", "")); - EXPECT_EQ("", SetCommandLineOption("test_uint64", "")); - EXPECT_EQ("", SetCommandLineOption("test_double", "")); - EXPECT_EQ("test_string set to \n", SetCommandLineOption("test_string", "")); - - EXPECT_TRUE(FLAGS_test_bool); - EXPECT_EQ(119, FLAGS_test_int32); - EXPECT_EQ(1191, FLAGS_test_int64); - EXPECT_EQ(11911, FLAGS_test_uint64); -} - - -// Tests that we only evaluate macro args once -TEST(MacroArgs, EvaluateOnce) { - EXPECT_EQ(13, FLAGS_changeable_var); - // Make sure we don't ++ the value somehow, when evaluating the flag. - EXPECT_EQ(13, FLAGS_changeable_var); - // Make sure the macro only evaluated this var once. - EXPECT_EQ(13, changeable_var); - // Make sure the actual value and default value are the same - SetCommandLineOptionWithMode("changeable_var", "21", SET_FLAG_IF_DEFAULT); - EXPECT_EQ(21, FLAGS_changeable_var); -} - -TEST(MacroArgs, EvaluateOnceBool) { - EXPECT_TRUE(FLAGS_changeable_bool_var); - EXPECT_TRUE(FLAGS_changeable_bool_var); - EXPECT_EQ(8009, changeable_bool_var); - SetCommandLineOptionWithMode("changeable_bool_var", "false", - SET_FLAG_IF_DEFAULT); - EXPECT_FALSE(FLAGS_changeable_bool_var); -} - -TEST(MacroArgs, EvaluateOnceStrings) { - EXPECT_EQ("1", FLAGS_changeable_string_var); - EXPECT_EQ("1", FLAGS_changeable_string_var); - EXPECT_EQ(1, changeable_string_var); - SetCommandLineOptionWithMode("changeable_string_var", "different", - SET_FLAG_IF_DEFAULT); - EXPECT_EQ("different", FLAGS_changeable_string_var); -} - -// Tests that the FooFromEnv does the right thing -TEST(FromEnvTest, LegalValues) { - setenv("BOOL_VAL1", "true", 1); - setenv("BOOL_VAL2", "false", 1); - setenv("BOOL_VAL3", "1", 1); - setenv("BOOL_VAL4", "F", 1); - EXPECT_TRUE(BoolFromEnv("BOOL_VAL1", false)); - EXPECT_FALSE(BoolFromEnv("BOOL_VAL2", true)); - EXPECT_TRUE(BoolFromEnv("BOOL_VAL3", false)); - EXPECT_FALSE(BoolFromEnv("BOOL_VAL4", true)); - EXPECT_TRUE(BoolFromEnv("BOOL_VAL_UNKNOWN", true)); - EXPECT_FALSE(BoolFromEnv("BOOL_VAL_UNKNOWN", false)); - - setenv("INT_VAL1", "1", 1); - setenv("INT_VAL2", "-1", 1); - EXPECT_EQ(1, Int32FromEnv("INT_VAL1", 10)); - EXPECT_EQ(-1, Int32FromEnv("INT_VAL2", 10)); - EXPECT_EQ(10, Int32FromEnv("INT_VAL_UNKNOWN", 10)); - - setenv("INT_VAL3", "1099511627776", 1); - EXPECT_EQ(1, Int64FromEnv("INT_VAL1", 20)); - EXPECT_EQ(-1, Int64FromEnv("INT_VAL2", 20)); - EXPECT_EQ(1099511627776LL, Int64FromEnv("INT_VAL3", 20)); - EXPECT_EQ(20, Int64FromEnv("INT_VAL_UNKNOWN", 20)); - - EXPECT_EQ(1, Uint64FromEnv("INT_VAL1", 30)); - EXPECT_EQ(1099511627776ULL, Uint64FromEnv("INT_VAL3", 30)); - EXPECT_EQ(30, Uint64FromEnv("INT_VAL_UNKNOWN", 30)); - - // I pick values here that can be easily represented exactly in floating-point - setenv("DOUBLE_VAL1", "0.0", 1); - setenv("DOUBLE_VAL2", "1.0", 1); - setenv("DOUBLE_VAL3", "-1.0", 1); - EXPECT_EQ(0.0, DoubleFromEnv("DOUBLE_VAL1", 40.0)); - EXPECT_EQ(1.0, DoubleFromEnv("DOUBLE_VAL2", 40.0)); - EXPECT_EQ(-1.0, DoubleFromEnv("DOUBLE_VAL3", 40.0)); - EXPECT_EQ(40.0, DoubleFromEnv("DOUBLE_VAL_UNKNOWN", 40.0)); - - setenv("STRING_VAL1", "", 1); - setenv("STRING_VAL2", "my happy string!", 1); - EXPECT_STREQ("", StringFromEnv("STRING_VAL1", "unknown")); - EXPECT_STREQ("my happy string!", StringFromEnv("STRING_VAL2", "unknown")); - EXPECT_STREQ("unknown", StringFromEnv("STRING_VAL_UNKNOWN", "unknown")); -} - -#ifdef GTEST_HAS_DEATH_TEST -// Tests that the FooFromEnv dies on parse-error -TEST(FromEnvDeathTest, IllegalValues) { - setenv("BOOL_BAD1", "so true!", 1); - setenv("BOOL_BAD2", "", 1); - EXPECT_DEATH(BoolFromEnv("BOOL_BAD1", false), "error parsing env variable"); - EXPECT_DEATH(BoolFromEnv("BOOL_BAD2", true), "error parsing env variable"); - - setenv("INT_BAD1", "one", 1); - setenv("INT_BAD2", "100000000000000000", 1); - setenv("INT_BAD3", "0xx10", 1); - setenv("INT_BAD4", "", 1); - EXPECT_DEATH(Int32FromEnv("INT_BAD1", 10), "error parsing env variable"); - EXPECT_DEATH(Int32FromEnv("INT_BAD2", 10), "error parsing env variable"); - EXPECT_DEATH(Int32FromEnv("INT_BAD3", 10), "error parsing env variable"); - EXPECT_DEATH(Int32FromEnv("INT_BAD4", 10), "error parsing env variable"); - - setenv("BIGINT_BAD1", "18446744073709551616000", 1); - EXPECT_DEATH(Int64FromEnv("INT_BAD1", 20), "error parsing env variable"); - EXPECT_DEATH(Int64FromEnv("INT_BAD3", 20), "error parsing env variable"); - EXPECT_DEATH(Int64FromEnv("INT_BAD4", 20), "error parsing env variable"); - EXPECT_DEATH(Int64FromEnv("BIGINT_BAD1", 200), "error parsing env variable"); - - setenv("BIGINT_BAD2", "-1", 1); - EXPECT_DEATH(Uint64FromEnv("INT_BAD1", 30), "error parsing env variable"); - EXPECT_DEATH(Uint64FromEnv("INT_BAD3", 30), "error parsing env variable"); - EXPECT_DEATH(Uint64FromEnv("INT_BAD4", 30), "error parsing env variable"); - EXPECT_DEATH(Uint64FromEnv("BIGINT_BAD1", 30), "error parsing env variable"); - // TODO(csilvers): uncomment this when we disallow negative numbers for uint64 -#if 0 - EXPECT_DEATH(Uint64FromEnv("BIGINT_BAD2", 30), "error parsing env variable"); -#endif - - setenv("DOUBLE_BAD1", "0.0.0", 1); - setenv("DOUBLE_BAD2", "", 1); - EXPECT_DEATH(DoubleFromEnv("DOUBLE_BAD1", 40.0), "error parsing env variable"); - EXPECT_DEATH(DoubleFromEnv("DOUBLE_BAD2", 40.0), "error parsing env variable"); -} -#endif - - -// Tests that FlagSaver can save the states of string flags. -TEST(FlagSaverTest, CanSaveStringFlagStates) { - // 1. Initializes the flags. - - // State of flag test_str1: - // default value - "initial" - // current value - "initial" - // not set - true - - SetCommandLineOptionWithMode("test_str2", "second", SET_FLAGS_VALUE); - // State of flag test_str2: - // default value - "initial" - // current value - "second" - // not set - false - - SetCommandLineOptionWithMode("test_str3", "second", SET_FLAGS_DEFAULT); - // State of flag test_str3: - // default value - "second" - // current value - "second" - // not set - true - - // 2. Saves the flag states. - - { - FlagSaver fs; - - // 3. Modifies the flag states. - - SetCommandLineOptionWithMode("test_str1", "second", SET_FLAGS_VALUE); - EXPECT_EQ("second", FLAGS_test_str1); - // State of flag test_str1: - // default value - "second" - // current value - "second" - // not set - true - - SetCommandLineOptionWithMode("test_str2", "third", SET_FLAGS_DEFAULT); - EXPECT_EQ("second", FLAGS_test_str2); - // State of flag test_str2: - // default value - "third" - // current value - "second" - // not set - false - - SetCommandLineOptionWithMode("test_str3", "third", SET_FLAGS_VALUE); - EXPECT_EQ("third", FLAGS_test_str3); - // State of flag test_str1: - // default value - "second" - // current value - "third" - // not set - false - - // 4. Restores the flag states. - } - - // 5. Verifies that the states were restored. - - // Verifies that the value of test_str1 was restored. - EXPECT_EQ("initial", FLAGS_test_str1); - // Verifies that the "not set" attribute of test_str1 was restored to true. - SetCommandLineOptionWithMode("test_str1", "second", SET_FLAG_IF_DEFAULT); - EXPECT_EQ("second", FLAGS_test_str1); - - // Verifies that the value of test_str2 was restored. - EXPECT_EQ("second", FLAGS_test_str2); - // Verifies that the "not set" attribute of test_str2 was restored to false. - SetCommandLineOptionWithMode("test_str2", "fourth", SET_FLAG_IF_DEFAULT); - EXPECT_EQ("second", FLAGS_test_str2); - - // Verifies that the value of test_str3 was restored. - EXPECT_EQ("second", FLAGS_test_str3); - // Verifies that the "not set" attribute of test_str3 was restored to true. - SetCommandLineOptionWithMode("test_str3", "fourth", SET_FLAG_IF_DEFAULT); - EXPECT_EQ("fourth", FLAGS_test_str3); -} - - -// Tests that FlagSaver can save the values of various-typed flags. -TEST(FlagSaverTest, CanSaveVariousTypedFlagValues) { - // Initializes the flags. - FLAGS_test_bool = false; - FLAGS_test_int32 = -1; - FLAGS_test_int64 = -2; - FLAGS_test_uint64 = 3; - FLAGS_test_double = 4.0; - FLAGS_test_string = "good"; - - // Saves the flag states. - { - FlagSaver fs; - - // Modifies the flags. - FLAGS_test_bool = true; - FLAGS_test_int32 = -5; - FLAGS_test_int64 = -6; - FLAGS_test_uint64 = 7; - FLAGS_test_double = 8.0; - FLAGS_test_string = "bad"; - - // Restores the flag states. - } - - // Verifies the flag values were restored. - EXPECT_FALSE(FLAGS_test_bool); - EXPECT_EQ(-1, FLAGS_test_int32); - EXPECT_EQ(-2, FLAGS_test_int64); - EXPECT_EQ(3, FLAGS_test_uint64); - EXPECT_DOUBLE_EQ(4.0, FLAGS_test_double); - EXPECT_EQ("good", FLAGS_test_string); -} - -TEST(GetAllFlagsTest, BaseTest) { - vector<CommandLineFlagInfo> flags; - GetAllFlags(&flags); - bool found_test_bool = false; - vector<CommandLineFlagInfo>::const_iterator i; - for (i = flags.begin(); i != flags.end(); ++i) { - if (i->name == "test_bool") { - found_test_bool = true; - EXPECT_EQ(i->type, "bool"); - EXPECT_EQ(i->default_value, "false"); - EXPECT_EQ(i->flag_ptr, &FLAGS_test_bool); - break; - } - } - EXPECT_TRUE(found_test_bool); -} - -TEST(ShowUsageWithFlagsTest, BaseTest) { - // TODO(csilvers): test this by allowing output other than to stdout. - // Not urgent since this functionality is tested via - // gflags_unittest.sh, though only through use of --help. -} - -TEST(ShowUsageWithFlagsRestrictTest, BaseTest) { - // TODO(csilvers): test this by allowing output other than to stdout. - // Not urgent since this functionality is tested via - // gflags_unittest.sh, though only through use of --helpmatch. -} - -// Note: all these argv-based tests depend on SetArgv being called -// before ParseCommandLineFlags() in main(), below. -TEST(GetArgvsTest, BaseTest) { - vector<string> argvs = GetArgvs(); - EXPECT_EQ(4, argvs.size()); - EXPECT_EQ("/test/argv/for/gflags_unittest", argvs[0]); - EXPECT_EQ("argv 2", argvs[1]); - EXPECT_EQ("3rd argv", argvs[2]); - EXPECT_EQ("argv #4", argvs[3]); -} - -TEST(GetArgvTest, BaseTest) { - EXPECT_STREQ("/test/argv/for/gflags_unittest " - "argv 2 3rd argv argv #4", GetArgv()); -} - -TEST(GetArgv0Test, BaseTest) { - EXPECT_STREQ("/test/argv/for/gflags_unittest", GetArgv0()); -} - -TEST(GetArgvSumTest, BaseTest) { - // This number is just the sum of the ASCII values of all the chars - // in GetArgv(). - EXPECT_EQ(4904, GetArgvSum()); -} - -TEST(ProgramInvocationNameTest, BaseTest) { - EXPECT_STREQ("/test/argv/for/gflags_unittest", - ProgramInvocationName()); -} - -TEST(ProgramInvocationShortNameTest, BaseTest) { - EXPECT_STREQ("gflags_unittest", ProgramInvocationShortName()); -} - -TEST(ProgramUsageTest, BaseTest) { // Depends on 1st arg to ParseCommandLineFlags() - EXPECT_STREQ("/test/argv/for/gflags_unittest: " - "<useless flag> [...]\nDoes something useless.\n", - ProgramUsage()); -} - -TEST(GetCommandLineOptionTest, NameExistsAndIsDefault) { - string value("will be changed"); - bool r = GetCommandLineOption("test_bool", &value); - EXPECT_TRUE(r); - EXPECT_EQ("false", value); - - r = GetCommandLineOption("test_int32", &value); - EXPECT_TRUE(r); - EXPECT_EQ("-1", value); -} - -TEST(GetCommandLineOptionTest, NameExistsAndWasAssigned) { - FLAGS_test_int32 = 400; - string value("will be changed"); - const bool r = GetCommandLineOption("test_int32", &value); - EXPECT_TRUE(r); - EXPECT_EQ("400", value); -} - -TEST(GetCommandLineOptionTest, NameExistsAndWasSet) { - SetCommandLineOption("test_int32", "700"); - string value("will be changed"); - const bool r = GetCommandLineOption("test_int32", &value); - EXPECT_TRUE(r); - EXPECT_EQ("700", value); -} - -TEST(GetCommandLineOptionTest, NameExistsAndWasNotSet) { - // This doesn't set the flag's value, but rather its default value. - // is_default is still true, but the 'default' value returned has changed! - SetCommandLineOptionWithMode("test_int32", "800", SET_FLAGS_DEFAULT); - string value("will be changed"); - const bool r = GetCommandLineOption("test_int32", &value); - EXPECT_TRUE(r); - EXPECT_EQ("800", value); - EXPECT_TRUE(GetCommandLineFlagInfoOrDie("test_int32").is_default); -} - -TEST(GetCommandLineOptionTest, NameExistsAndWasConditionallySet) { - SetCommandLineOptionWithMode("test_int32", "900", SET_FLAG_IF_DEFAULT); - string value("will be changed"); - const bool r = GetCommandLineOption("test_int32", &value); - EXPECT_TRUE(r); - EXPECT_EQ("900", value); -} - -TEST(GetCommandLineOptionTest, NameDoesNotExist) { - string value("will not be changed"); - const bool r = GetCommandLineOption("test_int3210", &value); - EXPECT_FALSE(r); - EXPECT_EQ("will not be changed", value); -} - -TEST(GetCommandLineFlagInfoTest, FlagExists) { - CommandLineFlagInfo info; - bool r = GetCommandLineFlagInfo("test_int32", &info); - EXPECT_TRUE(r); - EXPECT_EQ("test_int32", info.name); - EXPECT_EQ("int32", info.type); - EXPECT_EQ("", info.description); - EXPECT_EQ("-1", info.current_value); - EXPECT_EQ("-1", info.default_value); - EXPECT_TRUE(info.is_default); - EXPECT_FALSE(info.has_validator_fn); - EXPECT_EQ(&FLAGS_test_int32, info.flag_ptr); - - FLAGS_test_bool = true; - r = GetCommandLineFlagInfo("test_bool", &info); - EXPECT_TRUE(r); - EXPECT_EQ("test_bool", info.name); - EXPECT_EQ("bool", info.type); - EXPECT_EQ("tests bool-ness", info.description); - EXPECT_EQ("true", info.current_value); - EXPECT_EQ("false", info.default_value); - EXPECT_FALSE(info.is_default); - EXPECT_FALSE(info.has_validator_fn); - EXPECT_EQ(&FLAGS_test_bool, info.flag_ptr); - - FLAGS_test_bool = false; - r = GetCommandLineFlagInfo("test_bool", &info); - EXPECT_TRUE(r); - EXPECT_EQ("test_bool", info.name); - EXPECT_EQ("bool", info.type); - EXPECT_EQ("tests bool-ness", info.description); - EXPECT_EQ("false", info.current_value); - EXPECT_EQ("false", info.default_value); - EXPECT_FALSE(info.is_default); // value is same, but flag *was* modified - EXPECT_FALSE(info.has_validator_fn); - EXPECT_EQ(&FLAGS_test_bool, info.flag_ptr); -} - -TEST(GetCommandLineFlagInfoTest, FlagDoesNotExist) { - CommandLineFlagInfo info; - // Set to some random values that GetCommandLineFlagInfo should not change - info.name = "name"; - info.type = "type"; - info.current_value = "curr"; - info.default_value = "def"; - info.filename = "/"; - info.is_default = false; - info.has_validator_fn = true; - info.flag_ptr = NULL; - bool r = GetCommandLineFlagInfo("test_int3210", &info); - EXPECT_FALSE(r); - EXPECT_EQ("name", info.name); - EXPECT_EQ("type", info.type); - EXPECT_EQ("", info.description); - EXPECT_EQ("curr", info.current_value); - EXPECT_EQ("def", info.default_value); - EXPECT_EQ("/", info.filename); - EXPECT_FALSE(info.is_default); - EXPECT_TRUE(info.has_validator_fn); - EXPECT_EQ(NULL, info.flag_ptr); -} - -TEST(GetCommandLineFlagInfoOrDieTest, FlagExistsAndIsDefault) { - CommandLineFlagInfo info; - info = GetCommandLineFlagInfoOrDie("test_int32"); - EXPECT_EQ("test_int32", info.name); - EXPECT_EQ("int32", info.type); - EXPECT_EQ("", info.description); - EXPECT_EQ("-1", info.current_value); - EXPECT_EQ("-1", info.default_value); - EXPECT_TRUE(info.is_default); - EXPECT_EQ(&FLAGS_test_int32, info.flag_ptr); - info = GetCommandLineFlagInfoOrDie("test_bool"); - EXPECT_EQ("test_bool", info.name); - EXPECT_EQ("bool", info.type); - EXPECT_EQ("tests bool-ness", info.description); - EXPECT_EQ("false", info.current_value); - EXPECT_EQ("false", info.default_value); - EXPECT_TRUE(info.is_default); - EXPECT_FALSE(info.has_validator_fn); - EXPECT_EQ(&FLAGS_test_bool, info.flag_ptr); -} - -TEST(GetCommandLineFlagInfoOrDieTest, FlagExistsAndWasAssigned) { - FLAGS_test_int32 = 400; - CommandLineFlagInfo info; - info = GetCommandLineFlagInfoOrDie("test_int32"); - EXPECT_EQ("test_int32", info.name); - EXPECT_EQ("int32", info.type); - EXPECT_EQ("", info.description); - EXPECT_EQ("400", info.current_value); - EXPECT_EQ("-1", info.default_value); - EXPECT_FALSE(info.is_default); - EXPECT_EQ(&FLAGS_test_int32, info.flag_ptr); - FLAGS_test_bool = true; - info = GetCommandLineFlagInfoOrDie("test_bool"); - EXPECT_EQ("test_bool", info.name); - EXPECT_EQ("bool", info.type); - EXPECT_EQ("tests bool-ness", info.description); - EXPECT_EQ("true", info.current_value); - EXPECT_EQ("false", info.default_value); - EXPECT_FALSE(info.is_default); - EXPECT_FALSE(info.has_validator_fn); - EXPECT_EQ(&FLAGS_test_bool, info.flag_ptr); -} - -#ifdef GTEST_HAS_DEATH_TEST -TEST(GetCommandLineFlagInfoOrDieDeathTest, FlagDoesNotExist) { - EXPECT_DEATH(GetCommandLineFlagInfoOrDie("test_int3210"), - ".*: flag test_int3210 does not exist"); -} -#endif - - -// These are lightly tested because they're deprecated. Basically, -// the tests are meant to cover how existing users use these functions, -// but not necessarily how new users could use them. -TEST(DeprecatedFunctionsTest, CommandlineFlagsIntoString) { - string s = CommandlineFlagsIntoString(); - EXPECT_NE(string::npos, s.find("--test_bool=")); -} - -TEST(DeprecatedFunctionsTest, AppendFlagsIntoFile) { - FLAGS_test_int32 = 10; // just to make the test more interesting - string filename(TmpFile("flagfile")); - unlink(filename.c_str()); // just to be safe - const bool r = AppendFlagsIntoFile(filename, "not the real argv0"); - EXPECT_TRUE(r); - - FILE* fp = fopen(filename.c_str(), "r"); - EXPECT_TRUE(fp != NULL); - char line[8192]; - EXPECT_TRUE(fgets(line, sizeof(line)-1, fp) != NULL); // get the first line - // First line should be progname. - EXPECT_STREQ("not the real argv0\n", line); - - bool found_bool = false, found_int32 = false; - while (fgets(line, sizeof(line)-1, fp)) { - line[sizeof(line)-1] = '\0'; // just to be safe - if (strcmp(line, "--test_bool=false\n") == 0) - found_bool = true; - if (strcmp(line, "--test_int32=10\n") == 0) - found_int32 = true; - } - EXPECT_TRUE(found_int32); - EXPECT_TRUE(found_bool); - fclose(fp); -} - -TEST(DeprecatedFunctionsTest, ReadFromFlagsFile) { - FLAGS_test_int32 = -10; // just to make the test more interesting - string filename(TmpFile("flagfile2")); - unlink(filename.c_str()); // just to be safe - bool r = AppendFlagsIntoFile(filename, GetArgv0()); - EXPECT_TRUE(r); - - FLAGS_test_int32 = -11; - r = ReadFromFlagsFile(filename, GetArgv0(), true); - EXPECT_TRUE(r); - EXPECT_EQ(-10, FLAGS_test_int32); -} // unnamed namespace - -TEST(DeprecatedFunctionsTest, ReadFromFlagsFileFailure) { - FLAGS_test_int32 = -20; - string filename(TmpFile("flagfile3")); - FILE* fp = fopen(filename.c_str(), "w"); - EXPECT_TRUE(fp != NULL); - // Note the error in the bool assignment below... - fprintf(fp, "%s\n--test_int32=-21\n--test_bool=not_a_bool!\n", GetArgv0()); - fclose(fp); - - FLAGS_test_int32 = -22; - const bool r = ReadFromFlagsFile(filename, GetArgv0(), false); - EXPECT_FALSE(r); - EXPECT_EQ(-22, FLAGS_test_int32); // the -21 from the flagsfile didn't take -} - -TEST(FlagsSetBeforeInitTest, TryFromEnv) { - EXPECT_EQ("pre-set", FLAGS_test_tryfromenv); -} - -// The following test case verifies that ParseCommandLineFlags() and -// ParseCommandLineNonHelpFlags() uses the last definition of a flag -// in case it's defined more than once. - -DEFINE_int32(test_flag, -1, "used for testing gflags.cc"); - -// Parses and returns the --test_flag flag. -// If with_help is true, calls ParseCommandLineFlags; otherwise calls -// ParseCommandLineNonHelpFlags. -int32 ParseTestFlag(bool with_help, int argc, const char** const_argv) { - FlagSaver fs; // Restores the flags before returning. - - // Makes a copy of the input array s.t. it can be reused - // (ParseCommandLineFlags() will alter the array). - char** const argv_save = new char*[argc + 1]; - char** argv = argv_save; - memcpy(argv, const_argv, sizeof(*argv)*(argc + 1)); - - if (with_help) { - ParseCommandLineFlags(&argc, &argv, true); - } else { - ParseCommandLineNonHelpFlags(&argc, &argv, true); - } - - delete[] argv_save; - return FLAGS_test_flag; -} - -TEST(ParseCommandLineFlagsUsesLastDefinitionTest, - WhenFlagIsDefinedTwiceOnCommandLine) { - const char* argv[] = { - "my_test", - "--test_flag=1", - "--test_flag=2", - NULL, - }; - - EXPECT_EQ(2, ParseTestFlag(true, arraysize(argv) - 1, argv)); - EXPECT_EQ(2, ParseTestFlag(false, arraysize(argv) - 1, argv)); -} - -TEST(ParseCommandLineFlagsUsesLastDefinitionTest, - WhenFlagIsDefinedTwiceInFlagFile) { - const char* argv[] = { - "my_test", - GetFlagFileFlag(), - NULL, - }; - - EXPECT_EQ(2, ParseTestFlag(true, arraysize(argv) - 1, argv)); - EXPECT_EQ(2, ParseTestFlag(false, arraysize(argv) - 1, argv)); -} - -TEST(ParseCommandLineFlagsUsesLastDefinitionTest, - WhenFlagIsDefinedInCommandLineAndThenFlagFile) { - const char* argv[] = { - "my_test", - "--test_flag=0", - GetFlagFileFlag(), - NULL, - }; - - EXPECT_EQ(2, ParseTestFlag(true, arraysize(argv) - 1, argv)); - EXPECT_EQ(2, ParseTestFlag(false, arraysize(argv) - 1, argv)); -} - -TEST(ParseCommandLineFlagsUsesLastDefinitionTest, - WhenFlagIsDefinedInFlagFileAndThenCommandLine) { - const char* argv[] = { - "my_test", - GetFlagFileFlag(), - "--test_flag=3", - NULL, - }; - - EXPECT_EQ(3, ParseTestFlag(true, arraysize(argv) - 1, argv)); - EXPECT_EQ(3, ParseTestFlag(false, arraysize(argv) - 1, argv)); -} - -TEST(ParseCommandLineFlagsUsesLastDefinitionTest, - WhenFlagIsDefinedInCommandLineAndFlagFileAndThenCommandLine) { - const char* argv[] = { - "my_test", - "--test_flag=0", - GetFlagFileFlag(), - "--test_flag=3", - NULL, - }; - - EXPECT_EQ(3, ParseTestFlag(true, arraysize(argv) - 1, argv)); - EXPECT_EQ(3, ParseTestFlag(false, arraysize(argv) - 1, argv)); -} - -TEST(ParseCommandLineFlagsAndDashArgs, TwoDashArgFirst) { - const char* argv[] = { - "my_test", - "--", - "--test_flag=0", - NULL, - }; - - EXPECT_EQ(-1, ParseTestFlag(true, arraysize(argv) - 1, argv)); - EXPECT_EQ(-1, ParseTestFlag(false, arraysize(argv) - 1, argv)); -} - -TEST(ParseCommandLineFlagsAndDashArgs, TwoDashArgMiddle) { - const char* argv[] = { - "my_test", - "--test_flag=7", - "--", - "--test_flag=0", - NULL, - }; - - EXPECT_EQ(7, ParseTestFlag(true, arraysize(argv) - 1, argv)); - EXPECT_EQ(7, ParseTestFlag(false, arraysize(argv) - 1, argv)); -} - -TEST(ParseCommandLineFlagsAndDashArgs, OneDashArg) { - const char* argv[] = { - "my_test", - "-", - "--test_flag=0", - NULL, - }; - - EXPECT_EQ(0, ParseTestFlag(true, arraysize(argv) - 1, argv)); - EXPECT_EQ(0, ParseTestFlag(false, arraysize(argv) - 1, argv)); -} - -#ifdef GTEST_HAS_DEATH_TEST -TEST(ParseCommandLineFlagsUnknownFlagDeathTest, - FlagIsCompletelyUnknown) { - const char* argv[] = { - "my_test", - "--this_flag_does_not_exist", - NULL, - }; - - EXPECT_DEATH(ParseTestFlag(true, arraysize(argv) - 1, argv), - "unknown command line flag.*"); - EXPECT_DEATH(ParseTestFlag(false, arraysize(argv) - 1, argv), - "unknown command line flag.*"); -} - -TEST(ParseCommandLineFlagsUnknownFlagDeathTest, - BoolFlagIsCompletelyUnknown) { - const char* argv[] = { - "my_test", - "--nothis_flag_does_not_exist", - NULL, - }; - - EXPECT_DEATH(ParseTestFlag(true, arraysize(argv) - 1, argv), - "unknown command line flag.*"); - EXPECT_DEATH(ParseTestFlag(false, arraysize(argv) - 1, argv), - "unknown command line flag.*"); -} - -TEST(ParseCommandLineFlagsUnknownFlagDeathTest, - FlagIsNotABool) { - const char* argv[] = { - "my_test", - "--notest_string", - NULL, - }; - - EXPECT_DEATH(ParseTestFlag(true, arraysize(argv) - 1, argv), - "boolean value .* specified for .* command line flag"); - EXPECT_DEATH(ParseTestFlag(false, arraysize(argv) - 1, argv), - "boolean value .* specified for .* command line flag"); -} -#endif - -TEST(ParseCommandLineFlagsWrongFields, - DescriptionIsInvalid) { - // These must not be automatic variables, since command line flags - // aren't unregistered and gUnit uses FlagSaver to save and restore - // command line flags' values. If these are on the stack, then when - // later tests attempt to save and restore their values, the stack - // addresses of these variables will be overwritten... Stack smash! - static bool current_storage; - static bool defvalue_storage; - FlagRegisterer fr("flag_name", "bool", 0, "filename", - ¤t_storage, &defvalue_storage); - CommandLineFlagInfo fi; - EXPECT_TRUE(GetCommandLineFlagInfo("flag_name", &fi)); - EXPECT_EQ("", fi.description); - EXPECT_EQ(¤t_storage, fi.flag_ptr); -} - -static bool ValidateTestFlagIs5(const char* flagname, int32 flagval) { - if (flagval == 5) - return true; - printf("%s isn't 5!\n", flagname); - return false; -} - -static bool ValidateTestFlagIs10(const char* flagname, int32 flagval) { - return flagval == 10; -} - - -TEST(FlagsValidator, ValidFlagViaArgv) { - const char* argv[] = { - "my_test", - "--test_flag=5", - NULL, - }; - EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs5)); - EXPECT_EQ(5, ParseTestFlag(true, arraysize(argv) - 1, argv)); - // Undo the flag validator setting - EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, NULL)); -} - -TEST(FlagsValidator, ValidFlagViaSetDefault) { - EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs5)); - // SetCommandLineOptionWithMode returns the empty string on error. - EXPECT_NE("", SetCommandLineOptionWithMode("test_flag", "5", - SET_FLAG_IF_DEFAULT)); - EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, NULL)); -} - -TEST(FlagsValidator, ValidFlagViaSetValue) { - EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs5)); - FLAGS_test_flag = 100; // doesn't trigger the validator - // SetCommandLineOptionWithMode returns the empty string on error. - EXPECT_NE("", SetCommandLineOptionWithMode("test_flag", "5", - SET_FLAGS_VALUE)); - EXPECT_NE("", SetCommandLineOptionWithMode("test_flag", "5", - SET_FLAGS_DEFAULT)); - EXPECT_NE("", SetCommandLineOption("test_flag", "5")); - EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, NULL)); -} - -#ifdef GTEST_HAS_DEATH_TEST -TEST(FlagsValidatorDeathTest, InvalidFlagViaArgv) { - const char* argv[] = { - "my_test", - "--test_flag=50", - NULL, - }; - EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs5)); - EXPECT_DEATH(ParseTestFlag(true, arraysize(argv) - 1, argv), - "ERROR: failed validation of new value '50' for flag 'test_flag'"); - EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, NULL)); -} -#endif - -TEST(FlagsValidator, InvalidFlagViaSetDefault) { - EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs5)); - // SetCommandLineOptionWithMode returns the empty string on error. - EXPECT_EQ("", SetCommandLineOptionWithMode("test_flag", "50", - SET_FLAG_IF_DEFAULT)); - EXPECT_EQ(-1, FLAGS_test_flag); // the setting-to-50 should have failed - EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, NULL)); -} - -TEST(FlagsValidator, InvalidFlagViaSetValue) { - EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs5)); - FLAGS_test_flag = 100; // doesn't trigger the validator - // SetCommandLineOptionWithMode returns the empty string on error. - EXPECT_EQ("", SetCommandLineOptionWithMode("test_flag", "50", - SET_FLAGS_VALUE)); - EXPECT_EQ("", SetCommandLineOptionWithMode("test_flag", "50", - SET_FLAGS_DEFAULT)); - EXPECT_EQ("", SetCommandLineOption("test_flag", "50")); - EXPECT_EQ(100, FLAGS_test_flag); // the setting-to-50 should have failed - EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, NULL)); -} - -#ifdef GTEST_HAS_DEATH_TEST -TEST(FlagsValidatorDeathTest, InvalidFlagNeverSet) { - // If a flag keeps its default value, and that default value is - // invalid, we should die at argv-parse time. - const char* argv[] = { - "my_test", - NULL, - }; - EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs5)); - EXPECT_DEATH(ParseTestFlag(true, arraysize(argv) - 1, argv), - "ERROR: --test_flag must be set on the commandline"); -} -#endif - -TEST(FlagsValidator, InvalidFlagPtr) { - int32 dummy; - EXPECT_FALSE(RegisterFlagValidator(NULL, &ValidateTestFlagIs5)); - EXPECT_FALSE(RegisterFlagValidator(&dummy, &ValidateTestFlagIs5)); -} - -TEST(FlagsValidator, RegisterValidatorTwice) { - EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs5)); - EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs5)); - EXPECT_FALSE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs10)); - EXPECT_FALSE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs10)); - EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs5)); - EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, NULL)); - EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs10)); - EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, NULL)); -} - -TEST(FlagsValidator, CommandLineFlagInfo) { - CommandLineFlagInfo info; - info = GetCommandLineFlagInfoOrDie("test_flag"); - EXPECT_FALSE(info.has_validator_fn); - - EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs5)); - info = GetCommandLineFlagInfoOrDie("test_flag"); - EXPECT_TRUE(info.has_validator_fn); - - EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, NULL)); - info = GetCommandLineFlagInfoOrDie("test_flag"); - EXPECT_FALSE(info.has_validator_fn); -} - -TEST(FlagsValidator, FlagSaver) { - { - FlagSaver fs; - EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs5)); - EXPECT_EQ("", SetCommandLineOption("test_flag", "50")); // fails validation - } - EXPECT_NE("", SetCommandLineOption("test_flag", "50")); // validator is gone - - EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs5)); - { - FlagSaver fs; - EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, NULL)); - EXPECT_NE("", SetCommandLineOption("test_flag", "50")); // no validator - } - EXPECT_EQ("", SetCommandLineOption("test_flag", "50")); // validator is back -} - - -} // unnamed namespace - -int main(int argc, char **argv) { - // We need to call SetArgv before parsing flags, so our "test" argv will - // win out over this executable's real argv. That makes running this - // test with a real --help flag kinda annoying, unfortunately. - const char* test_argv[] = { "/test/argv/for/gflags_unittest", - "argv 2", "3rd argv", "argv #4" }; - SetArgv(arraysize(test_argv), test_argv); - - // The first arg is the usage message, also important for testing. - string usage_message = (string(GetArgv0()) + - ": <useless flag> [...]\nDoes something useless.\n"); - - // We test setting tryfromenv manually, and making sure - // ParseCommandLineFlags still evaluates it. - FLAGS_tryfromenv = "test_tryfromenv"; - setenv("FLAGS_test_tryfromenv", "pre-set", 1); - - // Modify flag values from declared default value in two ways. - // The recommended way: - SetCommandLineOptionWithMode("changed_bool1", "true", SET_FLAGS_DEFAULT); - - // The non-recommended way: - FLAGS_changed_bool2 = true; - - SetUsageMessage(usage_message.c_str()); - SetVersionString("test_version"); - ParseCommandLineFlags(&argc, &argv, true); - MakeTmpdir(&FLAGS_test_tmpdir); - - const int exit_status = RUN_ALL_TESTS(); - ShutDownCommandLineFlags(); - return exit_status; -} - -_END_GOOGLE_NAMESPACE_ - -int main(int argc, char** argv) { - return GOOGLE_NAMESPACE::main(argc, argv); -} - diff --git a/src/gflags_unittest.sh b/src/gflags_unittest.sh deleted file mode 100755 index c81e41e..0000000 --- a/src/gflags_unittest.sh +++ /dev/null @@ -1,237 +0,0 @@ -#!/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 diff --git a/src/gflags_unittest_flagfile b/src/gflags_unittest_flagfile deleted file mode 100644 index f4fa0c4..0000000 --- a/src/gflags_unittest_flagfile +++ /dev/null @@ -1,2 +0,0 @@ ---test_flag=1 ---test_flag=2 diff --git a/src/google/gflags.h b/src/google/gflags.h deleted file mode 100644 index c1adcb8..0000000 --- a/src/google/gflags.h +++ /dev/null @@ -1,34 +0,0 @@ -// 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> diff --git a/src/google/gflags_completions.h b/src/google/gflags_completions.h deleted file mode 100644 index 614ef09..0000000 --- a/src/google/gflags_completions.h +++ /dev/null @@ -1,34 +0,0 @@ -// 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> diff --git a/src/mutex.h b/src/mutex.h index 7c3c060..3e2f28e 100644 --- a/src/mutex.h +++ b/src/mutex.h @@ -32,11 +32,6 @@ // 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 @@ -108,13 +103,13 @@ // 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_ +#ifndef GFLAGS_MUTEX_H_ +#define GFLAGS_MUTEX_H_ -#include "config.h" // to figure out pthreads support +#include "gflags_declare.h" // to figure out pthreads support #if defined(NO_THREADS) - typedef int MutexType; // to keep a lock-count + 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 @@ -353,4 +348,4 @@ using namespace MUTEX_NAMESPACE; #undef MUTEX_NAMESPACE -#endif /* #define GOOGLE_MUTEX_H__ */ +#endif /* #define GFLAGS_MUTEX_H__ */ diff --git a/src/solaris/libstdc++.la b/src/solaris/libstdc++.la deleted file mode 100644 index 3edf425..0000000 --- a/src/solaris/libstdc++.la +++ /dev/null @@ -1,51 +0,0 @@ -# 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' @@ -34,48 +34,56 @@ #ifndef GFLAGS_UTIL_H_ #define GFLAGS_UTIL_H_ +#include "config.h" + #include <assert.h> #include <config.h> #ifdef HAVE_INTTYPES_H -# include <inttypes.h> +# include <inttypes.h> #endif #include <stdarg.h> // for va_* #include <stdlib.h> #include <stdio.h> #include <iostream> #include <string> +#include <errno.h> #ifdef HAVE_SYS_STAT_H -# include <sys/stat.h> -#endif // for mkdir() +# include <sys/stat.h> // for mkdir +#endif + + +namespace GFLAGS_NAMESPACE { -_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 +#if defined(HAVE_STRTOLL) +# define strto64 strtoll +# define strtou64 strtoull +#elif defined(HAVE_STRTOQ) +# define strto64 strtoq +# define strtou64 strtouq +#elif defined(_WIN32) && !defined(__MINGW32__) && !defined(__MINGW64__) +# define strto64 _strtoi64 +# define strtou64 _strtoui64 // Neither strtoll nor strtoq are defined. I hope strtol works! -# define strto64 strtol -# define strtou64 strtoul +#else +# 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. +// If we have inttypes.h, it will have defined PRId32/etc for us. +// If not, take our best guess. #ifndef PRId32 -# define PRId32 "d" +# define PRId32 "d" #endif #ifndef PRId64 -# define PRId64 "lld" +# define PRId64 "lld" #endif #ifndef PRIu64 -# define PRIu64 "llu" +# define PRIu64 "llu" #endif typedef signed char int8; @@ -230,23 +238,36 @@ class Test {}; #if defined(__MINGW32__) #include <io.h> inline void MakeTmpdir(std::string* path) { + if (!path->empty()) { + path->append("/gflags_unittest_testdir"); + int err = mkdir(path->c_str()); + if (err == 0 || errno == EEXIST) return; + } // 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 + *path = "./gflags_unittest"; + mkdir(path->c_str()); } #elif defined(_MSC_VER) #include <direct.h> inline void MakeTmpdir(std::string* path) { + if (!path->empty()) { + int err = _mkdir(path->c_str()); + if (err == 0 || errno == EEXIST) return; + } 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"; + *path = std::string(tmppath_buffer) + "gflags_unittest"; _mkdir(path->c_str()); } #else inline void MakeTmpdir(std::string* path) { - mkdir(path->c_str(), 0755); + if (!path->empty()) { + int err = mkdir(path->c_str(), 0755); + if (err == 0 || errno == EEXIST) return; + } + mkdir("/tmp/gflags_unittest", 0755); } #endif @@ -320,6 +341,36 @@ inline std::string StringPrintf(const char* format, ...) { return output; } -_END_GOOGLE_NAMESPACE_ +inline bool SafeGetEnv(const char *varname, std::string &valstr) +{ +#if defined(_MSC_VER) && _MSC_VER >= 1400 + char *val; + size_t sz; + if (_dupenv_s(&val, &sz, varname) != 0 || !val) return false; + valstr = val; + free(val); +#else + const char * const val = getenv(varname); + if (!val) return false; + valstr = val; +#endif + return true; +} + +inline int SafeFOpen(FILE **fp, const char* fname, const char *mode) +{ +#if defined(_MSC_VER) && _MSC_VER >= 1400 + return fopen_s(fp, fname, mode); +#else + assert(fp != NULL); + *fp = fopen(fname, mode); + // errno only guaranteed to be set on failure + return ((*fp == NULL) ? errno : 0); +#endif +} + + +} // namespace GFLAGS_NAMESPACE + #endif // GFLAGS_UTIL_H_ diff --git a/src/windows/config.h b/src/windows/config.h deleted file mode 100644 index dcca757..0000000 --- a/src/windows/config.h +++ /dev/null @@ -1,139 +0,0 @@ -/* 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_ */ diff --git a/src/windows/gflags/gflags_completions.h b/src/windows/gflags/gflags_completions.h deleted file mode 100644 index bf049fe..0000000 --- a/src/windows/gflags/gflags_completions.h +++ /dev/null @@ -1,132 +0,0 @@ -// 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_ diff --git a/src/windows/gflags/gflags_declare.h b/src/windows/gflags/gflags_declare.h deleted file mode 100644 index 5fca1e4..0000000 --- a/src/windows/gflags/gflags_declare.h +++ /dev/null @@ -1,114 +0,0 @@ -// 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_ diff --git a/src/windows/port.cc b/src/windows_port.cc index fb47698..1f40458 100644 --- a/src/windows/port.cc +++ b/src/windows_port.cc @@ -32,24 +32,32 @@ */ #ifndef _WIN32 -# error You should only be including windows/port.cc in a windows environment! +# 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" + +#include "windows_port.h" // These call the windows _vsnprintf, but always NUL-terminate. #if !defined(__MINGW32__) && !defined(__MINGW64__) /* mingw already defines */ + +#ifdef _MSC_VER +# pragma warning(push) +# pragma warning(disable: 4996) // ignore _vsnprintf security warning +#endif 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'; + str[size-1] = '\0'; return _vsnprintf(str, size-1, format, ap); } +#ifdef _MSC_VER +# pragma warning(pop) +#endif int snprintf(char *str, size_t size, const char *format, ...) { int r; @@ -59,4 +67,5 @@ int snprintf(char *str, size_t size, const char *format, ...) { va_end(ap); return r; } + #endif /* #if !defined(__MINGW32__) && !defined(__MINGW64__) */ diff --git a/src/windows/port.h b/src/windows_port.h index fbeccd7..246f715 100644 --- a/src/windows/port.h +++ b/src/windows_port.h @@ -37,13 +37,19 @@ * http://developer.gnome.org/doc/API/glib/glib-windows-compatability-functions.html */ -#ifndef GOOGLE_GFLAGS_WINDOWS_PORT_H_ -#define GOOGLE_GFLAGS_WINDOWS_PORT_H_ +#ifndef GFLAGS_WINDOWS_PORT_H_ +#define GFLAGS_WINDOWS_PORT_H_ -#ifdef _WIN32 +#include "config.h" +// This must be defined before the windows.h is included. +// It's needed for mutex.h, to give access to the TryLock method. +# if !defined(_WIN32_WINNT) && !(defined( __MINGW32__) || defined(__MINGW64__)) +# define _WIN32_WINNT 0x0400 +# endif +// We always want minimal includes #ifndef WIN32_LEAN_AND_MEAN -#define WIN32_LEAN_AND_MEAN /* We always want minimal includes */ +# define WIN32_LEAN_AND_MEAN #endif #include <windows.h> #include <direct.h> /* for mkdir */ @@ -65,6 +71,10 @@ extern int GFLAGS_DLL_DECL safe_vsnprintf(char *str, size_t size, #define va_copy(dst, src) (dst) = (src) #endif /* #if !defined(__MINGW32__) && !defined(__MINGW64__) */ +#ifdef _MSC_VER +# pragma warning(push) +# pragma warning(disable: 4996) // ignore getenv security warning +#endif 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. @@ -76,7 +86,7 @@ inline void setenv(const char* name, const char* value, int) { 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; + const size_t 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); @@ -86,6 +96,9 @@ inline void setenv(const char* name, const char* value, int) { *getenv(name) = '\0'; // works when putenv() copies nameval } } +#ifdef _MSC_VER +# pragma warning(pop) +#endif #define strcasecmp _stricmp @@ -111,6 +124,4 @@ inline void setenv(const char* name, const char* value, int) { #define PATH_MAX 1024 #endif -#endif /* _WIN32 */ - -#endif /* GOOGLE_GFLAGS_WINDOWS_PORT_H_ */ +#endif /* GFLAGS_WINDOWS_PORT_H_ */ |