From 96e4b52ab2c6fae3e46a197d44c42cb6ebde7d9c Mon Sep 17 00:00:00 2001 From: Claude Paroz Date: Fri, 6 Jun 2014 21:12:18 +0200 Subject: [PATCH] Converted Django scripts to argparse Refs #19973. --- django/contrib/admin/bin/compress.py | 30 ++++++++-------- extras/csrf_migration_helper.py | 31 ++++++---------- scripts/manage_translations.py | 19 +++++----- tests/runtests.py | 54 +++++++++++++--------------- 4 files changed, 59 insertions(+), 75 deletions(-) diff --git a/django/contrib/admin/bin/compress.py b/django/contrib/admin/bin/compress.py index 7e5d4ea779..f21972708f 100644 --- a/django/contrib/admin/bin/compress.py +++ b/django/contrib/admin/bin/compress.py @@ -1,6 +1,6 @@ #!/usr/bin/env python +import argparse import os -import optparse import subprocess import sys @@ -8,35 +8,37 @@ js_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'static', 'ad def main(): - usage = "usage: %prog [file1..fileN]" description = """With no file paths given this script will automatically compress all jQuery-based files of the admin app. Requires the Google Closure Compiler library and Java version 6 or later.""" - parser = optparse.OptionParser(usage, description=description) - parser.add_option("-c", dest="compiler", default="~/bin/compiler.jar", + parser = argparse.ArgumentParser(description=description) + parser.add_argument('file', nargs='*') + parser.add_argument("-c", dest="compiler", default="~/bin/compiler.jar", help="path to Closure Compiler jar file") - parser.add_option("-v", "--verbose", + parser.add_argument("-v", "--verbose", action="store_true", dest="verbose") - parser.add_option("-q", "--quiet", + parser.add_argument("-q", "--quiet", action="store_false", dest="verbose") - (options, args) = parser.parse_args() + options = parser.parse_args() compiler = os.path.expanduser(options.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) - if not args: + if not options.file: if options.verbose: 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"]] + else: + files = options.file - for arg in args: - if not arg.endswith(".js"): - arg = arg + ".js" - to_compress = os.path.expanduser(arg) + for file_name in files: + if not file_name.endswith(".js"): + file_name = file_name + ".js" + to_compress = os.path.expanduser(file_name) 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) if options.verbose: sys.stdout.write("Running: %s\n" % cmd) diff --git a/extras/csrf_migration_helper.py b/extras/csrf_migration_helper.py index 9e7b04b85b..e7df65d056 100755 --- a/extras/csrf_migration_helper.py +++ b/extras/csrf_migration_helper.py @@ -112,25 +112,15 @@ PYTHON_ENCODING = "UTF-8" # and fail to find real instances. +from argparse import ArgumentParser import os import sys import re -from optparse import OptionParser -USAGE = """ -This tool helps to locate forms that need CSRF tokens added and the +DESCRIPTION = """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 the help contained in the script itself. Also, this script may need configuring -(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. -""" +(by editing the script) before use.""" _POST_FORM_RE = \ re.compile(r'(]*\bmethod\s*=\s*(\'|"|)POST(\'|"|)\b[^>]*>)', re.IGNORECASE) @@ -347,21 +337,20 @@ def main(pythonpaths): print("----") -parser = OptionParser(usage=USAGE) -parser.add_option("", "--settings", action="store", dest="settings", help="Dotted path to settings file") - if __name__ == '__main__': - options, args = parser.parse_args() - if len(args) == 0: + parser = ArgumentParser(description=DESCRIPTION) + 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() sys.exit(1) - settings = getattr(options, 'settings', None) - if settings is None: + if options.settings 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") sys.exit(1) else: os.environ["DJANGO_SETTINGS_MODULE"] = settings - main(args) + main(options.files) diff --git a/scripts/manage_translations.py b/scripts/manage_translations.py index 9bc7c571d9..bedb3d82b3 100644 --- a/scripts/manage_translations.py +++ b/scripts/manage_translations.py @@ -18,8 +18,8 @@ # # $ python scripts/manage_translations.py lang_stats --language=es --resources=admin +from argparse import ArgumentParser import os -from optparse import OptionParser from subprocess import call, Popen, PIPE from django.core.management import call_command @@ -167,18 +167,15 @@ def fetch(resources=None, languages=None): if __name__ == "__main__": RUNABLE_SCRIPTS = ('update_catalogs', 'lang_stats', 'fetch') - parser = OptionParser(usage="usage: %prog [options] cmd") - parser.add_option("-r", "--resources", action='append', + parser = ArgumentParser() + parser.add_argument('cmd', nargs=1) + parser.add_argument("-r", "--resources", action='append', 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") - options, args = parser.parse_args() + options = parser.parse_args() - if not args: - parser.print_usage() - exit(1) - - if args[0] in RUNABLE_SCRIPTS: - eval(args[0])(options.resources, options.languages) + if options.cmd[0] in RUNABLE_SCRIPTS: + eval(options.cmd[0])(options.resources, options.languages) else: print("Available commands are: %s" % ", ".join(RUNABLE_SCRIPTS)) diff --git a/tests/runtests.py b/tests/runtests.py index 04c0d6a02f..61e90e3845 100755 --- a/tests/runtests.py +++ b/tests/runtests.py @@ -1,6 +1,6 @@ #!/usr/bin/env python +from argparse import ArgumentParser import logging -from optparse import OptionParser import os import shutil import subprocess @@ -213,7 +213,7 @@ def django_tests(verbosity, interactive, failfast, 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() @@ -271,7 +271,7 @@ def bisect_tests(bisection_label, 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() @@ -307,43 +307,39 @@ def paired_tests(paired_test, options, test_labels): if __name__ == "__main__": - usage = "%prog [options] [module module module ...]" - parser = OptionParser(usage=usage) - parser.add_option( - '-v', '--verbosity', action='store', dest='verbosity', default='1', - type='choice', choices=['0', '1', '2', '3'], - help='Verbosity level; 0=minimal output, 1=normal output, 2=all ' - 'output') - parser.add_option( + parser = ArgumentParser(description="Run the Django test suite.") + parser.add_argument('modules', nargs='*', metavar='module', + help='Optional path(s) to test modules; e.g. "i18n" or ' + '"i18n.tests.TranslationTests.test_lazy_objects".') + parser.add_argument( + '-v', '--verbosity', default=1, type=int, choices=[0, 1, 2, 3], + help='Verbosity level; 0=minimal output, 1=normal output, 2=all output') + parser.add_argument( '--noinput', action='store_false', dest='interactive', default=True, 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, help='Tells Django to stop running the test suite after first failed ' 'test.') - parser.add_option( + parser.add_argument( '--settings', help='Python path to settings module, e.g. "myproject.settings". If ' - 'this isn\'t provided, the DJANGO_SETTINGS_MODULE environment ' - 'variable will be used.') - parser.add_option( - '--bisect', action='store', dest='bisect', default=None, + 'this isn\'t provided, either the DJANGO_SETTINGS_MODULE ' + 'environment variable or "test_sqlite" will be used.') + parser.add_argument('--bisect', help='Bisect the test suite to discover a test that causes a test ' 'failure when combined with the named test.') - parser.add_option( - '--pair', action='store', dest='pair', default=None, + parser.add_argument('--pair', help='Run the test suite in pairs with the named test to find problem ' 'pairs.') - parser.add_option( - '--liveserver', action='store', dest='liveserver', default=None, + parser.add_argument('--liveserver', help='Overrides the default address where the live server (used with ' 'LiveServerTestCase) is expected to run from. The default value ' 'is localhost:8081.') - parser.add_option( - '--selenium', action='store_true', dest='selenium', - default=False, + parser.add_argument( + '--selenium', action='store_true', dest='selenium', default=False, help='Run the Selenium tests as well (if Selenium is installed)') - options, args = parser.parse_args() + options = parser.parse_args() if options.settings: os.environ['DJANGO_SETTINGS_MODULE'] = options.settings else: @@ -358,11 +354,11 @@ if __name__ == "__main__": os.environ['DJANGO_SELENIUM_TESTS'] = '1' if options.bisect: - bisect_tests(options.bisect, options, args) + bisect_tests(options.bisect, options, options.modules) elif options.pair: - paired_tests(options.pair, options, args) + paired_tests(options.pair, options, options.modules) else: - failures = django_tests(int(options.verbosity), options.interactive, - options.failfast, args) + failures = django_tests(options.verbosity, options.interactive, + options.failfast, options.modules) if failures: sys.exit(bool(failures))