]> git.ozlabs.org Git - patchwork/blob - apps/patchwork/bin/pwclient.py
765e66b3db277d81b1dc5b45ed30e2372e40d9b5
[patchwork] / apps / patchwork / bin / pwclient.py
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 getopt
26 import string
27 import tempfile
28 import subprocess
29
30 # Default Patchwork remote XML-RPC server URL
31 # This script will check the PW_XMLRPC_URL environment variable
32 # for the URL to access.  If that is unspecified, it will fallback to
33 # the hardcoded default value specified here.
34 DEFAULT_URL = "http://patchwork:80/xmlrpc/"
35
36 PW_XMLRPC_URL = os.getenv("PW_XMLRPC_URL")
37 if not PW_XMLRPC_URL:
38     PW_XMLRPC_URL = DEFAULT_URL
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 def usage():
84     sys.stderr.write("Usage: %s <action> [options]\n\n" % \
85                         (os.path.basename(sys.argv[0])))
86     sys.stderr.write("Where <action> is one of:\n")
87     sys.stderr.write(
88 """        apply <ID>    : Apply a patch (in the current dir, using -p1)
89         get <ID>      : Download a patch and save it locally
90         projects      : List all projects
91         states        : Show list of potential patch states
92         list [str]    : List patches, using the optional filters specified
93                         below and an optional substring to search for patches
94                         by name
95         search [str]  : Same as 'list'
96         view <ID>     : View a patch\n""")
97     sys.stderr.write("""\nFilter options for 'list' and 'search':
98         -s <state>    : Filter by patch state (e.g., 'New', 'Accepted', etc.)
99         -p <project>  : Filter by project name (see 'projects' for list)
100         -w <who>      : Filter by submitter (name, e-mail substring search)
101         -d <who>      : Filter by delegate (name, e-mail substring search)
102         -n <max #>    : Restrict number of results\n""")
103     sys.exit(1)
104
105 def project_id_by_name(rpc, linkname):
106     """Given a project short name, look up the Project ID."""
107     if len(linkname) == 0:
108         return 0
109     # The search requires - instead of _
110     search = linkname.replace("_", "-")
111     projects = rpc.project_list(search, 0)
112     for project in projects:
113         if project['linkname'].replace("_", "-") == search:
114             return project['id']
115     return 0
116
117 def state_id_by_name(rpc, name):
118     """Given a partial state name, look up the state ID."""
119     if len(name) == 0:
120         return 0
121     states = rpc.state_list(name, 0)
122     for state in states:
123         if state['name'].lower().startswith(name.lower()):
124             return state['id']
125     return 0
126
127 def person_ids_by_name(rpc, name):
128     """Given a partial name or email address, return a list of the
129     person IDs that match."""
130     if len(name) == 0:
131         return []
132     people = rpc.person_list(name, 0)
133     return map(lambda x: x['id'], people)
134
135 def list_patches(patches):
136     """Dump a list of patches to stdout."""
137     print("%-5s %-12s %s" % ("ID", "State", "Name"))
138     print("%-5s %-12s %s" % ("--", "-----", "----"))
139     for patch in patches:
140         print("%-5d %-12s %s" % (patch['id'], patch['state'], patch['name']))
141
142 def action_list(rpc, filter, submitter_str, delegate_str):
143     filter.resolve_ids(rpc)
144
145     if submitter_str != "":
146         ids = person_ids_by_name(rpc, submitter_str)
147         if len(ids) == 0:
148             sys.stderr.write("Note: Nobody found matching *%s*\n", \
149                              submitter_str)
150         else:
151             for id in ids:
152                 person = rpc.person_get(id)
153                 print "Patches submitted by %s <%s>:" % \
154                         (person['name'], person['email'])
155                 f = filter
156                 f.add("submitter_id", id)
157                 patches = rpc.patch_list(f.d)
158                 list_patches(patches)
159         return
160
161     if delegate_str != "":
162         ids = person_ids_by_name(rpc, delegate_str)
163         if len(ids) == 0:
164             sys.stderr.write("Note: Nobody found matching *%s*\n", \
165                              delegate_str)
166         else:
167             for id in ids:
168                 person = rpc.person_get(id)
169                 print "Patches delegated to %s <%s>:" % \
170                         (person['name'], person['email'])
171                 f = filter
172                 f.add("delegate_id", id)
173                 patches = rpc.patch_list(f.d)
174                 list_patches(patches)
175         return
176
177     patches = rpc.patch_list(filter.d)
178     list_patches(patches)
179
180 def action_projects(rpc):
181     projects = rpc.project_list("", 0)
182     print("%-5s %-24s %s" % ("ID", "Name", "Description"))
183     print("%-5s %-24s %s" % ("--", "----", "-----------"))
184     for project in projects:
185         print("%-5d %-24s %s" % (project['id'], \
186                 project['linkname'].replace("_", "-"), \
187                 project['name']))
188
189 def action_states(rpc):
190     states = rpc.state_list("", 0)
191     print("%-5s %s" % ("ID", "Name"))
192     print("%-5s %s" % ("--", "----"))
193     for state in states:
194         print("%-5d %s" % (state['id'], state['name']))
195
196 def action_get(rpc, patch_id):
197     patch = rpc.patch_get(patch_id)
198     s = rpc.patch_get_mbox(patch_id)
199
200     if patch == {} or len(s) == 0:
201         sys.stderr.write("Unable to get patch %d\n" % patch_id)
202         sys.exit(1)
203
204     base_fname = fname = os.path.basename(patch['filename'])
205     i = 0
206     while os.path.exists(fname):
207         fname = "%s.%d" % (base_fname, i)
208         i += 1
209
210     try:
211         f = open(fname, "w")
212     except:
213         sys.stderr.write("Unable to open %s for writing\n" % fname)
214         sys.exit(1)
215
216     try:
217         f.write(s)
218         f.close()
219         print "Saved patch to %s" % fname
220     except:
221         sys.stderr.write("Failed to write to %s\n" % fname)
222         sys.exit(1)
223
224 def action_apply(rpc, patch_id):
225     patch = rpc.patch_get(patch_id)
226     if patch == {}:
227         sys.stderr.write("Error getting information on patch ID %d\n" % \
228                          patch_id)
229         sys.exit(1)
230     print "Applying patch #%d to current directory" % patch_id
231     print "Description: %s" % patch['name']
232     s = rpc.patch_get_mbox(patch_id)
233     if len(s) > 0:
234         proc = subprocess.Popen(['patch', '-p1'], stdin = subprocess.PIPE)
235         proc.communicate(s)
236     else:
237         sys.stderr.write("Error: No patch content found\n")
238         sys.exit(1)
239
240 def main():
241     try:
242         opts, args = getopt.getopt(sys.argv[2:], 's:p:w:d:n:')
243     except getopt.GetoptError, err:
244         print str(err)
245         usage()
246
247     if len(sys.argv) < 2:
248         usage()
249
250     action = sys.argv[1].lower()
251
252     filt = Filter()
253     submitter_str = ""
254     delegate_str = ""
255
256     for name, value in opts:
257         if name == '-s':
258             filt.add("state", value)
259         elif name == '-p':
260             filt.add("project", value)
261         elif name == '-w':
262             submitter_str = value
263         elif name == '-d':
264             delegate_str = value
265         elif name == '-n':
266             try:
267                 filt.add("max_count", int(value))
268             except:
269                 sys.stderr.write("Invalid maximum count '%s'\n" % value)
270                 usage()
271         else:
272             sys.stderr.write("Unknown option '%s'\n" % name)
273             usage()
274
275     if len(args) > 1:
276         sys.stderr.write("Too many arguments specified\n")
277         usage()
278
279     try:
280         rpc = xmlrpclib.Server(PW_XMLRPC_URL)
281     except:
282         sys.stderr.write("Unable to connect to %s\n" % PW_XMLRPC_URL)
283         sys.exit(1)
284
285     if action == 'list' or action == 'search':
286         if len(args) > 0:
287             filt.add("name__icontains", args[0])
288         action_list(rpc, filt, submitter_str, delegate_str)
289
290     elif action.startswith('project'):
291         action_projects(rpc)
292
293     elif action.startswith('state'):
294         action_states(rpc)
295
296     elif action == 'view':
297         try:
298             patch_id = int(args[0])
299         except:
300             sys.stderr.write("Invalid patch ID given\n")
301             sys.exit(1)
302
303         s = rpc.patch_get_mbox(patch_id)
304         if len(s) > 0:
305             print s
306
307     elif action == 'get' or action == 'save':
308         try:
309             patch_id = int(args[0])
310         except:
311             sys.stderr.write("Invalid patch ID given\n")
312             sys.exit(1)
313
314         action_get(rpc, patch_id)
315
316     elif action == 'apply':
317         try:
318             patch_id = int(args[0])
319         except:
320             sys.stderr.write("Invalid patch ID given\n")
321             sys.exit(1)
322
323         action_apply(rpc, patch_id)
324
325     else:
326         sys.stderr.write("Unknown action '%s'\n" % action)
327         usage()
328
329 if __name__ == "__main__":
330     main()