aboutsummaryrefslogtreecommitdiffstats
path: root/libbe/command/tag.py
blob: 51e2abe7b9f0efc2af1a94303c7bb1b7649ed596 (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
# Copyright (C) 2009-2012 Chris Ball <cjb@laptop.org>
#                         Gianluca Montecchi <gian@grys.it>
#                         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 itertools

import libbe
import libbe.command
import libbe.command.util


TAG_TAG = 'TAG:'


class Tag (libbe.command.Command):
    __doc__ = """Tag a bug, or search bugs for tags

    >>> import 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_bugdirs({bd.uuid: bd})
    >>> cmd = Tag(ui=ui)

    >>> a = bd.bug_from_uuid('a')
    >>> print(a.extra_strings)
    []
    >>> ret = ui.run(cmd, args=['/a', 'GUI'])
    Tags for abc/a:
    GUI
    >>> bd.flush_reload()
    >>> a = bd.bug_from_uuid('a')
    >>> print(a.extra_strings)
    ['%(tag_tag)sGUI']
    >>> ret = ui.run(cmd, args=['/a', 'later'])
    Tags for abc/a:
    GUI
    later
    >>> ret = ui.run(cmd, args=['/a'])
    Tags for abc/a:
    GUI
    later
    >>> ret = ui.run(cmd, {'list':True})
    GUI
    later
    >>> ret = ui.run(cmd, args=['/a', 'Alphabetically first'])
    Tags for abc/a:
    Alphabetically first
    GUI
    later
    >>> bd.flush_reload()
    >>> a = bd.bug_from_uuid('a')
    >>> print(a.extra_strings)
    ['%(tag_tag)sAlphabetically first', '%(tag_tag)sGUI', '%(tag_tag)slater']
    >>> a.extra_strings = []
    >>> print(a.extra_strings)
    []
    >>> ret = ui.run(cmd, args=['/a'])
    >>> bd.flush_reload()
    >>> a = bd.bug_from_uuid('a')
    >>> print(a.extra_strings)
    []
    >>> ret = ui.run(cmd, args=['/a', 'Alphabetically first'])
    Tags for abc/a:
    Alphabetically first
    >>> ret = ui.run(cmd, {'remove':True}, ['/a', 'Alphabetically first'])
    >>> ui.cleanup()
    >>> bd.cleanup()
    """ % {'tag_tag':TAG_TAG}
    name = 'tag'

    def __init__(self, *args, **kwargs):
        libbe.command.Command.__init__(self, *args, **kwargs)
        self.options.extend([
                libbe.command.Option(name='remove', short_name='r',
                    help='Remove TAG (instead of adding it)'),
                libbe.command.Option(name='list', short_name='l',
                    help='List all available tags and exit'),
                ])
        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='tag', metavar='TAG', default=tuple(),
                    optional=True, repeatable=True),
                ])

    def _run(self, **params):
        if params['id'] == None and params['list'] == False:
            raise libbe.command.UserError('Please specify a bug id.')
        if params['id'] != None and params['list'] == True:
            raise libbe.command.UserError(
                'Do not specify a bug id with the --list option.')
        bugdirs = self._get_bugdirs()
        if params['list'] == True:
            tags = list(itertools.chain(*
                    [get_all_tags(bugdir) for bugdir in list(bugdirs.values())]))
            tags.sort()
            if len(tags) > 0:
                print('\n'.join(tags), file=self.stdout)
            return 0

        bugdir,bug,comment = (
            libbe.command.util.bugdir_bug_comment_from_user_id(
                bugdirs, params['id']))
        if len(params['tag']) > 0:
            tags = get_tags(bug)
            for tag in params['tag']:
                if params['remove'] == True:
                    tags.remove(tag)
                else: # add the tag
                    tags.append(tag)
            set_tags(bug, tags)

        tags = []
        for estr in bug.extra_strings:
            if estr.startswith(TAG_TAG):
                tags.append(estr[len(TAG_TAG):])

        if len(tags) > 0:
            print("Tags for %s:" % bug.id.user())
            print('\n'.join(tags))
        return 0

    def _long_help(self):
        return """
If TAG is given, add TAG to BUG-ID.  If it is not specified, just
print the tags for BUG-ID.

To search for bugs with a particular tag, try
  $ be list --extra-strings %s<your-tag>
""" % TAG_TAG

# functions exposed to other modules

def get_all_tags(bugdir):
    bugdir.load_all_bugs()
    tags = []
    for bug in bugdir:
        for tag in get_tags(bug):
            if tag not in tags:
                tags.append(tag)
    return tags

def get_tags(bug):
    tags = []
    for estr in bug.extra_strings:
        if estr.startswith(TAG_TAG):
            tag = estr[len(TAG_TAG):]
            if tag not in tags:
                tags.append(tag)
    return tags

def set_tags(bug, tags):
    estrs = bug.extra_strings
    new_estrs = []
    for estr in estrs:
        if not estr.startswith(TAG_TAG):
            new_estrs.append(estr)
    for tag in tags:
        new_estrs.append('%s%s' % (TAG_TAG, tag))
    bug.extra_strings = new_estrs # reassign to notice change

def append_tag(bug, tag):
    estrs = bug.extra_strings
    estrs.append('%s%s' % (TAG_TAG, tag))
    bug.extra_strings = estrs # reassign to notice change

def remove_tag(bug, tag):
    estrs = bug.extra_strings
    estrs.remove('%s%s' % (TAG_TAG, tag))
    bug.extra_strings = estrs # reassign to notice change