|
| 1 | +use std::fmt; |
| 2 | +use std::str::FromStr; |
| 3 | + |
| 4 | +use thiserror::Error; |
| 5 | +use toml_edit::{Array, DocumentMut, Item, RawString, TomlError, Value}; |
| 6 | + |
| 7 | +use pep508_rs::{PackageName, Requirement}; |
| 8 | +use pypi_types::VerbatimParsedUrl; |
| 9 | + |
| 10 | +use crate::pyproject::PyProjectToml; |
| 11 | + |
| 12 | +/// Raw and mutable representation of a `pyproject.toml`. |
| 13 | +/// |
| 14 | +/// This is useful for operations that require editing an existing `pyproject.toml` while |
| 15 | +/// preserving comments and other structure, such as `uv add` and `uv remove`. |
| 16 | +pub struct PyProjectTomlMut { |
| 17 | + doc: DocumentMut, |
| 18 | +} |
| 19 | + |
| 20 | +#[derive(Error, Debug)] |
| 21 | +pub enum Error { |
| 22 | + #[error("Failed to parse `pyproject.toml`")] |
| 23 | + Parse(#[from] Box<TomlError>), |
| 24 | + #[error("Dependencies in `pyproject.toml` are malformed")] |
| 25 | + MalformedDependencies, |
| 26 | +} |
| 27 | + |
| 28 | +impl PyProjectTomlMut { |
| 29 | + /// Initialize a `PyProjectTomlMut` from a `PyProjectToml`. |
| 30 | + pub fn from_toml(pyproject: &PyProjectToml) -> Result<Self, Error> { |
| 31 | + Ok(Self { |
| 32 | + doc: pyproject.raw.parse().map_err(Box::new)?, |
| 33 | + }) |
| 34 | + } |
| 35 | + |
| 36 | + /// Adds a dependency. |
| 37 | + pub fn add_dependency(&mut self, req: &Requirement) -> Result<(), Error> { |
| 38 | + let deps = &mut self.doc["project"]["dependencies"]; |
| 39 | + if deps.is_none() { |
| 40 | + *deps = Item::Value(Value::Array(Array::new())); |
| 41 | + } |
| 42 | + let deps = deps.as_array_mut().ok_or(Error::MalformedDependencies)?; |
| 43 | + |
| 44 | + // Try to find matching dependencies. |
| 45 | + let mut to_replace = Vec::new(); |
| 46 | + for (i, dep) in deps.iter().enumerate() { |
| 47 | + if dep |
| 48 | + .as_str() |
| 49 | + .and_then(try_parse_requirement) |
| 50 | + .filter(|dep| dep.name == req.name) |
| 51 | + .is_some() |
| 52 | + { |
| 53 | + to_replace.push(i); |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + if to_replace.is_empty() { |
| 58 | + deps.push(req.to_string()); |
| 59 | + } else { |
| 60 | + // Replace the first occurrence of the dependency and remove the rest. |
| 61 | + deps.replace(to_replace[0], req.to_string()); |
| 62 | + for &i in to_replace[1..].iter().rev() { |
| 63 | + deps.remove(i); |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + reformat_array_multiline(deps); |
| 68 | + Ok(()) |
| 69 | + } |
| 70 | + |
| 71 | + /// Removes all occurrences of dependencies with the given name. |
| 72 | + pub fn remove_dependency(&mut self, req: &PackageName) -> Result<Vec<Requirement>, Error> { |
| 73 | + let deps = &mut self.doc["project"]["dependencies"]; |
| 74 | + if deps.is_none() { |
| 75 | + return Ok(Vec::new()); |
| 76 | + } |
| 77 | + |
| 78 | + let deps = deps.as_array_mut().ok_or(Error::MalformedDependencies)?; |
| 79 | + |
| 80 | + // Try to find matching dependencies. |
| 81 | + let mut to_remove = Vec::new(); |
| 82 | + for (i, dep) in deps.iter().enumerate() { |
| 83 | + if dep |
| 84 | + .as_str() |
| 85 | + .and_then(try_parse_requirement) |
| 86 | + .filter(|dep| dep.name == *req) |
| 87 | + .is_some() |
| 88 | + { |
| 89 | + to_remove.push(i); |
| 90 | + } |
| 91 | + } |
| 92 | + |
| 93 | + let removed = to_remove |
| 94 | + .into_iter() |
| 95 | + .rev() // Reverse to preserve indices as we remove them. |
| 96 | + .filter_map(|i| { |
| 97 | + deps.remove(i) |
| 98 | + .as_str() |
| 99 | + .and_then(|req| Requirement::from_str(req).ok()) |
| 100 | + }) |
| 101 | + .collect::<Vec<_>>(); |
| 102 | + |
| 103 | + if !removed.is_empty() { |
| 104 | + reformat_array_multiline(deps); |
| 105 | + } |
| 106 | + |
| 107 | + Ok(removed) |
| 108 | + } |
| 109 | +} |
| 110 | + |
| 111 | +impl fmt::Display for PyProjectTomlMut { |
| 112 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 113 | + self.doc.fmt(f) |
| 114 | + } |
| 115 | +} |
| 116 | + |
| 117 | +fn try_parse_requirement(req: &str) -> Option<Requirement<VerbatimParsedUrl>> { |
| 118 | + Requirement::from_str(req).ok() |
| 119 | +} |
| 120 | + |
| 121 | +/// Reformats a TOML array to multi line while trying to preserve all comments |
| 122 | +/// and move them around. This also formats the array to have a trailing comma. |
| 123 | +fn reformat_array_multiline(deps: &mut Array) { |
| 124 | + fn find_comments(s: Option<&RawString>) -> impl Iterator<Item = &str> { |
| 125 | + s.and_then(|x| x.as_str()) |
| 126 | + .unwrap_or("") |
| 127 | + .lines() |
| 128 | + .filter_map(|line| { |
| 129 | + let line = line.trim(); |
| 130 | + line.starts_with('#').then_some(line) |
| 131 | + }) |
| 132 | + } |
| 133 | + |
| 134 | + for item in deps.iter_mut() { |
| 135 | + let decor = item.decor_mut(); |
| 136 | + let mut prefix = String::new(); |
| 137 | + for comment in find_comments(decor.prefix()).chain(find_comments(decor.suffix())) { |
| 138 | + prefix.push_str("\n "); |
| 139 | + prefix.push_str(comment); |
| 140 | + } |
| 141 | + prefix.push_str("\n "); |
| 142 | + decor.set_prefix(prefix); |
| 143 | + decor.set_suffix(""); |
| 144 | + } |
| 145 | + |
| 146 | + deps.set_trailing(&{ |
| 147 | + let mut comments = find_comments(Some(deps.trailing())).peekable(); |
| 148 | + let mut rv = String::new(); |
| 149 | + if comments.peek().is_some() { |
| 150 | + for comment in comments { |
| 151 | + rv.push_str("\n "); |
| 152 | + rv.push_str(comment); |
| 153 | + } |
| 154 | + } |
| 155 | + if !rv.is_empty() || !deps.is_empty() { |
| 156 | + rv.push('\n'); |
| 157 | + } |
| 158 | + rv |
| 159 | + }); |
| 160 | + deps.set_trailing_comma(true); |
| 161 | +} |
0 commit comments