0

Can pre-commit hooks (with pre-commit.com) add files to a commit?

My use case: I do work in jupyter notebooks. On commit, I want to generate and git-add an html version of any ipynb files in the commit.

Eg a commit hook like:

- repo: local
  hooks:
    - id: nb-as-html
      name: nb-as-html
      stages: [commit]
      language: system
      verbose: false
      pass_filenames: false
      always_run: true
      entry: find devtools \( -name \*.ipynb -not -name \*checkpoint.ipynb \) -type f -exec jupyter nbconvert --to HTML {} \; 

and add the file somehow to the commit.

How do I do this? Or is pre-commit not intended for this?

william_grisaitis
  • 5,170
  • 3
  • 33
  • 40
  • 1
    A git `pre-commit` hook can certainly add files to a commit (just use `git add` as you usually would). I guess you could have your [pre-commit](https://pre-commit.com/) hook call `git add` on the discovered files. – larsks May 21 '22 at 00:13
  • 3
    It *can* do that (with some restrictions). I would advise not doing that, though; it's impolite to change the user said they would like to commit. I don't want my pre-commit hook to *change* my commit, only to *inspect* it. I want to use a different command to change it. The fact that restrictions exist, which make this not always work, is another reason to avoid it. – torek May 21 '22 at 00:26
  • 2
    Here is a setup we use at my work to ensure file formatting is enforced when committing : we have two scripts, one `fmt.sh` which actually formats files on disk, and one `checkfmt.sh` which only checks whether running a file through `fmt.sh` yields a different result. Our `pre-commit` hook runs `checkfmt.sh` on each staged file, and blocks the commit if one file is incorrectly formatted. The developper can run `fmt.sh`, and always has the opportunity to *read the staged content* before committing. – LeGEC May 21 '22 at 05:35
  • Does this answer your question? [Can a Git hook automatically add files to the commit?](https://stackoverflow.com/questions/3284292/can-a-git-hook-automatically-add-files-to-the-commit) – Inigo Dec 16 '22 at 11:13

1 Answers1

1

It is possible to add files in a pre-commit hook, but it is not recommended to do so. The Git developers will usually fix issues that come up with this workflow, but they don't do so gladly and it's not something that is encouraged. In addition, the user will not have expected you to do this and may not be pleased that you have done so. Since hooks aren't cloned when you clone the repository (since that would allow executing arbitrary code), you also can't assume other contributors will run them.

In addition, you should avoid committing generated files to the repository altogether. That tends to bloat the repository and cause conflicts when merges or rebases happen down the line. You'd be better off generating this file in CI and uploading it somewhere else.

bk2204
  • 64,793
  • 6
  • 84
  • 100