Skip to main content

cargo_wizard/workspace/
manifest.rs

1use std::path::{Path, PathBuf};
2
3use anyhow::Context;
4use toml_edit::{Array, DocumentMut, Item, Value, table, value};
5
6use crate::template::{TemplateItemId, dev_profile, release_profile};
7use crate::{Template, TomlValue};
8
9/// Tries to resolve the workspace root manifest (Cargo.toml) path from the current directory.
10pub fn resolve_manifest_path() -> anyhow::Result<PathBuf> {
11    let cmd = cargo_metadata::MetadataCommand::new();
12    let metadata = cmd
13        .exec()
14        .map_err(|error| anyhow::anyhow!("Cannot get cargo metadata: {:?}", error))?;
15    let manifest_path = metadata
16        .workspace_root
17        .into_std_path_buf()
18        .join("Cargo.toml");
19    Ok(manifest_path)
20}
21
22#[derive(Clone, Copy, Debug)]
23pub enum BuiltinProfile {
24    Dev,
25    Release,
26}
27
28impl BuiltinProfile {
29    fn name(&self) -> &str {
30        match self {
31            BuiltinProfile::Dev => "dev",
32            BuiltinProfile::Release => "release",
33        }
34    }
35}
36
37#[derive(Clone, Debug)]
38pub enum Profile {
39    Builtin(BuiltinProfile),
40    Custom(String),
41}
42
43impl Profile {
44    pub fn dev() -> Self {
45        Self::Builtin(BuiltinProfile::Dev)
46    }
47
48    pub fn release() -> Self {
49        Self::Builtin(BuiltinProfile::Release)
50    }
51
52    pub fn name(&self) -> &str {
53        match self {
54            Profile::Builtin(builtin) => builtin.name(),
55            Profile::Custom(name) => name.as_str(),
56        }
57    }
58
59    pub fn is_builtin(&self) -> bool {
60        matches!(self, Profile::Builtin(_))
61    }
62}
63
64/// Manifest parsed out of a `Cargo.toml` file.
65#[derive(Clone)]
66pub struct CargoManifest {
67    path: PathBuf,
68    document: DocumentMut,
69}
70
71impl CargoManifest {
72    pub fn from_path(path: &Path) -> anyhow::Result<Self> {
73        let manifest = std::fs::read_to_string(path)
74            .with_context(|| format!("Cannot read Cargo.toml manifest from {}", path.display()))?;
75        let document = manifest
76            .parse::<DocumentMut>()
77            .with_context(|| format!("Cannot parse Cargo.toml manifest from {}", path.display()))?;
78        Ok(Self {
79            document,
80            path: path.to_path_buf(),
81        })
82    }
83
84    pub fn get_profiles(&self) -> Vec<String> {
85        self.document
86            .get("profile")
87            .and_then(|p| p.as_table_like())
88            .map(|t| t.iter().map(|(name, _)| name.to_string()).collect())
89            .unwrap_or_default()
90    }
91
92    pub fn get_text(&self) -> String {
93        self.document.to_string()
94    }
95
96    pub fn apply_template(
97        mut self,
98        profile: &Profile,
99        template: &Template,
100    ) -> anyhow::Result<Self> {
101        let profiles_table = self
102            .document
103            .entry("profile")
104            .or_insert(table())
105            .as_table_mut()
106            .ok_or_else(|| anyhow::anyhow!("The profile item in Cargo.toml is not a table"))?;
107        profiles_table.set_dotted(true);
108
109        let profile_table = profiles_table
110            .entry(profile.name())
111            .or_insert(table())
112            .as_table_mut()
113            .ok_or_else(|| {
114                anyhow::anyhow!(
115                    "The profile.{} table in Cargo.toml is not a table",
116                    profile.name()
117                )
118            })?;
119
120        // If we're applying the template to a built-in profile (dev or release), we skip the items
121        // that still have the default value.
122        // However, we don't do that for custom profiles based on dev/release, since dev/release
123        // might not actually contain the default values in that case.
124        let base_template = if profile.is_builtin() {
125            Some(match template.inherits() {
126                BuiltinProfile::Dev => dev_profile().build(),
127                BuiltinProfile::Release => release_profile().build(),
128            })
129        } else {
130            None
131        };
132        let mut values: Vec<_> = template
133            .iter_items()
134            .filter_map(|(id, value)| {
135                let name = id_to_item_name(id)?;
136
137                // Check if there is any existing value in the TOML profile table
138                let existing_value = profile_table.get(name).and_then(|item| {
139                    if let Some(value) = item.as_bool() {
140                        Some(TomlValue::Bool(value))
141                    } else if let Some(value) = item.as_integer() {
142                        Some(TomlValue::Int(value))
143                    } else {
144                        item.as_str()
145                            .map(|value| TomlValue::String(value.to_string()))
146                    }
147                });
148                // Check if we modify a built-in profile, and if we have a default vaule for this
149                // item in the profile.
150                let default_item = base_template.as_ref().and_then(|t| t.get_item(id).cloned());
151
152                // If we have the same value as the default, and the existing value also matches the
153                // default, skip this item.
154                let base_item = existing_value.or(default_item);
155                if let Some(base_value) = base_item
156                    && &base_value == value
157                {
158                    return None;
159                };
160
161                Some(TableItem {
162                    name: name.to_string(),
163                    value: value.clone(),
164                })
165            })
166            .collect();
167
168        if !profile.is_builtin() {
169            // Add "inherits" to the table
170            values.insert(0, TableItem::string("inherits", template.inherits().name()));
171        }
172
173        for entry in values {
174            let mut new_value = entry.value.to_toml_value();
175
176            if let Some(existing_item) = profile_table.get_mut(&entry.name) {
177                if let Some(value) = existing_item.as_value() {
178                    *new_value.decor_mut() = value.decor().clone();
179                }
180                *existing_item = value(new_value);
181            } else {
182                profile_table.insert(&entry.name, value(new_value));
183            }
184        }
185
186        // Add necessary Cargo features
187        if template.get_item(TemplateItemId::CodegenBackend).is_some()
188            && let Some(features) = self
189                .document
190                .entry("cargo-features")
191                .or_insert(Item::Value(Value::Array(Array::new())))
192                .as_array_mut()
193            && !features
194                .iter()
195                .any(|v| v.as_str() == Some("codegen-backend"))
196        {
197            features.push("codegen-backend");
198        }
199
200        Ok(self)
201    }
202
203    pub fn write(self) -> anyhow::Result<()> {
204        std::fs::write(self.path, self.document.to_string())
205            .context("Cannot write Cargo.toml manifest")?;
206        Ok(())
207    }
208}
209
210fn id_to_item_name(id: TemplateItemId) -> Option<&'static str> {
211    match id {
212        TemplateItemId::DebugInfo => Some("debug"),
213        TemplateItemId::SplitDebugInfo => Some("split-debuginfo"),
214        TemplateItemId::Strip => Some("strip"),
215        TemplateItemId::Lto => Some("lto"),
216        TemplateItemId::CodegenUnits => Some("codegen-units"),
217        TemplateItemId::Panic => Some("panic"),
218        TemplateItemId::OptimizationLevel => Some("opt-level"),
219        TemplateItemId::CodegenBackend => Some("codegen-backend"),
220        TemplateItemId::Incremental => Some("incremental"),
221        TemplateItemId::TargetCpuInstructionSet
222        | TemplateItemId::FrontendThreads
223        | TemplateItemId::Linker => None,
224    }
225}
226
227#[derive(Clone, Debug)]
228struct TableItem {
229    name: String,
230    value: TomlValue,
231}
232
233impl TableItem {
234    fn string(name: &str, value: &str) -> Self {
235        Self {
236            name: name.to_string(),
237            value: TomlValue::String(value.to_string()),
238        }
239    }
240}