Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ repos:
- id: yamlfmt
name: Format YAML files
description: Format YAML files
entry: pre_commit_hooks/yamlfmt
entry: python3 -m pre_commit_hooks.yamlfmt
language: python
types: [yaml]
additional_dependencies:
Expand All @@ -28,7 +28,7 @@ repos:
- id: yamlfmt
name: Format YAML files with overrides
description: Format YAML files with overrides
entry: pre_commit_hooks/yamlfmt
entry: python3 -m pre_commit_hooks.yamlfmt
language: python
files: .pre-commit-hooks.yaml
additional_dependencies:
Expand Down
16 changes: 8 additions & 8 deletions ci/test
Original file line number Diff line number Diff line change
Expand Up @@ -8,45 +8,45 @@ set -o pipefail
################################################################################
. ci/functions.sh

run pre_commit_hooks/yamlfmt --help
run python3 pre_commit_hooks/yamlfmt.py --help
echo

run pre-commit try-repo . --files .pre-commit-config.yaml

while read -r file; do
run pre_commit_hooks/yamlfmt --mapping 4 --sequence 6 --offset 4 "${file}"
run python3 pre_commit_hooks/yamlfmt.py --mapping 4 --sequence 6 --offset 4 "${file}"
done < <(find . -regex '.*\.yaml')

echo "[INFO] Use with xargs"
find . -regex '.*\.yaml' -print0 |
xargs -0 pre_commit_hooks/yamlfmt -m 4 -s 6 -o 4
xargs -0 python3 pre_commit_hooks/yamlfmt.py -m 4 -s 6 -o 4
echo

run pre_commit_hooks/yamlfmt -m 2 -s 2 -o 0 .pre-commit-hooks.yaml
run python3 pre_commit_hooks/yamlfmt.py -m 2 -s 2 -o 0 .pre-commit-hooks.yaml

# Ensure we never break multidoc.
TMP_FILE="$(mktemp pre-commit-hook-yamlfmt-test.XXXXXXXXXXXXXXXXXXXX)"
run cp -f ci/multidoc-before.txt "${TMP_FILE}"
run pre_commit_hooks/yamlfmt --mapping 4 --sequence 6 --offset 4 "${TMP_FILE}"
run python3 pre_commit_hooks/yamlfmt.py --mapping 4 --sequence 6 --offset 4 "${TMP_FILE}"
run diff ci/multidoc-after.yaml "${TMP_FILE}"
# If the diff fails, the temp file is still there to inspect.
run rm -f "${TMP_FILE}"

# Test preserve quotes
TMP_FILE="$(mktemp pre-commit-hook-yamlfmt-test.XXXXXXXXXXXXXXXXXXXX)"
run cp -f ci/quotes-before.txt "${TMP_FILE}"
run pre_commit_hooks/yamlfmt --mapping 4 --sequence 6 --offset 4 --preserve-quotes "${TMP_FILE}"
run python3 pre_commit_hooks/yamlfmt.py --mapping 4 --sequence 6 --offset 4 --preserve-quotes "${TMP_FILE}"
run diff ci/quotes-after.txt "${TMP_FILE}"
# If the diff fails, the temp file is still there to inspect.
run rm -f "${TMP_FILE}"

