[devscripts] 01/03: Fix all pylint3 issues
Benjamin Drung
bdrung at moszumanska.debian.org
Sun Feb 4 22:45:11 UTC 2018
This is an automated email from the git hooks/post-receive script.
bdrung pushed a commit to branch master
in repository devscripts.
commit 5b9506ac4a5ec73e0cc14ba227d8938e8bd4d15c
Author: Benjamin Drung <bdrung at debian.org>
Date: Sun Feb 4 22:49:16 2018 +0100
Fix all pylint3 issues
Signed-off-by: Benjamin Drung <bdrung at debian.org>
---
scripts/debdiff-apply | 73 ++++++++++---------
scripts/devscripts/test/__init__.py | 8 ++
scripts/devscripts/test/test_help.py | 8 +-
scripts/devscripts/test/test_pylint.py | 6 +-
scripts/reproducible-check | 26 ++++---
scripts/sadt | 20 ++---
scripts/setup.py | 27 ++++---
scripts/suspicious-source | 59 +++++++--------
scripts/wrap-and-sort | 129 ++++++++++++++++-----------------
9 files changed, 185 insertions(+), 171 deletions(-)
diff --git a/scripts/debdiff-apply b/scripts/debdiff-apply
index 1f7b0e8..2b2a613 100755
--- a/scripts/debdiff-apply
+++ b/scripts/debdiff-apply
@@ -26,18 +26,15 @@ import email.utils
import hashlib
import logging
import os
-import unidiff
import shutil
import subprocess
import sys
import tempfile
import time
-from debian.changelog import Changelog, ChangeBlock
+import unidiff
-dirname = os.path.dirname
-basename = os.path.basename
-C = subprocess.check_call
+from debian.changelog import Changelog, ChangeBlock
# this can be any valid value, it doesn't appear in the final output
DCH_DUMMY_TAIL = "\n -- debdiff-apply dummy tool <infinity0 at debian.org> " \
@@ -48,15 +45,16 @@ DISTRIBUTION_DEFAULT = "experimental"
def workaround_dpkg_865430(dscfile, origdir, stdout):
- f = subprocess.check_output(["dcmd", "--tar", "echo", dscfile]).rstrip()
- if not os.path.exists(os.path.join(origdir.encode("utf-8"), os.path.basename(f))):
- C(["dcmd", "--tar", "cp", dscfile, origdir], stdout=stdout)
+ filename = subprocess.check_output(["dcmd", "--tar", "echo", dscfile]).rstrip()
+ if not os.path.exists(os.path.join(origdir.encode("utf-8"), os.path.basename(filename))):
+ subprocess.check_call(["dcmd", "--tar", "cp", dscfile, origdir], stdout=stdout)
def is_dch(path):
- return (basename(path) == 'changelog'
- and basename(dirname(path)) == 'debian'
- and dirname(dirname(dirname(path))) == '')
+ dirname = os.path.dirname(path)
+ return (os.path.basename(path) == 'changelog'
+ and os.path.basename(dirname) == 'debian'
+ and os.path.dirname(os.path.dirname(dirname)) == '')
def hunk_lines_to_str(hunk_lines):
@@ -77,15 +75,16 @@ def read_dch_patch(dch_patch):
return source_version, target
-def apply_dch_patch(source_file, current, patch_name, old_version, target, dry_run):
+def apply_dch_patch(source_file, current, old_version, target, dry_run):
target_version = str(target.version)
if not old_version or not target_version.startswith(old_version):
- logging.warn("don't know how to rebase version-change (%s => %s) onto %s" %
- (old_version, target_version, old_version))
+ logging.warning("don't know how to rebase version-change (%s => %s) onto %s",
+ old_version, target_version, old_version)
newlog = subprocess.getoutput("EDITOR=cat dch -n 2>/dev/null").rstrip()
version = str(Changelog(newlog, 1)[0].version)
- logging.warn("using version %s based on `dch -n`; feel free to make me smarter", version)
+ logging.warning("using version %s based on `dch -n`; feel free to make me smarter",
+ version)
else:
version_suffix = target_version[len(old_version):]
version = str(current[0].version) + version_suffix
@@ -94,7 +93,7 @@ def apply_dch_patch(source_file, current, patch_name, old_version, target, dry_r
if dry_run:
return version
- current._blocks.insert(0, target)
+ current._blocks.insert(0, target) # pylint: disable=protected-access
current.set_version(version)
shutil.copy(source_file, source_file + ".new")
@@ -103,10 +102,11 @@ def apply_dch_patch(source_file, current, patch_name, old_version, target, dry_r
current.write_to_open_file(fp)
os.rename(source_file + ".new", source_file)
except Exception:
- logging.warn("failed to patch %s", source_file)
- logging.warn("half-applied changes in %s", source_file + ".new")
- logging.warn("current working directory is %s", os.getcwd())
+ logging.warning("failed to patch %s", source_file)
+ logging.warning("half-applied changes in %s", source_file + ".new")
+ logging.warning("current working directory is %s", os.getcwd())
raise
+ return version
def call_patch(patch_str, *args, check=True, **kwargs):
@@ -134,7 +134,7 @@ def debdiff_apply(patch, patch_name, args):
changelog = list(filter(lambda x: is_dch(x.path), patch))
if not changelog:
- logging.info("no debian/changelog in patch: %s" % args.patch_file)
+ logging.info("no debian/changelog in patch: %s", args.patch_file)
old_version = None
target = ChangeBlock(
package=CHBLOCK_DUMMY_PACKAGE,
@@ -169,15 +169,14 @@ def debdiff_apply(patch, patch_name, args):
call_patch(patch_str)
logging.info("patch %s applies!", patch_name)
elif check_patch(patch_str, "-R"):
- logging.warn("patch %s already applied", patch_name)
+ logging.warning("patch %s already applied", patch_name)
return False
else:
call_patch(patch_str, "--dry-run", "-f")
- raise ValueError("patch %s doesn't apply!", patch_name)
+ raise ValueError("patch %s doesn't apply!" % (patch_name))
# only apply d/changelog patch if the rest of the patch applied
- new_version = apply_dch_patch(args.changelog, current, patch_name,
- old_version, target, dry_run)
+ new_version = apply_dch_patch(args.changelog, current, old_version, target, dry_run)
if args.target_version:
print(new_version)
return False
@@ -189,7 +188,7 @@ def debdiff_apply(patch, patch_name, args):
return True
-def main(args):
+def parse_args(args):
parser = argparse.ArgumentParser(
description='Apply a debdiff to a Debian source package')
parser.add_argument(
@@ -250,8 +249,12 @@ def main(args):
"after debdiff-apply(1) exits. If not given, then it will be extracted to a "
"temporary directory.",
)
- args = parser.parse_args(args)
+ return parser.parse_args(args)
+
+def main(args):
+ # Split this function! pylint: disable=too-many-branches,too-many-locals,too-many-statements
+ args = parse_args(args)
if args.verbose:
logging.getLogger().setLevel(logging.DEBUG)
@@ -261,14 +264,14 @@ def main(args):
try:
patch = unidiff.PatchSet(data.splitlines(keepends=True), encoding=enc)
break
- except Exception:
+ except Exception: # pylint: disable=broad-except
if enc == TRY_ENCODINGS[-1]:
raise
else:
continue
patch_name = '%s:%s' % (
- basename(args.patch_file),
+ os.path.basename(args.patch_file),
hashlib.sha256(data).hexdigest()[:20 if args.patch_file == '/dev/stdin' else 8])
quiet = args.source_version or args.target_version
dry_run = args.source_version or args.target_version
@@ -288,7 +291,8 @@ def main(args):
os.makedirs(extractdir)
try:
builddir = os.path.join(extractdir, parts[0]) # dpkg-source doesn't like existing dirs
- C(["dpkg-source", "-x", "--skip-patches", dscfile, builddir], stdout=stdout)
+ subprocess.check_call(["dpkg-source", "-x", "--skip-patches", dscfile, builddir],
+ stdout=stdout)
origdir = os.getcwd()
workaround_dpkg_865430(dscfile, origdir, stdout)
os.chdir(builddir)
@@ -297,22 +301,21 @@ def main(args):
return
os.chdir(origdir)
try:
- C(["dpkg-source", "-b", builddir])
+ subprocess.check_call(["dpkg-source", "-b", builddir])
except subprocess.CalledProcessError:
if args.quilt_refresh:
- C(["sh", "-c", """
+ subprocess.check_call(["sh", "-c", """
set -ex
export QUILT_PATCHES=debian/patches
while quilt push; do quilt refresh; done
-"""
- ], cwd=builddir)
- C(["dpkg-source", "-b", builddir])
+"""], cwd=builddir)
+ subprocess.check_call(["dpkg-source", "-b", builddir])
else:
raise
finally:
cleandir = builddir if args.directory else extractdir
if args.no_clean:
- logging.warn("you should clean up temp files in %s", cleandir)
+ logging.warning("you should clean up temp files in %s", cleandir)
else:
shutil.rmtree(cleandir)
diff --git a/scripts/devscripts/test/__init__.py b/scripts/devscripts/test/__init__.py
index f19955c..3de1e9e 100644
--- a/scripts/devscripts/test/__init__.py
+++ b/scripts/devscripts/test/__init__.py
@@ -22,6 +22,14 @@ if sys.version_info < (2, 7):
else:
import unittest
+SCRIPTS = [
+ "debdiff-apply",
+ "reproducible-check",
+ "sadt",
+ "suspicious-source",
+ "wrap-and-sort",
+]
+
def discover():
# import __main__ triggers code re-execution
diff --git a/scripts/devscripts/test/test_help.py b/scripts/devscripts/test/test_help.py
index 33ceb03..42a7d10 100644
--- a/scripts/devscripts/test/test_help.py
+++ b/scripts/devscripts/test/test_help.py
@@ -20,14 +20,14 @@ import select
import signal
import subprocess
import time
+import unittest
-import setup
-from devscripts.test import unittest
+from . import SCRIPTS
TIMEOUT = 5
-def load_tests(loader, tests, pattern):
+def load_tests(loader, tests, pattern): # pylint: disable=unused-argument
"Give HelpTestCase a chance to populate before loading its test cases"
suite = unittest.TestSuite()
HelpTestCase.populate()
@@ -38,7 +38,7 @@ def load_tests(loader, tests, pattern):
class HelpTestCase(unittest.TestCase):
@classmethod
def populate(cls):
- for script in setup.scripts:
+ for script in SCRIPTS:
setattr(cls, 'test_' + script, cls.make_help_tester(script))
@classmethod
diff --git a/scripts/devscripts/test/test_pylint.py b/scripts/devscripts/test/test_pylint.py
index 33b0b9c..591dfe0 100644
--- a/scripts/devscripts/test/test_pylint.py
+++ b/scripts/devscripts/test/test_pylint.py
@@ -16,9 +16,9 @@
import re
import subprocess
+import unittest
-import setup
-from devscripts.test import unittest
+from . import SCRIPTS
WHITELIST = [re.compile(': %s$' % x) for x in (
# Wildcard import:
@@ -35,7 +35,7 @@ class PylintTestCase(unittest.TestCase):
def test_pylint(self):
"Test: Run pylint on Python source code"
files = ['devscripts']
- for script in setup.scripts:
+ for script in SCRIPTS:
f = open(script, 'r', encoding='utf-8')
if 'python' in f.readline():
files.append(script)
diff --git a/scripts/reproducible-check b/scripts/reproducible-check
index eed705a..852731a 100755
--- a/scripts/reproducible-check
+++ b/scripts/reproducible-check
@@ -15,16 +15,17 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
-import os
+import argparse
import bz2
-import apt
-import sys
+import collections
import json
-import time
import logging
+import os
+import sys
+import time
+
+import apt
import requests
-import argparse
-import collections
try:
from xdg.BaseDirectory import xdg_cache_home
@@ -138,7 +139,8 @@ class ReproducibleCheck(object):
if y['status'] == 'unreproducible'
}
- def get_installed_packages(self):
+ @staticmethod
+ def get_installed_packages():
result = collections.defaultdict(list)
for x in apt.Cache():
@@ -151,7 +153,8 @@ class ReproducibleCheck(object):
return result
- def output_by_source(self, unreproducible, installed):
+ @staticmethod
+ def output_by_source(unreproducible, installed):
num_installed = sum(len(x) for x in installed.keys())
num_unreproducible = sum(len(x) for x in unreproducible.keys())
default_architecture = apt.apt_pkg.config.find('APT::Architecture')
@@ -173,14 +176,15 @@ class ReproducibleCheck(object):
source,
))
- x = "{}/{} ({:.2f}%) of installed binary packages are unreproducible."
- print(x.format(
+ msg = "{}/{} ({:.2f}%) of installed binary packages are unreproducible."
+ print(msg.format(
num_unreproducible,
num_installed,
100. * num_unreproducible / num_installed,
))
- def output_raw(self, unreproducible, installed):
+ @staticmethod
+ def output_raw(unreproducible, installed): # pylint: disable=unused-argument
for x in sorted(x for xs in unreproducible.values() for x in set(xs)):
print(x)
diff --git a/scripts/sadt b/scripts/sadt
index 32fb57a..cb96c5a 100755
--- a/scripts/sadt
+++ b/scripts/sadt
@@ -99,7 +99,8 @@ class Progress(object):
else:
self._back = ''
- def _write(self, s):
+ @staticmethod
+ def _write(s):
sys.stdout.write(s)
sys.stdout.flush()
@@ -172,6 +173,7 @@ class TestGroup(object):
self.depends = '@'
self.tests_directory = 'debian/tests'
self._check_depends_cache = None
+ self._depends_cache = None
def __iter__(self):
return iter(self.tests)
@@ -211,7 +213,7 @@ class TestGroup(object):
def check_depends(self):
if self._check_depends_cache is not None:
if isinstance(self._depends_cache, Exception):
- raise self._check_depends_cache
+ raise self._check_depends_cache # false positive, pylint: disable=raising-bad-type
return
child = ipc.Popen(['dpkg-checkbuilddeps', '-d', self.depends], stderr=ipc.PIPE, env={})
error = child.stderr.read().decode('ASCII')
@@ -229,7 +231,7 @@ class TestGroup(object):
def check_restrictions(self, ignored_restrictions):
restrictions = self.restrictions - frozenset(ignored_restrictions)
- class Options:
+ class Options: # pylint: disable=too-few-public-methods
rw_build_tree_needed = False
allow_stderr = False
for r in restrictions:
@@ -289,7 +291,7 @@ class TestGroup(object):
if cwd is not None:
os.chdir(cwd)
- def _run(self, test, progress, allow_stderr=False):
+ def _run(self, test, progress, allow_stderr=False): # pylint: disable=too-many-locals
path = os.path.join(self.tests_directory, test)
tmpdir1 = tempfile.mkdtemp(prefix='sadt.')
tmpdir2 = tempfile.mkdtemp(prefix='sadt.')
@@ -352,10 +354,9 @@ def copy_build_tree():
def main():
- for description in __doc__.splitlines():
- if description:
- break
- parser = argparse.ArgumentParser(description=description)
+ # TODO: refactor main function
+ # pylint: disable=too-many-branches,too-many-statements,too-many-locals,too-many-nested-blocks
+ parser = argparse.ArgumentParser(description=__doc__.strip())
parser.add_argument('-v', '--verbose', action='store_true', help='verbose output')
parser.add_argument('-b', '--built-source-tree', action='store_true',
help='assume built source tree')
@@ -377,7 +378,8 @@ def main():
with file:
for n, para in enumerate(deb822.Packages.iter_paragraphs(file)):
if n == 0:
- para['Source']
+ # FIXME statement with no effect
+ # para['Source']
for field in 'Build-Depends', 'Build-Depends-Indep':
try:
build_depends += deb822.PkgRelation.parse_relations(para[field])
diff --git a/scripts/setup.py b/scripts/setup.py
index 091e4d3..b0e7bd2 100755
--- a/scripts/setup.py
+++ b/scripts/setup.py
@@ -1,24 +1,29 @@
#!/usr/bin/python3
-from setuptools import setup
import os
import re
-# look/set what version we have
-changelog = "../debian/changelog"
-if os.path.exists(changelog):
- head = open(changelog, encoding="utf8").readline()
- match = re.compile(".*\((.*)\).*").match(head)
- if match:
- version = match.group(1)
+from setuptools import setup
+
+from devscripts.test import SCRIPTS
+
+
+def get_version():
+ # look/set what version we have
+ changelog = "../debian/changelog"
+ if os.path.exists(changelog):
+ head = open(changelog, encoding="utf8").readline()
+ match = re.compile(r".*\((.*)\).*").match(head)
+ if match:
+ return match.group(1)
+ raise Exception("Failed to determine version from debian/changelog")
-scripts = "debdiff-apply sadt suspicious-source wrap-and-sort reproducible-check".split()
if __name__ == '__main__':
setup(
name='devscripts',
- version=version,
- scripts=scripts,
+ version=get_version(),
+ scripts=SCRIPTS,
packages=['devscripts', 'devscripts/test'],
test_suite='devscripts.test.discover',
)
diff --git a/scripts/suspicious-source b/scripts/suspicious-source
index c860b10..27b69f6 100755
--- a/scripts/suspicious-source
+++ b/scripts/suspicious-source
@@ -1,6 +1,6 @@
#!/usr/bin/python3
-# Copyright (c) 2010-2014, Benjamin Drung <bdrung at debian.org>
+# Copyright (c) 2010-2018, Benjamin Drung <bdrung at debian.org>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
@@ -14,7 +14,7 @@
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-import optparse
+import argparse
import os
import sys
@@ -109,12 +109,12 @@ def suspicious_source(whitelisted_mimetypes, whitelisted_extensions, directory,
magic_cookie.load()
for root, dirs, files in os.walk(directory):
- for f in files:
- mimetype = magic_cookie.file(os.path.join(root, f))
+ for _file in files:
+ mimetype = magic_cookie.file(os.path.join(root, _file))
if mimetype not in whitelisted_mimetypes:
if not [x for x in whitelisted_extensions
- if f.lower().endswith(x)]:
- output = os.path.join(root, f)
+ if _file.lower().endswith(x)]:
+ output = os.path.join(root, _file)
if verbose:
output += " (" + mimetype + ")"
print(output)
@@ -125,33 +125,28 @@ def suspicious_source(whitelisted_mimetypes, whitelisted_extensions, directory,
def main():
script_name = os.path.basename(sys.argv[0])
- usage = "%s [options]" % (script_name)
epilog = "See %s(1) for more info." % (script_name)
- parser = optparse.OptionParser(usage=usage, epilog=epilog)
-
- parser.add_option("-v", "--verbose", help="print more information",
- dest="verbose", action="store_true", default=False)
- parser.add_option("-d", "--directory",
- help="check the files in the specified directory",
- dest="directory", default=".")
- parser.add_option("-m", "--mimetype", metavar="MIMETYPE",
- help="Add MIMETYPE to list of whitelisted mimetypes.",
- dest="whitelisted_mimetypes", action="append",
- default=DEFAULT_WHITELISTED_MIMETYPES)
- parser.add_option("-e", "--extension", metavar="EXTENSION",
- help="Add EXTENSION to list of whitelisted extensions.",
- dest="whitelisted_extensions", action="append",
- default=DEFAULT_WHITELISTED_EXTENSIONS)
-
- (options, args) = parser.parse_args()
-
- if len(args) != 0:
- Logger.error("This script does not take any additional parameters.")
- sys.exit(1)
-
- whitelisted_extensions = [x.lower() for x in options.whitelisted_extensions]
- suspicious_source(options.whitelisted_mimetypes, whitelisted_extensions,
- options.directory, options.verbose)
+ parser = argparse.ArgumentParser(epilog=epilog)
+
+ parser.add_argument("-v", "--verbose", help="print more information",
+ dest="verbose", action="store_true", default=False)
+ parser.add_argument("-d", "--directory",
+ help="check the files in the specified directory",
+ dest="directory", default=".")
+ parser.add_argument("-m", "--mimetype", metavar="MIMETYPE",
+ help="Add MIMETYPE to list of whitelisted mimetypes.",
+ dest="whitelisted_mimetypes", action="append",
+ default=DEFAULT_WHITELISTED_MIMETYPES)
+ parser.add_argument("-e", "--extension", metavar="EXTENSION",
+ help="Add EXTENSION to list of whitelisted extensions.",
+ dest="whitelisted_extensions", action="append",
+ default=DEFAULT_WHITELISTED_EXTENSIONS)
+
+ args = parser.parse_args()
+
+ whitelisted_extensions = [x.lower() for x in args.whitelisted_extensions]
+ suspicious_source(args.whitelisted_mimetypes, whitelisted_extensions,
+ args.directory, args.verbose)
if __name__ == "__main__":
diff --git a/scripts/wrap-and-sort b/scripts/wrap-and-sort
index 4d1d24d..dfbee29 100755
--- a/scripts/wrap-and-sort
+++ b/scripts/wrap-and-sort
@@ -1,6 +1,6 @@
#!/usr/bin/python3
#
-# Copyright (C) 2010-2016, Benjamin Drung <bdrung at debian.org>
+# Copyright (C) 2010-2018, Benjamin Drung <bdrung at debian.org>
# 2010, Stefano Rivera <stefanor at ubuntu.com>
#
# Permission to use, copy, modify, and/or distribute this software for any
@@ -15,9 +15,9 @@
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+import argparse
import glob
import operator
-import optparse
import os
import re
import sys
@@ -76,6 +76,7 @@ class WrapAndSortControl(Control):
def wrap_and_sort(self, wrap_always, short_indent, sort_paragraphs,
keep_first, trailing_comma):
+ # pylint: disable=too-many-arguments
for paragraph in self.paragraphs:
for field in CONTROL_LIST_FIELDS:
if field in paragraph:
@@ -97,6 +98,7 @@ class WrapAndSortControl(Control):
def _wrap_field(self, control, entry, wrap_always, short_indent,
trailing_comma, sort=True):
+ # pylint: disable=too-many-arguments
# An empty element is not explicitly disallowed by Policy but known to
# break QA tools, so remove any
packages = [x.strip() for x in control[entry].split(",") if x.strip()]
@@ -151,15 +153,14 @@ class Install(object):
def remove_trailing_whitespaces(filename):
assert os.path.isfile(filename), "%s does not exist." % (filename)
content = open(filename).read()
- if len(content) == 0:
+ if not content:
return
content = content.rstrip() + "\n"
lines = content.split("\n")
lines = [l.rstrip() for l in lines]
new_content = "\n".join(lines)
- f = open(filename, "w")
- f.write(new_content)
- f.close()
+ with open(filename, "w") as _file:
+ _file.write(new_content)
def sort_list(unsorted_list):
@@ -168,30 +169,30 @@ def sort_list(unsorted_list):
return sorted(packages) + sorted(special)
-def wrap_and_sort(options):
- control_files = [f for f in options.files if re.search("/control[^/]*$", f)]
+def wrap_and_sort(args):
+ control_files = [f for f in args.files if re.search("/control[^/]*$", f)]
for control_file in control_files:
- if options.verbose:
+ if args.verbose:
print(control_file)
- control = WrapAndSortControl(control_file, options.max_line_length)
- if options.cleanup:
+ control = WrapAndSortControl(control_file, args.max_line_length)
+ if args.cleanup:
control.strip_trailing_spaces()
- control.wrap_and_sort(options.wrap_always, options.short_indent,
- options.sort_binary_packages, options.keep_first,
- options.trailing_comma)
+ control.wrap_and_sort(args.wrap_always, args.short_indent,
+ args.sort_binary_packages, args.keep_first,
+ args.trailing_comma)
control.save()
- copyright_files = [f for f in options.files
+ copyright_files = [f for f in args.files
if re.search("/copyright[^/]*$", f)]
for copyright_file in copyright_files:
- if options.verbose:
+ if args.verbose:
print(copyright_file)
remove_trailing_whitespaces(copyright_file)
pattern = "(dirs|docs|examples|info|install|links|maintscript|manpages)$"
- install_files = [f for f in options.files if re.search(pattern, f)]
+ install_files = [f for f in args.files if re.search(pattern, f)]
for install_file in sorted(install_files):
- if options.verbose:
+ if args.verbose:
print(install_file)
install = Install(install_file)
install.sort()
@@ -210,61 +211,57 @@ def get_files(debian_directory):
def main():
script_name = os.path.basename(sys.argv[0])
- usage = "%s [options]" % (script_name)
epilog = "See %s(1) for more info." % (script_name)
- parser = optparse.OptionParser(usage=usage, epilog=epilog)
-
- parser.add_option("-a", "--wrap-always", action="store_true", default=False,
- help="wrap lists even if they do not exceed the line length limit")
- parser.add_option("-s", "--short-indent", dest="short_indent",
- help="only indent wrapped lines by one space (default is "
- "in-line with the field name)",
- action="store_true", default=False)
- parser.add_option("-b", "--sort-binary-packages",
- help="Sort binary package paragraphs by name",
- dest="sort_binary_packages", action="store_true",
- default=False)
- parser.add_option("-k", "--keep-first",
- help="When sorting binary package paragraphs, leave the "
- "first one at the top. Unqualified debhelper "
- "configuration files are applied to the first "
- "package.",
- dest="keep_first", action="store_true", default=False)
- parser.add_option("-n", "--no-cleanup", help="don't cleanup whitespaces",
- dest="cleanup", action="store_false", default=True)
- parser.add_option("-t", "--trailing-comma", help="add trailing comma",
- dest="trailing_comma", action="store_true",
- default=False)
- parser.add_option("-d", "--debian-directory", dest="debian_directory",
- help="location of the 'debian' directory (default: "
- "./debian)", metavar="PATH", default="debian")
- parser.add_option("-f", "--file", metavar="FILE",
- dest="files", action="append", default=list(),
- help="Wrap and sort only the specified file.")
- parser.add_option("-v", "--verbose",
- help="print all files that are touched",
- dest="verbose", action="store_true", default=False)
- parser.add_option("--max-line-length", type='int', default=79,
- help="set maximum allowed line length before wrapping (default: %default)")
-
- (options, args) = parser.parse_args()
-
- if len(args) != 0:
- parser.error("Unsupported additional parameters specified: %s" %
- ", ".join(args))
-
- if not os.path.isdir(options.debian_directory):
+ parser = argparse.ArgumentParser(epilog=epilog)
+
+ parser.add_argument("-a", "--wrap-always", action="store_true", default=False,
+ help="wrap lists even if they do not exceed the line length limit")
+ parser.add_argument("-s", "--short-indent", dest="short_indent",
+ help="only indent wrapped lines by one space (default is "
+ "in-line with the field name)",
+ action="store_true", default=False)
+ parser.add_argument("-b", "--sort-binary-packages",
+ help="Sort binary package paragraphs by name",
+ dest="sort_binary_packages", action="store_true",
+ default=False)
+ parser.add_argument("-k", "--keep-first",
+ help="When sorting binary package paragraphs, leave the "
+ "first one at the top. Unqualified debhelper "
+ "configuration files are applied to the first "
+ "package.",
+ dest="keep_first", action="store_true", default=False)
+ parser.add_argument("-n", "--no-cleanup", help="don't cleanup whitespaces",
+ dest="cleanup", action="store_false", default=True)
+ parser.add_argument("-t", "--trailing-comma", help="add trailing comma",
+ dest="trailing_comma", action="store_true",
+ default=False)
+ parser.add_argument("-d", "--debian-directory", dest="debian_directory",
+ help="location of the 'debian' directory (default: ./debian)",
+ metavar="PATH", default="debian")
+ parser.add_argument("-f", "--file", metavar="FILE",
+ dest="files", action="append", default=list(),
+ help="Wrap and sort only the specified file.")
+ parser.add_argument("-v", "--verbose",
+ help="print all files that are touched",
+ dest="verbose", action="store_true", default=False)
+ parser.add_argument("--max-line-length", type=int, default=79,
+ help="set maximum allowed line length before wrapping "
+ "(default: %(default)i)")
+
+ args = parser.parse_args()
+
+ if not os.path.isdir(args.debian_directory):
parser.error('Debian directory not found, expecting "%s".' %
- options.debian_directory)
+ args.debian_directory)
- not_found = [f for f in options.files if not os.path.isfile(f)]
+ not_found = [f for f in args.files if not os.path.isfile(f)]
if not_found:
parser.error('Specified files not found: %s' % ", ".join(not_found))
- if not options.files:
- options.files = get_files(options.debian_directory)
+ if not args.files:
+ args.files = get_files(args.debian_directory)
- wrap_and_sort(options)
+ wrap_and_sort(args)
if __name__ == "__main__":
--
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/collab-maint/devscripts.git
More information about the devscripts-devel
mailing list