/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
5809.3.2 by Aaron Bentley
Support PreviewTree.has_filename.
1
# Copyright (C) 2005-2011 Canonical Ltd
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
2
#
1185.31.12 by John Arbash Meinel
Refactored the export code to make it easier to add new export formats.
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
7
#
1185.31.12 by John Arbash Meinel
Refactored the export code to make it easier to add new export formats.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
12
#
1185.31.12 by John Arbash Meinel
Refactored the export code to make it easier to add new export formats.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1185.31.12 by John Arbash Meinel
Refactored the export code to make it easier to add new export formats.
16
5967.6.1 by Martin Pool
pep8 cleanup
17
"""Export trees to tarballs, non-controlled directories, zipfiles, etc.
1185.31.12 by John Arbash Meinel
Refactored the export code to make it easier to add new export formats.
18
"""
19
6379.6.7 by Jelmer Vernooij
Move importing from future until after doc string, otherwise the doc string will disappear.
20
from __future__ import absolute_import
21
6968.2.8 by Jelmer Vernooij
Make export a module.
22
import errno
1185.31.12 by John Arbash Meinel
Refactored the export code to make it easier to add new export formats.
23
import os
6968.2.7 by Jelmer Vernooij
Add breezy.archive.
24
import sys
5718.5.1 by Jelmer Vernooij
per_file_timestamp -> force_mtime.
25
import time
6006.3.6 by Martin Pool
Deprecate export(filtered=True)
26
import warnings
27
6968.2.8 by Jelmer Vernooij
Make export a module.
28
from . import (
6968.2.6 by Jelmer Vernooij
Move tar/zip to breezy.archive.
29
    archive,
5436.2.1 by Andrew Bennetts
Add bzrlib.pyutils, which has get_named_object, a wrapper around __import__.
30
    errors,
6968.2.8 by Jelmer Vernooij
Make export a module.
31
    osutils,
5718.5.4 by Jelmer Vernooij
fix timestamp in tgz files.
32
    trace,
5436.2.1 by Andrew Bennetts
Add bzrlib.pyutils, which has get_named_object, a wrapper around __import__.
33
    )
1185.31.12 by John Arbash Meinel
Refactored the export code to make it easier to add new export formats.
34
5967.6.1 by Martin Pool
pep8 cleanup
35
6968.2.9 by Jelmer Vernooij
Simplify export module.
36
def export(tree, dest, format=None, root=None, subdir=None,
37
           per_file_timestamps=False, fileobj=None):
38
    """Export the given Tree to the specific destination.
1185.31.12 by John Arbash Meinel
Refactored the export code to make it easier to add new export formats.
39
40
    :param tree: A Tree (such as RevisionTree) to export
6968.2.9 by Jelmer Vernooij
Simplify export module.
41
    :param dest: The destination where the files,etc should be put
1185.31.12 by John Arbash Meinel
Refactored the export code to make it easier to add new export formats.
42
    :param format: The format (dir, zip, etc), if None, it will check the
6968.2.9 by Jelmer Vernooij
Simplify export module.
43
                   extension on dest, looking for a match
44
    :param root: The root location inside the format.
45
                 It is common practise to have zipfiles and tarballs
46
                 extract into a subdirectory, rather than into the
47
                 current working directory.
48
                 If root is None, the default root will be
49
                 selected as the destination without its
50
                 extension.
3613.2.1 by Robert Collins
Teach export how to export a subdirectory. (Robert Collins)
51
    :param subdir: A starting directory within the tree. None means to export
52
        the entire tree, and anything else should specify the relative path to
53
        a directory to start exporting from.
6968.2.9 by Jelmer Vernooij
Simplify export module.
54
    :param per_file_timestamps: Whether to use the timestamp stored in the
55
        tree rather than now(). This will do a revision lookup
56
        for every file so will be significantly slower.
5952.1.6 by geoffreyfishing at gmail
Created get_export_generator.
57
    :param fileobj: Optional file object to use
1185.31.12 by John Arbash Meinel
Refactored the export code to make it easier to add new export formats.
58
    """
5952.1.6 by geoffreyfishing at gmail
Created get_export_generator.
59
    if format is None and dest is not None:
6968.2.9 by Jelmer Vernooij
Simplify export module.
60
        format = guess_format(dest)
1185.31.12 by John Arbash Meinel
Refactored the export code to make it easier to add new export formats.
61
62
    # Most of the exporters will just have to call
63
    # this function anyway, so why not do it for them
64
    if root is None:
65
        root = get_root_name(dest)
66
5718.5.1 by Jelmer Vernooij
per_file_timestamp -> force_mtime.
67
    if not per_file_timestamps:
68
        force_mtime = time.time()
69
    else:
70
        force_mtime = None
