/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
0.358.2 by Jelmer Vernooij
Refresh copyright headers, add my email.
1
# Copyright (C) 2008-2018 Jelmer Vernooij <jelmer@jelmer.uk>
0.200.135 by Jelmer Vernooij
Add stub for fetching data.
2
#
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.
7
#
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.
12
#
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
0.358.1 by Jelmer Vernooij
Fix FSF address.
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
0.200.135 by Jelmer Vernooij
Add stub for fetching data.
16
0.358.3 by Jelmer Vernooij
Enable absolute import.
17
"""Fetching from git into bzr."""
18
0.200.1594 by Jelmer Vernooij
Use absolute_import everywhere.
19
from __future__ import absolute_import
20
0.200.1636 by Jelmer Vernooij
Some formatting fixes.
21
from dulwich.errors import (
22
    NotCommitError,
23
    )
0.200.261 by Jelmer Vernooij
More formatting fixes.
24
from dulwich.objects import (
25
    Commit,
0.200.303 by Jelmer Vernooij
Cope with tags during fetch.
26
    Tag,
0.200.814 by Jelmer Vernooij
Avoid the use of InventoryDirectory.children. This speeds up
27
    Tree,
0.200.1407 by Jelmer Vernooij
Don't consider submodule modes unusual.
28
    S_IFGITLINK,
0.200.540 by Jelmer Vernooij
Handle submodules explicitly.
29
    S_ISGITLINK,
0.200.1176 by Jelmer Vernooij
Fix fetch return value for inter git fetching.
30
    ZERO_SHA,
0.200.261 by Jelmer Vernooij
More formatting fixes.
31
    )
0.200.883 by Jelmer Vernooij
Add function for verifying reconstruction of objects still works.
32
from dulwich.object_store import (
0.281.5 by William Grant
Fix pull with new dulwich by avoiding removed ObjectStore.get_graph_walker.
33
    ObjectStoreGraphWalker,
0.200.883 by Jelmer Vernooij
Add function for verifying reconstruction of objects still works.
34
    tree_lookup_path,
35
    )
0.200.1350 by Jelmer Vernooij
Implement search_missing_revision_ids.
36
from dulwich.walk import Walker
0.200.830 by Jelmer Vernooij
Bump minimum dulwich version.
37
from itertools import (
38
    imap,
39
    )
0.200.819 by Jelmer Vernooij
Avoid decoding basename twice.
40
import posixpath
0.200.563 by Jelmer Vernooij
Attempt to parse progress indication from git status reports.
41
import re
0.200.352 by Jelmer Vernooij
Simplify mode handling.
42
import stat
0.200.252 by Jelmer Vernooij
Clarify history, copyright.
43
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
44
from ... import (
0.231.2 by Jelmer Vernooij
Add -Dverify flag (not fully implemented yet).
45
    debug,
0.200.1433 by Jelmer Vernooij
Fix fetching between git repositories.
46
    errors,
0.200.252 by Jelmer Vernooij
Clarify history, copyright.
47
    osutils,
0.200.261 by Jelmer Vernooij
More formatting fixes.
48
    trace,
0.200.252 by Jelmer Vernooij
Clarify history, copyright.
49
    ui,
50
    )
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
51
from ...errors import (
0.239.5 by Jelmer Vernooij
Print user-understandable error message when encountering submodules.
52
    BzrError,
0.200.252 by Jelmer Vernooij
Clarify history, copyright.
53
    )
0.200.1648 by Jelmer Vernooij
Fix compatibility with newer versions of breezy.
54
from ...bzr.inventory import (
0.229.2 by Jelmer Vernooij
Initial work relying on inventory deltas.
55
    InventoryDirectory,
56
    InventoryFile,
0.229.3 by Jelmer Vernooij
Use inventory deltas internally so fetch is O(changes) rather than O(tree).
57
    InventoryLink,
0.200.664 by Jelmer Vernooij
Support submodules during fetch.
58
    TreeReference,
0.200.261 by Jelmer Vernooij
More formatting fixes.
59
    )
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
60
from ...repository import (
0.200.261 by Jelmer Vernooij
More formatting fixes.
61
    InterRepository,
62
    )
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
63
from ...revision import (
0.229.3 by Jelmer Vernooij
Use inventory deltas internally so fetch is O(changes) rather than O(tree).
64
    NULL_REVISION,
65
    )
0.200.1648 by Jelmer Vernooij
Fix compatibility with newer versions of breezy.
66
from ...bzr.inventorytree import InventoryRevisionTree
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
67
from ...testament import (
0.200.1023 by Jelmer Vernooij
Set and verify testament.
68
    StrictTestament3,
69
    )
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
70
from ...tsort import (
0.200.292 by Jelmer Vernooij
Fix formatting.
71
    topo_sort,
72
    )
0.200.1648 by Jelmer Vernooij
Fix compatibility with newer versions of breezy.
73
from ...bzr.versionedfile import (
0.200.811 by Jelmer Vernooij
Use ChunkedContentFactory when possible.
74
    ChunkedContentFactory,
0.200.417 by Jelmer Vernooij
use insert_record_stream rather than add_lines.
75
    )
0.200.135 by Jelmer Vernooij
Add stub for fetching data.
76
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
77
from .mapping import (
0.200.345 by Jelmer Vernooij
Keep track of file modes to use.
78
    DEFAULT_FILE_MODE,
0.200.521 by Jelmer Vernooij
Abstract out kind mapping a bit, initial work on support tree-references.
79
    mode_is_executable,
0.200.820 by Jelmer Vernooij
Avoid relying on InventoryDirectory.children.
80
    mode_kind,
0.200.490 by Jelmer Vernooij
Warn about unusual modes and escaped XML-invalid characters.
81
    warn_unusual_mode,
0.231.2 by Jelmer Vernooij
Add -Dverify flag (not fully implemented yet).
82
    )
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
83
from .object_store import (
0.200.456 by Jelmer Vernooij
Fix git -> git fetching.
84
    BazaarObjectStore,
0.200.852 by Jelmer Vernooij
Cache trees rather than inventories.
85
    LRUTreeCache,
0.200.883 by Jelmer Vernooij
Add function for verifying reconstruction of objects still works.
86
    _tree_to_objects,
0.200.456 by Jelmer Vernooij
Fix git -> git fetching.
87
    )
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
88
from .refs import (
0.200.1487 by Jelmer Vernooij
Use peeling.
89
    is_tag,
0.200.1458 by Jelmer Vernooij
Gather peeled shas rather than unpeeled.
90
    )
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
91
from .remote import (
0.200.426 by Jelmer Vernooij
Fix import of RemoteGitRepository.
92
    RemoteGitRepository,
93
    )
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
94
from .repository import (
0.200.664 by Jelmer Vernooij
Support submodules during fetch.
95
    GitRepository,
0.200.289 by Jelmer Vernooij
Cope with new member variables in RepositoryFormat.
96
    GitRepositoryFormat,
0.200.426 by Jelmer Vernooij
Fix import of RemoteGitRepository.
97
    LocalGitRepository,
0.200.261 by Jelmer Vernooij
More formatting fixes.
98
    )
0.216.4 by Jelmer Vernooij
Add basic pack fetch infrastructure.
99
100
0.200.1636 by Jelmer Vernooij
Some formatting fixes.
101
def import_git_blob(texts, mapping, path, name, (base_hexsha, hexsha),
0.275.3 by Jelmer Vernooij
Avoid inventories in a few more places.
102
        base_bzr_tree, parent_id, revision_id,
103
        parent_bzr_trees, lookup_object, (base_mode, mode), store_updater,
0.200.896 by Jelmer Vernooij
Add separate function for looking up file ids.
104
        lookup_file_id):
0.200.151 by Jelmer Vernooij
Support converting git objects to bzr objects.
105
    """Import a git blob object into a bzr repository.
106
0.200.261 by Jelmer Vernooij
More formatting fixes.
107
    :param texts: VersionedFiles to add to
0.200.151 by Jelmer Vernooij
Support converting git objects to bzr objects.
108
    :param path: Path in the tree
109
    :param blob: A git blob
0.229.1 by Jelmer Vernooij
Start working with inventory deltas.
110
    :return: Inventory delta for this file
0.200.151 by Jelmer Vernooij
Support converting git objects to bzr objects.
111
    """
0.200.1752 by Jelmer Vernooij
Don't traverse nested trees in WorkingTree.smart_add.
112
    if mapping.is_special_file(path):
0.252.28 by Jelmer Vernooij
Don't import control files.
113
        return []
0.200.816 by Jelmer Vernooij
Leave mode handling for blobs to import_git_blob.
114
    if base_hexsha == hexsha and base_mode == mode:
115
        # If nothing has changed since the base revision, we're done
0.200.839 by Jelmer Vernooij
Add convenience object for updating the object store caching layer.
116
        return []
0.200.896 by Jelmer Vernooij
Add separate function for looking up file ids.
117
    file_id = lookup_file_id(path)
0.200.816 by Jelmer Vernooij
Leave mode handling for blobs to import_git_blob.
118
    if stat.S_ISLNK(mode):
0.200.320 by Jelmer Vernooij
Handle lightweight checkouts.
119
        cls = InventoryLink
120
    else:
121
        cls = InventoryFile
0.200.821 by Jelmer Vernooij
Remove last references to ID.children.
122
    ie = cls(file_id, name.decode("utf-8"), parent_id)
0.200.995 by Jelmer Vernooij
Support newer versions of bzr where only some InventoryFile/InventoryLink attributes are writable.
123
    if ie.kind == "file":
124
        ie.executable = mode_is_executable(mode)
0.200.821 by Jelmer Vernooij
Remove last references to ID.children.
125
    if base_hexsha == hexsha and mode_kind(base_mode) == mode_kind(mode):
0.285.1 by Jelmer Vernooij
Swap arguments for tree methods.
126
        base_exec = base_bzr_tree.is_executable(path)
