/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.200.1490 by Jelmer Vernooij
Fix target_has_shas.
549
        raise NotImplementedError(self.get_determine_wants_heads)
0.200.1154 by Jelmer Vernooij
Share more code in InterGitRepository.
550
551
    def determine_wants_all(self, refs):
0.200.1490 by Jelmer Vernooij
Fix target_has_shas.
552
        raise NotImplementedError(self.determine_wants_all)
0.200.1154 by Jelmer Vernooij
Share more code in InterGitRepository.
553
0.200.143 by Jelmer Vernooij
Reoncile InterGitRepository objects.
554
    @staticmethod
555
    def _get_repo_format_to_test():
556
        return None
557
0.200.1492 by Jelmer Vernooij
Fix test
558
    def copy_content(self, revision_id=None):
0.200.135 by Jelmer Vernooij
Add stub for fetching data.
559
        """See InterRepository.copy_content."""
0.200.1492 by Jelmer Vernooij
Fix test
560
        self.fetch(revision_id, find_ghosts=False)
0.200.135 by Jelmer Vernooij
Add stub for fetching data.
561
0.200.1350 by Jelmer Vernooij
Implement search_missing_revision_ids.
562
    def search_missing_revision_ids(self,
563
            find_ghosts=True, revision_ids=None, if_present_ids=None,
564
            limit=None):
0.299.1 by Jelmer Vernooij
Raise FetchLimitUnsupported.
565
        if limit is not None:
566
            raise errors.FetchLimitUnsupported(self)
0.200.1350 by Jelmer Vernooij
Implement search_missing_revision_ids.
567
        git_shas = []
568
        todo = []
569
        if revision_ids:
570
            todo.extend(revision_ids)
571
        if if_present_ids:
572
            todo.extend(revision_ids)
573
        for revid in revision_ids:
574
            if revid == NULL_REVISION:
575
                continue
576
            git_sha, mapping = self.source.lookup_bzr_revision_id(revid)
577
            git_shas.append(git_sha)
578
        walker = Walker(self.source._git.object_store,
0.200.1648 by Jelmer Vernooij
Fix compatibility with newer versions of breezy.
579
            include=git_shas, exclude=[
580
                sha for sha in self.target.controldir.get_refs_container().as_dict().values() if sha != ZERO_SHA])
0.200.1350 by Jelmer Vernooij
Implement search_missing_revision_ids.
581
        missing_revids = set()
582
        for entry in walker:
583
            missing_revids.add(self.source.lookup_foreign_revision_id(entry.commit.id))
584
        return self.source.revision_ids_to_search_result(missing_revids)
585
586
587
class InterGitNonGitRepository(InterFromGitRepository):
0.200.664 by Jelmer Vernooij
Support submodules during fetch.
588
    """Base InterRepository that copies revisions from a Git into a non-Git
0.200.456 by Jelmer Vernooij
Fix git -> git fetching.
589
    repository."""
590
0.259.4 by Jelmer Vernooij
Put determine_wants methods on InterRepo.
591
    def _target_has_shas(self, shas):
0.200.1456 by Jelmer Vernooij
Fix target_has_shas.
592
        revids = {}
0.200.1403 by Jelmer Vernooij
Cope with tags pointing at tree objects when cloning local git repositories.
593
        for sha in shas:
594
            try:
595
                revid = self.source.lookup_foreign_revision_id(sha)
596
            except NotCommitError:
0.200.1456 by Jelmer Vernooij
Fix target_has_shas.
597
                # Commit is definitely not present
0.200.1403 by Jelmer Vernooij
Cope with tags pointing at tree objects when cloning local git repositories.
598
                continue
599
            else:
0.200.1456 by Jelmer Vernooij
Fix target_has_shas.
600
                revids[revid] = sha
601
        return set([revids[r] for r in self.target.has_revisions(revids)])
0.259.4 by Jelmer Vernooij
Put determine_wants methods on InterRepo.
602
0.200.1489 by Jelmer Vernooij
More fixes to peel handling.
603
    def determine_wants_all(self, refs):
604
        potential = set()
0.377.1 by Jelmer Vernooij
Fix some remote operations and add more tests.
605
        for k, v in refs.iteritems():
