Git's the nightclub, Perltidy's the bouncer

Yanick on 2008-02-09T22:18:41

I finally wrapped my CVS-encrusted mind around Git's hooks. Huzzah! The biggest hurdle, really, was realizing that there is no spoon.

Anyway, as I'm an unsalvageable slob who always forget to run perltidy before committing changes, I've written a pre-commit hook that makes sure that all Perl files to be committed are all clean, neat and tidy (and aborts the commit and chides me if they are not):

#!/usr/bin/perl

use Perl6::Slurp;

my $status = slurp '-|', 'git-status';

# only want what is going to be commited
$status =~ s/Changed but not updated.*$//s;

my @dirty =
  grep { !file_is_tidy($_) }                   # not tidy
  grep { /\.(pl|pod|pm|t)$/ }                  # perl file
  map  { /(?:modified|new file):\s+(\S+)/ }    # to be commited
  split "\n", $status;

exit 0 unless @dirty;                          # Alles gut

warn "following files are not tidy, aborting commit\n",
     map "\t$_\n" => @dirty;

exit 1;

### utility functions ###############################################

sub file_is_tidy {
    my $file = shift;

    my $original = slurp $file;
    my $tidied = slurp '-|', 'perltidy', $file, '-st';

    return $original eq $tidied;
}


Why bounce it?

clscott on 2008-02-11T16:32:30

When you can make it conform?

What's the issue with the hook running the code through Perl::Tidy and then committing it instead of
rejecting it and forcing the user to perform the task manually and hope that .perltidyrc are used by
the developer and the hook?

Clayton

Re:Why bounce it?

Yanick on 2008-02-11T17:00:58

I thought of doing that, but my little paranoid and control freak heart decided to go bouncy instead.

I love and trust Perltidy. But, just the same, I prefer to verify that the changes it makes don't break anything. Also, in the case that a file has to be tidied outside of the scope of the initially to-be-commited changes, I want to be able to split the commit into (a) tidying the file and (b) commiting the changes.

But that's all just personal taste. Modifying the hook to auto-tidy the commits should be trivial. You just have to ask yourself the question: "do you feel lucky? Well, do ya, punk?" :-)