71
5718.5.4 by Jelmer Vernooij
fix timestamp in tgz files.
72
    trace.mutter('export version %r', tree)
73
6968.2.7 by Jelmer Vernooij
Add breezy.archive.
74
    if format == 'dir':
6968.2.9 by Jelmer Vernooij
Simplify export module.
75
        # TODO(jelmer): If the tree is remote (e.g. HPSS, Git Remote),
76
        # then we should stream a tar file and unpack that on the fly.
6968.2.7 by Jelmer Vernooij
Add breezy.archive.
77
        with tree.lock_read():
78
            for unused in dir_exporter_generator(tree, dest, root, subdir,
79
                    force_mtime):
6968.2.9 by Jelmer Vernooij
Simplify export module.
80
                pass
6968.2.7 by Jelmer Vernooij
Add breezy.archive.
81
        return
82
6754.8.4 by Jelmer Vernooij
Use new context stuff.
83
    with tree.lock_read():
6968.4.4 by Jelmer Vernooij
Update for API changes from archive branch.
84
        chunks = tree.archive(format, dest, root=root, subdir=subdir, force_mtime=force_mtime)
6968.2.7 by Jelmer Vernooij
Add breezy.archive.
85
        if dest == '-':
86
            for chunk in chunks:
87
                 sys.stdout.write(chunk)
88
        elif fileobj is not None:
89
            for chunk in chunks:
90
                fileobj.write(chunk)
91
        else:
92
            with open(dest, 'wb') as f:
93
                for chunk in chunks:
6973.11.1 by Jelmer Vernooij
Fix export_pot.
94
                    f.write(chunk)
6968.2.9 by Jelmer Vernooij
Simplify export module.
95
96
97
def guess_format(filename, default='dir'):
98
    """Guess the export format based on a file name.
99
100
    :param filename: Filename to guess from
101
    :param default: Default format to fall back to
102
    :return: format name
5952.1.6 by geoffreyfishing at gmail
Created get_export_generator.
103
    """
6968.2.7 by Jelmer Vernooij
Add breezy.archive.
104
    format = archive.format_registry.get_format_from_filename(filename)
105
    if format is None:
6968.2.9 by Jelmer Vernooij
Simplify export module.
106
        format = default
6968.2.7 by Jelmer Vernooij
Add breezy.archive.
107
    return format
108
109
1185.31.12 by John Arbash Meinel
Refactored the export code to make it easier to add new export formats.
110
def get_root_name(dest):
111
    """Get just the root name for an export.
112
113
    """
114
    global _exporter_extensions
5718.5.18 by Jelmer Vernooij
Don't export to '-', but rather to ''.
115
    if dest == '-':
116
        # Exporting to -/foo doesn't make sense so use relative paths.
117
        return ''
1185.31.12 by John Arbash Meinel
Refactored the export code to make it easier to add new export formats.
118
    dest = os.path.basename(dest)
6968.2.7 by Jelmer Vernooij
Add breezy.archive.
119
    for ext in archive.format_registry.extensions:
1185.31.12 by John Arbash Meinel
Refactored the export code to make it easier to add new export formats.
120
        if dest.endswith(ext):
121
            return dest[:-len(ext)]
1185.31.13 by John Arbash Meinel
Updated the test to also test zip exports. Fixed some small bugs exposed by test suite.
122
    return dest
1185.31.12 by John Arbash Meinel
Refactored the export code to make it easier to add new export formats.
123
124
5718.5.8 by Jelmer Vernooij
add skip_special option.
125
def _export_iter_entries(tree, subdir, skip_special=True):
3613.2.2 by Robert Collins
Refactor exporters to remove obvious duplication to a helper function.
126
    """Iter the entries for tree suitable for exporting.
127
128
    :param tree: A tree object.
4988.10.2 by michal
bzr export won't fail on symlink exporting
129
    :param subdir: None or the path of an entry to start exporting from.
5718.5.8 by Jelmer Vernooij
add skip_special option.
130
    :param skip_special: Whether to skip .bzr files.
6331.2.1 by Jelmer Vernooij
Consistently pass tree path when exporting.
131
    :return: iterator over tuples with final path, tree path and inventory
132
        entry for each entry to export
3613.2.2 by Robert Collins
Refactor exporters to remove obvious duplication to a helper function.
133
    """
5809.3.1 by Aaron Bentley
Switch to iter_entries_by_dir.
134
    if subdir == '':
135
        subdir = None
136
    if subdir is not None:
137
        subdir = subdir.rstrip('/')
138
    entries = tree.iter_entries_by_dir()
139
    for path, entry in entries:
6928.1.2 by Jelmer Vernooij
Fix path specification.
140
        if path == '':
141
            continue
