/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.2.7 by Jelmer Vernooij
Add breezy.archive.
84
        chunks = archive.create_archive(format, tree, dest, root, subdir,
85
                                        force_mtime)
86
        if dest == '-':
87
            for chunk in chunks:
88
                 sys.stdout.write(chunk)
89
        elif fileobj is not None:
90
            for chunk in chunks:
91
                fileobj.write(chunk)
92
        else:
93
            with open(dest, 'wb') as f:
94
                for chunk in chunks:
95
                    f.writelines(chunk)
6968.2.9 by Jelmer Vernooij
Simplify export module.
96
97
98
def guess_format(filename, default='dir'):
99
    """Guess the export format based on a file name.
100
101
    :param filename: Filename to guess from
102
    :param default: Default format to fall back to
103
    :return: format name
5952.1.6 by geoffreyfishing at gmail
Created get_export_generator.
104
    """
6968.2.7 by Jelmer Vernooij
Add breezy.archive.
105
    format = archive.format_registry.get_format_from_filename(filename)
106
    if format is None:
6968.2.9 by Jelmer Vernooij
Simplify export module.
107
        format = default
6968.2.7 by Jelmer Vernooij
Add breezy.archive.
108
    return format
109
110
1185.31.12 by John Arbash Meinel
Refactored the export code to make it easier to add new export formats.
111
def get_root_name(dest):
112
    """Get just the root name for an export.
113
114
    """
115
    global _exporter_extensions
5718.5.18 by Jelmer Vernooij
Don't export to '-', but rather to ''.
116
    if dest == '-':
117
        # Exporting to -/foo doesn't make sense so use relative paths.
118
        return ''
1185.31.12 by John Arbash Meinel
Refactored the export code to make it easier to add new export formats.
119
    dest = os.path.basename(dest)
6968.2.7 by Jelmer Vernooij
Add breezy.archive.
120
    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.
121
        if dest.endswith(ext):
122
            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.
123
    return dest
1185.31.12 by John Arbash Meinel
Refactored the export code to make it easier to add new export formats.
124
125
5718.5.8 by Jelmer Vernooij
add skip_special option.
126
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.
127
    """Iter the entries for tree suitable for exporting.
128
129
    :param tree: A tree object.
4988.10.2 by michal
bzr export won't fail on symlink exporting
130
    :param subdir: None or the path of an entry to start exporting from.
5718.5.8 by Jelmer Vernooij
add skip_special option.
131
    :param skip_special: Whether to skip .bzr files.
6331.2.1 by Jelmer Vernooij
Consistently pass tree path when exporting.
132
    :return: iterator over tuples with final path, tree path and inventory
133
        entry for each entry to export
3613.2.2 by Robert Collins
Refactor exporters to remove obvious duplication to a helper function.
134
    """
5809.3.1 by Aaron Bentley
Switch to iter_entries_by_dir.
135
    if subdir == '':
136
        subdir = None
137
    if subdir is not None:
138
        subdir = subdir.rstrip('/')
139
    entries = tree.iter_entries_by_dir()
140
    for path, entry in entries:
6928.1.2 by Jelmer Vernooij
Fix path specification.
141
        if path == '':
142
            continue
143
3613.2.2 by Robert Collins
Refactor exporters to remove obvious duplication to a helper function.
144
        # The .bzr* namespace is reserved for "magic" files like
145
        # .bzrignore and .bzrrules - do not export these
5809.3.1 by Aaron Bentley
Switch to iter_entries_by_dir.
146
        if skip_special and path.startswith(".bzr"):
3613.2.2 by Robert Collins
Refactor exporters to remove obvious duplication to a helper function.
147
            continue
5809.3.1 by Aaron Bentley
Switch to iter_entries_by_dir.
148
        if path == subdir:
149
            if entry.kind == 'directory':
150
                continue
151
            final_path = entry.name
152
        elif subdir is not None:
153
            if path.startswith(subdir + '/'):
154
                final_path = path[len(subdir) + 1:]
155
            else:
4010.2.1 by James Westby
Handle files that are not present in the tree when exporting (#174539)
156
                continue
157
        else:
5809.3.1 by Aaron Bentley
Switch to iter_entries_by_dir.
158
            final_path = path
159
        if not tree.has_filename(path):
160
            continue
5967.6.1 by Martin Pool
pep8 cleanup
161
6331.2.1 by Jelmer Vernooij
Consistently pass tree path when exporting.
162
        yield final_path, path, entry
6968.2.8 by Jelmer Vernooij
Make export a module.
163
164
165
def dir_exporter_generator(tree, dest, root, subdir=None,
166
                           force_mtime=None, fileobj=None):
167
    """Return a generator that exports this tree to a new directory.
168
169
    `dest` should either not exist or should be empty. If it does not exist it
170
    will be created holding the contents of this tree.
171
172
    :note: If the export fails, the destination directory will be
173
           left in an incompletely exported state: export is not transactional.
174
    """
175
    try:
176
        os.mkdir(dest)
177
    except OSError as e:
178
        if e.errno == errno.EEXIST:
179
            # check if directory empty
180
            if os.listdir(dest) != []:
181
                raise errors.BzrError(
182
                    "Can't export tree to non-empty directory.")
183
        else:
184
            raise
185
    # Iterate everything, building up the files we will want to export, and
186
    # creating the directories and symlinks that we need.
187
    # This tracks (file_id, (destination_path, executable))
188
    # This matches the api that tree.iter_files_bytes() wants
189
    # Note in the case of revision trees, this does trigger a double inventory
190
    # lookup, hopefully it isn't too expensive.
191
    to_fetch = []
192
    for dp, tp, ie in _export_iter_entries(tree, subdir):
193
        fullpath = osutils.pathjoin(dest, dp)
194
        if ie.kind == "file":
195
            to_fetch.append((tp, (dp, tp, ie.file_id)))
196
        elif ie.kind in ("directory", "tree-reference"):
197
            os.mkdir(fullpath)
198
        elif ie.kind == "symlink":
199
            try:
200
                symlink_target = tree.get_symlink_target(tp, ie.file_id)
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