~abentley/bzrtools/bzrtools.dev

« back to all changes in this revision

Viewing changes to upstream_import.py

  • Committer: abentley
  • Date: 2005-10-16 00:01:58 UTC
  • Revision ID: abentley@lappy-20051016000158-7e35573ad3792faa
Added .tmp to --detrius

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
"""Import upstream source into a branch"""
2
 
 
3
 
from bz2 import BZ2File
4
 
import errno
5
 
import os
6
 
from StringIO import StringIO
7
 
import stat
8
 
import tarfile
9
 
import zipfile
10
 
 
11
 
from bzrlib import generate_ids
12
 
from bzrlib.bzrdir import BzrDir
13
 
from bzrlib.errors import NoSuchFile, BzrCommandError, NotBranchError
14
 
from bzrlib.osutils import (pathjoin, isdir, file_iterator, basename,
15
 
                            file_kind, splitpath)
16
 
from bzrlib.trace import warning
17
 
from bzrlib.transform import TreeTransform, resolve_conflicts, cook_conflicts
18
 
from bzrlib.workingtree import WorkingTree
19
 
from bzrlib.plugins.bzrtools.bzrtools import open_from_url
20
 
 
21
 
class ZipFileWrapper(object):
22
 
 
23
 
    def __init__(self, fileobj, mode):
24
 
        self.zipfile = zipfile.ZipFile(fileobj, mode)
25
 
 
26
 
    def getmembers(self):
27
 
        for info in self.zipfile.infolist():
28
 
            yield ZipInfoWrapper(self.zipfile, info)
29
 
 
30
 
    def extractfile(self, infowrapper):
31
 
        return StringIO(self.zipfile.read(infowrapper.name))
32
 
 
33
 
    def add(self, filename):
34
 
        if isdir(filename):
35
 
            self.zipfile.writestr(filename+'/', '')
36
 
        else:
37
 
            self.zipfile.write(filename)
38
 
 
39
 
    def close(self):
40
 
        self.zipfile.close()
41
 
 
42
 
 
43
 
class ZipInfoWrapper(object):
44
 
 
45
 
    def __init__(self, zipfile, info):
46
 
        self.info = info
47
 
        self.type = None
48
 
        self.name = info.filename
49
 
        self.zipfile = zipfile
50
 
        self.mode = 0666
51
 
 
52
 
    def isdir(self):
53
 
        # Really? Eeeew!
54
 
        return bool(self.name.endswith('/'))
55
 
 
56
 
    def isreg(self):
57
 
        # Really? Eeeew!
58
 
        return not self.isdir()
59
 
 
60
 
 
61
 
class DirWrapper(object):
62
 
    def __init__(self, fileobj, mode='r'):
63
 
        assert mode == 'r', mode
64
 
        self.root = os.path.realpath(fileobj.read())
65
 
 
66
 
    def __repr__(self):
67
 
        return 'DirWrapper(%r)' % self.root
68
 
 
69
 
    def getmembers(self, subdir=None):
70
 
        if subdir is not None:
71
 
            mydir = pathjoin(self.root, subdir)
72
 
        else:
73
 
            mydir = self.root
74
 
        for child in os.listdir(mydir):
75
 
            if subdir is not None:
76
 
                child = pathjoin(subdir, child)
77
 
            fi = FileInfo(self.root, child)
78
 
            yield fi
79
 
            if fi.isdir():
80
 
                for v in self.getmembers(child):
81
 
                    yield v
82
 
 
83
 
    def extractfile(self, member):
84
 
        return open(member.fullpath)
85
 
 
86
 
 
87
 
class FileInfo(object):
88
 
 
89
 
    def __init__(self, root, filepath):
90
 
        self.fullpath = pathjoin(root, filepath)
91
 
        self.root = root
92
 
        if filepath != '':
93
 
            self.name = pathjoin(basename(root), filepath)
94
 
        else:
95
 
            print 'root %r' % root
96
 
            self.name = basename(root)
97
 
        self.type = None
98
 
        stat = os.lstat(self.fullpath)
