rename all crates
This commit is contained in:
@@ -0,0 +1,198 @@
|
||||
use std::fs::{read_to_string, File};
|
||||
use std::hash::Hash;
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::{collections::HashSet, fmt::Display};
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
|
||||
use super::{Package, Section};
|
||||
|
||||
use crate::Config;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Group {
|
||||
pub(crate) name: String,
|
||||
pub(crate) sections: HashSet<Section>,
|
||||
pub(crate) path: PathBuf,
|
||||
}
|
||||
|
||||
impl Group {
|
||||
pub fn load(config: &Config) -> Result<HashSet<Self>> {
|
||||
let mut result = HashSet::new();
|
||||
|
||||
let path = crate::path::get_pacdef_group_dir().context("getting pacdef group dir")?;
|
||||
for entry in path.read_dir().context("reading group dir")? {
|
||||
let file = entry.context("getting group file")?;
|
||||
let path = file.path();
|
||||
|
||||
if config.warn_not_symlinks && !path.is_symlink() {
|
||||
eprintln!(
|
||||
"WARNING: group file {} is not a symlink",
|
||||
path.to_string_lossy()
|
||||
);
|
||||
}
|
||||
|
||||
let group =
|
||||
Self::try_from(&path).with_context(|| format!("reading group file {path:?}"))?;
|
||||
|
||||
result.insert(group);
|
||||
}
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialOrd for Group {
|
||||
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
|
||||
match self.name.partial_cmp(&other.name) {
|
||||
Some(core::cmp::Ordering::Equal) => None,
|
||||
ord => ord,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Ord for Group {
|
||||
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
|
||||
self.name.cmp(&other.name)
|
||||
}
|
||||
}
|
||||
|
||||
impl Hash for Group {
|
||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
||||
self.name.hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for Group {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.name == other.name
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for Group {
|
||||
fn assert_receiver_is_total_eq(&self) {}
|
||||
}
|
||||
|
||||
impl Group {
|
||||
fn try_from<P>(p: P) -> Result<Self>
|
||||
where
|
||||
P: AsRef<Path>,
|
||||
{
|
||||
let path = p.as_ref();
|
||||
let content = read_to_string(path).context("reading file content")?;
|
||||
let name = path
|
||||
.file_name()
|
||||
.context("getting file name")?
|
||||
.to_string_lossy()
|
||||
.to_string();
|
||||
|
||||
let mut lines = content.lines().peekable();
|
||||
let mut sections = HashSet::new();
|
||||
|
||||
while lines.peek().is_some() {
|
||||
let result = Section::try_from_lines(&mut lines).context("reading section");
|
||||
match result {
|
||||
Ok(section) => {
|
||||
sections.insert(section);
|
||||
}
|
||||
Err(e) => {
|
||||
let err = e.root_cause();
|
||||
eprintln!("WARNING: could not process a section under group '{name}': {err}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if sections.is_empty() {
|
||||
eprintln!("WARNING: no sections found in group '{name}'");
|
||||
}
|
||||
|
||||
let path = path.into();
|
||||
|
||||
Ok(Self {
|
||||
name,
|
||||
sections,
|
||||
path,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn save_packages(&self, section_header: &str, packages: &[Package]) -> Result<()> {
|
||||
let mut content = read_to_string(&self.path)
|
||||
.with_context(|| format!("reading existing file contents from {:?}", &self.path))?;
|
||||
|
||||
if content.contains(section_header) {
|
||||
write_packages_to_existing_section(&mut content, section_header, packages)
|
||||
.context("existing section")?;
|
||||
} else {
|
||||
add_new_section_with_packages(&mut content, section_header, packages);
|
||||
}
|
||||
|
||||
let mut file = File::create(&self.path)
|
||||
.with_context(|| format!("creating descriptor to output file {:?}", &self.path))?;
|
||||
|
||||
write!(file, "{content}").with_context(|| format!("writing file {:?}", &self.path))
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for Group {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
let mut sections: Vec<_> = self.sections.iter().collect();
|
||||
sections.sort_unstable();
|
||||
|
||||
let mut iter = sections.into_iter().peekable();
|
||||
|
||||
while let Some(section) = iter.next() {
|
||||
section.fmt(f)?;
|
||||
if iter.peek().is_some() {
|
||||
f.write_str("\n\n")?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn write_packages_to_existing_section(
|
||||
group_file_content: &mut String,
|
||||
section_header: &str,
|
||||
packages: &[Package],
|
||||
) -> Result<()> {
|
||||
let idx_of_first_package_line_in_section =
|
||||
find_first_package_line_in_section(group_file_content, section_header)?;
|
||||
|
||||
let after = group_file_content.split_off(idx_of_first_package_line_in_section);
|
||||
|
||||
for p in packages {
|
||||
group_file_content.push_str(&format!("{p}\n"));
|
||||
}
|
||||
|
||||
group_file_content.push_str(&after);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn find_first_package_line_in_section(
|
||||
group_file_content: &str,
|
||||
section_header: &str,
|
||||
) -> Result<usize> {
|
||||
let section_start = group_file_content
|
||||
.find(section_header)
|
||||
.context("finding first package after section header")?;
|
||||
|
||||
let distance_to_next_newline = group_file_content[section_start..]
|
||||
.find('\n')
|
||||
.context("getting next newline")?;
|
||||
|
||||
Ok(section_start + distance_to_next_newline + 1) // + 1 to be after the newline
|
||||
}
|
||||
|
||||
fn add_new_section_with_packages(
|
||||
group_file_content: &mut String,
|
||||
section_header: &str,
|
||||
packages: &[Package],
|
||||
) {
|
||||
group_file_content.push('\n');
|
||||
group_file_content.push_str(section_header);
|
||||
group_file_content.push('\n');
|
||||
for p in packages {
|
||||
group_file_content.push_str(&format!("{p}\n"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
mod group;
|
||||
mod package;
|
||||
mod section;
|
||||
|
||||
pub use group::Group;
|
||||
pub use package::Package;
|
||||
pub use section::Section;
|
||||
@@ -0,0 +1,108 @@
|
||||
use std::fmt::{Display, Write};
|
||||
use std::hash::Hash;
|
||||
|
||||
#[derive(Debug, Eq, PartialOrd, Ord, Clone)]
|
||||
pub struct Package {
|
||||
pub(crate) name: String,
|
||||
repo: Option<String>,
|
||||
}
|
||||
|
||||
fn remove_all_but_package_name(s: &str) -> &str {
|
||||
s.split('#') // remove comment
|
||||
.next()
|
||||
.expect("line contains something")
|
||||
.trim() // remove whitespace
|
||||
}
|
||||
|
||||
impl From<String> for Package {
|
||||
fn from(value: String) -> Self {
|
||||
let trimmed = remove_all_but_package_name(&value);
|
||||
debug_assert!(!trimmed.is_empty(), "empty package names are not allowed");
|
||||
|
||||
let (name, repo) = Self::split_into_name_and_repo(trimmed);
|
||||
Self { name, repo }
|
||||
}
|
||||
}
|
||||
|
||||
impl Package {
|
||||
fn split_into_name_and_repo(s: &str) -> (String, Option<String>) {
|
||||
let mut iter = s.split('/').rev();
|
||||
let name = iter.next().expect("we checked that earlier").to_string();
|
||||
let repo = iter.next().map(|s| s.to_string());
|
||||
(name, repo)
|
||||
}
|
||||
|
||||
pub(crate) fn try_from<S>(s: S) -> Option<Self>
|
||||
where
|
||||
S: AsRef<str>,
|
||||
{
|
||||
let trimmed = remove_all_but_package_name(s.as_ref());
|
||||
if trimmed.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let (name, repo) = Self::split_into_name_and_repo(trimmed);
|
||||
Some(Self { name, repo })
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for Package {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
let self_repo = self.repo.as_ref();
|
||||
let other_repo = other.repo.as_ref();
|
||||
|
||||
// iff both packages have repos, they must be identical, otherwise we don't care
|
||||
let repos_are_identical =
|
||||
self_repo.map_or(true, |sr| other_repo.map_or(true, |or| sr == or));
|
||||
|
||||
let names_are_identical = self.name == other.name;
|
||||
|
||||
names_are_identical && repos_are_identical
|
||||
}
|
||||
}
|
||||
|
||||
impl Hash for Package {
|
||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
||||
self.name.hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for Package {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match &self.repo {
|
||||
None => (),
|
||||
Some(repo) => {
|
||||
f.write_str(repo)?;
|
||||
f.write_char('/')?;
|
||||
}
|
||||
}
|
||||
f.write_str(&self.name)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::Package;
|
||||
|
||||
#[test]
|
||||
fn split_into_name_and_repo() {
|
||||
let x = "repo/name".to_string();
|
||||
let (name, repo) = Package::split_into_name_and_repo(&x);
|
||||
assert_eq!(name, "name");
|
||||
assert_eq!(repo, Some("repo".to_string()));
|
||||
|
||||
let x = "something".to_string();
|
||||
let (name, repo) = super::Package::split_into_name_and_repo(&x);
|
||||
assert_eq!(name, "something");
|
||||
assert_eq!(repo, None);
|
||||
}
|
||||
|
||||
#[allow(clippy::unwrap_used)]
|
||||
#[test]
|
||||
fn from() {
|
||||
let x = "myrepo/somepackage # ".to_string();
|
||||
let p = Package::try_from(x).unwrap();
|
||||
assert_eq!(p.name, "somepackage");
|
||||
assert_eq!(p.repo, Some("myrepo".to_string()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
use std::{
|
||||
collections::HashSet,
|
||||
fmt::{Display, Write},
|
||||
hash::Hash,
|
||||
iter::Peekable,
|
||||
};
|
||||
|
||||
use anyhow::{ensure, Context, Result};
|
||||
|
||||
use super::Package;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Section {
|
||||
pub name: String,
|
||||
pub packages: HashSet<Package>,
|
||||
}
|
||||
|
||||
impl Section {
|
||||
pub(crate) fn new(name: String, packages: HashSet<Package>) -> Self {
|
||||
Self { name, packages }
|
||||
}
|
||||
|
||||
pub(crate) fn try_from_lines<'a>(
|
||||
iter: &mut Peekable<(impl Iterator<Item = &'a str> + std::fmt::Debug)>,
|
||||
) -> Result<Self> {
|
||||
let name = iter
|
||||
.find(|line| line.starts_with('['))
|
||||
.context("finding beginning of next section")?
|
||||
.trim()
|
||||
.trim_start_matches('[')
|
||||
.trim_end_matches(']')
|
||||
.to_string();
|
||||
|
||||
let mut packages = HashSet::new();
|
||||
// `while let` chains are unstable, unfortunately
|
||||
while iter.peek().is_some()
|
||||
&& !iter
|
||||
.peek()
|
||||
.expect("we checked this is some")
|
||||
.starts_with('[')
|
||||
{
|
||||
if let Some(package) = Package::try_from(iter.next().expect("we checked this is some"))
|
||||
{
|
||||
packages.insert(package);
|
||||
}
|
||||
}
|
||||
|
||||
ensure!(!packages.is_empty(), "[{name}] is empty");
|
||||
|
||||
Ok(Self::new(name, packages))
|
||||
}
|
||||
}
|
||||
|
||||
impl Hash for Section {
|
||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
||||
self.name.hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for Section {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.name == other.name
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for Section {
|
||||
fn assert_receiver_is_total_eq(&self) {}
|
||||
}
|
||||
|
||||
impl PartialOrd for Section {
|
||||
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
|
||||
self.name.partial_cmp(&other.name)
|
||||
}
|
||||
}
|
||||
|
||||
impl Ord for Section {
|
||||
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
|
||||
self.partial_cmp(other).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for Section {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_fmt(format_args!("[{}]\n", &self.name))?;
|
||||
|
||||
let mut packages: Vec<_> = self.packages.iter().collect();
|
||||
packages.sort_unstable();
|
||||
|
||||
let mut iter = packages.iter().peekable();
|
||||
|
||||
while let Some(package) = iter.next() {
|
||||
package.fmt(f)?;
|
||||
if iter.peek().is_some() {
|
||||
f.write_char('\n')?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user