/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to breezy/git/git_remote_helper.py

  • Committer: Jelmer Vernooij
  • Date: 2020-05-06 02:13:25 UTC
  • mfrom: (7490.7.21 work)
  • mto: This revision was merged to the branch mainline in revision 7501.
  • Revision ID: jelmer@jelmer.uk-20200506021325-awbmmqu1zyorz7sj
Merge 3.1 branch.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#!/usr/bin/env python3
 
2
# vim: expandtab
 
3
 
 
4
# Copyright (C) 2011-2018 Jelmer Vernooij <jelmer@jelmer.uk>
 
5
 
 
6
# This program is free software; you can redistribute it and/or modify
 
7
# it under the terms of the GNU General Public License as published by
 
8
# the Free Software Foundation; either version 2 of the License, or
 
9
# (at your option) any later version.
 
10
#
 
11
# This program is distributed in the hope that it will be useful,
 
12
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
13
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
14
# GNU General Public License for more details.
 
15
#
 
16
# You should have received a copy of the GNU General Public License
 
17
# along with this program; if not, write to the Free Software
 
18
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
19
 
 
20
 
 
21
"""Remote helper for git for accessing bzr repositories."""
 
22
 
 
23
CAPABILITIES = ["fetch", "option", "push"]
 
24
 
 
25
import os
 
26
 
 
27
from ..controldir import ControlDir
 
28
from ..errors import NotBranchError, NoRepositoryPresent
 
29
from ..repository import InterRepository
 
30
from ..transport import get_transport_from_path
 
31
 
 
32
from . import (
 
33
    LocalGitProber,
 
34
    )
 
35
from .dir import (
 
36
    BareLocalGitControlDirFormat,
 
37
    LocalGitControlDirFormat,
 
38
    )
 
39
 
 
40
from .object_store import (
 
41
    get_object_store,
 
42
    )
 
43
from .refs import (
 
44
    get_refs_container,
 
45
    ref_to_branch_name,
 
46
    )
 
47
from .repository import (
 
48
    GitRepository,
 
49
    )
 
50
 
 
51
from ..plugins.fastimport import exporter as fastexporter
 
52
 
 
53
try:
 
54
    import fastimport  # noqa: F401
 
55
except ImportError:
 
56
    pass
 
57
else:
 
58
    CAPABILITIES.append("import")
 
59
    CAPABILITIES.append("refspec *:*")
 
60
 
 
61
 
 
62
def open_remote_dir(url):
 
63
    try:
 
64
        return ControlDir.open(url)
 
65
    except NotBranchError:
 
66
        return ControlDir.create(url)
 
67
 
 
68
 
 
69
def fetch(outf, wants, shortname, remote_dir, local_dir):
 
70
    remote_repo = remote_dir.find_repository()
 
71
    local_repo = local_dir.find_repository()
 
72
    inter = InterRepository.get(remote_repo, local_repo)
 
73
    revs = []
 
74
    for (sha1, ref) in wants:
 
75
        revs.append((sha1, None))
 
76
    if (isinstance(remote_repo, GitRepository) and
 
77
            isinstance(local_repo, GitRepository)):
 
78
        lossy = False
 
79
    else:
 
80
        lossy = True
 
81
    inter.fetch_objects(revs, lossy=lossy)
 
82
    outf.write(b"\n")
 
83
 
 
84
 
 
85
def push(outf, wants, shortname, remote_dir, local_dir):
 
86
    for (src_ref, dest_ref) in wants:
 
87
        local_branch = local_dir.open_branch(ref=src_ref)
 
88
        dest_branch_name = ref_to_branch_name(dest_ref)
 
89
        if dest_branch_name == "master":
 
90
            dest_branch_name = None
 
91
        try:
 
92
            remote_branch = remote_dir.open_branch(name=dest_branch_name)
 
93
        except NotBranchError:
 
94
            remote_branch = remote_dir.create_branch(name=dest_branch_name)
 
95
        local_branch.push(remote_branch)
 
96
        outf.write(b"ok %s\n" % dest_ref)
 
97
    outf.write(b"\n")
 
98
 
 
99
 
 
100
class RemoteHelper(object):
 
101
    """Git remote helper."""
 
102
 
 
103
    def __init__(self, local_dir, shortname, remote_dir):
 
104
        self.local_dir = local_dir
 
105
        self.shortname = shortname
 
106
        self.remote_dir = remote_dir
 
107
        self.batchcmd = None
 
