~bzr-pqm/bzr/bzr.dev

184 by mbp at sourcefrog
pychecker fixups
1
# This program is free software; you can redistribute it and/or modify
1 by mbp at sourcefrog
import from baz patch-364
2
# it under the terms of the GNU General Public License as published by
3
# the Free Software Foundation; either version 2 of the License, or
4
# (at your option) any later version.
5
6
# This program is distributed in the hope that it will be useful,
7
# but WITHOUT ANY WARRANTY; without even the implied warranty of
8
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
9
# GNU General Public License for more details.
10
11
# You should have received a copy of the GNU General Public License
12
# along with this program; if not, write to the Free Software
13
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
14
15
"""Stores are the main data-storage mechanism for Bazaar-NG.
16
17
A store is a simple write-once container indexed by a universally
18
unique ID, which is typically the SHA-1 of the content."""
19
20
__copyright__ = "Copyright (C) 2005 Canonical Ltd."
21
__author__ = "Martin Pool <mbp@canonical.com>"
22
23
import os, tempfile, types, osutils, gzip, errno
24
from stat import ST_SIZE
127 by mbp at sourcefrog
- store support for retrieving compressed files
25
from StringIO import StringIO
81 by mbp at sourcefrog
show space usage for various stores in the info command
26
from trace import mutter
1 by mbp at sourcefrog
import from baz patch-364
27
28
######################################################################
29
# stores
30
31
class StoreError(Exception):
32
    pass
33
34
35
class ImmutableStore(object):
36
    """Store that holds files indexed by unique names.
558 by Martin Pool
- All top-level classes inherit from object
37
1 by mbp at sourcefrog
import from baz patch-364
38
    Files can be added, but not modified once they are in.  Typically
39
    the hash is used as the name, or something else known to be unique,
40
    such as a UUID.
41
42
    >>> st = ImmutableScratchStore()
43
44
    >>> st.add(StringIO('hello'), 'aa')
45
    >>> 'aa' in st
46
    True
47
    >>> 'foo' in st
48
    False
49
50
    You are not allowed to add an id that is already present.
51
52
    Entries can be retrieved as files, which may then be read.
53
54
    >>> st.add(StringIO('goodbye'), '123123')
55
    >>> st['123123'].read()
56
    'goodbye'
57
58
    TODO: Atomic add by writing to a temporary file and renaming.
59
254 by Martin Pool
- Doc cleanups from Magnus Therning
60
    TODO: Perhaps automatically transform to/from XML in a method?
1 by mbp at sourcefrog
import from baz patch-364
61
           Would just need to tell the constructor what class to
254 by Martin Pool
- Doc cleanups from Magnus Therning
62
           use...
1 by mbp at sourcefrog
import from baz patch-364
63
64
    TODO: Even within a simple disk store like this, we could
65
           gzip the files.  But since many are less than one disk
254 by Martin Pool
- Doc cleanups from Magnus Therning
66
           block, that might not help a lot.
1 by mbp at sourcefrog
import from baz patch-364
67
68
    """
69
70
    def __init__(self, basedir):
71
        """ImmutableStore constructor."""
72
        self._basedir = basedir
73
74
    def _path(self, id):
75
        assert '/' not in id
76
        return os.path.join(self._basedir, id)
495 by Martin Pool
- disallow slash in store ids
77
1 by mbp at sourcefrog
import from baz patch-364
78
    def __repr__(self):
79
        return "%s(%r)" % (self.__class__.__name__, self._basedir)
80
81
    def add(self, f, fileid, compressed=True):
82
        """Add contents of a file into the store.
129 by mbp at sourcefrog
Store.add defaults to adding gzipped files
83
1 by mbp at sourcefrog
import from baz patch-364
84
        f -- An open file, or file-like object."""
85
        # FIXME: Only works on smallish files
254 by Martin Pool
- Doc cleanups from Magnus Therning
86
        # TODO: Can be optimized by copying at the same time as
1 by mbp at sourcefrog
import from baz patch-364
87
        # computing the sum.
88
        mutter("add store entry %r" % (fileid))
89
        if isinstance(f, types.StringTypes):
90
            content = f
91
        else:
92
            content = f.read()
93
94
        p = self._path(fileid)
129 by mbp at sourcefrog
Store.add defaults to adding gzipped files
95
        if os.access(p, os.F_OK) or os.access(p + '.gz', os.F_OK):
