Skip to main content

r_packages/
lib.rs

1//! Lossless, failure-tolerant access to R repository `PACKAGES` files.
2//!
3//! Parsing never rejects DCF syntax. Use [`Packages::validate`] when semantic
4//! findings are wanted, and the typed methods on [`PackageRecord`] when only a
5//! particular field should be interpreted.
6//!
7//! Individual records convert losslessly to [`r_description::Description`] via
8//! `Description::from(&record)`. Convert back with
9//! `PackageRecord::try_from(&description)`, which requires exactly one record
10//! (see [`RecordConversionError`]). Both conversions also accept owned values.
11
12#![forbid(unsafe_code)]
13
14mod builder;
15mod conversion;
16mod edit;
17mod validation;
18
19use std::{borrow::Borrow, fmt, str::Utf8Error};
20
21use r_dcf_syntax::{Field, Parse, ValueText};
22use r_metadata::{
23    Logical, LogicalParseError, OsType, OsTypeParseError, Priority, PriorityParseError,
24    RelationList, UrlList, Version, VersionParseError,
25};
26
27pub use builder::{BuildError, PackagesBuilder, RecordBuilder};
28pub use conversion::RecordConversionError;
29pub use edit::EditError;
30pub use r_dcf_syntax::{FormatStyle, LineEnding};
31pub use validation::{Finding, FindingKind};
32
33/// A persistent, lossless parse of zero or more repository package records.
34///
35/// This type owns only the syntax crate's compact [`Parse`]. Materialized
36/// records and fields are transient wrappers around that persistent tree.
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct Packages {
39    parse: Parse,
40}
41
42impl Packages {
43    /// Assembles owned or borrowed records in iteration order without normalization
44    /// or validation. Empty input produces an empty document.
45    ///
46    /// Record-local text is preserved. Between records, adds one blank line using
47    /// the preceding trailing newline convention, or two LF line endings if the
48    /// preceding record has no newline. The final record is unchanged.
49    /// Construction takes linear time and memory in the total text size.
50    /// See [`PackagesBuilder`] for mixing existing and newly constructed records.
51    pub fn from_records<R: Borrow<PackageRecord>>(records: impl IntoIterator<Item = R>) -> Self {
52        Self::builder().records(records).build()
53    }
54
55    /// Starts a lossless `PACKAGES` assembly builder.
56    pub fn builder() -> PackagesBuilder {
57        PackagesBuilder::new()
58    }
59
60    /// Parses UTF-8 text without failing on malformed DCF syntax.
61    pub fn parse(source: &str) -> Self {
62        Self {
63            parse: r_dcf_syntax::parse(source),
64        }
65    }
66
67    /// Parses bytes after validating UTF-8.
68    ///
69    /// # Errors
70    ///
71    /// Returns the UTF-8 error without attempting a lossy conversion.
72    pub fn parse_utf8(source: &[u8]) -> Result<Self, Utf8Error> {
73        std::str::from_utf8(source).map(Self::parse)
74    }
75
76    /// Returns the number of records, including semantically invalid records.
77    pub fn len(&self) -> usize {
78        self.parse.records().count()
79    }
80
81    /// Returns whether the file has no records.
82    pub fn is_empty(&self) -> bool {
83        self.len() == 0
84    }
85
86    /// Iterates over transient records in source order.
87    pub fn records(&self) -> impl Iterator<Item = PackageRecord> {
88        self.parse.records().map(|record| PackageRecord { record })
89    }
90
91    /// Returns the record at a zero-based index.
92    pub fn record(&self, index: usize) -> Option<PackageRecord> {
93        self.records().nth(index)
94    }
95}
96
97impl fmt::Display for Packages {
98    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
99        fmt::Display::fmt(&self.parse, formatter)
100    }
101}
102
103/// Parses UTF-8 text into a lossless [`Packages`] value.
104pub fn parse(source: &str) -> Packages {
105    Packages::parse(source)
106}
107
108/// Parses bytes into [`Packages`] after validating UTF-8.
109///
110/// # Errors
111///
112/// Returns an error when `source` is not UTF-8.
113pub fn parse_utf8(source: &[u8]) -> Result<Packages, Utf8Error> {
114    Packages::parse_utf8(source)
115}
116
117/// A transient view of one package record.
118#[derive(Debug, Clone, PartialEq, Eq, Hash)]
119pub struct PackageRecord {
120    record: r_dcf_syntax::Record,
121}
122
123impl fmt::Display for PackageRecord {
124    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
125        fmt::Display::fmt(&self.record, formatter)
126    }
127}
128
129impl PackageRecord {
130    /// Starts a standalone record builder with checked initial identity fields.
131    ///
132    /// # Errors
133    ///
134    /// Returns an error for an invalid package name or version.
135    pub fn builder(package: &str, version: &str) -> Result<RecordBuilder, BuildError> {
136        RecordBuilder::new(package, version)
137    }
138
139    /// Returns the last value whose field name exactly equals `name`.
140    pub fn field(&self, name: &str) -> Option<ValueText> {
141        self.record.last_field(name).map(|field| field.value())
142    }
143
144    /// Iterates over all values whose field names exactly equal `name`.
145    pub fn fields<'a>(&'a self, name: &'a str) -> impl Iterator<Item = ValueText> + 'a {
146        self.record.fields_named(name).map(|field| field.value())
147    }
148
149    /// Iterates over all structurally valid DCF fields in source order.
150    pub fn all_fields(&self) -> impl Iterator<Item = Field> + '_ {
151        self.record.fields()
152    }
153
154    /// Parses the last `Version` value, without inspecting any other field.
155    pub fn parsed_version(&self) -> Option<Result<Version, VersionParseError>> {
156        self.field("Version").map(|value| value.as_str().parse())
157    }
158
159    /// Parses the last named field as a recoverable relation list.
160    pub fn relations(&self, name: &str) -> Option<RelationList> {
161        self.field(name)
162            .map(|value| RelationList::parse(value.as_str()))
163    }
164
165    /// Parses the last named field as an R logical scalar.
166    pub fn logical(&self, name: &str) -> Option<Result<Logical, LogicalParseError>> {
167        self.field(name).map(|value| value.as_str().parse())
168    }
169
170    /// Parses the last named field as a recoverable URL list.
171    pub fn urls(&self, name: &str) -> Option<UrlList> {
172        self.field(name).map(|value| UrlList::parse(value.as_str()))
173    }
174
175    /// Parses the last `Priority` value.
176    pub fn parsed_priority(&self) -> Option<Result<Priority, PriorityParseError>> {
177        self.field("Priority").map(|value| value.as_str().parse())
178    }
179
180    /// Parses the last `OS_type` value.
181    pub fn parsed_os_type(&self) -> Option<Result<OsType, OsTypeParseError>> {
182        self.field("OS_type").map(|value| value.as_str().parse())
183    }
184
185    /// Parses the last `Depends` relation list.
186    pub fn parsed_depends(&self) -> Option<RelationList> {
187        self.relations("Depends")
188    }
189
190    /// Parses the last `Imports` relation list.
191    pub fn parsed_imports(&self) -> Option<RelationList> {
192        self.relations("Imports")
193    }
194
195    /// Parses the last `Suggests` relation list.
196    pub fn parsed_suggests(&self) -> Option<RelationList> {
197        self.relations("Suggests")
198    }
199
200    /// Parses the last `Enhances` relation list.
201    pub fn parsed_enhances(&self) -> Option<RelationList> {
202        self.relations("Enhances")
203    }
204
205    /// Parses the last `LinkingTo` relation list.
206    pub fn parsed_linking_to(&self) -> Option<RelationList> {
207        self.relations("LinkingTo")
208    }
209
210    /// Parses the last `NeedsCompilation` logical value.
211    pub fn parsed_needs_compilation(&self) -> Option<Result<Logical, LogicalParseError>> {
212        self.logical("NeedsCompilation")
213    }
214
215    /// Parses the last `License_is_FOSS` logical value.
216    pub fn parsed_license_is_foss(&self) -> Option<Result<Logical, LogicalParseError>> {
217        self.logical("License_is_FOSS")
218    }
219
220    /// Parses the last `License_restricts_use` logical value.
221    pub fn parsed_license_restricts_use(&self) -> Option<Result<Logical, LogicalParseError>> {
222        self.logical("License_restricts_use")
223    }
224
225    /// Parses the last `URL` value as a recoverable URL list.
226    pub fn parsed_url(&self) -> Option<UrlList> {
227        self.urls("URL")
228    }
229}
230
231macro_rules! raw_accessors {
232    ($(($method:ident, $name:literal)),+ $(,)?) => {
233        impl PackageRecord {
234            $(
235                #[doc = concat!("Returns the last raw `", $name, "` value.")]
236                pub fn $method(&self) -> Option<ValueText> {
237                    self.field($name)
238                }
239            )+
240        }
241    };
242}
243
244raw_accessors!(
245    (package, "Package"),
246    (version, "Version"),
247    (priority, "Priority"),
248    (depends, "Depends"),
249    (imports, "Imports"),
250    (suggests, "Suggests"),
251    (enhances, "Enhances"),
252    (linking_to, "LinkingTo"),
253    (license, "License"),
254    (license_is_foss, "License_is_FOSS"),
255    (license_restricts_use, "License_restricts_use"),
256    (os_type, "OS_type"),
257    (archs, "Archs"),
258    (md5sum, "MD5sum"),
259    (needs_compilation, "NeedsCompilation"),
260    (built, "Built"),
261    (repository, "Repository"),
262    (path, "Path"),
263    (file, "File"),
264    (packaged, "Packaged"),
265    (date_publication, "Date/Publication"),
266    (title, "Title"),
267    (description, "Description"),
268    (author, "Author"),
269    (authors_at_r, "Authors@R"),
270    (maintainer, "Maintainer"),
271    (url, "URL"),
272    (bug_reports, "BugReports"),
273    (encoding, "Encoding"),
274    (roxygen_note, "RoxygenNote"),
275    (system_requirements, "SystemRequirements"),
276    (additional_repositories, "Additional_repositories")
277);
278
279#[cfg(test)]
280mod tests;