0.200.995 by Jelmer Vernooij
Support newer versions of bzr where only some InventoryFile/InventoryLink attributes are writable.
127
        if ie.kind == "symlink":
0.285.1 by Jelmer Vernooij
Swap arguments for tree methods.
128
            ie.symlink_target = base_bzr_tree.get_symlink_target(path)
0.275.3 by Jelmer Vernooij
Avoid inventories in a few more places.
129
        else:
0.285.1 by Jelmer Vernooij
Swap arguments for tree methods.
130
            ie.text_size = base_bzr_tree.get_file_size(path)
131
            ie.text_sha1 = base_bzr_tree.get_file_sha1(path)
0.275.3 by Jelmer Vernooij
Avoid inventories in a few more places.
132
        if ie.kind == "symlink" or ie.executable == base_exec:
0.285.1 by Jelmer Vernooij
Swap arguments for tree methods.
133
            ie.revision = base_bzr_tree.get_file_revision(path)
0.200.537 by Jelmer Vernooij
Fix handling of not-executable files becoming executable without any other changes.
134
        else:
135
            blob = lookup_object(hexsha)
0.200.304 by Jelmer Vernooij
Try a bit harder to avoid fetching objects we don't need.
136
    else:
137
        blob = lookup_object(hexsha)
0.200.320 by Jelmer Vernooij
Handle lightweight checkouts.
138
        if ie.kind == "symlink":
0.200.551 by Jelmer Vernooij
Properly set InventoryEntry revision when changing symlink targets.
139
            ie.revision = None
0.200.1344 by Jelmer Vernooij
Unicode symlinks should be unicode in inventory entries.
140
            ie.symlink_target = blob.data.decode("utf-8")
0.200.320 by Jelmer Vernooij
Handle lightweight checkouts.
141
        else:
0.200.830 by Jelmer Vernooij
Bump minimum dulwich version.
142
            ie.text_size = sum(imap(len, blob.chunked))
143
            ie.text_sha1 = osutils.sha_strings(blob.chunked)
0.229.3 by Jelmer Vernooij
Use inventory deltas internally so fetch is O(changes) rather than O(tree).
144
    # Check what revision we should store
0.200.283 by Jelmer Vernooij
Avoid storing repeated texts for blobs.
145
    parent_keys = []
0.275.3 by Jelmer Vernooij
Avoid inventories in a few more places.
146
    for ptree in parent_bzr_trees:
0.200.1576 by Jelmer Vernooij
Merge a bunch of fixes from store-roundtrip-info.
147
        try:
0.285.1 by Jelmer Vernooij
Swap arguments for tree methods.
148
            ppath = ptree.id2path(file_id)
0.200.1576 by Jelmer Vernooij
Merge a bunch of fixes from store-roundtrip-info.
149
        except errors.NoSuchId:
0.200.829 by Jelmer Vernooij
Cope with the fact that _type is gone in upstream dulwich.
150
            continue
0.285.1 by Jelmer Vernooij
Swap arguments for tree methods.
151
        pkind = ptree.kind(ppath, file_id)
0.275.3 by Jelmer Vernooij
Avoid inventories in a few more places.
152
        if (pkind == ie.kind and
0.285.1 by Jelmer Vernooij
Swap arguments for tree methods.
153
            ((pkind == "symlink" and ptree.get_symlink_target(ppath, file_id) == ie.symlink_target) or
154
             (pkind == "file" and ptree.get_file_sha1(ppath, file_id) == ie.text_sha1 and
155
                ptree.is_executable(ppath, file_id) == ie.executable))):
0.229.3 by Jelmer Vernooij
Use inventory deltas internally so fetch is O(changes) rather than O(tree).
156
            # found a revision in one of the parents to use
0.285.1 by Jelmer Vernooij
Swap arguments for tree methods.
157
            ie.revision = ptree.get_file_revision(ppath, file_id)
0.229.3 by Jelmer Vernooij
Use inventory deltas internally so fetch is O(changes) rather than O(tree).
158
            break
0.285.1 by Jelmer Vernooij
Swap arguments for tree methods.
159
        parent_key = (file_id, ptree.get_file_revision(ppath, file_id))
0.200.904 by Jelmer Vernooij
Fix inconsistent parents.
160
        if not parent_key in parent_keys:
161
            parent_keys.append(parent_key)
0.229.3 by Jelmer Vernooij
Use inventory deltas internally so fetch is O(changes) rather than O(tree).
162
    if ie.revision is None:
163
        # Need to store a new revision
164
        ie.revision = revision_id
0.361.1 by Jelmer Vernooij
Don't use assert.
165
        if ie.revision is None:
166
            raise ValueError("no file revision set")
0.200.698 by Jelmer Vernooij
Merge fixes for SHA1s of symlinks.
167
        if ie.kind == 'symlink':
0.200.811 by Jelmer Vernooij
Use ChunkedContentFactory when possible.
168
            chunks = []
0.200.1292 by Jelmer Vernooij
Fix repeeling objects when determining what to send.
169
        else:
0.200.830 by Jelmer Vernooij
Bump minimum dulwich version.
170
            chunks = blob.chunked
0.252.25 by Jelmer Vernooij
Reformatting.
171
        texts.insert_record_stream([
172
            ChunkedContentFactory((file_id, ie.revision),
173
                tuple(parent_keys), ie.text_sha1, chunks)])
0.200.572 by Jelmer Vernooij
Avoid some extra path lookups.
174
    invdelta = []
0.200.820 by Jelmer Vernooij
Avoid relying on InventoryDirectory.children.
175
    if base_hexsha is not None:
0.200.984 by Jelmer Vernooij
Handle non-ascii characters in filenames.
176
        old_path = path.decode("utf-8") # Renames are not supported yet
0.200.820 by Jelmer Vernooij
Avoid relying on InventoryDirectory.children.
177
        if stat.S_ISDIR(base_mode):
0.275.3 by Jelmer Vernooij
Avoid inventories in a few more places.
178
            invdelta.extend(remove_disappeared_children(base_bzr_tree, old_path,
0.200.826 by Jelmer Vernooij
Fix some long lines.
179
                lookup_object(base_hexsha), [], lookup_object))
0.229.3 by Jelmer Vernooij
Use inventory deltas internally so fetch is O(changes) rather than O(tree).
180
    else:
181
        old_path = None
0.200.984 by Jelmer Vernooij
Handle non-ascii characters in filenames.
182
    new_path = path.decode("utf-8")
183
    invdelta.append((old_path, new_path, file_id, ie))
0.200.839 by Jelmer Vernooij
Add convenience object for updating the object store caching layer.
184
    if base_hexsha != hexsha:
0.275.2 by Jelmer Vernooij
Pass tuples around for cache entries, rather than inventory entries.
185
        store_updater.add_object(blob, (ie.file_id, ie.revision), path)
0.200.839 by Jelmer Vernooij
Add convenience object for updating the object store caching layer.
186
    return invdelta
0.200.261 by Jelmer Vernooij
More formatting fixes.
187
188
0.200.664 by Jelmer Vernooij
Support submodules during fetch.
189
class SubmodulesRequireSubtrees(BzrError):
0.200.1596 by Jelmer Vernooij
Don't mention development-subtree when submodules are encountered.
190
    _fmt = ("The repository you are fetching from contains submodules, "
191
            "which are not yet supported.")
0.239.5 by Jelmer Vernooij
Print user-understandable error message when encountering submodules.
192
    internal = False
193
194
0.200.821 by Jelmer Vernooij
Remove last references to ID.children.
195
def import_git_submodule(texts, mapping, path, name, (base_hexsha, hexsha),
0.275.3 by Jelmer Vernooij
Avoid inventories in a few more places.
196
    base_bzr_tree, parent_id, revision_id, parent_bzr_trees, lookup_object,
0.200.896 by Jelmer Vernooij
Add separate function for looking up file ids.
197
    (base_mode, mode), store_updater, lookup_file_id):
0.200.1309 by Jelmer Vernooij
Break some more long lines.
198
    """Import a git submodule."""
0.200.817 by Jelmer Vernooij
Deal with all modes locally.
199
    if base_hexsha == hexsha and base_mode == mode:
0.200.839 by Jelmer Vernooij
Add convenience object for updating the object store caching layer.
200
        return [], {}
0.200.896 by Jelmer Vernooij
Add separate function for looking up file ids.
201
    file_id = lookup_file_id(path)
0.200.1408 by Jelmer Vernooij
Remove old ie children when converting directory into tree reference.
202
    invdelta = []
0.200.821 by Jelmer Vernooij
Remove last references to ID.children.
203
    ie = TreeReference(file_id, name.decode("utf-8"), parent_id)
0.200.664 by Jelmer Vernooij
Support submodules during fetch.
204
    ie.revision = revision_id
0.200.1408 by Jelmer Vernooij
Remove old ie children when converting directory into tree reference.
205
    if base_hexsha is not None:
206
        old_path = path.decode("utf-8") # Renames are not supported yet
207
        if stat.S_ISDIR(base_mode):
0.275.3 by Jelmer Vernooij
Avoid inventories in a few more places.
208
            invdelta.extend(remove_disappeared_children(base_bzr_tree, old_path,
0.200.1408 by Jelmer Vernooij
Remove old ie children when converting directory into tree reference.
209
                lookup_object(base_hexsha), [], lookup_object))
0.200.664 by Jelmer Vernooij
Support submodules during fetch.
210
    else:
0.200.1408 by Jelmer Vernooij
Remove old ie children when converting directory into tree reference.
211
        old_path = None
0.200.664 by Jelmer Vernooij
Support submodules during fetch.
212
    ie.reference_revision = mapping.revision_id_foreign_to_bzr(hexsha)
0.252.25 by Jelmer Vernooij
Reformatting.
213
    texts.insert_record_stream([
214
        ChunkedContentFactory((file_id, ie.revision), (), None, [])])
0.200.1408 by Jelmer Vernooij
Remove old ie children when converting directory into tree reference.
215
    invdelta.append((old_path, path, file_id, ie))
