/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
# Copyright (C) 2007 Canonical Ltd
# Copyright (C) 2009 Jelmer Vernooij <jelmer@samba.org>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

"""An adapter between a Git Branch and a Bazaar Branch"""

from dulwich.objects import (
    Commit,
    Tag,
    )

from bzrlib import (
    branch,
    config,
    errors,
    foreign,
    repository,
    revision,
    tag,
    transport,
    )
from bzrlib.decorators import (
    needs_read_lock,
    )
from bzrlib.trace import (
    is_quiet,
    mutter,
    )

from bzrlib.plugins.git.config import (
    GitBranchConfig,
    )
from bzrlib.plugins.git.errors import (
    NoSuchRef,
    )

try:
    from bzrlib.foreign import ForeignBranch
except ImportError:
    class ForeignBranch(branch.Branch):
        def __init__(self, mapping):
            self.mapping = mapping
            super(ForeignBranch, self).__init__()


def extract_tags(refs, mapping):
    ret = {}
    for k,v in refs.iteritems():
        if k.startswith("refs/tags/") and not k.endswith("^{}"):
            v = refs.get(k+"^{}", v)
            ret[k[len("refs/tags/"):]] = mapping.revision_id_foreign_to_bzr(v)
    return ret


class GitPullResult(branch.PullResult):

    def _lookup_revno(self, revid):
        assert isinstance(revid, str), "was %r" % revid
        # Try in source branch first, it'll be faster
        return self.target_branch.revision_id_to_revno(revid)

    @property
    def old_revno(self):
        return self._lookup_revno(self.old_revid)

    @property
    def new_revno(self):
        return self._lookup_revno(self.new_revid)


class LocalGitTagDict(tag.BasicTags):
    """Dictionary with tags in a local repository."""

    def __init__(self, branch):
        self.branch = branch
        self.repository = branch.repository

    def get_tag_dict(self):
        ret = {}
        for k,v in self.repository._git.tags.iteritems():
            obj = self.repository._git.get_object(v)
            while isinstance(obj, Tag):
                v = obj.object[1]
                obj = self.repository._git.get_object(v)
            if not isinstance(obj, Commit):
                mutter("Tag %s points at object %r that is not a commit, "
                       "ignoring", k, obj)
                continue
            ret[k] = self.branch.mapping.revision_id_foreign_to_bzr(v)
        return ret

    def set_tag(self, name, revid):
        self.repository._git.tags[name], _ = \
            self.branch.mapping.revision_id_bzr_to_foreign(revid)


class GitBranchFormat(branch.BranchFormat):

    def get_format_description(self):
        return 'Git Branch'

    def supports_tags(self):
        return True

    def make_tags(self, branch):
        if getattr(branch.repository, "get_refs", None) is not None:
            from bzrlib.plugins.git.remote import RemoteGitTagDict
            return RemoteGitTagDict(branch)
        else:
            return LocalGitTagDict(branch)


class GitBranch(ForeignBranch):
    """An adapter to git repositories for bzr Branch objects."""

    def __init__(self, bzrdir, repository, name, lockfiles):
        self.repository = repository
        self._format = GitBranchFormat()
        self.control_files = lockfiles
        self.bzrdir = bzrdir
        super(GitBranch, self).__init__(repository.get_mapping())
        self.name = name
        self._head = None
        self.base = bzrdir.transport.base

    def _get_nick(self, local=False, possible_master_transports=None):
        """Find the nick name for this branch.

        :return: Branch nick
        """
        return self.name

    def _set_nick(self, nick):
        raise NotImplementedError

    nick = property(_get_nick, _set_nick)

    def __repr__(self):
        return "%s(%r, %r)" % (self.__class__.__name__, self.repository.base, self.name)

    def dpull(self, source, stop_revision=None):
        if stop_revision is None:
            stop_revision = source.last_revision()
        # FIXME: Check for diverged branches
        refs = { "refs/heads/master": stop_revision }
        for name, revid in source.tags.get_tag_dict().iteritems():
            if source.repository.has_revision(revid):
                refs["refs/tags/%s" % name] = revid
        revidmap, new_refs = self.repository.dfetch_refs(source.repository, 
                refs)
        if revidmap != {}:
            self.generate_revision_history(revidmap[stop_revision])
        return revidmap

    def generate_revision_history(self, revid, old_revid=None):
        # FIXME: Check that old_revid is in the ancestry of revid
        newhead, self.mapping = self.mapping.revision_id_bzr_to_foreign(revid)
        self._set_head(newhead)

    def lock_write(self):
        self.control_files.lock_write()

    def get_stacked_on_url(self):
        # Git doesn't do stacking (yet...)
        return None

    def get_parent(self):
        """See Branch.get_parent()."""
        # FIXME: Set "origin" url from .git/config ?
        return None

    def set_parent(self, url):
        # FIXME: Set "origin" url in .git/config ?
        pass

    def lock_read(self):
        self.control_files.lock_read()

    def is_locked(self):
        return self.control_files.is_locked()

    def unlock(self):
        self.control_files.unlock()

    def get_physical_lock_status(self):
        return False

 
