3 # Patchwork command line client
4 # Copyright (C) 2008 Nate Case <ncase@xes-inc.com>
6 # This file is part of the Patchwork package.
8 # Patchwork is free software; you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 2 of the License, or
11 # (at your option) any later version.
13 # Patchwork is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with Patchwork; if not, write to the Free Software
20 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
33 # Default Patchwork remote XML-RPC server URL
34 # This script will check the PW_XMLRPC_URL environment variable
35 # for the URL to access. If that is unspecified, it will fallback to
36 # the hardcoded default value specified here.
37 DEFAULT_URL = "http://patchwork/xmlrpc/"
38 CONFIG_FILE = os.path.expanduser('~/.pwclientrc')
41 """Filter for selecting patches."""
43 # These fields refer to specific objects, so they are special
44 # because we have to resolve them to IDs before passing the
45 # filter to the server
49 # The dictionary that gets passed to via XML-RPC
52 def add(self, field, value):
55 elif field == 'project':
61 def resolve_ids(self, rpc):
62 """Resolve State, Project, and Person IDs based on filter strings."""
64 id = state_id_by_name(rpc, self.state)
66 sys.stderr.write("Note: No State found matching %s*, " \
67 "ignoring filter\n" % self.state)
69 self.d['state_id'] = id
71 if self.project != "":
72 id = project_id_by_name(rpc, self.project)
74 sys.stderr.write("Note: No Project found matching %s, " \
75 "ignoring filter\n" % self.project)
77 self.d['project_id'] = id
80 """Return human-readable description of the filter."""
83 class BasicHTTPAuthTransport(xmlrpclib.SafeTransport):
85 def __init__(self, username = None, password = None, use_https = False):
86 self.username = username
87 self.password = password
88 self.use_https = use_https
89 xmlrpclib.SafeTransport.__init__(self)
91 def authenticated(self):
92 return self.username != None and self.password != None
94 def send_host(self, connection, host):
95 xmlrpclib.Transport.send_host(self, connection, host)
96 if not self.authenticated():
98 credentials = '%s:%s' % (self.username, self.password)
99 auth = 'Basic ' + base64.encodestring(credentials).strip()
100 connection.putheader('Authorization', auth)
102 def make_connection(self, host):
104 fn = xmlrpclib.SafeTransport.make_connection
106 fn = xmlrpclib.Transport.make_connection
107 return fn(self, host)
110 sys.stderr.write("Usage: %s <action> [options]\n\n" % \
111 (os.path.basename(sys.argv[0])))
112 sys.stderr.write("Where <action> is one of:\n")
114 """ apply <ID> : Apply a patch (in the current dir, using -p1)
115 git-am <ID> : Apply a patch to current git branch using "git am"
116 get <ID> : Download a patch and save it locally
117 info <ID> : Display patchwork info about a given patch ID
118 projects : List all projects
119 states : Show list of potential patch states
120 list [str] : List patches, using the optional filters specified
121 below and an optional substring to search for patches
123 search [str] : Same as 'list'
124 view <ID> : View a patch
125 update [-s state] [-c commit-ref] <ID>
127 sys.stderr.write("""\nFilter options for 'list' and 'search':
128 -s <state> : Filter by patch state (e.g., 'New', 'Accepted', etc.)
129 -p <project> : Filter by project name (see 'projects' for list)
130 -w <who> : Filter by submitter (name, e-mail substring search)
131 -d <who> : Filter by delegate (name, e-mail substring search)
132 -n <max #> : Restrict number of results
133 -m <messageid>: Filter by Message-Id\n""")
134 sys.stderr.write("""\nActions that take an ID argument can also be \
136 -h <hash> : Lookup by patch hash\n""")
139 def project_id_by_name(rpc, linkname):
140 """Given a project short name, look up the Project ID."""
141 if len(linkname) == 0:
143 projects = rpc.project_list(linkname, 0)
144 for project in projects:
145 if project['linkname'] == linkname:
149 def state_id_by_name(rpc, name):
150 """Given a partial state name, look up the state ID."""
153 states = rpc.state_list(name, 0)
155 if state['name'].lower().startswith(name.lower()):
159 def person_ids_by_name(rpc, name):
160 """Given a partial name or email address, return a list of the
161 person IDs that match."""
164 people = rpc.person_list(name, 0)
165 return map(lambda x: x['id'], people)
167 def list_patches(patches):
168 """Dump a list of patches to stdout."""
169 print("%-7s %-12s %s" % ("ID", "State", "Name"))
170 print("%-7s %-12s %s" % ("--", "-----", "----"))
171 for patch in patches:
172 print("%-7d %-12s %s" % (patch['id'], patch['state'], patch['name']))
174 def action_list(rpc, filter, submitter_str, delegate_str):
175 filter.resolve_ids(rpc)
177 if submitter_str != "":
178 ids = person_ids_by_name(rpc, submitter_str)
180 sys.stderr.write("Note: Nobody found matching *%s*\n" % \
184 person = rpc.person_get(id)
185 print "Patches submitted by %s <%s>:" % \
186 (unicode(person['name']).encode("utf-8"), \
187 unicode(person['email']).encode("utf-8"))
189 f.add("submitter_id", id)
190 patches = rpc.patch_list(f.d)
191 list_patches(patches)
194 if delegate_str != "":
195 ids = person_ids_by_name(rpc, delegate_str)
197 sys.stderr.write("Note: Nobody found matching *%s*\n" % \
201 person = rpc.person_get(id)
202 print "Patches delegated to %s <%s>:" % \
203 (person['name'], person['email'])
205 f.add("delegate_id", id)
206 patches = rpc.patch_list(f.d)
207 list_patches(patches)
210 patches = rpc.patch_list(filter.d)
211 list_patches(patches)
213 def action_projects(rpc):
214 projects = rpc.project_list("", 0)
215 print("%-5s %-24s %s" % ("ID", "Name", "Description"))
216 print("%-5s %-24s %s" % ("--", "----", "-----------"))
217 for project in projects:
218 print("%-5d %-24s %s" % (project['id'], \
219 project['linkname'], \
222 def action_states(rpc):
223 states = rpc.state_list("", 0)
224 print("%-5s %s" % ("ID", "Name"))
225 print("%-5s %s" % ("--", "----"))
227 print("%-5d %s" % (state['id'], state['name']))
229 def action_info(rpc, patch_id):
230 patch = rpc.patch_get(patch_id)
231 s = "Information for patch id %d" % (patch_id)
234 for key, value in sorted(patch.iteritems()):
235 print("- %- 14s: %s" % (key, unicode(value).encode("utf-8")))
237 def action_get(rpc, patch_id):
238 patch = rpc.patch_get(patch_id)
239 s = rpc.patch_get_mbox(patch_id)
241 if patch == {} or len(s) == 0:
242 sys.stderr.write("Unable to get patch %d\n" % patch_id)
245 base_fname = fname = os.path.basename(patch['filename'])
247 while os.path.exists(fname):
248 fname = "%s.%d" % (base_fname, i)
254 sys.stderr.write("Unable to open %s for writing\n" % fname)
258 f.write(unicode(s).encode("utf-8"))
260 print "Saved patch to %s" % fname
262 sys.stderr.write("Failed to write to %s\n" % fname)
265 def action_apply(rpc, patch_id, apply_cmd=None):
266 patch = rpc.patch_get(patch_id)
268 sys.stderr.write("Error getting information on patch ID %d\n" % \
272 if apply_cmd is None:
273 print "Applying patch #%d to current directory" % patch_id
274 apply_cmd = ['patch', '-p1']
276 print "Applying patch #%d using %s" % (
277 patch_id, repr(' '.join(apply_cmd)))
279 print "Description: %s" % patch['name']
280 s = rpc.patch_get_mbox(patch_id)
282 proc = subprocess.Popen(apply_cmd, stdin = subprocess.PIPE)
283 proc.communicate(unicode(s).encode('utf-8'))
285 sys.stderr.write("Error: No patch content found\n")
288 def action_update_patch(rpc, patch_id, state = None, commit = None):
289 patch = rpc.patch_get(patch_id)
291 sys.stderr.write("Error getting information on patch ID %d\n" % \
298 state_id = state_id_by_name(rpc, state)
300 sys.stderr.write("Error: No State found matching %s*\n" % state)
302 params['state'] = state_id
305 params['commit_ref'] = commit
309 success = rpc.patch_set(patch_id, params)
310 except xmlrpclib.Fault, f:
311 sys.stderr.write("Error updating patch: %s\n" % f.faultString)
314 sys.stderr.write("Patch not updated\n")
316 def patch_id_from_hash(rpc, project, hash):
318 patch = rpc.patch_get_by_project_hash(project, hash)
319 except xmlrpclib.Fault:
320 # the server may not have the newer patch_get_by_project_hash function,
321 # so fall back to hash-only.
322 patch = rpc.patch_get_by_hash(hash)
325 sys.stderr.write("No patch has the hash provided\n")
328 patch_id = patch['id']
331 patch_id = int(patch_id)
333 sys.stderr.write("Invalid patch ID obtained from server\n")
337 auth_actions = ['update']
339 # unfortunately we currently have to revert to this ugly hack..
340 class _RecursiveHelpAction(argparse._HelpAction):
342 def __call__(self, parser, namespace, values, option_string=None):
346 subparsers_actions = [
347 action for action in parser._actions
348 if isinstance(action, argparse._SubParsersAction)
350 for subparsers_action in subparsers_actions:
351 for choice, subparser in subparsers_action.choices.items():
352 # gross but the whole thing is..
353 if (len(subparser._actions) == 2 \
354 and ['hash', 'id'] == [a.dest for a in subparser._actions])\
355 or len(subparser._actions) == 0:
357 print("command '{}'".format(choice))
358 print(subparser.format_help())
363 hash_parser = argparse.ArgumentParser(add_help=False, version=False)
364 hash_parser_x = hash_parser.add_mutually_exclusive_group(required=True)
365 hash_parser_x.add_argument(
366 '-h', metavar='HASH', dest='hash', action='store', required=False,
367 help='''Lookup by patch hash'''
369 hash_parser_x.add_argument(
370 'id', metavar='ID', nargs='?', action='store', type=int,
374 filter_parser = argparse.ArgumentParser(add_help=False, version=False)
375 filter_parser.add_argument(
376 '-s', metavar='STATE',
377 help='''Filter by patch state (e.g., 'New', 'Accepted', etc.)'''
379 filter_parser.add_argument(
380 '-p', metavar='PROJECT',
381 help='''Filter by project name (see 'projects' for list)'''
383 filter_parser.add_argument(
385 help='''Filter by submitter (name, e-mail substring search)'''
387 filter_parser.add_argument(
389 help='''Filter by delegate (name, e-mail substring search)'''
391 filter_parser.add_argument(
392 '-n', metavar='MAX#',
394 help='''Restrict number of results'''
396 filter_parser.add_argument(
397 '-m', metavar='MESSAGEID',
398 help='''Filter by Message-Id'''
400 filter_parser.add_argument(
401 'patch_name', metavar='STR', nargs='?',
402 help='substring to search for patches by name',
405 action_parser = argparse.ArgumentParser(
409 formatter_class=argparse.RawDescriptionHelpFormatter,
410 epilog='''(apply | get | info | view | update) (-h HASH | ID)''',
412 action_parser.add_argument(
415 action=_RecursiveHelpAction,
416 help='''Print this help text'''
419 subparsers = action_parser.add_subparsers(
423 apply_parser = subparsers.add_parser(
424 'apply', parents=[hash_parser],
426 help='''Apply a patch (in the current dir, using -p1)'''
428 apply_parser.set_defaults(subcmd='apply')
429 git_am_parser = subparsers.add_parser(
430 'git-am', parents=[hash_parser],
432 help='''Apply a patch to current git branch using "git am".'''
434 git_am_parser.set_defaults(subcmd='git-am')
435 git_am_parser.add_argument(
438 help='''pass --signoff to git-am'''
440 get_parser = subparsers.add_parser(
441 'get', parents=[hash_parser],
443 help='''Download a patch and save it locally'''
445 get_parser.set_defaults(subcmd='get')
446 info_parser = subparsers.add_parser(
447 'info', parents=[hash_parser],
449 help='''Display patchwork info about a given patch ID'''
451 info_parser.set_defaults(subcmd='info')
452 projects_parser = subparsers.add_parser(
455 help='''List all projects'''
457 projects_parser.set_defaults(subcmd='projects')
458 states_parser = subparsers.add_parser(
461 help='''Show list of potential patch states'''
463 states_parser.set_defaults(subcmd='states')
464 view_parser = subparsers.add_parser(
465 'view', parents=[hash_parser],
467 help='''View a patch'''
469 view_parser.set_defaults(subcmd='view')
470 update_parser = subparsers.add_parser(
471 'update', parents=[hash_parser],
473 help='''Update patch'''
475 update_parser.set_defaults(subcmd='update')
476 update_parser.add_argument(
477 '-c', metavar='COMMIT-REF',
478 help='''commit reference hash'''
480 update_parser.add_argument(
481 '-s', metavar='STATE',
483 help='''Set patch state (e.g., 'Accepted', 'Superseded' etc.)'''
486 list_parser = subparsers.add_parser("list",
489 parents=[filter_parser],
490 help='''List patches, using the optional filters specified
491 below and an optional substring to search for patches
494 list_parser.set_defaults(subcmd='list')
495 search_parser = subparsers.add_parser("search",
497 parents=[filter_parser],
498 help='''Alias for "list"'''
500 search_parser.set_defaults(subcmd='list')
501 if len(sys.argv) < 2:
502 action_parser.print_help()
505 args = action_parser.parse_args()
506 args=dict(vars(args))
520 action = args.get('subcmd')
523 state_str = args.get('s')
525 project_str = args.get('p')
527 submitter_str = args.get('w')
529 delegate_str = args.get('d')
531 commit_str = args.get('c')
533 hash_str = args.get('hash')
535 id_str = args.get('id')
537 msgid_str = args.get('m')
538 if args.get('n') != None:
540 filt.add("max_count", args.get('n'))
542 sys.stderr.write("Invalid maximum count '%s'\n" % args.get('n'))
543 action_parser.print_help()
546 # grab settings from config files
547 config = ConfigParser.ConfigParser()
548 config.read([CONFIG_FILE])
550 if not config.has_section('options'):
551 sys.stderr.write('~/.pwclientrc is in the old format. Migrating it...')
553 old_project = config.get('base','project')
555 new_config = ConfigParser.ConfigParser()
556 new_config.add_section('options')
558 new_config.set('options','default',old_project)
559 new_config.add_section(old_project)
561 new_config.set(old_project,'url',config.get('base','url'))
562 if config.has_option('auth', 'username'):
563 new_config.set(old_project,'username',config.get('auth','username'))
564 if config.has_option('auth', 'password'):
565 new_config.set(old_project,'password',config.get('auth','password'))
567 old_config_file = CONFIG_FILE + '.orig'
568 shutil.copy2(CONFIG_FILE,old_config_file)
570 with open(CONFIG_FILE, 'wb') as fd:
573 sys.stderr.write(' Done.\n')
574 sys.stderr.write('Your old ~/.pwclientrc was saved to %s\n' % old_config_file)
575 sys.stderr.write('and was converted to the new format. You may want to\n')
576 sys.stderr.write('inspect it before continuing.\n')
581 project_str = config.get('options', 'default')
583 sys.stderr.write("No default project configured in ~/.pwclientrc\n")
586 if not config.has_section(project_str):
587 sys.stderr.write("No section for project %s\n" % project_str)
590 if not config.has_option(project_str, 'url'):
591 sys.stderr.write("No URL for project %s\n" % project_str)
594 url = config.get(project_str, 'url')
596 (username, password) = (None, None)
598 if action in auth_actions:
599 if config.has_option(project_str, 'username') and \
600 config.has_option(project_str, 'password'):
602 use_https = url.startswith('https')
604 transport = BasicHTTPAuthTransport( \
605 config.get(project_str, 'username'),
606 config.get(project_str, 'password'),
610 sys.stderr.write(("The %s action requires authentication, "
611 "but no username or password\nis configured\n") % action)
615 filt.add("project", project_str)
618 filt.add("state", state_str)
621 filt.add("msgid", msgid_str)
624 rpc = xmlrpclib.Server(url, transport = transport)
626 sys.stderr.write("Unable to connect to %s\n" % url)
630 # hash_str and id_str are mutually exclusive
632 patch_id = patch_id_from_hash(rpc, project_str, hash_str)
634 # id_str from argparse is an int
637 if action == 'list' or action == 'search':
638 if args.get('patch_name') != None:
639 filt.add("name__icontains", args.get('patch_name'))
640 action_list(rpc, filt, submitter_str, delegate_str)
642 elif action.startswith('project'):
645 elif action.startswith('state'):
648 elif action == 'view':
649 s = rpc.patch_get_mbox(patch_id)
651 print unicode(s).encode("utf-8")
653 elif action in ('get', 'save', 'info'):
655 action_info(rpc, patch_id)
657 action_get(rpc, patch_id)
659 elif action == 'apply':
660 action_apply(rpc, patch_id)
662 elif action == 'git-am':
664 if args.get('signoff'):
666 action_apply(rpc, patch_id, cmd)
668 elif action == 'update':
669 action_update_patch(rpc, patch_id, state = state_str,
673 sys.stderr.write("Unknown action '%s'\n" % action)
676 if __name__ == "__main__":