~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/store.py

  • Committer: Martin Pool
  • Date: 2005-06-06 04:15:44 UTC
  • Revision ID: mbp@sourcefrog.net-20050606041544-83be94eb35eef7de
- script to create rollups, from John

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
#! /usr/bin/env python
2
 
# -*- coding: UTF-8 -*-
 
1
 
3
2
 
4
3
# This program is free software; you can redistribute it and/or modify
5
4
# it under the terms of the GNU General Public License as published by
23
22
__copyright__ = "Copyright (C) 2005 Canonical Ltd."
24
23
__author__ = "Martin Pool <mbp@canonical.com>"
25
24
 
26
 
import os, tempfile, types, osutils
 
25
import os, tempfile, types, osutils, gzip, errno
27
26
from stat import ST_SIZE
28
27
from StringIO import StringIO
29
28
from trace import mutter
30
29
 
31
 
 
32
30
######################################################################
33
31
# stores
34
32
 
36
34
    pass
37
35
 
38
36
 
39
 
class ImmutableStore:
 
37
class ImmutableStore(object):
40
38
    """Store that holds files indexed by unique names.
41
39
 
42
40
    Files can be added, but not modified once they are in.  Typically
59
57
    >>> st['123123'].read()
60
58
    'goodbye'
61
59
 
62
 
    :todo: Atomic add by writing to a temporary file and renaming.
 
60
    TODO: Atomic add by writing to a temporary file and renaming.
63
61
 
64
 
    :todo: Perhaps automatically transform to/from XML in a method?
 
62
    TODO: Perhaps automatically transform to/from XML in a method?
65
63
           Would just need to tell the constructor what class to
66
64
           use...
67
65
 
68
 
    :todo: Even within a simple disk store like this, we could
 
66
    TODO: Even within a simple disk store like this, we could
69
67
           gzip the files.  But since many are less than one disk
70
68
           block, that might not help a lot.
71
69
 
76
74
        self._basedir = basedir
77
75
 
78
76
    def _path(self, id):
 
77
        assert '/' not in id
79
78
        return os.path.join(self._basedir, id)
80
79
 
81
80
    def __repr__(self):
82
81
        return "%s(%r)" % (self.__class__.__name__, self._basedir)
83
82
 
84
 
    def add(self, f, fileid):
 
83
    def add(self, f, fileid, compressed=True):
85
84
        """Add contents of a file into the store.
86
85
 
87
 
        :param f: An open file, or file-like object."""
 
86
        f -- An open file, or file-like object."""
88
87
        # FIXME: Only works on smallish files
89
88
        # TODO: Can be optimized by copying at the same time as
90
89
        # computing the sum.
93
92
            content = f
94
93
        else:
95
94
            content = f.read()
96
 
        if fileid not in self:
97
 
            filename = self._path(fileid)
98
 
            f = file(filename, 'wb')
99
 
            f.write(content)
100
 
            f.flush()
101
 
            os.fsync(f.fileno())
102
 
            f.close()
103
 
            osutils.make_readonly(filename)
 
95
 
 
96
        p = self._path(fileid)
 
97
        if os.access(p, os.F_OK) or os.access(p + '.gz', os.F_OK):
 
98
            bailout("store %r already contains id %r" % (self._basedir, fileid))
 
99
 
 
100
        if compressed:
 
101
            f = gzip.GzipFile(p + '.gz', 'wb')
 
102
            os.chmod(p + '.gz', 0444)
 
103
        else:
 
104
            f = file(p, 'wb')
 
105
            os.chmod(p, 0444)
 
106
            
 
107
        f.write(content)
 
108
        f.close()
104
109
 
105
110
 
106
111
    def __contains__(self, fileid):
107
112
        """"""
108
 
        return os.access(self._path(fileid), os.R_OK)
 
113
        p = self._path(fileid)
 
114
        return (os.access(p, os.R_OK)
 
115
                or os.access(p + '.gz', os.R_OK))
109
116
 
 
117
    # TODO: Guard against the same thing being stored twice, compressed and uncompresse
110
118
 
111
119
    def __iter__(self):
112
 
        return iter(os.listdir(self._basedir))
 
120
        for f in os.listdir(self._basedir):
 
121
            if f[-3:] == '.gz':
 
122
                # TODO: case-insensitive?
 
123
                yield f[:-3]
 
124
            else:
 
125
                yield f
113
126
 
114
127
    def __len__(self):
115
128
        return len(os.listdir(self._basedir))
116
129
 
117
130
    def __getitem__(self, fileid):
118
131
        """Returns a file reading from a particular entry."""
119
 
        return file(self._path(fileid), 'rb')
 
132
        p = self._path(fileid)
 
133
        try:
 
134
            return gzip.GzipFile(p + '.gz', 'rb')
 
135
        except IOError, e:
 
136
            if e.errno == errno.ENOENT:
 
137
                return file(p, 'rb')
 
138
            else:
 
139
                raise e
120
140
 
121
141
    def total_size(self):
122
 
        """Return (count, bytes)"""
 
142
        """Return (count, bytes)
 
143
 
 
144
        This is the (compressed) size stored on disk, not the size of
 
145
        the content."""
123
146
        total = 0
124
147
        count = 0
125
148
        for fid in self:
126
149
            count += 1
127
 
            total += os.stat(self._path(fid))[ST_SIZE]
 
150
            p = self._path(fid)
 
151
            try:
 
152
                total += os.stat(p)[ST_SIZE]
 
153
            except OSError:
 
154
                total += os.stat(p + '.gz')[ST_SIZE]
 
155
                
128
156
        return count, total
129
157
 
130
 
    def delete_all(self):
131
 
        for fileid in self:
132
 
            self.delete(fileid)
133
 
 
134
 
    def delete(self, fileid):
135
 
        """Remove nominated store entry.
136
 
 
137
 
        Most stores will be add-only."""
138
 
        filename = self._path(fileid)
139
 
        ## osutils.make_writable(filename)
140
 
        os.remove(filename)
141
 
 
142
 
    def destroy(self):
143
 
        """Remove store; only allowed if it is empty."""
144
 
        os.rmdir(self._basedir)
145
 
        mutter("%r destroyed" % self)
146
158
 
147
159
 
148
160
 
156
168
        ImmutableStore.__init__(self, tempfile.mkdtemp())
157
169
 
158
170
    def __del__(self):
159
 
        self.delete_all()
160
 
        self.destroy()
 
171
        for f in os.listdir(self._basedir):
 
172
            fpath = os.path.join(self._basedir, f)
 
173
            # needed on windows, and maybe some other filesystems
 
174
            os.chmod(fpath, 0600)
 
175
            os.remove(fpath)
 
176
        os.rmdir(self._basedir)
 
177
        mutter("%r destroyed" % self)