Debian Codegraph @

src/iterators/version.rs

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 use std::cell::OnceCell;
2 use std::cmp::Ordering;
3 use std::collections::HashMap;
4 use std::fmt;
5
6 use cxx::UniquePtr;
7
8 use crate::raw::{IntoRawIter, VerIterator};
9 use crate::util::cmp_versions;
10 use crate::{
11 create_depends_map, Cache, DepType, Dependency, Package, PackageFile, PackageRecords, Provider,
12 VersionFile,
13 };
14
15 /// Represents a single Version of a package.
16 pub struct Version<'a> {
17 pub(crate) ptr: UniquePtr<VerIterator>,
18 cache: &'a Cache,
19 depends_map: OnceCell<HashMap<DepType, Vec<Dependency<'a>>>>,
20 }
21
22 impl<'a> Version<'a> {
23 pub fn new(ptr: UniquePtr<VerIterator>, cache: &'a Cache) -> Version<'a> {
24 Version {
25 ptr,
26 cache,
27 depends_map: OnceCell::new(),
28 }
29 }
30
31 /// Returns a list of providers
32 pub fn provides(&self) -> impl Iterator<Item = Provider<'a>> {
33 unsafe { self.ptr.provides() }
34 .raw_iter()
35 .map(|p| Provider::new(p, self.cache))
36 }
37
38 pub fn version_files(&self) -> impl Iterator<Item = VersionFile<'a>> {
39 unsafe { self.ptr.version_files() }
40 .raw_iter()
41 .map(|v| VersionFile::new(v, self.cache))
42 }
43
44 /// Returns an iterator of PackageFiles (Origins) for the version
45 pub fn package_files(&self) -> impl Iterator<Item = PackageFile<'a>> {
46 self.version_files().map(|v| v.package_file())
47 }
48
49 /// Return the version's parent package.
50 pub fn parent(&self) -> Package<'a> { Package::new(self.cache, unsafe { self.parent_pkg() }) }
51
52 /// Returns a reference to the Dependency Map owned by the Version
53 ///
54 /// Dependencies are in a `Vec<Dependency>`
55 ///
56 /// The Dependency struct represents an Or Group of dependencies.
57 /// The base deps are located in `Dependency.base_deps`
58 ///
59 /// For example where we use the `DepType::Depends` key:
60 ///
61 /// ```
62 /// use rust_apt::{new_cache, DepType};
63 /// let cache = new_cache!().unwrap();
64 /// let pkg = cache.get("apt").unwrap();
65 /// let version = pkg.candidate().unwrap();
66 /// for dep in version.depends_map().get(&DepType::Depends).unwrap() {
67 /// if dep.is_or() {
68 /// for base_dep in dep.iter() {
69 /// println!("{}", base_dep.name())
70 /// }
71 /// } else {
72 /// // is_or is false so there is only one BaseDep
73 /// println!("{}", dep.first().name())
74 /// }
75 /// }
76 /// ```
77 pub fn depends_map(&self) -> &HashMap<DepType, Vec<Dependency<'a>>> {
78 self.depends_map
79 .get_or_init(|| create_depends_map(self.cache, unsafe { self.depends().make_safe() }))
80 }
81
82 /// Returns a reference Vector, if it exists, for the given key.
83 ///
84 /// See the doc for `depends_map()` for more information.
85 pub fn get_depends(&self, key: &DepType) -> Option<&Vec<Dependency<'a>>> {
86 self.depends_map().get(key)
87 }
88
89 /// Returns a Reference Vector, if it exists, for "Enhances".
90 pub fn enhances(&self) -> Option<&Vec<Dependency<'a>>> { self.get_depends(&DepType::Enhances) }
91
92 /// Returns a Reference Vector, if it exists,
93 /// for "Depends" and "PreDepends".
94 pub fn dependencies(&self) -> Option<Vec<&Dependency<'a>>> {
95 let mut ret_vec: Vec<&Dependency> = Vec::new();
96
97 for dep_type in [DepType::Depends, DepType::PreDepends] {
98 if let Some(dep_list) = self.get_depends(&dep_type) {
99 for dep in dep_list {
100 ret_vec.push(dep)
101 }
102 }
103 }
104
105 if ret_vec.is_empty() {
106 return None;
107 }
108 Some(ret_vec)
109 }
110
111 /// Returns a Reference Vector, if it exists, for "Recommends".
112 pub fn recommends(&self) -> Option<&Vec<Dependency<'a>>> {
113 self.get_depends(&DepType::Recommends)
114 }
115
116 /// Returns a Reference Vector, if it exists, for "suggests".
117 pub fn suggests(&self) -> Option<&Vec<Dependency<'a>>> { self.get_depends(&DepType::Suggests) }
118
119 /// Move the PkgRecords into the correct place for the Description
120 fn desc_lookup(&self) -> Option<&PackageRecords> {
121 let desc = unsafe { self.translated_desc().make_safe()? };
122 Some(self.cache.records().desc_lookup(&desc))
123 }
124
125 /// Get the translated long description
126 pub fn description(&self) -> Option<String> { self.desc_lookup()?.long_desc() }
127
128 /// Get the translated short description
129 pub fn summary(&self) -> Option<String> { self.desc_lookup()?.short_desc() }
130
131 /// Get data from the specified record field
132 ///
133 /// # Returns:
134 /// * Some String or None if the field doesn't exist.
135 ///
136 /// # Example:
137 /// ```
138 /// use rust_apt::new_cache;
139 /// use rust_apt::records::RecordField;
140 ///
141 /// let cache = new_cache!().unwrap();
142 /// let pkg = cache.get("apt").unwrap();
143 /// let cand = pkg.candidate().unwrap();
144 ///
145 /// println!("{}", cand.get_record(RecordField::Maintainer).unwrap());
146 /// // Or alternatively you can just pass any string
147 /// println!("{}", cand.get_record("Description-md5").unwrap());
148 /// ```
149 pub fn get_record<T: ToString + ?Sized>(&self, field: &T) -> Option<String> {
150 self.version_files()
151 .next()?
152 .lookup()
153 .get_field(field.to_string())
154 }
155
156 /// Get the hash specified. If there isn't one returns None
157 /// `version.hash("md5sum")`
158 pub fn hash<T: ToString + ?Sized>(&self, hash_type: &T) -> Option<String> {
159 self.version_files()
160 .next()?
161 .lookup()
162 .hash_find(hash_type.to_string())
163 }
164
165 /// Get the sha256 hash. If there isn't one returns None
166 /// This is equivalent to `version.hash("sha256")`
167 pub fn sha256(&self) -> Option<String> { self.hash("sha256") }
168
169 /// Get the sha512 hash. If there isn't one returns None
170 /// This is equivalent to `version.hash("sha512")`
171 pub fn sha512(&self) -> Option<String> { self.hash("sha512") }
172
173 /// Returns an Iterator of URIs for the Version.
174 pub fn uris(&self) -> impl Iterator<Item = String> + 'a {
175 self.version_files().filter_map(|v| {
176 let pkg_file = v.package_file();
177 if !pkg_file.is_downloadable() {
178 return None;
179 }
180 Some(pkg_file.index_file().archive_uri(&v.lookup().filename()))
181 })
182 }
183
184 /// Set this version as the candidate.
185 pub fn set_candidate(&self) { self.cache.depcache().set_candidate_version(self); }
186
187 /// The priority of the Version as shown in `apt policy`.
188 pub fn priority(&self) -> i32 { self.cache.priority(self) }
189 }
190
191 // Implementations for comparing versions.
192 impl<'a> PartialEq for Version<'a> {
193 fn eq(&self, other: &Self) -> bool {
194 matches!(
195 cmp_versions(self.version(), other.version()),
196 Ordering::Equal
197 )
198 }
199 }
200
201 impl<'a> PartialOrd for Version<'a> {
202 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
203 Some(cmp_versions(self.version(), other.version()))
204 }
205 }
206
207 impl<'a> fmt::Display for Version<'a> {
208 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
209 write!(f, "{}", self.version())?;
210 Ok(())
211 }
212 }
213
214 impl<'a> fmt::Debug for Version<'a> {
215 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
216 let parent = self.parent();
217 f.debug_struct("Version")
218 .field("pkg", &parent.name())
219 .field("arch", &self.arch())
220 .field("version", &self.version())
221 .field(
222 "is_candidate",
223 &parent.candidate().is_some_and(|cand| self == &cand),
224 )
225 .field("is_installed", &self.is_installed())
226 .finish_non_exhaustive()
227 }
228 }
229
230 #[cxx::bridge]
231 pub(crate) mod raw {
232 impl CxxVector<VerIterator> {}
233 unsafe extern "C++" {
234 include!("rust-apt/apt-pkg-c/package.h");
235
236 type VerIterator;
237
238 type PkgIterator = crate::iterators::PkgIterator;
239 type PrvIterator = crate::iterators::PrvIterator;
240 type DepIterator = crate::iterators::DepIterator;
241 type DescIterator = crate::iterators::DescIterator;
242 type VerFileIterator = crate::iterators::VerFileIterator;
243
244 /// The version string of the version. "1.4.10".
245 pub fn version(self: &VerIterator) -> &str;
246
247 /// The Arch of the version. "amd64".
248 pub fn arch(self: &VerIterator) -> &str;
249
250 /// Return the version's parent PkgIterator.
251 ///
252 /// # Safety
253 ///
254 /// The returned UniquePtr cannot outlive the cache.
255 unsafe fn parent_pkg(self: &VerIterator) -> UniquePtr<PkgIterator>;
256
257 /// The section of the version as shown in `apt show`.
258 pub fn section(self: &VerIterator) -> Result<&str>;
259
260 /// The priority string as shown in `apt show`.
261 pub fn priority_str(self: &VerIterator) -> Result<&str>;
262
263 /// The size of the .deb file.
264 pub fn size(self: &VerIterator) -> u64;
265
266 /// The uncompressed size of the .deb file.
267 pub fn installed_size(self: &VerIterator) -> u64;
268
269 /// True if the version is able to be downloaded.
270 #[cxx_name = "Downloadable"]
271 pub fn is_downloadable(self: &VerIterator) -> bool;
272
273 /// True if the version is currently installed
274 pub fn is_installed(self: &VerIterator) -> bool;
275
276 /// Always contains the name, even if it is the same as the binary name
277 pub fn source_name(self: &VerIterator) -> &str;
278
279 // Always contains the version string,
280 // even if it is the same as the binary version.
281 pub fn source_version(self: &VerIterator) -> &str;
282
283 /// Return Providers Iterator
284 ///
285 /// # Safety
286 ///
287 /// If the inner pointer is null segfaults can occur.
288 ///
289 /// Using [`crate::raw::IntoRawIter::make_safe`] to convert to an Option
290 /// is recommended.
291 ///
292 /// The returned UniquePtr cannot outlive the cache.
293 unsafe fn provides(self: &VerIterator) -> UniquePtr<PrvIterator>;
294
295 /// Return Dependency Iterator
296 ///
297 /// # Safety
298 ///
299 /// If the inner pointer is null segfaults can occur.
300 ///
301 /// Using [`crate::raw::IntoRawIter::make_safe`] to convert to an Option
302 /// is recommended.
303 ///
304 /// The returned UniquePtr cannot outlive the cache.
305 unsafe fn depends(self: &VerIterator) -> UniquePtr<DepIterator>;
306
307 /// Return the version files.
308 /// You go through here to get the package files.
309 ///
310 /// # Safety
311 ///
312 /// If the inner pointer is null segfaults can occur.
313 ///
314 /// Using [`crate::raw::IntoRawIter::make_safe`] to convert to an Option
315 /// is recommended.
316 ///
317 /// The returned UniquePtr cannot outlive the cache.
318 unsafe fn version_files(self: &VerIterator) -> UniquePtr<VerFileIterator>;
319
320 /// This is for backend records lookups.
321 ///
322 /// # Safety
323 ///
324 /// If the inner pointer is null segfaults can occur.
325 ///
326 /// Using [`crate::raw::IntoRawIter::make_safe`] to convert to an Option
327 /// is recommended.
328 ///
329 /// The returned UniquePtr cannot outlive the cache.
330 unsafe fn translated_desc(self: &VerIterator) -> UniquePtr<DescIterator>;
331
•332 pub fn index(self: &VerIterator) -> usize;
333 /// Clone the pointer.
334 ///
335 /// # Safety
336 ///
337 /// The returned UniquePtr cannot outlive the cache.
338 unsafe fn unique(self: &VerIterator) -> UniquePtr<VerIterator>;
339 pub fn raw_next(self: Pin<&mut VerIterator>);
340 pub fn end(self: &VerIterator) -> bool;
341 }
342 }