0.200.839 by Jelmer Vernooij
Add convenience object for updating the object store caching layer.
216
    return invdelta, {}
0.200.540 by Jelmer Vernooij
Handle submodules explicitly.
217
218
0.275.3 by Jelmer Vernooij
Avoid inventories in a few more places.
219
def remove_disappeared_children(base_bzr_tree, path, base_tree, existing_children,
0.200.820 by Jelmer Vernooij
Avoid relying on InventoryDirectory.children.
220
        lookup_object):
0.200.930 by Jelmer Vernooij
Add assert demonstrating 571055 and triggering it for all target formats.
221
    """Generate an inventory delta for removed children.
222
0.200.1636 by Jelmer Vernooij
Some formatting fixes.
223
    :param base_bzr_tree: Base bzr tree against which to generate the
0.200.930 by Jelmer Vernooij
Add assert demonstrating 571055 and triggering it for all target formats.
224
        inventory delta.
0.200.984 by Jelmer Vernooij
Handle non-ascii characters in filenames.
225
    :param path: Path to process (unicode)
0.200.930 by Jelmer Vernooij
Add assert demonstrating 571055 and triggering it for all target formats.
226
    :param base_tree: Git Tree base object
227
    :param existing_children: Children that still exist
228
    :param lookup_object: Lookup a git object by its SHA1
229
    :return: Inventory delta, as list
230
    """
0.361.1 by Jelmer Vernooij
Don't use assert.
231
    if type(path) is not unicode:
232
        raise TypeError(path)
0.200.552 by Jelmer Vernooij
Cope with directories becoming symlinks.
233
    ret = []
0.200.820 by Jelmer Vernooij
Avoid relying on InventoryDirectory.children.
234
    for name, mode, hexsha in base_tree.iteritems():
235
        if name in existing_children:
236
            continue
237
        c_path = posixpath.join(path, name.decode("utf-8"))
0.275.3 by Jelmer Vernooij
Avoid inventories in a few more places.
238
        file_id = base_bzr_tree.path2id(c_path)
0.361.1 by Jelmer Vernooij
Don't use assert.
239
        if file_id is None:
240
            raise TypeError(file_id)
0.200.930 by Jelmer Vernooij
Add assert demonstrating 571055 and triggering it for all target formats.
241
        ret.append((c_path, None, file_id, None))
0.200.820 by Jelmer Vernooij
Avoid relying on InventoryDirectory.children.
242
        if stat.S_ISDIR(mode):
243
            ret.extend(remove_disappeared_children(
0.275.3 by Jelmer Vernooij
Avoid inventories in a few more places.
244
                base_bzr_tree, c_path, lookup_object(hexsha), [], lookup_object))
0.200.552 by Jelmer Vernooij
Cope with directories becoming symlinks.
245
    return ret
246
247
0.200.821 by Jelmer Vernooij
Remove last references to ID.children.
248
def import_git_tree(texts, mapping, path, name, (base_hexsha, hexsha),
0.275.3 by Jelmer Vernooij
Avoid inventories in a few more places.
249
        base_bzr_tree, parent_id, revision_id, parent_bzr_trees,
0.200.896 by Jelmer Vernooij
Add separate function for looking up file ids.
250
        lookup_object, (base_mode, mode), store_updater,
251
        lookup_file_id, allow_submodules=False):
0.200.151 by Jelmer Vernooij
Support converting git objects to bzr objects.
252
    """Import a git tree object into a bzr repository.
253
0.200.261 by Jelmer Vernooij
More formatting fixes.
254
    :param texts: VersionedFiles object to add to
0.200.984 by Jelmer Vernooij
Handle non-ascii characters in filenames.
255
    :param path: Path in the tree (str)
256
    :param name: Name of the tree (str)
0.200.151 by Jelmer Vernooij
Support converting git objects to bzr objects.
257
    :param tree: A git tree object
0.275.3 by Jelmer Vernooij
Avoid inventories in a few more places.
258
    :param base_bzr_tree: Base inventory against which to return inventory delta
0.229.1 by Jelmer Vernooij
Start working with inventory deltas.
259
    :return: Inventory delta for this subtree
0.200.151 by Jelmer Vernooij
Support converting git objects to bzr objects.
260
    """
0.361.1 by Jelmer Vernooij
Don't use assert.
261
    if type(path) is not str:
262
        raise TypeError(path)
263
    if type(name) is not str:
264
        raise TypeError(name)
0.200.817 by Jelmer Vernooij
Deal with all modes locally.
265
    if base_hexsha == hexsha and base_mode == mode:
266
        # If nothing has changed since the base revision, we're done
0.200.839 by Jelmer Vernooij
Add convenience object for updating the object store caching layer.
267
        return [], {}
0.200.344 by Jelmer Vernooij
Clarify names, use convenience function
268
    invdelta = []
0.200.896 by Jelmer Vernooij
Add separate function for looking up file ids.
269
    file_id = lookup_file_id(path)
0.200.297 by Jelmer Vernooij
Cope with non-ascii characters in filenames (needs a test..).
270
    # We just have to hope this is indeed utf-8:
0.200.821 by Jelmer Vernooij
Remove last references to ID.children.
271
    ie = InventoryDirectory(file_id, name.decode("utf-8"), parent_id)
0.200.817 by Jelmer Vernooij
Deal with all modes locally.
272
    tree = lookup_object(hexsha)
273
    if base_hexsha is None:
274
        base_tree = None
0.200.823 by Jelmer Vernooij
Simplify logic in import_git_tree a bit.
275
        old_path = None # Newly appeared here
0.200.817 by Jelmer Vernooij
Deal with all modes locally.
276
    else:
277
        base_tree = lookup_object(base_hexsha)
0.200.984 by Jelmer Vernooij
Handle non-ascii characters in filenames.
278
        old_path = path.decode("utf-8") # Renames aren't supported yet
279
    new_path = path.decode("utf-8")
0.200.823 by Jelmer Vernooij
Simplify logic in import_git_tree a bit.
280
    if base_tree is None or type(base_tree) is not Tree:
281
        ie.revision = revision_id
0.200.984 by Jelmer Vernooij
Handle non-ascii characters in filenames.
282
        invdelta.append((old_path, new_path, ie.file_id, ie))
0.252.24 by Jelmer Vernooij
Support reading fileid map.
283
        texts.insert_record_stream([
284
            ChunkedContentFactory((ie.file_id, ie.revision), (), None, [])])
0.229.3 by Jelmer Vernooij
Use inventory deltas internally so fetch is O(changes) rather than O(tree).
285
    # Remember for next time
0.200.300 by Jelmer Vernooij
Fix recursive deletion of dirs.
286
    existing_children = set()
0.200.345 by Jelmer Vernooij
Keep track of file modes to use.
287
    child_modes = {}
0.200.1147 by Jelmer Vernooij
Use Tree.items() rather than Tree.entries().
288
    for name, child_mode, child_hexsha in tree.iteritems():
0.200.820 by Jelmer Vernooij
Avoid relying on InventoryDirectory.children.
289
        existing_children.add(name)
0.200.819 by Jelmer Vernooij
Avoid decoding basename twice.
290
        child_path = posixpath.join(path, name)
0.200.814 by Jelmer Vernooij
Avoid the use of InventoryDirectory.children. This speeds up
291
        if type(base_tree) is Tree:
292
            try:
293
                child_base_mode, child_base_hexsha = base_tree[name]
294
            except KeyError:
295
                child_base_hexsha = None
296
                child_base_mode = 0
297
        else:
298
            child_base_hexsha = None
299
            child_base_mode = 0
0.200.816 by Jelmer Vernooij
Leave mode handling for blobs to import_git_blob.
300
        if stat.S_ISDIR(child_mode):
0.252.25 by Jelmer Vernooij
Reformatting.
301
            subinvdelta, grandchildmodes = import_git_tree(texts, mapping,
0.275.3 by Jelmer Vernooij
Avoid inventories in a few more places.
302
                child_path, name, (child_base_hexsha, child_hexsha),
303
                base_bzr_tree, file_id, revision_id, parent_bzr_trees,
304
                lookup_object, (child_base_mode, child_mode), store_updater,
305
                lookup_file_id, allow_submodules=allow_submodules)
0.200.816 by Jelmer Vernooij
Leave mode handling for blobs to import_git_blob.
306
        elif S_ISGITLINK(child_mode): # submodule
0.200.666 by Jelmer Vernooij
Refuse to add tree references to non-subtree formats.
307
            if not allow_submodules:
308
                raise SubmodulesRequireSubtrees()
0.252.25 by Jelmer Vernooij
Reformatting.
309
            subinvdelta, grandchildmodes = import_git_submodule(texts, mapping,
0.275.3 by Jelmer Vernooij
Avoid inventories in a few more places.
310
                child_path, name, (child_base_hexsha, child_hexsha),
311
                base_bzr_tree, file_id, revision_id, parent_bzr_trees,
312
                lookup_object, (child_base_mode, child_mode), store_updater,
313
                lookup_file_id)
0.200.352 by Jelmer Vernooij
Simplify mode handling.
314
        else:
0.200.1328 by Jelmer Vernooij
More test fixes.
315
            if not mapping.is_special_file(name):
316
                subinvdelta = import_git_blob(texts, mapping, child_path, name,
0.275.3 by Jelmer Vernooij
Avoid inventories in a few more places.
317
                    (child_base_hexsha, child_hexsha), base_bzr_tree, file_id,
318
                    revision_id, parent_bzr_trees, lookup_object,
0.200.1328 by Jelmer Vernooij
More test fixes.
319
                    (child_base_mode, child_mode), store_updater, lookup_file_id)
320
            else:
321
                subinvdelta = []
0.200.757 by Jelmer Vernooij
Use inventory deltas.
322
            grandchildmodes = {}
323
        child_modes.update(grandchildmodes)
324
        invdelta.extend(subinvdelta)