0.200.1489 by Jelmer Vernooij
More fixes to peel handling.
606
            # For non-git target repositories, only worry about peeled
0.200.1513 by Jelmer Vernooij
Cope with zero shas.
607
            if v == ZERO_SHA:
608
                continue
0.200.1648 by Jelmer Vernooij
Fix compatibility with newer versions of breezy.
609
            potential.add(self.source.controldir.get_peeled(k))
0.200.1489 by Jelmer Vernooij
More fixes to peel handling.
610
        return list(potential - self._target_has_shas(potential))
611
0.200.1490 by Jelmer Vernooij
Fix target_has_shas.
612
    def get_determine_wants_heads(self, wants, include_tags=False):
613
        wants = set(wants)
614
        def determine_wants(refs):
615
            potential = set(wants)
616
            if include_tags:
0.377.1 by Jelmer Vernooij
Fix some remote operations and add more tests.
617
                for k, unpeeled in refs.iteritems():
0.200.1490 by Jelmer Vernooij
Fix target_has_shas.
618
                    if not is_tag(k):
619
                        continue
0.200.1513 by Jelmer Vernooij
Cope with zero shas.
620
                    if unpeeled == ZERO_SHA:
621
                        continue
0.200.1648 by Jelmer Vernooij
Fix compatibility with newer versions of breezy.
622
                    potential.add(self.source.controldir.get_peeled(k))
0.200.1490 by Jelmer Vernooij
Fix target_has_shas.
623
            return list(potential - self._target_has_shas(potential))
624
        return determine_wants
625
0.375.1 by Jelmer Vernooij
Fix remote tests, warn when fetching git->bzr and bzr->git.
626
    def _warn_slow(self):
627
        trace.warning(
628
            'Fetching from Git to Bazaar repository. '
629
            'For better performance, fetch into a Git repository.')
630
0.259.6 by Jelmer Vernooij
Fetch tags during pull.
631
    def get_determine_wants_revids(self, revids, include_tags=False):
632
        wants = set()
633
        for revid in set(revids):
0.200.1388 by Jelmer Vernooij
Don't fetch revision already present.
634
            if self.target.has_revision(revid):
635
                continue
0.259.6 by Jelmer Vernooij
Fetch tags during pull.
636
            git_sha, mapping = self.source.lookup_bzr_revision_id(revid)
637
            wants.add(git_sha)
0.200.1489 by Jelmer Vernooij
More fixes to peel handling.
638
        return self.get_determine_wants_heads(wants, include_tags=include_tags)
0.259.6 by Jelmer Vernooij
Fetch tags during pull.
639
0.337.1 by Jelmer Vernooij
Various git remote helper fixes.
640
    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().
641
        """Fetch objects from a remote server.
642
643
        :param determine_wants: determine_wants callback
644
        :param mapping: BzrGitMapping to use
645
        :param limit: Maximum number of commits to import.
0.200.1002 by Jelmer Vernooij
Fix regression in git-import.
646
        :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().
647
        """
648
        raise NotImplementedError(self.fetch_objects)
649
0.200.1491 by Jelmer Vernooij
Fix progress reporting for git -> git.
650
    def fetch(self, revision_id=None, find_ghosts=False,
0.296.1 by Jelmer Vernooij
Fix tag fetching.
651
              mapping=None, fetch_spec=None, include_tags=False):
0.200.225 by Jelmer Vernooij
Implement custom InterBranch to support fetching from remote git branches.
652
        if mapping is None:
653
            mapping = self.source.get_mapping()
0.226.2 by Jelmer Vernooij
Cope with new fetch_spec argument.
654
        if revision_id is not None:
655
            interesting_heads = [revision_id]
656
        elif fetch_spec is not None:
0.200.1089 by Jelmer Vernooij
Cope with fancy fetch_spec behaviour.
657
            recipe = fetch_spec.get_recipe()
658
            if recipe[0] in ("search", "proxy-search"):
659
                interesting_heads = recipe[1]
660
            else:
0.200.1300 by Jelmer Vernooij
Fix formatting.
661
                raise AssertionError("Unsupported search result type %s" %
662
                        recipe[0])
0.226.2 by Jelmer Vernooij
Cope with new fetch_spec argument.
663
        else:
