~bzr-pqm/bzr/bzr.dev

3586.1.2 by Ian Clatworthy
first cut of views.py
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
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
3586.1.2 by Ian Clatworthy
first cut of views.py
16
17
"""View management.
18
3586.1.33 by Ian Clatworthy
cleanup trailing whitespace
19
Views are contained within a working tree and normally constructed
3586.1.2 by Ian Clatworthy
first cut of views.py
20
when first accessed.  Clients should do, for example, ...
21
22
  tree.views.lookup_view()
23
"""
24
25
26
import re
27
28
from bzrlib import (
29
    errors,
4032.4.1 by Eduardo Padoan
Moved diff._check_path_in_view() to views.check_path_in_view()
30
    osutils,
3586.1.2 by Ian Clatworthy
first cut of views.py
31
    )
32
33
34
_VIEWS_FORMAT_MARKER_RE = re.compile(r'Bazaar views format (\d+)')
3586.2.4 by Ian Clatworthy
fix storage after deleting the last view
35
_VIEWS_FORMAT1_MARKER = "Bazaar views format 1\n"
3586.1.2 by Ian Clatworthy
first cut of views.py
36
37
38
class _Views(object):
39
    """Base class for View managers."""
40
41
    def supports_views(self):
42
        raise NotImplementedError(self.supports_views)
43
44
45
class PathBasedViews(_Views):
46
    """View storage in an unversioned tree control file.
47
48
    Views are stored in terms of paths relative to the tree root.
49
50
    The top line of the control file is a format marker in the format:
51
52
      Bazaar views format X
53
3586.2.11 by Ian Clatworthy
use name-values pairs instead of positions in views file
54
    where X is an integer number. After this top line, version 1 format is
55
    stored as follows:
56
57
     * optional name-values pairs in the format 'name=value'
58
59
     * optional view definitions, one per line in the format
60
61
       views:
62
       name file1 file2 ...
3586.1.2 by Ian Clatworthy
first cut of views.py
63
       name file1 file2 ...
64
65
    where the fields are separated by a nul character (\0). The views file
3586.2.11 by Ian Clatworthy
use name-values pairs instead of positions in views file
66
    is encoded in utf-8. The only supported keyword in version 1 is
67
    'current' which stores the name of the current view, if any.
3586.1.2 by Ian Clatworthy
first cut of views.py
68
    """
69
70
    def __init__(self, tree):
3586.1.7 by Ian Clatworthy
first cut at WTF5
71
        self.tree = tree
3586.1.2 by Ian Clatworthy
first cut of views.py
72
        self._loaded = False
73
        self._current = None
74
        self._views = {}
75
76
    def supports_views(self):
77
        return True
78
79
    def get_view_info(self):
80
        """Get the current view and dictionary of views.
81
82
        :return: current, views where
83
          current = the name of the current view or None if no view is enabled
84
          views = a map from view name to list of files/directories
85
        """
86
        self._load_view_info()
87
        return self._current, self._views
88
89
    def set_view_info(self, current, views):
90
        """Set the current view and dictionary of views.
91
92
        :param current: the name of the current view or None if no view is
93
          enabled
94
        :param views: a map from view name to list of files/directories
95
        """
96
        if current is not None and current not in views:
97
            raise errors.NoSuchView(current)
98
        self.tree.lock_write()
99
        try:
100
            self._current = current
101
            self._views = views
102
            self._save_view_info()
103
        finally:
104
            self.tree.unlock()
105
106
    def lookup_view(self, view_name=None):
107
        """Return the contents of a view.
4032.1.2 by John Arbash Meinel
Track down a few more files that have trailing whitespace.
108
3586.1.2 by Ian Clatworthy
first cut of views.py
109
        :param view_Name: name of the view or None to lookup the current view
110
        :return: the list of files/directories in the requested view
111
        """
112
        self._load_view_info()
113
        try:
114
            if view_name is None:
115
                if self._current:
