Fixup script integration

A useful technique for interactive rebasing is to let git figure out if a staged change (must include removed lines!) can be associated with a recent commit, and automatically create a fixup commit. This can then be auto-squashed in place.

I added this to magit.

First, we need the fixup script itself. Make sure it is found in PATH!

# MIT License

# Copyright (c) 2024 Diez Roggisch

# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

import os
import sys
import subprocess
import re
import platform


USAGE = """\
Usage: %s [-n]

This tool will look at either your staged changes, if any, or your unstaged
changes otherwise, and try to figure out which commit they could be amending.
If all changes belong to the same base commit, it will automatically create a
"fixup!" commit for that base commit (unless the base commit is already on
master).

With -n it only prints what it would do (dry-run).
"""


HUNK_HEADER_RE = re.compile(r"@@ -(\d+)(?:,\d+)? \+\d+(?:,\d+)? @@")


def error(msg):
    print("%s." % msg)
    sys.exit(1)


def git(args, input=None):
    if platform.system() == "Windows":
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.dwFlags |= 1  # STARTF_USESHOWWINDOW
    else:
        startupinfo = None

    process = subprocess.Popen(
        ["git"] + args,
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        startupinfo=startupinfo,
    )
    output, err = process.communicate(
        input=None if input is None else input.encode("utf-8")
    )
    retcode = process.poll()
    if retcode:
        raise Exception("git call failed: %s" % args + "\n" + err)
    return output.decode("utf-8")


def parse_diff(diff):
    deleted_lines = []
    current_file = None
    hunk_base_offset = None  # Also serves as 'inside hunk' state
    for line in diff.splitlines():
        if line.startswith("diff --git"):
            current_file = None
            hunk_base_offset = None
        elif hunk_base_offset is None and line.startswith("--- "):
            current_file = line[6:].rstrip("\t")
        elif line.startswith("@@ "):
            assert current_file is not None
            m = HUNK_HEADER_RE.match(line)
            assert m, "Hunk header parse error in line %s" % line
            hunk_base_offset = int(m.groups()[0])
            hunk_offset = 0
        elif hunk_base_offset is not None:
            if line.startswith("-"):
                deleted_lines.append((current_file, hunk_base_offset + hunk_offset))
            hunk_offset += 1
    return deleted_lines


def get_commits(deleted_lines):
    commits = set()
    for file, line in deleted_lines:
        commit = git(["blame", "-l", "-L%d,+1" % line, "HEAD", "--", file]).split()[0]
        commits.add(commit)
    return commits


def get_subjects_for_commits(commits):
    output = git(
        ["rev-list", "--no-walk", "--pretty=oneline", "--stdin"],
        input="\n".join(commits),
    )
    commits_and_subjects = [line.split(None, 1) for line in output.splitlines()]
    return dict(commits_and_subjects)


def remove_fixup_or_squash_prefix(commit_subject):
    return re.sub("^(fixup! |squash! )", "", commit_subject)


def main(dry_run):
    use_index = True
    diff_args = ["diff-index", "--no-color", "-p", "-U0"]
    diff = git(diff_args + ["--cached", "HEAD"])
    if diff == "":
        diff = git(diff_args + ["HEAD"])
        use_index = False
    if diff == "":
        error("No changes to commit")

    deleted_lines = parse_diff(diff)
    if not deleted_lines:
        error("No deleted lines in diff; cannot determine base commit")

    commits = get_commits(deleted_lines)
    commits_and_subjects = get_subjects_for_commits(commits)

    if len(commits_and_subjects) > 1:
        pruned_subjects = [
            remove_fixup_or_squash_prefix(s) for s in commits_and_subjects.values()
        ]
        if len(set(pruned_subjects)) > 1:
            print("More than one base commit; giving up:")
            for commit, subject in commits_and_subjects.items():
                print("  %s %s" % (commit[:10], subject))
            sys.exit(1)
        else:
            print(
                "More than one base commit, but they all seem to be fixup or squash commits for the same base commit; continuing:"
            )
            for commit, subject in commits_and_subjects.items():
                print("  %s %s" % (commit[:10], subject))
            print("")

    commit = commits.pop()

    try:
        master_merge_base = git(["merge-base", "HEAD", "origin/master"]).rstrip("\n")
        if commit == git(["merge-base", commit, master_merge_base]).rstrip("\n"):
            print("Base commit is already on master; cannot fix it up:")
            print("  %s %s" % (commit[:10], commits_and_subjects[commit]))
            sys.exit(1)
    except SystemExit:
        raise
    except:
        pass

    commit_id = "(none)"
    try:
        if dry_run:
            print("(Dry run, not creating the commit for real)")
            return

        if not use_index:
            git(["add", "-u"])
        git(["commit", "--fixup=%s" % commit])
        commit_id = git(["rev-parse", "--short", "HEAD"]).rstrip("\n")
    except Exception:
        raise
    finally:
        print("Creating fixup commit %s for:" % commit_id)
        print("  %s %s" % (commit[:10], commits_and_subjects[commit]))


if __name__ == "__main__":
    cdup = git(["rev-parse", "--show-cdup"]).rstrip("\n")
    if cdup:
        os.chdir(cdup)

    dry_run = False
    if "-n" in sys.argv:
        sys.argv.remove("-n")
        dry_run = True

    if len(sys.argv) > 1:
        sys.stdout.write(USAGE % os.path.basename(sys.argv[0]))
        sys.exit(0)

    main(dry_run)

Then we hook the script into a keyboard command similar to "commit fixup" in magit.

(use-package magit
  :config
  (defun deets/magit-fixup ()
    (interactive)
      (let ((default-directory (magit-toplevel)))
        (message (concat "fixing things up in: " default-directory))
        (shell-command "fixup.py")
        (magit-status)))
  ;; remove the default binding that conflicts with my
  ;; rgrep binding. Strangely on the mac this
  ;; does not work on sytem start.
  (if (boundp 'magit-file-mode-map)
      (define-key magit-file-mode-map "\C-xg" nil))

  ;; this should be part of magit
  (require 'git-rebase)
  (define-key magit-status-mode-map (kbd "C-c f") 'deets/magit-fixup))

In a magit-buffer just press C-c f to fixup the staged lines.

Created: 2024-10-05 Sa 14:06

Validate