Skip to main content

cargo/workspace/editor/
manifest.rs

1//! Parsing and editing of manifest files.
2
3use std::ops::{Deref, DerefMut};
4use std::path::{Path, PathBuf};
5use std::str;
6
7use anyhow::Context as _;
8
9use super::dependency::Dependency;
10use crate::util::closest;
11use crate::util::frontmatter::ScriptSource;
12use crate::workspace::dependency::DepKind;
13use crate::workspace::parser::is_embedded;
14use crate::workspace::{FeatureValue, Features, Workspace};
15use crate::{CargoResult, GlobalContext};
16
17/// Dependency table to add deps to.
18#[derive(Clone, Debug, PartialEq, Eq)]
19pub struct DepTable {
20    kind: DepKind,
21    target: Option<String>,
22}
23
24impl DepTable {
25    const KINDS: &'static [Self] = &[
26        Self::new().set_kind(DepKind::Normal),
27        Self::new().set_kind(DepKind::Development),
28        Self::new().set_kind(DepKind::Build),
29    ];
30
31    /// Reference to a Dependency Table.
32    pub const fn new() -> Self {
33        Self {
34            kind: DepKind::Normal,
35            target: None,
36        }
37    }
38
39    /// Choose the type of dependency.
40    pub const fn set_kind(mut self, kind: DepKind) -> Self {
41        self.kind = kind;
42        self
43    }
44
45    /// Choose the platform for the dependency.
46    pub fn set_target(mut self, target: impl Into<String>) -> Self {
47        self.target = Some(target.into());
48        self
49    }
50
51    /// Type of dependency.
52    pub fn kind(&self) -> DepKind {
53        self.kind
54    }
55
56    /// Platform for the dependency.
57    pub fn target(&self) -> Option<&str> {
58        self.target.as_deref()
59    }
60
61    /// Keys to the table.
62    pub fn to_table(&self) -> Vec<&str> {
63        if let Some(target) = &self.target {
64            vec!["target", target, self.kind.kind_table()]
65        } else {
66            vec![self.kind.kind_table()]
67        }
68    }
69}
70
71impl Default for DepTable {
72    fn default() -> Self {
73        Self::new()
74    }
75}
76
77impl From<DepKind> for DepTable {
78    fn from(other: DepKind) -> Self {
79        Self::new().set_kind(other)
80    }
81}
82
83/// An editable Cargo manifest.
84#[derive(Debug, Clone)]
85pub struct Manifest {
86    /// Manifest contents as TOML data.
87    pub data: toml_edit::DocumentMut,
88}
89
90impl Manifest {
91    /// Get the manifest's package name.
92    pub fn package_name(&self) -> CargoResult<&str> {
93        self.data
94            .as_table()
95            .get("package")
96            .and_then(|m| m.get("name"))
97            .and_then(|m| m.as_str())
98            .ok_or_else(parse_manifest_err)
99    }
100
101    /// Get the specified table from the manifest.
102    pub fn get_table<'a>(&'a self, table_path: &[String]) -> Option<&'a toml_edit::Item> {
103        /// Descend into a manifest until the required table is found.
104        fn descend<'a>(input: &'a toml_edit::Item, path: &[String]) -> Option<&'a toml_edit::Item> {
105            if let Some(segment) = path.get(0) {
106                let value = input.get(&segment)?;
107
108                if value.is_table_like() {
109                    descend(value, &path[1..])
110                } else {
111                    None
112                }
113            } else {
114                Some(input)
115            }
116        }
117
118        descend(self.data.as_item(), table_path)
119    }
120
121    /// Get the specified table from the manifest.
122    pub fn get_table_mut<'a>(
123        &'a mut self,
124        table_path: &[String],
125    ) -> Option<&'a mut toml_edit::Item> {
126        /// Descend into a manifest until the required table is found.
127        fn descend<'a>(
128            input: &'a mut toml_edit::Item,
129            path: &[String],
130        ) -> Option<&'a mut toml_edit::Item> {
131            if let Some(segment) = path.get(0) {
132                let mut default_table = toml_edit::Table::new();
133                default_table.set_implicit(true);
134                let value = input[&segment].or_insert(toml_edit::Item::Table(default_table));
135
136                if value.is_table_like() {
137                    descend(value, &path[1..])
138                } else {
139                    None
140                }
141            } else {
142                Some(input)
143            }
144        }
145
146        descend(self.data.as_item_mut(), table_path)
147    }
148
149    /// Get all sections in the manifest that exist and might contain
150    /// dependencies. The returned items are always `Table` or
151    /// `InlineTable`.
152    pub fn get_sections(&self) -> Vec<(DepTable, toml_edit::Item)> {
153        let mut sections = Vec::new();
154
155        for table in DepTable::KINDS {
156            let dependency_type = table.kind.kind_table();
157            // Dependencies can be in the three standard sections...
158            if self
159                .data
160                .get(dependency_type)
161                .map(|t| t.is_table_like())
162                .unwrap_or(false)
163            {
164                sections.push((table.clone(), self.data[dependency_type].clone()))
165            }
166
167            // ... and in `target.<target>.(build-/dev-)dependencies`.
168            let target_sections = self
169                .data
170                .as_table()
171                .get("target")
172                .and_then(toml_edit::Item::as_table_like)
173                .into_iter()
174                .flat_map(toml_edit::TableLike::iter)
175                .filter_map(|(target_name, target_table)| {
176                    let dependency_table = target_table.get(dependency_type)?;
177                    dependency_table.as_table_like().map(|_| {
178                        (
179                            table.clone().set_target(target_name),
180                            dependency_table.clone(),
181                        )
182                    })
183                });
184
185            sections.extend(target_sections);
186        }
187
188        sections
189    }
190
191    pub fn get_legacy_sections(&self) -> Vec<String> {
192        let mut result = Vec::new();
193
194        for dependency_type in ["dev_dependencies", "build_dependencies"] {
195            if self.data.contains_key(dependency_type) {
196                result.push(dependency_type.to_owned());
197            }
198
199            // ... and in `target.<target>.(build-/dev-)dependencies`.
200            result.extend(
201                self.data
202                    .as_table()
203                    .get("target")
204                    .and_then(toml_edit::Item::as_table_like)
205                    .into_iter()
206                    .flat_map(toml_edit::TableLike::iter)
207                    .filter_map(|(target_name, target_table)| {
208                        if target_table.as_table_like()?.contains_key(dependency_type) {
209                            Some(format!("target.{target_name}.{dependency_type}"))
210                        } else {
211                            None
212                        }
213                    }),
214            );
215        }
216        result
217    }
218}
219
220impl str::FromStr for Manifest {
221    type Err = anyhow::Error;
222
223    /// Read manifest data from string
224    fn from_str(input: &str) -> ::std::result::Result<Self, Self::Err> {
225        let d: toml_edit::DocumentMut = input.parse().context("manifest not valid TOML")?;
226
227        Ok(Manifest { data: d })
228    }
229}
230
231impl std::fmt::Display for Manifest {
232    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
233        self.data.fmt(f)
234    }
235}
236
237/// An editable Cargo manifest that is available locally.
238#[derive(Debug, Clone)]
239pub struct LocalManifest {
240    /// Path to the manifest.
241    pub path: PathBuf,
242    /// Manifest contents.
243    pub manifest: Manifest,
244    /// The raw, unparsed package file
245    pub raw: String,
246    /// Edit location for an embedded manifest, if relevant
247    pub embedded: Option<Embedded>,
248}
249
250impl Deref for LocalManifest {
251    type Target = Manifest;
252
253    fn deref(&self) -> &Manifest {
254        &self.manifest
255    }
256}
257
258impl DerefMut for LocalManifest {
259    fn deref_mut(&mut self) -> &mut Manifest {
260        &mut self.manifest
261    }
262}
263
264impl LocalManifest {
265    /// Construct the `LocalManifest` corresponding to the `Path` provided..
266    pub fn try_new(path: &Path) -> CargoResult<Self> {
267        if !path.is_absolute() {
268            anyhow::bail!("can only edit absolute paths, got {}", path.display());
269        }
270        let raw = cargo_util::paths::read(&path)?;
271        let mut data = raw.clone();
272        let mut embedded = None;
273        if is_embedded(path) {
274            let source = ScriptSource::parse(&data)?;
275            if let Some(frontmatter) = source.frontmatter_span() {
276                embedded = Some(Embedded::exists(frontmatter));
277                data = source.frontmatter().unwrap().to_owned();
278            } else if let Some(shebang) = source.shebang_span() {
279                embedded = Some(Embedded::after(shebang));
280                data = String::new();
281            } else {
282                // Insert after a byte order mark, if any
283                embedded = Some(Embedded::start(source.content_span().start));
284                data = String::new();
285            }
286        }
287        let manifest = data.parse().context("unable to parse Cargo.toml")?;
288        Ok(LocalManifest {
289            manifest,
290            path: path.to_owned(),
291            raw,
292            embedded,
293        })
294    }
295
296    /// Write changes back to the file.
297    pub fn write(&self) -> CargoResult<()> {
298        let mut manifest = self.manifest.data.to_string();
299        let raw = match self.embedded.as_ref() {
300            Some(Embedded::Implicit(start)) => {
301                if !manifest.ends_with("\n") {
302                    manifest.push_str("\n");
303                }
304                let fence = "---\n";
305                let prefix = &self.raw[0..*start];
306                let suffix = &self.raw[*start..];
307                let empty_line = if prefix.trim_start_matches('\u{feff}').is_empty() {
308                    "\n"
309                } else {
310                    ""
311                };
312                format!("{prefix}{fence}{manifest}{fence}{empty_line}{suffix}")
313            }
314            Some(Embedded::Explicit(span)) => {
315                if !manifest.ends_with("\n") {
316                    manifest.push_str("\n");
317                }
318                let prefix = &self.raw[0..span.start];
319                let suffix = &self.raw[span.end..];
320                format!("{prefix}{manifest}{suffix}")
321            }
322            None => manifest,
323        };
324        let new_contents_bytes = raw.as_bytes();
325
326        cargo_util::paths::write_atomic(&self.path, new_contents_bytes)
327    }
328
329    /// Lookup a dependency.
330    pub fn get_dependencies<'s>(
331        &'s self,
332        ws: &'s Workspace<'_>,
333        unstable_features: &'s Features,
334    ) -> impl Iterator<Item = (String, DepTable, CargoResult<Dependency>)> + 's {
335        let crate_root = self.path.parent().expect("manifest path is absolute");
336        self.get_sections()
337            .into_iter()
338            .filter_map(move |(table_path, table)| {
339                let table = table.into_table().ok()?;
340                Some(
341                    table
342                        .into_iter()
343                        .map(|(key, item)| (table_path.clone(), key, item))
344                        .collect::<Vec<_>>(),
345                )
346            })
347            .flatten()
348            .map(move |(table_path, dep_key, dep_item)| {
349                let dep = Dependency::from_toml(
350                    ws.gctx(),
351                    ws.root(),
352                    crate_root,
353                    unstable_features,
354                    &dep_key,
355                    &dep_item,
356                );
357                (dep_key, table_path, dep)
358            })
359    }
360
361    pub fn ensure_edition(&mut self) -> bool {
362        if self.embedded.is_none() {
363            return false;
364        }
365
366        let root = self.data.as_table_mut();
367        let package = root.entry("package").or_insert_with(|| {
368            let mut t = toml_edit::Table::new();
369            t.set_position(Some(-1));
370            t.into()
371        });
372        let Some(package) = package.as_table_like_mut() else {
373            return false;
374        };
375
376        let mut changed = false;
377        package.entry("edition").or_insert_with(|| {
378            changed = true;
379            crate::workspace::features::Edition::LATEST_STABLE
380                .to_string()
381                .into()
382        });
383
384        changed
385    }
386
387    /// Add entry to a Cargo.toml.
388    pub fn insert_into_table(
389        &mut self,
390        table_path: &[String],
391        dep: &Dependency,
392        gctx: &GlobalContext,
393        workspace_root: &Path,
394        unstable_features: &Features,
395    ) -> CargoResult<()> {
396        let crate_root = self
397            .path
398            .parent()
399            .expect("manifest path is absolute")
400            .to_owned();
401        let dep_key = dep.toml_key();
402
403        let table = self
404            .get_table_mut(table_path)
405            .expect("manifest validated, path should be to a table");
406        if let Some((mut dep_key, dep_item)) = table
407            .as_table_like_mut()
408            .unwrap()
409            .get_key_value_mut(dep_key)
410        {
411            dep.update_toml(
412                gctx,
413                workspace_root,
414                &crate_root,
415                unstable_features,
416                &mut dep_key,
417                dep_item,
418            )?;
419            if let Some(table) = dep_item.as_inline_table_mut() {
420                // So long as we don't have `Cargo.toml` auto-formatting and inline-tables can only
421                // be on one line, there isn't really much in the way of interesting formatting to
422                // include (no comments), so let's just wipe it clean
423                table.fmt();
424            }
425        } else {
426            let new_dependency =
427                dep.to_toml(gctx, workspace_root, &crate_root, unstable_features)?;
428            table[dep_key] = new_dependency;
429        }
430
431        Ok(())
432    }
433
434    /// Remove entry from a Cargo.toml.
435    pub fn remove_from_table(
436        &mut self,
437        table_path: &[String],
438        name: &str,
439    ) -> Result<(), MissingDependencyError> {
440        let parent_table = self
441            .get_table_mut(table_path)
442            .expect("manifest validated, path should be to a table");
443
444        match parent_table.get_mut(name).filter(|t| !t.is_none()) {
445            Some(dep) => {
446                // remove the dependency
447                *dep = toml_edit::Item::None;
448
449                // remove table if empty
450                if parent_table.as_table_like().unwrap().is_empty() {
451                    *parent_table = toml_edit::Item::None;
452                }
453            }
454            None => {
455                let names = parent_table
456                    .as_table_like()
457                    .map(|t| t.iter())
458                    .into_iter()
459                    .flatten();
460                let alt_name = closest(name, names.map(|(k, _)| k), |k| k).map(|n| n.to_owned());
461
462                // Search in other tables.
463                let sections = self.get_sections();
464                let found_table_path = sections.iter().find_map(|(t, i)| {
465                    let table_path: Vec<String> =
466                        t.to_table().iter().map(|s| s.to_string()).collect();
467                    i.get(name).is_some().then(|| table_path)
468                });
469
470                return Err(MissingDependencyError {
471                    expected_name: name.to_owned(),
472                    expected_path: table_path.to_owned(),
473                    alt_name: alt_name,
474                    alt_path: found_table_path,
475                });
476            }
477        }
478
479        Ok(())
480    }
481
482    /// Allow mutating dependencies, wherever they live.
483    /// Copied from cargo-edit.
484    pub fn get_dependency_tables_mut(
485        &mut self,
486    ) -> impl Iterator<Item = &mut dyn toml_edit::TableLike> + '_ {
487        let root = self.data.as_table_mut();
488        root.iter_mut().flat_map(|(k, v)| {
489            if DepTable::KINDS
490                .iter()
491                .any(|dt| dt.kind.kind_table() == k.get())
492            {
493                v.as_table_like_mut().into_iter().collect::<Vec<_>>()
494            } else if k == "workspace" {
495                v.as_table_like_mut()
496                    .unwrap()
497                    .iter_mut()
498                    .filter_map(|(k, v)| {
499                        if k.get() == "dependencies" {
500                            v.as_table_like_mut()
501                        } else {
502                            None
503                        }
504                    })
505                    .collect::<Vec<_>>()
506            } else if k == "target" {
507                v.as_table_like_mut()
508                    .unwrap()
509                    .iter_mut()
510                    .flat_map(|(_, v)| {
511                        v.as_table_like_mut().into_iter().flat_map(|v| {
512                            v.iter_mut().filter_map(|(k, v)| {
513                                if DepTable::KINDS
514                                    .iter()
515                                    .any(|dt| dt.kind.kind_table() == k.get())
516                                {
517                                    v.as_table_like_mut()
518                                } else {
519                                    None
520                                }
521                            })
522                        })
523                    })
524                    .collect::<Vec<_>>()
525            } else {
526                Vec::new()
527            }
528        })
529    }
530
531    /// Remove references to `dep_key` if its no longer present.
532    pub fn gc_dep(&mut self, dep_key: &str) {
533        let explicit_dep_activation = self.is_explicit_dep_activation(dep_key);
534        let status = self.dep_status(dep_key);
535
536        if let Some(toml_edit::Item::Table(feature_table)) =
537            self.data.as_table_mut().get_mut("features")
538        {
539            for (_feature, mut feature_values) in feature_table.iter_mut() {
540                if let toml_edit::Item::Value(toml_edit::Value::Array(feature_values)) =
541                    &mut feature_values
542                {
543                    fix_feature_activations(
544                        feature_values,
545                        dep_key,
546                        status,
547                        explicit_dep_activation,
548                    );
549                }
550            }
551        }
552    }
553
554    pub fn is_explicit_dep_activation(&self, dep_key: &str) -> bool {
555        if let Some(toml_edit::Item::Table(feature_table)) = self.data.as_table().get("features") {
556            for values in feature_table
557                .iter()
558                .map(|(_, a)| a)
559                .filter_map(|i| i.as_value())
560                .filter_map(|v| v.as_array())
561            {
562                for value in values.iter().filter_map(|v| v.as_str()) {
563                    let value = FeatureValue::new(value.into());
564                    if let FeatureValue::Dep { dep_name } = &value {
565                        if dep_name.as_str() == dep_key {
566                            return true;
567                        }
568                    }
569                }
570            }
571        }
572
573        false
574    }
575
576    fn dep_status(&self, dep_key: &str) -> DependencyStatus {
577        let mut status = DependencyStatus::None;
578        for (_, tbl) in self.get_sections() {
579            if let toml_edit::Item::Table(tbl) = tbl {
580                if let Some(dep_item) = tbl.get(dep_key) {
581                    let optional = dep_item
582                        .get("optional")
583                        .and_then(|i| i.as_value())
584                        .and_then(|i| i.as_bool())
585                        .unwrap_or(false);
586                    if optional {
587                        return DependencyStatus::Optional;
588                    } else {
589                        status = DependencyStatus::Required;
590                    }
591                }
592            }
593        }
594        status
595    }
596}
597
598impl std::fmt::Display for LocalManifest {
599    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
600        self.manifest.fmt(f)
601    }
602}
603
604/// Edit location for an embedded manifest
605#[derive(Clone, Debug)]
606pub enum Embedded {
607    /// Manifest is implicit
608    ///
609    /// This is the insert location for a frontmatter
610    Implicit(usize),
611    /// Manifest is explicit in a frontmatter
612    ///
613    /// This is the span of the frontmatter body
614    Explicit(std::ops::Range<usize>),
615}
616
617impl Embedded {
618    fn start(start: usize) -> Self {
619        Self::Implicit(start)
620    }
621
622    fn after(after: std::ops::Range<usize>) -> Self {
623        Self::Implicit(after.end)
624    }
625
626    fn exists(exists: std::ops::Range<usize>) -> Self {
627        Self::Explicit(exists)
628    }
629}
630
631#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
632enum DependencyStatus {
633    None,
634    Optional,
635    Required,
636}
637
638fn fix_feature_activations(
639    feature_values: &mut toml_edit::Array,
640    dep_key: &str,
641    status: DependencyStatus,
642    explicit_dep_activation: bool,
643) {
644    let remove_list: Vec<usize> = feature_values
645        .iter()
646        .enumerate()
647        .filter_map(|(idx, value)| value.as_str().map(|s| (idx, s)))
648        .filter_map(|(idx, value)| {
649            let parsed_value = FeatureValue::new(value.into());
650            match status {
651                DependencyStatus::None => match (parsed_value, explicit_dep_activation) {
652                    (FeatureValue::Feature(dep_name), false)
653                    | (FeatureValue::Dep { dep_name }, _)
654                    | (FeatureValue::DepFeature { dep_name, .. }, _) => dep_name == dep_key,
655                    _ => false,
656                },
657                DependencyStatus::Optional => false,
658                DependencyStatus::Required => match (parsed_value, explicit_dep_activation) {
659                    (FeatureValue::Feature(dep_name), false)
660                    | (FeatureValue::Dep { dep_name }, _) => dep_name == dep_key,
661                    (FeatureValue::Feature(_), true) | (FeatureValue::DepFeature { .. }, _) => {
662                        false
663                    }
664                },
665            }
666            .then(|| idx)
667        })
668        .collect();
669
670    // Remove found idx in revers order so we don't invalidate the idx.
671    for idx in remove_list.iter().rev() {
672        remove_array_index(feature_values, *idx);
673    }
674
675    if status == DependencyStatus::Required {
676        for value in feature_values.iter_mut() {
677            let parsed_value = if let Some(value) = value.as_str() {
678                FeatureValue::new(value.into())
679            } else {
680                continue;
681            };
682            if let FeatureValue::DepFeature {
683                dep_name,
684                dep_feature,
685                weak,
686            } = parsed_value
687            {
688                if dep_name == dep_key && weak {
689                    let mut new_value = toml_edit::Value::from(format!("{dep_name}/{dep_feature}"));
690                    *new_value.decor_mut() = value.decor().clone();
691                    *value = new_value;
692                }
693            }
694        }
695    }
696}
697
698pub fn str_or_1_len_table(item: &toml_edit::Item) -> bool {
699    item.is_str() || item.as_table_like().map(|t| t.len() == 1).unwrap_or(false)
700}
701
702fn parse_manifest_err() -> anyhow::Error {
703    anyhow::format_err!("unable to parse external Cargo.toml")
704}
705
706#[derive(Debug)]
707pub struct MissingDependencyError {
708    pub expected_name: String,
709    pub expected_path: Vec<String>,
710    pub alt_path: Option<Vec<String>>,
711    pub alt_name: Option<String>,
712}
713
714impl std::fmt::Display for MissingDependencyError {
715    fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
716        let expected_name = &self.expected_name;
717        let expected_path = self.expected_path.join(".");
718        write!(
719            fmt,
720            "the dependency `{expected_name}` could not be found in `{expected_path}`"
721        )?;
722        if let Some(alt_path) = &self.alt_path {
723            let alt_path = alt_path.join(".");
724            write!(
725                fmt,
726                "\n\nhelp: a dependency with the same name exists in `{alt_path}`"
727            )?;
728        } else if let Some(alt_name) = &self.alt_name {
729            write!(
730                fmt,
731                "\n\nhelp: a dependency with a similar name exists: `{alt_name}`"
732            )?;
733        }
734        Ok(())
735    }
736}
737
738impl std::error::Error for MissingDependencyError {}
739
740fn remove_array_index(array: &mut toml_edit::Array, index: usize) {
741    let value = array.remove(index);
742
743    // Captures all lines before leading whitespace
744    let prefix_lines = value
745        .decor()
746        .prefix()
747        .and_then(|p| p.as_str().expect("spans removed").rsplit_once('\n'))
748        .map(|(lines, _current)| lines);
749    // Captures all lines after trailing whitespace, before the next comma
750    let suffix_lines = value
751        .decor()
752        .suffix()
753        .and_then(|p| p.as_str().expect("spans removed").split_once('\n'))
754        .map(|(_current, lines)| lines);
755    let mut merged_lines = String::new();
756    if let Some(prefix_lines) = prefix_lines {
757        merged_lines.push_str(prefix_lines);
758        merged_lines.push('\n');
759    }
760    if let Some(suffix_lines) = suffix_lines {
761        merged_lines.push_str(suffix_lines);
762        merged_lines.push('\n');
763    }
764
765    let next_index = index; // Since `index` was removed, that effectively auto-advances us
766    if let Some(next) = array.get_mut(next_index) {
767        let next_decor = next.decor_mut();
768        let next_prefix = next_decor
769            .prefix()
770            .map(|s| s.as_str().expect("spans removed"))
771            .unwrap_or_default();
772        merged_lines.push_str(next_prefix);
773        next_decor.set_prefix(merged_lines);
774    } else {
775        let trailing = array.trailing().as_str().expect("spans removed");
776        merged_lines.push_str(trailing);
777        array.set_trailing(merged_lines);
778    }
779}