/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to breezy/export.py

  • Committer: Jelmer Vernooij
  • Date: 2018-11-16 10:50:21 UTC
  • mfrom: (7164 work)
  • mto: This revision was merged to the branch mainline in revision 7165.
  • Revision ID: jelmer@jelmer.uk-20181116105021-xl419v2rh4aus1au
Merge trunk.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2010 Canonical Ltd
 
1
# Copyright (C) 2005-2011 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
 
"""Export functionality, which can take a Tree and create a different representation.
18
 
 
19
 
Such as non-controlled directories, tarfiles, zipfiles, etc.
 
17
"""Export trees to tarballs, non-controlled directories, zipfiles, etc.
20
18
"""
21
19
 
 
20
from __future__ import absolute_import
 
21
 
 
22
import errno
22
23
import os
23
 
import bzrlib.errors as errors
24
 
 
25
 
# Maps format name => export function
26
 
_exporters = {}
27
 
# Maps filename extensions => export format name
28
 
_exporter_extensions = {}
29
 
 
30
 
def register_exporter(format, extensions, func, override=False):
31
 
    """Register an exporter.
32
 
 
33
 
    :param format: This is the name of the format, such as 'tgz' or 'zip'
34
 
    :param extensions: Extensions which should be used in the case that a
35
 
                       format was not explicitly specified.
36
 
    :type extensions: List
37
 
    :param func: The function. It will be called with (tree, dest, root)
38
 
    :param override: Whether to override an object which already exists.
39
 
                     Frequently plugins will want to provide functionality
40
 
                     until it shows up in mainline, so the default is False.
41
 
    """
42
 
    global _exporters, _exporter_extensions
43
 
 
44
 
    if (format not in _exporters) or override:
45
 
        _exporters[format] = func
46
 
 
47
 
    for ext in extensions:
48
 
        if (ext not in _exporter_extensions) or override:
49
 
            _exporter_extensions[ext] = format
50
 
 
51
 
 
52
 
def register_lazy_exporter(scheme, extensions, module, funcname):
53
 
    """Register lazy-loaded exporter function.
54
 
 
55
 
    When requesting a specific type of export, load the respective path.
56
 
    """
57
 
    def _loader(tree, dest, root, subdir, filtered, per_file_timestamps):
58
 
        mod = __import__(module, globals(), locals(), [funcname])
59
 
        func = getattr(mod, funcname)
60
 
        return func(tree, dest, root, subdir, filtered=filtered,
61
 
                    per_file_timestamps=per_file_timestamps)
62
 
    register_exporter(scheme, extensions, _loader)
63
 
 
64
 
 
65
 
def export(tree, dest, format=None, root=None, subdir=None, filtered=False,
66
 
           per_file_timestamps=False):
 
24
import sys
 
25
import time
 
26
 
 
27
from . import (
 
28
    archive,
 
29
    errors,
 
30
    osutils,
 
31
    trace,
 
32
    )
 
33
 
 
34
 
 
35
def export(tree, dest, format=None, root=None, subdir=None,
 
36
           per_file_timestamps=False, fileobj=None):
67
37
    """Export the given Tree to the specific destination.
68
38
 
69
39
    :param tree: A Tree (such as RevisionTree) to export
80
50
    :param subdir: A starting directory within the tree. None means to export
81
51
        the entire tree, and anything else should specify the relative path to
82
52
        a directory to start exporting from.
83
 
    :param filtered: If True, content filtering is applied to the
84
 
                     files exported.
85
 
    :param per_file_timestamps: Whether to use the timestamp stored in the 
86
 
        tree rather than now(). This will do a revision lookup 
 
53
    :param per_file_timestamps: Whether to use the timestamp stored in the
 
54
        tree rather than now(). This will do a revision lookup
87
55
        for every file so will be significantly slower.
 
56
    :param fileobj: Optional file object to use
