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