0.200.816 by Jelmer Vernooij
Leave mode handling for blobs to import_git_blob.
325
        if child_mode not in (stat.S_IFDIR, DEFAULT_FILE_MODE,
0.200.1407 by Jelmer Vernooij
Don't consider submodule modes unusual.
326
                        stat.S_IFLNK, DEFAULT_FILE_MODE|0111,
327
                        S_IFGITLINK):
0.200.879 by Jelmer Vernooij
Fix unusual modes.
328
            child_modes[child_path] = child_mode
0.229.3 by Jelmer Vernooij
Use inventory deltas internally so fetch is O(changes) rather than O(tree).
329
    # Remove any children that have disappeared
0.200.817 by Jelmer Vernooij
Deal with all modes locally.
330
    if base_tree is not None and type(base_tree) is Tree:
0.275.3 by Jelmer Vernooij
Avoid inventories in a few more places.
331
        invdelta.extend(remove_disappeared_children(base_bzr_tree, old_path,
0.200.820 by Jelmer Vernooij
Avoid relying on InventoryDirectory.children.
332
            base_tree, existing_children, lookup_object))
0.275.2 by Jelmer Vernooij
Pass tuples around for cache entries, rather than inventory entries.
333
    store_updater.add_object(tree, (file_id, ), path)
0.200.839 by Jelmer Vernooij
Add convenience object for updating the object store caching layer.
334
    return invdelta, child_modes
0.200.151 by Jelmer Vernooij
Support converting git objects to bzr objects.
335
336
0.200.883 by Jelmer Vernooij
Add function for verifying reconstruction of objects still works.
337
def verify_commit_reconstruction(target_git_object_retriever, lookup_object,
0.200.1047 by Jelmer Vernooij
Fix -Dverify.
338
    o, rev, ret_tree, parent_trees, mapping, unusual_modes, verifiers):
0.200.883 by Jelmer Vernooij
Add function for verifying reconstruction of objects still works.
339
    new_unusual_modes = mapping.export_unusual_file_modes(rev)
340
    if new_unusual_modes != unusual_modes:
341
        raise AssertionError("unusual modes don't match: %r != %r" % (
342
            unusual_modes, new_unusual_modes))
343
    # Verify that we can reconstruct the commit properly
0.200.1047 by Jelmer Vernooij
Fix -Dverify.
344
    rec_o = target_git_object_retriever._reconstruct_commit(rev, o.tree, True,
345
        verifiers)
0.200.883 by Jelmer Vernooij
Add function for verifying reconstruction of objects still works.
346
    if rec_o != o:
347
        raise AssertionError("Reconstructed commit differs: %r != %r" % (
348
            rec_o, o))
349
    diff = []
350
    new_objs = {}
351
    for path, obj, ie in _tree_to_objects(ret_tree, parent_trees,
0.200.1309 by Jelmer Vernooij
Break some more long lines.
352
        target_git_object_retriever._cache.idmap, unusual_modes,
353
        mapping.BZR_DUMMY_FILE):
0.200.883 by Jelmer Vernooij
Add function for verifying reconstruction of objects still works.
354
        old_obj_id = tree_lookup_path(lookup_object, o.tree, path)[1]
355
        new_objs[path] = obj
356
        if obj.id != old_obj_id:
357
            diff.append((path, lookup_object(old_obj_id), obj))
358
    for (path, old_obj, new_obj) in diff:
359
        while (old_obj.type_name == "tree" and
360
               new_obj.type_name == "tree" and
361
               sorted(old_obj) == sorted(new_obj)):
362
            for name in old_obj:
363
                if old_obj[name][0] != new_obj[name][0]:
0.252.25 by Jelmer Vernooij
Reformatting.
364
                    raise AssertionError("Modes for %s differ: %o != %o" %
365
                        (path, old_obj[name][0], new_obj[name][0]))
0.200.883 by Jelmer Vernooij
Add function for verifying reconstruction of objects still works.
366
                if old_obj[name][1] != new_obj[name][1]:
367
                    # Found a differing child, delve deeper
368
                    path = posixpath.join(path, name)
369
                    old_obj = lookup_object(old_obj[name][1])
370
                    new_obj = new_objs[path]
371
                    break
372
        raise AssertionError("objects differ for %s: %r != %r" % (path,
373
            old_obj, new_obj))
374
375
0.200.1409 by Jelmer Vernooij
Support fetching into repositories that are stacked.
376
def ensure_inventories_in_repo(repo, trees):
377
    real_inv_vf = repo.inventories.without_fallbacks()
378
    for t in trees:
379
        revid = t.get_revision_id()
380
        if not real_inv_vf.get_parent_map([(revid, )]):
381
            repo.add_inventory(revid, t.inventory, t.get_parent_ids())
382
383
0.200.679 by Jelmer Vernooij
Moving commit import functionality to a separate function.
384
def import_git_commit(repo, mapping, head, lookup_object,
0.200.852 by Jelmer Vernooij
Cache trees rather than inventories.
385
                      target_git_object_retriever, trees_cache):
0.200.679 by Jelmer Vernooij
Moving commit import functionality to a separate function.
386
    o = lookup_object(head)
0.261.5 by Jelmer Vernooij
Fix looking up of parents during fetch.
387
    # Note that this uses mapping.revision_id_foreign_to_bzr. If the parents
388
    # were bzr roundtripped revisions they would be specified in the
389
    # roundtrip data.
0.261.4 by Jelmer Vernooij
Fix tests.
390
    rev, roundtrip_revid, verifiers = mapping.import_commit(
0.261.5 by Jelmer Vernooij
Fix looking up of parents during fetch.
391
        o, mapping.revision_id_foreign_to_bzr)
0.200.1329 by Jelmer Vernooij
Fix more tests.
392
    if roundtrip_revid is not None:
393
        original_revid = rev.revision_id
394
        rev.revision_id = roundtrip_revid
0.200.679 by Jelmer Vernooij
Moving commit import functionality to a separate function.
395
    # We have to do this here, since we have to walk the tree and
396
    # we need to make sure to import the blobs / trees with the right
397
    # path; this may involve adding them more than once.
0.200.852 by Jelmer Vernooij
Cache trees rather than inventories.
398
    parent_trees = trees_cache.revision_trees(rev.parent_ids)
0.200.1409 by Jelmer Vernooij
Support fetching into repositories that are stacked.
399
    ensure_inventories_in_repo(repo, parent_trees)
0.200.852 by Jelmer Vernooij
Cache trees rather than inventories.
400
    if parent_trees == []:
0.275.3 by Jelmer Vernooij
Avoid inventories in a few more places.
401
        base_bzr_tree = trees_cache.revision_tree(NULL_REVISION)
0.200.814 by Jelmer Vernooij
Avoid the use of InventoryDirectory.children. This speeds up
402
        base_tree = None
0.200.817 by Jelmer Vernooij
Deal with all modes locally.
403
        base_mode = None
0.200.679 by Jelmer Vernooij
Moving commit import functionality to a separate function.
404
    else:
0.275.3 by Jelmer Vernooij
Avoid inventories in a few more places.
405
        base_bzr_tree = parent_trees[0]
0.200.814 by Jelmer Vernooij
Avoid the use of InventoryDirectory.children. This speeds up
406
        base_tree = lookup_object(o.parents[0]).tree
0.200.817 by Jelmer Vernooij
Deal with all modes locally.
407
        base_mode = stat.S_IFDIR
0.200.839 by Jelmer Vernooij
Add convenience object for updating the object store caching layer.
408
    store_updater = target_git_object_retriever._get_updater(rev)
0.200.1324 by Jelmer Vernooij
More work on roundtripping support.
409
    tree_supplement = mapping.get_fileid_map(lookup_object, o.tree)
0.200.839 by Jelmer Vernooij
Add convenience object for updating the object store caching layer.
410
    inv_delta, unusual_modes = import_git_tree(repo.texts,
0.275.3 by Jelmer Vernooij
Avoid inventories in a few more places.
411
            mapping, "", "", (base_tree, o.tree), base_bzr_tree,
412
            None, rev.revision_id, parent_trees,
0.200.852 by Jelmer Vernooij
Cache trees rather than inventories.
413
            lookup_object, (base_mode, stat.S_IFDIR), store_updater,
0.200.1324 by Jelmer Vernooij
More work on roundtripping support.
414
            tree_supplement.lookup_file_id,
0.200.1309 by Jelmer Vernooij
Break some more long lines.
415
            allow_submodules=getattr(repo._format, "supports_tree_reference",
416
                False))
0.200.679 by Jelmer Vernooij
Moving commit import functionality to a separate function.
417
    if unusual_modes != {}:
418
        for path, mode in unusual_modes.iteritems():
419
            warn_unusual_mode(rev.foreign_revid, path, mode)
420
        mapping.import_unusual_file_modes(rev, unusual_modes)
421
    try:
422
        basis_id = rev.parent_ids[0]
423
    except IndexError:
424
        basis_id = NULL_REVISION
0.275.3 by Jelmer Vernooij
Avoid inventories in a few more places.
425
        base_bzr_inventory = None
426
    else:
427
        try:
428
            base_bzr_inventory = base_bzr_tree.root_inventory
429
        except AttributeError: # bzr < 2.6
430
            base_bzr_inventory = base_bzr_tree.inventory
0.200.679 by Jelmer Vernooij
Moving commit import functionality to a separate function.
431
    rev.inventory_sha1, inv = repo.add_inventory_by_delta(basis_id,
0.275.3 by Jelmer Vernooij
Avoid inventories in a few more places.
432
              inv_delta, rev.revision_id, rev.parent_ids,
433
              base_bzr_inventory)
0.200.1195 by Jelmer Vernooij
Cope with new StrictTestament3 arguments.
434
    ret_tree = InventoryRevisionTree(repo, inv, rev.revision_id)
0.200.1329 by Jelmer Vernooij
Fix more tests.
435
    # Check verifiers
436
    if verifiers and roundtrip_revid is not None:
0.200.1559 by Jelmer Vernooij
Fix compatibility with bzr 2.5.
437
        testament = StrictTestament3(rev, ret_tree)