664
            interesting_heads = None
0.259.4 by Jelmer Vernooij
Put determine_wants methods on InterRepo.
665
666
        if interesting_heads is not None:
0.200.1309 by Jelmer Vernooij
Break some more long lines.
667
            determine_wants = self.get_determine_wants_revids(
0.296.1 by Jelmer Vernooij
Fix tag fetching.
668
                interesting_heads, include_tags=include_tags)
0.259.4 by Jelmer Vernooij
Put determine_wants methods on InterRepo.
669
        else:
670
            determine_wants = self.determine_wants_all
0.200.1079 by Jelmer Vernooij
Avoid looking up revid if not necessary.
671
672
        (pack_hint, _, remote_refs) = self.fetch_objects(determine_wants,
0.200.1491 by Jelmer Vernooij
Fix progress reporting for git -> git.
673
            mapping)
0.200.579 by Jelmer Vernooij
Only pack if it makes the target repo smaller.
674
        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.
675
            self.target.pack(hint=pack_hint)
0.200.1002 by Jelmer Vernooij
Fix regression in git-import.
676
        return remote_refs
0.200.225 by Jelmer Vernooij
Implement custom InterBranch to support fetching from remote git branches.
677
0.200.306 by Jelmer Vernooij
Fix tests, split up InterGitNonGitRepository.
678
0.200.563 by Jelmer Vernooij
Attempt to parse progress indication from git status reports.
679
_GIT_PROGRESS_RE = re.compile(r"(.*?): +(\d+)% \((\d+)/(\d+)\)")
680
def report_git_progress(pb, text):
681
    text = text.rstrip("\r\n")
0.375.1 by Jelmer Vernooij
Fix remote tests, warn when fetching git->bzr and bzr->git.
682
    trace.mutter('git: %s', text)
0.200.563 by Jelmer Vernooij
Attempt to parse progress indication from git status reports.
683
    g = _GIT_PROGRESS_RE.match(text)
684
    if g is not None:
685
        (text, pct, current, total) = g.groups()
686
        pb.update(text, int(current), int(total))
687
    else:
688
        pb.update(text, 0, 0)
689
690
0.200.1001 by Jelmer Vernooij
Simplify handling of determine wants, add stub for fetch_objects().
691
class DetermineWantsRecorder(object):
692
693
    def __init__(self, actual):
694
        self.actual = actual
695
        self.wants = []
696
        self.remote_refs = {}
697
698
    def __call__(self, refs):
0.361.1 by Jelmer Vernooij
Don't use assert.
699
        if type(refs) is not dict:
700
            raise TypeError(refs)
0.200.1001 by Jelmer Vernooij
Simplify handling of determine wants, add stub for fetch_objects().
701
        self.remote_refs = refs
702
        self.wants = self.actual(refs)
703
        return self.wants
704
705
0.200.306 by Jelmer Vernooij
Fix tests, split up InterGitNonGitRepository.
706
class InterRemoteGitNonGitRepository(InterGitNonGitRepository):
0.200.664 by Jelmer Vernooij
Support submodules during fetch.
707
    """InterRepository that copies revisions from a remote Git into a non-Git
0.200.306 by Jelmer Vernooij
Fix tests, split up InterGitNonGitRepository.
708
    repository."""
709
0.200.582 by Jelmer Vernooij
Use more efficient algorithm for finding out heads.
710
    def get_target_heads(self):
711
        # FIXME: This should be more efficient
712
        all_revs = self.target.all_revision_ids()
713
        parent_map = self.target.get_parent_map(all_revs)
714
        all_parents = set()
715
        map(all_parents.update, parent_map.itervalues())
716
        return set(all_revs) - all_parents
717
0.337.1 by Jelmer Vernooij
Various git remote helper fixes.
718
    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().
719
        """See `InterGitNonGitRepository`."""
0.375.1 by Jelmer Vernooij
Fix remote tests, warn when fetching git->bzr and bzr->git.
720
        self._warn_slow()
0.200.466 by Jelmer Vernooij
Fix finding of heads for fetch_objects.
721
        store = BazaarObjectStore(self.target, mapping)
0.375.1 by Jelmer Vernooij
Fix remote tests, warn when fetching git->bzr and bzr->git.
722
        with store.lock_write():
