/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to breezy/views.py

  • Committer: Jelmer Vernooij
  • Date: 2018-05-19 13:16:11 UTC
  • mto: (6968.4.3 git-archive)
  • mto: This revision was merged to the branch mainline in revision 6972.
  • Revision ID: jelmer@jelmer.uk-20180519131611-l9h9ud41j7qg1m03
Move tar/zip to breezy.archive.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2008 Canonical Ltd
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
"""View management.
 
18
 
 
19
Views are contained within a working tree and normally constructed
 
20
when first accessed.  Clients should do, for example, ...
 
21
 
 
22
  tree.views.lookup_view()
 
23
"""
 
24
 
 
25
from __future__ import absolute_import
 
26
 
 
27
import re
 
28
 
 
29
from . import (
 
30
    errors,
 
31
    osutils,
 
32
    )
 
33
 
 
34
 
 
35
_VIEWS_FORMAT_MARKER_RE = re.compile(r'Bazaar views format (\d+)')
 
36
_VIEWS_FORMAT1_MARKER = "Bazaar views format 1\n"
 
37
 
 
38
 
 
39
class NoSuchView(errors.BzrError):
 
40
    """A view does not exist.
 
41
    """
 
42
 
 
43
    _fmt = u"No such view: %(view_name)s."
 
44
 
 
45
    def __init__(self, view_name):
 
46
        self.view_name = view_name
 
47
 
 
48
 
 
49
class ViewsNotSupported(errors.BzrError):
 
50
    """Views are not supported by a tree format.
 
51
    """
 
52
 
 
53
    _fmt = ("Views are not supported by %(tree)s;"
 
54
            " use 'brz upgrade' to change your tree to a later format.")
 
55
 
 
56
    def __init__(self, tree):
 
57
        self.tree = tree
 
58
 
 
59
 
 
60
class FileOutsideView(errors.BzrError):
 
61
 
 
62
    _fmt = ('Specified file "%(file_name)s" is outside the current view: '
 
63
            '%(view_str)s')
 
64
 
 
65
    def __init__(self, file_name, view_files):
 
66
        self.file_name = file_name
 
67
        self.view_str = ", ".join(view_files)
 
68
 
 
69
 
 
70
class _Views(object):
 
71
    """Base class for View managers."""
 
72
 
 
73
    def supports_views(self):
 
74
        raise NotImplementedError(self.supports_views)
 
75
 
 
76
 
 
77
class PathBasedViews(_Views):
 
78
    """View storage in an unversioned tree control file.
 
79
 
 
80
    Views are stored in terms of paths relative to the tree root.
 
81
 
 
82
    The top line of the control file is a format marker in the format:
 
83
 
 
84
      Bazaar views format X
 
85
 
 
86
    where X is an integer number. After this top line, version 1 format is
 
87
    stored as follows:
 
88
 
 
89
     * optional name-values pairs in the format 'name=value'
 
90
 
 
91
     * optional view definitions, one per line in the format
 
92
 
 
93
       views:
 
94
       name file1 file2 ...
 
95
       name file1 file2 ...
 
96
 
 
97
    where the fields are separated by a nul character (\0). The views file
 
98
    is encoded in utf-8. The only supported keyword in version 1 is
 
99
    'current' which stores the name of the current view, if any.
 
100
    """
 
101
 
 
102
    def __init__(self, tree):
 
103
        self.tree = tree
 
104
        self._loaded = False
 
105
        self._current = None
 
106
        self._views = {}
 
107
 
 
108
    def supports_views(self):
 
109
        return True
 
110
 
 
111
    def get_view_info(self):
 
112
        """Get the current view and dictionary of views.
 
113
 
 
114
        :return: current, views where
 
115
          current = the name of the current view or None if no view is enabled
 
116
          views = a map from view name to list of files/directories
 
117
        """
 
118
        self._load_view_info()
 
119
        return self._current, self._views
 
120
 
 
121
    def set_view_info(self, current, views):
 
122
        """Set the current view and dictionary of views.
 
123
 
 
124
        :param current: the name of the current view or None if no view is
 
125
          enabled
 
126
        :param views: a map from view name to list of files/directories
 
127
        """
 
128
        if current is not None and current not in views:
 
129
            raise NoSuchView(current)
 
130
        self.tree.lock_write()
 
131
        try:
 
132
            self._current = current
 
133
            self._views = views
 
134
            self._save_view_info()
 
135
        finally:
 
136
            self.tree.unlock()
 
137
 
 
138
    def lookup_view(self, view_name=None):
 
139
        """Return the contents of a view.
 
140
 
 
141
        :param view_Name: name of the view or None to lookup the current view
 
142
        :return: the list of files/directories in the requested view
 
143
        """
 
144
        self._load_view_info()
 
145
        try:
 
146
            if view_name is None:
 
147
                if self._current:
 
148
                    view_name = self._current
 
149
                else:
 
150
                    return []
 
151
            return self._views[view_name]
 
152
        except KeyError:
 
153
            raise NoSuchView(view_name)
 
154
 
 
155
    def set_view(self, view_name, view_files, make_current=True):
 
156
        """Add or update a view definition.
 
157
 
 
158
        :param view_name: the name of the view
 
159
        :param view_files: the list of files/directories in the view
 
160
        :param make_current: make this view the current one or not
 
161
        """
 
162
        self.tree.lock_write()
 
163
        try:
 
164
            self._load_view_info()
 
165
            self._views[view_name] = view_files
 
166
            if make_current:
 
167
                self._current = view_name
 
168
            self._save_view_info()
 
169
        finally:
 