class LocalGitBranch(GitBranch):
    """A local Git branch."""

    @needs_read_lock
    def last_revision(self):
        # perhaps should escape this ?
        if self.head is None:
            return revision.NULL_REVISION
        return self.mapping.revision_id_foreign_to_bzr(self.head)

    def _get_checkout_format(self):
        """Return the most suitable metadir for a checkout of this branch.
        Weaves are used if this branch's repository uses weaves.
        """
        format = self.repository.bzrdir.checkout_metadir()
        format.set_branch_format(self._format)
        return format

    def create_checkout(self, to_location, revision_id=None, lightweight=False,
        accelerator_tree=None, hardlink=False):
        if lightweight:
            t = transport.get_transport(to_location)
            t.ensure_base()
            format = self._get_checkout_format()
            checkout = format.initialize_on_transport(t)
            from_branch = branch.BranchReferenceFormat().initialize(checkout, 
                self)
            tree = checkout.create_workingtree(revision_id,
                from_branch=from_branch, hardlink=hardlink)
            return tree
        else:
            return self._create_heavyweight_checkout(to_location, revision_id,
            hardlink)

    def _create_heavyweight_checkout(self, to_location, revision_id=None, 
                                     hardlink=False):
        """Create a new heavyweight checkout of this branch.

        :param to_location: URL of location to create the new checkout in.
        :param revision_id: Revision that should be the tip of the checkout.
        :param hardlink: Whether to hardlink
        :return: WorkingTree object of checkout.
        """
        checkout_branch = BzrDir.create_branch_convenience(
            to_location, force_new_tree=False, format=get_rich_root_format())
        checkout = checkout_branch.bzrdir
        checkout_branch.bind(self)
        # pull up to the specified revision_id to set the initial 
        # branch tip correctly, and seed it with history.
        checkout_branch.pull(self, stop_revision=revision_id)
        return checkout.create_workingtree(revision_id, hardlink=hardlink)

    def _gen_revision_history(self):
        if self.head is None:
            return []
        ret = list(self.repository.iter_reverse_revision_history(
            self.last_revision()))
        ret.reverse()
        return ret

    def _get_head(self):
        return self.repository._git.ref(self.name)

    def _set_head(self, value):
        self._head = value
        self.repository._git.set_ref(self.name, self._head)
        self._clear_cached_state()

    head = property(_get_head, _set_head)

    def get_config(self):
        return GitBranchConfig(self)

    def get_push_location(self):
        """See Branch.get_push_location."""
        push_loc = self.get_config().get_user_option('push_location')
        return push_loc

    def set_push_location(self, location):
        """See Branch.set_push_location."""
        self.get_config().set_user_option('push_location', location,
                                          store=config.STORE_LOCATION)

    def supports_tags(self):
        return True


class GitBranchPullResult(branch.PullResult):

    def report(self, to_file):
        if not is_quiet():
            if self.old_revid == self.new_revid:
                to_file.write('No revisions to pull.\n')
            else:
                to_file.write('Now on revision %d (git sha: %s).\n' % 
                        (self.new_revno, self.new_git_head))
        self._show_tag_conficts(to_file)


