~jelmer/qbrz/relative

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
226
227
228
229
230
231
232
233
234
235
236
# -*- coding: utf-8 -*-
#
# QBzr - Qt frontend to Bazaar commands
# Copyright (C) 2009 Alexander Belchenko
#
# This program 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.
#
# This program 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 this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

"""Commit data save/restore support."""


class CommitData(object):
    """Class to manipulate with commit data.

    Hold the data as dictionary and provide dict-like interface.
    All strings saved internally as unicode.

    Known items for data dict:
        message: main commit message.
        bugs: string with space separated fixed bugs ids
            in the form 'id:number'
        authors: string with name(s) of patch author(s)
        file_message: dict for per-file commit messages (used e.g. in MySQL),
            keys in this dict are filenames/fileids,
            values are specific commit messages.
        old_revid: old tip revid (before uncommit)
        new_revid: new tip revid (after uncommit)

    Pair of revision ids (old_revid and new_revid) could be used
    to get all revision messages from uncommitted chain.
    XXX provide some helper API to get uncommitted chain of revisions
    and/or graph and/or revisions data.

    [bialix 20090812] Data saved in branch.conf in [commit_data] section
    as plain dict.
    """

    def __init__(self, branch=None, tree=None, data=None):
        """Initialize data object attached to some tree.
        @param tree: working tree object for commit/uncommit.
        @param branch: branch object for commit/uncommit.
        @param data: initial data values (dictionary).
        """
        self._tree = tree
        self._branch = branch
        self._data = {}
        if data:
            self._data.update(data)

    def _filtered_data(self):
        """Return copy of internal data dictionary without
        keys with "empty" values (i.e. those equal to empty
        string or None).
        """
        d = {}
        for k,v in self._data.items():
            if v not in (None, ''):
                d[k] = v
        return d

    def __bool__(self):
        """Check if there is some data actually.
        @return: True if data dictionary is not empty.
        """
        return bool(self._filtered_data())

    def __getitem__(self, key):
        """Read the value of specified key via dict-like interface, e.g. a[key].
        @param key: key in data dictionary.
        @return: value or None if there is no such key.
        """
        return self._data.get(key)

    def __setitem__(self, key, value):
        """Set new value for specified key."""
        self._data[key] = value

    def __delitem__(self, key):
        """Delete key from dictionary."""
        del self._data[key]

    def keys(self):
        """Return keys of internal dict."""
        return list(self._data.keys())

    def as_dict(self):
        return self._data.copy()

    def set_data(self, data=None, **kw):
        """Set new data to dictionary (e.g. to save data from commit dialog).
        @param data: dictionary with new data.
        @param kw: pairs name=value to insert.
        """
        if data:
            self._data.update(data)
        for key, value in kw.items():
            self._data[key] = value

    def set_data_on_uncommit(self, old_revid, new_revid):
        """Set data from post_uncommit hook.
        @param old_revid: old tip revid (before uncommit)
        @param new_revid: new tip revid (after uncommit). Could be None.
        """
        from breezy.plugins.qbrz.lib.bugs import bug_urls_to_ids
        branch = self._get_branch()
        revision = branch.repository.get_revision(old_revid)
        # remember revids
        self._data['old_revid'] = old_revid
        if new_revid is None:
            from breezy.revision import NULL_REVISION
            new_revid = NULL_REVISION
        self._data['new_revid'] = new_revid
        # set data from revision
        self._data['message'] = revision.message or ''
        bug_urls = revision.properties.get('bugs', None)
        if bug_urls:
            self._data['bugs'] = ' '.join(bug_urls_to_ids(bug_urls.split('\n')))

    def compare_data(self, other, all_keys=True):
        """Compare this data with other data.
        @return:    True if data equals.
        @param other: other object (dict or instance of CommitData).
        @param all_keys: if True all keys in both objects
            are compared. If False then only keys in this
            instance compared with corresponding keys in other
            instance.
        """
        try:
            for k,v in self._data.items():
                if v != other[k]:
                    return False
        except KeyError:
            return False
        if all_keys:
            if set(self._data.keys()) != set(other.keys()):
                return False
        return True

    def _load_old_data(self):
        """Load saved data in old format."""
        return

    def load(self):
        """Load saved data from branch/tree."""
        config = self._get_branch_config()
        data = config.get_user_option('commit_data', expand=False)
        if data:
            self.set_data(data)
        else:
            # for backward compatibility
            self._load_old_data()

    def save(self):
        """Save data to the branch/tree."""
        br = self._get_branch()
        br.lock_write()
        try:
            # XXX save should wipe if self._data is empty
            self._set_new_commit_data(self._filtered_data())
            # clear old data
            self._wipe_old_data()
        finally:
            br.unlock()

    def _wipe_old_data(self):
        """Wipe saved data in old format."""
        return

    def wipe(self):
        """Delete saved data from branch/tree config."""
        br = self._get_branch()
        br.lock_write()
        try:
            self._set_new_commit_data({})
            # clear old data
            self._wipe_old_data()
        finally:
            br.unlock()

    def _get_branch(self):
        """Return branch object if either branch or tree was specified on init.
        Raise BzrInternalError otherwise.
        """
        if self._branch:
            return self._branch
        if self._tree:
            return self._tree.branch
        # too bad
        from breezy import errors
        raise errors.BzrInternalError("CommitData has no saved branch or tree.")

    def _get_branch_config(self):
        return self._get_branch().get_config()

    def _set_new_commit_data(self, new_data):
        config = self._get_branch_config()
        old_data = config.get_user_option('commit_data', expand=False)
        if old_data == new_data:
            return
        try:
            config.set_user_option('commit_data', new_data)
        except AttributeError:
            pass


class QBzrCommitData(CommitData):
    """CommitData variant with backward compatibility support.
    This class knows about old data saved as qbrz_commit_message
    and can provide automatic migration of data.
    """

    def _load_old_data(self):
        config = self._get_branch_config()
        old_data = config.get_user_option('qbrz_commit_message', expand=False)
        if old_data:
            self.set_data(message=old_data)

    def _wipe_old_data(self):
        config = self._get_branch_config()
        if config.get_user_option('qbrz_commit_message', expand=False):
            config.set_user_option('qbrz_commit_message', '')


# in similar way to QBzrCommitData it's possible to implement
# class for bzr-gtk.