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)
109 def project_id_by_name(rpc, linkname):
110 """Given a project short name, look up the Project ID."""
111 if len(linkname) == 0:
113 projects = rpc.project_list(linkname, 0)
114 for project in projects:
115 if project['linkname'] == linkname:
119 def state_id_by_name(rpc, name):
120 """Given a partial state name, look up the state ID."""
123 states = rpc.state_list(name, 0)
125 if state['name'].lower().startswith(name.lower()):
129 def person_ids_by_name(rpc, name):
130 """Given a partial name or email address, return a list of the
131 person IDs that match."""
134 people = rpc.person_list(name, 0)
135 return map(lambda x: x['id'], people)
137 def list_patches(patches):
138 """Dump a list of patches to stdout."""
139 print("%-7s %-12s %s" % ("ID", "State", "Name"))
140 print("%-7s %-12s %s" % ("--", "-----", "----"))
141 for patch in patches:
142 print("%-7d %-12s %s" % (patch['id'], patch['state'], patch['name']))
144 def action_list(rpc, filter, submitter_str, delegate_str):
145 filter.resolve_ids(rpc)
147 if submitter_str != "":
148 ids = person_ids_by_name(rpc, submitter_str)
150 sys.stderr.write("Note: Nobody found matching *%s*\n" % \
154 person = rpc.person_get(id)
155 print "Patches submitted by %s <%s>:" % \
156 (unicode(person['name']).encode("utf-8"), \
157 unicode(person['email']).encode("utf-8"))
159 f.add("submitter_id", id)
160 patches = rpc.patch_list(f.d)
161 list_patches(patches)
164 if delegate_str != "":
165 ids = person_ids_by_name(rpc, delegate_str)
167 sys.stderr.write("Note: Nobody found matching *%s*\n" % \
171 person = rpc.person_get(id)
172 print "Patches delegated to %s <%s>:" % \
173 (person['name'], person['email'])
175 f.add("delegate_id", id)
176 patches = rpc.patch_list(f.d)
177 list_patches(patches)
180 patches = rpc.patch_list(filter.d)
181 list_patches(patches)
183 def action_projects(rpc):
184 projects = rpc.project_list("", 0)
185 print("%-5s %-24s %s" % ("ID", "Name", "Description"))
186 print("%-5s %-24s %s" % ("--", "----", "-----------"))
187 for project in projects:
188 print("%-5d %-24s %s" % (project['id'], \
189 project['linkname'], \
192 def action_states(rpc):
193 states = rpc.state_list("", 0)
194 print("%-5s %s" % ("ID", "Name"))
195 print("%-5s %s" % ("--", "----"))
197 print("%-5d %s" % (state['id'], state['name']))
199 def action_info(rpc, patch_id):
200 patch = rpc.patch_get(patch_id)
201 s = "Information for patch id %d" % (patch_id)
204 for key, value in sorted(patch.iteritems()):
205 print("- %- 14s: %s" % (key, unicode(value).encode("utf-8")))
207 def action_get(rpc, patch_id):
208 patch = rpc.patch_get(patch_id)
209 s = rpc.patch_get_mbox(patch_id)
211 if patch == {} or len(s) == 0:
212 sys.stderr.write("Unable to get patch %d\n" % patch_id)
215 base_fname = fname = os.path.basename(patch['filename'])
217 while os.path.exists(fname):
218 fname = "%s.%d" % (base_fname, i)
224 sys.stderr.write("Unable to open %s for writing\n" % fname)
228 f.write(unicode(s).encode("utf-8"))
230 print "Saved patch to %s" % fname
232 sys.stderr.write("Failed to write to %s\n" % fname)
235 def action_apply(rpc, patch_id, apply_cmd=None):
236 patch = rpc.patch_get(patch_id)
238 sys.stderr.write("Error getting information on patch ID %d\n" % \
242 if apply_cmd is None:
243 print "Applying patch #%d to current directory" % patch_id
244 apply_cmd = ['patch', '-p1']
246 print "Applying patch #%d using %s" % (
247 patch_id, repr(' '.join(apply_cmd)))
249 print "Description: %s" % patch['name']
250 s = rpc.patch_get_mbox(patch_id)
252 proc = subprocess.Popen(apply_cmd, stdin = subprocess.PIPE)
253 proc.communicate(unicode(s).encode('utf-8'))
255 sys.stderr.write("Error: No patch content found\n")
258 def action_update_patch(rpc, patch_id, state = None, commit = None):
259 patch = rpc.patch_get(patch_id)
261 sys.stderr.write("Error getting information on patch ID %d\n" % \
268 state_id = state_id_by_name(rpc, state)
270 sys.stderr.write("Error: No State found matching %s*\n" % state)
272 params['state'] = state_id
275 params['commit_ref'] = commit
279 success = rpc.patch_set(patch_id, params)
280 except xmlrpclib.Fault, f:
281 sys.stderr.write("Error updating patch: %s\n" % f.faultString)
284 sys.stderr.write("Patch not updated\n")
286 def patch_id_from_hash(rpc, project, hash):
288 patch = rpc.patch_get_by_project_hash(project, hash)
289 except xmlrpclib.Fault:
290 # the server may not have the newer patch_get_by_project_hash function,
291 # so fall back to hash-only.
292 patch = rpc.patch_get_by_hash(hash)
295 sys.stderr.write("No patch has the hash provided\n")
298 patch_id = patch['id']
301 patch_id = int(patch_id)
303 sys.stderr.write("Invalid patch ID obtained from server\n")
307 auth_actions = ['update']
309 # unfortunately we currently have to revert to this ugly hack..
310 class _RecursiveHelpAction(argparse._HelpAction):
312 def __call__(self, parser, namespace, values, option_string=None):
316 subparsers_actions = [
317 action for action in parser._actions
318 if isinstance(action, argparse._SubParsersAction)
320 for subparsers_action in subparsers_actions:
321 for choice, subparser in subparsers_action.choices.items():
322 # gross but the whole thing is..
323 if (len(subparser._actions) == 2 \
324 and ['hash', 'id'] == [a.dest for a in subparser._actions])\
325 or len(subparser._actions) == 0:
327 print("command '{}'".format(choice))
328 print(subparser.format_help())
333 hash_parser = argparse.ArgumentParser(add_help=False, version=False)
334 hash_parser_x = hash_parser.add_mutually_exclusive_group(required=True)
335 hash_parser_x.add_argument(
336 '-h', metavar='HASH', dest='hash', action='store', required=False,
337 help='''Lookup by patch hash'''
339 hash_parser_x.add_argument(
340 'id', metavar='ID', nargs='?', action='store', type=int,
344 filter_parser = argparse.ArgumentParser(add_help=False, version=False)
345 filter_parser.add_argument(
346 '-s', metavar='STATE',
347 help='''Filter by patch state (e.g., 'New', 'Accepted', etc.)'''
349 filter_parser.add_argument(
350 '-p', metavar='PROJECT',
351 help='''Filter by project name (see 'projects' for list)'''
353 filter_parser.add_argument(
355 help='''Filter by submitter (name, e-mail substring search)'''
357 filter_parser.add_argument(
359 help='''Filter by delegate (name, e-mail substring search)'''
361 filter_parser.add_argument(
362 '-n', metavar='MAX#',
364 help='''Restrict number of results'''
366 filter_parser.add_argument(
367 '-m', metavar='MESSAGEID',
368 help='''Filter by Message-Id'''
370 filter_parser.add_argument(
371 'patch_name', metavar='STR', nargs='?',
372 help='substring to search for patches by name',
375 action_parser = argparse.ArgumentParser(
379 formatter_class=argparse.RawDescriptionHelpFormatter,
380 epilog='''(apply | get | info | view | update) (-h HASH | ID)''',
382 action_parser.add_argument(
385 action=_RecursiveHelpAction,
386 help='''Print this help text'''
389 subparsers = action_parser.add_subparsers(
393 apply_parser = subparsers.add_parser(
394 'apply', parents=[hash_parser],
396 help='''Apply a patch (in the current dir, using -p1)'''
398 apply_parser.set_defaults(subcmd='apply')
399 git_am_parser = subparsers.add_parser(
400 'git-am', parents=[hash_parser],
402 help='''Apply a patch to current git branch using "git am".'''
404 git_am_parser.set_defaults(subcmd='git-am')
405 git_am_parser.add_argument(
408 help='''pass --signoff to git-am'''
410 get_parser = subparsers.add_parser(
411 'get', parents=[hash_parser],
413 help='''Download a patch and save it locally'''
415 get_parser.set_defaults(subcmd='get')
416 info_parser = subparsers.add_parser(
417 'info', parents=[hash_parser],
419 help='''Display patchwork info about a given patch ID'''
421 info_parser.set_defaults(subcmd='info')
422 projects_parser = subparsers.add_parser(
425 help='''List all projects'''
427 projects_parser.set_defaults(subcmd='projects')
428 states_parser = subparsers.add_parser(
431 help='''Show list of potential patch states'''
433 states_parser.set_defaults(subcmd='states')
434 view_parser = subparsers.add_parser(
435 'view', parents=[hash_parser],
437 help='''View a patch'''
439 view_parser.set_defaults(subcmd='view')
440 update_parser = subparsers.add_parser(
441 'update', parents=[hash_parser],
443 help='''Update patch'''
445 update_parser.set_defaults(subcmd='update')
446 update_parser.add_argument(
447 '-c', metavar='COMMIT-REF',
448 help='''commit reference hash'''
450 update_parser.add_argument(
451 '-s', metavar='STATE',
453 help='''Set patch state (e.g., 'Accepted', 'Superseded' etc.)'''
456 list_parser = subparsers.add_parser("list",
459 parents=[filter_parser],
460 help='''List patches, using the optional filters specified
461 below and an optional substring to search for patches
464 list_parser.set_defaults(subcmd='list')
465 search_parser = subparsers.add_parser("search",
467 parents=[filter_parser],
468 help='''Alias for "list"'''
470 search_parser.set_defaults(subcmd='list')
471 if len(sys.argv) < 2:
472 action_parser.print_help()
475 args = action_parser.parse_args()
476 args=dict(vars(args))
490 action = args.get('subcmd')
493 state_str = args.get('s')
495 project_str = args.get('p')
497 submitter_str = args.get('w')
499 delegate_str = args.get('d')
501 commit_str = args.get('c')
503 hash_str = args.get('hash')
505 id_str = args.get('id')
507 msgid_str = args.get('m')
508 if args.get('n') != None:
510 filt.add("max_count", args.get('n'))
512 sys.stderr.write("Invalid maximum count '%s'\n" % args.get('n'))
513 action_parser.print_help()
516 do_signoff = args.get('signoff')
518 # grab settings from config files
519 config = ConfigParser.ConfigParser()
520 config.read([CONFIG_FILE])
522 if not config.has_section('options'):
523 sys.stderr.write('~/.pwclientrc is in the old format. Migrating it...')
525 old_project = config.get('base','project')
527 new_config = ConfigParser.ConfigParser()
528 new_config.add_section('options')
530 new_config.set('options','default',old_project)
531 new_config.add_section(old_project)
533 new_config.set(old_project,'url',config.get('base','url'))
534 if config.has_option('auth', 'username'):
535 new_config.set(old_project,'username',config.get('auth','username'))
536 if config.has_option('auth', 'password'):
537 new_config.set(old_project,'password',config.get('auth','password'))
539 old_config_file = CONFIG_FILE + '.orig'
540 shutil.copy2(CONFIG_FILE,old_config_file)
542 with open(CONFIG_FILE, 'wb') as fd:
545 sys.stderr.write(' Done.\n')
546 sys.stderr.write('Your old ~/.pwclientrc was saved to %s\n' % old_config_file)
547 sys.stderr.write('and was converted to the new format. You may want to\n')
548 sys.stderr.write('inspect it before continuing.\n')
553 project_str = config.get('options', 'default')
555 sys.stderr.write("No default project configured in ~/.pwclientrc\n")
556 action_parser.print_help()
559 if not config.has_section(project_str):
560 sys.stderr.write("No section for project %s\n" % project_str)
563 if not config.has_option(project_str, 'url'):
564 sys.stderr.write("No URL for project %s\n" % project_str)
566 if not do_signoff and config.has_option('options', 'signoff'):
567 do_signoff = config.getboolean('options', 'signoff')
568 if not do_signoff and config.has_option(project_str, 'signoff'):
569 do_signoff = config.getboolean(project_str, 'signoff')
571 url = config.get(project_str, 'url')
573 (username, password) = (None, None)
575 if action in auth_actions:
576 if config.has_option(project_str, 'username') and \
577 config.has_option(project_str, 'password'):
579 use_https = url.startswith('https')
581 transport = BasicHTTPAuthTransport( \
582 config.get(project_str, 'username'),
583 config.get(project_str, 'password'),
587 sys.stderr.write(("The %s action requires authentication, "
588 "but no username or password\nis configured\n") % action)
592 filt.add("project", project_str)
595 filt.add("state", state_str)
598 filt.add("msgid", msgid_str)
601 rpc = xmlrpclib.Server(url, transport = transport)
603 sys.stderr.write("Unable to connect to %s\n" % url)
607 # hash_str and id_str are mutually exclusive
609 patch_id = patch_id_from_hash(rpc, project_str, hash_str)
611 # id_str from argparse is an int
614 if action == 'list' or action == 'search':
615 if args.get('patch_name') != None:
616 filt.add("name__icontains", args.get('patch_name'))
617 action_list(rpc, filt, submitter_str, delegate_str)
619 elif action.startswith('project'):
622 elif action.startswith('state'):
625 elif action == 'view':
626 s = rpc.patch_get_mbox(patch_id)
628 print unicode(s).encode("utf-8")
630 elif action in ('get', 'save', 'info'):
632 action_info(rpc, patch_id)
634 action_get(rpc, patch_id)
636 elif action == 'apply':
637 action_apply(rpc, patch_id)
639 elif action == 'git-am':
643 action_apply(rpc, patch_id, cmd)
645 elif action == 'update':
646 action_update_patch(rpc, patch_id, state = state_str,
650 sys.stderr.write("Unknown action '%s'\n" % action)
651 action_parser.print_help()
654 if __name__ == "__main__":