Skip to content
This repository was archived by the owner on Dec 29, 2022. It is now read-only.

Commit

Permalink
I'm moving to a new way of maintaining the opensource tree, and this
Browse files Browse the repository at this point in the history
is a bunch of (mostly) non-contentful changes to support that.  Some
of the changes are truly administrative, such as newlines added and
deleted in various places.  Here are the bigger ones:

1) Several places used the older name 'flags' for this product instead
of gflags, especially in comments.  These have been mostly, if not
totally, fixed.

2) Likewise, I no longer do 'import gflags as flags' for the tests --
they all just use 'gflags' now.

3) A few files had the wrong copyright year; fix that.

4) Some of gflags_test is a bit more awkward now (some lines with ""
empty strings for no apparent reason, one place where we insert
one string into another to created an expected-output, for no apparent
reason).  These are artifacts of the new maintenance system.  They're
a bit ugly but harmless.

5) The directory structure has been reorganized, to put all tests into
their own subdirectory.  There's now a MANIFEST.in file, since the
automatically generated one doesn't handle the new structure quite
right.

Some contentful changes:

6) A new file, gflags_googletest.py, which subclasses the standard
unittest module to provide a few helper assert routines.  These used
to be embedded directly into the various *_test.py files, which
resulted in duplication.

7) The Makefile now has 'make check' to automatically run all the
tests

8) We no longer check if we're running a python version < 2.2
  • Loading branch information
csilvers committed Jul 29, 2011
1 parent 0158473 commit 66a638a
Show file tree
Hide file tree
Showing 14 changed files with 561 additions and 575 deletions.
3 changes: 3 additions & 0 deletions MANIFEST.in
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
recursive-include tests *.py
include Makefile
include NEWS
28 changes: 16 additions & 12 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ prep:
@echo
# Install needed packages
sudo apt-get install subversion fakeroot python-setuptools python-subversion

#
@echo
# Check that the person has .pypirc
@if [ ! -e ~/.pypirc ]; then \
Expand All @@ -12,38 +12,38 @@ prep:
echo "username:google_opensource"; \
echo "password:<see valentine>"; \
fi

#
@echo
# FIXME(tansell): Check that the person has .dputrc for PPA

clean:
# Clean up any build files.
python setup.py clean --all

#
# Clean up the debian stuff
fakeroot ./debian/rules clean

#
# Clean up everything else
rm MANIFEST || true
rm -rf build-*

#
# Clean up the egg files
rm -rf *egg*

#
# Remove dist
rm -rf dist

dist:
# Generate the tarball based on MANIFEST.in
python setup.py sdist

#
# Build the debian packages
fakeroot ./debian/rules binary
mv ../python-gflags*.deb ./dist/

#
# Build the python Egg
python setup.py bdist_egg

