cargo_wizard/workspace/
manifest.rs

1use std::path::{Path, PathBuf};
2
3use anyhow::Context;
4use toml_edit::{table, value, Array, Document, Item, Value};
5
6use crate::template::{dev_profile, release_profile, TemplateItemId};
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: Document,
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::<Document>()
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 Some(name) = id_to_item_name(id) else {
136                    return None;
137                };
138
139                // Check if there is any existing value in the TOML profile table
140                let existing_value = profile_table.get(name).and_then(|item| {
141                    if let Some(value) = item.as_bool() {
142                        Some(TomlValue::Bool(value))
143                    } else if let Some(value) = item.as_integer() {
144                        Some(TomlValue::Int(value))
145                    } else if let Some(value) = item.as_str() {
146                        Some(TomlValue::String(value.to_string()))
147                    } else {
148                        None
149                    }
150                });
151                // Check if we modify a built-in profile, and if we have a default vaule for this
152                // item in the profile.
153                let default_item = base_template.as_ref().and_then(|t| t.get_item(id).cloned());
154
155                // If we have the same value as the default, and the existing value also matches the
156                // default, skip this item.
157                let base_item = existing_value.or(default_item);
158                if let Some(base_value) = base_item {
159                    if &base_value == value {
160                        return None;
161                    }
162                };
163
164                Some(TableItem {
165                    name: name.to_string(),
166                    value: value.clone(),
167                })
168            })
169            .collect();
170
171        if !profile.is_builtin() {
172            // Add "inherits" to the table
173            values.insert(0, TableItem::string("inherits", template.inherits().name()));
174        }
175
176        for entry in values {
177            let mut new_value = entry.value.to_toml_value();
178
179            if let Some(existing_item) = profile_table.get_mut(&entry.name) {
180                if let Some(value) = existing_item.as_value() {
181                    *new_value.decor_mut() = value.decor().clone();
182                }
183                *existing_item = value(new_value);
184            } else {
185                profile_table.insert(&entry.name, value(new_value));
186            }
187        }
188
189        // Add necessary Cargo features
190        if template.get_item(TemplateItemId::CodegenBackend).is_some() {
191            if let Some(features) = self
192                .document
193                .entry("cargo-features")
194                .or_insert(Item::Value(Value::Array(Array::new())))
195                .as_array_mut()
196            {
197                if !features
198                    .iter()
199                    .any(|v| v.as_str() == Some("codegen-backend"))
200                {
201                    features.push("codegen-backend");
202                }
203            }
204        }
205
206        Ok(self)
207    }
208
209    pub fn write(self) -> anyhow::Result<()> {
210        std::fs::write(self.path, self.document.to_string())
211            .context("Cannot write Cargo.toml manifest")?;
212        Ok(())
213    }
214}
215
216fn id_to_item_name(id: TemplateItemId) -> Option<&'static str> {
217    match id {
218        TemplateItemId::DebugInfo => Some("debug"),
219        TemplateItemId::SplitDebugInfo => Some("split-debuginfo"),
220        TemplateItemId::Strip => Some("strip"),
221        TemplateItemId::Lto => Some("lto"),
222        TemplateItemId::CodegenUnits => Some("codegen-units"),
223        TemplateItemId::Panic => Some("panic"),
224        TemplateItemId::OptimizationLevel => Some("opt-level"),
225        TemplateItemId::CodegenBackend => Some("codegen-backend"),
226        TemplateItemId::Incremental => Some("incremental"),
227        TemplateItemId::TargetCpuInstructionSet
228        | TemplateItemId::FrontendThreads
229        | TemplateItemId::Linker => None,
230    }
231}
232
233#[derive(Clone, Debug)]
234struct TableItem {
235    name: String,
236    value: TomlValue,
237}
238
239impl TableItem {
240    fn string(name: &str, value: &str) -> Self {
241        Self {
242            name: name.to_string(),
243            value: TomlValue::String(value.to_string()),
244        }
245    }
246}