~abentley/bzrtools/bzrtools.dev

« back to all changes in this revision

Viewing changes to upstream_import.py

  • Committer: Aaron Bentley
  • Date: 2006-11-23 18:06:43 UTC
  • Revision ID: abentley@panoramicfeedback.com-20061123180643-6ry3xqozdbn4cfhy
Update docs

Show diffs side-by-side

added added

removed removed

Lines of Context:
3
3
from bz2 import BZ2File
4
4
import errno
5
5
import os
 
6
from shutil import rmtree
6
7
from StringIO import StringIO
7
 
import stat
8
8
import tarfile
9
 
import zipfile
 
9
from unittest import makeSuite
10
10
 
11
 
from bzrlib import generate_ids
12
11
from bzrlib.bzrdir import BzrDir
13
12
from bzrlib.errors import NoSuchFile, BzrCommandError, NotBranchError
14
 
from bzrlib.osutils import (pathjoin, isdir, file_iterator, basename,
15
 
                            file_kind)
 
13
from bzrlib.osutils import pathjoin, isdir, file_iterator
 
14
from bzrlib.tests import TestCaseInTempDir
16
15
from bzrlib.trace import warning
17
16
from bzrlib.transform import TreeTransform, resolve_conflicts, cook_conflicts
18
17
from bzrlib.workingtree import WorkingTree
19
18
 
20
 
class ZipFileWrapper(object):
21
 
 
22
 
    def __init__(self, fileobj, mode):
23
 
        self.zipfile = zipfile.ZipFile(fileobj, mode)
24
 
 
25
 
    def getmembers(self):
26
 
        for info in self.zipfile.infolist():
27
 
            yield ZipInfoWrapper(self.zipfile, info)
28
 
 
29
 
    def extractfile(self, infowrapper):
30
 
        return StringIO(self.zipfile.read(infowrapper.name))
31
 
 
32
 
    def add(self, filename):
33
 
        if isdir(filename):
34
 
            self.zipfile.writestr(filename+'/', '')
35
 
        else:
36
 
            self.zipfile.write(filename)
37
 
 
38
 
    def close(self):
39
 
        self.zipfile.close()
40
 
 
41
 
 
42
 
class ZipInfoWrapper(object):
43
 
    
44
 
    def __init__(self, zipfile, info):
45
 
        self.info = info
46
 
        self.type = None
47
 
        self.name = info.filename
48
 
        self.zipfile = zipfile
49
 
        self.mode = 0666
50
 
 
51
 
    def isdir(self):
52
 
        # Really? Eeeew!
53
 
        return bool(self.name.endswith('/'))
54
 
 
55
 
    def isreg(self):
56
 
        # Really? Eeeew!
57
 
        return not self.isdir()
58
 
 
59
 
 
60
 
class DirWrapper(object):
61
 
    def __init__(self, fileobj, mode='r'):
62
 
        assert mode == 'r', mode
63
 
        self.root = os.path.realpath(fileobj.read())
64
 
 
65
 
    def __repr__(self):
66
 
        return 'DirWrapper(%r)' % self.root
67
 
 
68
 
    def getmembers(self, subdir=None):
69
 
        if subdir is not None:
70
 
            mydir = pathjoin(self.root, subdir)
71
 
        else:
72
 
            mydir = self.root
73
 
        for child in os.listdir(mydir):
74
 
            if subdir is not None:
75
 
                child = pathjoin(subdir, child)
76
 
            fi = FileInfo(self.root, child)
77
 
            yield fi
78
 
            if fi.isdir():
79
 
                for v in self.getmembers(child):
80
 
                    yield v
81
 
 
82
 
    def extractfile(self, member):
83
 
        return open(member.fullpath)
84
 
 
85
 
 
86
 
class FileInfo(object):
87
 
 
88
 
    def __init__(self, root, filepath):
89
 
        self.fullpath = pathjoin(root, filepath)
90
 
        self.root = root
91
 
        if filepath != '':
92
 
            self.name = pathjoin(basename(root), filepath)
93
 
        else:
94
 
            print 'root %r' % root
95
 
            self.name = basename(root)
96
 
        self.type = None
97
 
        stat = os.lstat(self.fullpath)
98
 
        self.mode = stat.st_mode
99
 
        if self.isdir():
100
 
            self.name += '/'
101
 
 
102
 
    def __repr__(self):
103
 
        return 'FileInfo(%r)' % self.name
104
 
 
105
 
    def isreg(self):
106
 
        return stat.S_ISREG(self.mode)
107
 
 
108
 
    def isdir(self):
109
 
        return stat.S_ISDIR(self.mode)
110
 
 
111
 
        
 
19
 
112
20
def top_directory(path):
113
21
    """Return the top directory given in a path."""
