Skip to content

yamlfix

Actions Status Actions Status Coverage Status

A simple opinionated yaml formatter that keeps your comments!

Installing

pip install yamlfix

Usage

Imagine we've got the following source code:

book_library:
- title: Why we sleep
  author: Matthew Walker
- title: Harry Potter and the Methods of Rationality
  author: Eliezer Yudkowsky

It has the following errors:

  • There is no --- at the top.
  • The indentation is all wrong.

After running yamlfix the resulting source code will be:

---
book_library:
  - title: Why we sleep
    author: Matthew Walker
  - title: Harry Potter and the Methods of Rationality
    author: Eliezer Yudkowsky

yamlfix can be used both as command line tool and as a library.

As a command line tool:

$: yamlfix file.yaml

As a library:

from yamlfix import fix_files

fix_files(['file.py'])

If instead of reading from a file you want to fix the code saved into a variable, use fix_code:

from yamlfix import fix_code

source_code = "a: 1"

fixed_code = fix_code(source_code)

assert fixed_code == "---\na: 1\n"

Features

yamlfix will do the following changes in your code:

  • Add the header --- to your file.
  • Correct truthy strings: 'True' -> true, 'no' -> 'false'
  • Remove unnecessary apostrophes: title: 'Why we sleep' -> title: Why we sleep.
  • Correct comments
  • Ensure that there is exactly one newline at the end of each file, to comply with the POSIX standard.
  • Split long lines.
  • Respect Jinja2 syntax.
  • Ensure a \n exists at the end of the file.

References

As most open sourced programs, yamlfix is standing on the shoulders of giants, namely:

yamlfmt
Inspiration and alternative of this program. I created a new one because the pace of their pull requests is really slow, they don't have tests, CI pipelines or documentation.
ruyaml
A git based community maintained for of ruamel yaml parser.
Click
Used to create the command line interface.
Pytest
Testing framework, enhanced by the awesome pytest-cases library that made the parametrization of the tests a lovely experience.
Mypy
Python static type checker.
Flakeheaven
Python linter with lots of checks.
Black
Python formatter to keep a nice style without effort.
Autoimport
Python formatter to automatically fix wrong import statements.
isort
Python formatter to order the import statements.
PDM
Command line tool to manage the dependencies.
Mkdocs
To build this documentation site, with the Material theme.
Safety
To check the installed dependencies for known security vulnerabilities.
Bandit
To finds common security issues in Python code.

Contributing

For guidance on setting up a development environment, and how to make a contribution to yamlfix, see Contributing to yamlfix.


Last update: 2022-08-08