0.200.1329 by Jelmer Vernooij
Fix more tests.
438
        calculated_verifiers = { "testament3-sha1": testament.as_sha1() }
439
        if calculated_verifiers != verifiers:
440
            trace.mutter("Testament SHA1 %r for %r did not match %r.",
441
                         calculated_verifiers["testament3-sha1"],
442
                         rev.revision_id, verifiers["testament3-sha1"])
443
            rev.revision_id = original_revid
444
            rev.inventory_sha1, inv = repo.add_inventory_by_delta(basis_id,
0.275.3 by Jelmer Vernooij
Avoid inventories in a few more places.
445
              inv_delta, rev.revision_id, rev.parent_ids, base_bzr_tree)
0.200.1329 by Jelmer Vernooij
Fix more tests.
446
            ret_tree = InventoryRevisionTree(repo, inv, rev.revision_id)
0.200.1179 by Jelmer Vernooij
Avoid using verifiers for natively imported revisions, save a lot of time.
447
    else:
448
        calculated_verifiers = {}
0.200.1029 by Jelmer Vernooij
Use dictionary with verifiers rather than requiring testament3-sha1 everywhere.
449
    store_updater.add_object(o, calculated_verifiers, None)
450
    store_updater.finish()
0.200.883 by Jelmer Vernooij
Add function for verifying reconstruction of objects still works.
451
    trees_cache.add(ret_tree)
0.200.679 by Jelmer Vernooij
Moving commit import functionality to a separate function.
452
    repo.add_revision(rev.revision_id, rev)
453
    if "verify" in debug.debug_flags:
0.200.1636 by Jelmer Vernooij
Some formatting fixes.
454
        verify_commit_reconstruction(target_git_object_retriever,
0.200.883 by Jelmer Vernooij
Add function for verifying reconstruction of objects still works.
455
            lookup_object, o, rev, ret_tree, parent_trees, mapping,
0.200.1047 by Jelmer Vernooij
Fix -Dverify.
456
            unusual_modes, verifiers)
0.200.679 by Jelmer Vernooij
Moving commit import functionality to a separate function.
457
458
0.248.5 by Jelmer Vernooij
Reformatting, fix dpush.
459
def import_git_objects(repo, mapping, object_iter,
460
    target_git_object_retriever, heads, pb=None, limit=None):
0.200.151 by Jelmer Vernooij
Support converting git objects to bzr objects.
461
    """Import a set of git objects into a bzr repository.
462
0.200.483 by Jelmer Vernooij
Add NEWS entry about sha map.
463
    :param repo: Target Bazaar repository
0.200.151 by Jelmer Vernooij
Support converting git objects to bzr objects.
464
    :param mapping: Mapping to use
465
    :param object_iter: Iterator over Git objects.
0.248.5 by Jelmer Vernooij
Reformatting, fix dpush.
466
    :return: Tuple with pack hints and last imported revision id
0.200.151 by Jelmer Vernooij
Support converting git objects to bzr objects.
467
    """
0.200.469 by Jelmer Vernooij
Fix fetch when revisions are already present locally, just only mapped.
468
    def lookup_object(sha):
469
        try:
470
            return object_iter[sha]
471
        except KeyError:
472
            return target_git_object_retriever[sha]
0.200.158 by Jelmer Vernooij
fetch works \o/
473
    graph = []
0.200.296 by Jelmer Vernooij
Avoid iterating over all objects just to find the *Commits* to retrieve.
474
    checked = set()
0.200.734 by Jelmer Vernooij
Don't import head revision twice when pulling from Git.
475
    heads = list(set(heads))
0.200.852 by Jelmer Vernooij
Cache trees rather than inventories.
476
    trees_cache = LRUTreeCache(repo)
0.200.151 by Jelmer Vernooij
Support converting git objects to bzr objects.
477
    # Find and convert commit objects
0.200.296 by Jelmer Vernooij
Avoid iterating over all objects just to find the *Commits* to retrieve.
478
    while heads:
479
        if pb is not None:
480
            pb.update("finding revisions to fetch", len(graph), None)
481
        head = heads.pop()
0.200.1350 by Jelmer Vernooij
Implement search_missing_revision_ids.
482
        if head == ZERO_SHA:
483
            continue
0.361.1 by Jelmer Vernooij
Don't use assert.
484
        if type(head) is not str:
485
            raise TypeError(head)
0.200.310 by Jelmer Vernooij
Fix pull from remote branches.
486
        try:
0.248.5 by Jelmer Vernooij
Reformatting, fix dpush.
487
            o = lookup_object(head)
0.200.310 by Jelmer Vernooij
Fix pull from remote branches.
488
        except KeyError:
489
            continue
0.200.151 by Jelmer Vernooij
Support converting git objects to bzr objects.
490
        if isinstance(o, Commit):
0.200.1029 by Jelmer Vernooij
Use dictionary with verifiers rather than requiring testament3-sha1 everywhere.
491
            rev, roundtrip_revid, verifiers = mapping.import_commit(o,
0.261.6 by Jelmer Vernooij
Use mapping.revision_id_foreign_to_bzr to find parents everywhere.
492
                mapping.revision_id_foreign_to_bzr)
0.200.1021 by Jelmer Vernooij
Put testament sha1 in revisions.
493
            if (repo.has_revision(rev.revision_id) or
494
                (roundtrip_revid and repo.has_revision(roundtrip_revid))):
0.200.295 by Jelmer Vernooij
Don't re-import revisions already fetched.
495
                continue
0.200.668 by Jelmer Vernooij
Fix some places where we were way too much memory for repositories with a large number of entries in the inventory and a large number of revisions.
496
            graph.append((o.id, o.parents))
0.200.296 by Jelmer Vernooij
Avoid iterating over all objects just to find the *Commits* to retrieve.
497
            heads.extend([p for p in o.parents if p not in checked])
0.200.303 by Jelmer Vernooij
Cope with tags during fetch.
498
        elif isinstance(o, Tag):
0.200.734 by Jelmer Vernooij
Don't import head revision twice when pulling from Git.
499
            if o.object[1] not in checked:
500
                heads.append(o.object[1])
0.200.296 by Jelmer Vernooij
Avoid iterating over all objects just to find the *Commits* to retrieve.
501
        else:
502
            trace.warning("Unable to import head object %r" % o)
0.200.668 by Jelmer Vernooij
Fix some places where we were way too much memory for repositories with a large number of entries in the inventory and a large number of revisions.
503
        checked.add(o.id)
504
    del checked
0.200.158 by Jelmer Vernooij
fetch works \o/
505
    # Order the revisions
0.200.151 by Jelmer Vernooij
Support converting git objects to bzr objects.
506
    # Create the inventory objects
0.200.821 by Jelmer Vernooij
Remove last references to ID.children.
507
    batch_size = 1000
0.200.680 by Jelmer Vernooij
fetch revisions in batches
508
    revision_ids = topo_sort(graph)
509
    pack_hints = []
0.247.2 by Michael Hudson
this works for my tests, but i'm pretty sure it's wrong in general
510
    if limit is not None:
511
        revision_ids = revision_ids[:limit]
0.247.3 by Michael Hudson
oh, so it wasn't (particularly) wrong, but it was a bit obscure
512
    last_imported = None
0.200.680 by Jelmer Vernooij
fetch revisions in batches
513
    for offset in range(0, len(revision_ids), batch_size):
0.200.1636 by Jelmer Vernooij
Some formatting fixes.
514
        target_git_object_retriever.start_write_group()
0.200.680 by Jelmer Vernooij
fetch revisions in batches
515
        try:
0.254.33 by Jelmer Vernooij
Merge trunk.
516
            repo.start_write_group()
517
            try:
0.200.824 by Jelmer Vernooij
Commit cache data in batches as well.
518
                for i, head in enumerate(
519
                    revision_ids[offset:offset+batch_size]):
0.254.33 by Jelmer Vernooij
Merge trunk.
520
                    if pb is not None:
0.200.824 by Jelmer Vernooij
Commit cache data in batches as well.
521
                        pb.update("fetching revisions", offset+i,
522
                                  len(revision_ids))
0.254.33 by Jelmer Vernooij
Merge trunk.
523
                    import_git_commit(repo, mapping, head, lookup_object,
0.252.25 by Jelmer Vernooij
Reformatting.
524
                        target_git_object_retriever, trees_cache)
0.254.33 by Jelmer Vernooij
Merge trunk.
525
                    last_imported = head
526
            except:
527
                repo.abort_write_group()
528
                raise
529
            else:
530
                hint = repo.commit_write_group()
531
                if hint is not None:
532
                    pack_hints.extend(hint)
0.200.680 by Jelmer Vernooij
fetch revisions in batches
533
        except:
0.254.33 by Jelmer Vernooij
Merge trunk.
534
            target_git_object_retriever.abort_write_group()
0.200.680 by Jelmer Vernooij
fetch revisions in batches
535
            raise
536
        else:
0.254.33 by Jelmer Vernooij
Merge trunk.
537
            target_git_object_retriever.commit_write_group()
0.247.2 by Michael Hudson
this works for my tests, but i'm pretty sure it's wrong in general
538
    return pack_hints, last_imported
0.200.141 by Jelmer Vernooij
Separate out local and remote fetching.
539
540
0.200.1350 by Jelmer Vernooij
Implement search_missing_revision_ids.
541
class InterFromGitRepository(InterRepository):
0.200.135 by Jelmer Vernooij
Add stub for fetching data.
542
0.200.289 by Jelmer Vernooij
Cope with new member variables in RepositoryFormat.
543
    _matching_repo_format = GitRepositoryFormat()
0.200.143 by Jelmer Vernooij
Reoncile InterGitRepository objects.
544
0.200.1154 by Jelmer Vernooij
Share more code in InterGitRepository.
545
    def _target_has_shas(self, shas):
546
        raise NotImplementedError(self._target_has_shas)
547
548
    def get_determine_wants_heads(self, wants, include_tags=False):
