mvdan / sh

A shell parser, formatter, and interpreter with bash support; includes shfmt
https://pkg.go.dev/mvdan.cc/sh/v3
BSD 3-Clause "New" or "Revised" License
6.98k stars 332 forks source link

Add a pre-commit hook #976

Closed Freed-Wu closed 1 year ago

Freed-Wu commented 1 year ago

Refer https://pre-commit.com/#golang

Usage:

Shell developers can create a file named .pre-commit-config.yaml in their repos:

repos:
  - repo: https://github.com/Freed-Wu/sh
    rev: v3.6.0
    hooks:
      - id: shfmt

Then enable pre-commit by pre-commit install.

Then if they write a code like this:

if [[ $OSTYPE == msys2 || $OSTYPE == cygwin ]]; then
shopt -s completion_strip_exe
fi

When they git commit, pre-commit will auto run shftm -w for all shell files except zsh files:

[INFO] Initializing environment for https://github.com/Freed-Wu/sh.
[INFO] Installing environment for https://github.com/Freed-Wu/sh.
[INFO] Once installed this environment will be reused.
[INFO] This may take a few minutes...
shfmt.........................................................................Failed
- hook id: shfmt
- files were modified by this hook

Now your bash file has be changed to

if [[ $OSTYPE == msys2 || $OSTYPE == cygwin ]]; then
    shopt -s completion_strip_exe
fi

You must git add the_changed_bash_file, then git commit:

shfmt.........................................................................Passed

Now it is OK.

I think it will be useful for shell developers.

And if you merge this change, remember Publish a new version, because

repos:
  - repo: https://github.com/Freed-Wu/sh
    rev: v3.6.0
    hooks:
      - id: shfmt

Only download the shfmt of v3.6.0, which don't contain a pre-commit-hook.

Freed-Wu commented 1 year ago

Oh, I found #966 :smile: