/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
6968.2.8 by Jelmer Vernooij
Make export a module.
27
from . import (
6968.2.6 by Jelmer Vernooij
Move tar/zip to breezy.archive.
28
    archive,
5436.2.1 by Andrew Bennetts
Add bzrlib.pyutils, which has get_named_object, a wrapper around __import__.
29
    errors,
6968.2.8 by Jelmer Vernooij
Make export a module.
30
    osutils,
5718.5.4 by Jelmer Vernooij
fix timestamp in tgz files.
31
    trace,
5436.2.1 by Andrew Bennetts
Add bzrlib.pyutils, which has get_named_object, a wrapper around __import__.
32
    )
1185.31.12 by John Arbash Meinel
Refactored the export code to make it easier to add new export formats.
33
5967.6.1 by Martin Pool
pep8 cleanup
34
6968.2.9 by Jelmer Vernooij
Simplify export module.
35
def export(tree, dest, format=None, root=None, subdir=None,
36
           per_file_timestamps=False, fileobj=None):
37
    """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.
38
39
    :param tree: A Tree (such as RevisionTree) to export
6968.2.9 by Jelmer Vernooij
Simplify export module.
40
    :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.
41
    :param format: The format (dir, zip, etc), if None, it will check the
6968.2.9 by Jelmer Vernooij
Simplify export module.
42
                   extension on dest, looking for a match
43
    :param root: The root location inside the format.
44
                 It is common practise to have zipfiles and tarballs
45
                 extract into a subdirectory, rather than into the
46
                 current working directory.
47
                 If root is None, the default root will be
48
                 selected as the destination without its
49
                 extension.
3613.2.1 by Robert Collins
Teach export how to export a subdirectory. (Robert Collins)
50
    :param subdir: A starting directory within the tree. None means to export
51
        the entire tree, and anything else should specify the relative path to
52
        a directory to start exporting from.
6968.2.9 by Jelmer Vernooij
Simplify export module.
53
    :param per_file_timestamps: Whether to use the timestamp stored in the
54
        tree rather than now(). This will do a revision lookup
55
        for every file so will be significantly slower.
5952.1.6 by geoffreyfishing at gmail
Created get_export_generator.
56
    :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.
57
    """
5952.1.6 by geoffreyfishing at gmail
Created get_export_generator.
58
    if format is None and dest is not None:
6968.2.9 by Jelmer Vernooij
Simplify export module.
59
        format = guess_format(dest)
1185.31.12 by John Arbash Meinel
Refactored the export code to make it easier to add new export formats.
60
61
    # Most of the exporters will just have to call
62
    # this function anyway, so why not do it for them
63
    if root is None:
64
        root = get_root_name(dest)
65
5718.5.1 by Jelmer Vernooij
per_file_timestamp -> force_mtime.
66
    if not per_file_timestamps:
67
        force_mtime = time.time()
68
    else:
69
        force_mtime = None
70
5718.5.4 by Jelmer Vernooij
fix timestamp in tgz files.
71
    trace.mutter('export version %r', tree)
72
6968.2.7 by Jelmer Vernooij
Add breezy.archive.
73
    if format == 'dir':
6968.2.9 by Jelmer Vernooij
Simplify export module.
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.
6968.2.7 by Jelmer Vernooij
Add breezy.archive.
76
        with tree.lock_read():
77
            for unused in dir_exporter_generator(tree, dest, root, subdir,
78
                    force_mtime):
6968.2.9 by Jelmer Vernooij
Simplify export module.
79
                pass
6968.2.7 by Jelmer Vernooij
Add breezy.archive.
80
        return
81
6754.8.4 by Jelmer Vernooij
Use new context stuff.
82
    with tree.lock_read():
6968.4.4 by Jelmer Vernooij
Update for API changes from archive branch.
83
        chunks = tree.archive(format, dest, root=root, subdir=subdir, force_mtime=force_mtime)
6968.2.7 by Jelmer Vernooij
Add breezy.archive.
84
        if dest == '-':
85
            for chunk in chunks:
7045.1.10 by Jelmer Vernooij
Fix iterator use in export.
86
                 getattr(sys.stdout, 'buffer', sys.stdout).write(chunk)
6968.2.7 by Jelmer Vernooij
Add breezy.archive.
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:
6973.11.1 by Jelmer Vernooij
Fix export_pot.
93
                    f.write(chunk)
