dflock 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
dflock/main.py ADDED
@@ -0,0 +1,1087 @@
1
+ import configparser
2
+ import functools
3
+ import re
4
+ import subprocess
5
+ import tempfile
6
+ import typing
7
+ from dataclasses import dataclass
8
+ from graphlib import TopologicalSorter
9
+ from hashlib import md5
10
+ from pathlib import Path
11
+
12
+ import click
13
+
14
+ from dflock import utils
15
+
16
+ DEFAULT_UPSTREAM = "main"
17
+ DEFAULT_LOCAL = "main"
18
+ DEFAULT_REMOTE = "origin"
19
+ DEFAULT_BRANCH_ANCHOR = "first" # first/last
20
+ DEFAULT_BRANCH_TEMPLATE = "{}"
21
+ DEFAULT_EDITOR = "nano"
22
+
23
+ INSTRUCTIONS = """
24
+
25
+ # Edit the integration plan.
26
+ #
27
+ # Commands:
28
+ # d<label> <commit> = use commit in labeled delta
29
+ # d<label>@d<target-label> <commit> = use commit in labeled delta depending on
30
+ # delta with target-label
31
+ # s <commit> = do not use commit
32
+ #
33
+ # If you delete a line, the commit will not be used (equivalent to "s")
34
+ # If you remove everything, the plan creation is aborted.
35
+ #
36
+ """
37
+
38
+
39
+ T = typing.TypeVar("T", covariant=True)
40
+
41
+
42
+ class AppCommand(typing.Protocol, typing.Generic[T]):
43
+ def __call__(self, app: "App", *args) -> T:
44
+ ...
45
+
46
+
47
+ def local_and_upstream_exist(f: AppCommand):
48
+ @functools.wraps(f)
49
+ def wrapper(app, *args, **kwargs):
50
+ if not utils.object_exists(app.local):
51
+ hints = ["use `dflock init` to configure dflock."]
52
+ raise GitStateError(f"Local {app.local} does not exist.", hints=hints)
53
+ if not utils.object_exists(app.upstream_name):
54
+ hints = ["use `dflock init` to configure dflock."]
55
+ raise GitStateError(
56
+ f"Upstream {app.upstream_name} does not exist.", hints=hints
57
+ )
58
+ return f(app, *args, **kwargs)
59
+
60
+ return wrapper
61
+
62
+
63
+ def on_local(f: AppCommand):
64
+ @functools.wraps(f)
65
+ @local_and_upstream_exist
66
+ def wrapper(app, *args, **kwargs):
67
+ if utils.get_current_branch() != app.local:
68
+ hints = ["use `dfl checkout local` to return to local."]
69
+ raise GitStateError(
70
+ f"you must be on the local branch: {app.local}.", hints=hints
71
+ )
72
+ return f(app, *args, **kwargs)
73
+
74
+ return wrapper
75
+
76
+
77
+ def inside_work_tree(f):
78
+ @functools.wraps(f)
79
+ def wrapper(*args, **kwargs):
80
+ if not is_inside_work_tree():
81
+ raise click.ClickException("No git repository detected.")
82
+ return f(*args, **kwargs)
83
+
84
+ return wrapper
85
+
86
+
87
+ def no_hot_branch(f: AppCommand) -> typing.Callable:
88
+ @functools.wraps(f)
89
+ def wrapper(app, *args, **kwargs):
90
+ if utils.get_current_branch() in app.get_hot_branches():
91
+ raise click.ClickException(
92
+ "switch to a branch not managed by dflock before continuing."
93
+ )
94
+ return f(app, *args, **kwargs)
95
+
96
+ return wrapper
97
+
98
+
99
+ def valid_local_commits(f: AppCommand[T]) -> AppCommand[T]:
100
+ @functools.wraps(f)
101
+ @local_and_upstream_exist
102
+ def wrapper(app: "App", *args, **kwargs) -> T:
103
+ commits = app._get_branch_commits()
104
+ if len(commits) != len(set(c.message for c in commits)):
105
+ hints = ["use `dfl remix` to edit local commit messages."]
106
+ raise GitStateError(
107
+ "Duplicate commit messages found in local commits.", hints=hints
108
+ )
109
+ return f(app, *args, **kwargs)
110
+
111
+ return wrapper
112
+
113
+
114
+ def undiverged(f: AppCommand):
115
+ @functools.wraps(f)
116
+ def wrapper(app, *args, **kwargs):
117
+ if utils.have_diverged(app.upstream_name, app.local):
118
+ hints = ["use `dfl pull` to pull upstream changes into local."]
119
+ raise GitStateError("Your local and upstream have diverged.", hints=hints)
120
+ return f(app, *args, **kwargs)
121
+
122
+ return wrapper
123
+
124
+
125
+ def pass_app(f):
126
+ @click.pass_context
127
+ @functools.wraps(f)
128
+ def wrapper(ctx, *args, **kwargs):
129
+ app = App.from_config(ctx.obj["config"])
130
+ return f(app, *args, **kwargs)
131
+
132
+ return wrapper
133
+
134
+
135
+ def clean_work_tree(f):
136
+ @functools.wraps(f)
137
+ def wrapper(*args, **kwargs):
138
+ result = utils.run("status", "--untracked-files=no", "--porcelain")
139
+ if bool(result.strip()):
140
+ hints = ["use `git stash` to stash uncommitted changes."]
141
+ raise GitStateError("Work tree not clean.", hints=hints)
142
+ return f(*args, **kwargs)
143
+
144
+ return wrapper
145
+
146
+
147
+ class DflockException(Exception):
148
+ def __init__(self, *args, hints: None | list[str] = None, **kwargs):
149
+ self.hints = [] if hints is None else hints
150
+ super().__init__(*args, **kwargs)
151
+
152
+ def handle_in_cli(self):
153
+ msg = str(self)
154
+ if len(self.hints) > 0:
155
+ msg += "\n" + "\n".join(f"Hint: {h}" for h in self.hints)
156
+ raise click.ClickException(msg)
157
+
158
+
159
+ class ParsingError(DflockException):
160
+ pass
161
+
162
+
163
+ class PlanError(DflockException):
164
+ pass
165
+
166
+
167
+ class CherryPickFailed(DflockException):
168
+ pass
169
+
170
+
171
+ class NoRemoteTrackingBranch(DflockException):
172
+ pass
173
+
174
+
175
+ class GitStateError(DflockException):
176
+ pass
177
+
178
+
179
+ class Commit(typing.NamedTuple):
180
+ sha: str
181
+ message: str
182
+
183
+ @classmethod
184
+ def from_oneline(cls, oneline: str):
185
+ """Parse from 'oneline' format of git rev-list."""
186
+ sha, *message_words = oneline.split()
187
+ return cls(sha, " ".join(message_words))
188
+
189
+ @property
190
+ def short_message(self) -> str:
191
+ return self.message.split("\n")[0]
192
+
193
+ @property
194
+ def short_str(self) -> str:
195
+ return f"{self.sha[:8]} {self.short_message}"
196
+
197
+
198
+ class Delta(typing.NamedTuple):
199
+ commits: tuple[Commit, ...]
200
+ target: typing.Optional["Delta"]
201
+ branch_name: str
202
+ target_branch_name: str
203
+
204
+ @property
205
+ def full_branch_name(self) -> str:
206
+ return f"refs/heads/{self.branch_name}"
207
+
208
+ def branch_exists(self) -> bool:
209
+ return utils.object_exists(self.full_branch_name)
210
+
211
+ def delete_branch(self) -> None:
212
+ utils.run("branch", "-D", self.branch_name)
213
+
214
+ def create_branch(self) -> None:
215
+ utils.checkout("-b", self.branch_name)
216
+
217
+ @property
218
+ def create_instructions(self) -> str:
219
+ return (
220
+ f"git checkout {self.target_branch_name}\n"
221
+ f"git checkout -b temporary-investigation-branch\n"
222
+ f"git cherry-pick {' '.join([c.sha for c in self.commits])}"
223
+ )
224
+
225
+ def cherry_pick(self) -> None:
226
+ try:
227
+ utils.run("cherry-pick", *[c.sha for c in self.commits])
228
+ except subprocess.CalledProcessError:
229
+ hint = (
230
+ f"To reproduce the failed cherry-pick, run the following "
231
+ f"commands:\n\n{self.create_instructions}"
232
+ )
233
+ raise CherryPickFailed(
234
+ f"Cherry-pick failed at branch {self.branch_name}.", hints=[hint]
235
+ )
236
+
237
+ def get_force_push_command(
238
+ self, remote: str, merge_request: bool = False
239
+ ) -> list[str]:
240
+ command = [
241
+ "push",
242
+ "--force-with-lease",
243
+ "--set-upstream",
244
+ remote,
245
+ f"{self.full_branch_name}:{self.full_branch_name}",
246
+ ]
247
+ if merge_request:
248
+ command += ["--push-option", "merge_request.create"]
249
+ if self.target is not None:
250
+ command += [
251
+ "--push-option",
252
+ f"merge_request.target={self.target_branch_name}",
253
+ ]
254
+ return command
255
+
256
+ def __str__(self) -> str:
257
+ return f"Branch {self.branch_name} with commits:\n" + "\n".join(
258
+ f"\t{c.short_message}" for c in self.commits
259
+ )
260
+
261
+
262
+ class _BranchCommand(typing.NamedTuple):
263
+ label: str
264
+ target_label: None | str
265
+ commit_sha: str
266
+
267
+
268
+ class _CommitList(typing.NamedTuple):
269
+ label: str
270
+ target_label: None | str
271
+ commits: list[Commit]
272
+
273
+
274
+ @dataclass
275
+ class App:
276
+ local: str
277
+ upstream: str
278
+ remote: str
279
+ branch_template: str
280
+ anchor_commit: str
281
+ editor: str
282
+ change_request_templates: dict[str, str]
283
+
284
+ @classmethod
285
+ def from_config(cls, config: typing.Mapping) -> typing.Self:
286
+ dflock = config["dflock"]
287
+ integrations = [
288
+ (k, k.split(".")[1])
289
+ for k in config.keys()
290
+ if re.match(r"^integrations.[a-z-]+$", k)
291
+ ]
292
+ change_request_templates = {}
293
+ for config_key, integration in integrations:
294
+ change_request_templates[integration] = config[config_key][
295
+ "change-request-template"
296
+ ]
297
+ return cls(
298
+ local=dflock["local"],
299
+ upstream=dflock["upstream"],
300
+ remote=dflock["remote"],
301
+ branch_template=dflock["branch-template"],
302
+ anchor_commit=dflock["anchor-commit"],
303
+ editor=dflock["editor"],
304
+ change_request_templates=change_request_templates,
305
+ )
306
+
307
+ @property
308
+ def upstream_name(self):
309
+ if self.remote == "":
310
+ return self.upstream
311
+ return f"{self.remote}/{self.upstream}"
312
+
313
+ def get_commit_branch_name(self, commit):
314
+ uniqueish = md5(commit.message.encode()).hexdigest()[:8]
315
+ words = re.findall(r"\w+", commit.message.lower())
316
+ readable = "-".join(words)
317
+ return self.branch_template.format(f"{readable}-{uniqueish}")
318
+
319
+ def build_tree(self, stack: bool = True) -> dict[str, "Delta"]:
320
+ """Create a simple plan including all local commits.
321
+
322
+ If stack is False, treat every commit as an independent delta,
323
+ otherwise create a stack of deltas.
324
+ """
325
+ commits = self._get_branch_commits()
326
+ tree: dict[str, Delta] = {}
327
+ target = None
328
+ for commit in commits:
329
+ delta = self._create_delta([commit], target)
330
+ tree[delta.branch_name] = delta
331
+ if stack:
332
+ target = delta
333
+ return tree
334
+
335
+ def validate_ephemeral_branch(self, branch_name, commits, delta_commits):
336
+ unrecognized = set(c.message for c in commits) - set(
337
+ c.message for c in delta_commits
338
+ )
339
+ if len(unrecognized) > 0:
340
+ for message in unrecognized:
341
+ click.echo(
342
+ f"WARNING: Unfamiliar commit message encountered on {branch_name}: {message}.",
343
+ err=True,
344
+ )
345
+ if self.anchor_commit == "first":
346
+ anchor_commit_branch_name = self.get_commit_branch_name(commits[0])
347
+ else:
348
+ anchor_commit_branch_name = self.get_commit_branch_name(commits[-1])
349
+ if branch_name != anchor_commit_branch_name:
350
+ click.echo(
351
+ f"WARNING: Branch name of inferred delta {branch_name} is inconsistent with {self.anchor_commit} commit.",
352
+ err=True,
353
+ )
354
+
355
+ def reconstruct_tree(self) -> dict[str, Delta]:
356
+ local_commits = self._get_branch_commits()
357
+ local_branches = utils.get_local_branches()
358
+ branch_names_by_last_commit: dict[str, str] = {}
359
+ deltas: dict[str, Delta] = {}
360
+ for commit in local_commits:
361
+ branch_name = self.get_commit_branch_name(commit)
362
+ if branch_name in local_branches:
363
+ commits = self._get_branch_commits(branch_name)
364
+ if len(commits) == 0:
365
+ raise GitStateError(
366
+ f"Cannot reconstruct tree: ephemeral branch {branch_name} has no commits."
367
+ )
368
+ messages = [c.message for c in commits]
369
+ target: Delta | None = None
370
+ delta_start = 0
371
+ for i, msg in enumerate(reversed(messages)):
372
+ if msg in branch_names_by_last_commit:
373
+ target = deltas[branch_names_by_last_commit[msg]]
374
+ delta_start = len(messages) - i
375
+ break
376
+ branch_names_by_last_commit[commits[-1].message] = branch_name
377
+ delta_commits = [
378
+ c for c in local_commits if c.message in messages[delta_start:]
379
+ ]
380
+ if len(delta_commits) == 0:
381
+ raise GitStateError(
382
+ f"Cannot reconstruct tree: delta {branch_name} has no commits."
383
+ )
384
+ self.validate_ephemeral_branch(
385
+ branch_name, commits[delta_start:], delta_commits
386
+ )
387
+ deltas[branch_name] = self._create_delta(delta_commits, target)
388
+ return deltas
389
+
390
+ def parse_plan(self, plan: str) -> dict[str, Delta]:
391
+ tokens = _tokenize_plan(plan)
392
+ commit_lists = self._make_commit_lists(tokens)
393
+ return self._build_tree(commit_lists)
394
+
395
+ def render_plan(self, tree: dict[str, Delta], include_skipped=True) -> str:
396
+ local_commits = self._get_branch_commits()
397
+ sorted_deltas = sorted(
398
+ tree.values(), key=lambda d: local_commits.index(d.commits[0])
399
+ )
400
+ delta_indices = {d: i for i, d in enumerate(sorted_deltas)}
401
+ lines = []
402
+ for commit in local_commits:
403
+ command = "s"
404
+ for delta, index in delta_indices.items():
405
+ if commit in delta.commits:
406
+ command = f"d{index}"
407
+ if delta.target is not None:
408
+ command += f"@{delta_indices[delta.target]}"
409
+ lines.append(f"{command} {commit.short_str}")
410
+ break
411
+ else:
412
+ if include_skipped:
413
+ lines.append(f"s {commit.short_str}")
414
+ return "\n".join(lines)
415
+
416
+ def prune_local_branches(
417
+ self, tree: None | dict[str, Delta] = None, hot_branches=None
418
+ ) -> None:
419
+ if tree is None:
420
+ tree = self.reconstruct_tree()
421
+ if hot_branches is None:
422
+ hot_branches = self.get_hot_branches()
423
+ branches_to_prune = hot_branches - set(tree.keys())
424
+ for branch_name in branches_to_prune:
425
+ click.echo(f"Pruning {branch_name}.")
426
+ utils.run("branch", "-D", branch_name)
427
+
428
+ def create_change_request_command(
429
+ self, integration: str, source_branch: str, target_branch: str
430
+ ) -> str:
431
+ return self.change_request_templates[integration].format(
432
+ source=source_branch, target=target_branch
433
+ )
434
+
435
+ def get_delta_branches(self) -> list[str]:
436
+ branches = utils.get_local_branches()
437
+ commits = self._get_branch_commits()
438
+ return [
439
+ self.get_commit_branch_name(c)
440
+ for c in commits
441
+ if self.get_commit_branch_name(c) in branches
442
+ ]
443
+
444
+ def get_hot_branches(self) -> set[str]:
445
+ commits = self._get_branch_commits()
446
+ local_branches = utils.get_local_branches()
447
+ return set(local_branches) & set(
448
+ self.get_commit_branch_name(c) for c in commits
449
+ )
450
+
451
+ def print_deltas(self, deltas: dict[str, None | str]) -> None:
452
+ for i, (branch, target) in enumerate(deltas.items()):
453
+ try:
454
+ up_to_date = branch_up_to_date(branch)
455
+ click.echo(
456
+ f"{'d' + str(i):>4}: "
457
+ f"{branch}{'' if up_to_date else ' (diverged)'}"
458
+ )
459
+ except NoRemoteTrackingBranch:
460
+ click.echo(f"{'d' + str(i):>4}: {branch} (not pushed)")
461
+ if target is not None:
462
+ click.echo(f"{' ' * 6}@ {target}")
463
+
464
+ def _create_delta(
465
+ self, commits: typing.Sequence[Commit], target: None | Delta
466
+ ) -> Delta:
467
+ commits = list(commits)
468
+ branch_name = (
469
+ self.get_commit_branch_name(commits[0])
470
+ if self.anchor_commit == "first"
471
+ else self.get_commit_branch_name(commits[-1])
472
+ )
473
+ target_branch_name = (
474
+ self.upstream_name if target is None else target.branch_name
475
+ )
476
+ return Delta(tuple(commits), target, branch_name, target_branch_name)
477
+
478
+ def _get_branch_commits(self, branch: None | str = None) -> list[Commit]:
479
+ """Return all commits between upstream and branch.
480
+
481
+ If branch is None, the local branch is used.
482
+ """
483
+ if branch is None:
484
+ branch = self.local
485
+ commits = get_commits_between(self.upstream_name, branch)
486
+ return commits
487
+
488
+ def _make_commit_lists(
489
+ self,
490
+ branch_commands: typing.Iterable[_BranchCommand],
491
+ ) -> list[_CommitList]:
492
+ """Build lists of contiguous commits belonging to a branch."""
493
+ branches: list[_CommitList] = []
494
+ local_commits = iter(self._get_branch_commits())
495
+ for bc in branch_commands:
496
+ if len(branches) == 0 or bc.label != branches[-1].label:
497
+ branches.append(_CommitList(bc.label, None, []))
498
+ try:
499
+ commit = next(
500
+ c for c in local_commits if c.sha.startswith(bc.commit_sha)
501
+ )
502
+ except StopIteration:
503
+ raise PlanError("cannot match commits in plan to local commits")
504
+ branches[-1].commits.append(commit)
505
+ if bc.target_label is not None:
506
+ if branches[-1].target_label is None:
507
+ branch = branches.pop(-1)
508
+ branches.append(branch._replace(target_label=bc.target_label))
509
+ elif branches[-1].target_label != bc.target_label:
510
+ raise PlanError(
511
+ f"multiple targets specified for {branches[-1].label}"
512
+ )
513
+ return branches
514
+
515
+ def _build_tree(
516
+ self,
517
+ candidate_deltas: typing.Iterable[_CommitList],
518
+ ) -> dict[str, Delta]:
519
+ """Parse branching plan and return a branch DAG.
520
+
521
+ Enforce the following constraints on the DAG:
522
+
523
+ - branches point to either
524
+ - the target of the last branch
525
+ - one of the set of immediately preceding branches with the same target
526
+ - commits in a branch appear in the same order as the local commits
527
+ """
528
+ deltas: dict[str, Delta] = {}
529
+ last_target_label = None
530
+ valid_target_labels: set[None | str] = {None}
531
+ for d in candidate_deltas:
532
+ if d.target_label not in valid_target_labels:
533
+ hints = ["re-order commits with `dfl remix`."]
534
+ raise PlanError(
535
+ f'invalid target for "{d.label}": "{d.target_label}"', hints=hints
536
+ )
537
+ target_branch = None
538
+ if d.target_label is not None:
539
+ target_branch = deltas[d.target_label]
540
+ if d.target_label != last_target_label:
541
+ last_target_label = d.target_label
542
+ valid_target_labels = {last_target_label}
543
+ valid_target_labels.add(d.label)
544
+ deltas[d.label] = self._create_delta(d.commits, target_branch)
545
+ return {b.branch_name: b for b in deltas.values()}
546
+
547
+
548
+ def _tokenize_plan(plan: str) -> typing.Iterable[_BranchCommand]:
549
+ for line in iterate_plan(plan):
550
+ try:
551
+ command, sha, *_ = line.split()
552
+ except ValueError:
553
+ raise ParsingError(
554
+ "each line should contain at least a command and a commit SHA"
555
+ )
556
+ if command.startswith("d"):
557
+ m = re.match(r"d([0-9]*)(@d?([0-9]*))?$", command)
558
+ if not m:
559
+ raise ParsingError(f"unrecognized command: {command}")
560
+ label, _, target = m.groups()
561
+
562
+ yield _BranchCommand(label, target, sha)
563
+ elif command != "s":
564
+ raise ParsingError(f"unrecognized command: {command}")
565
+
566
+
567
+ def is_inside_work_tree() -> bool:
568
+ try:
569
+ utils.run("rev-parse", "--is-inside-work-tree")
570
+ except subprocess.CalledProcessError as cpe:
571
+ if cpe.returncode == 128:
572
+ return False
573
+ raise cpe
574
+ return True
575
+
576
+
577
+ def resolve_delta(name: str, branches: list[str]) -> str:
578
+ name = name.strip()
579
+ if not re.match(r"^[\w-]+$", name):
580
+ raise ValueError(f"Invalid name: {name}")
581
+ if m := re.match(r"^b?([0-9]+)$", name):
582
+ index = int(m.group(1))
583
+ if index < len(branches):
584
+ return branches[index]
585
+ matching_branches = [b for b in branches if name.lower() in b.lower()]
586
+ if len(matching_branches) == 1:
587
+ return matching_branches[0]
588
+ raise ValueError(f"Could not match {name} to a unique branch")
589
+
590
+
591
+ def write_plan(tree: dict[str, Delta]) -> None:
592
+ """Create feature branches based on the plan in tree.
593
+
594
+ Start at the roots of the tree and for each branch in the topologically
595
+ sorted branches, checkout its target (the upstream if None), delete the
596
+ branch if it already exists, create the branch, cherry-pick its commits.
597
+
598
+ Return a dictionary that maps each branch name to a boolean that is True
599
+ only if the branch already existed and was re-created.
600
+ """
601
+ dag: dict[str, list[str]] = {}
602
+ for name, delta in tree.items():
603
+ if name not in dag:
604
+ dag[name] = []
605
+ if delta.target is not None:
606
+ dag[name].append(delta.target.branch_name)
607
+ ts = TopologicalSorter(dag)
608
+ for branch_name in ts.static_order():
609
+ delta = tree[branch_name]
610
+ utils.checkout(delta.target_branch_name)
611
+ with utils.temporary_branch():
612
+ try:
613
+ delta.cherry_pick()
614
+ except CherryPickFailed:
615
+ try:
616
+ utils.run("cherry-pick", "--abort")
617
+ except subprocess.CalledProcessError:
618
+ click.echo("WARNING: Failed to abort cherry-pick.", err=True)
619
+ raise
620
+ if delta.branch_exists():
621
+ delta.delete_branch()
622
+ delta.create_branch()
623
+
624
+
625
+ def iterate_plan(plan: str):
626
+ """Iterate through lines, skipping empty lines or comments."""
627
+ for line in plan.split("\n"):
628
+ if line.startswith("#") or not line.strip():
629
+ continue
630
+ yield line
631
+
632
+
633
+ def get_remote_tracking_branch(branch) -> str:
634
+ return utils.run(
635
+ "for-each-ref", "--format=%(upstream:short)", f"refs/heads/{branch}"
636
+ ).strip()
637
+
638
+
639
+ def branch_up_to_date(branch):
640
+ remote_tracking_branch = get_remote_tracking_branch(branch)
641
+ if remote_tracking_branch == "":
642
+ raise NoRemoteTrackingBranch()
643
+ return utils.run("rev-parse", remote_tracking_branch) == utils.run(
644
+ "rev-parse", branch
645
+ )
646
+
647
+
648
+ def get_commits_between(rev_a, rev_b) -> list[Commit]:
649
+ """Return commits from rev_a up to and including rev_b."""
650
+ return get_commits(f"{rev_a}..{rev_b}")
651
+
652
+
653
+ def get_commits(commits: str, number: None | int = None) -> list[Commit]:
654
+ """Return commits chronological order."""
655
+ args = [
656
+ "rev-list",
657
+ "--no-merges",
658
+ "--format=oneline",
659
+ commits,
660
+ ]
661
+ if number is not None:
662
+ args += ["--max-count", str(number)]
663
+ rev_list_output = utils.run(*args, "--")
664
+ rev_list = reversed(rev_list_output.strip().split("\n"))
665
+ return [Commit.from_oneline(line) for line in rev_list if line]
666
+
667
+
668
+ def get_last_n_commits(rev, n) -> list[Commit]:
669
+ """Return at most n commits leading up to rev, including rev."""
670
+ return get_commits(rev, number=n)
671
+
672
+
673
+ def edit_interactively(contents: str, editor: str) -> str:
674
+ with tempfile.NamedTemporaryFile("w") as text_file:
675
+ text_file.write(contents)
676
+ text_file.seek(0)
677
+ subprocess.run([editor, text_file.name])
678
+ with open(text_file.name, "r") as text_file_read:
679
+ return text_file_read.read()
680
+
681
+
682
+ def get_config_paths():
683
+ paths = []
684
+ if is_inside_work_tree():
685
+ root_path = Path(utils.run("rev-parse", "--show-toplevel").strip())
686
+ paths = [root_path / ".dflock"]
687
+ paths.append(Path("~/.dflock").expanduser())
688
+ return paths
689
+
690
+
691
+ def read_config(ctx, cmd, path):
692
+ config = configparser.ConfigParser()
693
+ config["dflock"] = {
694
+ "upstream": DEFAULT_UPSTREAM,
695
+ "local": DEFAULT_LOCAL,
696
+ "remote": DEFAULT_REMOTE,
697
+ "anchor-commit": DEFAULT_BRANCH_ANCHOR,
698
+ "branch-template": DEFAULT_BRANCH_TEMPLATE,
699
+ "editor": DEFAULT_EDITOR,
700
+ }
701
+ if path is not None:
702
+ paths = [path]
703
+ else:
704
+ paths = get_config_paths()
705
+ config.read(paths)
706
+ return config
707
+
708
+
709
+ @click.group()
710
+ @click.option(
711
+ "-c",
712
+ "--config",
713
+ callback=read_config,
714
+ type=click.Path(
715
+ exists=True,
716
+ file_okay=True,
717
+ dir_okay=False,
718
+ readable=True,
719
+ allow_dash=False,
720
+ path_type=str,
721
+ ),
722
+ help="Use a custom config file.",
723
+ )
724
+ @click.pass_context
725
+ def cli_group(ctx, config):
726
+ ctx.ensure_object(dict)
727
+ ctx.obj["config"] = config
728
+
729
+
730
+ def cli_command(f):
731
+ @cli_group.command
732
+ @functools.wraps(f)
733
+ def wrapper(*args, **kwargs):
734
+ try:
735
+ return f(*args, **kwargs)
736
+ except (GitStateError, CherryPickFailed) as exc:
737
+ exc.handle_in_cli()
738
+
739
+ return wrapper
740
+
741
+
742
+ def cli():
743
+ try:
744
+ cli_group()
745
+ except subprocess.CalledProcessError as exc:
746
+ click.echo(f"Subprocess failed:\n{exc}\n", err=True)
747
+ click.echo(f"Captured output:\n{exc.output}\n{exc.stderr}\n", err=True)
748
+ raise
749
+
750
+
751
+ @cli_command
752
+ @click.argument(
753
+ "delta-references",
754
+ nargs=-1,
755
+ type=str,
756
+ )
757
+ @click.option(
758
+ "-w",
759
+ "--write",
760
+ is_flag=True,
761
+ type=bool,
762
+ help="Also detect the current plan and update the ephemeral branches.",
763
+ )
764
+ @click.option(
765
+ "-i",
766
+ "--interactive",
767
+ is_flag=True,
768
+ type=bool,
769
+ help="Ask for confirmation before pushing each branch.",
770
+ )
771
+ @click.option(
772
+ "-m",
773
+ "--merge-request",
774
+ is_flag=True,
775
+ type=bool,
776
+ help="Use Gitlab-compatible push-options to create a merge request.",
777
+ )
778
+ @click.option(
779
+ "-c",
780
+ "--change-request",
781
+ nargs=1,
782
+ type=str,
783
+ default=None,
784
+ metavar="INTEGRATION",
785
+ help="Create a change request using the provided INTEGRATION.",
786
+ )
787
+ @inside_work_tree
788
+ @pass_app
789
+ @valid_local_commits
790
+ def push(
791
+ app, delta_references, write, interactive, merge_request, change_request
792
+ ) -> None:
793
+ """Push deltas to the remote.
794
+
795
+ The optional argument DELTA_REFERENCES is a list of delta references. If
796
+ provided, only these deltas as pushed.
797
+
798
+ A delta reference is resolved as follows: If it is a number (optionally
799
+ prefixed by 'd'), checkout the delta branch that has that label in the
800
+ output of `dfl status`.
801
+
802
+ If not a number, match against delta-branch names and if there is a unique
803
+ match, checkout that branch.
804
+ """
805
+ if app.remote == "":
806
+ raise click.ClickException("Remote must be set.")
807
+ tree = app.reconstruct_tree()
808
+ if write:
809
+ with utils.return_to_head():
810
+ write_plan(tree)
811
+ click.echo("Delta branches updated.")
812
+ deltas = list(tree.values())
813
+ if len(delta_references) > 0:
814
+ branches = [d.branch_name for d in deltas]
815
+ try:
816
+ names = [resolve_delta(d, branches) for d in delta_references]
817
+ except ValueError as exc:
818
+ raise click.ClickException(str(exc))
819
+ deltas = [tree[n] for n in names]
820
+ for delta in deltas:
821
+ if interactive:
822
+ do_it = click.confirm(
823
+ f"Push {delta.branch_name} to {app.remote}?", default=True
824
+ )
825
+ if not interactive or do_it:
826
+ push_command = delta.get_force_push_command(
827
+ app.remote, merge_request=merge_request
828
+ )
829
+ click.echo(f"Pushing {delta.branch_name}.")
830
+ output = utils.run(*push_command)
831
+ click.echo(output)
832
+ if change_request is not None:
833
+ click.echo(f"Creating change request for {change_request}.")
834
+ command = app.create_change_request_command(
835
+ change_request, delta.branch_name, delta.target_branch_name
836
+ )
837
+ subprocess.run(command, shell=True)
838
+
839
+
840
+ @cli_command
841
+ @click.argument(
842
+ "strategy",
843
+ type=click.Choice(["detect", "stack", "flat", "empty"]),
844
+ default="detect",
845
+ )
846
+ @click.option(
847
+ "-e",
848
+ "--edit",
849
+ is_flag=True,
850
+ type=bool,
851
+ help="Set this flag to always edit the plan before executing it.",
852
+ )
853
+ @click.option(
854
+ "-s",
855
+ "--show",
856
+ is_flag=True,
857
+ type=bool,
858
+ help="Only show the plan without executing it.",
859
+ )
860
+ @inside_work_tree
861
+ @pass_app
862
+ @clean_work_tree
863
+ @valid_local_commits
864
+ @no_hot_branch
865
+ @undiverged
866
+ def plan(app, strategy, edit, show) -> None:
867
+ """Create a plan and update ephemeral branches.
868
+
869
+ The optional STRATEGY argument can be used to generate a plan. Available
870
+ strategies are:
871
+
872
+ \b
873
+ detect (default): use the last-applied plan
874
+ stack: create one delta per commit and make delta depend on the
875
+ previous one
876
+ flat: create one delta per commit
877
+ empty: do not create any deltas
878
+
879
+ Unless detect is used the previous plan will be overwritten.
880
+ """
881
+ if strategy == "stack":
882
+ tree = app.build_tree(stack=True)
883
+ elif strategy == "flat":
884
+ tree = app.build_tree(stack=False)
885
+ elif strategy == "empty":
886
+ tree = {}
887
+ elif strategy == "detect":
888
+ tree = app.reconstruct_tree()
889
+ else:
890
+ raise ValueError("This shouldn't happen")
891
+ plan = app.render_plan(tree)
892
+ if (edit or strategy == "detect") and not show:
893
+ new_plan = edit_interactively(plan + INSTRUCTIONS, app.editor)
894
+ new_plan = "\n".join(iterate_plan(new_plan))
895
+ if not new_plan.strip():
896
+ click.echo("Aborting.")
897
+ return
898
+ else:
899
+ new_plan = plan
900
+ if not show:
901
+ try:
902
+ tree = app.parse_plan(new_plan)
903
+ with utils.return_to_head():
904
+ write_plan(tree)
905
+ app.prune_local_branches(tree=tree)
906
+ if len(tree) > 0:
907
+ click.echo("Deltas written:")
908
+ app.print_deltas({b: None for b in tree.keys()})
909
+ click.echo("Run `dfl push` to push deltas to the remote.")
910
+ except (ParsingError, PlanError, CherryPickFailed) as exc:
911
+ click.echo(f"Received plan:\n\n{new_plan}\n")
912
+ exc.handle_in_cli()
913
+
914
+
915
+ @cli_command
916
+ @click.option(
917
+ "-t",
918
+ "--show-targets",
919
+ is_flag=True,
920
+ type=bool,
921
+ help="Print target of each branch",
922
+ )
923
+ @inside_work_tree
924
+ @pass_app
925
+ @local_and_upstream_exist
926
+ def status(app, show_targets) -> None:
927
+ """Show status of delta branches."""
928
+ diverged = utils.have_diverged(app.upstream_name, app.local)
929
+ on_local = utils.get_current_branch() == app.local
930
+ if on_local:
931
+ click.echo("On local branch.")
932
+ else:
933
+ click.echo("NOT on local branch.")
934
+ if diverged:
935
+ click.echo("Local and upstream have diverged")
936
+ if show_targets:
937
+ tree = app.reconstruct_tree()
938
+ else:
939
+ tree = {b: None for b in app.get_delta_branches()}
940
+ if len(tree) > 0:
941
+ click.echo("\nDeltas:")
942
+ app.print_deltas(tree)
943
+
944
+
945
+ @cli_command
946
+ @inside_work_tree
947
+ @clean_work_tree
948
+ @pass_app
949
+ @undiverged
950
+ @on_local
951
+ def remix(app) -> None:
952
+ """Alias for `git rebase -i <upstream>`.
953
+
954
+ Only works when on local branch.
955
+ """
956
+ subprocess.run(f"git rebase -i {app.upstream_name}", shell=True)
957
+ hot_branches = app.get_hot_branches()
958
+ app.prune_local_branches(hot_branches=hot_branches)
959
+ click.echo(
960
+ "Hint: if you changed or amended commits, you need to run `dfl write` to "
961
+ "update your delta branches."
962
+ )
963
+
964
+
965
+ @cli_command
966
+ @inside_work_tree
967
+ @pass_app
968
+ @valid_local_commits
969
+ @on_local
970
+ def pull(app) -> None:
971
+ """Alias for `git pull --rebase <upstream>`.
972
+
973
+ Only works when on local branch.
974
+ """
975
+ if app.remote == "":
976
+ raise click.ClickException("Remote must be set.")
977
+ hot_branches = app.get_hot_branches()
978
+ subprocess.run(f"git pull --rebase {app.remote} {app.upstream}", shell=True)
979
+ app.prune_local_branches(hot_branches=hot_branches)
980
+
981
+
982
+ @cli_command
983
+ @inside_work_tree
984
+ @pass_app
985
+ @undiverged
986
+ def log(app) -> None:
987
+ """Alias for `git log <local> ^<upstream>`."""
988
+ if utils.get_current_branch() != app.local:
989
+ click.echo("Warning: not on local branch.")
990
+ subprocess.run(f"git log {app.local} ^{app.upstream_name}", shell=True)
991
+
992
+
993
+ @cli_command
994
+ @inside_work_tree
995
+ @click.argument("reference", required=False, default=None, type=str)
996
+ @pass_app
997
+ @local_and_upstream_exist
998
+ def checkout(app, reference) -> None:
999
+ """Checkout deltas or the local branch.
1000
+
1001
+ If REFERENCE isn't provided, "local", or the name of the local branch,
1002
+ checkout the local branch.
1003
+
1004
+ Otherwise, REFERENCE is treated as a delta reference. If it is a number
1005
+ (optionally prefixed by 'd'), checkout the delta branch that has that label
1006
+ in the output of `dfl status`.
1007
+
1008
+ If not a number, match against delta-branch names and if there is a unique
1009
+ match, checkout that branch.
1010
+ """
1011
+ if reference in ["local", app.local, None]:
1012
+ branch = app.local
1013
+ else:
1014
+ branches = app.get_delta_branches()
1015
+ try:
1016
+ branch = resolve_delta(reference, branches)
1017
+ except ValueError as exc:
1018
+ raise click.ClickException(str(exc))
1019
+ subprocess.run(f"git checkout {branch}", shell=True)
1020
+
1021
+
1022
+ @cli_command
1023
+ @inside_work_tree
1024
+ @clean_work_tree
1025
+ @pass_app
1026
+ @no_hot_branch
1027
+ @undiverged
1028
+ def write(app) -> None:
1029
+ """Write ephemeral branches based on the current plan."""
1030
+ tree = app.reconstruct_tree()
1031
+ with utils.return_to_head():
1032
+ write_plan(tree)
1033
+ if len(tree) > 0:
1034
+ click.echo("Deltas written")
1035
+ app.print_deltas({b: None for b in tree.keys()})
1036
+ click.echo("Run `dfl push` to push deltas to the remote.")
1037
+
1038
+
1039
+ @cli_command
1040
+ @click.option("-y", "--yes", is_flag=True, help="Do not ask for confirmation.")
1041
+ @pass_app
1042
+ @inside_work_tree
1043
+ @local_and_upstream_exist
1044
+ def reset(app, yes) -> None:
1045
+ """Reset the plan.
1046
+
1047
+ This removes all dflock-managed branches.
1048
+ """
1049
+ branches = app.get_delta_branches()
1050
+ if len(branches) == 0:
1051
+ click.echo("No active branches found")
1052
+ return
1053
+ if not yes:
1054
+ click.echo("This will delete the following branches:")
1055
+ for branch_name in branches:
1056
+ click.echo(branch_name)
1057
+ confirmed = click.confirm("Continue?")
1058
+ if confirmed or yes:
1059
+ for branch_name in branches:
1060
+ utils.run("branch", "-D", branch_name)
1061
+
1062
+
1063
+ @cli_command
1064
+ @inside_work_tree
1065
+ def init() -> None:
1066
+ paths = get_config_paths()
1067
+ for path in paths:
1068
+ if path.exists():
1069
+ click.echo(f"Note: existing config found at {path}.")
1070
+ root_path = Path(utils.run("rev-parse", "--show-toplevel").strip())
1071
+ upstream = click.prompt("Name of your upstream branch?", default=DEFAULT_UPSTREAM)
1072
+ local = click.prompt("Name of your local branch?", default=DEFAULT_LOCAL)
1073
+ remote = click.prompt("Name of your remote?", default=DEFAULT_REMOTE)
1074
+ editor = click.prompt("Command for invoking your editor?", default=DEFAULT_EDITOR)
1075
+ config_path = root_path / ".dflock"
1076
+ click.confirm(
1077
+ f"Continue to write provided values to {config_path}?", abort=True, default="Y"
1078
+ )
1079
+ config = configparser.ConfigParser()
1080
+ with open(config_path, "w") as f:
1081
+ config["dflock"] = {
1082
+ "upstream": upstream,
1083
+ "local": local,
1084
+ "remote": remote,
1085
+ "editor": editor,
1086
+ }
1087
+ config.write(f)