~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
1 by mbp at sourcefrog
import from baz patch-364
109
    def __contains__(self, fileid):
110
        """"""
111
        p = self._path(fileid)
112
        return (os.access(p, os.R_OK)
128 by mbp at sourcefrog
More support for compressed files in stores
113
                or os.access(p + '.gz', os.R_OK))
114
115
    # TODO: Guard against the same thing being stored twice, compressed and uncompresse
1 by mbp at sourcefrog
import from baz patch-364
116
128 by mbp at sourcefrog
More support for compressed files in stores
117
    def __iter__(self):
1 by mbp at sourcefrog
import from baz patch-364
118
        for f in os.listdir(self._basedir):
119
            if f[-3:] == '.gz':
128 by mbp at sourcefrog
More support for compressed files in stores
120
                # TODO: case-insensitive?
121
                yield f[:-3]
122
            else:
123
                yield f
124
125
    def __len__(self):
1 by mbp at sourcefrog
import from baz patch-364
126
        return len(os.listdir(self._basedir))
80 by mbp at sourcefrog
show_info: Show number of entries in the branch stores
127
128
    def __getitem__(self, fileid):
129
        """Returns a file reading from a particular entry."""
1 by mbp at sourcefrog
import from baz patch-364
130
        p = self._path(fileid)
131
        try:
127 by mbp at sourcefrog
- store support for retrieving compressed files
132
            return gzip.GzipFile(p + '.gz', 'rb')
133
        except IOError, e:
134
            if e.errno == errno.ENOENT:
135
                return file(p, 'rb')
136
            else:
137
                raise e
138
139
    def total_size(self):
1 by mbp at sourcefrog
import from baz patch-364
140
        """Return (count, bytes)
81 by mbp at sourcefrog
show space usage for various stores in the info command
141
127 by mbp at sourcefrog
- store support for retrieving compressed files
142
        This is the (compressed) size stored on disk, not the size of
143
        the content."""
144
        total = 0
145
        count = 0
81 by mbp at sourcefrog
show space usage for various stores in the info command
146
        for fid in self:
147
            count += 1
148
            p = self._path(fid)
149
            try:
128 by mbp at sourcefrog
More support for compressed files in stores
150
                total += os.stat(p)[ST_SIZE]
151
            except OSError:
152
                total += os.stat(p + '.gz')[ST_SIZE]
153
                
154
        return count, total
155
81 by mbp at sourcefrog
show space usage for various stores in the info command
156
157
1 by mbp at sourcefrog
import from baz patch-364
158
159
class ImmutableScratchStore(ImmutableStore):
160
    """Self-destructing test subclass of ImmutableStore.
161
162
    The Store only exists for the lifetime of the Python object.
163
    Obviously you should not put anything precious in it.
164
    """
165
    def __init__(self):
166
        ImmutableStore.__init__(self, tempfile.mkdtemp())
167
168
    def __del__(self):
169
        for f in os.listdir(self._basedir):
170
            fpath = os.path.join(self._basedir, f)
130 by mbp at sourcefrog
- fixup checks on retrieved files to cope with compression,
171
            # needed on windows, and maybe some other filesystems
163 by mbp at sourcefrog
merge win32 portability fixes
172
            os.chmod(fpath, 0600)
173
            os.remove(fpath)
174
        os.rmdir(self._basedir)
175
        mutter("%r destroyed" % self)
130 by mbp at sourcefrog
- fixup checks on retrieved files to cope with compression,
176
177