Abort commit if changeset generate pylint error

Sietse Brouwer sbbrouwer at gmail.com
Sat Feb 10 17:59:03 UTC 2018


Hi Diogo,

Two approaches you can use:

Approach 1: Lint the working directory's parent commit (in a temporary
clone), lint your working directory, and compare the error counts. If
your working directory has more errors than its parent, that means you
added errors. This approach is simplest, and I'd use it so long as (a)
you are okay with linting the entire repo twice, and (b) you are okay
with having all modified files count towards the check, whether you
are committing them or not. I've sketched some shell code below.

Approach 2, for when you MUST limit yourself to the changes you are
about to commit: inside a `pretxncommit` hook, the changeset about to
be commited is available as `tip`. You could ...

* get the diff with `hg export tip`,
* or get the list of files added and modified with `hg log -r tip
--template '{file_adds % "{file}\n"}\n{file_mods % "{file}\n"}'`,
* and get copies of those files with `hg cat SOME_FILE -r tip >
/tmp/SOME_FILE`, so you can lint them.

For Approach 2, here are two pretxncommit hooks that check for added
trailing whitespace. The first is a simple shell hook, the second a
more elaborate Python hook. The second is from my own dotfiles; it
adds some niceties/complications like not running on a merge (so I can
merge in someone else's dirty work), and printing the names of the
files whose patch added trailing whitespace.

* http://hgbook.red-bean.com/read/handling-repository-events-with-hooks.html#id403945
* https://bitbucket.org/sietsebb/dotfiles/src/5c76523/hg/hooks/whitespace.py?at=default&fileviewer=file-view-default

Below is a sketch of some shell code for Approach 1.

Hope this helps!

Cheers,
Sietse

    #!/bin/sh

    # Which commit in which repo do we want to make a copy of?

    working_directory_parent=$(hg id --id -r .)
    working_repo=$(hg root)

    # Let's make a copy of myrepo at /tmp/myrepo. (You could use `mktemp` if
    # you wanted a truly random temporary directory.)
    #
    # Because we are not rewriting history, it's okay to use `hg share`:
    # a cheap clone with shared history is exactly what we want.

    test_repo=/tmp/$(basename $working_repo)
    rm -r $test_repo
    hg share $repo $test_repo --noupdate

    # Let's count our parent commit's errors, and our own

    cd $test_repo
        hg update $working_directory_parent
        n_failures_parent=$(SOME CODE THAT COUNTS LINTING FAILURES)

    cd $working_repo
        n_failures_self=$(SOME CODE THAT COUNTS LINTING FAILURES)

    # End with the test (this is the final line, so its exit code is our
    # exit code): we have less or equal failures than our parent, right?

    /usr/bin/test $n_failures_self -le $n_failures_parent



More information about the Mercurial mailing list