0.382.1 by Jelmer Vernooij
Various fixes for annotated tags and symrefs.
549
        wants = set(wants)
550
        def determine_wants(refs):
551
            potential = set(wants)
552
            if include_tags:
553
                for k, unpeeled in refs.iteritems():
554
                    if k.endswith("^{}"):
555
                        continue
556
                    if not is_tag(k):
557
                        continue
558
                    if unpeeled == ZERO_SHA:
559
                        continue
560
                    potential.add(unpeeled)
561
            return list(potential - self._target_has_shas(potential))
562
        return determine_wants
0.200.1154 by Jelmer Vernooij
Share more code in InterGitRepository.
563
564
    def determine_wants_all(self, refs):
0.200.1490 by Jelmer Vernooij
Fix target_has_shas.
565
        raise NotImplementedError(self.determine_wants_all)
0.200.1154 by Jelmer Vernooij
Share more code in InterGitRepository.
566
0.200.143 by Jelmer Vernooij
Reoncile InterGitRepository objects.
567
    @staticmethod
568
    def _get_repo_format_to_test():
569
        return None
570
0.200.1492 by Jelmer Vernooij
Fix test
571
    def copy_content(self, revision_id=None):
0.200.135 by Jelmer Vernooij
Add stub for fetching data.
572
        """See InterRepository.copy_content."""
0.200.1492 by Jelmer Vernooij
Fix test
573
        self.fetch(revision_id, find_ghosts=False)
0.200.135 by Jelmer Vernooij
Add stub for fetching data.
574
0.200.1350 by Jelmer Vernooij
Implement search_missing_revision_ids.
575
    def search_missing_revision_ids(self,
576
            find_ghosts=True, revision_ids=None, if_present_ids=None,
577
            limit=None):
0.299.1 by Jelmer Vernooij
Raise FetchLimitUnsupported.
578
        if limit is not None:
579
            raise errors.FetchLimitUnsupported(self)
0.200.1350 by Jelmer Vernooij
Implement search_missing_revision_ids.
580
        git_shas = []
581
        todo = []
582
        if revision_ids:
583
            todo.extend(revision_ids)
584
        if if_present_ids:
585
            todo.extend(revision_ids)
586
        for revid in revision_ids:
587
            if revid == NULL_REVISION:
588
                continue
589
            git_sha, mapping = self.source.lookup_bzr_revision_id(revid)
590
            git_shas.append(git_sha)
591
        walker = Walker(self.source._git.object_store,
0.200.1648 by Jelmer Vernooij
Fix compatibility with newer versions of breezy.
592
            include=git_shas, exclude=[
0.382.1 by Jelmer Vernooij
Various fixes for annotated tags and symrefs.
593
                sha for sha in self.target.controldir.get_refs_container().as_dict().values()
594
                if sha != ZERO_SHA])
0.200.1350 by Jelmer Vernooij
Implement search_missing_revision_ids.
595
        missing_revids = set()
596
        for entry in walker:
597
            missing_revids.add(self.source.lookup_foreign_revision_id(entry.commit.id))
598
        return self.source.revision_ids_to_search_result(missing_revids)
599
600
601
class InterGitNonGitRepository(InterFromGitRepository):
0.200.664 by Jelmer Vernooij
Support submodules during fetch.
602
    """Base InterRepository that copies revisions from a Git into a non-Git
0.200.456 by Jelmer Vernooij
Fix git -> git fetching.
603
    repository."""
604
0.259.4 by Jelmer Vernooij
Put determine_wants methods on InterRepo.
605
    def _target_has_shas(self, shas):
0.200.1456 by Jelmer Vernooij
Fix target_has_shas.
606
        revids = {}
0.200.1403 by Jelmer Vernooij
Cope with tags pointing at tree objects when cloning local git repositories.
607
        for sha in shas:
608
            try:
609
                revid = self.source.lookup_foreign_revision_id(sha)
610
            except NotCommitError:
0.200.1456 by Jelmer Vernooij
Fix target_has_shas.
611
                # Commit is definitely not present
0.200.1403 by Jelmer Vernooij
Cope with tags pointing at tree objects when cloning local git repositories.
612
                continue
613
            else:
0.200.1456 by Jelmer Vernooij
Fix target_has_shas.
614
                revids[revid] = sha
615
        return set([revids[r] for r in self.target.has_revisions(revids)])
0.259.4 by Jelmer Vernooij
Put determine_wants methods on InterRepo.
616
0.200.1489 by Jelmer Vernooij
More fixes to peel handling.
617
    def determine_wants_all(self, refs):
618
        potential = set()
0.377.1 by Jelmer Vernooij
Fix some remote operations and add more tests.
619
        for k, v in refs.iteritems():
0.200.1489 by Jelmer Vernooij
More fixes to peel handling.
620
            # For non-git target repositories, only worry about peeled
0.200.1513 by Jelmer Vernooij
Cope with zero shas.
621
            if v == ZERO_SHA:
622
                continue
0.382.1 by Jelmer Vernooij
Various fixes for annotated tags and symrefs.
623
            potential.add(self.source.controldir.get_peeled(k) or v)
0.200.1489 by Jelmer Vernooij
More fixes to peel handling.
624
        return list(potential - self._target_has_shas(potential))
625
0.200.1490 by Jelmer Vernooij
Fix target_has_shas.
626
    def get_determine_wants_heads(self, wants, include_tags=False):
627
        wants = set(wants)
628
        def determine_wants(refs):
629
            potential = set(wants)
630
            if include_tags:
0.377.1 by Jelmer Vernooij
Fix some remote operations and add more tests.
631
                for k, unpeeled in refs.iteritems():
0.200.1490 by Jelmer Vernooij
Fix target_has_shas.
632
                    if not is_tag(k):
633
                        continue
0.200.1513 by Jelmer Vernooij
Cope with zero shas.
634
                    if unpeeled == ZERO_SHA:
635
                        continue
0.382.1 by Jelmer Vernooij
Various fixes for annotated tags and symrefs.
636
                    potential.add(self.source.controldir.get_peeled(k) or unpeeled)
0.200.1490 by Jelmer Vernooij
Fix target_has_shas.
637
            return list(potential - self._target_has_shas(potential))
638
        return determine_wants
639
0.375.1 by Jelmer Vernooij
Fix remote tests, warn when fetching git->bzr and bzr->git.
640
    def _warn_slow(self):
641
        trace.warning(
642
            'Fetching from Git to Bazaar repository. '
643
            'For better performance, fetch into a Git repository.')
644
0.337.1 by Jelmer Vernooij
Various git remote helper fixes.
645
    def fetch_objects(self, determine_wants, mapping, limit=None, lossy=False):
0.200.1001 by Jelmer Vernooij
Simplify handling of determine wants, add stub for fetch_objects().
646
        """Fetch objects from a remote server.
647
648
        :param determine_wants: determine_wants callback
649
        :param mapping: BzrGitMapping to use
650
        :param limit: Maximum number of commits to import.
0.200.1002 by Jelmer Vernooij
Fix regression in git-import.
651
        :return: Tuple with pack hint, last imported revision id and remote refs
0.200.1001 by Jelmer Vernooij
Simplify handling of determine wants, add stub for fetch_objects().
652
        """
653
        raise NotImplementedError(self.fetch_objects)
654
0.382.1 by Jelmer Vernooij
Various fixes for annotated tags and symrefs.
655
    def get_determine_wants_revids(self, revids, include_tags=False):
656
        wants = set()
657
        for revid in set(revids):
658
            if self.target.has_revision(revid):
659
                continue
660
            git_sha, mapping = self.source.lookup_bzr_revision_id(revid)
661
            wants.add(git_sha)
662
        return self.get_determine_wants_heads(wants, include_tags=include_tags)
663
0.200.1491 by Jelmer Vernooij
Fix progress reporting for git -> git.
664
    def fetch(self, revision_id=None, find_ghosts=False,
0.296.1 by Jelmer Vernooij
Fix tag fetching.
665
              mapping=None, fetch_spec=None, include_tags=False):
0.200.225 by Jelmer Vernooij
Implement custom InterBranch to support fetching from remote git branches.
666
        if mapping is None:
667
            mapping = self.source.get_mapping()
0.226.2 by Jelmer Vernooij
Cope with new fetch_spec argument.
668
        if revision_id is not None:
669
            interesting_heads = [revision_id]
670
        elif fetch_spec is not None:
0.200.1089 by Jelmer Vernooij
Cope with fancy fetch_spec behaviour.
671
            recipe = fetch_spec.get_recipe()
672
            if recipe[0] in ("search", "proxy-search"):
673
                interesting_heads = recipe[1]
674
            else:
0.200.1300 by Jelmer Vernooij
Fix formatting.
675
                raise AssertionError("Unsupported search result type %s" %
676
                        recipe[0])
0.226.2 by Jelmer Vernooij
Cope with new fetch_spec argument.
677
        else:
678
            interesting_heads = None
0.259.4 by Jelmer Vernooij
Put determine_wants methods on InterRepo.
679
680
        if interesting_heads is not None:
0.200.1309 by Jelmer Vernooij
Break some more long lines.
681
            determine_wants = self.get_determine_wants_revids(
0.296.1 by Jelmer Vernooij
Fix tag fetching.
682
                interesting_heads, include_tags=include_tags)
0.259.4 by Jelmer Vernooij
Put determine_wants methods on InterRepo.
683
        else:
684
            determine_wants = self.determine_wants_all
0.200.1079 by Jelmer Vernooij
Avoid looking up revid if not necessary.
685
686
        (pack_hint, _, remote_refs) = self.fetch_objects(determine_wants,
0.200.1491 by Jelmer Vernooij
Fix progress reporting for git -> git.
687
            mapping)
0.200.579 by Jelmer Vernooij
Only pack if it makes the target repo smaller.
688
        if pack_hint is not None and self.target._format.pack_compresses:
