Converted Django scripts to argparse

Refs #19973.
This commit is contained in:
Claude Paroz 2014-06-06 21:12:18 +02:00
parent 7018bcfb71
commit 96e4b52ab2
4 changed files with 59 additions and 75 deletions

View File

@ -1,6 +1,6 @@
#!/usr/bin/env python #!/usr/bin/env python
import argparse
import os import os
import optparse
import subprocess import subprocess
import sys import sys
@ -8,35 +8,37 @@ js_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'static', 'ad
def main(): def main():
usage = "usage: %prog [file1..fileN]"
description = """With no file paths given this script will automatically description = """With no file paths given this script will automatically
compress all jQuery-based files of the admin app. Requires the Google Closure compress all jQuery-based files of the admin app. Requires the Google Closure
Compiler library and Java version 6 or later.""" Compiler library and Java version 6 or later."""
parser = optparse.OptionParser(usage, description=description) parser = argparse.ArgumentParser(description=description)
parser.add_option("-c", dest="compiler", default="~/bin/compiler.jar", parser.add_argument('file', nargs='*')
parser.add_argument("-c", dest="compiler", default="~/bin/compiler.jar",
help="path to Closure Compiler jar file") help="path to Closure Compiler jar file")
parser.add_option("-v", "--verbose", parser.add_argument("-v", "--verbose",
action="store_true", dest="verbose") action="store_true", dest="verbose")
parser.add_option("-q", "--quiet", parser.add_argument("-q", "--quiet",
action="store_false", dest="verbose") action="store_false", dest="verbose")
(options, args) = parser.parse_args() options = parser.parse_args()
compiler = os.path.expanduser(options.compiler) compiler = os.path.expanduser(options.compiler)
if not os.path.exists(compiler): if not os.path.exists(compiler):
sys.exit("Google Closure compiler jar file %s not found. Please use the -c option to specify the path." % compiler) sys.exit("Google Closure compiler jar file %s not found. Please use the -c option to specify the path." % compiler)
if not args: if not options.file:
if options.verbose: if options.verbose:
sys.stdout.write("No filenames given; defaulting to admin scripts\n") sys.stdout.write("No filenames given; defaulting to admin scripts\n")
args = [os.path.join(js_path, f) for f in [ files = [os.path.join(js_path, f) for f in [
"actions.js", "collapse.js", "inlines.js", "prepopulate.js"]] "actions.js", "collapse.js", "inlines.js", "prepopulate.js"]]
else:
files = options.file
for arg in args: for file_name in files:
if not arg.endswith(".js"): if not file_name.endswith(".js"):
arg = arg + ".js" file_name = file_name + ".js"
to_compress = os.path.expanduser(arg) to_compress = os.path.expanduser(file_name)
if os.path.exists(to_compress): if os.path.exists(to_compress):
to_compress_min = "%s.min.js" % "".join(arg.rsplit(".js")) to_compress_min = "%s.min.js" % "".join(file_name.rsplit(".js"))
cmd = "java -jar %s --js %s --js_output_file %s" % (compiler, to_compress, to_compress_min) cmd = "java -jar %s --js %s --js_output_file %s" % (compiler, to_compress, to_compress_min)
if options.verbose: if options.verbose:
sys.stdout.write("Running: %s\n" % cmd) sys.stdout.write("Running: %s\n" % cmd)

View File

