Skip to main content

r_description/
collections.rs

1//! Typed whole-field collection edits.
2
3use std::{borrow::Borrow, fmt::Display, str::FromStr};
4
5use r_metadata::{PositionedRemoteParseError, Relation, Remote, Url};
6
7use crate::{
8    Description, EditError, FieldName, FormatStyle, InvalidFieldName, InvalidLogicalValue,
9    LineEnding, LogicalValue,
10};
11
12/// Failure to serialize or apply a typed collection edit.
13#[derive(Debug, thiserror::Error)]
14pub enum CollectionEditError {
15    /// A structured DCF edit failed.
16    #[error(transparent)]
17    Edit(#[from] EditError),
18    /// An internal constant field name was rejected.
19    #[error(transparent)]
20    FieldName(#[from] InvalidFieldName),
21    /// A serialized collection cannot be represented as logical DCF text.
22    #[error(transparent)]
23    Value(#[from] InvalidLogicalValue),
24    /// A constructed remote serialized to invalid remote syntax.
25    #[error("remote at collection index {index} is invalid: {source}")]
26    Remote {
27        /// Zero-based collection index.
28        index: usize,
29        /// Typed parse failure for the serialized remote.
30        #[source]
31        source: PositionedRemoteParseError,
32    },
33}
34
35impl Description {
36    /// Sets the complete `Depends` collection in iteration order.
37    ///
38    /// # Errors
39    ///
40    /// Returns an error if the collection cannot be serialized or the field
41    /// cannot be edited.
42    pub fn set_depends<I, T>(&self, values: I) -> Result<Self, CollectionEditError>
43    where
44        I: IntoIterator<Item = T>,
45        T: Borrow<Relation>,
46    {
47        self.set_relations("Depends", values)
48    }
49
50    /// Sets the complete `Imports` collection in iteration order.
51    ///
52    /// # Errors
53    ///
54    /// Returns an error if the collection cannot be serialized or the field
55    /// cannot be edited.
56    pub fn set_imports<I, T>(&self, values: I) -> Result<Self, CollectionEditError>
57    where
58        I: IntoIterator<Item = T>,
59        T: Borrow<Relation>,
60    {
61        self.set_relations("Imports", values)
62    }
63
64    /// Sets the complete `Suggests` collection in iteration order.
65    ///
66    /// # Errors
67    ///
68    /// Returns an error if the collection cannot be serialized or the field
69    /// cannot be edited.
70    pub fn set_suggests<I, T>(&self, values: I) -> Result<Self, CollectionEditError>
71    where
72        I: IntoIterator<Item = T>,
73        T: Borrow<Relation>,
74    {
75        self.set_relations("Suggests", values)
76    }
77
78    /// Sets the complete `Enhances` collection in iteration order.
79    ///
80    /// # Errors
81    ///
82    /// Returns an error if the collection cannot be serialized or the field
83    /// cannot be edited.
84    pub fn set_enhances<I, T>(&self, values: I) -> Result<Self, CollectionEditError>
85    where
86        I: IntoIterator<Item = T>,
87        T: Borrow<Relation>,
88    {
89        self.set_relations("Enhances", values)
90    }
91
92    /// Sets the complete `LinkingTo` collection in iteration order.
93    ///
94    /// # Errors
95    ///
96    /// Returns an error if the collection cannot be serialized or the field
97    /// cannot be edited.
98    pub fn set_linking_to<I, T>(&self, values: I) -> Result<Self, CollectionEditError>
99    where
100        I: IntoIterator<Item = T>,
101        T: Borrow<Relation>,
102    {
103        self.set_relations("LinkingTo", values)
104    }
105
106    /// Sets the complete `VignetteBuilder` collection in iteration order.
107    ///
108    /// # Errors
109    ///
110    /// Returns an error if the collection cannot be serialized or the field
111    /// cannot be edited.
112    pub fn set_vignette_builder<I, T>(&self, values: I) -> Result<Self, CollectionEditError>
113    where
114        I: IntoIterator<Item = T>,
115        T: Borrow<Relation>,
116    {
117        self.set_relations("VignetteBuilder", values)
118    }
119
120    /// Sets the complete `Additional_repositories` collection in iteration order.
121    ///
122    /// # Errors
123    ///
124    /// Returns an error if the collection cannot be serialized or the field
125    /// cannot be edited.
126    pub fn set_additional_repositories<I, T>(&self, values: I) -> Result<Self, CollectionEditError>
127    where
128        I: IntoIterator<Item = T>,
129        T: Borrow<Url>,
130    {
131        let rendered = values
132            .into_iter()
133            .map(|value| value.borrow().to_string())
134            .collect::<Vec<_>>();
135        self.set_rendered_collection("Additional_repositories", &rendered)
136    }
137
138    /// Sets the complete `Remotes` collection in iteration order.
139    ///
140    /// # Errors
141    ///
142    /// Returns an error if a remote serializes to invalid syntax or the field
143    /// cannot be edited.
144    pub fn set_remotes<I, T>(&self, values: I) -> Result<Self, CollectionEditError>
145    where
146        I: IntoIterator<Item = T>,
147        T: Borrow<Remote>,
148    {
149        let mut rendered = Vec::new();
150        for (index, value) in values.into_iter().enumerate() {
151            let value = value.borrow().to_string();
152            Remote::from_str(&value)
153                .map_err(|source| CollectionEditError::Remote { index, source })?;
154            rendered.push(value);
155        }
156        self.set_rendered_collection("Remotes", &rendered)
157    }
158
159    fn set_relations<I, T>(&self, name: &str, values: I) -> Result<Self, CollectionEditError>
160    where
161        I: IntoIterator<Item = T>,
162        T: Borrow<Relation>,
163    {
164        self.set_rendered_collection(name, &render(values))
165    }
166
167    fn set_rendered_collection(
168        &self,
169        name: &str,
170        values: &[String],
171    ) -> Result<Self, CollectionEditError> {
172        if values.is_empty() {
173            return if self.field(name).is_some() {
174                self.remove_all(name).map_err(Into::into)
175            } else {
176                Ok(self.clone())
177            };
178        }
179
180        let value = LogicalValue::new(format!("\n{}", values.join(",\n")))?;
181        let name = FieldName::new(name)?;
182        let style = FormatStyle {
183            line_ending: self.collection_line_ending(name.as_str()),
184            continuation_indent: "    ".to_owned(),
185            space_after_colon: false,
186        };
187        self.parse
188            .set_unique(0, &name, &value, &style)
189            .map(Self::from_parse)
190            .map_err(Into::into)
191    }
192
193    fn collection_line_ending(&self, name: &str) -> LineEnding {
194        let raw = self
195            .field(name)
196            .or_else(|| self.primary_record()?.fields().last())
197            .map(|field| field.raw_text());
198        let source = raw
199            .filter(|raw| raw.contains(['\r', '\n']))
200            .unwrap_or_else(|| self.to_string());
201        match source.as_str() {
202            raw if raw.contains("\r\n") => LineEnding::CrLf,
203            raw if raw.contains('\r') => LineEnding::Cr,
204            _ => LineEnding::Lf,
205        }
206    }
207}
208
209fn render<I, T, V>(values: I) -> Vec<String>
210where
211    I: IntoIterator<Item = T>,
212    T: Borrow<V>,
213    V: Display + ?Sized,
214{
215    values
216        .into_iter()
217        .map(|value| value.borrow().to_string())
218        .collect()
219}