~bzr-pqm/bzr/bzr.dev

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
#! /usr/bin/env python
# -*- coding: UTF-8 -*-

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

"""Stores are the main data-storage mechanism for Bazaar-NG.

A store is a simple write-once container indexed by a universally
unique ID, which is typically the SHA-1 of the content."""

__copyright__ = "Copyright (C) 2005 Canonical Ltd."
__author__ = "Martin Pool <mbp@canonical.com>"

import os, tempfile, types, osutils, gzip, errno
from stat import ST_SIZE
from StringIO import StringIO
from trace import mutter

######################################################################
# stores

class StoreError(Exception):
    pass


class ImmutableStore:
    """Store that holds files indexed by unique names.

    Files can be added, but not modified once they are in.  Typically
    the hash is used as the name, or something else known to be unique,
    such as a UUID.

    >>> st = ImmutableScratchStore()

    >>> st.add(StringIO('hello'), 'aa')
    >>> 'aa' in st
    True
    >>> 'foo' in st
    False

    You are not allowed to add an id that is already present.

    Entries can be retrieved as files, which may then be read.

    >>> st.add(StringIO('goodbye'), '123123')
    >>> st['123123'].read()
    'goodbye'

    :todo: Atomic add by writing to a temporary file and renaming.

    :todo: Perhaps automatically transform to/from XML in a method?
           Would just need to tell the constructor what class to
           use...

    :todo: Even within a simple disk store like this, we could
           gzip the files.  But since many are less than one disk
           block, that might not help a lot.

    """

    def __init__(self, basedir):
        """ImmutableStore constructor."""
        self._basedir = basedir

    def _path(self, id):
        return os.path.join(self._basedir, id)

    def __repr__(self):
        return "%s(%r)" % (self.__class__.__name__, self._basedir)

    def add(self, f, fileid, compressed=True):
        """Add contents of a file into the store.

        :param f: An open file, or file-like object."""
        # FIXME: Only works on smallish files
        # TODO: Can be optimized by copying at the same time as
        # computing the sum.
        mutter("add store entry %r" % (fileid))
        if isinstance(f, types.StringTypes):
            content = f
        else:
            content = f.read()

        p = self._path(fileid)
        if os.access(p, os.F_OK) or os.access(p + '.gz', os.F_OK):
            bailout("store %r already contains id %r" % (self._basedir, fileid))

        if compressed:
            f = gzip.GzipFile(p + '.gz', 'wb')
            os.chmod(p + '.gz', 0444)
        else:
            f = file(p, 'wb')
            os.chmod(p, 0444)
            
        f.write(content)
        f.close()


    def __contains__(self, fileid):
        """"""
        p = self._path(fileid)
        return (os.access(p, os.R_OK)
                or os.access(p + '.gz', os.R_OK))

    # TODO: Guard against the same thing being stored twice, compressed and uncompresse

    def __iter__(self):
        for f in os.listdir(self._basedir):
            if f[-3:] == '.gz':
                # TODO: case-insensitive?
                yield f[:-3]
            else:
                yield f

    def __len__(self):
        return len(os.listdir(self._basedir))

    def __getitem__(self, fileid):
        """Returns a file reading from a particular entry."""
        p = self._path(fileid)
        try:
            return gzip.GzipFile(p + '.gz', 'rb')
        except IOError, e:
            if e.errno == errno.ENOENT:
                return file(p, 'rb')
            else:
                raise e

    def total_size(self):
        """Return (count, bytes)

        This is the (compressed) size stored on disk, not the size of
        the content."""
        total = 0
        count = 0
        for fid in self:
            count += 1
            p = self._path(fid)
            try:
                total += os.stat(p)[ST_SIZE]
            except OSError:
                total += os.stat(p + '.gz')[ST_SIZE]
                
        return count, total




class ImmutableScratchStore(ImmutableStore):
    """Self-destructing test subclass of ImmutableStore.

    The Store only exists for the lifetime of the Python object.
    Obviously you should not put anything precious in it.
    """
    def __init__(self):
        ImmutableStore.__init__(self, tempfile.mkdtemp())

    def __del__(self):
        for f in os.listdir(self._basedir):
            os.remove(os.path.join(self._basedir, f))
        os.rmdir(self._basedir)
        mutter("%r destroyed" % self)