Skip to main content

r_packages/
builder.rs

1use std::{borrow::Borrow, error::Error, fmt};
2
3use r_dcf_syntax::{FieldName, InvalidFieldName, InvalidLogicalValue, LogicalValue, make};
4use r_metadata::{Version, VersionParseError};
5
6use crate::{FormatStyle, LineEnding, PackageRecord, Packages, validation::valid_package_name};
7
8/// An invalid value supplied to a structural builder.
9#[derive(Debug, Clone, PartialEq, Eq)]
10pub enum BuildError {
11    /// The field name is not valid DCF syntax.
12    FieldName(InvalidFieldName),
13    /// The logical value cannot be represented losslessly by the builder.
14    Value(InvalidLogicalValue),
15    /// The required package name is invalid.
16    PackageName,
17    /// The required package version is invalid.
18    Version(VersionParseError),
19}
20
21impl fmt::Display for BuildError {
22    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
23        match self {
24            Self::FieldName(error) => error.fmt(formatter),
25            Self::Value(error) => error.fmt(formatter),
26            Self::PackageName => formatter.write_str("invalid package name"),
27            Self::Version(error) => error.fmt(formatter),
28        }
29    }
30}
31
32impl Error for BuildError {
33    fn source(&self) -> Option<&(dyn Error + 'static)> {
34        match self {
35            Self::FieldName(error) => Some(error),
36            Self::Value(error) => Some(error),
37            Self::Version(error) => Some(error),
38            Self::PackageName => None,
39        }
40    }
41}
42
43/// Builds structurally valid DCF with checked initial package and version fields.
44/// Full semantic validation remains explicit, including for duplicate fields.
45#[derive(Debug, Clone)]
46pub struct RecordBuilder {
47    fields: Vec<(FieldName, LogicalValue)>,
48    style: FormatStyle,
49}
50
51impl RecordBuilder {
52    /// Starts a record with validated required `Package` and `Version` fields.
53    ///
54    /// # Errors
55    ///
56    /// Returns an error for an invalid package name or version.
57    pub fn new(package: &str, version: &str) -> Result<Self, BuildError> {
58        if !valid_package_name(package) {
59            return Err(BuildError::PackageName);
60        }
61        let version: Version = version.parse().map_err(BuildError::Version)?;
62        let mut builder = Self {
63            fields: Vec::new(),
64            style: FormatStyle::default(),
65        };
66        builder.push_valid("Package", package)?;
67        builder.push_valid("Version", version.as_str())?;
68        Ok(builder)
69    }
70
71    /// Appends a validated field, preserving duplicate fields and order.
72    ///
73    /// # Errors
74    ///
75    /// Returns an error when the name or logical value is not representable.
76    pub fn field(mut self, name: &str, value: &str) -> Result<Self, BuildError> {
77        self.push_valid(name, value)?;
78        Ok(self)
79    }
80
81    fn push_valid(&mut self, name: &str, value: &str) -> Result<(), BuildError> {
82        let name = FieldName::new(name).map_err(BuildError::FieldName)?;
83        let value = LogicalValue::new(value).map_err(BuildError::Value)?;
84        self.fields.push((name, value));
85        Ok(())
86    }
87
88    /// Sets formatting for all fields in this record.
89    /// Empty or non-whitespace continuation indentation is replaced with a space.
90    pub fn format_style(mut self, style: FormatStyle) -> Self {
91        self.style = style;
92        self
93    }
94
95    /// Builds a standalone record without a trailing newline.
96    /// Does not perform full semantic validation or normalize field values.
97    ///
98    /// # Panics
99    ///
100    /// Panics if the rendered record exceeds the syntax tree's 4 GiB size limit.
101    pub fn build(self) -> PackageRecord {
102        let style = clean_style(&self.style);
103        let fields = self
104            .fields
105            .iter()
106            .map(|(name, value)| make::field(name, value, &style))
107            .collect::<Vec<_>>();
108        let parse = r_dcf_syntax::parse(&make::record(&fields, &style));
109        PackageRecord {
110            record: parse
111                .records()
112                .next()
113                .expect("required fields form one record"),
114        }
115    }
116}
117
118/// A builder for a zero-or-more-record `PACKAGES` file.
119///
120/// All records are preserved without normalization or validation, regardless of
121/// whether they were parsed, converted from DESCRIPTION, or built independently.
122#[derive(Debug, Clone, Default)]
123pub struct PackagesBuilder {
124    records: Vec<String>,
125    line_ending: LineEnding,
126}
127
128impl PackagesBuilder {
129    /// Creates an empty builder using LF for unterminated record boundaries.
130    pub fn new() -> Self {
131        Self::default()
132    }
133
134    /// Sets boundary line endings when the preceding record has no trailing newline.
135    /// Applies to all records in this builder; record-local text is unaffected.
136    pub fn line_ending(mut self, line_ending: LineEnding) -> Self {
137        self.line_ending = line_ending;
138        self
139    }
140
141    /// Appends an owned or borrowed record, preserving its exact text.
142    /// No normalization, filtering, or validation is performed.
143    pub fn record(mut self, record: impl Borrow<PackageRecord>) -> Self {
144        self.records.push(record.borrow().to_string());
145        self
146    }
147
148    /// Appends owned or borrowed records in iteration order.
149    pub fn records<R: Borrow<PackageRecord>>(
150        mut self,
151        records: impl IntoIterator<Item = R>,
152    ) -> Self {
153        self.records.extend(
154            records
155                .into_iter()
156                .map(|record| record.borrow().to_string()),
157        );
158        self
159    }
160
161    /// Constructs the document in linear time and memory in the total text size.
162    ///
163    /// Empty input produces empty text. Existing record text is retained verbatim,
164    /// with one blank line inserted between records. A preceding record's trailing
165    /// line ending supplies the separator convention; if absent, two configured
166    /// line endings are inserted. The final record's newline state is preserved.
167    /// The completed text is parsed once, retaining malformed content and findings.
168    pub fn build(self) -> Packages {
169        let mut output = String::new();
170        for record in self.records {
171            separate_record(&mut output, self.line_ending);
172            output.push_str(&record);
173        }
174        Packages::parse(&output)
175    }
176}
177
178/// Completes a blank separator line, preserving all existing document text.
179/// Only inspects the final physical line, never the accumulated document prefix.
180pub(crate) fn separate_record(output: &mut String, fallback: LineEnding) {
181    if output.is_empty() {
182        return;
183    }
184    let ending = trailing_line_ending(output);
185    let body_end = output.len() - ending.map_or(0, str::len);
186    let prefix = &output[..body_end];
187    let body_start = prefix.rfind(['\r', '\n']).map_or(0, |index| index + 1);
188    let blank = prefix[body_start..]
189        .bytes()
190        .all(|byte| matches!(byte, b' ' | b'\t' | 0x0c));
191    if blank {
192        if ending.is_none() {
193            let separator =
194                trailing_line_ending(&prefix[..body_start]).unwrap_or(fallback.as_str());
195            output.push_str(separator);
196        }
197    } else if let Some(ending) = ending {
198        // Reusing a lone CR avoids coalescing it with LF and losing the blank line.
199        output.push_str(ending);
200    } else {
201        output.push_str(fallback.as_str());
202        output.push_str(fallback.as_str());
203    }
204}
205
206fn trailing_line_ending(text: &str) -> Option<&'static str> {
207    if text.ends_with("\r\n") {
208        Some("\r\n")
209    } else if text.ends_with('\r') {
210        Some("\r")
211    } else if text.ends_with('\n') {
212        Some("\n")
213    } else {
214        None
215    }
216}
217
218fn clean_style(style: &FormatStyle) -> FormatStyle {
219    let mut style = style.clone();
220    if style.continuation_indent.is_empty()
221        || !style
222            .continuation_indent
223            .bytes()
224            .all(|byte| matches!(byte, b' ' | b'\t'))
225    {
226        " ".clone_into(&mut style.continuation_indent);
227    }
228    style
229}