Skip to main content

wasi_virt_layer_cli/
config_checker.rs

1use std::fs;
2
3use camino::Utf8PathBuf;
4use eyre::Context as _;
5use toml_edit::{Document, DocumentMut, Item};
6
7/// Represents a single modification to a `Cargo.toml` file, storing both the original
8/// string and the applied changes so that it can be cleanly reverted later.
9#[derive(Debug, Clone)]
10pub struct TomlRestorer {
11    path: Utf8PathBuf,
12    original: String,
13    changed: String,
14}
15
16use std::sync::{Arc, Mutex};
17
18/// A thread-safe collection of `TomlRestorer` instances.
19///
20/// Automatically drops and reverts any `Cargo.toml` modifications if a thread panics.
21#[derive(Debug, Clone)]
22pub struct TomlRestorers {
23    inner: Arc<Mutex<Vec<TomlRestorer>>>,
24}
25
26impl Drop for TomlRestorers {
27    fn drop(&mut self) {
28        if std::thread::panicking() {
29            self.restore_if_needed();
30        }
31    }
32}
33
34impl TomlRestorers {
35    /// Creates a new, empty collection of `TomlRestorer` instances.
36    pub fn new() -> Self {
37        Self {
38            inner: Arc::new(Mutex::new(Vec::new())),
39        }
40    }
41
42    /// Creates a new `TomlRestorers` collection initialized with a single restorer.
43    pub fn with(restorer: TomlRestorer) -> Self {
44        Self {
45            inner: Arc::new(Mutex::new(vec![restorer])),
46        }
47    }
48
49    /// Extends the collection with multiple restorers.
50    pub fn extend(&mut self, restorers: Vec<TomlRestorer>) {
51        for restorer in restorers {
52            self.push(restorer);
53        }
54    }
55
56    /// Adds a single restorer to the collection.
57    pub fn push(&mut self, restorer: TomlRestorer) {
58        self.inner.lock().unwrap().push(restorer);
59    }
60
61    /// Restore if any restorers are present. This does not consume the restorers, but clears them after restoring.
62    pub fn restore_if_needed(&self) {
63        if let Ok(mut restorers) = self.inner.lock() {
64            if !restorers.is_empty() {
65                for restorer in restorers.iter() {
66                    let _ = std::fs::write(&restorer.path, &restorer.original);
67                }
68                restorers.clear();
69            }
70        }
71    }
72
73    /// Explicitly restores all recorded modifications and consumes the collection.
74    pub fn restore(self) -> eyre::Result<()> {
75        let mut restorers_lock = self
76            .inner
77            .lock()
78            .map_err(|_| eyre::eyre!("Failed to lock restorers"))?;
79        let restorers = std::mem::take(&mut *restorers_lock);
80        drop(restorers_lock); // Release lock before I/O
81        for restorer in restorers {
82            restorer.restore()?;
83        }
84        Ok(())
85    }
86}
87
88impl TomlRestorer {
89    /// Creates a new `TomlRestorer` recording the path, original content, and changed content.
90    pub fn new(path: &Utf8PathBuf, original: String, changed: String) -> Self {
91        Self {
92            path: path.clone(),
93            original,
94            changed,
95        }
96    }
97
98    /// Reads the original state, writes new content, and returns a restorer for later reversion.
99    pub fn with_write(path: &Utf8PathBuf, changed: String) -> eyre::Result<Self> {
100        let file_data = fs::read_to_string(&path).wrap_err("Failed to read manifest file")?;
101        fs::write(&path, &changed).wrap_err("Failed to write manifest file")?;
102        Ok(Self::new(path, file_data, changed))
103    }
104
105    /// Consumes the restorer by pushing it into a list and merging duplicates where possible.
106    pub fn push(self, mut restorers: Vec<TomlRestorer>) -> Vec<TomlRestorer> {
107        loop {
108            let mut merged = vec![];
109            let len = restorers.len();
110            for restorer in restorers {
111                merged.extend(self.merge(restorer));
112            }
113            if merged.len() == len {
114                break merged;
115            }
116            restorers = merged;
117        }
118    }
119
120    /// Merges this restorer with another, reducing redundant entries for the same file.
121    pub fn merge(&self, other: TomlRestorer) -> Vec<TomlRestorer> {
122        if self.path != other.path {
123            return vec![self.clone(), other];
124        }
125
126        if other.original == self.changed {
127            vec![TomlRestorer::new(
128                &self.path,
129                self.original.clone(),
130                other.changed,
131            )]
132        } else if self.original == other.changed {
133            vec![TomlRestorer::new(
134                &self.path,
135                other.original,
136                self.changed.clone(),
137            )]
138        } else if self.original == other.original {
139            panic!("Merging two same original toml restorer");
140        } else {
141            vec![self.clone(), other]
142        }
143    }
144
145    /// Reverts the file content to its original state recorded by this restorer.
146    pub fn restore(self) -> eyre::Result<()> {
147        fs::write(&self.path, self.original).wrap_err("Failed to write manifest file")?;
148        Ok(())
149    }
150}
151
152/// Indicates whether a feature is present and where it is enabled.
153pub enum HasFeature {
154    /// The feature is disabled.
155    Disabled,
156    /// The feature is enabled directly in the crate's `Cargo.toml`.
157    EnabledOnNormal,
158    /// The feature is inherited from the `[workspace.dependencies]` table.
159    EnabledOnWorkspace,
160}
161
162/// Verifies and manipulates Cargo manifest features for a specific crate.
163///
164/// Handles both the crate's individual `Cargo.toml` and the root workspace
165/// `Cargo.toml` to accurately determine and adjust feature sets.
166#[derive(Debug)]
167pub struct FeatureChecker<'a, 'b, 'c, 'd> {
168    feature: Option<&'a str>,
169    manifest_path: &'b Utf8PathBuf,
170    root_manifest_path: &'c Utf8PathBuf,
171    crate_name: &'d str,
172}
173
174impl<'a, 'b, 'c, 'd> FeatureChecker<'a, 'b, 'c, 'd> {
175    /// Initializes a new `FeatureChecker` targeting a specific feature across manifest boundaries.
176    pub const fn new(
177        feature: &'a str,
178        manifest_path: &'b Utf8PathBuf,
179        root_manifest_path: &'c Utf8PathBuf,
180        crate_name: &'d str,
181    ) -> Self {
182        Self {
183            feature: Some(feature),
184            manifest_path,
185            root_manifest_path,
186            crate_name,
187        }
188    }
189
190    /// Initializes a `FeatureChecker` without a specific feature target for general manifest checks.
191    pub const fn new_no_feature(
192        manifest_path: &'b Utf8PathBuf,
193        root_manifest_path: &'c Utf8PathBuf,
194        crate_name: &'d str,
195    ) -> Self {
196        Self {
197            manifest_path,
198            feature: None,
199            root_manifest_path,
200            crate_name,
201        }
202    }
203
204    fn has_feature(item: &Item, feature: &str) -> bool {
205        if item.is_none() {
206            return false;
207        }
208        match item {
209            Item::Table(table) => table.get("features").map_or(false, |v| {
210                v.as_array()
211                    .map(|arr| arr.iter().any(|s| s.as_str() == Some(feature)))
212                    .unwrap_or(false)
213            }),
214            Item::Value(toml_edit::Value::InlineTable(inline)) => {
215                inline.get("features").map_or(false, |v| {
216                    v.as_array()
217                        .map(|arr| arr.iter().any(|s| s.as_str() == Some(feature)))
218                        .unwrap_or(false)
219                })
220            }
221            _ => false,
222        }
223    }
224
225    fn read_manifest<T: std::str::FromStr<Err = toml_edit::TomlError>>(&self) -> eyre::Result<T> {
226        let file_data =
227            fs::read_to_string(&self.manifest_path).wrap_err("Failed to read manifest file")?;
228        let doc = file_data
229            .parse::<T>()
230            .wrap_err("Failed to parse manifest file")?;
231        Ok(doc)
232    }
233
234    fn read_workspace_manifest<T: std::str::FromStr<Err = toml_edit::TomlError>>(
235        &self,
236    ) -> eyre::Result<T> {
237        let file_data = fs::read_to_string(&self.root_manifest_path)
238            .wrap_err("Failed to read workspace manifest file")?;
239        let doc = file_data
240            .parse::<T>()
241            .wrap_err("Failed to parse workspace manifest file")?;
242        Ok(doc)
243    }
244
245    /// Investigates the current state of a feature within the manifest or workspace dependencies.
246    pub fn has(&self) -> eyre::Result<HasFeature> {
247        let Self {
248            crate_name,
249            feature,
250            ..
251        } = self;
252
253        let feature = feature.ok_or_else(|| eyre::eyre!("Feature is not set"))?;
254
255        let doc = self.read_manifest::<Document<String>>()?;
256
257        if doc
258            .get("dependencies")
259            .map_or(true, |inner| inner.is_none())
260        {
261            eyre::bail!("No dependencies found in manifest");
262        }
263
264        if doc["dependencies"]
265            .get(crate_name)
266            .map_or(true, |inner| inner.is_none())
267        {
268            eyre::bail!("Required crate `{crate_name}` not found in dependencies");
269        }
270
271        let crate_setting = &doc["dependencies"][crate_name];
272
273        // check normal crate setting
274        Ok(if Self::has_feature(crate_setting, feature) {
275            HasFeature::EnabledOnNormal
276        } else {
277            // check workspace
278            match &crate_setting.get("workspace") {
279                Some(v) if v.as_bool().unwrap_or(false) => {
280                    let doc = self.read_workspace_manifest::<Document<String>>()?;
281
282                    let crate_setting = &doc["workspace"]["dependencies"][crate_name];
283
284                    if Self::has_feature(crate_setting, feature) {
285                        HasFeature::EnabledOnWorkspace
286                    } else {
287                        HasFeature::Disabled
288                    }
289                }
290                None => HasFeature::Disabled,
291                _ => HasFeature::Disabled,
292            }
293        })
294    }
295
296    fn set_table(table: &mut Item, feature: &str, on: bool) -> eyre::Result<()> {
297        if on {
298            if matches!(table.get("features"), None) {
299                table["features"] = toml_edit::value(toml_edit::Array::new());
300            }
301            if table["features"]
302                .as_array()
303                .unwrap()
304                .iter()
305                .filter_map(|s| s.as_str())
306                .any(|s| s == feature)
307            {
308                return Ok(());
309            }
310            table["features"].as_array_mut().unwrap().push(feature);
311        } else {
312            if matches!(table.get("features"), None) {
313                return Ok(());
314            }
315            if table["features"]
316                .as_array()
317                .unwrap()
318                .iter()
319                .filter_map(|s| s.as_str())
320                .any(|s| s == feature)
321            {
322                table["features"]
323                    .as_array_mut()
324                    .unwrap()
325                    .retain(|s| s.as_str() != Some(feature));
326                if table["features"].as_array().unwrap().is_empty() {
327                    table["features"] = Item::None;
328                }
329            }
330        }
331
332        Ok(())
333    }
334
335    /// Dynamically enabling or disabling a specific feature and returns a restorer if changed.
336    pub fn set(&self, on: bool) -> eyre::Result<Option<TomlRestorer>> {
337        let Self {
338            feature,
339            manifest_path,
340            root_manifest_path,
341            crate_name,
342        } = self;
343
344        let feature = feature.ok_or_else(|| eyre::eyre!("Feature is not set"))?;
345
346        let now = self.has()?;
347        let mut doc = self.read_manifest::<DocumentMut>()?;
348
349        let crate_setting = &mut doc["dependencies"][crate_name];
350
351        let (path, data) = match (now, on) {
352            (HasFeature::Disabled, true) | (HasFeature::EnabledOnNormal, false) => {
353                Self::set_table(crate_setting, feature, on)?;
354                (manifest_path.to_owned(), doc)
355            }
356            (HasFeature::EnabledOnWorkspace, false) => {
357                log::warn!(
358                    "Feature `{feature}` is enabled on workspace, so changing it may affect other crates."
359                );
360
361                let mut doc = self.read_workspace_manifest::<DocumentMut>()?;
362                let crate_setting = &mut doc["workspace"]["dependencies"][crate_name];
363
364                Self::set_table(crate_setting, feature, on)?;
365
366                (root_manifest_path.to_owned(), doc)
367            }
368            _ => {
369                return Ok(None);
370            }
371        };
372
373        Ok(Some(TomlRestorer::with_write(&path, data.to_string())?))
374    }
375
376    /// Set [profile.release] debug = true/false
377    /// [profile.release]
378    /// debug = true
379    pub fn set_dwarf(&self, on: bool) -> eyre::Result<TomlRestorer> {
380        // if workspace, we set workspace
381        // else we set normal toml
382        fn set(doc: &mut DocumentMut, on: bool) -> eyre::Result<()> {
383            if let Some(debug) = doc.get_mut("profile.release") {
384                if debug.as_bool().unwrap_or(false) == on {
385                    return Ok(());
386                }
387                debug["debug"] = toml_edit::value(on);
388            }
389
390            if let Some(profile) = doc.get_mut("profile") {
391                if let Some(release) = profile.get_mut("release") {
392                    release["debug"] = toml_edit::value(on);
393                } else {
394                    profile["release"] = toml_edit::table();
395                    profile["release"]["debug"] = toml_edit::value(on);
396                }
397            } else {
398                // inline
399                let mut profile = toml_edit::Table::new();
400                profile.set_implicit(true);
401                profile["release"] = toml_edit::table();
402                profile["release"]["debug"] = toml_edit::value(on);
403                doc["profile"] = toml_edit::Item::Table(profile);
404            }
405
406            Ok(())
407        }
408
409        if self.manifest_path != self.root_manifest_path {
410            let mut doc = self.read_workspace_manifest::<DocumentMut>()?;
411            set(&mut doc, on)?;
412
413            return TomlRestorer::with_write(&self.root_manifest_path, doc.to_string());
414        }
415
416        let mut doc = self.read_manifest::<DocumentMut>()?;
417        set(&mut doc, on)?;
418        return TomlRestorer::with_write(&self.manifest_path, doc.to_string());
419    }
420}