gitgit-blame

Is it possible to make a commit that does not rewrite the previous commit author?


I know this sounds bad but this is my use case.

We have a big old code base that always carries some dumb merge conflicts like extra commas or new formats.

We want to introduce an automatic code formatter to give consistence between the entire project and let it run for the complete project once and then automatically before each push.

Here comes the problem. We want to avoid, if possible, loss the information about who changed what in the previous commit since this big "format commit" just will contains spaces, new lines and maybe a couple of commas. Is this possible?


Solution

  • When you commit you can specify whatever author (and even committer, though I don't think that matters here) you want - which is why these values must not be used for any sort of sensitive audit (which is why GPG signing is a thing). I'll talk a bit about how, but then I'm going to explain why it's probably the wrong solution.

    Declaring who the author is... that's pretty easy. git commit has an --author option. (See https://git-scm.com/docs/git-commit.)

    git commit --author 'Bob <bob@company.com>'
    

    So you could write a script to grab that info from the previous commit (see https://git-scm.com/docs/git-show for one way to get it).

    But like I said, it's probably the wrong solution. Think about why you'd do it in the first place...

    From comments, it seems you're concerned about git blame output.

    IN general, why would it be any more accurate for blame to name "the last person who committed before the format commit", than for it to name 'the id that ran the formatting'? Suppose you have commits from Alice, Bob, and Charlie, and then a format commit.

    A -- B -- C -- F
    

    Now maybe Alice changed file-a.txt, and Bob changed file-b.txt, but even if Charlie only touched file-c.txt, if reformatting was required on any line from any of these files, that line will appear to be authored by Charlie. For my money, that's worse than having a service account run the formatting and just having blame "not know better".

    You could improve on that by putting a format commit after every "real" commit... but once you're doing that...

    Since you're only affecting the immediately-prior commit, you could use commit --amend when committing a formatting commit; by default this won't change teh original commit's author

    BUT that is a (small) history rewrite, so you'd really want to do it locally, before the affected commit is pushed. And once you've gone that far...

    Why not just set up hooks that won't accept the commit if it's improperly formatted? Your server could set a post-receive hook to check this, and most likely your users would then choose to add commit hooks so that the problem gets eliminated right away and they don't have to go back and fix it later.