Repository: carbon-language/carbon-lang
File: scripts/create_compdb.py (Python)

Code before:
    # Only handle files where the object file argument is easily found as
    # the last argument, which matches the expected structure from Bazel.
    if not arguments or len(arguments) < 2 or arguments[-2] != "-o":
        return "unknown"
    obj_file = arguments[-1]

    # The configuration is the name of the subdirectory of `bazel-out`.
    if not obj_file.startswith("bazel-out/"):
        return "unknown"
    return str(obj_file.split("/")[1])


def _filter_compilation_database(file_path: str) -> None:
    """Filters out duplicate exec-configuration entries from the compilation
    database.
    """
    print("Filtering out duplicate exec-configuration entries...")
    try:
        with open(file_path, "r") as f:
            commands = json.load(f)
    except FileNotFoundError:
        print(f"Error: The file '{file_path}' was not found.")
        sys.exit(1)
    except json.JSONDecodeError:
        print(f"Error: The file '{file_path}' is not a valid JSON file.")
        sys.exit(1)

    # We want to skip compiles that were in the "exec" configuration for tools.
    # Because we generate compile commands for every target, these will already
    # be covered there and this creates a smaller and more minimal compilation
    # database.
    #
    # Detecting this based on the `-exec-` string in the configuration name of
    # the directory is a bit of a hack, but there doesn't appear to be any way
    # to filter these out using Bazel when creating the compilation database, or
    # a way to easily ask Bazel to compute what this string would be for th exec
    # configuration.
    filtered_commands = [
        entry
        for entry in commands
        if "-exec-" not in _get_config_for_entry(entry)
    ]

    with open(file_path, "w") as f:
        # Use indent=4 for a human-readable, pretty-printed output file
        json.dump(filtered_commands, f, indent=4)
    print(
        "Filtered out "
        f"{len(commands) - len(filtered_commands)} "
        "duplicate entries..."
    )

Review comment (suggestion):
Had you considered passing the string straight to exit?

```suggestion
        sys.exit(f"Error: The file '{file_path}' was not found.")
    except json.JSONDecodeError:
        sys.exit(f"Error: The file '{file_path}' is not a valid JSON file.")
```

Code after:
        "--alsologtostderr",
        action="store_true",
        help="Prints subcommand errors to stderr (default: False)",
    )
    parser.add_argument(
        "--dump-files",
        action="store_true",
        help="Dumps the full list of generated files (default: False)",
    )

    args = parser.parse_args()
    scripts_utils.chdir_repo_root()
    bazel = scripts_utils.locate_bazel()

    _build_generated_files(bazel, args.alsologtostderr, args.dump_files)

    print(
        "Generating compile_commands.json (may take a few minutes)...",
        flush=True,
    )
    subprocess.run(
        [
            bazel,
            "run",
            "@hedron_compile_commands//:refresh_all",
            "--",
            "--notool_deps",
        ]
    )


if __name__ == "__main__":
    main()