|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# SPDX-License-Identifier: GPL-2.0 |
| 3 | +"""generate_rust_analyzer - Generates an out-of-tree module `rust-project.json` file for `rust-analyzer` |
| 4 | +based on the kernel rust-project.json. |
| 5 | +""" |
| 6 | + |
| 7 | +import argparse |
| 8 | +import json |
| 9 | +import logging |
| 10 | +import os |
| 11 | +import pathlib |
| 12 | +import sys |
| 13 | + |
| 14 | +def generate_rust_project(kdir, root_module): |
| 15 | + with open(kdir / "rust-project.json") as fd: |
| 16 | + rust_project = json.loads(fd.read()) |
| 17 | + |
| 18 | + crate_indices = {} |
| 19 | + |
| 20 | + for i, crate in enumerate(rust_project["crates"]): |
| 21 | + crate_indices[crate["display_name"]] = i |
| 22 | + |
| 23 | + # Prepend kdir to existing root_module |
| 24 | + crate["root_module"] = os.path.join(kdir, crate["root_module"]) |
| 25 | + if crate.get("source"): |
| 26 | + for e_dir in crate["source"].get("exclude_dirs", []): |
| 27 | + e_dir = os.path.join(kdir, e_dir) |
| 28 | + for i_dir in crate["source"].get("incude_dirs", []): |
| 29 | + i_dir = os.path.join(kdir, i_dir) |
| 30 | + |
| 31 | + # Finally, append this module as a crate |
| 32 | + rust_project["crates"].append({ |
| 33 | + "display_name": root_module.removesuffix(".rs"), |
| 34 | + "root_module": root_module, |
| 35 | + "is_workspace_member": False, |
| 36 | + "is_proc_macro": False, |
| 37 | + "deps": [ |
| 38 | + {"crate": index, "name": name} |
| 39 | + for name, index in crate_indices.items() |
| 40 | + if name == "kernel" |
| 41 | + ], |
| 42 | + "cfg": [], |
| 43 | + "edition": "2021", |
| 44 | + "env": { |
| 45 | + "RUST_MODFILE": "This is only for rust-analyzer" |
| 46 | + } |
| 47 | + }) |
| 48 | + return rust_project |
| 49 | + |
| 50 | + |
| 51 | +def main(): |
| 52 | + parser = argparse.ArgumentParser() |
| 53 | + parser.add_argument('--verbose', '-v', action='store_true') |
| 54 | + parser.add_argument("kdir", type=pathlib.Path) |
| 55 | + parser.add_argument("root_module", type=str) |
| 56 | + args = parser.parse_args() |
| 57 | + |
| 58 | + logging.basicConfig( |
| 59 | + format="[%(asctime)s] [%(levelname)s] %(message)s", |
| 60 | + level=logging.INFO if args.verbose else logging.WARNING |
| 61 | + ) |
| 62 | + |
| 63 | + rust_project = generate_rust_project(args.kdir, args.root_module) |
| 64 | + json.dump(rust_project, sys.stdout, sort_keys=True, indent=4) |
| 65 | + |
| 66 | +if __name__ == "__main__": |
| 67 | + main() |
0 commit comments