|
| 1 | +#!/usr/bin/env -S v -raw-vsh-tmp-prefix tmp |
| 2 | + |
| 3 | +import os |
| 4 | +import term |
| 5 | + |
| 6 | +// This script can be used to ensure that all commited V files are vfmt-ed automatically. |
| 7 | +// By default, once setup, it will run `v fmt -w` on them, before commiting them. |
| 8 | + |
| 9 | +// To use the script in your V project, you need to be in the main folder |
| 10 | +// of your project, then do the equivalent of: |
| 11 | +// ```sh |
| 12 | +// cp /PATH/TO_YOUR/V/cmd/tools/git_pre_commit_hook.vsh .git/hooks/pre-commit |
| 13 | +// chmod 755 .git/hooks/pre-commit |
| 14 | +// ``` |
| 15 | +// |
| 16 | +// Note: you can use this command: |
| 17 | +// `git config --bool --add hooks.stopCommitOfNonVfmtedVFiles true` |
| 18 | +// ... to make it just *prevent* the commiting of unformatted .v files, |
| 19 | +// i.e. stop the commiting, if they are not, but *without modifying them* |
| 20 | +// automatically (you will then need to run `v fmt -w` on them manually). |
| 21 | +// |
| 22 | +// Note 2: Git supports skipping the hooks, by passing the `--no-verify` option. |
| 23 | +// That can be used to commit some .v files that are not formatted, without removing |
| 24 | +// the hook. |
| 25 | + |
| 26 | +fn main() { |
| 27 | + // This hook cares only about the changed V files, that will be commited, as reported by git itself: |
| 28 | + changed := os.execute("git diff --cached --name-only --diff-filter=ACMR -- '*.v' '*.vsh' '*.vv'") |
| 29 | + if changed.output == '' { |
| 30 | + eprintln('>>> 0 changed V files found.') |
| 31 | + exit(0) |
| 32 | + } |
| 33 | + vfiles := changed.output.trim_space().split('\n') |
| 34 | + configured_stop_commiting := os.execute('git config --bool hooks.stopCommitOfNonVfmtedVFiles') |
| 35 | + if configured_stop_commiting.output.trim_space().bool() { |
| 36 | + verify_result := os.execute('v fmt -verify ${vfiles.join(' ')}') |
| 37 | + if verify_result.exit_code != 0 { |
| 38 | + eprintln(verify_result.output) |
| 39 | + } |
| 40 | + exit(verify_result.exit_code) |
| 41 | + } else { |
| 42 | + eprintln('The V pre commit hook will format $vfiles.len V file(s):') |
| 43 | + for vfile in vfiles { |
| 44 | + eprintln(' ${term.bold('$vfile')}') |
| 45 | + } |
| 46 | + os.system('v fmt -w ${vfiles.join(' ')}') |
| 47 | + os.system('git add ${vfiles.join(' ')}') |
| 48 | + } |
| 49 | +} |
0 commit comments