116
                    view_name = self._current
117
                else:
118
                    return []
119
            return self._views[view_name]
120
        except KeyError:
121
            raise errors.NoSuchView(view_name)
122
123
    def set_view(self, view_name, view_files, make_current=True):
124
        """Add or update a view definition.
4032.1.2 by John Arbash Meinel
Track down a few more files that have trailing whitespace.
125
3586.1.2 by Ian Clatworthy
first cut of views.py
126
        :param view_name: the name of the view
127
        :param view_files: the list of files/directories in the view
128
        :param make_current: make this view the current one or not
129
        """
130
        self.tree.lock_write()
131
        try:
132
            self._load_view_info()
133
            self._views[view_name] = view_files
134
            if make_current:
135
                self._current = view_name
136
            self._save_view_info()
137
        finally:
138
            self.tree.unlock()
139
140
    def delete_view(self, view_name):
141
        """Delete a view definition.
142
143
        If the view deleted is the current one, the current view is reset.
144
        """
145
        self.tree.lock_write()
146
        try:
147
            self._load_view_info()
148
            try:
149
                del self._views[view_name]
150
            except KeyError:
151
                raise errors.NoSuchView(view_name)
3586.1.7 by Ian Clatworthy
first cut at WTF5
152
            if view_name == self._current:
3586.1.2 by Ian Clatworthy
first cut of views.py
153
                self._current = None
154
            self._save_view_info()
155
        finally:
156
            self.tree.unlock()
157
158
    def _save_view_info(self):
159
        """Save the current view and all view definitions.
160
161
        Be sure to have initialised self._current and self._views before
162
        calling this method.
163
        """
164
        self.tree.lock_write()
165
        try:
3586.2.11 by Ian Clatworthy
use name-values pairs instead of positions in views file
166
            if self._current is None:
167
                keywords = {}
168
            else:
169
                keywords = {'current': self._current}
3586.1.2 by Ian Clatworthy
first cut of views.py
170
            self.tree._transport.put_bytes('views',
3586.2.11 by Ian Clatworthy
use name-values pairs instead of positions in views file
171
                self._serialize_view_content(keywords, self._views))
3586.1.2 by Ian Clatworthy
first cut of views.py
172
        finally:
173
            self.tree.unlock()
174
175
    def _load_view_info(self):
176
        """Load the current view and dictionary of view definitions."""
177
        if not self._loaded:
178
            self.tree.lock_read()
179
            try:
180
                try:
181
                    view_content = self.tree._transport.get_bytes('views')
182
                except errors.NoSuchFile, e:
183
                    self._current, self._views = None, {}
184
                else:
3586.2.11 by Ian Clatworthy
use name-values pairs instead of positions in views file
185
                    keywords, self._views = \
3586.1.2 by Ian Clatworthy
first cut of views.py
186
                        self._deserialize_view_content(view_content)
3586.2.11 by Ian Clatworthy
use name-values pairs instead of positions in views file
187
                    self._current = keywords.get('current')
3586.1.2 by Ian Clatworthy
first cut of views.py
188
            finally:
189
                self.tree.unlock()
190
            self._loaded = True
191
3586.2.11 by Ian Clatworthy
use name-values pairs instead of positions in views file
192
    def _serialize_view_content(self, keywords, view_dict):
193
        """Convert view keywords and a view dictionary into a stream."""
3586.1.7 by Ian Clatworthy
first cut at WTF5
194
        lines = [_VIEWS_FORMAT1_MARKER]
3586.2.11 by Ian Clatworthy
use name-values pairs instead of positions in views file
195
        for key in keywords:
196
            line = "%s=%s\n" % (key,keywords[key])
197
            lines.append(line.encode('utf-8'))
198
        if view_dict:
199
            lines.append("views:\n".encode('utf-8'))
200
            for view in sorted(view_dict):
201
                view_data = "%s\0%s\n" % (view, "\0".join(view_dict[view]))