114
22
    dirname = os.path.dirname(path)
125
33
    possible_prefix = None
126
34
    for name in names:
127
35
        name_top = top_directory(name)
128
 
        if name_top == '':
129
 
            return None
130
36
        if possible_prefix is None:
131
37
            possible_prefix = name_top
132
38
        else:
162
68
    The tarfile may be a gzipped stream.  File ids will be updated.
163
69
    """
164
70
    tar_file = tarfile.open('lala', 'r', tar_input)
165
 
    import_archive(tree, tar_file)
166
 
 
167
 
def import_zip(tree, zip_input):
168
 
    zip_file = ZipFileWrapper(zip_input, 'r')
169
 
    import_archive(tree, zip_file)
170
 
 
171
 
def import_dir(tree, dir_input):
172
 
    dir_file = DirWrapper(dir_input)
173
 
    import_archive(tree, dir_file)
174
 
 
175
 
def import_archive(tree, archive_file):
176
 
    prefix = common_directory(names_of_files(archive_file))
 
71
    prefix = common_directory(names_of_files(tar_file))
177
72
    tt = TreeTransform(tree)
178
73
 
179
74
    removed = set()
187
82
    added = set() 
188
83
    implied_parents = set()
189
84
    seen = set()
190
 
    for member in archive_file.getmembers():
 
85
    for member in tar_file.getmembers():
191
86
        if member.type == 'g':
192
87
            # type 'g' is a header
193
88
            continue
194
89
        relative_path = member.name 
195
90
        if prefix is not None:
196
91
            relative_path = relative_path[len(prefix)+1:]
197
 
            relative_path = relative_path.rstrip('/')
198
92
        if relative_path == '':
199
93
            continue
200
94
        add_implied_parents(implied_parents, relative_path)
202
96
        added.add(relative_path.rstrip('/'))
203
97
        path = tree.abspath(relative_path)
204
98
        if member.name in seen:
205
 
            if tt.final_kind(trans_id) == 'file':
206
 
                tt.set_executability(None, trans_id)
207
99
            tt.cancel_creation(trans_id)
208
100
        seen.add(member.name)
209
101
        if member.isreg():
210
 
            tt.create_file(file_iterator(archive_file.extractfile(member)), 
 
102
            tt.create_file(file_iterator(tar_file.extractfile(member)), 
211
103
                           trans_id)
212
 
            executable = (member.mode & 0111) != 0
213
 
            tt.set_executability(executable, trans_id)
214
104
        elif member.isdir():
215
105
            do_directory(tt, trans_id, tree, relative_path, path)
216
106
        elif member.issym():
217
107
            tt.create_symlink(member.linkname, trans_id)
218
 
        else:
219
 
            continue
220
 
        if tt.tree_file_id(trans_id) is None:
221
 
            name = basename(member.name.rstrip('/'))
222
 
            file_id = generate_ids.gen_file_id(name)
223
 
            tt.version_file(file_id, trans_id)
224
108
 
225
109
    for relative_path in implied_parents.difference(added):
226
110
        if relative_path == "":
228
112
        trans_id = tt.trans_id_tree_path(relative_path)
229
113
        path = tree.abspath(relative_path)
230
114
        do_directory(tt, trans_id, tree, relative_path, path)
231
 
        if tt.tree_file_id(trans_id) is None:
232
 
            tt.version_file(trans_id, trans_id)
233
115
        added.add(relative_path)
234
116
 
235
 
    for path in removed.difference(added):
236
 
        tt.unversion_file(tt.trans_id_tree_path(path))
237
 
 
238
117
    for conflict in cook_conflicts(resolve_conflicts(tt), tt):
239
118
        warning(conflict)
240
119
    tt.apply()
 
120
    update_ids(tree, added, removed)
 
121
 
 
122
 
 
123
def update_ids(tree, added, removed):
 
124
    """Make sure that all present files files have file_ids.
 
