-
Notifications
You must be signed in to change notification settings - Fork 56
/
Copy pathcli.py
1013 lines (924 loc) · 51.5 KB
/
cli.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
#!/usr/bin/env python3
import argparse
import itertools
import os
import pkgutil
import re
import sys
import textwrap
from typing import (Any, Dict, Iterable, List, Optional, Sequence, Tuple,
TypeVar, Union)
import git_machete.options
from git_machete import __version__, git_config_keys, utils
from git_machete.github import GitHubClient
from git_machete.gitlab import GitLabClient
from .client import (MacheteClient, SquashMergeDetection, TraverseReturnTo,
TraverseStartFrom)
from .exceptions import (ExitCode, InteractionStopped, MacheteException,
UnderlyingGitException, UnexpectedMacheteException)
from .generated_docs import long_docs, short_docs
from .git_operations import (AnyBranchName, AnyRevision, GitContext,
LocalBranchShortName, RemoteBranchShortName)
from .utils import bold, excluding, fmt, underline, warn
T = TypeVar('T')
alias_by_command: Dict[str, str] = {
"diff": "d",
"edit": "e",
"go": "g",
"log": "l",
"status": "s",
"traverse": "t"
}
command_by_alias: Dict[str, str] = {v: k for k, v in alias_by_command.items()}
command_groups: List[Tuple[str, List[str]]] = [
("General topics",
["completion", "config", "file", "format", "help", "hooks", "version"]),
("Build, display and modify the tree of branch dependencies",
["add", "anno", "discover", "edit", "status"]),
("List, check out and delete branches",
["delete-unmanaged", "go", "is-managed", "list", "show"]),
("Determine changes specific to the given branch",
["diff", "fork-point", "log"]),
("Update git history in accordance with the tree of branch dependencies",
["advance", "reapply", "slide-out", "squash", "traverse", "update"]),
("Integrate with third party tools",
["github", "gitlab"])
]
commands_and_aliases = list(long_docs.keys()) + list(command_by_alias.keys())
def get_help_description(display_help_topics: bool, command: Optional[str] = None) -> str:
usage_str = ''
if command in long_docs:
usage_str += fmt(textwrap.dedent(long_docs[command]))
elif command in command_by_alias:
usage_str += fmt(textwrap.dedent(long_docs[command_by_alias[command]]))
else:
usage_str += get_short_general_usage() + '\n' + fmt(
"\n<u>Quick start tip</u>\n\n"
" Get familiar with the help for <b>format</b>, <b>edit</b>,"
" <b>status</b> and <b>update</b>, in this order.\n\n")
for hdr, cmds in command_groups:
if not display_help_topics:
if hdr == 'General topics':
cmds = [topic for topic in cmds if topic not in ['config', 'format', 'hooks']]
usage_str += underline(hdr) + '\n\n'
for cm in cmds:
alias = f", {alias_by_command[cm]}" if cm in alias_by_command else ""
usage_str += f' {bold(cm + alias): <{18 if utils.ascii_only else 27}}{short_docs[cm]}'
usage_str += '\n'
usage_str += '\n'
usage_str += fmt(textwrap.dedent("""
<u>General options</u>\n
<b>--debug</b> Log detailed diagnostic info, including outputs of the executed git commands.
<b>-h, --help</b> Print help and exit.
<b>-v, --verbose</b> Log the executed git commands.
<b>--version</b> Print version and exit.
"""[1:]))
return usage_str
def get_short_general_usage() -> str:
return (fmt("<b>Usage: git machete [--debug] [-h] [-v|--verbose] [--version] "
"<command> [command-specific options] [command-specific argument]</b>"))
def version() -> None:
print(f"git-machete version {__version__}")
class MacheteHelpAction(argparse.Action):
def __init__(
self,
option_strings: str,
dest: str = argparse.SUPPRESS,
default: Any = argparse.SUPPRESS,
help: Optional[str] = None
) -> None:
super(MacheteHelpAction, self).__init__(
option_strings=option_strings,
dest=dest,
default=default,
nargs=0,
help=help)
def __call__(
self,
parser: argparse.ArgumentParser,
namespace: argparse.Namespace, # noqa: F841, U100
values: Union[str, Sequence[Any], None], # noqa: U100
option_string: Optional[str] = None # noqa: F841, U100
) -> None:
# parser name (prog) is expected to be `git machete` or `git machete <command>`
command_name = parser.prog.replace('git machete', '').strip()
print(get_help_description(display_help_topics=True, command=command_name))
parser.exit(status=ExitCode.SUCCESS)
def create_cli_parser() -> argparse.ArgumentParser:
common_args_parser = argparse.ArgumentParser(
prog='git machete',
argument_default=argparse.SUPPRESS,
add_help=False)
common_args_parser.add_argument('--debug', action='store_true')
common_args_parser.add_argument('-h', '--help', action=MacheteHelpAction)
common_args_parser.add_argument('--version', action='version', version=f'git-machete version {__version__}')
common_args_parser.add_argument('-v', '--verbose', action='store_true')
cli_parser = argparse.ArgumentParser(
prog='git machete',
argument_default=argparse.SUPPRESS,
add_help=False,
parents=[common_args_parser])
subparsers = cli_parser.add_subparsers(dest='command')
add_parser = subparsers.add_parser(
'add',
argument_default=argparse.SUPPRESS,
usage=argparse.SUPPRESS,
add_help=False,
parents=[common_args_parser])
add_parser.add_argument('branch', nargs='?')
add_parser.add_argument('-f', '--as-first-child', action='store_true')
add_parser.add_argument('-o', '--onto')
add_parser.add_argument('-R', '--as-root', action='store_true')
add_parser.add_argument('-y', '--yes', action='store_true')
advance_parser = subparsers.add_parser(
'advance',
usage=argparse.SUPPRESS,
add_help=False,
parents=[common_args_parser])
advance_parser.add_argument('-y', '--yes', action='store_true', default=argparse.SUPPRESS)
anno_parser = subparsers.add_parser(
'anno',
usage=argparse.SUPPRESS,
add_help=False,
parents=[common_args_parser])
# possible values of 'annotation_text' include: [], [''], ['some_val'], ['text_1', 'text_2']
anno_parser.add_argument('annotation_text', nargs='*')
anno_parser.add_argument('-b', '--branch', default=argparse.SUPPRESS)
anno_parser.add_argument('-H', '--sync-github-prs', action='store_true', default=argparse.SUPPRESS)
anno_parser.add_argument('-L', '--sync-gitlab-mrs', action='store_true', default=argparse.SUPPRESS)
clean_parser = subparsers.add_parser(
'clean',
usage=argparse.SUPPRESS,
add_help=False,
parents=[common_args_parser])
clean_parser.add_argument('-H', '--checkout-my-github-prs', action='store_true', default=argparse.SUPPRESS)
clean_parser.add_argument('-y', '--yes', action='store_true', default=argparse.SUPPRESS)
completion_parser = subparsers.add_parser(
'completion',
argument_default=argparse.SUPPRESS,
usage=argparse.SUPPRESS,
add_help=False,
parents=[common_args_parser])
completion_parser.add_argument('shell', choices=['bash', 'fish', 'zsh'])
delete_unmanaged_parser = subparsers.add_parser(
'delete-unmanaged',
usage=argparse.SUPPRESS,
add_help=False,
parents=[common_args_parser])
delete_unmanaged_parser.add_argument('-y', '--yes', action='store_true', default=argparse.SUPPRESS)
diff_full_parser = subparsers.add_parser(
'diff',
aliases=['d'],
usage=argparse.SUPPRESS,
add_help=False,
parents=[common_args_parser])
diff_full_parser.add_argument('branch', nargs='?')
diff_full_parser.add_argument('-s', '--stat', action='store_true', default=argparse.SUPPRESS)
discover_parser = subparsers.add_parser(
'discover',
argument_default=argparse.SUPPRESS,
usage=argparse.SUPPRESS,
add_help=False,
parents=[common_args_parser])
discover_parser.add_argument('-C', '--checked-out-since')
discover_parser.add_argument('-l', '--list-commits', action='store_true')
discover_parser.add_argument('-r', '--roots')
discover_parser.add_argument('-y', '--yes', action='store_true')
subparsers.add_parser(
'edit',
aliases=['e'],
usage=argparse.SUPPRESS,
add_help=False,
parents=[common_args_parser])
subparsers.add_parser(
'file',
usage=argparse.SUPPRESS,
add_help=False,
parents=[common_args_parser])
fork_point_parser = subparsers.add_parser(
'fork-point',
argument_default=argparse.SUPPRESS,
usage=argparse.SUPPRESS,
add_help=False,
parents=[common_args_parser])
fork_point_parser.add_argument('branch', nargs='?')
fork_point_exclusive_optional_args = fork_point_parser.add_mutually_exclusive_group()
fork_point_exclusive_optional_args.add_argument('--inferred', action='store_true')
fork_point_exclusive_optional_args.add_argument('--override-to')
fork_point_exclusive_optional_args.add_argument('--override-to-inferred', action='store_true')
fork_point_exclusive_optional_args.add_argument('--override-to-parent', action='store_true')
fork_point_exclusive_optional_args.add_argument('--unset-override', action='store_true')
def add_code_hosting_parser(command: str, pr_or_mr: str, include_sync: bool) -> Any:
parser = subparsers.add_parser(
command,
argument_default=argparse.SUPPRESS,
usage=argparse.SUPPRESS,
add_help=False,
parents=[common_args_parser])
parser.add_argument('subcommand', choices=[
f'anno-{pr_or_mr}s',
f'checkout-{pr_or_mr}s',
f'create-{pr_or_mr}',
f'restack-{pr_or_mr}',
f'retarget-{pr_or_mr}',
f'update-{pr_or_mr}-descriptions'
] + (['sync'] if include_sync else []))
parser.add_argument('request_id', nargs='*', type=int)
parser.add_argument('-b', '--branch')
parser.add_argument('--all', action='store_true')
parser.add_argument('--by')
parser.add_argument('--draft', action='store_true')
parser.add_argument('--ignore-if-missing', action='store_true')
parser.add_argument('--mine', action='store_true')
parser.add_argument('--related', action='store_true')
parser.add_argument('--title')
parser.add_argument('-U', '--update-related-descriptions', action='store_true')
parser.add_argument('--with-urls', action='store_true')
parser.add_argument('--yes', action='store_true')
add_code_hosting_parser('github', 'pr', include_sync=True)
add_code_hosting_parser('gitlab', 'mr', include_sync=False)
go_parser = subparsers.add_parser(
'go',
aliases=['g'],
usage=argparse.SUPPRESS,
add_help=False,
parents=[common_args_parser])
go_parser.add_argument(
'direction',
choices=['d', 'down', 'f', 'first', 'l', 'last', 'n', 'next',
'p', 'prev', 'r', 'root', 'u', 'up']
)
help_parser = subparsers.add_parser(
'help',
add_help=False,
usage=argparse.SUPPRESS,
parents=[common_args_parser])
help_parser.add_argument('topic_or_cmd', nargs='?', choices=commands_and_aliases)
is_managed_parser = subparsers.add_parser(
'is-managed',
usage=argparse.SUPPRESS,
add_help=False,
parents=[common_args_parser])
is_managed_parser.add_argument('branch', nargs='?')
list_parser = subparsers.add_parser(
'list',
usage=argparse.SUPPRESS,
add_help=False,
parents=[common_args_parser])
list_parser.add_argument(
'category',
choices=[
'addable', 'childless', 'managed', 'slidable', 'slidable-after', 'unmanaged',
'with-overridden-fork-point']
)
list_parser.add_argument('branch', nargs='?', default=argparse.SUPPRESS)
log_parser = subparsers.add_parser(
'log',
aliases=['l'],
usage=argparse.SUPPRESS,
add_help=False,
parents=[common_args_parser])
log_parser.add_argument('branch', nargs='?', default=argparse.SUPPRESS)
reapply_parser = subparsers.add_parser(
'reapply',
usage=argparse.SUPPRESS,
add_help=False,
parents=[common_args_parser])
reapply_parser.add_argument('-f', '--fork-point', default=argparse.SUPPRESS)
show_parser = subparsers.add_parser(
'show',
usage=argparse.SUPPRESS,
add_help=False,
parents=[common_args_parser])
show_parser.add_argument(
'direction',
choices=['c', 'current', 'd', 'down', 'f', 'first', 'l', 'last',
'n', 'next', 'p', 'prev', 'r', 'root', 'u', 'up']
)
show_parser.add_argument('branch', nargs='?', default=argparse.SUPPRESS)
slide_out_parser = subparsers.add_parser(
'slide-out',
argument_default=argparse.SUPPRESS,
usage=argparse.SUPPRESS,
add_help=False,
parents=[common_args_parser])
slide_out_parser.add_argument('branches', nargs='*')
slide_out_parser.add_argument('-d', '--down-fork-point')
slide_out_parser.add_argument('--delete', action='store_true')
slide_out_parser.add_argument('-M', '--merge', action='store_true')
slide_out_parser.add_argument('-n', action='store_true')
slide_out_parser.add_argument('--no-edit-merge', action='store_true')
slide_out_parser.add_argument('--no-interactive-rebase', action='store_true')
slide_out_parser.add_argument('--removed-from-remote', action='store_true')
squash_parser = subparsers.add_parser(
'squash',
usage=argparse.SUPPRESS,
add_help=False,
parents=[common_args_parser])
squash_parser.add_argument('-f', '--fork-point', default=argparse.SUPPRESS)
status_parser = subparsers.add_parser(
'status',
aliases=['s'],
argument_default=argparse.SUPPRESS,
usage=argparse.SUPPRESS,
add_help=False,
parents=[common_args_parser])
status_parser.add_argument('--color', choices=['always', 'auto', 'never'], default='auto')
status_parser.add_argument('-l', '--list-commits', action='store_true')
status_parser.add_argument('-L', '--list-commits-with-hashes', action='store_true')
status_parser.add_argument('--no-detect-squash-merges', action='store_true')
status_parser.add_argument('--squash-merge-detection')
traverse_parser = subparsers.add_parser(
'traverse',
aliases=['t'],
argument_default=argparse.SUPPRESS,
usage=argparse.SUPPRESS,
add_help=False,
parents=[common_args_parser])
traverse_parser.add_argument('-F', '--fetch', action='store_true')
traverse_parser.add_argument('-H', '--sync-github-prs', action='store_true')
traverse_parser.add_argument('-l', '--list-commits', action='store_true')
traverse_parser.add_argument('-L', '--sync-gitlab-mrs', action='store_true')
traverse_parser.add_argument('-M', '--merge', action='store_true')
traverse_parser.add_argument('-n', action='store_true')
traverse_parser.add_argument('--no-detect-squash-merges', action='store_true')
traverse_parser.add_argument('--no-edit-merge', action='store_true')
traverse_parser.add_argument('--no-interactive-rebase', action='store_true')
traverse_parser.add_argument('--no-push', action='store_true')
traverse_parser.add_argument('--no-push-untracked', action='store_true')
traverse_parser.add_argument('--push', action='store_true')
traverse_parser.add_argument('--push-untracked', action='store_true')
traverse_parser.add_argument('--return-to')
traverse_parser.add_argument('--squash-merge-detection')
traverse_parser.add_argument('--start-from')
traverse_parser.add_argument('-W', action='store_true')
traverse_parser.add_argument('-w', '--whole', action='store_true')
traverse_parser.add_argument('-y', '--yes', action='store_true')
update_parser = subparsers.add_parser(
'update',
argument_default=argparse.SUPPRESS,
usage=argparse.SUPPRESS,
add_help=False,
parents=[common_args_parser])
update_parser.add_argument('-f', '--fork-point')
update_parser.add_argument('-M', '--merge', action='store_true')
update_parser.add_argument('-n', action='store_true')
update_parser.add_argument('--no-edit-merge', action='store_true')
update_parser.add_argument('--no-interactive-rebase', action='store_true')
subparsers.add_parser(
'version',
usage=argparse.SUPPRESS,
add_help=False,
parents=[common_args_parser])
return cli_parser
def update_cli_options_using_parsed_args(
cli_opts: git_machete.options.CommandLineOptions,
parsed_args: argparse.Namespace) -> None:
# Warning: In mypy, Arguments that come from untyped functions/variables are silently treated by mypy as Any.
# Since argparse is not typed, everything that comes from argparse.Namespace will be taken as Any :(
# Even if we add type=LocalBranchShortName into argument parser for branch,
# python debugger will see branch as LocalBranchShortName but mypy always will see it as Any,
# until you specifically tell mypy what is the exact type by casting
# (right now it's done this way below, but casting does not solve all of the problems).
#
# The reasonable solution here would be to use Typed Argument Parser
# which is a wrapper over argparse with modernised solution for typing.
# But it would add external dependency to git-machete, so let's stick to current casting.
for opt, arg in vars(parsed_args).items():
# --color, --debug and --verbose are handled outside this method
if opt == "all":
cli_opts.opt_all = True
elif opt == "as_first_child":
cli_opts.opt_as_first_child = True
elif opt == "as_root":
cli_opts.opt_as_root = True
elif opt == "branch":
cli_opts.opt_branch = AnyBranchName.of(arg) if arg else None
elif opt == "by":
cli_opts.opt_by = arg
elif opt == "checked_out_since":
cli_opts.opt_checked_out_since = arg
elif opt == "delete":
cli_opts.opt_delete = True
elif opt == "down_fork_point":
cli_opts.opt_down_fork_point = AnyRevision.of(arg) if arg else None
elif opt == "draft":
cli_opts.opt_draft = True
elif opt == "fetch":
cli_opts.opt_fetch = True
elif opt == "fork_point":
cli_opts.opt_fork_point = AnyRevision.of(arg) if arg else None
elif opt == "ignore_if_missing":
cli_opts.opt_ignore_if_missing = True
elif opt == "inferred":
cli_opts.opt_inferred = True
elif opt == "list_commits":
cli_opts.opt_list_commits = True
elif opt == "list_commits_with_hashes":
cli_opts.opt_list_commits = cli_opts.opt_list_commits_with_hashes = True
elif opt == "merge":
cli_opts.opt_merge = True
elif opt == "mine":
cli_opts.opt_mine = True
elif opt == "n":
cli_opts.opt_n = True
elif opt == "no_detect_squash_merges":
warn("`--no-detect-squash-merges` is deprecated, use `--squash-merge-detection=none` instead", end="\n\n")
cli_opts.opt_squash_merge_detection_string = "none"
elif opt == "no_edit_merge":
cli_opts.opt_no_edit_merge = True
elif opt == "no_interactive_rebase":
cli_opts.opt_no_interactive_rebase = True
elif opt == "no_push":
cli_opts.opt_push_tracked = False
cli_opts.opt_push_untracked = False
elif opt == "no_push_untracked":
cli_opts.opt_push_untracked = False
elif opt == "onto":
cli_opts.opt_onto = LocalBranchShortName.of(arg) if arg else None
elif opt == "override_to":
cli_opts.opt_override_to = arg
elif opt == "override_to_inferred":
cli_opts.opt_override_to_inferred = True
elif opt == "override_to_parent":
cli_opts.opt_override_to_parent = True
elif opt == "push":
cli_opts.opt_push_tracked = True
cli_opts.opt_push_untracked = True
elif opt == "push_untracked":
cli_opts.opt_push_untracked = True
elif opt == "related":
cli_opts.opt_related = True
elif opt == "removed_from_remote":
cli_opts.opt_removed_from_remote = True
elif opt == "return_to":
cli_opts.opt_return_to = arg
elif opt == "roots":
roots: Iterable[str] = filter(None, arg.split(","))
cli_opts.opt_roots = [LocalBranchShortName.of(root) for root in roots]
elif opt == "squash_merge_detection" and arg is not None: # if no arg is passed, argparse will fail anyway
cli_opts.opt_squash_merge_detection_string = arg
cli_opts.opt_squash_merge_detection_origin = "`--squash-merge-detection` flag"
elif opt == "start_from":
cli_opts.opt_start_from = arg
elif opt == "stat":
cli_opts.opt_stat = True
elif opt == "sync_github_prs":
cli_opts.opt_sync_github_prs = True
elif opt == "sync_gitlab_mrs":
cli_opts.opt_sync_gitlab_mrs = True
elif opt == "title":
cli_opts.opt_title = arg
elif opt == "unset_override":
cli_opts.opt_unset_override = True
elif opt == "update_related_descriptions":
cli_opts.opt_update_related_descriptions = True
elif opt == "W":
cli_opts.opt_fetch = True
cli_opts.opt_start_from = "first-root"
cli_opts.opt_n = True
cli_opts.opt_return_to = "nearest-remaining"
elif opt == "whole":
cli_opts.opt_start_from = "first-root"
cli_opts.opt_n = True
cli_opts.opt_return_to = "nearest-remaining"
elif opt == "with_urls":
cli_opts.opt_with_urls = True
elif opt == "yes":
cli_opts.opt_yes = True
if cli_opts.opt_n or cli_opts.opt_yes:
# Set no-edit-merge as the default, as some branches might have a merge strategy even without --merge set
cli_opts.opt_no_edit_merge = True
if not cli_opts.opt_merge:
if cli_opts.opt_yes or cli_opts.opt_n:
cli_opts.opt_no_interactive_rebase = True
def update_cli_options_using_config_keys(
cli_opts: git_machete.options.CommandLineOptions,
git: GitContext
) -> None:
machete_traverse_push_config_key = git.get_boolean_config_attr_or_none(key=git_config_keys.TRAVERSE_PUSH)
if machete_traverse_push_config_key is not None:
if machete_traverse_push_config_key:
cli_opts.opt_push_tracked, cli_opts.opt_push_untracked = True, True
else:
cli_opts.opt_push_tracked, cli_opts.opt_push_untracked = False, False
squash_merge_detection = git.get_config_attr_or_none(key=git_config_keys.SQUASH_MERGE_DETECTION)
if squash_merge_detection is not None:
# Let's defer the validation until the value is actually used in `status` or `traverse`.
# Otherwise, if an invalid value ends up in git config, `git machete help` will instantly fail.
cli_opts.opt_squash_merge_detection_string = squash_merge_detection
cli_opts.opt_squash_merge_detection_origin = f"`{git_config_keys.SQUASH_MERGE_DETECTION}` git config key"
def set_utils_global_variables(parsed_args: argparse.Namespace) -> None:
args = vars(parsed_args)
utils.ascii_only = args.get("color") == "never" or (args.get("color") in {None, "auto"} and not sys.stdout.isatty())
utils.debug_mode = "debug" in args
utils.verbose_mode = "verbose" in args
def get_local_branch_short_name_from_arg_or_current_branch(
branch_from_arg: Optional[AnyBranchName], git_context: GitContext) -> LocalBranchShortName:
return get_local_branch_short_name_from_arg(branch_from_arg) if branch_from_arg else git_context.get_current_branch()
def get_local_branch_short_name_from_arg(branch_from_arg: AnyBranchName) -> LocalBranchShortName:
return LocalBranchShortName.of(branch_from_arg.replace('refs/heads/', ''))
def launch(orig_args: List[str]) -> None:
initial_current_directory: Optional[str] = utils.get_current_directory_or_none()
try:
cli_opts = git_machete.options.CommandLineOptions()
git = GitContext()
direct_args = list(itertools.takewhile(lambda arg: arg != "--", orig_args))
pass_through_args = list(itertools.dropwhile(lambda arg: arg != "--", orig_args))
cli_parser: argparse.ArgumentParser = create_cli_parser()
parsed_cli: argparse.Namespace = cli_parser.parse_args(direct_args)
parsed_cli_as_dict: Dict[str, Any] = vars(parsed_cli)
# Let's set up options like debug/verbose before we first start reading `git config`.
set_utils_global_variables(parsed_cli)
update_cli_options_using_config_keys(cli_opts, git)
update_cli_options_using_parsed_args(cli_opts, parsed_cli)
cli_opts.validate()
if not direct_args:
print(get_help_description(display_help_topics=False))
sys.exit(ExitCode.ARGUMENT_ERROR)
cmd = parsed_cli.command
if cmd not in ("d", "diff", "l", "log") and pass_through_args:
print(fmt("Extra arguments after `--` are only allowed after `diff` and `log`"))
sys.exit(ExitCode.ARGUMENT_ERROR)
if pass_through_args and pass_through_args[0] == "--":
pass_through_args = pass_through_args[1:]
if cmd == "completion":
completion_shell = parsed_cli.shell
def print_completion_resource(name: str) -> None:
data = pkgutil.get_data("completion", name)
if not data:
raise UnexpectedMacheteException(f"Completion file `{name}` not found.")
print(data.decode())
# Deliberately using if/else instead of a dict - to measure coverage more accurately.
if completion_shell == "bash":
print_completion_resource("git-machete.completion.bash")
elif completion_shell == "fish":
print_completion_resource("git-machete.fish")
elif completion_shell == "zsh": # an unknown shell is handled by argparse
print_completion_resource("git-machete.completion.zsh")
else: # an unknown shell is handled by argparse
raise UnexpectedMacheteException(f"Unknown shell: `{completion_shell}`")
return
elif cmd == "help":
print(get_help_description(display_help_topics=True, command=parsed_cli.topic_or_cmd))
return
elif cmd == "version":
version()
return
machete_client = MacheteClient(git)
if not os.path.exists(machete_client.branch_layout_file_path):
# We're opening in "append" and not "write" mode to avoid a race condition:
# if other process writes to the file between we check the
# result of `os.path.exists` and call `open`,
# then open(..., "w") would result in us clearing up the file
# contents, while open(..., "a") has no effect.
with open(machete_client.branch_layout_file_path, "a"):
pass
elif os.path.isdir(machete_client.branch_layout_file_path):
# Extremely unlikely case, basically checking if anybody
# tampered with the repository.
raise MacheteException(
f"{machete_client.branch_layout_file_path} is a directory "
"rather than a regular file, aborting")
should_perform_interactive_slide_out = MacheteClient.should_perform_interactive_slide_out(cmd)
if cmd == "add":
machete_client.read_branch_layout_file(perform_interactive_slide_out=should_perform_interactive_slide_out)
branch = get_local_branch_short_name_from_arg_or_current_branch(cli_opts.opt_branch, git)
machete_client.add(
branch=branch,
opt_onto=cli_opts.opt_onto,
opt_as_first_child=cli_opts.opt_as_first_child,
opt_as_root=cli_opts.opt_as_root,
opt_yes=cli_opts.opt_yes,
verbose=True,
switch_head_if_new_branch=True)
elif cmd == "advance":
machete_client.read_branch_layout_file(perform_interactive_slide_out=should_perform_interactive_slide_out)
git.expect_no_operation_in_progress()
current_branch = git.get_current_branch()
machete_client.expect_in_managed_branches(current_branch)
machete_client.advance(branch=current_branch, opt_yes=cli_opts.opt_yes)
elif cmd == "anno":
machete_client.read_branch_layout_file(perform_interactive_slide_out=should_perform_interactive_slide_out,
verify_branches=False)
if cli_opts.opt_sync_github_prs:
machete_client.sync_annotations_to_prs(GitHubClient.spec(), include_urls=False)
elif cli_opts.opt_sync_gitlab_mrs:
machete_client.sync_annotations_to_prs(GitLabClient.spec(), include_urls=False)
else:
branch = get_local_branch_short_name_from_arg_or_current_branch(cli_opts.opt_branch, git)
machete_client.expect_in_managed_branches(branch)
if parsed_cli.annotation_text:
machete_client.annotate(branch, parsed_cli.annotation_text)
else:
machete_client.print_annotation(branch)
elif cmd == "clean":
machete_client.read_branch_layout_file(perform_interactive_slide_out=should_perform_interactive_slide_out)
if 'checkout_my_github_prs' in parsed_cli:
machete_client.checkout_pull_requests(GitHubClient.spec(), pr_numbers=[], mine=True)
machete_client.delete_unmanaged(opt_squash_merge_detection=SquashMergeDetection.NONE, opt_yes=cli_opts.opt_yes)
machete_client.delete_untracked(opt_yes=cli_opts.opt_yes)
elif cmd == "delete-unmanaged":
machete_client.read_branch_layout_file(perform_interactive_slide_out=should_perform_interactive_slide_out)
opt_squash_merge_detection = SquashMergeDetection.from_string(
cli_opts.opt_squash_merge_detection_string, cli_opts.opt_squash_merge_detection_origin)
machete_client.delete_unmanaged(opt_squash_merge_detection=opt_squash_merge_detection, opt_yes=cli_opts.opt_yes)
elif cmd in {"diff", alias_by_command["diff"]}:
machete_client.read_branch_layout_file(perform_interactive_slide_out=should_perform_interactive_slide_out)
diff_branch = get_local_branch_short_name_from_arg(cli_opts.opt_branch) if (cli_opts.opt_branch is not None) else None
machete_client.display_diff(branch=diff_branch, opt_stat=cli_opts.opt_stat, extra_git_diff_args=pass_through_args)
elif cmd == "discover":
machete_client.read_branch_layout_file(perform_interactive_slide_out=should_perform_interactive_slide_out)
machete_client.discover_tree(
opt_checked_out_since=cli_opts.opt_checked_out_since,
opt_list_commits=cli_opts.opt_list_commits,
opt_roots=cli_opts.opt_roots,
opt_yes=cli_opts.opt_yes)
elif cmd in {"edit", alias_by_command["edit"]}:
# No need to read branch layout file.
machete_client.edit()
elif cmd == "file":
# No need to read branch layout file.
print(os.path.abspath(machete_client.branch_layout_file_path))
elif cmd == "fork-point":
machete_client.read_branch_layout_file(perform_interactive_slide_out=should_perform_interactive_slide_out)
branch = get_local_branch_short_name_from_arg_or_current_branch(cli_opts.opt_branch, git)
machete_client.expect_in_local_branches(branch)
if cli_opts.opt_inferred:
print(machete_client.fork_point(branch=branch, use_overrides=False))
elif cli_opts.opt_override_to:
machete_client.set_fork_point_override(branch, AnyRevision.of(cli_opts.opt_override_to))
elif cli_opts.opt_override_to_inferred:
fork_point = machete_client.fork_point(branch=branch, use_overrides=False)
machete_client.set_fork_point_override(branch, fork_point)
elif cli_opts.opt_override_to_parent:
upstream = machete_client.up_branch_for(branch)
if upstream:
machete_client.set_fork_point_override(branch, upstream)
else:
raise MacheteException(
f"Branch {bold(branch)} does not have upstream (parent) branch")
elif cli_opts.opt_unset_override:
machete_client.unset_fork_point_override(branch)
else:
print(machete_client.fork_point(branch=branch, use_overrides=True))
elif cmd in {"go", alias_by_command["go"]}:
machete_client.read_branch_layout_file(perform_interactive_slide_out=should_perform_interactive_slide_out)
git.expect_no_operation_in_progress()
current_branch = git.get_current_branch()
dest = machete_client.parse_direction(parsed_cli.direction, current_branch, allow_current=False, down_pick_mode=True)[0]
# with down_pick_mode=True there is only one element in list allowed
if dest != current_branch:
git.checkout(dest)
elif cmd in ("github", "gitlab"):
subcommand = parsed_cli.subcommand
spec = GitHubClient.spec() if cmd == "github" else GitLabClient.spec()
pr_or_mr = spec.pr_short_name.lower()
machete_client.read_branch_layout_file(perform_interactive_slide_out=should_perform_interactive_slide_out)
if "request_id" in parsed_cli and subcommand != f"checkout-{pr_or_mr}s":
raise MacheteException(f"{spec.pr_short_name} number is only valid with `checkout-{pr_or_mr}s` subcommand.")
for name, value in (("all", cli_opts.opt_all), ("mine", cli_opts.opt_mine)):
if value and subcommand not in (f"checkout-{pr_or_mr}s", f"update-{pr_or_mr}-descriptions"):
raise MacheteException(f"`--{name}` option is only valid with "
f"`checkout-{pr_or_mr}s` and `update-{pr_or_mr}-descriptions` subcommands.")
if cli_opts.opt_branch is not None and subcommand != f"retarget-{pr_or_mr}":
raise MacheteException(f"`--branch` option is only valid with `retarget-{pr_or_mr}` subcommand.")
if cli_opts.opt_by is not None and subcommand not in (f"checkout-{pr_or_mr}s", f"update-{pr_or_mr}-descriptions"):
raise MacheteException(f"`--by` option is only valid with "
f"`checkout-{pr_or_mr}s` and `update-{pr_or_mr}-descriptions` subcommands.")
if cli_opts.opt_draft and subcommand != f"create-{pr_or_mr}":
raise MacheteException(f"`--draft` option is only valid with `create-{pr_or_mr}` subcommand.")
if cli_opts.opt_ignore_if_missing and subcommand != f"retarget-{pr_or_mr}":
raise MacheteException(f"`--ignore-if-missing` option is only valid with `retarget-{pr_or_mr}` subcommand.")
if cli_opts.opt_related and subcommand != f"update-{pr_or_mr}-descriptions":
raise MacheteException(f"`--related` option is only valid with `update-{pr_or_mr}-descriptions` subcommand.")
if cli_opts.opt_title is not None and subcommand != f"create-{pr_or_mr}":
raise MacheteException(f"`--title` option is only valid with `create-{pr_or_mr}` subcommand.")
if (cli_opts.opt_update_related_descriptions and
subcommand not in (f"create-{pr_or_mr}", f"restack-{pr_or_mr}", f"retarget-{pr_or_mr}")):
raise MacheteException(f"`--update-related-descriptions` option is only valid "
f"with `create-{pr_or_mr}`, `restack-{pr_or_mr}` and `retarget-{pr_or_mr}` subcommands.")
if cli_opts.opt_with_urls and subcommand != f"anno-{pr_or_mr}s":
raise MacheteException(f"`--with-urls` option is only valid with `anno-{pr_or_mr}s` subcommand.")
if cli_opts.opt_yes and subcommand != f"create-{pr_or_mr}":
raise MacheteException(f"`--yes` option is only valid with `create-{pr_or_mr}` subcommand.")
if subcommand == f"anno-{pr_or_mr}s":
machete_client.sync_annotations_to_prs(spec, include_urls=cli_opts.opt_with_urls)
elif subcommand == f"checkout-{pr_or_mr}s":
if len(set(parsed_cli_as_dict.keys()).intersection({'all', 'by', 'mine', 'request_id'})) != 1:
raise MacheteException(
f"`checkout-{pr_or_mr}s` subcommand must take exactly one of the following options: "
f'`--all`, `--by=...`, `--mine`, `{pr_or_mr}-number(s)`')
machete_client.checkout_pull_requests(
spec,
pr_numbers=parsed_cli.request_id if 'request_id' in parsed_cli else [],
all=cli_opts.opt_all,
mine=cli_opts.opt_mine,
by=cli_opts.opt_by,
fail_on_missing_current_user_for_my_open_prs=True)
elif subcommand == f"create-{pr_or_mr}":
current_branch = git.get_current_branch()
machete_client.create_pull_request(
spec,
head=current_branch,
opt_draft=cli_opts.opt_draft,
opt_onto=cli_opts.opt_onto,
opt_title=cli_opts.opt_title,
opt_update_related_descriptions=cli_opts.opt_update_related_descriptions,
opt_yes=cli_opts.opt_yes)
elif subcommand == f"restack-{pr_or_mr}":
machete_client.restack_pull_request(spec, opt_update_related_descriptions=cli_opts.opt_update_related_descriptions)
elif subcommand == f"retarget-{pr_or_mr}":
branch = parsed_cli.branch if 'branch' in parsed_cli else git.get_current_branch()
machete_client.expect_in_managed_branches(branch)
machete_client.retarget_pull_request(
spec,
head=branch,
opt_ignore_if_missing=cli_opts.opt_ignore_if_missing,
opt_update_related_descriptions=cli_opts.opt_update_related_descriptions
)
elif subcommand == "sync": # GitHub only
machete_client.checkout_pull_requests(spec, pr_numbers=[], mine=True)
machete_client.delete_unmanaged(opt_squash_merge_detection=SquashMergeDetection.NONE, opt_yes=False)
machete_client.delete_untracked(opt_yes=cli_opts.opt_yes)
elif subcommand == f"update-{pr_or_mr}-descriptions":
if len(set(parsed_cli_as_dict.keys()).intersection({'all', 'by', 'mine', 'related'})) != 1:
raise MacheteException(
f"`update-{pr_or_mr}-descriptions` subcommand must take exactly one of the following options: "
'`--all`, `--by=...`, `--mine`, `--related`')
machete_client.update_pull_request_descriptions(
spec, all=cli_opts.opt_all, by=cli_opts.opt_by, mine=cli_opts.opt_mine, related=cli_opts.opt_related)
else: # an unknown subcommand is handled by argparse
raise UnexpectedMacheteException(f"Unknown subcommand: `{subcommand}`")
elif cmd == "is-managed":
machete_client.read_branch_layout_file(perform_interactive_slide_out=should_perform_interactive_slide_out)
branch = get_local_branch_short_name_from_arg_or_current_branch(cli_opts.opt_branch, git)
if branch is None or branch not in machete_client.managed_branches:
sys.exit(ExitCode.MACHETE_EXCEPTION)
elif cmd == "list":
category = parsed_cli.category
if category == 'slidable-after' and 'branch' not in parsed_cli:
raise MacheteException(f"`git machete list {category}` requires an extra <branch> argument")
elif category != 'slidable-after' and 'branch' in parsed_cli:
raise MacheteException(f"`git machete list {category}` does not expect extra arguments")
machete_client.read_branch_layout_file(perform_interactive_slide_out=should_perform_interactive_slide_out)
res = []
if category == "addable":
def strip_remote_name(remote_branch: RemoteBranchShortName) -> LocalBranchShortName:
return LocalBranchShortName.of(re.sub("^[^/]+/", "", remote_branch))
remote_counterparts_of_local_branches = utils.map_truthy_only(
git.get_combined_counterpart_for_fetching_of_branch,
git.get_local_branches())
qualifying_remote_branches: List[RemoteBranchShortName] = \
excluding(git.get_remote_branches(), remote_counterparts_of_local_branches)
res = excluding(git.get_local_branches(), machete_client.managed_branches) + [
strip_remote_name(branch) for branch in qualifying_remote_branches]
elif category == "childless":
res = machete_client.get_childless_managed_branches()
elif category == "managed":
res = machete_client.managed_branches
elif category == "slidable":
res = machete_client.get_slidable_branches()
elif category == "slidable-after":
machete_client.expect_in_managed_branches(parsed_cli.branch)
res = machete_client.get_slidable_after(parsed_cli.branch)
elif category == "unmanaged":
res = excluding(git.get_local_branches(), machete_client.managed_branches)
elif category == "with-overridden-fork-point":
res = list(
filter(
lambda _branch: machete_client.has_any_fork_point_override_config(_branch),
git.get_local_branches()))
else: # an unknown category is handled by argparse
raise UnexpectedMacheteException(f"Invalid category: `{category}`")
if res:
print("\n".join(res))
elif cmd in {"log", alias_by_command["log"]}:
machete_client.read_branch_layout_file(perform_interactive_slide_out=should_perform_interactive_slide_out)
branch = get_local_branch_short_name_from_arg_or_current_branch(cli_opts.opt_branch, git)
machete_client.display_log(branch, extra_git_log_args=pass_through_args)
elif cmd == "reapply":
machete_client.read_branch_layout_file(perform_interactive_slide_out=should_perform_interactive_slide_out)
git.expect_no_operation_in_progress()
current_branch = git.get_current_branch()
if cli_opts.opt_fork_point is not None:
machete_client.check_that_fork_point_is_ancestor_or_equal_to_tip_of_branch(
fork_point_hash=cli_opts.opt_fork_point, branch=current_branch)
reapply_fork_point = cli_opts.opt_fork_point or machete_client.fork_point(branch=current_branch, use_overrides=True)
machete_client.rebase(reapply_fork_point, reapply_fork_point, current_branch, cli_opts.opt_no_interactive_rebase)
elif cmd == "show":
direction = parsed_cli.direction
if direction == "current" and "branch" in parsed_cli:
raise MacheteException('`show current` with a `<branch>` argument does not make sense')
branch = get_local_branch_short_name_from_arg_or_current_branch(cli_opts.opt_branch, git)
machete_client.read_branch_layout_file(perform_interactive_slide_out=should_perform_interactive_slide_out,
verify_branches=False)
print('\n'.join(machete_client.parse_direction(direction, branch, allow_current=True, down_pick_mode=False)))
elif cmd == "slide-out":
machete_client.read_branch_layout_file(perform_interactive_slide_out=should_perform_interactive_slide_out)
git.expect_no_operation_in_progress()
branches_to_slide_out: Optional[List[str]] = parsed_cli_as_dict.get('branches')
if cli_opts.opt_removed_from_remote:
if branches_to_slide_out or cli_opts.opt_down_fork_point or cli_opts.opt_merge or cli_opts.opt_no_interactive_rebase:
raise MacheteException("Only `--delete` can be passed with `--removed-from-remote`")
machete_client.slide_out_removed_from_remote(opt_delete=cli_opts.opt_delete)
else:
machete_client.slide_out(
branches_to_slide_out=[LocalBranchShortName.of(branch)
for branch in (branches_to_slide_out or [git.get_current_branch()])],
opt_delete=cli_opts.opt_delete,
opt_down_fork_point=cli_opts.opt_down_fork_point,
opt_merge=cli_opts.opt_merge,
opt_no_interactive_rebase=cli_opts.opt_no_interactive_rebase,
opt_no_edit_merge=cli_opts.opt_no_edit_merge)
elif cmd == "squash":
machete_client.read_branch_layout_file(perform_interactive_slide_out=should_perform_interactive_slide_out)
git.expect_no_operation_in_progress()
current_branch = git.get_current_branch()
if cli_opts.opt_fork_point is not None:
machete_client.check_that_fork_point_is_ancestor_or_equal_to_tip_of_branch(
fork_point_hash=cli_opts.opt_fork_point, branch=current_branch)
squash_fork_point = cli_opts.opt_fork_point or machete_client.fork_point_or_none(branch=current_branch, use_overrides=True)
if squash_fork_point is None:
raise MacheteException(
f"git-machete cannot determine the range of commits unique to branch <b>{current_branch}</b>.\n"
f"Use `git machete squash --fork-point=...` to select the commit "
f"after which the commits of <b>{current_branch}</b> start.\n"
"For example, if you want to squash 3 latest commits, use `git machete squash --fork-point=HEAD~3`."
)
machete_client.squash(current_branch=current_branch, opt_fork_point=squash_fork_point)
elif cmd in {"status", alias_by_command["status"]}:
opt_squash_merge_detection = SquashMergeDetection.from_string(
cli_opts.opt_squash_merge_detection_string, cli_opts.opt_squash_merge_detection_origin)
machete_client.read_branch_layout_file(perform_interactive_slide_out=should_perform_interactive_slide_out)
machete_client.expect_at_least_one_managed_branch()
machete_client.status(
warn_when_branch_in_sync_but_fork_point_off=True,
opt_list_commits=cli_opts.opt_list_commits,
opt_list_commits_with_hashes=cli_opts.opt_list_commits_with_hashes,
opt_squash_merge_detection=opt_squash_merge_detection)
elif cmd in {"traverse", alias_by_command["traverse"]}:
if cli_opts.opt_return_to not in {"here", "nearest-remaining", "stay"}:
raise MacheteException(f"Invalid value for `--return-to` flag: `{cli_opts.opt_return_to}`. "
"Valid values are here, nearest-remaining, stay")
if cli_opts.opt_start_from not in {"here", "root", "first-root"}:
raise MacheteException(f"Invalid value for `--start-from` flag: `{cli_opts.opt_start_from}`. "
"Valid values are here, root, first-root")
opt_return_to = TraverseReturnTo.from_string(cli_opts.opt_return_to, "`--return-to` flag")
opt_squash_merge_detection = SquashMergeDetection.from_string(
cli_opts.opt_squash_merge_detection_string, cli_opts.opt_squash_merge_detection_origin)
opt_start_from = TraverseStartFrom.from_string(cli_opts.opt_start_from, "`--start-from` flag")
machete_client.read_branch_layout_file(perform_interactive_slide_out=should_perform_interactive_slide_out)
git.expect_no_operation_in_progress()
machete_client.traverse(
opt_fetch=cli_opts.opt_fetch,
opt_list_commits=cli_opts.opt_list_commits,
opt_merge=cli_opts.opt_merge,
opt_no_edit_merge=cli_opts.opt_no_edit_merge,
opt_no_interactive_rebase=cli_opts.opt_no_interactive_rebase,
opt_push_tracked=cli_opts.opt_push_tracked,
opt_push_untracked=cli_opts.opt_push_untracked,
opt_return_to=opt_return_to,
opt_squash_merge_detection=opt_squash_merge_detection,
opt_start_from=opt_start_from,
opt_sync_github_prs=cli_opts.opt_sync_github_prs,
opt_sync_gitlab_mrs=cli_opts.opt_sync_gitlab_mrs,
opt_yes=cli_opts.opt_yes)
elif cmd == "update":
machete_client.read_branch_layout_file(perform_interactive_slide_out=should_perform_interactive_slide_out)
git.expect_no_operation_in_progress()
if cli_opts.opt_fork_point is not None:
machete_client.check_that_fork_point_is_ancestor_or_equal_to_tip_of_branch(
fork_point_hash=cli_opts.opt_fork_point, branch=git.get_current_branch())
machete_client.update(
opt_merge=cli_opts.opt_merge,
opt_no_edit_merge=cli_opts.opt_no_edit_merge,
opt_no_interactive_rebase=cli_opts.opt_no_interactive_rebase,
opt_fork_point=cli_opts.opt_fork_point)
else: # an unknown command is handled by argparse
raise UnexpectedMacheteException(f"Unknown command: `{cmd}`")
finally:
# Note that this problem (current directory no longer existing due to e.g. underlying git checkouts)
# has been fixed in git itself as of 2.35.0:
# see https://github.com/git/git/blob/master/Documentation/RelNotes/2.35.0.txt#L81
if initial_current_directory and not utils.does_directory_exist(initial_current_directory):
nearest_existing_parent_directory = initial_current_directory
while not utils.does_directory_exist(nearest_existing_parent_directory):
nearest_existing_parent_directory = os.path.join(
nearest_existing_parent_directory, os.path.pardir)
warn(f"current directory {initial_current_directory} no longer exists, "
f"the nearest existing parent directory is {os.path.abspath(nearest_existing_parent_directory)}")
def main() -> None:
try:
launch(sys.argv[1:])