= Hooks

== Using hooks

At the root of your repository, create a `.hooks.yml` file.
You can find the one for this repository link:.hooks.yml[here].
It has two main sections: `repos` and `hooks`.

`repos` defines which valid git URL to contact to get hook definitions.
`hooks` lets you choose which hooks to use.

..hooks.yml
[source,yaml]
----
repos:
  - url: https://github.com/paulollivier/rust-hooks
    # Optional version. Must be a valid git reference, such as a tag, a branch…
    # If left unspecified, will use the default branch for the given hook repository
    version: HEAD

hooks:
  - name: cargofmt
  - name: cargocheck
    on_event: # Hooks general config may be overridden
      - pre-commit
      - pre-push
----

=== List of available hooks

Feel free to expand this list via a https://github.com/paulollivier/git-hooks/issues/new?title=New%20hook%20repository[github issue]

* https://github.com/paulollivier/rust-hooks/

== Writing hooks

This requires 2 things: a git repository, and a file inside it named `hooks.yml`.
Not to be confused with `.hooks.yml`, which is for client configuration...

A good sample hook definition repo is https://github.com/paulollivier/rust-hooks/[rust-hooks].

=== The hooks.yml file

.hooks.yml
[source,yaml]
----

# begins by the root element, `hooks`
hooks:
  - name: rustfmt # a name

    on_event: # an event list to react to. defaults to pre-commit, if absent
      - pre-commit
    on_file_regex: # a list of file regexps. defaults to .*
      - .*\.rs
    action: "rustfmt {files}" # the action (cli) to perform.
    setup_script: rustfmt_setup.sh # an optional setup script
----

The `{files}` string seen above is a replacement token.
This string will be substituted to appropriate context-dependant values.
The following tables details the available replacement tokens.

[cols="1,3,3", options="header"]
.Replacement tokens
|===
| token | replaced by | example

| {files}
| all repository files matching any of `on_file_regex`
| rustfmt {files} => rustfmt /home/paul/dev/my-repo/src/main.rs /home/paul/dev/my-repo/src/utils.rs

| {changed_files}
| all repository files currently in the git index matching any of `on_file_regex`
| rustfmt {changed_files} => rustfmt /home/paul/dev/my-repo/src/main.rs

| {root}
| the path to the root of the current repository
| rustfmt {root} => rustfmt /home/paul/dev/my-repo
|===