/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
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 copy_multi(self, other, ids):
670 by Martin Pool
- Show progress while branching
110
        """Copy texts for ids from other into self.
626 by Martin Pool
- add Store.copy_multi for use in pulling changes into a branch
111
112
        If an id is present in self, it is skipped.  A count of copied
113
        ids is returned, which may be less than len(ids).
114
        """
115
        from bzrlib.progress import ProgressBar
116
        pb = ProgressBar()
670 by Martin Pool
- Show progress while branching
117
        pb.update('preparing to copy')
118
        to_copy = [id for id in ids if id not in self]
119
        count = 0
120
        for id in to_copy:
626 by Martin Pool
- add Store.copy_multi for use in pulling changes into a branch
121
            count += 1
670 by Martin Pool
- Show progress while branching
122
            pb.update('copy', count, len(to_copy))
123
            self.add(other[id], id)
124
        assert count == len(to_copy)
626 by Martin Pool
- add Store.copy_multi for use in pulling changes into a branch
125
        pb.clear()
670 by Martin Pool
- Show progress while branching
126
        return count
127
    
626 by Martin Pool
- add Store.copy_multi for use in pulling changes into a branch
128
670 by Martin Pool
- Show progress while branching
129
    def __contains__(self, fileid):
1 by mbp at sourcefrog
import from baz patch-364
130
        """"""
131
        p = self._path(fileid)
132
        return (os.access(p, os.R_OK)
128 by mbp at sourcefrog
More support for compressed files in stores
133
                or os.access(p + '.gz', os.R_OK))
134
135
    # TODO: Guard against the same thing being stored twice, compressed and uncompresse
1 by mbp at sourcefrog
import from baz patch-364
136
128 by mbp at sourcefrog
More support for compressed files in stores
137
    def __iter__(self):
1 by mbp at sourcefrog
import from baz patch-364
138
        for f in os.listdir(self._basedir):
139
            if f[-3:] == '.gz':
128 by mbp at sourcefrog
More support for compressed files in stores
140
                # TODO: case-insensitive?
141
                yield f[:-3]
142
            else:
143
                yield f
144
145
    def __len__(self):
1 by mbp at sourcefrog
import from baz patch-364
146
        return len(os.listdir(self._basedir))
80 by mbp at sourcefrog
show_info: Show number of entries in the branch stores
147
148
    def __getitem__(self, fileid):
149
        """Returns a file reading from a particular entry."""
1 by mbp at sourcefrog
import from baz patch-364
150
        p = self._path(fileid)
151
        try:
127 by mbp at sourcefrog
- store support for retrieving compressed files
152
            return gzip.GzipFile(p + '.gz', 'rb')
153
        except IOError, e:
154
            if e.errno == errno.ENOENT:
155
                return file(p, 'rb')
156
            else:
157
                raise e
158
159
    def total_size(self):
1 by mbp at sourcefrog
import from baz patch-364
160
        """Return (count, bytes)
81 by mbp at sourcefrog
show space usage for various stores in the info command
161
127 by mbp at sourcefrog
- store support for retrieving compressed files
162
        This is the (compressed) size stored on disk, not the size of
163
        the content."""
164
        total = 0
165
        count = 0
81 by mbp at sourcefrog
show space usage for various stores in the info command
166
        for fid in self:
167
            count += 1
168
            p = self._path(fid)
169
            try:
128 by mbp at sourcefrog
More support for compressed files in stores
170
                total += os.stat(p)[ST_SIZE]
171
            except OSError:
172
                total += os.stat(p + '.gz')[ST_SIZE]
173
                
174
        return count, total
175
81 by mbp at sourcefrog
show space usage for various stores in the info command
176
177
1 by mbp at sourcefrog
import from baz patch-364
178
179
class ImmutableScratchStore(ImmutableStore):
180
    """Self-destructing test subclass of ImmutableStore.
181
182
    The Store only exists for the lifetime of the Python object.
183
    Obviously you should not put anything precious in it.
184
    """
185
    def __init__(self):
186
        ImmutableStore.__init__(self, tempfile.mkdtemp())
187
188
    def __del__(self):
189
        for f in os.listdir(self._basedir):
190
            fpath = os.path.join(self._basedir, f)
130 by mbp at sourcefrog
- fixup checks on retrieved files to cope with compression,
191
            # needed on windows, and maybe some other filesystems
163 by mbp at sourcefrog
merge win32 portability fixes
192
            os.chmod(fpath, 0600)
193
            os.remove(fpath)
194
        os.rmdir(self._basedir)
195
        mutter("%r destroyed" % self)
130 by mbp at sourcefrog
- fixup checks on retrieved files to cope with compression,
196
197