cargo/util/
machine_message.rs

1use std::path::{Path, PathBuf};
2
3use cargo_util_schemas::core::PackageIdSpec;
4use serde::Serialize;
5use serde::ser;
6use serde_json::value::RawValue;
7
8use crate::core::Target;
9
10pub trait Message: ser::Serialize {
11    fn reason(&self) -> &str;
12
13    fn to_json_string(&self) -> String {
14        #[derive(Serialize)]
15        struct WithReason<'a, S: Serialize> {
16            reason: &'a str,
17            #[serde(flatten)]
18            msg: &'a S,
19        }
20        let with_reason = WithReason {
21            reason: self.reason(),
22            msg: &self,
23        };
24        serde_json::to_string(&with_reason).unwrap()
25    }
26}
27
28#[derive(Serialize)]
29pub struct FromCompiler<'a> {
30    pub package_id: PackageIdSpec,
31    pub manifest_path: &'a Path,
32    pub target: &'a Target,
33    pub message: Box<RawValue>,
34}
35
36impl<'a> Message for FromCompiler<'a> {
37    fn reason(&self) -> &str {
38        "compiler-message"
39    }
40}
41
42#[derive(Serialize)]
43pub struct Artifact<'a> {
44    pub package_id: PackageIdSpec,
45    pub manifest_path: PathBuf,
46    pub target: &'a Target,
47    pub profile: ArtifactProfile,
48    pub features: Vec<String>,
49    pub filenames: Vec<PathBuf>,
50    pub executable: Option<PathBuf>,
51    pub fresh: bool,
52}
53
54impl<'a> Message for Artifact<'a> {
55    fn reason(&self) -> &str {
56        "compiler-artifact"
57    }
58}
59
60/// This is different from the regular `Profile` to maintain backwards
61/// compatibility (in particular, `test` is no longer in `Profile`, but we
62/// still want it to be included here).
63#[derive(Serialize)]
64pub struct ArtifactProfile {
65    pub opt_level: &'static str,
66    pub debuginfo: Option<ArtifactDebuginfo>,
67    pub debug_assertions: bool,
68    pub overflow_checks: bool,
69    pub test: bool,
70}
71
72/// Internally this is an enum with different variants, but keep using 0/1/2 as integers for compatibility.
73#[derive(Serialize)]
74#[serde(untagged)]
75pub enum ArtifactDebuginfo {
76    Int(u32),
77    Named(&'static str),
78}
79
80#[derive(Serialize)]
81pub struct BuildScript<'a> {
82    pub package_id: PackageIdSpec,
83    pub linked_libs: &'a [String],
84    pub linked_paths: &'a [String],
85    pub cfgs: &'a [String],
86    pub env: &'a [(String, String)],
87    pub out_dir: &'a Path,
88}
89
90impl<'a> Message for BuildScript<'a> {
91    fn reason(&self) -> &str {
92        "build-script-executed"
93    }
94}
95
96#[derive(Serialize)]
97pub struct BuildFinished {
98    pub success: bool,
99}
100
101impl Message for BuildFinished {
102    fn reason(&self) -> &str {
103        "build-finished"
104    }
105}