-
Notifications
You must be signed in to change notification settings - Fork 268
/
git_handler.py
1885 lines (1622 loc) · 69.3 KB
/
git_handler.py
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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import collections
import itertools
import os
import re
import shutil
# pyre-fixme[21]: Could not find `_ssh`.
import _ssh
# pyre-fixme[21]: Could not find `compat`.
import compat
# pyre-fixme[21]: Could not find `git2hg`.
import git2hg
# pyre-fixme[21]: Could not find `hg2git`.
import hg2git
# pyre-fixme[21]: Could not find `util`.
import util
# pyre-fixme[21]: Could not find `bindings`.
from bindings import nodemap
from dulwich import client, config as dul_config, diff_tree
from dulwich.errors import GitProtocolError, HangupException
from dulwich.objects import Blob, Commit, Tag, Tree, parse_timezone
from dulwich.pack import apply_delta, create_delta
from dulwich.repo import Repo, check_ref_format
from edenscm.mercurial import (
bookmarks,
commands,
context,
encoding,
error,
phases,
progress,
pycompat,
util as hgutil,
vfs as vfsmod,
)
from edenscm.mercurial.i18n import _
from edenscm.mercurial.node import bin, hex, nullid, nullrev
# pyre-fixme[21]: Could not find `overlay`.
from overlay import overlayrepo
RE_GIT_AUTHOR = re.compile("^(.*?) ?\<(.*?)(?:\>(.*))?$")
RE_GIT_SANITIZE_AUTHOR = re.compile("[<>\n]")
RE_GIT_AUTHOR_EXTRA = re.compile("^(.*?)\ ext:\((.*)\) <(.*)\>$")
RE_GIT_EXTRA_KEY = re.compile("GIT([0-9]*)-(.*)")
# Test for git:// and git+ssh:// URI.
# Support several URL forms, including separating the
# host and path with either a / or : (sepr)
RE_GIT_URI = re.compile(
r"^(?P<scheme>git([+]ssh)?://)(?P<host>.*?)(:(?P<port>\d+))?"
r"(?P<sepr>[:/])(?P<path>.*)$"
)
RE_NEWLINES = re.compile("[\r\n]")
RE_GIT_PROGRESS = re.compile("\((\d+)/(\d+)\)")
RE_AUTHOR_FILE = re.compile("\s*=\s*")
CALLBACK_BUFFER = ""
class GitProgress(object):
"""convert git server progress strings into mercurial progress"""
def __init__(self, ui, prog):
self.ui = ui
self.prog = prog
self.lasttopic = None
self.msgbuf = ""
def progress(self, msg):
# 'Counting objects: 33640, done.\n'
# 'Compressing objects: 0% (1/9955) \r
msgs = RE_NEWLINES.split(self.msgbuf + msg)
self.msgbuf = msgs.pop()
for msg in msgs:
td = msg.split(":", 1)
data = td.pop()
if not td:
self.ui.note(data + "\n")
continue
topic = td[0]
m = RE_GIT_PROGRESS.search(data)
if m:
pos, total = map(int, m.group(1, 2))
if topic != self.lasttopic:
self.prog.reset(topic, total=total)
self.lasttopic = topic
self.prog.value = pos
else:
self.ui.note(msg + "\n")
class GitHandler(object):
map_file = "git-mapfile"
remote_refs_file = "git-remote-refs"
tags_file = "git-tags"
def __init__(self, dest_repo, ui):
self.repo = dest_repo
self.ui = ui
self.vfs = self.repo.sharedvfs
if compat.config(ui, "bool", "git", "intree"):
self.gitdir = self.repo.wvfs.join(".git")
else:
self.gitdir = self.vfs.join("git")
self.init_author_file()
self.paths = ui.configitems("paths")
self.branch_bookmark_suffix = compat.config(
ui, "string", "git", "branch_bookmark_suffix"
)
self._map_real = None
self._map_hg_modifications = set()
self.load_tags()
self._remote_refs = None
@property
def _map(self):
if self._map_real is None:
self.load_map()
return self._map_real
@property
def remote_refs(self):
if self._remote_refs is None:
self.load_remote_refs()
return self._remote_refs
@hgutil.propertycache
def git(self):
# Dulwich is going to try and join unicode ref names against
# the repository path to try and read unpacked refs. This
# doesn't match hg's bytes-only view of filesystems, we just
# have to cope with that. As a workaround, try decoding our
# (bytes) path to the repo in hg's active encoding and hope
# for the best.
gitpath = self.gitdir.decode(encoding.encoding, encoding.encodingmode)
# make the git data directory
if os.path.exists(self.gitdir):
return Repo(gitpath)
else:
# Set disallowinitbare to prevent hggit from creating a .hg/git
# directory. This is useful when the .hg/git directory should be
# managed externally.
if self.ui.configbool("hggit", "disallowinitbare"):
raise error.Abort(_("missing .hg/git repo"))
os.mkdir(self.gitdir)
return Repo.init_bare(gitpath)
def init_author_file(self):
self.author_map = {}
authors_path = compat.config(self.ui, "string", "git", "authors")
if authors_path:
with open(self.repo.wvfs.join(authors_path)) as f:
for line in f:
line = line.strip()
if not line or line.startswith("#"):
continue
from_, to = RE_AUTHOR_FILE.split(line, 2)
self.author_map[from_] = to
# FILE LOAD AND SAVE METHODS
def map_set(self, gitsha, hgsha):
hgnode = bin(hgsha)
self._map.add(bin(gitsha), hgnode)
self._map_hg_modifications.add(hgnode)
def map_hg_get(self, gitsha):
node = self._map.lookupbyfirst(bin(gitsha))
if node is not None:
node = hex(node)
return node
def map_git_get(self, hgsha):
node = self._map.lookupbysecond(bin(hgsha))
if node is not None:
node = hex(node)
return node
def load_map(self):
if self.ui.configbool("hggit", "indexedlognodemap", False):
dir = self.vfs.join(self.map_file + "-log")
# Check for log existance before we instantiate it.
logexists = self.vfs.exists(dir)
self._map_real = nodemap.nodemap(dir)
# If the indexedlog map doesn't exist, populate it.
if not logexists and self.vfs.exists(self.map_file):
# Don't construct
oldmap = GitMap(self.vfs(self.map_file))
for gitsha, hgsha in oldmap.items():
self._map_real.add(gitsha, hgsha)
self._map_real.flush()
else:
content = []
if os.path.exists(self.vfs.join(self.map_file)):
content = self.vfs(self.map_file)
self._map_real = GitMap(content)
def save_map(self, map_file):
wlock = self.repo.wlock()
try:
map = self._map
if self.ui.configbool("hggit", "indexedlognodemap", False):
# If using index log, also write the flat map, so we can roll
# back easily.
self._map_real.flush()
file = self.vfs(map_file, "a+", atomictemp=True)
buf = hgutil.stringio()
bwrite = buf.write
# Append new entries to the end of the file so we can search
# backwards from the end for recently added entries.
for hgnode in self._map_hg_modifications:
gitnode = map.lookupbysecond(hgnode)
if gitnode is None:
raise KeyError(hex(hgnode))
bwrite("%s %s\n" % (hex(gitnode), hex(hgnode)))
self._map_hg_modifications.clear()
file.write(buf.getvalue())
buf.close()
# If this complains, atomictempfile no longer has close
file.close()
finally:
wlock.release()
def load_tags(self):
self.tags = {}
if os.path.exists(self.vfs.join(self.tags_file)):
for line in self.vfs(self.tags_file):
sha, name = line.strip().split(" ", 1)
self.tags[name] = sha
def save_tags(self):
file = self.vfs(self.tags_file, "w+", atomictemp=True)
for name, sha in sorted(self.tags.iteritems()):
if not self.repo.tagtype(name) == "global":
file.write("%s %s\n" % (sha, name))
# If this complains, atomictempfile no longer has close
file.close()
def load_remote_refs(self):
self._remote_refs = {}
refdir = os.path.join(self.git.path, "refs", "remotes")
paths = self.paths
# if paths are set, we should still check 'default'
if not paths:
paths = [("default", None)]
# we avoid using dulwich's refs method because it is incredibly slow;
# on a repo with a few hundred branches and a few thousand tags,
# dulwich took about 200ms
for p in paths:
remotedir = os.path.join(refdir, p[0])
for root, dirs, files in os.walk(remotedir):
for f in files:
try:
ref = root.replace(refdir + pycompat.ossep, "") + "/"
node = open(os.path.join(root, f)).read().strip()
hgsha = self._map.lookupbyfirst(bin(node))
if hgsha is None:
raise KeyError(hex(node))
self._remote_refs[ref + f] = hgsha
except (KeyError, IOError):
pass
# END FILE LOAD AND SAVE METHODS
# COMMANDS METHODS
def import_commits(self, remote_name):
refs = self.git.refs.as_dict()
filteredrefs = self.filter_min_date(refs)
self.import_git_objects(remote_name, filteredrefs)
self.update_hg_bookmarks(refs)
self.save_map(self.map_file)
def fetch(self, remote, heads):
refs = self.fetch_pack(remote, heads)
remote_name = self.remote_name(remote)
# if remote returns a symref for HEAD, then let's store that
rhead = None
rnode = None
oldheads = self.repo.heads()
imported = 0
if refs:
filteredrefs = self.filter_min_date(self.filter_refs(refs, heads))
imported = self.import_git_objects(remote_name, filteredrefs)
self.import_tags(refs)
self.update_hg_bookmarks(refs)
try:
symref = refs["HEAD"]
if symref.startswith("refs/heads"):
rhead = symref.replace("refs/heads/", "")
rnode = refs["refs/heads/%s" % rhead]
hgrnode = self._map.lookupbyfirst(bin(rnode))
if hgrnode is None:
raise KeyError(rnode)
rnode = self.repo[hgrnode].node()
except KeyError:
# if there is any error make sure to clear the variables
rhead = None
rnode = None
if remote_name:
self.update_remote_branches(remote_name, refs)
elif not self.paths:
# intial cloning
self.update_remote_branches("default", refs)
# "Activate" a tipmost bookmark.
bms = self.repo["tip"].bookmarks()
# override the 'tipmost' behavior if we know the remote HEAD
if rnode:
# make sure the bookmark exists; at the point the remote
# branches has already been set up
suffix = self.branch_bookmark_suffix or ""
changes = [(rhead + suffix, rnode)]
util.updatebookmarks(self.repo, changes)
bms = [rhead + suffix]
if bms:
try:
bookmarks.activate(self.repo, bms[0])
except AttributeError:
# hg < 3.5
bookmarks.setcurrent(self.repo, bms[0])
self.save_map(self.map_file)
# also mark public any branches the user specified
blist = [
self.repo[branch].node() for branch in self.ui.configlist("git", "public")
]
if rnode and self.ui.configbool("hggit", "usephases"):
blist.append(rnode)
if blist:
lock = self.repo.lock()
try:
tr = self.repo.transaction("phase")
try:
phases.advanceboundary(self.repo, tr, phases.public, blist)
except TypeError:
# hg < 3.2
phases.advanceboundary(self.repo, phases.public, blist)
tr.close()
finally:
if tr is not None:
tr.release()
lock.release()
if imported == 0:
return 0
# code taken from localrepo.py:addchangegroup
dh = 0
if oldheads:
heads = self.repo.heads()
dh = len(heads) - len(oldheads)
for h in heads:
if h not in oldheads and self.repo[h].closesbranch():
dh -= 1
if dh < 0:
return dh - 1
else:
return dh + 1
def export_commits(self):
try:
self.export_git_objects()
self.export_hg_tags()
self.update_references()
finally:
self.save_map(self.map_file)
def get_refs(self, remote):
self.export_commits()
client, path = self.get_transport_and_path(remote)
old_refs = {}
new_refs = {}
def changed(refs):
old_refs.update(refs)
exportable = self.get_exportable()
new_refs.update(self.get_changed_refs(refs, exportable, True))
return refs # always return the same refs to make the send a no-op
try:
client.send_pack(path, changed, lambda have, want: [])
changed_refs = [
ref for ref, sha in new_refs.iteritems() if sha != old_refs.get(ref)
]
new = [bin(self.map_hg_get(new_refs[ref])) for ref in changed_refs]
old = {}
for r in old_refs:
old_ref = self.map_hg_get(old_refs[r])
if old_ref:
old[bin(old_ref)] = 1
return old, new
except (HangupException, GitProtocolError) as e:
raise error.Abort(_("git remote error: ") + str(e))
def push(self, remote, revs, force):
self.export_commits()
old_refs, new_refs = self.upload_pack(remote, revs, force)
remote_name = self.remote_name(remote)
if remote_name and new_refs:
for ref, new_sha in sorted(new_refs.iteritems()):
old_sha = old_refs.get(ref)
if old_sha is None:
if self.ui.verbose:
self.ui.note(
_("adding reference %s::%s => GIT:%s\n")
% (remote_name, ref, new_sha[0:8])
)
else:
self.ui.status(_("adding reference %s\n") % ref)
elif new_sha != old_sha:
if self.ui.verbose:
self.ui.note(
_("updating reference %s::%s => GIT:%s\n")
% (remote_name, ref, new_sha[0:8])
)
else:
self.ui.status(_("updating reference %s\n") % ref)
else:
self.ui.debug(
"unchanged reference %s::%s => GIT:%s\n"
% (remote_name, ref, new_sha[0:8])
)
self.update_remote_branches(remote_name, new_refs)
if old_refs == new_refs:
self.ui.status(_("no changes found\n"))
ret = None
elif len(new_refs) > len(old_refs):
ret = 1 + (len(new_refs) - len(old_refs))
elif len(old_refs) > len(new_refs):
ret = -1 - (len(new_refs) - len(old_refs))
else:
ret = 1
return ret
def clear(self):
mapfile = self.vfs.join(self.map_file)
if self.ui.configbool("hggit", "indexedlognodemap", False):
shutil.rmtree(mapfile + "-log")
if os.path.exists(self.gitdir):
for root, dirs, files in os.walk(self.gitdir, topdown=False):
for name in files:
os.remove(os.path.join(root, name))
for name in dirs:
os.rmdir(os.path.join(root, name))
os.rmdir(self.gitdir)
if os.path.exists(mapfile):
os.remove(mapfile)
# incoming support
def getremotechanges(self, remote, revs):
self.export_commits()
refs = self.fetch_pack(remote.path, revs)
# refs contains all remote refs. Prune to only those requested.
if revs:
reqrefs = {}
for rev in revs:
for n in ("refs/heads/" + rev, "refs/tags/" + rev):
if n in refs:
reqrefs[n] = refs[n]
else:
reqrefs = refs
commits = [bin(c) for c in self.get_git_incoming(reqrefs).commits]
b = overlayrepo(self, commits, refs)
return (b, commits, lambda: None)
# CHANGESET CONVERSION METHODS
def export_git_objects(self):
self.ui.note(_("finding hg commits to export\n"))
repo = self.repo
clnode = repo.changelog.node
clparents = repo.changelog.parentrevs
# Starting at the heads, walk back and find any commits that aren't in
# the git/hg mapping.
pending = []
if len(repo) > 0:
# repo.heads() returns the nullrev in an empty repo
pending = list(repo.headrevs())
exportrevs = set()
while pending:
rev = pending.pop()
node = clnode(rev)
if self._map.lookupbysecond(node) is None:
exportrevs.add(rev)
for parentrev in clparents(rev):
if parentrev != nullrev and parentrev not in exportrevs:
pending.append(parentrev)
# Sorting here is important, because the below code expects to process
# these in topological order.
to_export = list(repo[r] for r in sorted(exportrevs))
todo_total = len(exportrevs)
pos = 0
export = []
with progress.bar(
repo.ui, "find commits to export", "commits", todo_total
) as prog:
for ctx in to_export:
item = hex(ctx.node())
pos += 1
prog.value = (pos, item)
if ctx.extra().get("hg-git", None) != "octopus":
export.append(ctx)
total = len(export)
if not total:
return
self.ui.note(_("exporting hg objects to git\n"))
# By only exporting deltas, the assertion is that all previous objects
# for all other changesets are already present in the Git repository.
# This assertion is necessary to prevent redundant work. Here, nodes,
# and therefore export, is in topological order. By definition,
# export[0]'s parents must be present in Git, so we start the
# incremental exporter from there.
pctx = export[0].p1()
pnode = pctx.node()
if pnode == nullid:
gitcommit = None
else:
gitnode = self._map.lookupbysecond(pnode)
if gitnode is None:
raise KeyError(hex(pnode))
gitsha = hex(gitnode)
try:
gitcommit = self.git[gitsha]
except KeyError:
raise error.Abort(
_("Parent SHA-1 not present in Git " "repo: %s") % gitsha
)
exporter = hg2git.IncrementalChangesetExporter(
self.repo, pctx, self.git.object_store, gitcommit
)
mapsavefreq = compat.config(self.ui, "int", "hggit", "mapsavefrequency")
with progress.bar(self.ui, _("exporting"), total=total) as prog:
for i, ctx in enumerate(export):
prog.value = i
self.export_hg_commit(ctx.node(), exporter)
if mapsavefreq and i % mapsavefreq == 0:
self.ui.debug("saving mapfile\n")
self.save_map(self.map_file)
def set_commiter_from_author(self, commit):
commit.committer = commit.author
commit.commit_time = commit.author_time
commit.commit_timezone = commit.author_timezone
# convert this commit into git objects
# go through the manifest, convert all blobs/trees we don't have
# write the commit object (with metadata info)
def export_hg_commit(self, rev, exporter):
self.ui.note(_("converting revision %s\n") % hex(rev))
oldenc = self.swap_out_encoding()
ctx = self.repo.changectx(rev)
extra = ctx.extra()
commit = Commit()
(time, timezone) = ctx.date()
# work around to bad timezone offets - dulwich does not handle
# sub minute based timezones. In the one known case, it was a
# manual edit that led to the unusual value. Based on that,
# there is no reason to round one way or the other, so do the
# simplest and round down.
timezone -= timezone % 60
commit.author = self.get_git_author(ctx)
commit.author_time = int(time)
commit.author_timezone = -timezone
if "committer" in extra:
try:
# fixup timezone
(name, timestamp, timezone) = extra["committer"].rsplit(" ", 2)
commit.committer = name
commit.commit_time = timestamp
# work around a timezone format change
if int(timezone) % 60 != 0: # pragma: no cover
timezone = parse_timezone(timezone)
# Newer versions of Dulwich return a tuple here
if isinstance(timezone, tuple):
timezone, neg_utc = timezone
commit._commit_timezone_neg_utc = neg_utc
else:
timezone = -int(timezone)
commit.commit_timezone = timezone
except Exception: # extra is essentially user-supplied; be careful
self.set_commiter_from_author(commit)
else:
self.set_commiter_from_author(commit)
commit.parents = []
for parent in self.get_git_parents(ctx):
hgsha = hex(parent.node())
git_sha = self.map_git_get(hgsha)
if git_sha:
if git_sha not in self.git.object_store:
raise error.Abort(
_("Parent SHA-1 not present in Git " "repo: %s") % git_sha
)
commit.parents.append(git_sha)
commit.message, extra = self.get_git_message_and_extra(ctx)
commit.extra.extend(extra)
if "encoding" in extra:
commit.encoding = extra["encoding"]
for obj, nodeid in exporter.update_changeset(ctx):
# In theory we should check if the object exists before adding it,
# but in practice it's unlikely to exist, and scanning all the packs
# to determine that is expensive.
self.git.object_store.add_object(obj)
tree_sha = exporter.root_tree_sha
if tree_sha not in self.git.object_store:
raise error.Abort(_("Tree SHA-1 not present in Git repo: %s") % tree_sha)
commit.tree = tree_sha
if commit.id not in self.git.object_store:
self.git.object_store.add_object(commit)
self.map_set(commit.id, ctx.hex())
self.swap_out_encoding(oldenc)
return commit.id
def get_valid_git_username_email(self, name):
r"""Sanitize usernames and emails to fit git's restrictions.
The following is taken from the man page of git's fast-import
command:
[...] Likewise LF means one (and only one) linefeed [...]
committer
The committer command indicates who made this commit,
and when they made it.
Here <name> is the person's display name (for example
"Com M Itter") and <email> is the person's email address
("cm@example.com[1]"). LT and GT are the literal
less-than (\x3c) and greater-than (\x3e) symbols. These
are required to delimit the email address from the other
fields in the line. Note that <name> and <email> are
free-form and may contain any sequence of bytes, except
LT, GT and LF. <name> is typically UTF-8 encoded.
Accordingly, this function makes sure that there are none of the
characters <, >, or \n in any string which will be used for
a git username or email. Before this, it first removes left
angle brackets and spaces from the beginning, and right angle
brackets and spaces from the end, of this string, to convert
such things as " <john@doe.com> " to "john@doe.com" for
convenience.
TESTS:
>>> from collections import namedtuple
>>> from edenscm.mercurial.ui import ui
>>> mockrepo = namedtuple('localrepo', ['sharedvfs'])
>>> mockrepo.sharedvfs = ''
>>> g = GitHandler(mockrepo, ui()).get_valid_git_username_email
>>> g('John Doe')
'John Doe'
>>> g('john@doe.com')
'john@doe.com'
>>> g(' <john@doe.com> ')
'john@doe.com'
>>> g(' <random<\n<garbage\n> > > ')
'random???garbage?'
>>> g('Typo in hgrc >but.hg-git@handles.it.gracefully>')
'Typo in hgrc ?but.hg-git@handles.it.gracefully'
"""
return RE_GIT_SANITIZE_AUTHOR.sub("?", name.lstrip("< ").rstrip("> "))
def get_git_author(self, ctx):
# hg authors might not have emails
author = ctx.user()
# see if a translation exists
author = self.author_map.get(author, author)
# check for git author pattern compliance
a = RE_GIT_AUTHOR.match(author)
if a:
name = self.get_valid_git_username_email(a.group(1))
email = self.get_valid_git_username_email(a.group(2))
if a.group(3) is not None and len(a.group(3)) != 0:
name += " ext:(" + hgutil.urlreq.quote(a.group(3)) + ")"
author = "%s <%s>" % (
self.get_valid_git_username_email(name),
self.get_valid_git_username_email(email),
)
elif "@" in author:
author = "%s <%s>" % (
self.get_valid_git_username_email(author),
self.get_valid_git_username_email(author),
)
else:
author = self.get_valid_git_username_email(author) + " <none@none>"
if "author" in ctx.extra():
author = "".join(apply_delta(author, ctx.extra()["author"]))
return author
def get_git_parents(self, ctx):
def is_octopus_part(ctx):
olist = ("octopus", "octopus-done")
return ctx.extra().get("hg-git", None) in olist
parents = []
if ctx.extra().get("hg-git", None) == "octopus-done":
# implode octopus parents
part = ctx
while is_octopus_part(part):
(p1, p2) = part.parents()
assert ctx.extra().get("hg-git", None) != "octopus"
parents.append(p1)
part = p2
parents.append(p2)
else:
parents = ctx.parents()
return parents
def get_git_message_and_extra(self, ctx):
extra = ctx.extra()
message = ctx.description() + "\n"
if "message" in extra:
message = "".join(apply_delta(message, extra["message"]))
# HG EXTRA INFORMATION
# test only -- do not document this!
extra_in_message = compat.config(self.ui, "bool", "git", "debugextrainmessage")
extra_message = ""
git_extra = []
if ctx.branch() != "default":
# we always store the branch in the extra message
extra_message += "branch : " + ctx.branch() + "\n"
# Git native extra items always come first, followed by hg renames,
# followed by hg extra keys
git_extraitems = []
for key, value in extra.items():
m = RE_GIT_EXTRA_KEY.match(key)
if m is not None:
git_extraitems.append((int(m.group(1)), m.group(2), value))
del extra[key]
git_extraitems.sort()
for i, field, value in git_extraitems:
git_extra.append(
(hgutil.urlreq.unquote(field), hgutil.urlreq.unquote(value))
)
if extra.get("hg-git-rename-source", None) != "git":
renames = []
for f in ctx.files():
if f not in ctx.manifest():
continue
rename = ctx.filectx(f).renamed()
if rename:
renames.append((rename[0], f))
if renames:
for oldfile, newfile in renames:
if extra_in_message:
extra_message += "rename : " + oldfile + " => " + newfile + "\n"
else:
spec = "%s:%s" % (
hgutil.urlreq.quote(oldfile),
hgutil.urlreq.quote(newfile),
)
git_extra.append(("HG:rename", spec))
# hg extra items always go at the end
extraitems = extra.items()
extraitems.sort()
for key, value in extraitems:
if key in (
"author",
"committer",
"encoding",
"message",
"branch",
"hg-git",
"hg-git-rename-source",
):
continue
else:
if extra_in_message:
extra_message += (
"extra : " + key + " : " + hgutil.urlreq.quote(value) + "\n"
)
else:
spec = "%s:%s" % (
hgutil.urlreq.quote(key),
hgutil.urlreq.quote(value),
)
git_extra.append(("HG:extra", spec))
if extra_message:
message += "\n--HG--\n" + extra_message
if (
extra.get("hg-git-rename-source", None) != "git"
and not extra_in_message
and not git_extra
and extra_message == ""
):
# We need to store this if no other metadata is stored. This
# indicates that when reimporting the commit into Mercurial we'll
# know not to detect renames.
git_extra.append(("HG:rename-source", "hg"))
return message, git_extra
def get_git_incoming(self, refs):
return git2hg.find_incoming(self.git.object_store, self._map, refs)
def import_git_objects(self, remote_name, refs):
result = self.get_git_incoming(refs)
commits = result.commits
commit_cache = result.commit_cache
# import each of the commits, oldest first
total = len(commits)
if total:
self.ui.status(_("importing git objects into hg\n"))
else:
self.ui.status(_("no changes found\n"))
mapsavefreq = compat.config(self.ui, "int", "hggit", "mapsavefrequency")
with progress.bar(self.ui, _("importing"), "commits", total=total) as prog:
icommits = enumerate(commits)
while True:
isubcommits = list(itertools.islice(icommits, mapsavefreq or 1))
if not isubcommits:
break
with self.repo.transaction("git import"):
for i, csha in isubcommits:
prog.value = i
commit = commit_cache[csha]
self.import_git_commit(commit)
self.ui.debug("committing transaction\n")
if mapsavefreq:
self.ui.debug("saving mapfile\n")
self.save_map(self.map_file)
# TODO if the tags cache is used, remove any dangling tag references
return total
def import_git_commit(self, commit):
self.ui.debug("importing: %s\n" % commit.id)
detect_renames = False
(strip_message, hg_renames, hg_branch, extra) = git2hg.extract_hg_metadata(
commit.message, commit.extra
)
# Store the original git commit hash in the Mercurial extras. This
# breaks bidirectionality, but makes it possible for a Mercurial client
# to compute the git/hg mapping without having the entire git repo.
# "convert_revision" was chosen to match the hgsubversion and hg convert
# extra field.
extra["convert_revision"] = commit.id
if hg_renames is None:
detect_renames = True
# We have to store this unconditionally, even if there are no
# renames detected from Git. This is because we export an extra
# 'HG:rename-source' Git parameter when this isn't set, which will
# break bidirectionality.
extra["hg-git-rename-source"] = "git"
else:
renames = hg_renames
gparents = map(self.map_hg_get, commit.parents)
for parent in gparents:
if parent not in self.repo:
raise error.Abort(
_("you appear to have run strip - " "please run hg git-cleanup")
)
# get a list of the changed, added, removed files and gitlinks
files, gitlinks, git_renames = self.get_files_changed(commit, detect_renames)
if detect_renames:
renames = git_renames
date = (commit.author_time, -commit.author_timezone)
text = strip_message
origtext = text
try:
text.decode("utf-8")
except UnicodeDecodeError:
text = self.decode_guess(text, commit.encoding)
text = "\n".join([l.rstrip() for l in text.splitlines()]).strip("\n")
if text + "\n" != origtext:
extra["message"] = create_delta(text + "\n", origtext)
author = commit.author
# convert extra data back to the end
if " ext:" in commit.author:
m = RE_GIT_AUTHOR_EXTRA.match(commit.author)
if m:
name = m.group(1)
ex = hgutil.urlreq.unquote(m.group(2))
email = m.group(3)
author = name + " <" + email + ">" + ex
if " <none@none>" in commit.author:
author = commit.author[:-12]
try:
author.decode("utf-8")
except UnicodeDecodeError:
origauthor = author
author = self.decode_guess(author, commit.encoding)
extra["author"] = create_delta(author, origauthor)
oldenc = self.swap_out_encoding()
def findconvergedfiles(p1, p2):
# If any files have the same contents in both parents of a merge
# (and are therefore not reported as changed by Git) but are at
# different file revisions in Mercurial (because they arrived at
# those contents in different ways), we need to include them in
# the list of changed files so that Mercurial can join up their
# filelog histories (same as if the merge was done in Mercurial to
# begin with).
if p2 == nullid:
return []
manifest1 = self.repo.changectx(p1).manifest()
manifest2 = self.repo.changectx(p2).manifest()
return [