99
 
        self.mode = stat.st_mode
100
 
        if self.isdir():
101
 
            self.name += '/'
102
 
 
103
 
    def __repr__(self):
104
 
        return 'FileInfo(%r)' % self.name
105
 
 
106
 
    def isreg(self):
107
 
        return stat.S_ISREG(self.mode)
108
 
 
109
 
    def isdir(self):
110
 
        return stat.S_ISDIR(self.mode)
111
 
 
112
 
    def issym(self):
113
 
        if stat.S_ISLNK(self.mode):
114
 
            self.linkname = os.readlink(self.fullpath)
115
 
            return True
116
 
        else:
117
 
            return False
118
 
 
119
 
 
120
 
def top_path(path):
121
 
    """Return the top directory given in a path."""
122
 
    components = splitpath(path)
123
 
    if len(components) > 0:
124
 
        return components[0]
125
 
    else:
126
 
        return ''
127
 
 
128
 
 
129
 
def common_directory(names):
130
 
    """Determine a single directory prefix from a list of names"""
131
 
    possible_prefix = None
132
 
    for name in names:
133
 
        name_top = top_path(name)
134
 
        if name_top == '':
135
 
            return None
136
 
        if possible_prefix is None:
137
 
            possible_prefix = name_top
138
 
        else:
139
 
            if name_top != possible_prefix:
140
 
                return None
141
 
    return possible_prefix
142
 
 
143
 
 
144
 
def do_directory(tt, trans_id, tree, relative_path, path):
145
 
    if isdir(path) and tree.path2id(relative_path) is not None:
146
 
        tt.cancel_deletion(trans_id)
147
 
    else:
148
 
        tt.create_directory(trans_id)
149
 
 
150
 
 
151
 
def add_implied_parents(implied_parents, path):
152
 
    """Update the set of implied parents from a path"""
153
 
    parent = os.path.dirname(path)
154
 
    if parent in implied_parents:
155
 
        return
156
 
    implied_parents.add(parent)
157
 
    add_implied_parents(implied_parents, parent)
158
 
 
159
 
 
160
 
def names_of_files(tar_file):
161
 
    for member in tar_file.getmembers():
162
 
        if member.type != "g":
163
 
            yield member.name
164
 
 
165
 
 
166
 
def should_ignore(relative_path):
167
 
    return top_path(relative_path) == '.bzr'
168
 
 
169
 
 
170
 
def import_tar(tree, tar_input):
171
 
    """Replace the contents of a working directory with tarfile contents.
172
 
    The tarfile may be a gzipped stream.  File ids will be updated.
173
 
    """
174
 
    tar_file = tarfile.open('lala', 'r', tar_input)
175
 
    import_archive(tree, tar_file)
176
 
 
177
 
def import_zip(tree, zip_input):
178
 
    zip_file = ZipFileWrapper(zip_input, 'r')
179
 
    import_archive(tree, zip_file)
180
 
 
181
 
def import_dir(tree, dir_input):
182
 
    dir_file = DirWrapper(dir_input)
183
 
    import_archive(tree, dir_file)
184
 
 
185
 
def import_archive(tree, archive_file):
186
 
    prefix = common_directory(names_of_files(archive_file))
187
 
    tt = TreeTransform(tree)
188
 
 
189
 
    removed = set()
190
 
    for path, entry in tree.inventory.iter_entries():
191
 
        if entry.parent_id is None:
192
 
            continue
193
 
        trans_id = tt.trans_id_tree_path(path)
194
 
        tt.delete_contents(trans_id)
195
 
        removed.add(path)
196
 
 
197
 
    added = set()
198
 
    implied_parents = set()
199
 
    seen = set()
200
 
    for member in archive_file.getmembers():
201
 
        if member.type == 'g':
202
 
            # type 'g' is a header
203
 
            continue
204
 
        relative_path = member.name
205
 
        if prefix is not None:
206
 
            relative_path = relative_path[len(prefix)+1:]
207
 
            relative_path = relative_path.rstrip('/')