#
@echo
@echo "Files to upload:"
@echo "--------------------------"
Expand All @@ -54,12 +54,16 @@ push:
# Upload the source package to code.google.com
- /home/build/opensource/tools/googlecode_upload.py \
-p python-gflags ./dist/*

#
# Upload the package to PyPi
- python setup.py sdist upload
- python setup.py bdist_egg upload

#
# Upload the package to the ppa
# FIXME(tansell): dput should run here

.PHONY: prep dist clean push
check:
# Run all the tests.
for test in tests/*.py; do PYTHONPATH=. python $$test || exit 1; done

.PHONY: prep dist clean push check
94 changes: 37 additions & 57 deletions gflags.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#!/usr/bin/env python

# Copyright (c) 2007, Google Inc.
#
# Copyright (c) 2002, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
Expand Down Expand Up @@ -58,8 +58,8 @@
available as attributes of the 'FlagValues' object.
Code can access the flag through a FlagValues object, for instance
gflags.FLAGS.myflag. Typically, the __main__ module passes the
command line arguments to gflags.FLAGS for parsing.
gflags.FLAGS.myflag. Typically, the __main__ module passes the command
line arguments to gflags.FLAGS for parsing.
At bottom, this module calls getopt(), so getopt functionality is
supported, including short- and long-style flags, and the use of -- to
Expand Down Expand Up @@ -144,7 +144,7 @@
Howto:
If you want to enforce a constraint over one flag, use
flags.RegisterValidator(flag_name,
gflags.RegisterValidator(flag_name,
checker,
message='Flag validation failed',
flag_values=FLAGS)
Expand All @@ -158,15 +158,15 @@
EXAMPLE USAGE:
FLAGS = flags.FLAGS
FLAGS = gflags.FLAGS
flags.DEFINE_integer('my_version', 0, 'Version number.')
flags.DEFINE_string('filename', None, 'Input file name', short_name='f')
gflags.DEFINE_integer('my_version', 0, 'Version number.')
gflags.DEFINE_string('filename', None, 'Input file name', short_name='f')
flags.RegisterValidator('my_version',
gflags.RegisterValidator('my_version',
lambda value: value % 2 == 0,
message='--my_version must be divisible by 2')
flags.MarkFlagAsRequired('filename')
gflags.MarkFlagAsRequired('filename')
NOTE ON --flagfile:
Expand Down Expand Up @@ -202,7 +202,7 @@
EXAMPLE USAGE:
import gflags
FLAGS = gflags.FLAGS
# Flag names are globally defined! So in general, we need to be
Expand All @@ -222,7 +222,7 @@ def main(argv):
if FLAGS.debug: print 'non-flag arguments:', argv
print 'Happy Birthday', FLAGS.name
if FLAGS.age is not None:
print 'You are a %s, who is %d years old' % (FLAGS.gender, FLAGS.age)
print 'You are a %d year old %s' % (FLAGS.age, FLAGS.gender)
if __name__ == '__main__':
main(sys.argv)
Expand Down Expand Up @@ -285,7 +285,7 @@ def main(argv):
EXAMPLE USAGE 2 (WITH KEY FLAGS):
Consider an application that contains the following three files (two
auxiliary modules and a main module):
auxiliary modules and a main module)
File libfoo.py:
Expand All @@ -301,11 +301,11 @@ def main(argv):
import gflags
gflags.DEFINE_string('bar_gfs_path', '/gfs/path',
'Path to the GFS files for libbar.')
'Path to the GFS files for libbar.')
gflags.DEFINE_string('email_for_bar_errors', '[email protected]',
'Email address for bug reports about module libbar.')
'Email address for bug reports about module libbar.')
gflags.DEFINE_boolean('bar_risky_hack', False,
'Turn on an experimental and buggy optimization.')
'Turn on an experimental and buggy optimization.')
... some code ...
Expand All @@ -329,8 +329,7 @@ def main(argv):
When myscript is invoked with the flag --helpshort, the resulted help
message lists information about all the key flags for myscript:
--num_iterations, --num_replicas, --rpc2, and --bar_gfs_path (in
addition to the special flags --help and --helpshort).
--num_iterations, --num_replicas, --rpc2, and --bar_gfs_path.
Of course, myscript uses all the flags declared by it (in this case,
just --num_replicas) or by any of the modules it transitively imports
Expand Down Expand Up @@ -384,6 +383,8 @@ def main(argv):
a list of values, separated by a special token).
6. We do not provide any example here: please use --helpxml instead.
This module requires at least python 2.2.1 to run.
"""

import cgi
Expand All @@ -395,25 +396,6 @@ def main(argv):

import gflags_validators

# Are we running at least python 2.2?
try:
if tuple(sys.version_info[:3]) < (2,2,0):
raise NotImplementedError("requires python 2.2.0 or later")
except AttributeError: # a very old python, that lacks sys.version_info
raise NotImplementedError("requires python 2.2.0 or later")

# If we're not running at least python 2.2.1, define True, False, and bool.
# Thanks, Guido, for the code.
try:
True, False, bool
except NameError:
False = 0
True = 1
def bool(x):
if x:
return True
else:
return False

# Are we running under pychecker?
_RUNNING_PYCHECKER = 'pychecker.python' in sys.modules
Expand Down Expand Up @@ -1070,8 +1052,8 @@ def __delattr__(self, flag_name):
E.g.,
flags.DEFINE_integer('foo', 1, 'Integer flag.')
del flags.FLAGS.foo
gflags.DEFINE_integer('foo', 1, 'Integer flag.')
del gflags.FLAGS.foo
Args:
flag_name: A string, the name of the flag to be deleted.
Expand Down Expand Up @@ -1545,6 +1527,7 @@ def __GetFlagFileLines(self, filename, parsed_file_list):

def ReadFlagsFromFiles(self, argv, force_gnu=True):
"""Processes command line args, but also allow args to be read from file.
Args:
argv: A list of strings, usually sys.argv[1:], which may contain one or
more flagfile directives of the form --flagfile="./filename".
Expand Down Expand Up @@ -1617,8 +1600,8 @@ def FlagsIntoString(self):
This function ignores flags whose value is None. Each flag
assignment is separated by a newline.
NOTE: MUST mirror the behavior of the C++ function
CommandlineFlagsIntoString from google3/base/commandlineflags.cc.
NOTE: MUST mirror the behavior of the C++ CommandlineFlagsIntoString
from http://code.google.com/p/google-gflags
"""
s = ''
for flag in self.FlagDict().values():
Expand All @@ -1631,8 +1614,8 @@ def AppendFlagsIntoFile(self, filename):
Output will be in the format of a flagfile.
NOTE: MUST mirror the behavior of the C++ version of
AppendFlagsIntoFile from google3/base/commandlineflags.cc.
NOTE: MUST mirror the behavior of the C++ AppendFlagsIntoFile
from http://code.google.com/p/google-gflags
"""
out_file = open(filename, 'a')
out_file.write(self.FlagsIntoString())
Expand All @@ -1643,10 +1626,10 @@ def WriteHelpInXMLFormat(self, outfile=None):
NOTE: We use element names that are consistent with those used by
the C++ command-line flag library, from
google3/base/commandlineflags_reporting.cc. We also use a few new
elements (e.g., <key>), but we do not interfere / overlap with
existing XML elements used by the C++ library. Please maintain this
consistency.
http://code.google.com/p/google-gflags
We also use a few new elements (e.g., <key>), but we do not
interfere / overlap with existing XML elements used by the C++
library. Please maintain this consistency.
Args:
outfile: File object we write to. Default None means sys.stdout.
Expand Down Expand Up @@ -2023,8 +2006,8 @@ def RegisterValidator(flag_name,
AttributeError: if flag_name is not registered as a valid flag name.
"""
flag_values.AddValidator(gflags_validators.SimpleValidator(flag_name,
checker,
message))
checker,
message))


def MarkFlagAsRequired(flag_name, flag_values=FLAGS):
Expand Down Expand Up @@ -2162,7 +2145,7 @@ def DECLARE_key_flag(flag_name, flag_values=FLAGS):
Sample usage:
flags.DECLARED_key_flag('flag_1')
gflags.DECLARED_key_flag('flag_1')
Args:
flag_name: A string, the name of an already declared flag.
Expand Down Expand Up @@ -2232,7 +2215,7 @@ def DEFINE_string(name, default, help, flag_values=FLAGS, **args):
#
# BOOLEAN FLAGS
#
# and the special HELP flags.


class BooleanParser(ArgumentParser):
"""Parser of boolean values."""
Expand Down Expand Up @@ -2293,9 +2276,11 @@ def DEFINE_boolean(name, default, help, flag_values=FLAGS, **args):
"""
DEFINE_flag(BooleanFlag(name, default, help, **args), flag_values)


# Match C++ API to unconfuse C++ people.
DEFINE_bool = DEFINE_boolean


class HelpFlag(BooleanFlag):
"""
HelpFlag is a special boolean flag that prints usage information and
Expand All @@ -2315,22 +2300,16 @@ def Parse(self, arg):
print "flags:"
print flags
sys.exit(1)


class HelpXMLFlag(BooleanFlag):
"""Similar to HelpFlag, but generates output in XML format."""

def __init__(self):
BooleanFlag.__init__(self, 'helpxml', False,
'like --help, but generates XML output',
allow_override=1)

def Parse(self, arg):
if arg:
FLAGS.WriteHelpInXMLFormat(sys.stdout)
sys.exit(1)


class HelpshortFlag(BooleanFlag):
"""
HelpshortFlag is a special boolean flag that prints usage
Expand Down Expand Up @@ -2389,6 +2368,7 @@ def Convert(self, argument):
# FLOAT FLAGS
#


class FloatParser(NumericParser):
"""Parser of floating point values.
Expand Down
Loading

0 comments on commit 66a638a

Please sign in to comment.