Commit 4dae990a authored by nimrod's avatar nimrod
Browse files

Allow pretty printing files in place.

So now this is sort-of Black for YAML files. Next, pre-commit hooks.
parent 2b6c9fe2
Loading
Loading
Loading
Loading
+0 −7
Original line number Diff line number Diff line
@@ -24,13 +24,6 @@ repos:
    hooks:
      - id: detect-secrets

  - repo: https://github.com/amperser/proselint.git
    rev: 0.10.2
    hooks:
      - id: proselint
        types: [plain-text]
        exclude: LICENSE

  - repo: https://gitlab.com/devopshq/gitlab-ci-linter.git
    rev: v1.0.2
    hooks:
+18 −10
Original line number Diff line number Diff line
@@ -16,7 +16,7 @@ Usage

.. code:: shell

   usage: yt [-h] [infile] [outfile]
    usage: yt [-h] [-i] [files ...]

    YAML tool, a clone of the json.tool Python module for YAML.

@@ -25,11 +25,19 @@ Usage
    documents (like comments and anchors).

    positional arguments:
     infile      a YAML file to be validated or pretty-printed
     outfile     write the output of infile to outfile
      files           a YAML file to be validated or pretty-printed

    optional arguments:
      -h, --help      show this help message and exit
      -i, --in-place  Perform the pretty-print in place, overwriting the existing files.

    When enabling --in-place, all files are processed as input files.
    When --in-place is not enabled and there are more then 2 files
    passed, the last files is considered as the output file. If you
    wish to pretty-print multiple files and output to standard out,
    specify the last file as "-" .
    Please note that specifying multiple input files will concatenate
    them, resulting in a single file that has multiple documents.

License
-------
+50 −21
Original line number Diff line number Diff line
@@ -9,41 +9,70 @@ documents (like comments and anchors).
import argparse
import pathlib
import sys
import textwrap
import ruamel.yaml  # pylint: disable=import-error


def main():
    """Main entrypoint."""
    epilog = textwrap.dedent(
        """
        When enabling --in-place, all files are processed as input files.
        When --in-place is not enabled and there are more then 2 files
        passed, the last files is considered as the output file. If you
        wish to pretty-print multiple files and output to standard out,
        specify the last file as "-" .
        Please note that specifying multiple input files will concatenate
        them, resulting in a single file that has multiple documents."""
    )
    parser = argparse.ArgumentParser(
        description=__doc__,
        epilog=epilog,
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    parser.add_argument(
        "infile",
        nargs="?",
        type=argparse.FileType(encoding="utf-8"),
        "files",
        nargs="*",
        type=pathlib.Path,
        help="a YAML file to be validated or pretty-printed",
        default=sys.stdin,
    )
    parser.add_argument(
        "outfile",
        nargs="?",
        type=pathlib.Path,
        help="write the output of infile to outfile",
        default=None,
        "-i",
        "--in-place",
        help="Perform the pretty-print in place, overwriting the existing files.",  # noqa: E501
        action="store_true",
    )
    options = parser.parse_args()
    with options.infile as infile:
    try:
        yaml = ruamel.yaml.YAML(typ="rt")
        yaml.explicit_start = True
        yaml.indent(mapping=2, sequence=4, offset=2)
        yaml.preserve_quotes = True
            if options.outfile is None:
                out = sys.stdout
        if options.in_place:
            if len(options.files) == 0:
                raise Exception("You must provide a list of files to process.")
            for file in options.files:
                with open(file, "r", encoding="utf-8") as infile:
                    docs = list(yaml.load_all(infile))
                with open(file, "w", encoding="utf-8") as outfile:
                    yaml.dump_all(docs, outfile)
        else:
            if len(options.files) < 2:
                outfile = sys.stdout
            elif options.files[-1] == "-":
                outfile = sys.stdout
                options.files.pop(-1)
            else:
                outfile = open(  # pylint: disable=consider-using-with
                    options.files[-1], "w", encoding="utf-8"
                )
                options.files.pop(-1)
            if options.files:
                for file in options.files:
                    with open(file, "r", encoding="utf-8") as infile:
                        yaml.dump_all(yaml.load_all(infile), outfile)
            else:
                out = options.outfile.open("w", encoding="utf-8")
            yaml.dump_all(yaml.load_all(infile), out)
                yaml.dump_all(yaml.load_all(sys.stdin), outfile)
    except Exception as ex:
        raise SystemExit(ex)  # pylint: disable=raise-missing-from