0.200.578 by Jelmer Vernooij
Only do optimal packing on bzr >= 1.17.
689
            self.target.pack(hint=pack_hint)
0.200.1002 by Jelmer Vernooij
Fix regression in git-import.
690
        return remote_refs
0.200.225 by Jelmer Vernooij
Implement custom InterBranch to support fetching from remote git branches.
691
0.200.306 by Jelmer Vernooij
Fix tests, split up InterGitNonGitRepository.
692
0.200.563 by Jelmer Vernooij
Attempt to parse progress indication from git status reports.
693
_GIT_PROGRESS_RE = re.compile(r"(.*?): +(\d+)% \((\d+)/(\d+)\)")
694
def report_git_progress(pb, text):
695
    text = text.rstrip("\r\n")
0.375.1 by Jelmer Vernooij
Fix remote tests, warn when fetching git->bzr and bzr->git.
696
    trace.mutter('git: %s', text)
0.200.563 by Jelmer Vernooij
Attempt to parse progress indication from git status reports.
697
    g = _GIT_PROGRESS_RE.match(text)
698
    if g is not None:
699
        (text, pct, current, total) = g.groups()
700
        pb.update(text, int(current), int(total))
701
    else:
702
        pb.update(text, 0, 0)
703
704
0.200.1001 by Jelmer Vernooij
Simplify handling of determine wants, add stub for fetch_objects().
705
class DetermineWantsRecorder(object):
706
707
    def __init__(self, actual):
708
        self.actual = actual
709
        self.wants = []
710
        self.remote_refs = {}
711
712
    def __call__(self, refs):
0.361.1 by Jelmer Vernooij
Don't use assert.
713
        if type(refs) is not dict:
714
            raise TypeError(refs)
0.200.1001 by Jelmer Vernooij
Simplify handling of determine wants, add stub for fetch_objects().
715
        self.remote_refs = refs
716
        self.wants = self.actual(refs)
717
        return self.wants
718
719
0.200.306 by Jelmer Vernooij
Fix tests, split up InterGitNonGitRepository.
720
class InterRemoteGitNonGitRepository(InterGitNonGitRepository):
0.200.664 by Jelmer Vernooij
Support submodules during fetch.
721
    """InterRepository that copies revisions from a remote Git into a non-Git
0.200.306 by Jelmer Vernooij
Fix tests, split up InterGitNonGitRepository.
722
    repository."""
723
0.200.582 by Jelmer Vernooij
Use more efficient algorithm for finding out heads.
724
    def get_target_heads(self):
725
        # FIXME: This should be more efficient
726
        all_revs = self.target.all_revision_ids()
727
        parent_map = self.target.get_parent_map(all_revs)
728
        all_parents = set()
729
        map(all_parents.update, parent_map.itervalues())
730
        return set(all_revs) - all_parents
731
0.337.1 by Jelmer Vernooij
Various git remote helper fixes.
732
    def fetch_objects(self, determine_wants, mapping, limit=None, lossy=False):
0.200.1001 by Jelmer Vernooij
Simplify handling of determine wants, add stub for fetch_objects().
733
        """See `InterGitNonGitRepository`."""
0.375.1 by Jelmer Vernooij
Fix remote tests, warn when fetching git->bzr and bzr->git.
734
        self._warn_slow()
0.200.466 by Jelmer Vernooij
Fix finding of heads for fetch_objects.
735
        store = BazaarObjectStore(self.target, mapping)
0.375.1 by Jelmer Vernooij
Fix remote tests, warn when fetching git->bzr and bzr->git.
736
        with store.lock_write():
0.200.582 by Jelmer Vernooij
Use more efficient algorithm for finding out heads.
737
            heads = self.get_target_heads()
0.281.5 by William Grant
Fix pull with new dulwich by avoiding removed ObjectStore.get_graph_walker.
738
            graph_walker = ObjectStoreGraphWalker(
739
                [store._lookup_revision_sha1(head) for head in heads],
0.200.1631 by William Grant
Fix ObjectStoreGraphWalker invocation.
740
                lambda sha: store[sha].parents)
0.200.1001 by Jelmer Vernooij
Simplify handling of determine wants, add stub for fetch_objects().
741
            wants_recorder = DetermineWantsRecorder(determine_wants)
0.200.664 by Jelmer Vernooij
Support submodules during fetch.
742
0.200.1491 by Jelmer Vernooij
Fix progress reporting for git -> git.
743
            pb = ui.ui_factory.nested_progress_bar()
0.200.306 by Jelmer Vernooij
Fix tests, split up InterGitNonGitRepository.
744
            try:
0.200.1000 by Jelmer Vernooij
Fix fetch between local and remote git branches.
745
                objects_iter = self.source.fetch_objects(
0.200.1001 by Jelmer Vernooij
Simplify handling of determine wants, add stub for fetch_objects().
746
                    wants_recorder, graph_walker, store.get_raw,
0.337.1 by Jelmer Vernooij
Various git remote helper fixes.
747
                    progress=lambda text: report_git_progress(pb, text),)
0.200.1300 by Jelmer Vernooij
Fix formatting.
748
                trace.mutter("Importing %d new revisions",
749
                             len(wants_recorder.wants))
750
                (pack_hint, last_rev) = import_git_objects(self.target,
751
                    mapping, objects_iter, store, wants_recorder.wants, pb,
752
                    limit)
0.200.1002 by Jelmer Vernooij
Fix regression in git-import.
753
                return (pack_hint, last_rev, wants_recorder.remote_refs)
0.200.306 by Jelmer Vernooij
Fix tests, split up InterGitNonGitRepository.
754
            finally:
0.200.1491 by Jelmer Vernooij
Fix progress reporting for git -> git.
755
                pb.finished()
0.200.306 by Jelmer Vernooij
Fix tests, split up InterGitNonGitRepository.
756
757
    @staticmethod
758
    def is_compatible(source, target):
759
        """Be compatible with GitRepository."""
0.200.1222 by Jelmer Vernooij
Better checks in is_compatible methods.
760
        if not isinstance(source, RemoteGitRepository):
761
            return False
762
        if not target.supports_rich_root():
763
            return False
764
        if isinstance(target, GitRepository):
765
            return False
0.200.1270 by Jelmer Vernooij
Cope with older versions of bzr.
766
        if not getattr(target._format, "supports_full_versioned_files", True):
0.200.1222 by Jelmer Vernooij
Better checks in is_compatible methods.
767
            return False
768
        return True
0.200.306 by Jelmer Vernooij
Fix tests, split up InterGitNonGitRepository.
769
770
771
class InterLocalGitNonGitRepository(InterGitNonGitRepository):
0.200.664 by Jelmer Vernooij
Support submodules during fetch.
772
    """InterRepository that copies revisions from a local Git into a non-Git
0.200.306 by Jelmer Vernooij
Fix tests, split up InterGitNonGitRepository.
773
    repository."""
774
0.337.1 by Jelmer Vernooij
Various git remote helper fixes.
775
    def fetch_objects(self, determine_wants, mapping, limit=None, lossy=False):
0.200.1001 by Jelmer Vernooij
Simplify handling of determine wants, add stub for fetch_objects().
776
        """See `InterGitNonGitRepository`."""
0.375.1 by Jelmer Vernooij
Fix remote tests, warn when fetching git->bzr and bzr->git.
777
        self._warn_slow()
0.377.1 by Jelmer Vernooij
Fix some remote operations and add more tests.
778
        remote_refs = self.source.controldir.get_refs_container().as_dict()
0.200.1002 by Jelmer Vernooij
Fix regression in git-import.
779
        wants = determine_wants(remote_refs)
0.200.306 by Jelmer Vernooij
Fix tests, split up InterGitNonGitRepository.
780
        create_pb = None
0.200.1491 by Jelmer Vernooij
Fix progress reporting for git -> git.
781
        pb = ui.ui_factory.nested_progress_bar()
0.200.320 by Jelmer Vernooij
Handle lightweight checkouts.
782
        target_git_object_retriever = BazaarObjectStore(self.target, mapping)
0.200.306 by Jelmer Vernooij
Fix tests, split up InterGitNonGitRepository.
783
        try:
0.296.1 by Jelmer Vernooij
Fix tag fetching.
784
            target_git_object_retriever.lock_write()
785
            try:
0.200.1300 by Jelmer Vernooij
Fix formatting.
786
                (pack_hint, last_rev) = import_git_objects(self.target,
787
                    mapping, self.source._git.object_store,
0.248.5 by Jelmer Vernooij
Reformatting, fix dpush.
788
                    target_git_object_retriever, wants, pb, limit)
0.200.1002 by Jelmer Vernooij
Fix regression in git-import.
789
                return (pack_hint, last_rev, remote_refs)
0.296.1 by Jelmer Vernooij
Fix tag fetching.
790
            finally:
791
                target_git_object_retriever.unlock()
0.200.306 by Jelmer Vernooij
Fix tests, split up InterGitNonGitRepository.
792
        finally:
0.200.1491 by Jelmer Vernooij
Fix progress reporting for git -> git.
793
            pb.finished()
0.200.306 by Jelmer Vernooij
Fix tests, split up InterGitNonGitRepository.
794
795
    @staticmethod
796
    def is_compatible(source, target):
797
        """Be compatible with GitRepository."""
0.200.1222 by Jelmer Vernooij
Better checks in is_compatible methods.
798
        if not isinstance(source, LocalGitRepository):
799
            return False
800
        if not target.supports_rich_root():
801
            return False
802
        if isinstance(target, GitRepository):
803
            return False
0.200.1266 by Jelmer Vernooij
Fix 2.3 support.
804
        if not getattr(target._format, "supports_full_versioned_files", True):
0.200.1222 by Jelmer Vernooij
Better checks in is_compatible methods.
805
            return False
806
        return True
0.200.175 by Jelmer Vernooij
Add optimized handling when fetching from git to git.
807
808
0.200.1350 by Jelmer Vernooij
Implement search_missing_revision_ids.
809
class InterGitGitRepository(InterFromGitRepository):
0.200.291 by Jelmer Vernooij
Print proper error about not supporting push.
810
    """InterRepository that copies between Git repositories."""
