##// END OF EJS Templates
hgweb/sshserver: extract capabilities for easier modification
Dirkjan Ochtman -
r9713:d193cc97 default
parent child Browse files
Show More
@@ -1,207 +1,208
1 #
1 #
2 # Copyright 21 May 2005 - (c) 2005 Jake Edge <jake@edge2.net>
2 # Copyright 21 May 2005 - (c) 2005 Jake Edge <jake@edge2.net>
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2, incorporated herein by reference.
6 # GNU General Public License version 2, incorporated herein by reference.
7
7
8 import cStringIO, zlib, tempfile, errno, os, sys, urllib
8 import cStringIO, zlib, tempfile, errno, os, sys, urllib, copy
9 from mercurial import util, streamclone
9 from mercurial import util, streamclone
10 from mercurial.node import bin, hex
10 from mercurial.node import bin, hex
11 from mercurial import changegroup as changegroupmod
11 from mercurial import changegroup as changegroupmod
12 from common import ErrorResponse, HTTP_OK, HTTP_NOT_FOUND, HTTP_SERVER_ERROR
12 from common import ErrorResponse, HTTP_OK, HTTP_NOT_FOUND, HTTP_SERVER_ERROR
13
13
14 # __all__ is populated with the allowed commands. Be sure to add to it if
14 # __all__ is populated with the allowed commands. Be sure to add to it if
15 # you're adding a new command, or the new command won't work.
15 # you're adding a new command, or the new command won't work.
16
16
17 __all__ = [
17 __all__ = [
18 'lookup', 'heads', 'branches', 'between', 'changegroup',
18 'lookup', 'heads', 'branches', 'between', 'changegroup',
19 'changegroupsubset', 'capabilities', 'unbundle', 'stream_out',
19 'changegroupsubset', 'capabilities', 'unbundle', 'stream_out',
20 'branchmap',
20 'branchmap',
21 ]
21 ]
22
22
23 HGTYPE = 'application/mercurial-0.1'
23 HGTYPE = 'application/mercurial-0.1'
24 basecaps = 'lookup changegroupsubset branchmap'.split()
24
25
25 def lookup(repo, req):
26 def lookup(repo, req):
26 try:
27 try:
27 r = hex(repo.lookup(req.form['key'][0]))
28 r = hex(repo.lookup(req.form['key'][0]))
28 success = 1
29 success = 1
29 except Exception, inst:
30 except Exception, inst:
30 r = str(inst)
31 r = str(inst)
31 success = 0
32 success = 0
32 resp = "%s %s\n" % (success, r)
33 resp = "%s %s\n" % (success, r)
33 req.respond(HTTP_OK, HGTYPE, length=len(resp))
34 req.respond(HTTP_OK, HGTYPE, length=len(resp))
34 yield resp
35 yield resp
35
36
36 def heads(repo, req):
37 def heads(repo, req):
37 resp = " ".join(map(hex, repo.heads())) + "\n"
38 resp = " ".join(map(hex, repo.heads())) + "\n"
38 req.respond(HTTP_OK, HGTYPE, length=len(resp))
39 req.respond(HTTP_OK, HGTYPE, length=len(resp))
39 yield resp
40 yield resp
40
41
41 def branchmap(repo, req):
42 def branchmap(repo, req):
42 branches = repo.branchmap()
43 branches = repo.branchmap()
43 heads = []
44 heads = []
44 for branch, nodes in branches.iteritems():
45 for branch, nodes in branches.iteritems():
45 branchname = urllib.quote(branch)
46 branchname = urllib.quote(branch)
46 branchnodes = [hex(node) for node in nodes]
47 branchnodes = [hex(node) for node in nodes]
47 heads.append('%s %s' % (branchname, ' '.join(branchnodes)))
48 heads.append('%s %s' % (branchname, ' '.join(branchnodes)))
48 resp = '\n'.join(heads)
49 resp = '\n'.join(heads)
49 req.respond(HTTP_OK, HGTYPE, length=len(resp))
50 req.respond(HTTP_OK, HGTYPE, length=len(resp))
50 yield resp
51 yield resp
51
52
52 def branches(repo, req):
53 def branches(repo, req):
53 nodes = []
54 nodes = []
54 if 'nodes' in req.form:
55 if 'nodes' in req.form:
55 nodes = map(bin, req.form['nodes'][0].split(" "))
56 nodes = map(bin, req.form['nodes'][0].split(" "))
56 resp = cStringIO.StringIO()
57 resp = cStringIO.StringIO()
57 for b in repo.branches(nodes):
58 for b in repo.branches(nodes):
58 resp.write(" ".join(map(hex, b)) + "\n")
59 resp.write(" ".join(map(hex, b)) + "\n")
59 resp = resp.getvalue()
60 resp = resp.getvalue()
60 req.respond(HTTP_OK, HGTYPE, length=len(resp))
61 req.respond(HTTP_OK, HGTYPE, length=len(resp))
61 yield resp
62 yield resp
62
63
63 def between(repo, req):
64 def between(repo, req):
64 if 'pairs' in req.form:
65 if 'pairs' in req.form:
65 pairs = [map(bin, p.split("-"))
66 pairs = [map(bin, p.split("-"))
66 for p in req.form['pairs'][0].split(" ")]
67 for p in req.form['pairs'][0].split(" ")]
67 resp = cStringIO.StringIO()
68 resp = cStringIO.StringIO()
68 for b in repo.between(pairs):
69 for b in repo.between(pairs):
69 resp.write(" ".join(map(hex, b)) + "\n")
70 resp.write(" ".join(map(hex, b)) + "\n")
70 resp = resp.getvalue()
71 resp = resp.getvalue()
71 req.respond(HTTP_OK, HGTYPE, length=len(resp))
72 req.respond(HTTP_OK, HGTYPE, length=len(resp))
72 yield resp
73 yield resp
73
74
74 def changegroup(repo, req):
75 def changegroup(repo, req):
75 req.respond(HTTP_OK, HGTYPE)
76 req.respond(HTTP_OK, HGTYPE)
76 nodes = []
77 nodes = []
77
78
78 if 'roots' in req.form:
79 if 'roots' in req.form:
79 nodes = map(bin, req.form['roots'][0].split(" "))
80 nodes = map(bin, req.form['roots'][0].split(" "))
80
81
81 z = zlib.compressobj()
82 z = zlib.compressobj()
82 f = repo.changegroup(nodes, 'serve')
83 f = repo.changegroup(nodes, 'serve')
83 while 1:
84 while 1:
84 chunk = f.read(4096)
85 chunk = f.read(4096)
85 if not chunk:
86 if not chunk:
86 break
87 break
87 yield z.compress(chunk)
88 yield z.compress(chunk)
88
89
89 yield z.flush()
90 yield z.flush()
90
91
91 def changegroupsubset(repo, req):
92 def changegroupsubset(repo, req):
92 req.respond(HTTP_OK, HGTYPE)
93 req.respond(HTTP_OK, HGTYPE)
93 bases = []
94 bases = []
94 heads = []
95 heads = []
95
96
96 if 'bases' in req.form:
97 if 'bases' in req.form:
97 bases = [bin(x) for x in req.form['bases'][0].split(' ')]
98 bases = [bin(x) for x in req.form['bases'][0].split(' ')]
98 if 'heads' in req.form:
99 if 'heads' in req.form:
99 heads = [bin(x) for x in req.form['heads'][0].split(' ')]
100 heads = [bin(x) for x in req.form['heads'][0].split(' ')]
100
101
101 z = zlib.compressobj()
102 z = zlib.compressobj()
102 f = repo.changegroupsubset(bases, heads, 'serve')
103 f = repo.changegroupsubset(bases, heads, 'serve')
103 while 1:
104 while 1:
104 chunk = f.read(4096)
105 chunk = f.read(4096)
105 if not chunk:
106 if not chunk:
106 break
107 break
107 yield z.compress(chunk)
108 yield z.compress(chunk)
108
109
109 yield z.flush()
110 yield z.flush()
110
111
111 def capabilities(repo, req):
112 def capabilities(repo, req):
112 caps = ['lookup', 'changegroupsubset', 'branchmap']
113 caps = copy.copy(basecaps)
113 if repo.ui.configbool('server', 'uncompressed', untrusted=True):
114 if repo.ui.configbool('server', 'uncompressed', untrusted=True):
114 caps.append('stream=%d' % repo.changelog.version)
115 caps.append('stream=%d' % repo.changelog.version)
115 if changegroupmod.bundlepriority:
116 if changegroupmod.bundlepriority:
116 caps.append('unbundle=%s' % ','.join(changegroupmod.bundlepriority))
117 caps.append('unbundle=%s' % ','.join(changegroupmod.bundlepriority))
117 rsp = ' '.join(caps)
118 rsp = ' '.join(caps)
118 req.respond(HTTP_OK, HGTYPE, length=len(rsp))
119 req.respond(HTTP_OK, HGTYPE, length=len(rsp))
119 yield rsp
120 yield rsp
120
121
121 def unbundle(repo, req):
122 def unbundle(repo, req):
122
123
123 proto = req.env.get('wsgi.url_scheme') or 'http'
124 proto = req.env.get('wsgi.url_scheme') or 'http'
124 their_heads = req.form['heads'][0].split(' ')
125 their_heads = req.form['heads'][0].split(' ')
125
126
126 def check_heads():
127 def check_heads():
127 heads = map(hex, repo.heads())
128 heads = map(hex, repo.heads())
128 return their_heads == [hex('force')] or their_heads == heads
129 return their_heads == [hex('force')] or their_heads == heads
129
130
130 # fail early if possible
131 # fail early if possible
131 if not check_heads():
132 if not check_heads():
132 req.drain()
133 req.drain()
133 raise ErrorResponse(HTTP_OK, 'unsynced changes')
134 raise ErrorResponse(HTTP_OK, 'unsynced changes')
134
135
135 # do not lock repo until all changegroup data is
136 # do not lock repo until all changegroup data is
136 # streamed. save to temporary file.
137 # streamed. save to temporary file.
137
138
138 fd, tempname = tempfile.mkstemp(prefix='hg-unbundle-')
139 fd, tempname = tempfile.mkstemp(prefix='hg-unbundle-')
139 fp = os.fdopen(fd, 'wb+')
140 fp = os.fdopen(fd, 'wb+')
140 try:
141 try:
141 length = int(req.env['CONTENT_LENGTH'])
142 length = int(req.env['CONTENT_LENGTH'])
142 for s in util.filechunkiter(req, limit=length):
143 for s in util.filechunkiter(req, limit=length):
143 fp.write(s)
144 fp.write(s)
144
145
145 try:
146 try:
146 lock = repo.lock()
147 lock = repo.lock()
147 try:
148 try:
148 if not check_heads():
149 if not check_heads():
149 raise ErrorResponse(HTTP_OK, 'unsynced changes')
150 raise ErrorResponse(HTTP_OK, 'unsynced changes')
150
151
151 fp.seek(0)
152 fp.seek(0)
152 header = fp.read(6)
153 header = fp.read(6)
153 if header.startswith('HG') and not header.startswith('HG10'):
154 if header.startswith('HG') and not header.startswith('HG10'):
154 raise ValueError('unknown bundle version')
155 raise ValueError('unknown bundle version')
155 elif header not in changegroupmod.bundletypes:
156 elif header not in changegroupmod.bundletypes:
156 raise ValueError('unknown bundle compression type')
157 raise ValueError('unknown bundle compression type')
157 gen = changegroupmod.unbundle(header, fp)
158 gen = changegroupmod.unbundle(header, fp)
158
159
159 # send addchangegroup output to client
160 # send addchangegroup output to client
160
161
161 oldio = sys.stdout, sys.stderr
162 oldio = sys.stdout, sys.stderr
162 sys.stderr = sys.stdout = cStringIO.StringIO()
163 sys.stderr = sys.stdout = cStringIO.StringIO()
163
164
164 try:
165 try:
165 url = 'remote:%s:%s:%s' % (
166 url = 'remote:%s:%s:%s' % (
166 proto,
167 proto,
167 urllib.quote(req.env.get('REMOTE_HOST', '')),
168 urllib.quote(req.env.get('REMOTE_HOST', '')),
168 urllib.quote(req.env.get('REMOTE_USER', '')))
169 urllib.quote(req.env.get('REMOTE_USER', '')))
169 try:
170 try:
170 ret = repo.addchangegroup(gen, 'serve', url)
171 ret = repo.addchangegroup(gen, 'serve', url)
171 except util.Abort, inst:
172 except util.Abort, inst:
172 sys.stdout.write("abort: %s\n" % inst)
173 sys.stdout.write("abort: %s\n" % inst)
173 ret = 0
174 ret = 0
174 finally:
175 finally:
175 val = sys.stdout.getvalue()
176 val = sys.stdout.getvalue()
176 sys.stdout, sys.stderr = oldio
177 sys.stdout, sys.stderr = oldio
177 req.respond(HTTP_OK, HGTYPE)
178 req.respond(HTTP_OK, HGTYPE)
178 return '%d\n%s' % (ret, val),
179 return '%d\n%s' % (ret, val),
179 finally:
180 finally:
180 lock.release()
181 lock.release()
181 except ValueError, inst:
182 except ValueError, inst:
182 raise ErrorResponse(HTTP_OK, inst)
183 raise ErrorResponse(HTTP_OK, inst)
183 except (OSError, IOError), inst:
184 except (OSError, IOError), inst:
184 error = getattr(inst, 'strerror', 'Unknown error')
185 error = getattr(inst, 'strerror', 'Unknown error')
185 if inst.errno == errno.ENOENT:
186 if inst.errno == errno.ENOENT:
186 code = HTTP_NOT_FOUND
187 code = HTTP_NOT_FOUND
187 else:
188 else:
188 code = HTTP_SERVER_ERROR
189 code = HTTP_SERVER_ERROR
189 filename = getattr(inst, 'filename', '')
190 filename = getattr(inst, 'filename', '')
190 # Don't send our filesystem layout to the client
191 # Don't send our filesystem layout to the client
191 if filename and filename.startswith(repo.root):
192 if filename and filename.startswith(repo.root):
192 filename = filename[len(repo.root)+1:]
193 filename = filename[len(repo.root)+1:]
193 text = '%s: %s' % (error, filename)
194 text = '%s: %s' % (error, filename)
194 else:
195 else:
195 text = error.replace(repo.root + os.path.sep, '')
196 text = error.replace(repo.root + os.path.sep, '')
196 raise ErrorResponse(code, text)
197 raise ErrorResponse(code, text)
197 finally:
198 finally:
198 fp.close()
199 fp.close()
199 os.unlink(tempname)
200 os.unlink(tempname)
200
201
201 def stream_out(repo, req):
202 def stream_out(repo, req):
202 req.respond(HTTP_OK, HGTYPE)
203 req.respond(HTTP_OK, HGTYPE)
203 try:
204 try:
204 for chunk in streamclone.stream_out(repo, untrusted=True):
205 for chunk in streamclone.stream_out(repo, untrusted=True):
205 yield chunk
206 yield chunk
206 except streamclone.StreamException, inst:
207 except streamclone.StreamException, inst:
207 yield str(inst)
208 yield str(inst)
@@ -1,225 +1,227
1 # sshserver.py - ssh protocol server support for mercurial
1 # sshserver.py - ssh protocol server support for mercurial
2 #
2 #
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 # Copyright 2006 Vadim Gelfer <vadim.gelfer@gmail.com>
4 # Copyright 2006 Vadim Gelfer <vadim.gelfer@gmail.com>
5 #
5 #
6 # This software may be used and distributed according to the terms of the
6 # This software may be used and distributed according to the terms of the
7 # GNU General Public License version 2, incorporated herein by reference.
7 # GNU General Public License version 2, incorporated herein by reference.
8
8
9 from i18n import _
9 from i18n import _
10 from node import bin, hex
10 from node import bin, hex
11 import streamclone, util, hook
11 import streamclone, util, hook
12 import os, sys, tempfile, urllib
12 import os, sys, tempfile, urllib, copy
13
13
14 class sshserver(object):
14 class sshserver(object):
15
16 caps = 'unbundle lookup changegroupsubset branchmap'.split()
17
15 def __init__(self, ui, repo):
18 def __init__(self, ui, repo):
16 self.ui = ui
19 self.ui = ui
17 self.repo = repo
20 self.repo = repo
18 self.lock = None
21 self.lock = None
19 self.fin = sys.stdin
22 self.fin = sys.stdin
20 self.fout = sys.stdout
23 self.fout = sys.stdout
21
24
22 hook.redirect(True)
25 hook.redirect(True)
23 sys.stdout = sys.stderr
26 sys.stdout = sys.stderr
24
27
25 # Prevent insertion/deletion of CRs
28 # Prevent insertion/deletion of CRs
26 util.set_binary(self.fin)
29 util.set_binary(self.fin)
27 util.set_binary(self.fout)
30 util.set_binary(self.fout)
28
31
29 def getarg(self):
32 def getarg(self):
30 argline = self.fin.readline()[:-1]
33 argline = self.fin.readline()[:-1]
31 arg, l = argline.split()
34 arg, l = argline.split()
32 val = self.fin.read(int(l))
35 val = self.fin.read(int(l))
33 return arg, val
36 return arg, val
34
37
35 def respond(self, v):
38 def respond(self, v):
36 self.fout.write("%d\n" % len(v))
39 self.fout.write("%d\n" % len(v))
37 self.fout.write(v)
40 self.fout.write(v)
38 self.fout.flush()
41 self.fout.flush()
39
42
40 def serve_forever(self):
43 def serve_forever(self):
41 try:
44 try:
42 while self.serve_one(): pass
45 while self.serve_one(): pass
43 finally:
46 finally:
44 if self.lock is not None:
47 if self.lock is not None:
45 self.lock.release()
48 self.lock.release()
46 sys.exit(0)
49 sys.exit(0)
47
50
48 def serve_one(self):
51 def serve_one(self):
49 cmd = self.fin.readline()[:-1]
52 cmd = self.fin.readline()[:-1]
50 if cmd:
53 if cmd:
51 impl = getattr(self, 'do_' + cmd, None)
54 impl = getattr(self, 'do_' + cmd, None)
52 if impl: impl()
55 if impl: impl()
53 else: self.respond("")
56 else: self.respond("")
54 return cmd != ''
57 return cmd != ''
55
58
56 def do_lookup(self):
59 def do_lookup(self):
57 arg, key = self.getarg()
60 arg, key = self.getarg()
58 assert arg == 'key'
61 assert arg == 'key'
59 try:
62 try:
60 r = hex(self.repo.lookup(key))
63 r = hex(self.repo.lookup(key))
61 success = 1
64 success = 1
62 except Exception, inst:
65 except Exception, inst:
63 r = str(inst)
66 r = str(inst)
64 success = 0
67 success = 0
65 self.respond("%s %s\n" % (success, r))
68 self.respond("%s %s\n" % (success, r))
66
69
67 def do_branchmap(self):
70 def do_branchmap(self):
68 branchmap = self.repo.branchmap()
71 branchmap = self.repo.branchmap()
69 heads = []
72 heads = []
70 for branch, nodes in branchmap.iteritems():
73 for branch, nodes in branchmap.iteritems():
71 branchname = urllib.quote(branch)
74 branchname = urllib.quote(branch)
72 branchnodes = [hex(node) for node in nodes]
75 branchnodes = [hex(node) for node in nodes]
73 heads.append('%s %s' % (branchname, ' '.join(branchnodes)))
76 heads.append('%s %s' % (branchname, ' '.join(branchnodes)))
74 self.respond('\n'.join(heads))
77 self.respond('\n'.join(heads))
75
78
76 def do_heads(self):
79 def do_heads(self):
77 h = self.repo.heads()
80 h = self.repo.heads()
78 self.respond(" ".join(map(hex, h)) + "\n")
81 self.respond(" ".join(map(hex, h)) + "\n")
79
82
80 def do_hello(self):
83 def do_hello(self):
81 '''the hello command returns a set of lines describing various
84 '''the hello command returns a set of lines describing various
82 interesting things about the server, in an RFC822-like format.
85 interesting things about the server, in an RFC822-like format.
83 Currently the only one defined is "capabilities", which
86 Currently the only one defined is "capabilities", which
84 consists of a line in the form:
87 consists of a line in the form:
85
88
86 capabilities: space separated list of tokens
89 capabilities: space separated list of tokens
87 '''
90 '''
88
91 caps = copy.copy(self.caps)
89 caps = ['unbundle', 'lookup', 'changegroupsubset', 'branchmap']
90 if self.ui.configbool('server', 'uncompressed'):
92 if self.ui.configbool('server', 'uncompressed'):
91 caps.append('stream=%d' % self.repo.changelog.version)
93 caps.append('stream=%d' % self.repo.changelog.version)
92 self.respond("capabilities: %s\n" % (' '.join(caps),))
94 self.respond("capabilities: %s\n" % (' '.join(caps),))
93
95
94 def do_lock(self):
96 def do_lock(self):
95 '''DEPRECATED - allowing remote client to lock repo is not safe'''
97 '''DEPRECATED - allowing remote client to lock repo is not safe'''
96
98
97 self.lock = self.repo.lock()
99 self.lock = self.repo.lock()
98 self.respond("")
100 self.respond("")
99
101
100 def do_unlock(self):
102 def do_unlock(self):
101 '''DEPRECATED'''
103 '''DEPRECATED'''
102
104
103 if self.lock:
105 if self.lock:
104 self.lock.release()
106 self.lock.release()
105 self.lock = None
107 self.lock = None
106 self.respond("")
108 self.respond("")
107
109
108 def do_branches(self):
110 def do_branches(self):
109 arg, nodes = self.getarg()
111 arg, nodes = self.getarg()
110 nodes = map(bin, nodes.split(" "))
112 nodes = map(bin, nodes.split(" "))
111 r = []
113 r = []
112 for b in self.repo.branches(nodes):
114 for b in self.repo.branches(nodes):
113 r.append(" ".join(map(hex, b)) + "\n")
115 r.append(" ".join(map(hex, b)) + "\n")
114 self.respond("".join(r))
116 self.respond("".join(r))
115
117
116 def do_between(self):
118 def do_between(self):
117 arg, pairs = self.getarg()
119 arg, pairs = self.getarg()
118 pairs = [map(bin, p.split("-")) for p in pairs.split(" ")]
120 pairs = [map(bin, p.split("-")) for p in pairs.split(" ")]
119 r = []
121 r = []
120 for b in self.repo.between(pairs):
122 for b in self.repo.between(pairs):
121 r.append(" ".join(map(hex, b)) + "\n")
123 r.append(" ".join(map(hex, b)) + "\n")
122 self.respond("".join(r))
124 self.respond("".join(r))
123
125
124 def do_changegroup(self):
126 def do_changegroup(self):
125 nodes = []
127 nodes = []
126 arg, roots = self.getarg()
128 arg, roots = self.getarg()
127 nodes = map(bin, roots.split(" "))
129 nodes = map(bin, roots.split(" "))
128
130
129 cg = self.repo.changegroup(nodes, 'serve')
131 cg = self.repo.changegroup(nodes, 'serve')
130 while True:
132 while True:
131 d = cg.read(4096)
133 d = cg.read(4096)
132 if not d:
134 if not d:
133 break
135 break
134 self.fout.write(d)
136 self.fout.write(d)
135
137
136 self.fout.flush()
138 self.fout.flush()
137
139
138 def do_changegroupsubset(self):
140 def do_changegroupsubset(self):
139 argmap = dict([self.getarg(), self.getarg()])
141 argmap = dict([self.getarg(), self.getarg()])
140 bases = [bin(n) for n in argmap['bases'].split(' ')]
142 bases = [bin(n) for n in argmap['bases'].split(' ')]
141 heads = [bin(n) for n in argmap['heads'].split(' ')]
143 heads = [bin(n) for n in argmap['heads'].split(' ')]
142
144
143 cg = self.repo.changegroupsubset(bases, heads, 'serve')
145 cg = self.repo.changegroupsubset(bases, heads, 'serve')
144 while True:
146 while True:
145 d = cg.read(4096)
147 d = cg.read(4096)
146 if not d:
148 if not d:
147 break
149 break
148 self.fout.write(d)
150 self.fout.write(d)
149
151
150 self.fout.flush()
152 self.fout.flush()
151
153
152 def do_addchangegroup(self):
154 def do_addchangegroup(self):
153 '''DEPRECATED'''
155 '''DEPRECATED'''
154
156
155 if not self.lock:
157 if not self.lock:
156 self.respond("not locked")
158 self.respond("not locked")
157 return
159 return
158
160
159 self.respond("")
161 self.respond("")
160 r = self.repo.addchangegroup(self.fin, 'serve', self.client_url())
162 r = self.repo.addchangegroup(self.fin, 'serve', self.client_url())
161 self.respond(str(r))
163 self.respond(str(r))
162
164
163 def client_url(self):
165 def client_url(self):
164 client = os.environ.get('SSH_CLIENT', '').split(' ', 1)[0]
166 client = os.environ.get('SSH_CLIENT', '').split(' ', 1)[0]
165 return 'remote:ssh:' + client
167 return 'remote:ssh:' + client
166
168
167 def do_unbundle(self):
169 def do_unbundle(self):
168 their_heads = self.getarg()[1].split()
170 their_heads = self.getarg()[1].split()
169
171
170 def check_heads():
172 def check_heads():
171 heads = map(hex, self.repo.heads())
173 heads = map(hex, self.repo.heads())
172 return their_heads == [hex('force')] or their_heads == heads
174 return their_heads == [hex('force')] or their_heads == heads
173
175
174 # fail early if possible
176 # fail early if possible
175 if not check_heads():
177 if not check_heads():
176 self.respond(_('unsynced changes'))
178 self.respond(_('unsynced changes'))
177 return
179 return
178
180
179 self.respond('')
181 self.respond('')
180
182
181 # write bundle data to temporary file because it can be big
183 # write bundle data to temporary file because it can be big
182 tempname = fp = None
184 tempname = fp = None
183 try:
185 try:
184 fd, tempname = tempfile.mkstemp(prefix='hg-unbundle-')
186 fd, tempname = tempfile.mkstemp(prefix='hg-unbundle-')
185 fp = os.fdopen(fd, 'wb+')
187 fp = os.fdopen(fd, 'wb+')
186
188
187 count = int(self.fin.readline())
189 count = int(self.fin.readline())
188 while count:
190 while count:
189 fp.write(self.fin.read(count))
191 fp.write(self.fin.read(count))
190 count = int(self.fin.readline())
192 count = int(self.fin.readline())
191
193
192 was_locked = self.lock is not None
194 was_locked = self.lock is not None
193 if not was_locked:
195 if not was_locked:
194 self.lock = self.repo.lock()
196 self.lock = self.repo.lock()
195 try:
197 try:
196 if not check_heads():
198 if not check_heads():
197 # someone else committed/pushed/unbundled while we
199 # someone else committed/pushed/unbundled while we
198 # were transferring data
200 # were transferring data
199 self.respond(_('unsynced changes'))
201 self.respond(_('unsynced changes'))
200 return
202 return
201 self.respond('')
203 self.respond('')
202
204
203 # push can proceed
205 # push can proceed
204
206
205 fp.seek(0)
207 fp.seek(0)
206 r = self.repo.addchangegroup(fp, 'serve', self.client_url())
208 r = self.repo.addchangegroup(fp, 'serve', self.client_url())
207 self.respond(str(r))
209 self.respond(str(r))
208 finally:
210 finally:
209 if not was_locked:
211 if not was_locked:
210 self.lock.release()
212 self.lock.release()
211 self.lock = None
213 self.lock = None
212 finally:
214 finally:
213 if fp is not None:
215 if fp is not None:
214 fp.close()
216 fp.close()
215 if tempname is not None:
217 if tempname is not None:
216 os.unlink(tempname)
218 os.unlink(tempname)
217
219
218 def do_stream_out(self):
220 def do_stream_out(self):
219 try:
221 try:
220 for chunk in streamclone.stream_out(self.repo):
222 for chunk in streamclone.stream_out(self.repo):
221 self.fout.write(chunk)
223 self.fout.write(chunk)
222 self.fout.flush()
224 self.fout.flush()
223 except streamclone.StreamException, inst:
225 except streamclone.StreamException, inst:
224 self.fout.write(str(inst))
226 self.fout.write(str(inst))
225 self.fout.flush()
227 self.fout.flush()
General Comments 0
You need to be logged in to leave comments. Login now