ui:util:pager: cleanup pager implementation
[be.git] / libbe / command / util.py
1 # Copyright (C) 2009-2012 Chris Ball <cjb@laptop.org>
2 #                         W. Trevor King <wking@tremily.us>
3 #
4 # This file is part of Bugs Everywhere.
5 #
6 # Bugs Everywhere is free software: you can redistribute it and/or modify it
7 # under the terms of the GNU General Public License as published by the Free
8 # Software Foundation, either version 2 of the License, or (at your option) any
9 # later version.
10 #
11 # Bugs Everywhere is distributed in the hope that it will be useful, but
12 # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 # FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
14 # more details.
15 #
16 # You should have received a copy of the GNU General Public License along with
17 # Bugs Everywhere.  If not, see <http://www.gnu.org/licenses/>.
18
19 import glob
20 import os.path
21
22 import libbe
23 import libbe.command
24
25 class Completer (object):
26     def __init__(self, options):
27         self.options = options
28     def __call__(self, bugdirs, fragment=None):
29         return [fragment]
30
31 def complete_command(command, argument, fragment=None):
32     """
33     List possible command completions for fragment.
34
35     command argument is not used.
36     """
37     return list(libbe.command.commands(command_names=True))
38
39 def comp_path(fragment=None):
40     """List possible path completions for fragment."""
41     if fragment == None:
42         fragment = '.'
43     comps = glob.glob(fragment+'*') + glob.glob(fragment+'/*')
44     if len(comps) == 1 and os.path.isdir(comps[0]):
45         comps.extend(glob.glob(comps[0]+'/*'))
46     return comps
47
48 def complete_path(command, argument, fragment=None):
49     """List possible path completions for fragment."""
50     return comp_path(fragment)
51
52 def complete_status(command, argument, fragment=None):
53     bd = sorted(command._get_bugdirs().items())[1]
54     import libbe.bug
55     return libbe.bug.status_values
56
57 def complete_severity(command, argument, fragment=None):
58     bd = sorted(command._get_bugdirs().items())[1]
59     import libbe.bug
60     return libbe.bug.severity_values
61
62 def assignees(bugdirs):
63     ret = set()
64     for bugdir in bugdirs.values():
65         bugdir.load_all_bugs()
66         ret.update(set([bug.assigned for bug in bugdir
67                         if bug.assigned != None]))
68     return list(ret)
69
70 def complete_assigned(command, argument, fragment=None):
71     return assignees(command._get_bugdirs())
72
73 def complete_extra_strings(command, argument, fragment=None):
74     if fragment == None:
75         return []
76     return [fragment]
77
78 def complete_bugdir_id(command, argument, fragment=None):
79     bugdirs = command._get_bugdirs()
80     return bugdirs.keys()
81
82 def complete_bug_id(command, argument, fragment=None):
83     return complete_bug_comment_id(command, argument, fragment,
84                                    comments=False)
85
86 def complete_bug_comment_id(command, argument, fragment=None,
87                             active_only=True, comments=True):
88     import libbe.bugdir
89     import libbe.util.id
90     bugdirs = command._get_bugdirs()
91     if fragment == None or len(fragment) == 0:
92         fragment = '/'
93     try:
94         p = libbe.util.id.parse_user(bugdirs, fragment)
95         matches = None
96         root,residual = (fragment, None)
97         if not root.endswith('/'):
98             root += '/'
99     except libbe.util.id.InvalidIDStructure, e:
100         return []
101     except libbe.util.id.NoIDMatches:
102         return []
103     except libbe.util.id.MultipleIDMatches, e:
104         if e.common == None:
105             # choose among bugdirs
106             return e.matches
107         common = e.common
108         matches = e.matches
109         root,residual = libbe.util.id.residual(common, fragment)
110         p = libbe.util.id.parse_user(bugdirs, e.common)
111     bug = None
112     if matches == None: # fragment was complete, get a list of children uuids
113         if p['type'] == 'bugdir':
114             bugdir = bugdirs[p['bugdir']]
115             matches = bugdir.uuids()
116             common = bugdir.id.user()
117         elif p['type'] == 'bug':
118             if comments == False:
119                 return [fragment]
120             bugdir = bugdirs[p['bugdir']]
121             bug = bugdir.bug_from_uuid(p['bug'])
122             matches = bug.uuids()
123             common = bug.id.user()
124         else:
125             assert p['type'] == 'comment', p
126             return [fragment]
127     if p['type'] == 'bugdir':
128         bugdir = bugdirs[p['bugdir']]
129         child_fn = bugdir.bug_from_uuid
130     elif p['type'] == 'bug':
131         if comments == False:
132             return[fragment]
133         bugdir = bugdirs[p['bugdir']]
134         if bug == None:
135             bug = bugdir.bug_from_uuid(p['bug'])
136         child_fn = bug.comment_from_uuid
137     elif p['type'] == 'comment':
138         assert matches == None, matches
139         return [fragment]
140     possible = []
141     common += '/'
142     for m in matches:
143         child = child_fn(m)
144         id = child.id.user()
145         possible.append(id.replace(common, root))
146     return possible
147
148 def select_values(string, possible_values, name="unkown"):
149     """
150     This function allows the user to select values from a list of
151     possible values.  The default is to select all the values:
152
153     >>> select_values(None, ['abc', 'def', 'hij'])
154     ['abc', 'def', 'hij']
155
156     The user selects values with a comma-separated limit_string.
157     Prepending a minus sign to such a list denotes blacklist mode:
158
159     >>> select_values('-abc,hij', ['abc', 'def', 'hij'])
160     ['def']
161
162     Without the leading -, the selection is in whitelist mode:
163
164     >>> select_values('abc,hij', ['abc', 'def', 'hij'])
165     ['abc', 'hij']
166
167     In either case, appropriate errors are raised if on of the
168     user-values is not in the list of possible values.  The name
169     parameter lets you make the error message more clear:
170
171     >>> select_values('-xyz,hij', ['abc', 'def', 'hij'], name="foobar")
172     Traceback (most recent call last):
173       ...
174     UserError: Invalid foobar xyz
175       ['abc', 'def', 'hij']
176     >>> select_values('xyz,hij', ['abc', 'def', 'hij'], name="foobar")
177     Traceback (most recent call last):
178       ...
179     UserError: Invalid foobar xyz
180       ['abc', 'def', 'hij']
181     """
182     possible_values = list(possible_values) # don't alter the original
183     if string == None:
184         pass
185     elif string.startswith('-'):
186         blacklisted_values = set(string[1:].split(','))
187         for value in blacklisted_values:
188             if value not in possible_values:
189                 raise libbe.command.UserError('Invalid %s %s\n  %s'
190                                 % (name, value, possible_values))
191             possible_values.remove(value)
192     else:
193         whitelisted_values = string.split(',')
194         for value in whitelisted_values:
195             if value not in possible_values:
196                 raise libbe.command.UserError(
197                     'Invalid %s %s\n  %s'
198                     % (name, value, possible_values))
199         possible_values = whitelisted_values
200     return possible_values
201
202 def bugdir_bug_comment_from_user_id(bugdirs, id):
203     p = libbe.util.id.parse_user(bugdirs, id)
204     if not p['type'] in ['bugdir', 'bug', 'comment']:
205         raise libbe.command.UserError(
206             '{} is a {} id, not a bugdir, bug, or comment id'.format(
207                 id, p['type']))
208     if p['bugdir'] not in bugdirs:
209         raise libbe.command.UserError(
210             "{} doesn't belong to any bugdirs in {}".format(
211                 id, sorted(bugdirs.keys())))
212     bugdir = bugdirs[p['bugdir']]
213     if p['bugdir'] != bugdir.uuid:
214         raise libbe.command.UserError(
215             "%s doesn't belong to this bugdir (%s)"
216             % (id, bugdir.uuid))
217     if 'bug' in p:
218         bug = bugdir.bug_from_uuid(p['bug'])
219         if 'comment' in p:
220             comment = bug.comment_from_uuid(p['comment'])
221         else:
222             comment = bug.comment_root
223     else:
224         bug = comment = None
225     return (bugdir, bug, comment)
226
227 def bug_from_uuid(bugdirs, uuid):
228     error = None
229     for bugdir in bugdirs.values():
230         try:
231             bug = bugdir.bug_from_uuid(uuid)
232         except libbe.bugdir.NoBugMatches as e:
233             error = e
234         else:
235             return bug
236     raise error