1use std::fs;
2
3use camino::Utf8PathBuf;
4use eyre::Context as _;
5use toml_edit::{Document, DocumentMut, Item};
6
7#[derive(Debug, Clone)]
8pub struct TomlRestorer {
9 path: Utf8PathBuf,
10 original: String,
11 changed: String,
12}
13
14use std::sync::{Arc, Mutex};
15
16#[derive(Debug, Clone)]
17pub struct TomlRestorers {
18 inner: Arc<Mutex<Vec<TomlRestorer>>>,
19}
20
21impl Drop for TomlRestorers {
22 fn drop(&mut self) {
23 if std::thread::panicking() {
24 self.restore_if_needed();
25 }
26 }
27}
28
29impl TomlRestorers {
30 pub fn new() -> Self {
31 Self {
32 inner: Arc::new(Mutex::new(Vec::new())),
33 }
34 }
35
36 pub fn with(restorer: TomlRestorer) -> Self {
37 Self {
38 inner: Arc::new(Mutex::new(vec![restorer])),
39 }
40 }
41
42 pub fn extend(&mut self, restorers: Vec<TomlRestorer>) {
43 for restorer in restorers {
44 self.push(restorer);
45 }
46 }
47
48 pub fn push(&mut self, restorer: TomlRestorer) {
49 self.inner.lock().unwrap().push(restorer);
50 }
51
52 pub fn restore_if_needed(&self) {
54 if let Ok(mut restorers) = self.inner.lock() {
55 if !restorers.is_empty() {
56 for restorer in restorers.iter() {
57 let _ = std::fs::write(&restorer.path, &restorer.original);
58 }
59 restorers.clear();
60 }
61 }
62 }
63
64 pub fn restore(self) -> eyre::Result<()> {
65 let mut restorers_lock = self
66 .inner
67 .lock()
68 .map_err(|_| eyre::eyre!("Failed to lock restorers"))?;
69 let restorers = std::mem::take(&mut *restorers_lock);
70 drop(restorers_lock); for restorer in restorers {
72 restorer.restore()?;
73 }
74 Ok(())
75 }
76}
77
78impl TomlRestorer {
79 pub fn new(path: &Utf8PathBuf, original: String, changed: String) -> Self {
80 Self {
81 path: path.clone(),
82 original,
83 changed,
84 }
85 }
86
87 pub fn with_write(path: &Utf8PathBuf, changed: String) -> eyre::Result<Self> {
88 let file_data = fs::read_to_string(&path).wrap_err("Failed to read manifest file")?;
89 fs::write(&path, &changed).wrap_err("Failed to write manifest file")?;
90 Ok(Self::new(path, file_data, changed))
91 }
92
93 pub fn push(self, mut restorers: Vec<TomlRestorer>) -> Vec<TomlRestorer> {
94 loop {
95 let mut merged = vec![];
96 let len = restorers.len();
97 for restorer in restorers {
98 merged.extend(self.merge(restorer));
99 }
100 if merged.len() == len {
101 break merged;
102 }
103 restorers = merged;
104 }
105 }
106
107 pub fn merge(&self, other: TomlRestorer) -> Vec<TomlRestorer> {
108 if self.path != other.path {
109 return vec![self.clone(), other];
110 }
111
112 if other.original == self.changed {
113 vec![TomlRestorer::new(
114 &self.path,
115 self.original.clone(),
116 other.changed,
117 )]
118 } else if self.original == other.changed {
119 vec![TomlRestorer::new(
120 &self.path,
121 other.original,
122 self.changed.clone(),
123 )]
124 } else if self.original == other.original {
125 panic!("Merging two same original toml restorer");
126 } else {
127 vec![self.clone(), other]
128 }
129 }
130
131 pub fn restore(self) -> eyre::Result<()> {
132 fs::write(&self.path, self.original).wrap_err("Failed to write manifest file")?;
133 Ok(())
134 }
135}
136
137pub enum HasFeature {
138 Disabled,
139 EnabledOnNormal,
140 EnabledOnWorkspace,
141}
142
143#[derive(Debug)]
144pub struct FeatureChecker<'a, 'b, 'c, 'd> {
145 feature: Option<&'a str>,
146 manifest_path: &'b Utf8PathBuf,
147 root_manifest_path: &'c Utf8PathBuf,
148 crate_name: &'d str,
149}
150
151impl<'a, 'b, 'c, 'd> FeatureChecker<'a, 'b, 'c, 'd> {
152 pub const fn new(
153 feature: &'a str,
154 manifest_path: &'b Utf8PathBuf,
155 root_manifest_path: &'c Utf8PathBuf,
156 crate_name: &'d str,
157 ) -> Self {
158 Self {
159 feature: Some(feature),
160 manifest_path,
161 root_manifest_path,
162 crate_name,
163 }
164 }
165
166 pub const fn new_no_feature(
167 manifest_path: &'b Utf8PathBuf,
168 root_manifest_path: &'c Utf8PathBuf,
169 crate_name: &'d str,
170 ) -> Self {
171 Self {
172 manifest_path,
173 feature: None,
174 root_manifest_path,
175 crate_name,
176 }
177 }
178
179 fn has_feature(item: &Item, feature: &str) -> bool {
180 if item.is_none() {
181 return false;
182 }
183 match item {
184 Item::Table(table) => table.get("features").map_or(false, |v| {
185 v.as_array()
186 .map(|arr| arr.iter().any(|s| s.as_str() == Some(feature)))
187 .unwrap_or(false)
188 }),
189 Item::Value(toml_edit::Value::InlineTable(inline)) => {
190 inline.get("features").map_or(false, |v| {
191 v.as_array()
192 .map(|arr| arr.iter().any(|s| s.as_str() == Some(feature)))
193 .unwrap_or(false)
194 })
195 }
196 _ => false,
197 }
198 }
199
200 fn read_manifest<T: std::str::FromStr<Err = toml_edit::TomlError>>(&self) -> eyre::Result<T> {
201 let file_data =
202 fs::read_to_string(&self.manifest_path).wrap_err("Failed to read manifest file")?;
203 let doc = file_data
204 .parse::<T>()
205 .wrap_err("Failed to parse manifest file")?;
206 Ok(doc)
207 }
208
209 fn read_workspace_manifest<T: std::str::FromStr<Err = toml_edit::TomlError>>(
210 &self,
211 ) -> eyre::Result<T> {
212 let file_data = fs::read_to_string(&self.root_manifest_path)
213 .wrap_err("Failed to read workspace manifest file")?;
214 let doc = file_data
215 .parse::<T>()
216 .wrap_err("Failed to parse workspace manifest file")?;
217 Ok(doc)
218 }
219
220 pub fn has(&self) -> eyre::Result<HasFeature> {
221 let Self {
222 crate_name,
223 feature,
224 ..
225 } = self;
226
227 let feature = feature.ok_or_else(|| eyre::eyre!("Feature is not set"))?;
228
229 let doc = self.read_manifest::<Document<String>>()?;
230
231 if doc
232 .get("dependencies")
233 .map_or(true, |inner| inner.is_none())
234 {
235 eyre::bail!("No dependencies found in manifest");
236 }
237
238 if doc["dependencies"]
239 .get(crate_name)
240 .map_or(true, |inner| inner.is_none())
241 {
242 eyre::bail!("Crate `{crate_name}` not found in dependencies");
243 }
244
245 let crate_setting = &doc["dependencies"][crate_name];
246
247 Ok(if Self::has_feature(crate_setting, feature) {
249 HasFeature::EnabledOnNormal
250 } else {
251 match &crate_setting.get("workspace") {
253 Some(v) if v.as_bool().unwrap_or(false) => {
254 let doc = self.read_workspace_manifest::<Document<String>>()?;
255
256 let crate_setting = &doc["workspace"]["dependencies"][crate_name];
257
258 if Self::has_feature(crate_setting, feature) {
259 HasFeature::EnabledOnWorkspace
260 } else {
261 HasFeature::Disabled
262 }
263 }
264 None => HasFeature::Disabled,
265 _ => HasFeature::Disabled,
266 }
267 })
268 }
269
270 fn set_table(table: &mut Item, feature: &str, on: bool) -> eyre::Result<()> {
271 if on {
272 if matches!(table.get("features"), None) {
273 table["features"] = toml_edit::value(toml_edit::Array::new());
274 }
275 if table["features"]
276 .as_array()
277 .unwrap()
278 .iter()
279 .filter_map(|s| s.as_str())
280 .any(|s| s == feature)
281 {
282 return Ok(());
283 }
284 table["features"].as_array_mut().unwrap().push(feature);
285 } else {
286 if matches!(table.get("features"), None) {
287 return Ok(());
288 }
289 if table["features"]
290 .as_array()
291 .unwrap()
292 .iter()
293 .filter_map(|s| s.as_str())
294 .any(|s| s == feature)
295 {
296 table["features"]
297 .as_array_mut()
298 .unwrap()
299 .retain(|s| s.as_str() != Some(feature));
300 if table["features"].as_array().unwrap().is_empty() {
301 table["features"] = Item::None;
302 }
303 }
304 }
305
306 Ok(())
307 }
308
309 pub fn set(&self, on: bool) -> eyre::Result<Option<TomlRestorer>> {
310 let Self {
311 feature,
312 manifest_path,
313 root_manifest_path,
314 crate_name,
315 } = self;
316
317 let feature = feature.ok_or_else(|| eyre::eyre!("Feature is not set"))?;
318
319 let now = self.has()?;
320 let mut doc = self.read_manifest::<DocumentMut>()?;
321
322 let crate_setting = &mut doc["dependencies"][crate_name];
323
324 let (path, data) = match (now, on) {
325 (HasFeature::Disabled, true) | (HasFeature::EnabledOnNormal, false) => {
326 Self::set_table(crate_setting, feature, on)?;
327 (manifest_path.to_owned(), doc)
328 }
329 (HasFeature::EnabledOnWorkspace, false) => {
330 log::warn!(
331 "Feature `{feature}` is enabled on workspace, so changing it may affect other crates."
332 );
333
334 let mut doc = self.read_workspace_manifest::<DocumentMut>()?;
335 let crate_setting = &mut doc["workspace"]["dependencies"][crate_name];
336
337 Self::set_table(crate_setting, feature, on)?;
338
339 (root_manifest_path.to_owned(), doc)
340 }
341 _ => {
342 return Ok(None);
343 }
344 };
345
346 Ok(Some(TomlRestorer::with_write(&path, data.to_string())?))
347 }
348
349 pub fn set_dwarf(&self, on: bool) -> eyre::Result<TomlRestorer> {
353 fn set(doc: &mut DocumentMut, on: bool) -> eyre::Result<()> {
356 if let Some(debug) = doc.get_mut("profile.release") {
357 if debug.as_bool().unwrap_or(false) == on {
358 return Ok(());
359 }
360 debug["debug"] = toml_edit::value(on);
361 }
362
363 if let Some(profile) = doc.get_mut("profile") {
364 if let Some(release) = profile.get_mut("release") {
365 release["debug"] = toml_edit::value(on);
366 } else {
367 profile["release"] = toml_edit::table();
368 profile["release"]["debug"] = toml_edit::value(on);
369 }
370 } else {
371 let mut profile = toml_edit::Table::new();
373 profile.set_implicit(true);
374 profile["release"] = toml_edit::table();
375 profile["release"]["debug"] = toml_edit::value(on);
376 doc["profile"] = toml_edit::Item::Table(profile);
377 }
378
379 Ok(())
380 }
381
382 if self.manifest_path != self.root_manifest_path {
383 let mut doc = self.read_workspace_manifest::<DocumentMut>()?;
384 set(&mut doc, on)?;
385
386 return TomlRestorer::with_write(&self.root_manifest_path, doc.to_string());
387 }
388
389 let mut doc = self.read_manifest::<DocumentMut>()?;
390 set(&mut doc, on)?;
391 return TomlRestorer::with_write(&self.manifest_path, doc.to_string());
392 }
393}