1
"""Import upstream source into a branch"""
3
from bz2 import BZ2File
6
from StringIO import StringIO
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,
16
from bzrlib.trace import warning
17
from bzrlib.transform import TreeTransform, resolve_conflicts, cook_conflicts
18
from bzrlib.workingtree import WorkingTree
20
class ZipFileWrapper(object):
22
def __init__(self, fileobj, mode):
23
self.zipfile = zipfile.ZipFile(fileobj, mode)
26
for info in self.zipfile.infolist():
27
yield ZipInfoWrapper(self.zipfile, info)
29
def extractfile(self, infowrapper):
30
return StringIO(self.zipfile.read(infowrapper.name))
32
def add(self, filename):
34
self.zipfile.writestr(filename+'/', '')
36
self.zipfile.write(filename)
42
class ZipInfoWrapper(object):
44
def __init__(self, zipfile, info):
47
self.name = info.filename
48
self.zipfile = zipfile
53
return bool(self.name.endswith('/'))
57
return not self.isdir()
60
class DirWrapper(object):
61
def __init__(self, fileobj, mode='r'):
62
assert mode == 'r', mode
63
self.root = os.path.realpath(fileobj.read())
66
return 'DirWrapper(%r)' % self.root
68
def getmembers(self, subdir=None):
69
if subdir is not None:
70
mydir = pathjoin(self.root, subdir)
73
for child in os.listdir(mydir):
74
if subdir is not None:
75
child = pathjoin(subdir, child)
76
fi = FileInfo(self.root, child)
79
for v in self.getmembers(child):
82
def extractfile(self, member):
83
return open(member.fullpath)
86
class FileInfo(object):
88
def __init__(self, root, filepath):
89
self.fullpath = pathjoin(root, filepath)
92
self.name = pathjoin(basename(root), filepath)
94
print 'root %r' % root
95
self.name = basename(root)
97
stat = os.lstat(self.fullpath)
98
self.mode = stat.st_mode
103
return 'FileInfo(%r)' % self.name
106
return stat.S_ISREG(self.mode)
109
return stat.S_ISDIR(self.mode)
112
def top_directory(path):
113
"""Return the top directory given in a path."""
114
dirname = os.path.dirname(path)
115
last_dirname = dirname
117
dirname = os.path.dirname(dirname)
118
if dirname == '' or dirname == last_dirname:
120
last_dirname = dirname
123
def common_directory(names):
124
"""Determine a single directory prefix from a list of names"""
125
possible_prefix = None
127
name_top = top_directory(name)
130
if possible_prefix is None:
131
possible_prefix = name_top
133
if name_top != possible_prefix:
135
return possible_prefix
138
def do_directory(tt, trans_id, tree, relative_path, path):
139
if isdir(path) and tree.path2id(relative_path) is not None:
140
tt.cancel_deletion(trans_id)
142
tt.create_directory(trans_id)
145
def add_implied_parents(implied_parents, path):
146
"""Update the set of implied parents from a path"""
147
parent = os.path.dirname(path)
148
if parent in implied_parents:
150
implied_parents.add(parent)
151
add_implied_parents(implied_parents, parent)
154
def names_of_files(tar_file):
155
for member in tar_file.getmembers():
156
if member.type != "g":
160
def import_tar(tree, tar_input):
161
"""Replace the contents of a working directory with tarfile contents.
162
The tarfile may be a gzipped stream. File ids will be updated.
164
tar_file = tarfile.open('lala', 'r', tar_input)
165
import_archive(tree, tar_file)
167
def import_zip(tree, zip_input):
168
zip_file = ZipFileWrapper(zip_input, 'r')
169
import_archive(tree, zip_file)
171
def import_dir(tree, dir_input):
172
dir_file = DirWrapper(dir_input)
173
import_archive(tree, dir_file)
175
def import_archive(tree, archive_file):
176
prefix = common_directory(names_of_files(archive_file))
177
tt = TreeTransform(tree)
180
for path, entry in tree.inventory.iter_entries():
181
if entry.parent_id is None:
183
trans_id = tt.trans_id_tree_path(path)
184
tt.delete_contents(trans_id)
188
implied_parents = set()
190
for member in archive_file.getmembers():
191
if member.type == 'g':
192
# type 'g' is a header
194
relative_path = member.name
195
if prefix is not None:
196
relative_path = relative_path[len(prefix)+1:]
197
relative_path = relative_path.rstrip('/')
198
if relative_path == '':
200
add_implied_parents(implied_parents, relative_path)
201
trans_id = tt.trans_id_tree_path(relative_path)
202
added.add(relative_path.rstrip('/'))
203
path = tree.abspath(relative_path)
204
if member.name in seen:
205
if tt.final_kind(trans_id) == 'file':
206
tt.set_executability(None, trans_id)
207
tt.cancel_creation(trans_id)
208
seen.add(member.name)
210
tt.create_file(file_iterator(archive_file.extractfile(member)),
212
executable = (member.mode & 0111) != 0
213
tt.set_executability(executable, trans_id)
215
do_directory(tt, trans_id, tree, relative_path, path)
217
tt.create_symlink(member.linkname, trans_id)
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)
225
for relative_path in implied_parents.difference(added):
226
if relative_path == "":
228
trans_id = tt.trans_id_tree_path(relative_path)
229
path = tree.abspath(relative_path)
230
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
added.add(relative_path)
235
for path in removed.difference(added):
236
tt.unversion_file(tt.trans_id_tree_path(path))
238
for conflict in cook_conflicts(resolve_conflicts(tt), tt):
243
def do_import(source, tree_directory=None):
244
"""Implementation of import command. Intended for UI only"""
245
if tree_directory is not None:
247
tree = WorkingTree.open(tree_directory)
248
except NotBranchError:
249
if not os.path.exists(tree_directory):
250
os.mkdir(tree_directory)
251
branch = BzrDir.create_branch_convenience(tree_directory)
252
tree = branch.bzrdir.open_workingtree()
254
tree = WorkingTree.open_containing('.')[0]
257
if tree.changes_from(tree.basis_tree()).has_changed():
258
raise BzrCommandError("Working tree has uncommitted changes.")
260
if (source.endswith('.tar') or source.endswith('.tar.gz') or
261
source.endswith('.tar.bz2')) or source.endswith('.tgz'):
263
if source.endswith('.bz2'):
264
tar_input = BZ2File(source, 'r')
265
tar_input = StringIO(tar_input.read())
267
tar_input = file(source, 'rb')
269
if e.errno == errno.ENOENT:
270
raise NoSuchFile(source)
272
import_tar(tree, tar_input)
275
elif source.endswith('.zip'):
276
import_zip(tree, open(source, 'rb'))
277
elif file_kind(source) == 'directory':
282
raise BzrCommandError('Unhandled import source')