summaryrefslogtreecommitdiff
path: root/util/check_clang_format.py
blob: 3be63774f7ab7064b8eb9ab589259acb1f37338a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#!/usr/bin/env python3
# Copyright 2022 The ChromiumOS Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Validate all C source is formatted with clang-format.

This isn't very useful to users to call directly, but it is run it the
CQ.  Most users will likely find out they forgot to clang-format by
the pre-upload checks.
"""

import logging
import pathlib
import subprocess
import sys

from chromite.lib import commandline


def main(argv=None):
    """Find all C files and runs clang-format on them."""
    parser = commandline.ArgumentParser()
    parser.parse_args(argv)

    logging.info("Validating all code is formatted with clang-format.")
    ec_dir = pathlib.Path(__file__).resolve().parent.parent
    all_files = [
        ec_dir / path
        for path in subprocess.run(
            ["git", "ls-files", "-z"],
            check=True,
            cwd=ec_dir,
            stdout=subprocess.PIPE,
            encoding="utf-8",
        ).stdout.split("\0")
        if path
    ]

    clang_format_files = []
    for path in all_files:
        if not path.is_file() or path.is_symlink():
            continue
        if "third_party" in path.parts:
            continue
        if path.name.endswith(".c") or path.name.endswith(".h"):
            clang_format_files.append(path)

    result = subprocess.run(
        ["clang-format", "--dry-run", *clang_format_files],
        check=False,
        cwd=ec_dir,
        stderr=subprocess.PIPE,
        encoding="utf-8",
    )
    if result.stderr:
        logging.error("All C source must be formatted with clang-format!")
        for line in result.stderr.splitlines():
            logging.error("%s", line)
        return 1
    if result.returncode != 0:
        logging.error("clang-format failed with no output!")
        return result.returncode

    logging.info("No clang-format issues found!")
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))