Search code examples
jsonpre-commitpre-commit.com

pre-commit - validate json-like files


in our project we add a big number of json-like files, which have a json structure, but are named with .meta extension (not a .json). We would like to validate the files against the json-schema before pushing them to the repo.

We already use the pre-commit tool and I have found the check-jsonschema hook for pre-commit: https://github.com/python-jsonschema/check-jsonschema. I have already tested the plugin, but it only works for the files that are ended with the .json extensions, not the ‘.meta’ ones, even if I pass the proper regexp via the files parameter. So:

^data/.*\.json -> data/file1.json works (found a schema violation)
^data/.*\.meta -> data/file1.meta does not works (skips validating file)

Any workaround to make file names with .meta extension be validated?
Any suggestion of other pre-commit plugin?


Pre-commit configuration:

# .pre-commit-config.yaml
repos:
- repo: https://github.com/python-jsonschema/check-jsonschema
  rev: '0.27.3'
  hooks:
    - id: check-jsonschema
      name: Validate meta files
      args: ["--schemafile", "schemas/my_schema.json"]
      files: ^data/.*\.meta$

Schema file:

# schemas/my_schema.json
{
    "type": "object",
    "properties": {
        "my-key": {
            "type": "string"
        }
    },
    "required": [
        "my-key"
    ]
}

Example data:

# data/file1.meta
# data/file1.json
{
    “another-key”: “value”
}

Solution

  • that hook uses types by default to classify files

    since your .meta files are not going to be classified as either yaml or json you need to either (1) rename them so they are (by adding .json to the filenames) or (2) override the filtering to manually work via filename instead

    I would recommend adding a special hook and keeping the original one in place. using your example it would look something like this:

    repos:
    - repo: https://github.com/python-jsonschema/check-jsonschema
      rev: '0.27.3'
      hooks:
        - id: check-jsonschema
          # not necessary, but can be useful for `pre-commit run` if you have other `check-jsonschema` hooks
          alias: check-jsonschema-meta  
          name: Validate meta files
          args: ["--schemafile", "schemas/my_schema.json"]
          types_or: []  # reset to default
          files: ^data/.*\.meta$
    

    disclaimer: I wrote pre-commit