@ -112,25 +112,15 @@ PYTHON_ENCODING = "UTF-8"
# and fail to find real instances. # and fail to find real instances.
from argparse import ArgumentParser
import os import os
import sys import sys
import re import re
from optparse import OptionParser
USAGE = """ DESCRIPTION = """This tool helps to locate forms that need CSRF tokens added and the
This tool helps to locate forms that need CSRF tokens added and the
corresponding view code. This processing is NOT fool proof, and you should read corresponding view code. This processing is NOT fool proof, and you should read
the help contained in the script itself. Also, this script may need configuring the help contained in the script itself. Also, this script may need configuring
(by editing the script) before use. (by editing the script) before use."""
Usage:
python csrf_migration_helper.py [--settings=path.to.your.settings] /path/to/python/code [more paths...]
Paths can be specified as relative paths.
With no arguments, this help is printed.
"""
_POST_FORM_RE = \ _POST_FORM_RE = \
re.compile(r'(<form\W[^>]*\bmethod\s*=\s*(\'|"|)POST(\'|"|)\b[^>]*>)', re.IGNORECASE) re.compile(r'(<form\W[^>]*\bmethod\s*=\s*(\'|"|)POST(\'|"|)\b[^>]*>)', re.IGNORECASE)
@ -347,21 +337,20 @@ def main(pythonpaths):
print("----") print("----")
parser = OptionParser(usage=USAGE)
parser.add_option("", "--settings", action="store", dest="settings", help="Dotted path to settings file")
if __name__ == '__main__': if __name__ == '__main__':
options, args = parser.parse_args() parser = ArgumentParser(description=DESCRIPTION)
if len(args) == 0: parser.add_argument('files', nargs='*', help='Paths can be specified as relative paths.')
parser.add_argument("--settings", help="Dotted path to settings file")
options = parser.parse_args()
if len(options.files) == 0:
parser.print_help() parser.print_help()
sys.exit(1) sys.exit(1)
settings = getattr(options, 'settings', None) if options.settings is None:
if settings is None:
if os.environ.get("DJANGO_SETTINGS_MODULE", None) is None: if os.environ.get("DJANGO_SETTINGS_MODULE", None) is None:
print("You need to set DJANGO_SETTINGS_MODULE or use the '--settings' parameter") print("You need to set DJANGO_SETTINGS_MODULE or use the '--settings' parameter")
sys.exit(1) sys.exit(1)
else: else:
os.environ["DJANGO_SETTINGS_MODULE"] = settings os.environ["DJANGO_SETTINGS_MODULE"] = settings
main(args) main(options.files)

View File

@ -18,8 +18,8 @@
# #
# $ python scripts/manage_translations.py lang_stats --language=es --resources=admin # $ python scripts/manage_translations.py lang_stats --language=es --resources=admin
from argparse import ArgumentParser
import os import os
from optparse import OptionParser
from subprocess import call, Popen, PIPE from subprocess import call, Popen, PIPE
from django.core.management import call_command from django.core.management import call_command
@ -167,18 +167,15 @@ def fetch(resources=None, languages=None):
if __name__ == "__main__": if __name__ == "__main__":
RUNABLE_SCRIPTS = ('update_catalogs', 'lang_stats', 'fetch') RUNABLE_SCRIPTS = ('update_catalogs', 'lang_stats', 'fetch')
parser = OptionParser(usage="usage: %prog [options] cmd") parser = ArgumentParser()
parser.add_option("-r", "--resources", action='append', parser.add_argument('cmd', nargs=1)
parser.add_argument("-r", "--resources", action='append',
help="limit operation to the specified resources") help="limit operation to the specified resources")
parser.add_option("-l", "--languages", action='append', parser.add_argument("-l", "--languages", action='append',
help="limit operation to the specified languages") help="limit operation to the specified languages")
options, args = parser.parse_args() options = parser.parse_args()
if not args: if options.cmd[0] in RUNABLE_SCRIPTS:
parser.print_usage() eval(options.cmd[0])(options.resources, options.languages)
exit(1)
if args[0] in RUNABLE_SCRIPTS:
eval(args[0])(options.resources, options.languages)
else: else:
print("Available commands are: %s" % ", ".join(RUNABLE_SCRIPTS)) print("Available commands are: %s" % ", ".join(RUNABLE_SCRIPTS))

View File