6968.2.9 by Jelmer Vernooij
Simplify export module.
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
5952.1.6 by geoffreyfishing at gmail
Created get_export_generator.
102
    """
6968.2.7 by Jelmer Vernooij
Add breezy.archive.
103
    format = archive.format_registry.get_format_from_filename(filename)
104
    if format is None:
6968.2.9 by Jelmer Vernooij
Simplify export module.
105
        format = default
6968.2.7 by Jelmer Vernooij
Add breezy.archive.
106
    return format
107
108
1185.31.12 by John Arbash Meinel
Refactored the export code to make it easier to add new export formats.
109
def get_root_name(dest):
110
    """Get just the root name for an export.
111
112
    """
113
    global _exporter_extensions
5718.5.18 by Jelmer Vernooij
Don't export to '-', but rather to ''.
114
    if dest == '-':
115
        # Exporting to -/foo doesn't make sense so use relative paths.
116
        return ''
1185.31.12 by John Arbash Meinel
Refactored the export code to make it easier to add new export formats.
117
    dest = os.path.basename(dest)
6968.2.7 by Jelmer Vernooij
Add breezy.archive.
118
    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.
119
        if dest.endswith(ext):
120
            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.
121
    return dest
1185.31.12 by John Arbash Meinel
Refactored the export code to make it easier to add new export formats.
122
123
5718.5.8 by Jelmer Vernooij
add skip_special option.
124
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.
125
    """Iter the entries for tree suitable for exporting.
126
127
    :param tree: A tree object.
4988.10.2 by michal
bzr export won't fail on symlink exporting
128
    :param subdir: None or the path of an entry to start exporting from.
5718.5.8 by Jelmer Vernooij
add skip_special option.
129
    :param skip_special: Whether to skip .bzr files.
6331.2.1 by Jelmer Vernooij
Consistently pass tree path when exporting.
130
    :return: iterator over tuples with final path, tree path and inventory
131
        entry for each entry to export
3613.2.2 by Robert Collins
Refactor exporters to remove obvious duplication to a helper function.
132
    """
5809.3.1 by Aaron Bentley
Switch to iter_entries_by_dir.
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:
6928.1.2 by Jelmer Vernooij
Fix path specification.
139
        if path == '':
140
            continue
141
3613.2.2 by Robert Collins
Refactor exporters to remove obvious duplication to a helper function.
142
        # The .bzr* namespace is reserved for "magic" files like
143
        # .bzrignore and .bzrrules - do not export these
5809.3.1 by Aaron Bentley
Switch to iter_entries_by_dir.
144
        if skip_special and path.startswith(".bzr"):
3613.2.2 by Robert Collins
Refactor exporters to remove obvious duplication to a helper function.
145
            continue
5809.3.1 by Aaron Bentley
Switch to iter_entries_by_dir.
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:
4010.2.1 by James Westby
Handle files that are not present in the tree when exporting (#174539)
154
                continue
155
        else:
5809.3.1 by Aaron Bentley
Switch to iter_entries_by_dir.
156
            final_path = path
157
        if not tree.has_filename(path):
158
            continue
5967.6.1 by Martin Pool
pep8 cleanup
159
6331.2.1 by Jelmer Vernooij
Consistently pass tree path when exporting.
160
        yield final_path, path, entry
6968.2.8 by Jelmer Vernooij
Make export a module.
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):
6973.3.4 by Jelmer Vernooij
Don't assume entries returned by trees have a 'file_id' attribute.
191
        file_id = getattr(ie, 'file_id', None)
6968.2.8 by Jelmer Vernooij
Make export a module.
192
        fullpath = osutils.pathjoin(dest, dp)
193
        if ie.kind == "file":
6973.3.4 by Jelmer Vernooij
Don't assume entries returned by trees have a 'file_id' attribute.
194
            to_fetch.append((tp, (dp, tp, file_id)))
6968.2.8 by Jelmer Vernooij
Make export a module.
195
        elif ie.kind in ("directory", "tree-reference"):
196
            os.mkdir(fullpath)
197
        elif ie.kind == "symlink":
198
            try:
6973.3.4 by Jelmer Vernooij
Don't assume entries returned by trees have a 'file_id' attribute.
199
                symlink_target = tree.get_symlink_target(tp, file_id)
6968.2.8 by Jelmer Vernooij
Make export a module.
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