]> git.ozlabs.org Git - patchwork/blob - apps/patchwork/bin/pwclient
pwclient: simplify hash/id handling
[patchwork] / apps / patchwork / bin / pwclient
1 #!/usr/bin/env python
2 #
3 # Patchwork command line client
4 # Copyright (C) 2008 Nate Case <ncase@xes-inc.com>
5 #
6 # This file is part of the Patchwork package.
7 #
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.
12 #
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.
17 #
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
21
22 import os
23 import sys
24 import xmlrpclib
25 import argparse
26 import string
27 import tempfile
28 import subprocess
29 import base64
30 import ConfigParser
31 import shutil
32
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')
39
40 class Filter:
41     """Filter for selecting patches."""
42     def __init__(self):
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
46         self.state = ""
47         self.project = ""
48
49         # The dictionary that gets passed to via XML-RPC
50         self.d = {}
51
52     def add(self, field, value):
53         if field == 'state':
54             self.state = value
55         elif field == 'project':
56             self.project = value
57         else:
58             # OK to add directly
59             self.d[field] = value
60
61     def resolve_ids(self, rpc):
62         """Resolve State, Project, and Person IDs based on filter strings."""
63         if self.state != "":
64             id = state_id_by_name(rpc, self.state)
65             if id == 0:
66                 sys.stderr.write("Note: No State found matching %s*, " \
67                                  "ignoring filter\n" % self.state)
68             else:
69                 self.d['state_id'] = id
70
71         if self.project != "":
72             id = project_id_by_name(rpc, self.project)
73             if id == 0:
74                 sys.stderr.write("Note: No Project found matching %s, " \
75                                  "ignoring filter\n" % self.project)
76             else:
77                 self.d['project_id'] = id
78
79     def __str__(self):
80         """Return human-readable description of the filter."""
81         return str(self.d)
82
83 class BasicHTTPAuthTransport(xmlrpclib.SafeTransport):
84
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)
90
91     def authenticated(self):
92         return self.username != None and self.password != None
93
94     def send_host(self, connection, host):
95         xmlrpclib.Transport.send_host(self, connection, host)
96         if not self.authenticated():
97             return
98         credentials = '%s:%s' % (self.username, self.password)
99         auth = 'Basic ' + base64.encodestring(credentials).strip()
100         connection.putheader('Authorization', auth)
101
102     def make_connection(self, host):
103         if self.use_https:
104             fn = xmlrpclib.SafeTransport.make_connection
105         else:
106             fn = xmlrpclib.Transport.make_connection
107         return fn(self, host)
108
109 def usage():
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")
113     sys.stderr.write(
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
122                         by name
123         search [str]  : Same as 'list'
124         view <ID>     : View a patch
125         update [-s state] [-c commit-ref] <ID>
126                       : Update patch\n""")
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 \
135 invoked with:
136         -h <hash>     : Lookup by patch hash\n""")
137     sys.exit(1)
138
139 def project_id_by_name(rpc, linkname):
140     """Given a project short name, look up the Project ID."""
141     if len(linkname) == 0:
142         return 0
143     projects = rpc.project_list(linkname, 0)
144     for project in projects:
145         if project['linkname'] == linkname:
146             return project['id']
147     return 0
148
149 def state_id_by_name(rpc, name):
150     """Given a partial state name, look up the state ID."""
151     if len(name) == 0:
152         return 0
153     states = rpc.state_list(name, 0)
154     for state in states:
155         if state['name'].lower().startswith(name.lower()):
156             return state['id']
157     return 0
158
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."""
162     if len(name) == 0:
163         return []
164     people = rpc.person_list(name, 0)
165     return map(lambda x: x['id'], people)
166
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']))
173
174 def action_list(rpc, filter, submitter_str, delegate_str):
175     filter.resolve_ids(rpc)
176
177     if submitter_str != "":
178         ids = person_ids_by_name(rpc, submitter_str)
179         if len(ids) == 0:
180             sys.stderr.write("Note: Nobody found matching *%s*\n" % \
181                              submitter_str)
182         else:
183             for id in ids:
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"))
188                 f = filter
189                 f.add("submitter_id", id)
190                 patches = rpc.patch_list(f.d)
191                 list_patches(patches)
192         return
193
194     if delegate_str != "":
195         ids = person_ids_by_name(rpc, delegate_str)
196         if len(ids) == 0:
197             sys.stderr.write("Note: Nobody found matching *%s*\n" % \
198                              delegate_str)
199         else:
200             for id in ids:
201                 person = rpc.person_get(id)
202                 print "Patches delegated to %s <%s>:" % \
203                         (person['name'], person['email'])
204                 f = filter
205                 f.add("delegate_id", id)
206                 patches = rpc.patch_list(f.d)
207                 list_patches(patches)
208         return
209
210     patches = rpc.patch_list(filter.d)
211     list_patches(patches)
212
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'], \
220                 project['name']))
221
222 def action_states(rpc):
223     states = rpc.state_list("", 0)
224     print("%-5s %s" % ("ID", "Name"))
225     print("%-5s %s" % ("--", "----"))
226     for state in states:
227         print("%-5d %s" % (state['id'], state['name']))
228
229 def action_info(rpc, patch_id):
230     patch = rpc.patch_get(patch_id)
231     s = "Information for patch id %d" % (patch_id)
232     print(s)
233     print('-' * len(s))
234     for key, value in sorted(patch.iteritems()):
235         print("- %- 14s: %s" % (key, unicode(value).encode("utf-8")))
236
237 def action_get(rpc, patch_id):
238     patch = rpc.patch_get(patch_id)
239     s = rpc.patch_get_mbox(patch_id)
240
241     if patch == {} or len(s) == 0:
242         sys.stderr.write("Unable to get patch %d\n" % patch_id)
243         sys.exit(1)
244
245     base_fname = fname = os.path.basename(patch['filename'])
246     i = 0
247     while os.path.exists(fname):
248         fname = "%s.%d" % (base_fname, i)
249         i += 1
250
251     try:
252         f = open(fname, "w")
253     except:
254         sys.stderr.write("Unable to open %s for writing\n" % fname)
255         sys.exit(1)
256
257     try:
258         f.write(unicode(s).encode("utf-8"))
259         f.close()
260         print "Saved patch to %s" % fname
261     except:
262         sys.stderr.write("Failed to write to %s\n" % fname)
263         sys.exit(1)
264
265 def action_apply(rpc, patch_id, apply_cmd=None):
266     patch = rpc.patch_get(patch_id)
267     if patch == {}:
268         sys.stderr.write("Error getting information on patch ID %d\n" % \
269                          patch_id)
270         sys.exit(1)
271
272     if apply_cmd is None:
273       print "Applying patch #%d to current directory" % patch_id
274       apply_cmd = ['patch', '-p1']
275     else:
276       print "Applying patch #%d using %s" % (
277           patch_id, repr(' '.join(apply_cmd)))
278
279     print "Description: %s" % patch['name']
280     s = rpc.patch_get_mbox(patch_id)
281     if len(s) > 0:
282         proc = subprocess.Popen(apply_cmd, stdin = subprocess.PIPE)
283         proc.communicate(unicode(s).encode('utf-8'))
284     else:
285         sys.stderr.write("Error: No patch content found\n")
286         sys.exit(1)
287
288 def action_update_patch(rpc, patch_id, state = None, commit = None):
289     patch = rpc.patch_get(patch_id)
290     if patch == {}:
291         sys.stderr.write("Error getting information on patch ID %d\n" % \
292                          patch_id)
293         sys.exit(1)
294
295     params = {}
296
297     if state:
298         state_id = state_id_by_name(rpc, state)
299         if state_id == 0:
300             sys.stderr.write("Error: No State found matching %s*\n" % state)
301             sys.exit(1)
302         params['state'] = state_id
303
304     if commit:
305         params['commit_ref'] = commit
306
307     success = False
308     try:
309         success = rpc.patch_set(patch_id, params)
310     except xmlrpclib.Fault, f:
311         sys.stderr.write("Error updating patch: %s\n" % f.faultString)
312
313     if not success:
314         sys.stderr.write("Patch not updated\n")
315
316 def patch_id_from_hash(rpc, project, hash):
317     try:
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)
323
324     if patch == {}:
325         sys.stderr.write("No patch has the hash provided\n")
326         sys.exit(1)
327
328     patch_id = patch['id']
329     # be super paranoid
330     try:
331         patch_id = int(patch_id)
332     except:
333         sys.stderr.write("Invalid patch ID obtained from server\n")
334         sys.exit(1)
335     return patch_id
336
337 auth_actions = ['update']
338
339 # unfortunately we currently have to revert to this ugly hack..
340 class _RecursiveHelpAction(argparse._HelpAction):
341
342     def __call__(self, parser, namespace, values, option_string=None):
343         parser.print_help()
344         print
345
346         subparsers_actions = [
347             action for action in parser._actions
348             if isinstance(action, argparse._SubParsersAction)
349         ]
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:
356                     continue
357                 print("command '{}'".format(choice))
358                 print(subparser.format_help())
359
360         parser.exit()
361
362 def main():
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'''
368     )
369     hash_parser_x.add_argument(
370         'id', metavar='ID', nargs='?', action='store', type=int,
371         help='Patch ID',
372     )
373
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.)'''
378     )
379     filter_parser.add_argument(
380         '-p', metavar='PROJECT',
381         help='''Filter by project name (see 'projects' for list)'''
382     )
383     filter_parser.add_argument(
384         '-w', metavar='WHO',
385         help='''Filter by submitter (name, e-mail substring search)'''
386     )
387     filter_parser.add_argument(
388         '-d', metavar='WHO',
389         help='''Filter by delegate (name, e-mail substring search)'''
390     )
391     filter_parser.add_argument(
392         '-n', metavar='MAX#',
393         type=int,
394         help='''Restrict number of results'''
395     )
396     filter_parser.add_argument(
397         '-m', metavar='MESSAGEID',
398         help='''Filter by Message-Id'''
399     )
400     filter_parser.add_argument(
401         'patch_name', metavar='STR', nargs='?',
402         help='substring to search for patches by name',
403     )
404
405     action_parser = argparse.ArgumentParser(
406         prog='pwclient',
407         add_help=False,
408         version=False,
409         formatter_class=argparse.RawDescriptionHelpFormatter,
410         epilog='''(apply | get | info | view | update) (-h HASH | ID)''',
411     )
412     action_parser.add_argument(
413         '--help',
414         #action='help',
415         action=_RecursiveHelpAction,
416         help='''Print this help text'''
417     )
418
419     subparsers = action_parser.add_subparsers(
420         title='Commands',
421         metavar=''
422     )
423     apply_parser = subparsers.add_parser(
424         'apply', parents=[hash_parser],
425         add_help=False,
426         help='''Apply a patch (in the current dir, using -p1)'''
427     )
428     apply_parser.set_defaults(subcmd='apply')
429     git_am_parser = subparsers.add_parser(
430         'git-am', parents=[hash_parser],
431         add_help=False,
432         help='''Apply a patch to current git branch using "git am".'''
433     )
434     git_am_parser.set_defaults(subcmd='git-am')
435     git_am_parser.add_argument(
436         '-s', '--signoff',
437         action='store_true',
438         help='''pass --signoff to git-am'''
439     )
440     get_parser = subparsers.add_parser(
441         'get', parents=[hash_parser],
442         add_help=False,
443         help='''Download a patch and save it locally'''
444     )
445     get_parser.set_defaults(subcmd='get')
446     info_parser = subparsers.add_parser(
447         'info', parents=[hash_parser],
448         add_help=False,
449         help='''Display patchwork info about a given patch ID'''
450     )
451     info_parser.set_defaults(subcmd='info')
452     projects_parser = subparsers.add_parser(
453         'projects',
454         add_help=False,
455         help='''List all projects'''
456     )
457     projects_parser.set_defaults(subcmd='projects')
458     states_parser = subparsers.add_parser(
459         'states',
460         add_help=False,
461         help='''Show list of potential patch states'''
462     )
463     states_parser.set_defaults(subcmd='states')
464     view_parser = subparsers.add_parser(
465         'view', parents=[hash_parser],
466         add_help=False,
467         help='''View a patch'''
468     )
469     view_parser.set_defaults(subcmd='view')
470     update_parser = subparsers.add_parser(
471         'update', parents=[hash_parser],
472         add_help=False,
473         help='''Update patch'''
474     )
475     update_parser.set_defaults(subcmd='update')
476     update_parser.add_argument(
477         '-c', metavar='COMMIT-REF',
478         help='''commit reference hash'''
479     )
480     update_parser.add_argument(
481         '-s', metavar='STATE',
482         required=True,
483         help='''Set patch state (e.g., 'Accepted', 'Superseded' etc.)'''
484     )
485
486     list_parser = subparsers.add_parser("list",
487         add_help=False,
488         #aliases=['search'],
489         parents=[filter_parser],
490         help='''List patches, using the optional filters specified
491         below and an optional substring to search for patches
492         by name'''
493     )
494     list_parser.set_defaults(subcmd='list')
495     search_parser = subparsers.add_parser("search",
496         add_help=False,
497         parents=[filter_parser],
498         help='''Alias for "list"'''
499     )
500     search_parser.set_defaults(subcmd='list')
501     if len(sys.argv) < 2:
502         action_parser.print_help()
503         sys.exit(0)
504
505     args = action_parser.parse_args()
506     args=dict(vars(args))
507
508     # set defaults
509     filt = Filter()
510     submitter_str = ""
511     delegate_str = ""
512     project_str = ""
513     commit_str = ""
514     state_str = ""
515     hash_str = None
516     msgid_str = ""
517     id_str = None
518     url = DEFAULT_URL
519
520     action = args.get('subcmd')
521
522     if args.get('s'):
523         state_str = args.get('s')
524     if args.get('p'):
525         project_str = args.get('p')
526     if args.get('w'):
527         submitter_str = args.get('w')
528     if args.get('d'):
529         delegate_str = args.get('d')
530     if args.get('c'):
531         commit_str = args.get('c')
532     if args.get('hash'):
533         hash_str = args.get('hash')
534     if args.get('id'):
535         id_str = args.get('id')
536     if args.get('m'):
537         msgid_str = args.get('m')
538     if args.get('n') != None:
539         try:
540             filt.add("max_count", args.get('n'))
541         except:
542             sys.stderr.write("Invalid maximum count '%s'\n" % args.get('n'))
543             action_parser.print_help()
544             sys.exit(1)
545
546     # grab settings from config files
547     config = ConfigParser.ConfigParser()
548     config.read([CONFIG_FILE])
549
550     if not config.has_section('options'):
551         sys.stderr.write('~/.pwclientrc is in the old format. Migrating it...')
552
553         old_project = config.get('base','project')
554
555         new_config = ConfigParser.ConfigParser()
556         new_config.add_section('options')
557
558         new_config.set('options','default',old_project)
559         new_config.add_section(old_project)
560
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'))
566
567         old_config_file = CONFIG_FILE + '.orig'
568         shutil.copy2(CONFIG_FILE,old_config_file)
569
570         with open(CONFIG_FILE, 'wb') as fd:
571             new_config.write(fd)
572
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')
577         sys.exit(1)
578
579     if not project_str:
580         try:
581             project_str = config.get('options', 'default')
582         except:
583             sys.stderr.write("No default project configured in ~/.pwclientrc\n")
584             usage()
585
586     if not config.has_section(project_str):
587         sys.stderr.write("No section for project %s\n" % project_str)
588         sys.exit(1)
589
590     if not config.has_option(project_str, 'url'):
591         sys.stderr.write("No URL for project %s\n" % project_str)
592         sys.exit(1)
593
594     url = config.get(project_str, 'url')
595
596     (username, password) = (None, None)
597     transport = None
598     if action in auth_actions:
599         if config.has_option(project_str, 'username') and \
600                 config.has_option(project_str, 'password'):
601
602             use_https = url.startswith('https')
603
604             transport = BasicHTTPAuthTransport( \
605                     config.get(project_str, 'username'),
606                     config.get(project_str, 'password'),
607                     use_https)
608
609         else:
610             sys.stderr.write(("The %s action requires authentication, "
611                     "but no username or password\nis configured\n") % action)
612             sys.exit(1)
613
614     if project_str:
615         filt.add("project", project_str)
616
617     if state_str:
618         filt.add("state", state_str)
619
620     if msgid_str:
621         filt.add("msgid", msgid_str)
622
623     try:
624         rpc = xmlrpclib.Server(url, transport = transport)
625     except:
626         sys.stderr.write("Unable to connect to %s\n" % url)
627         sys.exit(1)
628
629     patch_id = None
630     # hash_str and id_str are mutually exclusive
631     if hash_str:
632         patch_id = patch_id_from_hash(rpc, project_str, hash_str)
633     else:
634         # id_str from argparse is an int
635         patch_id = id_str
636
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)
641
642     elif action.startswith('project'):
643         action_projects(rpc)
644
645     elif action.startswith('state'):
646         action_states(rpc)
647
648     elif action == 'view':
649         s = rpc.patch_get_mbox(patch_id)
650         if len(s) > 0:
651             print unicode(s).encode("utf-8")
652
653     elif action in ('get', 'save', 'info'):
654         if action == 'info':
655             action_info(rpc, patch_id)
656         else:
657             action_get(rpc, patch_id)
658
659     elif action == 'apply':
660         action_apply(rpc, patch_id)
661
662     elif action == 'git-am':
663         cmd = ['git', 'am']
664         if args.get('signoff'):
665             cmd.append('-s')
666         action_apply(rpc, patch_id, cmd)
667
668     elif action == 'update':
669         action_update_patch(rpc, patch_id, state = state_str,
670                 commit = commit_str)
671
672     else:
673         sys.stderr.write("Unknown action '%s'\n" % action)
674         usage()
675
676 if __name__ == "__main__":
677     main()