96
            bailout("store %r already contains id %r" % (self._basedir, fileid))
97
98
        if compressed:
99
            f = gzip.GzipFile(p + '.gz', 'wb')
100
            os.chmod(p + '.gz', 0444)
101
        else:
102
            f = file(p, 'wb')
103
            os.chmod(p, 0444)
104
            
105
        f.write(content)
106
        f.close()
107
108
    def copy_multi(self, other, ids):
1 by mbp at sourcefrog
import from baz patch-364
109
        """Copy texts for ids from other into self.
626 by Martin Pool
- add Store.copy_multi for use in pulling changes into a branch
110
111
        If an id is present in self, it is skipped.  A count of copied
112
        ids is returned, which may be less than len(ids).
113
        """
114
        count = 0
115
        for id in ids:
116
            if id in self:
117
                continue
118
            self.add(other[id], id)
119
            count += 1
120
        return count
121
122
    def __contains__(self, fileid):
1 by mbp at sourcefrog
import from baz patch-364
123
        """"""
124
        p = self._path(fileid)
125
        return (os.access(p, os.R_OK)
128 by mbp at sourcefrog
More support for compressed files in stores
126
                or os.access(p + '.gz', os.R_OK))
127
128
    # TODO: Guard against the same thing being stored twice, compressed and uncompresse
1 by mbp at sourcefrog
import from baz patch-364
129
128 by mbp at sourcefrog
More support for compressed files in stores
130
    def __iter__(self):
1 by mbp at sourcefrog
import from baz patch-364
131
        for f in os.listdir(self._basedir):
132
            if f[-3:] == '.gz':
128 by mbp at sourcefrog
More support for compressed files in stores
133
                # TODO: case-insensitive?
134
                yield f[:-3]
135
            else:
136
                yield f
137
138
    def __len__(self):
1 by mbp at sourcefrog
import from baz patch-364
139
        return len(os.listdir(self._basedir))
80 by mbp at sourcefrog
show_info: Show number of entries in the branch stores
140
141
    def __getitem__(self, fileid):
142
        """Returns a file reading from a particular entry."""
1 by mbp at sourcefrog
import from baz patch-364
143
        p = self._path(fileid)
144
        try:
127 by mbp at sourcefrog
- store support for retrieving compressed files
145
            return gzip.GzipFile(p + '.gz', 'rb')
146
        except IOError, e:
147
            if e.errno == errno.ENOENT:
148
                return file(p, 'rb')
149
            else:
150
                raise e
151
152
    def total_size(self):
1 by mbp at sourcefrog
import from baz patch-364
153
        """Return (count, bytes)
81 by mbp at sourcefrog
show space usage for various stores in the info command
154
127 by mbp at sourcefrog
- store support for retrieving compressed files
155
        This is the (compressed) size stored on disk, not the size of
156
        the content."""
157
        total = 0
158
        count = 0
81 by mbp at sourcefrog
show space usage for various stores in the info command
159
        for fid in self:
160
            count += 1
161
            p = self._path(fid)
162
            try:
128 by mbp at sourcefrog
More support for compressed files in stores
163
                total += os.stat(p)[ST_SIZE]
164
            except OSError:
165
                total += os.stat(p + '.gz')[ST_SIZE]
166
                
167
        return count, total
168
81 by mbp at sourcefrog
show space usage for various stores in the info command
169
170
1 by mbp at sourcefrog
import from baz patch-364
171
172
class ImmutableScratchStore(ImmutableStore):
173
    """Self-destructing test subclass of ImmutableStore.
174
175
    The Store only exists for the lifetime of the Python object.
176
    Obviously you should not put anything precious in it.
177
    """
178
    def __init__(self):
179
        ImmutableStore.__init__(self, tempfile.mkdtemp())
180
181
    def __del__(self):
182
        for f in os.listdir(self._basedir):
183
            fpath = os.path.join(self._basedir, f)
130 by mbp at sourcefrog
- fixup checks on retrieved files to cope with compression,
184
            # needed on windows, and maybe some other filesystems
163 by mbp at sourcefrog
merge win32 portability fixes
185
            os.chmod(fpath, 0600)
186
            os.remove(fpath)
187
        os.rmdir(self._basedir)
188
        mutter("%r destroyed" % self)
130 by mbp at sourcefrog
- fixup checks on retrieved files to cope with compression,
189
190