0.200.582 by Jelmer Vernooij
Use more efficient algorithm for finding out heads.
723
            heads = self.get_target_heads()
0.281.5 by William Grant
Fix pull with new dulwich by avoiding removed ObjectStore.get_graph_walker.
724
            graph_walker = ObjectStoreGraphWalker(
725
                [store._lookup_revision_sha1(head) for head in heads],
0.200.1631 by William Grant
Fix ObjectStoreGraphWalker invocation.
726
                lambda sha: store[sha].parents)
0.200.1001 by Jelmer Vernooij
Simplify handling of determine wants, add stub for fetch_objects().
727
            wants_recorder = DetermineWantsRecorder(determine_wants)
0.200.664 by Jelmer Vernooij
Support submodules during fetch.
728
0.200.1491 by Jelmer Vernooij
Fix progress reporting for git -> git.
729
            pb = ui.ui_factory.nested_progress_bar()
0.200.306 by Jelmer Vernooij
Fix tests, split up InterGitNonGitRepository.
730
            try:
0.200.1000 by Jelmer Vernooij
Fix fetch between local and remote git branches.
731
                objects_iter = self.source.fetch_objects(
0.200.1001 by Jelmer Vernooij
Simplify handling of determine wants, add stub for fetch_objects().
732
                    wants_recorder, graph_walker, store.get_raw,
0.337.1 by Jelmer Vernooij
Various git remote helper fixes.
733
                    progress=lambda text: report_git_progress(pb, text),)
0.200.1300 by Jelmer Vernooij
Fix formatting.
734
                trace.mutter("Importing %d new revisions",
735
                             len(wants_recorder.wants))
736
                (pack_hint, last_rev) = import_git_objects(self.target,
737
                    mapping, objects_iter, store, wants_recorder.wants, pb,
738
                    limit)
0.200.1002 by Jelmer Vernooij
Fix regression in git-import.
739
                return (pack_hint, last_rev, wants_recorder.remote_refs)
0.200.306 by Jelmer Vernooij
Fix tests, split up InterGitNonGitRepository.
740
            finally:
0.200.1491 by Jelmer Vernooij
Fix progress reporting for git -> git.
741
                pb.finished()
0.200.306 by Jelmer Vernooij
Fix tests, split up InterGitNonGitRepository.
742
743
    @staticmethod
744
    def is_compatible(source, target):
745
        """Be compatible with GitRepository."""
0.200.1222 by Jelmer Vernooij
Better checks in is_compatible methods.
746
        if not isinstance(source, RemoteGitRepository):
747
            return False
748
        if not target.supports_rich_root():
749
            return False
750
        if isinstance(target, GitRepository):
751
            return False
0.200.1270 by Jelmer Vernooij
Cope with older versions of bzr.
752
        if not getattr(target._format, "supports_full_versioned_files", True):
0.200.1222 by Jelmer Vernooij
Better checks in is_compatible methods.
753
            return False
754
        return True
0.200.306 by Jelmer Vernooij
Fix tests, split up InterGitNonGitRepository.
755
756
757
class InterLocalGitNonGitRepository(InterGitNonGitRepository):
0.200.664 by Jelmer Vernooij
Support submodules during fetch.
758
    """InterRepository that copies revisions from a local Git into a non-Git
0.200.306 by Jelmer Vernooij
Fix tests, split up InterGitNonGitRepository.
759
    repository."""
760
0.337.1 by Jelmer Vernooij
Various git remote helper fixes.
761
    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().
762
        """See `InterGitNonGitRepository`."""
0.375.1 by Jelmer Vernooij
Fix remote tests, warn when fetching git->bzr and bzr->git.
763
        self._warn_slow()
0.377.1 by Jelmer Vernooij
Fix some remote operations and add more tests.
764
        remote_refs = self.source.controldir.get_refs_container().as_dict()
0.200.1002 by Jelmer Vernooij
Fix regression in git-import.
765
        wants = determine_wants(remote_refs)
0.200.306 by Jelmer Vernooij
Fix tests, split up InterGitNonGitRepository.
766
        create_pb = None
0.200.1491 by Jelmer Vernooij
Fix progress reporting for git -> git.
767
        pb = ui.ui_factory.nested_progress_bar()