125
    """
 
126
    # XXX detect renames
 
127
    new = added.difference(removed)
 
128
    deleted = removed.difference(added)
 
129
    tree.add(sorted(new))
 
130
    tree.remove(sorted(deleted, reverse=True))
241
131
 
242
132
 
243
133
def do_import(source, tree_directory=None):
272
162
                import_tar(tree, tar_input)
273
163
            finally:
274
164
                tar_input.close()
275
 
        elif source.endswith('.zip'):
276
 
            import_zip(tree, open(source, 'rb'))
277
 
        elif file_kind(source) == 'directory':
278
 
            s = StringIO(source)
279
 
            s.seek(0)
280
 
            import_dir(tree, s)
281
 
        else:
282
 
            raise BzrCommandError('Unhandled import source')
283
165
    finally:
284
166
        tree.unlock()
 
167
 
 
168
class TestImport(TestCaseInTempDir):
 
169
 
 
170
    def make_tar(self, mode='w'):
 
171
        result = StringIO()
 
172
        tar_file = tarfile.open('project-0.1.tar', mode, result)
 
173
        os.mkdir('project-0.1')
 
174
        tar_file.add('project-0.1')
 
175
        os.mkdir('project-0.1/junk')
 
176
        tar_file.add('project-0.1/junk')
 
177
        
 
178
        f = file('project-0.1/README', 'wb')
 
179
        f.write('What?')
 
180
        f.close()
 
181
        tar_file.add('project-0.1/README')
 
182
 
 
183
        f = file('project-0.1/FEEDME', 'wb')
 
184
        f.write('Hungry!!')
 
185
        f.close()
 
186
        tar_file.add('project-0.1/FEEDME')
 
187
 
 
188
        tar_file.close()
 
189
        rmtree('project-0.1')
 
190
        result.seek(0)
 
191
        return result
 
192
 
 
193
    def make_tar2(self):
 
194
        result = StringIO()
 
195
        tar_file = tarfile.open('project-0.2.tar', 'w', result)
 
196
        os.mkdir('project-0.2')
 
197
        tar_file.add('project-0.2')
 
198
        
 
199
        os.mkdir('project-0.2/junk')
 
200
        tar_file.add('project-0.2/junk')
 
201
 
 
202
        f = file('project-0.2/README', 'wb')
 
203
        f.write('Now?')
 
204
        f.close()
 
205
        tar_file.add('project-0.2/README')
 
206
        tar_file.close()
 
207
 
 
208
        tar_file = tarfile.open('project-0.2.tar', 'a', result)
 
209
        tar_file.add('project-0.2/README')
 
210
 
 
211
        rmtree('project-0.2')
 
212
        return result
 
213
 
 
214
    def make_messed_tar(self):
 
215
        result = StringIO()
 
216
        tar_file = tarfile.open('project-0.1.tar', 'w', result)
 
217
        os.mkdir('project-0.1')
 
218
        tar_file.add('project-0.1')
 
219
 
 
220
        os.mkdir('project-0.2')
 
221
        tar_file.add('project-0.2')
 
222
        
 
223
        f = file('project-0.1/README', 'wb')
 
224
        f.write('What?')
 
225
        f.close()
 
226
        tar_file.add('project-0.1/README')
 
227
        tar_file.close()
 
228
        rmtree('project-0.1')
 
229
        result.seek(0)
 
230
        return result
 
231
 
 
232
    def test_top_directory(self):
 
233
        self.assertEqual(top_directory('ab/b/c'), 'ab')
 
234
        self.assertEqual(top_directory('/etc'), '/')
 
235
 
 
236
    def test_common_directory(self):
 
237
        self.assertEqual(common_directory(['ab/c/d', 'ab/c/e']), 'ab')
 
238
        self.assertIs(common_directory(['ab/c/d', 'ac/c/e']), None)
 
239
 
 
240
    def test_untar(self):
 
241
        tar_file = self.make_tar()
 
242
        tree = BzrDir.create_standalone_workingtree('tree')
 
243
        import_tar(tree, tar_file)
 
244
        self.assertTrue(tree.path2id('README') is not None) 
 
245
        self.assertTrue(tree.path2id('FEEDME') is not None)
 
246
        self.assertTrue(os.path.isfile(tree.abspath('README')))
 
247
        self.assertEqual(tree.inventory[tree.path2id('README')].kind, 'file')
 
248
        self.assertEqual(tree.inventory[tree.path2id('FEEDME')].kind, 'file')
 
249
        
 
250
        f = file(tree.abspath('junk/food'), 'wb')
 
251
        f.write('I like food\n')
 
252
        f.close()
 
253
 
 
254
        tar_file = self.make_tar2()
 
255
        import_tar(tree, tar_file)
 
256
        self.assertTrue(tree.path2id('README') is not None) 
 
257
        self.assertTrue(not os.path.exists(tree.abspath('FEEDME')))
 
258
 
 
259
 
 
260
    def test_untar2(self):
 
261
        tar_file = self.make_messed_tar()
 
262
        tree = BzrDir.create_standalone_workingtree('tree')
 
263
        import_tar(tree, tar_file)
 
264
        self.assertTrue(tree.path2id('project-0.1/README') is not None) 
 
265
 
 
266
    def test_untar_gzip(self):
 
267
        tar_file = self.make_tar(mode='w:gz')
 
268
        tree = BzrDir.create_standalone_workingtree('tree')
 
269
        import_tar(tree, tar_file)
 
270
        self.assertTrue(tree.path2id('README') is not None) 
 
271
 
 
272
 
 
273
def test_suite():
 
274
    return makeSuite(TestImport)