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