aboutsummaryrefslogtreecommitdiffstats
path: root/libbe/command/util.py
blob: 66628346a3e4e562b7dfa497f66e5ac329ad8d2b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
# Copyright (C) 2009-2010 W. Trevor King <wking@drexel.edu>
#
# This file is part of Bugs Everywhere.
#
# Bugs Everywhere is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation, either version 2 of the License, or (at your
# option) any later version.
#
# Bugs Everywhere is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Bugs Everywhere.  If not, see <http://www.gnu.org/licenses/>.

import glob
import os.path

import libbe
import libbe.command

class Completer (object):
    def __init__(self, options):
        self.options = options
    def __call__(self, bugdir, fragment=None):
        return [fragment]

def complete_command(command, argument, fragment=None):
    """
    List possible command completions for fragment.

    command argument is not used.
    """
    return list(libbe.command.commands(command_names=True))

def comp_path(fragment=None):
    """List possible path completions for fragment."""
    if fragment == None:
        fragment = '.'
    comps = glob.glob(fragment+'*') + glob.glob(fragment+'/*')
    if len(comps) == 1 and os.path.isdir(comps[0]):
        comps.extend(glob.glob(comps[0]+'/*'))
    return comps

def complete_path(command, argument, fragment=None):
    """List possible path completions for fragment."""
    return comp_path(fragment)

def complete_status(command, argument, fragment=None):
    bd = command._get_bugdir()
    import libbe.bug
    return libbe.bug.status_values

def complete_severity(command, argument, fragment=None):
    bd = command._get_bugdir()
    import libbe.bug
    return libbe.bug.severity_values

def assignees(bugdir):
    bugdir.load_all_bugs()
    return list(set([bug.assigned for bug in bugdir
                     if bug.assigned != None]))

def complete_assigned(command, argument, fragment=None):
    return assignees(command._get_bugdir())

def complete_extra_strings(command, argument, fragment=None):
    if fragment == None:
        return []
    return [fragment]

def complete_bug_id(command, argument, fragment=None):
    return complete_bug_comment_id(command, argument, fragment,
                                   comments=False)

def complete_bug_comment_id(command, argument, fragment=None,
                            active_only=True, comments=True):
    import libbe.bugdir
    import libbe.util.id
    bd = command._get_bugdir()
    if fragment == None or len(fragment) == 0:
        fragment = '/'
    try:
        p = libbe.util.id.parse_user(bd, fragment)
        matches = None
        root,residual = (fragment, None)
        if not root.endswith('/'):
            root += '/'
    except libbe.util.id.InvalidIDStructure, e:
        return []
    except libbe.util.id.NoIDMatches:
        return []
    except libbe.util.id.MultipleIDMatches, e:
        if e.common == None:
            # choose among bugdirs
            return e.matches
        common = e.common
        matches = e.matches
        root,residual = libbe.util.id.residual(common, fragment)
        p = libbe.util.id.parse_user(bd, e.common)
    bug = None
    if matches == None: # fragment was complete, get a list of children uuids
        if p['type'] == 'bugdir':
            matches = bd.uuids()
            common = bd.id.user()
        elif p['type'] == 'bug':
            if comments == False:
                return [fragment]
            bug = bd.bug_from_uuid(p['bug'])
            matches = bug.uuids()
            common = bug.id.user()
        else:
            assert p['type'] == 'comment', p
            return [fragment]
    if p['type'] == 'bugdir':
        child_fn = bd.bug_from_uuid
    elif p['type'] == 'bug':
        if comments == False:
            return[fragment]
        if bug == None:
            bug = bd.bug_from_uuid(p['bug'])
        child_fn = bug.comment_from_uuid
    elif p['type'] == 'comment':
        assert matches == None, matches
        return [fragment]
    possible = []
    common += '/'
    for m in matches:
        child = child_fn(m)
        id = child.id.user()
        possible.append(id.replace(common, root))
    return possible

def select_values(string, possible_values, name="unkown"):
    """
    This function allows the user to select values from a list of
    possible values.  The default is to select all the values:

    >>> select_values(None, ['abc', 'def', 'hij'])
    ['abc', 'def', 'hij']

    The user selects values with a comma-separated limit_string.
    Prepending a minus sign to such a list denotes blacklist mode:

    >>> select_values('-abc,hij', ['abc', 'def', 'hij'])
    ['def']

    Without the leading -, the selection is in whitelist mode:

    >>> select_values('abc,hij', ['abc', 'def', 'hij'])
    ['abc', 'hij']

    In either case, appropriate errors are raised if on of the
    user-values is not in the list of possible values.  The name
    parameter lets you make the error message more clear:

    >>> select_values('-xyz,hij', ['abc', 'def', 'hij'], name="foobar")
    Traceback (most recent call last):
      ...
    UserError: Invalid foobar xyz
      ['abc', 'def', 'hij']
    >>> select_values('xyz,hij', ['abc', 'def', 'hij'], name="foobar")
    Traceback (most recent call last):
      ...
    UserError: Invalid foobar xyz
      ['abc', 'def', 'hij']
    """
    possible_values = list(possible_values) # don't alter the original
    if string == None:
        pass
    elif string.startswith('-'):
        blacklisted_values = set(string[1:].split(','))
        for value in blacklisted_values:
            if value not in possible_values:
                raise libbe.command.UserError('Invalid %s %s\n  %s'
                                % (name, value, possible_values))
            possible_values.remove(value)
    else:
        whitelisted_values = string.split(',')
        for value in whitelisted_values:
            if value not in possible_values:
                raise libbe.command.UserError(
                    'Invalid %s %s\n  %s'
                    % (name, value, possible_values))
        possible_values = whitelisted_values
    return possible_values

def bug_comment_from_user_id(bugdir, id):
    p = libbe.util.id.parse_user(bugdir, id)
    if not p['type'] in ['bug', 'comment']:
        raise libbe.command.UserError(
            '%s is a %s id, not a bug or comment id' % (id, p['type']))
    if p['bugdir'] != bugdir.uuid:
        raise libbe.command.UserError(
            "%s doesn't belong to this bugdir (%s)"
            % (id, bugdir.uuid))
    bug = bugdir.bug_from_uuid(p['bug'])
    if 'comment' in p:
        comment = bug.comment_from_uuid(p['comment'])
    else:
        comment = bug.comment_root
    return (bug, comment)