108
        self.wants = []
 
109
 
 
110
    def cmd_capabilities(self, outf, argv):
 
111
        outf.write(b"\n".join([c.encode() for c in CAPABILITIES]) + b"\n\n")
 
112
 
 
113
    def cmd_list(self, outf, argv):
 
114
        try:
 
115
            repo = self.remote_dir.find_repository()
 
116
        except NoRepositoryPresent:
 
117
            repo = self.remote_dir.create_repository()
 
118
        object_store = get_object_store(repo)
 
119
        with object_store.lock_read():
 
120
            refs = get_refs_container(self.remote_dir, object_store)
 
121
            for ref, git_sha1 in refs.as_dict().items():
 
122
                ref = ref.replace(b"~", b"_")
 
123
                outf.write(b"%s %s\n" % (git_sha1, ref))
 
124
            outf.write(b"\n")
 
125
 
 
126
    def cmd_option(self, outf, argv):
 
127
        outf.write(b"unsupported\n")
 
128
 
 
129
    def cmd_fetch(self, outf, argv):
 
130
        if self.batchcmd not in (None, "fetch"):
 
131
            raise Exception("fetch command inside other batch command")
 
132
        self.wants.append(tuple(argv[1:]))
 
133
        self.batchcmd = "fetch"
 
134
 
 
135
    def cmd_push(self, outf, argv):
 
136
        if self.batchcmd not in (None, "push"):
 
137
            raise Exception("push command inside other batch command")
 
138
        self.wants.append(tuple(argv[1].split(":", 1)))
 
139
        self.batchcmd = "push"
 
140
 
 
141
    def cmd_import(self, outf, argv):
 
142
        if "fastimport" in CAPABILITIES:
 
143
            raise Exception("install fastimport for 'import' command support")
 
144
        ref = argv[1].encode('utf-8')
 
145
        dest_branch_name = ref_to_branch_name(ref)
 
146
        if dest_branch_name == "master":
 
147
            dest_branch_name = None
 
148
        remote_branch = self.remote_dir.open_branch(name=dest_branch_name)
 
149
        exporter = fastexporter.BzrFastExporter(
 
150
            remote_branch, outf=outf, ref=ref, checkpoint=None,
 
151
            import_marks_file=None, export_marks_file=None, revision=None,
 
152
            verbose=None, plain_format=True, rewrite_tags=False)
 
153
        exporter.run()
 
154
 
 
155
    commands = {
 
156
        "capabilities": cmd_capabilities,
 
157
        "list": cmd_list,
 
158
        "option": cmd_option,
 
159
        "fetch": cmd_fetch,
 
160
        "push": cmd_push,
 
161
        "import": cmd_import,
 
162
        }
 
163
 
 
164
    def process(self, inf, outf):
 
165
        while True:
 
166
            line = inf.readline()
 
167
            if not line:
 
168
                break
 
169
            self.process_line(line, outf)
 
170
 
 
171
    def process_line(self, l, outf):
 
172
        argv = l.strip().split()
 
173
        if argv == []:
 
174
            if self.batchcmd == "fetch":
 
175
                fetch(outf, self.wants, self.shortname,
 
176
                      self.remote_dir, self.local_dir)
 
177
            elif self.batchcmd == "push":
 
178
                push(outf, self.wants, self.shortname,
 
179
                     self.remote_dir, self.local_dir)
 
180
            elif self.batchcmd is None:
 
181
                return
 
182
            else:
 
183
                raise AssertionError("invalid batch %r" % self.batchcmd)
 
184
            self.batchcmd = None
 
185
        else:
 
186
            try:
 
187
                self.commands[argv[0].decode()](self, outf, argv)
 
188
            except KeyError:
 
189
                raise Exception("Unknown remote command %r" % argv)
 
190
        outf.flush()
 
191
 
 
192
 
 
193
def open_local_dir():
 
194
    try:
 
195
        git_path = os.environ["GIT_DIR"]
 
196
    except KeyError:
 
197
        git_transport = get_transport_from_path(".")
 
198
        git_format = LocalGitProber().probe_transport(git_transport)
 
199
    else:
 
200
        if git_path.endswith("/.git"):
 
201
            git_format = LocalGitControlDirFormat()
 
202
            git_path = git_path[:-4]
 
203
        else:
 
204
            git_format = BareLocalGitControlDirFormat()
 
205
        git_transport = get_transport_from_path(git_path)
 
206
 
 
207
    return git_format.open(git_transport)