# Test width setting
TMP_FILE="$(mktemp pre-commit-hook-yamlfmt-test.XXXXXXXXXXXXXXXXXXXX)"
run cp -f ci/test-long.txt "${TMP_FILE}"
run pre_commit_hooks/yamlfmt --width 250 "${TMP_FILE}"
run python3 pre_commit_hooks/yamlfmt.py --width 250 "${TMP_FILE}"
# Width=250, no change
run diff ci/test-long.txt "${TMP_FILE}"
run pre_commit_hooks/yamlfmt --width 79 "${TMP_FILE}"
run python3 pre_commit_hooks/yamlfmt.py --width 79 "${TMP_FILE}"
# Now we should see no lines > 81 (it has some offset in ruamel)
run grep -v -q '.\{82\}' "${TMP_FILE}"
run rm -f "${TMP_FILE}"
Expand Down
1 change: 1 addition & 0 deletions pre_commit_hooks/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""Init to import yamlfmt."""
55 changes: 31 additions & 24 deletions pre_commit_hooks/yamlfmt → pre_commit_hooks/yamlfmt.py
100755 → 100644
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
#!/usr/bin/env python3
"""Format YAML files."""

import argparse
import sys
import argparse
from ruamel.yaml import YAML # pylint: disable=import-error

DEFAULT_INDENT = {
Expand All @@ -14,10 +13,10 @@

class Cli:
# pylint: disable=too-few-public-methods
""" command-line-interface """
"""Command-line-interface."""

def __init__(self):
""" initialize the CLI """
"""Initialize the CLI."""
parser = argparse.ArgumentParser(
description="Format YAML files",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
Expand Down Expand Up @@ -116,9 +115,12 @@ def __init__(self):
class Formatter:
"""
Reformat a yaml file with proper indentation.

Preserve comments.
"""

def __init__(self, **kwargs):
"""Initialize the formatter."""
yaml = YAML()
yaml.indent(
mapping=kwargs.get("mapping", DEFAULT_INDENT["mapping"]),
Expand All @@ -141,16 +143,16 @@ def represent_none(self, _data):
self.content = list({})

def format(self, path=None):
""" Read file and write it out to same path """
"""Read file and write it out to same path."""
if not path:
path = self.path
print(path, end="")
FORMATTER.parse_file(path)
FORMATTER.write_file(path)
self.parse_file(path)
self.write_file(path)
print(" Done")

def parse_file(self, path=None):
""" Read the file """
"""Read the file."""
if not path:
path = self.path
try:
Expand All @@ -160,7 +162,7 @@ def parse_file(self, path=None):
self.fail(f"Unable to read {path}")

def write_file(self, path=None):
""" Write the file """
"""Write the file."""
if not path:
path = self.path
try:
Expand All @@ -171,23 +173,28 @@ def write_file(self, path=None):

@staticmethod
def fail(msg):
""" Abort """
"""Abort."""
sys.stderr.write(msg)
sys.exit(1)


if __name__ == "__main__":
ARGS = Cli().parser.parse_args()
FORMATTER = Formatter(
mapping=ARGS.mapping,
sequence=ARGS.sequence,
offset=ARGS.offset,
colons=ARGS.colons,
width=ARGS.width,
preserve_quotes=ARGS.preserve_quotes,
preserve_null=ARGS.preserve_null,
explicit_start=ARGS.explicit_start,
explicit_end=ARGS.explicit_end
def main():
"""Fit formatter."""
args = Cli().parser.parse_args()
formatter = Formatter(
mapping=args.mapping,
sequence=args.sequence,
offset=args.offset,
colons=args.colons,
width=args.width,
preserve_quotes=args.preserve_quotes,
preserve_null=args.preserve_null,
explicit_start=args.explicit_start,
explicit_end=args.explicit_end
)
for file_name in ARGS.file_names:
FORMATTER.format(file_name)
for file_name in args.file_names:
formatter.format(file_name)


if __name__ == "__main__":
main()
11 changes: 5 additions & 6 deletions setup.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Fake setup for pre-commit hook."""

from setuptools import setup
from setuptools import find_packages

setup(
name='yamlfmt',
Expand All @@ -12,11 +13,9 @@
'ruamel.yaml>=0.16.10',
],

scripts=[
'pre_commit_hooks/yamlfmt',
],
packages=find_packages(),

# explicitly declare packages so setuptools does not attempt auto discovery
# taken from https://github.com/pypa/setuptools/issues/3197
packages=[],
entry_points={
'console_scripts':
['yamlfmt = pre_commit_hooks.yamlfmt:main']},
)