0.200.320 by Jelmer Vernooij
Handle lightweight checkouts.
768
        target_git_object_retriever = BazaarObjectStore(self.target, mapping)
0.200.306 by Jelmer Vernooij
Fix tests, split up InterGitNonGitRepository.
769
        try:
0.296.1 by Jelmer Vernooij
Fix tag fetching.
770
            target_git_object_retriever.lock_write()
771
            try:
0.200.1300 by Jelmer Vernooij
Fix formatting.
772
                (pack_hint, last_rev) = import_git_objects(self.target,
773
                    mapping, self.source._git.object_store,
0.248.5 by Jelmer Vernooij
Reformatting, fix dpush.
774
                    target_git_object_retriever, wants, pb, limit)
0.200.1002 by Jelmer Vernooij
Fix regression in git-import.
775
                return (pack_hint, last_rev, remote_refs)
0.296.1 by Jelmer Vernooij
Fix tag fetching.
776
            finally:
777
                target_git_object_retriever.unlock()
0.200.306 by Jelmer Vernooij
Fix tests, split up InterGitNonGitRepository.
778
        finally:
0.200.1491 by Jelmer Vernooij
Fix progress reporting for git -> git.
779
            pb.finished()
0.200.306 by Jelmer Vernooij
Fix tests, split up InterGitNonGitRepository.
780
781
    @staticmethod
782
    def is_compatible(source, target):
783
        """Be compatible with GitRepository."""
0.200.1222 by Jelmer Vernooij
Better checks in is_compatible methods.
784
        if not isinstance(source, LocalGitRepository):
785
            return False
786
        if not target.supports_rich_root():
787
            return False
788
        if isinstance(target, GitRepository):
789
            return False
0.200.1266 by Jelmer Vernooij
Fix 2.3 support.
790
        if not getattr(target._format, "supports_full_versioned_files", True):
0.200.1222 by Jelmer Vernooij
Better checks in is_compatible methods.
791
            return False
792
        return True
0.200.175 by Jelmer Vernooij
Add optimized handling when fetching from git to git.
793
794
0.200.1350 by Jelmer Vernooij
Implement search_missing_revision_ids.
795
class InterGitGitRepository(InterFromGitRepository):
0.200.291 by Jelmer Vernooij
Print proper error about not supporting push.
796
    """InterRepository that copies between Git repositories."""
0.200.175 by Jelmer Vernooij
Add optimized handling when fetching from git to git.
797
0.200.1433 by Jelmer Vernooij
Fix fetching between git repositories.
798
    def fetch_refs(self, update_refs, lossy=False):
799
        if lossy:
800
            raise errors.LossyPushToSameVCS(self.source, self.target)
0.200.1648 by Jelmer Vernooij
Fix compatibility with newer versions of breezy.
801
        old_refs = self.target.controldir.get_refs_container()
0.200.1433 by Jelmer Vernooij
Fix fetching between git repositories.
802
        ref_changes = {}
803
        def determine_wants(heads):
0.200.1524 by Jelmer Vernooij
Fix inter-git fetching.
804
            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.
805
            new_refs = update_refs(old_refs)
806
            ref_changes.update(new_refs)
807
            return [sha1 for (sha1, bzr_revid) in new_refs.itervalues()]
0.337.1 by Jelmer Vernooij
Various git remote helper fixes.
808
        self.fetch_objects(determine_wants, lossy=lossy)
0.200.1433 by Jelmer Vernooij
Fix fetching between git repositories.
809
        for k, (git_sha, bzr_revid) in ref_changes.iteritems():
810
            self.target._git.refs[k] = git_sha
0.200.1648 by Jelmer Vernooij
Fix compatibility with newer versions of breezy.
811
        new_refs = self.target.controldir.get_refs_container()
0.200.1433 by Jelmer Vernooij
Fix fetching between git repositories.
812
        return None, old_refs, new_refs
813
0.337.1 by Jelmer Vernooij
Various git remote helper fixes.
814
    def fetch_objects(self, determine_wants, mapping=None, limit=None, lossy=False):
815
        if lossy:
816
            raise errors.LossyPushToSameVCS(self.source, self.target)
