Skip to main content

r_description/
lib.rs

1//! Lossless, failure-tolerant access to R package `DESCRIPTION` files.
2//!
3//! [`Description`] preserves the input exactly. Raw accessors never parse
4//! semantic values; their typed counterparts report errors for only the field
5//! declaration being inspected.
6#![forbid(unsafe_code)]
7
8mod builder;
9mod collections;
10mod normalization;
11mod schema;
12mod typed;
13mod validation;
14
15use std::{fmt, str::Utf8Error};
16
17pub use builder::DescriptionBuilder;
18pub use collections::CollectionEditError;
19pub use normalization::{NormalizationDiagnostic, NormalizationError};
20pub use r_dcf_syntax::{
21    Diagnostic as SyntaxDiagnostic, DiagnosticKind as SyntaxDiagnosticKind, EditError, Field,
22    FieldName, FormatStyle, InvalidFieldName, InvalidLogicalValue, LineEnding, LogicalValue, Parse,
23    Record, SourceSpan, ValueText,
24};
25pub use r_metadata::{Relation, Remote, Url};
26pub use typed::{CollectionEntry, CollectionIssue, CollectionResult};
27pub use validation::{Severity, Validation, ValidationIssue};
28
29/// A lossless parsed R package `DESCRIPTION` document.
30///
31/// The type owns only the persistent syntax parse. Cloning is inexpensive and
32/// the type is safe to move or share between threads.
33#[derive(Debug, Clone, PartialEq, Eq)]
34pub struct Description {
35    parse: Parse,
36}
37
38impl Description {
39    /// Starts a canonical `DESCRIPTION` builder.
40    pub fn builder() -> DescriptionBuilder {
41        DescriptionBuilder::default()
42    }
43
44    /// Parses UTF-8 text infallibly, retaining malformed text and diagnostics.
45    pub fn parse(source: &str) -> Self {
46        Self {
47            parse: r_dcf_syntax::parse(source),
48        }
49    }
50
51    /// Parses bytes after validating UTF-8.
52    ///
53    /// # Errors
54    ///
55    /// Returns the standard UTF-8 error if `source` is not valid UTF-8.
56    pub fn parse_utf8(source: &[u8]) -> Result<Self, Utf8Error> {
57        std::str::from_utf8(source).map(Self::parse)
58    }
59
60    /// Wraps an existing DCF parse.
61    pub fn from_parse(parse: Parse) -> Self {
62        Self { parse }
63    }
64
65    /// Returns the owned lower-level parse.
66    pub const fn as_parse(&self) -> &Parse {
67        &self.parse
68    }
69
70    /// Consumes this wrapper and returns the lower-level parse.
71    pub fn into_parse(self) -> Parse {
72        self.parse
73    }
74
75    /// Returns syntax diagnostics in source order.
76    pub fn diagnostics(&self) -> &[SyntaxDiagnostic] {
77        self.parse.diagnostics()
78    }
79
80    /// Iterates over all records in source order.
81    pub fn records(&self) -> impl Iterator<Item = Record> {
82        self.parse.records()
83    }
84
85    /// Returns the first record, conventionally the package record.
86    pub fn primary_record(&self) -> Option<Record> {
87        self.records().next()
88    }
89
90    /// Returns the last case-sensitive match in the primary record.
91    pub fn field(&self, name: &str) -> Option<Field> {
92        self.primary_record()?.last_field(name)
93    }
94
95    /// Iterates over case-sensitive matches in the primary record.
96    pub fn fields<'a>(&'a self, name: &'a str) -> impl Iterator<Item = Field> + 'a {
97        self.primary_record()
98            .into_iter()
99            .flat_map(move |record| record.fields().collect::<Vec<_>>())
100            .filter(move |field| field.name().as_deref() == Some(name))
101    }
102
103    /// Iterates over every valid field in every record in source order.
104    pub fn fields_all(&self) -> impl Iterator<Item = Field> {
105        self.records()
106            .flat_map(|record| record.fields().collect::<Vec<_>>())
107    }
108
109    fn raw(&self, name: &str) -> Option<ValueText> {
110        self.field(name).map(|field| field.value())
111    }
112
113    /// Replaces the last matching field in the primary record.
114    ///
115    /// # Errors
116    ///
117    /// Returns an error if the primary record or matching field is absent.
118    pub fn replace_last(&self, name: &str, value: &LogicalValue) -> Result<Self, EditError> {
119        self.parse
120            .replace_last(0, name, value)
121            .map(Self::from_parse)
122    }
123
124    /// Replaces all matching fields in the primary record.
125    ///
126    /// # Errors
127    ///
128    /// Returns an error if the primary record or matching field is absent.
129    pub fn replace_all(&self, name: &str, value: &LogicalValue) -> Result<Self, EditError> {
130        self.parse.replace_all(0, name, value).map(Self::from_parse)
131    }
132
133    /// Inserts a field after the last case-sensitive anchor in the primary record.
134    ///
135    /// # Errors
136    ///
137    /// Returns an error if the primary record or anchor field is absent.
138    pub fn insert_after(
139        &self,
140        after: &str,
141        name: &FieldName,
142        value: &LogicalValue,
143    ) -> Result<Self, EditError> {
144        self.parse
145            .insert_after(0, after, name, value)
146            .map(Self::from_parse)
147    }
148
149    /// Removes the last matching field from the primary record.
150    ///
151    /// # Errors
152    ///
153    /// Returns an error if the primary record or matching field is absent.
154    pub fn remove_last(&self, name: &str) -> Result<Self, EditError> {
155        self.parse.remove_last(0, name).map(Self::from_parse)
156    }
157
158    /// Removes all matching fields from the primary record.
159    ///
160    /// # Errors
161    ///
162    /// Returns an error if the primary record or matching field is absent.
163    pub fn remove_all(&self, name: &str) -> Result<Self, EditError> {
164        self.parse.remove_all(0, name).map(Self::from_parse)
165    }
166
167    /// Replaces the last matching field, or inserts it after the final field.
168    ///
169    /// # Errors
170    ///
171    /// Returns an error when there is no primary record. Insertion into an
172    /// existing but fieldless malformed record is intentionally unsupported.
173    pub fn set_field(&self, name: &FieldName, value: &LogicalValue) -> Result<Self, EditError> {
174        if self.field(name.as_str()).is_some() {
175            return self.replace_last(name.as_str(), value);
176        }
177        let record = self
178            .primary_record()
179            .ok_or(EditError::RecordOutOfBounds { index: 0 })?;
180        let anchor = record
181            .fields()
182            .last()
183            .and_then(|field| field.name())
184            .ok_or_else(|| EditError::FieldNotFound {
185                name: "<insertion anchor>".to_owned(),
186            })?;
187        self.insert_after(&anchor, name, value)
188    }
189
190    /// Alias for [`Self::set_field`].
191    ///
192    /// # Errors
193    ///
194    /// Returns the same errors as [`Self::set_field`].
195    pub fn upsert(&self, name: &FieldName, value: &LogicalValue) -> Result<Self, EditError> {
196        self.set_field(name, value)
197    }
198}
199
200impl fmt::Display for Description {
201    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
202        fmt::Display::fmt(&self.parse, formatter)
203    }
204}
205
206macro_rules! raw_accessors {
207    ($($method:ident => $field:literal),+ $(,)?) => {$(
208        #[doc = concat!("Returns raw `", $field, "` from the last declaration.")]
209        pub fn $method(&self) -> Option<ValueText> { self.raw($field) }
210    )+};
211}
212
213impl Description {
214    raw_accessors! {
215        package => "Package", type_ => "Type", package_type => "Type", title => "Title", version => "Version",
216        date => "Date", date_publication => "Date/Publication", authors_at_r => "Authors@R",
217        author => "Author", maintainer => "Maintainer", copyright => "Copyright",
218        description => "Description",
219        license => "License", depends => "Depends", imports => "Imports", suggests => "Suggests",
220        enhances => "Enhances", linking_to => "LinkingTo", system_requirements => "SystemRequirements",
221        url => "URL", bug_reports => "BugReports", additional_repositories => "Additional_repositories",
222        remotes => "Remotes", encoding => "Encoding", repository => "Repository",
223        contact => "Contact", mailing_list => "MailingList", note => "Note",
224        needs_compilation => "NeedsCompilation",
225        os_type => "OS_type", priority => "Priority", archs => "Archs", biarch => "Biarch",
226        classification_acm => "Classification/ACM", classification_acm_2012 => "Classification/ACM-2012",
227        classification_jel => "Classification/JEL", classification_msc => "Classification/MSC",
228        classification_msc_2010 => "Classification/MSC-2010", collate => "Collate",
229        lazy_data => "LazyData", lazy_load => "LazyLoad", byte_compile => "ByteCompile",
230        keep_source => "KeepSource", use_lto => "UseLTO", staged_install => "StagedInstall",
231        zip_data => "ZipData", build_vignettes => "BuildVignettes",
232        license_is_foss => "License_is_FOSS", license_restricts_use => "License_restricts_use",
233        vignette_builder => "VignetteBuilder", roxygen_note => "RoxygenNote", rd_macros => "RdMacros",
234        packaged => "Packaged", built => "Built",
235    }
236}
237
238#[cfg(test)]
239mod tests;