208
 
        if relative_path == '':
209
 
            continue
210
 
        if should_ignore(relative_path):
211
 
            continue
212
 
        add_implied_parents(implied_parents, relative_path)
213
 
        trans_id = tt.trans_id_tree_path(relative_path)
214
 
        added.add(relative_path.rstrip('/'))
215
 
        path = tree.abspath(relative_path)
216
 
        if member.name in seen:
217
 
            if tt.final_kind(trans_id) == 'file':
218
 
                tt.set_executability(None, trans_id)
219
 
            tt.cancel_creation(trans_id)
220
 
        seen.add(member.name)
221
 
        if member.isreg():
222
 
            tt.create_file(file_iterator(archive_file.extractfile(member)),
223
 
                           trans_id)
224
 
            executable = (member.mode & 0111) != 0
225
 
            tt.set_executability(executable, trans_id)
226
 
        elif member.isdir():
227
 
            do_directory(tt, trans_id, tree, relative_path, path)
228
 
        elif member.issym():
229
 
            tt.create_symlink(member.linkname, trans_id)
230
 
        else:
231
 
            continue
232
 
        if tt.tree_file_id(trans_id) is None:
233
 
            name = basename(member.name.rstrip('/'))
234
 
            file_id = generate_ids.gen_file_id(name)
235
 
            tt.version_file(file_id, trans_id)
236
 
 
237
 
    for relative_path in implied_parents.difference(added):
238
 
        if relative_path == "":
239
 
            continue
240
 
        trans_id = tt.trans_id_tree_path(relative_path)
241
 
        path = tree.abspath(relative_path)
242
 
        do_directory(tt, trans_id, tree, relative_path, path)
243
 
        if tt.tree_file_id(trans_id) is None:
244
 
            tt.version_file(trans_id, trans_id)
245
 
        added.add(relative_path)
246
 
 
247
 
    for path in removed.difference(added):
248
 
        tt.unversion_file(tt.trans_id_tree_path(path))
249
 
 
250
 
    for conflict in cook_conflicts(resolve_conflicts(tt), tt):
251
 
        warning(conflict)
252
 
    tt.apply()
253
 
 
254
 
 
255
 
def do_import(source, tree_directory=None):
256
 
    """Implementation of import command.  Intended for UI only"""
257
 
    if tree_directory is not None:
258
 
        try:
259
 
            tree = WorkingTree.open(tree_directory)
260
 
        except NotBranchError:
261
 
            if not os.path.exists(tree_directory):
262
 
                os.mkdir(tree_directory)
263
 
            branch = BzrDir.create_branch_convenience(tree_directory)
264
 
            tree = branch.bzrdir.open_workingtree()
265
 
    else:
266
 
        tree = WorkingTree.open_containing('.')[0]
267
 
    tree.lock_write()
268
 
    try:
269
 
        if tree.changes_from(tree.basis_tree()).has_changed():
270
 
            raise BzrCommandError("Working tree has uncommitted changes.")
271
 
 
272
 
        if (source.endswith('.tar') or source.endswith('.tar.gz') or
273
 
            source.endswith('.tar.bz2')) or source.endswith('.tgz'):
274
 
            try:
275
 
                tar_input = open_from_url(source)
276
 
                if source.endswith('.bz2'):
277
 
                    tar_input = StringIO(tar_input.read().decode('bz2'))
278
 
            except IOError, e:
279
 
                if e.errno == errno.ENOENT:
280
 
                    raise NoSuchFile(source)
281
 
            try:
282
 
                import_tar(tree, tar_input)
283
 
            finally:
284
 
                tar_input.close()
285
 
        elif source.endswith('.zip'):
286
 
            import_zip(tree, open_from_url(source))
287
 
        elif file_kind(source) == 'directory':
288
 
            s = StringIO(source)
289
 
            s.seek(0)
290
 
            import_dir(tree, s)
291
 
        else:
292
 
            raise BzrCommandError('Unhandled import source')
293
 
    finally:
294
 
        tree.unlock()