170
            self.tree.unlock()
 
171
 
 
172
    def delete_view(self, view_name):
 
173
        """Delete a view definition.
 
174
 
 
175
        If the view deleted is the current one, the current view is reset.
 
176
        """
 
177
        self.tree.lock_write()
 
178
        try:
 
179
            self._load_view_info()
 
180
            try:
 
181
                del self._views[view_name]
 
182
            except KeyError:
 
183
                raise NoSuchView(view_name)
 
184
            if view_name == self._current:
 
185
                self._current = None
 
186
            self._save_view_info()
 
187
        finally:
 
188
            self.tree.unlock()
 
189
 
 
190
    def _save_view_info(self):
 
191
        """Save the current view and all view definitions.
 
192
 
 
193
        Be sure to have initialised self._current and self._views before
 
194
        calling this method.
 
195
        """
 
196
        self.tree.lock_write()
 
197
        try:
 
198
            if self._current is None:
 
199
                keywords = {}
 
200
            else:
 
201
                keywords = {'current': self._current}
 
202
            self.tree._transport.put_bytes('views',
 
203
                self._serialize_view_content(keywords, self._views))
 
204
        finally:
 
205
            self.tree.unlock()
 
206
 
 
207
    def _load_view_info(self):
 
208
        """Load the current view and dictionary of view definitions."""
 
209
        if not self._loaded:
 
210
            with self.tree.lock_read():
 
211
                try:
 
212
                    view_content = self.tree._transport.get_bytes('views')
 
213
                except errors.NoSuchFile as e:
 
214
                    self._current, self._views = None, {}
 
215
                else:
 
216
                    keywords, self._views = \
 
217
                        self._deserialize_view_content(view_content)
 
218
                    self._current = keywords.get('current')
 
219
            self._loaded = True
 
220
 
 
221
    def _serialize_view_content(self, keywords, view_dict):
 
222
        """Convert view keywords and a view dictionary into a stream."""
 
223
        lines = [_VIEWS_FORMAT1_MARKER]
 
224
        for key in keywords:
 
225
            line = "%s=%s\n" % (key, keywords[key])
 
226
            lines.append(line.encode('utf-8'))
 
227
        if view_dict:
 
228
            lines.append("views:\n".encode('utf-8'))
 
229
            for view in sorted(view_dict):
 
230
                view_data = "%s\0%s\n" % (view, "\0".join(view_dict[view]))
 
231
                lines.append(view_data.encode('utf-8'))
 
232
        return b"".join(lines)
 
233
 
 
234
    def _deserialize_view_content(self, view_content):
 
235
        """Convert a stream into view keywords and a dictionary of views."""
 
236
        # as a special case to make initialization easy, an empty definition
 
237
        # maps to no current view and an empty view dictionary
 
238
        if view_content == '':
 
239
            return {}, {}
 
240
        lines = view_content.splitlines()
 
241
        match = _VIEWS_FORMAT_MARKER_RE.match(lines[0])
 
242
        if not match:
 
243
            raise ValueError(
 
244
                "format marker missing from top of views file")
 
245
        elif match.group(1) != '1':
 
246
            raise ValueError(
 
247
                "cannot decode views format %s" % match.group(1))
 
248
        try:
 
249
            keywords = {}
 
250
            views = {}
 
251
            in_views = False
 
252
            for line in lines[1:]:
 
253
                text = line.decode('utf-8')
 
254
                if in_views:
 
255
                    parts = text.split('\0')
 
256
                    view = parts.pop(0)
 
257
                    views[view] = parts
 
258
                elif text == 'views:':
 
259
                    in_views = True
 
260
                    continue
 
261
                elif text.find('=') >= 0:
 
262
                    # must be a name-value pair
 
263
                    keyword, value = text.split('=', 1)
 
264
                    keywords[keyword] = value
 
265
                else:
 
266
                    raise ValueError("failed to deserialize views line %s",
 
267
                        text)
 
268
            return keywords, views
 
269
        except ValueError as e:
 
270
            raise ValueError("failed to deserialize views content %r: %s"
 
271
                % (view_content, e))
 
272
 
 
273
 
 
274
class DisabledViews(_Views):
 
275
    """View storage that refuses to store anything.
 
276
 
 
277
    This is used by older formats that can't store views.
 
278
    """
 
279
 
 
280
    def __init__(self, tree):
 
281
        self.tree = tree
 
282
 
 
283
    def supports_views(self):
 
284
        return False
 
285
 
 
286
    def _not_supported(self, *a, **k):
 
287
        raise ViewsNotSupported(self.tree)
 
288
 
 
289
    get_view_info = _not_supported
 
290
    set_view_info = _not_supported
 
291
    lookup_view = _not_supported
 
292
    set_view = _not_supported
 
293
    delete_view = _not_supported
 
294
 
 
295
 
 
296
def view_display_str(view_files, encoding=None):
 
297
    """Get the display string for a list of view files.
 
298
 
 
299
    :param view_files: the list of file names
 
300
    :param encoding: the encoding to display the files in
 
301
    """
 
302
    if encoding is None:
 
303
        return ", ".join(view_files)
 
304
    else:
 
305
        return ", ".join([v.encode(encoding, 'replace') for v in view_files])
 
306
 
 
307
 
 
308
def check_path_in_view(tree, relpath):
 
309
    """If a working tree has a view enabled, check the path is within it."""
 
310
    if tree.supports_views():
 
311
        view_files = tree.views.lookup_view()
 
312
        if  view_files and not osutils.is_inside_any(view_files, relpath):
 
313
            raise FileOutsideView(relpath, view_files)