xref: /DragonOS/build-scripts/kernel_build/src/utils/cargo_handler.rs (revision fae6e9ade46a52976ad5d099643d51cc20876448)
1 use std::{env, path::PathBuf};
2 
3 use crate::kconfig::Feature;
4 
5 lazy_static! {
6     static ref CARGO_HANDLER_DATA: CargoHandlerData = CargoHandlerData::new();
7 }
8 
9 struct CargoHandlerData {
10     target_arch: TargetArch,
11 }
12 
13 impl CargoHandlerData {
14     fn new() -> Self {
15         CargoHandlerData {
16             target_arch: TargetArch::new(),
17         }
18     }
19 }
20 
21 #[derive(Debug)]
22 pub struct CargoHandler;
23 
24 impl CargoHandler {
25     pub fn readenv(key: &str) -> Option<String> {
26         if let Ok(value) = env::var(key) {
27             Some(value)
28         } else {
29             None
30         }
31     }
32 
33     /// 获取当前编译的目标架构
34     pub fn target_arch() -> TargetArch {
35         CARGO_HANDLER_DATA.target_arch
36     }
37 
38     /// 设置Cargo对文件更改的监听
39     ///
40     /// ## Parameters
41     ///
42     /// - `files` - The files to set rerun build
43     pub fn emit_rerun_if_files_changed(files: &[PathBuf]) {
44         for f in files {
45             println!("cargo:rerun-if-changed={}", f.to_str().unwrap());
46         }
47     }
48 
49     /// 添加features
50     ///
51     /// ## Parameters
52     ///
53     /// - `features` - The features to be set
54     pub fn emit_features(features: &[Feature]) {
55         for f in features.iter() {
56             if f.enable() {
57                 println!("cargo:rustc-cfg=feature=\"{}\"", f.name());
58             }
59         }
60     }
61 }
62 
63 /// 目标架构
64 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
65 pub enum TargetArch {
66     X86_64,
67     Aarch64,
68     Riscv64,
69     Mips64,
70     Powerpc64,
71     S390x,
72     Sparc64,
73     Unknown,
74 }
75 
76 impl TargetArch {
77     pub fn new() -> Self {
78         let data = CargoHandler::readenv("CARGO_CFG_TARGET_ARCH")
79             .expect("CARGO_CFG_TARGET_ARCH is not set")
80             .to_ascii_lowercase();
81 
82         match data.as_str() {
83             "x86_64" => TargetArch::X86_64,
84             "aarch64" => TargetArch::Aarch64,
85             "riscv64" => TargetArch::Riscv64,
86             "mips64" => TargetArch::Mips64,
87             "powerpc64" => TargetArch::Powerpc64,
88             "s390x" => TargetArch::S390x,
89             "sparc64" => TargetArch::Sparc64,
90             _ => TargetArch::Unknown,
91         }
92     }
93 }
94