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)
329 auth_actions = ['update']
333 opts, args = getopt.getopt(sys.argv[2:], 's:p:w:d:n:c:h:m:')
334 except getopt.GetoptError, err:
338 if len(sys.argv) < 2:
341 action = sys.argv[1].lower()
354 for name, value in opts:
360 submitter_str = value
371 filt.add("max_count", int(value))
373 sys.stderr.write("Invalid maximum count '%s'\n" % value)
376 sys.stderr.write("Unknown option '%s'\n" % name)
380 sys.stderr.write("Too many arguments specified\n")
383 # grab settings from config files
384 config = ConfigParser.ConfigParser()
385 config.read([CONFIG_FILE])
387 if not config.has_section('options'):
388 sys.stderr.write('~/.pwclientrc is in the old format. Migrating it...')
390 old_project = config.get('base','project')
392 new_config = ConfigParser.ConfigParser()
393 new_config.add_section('options')
395 new_config.set('options','default',old_project)
396 new_config.add_section(old_project)
398 new_config.set(old_project,'url',config.get('base','url'))
399 if config.has_option('auth', 'username'):
400 new_config.set(old_project,'username',config.get('auth','username'))
401 if config.has_option('auth', 'password'):
402 new_config.set(old_project,'password',config.get('auth','password'))
404 old_config_file = CONFIG_FILE + '.orig'
405 shutil.copy2(CONFIG_FILE,old_config_file)
407 with open(CONFIG_FILE, 'wb') as fd:
410 sys.stderr.write(' Done.\n')
411 sys.stderr.write('Your old ~/.pwclientrc was saved to %s\n' % old_config_file)
412 sys.stderr.write('and was converted to the new format. You may want to\n')
413 sys.stderr.write('inspect it before continuing.\n')
418 project_str = config.get('options', 'default')
420 sys.stderr.write("No default project configured in ~/.pwclientrc\n")
423 if not config.has_section(project_str):
424 sys.stderr.write("No section for project %s\n" % project_str)
427 if not config.has_option(project_str, 'url'):
428 sys.stderr.write("No URL for project %s\n" % project_str)
431 url = config.get(project_str, 'url')
433 (username, password) = (None, None)
435 if action in auth_actions:
436 if config.has_option(project_str, 'username') and \
437 config.has_option(project_str, 'password'):
439 use_https = url.startswith('https')
441 transport = BasicHTTPAuthTransport( \
442 config.get(project_str, 'username'),
443 config.get(project_str, 'password'),
447 sys.stderr.write(("The %s action requires authentication, "
448 "but no username or password\nis configured\n") % action)
452 filt.add("project", project_str)
455 filt.add("state", state_str)
458 filt.add("msgid", msgid_str)
461 rpc = xmlrpclib.Server(url, transport = transport)
463 sys.stderr.write("Unable to connect to %s\n" % url)
468 patch_id = patch_id_from_hash(rpc, project_str, hash_str)
470 sys.stderr.write("No patch has the hash provided\n")
474 if action == 'list' or action == 'search':
476 filt.add("name__icontains", args[0])
477 action_list(rpc, filt, submitter_str, delegate_str)
479 elif action.startswith('project'):
482 elif action.startswith('state'):
485 elif action == 'view':
487 patch_id = patch_id or int(args[0])
489 sys.stderr.write("Invalid patch ID given\n")
492 s = rpc.patch_get_mbox(patch_id)
494 print unicode(s).encode("utf-8")
496 elif action in ('get', 'save', 'info'):
498 patch_id = patch_id or int(args[0])
500 sys.stderr.write("Invalid patch ID given\n")
504 action_info(rpc, patch_id)
506 action_get(rpc, patch_id)
508 elif action == 'apply':
510 patch_id = patch_id or int(args[0])
512 sys.stderr.write("Invalid patch ID given\n")
515 action_apply(rpc, patch_id)
517 elif action == 'git-am':
519 patch_id = patch_id or int(args[0])
521 sys.stderr.write("Invalid patch ID given\n")
524 action_apply(rpc, patch_id, ['git', 'am'])
526 elif action == 'update':
528 patch_id = patch_id or int(args[0])
530 sys.stderr.write("Invalid patch ID given\n")
533 action_update_patch(rpc, patch_id, state = state_str,
537 sys.stderr.write("Unknown action '%s'\n" % action)
540 if __name__ == "__main__":