@ -1,6 +1,6 @@
#!/usr/bin/env python #!/usr/bin/env python
from argparse import ArgumentParser
import logging import logging
from optparse import OptionParser
import os import os
import shutil import shutil
import subprocess import subprocess
@ -213,7 +213,7 @@ def django_tests(verbosity, interactive, failfast, test_labels):
def bisect_tests(bisection_label, options, test_labels): def bisect_tests(bisection_label, options, test_labels):
state = setup(int(options.verbosity), test_labels) state = setup(options.verbosity, test_labels)
test_labels = test_labels or get_installed() test_labels = test_labels or get_installed()
@ -271,7 +271,7 @@ def bisect_tests(bisection_label, options, test_labels):
def paired_tests(paired_test, options, test_labels): def paired_tests(paired_test, options, test_labels):
state = setup(int(options.verbosity), test_labels) state = setup(options.verbosity, test_labels)
test_labels = test_labels or get_installed() test_labels = test_labels or get_installed()
@ -307,43 +307,39 @@ def paired_tests(paired_test, options, test_labels):
if __name__ == "__main__": if __name__ == "__main__":
usage = "%prog [options] [module module module ...]" parser = ArgumentParser(description="Run the Django test suite.")
parser = OptionParser(usage=usage) parser.add_argument('modules', nargs='*', metavar='module',
parser.add_option( help='Optional path(s) to test modules; e.g. "i18n" or '
'-v', '--verbosity', action='store', dest='verbosity', default='1', '"i18n.tests.TranslationTests.test_lazy_objects".')
type='choice', choices=['0', '1', '2', '3'], parser.add_argument(
help='Verbosity level; 0=minimal output, 1=normal output, 2=all ' '-v', '--verbosity', default=1, type=int, choices=[0, 1, 2, 3],
'output') help='Verbosity level; 0=minimal output, 1=normal output, 2=all output')
parser.add_option( parser.add_argument(
'--noinput', action='store_false', dest='interactive', default=True, '--noinput', action='store_false', dest='interactive', default=True,
help='Tells Django to NOT prompt the user for input of any kind.') help='Tells Django to NOT prompt the user for input of any kind.')
parser.add_option( parser.add_argument(
'--failfast', action='store_true', dest='failfast', default=False, '--failfast', action='store_true', dest='failfast', default=False,
help='Tells Django to stop running the test suite after first failed ' help='Tells Django to stop running the test suite after first failed '
'test.') 'test.')
parser.add_option( parser.add_argument(
'--settings', '--settings',
help='Python path to settings module, e.g. "myproject.settings". If ' help='Python path to settings module, e.g. "myproject.settings". If '
'this isn\'t provided, the DJANGO_SETTINGS_MODULE environment ' 'this isn\'t provided, either the DJANGO_SETTINGS_MODULE '
'variable will be used.') 'environment variable or "test_sqlite" will be used.')
parser.add_option( parser.add_argument('--bisect',
'--bisect', action='store', dest='bisect', default=None,
help='Bisect the test suite to discover a test that causes a test ' help='Bisect the test suite to discover a test that causes a test '
'failure when combined with the named test.') 'failure when combined with the named test.')
parser.add_option( parser.add_argument('--pair',
'--pair', action='store', dest='pair', default=None,
help='Run the test suite in pairs with the named test to find problem ' help='Run the test suite in pairs with the named test to find problem '
'pairs.') 'pairs.')
parser.add_option( parser.add_argument('--liveserver',
'--liveserver', action='store', dest='liveserver', default=None,
help='Overrides the default address where the live server (used with ' help='Overrides the default address where the live server (used with '
'LiveServerTestCase) is expected to run from. The default value ' 'LiveServerTestCase) is expected to run from. The default value '
'is localhost:8081.') 'is localhost:8081.')
parser.add_option( parser.add_argument(
'--selenium', action='store_true', dest='selenium', '--selenium', action='store_true', dest='selenium', default=False,
default=False,
help='Run the Selenium tests as well (if Selenium is installed)') help='Run the Selenium tests as well (if Selenium is installed)')
options, args = parser.parse_args() options = parser.parse_args()
if options.settings: if options.settings:
os.environ['DJANGO_SETTINGS_MODULE'] = options.settings os.environ['DJANGO_SETTINGS_MODULE'] = options.settings
else: else:
@ -358,11 +354,11 @@ if __name__ == "__main__":
os.environ['DJANGO_SELENIUM_TESTS'] = '1' os.environ['DJANGO_SELENIUM_TESTS'] = '1'
if options.bisect: if options.bisect:
bisect_tests(options.bisect, options, args) bisect_tests(options.bisect, options, options.modules)
elif options.pair: elif options.pair:
paired_tests(options.pair, options, args) paired_tests(options.pair, options, options.modules)
else: else:
failures = django_tests(int(options.verbosity), options.interactive, failures = django_tests(options.verbosity, options.interactive,
options.failfast, args) options.failfast, options.modules)
if failures: if failures:
sys.exit(bool(failures)) sys.exit(bool(failures))