0.299.1 by Jelmer Vernooij
Raise FetchLimitUnsupported.
817
        if limit is not None:
818
            raise errors.FetchLimitUnsupported(self)
0.200.635 by Jelmer Vernooij
Fix fetching between git repositories.
819
        graphwalker = self.target._git.get_graph_walker()
0.200.695 by Jelmer Vernooij
Clean up trailing whitespace.
820
        if (isinstance(self.source, LocalGitRepository) and
821
            isinstance(self.target, LocalGitRepository)):
0.200.1493 by Jelmer Vernooij
Test fixes.
822
            def wrap_determine_wants(refs):
0.346.1 by Jelmer Vernooij
Fix tag caching.
823
                return determine_wants(self.source._git.refs.as_dict())
0.200.1491 by Jelmer Vernooij
Fix progress reporting for git -> git.
824
            pb = ui.ui_factory.nested_progress_bar()
825
            try:
0.200.1493 by Jelmer Vernooij
Test fixes.
826
                refs = self.source._git.fetch(self.target._git, wrap_determine_wants,
0.200.1491 by Jelmer Vernooij
Fix progress reporting for git -> git.
827
                    lambda text: report_git_progress(pb, text))
828
            finally:
829
                pb.finished()
0.200.1002 by Jelmer Vernooij
Fix regression in git-import.
830
            return (None, None, refs)
0.200.695 by Jelmer Vernooij
Clean up trailing whitespace.
831
        elif (isinstance(self.source, LocalGitRepository) and
832
              isinstance(self.target, RemoteGitRepository)):
0.200.635 by Jelmer Vernooij
Fix fetching between git repositories.
833
            raise NotImplementedError