88
57
    """
89
 
    global _exporters, _exporter_extensions
90
 
 
91
 
    if format is None:
92
 
        for ext in _exporter_extensions:
93
 
            if dest.endswith(ext):
94
 
                format = _exporter_extensions[ext]
95
 
                break
 
58
    if format is None and dest is not None:
 
59
        format = guess_format(dest)
96
60
 
97
61
    # Most of the exporters will just have to call
98
62
    # this function anyway, so why not do it for them
99
63
    if root is None:
100
64
        root = get_root_name(dest)
101
65
 
102
 
    if format not in _exporters:
103
 
        raise errors.NoSuchExportFormat(format)
104
 
    tree.lock_read()
105
 
    try:
106
 
        return _exporters[format](tree, dest, root, subdir, filtered=filtered,
107
 
                                  per_file_timestamps=per_file_timestamps)
108
 
    finally:
109
 
        tree.unlock()
 
66
    if not per_file_timestamps:
 
67
        force_mtime = time.time()
 
68
    else:
 
69
        force_mtime = None
 
70
 
 
71
    trace.mutter('export version %r', tree)
 
72
 
 
73
    if format == 'dir':
 
74
        # TODO(jelmer): If the tree is remote (e.g. HPSS, Git Remote),
 
75
        # then we should stream a tar file and unpack that on the fly.
 
76
        with tree.lock_read():
 
77
            for unused in dir_exporter_generator(tree, dest, root, subdir,
 
78
                    force_mtime):
 
79
                pass
 
80
        return
 
81
 
 
82
    with tree.lock_read():
 
83
        chunks = tree.archive(format, dest, root=root, subdir=subdir, force_mtime=force_mtime)
 
84
        if dest == '-':
 
85
            for chunk in chunks:
 
86
                 getattr(sys.stdout, 'buffer', sys.stdout).write(chunk)
 
87
        elif fileobj is not None:
 
88
            for chunk in chunks:
 
89
                fileobj.write(chunk)
 
90
        else:
 
91
            with open(dest, 'wb') as f:
 
92
                for chunk in chunks:
 
93
                    f.write(chunk)
 
94
 
 
95
 
 
96
def guess_format(filename, default='dir'):
 
97
    """Guess the export format based on a file name.
 
98
 
 
99
    :param filename: Filename to guess from
 
100
    :param default: Default format to fall back to
 
101
    :return: format name
 
102
    """
 
103
    format = archive.format_registry.get_format_from_filename(filename)
 
104
    if format is None:
 
105
        format = default
 
106
    return format
110
107
 
111
108
 
112
109
def get_root_name(dest):
113
110
    """Get just the root name for an export.
114
111
 
115
 
    >>> get_root_name('../mytest.tar')
116
 
    'mytest'
117
 
    >>> get_root_name('mytar.tar')
118
 
    'mytar'
119
 
    >>> get_root_name('mytar.tar.bz2')
120
 
    'mytar'
121
 
    >>> get_root_name('tar.tar.tar.tgz')
122
 
    'tar.tar.tar'
123
 
    >>> get_root_name('bzr-0.0.5.tar.gz')
124
 
    'bzr-0.0.5'
125
 
    >>> get_root_name('bzr-0.0.5.zip')
126
 
    'bzr-0.0.5'
127
 
    >>> get_root_name('bzr-0.0.5')
128
 
    'bzr-0.0.5'
129
 
    >>> get_root_name('a/long/path/mytar.tgz')
130
 
    'mytar'
131
 
    >>> get_root_name('../parent/../dir/other.tbz2')
132
 
    'other'
133
112
    """
134
113
    global _exporter_extensions
 
114
    if dest == '-':
 
115
        # Exporting to -/foo doesn't make sense so use relative paths.
 
116
        return ''
135
117
    dest = os.path.basename(dest)
136
 
    for ext in _exporter_extensions:
 
118
    for ext in archive.format_registry.extensions:
137
119
        if dest.endswith(ext):
138
120
            return dest[:-len(ext)]
139
121
    return dest
140
122
 
141
123
 
142
 
def _export_iter_entries(tree, subdir):
 
124
def _export_iter_entries(tree, subdir, skip_special=True):
143
125
    """Iter the entries for tree suitable for exporting.
144
126
 
145
127
    :param tree: A tree object.
146
128
    :param subdir: None or the path of an entry to start exporting from.
 
129
    :param skip_special: Whether to skip .bzr files.
 
130
    :return: iterator over tuples with final path, tree path and inventory
 
131
        entry for each entry to export
