|
| 1 | +import click |
| 2 | +import git |
| 3 | + |
| 4 | + |
| 5 | +def clone_commit(old, **kwargs): |
| 6 | + md = dict( |
| 7 | + message=old.message, |
| 8 | + parent_commits=old.parents, |
| 9 | + author=old.author, |
| 10 | + committer=old.committer, |
| 11 | + author_date=old.authored_datetime, |
| 12 | + commit_date=old.committed_datetime |
| 13 | + ) |
| 14 | + |
| 15 | + md.update(kwargs) |
| 16 | + |
| 17 | + return git.Commit.create_from_tree( |
| 18 | + old.repo, old.tree, **md) |
| 19 | + |
| 20 | + |
| 21 | +def replace(commit, target=None, seen=None, **kwargs): |
| 22 | + '''update commit <target> |
| 23 | +
|
| 24 | + traverse tree looking for target, then make any requested changes. |
| 25 | +
|
| 26 | + ensure we visit each node only once |
| 27 | + ''' |
| 28 | + |
| 29 | + if seen is None: |
| 30 | + seen = set() |
| 31 | + |
| 32 | + if commit.hexsha in seen: |
| 33 | + return commit |
| 34 | + |
| 35 | + seen.add(commit.hexsha) |
| 36 | + |
| 37 | + if commit == target: |
| 38 | + new = clone_commit(commit, **kwargs) |
| 39 | + return new |
| 40 | + |
| 41 | + parents = list(commit.parents) |
| 42 | + for i, parent in enumerate(parents): |
| 43 | + parents[i] = replace(parent, target=target, seen=seen, **kwargs) |
| 44 | + |
| 45 | + return clone_commit(commit, parent_commits=parents) |
| 46 | + |
| 47 | + |
| 48 | +@click.command() |
| 49 | +@click.option('-m', '--message', required=True) |
| 50 | +@click.argument('rev') |
| 51 | +def main(message, rev): |
| 52 | + repo = git.Repo() |
| 53 | + branch = repo.active_branch |
| 54 | + rev = repo.commit(rev) |
| 55 | + cur = repo.head.commit |
| 56 | + |
| 57 | + print('old:', branch.commit) |
| 58 | + new = replace(cur, target=rev, message=message) |
| 59 | + branch.set_commit(new) |
| 60 | + print('new:', branch.commit) |
| 61 | + |
| 62 | + |
| 63 | +if __name__ == '__main__': |
| 64 | + main() |
0 commit comments