class InterGitGenericBranch(branch.InterBranch):
    """InterBranch implementation that pulls from Git into bzr."""

    @classmethod
    def is_compatible(self, source, target):
        return (isinstance(source, GitBranch) and 
                not isinstance(target, GitBranch))

    def update_revisions(self, stop_revision=None, overwrite=False,
        graph=None):
        """See InterBranch.update_revisions()."""
        interrepo = repository.InterRepository.get(self.source.repository, 
            self.target.repository)
        self._head = None
        self._last_revid = None
        def determine_wants(heads):
            if not self.source.name in heads:
                raise NoSuchRef(self.source.name, heads.keys())
            if stop_revision is not None:
                self._last_revid = stop_revision
                self._head, mapping = self.source.repository.lookup_git_revid(
                    stop_revision)
            else:
                self._head = heads[self.source.name]
                self._last_revid = \
                    self.source.mapping.revision_id_foreign_to_bzr(self._head)
            if self.target.repository.has_revision(self._last_revid):
                return []
            return [self._head]
        interrepo.fetch_objects(determine_wants, self.source.mapping)
        if overwrite:
            prev_last_revid = None
        else:
            prev_last_revid = self.target.last_revision()
        self.target.generate_revision_history(self._last_revid, prev_last_revid)

    def pull(self, overwrite=False, stop_revision=None,
             possible_transports=None, _hook_master=None, run_hooks=True,
             _override_hook_target=None, local=False):
        """See Branch.pull.

        :param _hook_master: Private parameter - set the branch to
            be supplied as the master to pull hooks.
        :param run_hooks: Private parameter - if false, this branch
            is being called because it's the master of the primary branch,
            so it should not run its hooks.
        :param _override_hook_target: Private parameter - set the branch to be
            supplied as the target_branch to pull hooks.
        """
        # This type of branch can't be bound.
        if local:
            raise errors.LocalRequiresBoundBranch()
        result = GitBranchPullResult()
        result.source_branch = self.source
        if _override_hook_target is None:
            result.target_branch = self.target
        else:
            result.target_branch = _override_hook_target
        self.source.lock_read()
        try:
            # We assume that during 'pull' the target repository is closer than
            # the source one.
            graph = self.target.repository.get_graph(self.source.repository)
            result.old_revno, result.old_revid = \
                self.target.last_revision_info()
            self.update_revisions(stop_revision, overwrite=overwrite, 
                graph=graph)
            result.new_git_head = self._head
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
                overwrite)
            result.new_revno, result.new_revid = self.target.last_revision_info()
            if _hook_master:
                result.master_branch = _hook_master
                result.local_branch = result.target_branch
            else:
                result.master_branch = result.target_branch
                result.local_branch = None
            if run_hooks:
                for hook in branch.Branch.hooks['post_pull']:
                    hook(result)
        finally:
            self.source.unlock()
        return result




branch.InterBranch.register_optimiser(InterGitGenericBranch)


class InterGitRemoteLocalBranch(branch.InterBranch):
    """InterBranch implementation that pulls between Git branches."""

    @classmethod
    def is_compatible(self, source, target):
        from bzrlib.plugins.git.remote import RemoteGitBranch
        return (isinstance(source, RemoteGitBranch) and 
                isinstance(target, LocalGitBranch))

    def pull(self, stop_revision=None, overwrite=False, 
        possible_transports=None, local=False):
        # This type of branch can't be bound.
        if local:
            raise errors.LocalRequiresBoundBranch()
        result = GitPullResult()
        result.source_branch = self.source
        result.target_branch = self.target
        interrepo = repository.InterRepository.get(self.source.repository, 
            self.target.repository)
        result.old_revid = self.target.last_revision()
        if stop_revision is None:
            refs = interrepo.fetch_refs(branches=["HEAD"])
            stop_revision = self.target.mapping.revision_id_foreign_to_bzr(refs["HEAD"])
        else:
            refs = interrepo.fetch_refs(revision_id=stop_revision)
        self.target.generate_revision_history(stop_revision, result.old_revid)
        for name, revid in extract_tags(refs, self.target.mapping).iteritems():
            self.target.tags.set_tag(name, revid)
        result.new_revid = self.target.last_revision()
        return result


branch.InterBranch.register_optimiser(InterGitRemoteLocalBranch)