1 # server.py -- Implementation of the server side git protocols
2 # Copryight (C) 2008 John Carr <john.carr@unrouted.co.uk>
4 # This program is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU General Public License
6 # as published by the Free Software Foundation; version 2
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
14 # You should have received a copy of the GNU General Public License
15 # along with this program; if not, write to the Free Software
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
20 from dulwich.protocol import Protocol, ProtocolFile, TCP_GIT_PORT, extract_capabilities
21 from dulwich.repo import Repo
22 from dulwich.pack import PackData, Pack, write_pack_data
23 import os, sha, tempfile
25 class Backend(object):
29 Get all the refs in the repository
31 :return: list of tuple(name, sha)
33 raise NotImplementedError
35 def has_revision(self, sha):
37 Is a given sha in this repository?
39 :return: True or False
41 raise NotImplementedError
43 def apply_pack(self, refs, read):
44 """ Import a set of changes into a repository and update the refs
46 :param refs: list of tuple(name, sha)
47 :param read: callback to read from the incoming pack
49 raise NotImplementedError
51 def generate_pack(self, want, have, write, progress):
53 Generate a pack containing all commits a client is missing
55 :param want: is a list of sha's the client desires
56 :param have: is a list of sha's the client has (allowing us to send the minimal pack)
57 :param write: is a callback to write pack data to the client
58 :param progress: is a callback to send progress messages to the client
60 raise NotImplementedError
63 class GitBackend(Backend):
65 def __init__(self, gitdir=None):
69 self.gitdir = tempfile.mkdtemp()
70 Repo.create(self.gitdir)
72 self.repo = Repo(self.gitdir)
77 refs.append(('HEAD', self.repo.head()))
78 for ref, sha in self.repo.heads().items():
79 refs.append(('refs/heads/'+ref,sha))
82 def has_revision(self, sha):
83 return self.repo.get_object(sha) != None
85 def apply_pack(self, refs, read):
86 # store the incoming pack in the repository
87 fd, name = tempfile.mkstemp(suffix='.pack', prefix='pack-', dir=self.repo.pack_dir())
91 # strip '.pack' off our filename
94 # generate an index for it
96 pd.create_index_v2(basename+".idx")
98 for oldsha, sha, ref in refs:
100 self.repo.remove_ref(ref)
102 self.repo.set_ref(ref, sha)
106 def generate_pack(self, want, have, write, progress):
107 progress("dul-daemon says what\n")
111 commits_to_send = want[:]
112 for sha in commits_to_send:
116 sha_queue.append(sha)
118 c = self.repo.commit(sha)
120 if not p in commits_to_send:
121 commits_to_send.append(p)
123 def parse_tree(tree, sha_queue):
124 for mode, name, x in tree.entries():
125 if not x in sha_queue:
127 t = self.repo.tree(x)
129 parse_tree(t, sha_queue)
134 if treesha not in sha_queue:
135 sha_queue.append(treesha)
136 t = self.repo.tree(treesha)
137 parse_tree(t, sha_queue)
139 progress("counting objects: %d\r" % len(sha_queue))
141 progress("counting objects: %d, done.\n" % len(sha_queue))
143 write_pack_data(ProtocolFile(None, write), (self.repo.get_object(sha) for sha in sha_queue), len(sha_queue))
145 progress("how was that, then?\n")
148 class Handler(object):
150 def __init__(self, backend, read, write):
151 self.backend = backend
152 self.proto = Protocol(read, write)
154 def capabilities(self):
155 return " ".join(self.default_capabilities())
158 class UploadPackHandler(Handler):
160 def default_capabilities(self):
161 return ("multi_ack", "side-band-64k", "thin-pack", "ofs-delta")
164 refs = self.backend.get_refs()
167 self.proto.write_pkt_line("%s %s\x00%s\n" % (refs[0][1], refs[0][0], self.capabilities()))
168 for i in range(1, len(refs)):
170 self.proto.write_pkt_line("%s %s\n" % (ref[1], ref[0]))
173 self.proto.write("0000")
175 # Now client will either send "0000", meaning that it doesnt want to pull.
176 # or it will start sending want want want commands
177 want = self.proto.read_pkt_line()
181 want, client_capabilities = extract_capabilities(want)
183 # Keep reading the list of demands until we hit another "0000"
185 while want and want[:4] == 'want':
186 want_rev = want[5:45]
187 # FIXME: This check probably isnt needed?
188 if self.backend.has_revision(want_rev):
189 want_revs.append(want_rev)
190 want = self.proto.read_pkt_line()
192 # Client will now tell us which commits it already has - if we have them we ACK them
193 # this allows client to stop looking at that commits parents (main reason why git pull is fast)
196 have = self.proto.read_pkt_line()
197 while have and have[:4] == 'have':
198 have_ref = have[5:45]
199 if self.backend.has_revision(have_ref):
200 self.proto.write_pkt_line("ACK %s continue\n" % have_ref)
202 have_revs.append(have_ref)
203 have = self.proto.read_pkt_line()
205 # At some point client will stop sending commits and will tell us it is done
206 assert(have[:4] == "done")
208 # Oddness: Git seems to resend the last ACK, without the "continue" statement
210 self.proto.write_pkt_line("ACK %s\n" % last_sha)
212 # The exchange finishes with a NAK
213 self.proto.write_pkt_line("NAK\n")
215 self.backend.generate_pack(want_revs, have_revs, lambda x: self.proto.write_sideband(1, x), lambda x: self.proto.write_sideband(2, x))
218 self.proto.write("0000")
221 class ReceivePackHandler(Handler):
223 def default_capabilities(self):
224 return ("report-status", "delete-refs")
227 refs = self.backend.get_refs()
230 self.proto.write_pkt_line("%s %s\x00%s\n" % (refs[0][1], refs[0][0], self.capabilities()))
231 for i in range(1, len(refs)):
233 self.proto.write_pkt_line("%s %s\n" % (ref[1], ref[0]))
235 self.proto.write_pkt_line("0000000000000000000000000000000000000000 capabilities^{} %s" % self.capabilities())
237 self.proto.write("0000")
240 ref = self.proto.read_pkt_line()
242 # if ref is none then client doesnt want to send us anything..
246 ref, client_capabilities = extract_capabilities(ref)
248 # client will now send us a list of (oldsha, newsha, ref)
250 client_refs.append(ref.split())
251 ref = self.proto.read_pkt_line()
253 # backend can now deal with this refs and read a pack using self.read
254 self.backend.apply_pack(client_refs, self.proto.read)
256 # when we have read all the pack from the client, it assumes everything worked OK
257 # there is NO ack from the server before it reports victory.
260 class TCPGitRequestHandler(SocketServer.StreamRequestHandler):
263 proto = Protocol(self.rfile.read, self.wfile.write)
264 command, args = proto.read_cmd()
266 # switch case to handle the specific git command
267 if command == 'git-upload-pack':
268 cls = UploadPackHandler
269 elif command == 'git-receive-pack':
270 cls = ReceivePackHandler
274 h = cls(self.server.backend, self.rfile.read, self.wfile.write)
278 class TCPGitServer(SocketServer.TCPServer):
280 allow_reuse_address = True
281 serve = SocketServer.TCPServer.serve_forever
283 def __init__(self, backend, listen_addr, port=TCP_GIT_PORT):
284 self.backend = backend
285 SocketServer.TCPServer.__init__(self, (listen_addr, port), TCPGitRequestHandler)