cargo_wizard/workspace/
manifest.rs1use 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
9pub 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#[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 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 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 let default_item = base_template.as_ref().and_then(|t| t.get_item(id).cloned());
151
152 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 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 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}