0.200.175 by Jelmer Vernooij
Add optimized handling when fetching from git to git.
811
0.200.1433 by Jelmer Vernooij
Fix fetching between git repositories.
812
    def fetch_refs(self, update_refs, lossy=False):
813
        if lossy:
814
            raise errors.LossyPushToSameVCS(self.source, self.target)
0.200.1648 by Jelmer Vernooij
Fix compatibility with newer versions of breezy.
815
        old_refs = self.target.controldir.get_refs_container()
0.200.1433 by Jelmer Vernooij
Fix fetching between git repositories.
816
        ref_changes = {}
817
        def determine_wants(heads):
0.200.1524 by Jelmer Vernooij
Fix inter-git fetching.
818
            old_refs = dict([(k, (v, None)) for (k, v) in heads.as_dict().iteritems()])
0.200.1433 by Jelmer Vernooij
Fix fetching between git repositories.
819
            new_refs = update_refs(old_refs)
820
            ref_changes.update(new_refs)
821
            return [sha1 for (sha1, bzr_revid) in new_refs.itervalues()]
0.337.1 by Jelmer Vernooij
Various git remote helper fixes.
822
        self.fetch_objects(determine_wants, lossy=lossy)
0.200.1433 by Jelmer Vernooij
Fix fetching between git repositories.
823
        for k, (git_sha, bzr_revid) in ref_changes.iteritems():
824
            self.target._git.refs[k] = git_sha
0.200.1648 by Jelmer Vernooij
Fix compatibility with newer versions of breezy.
825
        new_refs = self.target.controldir.get_refs_container()
0.200.1433 by Jelmer Vernooij
Fix fetching between git repositories.
826
        return None, old_refs, new_refs
827
0.337.1 by Jelmer Vernooij
Various git remote helper fixes.
828
    def fetch_objects(self, determine_wants, mapping=None, limit=None, lossy=False):
829
        if lossy:
830
            raise errors.LossyPushToSameVCS(self.source, self.target)
0.299.1 by Jelmer Vernooij
Raise FetchLimitUnsupported.
831
        if limit is not None:
832
            raise errors.FetchLimitUnsupported(self)
0.200.635 by Jelmer Vernooij
Fix fetching between git repositories.
833
        graphwalker = self.target._git.get_graph_walker()
0.200.695 by Jelmer Vernooij
Clean up trailing whitespace.
834
        if (isinstance(self.source, LocalGitRepository) and
835
            isinstance(self.target, LocalGitRepository)):
0.200.1491 by Jelmer Vernooij
Fix progress reporting for git -> git.
836
            pb = ui.ui_factory.nested_progress_bar()
837
            try:
0.382.1 by Jelmer Vernooij
Various fixes for annotated tags and symrefs.
838
                refs = self.source._git.fetch(self.target._git, determine_wants,
0.200.1491 by Jelmer Vernooij
Fix progress reporting for git -> git.
839
                    lambda text: report_git_progress(pb, text))
840
            finally:
841
                pb.finished()
0.200.1002 by Jelmer Vernooij
Fix regression in git-import.
842
            return (None, None, refs)
0.200.695 by Jelmer Vernooij
Clean up trailing whitespace.
843
        elif (isinstance(self.source, LocalGitRepository) and
844
              isinstance(self.target, RemoteGitRepository)):
0.200.635 by Jelmer Vernooij
Fix fetching between git repositories.
845
            raise NotImplementedError
0.200.695 by Jelmer Vernooij
Clean up trailing whitespace.
846
        elif (isinstance(self.source, RemoteGitRepository) and
847
              isinstance(self.target, LocalGitRepository)):
0.200.1491 by Jelmer Vernooij
Fix progress reporting for git -> git.
848
            pb = ui.ui_factory.nested_progress_bar()
0.200.635 by Jelmer Vernooij
Fix fetching between git repositories.
849
            try:
0.200.1758 by Jelmer Vernooij
Fix call to add_pack.
850
                f, commit, abort = self.target._git.object_store.add_pack()
0.200.1491 by Jelmer Vernooij
Fix progress reporting for git -> git.
851
                try:
0.200.1648 by Jelmer Vernooij
Fix compatibility with newer versions of breezy.
852
                    refs = self.source.controldir.fetch_pack(
0.200.1491 by Jelmer Vernooij
Fix progress reporting for git -> git.
853
                        determine_wants, graphwalker, f.write,
854
                        lambda text: report_git_progress(pb, text))
855
                    commit()
856
                    return (None, None, refs)
0.200.1758 by Jelmer Vernooij
Fix call to add_pack.
857
                except BaseException:
858
                    abort()
0.200.1491 by Jelmer Vernooij
Fix progress reporting for git -> git.
859
                    raise
860
            finally:
861
                pb.finished()
0.200.635 by Jelmer Vernooij
Fix fetching between git repositories.
862
        else:
0.200.1433 by Jelmer Vernooij
Fix fetching between git repositories.
863
            raise AssertionError("fetching between %r and %r not supported" %
864
                    (self.source, self.target))
0.200.635 by Jelmer Vernooij
Fix fetching between git repositories.
865
0.200.1154 by Jelmer Vernooij
Share more code in InterGitRepository.
866
    def _target_has_shas(self, shas):
0.200.1490 by Jelmer Vernooij
Fix target_has_shas.
867
        return set([sha for sha in shas if sha in self.target._git.object_store])
0.200.1154 by Jelmer Vernooij
Share more code in InterGitRepository.
868
0.200.1491 by Jelmer Vernooij
Fix progress reporting for git -> git.
869
    def fetch(self, revision_id=None, find_ghosts=False,
0.296.1 by Jelmer Vernooij
Fix tag fetching.
870
              mapping=None, fetch_spec=None, branches=None, limit=None, include_tags=False):
0.200.175 by Jelmer Vernooij
Add optimized handling when fetching from git to git.
871
        if mapping is None:
872
            mapping = self.source.get_mapping()
873
        r = self.target._git
0.226.2 by Jelmer Vernooij
Cope with new fetch_spec argument.
874
        if revision_id is not None:
0.296.1 by Jelmer Vernooij
Fix tag fetching.
875
            args = [revision_id]
0.226.2 by Jelmer Vernooij
Cope with new fetch_spec argument.
876
        elif fetch_spec is not None:
0.200.1089 by Jelmer Vernooij
Cope with fancy fetch_spec behaviour.
877
            recipe = fetch_spec.get_recipe()
878
            if recipe[0] in ("search", "proxy-search"):
879
                heads = recipe[1]
880
            else:
0.200.1309 by Jelmer Vernooij
Break some more long lines.
881
                raise AssertionError(
882
                    "Unsupported search result type %s" % recipe[0])
0.296.1 by Jelmer Vernooij
Fix tag fetching.
883
            args = heads
0.200.456 by Jelmer Vernooij
Fix git -> git fetching.
884
        if branches is not None:
0.296.1 by Jelmer Vernooij
Fix tag fetching.
885
            def determine_wants(refs):
886
                ret = []
0.346.1 by Jelmer Vernooij
Fix tag caching.
887
                for name, value in refs.iteritems():
0.296.1 by Jelmer Vernooij
Fix tag fetching.
888
                    if value == ZERO_SHA:
889
                        continue
890
891
                    if name in branches or (include_tags and is_tag(name)):
892
                        ret.append(value)
893
                return ret
0.200.456 by Jelmer Vernooij
Fix git -> git fetching.
894
        elif fetch_spec is None and revision_id is None:
0.200.1154 by Jelmer Vernooij
Share more code in InterGitRepository.
895
            determine_wants = self.determine_wants_all
0.226.2 by Jelmer Vernooij
Cope with new fetch_spec argument.
896
        else:
0.296.1 by Jelmer Vernooij
Fix tag fetching.
897
            determine_wants = self.get_determine_wants_revids(args, include_tags=include_tags)
0.200.1176 by Jelmer Vernooij
Fix fetch return value for inter git fetching.
898
        wants_recorder = DetermineWantsRecorder(determine_wants)
0.299.1 by Jelmer Vernooij
Raise FetchLimitUnsupported.
899
        self.fetch_objects(wants_recorder, mapping, limit=limit)
0.200.1176 by Jelmer Vernooij
Fix fetch return value for inter git fetching.
900
        return wants_recorder.remote_refs
0.200.175 by Jelmer Vernooij
Add optimized handling when fetching from git to git.
901
902
    @staticmethod
903
    def is_compatible(source, target):
904
        """Be compatible with GitRepository."""
0.200.664 by Jelmer Vernooij
Support submodules during fetch.
905
        return (isinstance(source, GitRepository) and
0.200.175 by Jelmer Vernooij
Add optimized handling when fetching from git to git.
906
                isinstance(target, GitRepository))
0.200.1174 by Jelmer Vernooij
Fix specific revision fetching between git repositories.
907
908
    def get_determine_wants_revids(self, revids, include_tags=False):
909
        wants = set()
910
        for revid in set(revids):
0.200.1388 by Jelmer Vernooij
Don't fetch revision already present.
911
            if self.target.has_revision(revid):
912
                continue
0.200.1174 by Jelmer Vernooij
Fix specific revision fetching between git repositories.
913
            git_sha, mapping = self.source.lookup_bzr_revision_id(revid)
914
            wants.add(git_sha)
0.382.1 by Jelmer Vernooij
Various fixes for annotated tags and symrefs.
915
        return self.get_determine_wants_heads(wants, include_tags=include_tags)
0.200.1489 by Jelmer Vernooij
More fixes to peel handling.
916
917
    def determine_wants_all(self, refs):
0.346.1 by Jelmer Vernooij
Fix tag caching.
918
        potential = set([v for v in refs.values() if not v == ZERO_SHA])
0.200.1489 by Jelmer Vernooij
More fixes to peel handling.
919
        return list(potential - self._target_has_shas(potential))