-
Notifications
You must be signed in to change notification settings - Fork 2
/
git_darcs.py
998 lines (863 loc) · 26.5 KB
/
git_darcs.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
"""Incremental import of git into darcs."""
import os
import sys
import xml.etree.ElementTree as ET
from collections import OrderedDict
from contextlib import contextmanager
from datetime import datetime
from pathlib import Path
from shutil import copy, rmtree
from subprocess import DEVNULL, PIPE, CalledProcessError
from subprocess import Popen as SPOpen
from subprocess import run as srun
from threading import Thread
from time import sleep
import click
from click import ClickException
from colorama import Fore, Style, init
from readchar import readkey
from tqdm import tqdm
_large = False
_uuid = "_b531990e-3187-4b52-be1f-6e4d4d1e40c9"
_darcs_comment = Path("_darcs", _uuid)
_env_comment = {"EDITOR": f"mv {_darcs_comment}", "VISUAL": f"mv {_darcs_comment}"}
_isatty = sys.stdout.isatty()
_verbose = False
_devnull = DEVNULL
_disable = None
_shutdown = False
_darcs_date = "%Y%m%d%H%M%S"
_pull_question = "Shall I pull this patch"
_pull_help = """
y: pull this patch
n: don't pull it
w: decide later
a: pull all remaining patches
i: don't pull remaining patches
l: show full log message
f: show full patch
?: help
h: help
c: cancel without pulling
q: cancel without pulling
"""
_boring = """
# git
(^|/)\\.git($|/)
# darcs
(^|/)_darcs($|/)
"""
_gitignore = "/_darcs"
def handle_shutdown():
"""Wait for CTRL-D and set _shutdown, to flag a graceful shutdown request."""
global _shutdown
print("Use CTRL-D for a graceful shutdown.")
sys.stdin.read()
print("Shutting down, use CTRL-C if shutdown takes too long.")
print("If you use CTRL-C changes might be recorded twice.")
_shutdown = True
def args_print(args):
"""Print args of executed command."""
if _verbose:
args = [str(x) for x in args]
args = " ".join(args)
print(f"\n$ {args}")
class Popen(SPOpen):
"""Inject defaults into Popen."""
def __init__(self, *args, stderr=None, stdin=None, **kwargs):
"""Inject default into Popen."""
args_print(args[0])
if not stderr:
stderr = _devnull
if not stdin and "input" not in kwargs:
stdin = _devnull
super().__init__(*args, stderr=stderr, stdin=stdin, **kwargs)
def run(*args, stdout=None, stderr=None, stdin=None, **kwargs):
"""Inject defaults into run."""
args_print(args[0])
if not stdout:
stdout = _devnull
if not stderr:
stderr = _devnull
if not stdin and "input" not in kwargs:
stdin = _devnull
return srun(*args, stdout=stdout, stderr=stderr, stdin=stdin, **kwargs)
def hasnew():
"""Revert recorded changes in darcs."""
try:
run(["darcs", "whatsnew"], check=True)
except CalledProcessError:
return False
return True
def revert():
"""Revert recorded changes in darcs."""
run(["darcs", "revert", "--no-interactive"])
def initialize():
"""Initialize darcs."""
run(["darcs", "initialize"], check=True)
def relink():
"""Relink darcs-repo, this is a bit of cargo-cult."""
run(["darcs", "optimize", "relink"], check=True)
def optimize():
"""Optimize darcs-repo, this is a bit of a cargo-cult."""
run(["darcs", "optimize", "clean"], check=True)
run(["darcs", "optimize", "compress"], check=True)
run(["darcs", "optimize", "pristine"], check=True)
def move(orig, new):
"""Move a file in the darcs-repo."""
porig = Path(orig)
if (porig.is_file() or porig.is_dir()) and not porig.is_symlink():
dir = Path(new).parent
dir.mkdir(parents=True, exist_ok=True)
darcs_add(dir)
run(
["darcs", "move", "--case-ok", "--reserved-ok", orig, new],
check=True,
)
def darcs_add(path):
"""Add a path to the darcs-repo."""
try:
run(
["darcs", "add", "--case-ok", "--reserved-ok", str(path)],
stderr=PIPE,
check=True,
)
except CalledProcessError as e:
if "No files were added" not in e.stderr.decode("UTF-8"):
raise
def tag(name):
"""Tag a state in the darcs-repo."""
run(
["darcs", "tag", "--skip-long-comment", "--name", name],
check=True,
input=b"\n",
)
def get_tags():
"""Get tags from darcs."""
res = run(
["darcs", "show", "tags"],
check=True,
stdout=PIPE,
)
return res.stdout.decode("UTF-8").strip().splitlines()
def darcs_clone(source, destination):
"""Clone darcs-repo."""
run(
["darcs", "clone", source, destination],
check=True,
)
def get_patches(source, args):
"""Get patches from darcs."""
res = run(
["darcs", "pull", "--dry-run", "--xml-output"] + args + [source],
stdout=PIPE,
check=True,
)
res = res.stdout.decode("UTF-8").strip()
if res.startswith("No remote patches to pull in!"):
return ET.fromstring("<root></root>")
else:
return ET.fromstring(res)
def show_full_patch(source, patch):
"""Show full patch with darcs."""
run(
["darcs", "log", "-i", "--repodir", source, "-h", patch],
stdout=sys.stdout,
stderr=sys.stderr,
input=b"y",
check=True,
)
def pull_patch(source, hash):
"""Pull a darcs-patch."""
run(
[
"darcs",
"pull",
"--no-interactive",
"--no-set-default",
source,
"-h",
hash,
],
check=True,
)
def git_add(args=None):
"""Add changes to git."""
if args is None:
run(["git", "add", "."], check=True)
else:
run(["git", "add"] + args, check=True)
def git_commit(message):
"""Git commit."""
run(["git", "commit", "--allow-empty", "-m", message], check=True)
def git_clone(source, destination):
"""Clone git-repo."""
run(["git", "clone", source, destination], check=True)
def wipe():
"""Completely clean the git-repo except `_darcs`."""
run(
["git", "reset"],
check=True,
)
run(
["git", "clean", "-xdf", "--exclude", "/_darcs"],
check=True,
)
def checkout(rev):
"""Checkout a git-commit."""
if _large:
sleep(0.01) # Make sure timestamps differ
run(
["git", "checkout", rev],
check=True,
)
def is_ancestor(rev, last):
"""Check if revisiion can fast-forward."""
# I don't know why git thinks revs are their own ancestor
if rev == last:
return False
try:
run(["git", "merge-base", "--is-ancestor", last, rev], check=True)
return True
except CalledProcessError:
return False
def get_current_branch():
"""Get the current branch from git."""
res = run(
["git", "branch", "--show-current"],
stdout=PIPE,
check=True,
)
branch = res.stdout.decode("UTF-8").strip()
if _verbose:
print(branch)
return branch
def author(rev):
"""Get the author of a commit from git."""
res = run(
["git", "log", "--pretty=format:%cN <%cE>", "--max-count=1", rev],
stdout=PIPE,
check=True,
)
msg = res.stdout.decode("UTF-8").strip()
if _verbose:
print(msg)
return msg
def onelines(rev, *, last=None, merges=False):
"""Get the short-message of a commit from git."""
if last:
cmd = [
"git",
"log",
"--oneline",
"--no-decorate",
"--date-order",
]
if merges:
cmd += ["--no-merges"]
cmd += (f"{last}..{rev}",)
res = run(cmd, stdout=PIPE, check=True)
else:
res = run(
["git", "log", "--oneline", "--no-decorate", "--max-count=1", rev],
stdout=PIPE,
check=True,
)
msg = res.stdout.decode("UTF-8").strip()
if _verbose:
print(msg)
return msg.splitlines()
def get_head():
"""Get the current head from git."""
res = run(
["git", "rev-parse", "HEAD"],
check=True,
stdout=PIPE,
)
head = res.stdout.strip().decode("UTF-8")
if _verbose:
print(head)
return head
def record_all(rev, *, last=None, postfix=None, comments=None):
"""Record all change onto the darcs-repo."""
assert rev != last
msgs = onelines(rev, last=last, merges=False)
if not msgs:
msgs = onelines(rev, last=last, merges=True)
msg = msgs[0]
comments = "\n".join(msgs[1:])
by = author(rev)
if postfix:
msg = f"{msg} {postfix}"
elif comments:
msg = f"{msg}\n\n{comments}"
with _darcs_comment.open("w", encoding="UTF-8") as f:
f.write(msg)
try:
env = dict(os.environ)
env.update(_env_comment)
if _large:
ignore_times = []
else:
ignore_times = ["--ignore-times"]
res = run(
[
"darcs",
"record",
"--look-for-adds",
"--no-interactive",
]
+ ignore_times
+ [
"--edit-long-comment",
"--author",
by,
"--name",
"",
],
check=True,
stdout=PIPE,
env=env,
)
if _verbose:
print(res.stdout.decode("UTF-8").strip())
except CalledProcessError as e:
if "No changes!" not in e.stdout.decode("UTF-8"):
raise
def get_rev_list_cmd(head, base, merges=False):
"""Create the cmd to linearized path from git."""
cmd = [
"git",
"rev-list",
"--reverse",
"--topo-order",
"--ancestry-path",
]
if not merges:
cmd += ["--no-merges"]
cmd += [f"{base}..{head}"]
return cmd
def get_rev_list(head, base):
"""Get a linearized path from base to head from git."""
with Popen(
get_rev_list_cmd(head, base, merges=False),
stdout=PIPE,
) as res:
while line := res.stdout.readline():
yield line.decode("UTF-8").strip()
else:
with Popen(
get_rev_list_cmd(head, base, merges=True),
stdout=PIPE,
) as res:
while line := res.stdout.readline():
yield line.decode("UTF-8").strip()
def get_base():
"""Get the root/base commit from git."""
base = (
run(
["git", "rev-list", "--max-parents=0", "HEAD"],
check=True,
stdout=PIPE,
)
.stdout.strip()
.decode("UTF-8")
.splitlines()[-1]
)
if _verbose:
print(base)
return base
class RenameDiffState:
"""State-machine for the rename parser."""
INIT = 1
IN_DIFF = 2
ORIG_FOUND = 3
def get_rename_diff(rev, *, last=None):
"""Request the renames of a commit from git."""
assert last != rev
if last is None:
action = "show"
range = rev
else:
action = "diff"
range = f"{last}..{rev}"
with Popen(
["git", action, "--diff-filter=R", range],
stdout=PIPE,
) as res:
while line := res.stdout.readline():
yield line.decode("UTF-8").strip()
def get_renames(rev, *, last=None):
"""Parse the renames from a git-rename-diff."""
s = RenameDiffState
state = s.INIT
orig = ""
new = ""
for line in get_rename_diff(rev, last=last):
if state == s.INIT:
if line.startswith("diff --git"):
state = s.IN_DIFF
elif state == s.IN_DIFF:
start = "rename from "
if line.startswith(start):
_, _, orig = line.partition(start)
orig = orig.strip()
state = s.ORIG_FOUND
elif state == s.ORIG_FOUND:
start = "rename to "
if line.startswith(start):
_, _, new = line.partition(start)
yield (orig, new)
state = s.IN_DIFF
def record_revision(rev, *, last=None):
"""Record a revision, pre-record moves if there are any."""
iters = 0
count = 0
renames = 0
for _ in get_renames(rev, last=last):
renames += 1
if renames:
with tqdm(desc="moves", total=renames, leave=False, disable=_disable) as pbar:
for orig, new in get_renames(rev, last=last):
move(orig, new)
iters += 1
if iters % 50 == 0:
record_all(rev, postfix=f"move({count:03d})")
count += 1
pbar.update()
wipe()
checkout(rev)
record_all(rev, last=last)
def get_lastest_rev():
"""Get the latest git-commit recorded in darcs."""
res = []
start = "git-checkpoint "
for tag in get_tags():
if tag.startswith(start):
res.append(tag)
if len(res) > 0:
_, _, hash = sorted(res)[-1].partition(start)
return hash.split(" ")[1]
return None
def checkpoint(rev):
"""Tag/checkpoint the current git-commit."""
date = datetime.now().strftime("%Y-%m-%dT%H:%M:%S.%f%z")
tag(f"git-checkpoint {date} {rev}")
def warning():
"""Print a warning that git-darcs is going to wipe uncommitted change."""
print("Use git-darcs on an extra tracking-repository.")
print("git-darcs WILL CLEAR ALL YOUR WORK THAT IS NOT COMMITED!")
print("Use -nw to skip this warning.\n")
print("Press enter to continue")
sys.stdin.readline()
@contextmanager
def less_boring():
"""Replace boring with one that only ignores `.git` and `_darcs`."""
bfile = Path("_darcs/prefs/boring")
disable = Path(bfile.parent, "not_boring")
bfile.rename(disable)
with bfile.open("w", encoding="UTF-8") as f:
f.write(_boring)
yield
bfile.unlink()
disable.rename(bfile)
@contextmanager
def ignore_darcs():
"""Replace .gitignore with one that ignores `_darcs`."""
bfile = Path(".gitignore")
old = None
if bfile.exists():
with bfile.open("rb") as f:
old = f.read()
bfile.unlink()
with bfile.open("w", encoding="UTF-8") as f:
f.write(_gitignore)
yield
bfile.unlink()
if old:
with bfile.open("wb") as f:
f.write(old)
git_add([".gitignore"])
def transfer(gen, count, *, last=None):
"""Transfer the git-commits to darcs."""
try:
with tqdm(desc="commits", total=count, disable=_disable) as pbar:
records = 0
for rev in gen:
# Check if fast-forward is possible
if is_ancestor(rev, last):
record_revision(rev, last=last)
last = rev
records += 1
if records % 100 == 0:
checkpoint(last)
pbar.update()
if _shutdown:
sys.exit(0)
except Exception:
print(f"Failed on revision {last}")
raise
return last
def import_range(rbase, *, from_checkpoint=False):
"""Run the transfer to darcs."""
rhead = get_head()
if rbase == rhead:
return
count = 0
for _ in get_rev_list(rhead, rbase):
count += 1
if count == 0:
return
gen = get_rev_list(rhead, rbase)
wipe()
checkout(rbase)
with less_boring():
try:
last = rbase
if not from_checkpoint:
record_all(rbase)
last = transfer(gen, count, last=last)
if last != rhead:
checkout(rhead)
record_all(rhead)
finally:
checkpoint(rhead)
optimize()
def import_one():
"""Import current revisiion."""
head = get_head()
wipe()
checkout(head)
record_all(head)
checkpoint(head)
optimize()
def fix_pwd():
"""Fix pwd if GIT_DARCS_PWD is given."""
pwd = os.environ.get("GIT_DARCS_PWD")
if pwd:
os.chdir(pwd)
def setup(warn, verbose):
"""Set verbose and warn up."""
global _verbose
global _devnull
global _disable
if warn:
warning()
_verbose = verbose
if verbose:
_devnull = None
_disable = True
def prepare_update(base, shallow):
"""Check repo, arguments, find base and setup shutdown."""
if not Path(".git").exists():
raise ClickException("Please run git-darcs in the root of your git-repo.")
if not Path("_darcs").exists():
initialize()
rbase = get_lastest_rev()
from_checkpoint = False
if rbase:
from_checkpoint = True
do_one = False
if base:
print("Found git-checkpoint, ignoring base-option")
if shallow is True:
print("Found git-checkpoint, ignoring shallow-option")
else:
do_one = True
if base:
do_one = False
rbase = base
if shallow is True:
print("Found base-option, ignoring shallow-option")
if shallow is False:
do_one = False
rbase = get_base()
if _isatty:
_thread = Thread(target=handle_shutdown, daemon=True)
_thread.start()
return rbase, from_checkpoint, do_one
def run_update(rbase, from_checkpoint, do_one):
"""Run conversion loop."""
branch = get_current_branch()
failed = True
try:
try:
checkout(".")
except CalledProcessError:
pass
if do_one:
import_one()
else:
import_range(rbase, from_checkpoint=from_checkpoint)
failed = False
finally:
if branch:
if failed and _verbose:
print(f"Not restoring to `{branch}` in verbose-mode failure.")
else:
wipe()
checkout(branch)
def ask(question, choice, *, text="", state="", help=""):
"""Ask a question on the terminal."""
key = "?"
if text:
print(text)
while key in ("h", "?"):
sys.stdout.write(f"{question}? {state} [{choice}], or ? for more options: ")
sys.stdout.flush()
key = readkey()
print(key)
if key in ("h", "?"):
print(help)
return key
class Patch:
"""Represents a darcs-patch."""
def __init__(self, source, patch):
"""Dear flake8 this is a init function."""
self.source = source
self.patch = patch
fields = patch.attrib
self.author = fields["author"]
self.hash = fields["hash"]
self.chash = Fore.CYAN + f"patch {self.hash}" + Style.RESET_ALL
self.date = datetime.strptime(fields["date"], _darcs_date)
self.subject = patch.find("name").text
comment = patch.find("comment").text
if comment.startswith("Ignore-this: "):
comment = os.linesep.join(comment.splitlines()[1:])
self.comment = comment.strip()
self.pull = None
def short(self):
"""Get a short description of the patch."""
return f"""
{self.chash}
Author: {self.author}
Date: {self.date}
Subject: {self.subject}
""".strip()
def long(self):
"""Get a longer description of the patch."""
if self.comment:
return f"{self.short()}\n\n{self.comment}"
else:
return self.short()
def full(self):
"""Show the full patch."""
show_full_patch(self.source, self.hash)
def message(self):
"""Format patch message for git."""
return f"{self.subject}\n\n{self.comment}".strip()
def ask(self, index, of):
"""Ask if I should pull this patch."""
key = "l"
text = self.short()
while key in ("l", "f"):
key = ask(
_pull_question,
"ynwasc",
text=text,
state=f"{index + 1}/{of}",
help=_pull_help,
)
text = ""
if key == "l":
print(self.long())
elif key == "f":
self.full()
elif key == "y":
self.pull = True
elif key == "n":
self.pull = False
elif key == "a":
self.pull = True
elif key == "i":
self.pull = False
return key
class Pull:
"""Contains state for the pull-questions."""
def __init__(self, source, args, *, ignore_temp=True):
"""Dear flake8 this is a init function."""
self.source = source
self.args = args
self.ignore_temp = ignore_temp
self.patches_xml = get_patches(source, args)
self.patches = OrderedDict() # Legacy support
for patch in self.patches_xml:
obj = Patch(source, patch)
if self.ignore_temp:
if not obj.subject.startswith("temp: "):
self.patches[obj.hash] = obj
else:
self.patches[obj.hash] = obj
def pull(self, all=False):
"""Pull patches."""
if not self.patches:
print("No remote patches to pull in!")
return
if all:
for patch in self.patches.values():
patch.pull = True
else:
self.decide()
pull = [x for x in self.patches.values() if x.pull]
count = len(pull)
if not all:
key = ask(f"Shall I pull {count} patches", "yn")
if key in ("n", "q", "c"):
print("Cancel pull")
sys.exit(1)
with tqdm(desc="pull", total=count, disable=_disable) as pbar:
for patch in pull:
pull_patch(self.source, patch.hash)
with ignore_darcs():
git_add()
git_commit(patch.message())
pbar.update()
def pull_depends(self, hash):
"""Find dependent patches an set pull to True for these, too."""
xml = get_patches(self.source, ["-h", hash])
count = 0
for patch in xml:
hash = patch.attrib["hash"]
patch = self.patches[hash]
if not patch.pull:
count += 1
patch.pull = True
if count:
print(Fore.RED + f"Select {count} dependent patches" + Style.RESET_ALL)
def decide(self):
"""Decide patches to pull."""
decide = OrderedDict(self.patches)
while decide:
key = None
of = len(decide)
for index, (hash, patch) in enumerate(OrderedDict(decide).items()):
key = patch.ask(index, of)
if patch.pull is not None:
if patch.pull:
self.pull_depends(hash)
decide.pop(hash)
if key == "a":
break
elif key == "i":
break
elif key in ("c", "q"):
print("Cancel pull")
sys.exit(1)
of = len(decide)
with tqdm(desc="resolve", total=of, disable=_disable) as pbar:
for hash, patch in OrderedDict(decide).items():
if key == "a":
patch.pull = True
self.pull_depends(hash)
elif key == "i":
patch.pull = False
decide.pop(hash)
pbar.update()
@click.group()
def main():
"""Click entrypoint."""
fix_pwd()
@main.command()
@click.argument("source", type=click.Path(exists=True, dir_okay=True, file_okay=False))
@click.argument("destination", type=click.Path(exists=False))
@click.option("-v/-nv", "--verbose/--no-verbose", default=False)
def clone(source, destination, verbose):
"""Locally clone a tracking-repository to get a working-repository."""
setup(False, verbose=verbose)
with tqdm(desc="clone", total=5, disable=_disable) as pbar:
destination = Path(destination)
if destination.exists():
raise ClickException(f"Destination `{destination}` may not exist")
git_clone(source, destination)
pbar.update()
dest = Path(destination, ".git", "config")
dest.unlink()
copy(Path(source, ".git", "config"), dest)
pbar.update()
darcs_dest = Path(destination, _uuid)
repo_source = Path(darcs_dest, "_darcs")
darcs_clone(source, darcs_dest)
pbar.update()
repo_source = Path(darcs_dest, "_darcs")
repo_dest = Path(destination, "_darcs")
repo_source.rename(repo_dest)
rmtree(darcs_dest, ignore_errors=True)
pbar.update()
os.chdir(destination)
relink()
pbar.update()
@main.command()
@click.option("-v/-nv", "--verbose/--no-verbose", default=False)
@click.option(
"-w/-nw",
"--warn/--no-warn",
default=True,
help="Warn that repository will be cleared",
)
@click.option(
"--base",
"-b",
default=None,
help="On first update import from (commit-ish)",
)
@click.option(
"-s/-ns",
"--shallow/--no-shallow",
default=None,
help="On first update only import current commit",
)
@click.option(
"-l/-nl",
"--large/--no-large",
default=False,
help="Large repo mode, darcs might miss changes, but import is faster",
)
def update(verbose, warn, base, shallow, large):
"""Incremental import of git into darcs.
By default it imports a shallow copy (the current commit). Use `--no-shallow`
to import the complete history.
"""
global _large
_large = large
setup(warn, verbose=verbose)
run_update(*prepare_update(base, shallow))
@main.command()
@click.option("-v/-nv", "--verbose/--no-verbose", default=False)
@click.option(
"-w/-nw",
"--warn/--no-warn",
default=True,
help="Warn that repository will be cleared",
)
@click.option(
"-a/-na",
"--all/--no-all",
default=False,
help="Pull all patches",
)
@click.option(
"-i/-ni",
"--ignore-temp/--no-ignore-temp",
default=True,
help="Ignore temporary patches (with 'temp: ')",
)
@click.argument("source", type=click.Path(exists=True, dir_okay=True, file_okay=False))
@click.argument("darcs", nargs=-1)
def pull(verbose, all, warn, source, darcs, ignore_temp):
"""Pull from source darcs-repository into a tracking-repository.
A tracking-repository is created by `git darcs update` and contains a git- and a
darcs-repository. Arguments after `--` are passed to `darcs pull`.
"""
setup(warn, verbose=verbose)
if not Path("_darcs").exists():
raise ClickException("Please run git-darcs in the root of your darcs-repo.")
if not Path(".git").exists():
raise ClickException("Please run git-darcs in the root of your git-repo.")
wipe()
if hasnew():
raise ClickException(
"The git and the darcs repo in your tracking-repo are not in sync."
)
init()
Pull(source, list(darcs), ignore_temp=ignore_temp).pull(all)