aboutsummaryrefslogtreecommitdiffstats
path: root/libbe/command/target.py
blob: b13647ea38bce69029a665ff981de388f10c3153 (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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
# Copyright (C) 2005-2012 Aaron Bentley <abentley@panoramicfeedback.com>
#                         Chris Ball <cjb@laptop.org>
#                         Gianluca Montecchi <gian@grys.it>
#                         Marien Zwart <marien.zwart@gmail.com>
#                         Thomas Gerigk <tgerigk@gmx.de>
#                         W. Trevor King <wking@tremily.us>
#
# 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 libbe
import libbe.command
import libbe.command.util
import libbe.command.depend
import libbe.util.id


class Target (libbe.command.Command):
    """Assorted bug target manipulations and queries

    >>> import os, StringIO, sys
    >>> import libbe.bugdir
    >>> bd = libbe.bugdir.SimpleBugDir(memory=False)
    >>> io = libbe.command.StringInputOutput()
    >>> io.stdout = sys.stdout
    >>> ui = libbe.command.UserInterface(io=io)
    >>> ui.storage_callbacks.set_storage(bd.storage)
    >>> cmd = Target(ui=ui)

    >>> ret = ui.run(cmd, args=['/a'])
    No target assigned.
    >>> ret = ui.run(cmd, args=['/a', 'tomorrow'])
    >>> ret = ui.run(cmd, args=['/a'])
    tomorrow

    >>> ui.io.stdout = StringIO.StringIO()
    >>> ret = ui.run(cmd, {'resolve':True}, ['tomorrow'])
    >>> output = ui.io.get_stdout().strip()
    >>> bd.flush_reload()
    >>> target = bd.bug_from_uuid(output)
    >>> print(target.summary)
    tomorrow
    >>> print(target.severity)
    target

    >>> ui.io.stdout = sys.stdout
    >>> ret = ui.run(cmd, args=['/a', 'none'])
    >>> ret = ui.run(cmd, args=['/a'])
    No target assigned.
    >>> ui.cleanup()
    >>> bd.cleanup()
    """
    name = 'target'

    def __init__(self, *args, **kwargs):
        libbe.command.Command.__init__(self, *args, **kwargs)
        self.options.extend([
                libbe.command.Option(name='resolve', short_name='r',
                    help="Print the UUID for the target bug whose summary "
                    "matches TARGET.  If TARGET is not given, print the UUID "
                    "of the current bugdir target."),
                libbe.command.Option(name='bugdir', short_name='b',
                    help='Short bugdir UUID for the target resolution.  You '
                    'only need to set this if you have multiple bugdirs in '
                    'your repository.',
                    arg=libbe.command.Argument(
                        name='bugdir', metavar='ID', default=None,
                        completion_callback=libbe.command.util.complete_bugdir_id)),
                ])
        self.args.extend([
                libbe.command.Argument(
                    name='id', metavar='BUG-ID', optional=True,
                    completion_callback=libbe.command.util.complete_bug_id),
                libbe.command.Argument(
                    name='target', metavar='TARGET', optional=True,
                    completion_callback=complete_target),
                ])

    def _run(self, **params):
        if params['resolve'] == False:
            if params['id'] == None:
                raise libbe.command.UserError('Please specify a bug id.')
        else:
            if params['target'] != None:
                raise libbe.command.UserError('Too many arguments')
            params['target'] = params.pop('id')
        bugdirs = self._get_bugdirs()
        if params['resolve'] == True:
            if params['bugdir']:
                bugdir = bugdirs[params['bugdir']]
            elif len(bugdirs) == 1:
                bugdir = list(bugdirs.values())[0]
            else:
                raise libbe.command.UserError(
                    'Ambiguous bugdir {}'.format(sorted(bugdirs.values())))
            bug = bug_from_target_summary(bugdirs, bugdir, params['target'])
            if bug == None:
                print('No target assigned.', file=self.stdout)
            else:
                print(bug.id.long_user(), file=self.stdout)
            return 0
        bugdir,bug,comment = (
            libbe.command.util.bugdir_bug_comment_from_user_id(
                bugdirs, params['id']))
        if params['target'] == None:
            target = bug_target(bugdirs, bug)
            if target == None:
                print('No target assigned.', file=self.stdout)
            else:
                print(target.summary, file=self.stdout)
        else:
            if params['target'] == 'none':
                target = remove_target(bugdirs, bug)
            else:
                target = add_target(bugdirs, bugdir, bug, params['target'])
        return 0

    def usage(self):
        return 'usage: be %(name)s BUG-ID [TARGET]\nor:    be %(name)s --resolve [TARGET]' \
            % vars(self.__class__)

    def _long_help(self):
        return """
Assorted bug target manipulations and queries.

If no target is specified, the bug's current target is printed.  If
TARGET is specified, it will be assigned to the bug, creating a new
target bug if necessary.

Targets are free-form; any text may be specified.  They will generally
be milestone names or release numbers.  The value "none" can be used
to unset the target.

In the alternative `be target --resolve TARGET` form, print the UUID
of the target-bug with summary TARGET.  If target is not given, return
use the bugdir's current target (see `be set`).

If you want to list all bugs blocking the current target, try
  $ be depend --status -closed,fixed,wontfix --severity -target \
    $(be target --resolve)

If you want to set the current bugdir target by summary (rather than
by UUID), try
  $ be set target $(be target --resolve SUMMARY)
"""

def bug_from_target_summary(bugdirs, bugdir, summary=None):
    if summary == None:
        if bugdir.target == None:
            return None
        else:
            return bugdir.bug_from_uuid(bugdir.target)
    matched = []
    for uuid in bugdir.uuids():
        bug = bugdir.bug_from_uuid(uuid)
        if bug.severity == 'target' and bug.summary == summary:
            matched.append(bug)
    if len(matched) == 0:
        return None
    if len(matched) > 1:
        raise Exception('Several targets with same summary:  %s'
                        % '\n  '.join([bug.uuid for bug in matched]))
    return matched[0]

def bug_target(bugdirs, bug):
    if bug.severity == 'target':
        return bug
    matched = []
    for blocked in libbe.command.depend.get_blocks(bugdirs, bug):
        if blocked.severity == 'target':
            matched.append(blocked)
    if len(matched) == 0:
        return None
    if len(matched) > 1:
        raise Exception('This bug (%s) blocks several targets:  %s'
                        % (bug.uuid,
                           '\n  '.join([b.uuid for b in matched])))
    return matched[0]

def remove_target(bugdirs, bug):
    target = bug_target(bugdirs, bug)
    libbe.command.depend.remove_block(target, bug)
    return target

def add_target(bugdirs, bugdir, bug, summary):
    target = bug_from_target_summary(bugdirs, bugdir, summary)
    if target == None:
        target = bugdir.new_bug(summary=summary)
        target.severity = 'target'
    libbe.command.depend.add_block(target, bug)
    return target

def targets(bugdirs):
    """Generate all possible target bug summaries."""
    for bugdir in list(bugdirs.values()):
        bugdir.load_all_bugs()
        for bug in bugdir:
            if bug.severity == 'target':
                yield bug.summary

def target_dict(bugdirs):
    """
    Return a dict with bug UUID keys and bug summary values for all
    target bugs.
    """
    ret = {}
    for bug in targets(bugdirs):
        ret[bug.uuid] = bug
    return ret

def complete_target(command, argument, fragment=None):
    """List possible command completions for fragment."""
    return targets(command._get_bugdirs())