简体   繁体   中英

Force extension for given file type in a hook

How can I configure a pre-commit hook which will force yaml/yml files to have yaml extension. Pass:

lol.yaml

Fail:

lol.yml

List all the cached files excluding the deleted ones. Check the extension of each file. Fail the hook if any of them ends with .yml .

A demo in Bash,

#!/bin/bash

git diff --cached --name-status --diff-filter=d | awk '
    /\.yml$/ {
        print "ERROR: pre-commit failed"
        print $NF
        print "The extension \".yml\" is not allowed. Use \".yaml\" instead"
        exit 1
    }
'

The demo checks only the extension. You could also check if a file is really a YAML file before checking its extension when necessary. A YAML file starts with three dashes, so it's not complicated to find out the real YAML files.

Actually it turned out to be fairly easy. It's enough to add the following hook to the config:

  - repo: local
    hooks:
      - id: yaml-file-extension
        name: Check if YAML files has *.yaml extension.
        entry: YAML filenames must have .yaml extension.
        language: fail
        files: .yml$

It will not verify the content however, just the extension.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM