Commit 1dca5ce0 authored by Damien Lespiau's avatar Damien Lespiau
Browse files

pep8: Run autopep8 on the code base


Signed-off-by: default avatarDamien Lespiau <damien.lespiau@intel.com>
parent 4d525c86
......@@ -68,6 +68,7 @@ def die(message):
class HttpError(Exception):
def __init__(self, status_code):
self.status_code = status_code
self.response = None
......@@ -223,24 +224,24 @@ class Series(RestObject):
'name': {
'header': 'Name',
'can_shrink': True,
} ,
},
'n_patches': {
'header': 'Patches',
} ,
},
'submitter': {
'header': 'Submitter',
} ,
},
'submitted': {
'header': 'Submitted',
'format': 'date',
} ,
},
'last_updated': {
'header': 'Updated',
'format': 'date',
} ,
},
'version': {
'header': 'Version',
} ,
},
'reviewer': {
'header': 'Reviewer',
},
......@@ -400,7 +401,7 @@ class Table(object):
# we allow one column to shrink to accomodate 'max_width'
shrinking_column = None
if ('max_width' in self.config and
table_width > self.config['max_width']):
table_width > self.config['max_width']):
for key, column in columns.iteritems():
if 'can_shrink' in column:
shrinking_column = key
......@@ -657,7 +658,7 @@ class GitPatchwork(object):
# Human readable
filtered_fields = {key: Series.meta[key] for key in self.cmd.fields}
columns = OrderedDict(sorted(filtered_fields.items(),
key=lambda k: self.cmd.fields.index(k[0])))
key=lambda k: self.cmd.fields.index(k[0])))
config = {
'columns': columns,
'max_width': Terminal().get_size()[0],
......@@ -741,14 +742,14 @@ class GitPatchwork(object):
(series, revision) = self.cmd_get_series_revision()
self._do_post_results(revision, {
404: "No series with id %d" % self.cmd.series_id
404: "No series with id %d" % self.cmd.series_id
})
def do_post_result_patch(self):
patch = self.pw.get_patch(self.cmd.patch_id)
self._do_post_results(patch, {
404: "No patch with id %d" % self.cmd.patch_id
404: "No patch with id %d" % self.cmd.patch_id
})
def run(self):
......@@ -768,6 +769,7 @@ class AliasedSubParsersAction(argparse._SubParsersAction):
'''Aliases for argparse positional arguments.'''
class _AliasedPseudoAction(argparse.Action):
def __init__(self, name, aliases, help):
dest = name
if aliases:
......@@ -783,7 +785,7 @@ class AliasedSubParsersAction(argparse._SubParsersAction):
aliases = []
parser = super(AliasedSubParsersAction, self). \
add_parser(name, **kwargs)
add_parser(name, **kwargs)
# Make the aliases work.
for alias in aliases:
......
......@@ -47,8 +47,8 @@ from django.utils.six.moves import map
from patchwork import lock as lockmod
from patchwork.lock import release
from patchwork.models import (Patch, Project, Person, Comment, State, Series,
SeriesRevision, SeriesRevisionPatch, get_default_initial_patch_state,
series_revision_complete, SERIES_DEFAULT_NAME)
SeriesRevision, SeriesRevisionPatch, get_default_initial_patch_state,
series_revision_complete, SERIES_DEFAULT_NAME)
from patchwork.parser import parse_patch
LOGGER = logging.getLogger(__name__)
......@@ -106,7 +106,7 @@ def find_project(mail):
# order_by will put projects with a blank subject_prefix_tags
# first
projects = Project.objects.filter(listid=listid).\
order_by('subject_prefix_tags')
order_by('subject_prefix_tags')
if not projects:
break
......@@ -186,9 +186,9 @@ def mail_date(mail):
def mail_headers(mail):
return reduce(operator.__concat__,
['%s: %s\n' % (k, Header(v, header_name = k,
continuation_ws = '\t').encode())
for (k, v) in list(mail.items())])
['%s: %s\n' % (k, Header(v, header_name=k,
continuation_ws='\t').encode())
for (k, v) in list(mail.items())])
def find_pull_request(content):
......@@ -211,6 +211,7 @@ def try_decode(payload, charset):
class MailContent:
def __init__(self):
self.patch = None
self.comment = None
......@@ -318,7 +319,7 @@ def parse_series_marker(subject_prefixes):
def is_git_send_email(mail):
return mail.get('X-Mailer', '').startswith('git-send-email ') or \
'git-send-email' in mail.get('Message-ID', '')
'git-send-email' in mail.get('Message-ID', '')
def find_content(project, mail):
......@@ -389,12 +390,12 @@ def find_content(project, mail):
is_patch = patchbuf is not None
drop_patch = not is_attachment and \
project.git_send_email_only and not is_git_send_email(mail)
project.git_send_email_only and not is_git_send_email(mail)
if pullurl or (is_patch and not drop_patch):
ret.patch_order = x or 1
ret.patch = Patch(name=name, pull_url=pullurl, content=patchbuf,
date=mail_date(mail), headers=mail_headers(mail))
date=mail_date(mail), headers=mail_headers(mail))
# Create/update the Series and SeriesRevision objects
if is_cover_letter or is_patch:
......@@ -425,16 +426,16 @@ def find_content(project, mail):
# patch has been saved by the caller
if ret.patch:
ret.comment = Comment(date=mail_date(mail),
content = clean_content(commentbuf),
headers = mail_headers(mail))
content=clean_content(commentbuf),
headers=mail_headers(mail))
else:
cpatch = find_patch_for_comment(project, refs)
if not cpatch:
return ret
ret.comment = Comment(patch=cpatch, date=mail_date(mail),
content = clean_content(commentbuf),
headers = mail_headers(mail))
content=clean_content(commentbuf),
headers=mail_headers(mail))
# make sure we always have a valid (series,revision) tuple if we have a
# patch. We don't consider pull requests a series.
......@@ -486,7 +487,7 @@ def find_patch_order(revisions, previous_patch, order, n_patches):
for revision in revisions:
try:
order = SeriesRevisionPatch.objects.get(revision=revision,
patch=previous_patch).order
patch=previous_patch).order
if n_patches is None:
n_patches = revision.n_patches
break
......@@ -513,7 +514,7 @@ def find_series_for_mail(project, name, msgid, is_patch, order, n_patches,
# grab the latest revision for this mail thread
revisions = SeriesRevision.objects.filter(series__project=project,
root_msgid=root_msgid) \
.reverse()
.reverse()
revision = revisions[0]
series = revision.series
if name:
......@@ -600,7 +601,7 @@ def clean_subject(subject, drop_prefixes=None):
while match:
prefix_str = match.group(1)
prefixes += [p for p in split_prefixes(prefix_str)
if p.lower() not in drop_prefixes]
if p.lower() not in drop_prefixes]
subject = match.group(2)
match = prefix_re.match(subject)
......@@ -670,9 +671,9 @@ def on_revision_complete(sender, revision, **kwargs):
return
name = clean_series_name(new_series.name)
previous_series = Series.objects.filter(Q(project=new_series.project),
Q(name__iexact=name) &
~Q(pk=new_series.pk))
previous_series = Series.objects.filter(
Q(project=new_series.project),
Q(name__iexact=name) & ~Q(pk=new_series.pk))
if len(previous_series) != 1:
return
......@@ -752,7 +753,7 @@ def parse_mail(mail):
patch.project = project
patch.state = get_state(mail.get('X-Patchwork-State', '').strip())
patch.delegate = get_delegate(
mail.get('X-Patchwork-Delegate', '').strip())
mail.get('X-Patchwork-Delegate', '').strip())
patch.save()
if revision:
revision.add_patch(patch, content.patch_order)
......
......@@ -56,8 +56,10 @@ except NameError:
DEFAULT_URL = "http://patchwork/xmlrpc/"
CONFIG_FILE = os.path.expanduser('~/.pwclientrc')
class Filter(object):
"""Filter for selecting patches."""
def __init__(self):
# These fields refer to specific objects, so they are special
# because we have to resolve them to IDs before passing the
......@@ -82,7 +84,7 @@ class Filter(object):
if self.state != "":
id = state_id_by_name(rpc, self.state)
if id == 0:
sys.stderr.write("Note: No State found matching %s*, " \
sys.stderr.write("Note: No State found matching %s*, "
"ignoring filter\n" % self.state)
else:
self.d['state_id'] = id
......@@ -90,7 +92,7 @@ class Filter(object):
if self.project != None:
id = project_id_by_name(rpc, self.project)
if id == 0:
sys.stderr.write("Note: No Project found matching %s, " \
sys.stderr.write("Note: No Project found matching %s, "
"ignoring filter\n" % self.project)
else:
self.d['project_id'] = id
......@@ -99,9 +101,10 @@ class Filter(object):
"""Return human-readable description of the filter."""
return str(self.d)
class BasicHTTPAuthTransport(xmlrpclib.SafeTransport):
def __init__(self, username = None, password = None, use_https = False):
def __init__(self, username=None, password=None, use_https=False):
self.username = username
self.password = password
self.use_https = use_https
......@@ -125,6 +128,7 @@ class BasicHTTPAuthTransport(xmlrpclib.SafeTransport):
fn = xmlrpclib.Transport.make_connection
return fn(self, host)
def project_id_by_name(rpc, linkname):
"""Given a project short name, look up the Project ID."""
if len(linkname) == 0:
......@@ -135,6 +139,7 @@ def project_id_by_name(rpc, linkname):
return project['id']
return 0
def state_id_by_name(rpc, name):
"""Given a partial state name, look up the state ID."""
if len(name) == 0:
......@@ -145,6 +150,7 @@ def state_id_by_name(rpc, name):
return state['id']
return 0
def person_ids_by_name(rpc, name):
"""Given a partial name or email address, return a list of the
person IDs that match."""
......@@ -153,6 +159,7 @@ def person_ids_by_name(rpc, name):
people = rpc.person_list(name, 0)
return [x['id'] for x in people]
def list_patches(patches, format_str=None):
"""Dump a list of patches to stdout."""
if format_str:
......@@ -175,7 +182,9 @@ def list_patches(patches, format_str=None):
print("%-7s %-12s %s" % ("ID", "State", "Name"))
print("%-7s %-12s %s" % ("--", "-----", "----"))
for patch in patches:
print("%-7d %-12s %s" % (patch['id'], patch['state'], patch['name']))
print("%-7d %-12s %s" %
(patch['id'], patch['state'], patch['name']))
def action_list(rpc, filter, submitter_str, delegate_str, format_str=None):
filter.resolve_ids(rpc)
......@@ -183,7 +192,7 @@ def action_list(rpc, filter, submitter_str, delegate_str, format_str=None):
if submitter_str != None:
ids = person_ids_by_name(rpc, submitter_str)
if len(ids) == 0:
sys.stderr.write("Note: Nobody found matching *%s*\n" % \
sys.stderr.write("Note: Nobody found matching *%s*\n" %
submitter_str)
else:
for id in ids:
......@@ -200,7 +209,7 @@ def action_list(rpc, filter, submitter_str, delegate_str, format_str=None):
if delegate_str != None:
ids = person_ids_by_name(rpc, delegate_str)
if len(ids) == 0:
sys.stderr.write("Note: Nobody found matching *%s*\n" % \
sys.stderr.write("Note: Nobody found matching *%s*\n" %
delegate_str)
else:
for id in ids:
......@@ -216,14 +225,16 @@ def action_list(rpc, filter, submitter_str, delegate_str, format_str=None):
patches = rpc.patch_list(filter.d)
list_patches(patches, format_str)
def action_projects(rpc):
projects = rpc.project_list("", 0)
print("%-5s %-24s %s" % ("ID", "Name", "Description"))
print("%-5s %-24s %s" % ("--", "----", "-----------"))
for project in projects:
print("%-5d %-24s %s" % (project['id'], \
project['linkname'], \
project['name']))
print("%-5d %-24s %s" % (project['id'],
project['linkname'],
project['name']))
def action_states(rpc):
states = rpc.state_list("", 0)
......@@ -232,6 +243,7 @@ def action_states(rpc):
for state in states:
print("%-5d %s" % (state['id'], state['name']))
def action_info(rpc, patch_id):
patch = rpc.patch_get(patch_id)
s = "Information for patch id %d" % (patch_id)
......@@ -240,6 +252,7 @@ def action_info(rpc, patch_id):
for key, value in sorted(patch.items()):
print("- %- 14s: %s" % (key, unicode(value).encode("utf-8")))
def action_get(rpc, patch_id):
patch = rpc.patch_get(patch_id)
s = rpc.patch_get_mbox(patch_id)
......@@ -268,34 +281,36 @@ def action_get(rpc, patch_id):
sys.stderr.write("Failed to write to %s\n" % fname)
sys.exit(1)
def action_apply(rpc, patch_id, apply_cmd=None):
patch = rpc.patch_get(patch_id)
if patch == {}:
sys.stderr.write("Error getting information on patch ID %d\n" % \
sys.stderr.write("Error getting information on patch ID %d\n" %
patch_id)
sys.exit(1)
if apply_cmd is None:
print('Applying patch #%d to current directory' % patch_id)
apply_cmd = ['patch', '-p1']
print('Applying patch #%d to current directory' % patch_id)
apply_cmd = ['patch', '-p1']
else:
print('Applying patch #%d using %s' %
(patch_id, repr(' '.join(apply_cmd))))
print('Applying patch #%d using %s' %
(patch_id, repr(' '.join(apply_cmd))))
print('Description: %s' % patch['name'])
s = rpc.patch_get_mbox(patch_id)
if len(s) > 0:
proc = subprocess.Popen(apply_cmd, stdin = subprocess.PIPE)
proc = subprocess.Popen(apply_cmd, stdin=subprocess.PIPE)
proc.communicate(unicode(s).encode('utf-8'))
return proc.returncode
else:
sys.stderr.write("Error: No patch content found\n")
sys.exit(1)
def action_update_patch(rpc, patch_id, state = None, archived = None, commit = None):
def action_update_patch(rpc, patch_id, state=None, archived=None, commit=None):
patch = rpc.patch_get(patch_id)
if patch == {}:
sys.stderr.write("Error getting information on patch ID %d\n" % \
sys.stderr.write("Error getting information on patch ID %d\n" %
patch_id)
sys.exit(1)
......@@ -323,6 +338,7 @@ def action_update_patch(rpc, patch_id, state = None, archived = None, commit = N
if not success:
sys.stderr.write("Patch not updated\n")
def patch_id_from_hash(rpc, project, hash):
try:
patch = rpc.patch_get_by_project_hash(project, hash)
......@@ -346,6 +362,7 @@ def patch_id_from_hash(rpc, project, hash):
auth_actions = ['update']
def main():
hash_parser = argparse.ArgumentParser(add_help=False)
hash_parser.add_argument(
......@@ -367,7 +384,7 @@ def main():
help='''Filter by patch state (e.g., 'New', 'Accepted', etc.)'''
)
filter_parser.add_argument(
'-a', choices=['yes','no'],
'-a', choices=['yes', 'no'],
help='''Filter by patch archived state'''
)
filter_parser.add_argument(
......@@ -399,7 +416,7 @@ def main():
filter_parser.add_argument(
'-f', metavar='FORMAT',
help='''Print output in the given format. You can use tags matching '''
'''fields, e.g. %%{id}, %%{state}, or %%{msgid}.'''
'''fields, e.g. %%{id}, %%{state}, or %%{msgid}.'''
)
filter_parser.add_argument(
'patch_name', metavar='STR', nargs='?',
......@@ -473,17 +490,17 @@ def main():
)
update_parser.set_defaults(subcmd='update')
list_parser = subparsers.add_parser("list",
#aliases=['search'],
parents=[filter_parser],
help='''List patches, using the optional filters specified
# aliases=['search'],
parents=[filter_parser],
help='''List patches, using the optional filters specified
below and an optional substring to search for patches
by name'''
)
)
list_parser.set_defaults(subcmd='list')
search_parser = subparsers.add_parser("search",
parents=[filter_parser],
help='''Alias for "list"'''
)
parents=[filter_parser],
help='''Alias for "list"'''
)
# Poor man's argparse aliases:
# We register the "search" parser but effectively use "list" for the
# help-text.
......@@ -499,7 +516,7 @@ def main():
if args.get('hash') and len(args.get('id')):
# mimic mutual exclusive group
locals()[action + '_parser'].error(
"[-h HASH] and [ID [ID ...]] are mutually exlusive")
"[-h HASH] and [ID [ID ...]] are mutually exlusive")
# set defaults
filt = Filter()
......@@ -518,11 +535,13 @@ def main():
if args.get('c'):
# update multiple IDs with a single commit-hash does not make sense
if action == 'update' and patch_ids and len(patch_ids) > 1:
update_parser.error("Declining update with COMMIT-REF on multiple IDs")
update_parser.error(
"Declining update with COMMIT-REF on multiple IDs")
commit_str = args.get('c')
if state_str is None and archived_str is None and action == 'update':
update_parser.error('Must specify one or more update options (-a or -s)')
update_parser.error(
'Must specify one or more update options (-a or -s)')
if args.get('n') != None:
try:
......@@ -545,29 +564,33 @@ def main():
if not config.has_section('options') and os.path.exists(CONFIG_FILE):
sys.stderr.write('~/.pwclientrc is in the old format. Migrating it...')
old_project = config.get('base','project')
old_project = config.get('base', 'project')
new_config = ConfigParser.ConfigParser()
new_config.add_section('options')
new_config.set('options','default',old_project)
new_config.set('options', 'default', old_project)
new_config.add_section(old_project)
new_config.set(old_project,'url',config.get('base','url'))
new_config.set(old_project, 'url', config.get('base', 'url'))
if config.has_option('auth', 'username'):
new_config.set(old_project,'username',config.get('auth','username'))
new_config.set(old_project, 'username',
config.get('auth', 'username'))
if config.has_option('auth', 'password'):
new_config.set(old_project,'password',config.get('auth','password'))
new_config.set(old_project, 'password',
config.get('auth', 'password'))
old_config_file = CONFIG_FILE + '.orig'
shutil.copy2(CONFIG_FILE,old_config_file)
shutil.copy2(CONFIG_FILE, old_config_file)
with open(CONFIG_FILE, 'wb') as fd:
new_config.write(fd)
sys.stderr.write(' Done.\n')
sys.stderr.write('Your old ~/.pwclientrc was saved to %s\n' % old_config_file)
sys.stderr.write('and was converted to the new format. You may want to\n')
sys.stderr.write(
'Your old ~/.pwclientrc was saved to %s\n' % old_config_file)
sys.stderr.write(
'and was converted to the new format. You may want to\n')
sys.stderr.write('inspect it before continuing.\n')
sys.exit(1)
......@@ -575,13 +598,16 @@ def main():
try:
project_str = config.get('options', 'default')
except:
action_parser.error("No default project configured in ~/.pwclientrc")
action_parser.error(
"No default project configured in ~/.pwclientrc")
if not config.has_section(project_str):
sys.stderr.write('No section for project %s in ~/.pwclientrc\n' % project_str)
sys.stderr.write(
'No section for project %s in ~/.pwclientrc\n' % project_str)
sys.exit(1)
if not config.has_option(project_str, 'url'):
sys.stderr.write('No URL for project %s in ~/.pwclientrc\n' % project_str)
sys.stderr.write(
'No URL for project %s in ~/.pwclientrc\n' % project_str)
sys.exit(1)
if not do_signoff and config.has_option('options', 'signoff'):
do_signoff = config.getboolean('options', 'signoff')
......@@ -597,14 +623,14 @@ def main():
use_https = url.startswith('https')
transport = BasicHTTPAuthTransport( \
config.get(project_str, 'username'),
config.get(project_str, 'password'),
use_https)
transport = BasicHTTPAuthTransport(
config.get(project_str, 'username'),
config.get(project_str, 'password'),
use_https)
else:
sys.stderr.write(("The %s action requires authentication, "
"but no username or password\nis configured\n") % action)
"but no username or password\nis configured\n") % action)
sys.exit(1)
if project_str:
......@@ -620,7 +646,7 @@ def main():
filt.add("msgid", msgid_str)
try:
rpc = xmlrpclib.Server(url, transport = transport)
rpc = xmlrpclib.Server(url, transport=transport)
except:
sys.stderr.write("Unable to connect to %s\n" % url)
sys.exit(1)
......@@ -637,7 +663,7 @@ def main():
"""Error out if no patch IDs were specified"""
if patch_ids == None or len(patch_ids) < 1:
sys.stderr.write("Error: Missing Argument! " +
"Either [-h HASH] or [ID [ID ...]] are required\n")
"Either [-h HASH] or [ID [ID ...]] are required\n")
if h:
h.print_help()
sys.exit(1)
......@@ -702,9 +728,9 @@ def main():
elif action == 'update':
for patch_id in non_empty(h, patch_ids):
action_update_patch(rpc, patch_id, state = state_str,
archived = archived_str, commit = commit_str
)
action_update_patch(rpc, patch_id, state=state_str,
archived=archived_str, commit=commit_str
)
else:
sys.stderr.write("Unknown action '%s'\n" % action)
......
......@@ -25,9 +25,10 @@ from optparse import OptionParser
import subprocess
import sys
def commits(options, revlist):
cmd = ['git', 'rev-list', revlist]
proc = subprocess.Popen(cmd, stdout = subprocess.PIPE, cwd = options.repodir)
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, cwd=options.repodir)
revs = []
......@@ -36,9 +37,10 @@ def commits(options, revlist):
return revs
def commit(options, rev):
cmd = ['git', 'diff', '%(rev)s^..%(rev)s' % {'rev': rev}]
proc = subprocess.Popen(cmd, stdout = subprocess.PIPE, cwd = options.repodir)
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, cwd=options.repodir)
buf = proc.communicate()[0]
......@@ -46,11 +48,11 @@ def commit(options, rev):
def main(args):
parser = OptionParser(usage = '%prog [options] revspec')