0.200.695 by Jelmer Vernooij
Clean up trailing whitespace.
834
        elif (isinstance(self.source, RemoteGitRepository) 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()
0.200.635 by Jelmer Vernooij
Fix fetching between git repositories.
837
            try:
0.200.1758 by Jelmer Vernooij
Fix call to add_pack.
838
                f, commit, abort = self.target._git.object_store.add_pack()
0.200.1491 by Jelmer Vernooij
Fix progress reporting for git -> git.
839
                try:
0.200.1648 by Jelmer Vernooij
Fix compatibility with newer versions of breezy.
840
                    refs = self.source.controldir.fetch_pack(
0.200.1491 by Jelmer Vernooij
Fix progress reporting for git -> git.
841
                        determine_wants, graphwalker, f.write,
842
                        lambda text: report_git_progress(pb, text))
843
                    commit()
844
                    return (None, None, refs)
0.200.1758 by Jelmer Vernooij
Fix call to add_pack.
845
                except BaseException:
846
                    abort()
0.200.1491 by Jelmer Vernooij
Fix progress reporting for git -> git.
847
                    raise
848
            finally:
849
                pb.finished()
0.200.635 by Jelmer Vernooij
Fix fetching between git repositories.
850
        else:
0.200.1433 by Jelmer Vernooij
Fix fetching between git repositories.
851
            raise AssertionError("fetching between %r and %r not supported" %
852
                    (self.source, self.target))
0.200.635 by Jelmer Vernooij
Fix fetching between git repositories.
853
0.200.1154 by Jelmer Vernooij
Share more code in InterGitRepository.
854
    def _target_has_shas(self, shas):
0.200.1490 by Jelmer Vernooij
Fix target_has_shas.
855
        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.
856
0.200.1491 by Jelmer Vernooij
Fix progress reporting for git -> git.
857
    def fetch(self, revision_id=None, find_ghosts=False,
0.296.1 by Jelmer Vernooij
Fix tag fetching.
858
              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.
859
        if mapping is None:
860
            mapping = self.source.get_mapping()
861
        r = self.target._git
0.226.2 by Jelmer Vernooij
Cope with new fetch_spec argument.
862
        if revision_id is not None:
0.296.1 by Jelmer Vernooij
Fix tag fetching.
863
            args = [revision_id]
0.226.2 by Jelmer Vernooij
Cope with new fetch_spec argument.
864
        elif fetch_spec is not None:
0.200.1089 by Jelmer Vernooij
Cope with fancy fetch_spec behaviour.
865
            recipe = fetch_spec.get_recipe()
866
            if recipe[0] in ("search", "proxy-search"):
867
                heads = recipe[1]
868
            else:
0.200.1309 by Jelmer Vernooij
Break some more long lines.
869
                raise AssertionError(
870
                    "Unsupported search result type %s" % recipe[0])
0.296.1 by Jelmer Vernooij
Fix tag fetching.
871
            args = heads
0.200.456 by Jelmer Vernooij
Fix git -> git fetching.
872
        if branches is not None:
0.296.1 by Jelmer Vernooij
Fix tag fetching.
873
            def determine_wants(refs):
874
                ret = []
0.346.1 by Jelmer Vernooij
Fix tag caching.
875
                for name, value in refs.iteritems():
0.296.1 by Jelmer Vernooij
Fix tag fetching.
876
                    if value == ZERO_SHA:
877
                        continue
878
879
                    if name in branches or (include_tags and is_tag(name)):
880
                        ret.append(value)
881
                return ret
0.200.456 by Jelmer Vernooij
Fix git -> git fetching.
882
        elif fetch_spec is None and revision_id is None:
0.200.1154 by Jelmer Vernooij
Share more code in InterGitRepository.
883
            determine_wants = self.determine_wants_all
0.226.2 by Jelmer Vernooij
Cope with new fetch_spec argument.
884
        else:
0.296.1 by Jelmer Vernooij
Fix tag fetching.
885
            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.
886
        wants_recorder = DetermineWantsRecorder(determine_wants)
0.299.1 by Jelmer Vernooij
Raise FetchLimitUnsupported.
887
        self.fetch_objects(wants_recorder, mapping, limit=limit)
0.200.1176 by Jelmer Vernooij
Fix fetch return value for inter git fetching.
888
        return wants_recorder.remote_refs
0.200.175 by Jelmer Vernooij
Add optimized handling when fetching from git to git.
889
890
    @staticmethod
891
    def is_compatible(source, target):
892
        """Be compatible with GitRepository."""
0.200.664 by Jelmer Vernooij
Support submodules during fetch.
893
        return (isinstance(source, GitRepository) and
0.200.175 by Jelmer Vernooij
Add optimized handling when fetching from git to git.
894
                isinstance(target, GitRepository))
0.200.1174 by Jelmer Vernooij
Fix specific revision fetching between git repositories.
895
896
    def get_determine_wants_revids(self, revids, include_tags=False):
897
        wants = set()
898
        for revid in set(revids):
0.200.1388 by Jelmer Vernooij
Don't fetch revision already present.
899
            if self.target.has_revision(revid):
900
                continue
0.200.1174 by Jelmer Vernooij
Fix specific revision fetching between git repositories.
901
            git_sha, mapping = self.source.lookup_bzr_revision_id(revid)
902
            wants.add(git_sha)
0.200.1309 by Jelmer Vernooij
Break some more long lines.
903
        return self.get_determine_wants_heads(wants,
904
            include_tags=include_tags)
0.200.1489 by Jelmer Vernooij
More fixes to peel handling.
905
906
    def determine_wants_all(self, refs):
0.346.1 by Jelmer Vernooij
Fix tag caching.
907
        potential = set([v for v in refs.values() if not v == ZERO_SHA])
0.200.1489 by Jelmer Vernooij
More fixes to peel handling.
908
        return list(potential - self._target_has_shas(potential))
0.200.1490 by Jelmer Vernooij
Fix target_has_shas.
909
910
    def get_determine_wants_heads(self, wants, include_tags=False):
911
        wants = set(wants)
912
        def determine_wants(refs):
913
            potential = set(wants)
914
            if include_tags:
0.346.1 by Jelmer Vernooij
Fix tag caching.
915
                for k, unpeeled in refs.iteritems():
0.200.1490 by Jelmer Vernooij
Fix target_has_shas.
916
                    if not is_tag(k):
917
                        continue
0.200.1513 by Jelmer Vernooij
Cope with zero shas.
918
                    if unpeeled == ZERO_SHA:
919
                        continue
0.200.1490 by Jelmer Vernooij
Fix target_has_shas.
920
                    potential.add(unpeeled)
921
            return list(potential - self._target_has_shas(potential))
922
        return determine_wants
923
924