Skip to main content

r_packages/
edit.rs

1use std::{borrow::Borrow, error::Error, fmt};
2
3use r_dcf_syntax::{FieldName, InvalidFieldName, InvalidLogicalValue, LogicalValue};
4
5use crate::{LineEnding, PackageRecord, Packages, builder::separate_record};
6
7/// A failure to apply an immutable structured edit.
8#[derive(Debug, Clone, PartialEq, Eq)]
9pub enum EditError {
10    /// The selected record does not exist.
11    RecordOutOfBounds {
12        /// Requested zero-based record index.
13        index: usize,
14    },
15    /// No matching case-sensitive field exists.
16    FieldNotFound {
17        /// Requested case-sensitive field name.
18        name: String,
19    },
20    /// A new field name is invalid.
21    FieldName(InvalidFieldName),
22    /// A replacement value cannot be represented as logical DCF text.
23    Value(InvalidLogicalValue),
24}
25
26impl fmt::Display for EditError {
27    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
28        match self {
29            Self::RecordOutOfBounds { index } => {
30                write!(formatter, "record index {index} is out of bounds")
31            }
32            Self::FieldNotFound { name } => write!(formatter, "field {name:?} was not found"),
33            Self::FieldName(error) => error.fmt(formatter),
34            Self::Value(error) => error.fmt(formatter),
35        }
36    }
37}
38
39impl Error for EditError {}
40
41impl From<r_dcf_syntax::EditError> for EditError {
42    fn from(error: r_dcf_syntax::EditError) -> Self {
43        match error {
44            r_dcf_syntax::EditError::RecordOutOfBounds { index } => {
45                Self::RecordOutOfBounds { index }
46            }
47            r_dcf_syntax::EditError::FieldNotFound { name } => Self::FieldNotFound { name },
48        }
49    }
50}
51
52impl Packages {
53    /// Replaces the last matching field in one record.
54    ///
55    /// # Errors
56    ///
57    /// Returns an error for an invalid value or missing record or field.
58    pub fn replace_last(&self, record: usize, name: &str, value: &str) -> Result<Self, EditError> {
59        let value = LogicalValue::new(value).map_err(EditError::Value)?;
60        self.parse
61            .replace_last(record, name, &value)
62            .map(Self::from_parse)
63            .map_err(Into::into)
64    }
65
66    /// Replaces every matching field in one record.
67    ///
68    /// # Errors
69    ///
70    /// Returns an error for an invalid value or missing record or field.
71    pub fn replace_all(&self, record: usize, name: &str, value: &str) -> Result<Self, EditError> {
72        let value = LogicalValue::new(value).map_err(EditError::Value)?;
73        self.parse
74            .replace_all(record, name, &value)
75            .map(Self::from_parse)
76            .map_err(Into::into)
77    }
78
79    /// Inserts a field after the last matching anchor in one record.
80    ///
81    /// # Errors
82    ///
83    /// Returns an error for invalid input or a missing record or anchor.
84    pub fn insert_after(
85        &self,
86        record: usize,
87        after: &str,
88        name: &str,
89        value: &str,
90    ) -> Result<Self, EditError> {
91        let name = FieldName::new(name).map_err(EditError::FieldName)?;
92        let value = LogicalValue::new(value).map_err(EditError::Value)?;
93        self.parse
94            .insert_after(record, after, &name, &value)
95            .map(Self::from_parse)
96            .map_err(Into::into)
97    }
98
99    /// Removes the last matching field in one record.
100    ///
101    /// # Errors
102    ///
103    /// Returns an error when the record or field is missing.
104    pub fn remove_last(&self, record: usize, name: &str) -> Result<Self, EditError> {
105        self.parse
106            .remove_last(record, name)
107            .map(Self::from_parse)
108            .map_err(Into::into)
109    }
110
111    /// Removes every matching field in one record.
112    ///
113    /// # Errors
114    ///
115    /// Returns an error when the record or field is missing.
116    pub fn remove_all(&self, record: usize, name: &str) -> Result<Self, EditError> {
117        self.parse
118            .remove_all(record, name)
119            .map(Self::from_parse)
120            .map_err(Into::into)
121    }
122
123    /// Appends an owned or borrowed record, preserving all existing document text.
124    /// Reuses existing blank separators, completing an unterminated blank line
125    /// when necessary. Otherwise uses the preceding newline convention, or
126    /// `line_ending` if the last record has no trailing newline.
127    ///
128    /// This immutable edit copies and reparses the document. For bulk construction,
129    /// use [`Self::from_records`] or [`Self::builder`] instead of repeated appends.
130    pub fn append_record(
131        &self,
132        record: impl Borrow<PackageRecord>,
133        line_ending: LineEnding,
134    ) -> Self {
135        let mut source = self.to_string();
136        separate_record(&mut source, line_ending);
137        source.push_str(&record.borrow().to_string());
138        Self::parse(&source)
139    }
140
141    /// Removes a complete record and its adjacent record separator.
142    ///
143    /// # Errors
144    ///
145    /// Returns an error when `index` is out of bounds.
146    pub fn remove_record(&self, index: usize) -> Result<Self, EditError> {
147        let records = self.parse.records().collect::<Vec<_>>();
148        let selected = records
149            .get(index)
150            .ok_or(EditError::RecordOutOfBounds { index })?;
151        let source = self.to_string();
152        let range = if records.len() == 1 {
153            selected.source_range().start..selected.source_range().end
154        } else if let Some(next) = records.get(index + 1) {
155            selected.source_range().start..next.source_range().start
156        } else {
157            records[index - 1].source_range().end..selected.source_range().end
158        };
159        let mut output = source;
160        output.replace_range(range, "");
161        Ok(Self::parse(&output))
162    }
163
164    fn from_parse(parse: r_dcf_syntax::Parse) -> Self {
165        Self { parse }
166    }
167}