Commit d1c16340 authored by Guido Günther's avatar Guido Günther

pep8/pyflakes cleanups

parent f7db3b77
......@@ -8,6 +8,7 @@
import textwrap
import gbp.dch
def format_changelog_entry(commit_info, options, last_commit=False):
entry = gbp.dch.format_changelog_entry(commit_info, options, last_commit)
if entry:
......
......@@ -48,14 +48,14 @@ else:
try:
CLIENT = ZeitgeistClient()
except RuntimeError as e:
print("Unable to connect to Zeitgeist, won't send events. Reason: '%s'" %e)
print("Unable to connect to Zeitgeist, won't send events. Reason: '%s'" % e)
def get_repo():
"""Get uri of remote repository and its name"""
repo = None
uri = subprocess.Popen(['git', 'config', '--get', 'remote.origin.url'],
stdout=subprocess.PIPE).communicate()[0]
stdout=subprocess.PIPE).communicate()[0]
if uri:
uri = uri.strip().decode(sys.getfilesystemencoding())
......@@ -65,7 +65,7 @@ def get_repo():
sep = ':'
try:
repo = unicode(uri.rsplit(sep, 1)[1])
except IndexError: # no known separator
except IndexError: # no known separator
repo = uri
repo = repo.rsplit(u'.git', 1)[0]
return repo, uri
......@@ -86,19 +86,18 @@ def main(argv):
origin = uri
subject = Subject.new_for_values(
uri = uri,
interpretation = Interpretation.DOCUMENT.TEXT_DOCUMENT.PLAIN_TEXT_DOCUMENT.SOURCE_CODE.uri,
manifestation = Manifestation.FILE_DATA_OBJECT.uri,
text = repo,
origin = origin)
uri=uri,
interpretation=Interpretation.DOCUMENT.TEXT_DOCUMENT.PLAIN_TEXT_DOCUMENT.SOURCE_CODE.uri,
manifestation=Manifestation.FILE_DATA_OBJECT.uri,
text=repo,
origin=origin)
event = Event.new_for_values(
timestamp = int(time.time() * 1000),
interpretation = interpretation,
manifestation = Manifestation.USER_ACTIVITY.uri,
actor = "application://gitg.desktop",
subjects = [subject])
timestamp=int(time.time() * 1000),
interpretation=interpretation,
manifestation=Manifestation.USER_ACTIVITY.uri,
actor="application://gitg.desktop",
subjects=[subject])
CLIENT.insert_event(event)
if __name__ == '__main__':
main(sys.argv)
......@@ -21,7 +21,6 @@ git-buildpackage and friends
import subprocess
import os
import os.path
import signal
import gbp.log as log
......
......@@ -27,6 +27,7 @@ from gbp.git import GitRepositoryError
from gbp.deb.changelog import ChangeLog, NoChangeLogError
from gbp.deb.policy import DebianPkgPolicy
class DpkgCompareVersions(gbpc.Command):
dpkg = '/usr/bin/dpkg'
......@@ -43,16 +44,16 @@ class DpkgCompareVersions(gbpc.Command):
@raises CommandExecFailed: if the version comparison fails
"""
self.run_error = "Couldn't compare %s with %s" % (version1, version2)
res = self.call([ version1, 'lt', version2 ])
if res not in [ 0, 1 ]:
res = self.call([version1, 'lt', version2])
if res not in [0, 1]:
if self.stderr:
self.run_error += ' (%s)' % self.stderr
raise gbpc.CommandExecFailed("%s: bad return code %d" % (self.run_error, res))
if res == 0:
return -1
elif res == 1:
res = self.call([ version1, 'gt', version2 ])
if res not in [ 0, 1 ]:
res = self.call([version1, 'gt', version2])
if res not in [0, 1]:
if self.stderr:
self.run_error += ' (%s)' % self.stderr
raise gbpc.CommandExecFailed("%s: bad return code %d" % (self.run_error, res))
......
......@@ -23,10 +23,12 @@ import os
import subprocess
from gbp.command_wrappers import Command
class NoChangeLogError(Exception):
"""No changelog found"""
pass
class ParseChangeLogError(Exception):
"""Problem parsing changelog"""
pass
......@@ -92,9 +94,9 @@ class ChangeLog(object):
def _parse(self):
"""Parse a changelog based on the already read contents."""
cmd = subprocess.Popen(['dpkg-parsechangelog', '-l-'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
(output, errors) = cmd.communicate(self._contents)
if cmd.returncode:
raise ParseChangeLogError("Failed to parse changelog. "
......@@ -138,8 +140,8 @@ class ChangeLog(object):
@property
def version(self):
"""The full version string"""
return self._cp['Version']
"""The full version string"""
return self._cp['Version']
@property
def upstream_version(self):
......@@ -198,7 +200,7 @@ class ChangeLog(object):
"""
section = ''
for line in self._contents.split('\n'):
if line and line[0] not in [ ' ', '\t' ]:
if line and line[0] not in [' ', '\t']:
section += line
else:
if section:
......
......@@ -19,14 +19,17 @@
import email
import os
class NoControlError(Exception):
"""No control found"""
pass
class ParseControlError(Exception):
"""Problem parsing control"""
pass
class Control(object):
"""A Debian control"""
......
......@@ -29,16 +29,16 @@ class DscFile(object):
compressions = r"(%s)" % '|'.join(DebianUpstreamSource.known_compressions())
pkg_re = re.compile(r'Source:\s+(?P<pkg>.+)\s*')
version_re = re.compile(r'Version:\s((?P<epoch>\d+)\:)?'
'(?P<version>[%s]+)\s*$'
'(?P<version>[%s]+)\s*$'
% DebianPkgPolicy.debianversion_chars)
tar_re = re.compile(r'^\s\w+\s\d+\s+(?P<tar>[^_]+_[^_]+'
'(\.orig)?\.tar\.%s)' % compressions)
'(\.orig)?\.tar\.%s)' % compressions)
add_tar_re = re.compile(r'^\s\w+\s\d+\s+(?P<tar>[^_]+_[^_]+'
'\.orig-(?P<dir>[a-z0-9-]+)\.tar\.%s)' % compressions)
diff_re = re.compile(r'^\s\w+\s\d+\s+(?P<diff>[^_]+_[^_]+'
'\.diff.(gz|bz2))')
'\.diff.(gz|bz2))')
deb_tgz_re = re.compile(r'^\s\w+\s\d+\s+(?P<deb_tgz>[^_]+_[^_]+'
'\.debian.tar.%s)' % compressions)
'\.debian.tar.%s)' % compressions)
format_re = re.compile(r'Format:\s+(?P<format>[0-9.]+)\s*')
def __init__(self, dscfile):
......@@ -63,7 +63,7 @@ class DscFile(object):
self.upstream_version = "-".join(m.group('version').split("-")[0:-1])
self.native = False
else:
self.native = True # Debian native package
self.native = True # Debian native package
self.upstream_version = m.group('version')
if m.group('epoch'):
self.epoch = m.group('epoch')
......@@ -113,7 +113,7 @@ class DscFile(object):
self.additional_tarballs = dict(add_tars)
def _get_version(self):
version = [ "", self.epoch + ":" ][len(self.epoch) > 0]
version = ["", self.epoch + ":"][len(self.epoch) > 0]
if self.native:
version += self.upstream_version
else:
......
......@@ -16,9 +16,11 @@
# <http://www.gnu.org/licenses/>
"""Parse debian/source/format"""
class DebianSourceFormatError(Exception):
pass
class DebianSourceFormat(object):
"""
Contents of debian/source/format
......@@ -47,8 +49,7 @@ class DebianSourceFormat(object):
self._version = parts[0]
if len(parts) == 2:
if (parts[1][0] == '(' and
parts[1][-1] == ')'):
if (parts[1][0] == '(' and parts[1][-1] == ')'):
self._type = parts[1][1:-1]
else:
raise DebianSourceFormatError("Cannot get source format from "
......
......@@ -20,6 +20,7 @@ from gbp.pkg import compressor_opts
from gbp.pkg.pristinetar import PristineTar
from gbp.deb import DebianPkgPolicy
class DebianPristineTar(PristineTar):
"""The pristine-tar branch in a Debian git repository"""
def has_commit(self, package, version, comp_type=None):
......@@ -63,4 +64,3 @@ class DebianPristineTar(PristineTar):
output_dir,
component=component)
super(DebianPristineTar, self).checkout(name)
......@@ -22,6 +22,7 @@ from gbp.deb.changelog import ChangeLog
import six
class FileVfs(object):
def __init__(self, dir):
"""
......@@ -36,9 +37,11 @@ class FileVfs(object):
flags = flags or 'r'
return open(os.path.join(self._dir, path), flags)
class DebianSourceError(Exception):
pass
class DebianSource(object):
"""
A debianized source tree
......@@ -68,10 +71,10 @@ class DebianSource(object):
if f.type:
return f.type == 'native'
except IOError as e:
pass # Fall back to changelog parsing
pass # Fall back to changelog parsing
try:
return not '-' in self.changelog.version
return '-' not in self.changelog.version
except IOError as e:
raise DebianSourceError("Failed to determine source format: %s" % e)
......
......@@ -16,11 +16,15 @@
# <http://www.gnu.org/licenses/>
"""Interface to uscan"""
import os, re, subprocess
import os
import re
import subprocess
class UscanError(Exception):
pass
class Uscan(object):
cmd = '/usr/bin/uscan'
......@@ -84,7 +88,7 @@ class Uscan(object):
for n in ('package',
'upstream-version',
'upstream-url'):
m = re.match("<%s>(.*)</%s>" % (n,n), row)
m = re.match("<%s>(.*)</%s>" % (n, n), row)
if m:
d[n] = m.group(1)
d["ext"] = os.path.splitext(d['upstream-url'])[1]
......@@ -94,10 +98,10 @@ class Uscan(object):
# Fall back to the upstream source name otherwise
if not os.path.exists(source):
source = "../%s" % d['upstream-url'].rsplit('/',1)[1]
source = "../%s" % d['upstream-url'].rsplit('/', 1)[1]
if not os.path.exists(source):
raise UscanError("Couldn't find tarball at '%s'" %
source)
source)
except KeyError as e:
raise UscanError("Couldn't find '%s' in uscan output" %
e.args[0])
......@@ -157,7 +161,7 @@ class Uscan(object):
msg = None
for n in ('errors', 'warnings'):
m = re.search("<%s>(.*)</%s>" % (n,n), out, re.DOTALL)
m = re.search("<%s>(.*)</%s>" % (n, n), out, re.DOTALL)
if m:
msg = "Uscan failed: %s" % m.group(1)
break
......@@ -166,7 +170,6 @@ class Uscan(object):
msg = "Uscan failed - debug by running 'uscan --verbose'"
raise UscanError(msg)
def scan(self, destdir='..'):
"""Invoke uscan to fetch a new upstream version"""
p = subprocess.Popen(['uscan', '--symlink', '--destdir=%s' % destdir,
......
......@@ -19,13 +19,14 @@
import calendar
import dateutil.parser
from gbp.git.modifier import GitModifier
from gbp.git.commit import GitCommit
from gbp.git.errors import GitError
from gbp.git.repository import GitRepository, GitRepositoryError
from gbp.git.fastimport import FastImport
from gbp.git.args import GitArgs
from gbp.git.vfs import GitVfs
from gbp.git.modifier import GitModifier # noqa: F401
from gbp.git.commit import GitCommit # noqa: F401
from gbp.git.errors import GitError # noqa: F401
from gbp.git.repository import ( # noqa: F401
GitRepository, GitRepositoryError)
from gbp.git.fastimport import FastImport # noqa: F401
from gbp.git.args import GitArgs # noqa: F401
from gbp.git.vfs import GitVfs # noqa: F401
def rfc822_date_to_git(rfc822_date):
......
......@@ -21,6 +21,7 @@ Git command argument handling helpers
import six
import collections
class GitArgs(object):
"""
Handle arguments to git commands
......@@ -106,4 +107,3 @@ class GitArgs(object):
else:
self.add(noopt)
return self
......@@ -18,7 +18,6 @@
import re
from gbp.git.errors import GitError
class GitCommit(object):
"""A git commit"""
......@@ -44,5 +43,3 @@ class GitCommit(object):
@rtype: C{bool}
"""
return True if GitCommit.sha1_re.match(value) else False
......@@ -16,7 +16,7 @@
# <http://www.gnu.org/licenses/>
"""Git base error exception"""
class GitError(Exception):
"""Exception thrown by Git related classes"""
pass
......@@ -21,12 +21,13 @@ import subprocess
import time
from gbp.errors import GbpError
class FastImport(object):
"""Add data to a git repository using I{git fast-import}"""
_bufsize = 1024
m_regular = 644
m_exec = 755
m_exec = 755
m_symlink = 120000
def __init__(self, repo):
......@@ -36,7 +37,7 @@ class FastImport(object):
"""
self._repo = repo
try:
self._fi = subprocess.Popen([ 'git', 'fast-import', '--quiet'],
self._fi = subprocess.Popen(['git', 'fast-import', '--quiet'],
stdin=subprocess.PIPE, cwd=repo.path)
self._out = self._fi.stdin
except OSError as err:
......
......@@ -21,14 +21,17 @@ like committing changes or authoring a patch
"""
import six
import calendar, datetime
import calendar
import datetime
from gbp.git.errors import GitError
class GitModifierError(GitError):
"""Exception thrown by L{GitModifier}"""
pass
class GitTz(datetime.tzinfo):
"""Simple class to store the utc offset only"""
def __init__(self, offset_sec=0, *args, **kwargs):
......@@ -41,6 +44,7 @@ class GitTz(datetime.tzinfo):
def dst(self, dt):
return datetime.timedelta(0)
class GitModifier(object):
"""Stores authorship/committer information"""
def __init__(self, name=None, email=None, date=None):
......@@ -64,16 +68,16 @@ class GitModifier(object):
timestamp, offset = date.split()
offset_h = int(offset[:-2])
offset_m = int(offset[-2:])
tz = GitTz(offset_h*3600 + offset_m*60)
tz = GitTz(offset_h * 3600 + offset_m * 60)
self._date = datetime.datetime.fromtimestamp(int(timestamp), tz)
elif type(date) in [ type(0), type(0.0) ]:
elif type(date) in [type(0), type(0.0)]:
self._date = datetime.datetime.fromtimestamp(date, tz)
elif isinstance(date, datetime.datetime):
if date.tzinfo:
self._date = date
else:
self._date = date.replace(tzinfo=tz)
elif date != None:
elif date is not None:
raise ValueError("Date '%s' not timestamp, "
"datetime object or git raw date" % date)
......@@ -154,7 +158,7 @@ class GitModifier(object):
@staticmethod
def keys():
return [ 'name', 'email', 'date' ]
return ['name', 'email', 'date']
def items(self):
items = []
......
......@@ -17,7 +17,8 @@
"""Make blobs in a git repository accessible as file like objects"""
from six import StringIO
from gbp.git.repository import GitRepositoryError
from gbp.git.repository import GitRepositoryError
class GitVfs(object):
......
......@@ -124,24 +124,30 @@ def err(msg):
"""Logs a message with level ERROR on the GBP logger"""
LOGGER.error(msg)
def error(msg):
err(msg)
def warn(msg):
"""Logs a message with level WARNING on the GBP logger"""
LOGGER.warning(msg)
def warning(msg):
warn(msg)
def info(msg):
"""Logs a message with level INFO on the GBP logger"""
LOGGER.info(msg)
def debug(msg):
"""Logs a message with level DEBUG on the GBP logger"""
LOGGER.debug(msg)
def _parse_color_scheme(color_scheme=""):
"""Set logging colors"""
scheme = {}
......@@ -159,9 +165,11 @@ def _parse_color_scheme(color_scheme=""):
except ValueError:
try:
scheme[level] = COLORS[color.lower()]
except KeyError: pass
except KeyError:
pass
return scheme
def setup(color, verbose, color_scheme=""):
"""Basic logger setup"""
LOGGER.set_color(color)
......@@ -176,4 +184,3 @@ def setup(color, verbose, color_scheme=""):
logging.setLoggerClass(GbpLogger)
LOGGER = getLogger("gbp")
......@@ -20,9 +20,10 @@ import os
import gbp.log
from gbp.command_wrappers import Command
class PristineTar(Command):
"""The pristine-tar branch in a git repository"""
cmd='/usr/bin/pristine-tar'
cmd = '/usr/bin/pristine-tar'
branch = 'pristine-tar'
def __init__(self, repo):
......@@ -79,4 +80,3 @@ class PristineTar(Command):
self.run_error = ("Couldn't commit to '%s' with upstream '%s': {stderr}" %
(self.branch, upstream))
self.__call__(['commit', archive, upstream])
......@@ -15,7 +15,6 @@
# You should have received a copy of the GNU General Public License
# along with this program; if not, please see
# <http://www.gnu.org/licenses/>
import re
from gbp.format import format_str
from gbp.errors import GbpError
......
......@@ -26,8 +26,8 @@ try:
librpm = __import__(RpmPkgPolicy.python_rpmlib_module_name)
except ImportError:
gbp.log.warn("Failed to import '%s' as rpm python module, using host's "
"default rpm library instead" %
RpmPkgPolicy.python_rpmlib_module_name)
"default rpm library instead" %
RpmPkgPolicy.python_rpmlib_module_name)
import rpm as librpm
# Module initialization
......@@ -44,4 +44,3 @@ def get_librpm_log(truncate=True):
if truncate:
_rpmlogfd.truncate(0)
return log
# vim: set fileencoding=utf-8 :
#
# (C) 2006-2011 Guido Guenther <agx@sigxcpu.org>
# (C) 2006-2011, 2016 Guido Guenther <agx@sigxcpu.org>
# (C) 2012 Intel Corporation <markus.lehtonen@linux.intel.com>
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
......@@ -18,7 +18,8 @@
#
"""Common functionality for Debian and RPM buildpackage scripts"""
import os, os.path
import os
import os.path
import pipes
import tempfile
import shutil
......@@ -112,7 +113,7 @@ def git_archive_single(treeish, output, prefix, comp_type, comp_level, comp_opts
raise GbpError("Error creating %s: %d" % (output, ret))
#{ Functions to handle export-dir
# Functions to handle export-dir
def dump_tree(repo, export_dir, treeish, with_submodules, recursive=True):
"dump a tree to output_dir"
output_dir = os.path.dirname(export_dir)
......@@ -147,7 +148,7 @@ def dump_tree(repo, export_dir, treeish, with_submodules, recursive=True):
ret = pipe.copy('', '')
os.chdir(top)
if ret:
raise GbpError("Error in dump_tree archive pipe in submodule %s" % subdir)
raise GbpError("Error in dump_tree archive pipe in submodule %s" % subdir)
except OSError as err:
gbp.log.err("Error dumping tree to %s: %s" % (output_dir, err[0]))
return False
......
......@@ -35,6 +35,7 @@ try:
except ImportError:
pass
def orig_needs_repack(upstream_source, options):
"""
Determine if the upstream sources needs to be repacked
......
......@@ -176,6 +176,7 @@ def write_patch_file(filename, commit_info, diff):
DEFAULT_PATCH_NUM_PREFIX_FORMAT = "%04d-"
def format_patch(outdir, repo, commit_info, series, numbered=True,
path_exclude_regex=None, topic='', name=None, renumber=False,
patch_num_prefix_format=DEFAULT_PATCH_NUM_PREFIX_FORMAT):
......@@ -188,10 +189,10 @@ def format_patch(outdir, repo, commit_info, series, numbered=True,
try:
num_prefix = str(patch_num_prefix_format) % (len(series) + 1) \
if numbered else ''
if numbered else ''
except Exception:
gbp.log.warn("Bad format format string '%s', " \
"falling back to default '%s'" % \
gbp.log.warn("Bad format format string '%s', "
"falling back to default '%s'" %
(str(patch_num_prefix_format),
DEFAULT_PATCH_NUM_PREFIX_FORMAT))
num_prefix = DEFAULT_PATCH_NUM_PREFIX_FORMAT % (len(series) + 1)
......@@ -200,7 +201,7 @@ def format_patch(outdir, repo, commit_info, series, numbered=True,
if renumber:
# Remove any existing numeric prefix if the patch
# should be renumbered
name = re.sub('^\d+[-_]*', '', name)
name = re.sub('^\d+[-_]*', '', name)
else:
# Otherwise, clear proposed prefix
num_prefix = ''
......@@ -214,9 +215,8 @@ def format_patch(outdir, repo, commit_info, series, numbered=True,
filepath = os.path.join(outdir, filename)
# Make sure that we don't overwrite existing patches in the series
if filepath in series:
presuffix = '-%d' % \
len([p for p in series \
if p.startswith(os.path.splitext(filepath)[0])])
presuffix = '-%d' % len([p for p in series
if p.startswith(os.path.splitext(filepath)[0])])
filename = num_prefix + base + presuffix + suffix
filepath = os.path.join(outdir, filename)
......
......@@ -18,7 +18,7 @@
"""Query and display config file values"""
import sys
import os, os.path
import os
from gbp.config import GbpOptionParser
from gbp.errors import GbpError
from gbp.scripts.supercommand import import_command
......
......@@ -70,6 +70,7 @@ def print_config(remote, branches):
remote = %s
merge = refs/heads/%s""" % (branch, remote['name'], branch))
def sort_dict(d):
"""Return a sorted list of (key, value) tuples"""
s = []
......@@ -77,6 +78,7 @@ def sort_dict(d):
s.append((key, d[key]))
return s
def parse_url(remote_url, name, pkg, template_dir=None):
"""
Sanity check our remote URL
......@@ -116,7 +118,7 @@ def parse_url(remote_url, name, pkg, template_dir=None):
else:
raise GbpError("URL must use ssh protocol.")
if not '%(pkg)s' in remote_url and not remote_url.endswith(".git"):
if '%(pkg)s' not in remote_url and not remote_url.endswith(".git"):
raise GbpError("URL needs to contain either a repository name or '%(pkg)s'")
if ":" in frags.netloc:
......@@ -162,7 +164,7 @@ def build_remote_script(remote, branch):
args['git-init-args'] = '--bare --shared'
if args['template-dir']:
args['git-init-args'] += (' --template=%s'
% args['template-dir'])
% args['template-dir'])
remote_script_pattern = ['',
'set -e',
'umask 002',
......@@ -214,7 +216,7 @@ def read_yn():
if old_settings:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
if ch in ( 'y', 'Y' ):
if ch in ('y', 'Y'):
return True
else:
return False
......@@ -293,7 +295,7 @@ def parse_args(argv, sections=[]):
# section to parse, this makes e.g. --help work as expected:
for arg in argv:
if arg.startswith('--remote-config='):
sections = ['remote-config %s' % arg.split('=',1)[1]]
sections = ['remote-config %s' % arg.split('=', 1)[1]]
break
else:
sections = []
......@@ -325,12 +327,12 @@ def main(argv):
try:
branches = []
for branch in [ options.debian_branch, options.upstream_branch ]:
for branch in [options.debian_branch, options.upstream_branch]:
if repo.has_branch(branch):
branches += [ branch ]
branches += [branch]
if repo.has_pristine_tar_branch() and options.pristine_tar:
branches += [ repo.pristine_tar_branch ]
branches += [repo.pristine_tar_branch]