147
132
    """
148
 
    inv = tree.inventory
149
 
    if subdir is None:
150
 
        subdir_object = None
151
 
    else:
152
 
        subdir_id = inv.path2id(subdir)
153
 
        if subdir_id is not None:
154
 
            subdir_object = inv[subdir_id]
155
 
        # XXX: subdir is path not an id, so NoSuchId isn't proper error
156
 
        else:
157
 
            raise errors.NoSuchId(tree, subdir)
158
 
    if subdir_object is not None and subdir_object.kind != 'directory':
159
 
        yield subdir_object.name, subdir_object
160
 
        return
161
 
    else:
162
 
        entries = inv.iter_entries(subdir_object)
163
 
    if subdir is None:
164
 
        entries.next() # skip root
165
 
    for entry in entries:
 
133
    if subdir == '':
 
134
        subdir = None
 
135
    if subdir is not None:
 
136
        subdir = subdir.rstrip('/')
 
137
    entries = tree.iter_entries_by_dir()
 
138
    for path, entry in entries:
 
139
        if path == '':
 
140
            continue
 
141
 
166
142
        # The .bzr* namespace is reserved for "magic" files like
167
143
        # .bzrignore and .bzrrules - do not export these
168
 
        if entry[0].startswith(".bzr"):
169
 
            continue
170
 
        if subdir is None:
171
 
            if not tree.has_filename(entry[0]):
172
 
                continue
173
 
        else:
174
 
            if not tree.has_filename(os.path.join(subdir, entry[0])):
175
 
                continue
176
 
        yield entry
177
 
 
178
 
 
179
 
register_lazy_exporter(None, [], 'bzrlib.export.dir_exporter', 'dir_exporter')
180
 
register_lazy_exporter('dir', [], 'bzrlib.export.dir_exporter', 'dir_exporter')
181
 
register_lazy_exporter('tar', ['.tar'], 'bzrlib.export.tar_exporter', 'tar_exporter')
182
 
register_lazy_exporter('tgz', ['.tar.gz', '.tgz'], 'bzrlib.export.tar_exporter', 'tgz_exporter')
183
 
register_lazy_exporter('tbz2', ['.tar.bz2', '.tbz2'], 'bzrlib.export.tar_exporter', 'tbz_exporter')
184
 
register_lazy_exporter('zip', ['.zip'], 'bzrlib.export.zip_exporter', 'zip_exporter')
185
 
 
 
144
        if skip_special and path.startswith(".bzr"):
 
145
            continue
 
146
        if path == subdir:
 
147
            if entry.kind == 'directory':
 
148
                continue
 
149
            final_path = entry.name
 
150
        elif subdir is not None:
 
151
            if path.startswith(subdir + '/'):
 
152
                final_path = path[len(subdir) + 1:]
 
153
            else:
 
154
                continue
 
155
        else:
 
156
            final_path = path
 
157
        if not tree.has_filename(path):
 
158
            continue
 
159
 
 
160
        yield final_path, path, entry
 
161
 
 
162
 
 
163
def dir_exporter_generator(tree, dest, root, subdir=None,
 
164
                           force_mtime=None, fileobj=None):
 
165
    """Return a generator that exports this tree to a new directory.
 
166
 
 
167
    `dest` should either not exist or should be empty. If it does not exist it
 
168
    will be created holding the contents of this tree.
 
169
 
 
170
    :note: If the export fails, the destination directory will be
 
171
           left in an incompletely exported state: export is not transactional.
 
172
    """
 
173
    try:
 
174
        os.mkdir(dest)
 
175
    except OSError as e:
 
176
        if e.errno == errno.EEXIST:
 
177
            # check if directory empty
 
178
            if os.listdir(dest) != []:
 
179
                raise errors.BzrError(
 
180
                    "Can't export tree to non-empty directory.")
 
181
        else:
 
182
            raise
 
183
    # Iterate everything, building up the files we will want to export, and
 
184
    # creating the directories and symlinks that we need.
 
185
    # This tracks (file_id, (destination_path, executable))
 
186
    # This matches the api that tree.iter_files_bytes() wants
 
187
    # Note in the case of revision trees, this does trigger a double inventory
 
188
    # lookup, hopefully it isn't too expensive.
 
189
    to_fetch = []
 
190
    for dp, tp, ie in _export_iter_entries(tree, subdir):
 
191
        file_id = getattr(ie, 'file_id', None)
 
192
        fullpath = osutils.pathjoin(dest, dp)
 
193
        if ie.kind == "file":
 
194
            to_fetch.append((tp, (dp, tp, file_id)))
 
195
        elif ie.kind in ("directory", "tree-reference"):
 
196
            os.mkdir(fullpath)
 
197
        elif ie.kind == "symlink":
 
198
            try:
 
199
                symlink_target = tree.get_symlink_target(tp, file_id)
 
200
                os.symlink(symlink_target, fullpath)
 
201
            except OSError as e:
 
202
                raise errors.BzrError(
 
203
                    "Failed to create symlink %r -> %r, error: %s"
 
204
                    % (fullpath, symlink_target, e))
 
205
        else:
 
206
            raise errors.BzrError("don't know how to export {%s} of kind %r" %
 
207
               (tp, ie.kind))
 
208
 
 
209
        yield
 
210
    # The data returned here can be in any order, but we've already created all
 
211
    # the directories
 
212
    flags = os.O_CREAT | os.O_TRUNC | os.O_WRONLY | getattr(os, 'O_BINARY', 0)
 
213
    for (relpath, treepath, file_id), chunks in tree.iter_files_bytes(to_fetch):
 
214
        fullpath = osutils.pathjoin(dest, relpath)
 
215
        # We set the mode and let the umask sort out the file info
 
216
        mode = 0o666
 
217
        if tree.is_executable(treepath, file_id):
 
218
            mode = 0o777
 
219
        with os.fdopen(os.open(fullpath, flags, mode), 'wb') as out:
 
220
            out.writelines(chunks)
 
221
        if force_mtime is not None:
 
222
            mtime = force_mtime
 
223
        else:
 
224
            mtime = tree.get_file_mtime(treepath, file_id)
 
225
        os.utime(fullpath, (mtime, mtime))
 
226
 
 
227
        yield