forked from glandium/git-cinnabar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
git-remote-hg
executable file
·508 lines (461 loc) · 19.2 KB
/
git-remote-hg
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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
#!/usr/bin/env python2.7
from __future__ import division
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), 'pythonlib'))
from cinnabar.githg import (
UpgradeException,
GitHgStore,
LazyString,
)
from cinnabar.hg import (
bundlerepo,
getbundle,
get_repo,
push,
)
from cinnabar.bundle import (
PushStore,
)
from binascii import hexlify
from itertools import chain
import logging
from cinnabar.git import (
Git,
InvalidConfig,
NULL_NODE_ID,
)
from cinnabar.util import (
init_logging,
IOLogger,
VersionedDict,
)
import cinnabar.util
from collections import Sequence
from urllib import unquote
def read_cmd(fileobj):
line = fileobj.readline().strip()
if not line:
return None, None
line = line.split(' ')
return line[0], line[1:]
def autohexlify(h):
if len(h) == 40:
return h
elif len(h) == 20:
return hexlify(h)
assert False
class BranchMap(object):
def __init__(self, store, remote_branchmap, remote_heads):
self._heads = {}
self._all_heads = tuple(autohexlify(h) for h in reversed(remote_heads))
self._tips = {}
self._git_sha1s = {}
self._unknown_heads = set()
for branch, heads in remote_branchmap.iteritems():
# We can't keep track of tips if the list of heads is not sequenced
sequenced = isinstance(heads, Sequence) or len(heads) == 1
branch_heads = []
for head in heads:
head = autohexlify(head)
branch_heads.append(head)
sha1 = store.changeset_ref(head)
if not sha1:
self._unknown_heads.add(head)
continue
extra = store.read_changeset_data(sha1).get('extra')
if sequenced and extra and not extra.get('close'):
self._tips[branch] = head
assert head not in self._git_sha1s
self._git_sha1s[head] = sha1
# Use last head as tip if we didn't set one.
if heads and sequenced and branch not in self._tips:
self._tips[branch] = head
self._heads[branch] = tuple(branch_heads)
def names(self):
return self._heads.keys()
def heads(self, branch=None):
if branch:
return self._heads.get(branch, ())
return self._all_heads
def unknown_heads(self):
return self._unknown_heads
def git_sha1(self, head):
return self._git_sha1s.get(head, '?')
def tip(self, branch):
return self._tips.get(branch, None)
def sanitize_branch_name(name):
'''Valid characters in mercurial branch names are not necessarily valid
in git ref names. This function replaces unsupported characters with a
urlquote escape such that the name can be reversed straightforwardly with
urllib.unquote.'''
# TODO: Actually sanitize all the conflicting cases, see
# git-check-ref-format(1).
return name.replace('%', '%25').replace(' ', '%20')
def main(args):
if sys.platform == 'win32':
# By default, sys.stdout on Windows will transform \n into \r\n, which
# the calling git process won't recognize in our answers.
import msvcrt
msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
init_logging()
logger = logging.getLogger('-')
logger.info(args)
assert len(args) == 2
remote, url = args
if remote.startswith(('hg::', 'hg://')):
remote = None
repo = get_repo(url)
try:
store = GitHgStore()
except UpgradeException as e:
logging.error(e.message)
return 1
if isinstance(repo, bundlerepo):
repo.init(store)
logger.info(LazyString(lambda: '%s' % store.heads()))
helper = IOLogger(logging.getLogger('remote-helper'),
sys.stdin, sys.stdout)
branchmap = None
bookmarks = {}
HEAD = 'branches/default/tip'
has_unknown_heads = False
GRAFT = {
None: False,
'false': False,
'true': True,
}
try:
graft = Git.config('cinnabar.graft', remote=remote, values=GRAFT)
except InvalidConfig as e:
logging.error(e.message)
return 1
if Git.config('cinnabar.graft-refs') is not None:
logging.warn(
'The cinnabar.graft-refs configuration is deprecated.\n'
'Please unset it.'
)
while True:
cmd, args = read_cmd(helper)
if not cmd:
break
if cmd == 'capabilities':
assert not args
helper.write(
'option\n'
'import\n'
'push\n'
'refspec refs/heads/branches/*:'
'refs/cinnabar/refs/heads/branches/*\n'
'refspec refs/heads/bookmarks/*:'
'refs/cinnabar/refs/heads/bookmarks/*\n'
'refspec HEAD:refs/cinnabar/HEAD\n'
'\n'
)
helper.flush()
elif cmd == 'list':
assert not args or args == ['for-push']
if repo.capable('batch'):
batch = repo.batch()
branchmap = batch.branchmap()
heads = batch.heads()
bookmarks = batch.listkeys('bookmarks')
batch.submit()
branchmap = branchmap.value
heads = heads.value
bookmarks = bookmarks.value
if heads == ['\0' * 20]:
heads = []
else:
while True:
branchmap = repo.branchmap()
heads = repo.heads()
if heads == ['\0' * 20]:
heads = []
# Some branch heads can be non-heads topologically, but if
# some heads don't appear in the branchmap, then something
# was pushed to the repo between branchmap() and heads()
if set(heads).issubset(set(chain(*branchmap.values()))):
break
bookmarks = repo.listkeys('bookmarks')
branchmap = BranchMap(store, branchmap, heads)
has_unknown_heads = bool(branchmap.unknown_heads())
if graft and has_unknown_heads and 'for-push' not in args:
store.prepare_graft()
store.init_fast_import()
get_heads = set(branchmap.heads()) & branchmap.unknown_heads()
getbundle(repo, store, get_heads, branchmap.names())
# We may have failed to graft all changesets, in which case we
# skipped them. If that's what happened, we want to create a
# new branchmap containing all we do know about, so that we can
# avoid telling git about things we don't know, because if we
# didn't, it would ask for them, and subsequently fail because
# they are missing.
# Since we can't know for sure what the right tips might be for
# each branch, we won't expose the tips. This means we don't
# need to care about the order of the heads for the new
# branchmap.
has_unknown_heads = any(not(store.changeset_ref(h))
for h in get_heads)
if has_unknown_heads:
new_branchmap = {
branch: set(h for h in branchmap.heads(branch))
for branch in branchmap.names()
}
new_branchmap = {
branch: set(h for h in branchmap.heads(branch)
if h not in branchmap.unknown_heads())
for branch in branchmap.names()
}
new_heads = set(h for h in branchmap.heads()
if h not in branchmap.unknown_heads())
for status, head, branch in store._hgheads.iterchanges():
branch_heads = new_branchmap.get(branch)
if status == VersionedDict.REMOVED:
if branch_heads and head in branch_heads:
branch_heads.remove(head)
if head in new_heads:
new_heads.remove(head)
else:
if not branch_heads:
branch_heads = new_branchmap[branch] = set()
branch_heads.add(head)
new_heads.add(head)
branchmap = BranchMap(store, new_branchmap,
list(new_heads))
for branch in sorted(branchmap.names()):
branch_tip = branchmap.tip(branch)
for head in sorted(branchmap.heads(branch)):
sha1 = branchmap.git_sha1(head)
if head == branch_tip:
continue
helper.write('%s refs/heads/branches/%s/%s\n' % (
sha1,
sanitize_branch_name(branch),
head,
))
if branch_tip:
helper.write('%s refs/heads/branches/%s/tip\n' % (
branchmap.git_sha1(branch_tip),
sanitize_branch_name(branch),
))
for name, sha1 in sorted(bookmarks.iteritems()):
if sha1 == NULL_NODE_ID:
continue
ref = store.changeset_ref(sha1)
if graft and not ref:
continue
helper.write(
'%s refs/heads/bookmarks/%s\n'
% (ref if ref else '?', sanitize_branch_name(name))
)
if not has_unknown_heads:
for tag, ref in sorted(store.tags(branchmap.heads())):
helper.write('%s refs/tags/%s\n' %
(ref, sanitize_branch_name(tag)))
if '@' in bookmarks:
HEAD = 'bookmarks/@'
head = bookmarks.get('@', branchmap.tip('default'))
if graft and head:
head = store.changeset_ref(head)
if head:
helper.write('@refs/heads/%s HEAD\n' % HEAD)
helper.write('\n')
helper.flush()
elif cmd == 'option':
assert len(args) == 2
name, value = args
if name == 'progress':
if value == 'true':
cinnabar.util.progress = True
helper.write('ok\n')
elif value == 'false':
cinnabar.util.progress = False
helper.write('ok\n')
else:
helper.write('unsupported\n')
else:
helper.write('unsupported\n')
helper.flush()
elif cmd == 'import':
try:
assert len(args) == 1
refs = args
while cmd:
assert cmd == 'import'
cmd, args = read_cmd(helper)
assert args is None or len(args) == 1
if args:
refs.extend(args)
finally:
# If anything wrong happens at any time, we risk git picking
# the existing refs/cinnabar refs, so remove them preventively.
for sha1, ref in Git.for_each_ref('refs/cinnabar/refs/heads',
'refs/cinnabar/HEAD'):
Git.delete_ref(ref)
def resolve_head(head):
if head.startswith('refs/heads/branches/'):
head = head[20:]
if head[-4:] == '/tip':
return branchmap.tip(unquote(head[:-4]))
return head[-40:]
if head.startswith('refs/heads/bookmarks/'):
head = head[21:]
return bookmarks[unquote(head)]
if head == 'HEAD':
return bookmarks.get('@') or branchmap.tip('default')
return None
wanted_refs = {k: v for k, v in (
(h, resolve_head(h)) for h in refs) if v}
heads = wanted_refs.values()
if not heads:
heads = branchmap.heads()
try:
# Mercurial can be an order of magnitude slower when creating
# a bundle when not giving topological heads, which some of
# the branch heads might not be.
# http://bz.selenic.com/show_bug.cgi?id=4595
# So, when we're pulling all branch heads, just ask for the
# topological heads instead.
# `heads` might contain known heads, if e.g. the remote has
# never been pulled from, but we happen to have some of its
# heads locally already.
if has_unknown_heads:
unknown_heads = branchmap.unknown_heads()
if set(heads).issuperset(unknown_heads):
heads = set(branchmap.heads()) & unknown_heads
store.init_fast_import()
getbundle(repo, store, heads, branchmap.names())
except:
wanted_refs = {}
raise
finally:
for ref, value in wanted_refs.iteritems():
ref = 'refs/cinnabar/' + ref
Git.update_ref(ref, store.changeset_ref(value))
store.close()
helper.write('done\n')
helper.flush()
if remote:
if Git.config('fetch.prune', remote) != 'true':
prune = 'remote.%s.prune' % remote
sys.stderr.write(
'It is recommended that you set "%(conf)s" or '
'"fetch.prune" to "true".\n'
' git config %(conf)s true\n'
'or\n'
' git config fetch.prune true\n'
% {'conf': prune}
)
if store.tag_changes:
sys.stderr.write(
'\nRun the following command to update remote tags:\n')
if remote:
sys.stderr.write(' git remote update %s\n' % remote)
else:
fetch_url = (url if url.startswith('hg://')
else 'hg::' + url)
sys.stderr.write(' git fetch --tags %s\n' % fetch_url)
elif cmd == 'push':
try:
default = 'never' if graft else 'phase'
values = {
None: default,
'': default,
'never': 'never',
'phase': 'phase',
'always': 'always',
}
data = Git.config('cinnabar.data', remote, values=values)
except InvalidConfig as e:
logging.error(e.message)
return 1
refspecs = []
refspecs.extend(args)
while True:
cmd, args = read_cmd(helper)
if not cmd:
break
assert cmd == 'push'
refspecs.extend(args)
pushes = {s.lstrip('+'): (d, s.startswith('+'))
for s, d in (r.split(':', 1) for r in refspecs)}
if isinstance(repo, bundlerepo):
for source, (dest, force) in pushes.iteritems():
helper.write('error %s Cannot push to a bundle file\n'
% dest)
helper.write('\n')
helper.flush()
else:
repo_heads = branchmap.heads()
PushStore.adopt(store, graft)
pushed = push(repo, store, pushes, repo_heads,
branchmap.names())
status = {}
for source, (dest, _) in pushes.iteritems():
if dest.startswith('refs/tags/'):
if source:
status[dest] = 'Pushing tags is unsupported'
else:
status[dest] = \
'Deleting remote tags is unsupported'
continue
if not dest.startswith('refs/heads/bookmarks/'):
if source:
status[dest] = bool(len(pushed))
else:
status[dest] = \
'Deleting remote branches is unsupported'
continue
name = unquote(dest[21:])
if source:
source = store.hg_changeset(Git.resolve_ref(source)) \
or ''
status[dest] = repo.pushkey(
'bookmarks', name, bookmarks.get(name, ''), source)
for source, (dest, force) in pushes.iteritems():
if status[dest] is True:
helper.write('ok %s\n' % dest)
elif status[dest]:
helper.write('error %s %s\n' % (dest, status[dest]))
else:
helper.write('error %s nothing changed on remote\n'
% dest)
helper.write('\n')
helper.flush()
if not pushed:
data = False
elif data == 'always':
data = True
elif data == 'phase':
phases = repo.listkeys('phases')
drafts = {}
if not phases.get('publishing', False):
drafts = set(p for p, is_draft in phases.iteritems()
if int(is_draft))
if not drafts:
data = True
else:
def draft_commits():
for d in drafts:
c = store.changeset_ref(d)
if c:
yield '^%s^@' % c
for h in pushed.heads():
yield h
args = ['rev-list', '--ancestry-path', '--topo-order',
'--stdin']
pushed_drafts = tuple(
Git.iter(*args, stdin=draft_commits()))
# Theoretically, we could have commits with no
# metadata that the remote declares are public, while
# the rest of our push is in a draft state. That is
# however so unlikely that it's not worth the effort
# to support partial metadata storage.
data = not bool(pushed_drafts)
elif data == 'never':
data = False
store.close(rollback=not data)
store.close()
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))