142
3613.2.2 by Robert Collins
Refactor exporters to remove obvious duplication to a helper function.
143
        # The .bzr* namespace is reserved for "magic" files like
144
        # .bzrignore and .bzrrules - do not export these
5809.3.1 by Aaron Bentley
Switch to iter_entries_by_dir.
145
        if skip_special and path.startswith(".bzr"):
3613.2.2 by Robert Collins
Refactor exporters to remove obvious duplication to a helper function.
146
            continue
5809.3.1 by Aaron Bentley
Switch to iter_entries_by_dir.
147
        if path == subdir:
148
            if entry.kind == 'directory':
149
                continue
150
            final_path = entry.name
151
        elif subdir is not None:
152
            if path.startswith(subdir + '/'):
153
                final_path = path[len(subdir) + 1:]
154
            else:
4010.2.1 by James Westby
Handle files that are not present in the tree when exporting (#174539)
155
                continue
156
        else:
5809.3.1 by Aaron Bentley
Switch to iter_entries_by_dir.
157
            final_path = path
158
        if not tree.has_filename(path):
159
            continue
5967.6.1 by Martin Pool
pep8 cleanup
160
6331.2.1 by Jelmer Vernooij
Consistently pass tree path when exporting.
161
        yield final_path, path, entry
6968.2.8 by Jelmer Vernooij
Make export a module.
162
163
164
def dir_exporter_generator(tree, dest, root, subdir=None,
165
                           force_mtime=None, fileobj=None):
166
    """Return a generator that exports this tree to a new directory.
167
168
    `dest` should either not exist or should be empty. If it does not exist it
169
    will be created holding the contents of this tree.
170
171
    :note: If the export fails, the destination directory will be
172
           left in an incompletely exported state: export is not transactional.
173
    """
174
    try:
175
        os.mkdir(dest)
176
    except OSError as e:
177
        if e.errno == errno.EEXIST:
178
            # check if directory empty
179
            if os.listdir(dest) != []:
180
                raise errors.BzrError(
181
                    "Can't export tree to non-empty directory.")
182
        else:
183
            raise
184
    # Iterate everything, building up the files we will want to export, and
185
    # creating the directories and symlinks that we need.
186
    # This tracks (file_id, (destination_path, executable))
187
    # This matches the api that tree.iter_files_bytes() wants
188
    # Note in the case of revision trees, this does trigger a double inventory
189
    # lookup, hopefully it isn't too expensive.
190
    to_fetch = []
191
    for dp, tp, ie in _export_iter_entries(tree, subdir):
6973.3.4 by Jelmer Vernooij
Don't assume entries returned by trees have a 'file_id' attribute.
192
        file_id = getattr(ie, 'file_id', None)
6968.2.8 by Jelmer Vernooij
Make export a module.
193
        fullpath = osutils.pathjoin(dest, dp)
194
        if ie.kind == "file":
6973.3.4 by Jelmer Vernooij
Don't assume entries returned by trees have a 'file_id' attribute.
195
            to_fetch.append((tp, (dp, tp, file_id)))
6968.2.8 by Jelmer Vernooij
Make export a module.
196
        elif ie.kind in ("directory", "tree-reference"):
197
            os.mkdir(fullpath)
198
        elif ie.kind == "symlink":
199
            try:
6973.3.4 by Jelmer Vernooij
Don't assume entries returned by trees have a 'file_id' attribute.
200
                symlink_target = tree.get_symlink_target(tp, file_id)
6968.2.8 by Jelmer Vernooij
Make export a module.
201
                os.symlink(symlink_target, fullpath)
202
            except OSError as e:
203
                raise errors.BzrError(
204
                    "Failed to create symlink %r -> %r, error: %s"
205
                    % (fullpath, symlink_target, e))
206
        else:
207
            raise errors.BzrError("don't know how to export {%s} of kind %r" %
208
               (tp, ie.kind))
209
210
        yield
211
    # The data returned here can be in any order, but we've already created all
212
    # the directories
213
    flags = os.O_CREAT | os.O_TRUNC | os.O_WRONLY | getattr(os, 'O_BINARY', 0)
214
    for (relpath, treepath, file_id), chunks in tree.iter_files_bytes(to_fetch):
215
        fullpath = osutils.pathjoin(dest, relpath)
216
        # We set the mode and let the umask sort out the file info
217
        mode = 0o666
218
        if tree.is_executable(treepath, file_id):
219
            mode = 0o777
220
        with os.fdopen(os.open(fullpath, flags, mode), 'wb') as out:
221
            out.writelines(chunks)
222
        if force_mtime is not None:
223
            mtime = force_mtime
224
        else:
225
            mtime = tree.get_file_mtime(treepath, file_id)
226
        os.utime(fullpath, (mtime, mtime))
227
228
        yield