202
                lines.append(view_data.encode('utf-8'))
3586.2.4 by Ian Clatworthy
fix storage after deleting the last view
203
        return "".join(lines)
3586.1.2 by Ian Clatworthy
first cut of views.py
204
205
    def _deserialize_view_content(self, view_content):
3586.2.11 by Ian Clatworthy
use name-values pairs instead of positions in views file
206
        """Convert a stream into view keywords and a dictionary of views."""
3586.1.2 by Ian Clatworthy
first cut of views.py
207
        # as a special case to make initialization easy, an empty definition
208
        # maps to no current view and an empty view dictionary
209
        if view_content == '':
3586.2.11 by Ian Clatworthy
use name-values pairs instead of positions in views file
210
            return {}, {}
3586.1.2 by Ian Clatworthy
first cut of views.py
211
        lines = view_content.splitlines()
3586.1.7 by Ian Clatworthy
first cut at WTF5
212
        match = _VIEWS_FORMAT_MARKER_RE.match(lines[0])
3586.1.2 by Ian Clatworthy
first cut of views.py
213
        if not match:
214
            raise ValueError(
215
                "format marker missing from top of views file")
3586.1.7 by Ian Clatworthy
first cut at WTF5
216
        elif match.group(1) != '1':
3586.1.2 by Ian Clatworthy
first cut of views.py
217
            raise ValueError(
218
                "cannot decode views format %s" % match.group(1))
219
        try:
3586.2.11 by Ian Clatworthy
use name-values pairs instead of positions in views file
220
            keywords = {}
3586.1.2 by Ian Clatworthy
first cut of views.py
221
            views = {}
3586.2.11 by Ian Clatworthy
use name-values pairs instead of positions in views file
222
            in_views = False
223
            for line in lines[1:]:
224
                text = line.decode('utf-8')
225
                if in_views:
226
                    parts = text.split('\0')
227
                    view = parts.pop(0)
228
                    views[view] = parts
229
                elif text == 'views:':
230
                    in_views = True
231
                    continue
232
                elif text.find('=') >= 0:
233
                    # must be a name-value pair
234
                    keyword, value = text.split('=', 1)
235
                    keywords[keyword] = value
236
                else:
237
                    raise ValueError("failed to deserialize views line %s",
238
                        text)
239
            return keywords, views
3586.1.2 by Ian Clatworthy
first cut of views.py
240
        except ValueError, e:
241
            raise ValueError("failed to deserialize views content %r: %s"
242
                % (view_content, e))
243
244
245
class DisabledViews(_Views):
246
    """View storage that refuses to store anything.
247
248
    This is used by older formats that can't store views.
249
    """
250
251
    def __init__(self, tree):
252
        self.tree = tree
253
254
    def supports_views(self):
255
        return False
256
257
    def _not_supported(self, *a, **k):
258
        raise errors.ViewsNotSupported(self.tree)
259
260
    get_view_info = _not_supported
261
    set_view_info = _not_supported
262
    lookup_view = _not_supported
263
    set_view = _not_supported
264
    delete_view = _not_supported
3586.1.20 by Ian Clatworthy
centralise formatting of view file lists
265
266
267
def view_display_str(view_files, encoding=None):
268
    """Get the display string for a list of view files.
269
270
    :param view_files: the list of file names
271
    :param encoding: the encoding to display the files in
272
    """
273
    if encoding is None:
274
        return ", ".join(view_files)
275
    else:
276
        return ", ".join([v.encode(encoding, 'replace') for v in view_files])
4032.4.1 by Eduardo Padoan
Moved diff._check_path_in_view() to views.check_path_in_view()
277
278
279
def check_path_in_view(tree, relpath):
280
    """If a working tree has a view enabled, check the path is within it."""
281
    if tree.supports_views():
282
        view_files = tree.views.lookup_view()
283
        if  view_files and not osutils.is_inside_any(view_files, relpath):
284
            raise errors.FileOutsideView(relpath, view_files)