~jelmer/bzr-git/705807-dpush

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
424
425
426
427
428
429
430
431
432
# Copyright (C) 2007-2010 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

from bzrlib import (
    config,
    debug,
    trace,
    ui,
    urlutils,
    )
from bzrlib.errors import (
    BzrError,
    InvalidRevisionId,
    NoSuchFile,
    NoSuchRevision,
    NotBranchError,
    NotLocalUrl,
    UninitializableFormat,
    )
from bzrlib.transport import (
    Transport,
    )

from bzrlib.plugins.git import (
    lazy_check_versions,
    )
lazy_check_versions()

from bzrlib.plugins.git.branch import (
    GitBranch,
    GitTags,
    )
from bzrlib.plugins.git.dir import (
    GitControlDirFormat,
    GitDir,
    GitLockableFiles,
    GitLock,
    )
from bzrlib.plugins.git.errors import (
    GitSmartRemoteNotSupported,
    NoSuchRef,
    )
from bzrlib.plugins.git.mapping import (
    mapping_registry,
    )
from bzrlib.plugins.git.repository import (
    GitRepository,
    )
from bzrlib.plugins.git.refs import (
    extract_tags,
    branch_name_to_ref,
    )

import dulwich as git
from dulwich.errors import (
    GitProtocolError,
    )
from dulwich.pack import (
    Pack,
    ThinPackData,
    )
import os
import tempfile
import urllib
import urlparse
urlparse.uses_netloc.extend(['git', 'git+ssh'])

from dulwich.pack import load_pack_index


# Don't run any tests on GitSmartTransport as it is not intended to be
# a full implementation of Transport
def get_test_permutations():
    return []


def split_git_url(url):
    """Split a Git URL.

    :param url: Git URL
    :return: Tuple with host, port, username, path.
    """
    (scheme, netloc, loc, _, _) = urlparse.urlsplit(url)
    path = urllib.unquote(loc)
    if path.startswith("/~"):
        path = path[1:]
    (username, hostport) = urllib.splituser(netloc)
    (host, port) = urllib.splitnport(hostport, None)
    return (host, port, username, path)


class GitSmartTransport(Transport):

    def __init__(self, url, _client=None):
        Transport.__init__(self, url)
        (self._host, self._port, self._username, self._path) = \
            split_git_url(url)
        if 'transport' in debug.debug_flags:
            trace.mutter('host: %r, user: %r, port: %r, path: %r',
                         self._host, self._username, self._port, self._path)
        self._client = _client

    def external_url(self):
        return self.base

    def has(self, relpath):
        return False

    def _get_client(self, thin_packs):
        raise NotImplementedError(self._get_client)

    def _get_path(self):
        return self._path

    def fetch_pack(self, determine_wants, graph_walker, pack_data, progress=None):
        if progress is None:
            def progress(text):
                trace.info("git: %s" % text)
        client = self._get_client(thin_packs=False)
        try:
            return client.fetch_pack(self._get_path(), determine_wants,
                graph_walker, pack_data, progress)
        except GitProtocolError, e:
            raise BzrError(e)

    def send_pack(self, get_changed_refs, generate_pack_contents):
        client = self._get_client(thin_packs=False)
        try:
            return client.send_pack(self._get_path(), get_changed_refs,
                generate_pack_contents)
        except GitProtocolError, e:
            raise BzrError(e)

    def get(self, path):
        raise NoSuchFile(path)

    def abspath(self, relpath):
        return urlutils.join(self.base, relpath)

    def clone(self, offset=None):
        """See Transport.clone()."""
        if offset is None:
            newurl = self.base
        else:
            newurl = urlutils.join(self.base, offset)

        return self.__class__(newurl, self._client)


class TCPGitSmartTransport(GitSmartTransport):

    _scheme = 'git'

    def _get_client(self, thin_packs):
        if self._client is not None:
            ret = self._client
            self._client = None
            return ret
        return git.client.TCPGitClient(self._host, self._port,
            thin_packs=thin_packs, report_activity=self._report_activity)


class SSHGitSmartTransport(GitSmartTransport):

    _scheme = 'git+ssh'

    def _get_path(self):
        if self._path.startswith("/~/"):
            return self._path[3:]
        return self._path

    def _get_client(self, thin_packs):
        if self._client is not None:
            ret = self._client
            self._client = None
            return ret
        location_config = config.LocationConfig(self.base)
        client = git.client.SSHGitClient(self._host, self._port, self._username,
            thin_packs=thin_packs, report_activity=self._report_activity)
        # Set up alternate pack program paths
        upload_pack = location_config.get_user_option('git_upload_pack')
        if upload_pack:
            client.alternative_paths["upload-pack"] = upload_pack
        receive_pack = location_config.get_user_option('git_receive_pack')
        if receive_pack:
            client.alternative_paths["receive-pack"] = receive_pack
        return client


class RemoteGitDir(GitDir):

    def __init__(self, transport, lockfiles, format):
        self._format = format
        self.root_transport = transport
        self.transport = transport
        self._lockfiles = lockfiles
        self._mode_check_done = None

    @property
    def user_url(self):
        return self.control_url

    def _branch_name_to_ref(self, name, default=None):
        return branch_name_to_ref(name, default=default)

    def open_repository(self):
        return RemoteGitRepository(self, self._lockfiles)

    def open_branch(self, name=None, unsupported=False, ignore_fallbacks=False):
        repo = self.open_repository()
        refname = self._branch_name_to_ref(name)
        return RemoteGitBranch(self, repo, refname, self._lockfiles)

    def open_workingtree(self, recommend_upgrade=False):
        raise NotLocalUrl(self.transport.base)


