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