|
| 1 | +//! `importlib.metadata` distribution lookup over search paths, for code identity facts. |
| 2 | +
|
| 3 | +use std::io::ErrorKind; |
| 4 | +use std::path::{Path, PathBuf}; |
| 5 | + |
| 6 | +use crate::digest::constants::{METADATA_DIRECTORY_SUFFIXES, METADATA_FILES}; |
| 7 | + |
| 8 | +/// The first metadata folder of `name` along `search_paths`, as `importlib.metadata` finds it. |
| 9 | +pub(crate) fn distribution_directory(search_paths: &[PathBuf], name: &str) -> Option<PathBuf> { |
| 10 | + let wanted: String = normalized(name); |
| 11 | + for root in search_paths { |
| 12 | + let directory: &Path = if root.as_os_str().is_empty() { |
| 13 | + Path::new(".") |
| 14 | + } else { |
| 15 | + root |
| 16 | + }; |
| 17 | + if let Some(child) = children(directory) |
| 18 | + .into_iter() |
| 19 | + .find(|child| metadata_name(child).is_some_and(|found| normalized(&found) == wanted)) |
| 20 | + { |
| 21 | + return Some(root.join(child)); |
| 22 | + } |
| 23 | + } |
| 24 | + None |
| 25 | +} |
| 26 | + |
| 27 | +/// The `Version` header of a distribution's metadata, when it has one. |
| 28 | +pub(crate) fn distribution_version(directory: &Path) -> Option<String> { |
| 29 | + for file in METADATA_FILES { |
| 30 | + if let Some(text) = optional_text(&directory.join(file)) { |
| 31 | + return header_value(&text, "version"); |
| 32 | + } |
| 33 | + } |
| 34 | + None |
| 35 | +} |
| 36 | + |
| 37 | +/// A file's bytes, or `None` where `importlib.metadata` treats the file as absent. |
| 38 | +pub(crate) fn optional_bytes(path: &Path) -> Option<Vec<u8>> { |
| 39 | + match std::fs::read(path) { |
| 40 | + Ok(bytes) => Some(bytes), |
| 41 | + Err(error) if absent(&error) => None, |
| 42 | + Err(_) => None, |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +/// Entry names of a search path folder; folders Python cannot list have none. |
| 47 | +fn children(directory: &Path) -> Vec<String> { |
| 48 | + let entries: std::fs::ReadDir = match std::fs::read_dir(directory) { |
| 49 | + Ok(entries) => entries, |
| 50 | + Err(error) if absent(&error) => return Vec::new(), |
| 51 | + Err(_) => return Vec::new(), |
| 52 | + }; |
| 53 | + let mut names: Vec<String> = Vec::new(); |
| 54 | + for entry in entries.flatten() { |
| 55 | + names.push(entry.file_name().to_string_lossy().into_owned()); |
| 56 | + } |
| 57 | + names |
| 58 | +} |
| 59 | + |
| 60 | +fn optional_text(path: &Path) -> Option<String> { |
| 61 | + optional_bytes(path).map(|bytes| String::from_utf8_lossy(&bytes).into_owned()) |
| 62 | +} |
| 63 | + |
| 64 | +fn absent(error: &std::io::Error) -> bool { |
| 65 | + matches!( |
| 66 | + error.kind(), |
| 67 | + ErrorKind::NotFound | ErrorKind::NotADirectory | ErrorKind::IsADirectory |
| 68 | + ) |
| 69 | +} |
| 70 | + |
| 71 | +/// The distribution name a metadata folder entry names, before its version. |
| 72 | +fn metadata_name(child: &str) -> Option<String> { |
| 73 | + let lowered: String = child.to_lowercase(); |
| 74 | + METADATA_DIRECTORY_SUFFIXES |
| 75 | + .iter() |
| 76 | + .any(|suffix| lowered.ends_with(suffix)) |
| 77 | + .then(|| { |
| 78 | + let stem: &str = lowered.rsplit_once('.').map_or("", |(stem, _)| stem); |
| 79 | + stem.split('-').next().unwrap_or_default().to_owned() |
| 80 | + }) |
| 81 | +} |
| 82 | + |
| 83 | +/// `re.sub(r"[-_.]+", "-", name).lower().replace("-", "_")`. |
| 84 | +fn normalized(name: &str) -> String { |
| 85 | + let mut text: String = String::with_capacity(name.len()); |
| 86 | + let mut separator: bool = false; |
| 87 | + for character in name.chars() { |
| 88 | + if matches!(character, '-' | '_' | '.') { |
| 89 | + if !separator { |
| 90 | + text.push('_'); |
| 91 | + } |
| 92 | + separator = true; |
| 93 | + } else { |
| 94 | + text.extend(character.to_lowercase()); |
| 95 | + separator = false; |
| 96 | + } |
| 97 | + } |
| 98 | + text |
| 99 | +} |
| 100 | + |
| 101 | +/// The first value of a case-insensitive header in an RFC 822 style header block. |
| 102 | +fn header_value(text: &str, name: &str) -> Option<String> { |
| 103 | + let mut value: Option<String> = None; |
| 104 | + for line in text.lines() { |
| 105 | + if line.is_empty() { |
| 106 | + break; |
| 107 | + } |
| 108 | + if line.starts_with([' ', '\t']) { |
| 109 | + if let Some(current) = value.as_mut() { |
| 110 | + current.push_str(line); |
| 111 | + } |
| 112 | + continue; |
| 113 | + } |
| 114 | + if value.is_some() { |
| 115 | + break; |
| 116 | + } |
| 117 | + if let Some((header, rest)) = line.split_once(':') |
| 118 | + && header.eq_ignore_ascii_case(name) |
| 119 | + { |
| 120 | + value = Some(rest.trim_start().to_owned()); |
| 121 | + } |
| 122 | + } |
| 123 | + value.map(|text| text.trim_end().to_owned()) |
| 124 | +} |
0 commit comments