class EmptyObjectStoreIterator(dict):

    def iterobjects(self):
        return []


class TemporaryPackIterator(Pack):

    def __init__(self, path, resolve_ext_ref):
        super(TemporaryPackIterator, self).__init__(path)
        self.resolve_ext_ref = resolve_ext_ref

    @property
    def data(self):
        if self._data is None:
            self._data = ThinPackData(self.resolve_ext_ref, self._data_path)
        return self._data

    @property
    def index(self):
        if self._idx is None:
            if not os.path.exists(self._idx_path):
                pb = ui.ui_factory.nested_progress_bar()
                try:
                    def report_progress(cur, total):
                        pb.update("generating index", cur, total)
                    self.data.create_index(self._idx_path, 
                        progress=report_progress)
                finally:
                    pb.finished()
            self._idx = load_pack_index(self._idx_path)
        return self._idx

    def __del__(self):
        if self._idx is not None:
            self._idx.close()
            os.remove(self._idx_path)
        if self._data is not None:
            self._data.close()
            os.remove(self._data_path)


class RemoteGitControlDirFormat(GitControlDirFormat):
    """The .git directory control format."""

    supports_workingtrees = False

    @classmethod
    def _known_formats(self):
        return set([RemoteGitControlDirFormat()])

    def open(self, transport, _found=None):
        """Open this directory.

        """
        # we dont grok readonly - git isn't integrated with transport.
        url = transport.base
        if url.startswith('readonly+'):
            url = url[len('readonly+'):]
        if (not url.startswith("git://") and not url.startswith("git+")):
            raise NotBranchError(transport.base)
        if not isinstance(transport, GitSmartTransport):
            raise NotBranchError(transport.base)
        lockfiles = GitLockableFiles(transport, GitLock())
        return RemoteGitDir(transport, lockfiles, self)

    def get_format_description(self):
        return "Remote Git Repository"

    def initialize_on_transport(self, transport):
        raise UninitializableFormat(self)


class RemoteGitRepository(GitRepository):

    def __init__(self, gitdir, lockfiles):
        GitRepository.__init__(self, gitdir, lockfiles)
        self._refs = None

    @property
    def user_url(self):
        return self.control_url

    @property
    def inventories(self):
        raise GitSmartRemoteNotSupported()

    @property
    def revisions(self):
        raise GitSmartRemoteNotSupported()

    @property
    def texts(self):
        raise GitSmartRemoteNotSupported()

    def get_refs(self):
        if self._refs is not None:
            return self._refs
        self._refs = self.bzrdir.root_transport.fetch_pack(lambda x: [], None,
            lambda x: None, lambda x: trace.mutter("git: %s" % x))
        return self._refs

    def fetch_pack(self, determine_wants, graph_walker, pack_data,
                   progress=None):
        return self._transport.fetch_pack(determine_wants, graph_walker,
                                          pack_data, progress)

    def send_pack(self, get_changed_refs, generate_pack_contents):
        return self._transport.send_pack(get_changed_refs, generate_pack_contents)

    def fetch_objects(self, determine_wants, graph_walker, resolve_ext_ref,
                      progress=None):
        fd, path = tempfile.mkstemp(suffix=".pack")
        self.fetch_pack(determine_wants, graph_walker,
            lambda x: os.write(fd, x), progress)
        os.close(fd)
        if os.path.getsize(path) == 0:
            return EmptyObjectStoreIterator()
        return TemporaryPackIterator(path[:-len(".pack")], resolve_ext_ref)

    def lookup_bzr_revision_id(self, bzr_revid):
        # This won't work for any round-tripped bzr revisions, but it's a start..
        try:
            return mapping_registry.revision_id_bzr_to_foreign(bzr_revid)
        except InvalidRevisionId:
            raise NoSuchRevision(self, bzr_revid)

    def lookup_foreign_revision_id(self, foreign_revid, mapping=None):
        """Lookup a revision id.

        """
        if mapping is None:
            mapping = self.get_mapping()
        # Not really an easy way to parse foreign revids here..
        return mapping.revision_id_foreign_to_bzr(foreign_revid)


class RemoteGitTagDict(GitTags):

    def get_refs(self):
        return self.repository.get_refs()

    def _iter_tag_refs(self, refs):
        for k, (peeled, unpeeled) in extract_tags(refs).iteritems():
            yield (k, peeled, unpeeled,
                  self.branch.mapping.revision_id_foreign_to_bzr(peeled))

    def set_tag(self, name, revid):
        # FIXME: Not supported yet, should do a push of a new ref
        raise NotImplementedError(self.set_tag)


class RemoteGitBranch(GitBranch):

    def __init__(self, bzrdir, repository, name, lockfiles):
        self._sha = None
        super(RemoteGitBranch, self).__init__(bzrdir, repository, name,
                lockfiles)

    @property
    def user_url(self):
        return self.control_url

    @property
    def control_url(self):
        return self.base

    def revision_history(self):
        raise GitSmartRemoteNotSupported()

    def last_revision(self):
        return self.lookup_foreign_revision_id(self.head)

    def _get_config(self):
        class EmptyConfig(object):

            def _get_configobj(self):
                return config.ConfigObj()

        return EmptyConfig()

    @property
    def head(self):
        if self._sha is not None:
            return self._sha
        heads = self.repository.get_refs()
        name = self.bzrdir._branch_name_to_ref(self.name, "HEAD")
        if name in heads:
            self._sha = heads[name]
        else:
            raise NoSuchRef(self.name)
        return self._sha

    def _synchronize_history(self, destination, revision_id):
        """See Branch._synchronize_history()."""
        destination.generate_revision_history(self.last_revision())

    def get_push_location(self):
        return None

    def set_push_location(self, url):
        pass