This commit is contained in:
pivodevat
2025-08-08 00:00:14 +03:00
parent e90430f52c
commit 19d3481f8a
17 changed files with 726 additions and 170 deletions

33
src/utils/deletecopy.rs Normal file
View File

@ -0,0 +1,33 @@
use rayon::prelude::*;
use std::fs;
use std::io;
use std::path::Path;
use std::os::unix::fs::MetadataExt;
pub fn deletecopy(source: &Path, destination: &Path) -> io::Result<()> {
let metadata = fs::symlink_metadata(source)?;
if metadata.file_type().is_file() {
if let Ok(dest_metadata) = fs::metadata(destination) {
if dest_metadata.ino() == metadata.ino() {
fs::remove_file(destination)?;
return Ok(());
}
}
} else if metadata.file_type().is_dir() {
let entries: Vec<_> = fs::read_dir(source)?.collect::<io::Result<Vec<_>>>()?;
entries.par_iter().try_for_each(|entry| {
let path_source = entry.path();
if let Some(file_name) = path_source.file_name() {
deletecopy(&path_source, &destination.join(file_name))
} else {
Ok(())
}
})?;
} else if metadata.file_type().is_symlink() {
fs::remove_file(destination)?;
}
Ok(())
}

View File

@ -1,31 +1,216 @@
use rayon::prelude::*;
use std::fs;
use std::io;
use std::path::Path;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::os::unix;
use std::os::unix::fs::MetadataExt;
use std::sync::mpsc;
use std::thread;
pub fn hardcopy(source: &Path, destination: &Path) -> io::Result<()> {
fn hardcopy(
source: &Path,
destination: &Path,
conflict_sender: Option<mpsc::Sender<(Vec<PathBuf>, mpsc::Sender<PathBuf>)>>,
) -> io::Result<()> {
let metadata = fs::symlink_metadata(source)?;
if metadata.file_type().is_file() {
fs::hard_link(source, destination)?;
match fs::hard_link(source, destination) {
Ok(_) => {}
Err(_) => {
if let Ok(dest_metadata) = fs::metadata(destination) {
if dest_metadata.ino() == metadata.ino() {
return Ok(());
}
}
match crate::utils::parser::get_index_conflict(destination) {
Ok(index_source) => {
if index_source == source {
fs::remove_file(destination)?;
fs::hard_link(source, destination)?;
} else {
return Ok(());
}
}
Err(_) => {
let conflict_list = find_files_with_location(&destination);
let count = conflict_list.len();
if count == 1 {
fs::remove_file(destination)?;
fs::hard_link(source, destination)?;
} else if count >= 1 {
let (response_tx, response_rx) = mpsc::channel();
if let Some(sender) = &conflict_sender {
sender.send((conflict_list.clone(), response_tx)).unwrap(); }
let selected_source = response_rx.recv().unwrap();
append_index_block(&selected_source, &destination)?;
if selected_source == source {
fs::remove_file(destination)?;
fs::hard_link(source, destination)?;
} else {
return Ok(());
}
}
}
}
}
}
} else if metadata.file_type().is_dir() {
fs::create_dir_all(destination)?;
let entries: Vec<_> = fs::read_dir(source)?.collect::<io::Result<Vec<_>>>()?;
entries.par_iter().try_for_each(|entry| {
let path = entry.path();
if let Some(file_name) = path.file_name() {
let path_source = entry.path();
if let Some(file_name) = path_source.file_name() {
let dest_path = destination.join(file_name);
hardcopy(&path, &dest_path)
hardcopy(&path_source, &dest_path, conflict_sender.clone())
} else {
Ok(())
}
})?;
} else if metadata.file_type().is_symlink() {
let target = fs::read_link(source)?;
unix::fs::symlink(target, destination)?;
let symlink_value = fs::read_link(source)?;
fs::remove_file(destination)?;
unix::fs::symlink(symlink_value, destination)?;
}
Ok(())
}
pub fn hardcopy_handler(
source: &Path,
destination: &Path,
) -> io::Result<()> {
let (tx, rx): (
mpsc::Sender<(Vec<PathBuf>, mpsc::Sender<PathBuf>)>,
mpsc::Receiver<(Vec<PathBuf>, mpsc::Sender<PathBuf>)>,
) = mpsc::channel();
thread::spawn(move || {
for (conflict_list, response_tx) in rx {
let selected_source = choise_index_conflict(conflict_list);
response_tx.send(selected_source).unwrap();
}
});
hardcopy(source, destination, Some(tx))
}
fn find_files_with_location(destination: &Path) -> Vec<PathBuf> {
let mut found_files = Vec::new();
let mut components = destination.components();
let prefix = match (components.next(), components.next(), components.next()) {
(Some(first), Some(second), Some(third)) => {
PathBuf::from(first.as_os_str())
.join(second.as_os_str())
.join(third.as_os_str())
}
_ => {
return Vec::new();
}
};
let file_location: PathBuf = components.as_path().to_path_buf();
if let Ok(entries) = fs::read_dir(&prefix) {
for entry in entries.filter_map(Result::ok) {
let path = entry.path();
if path.is_dir() {
let target_path = path.join(&file_location);
if target_path.exists() {
if !path.join(PathBuf::from("disabled")).exists() {
found_files.push(target_path);
}
}
}
}
}
found_files
}
fn choise_index_conflict(conflict_list: Vec<PathBuf>) -> PathBuf {
for (index, path) in conflict_list.iter().enumerate() {
println!("{}: {}", index + 1, path.display());
}
let count = conflict_list.len();
loop {
print!("Choose a path to resolve the conflict (1-{}): ", count);
io::stdout().flush().unwrap();
let mut input = String::new();
io::stdin()
.read_line(&mut input)
.expect("Failed to read input");
match input.trim().parse::<usize>() {
Ok(selected) if selected >= 1 && selected <= count => {
return conflict_list[selected - 1].clone();
}
_ => {
println!("Invalid input. Please enter a number between 1 and {}.", count);
}
}
}
}
fn append_index_block(source: &Path, destination: &Path) -> io::Result<()> {
let source_components: Vec<_> = source.iter().collect();
let base_system_folder = source_components[4].to_str().unwrap();
let index_conflict_path = Path::new("/pkg/gnu/sexpkg/etc/index-conflict.md");
let content = fs::read_to_string(&index_conflict_path)?;
let start_marker = format!("``` cfg *** {} ***", base_system_folder);
let lines: Vec<&str> = content.lines().collect();
let mut start_block_index = None;
let mut end_block_index = None;
for (i, line) in lines.iter().enumerate() {
if line.contains(&start_marker) {
start_block_index = Some(i);
} else if start_block_index.is_some() && line.trim() == "```" {
end_block_index = Some(i);
break;
}
}
let end_block_index = end_block_index.ok_or_else(|| {
io::Error::new(io::ErrorKind::InvalidData, "End block not found")
})?;
let new_line = format!(
"{} {}",
destination.to_str().unwrap(),
source.to_str().unwrap()
);
let mut new_content = String::new();
for (i, line) in lines.iter().enumerate() {
if i == end_block_index {
new_content.push_str(&new_line);
new_content.push('\n');
}
new_content.push_str(line);
new_content.push('\n');
}
let mut file = fs::File::create(&index_conflict_path)?;
file.write_all(new_content.as_bytes())?;
Ok(())
}

View File

@ -1,2 +1,4 @@
pub mod hardcopy;
pub mod parser;
pub mod deletecopy;
pub mod shell;

View File

@ -1,7 +1,7 @@
use std::fs;
use std::env;
use std::io::{self, BufRead};
use std::path::Path;
use std::path::{Path,PathBuf};
pub fn get_name<P: AsRef<Path>>(file_path: P) -> io::Result<String> {
@ -131,6 +131,57 @@ pub fn get_use_status(repo: &str, dependency: &str) -> bool {
}
pub fn get_index_conflict<P: AsRef<Path>>(destination: P) -> io::Result<PathBuf> {
let destination_path = destination.as_ref();
let parts: Vec<&str> = destination_path
.iter()
.map(|component| component.to_str().unwrap_or(""))
.collect();
if parts.len() < 4 {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"Invalid destination path format",
));
}
let system_struct_folder = parts[3]; // bin, sbin, include, lib, share
let etc = Path::new("/pkg/gnu/sexpkg/etc");
let cfg_path = etc.join("index-conflict.md");
let start_marker = format!("``` cfg *** {} ***", system_struct_folder);
let end_marker = "```";
let block_content = extract_block(&cfg_path, &start_marker, end_marker)?;
let destination_str = destination_path.to_str().ok_or_else(|| {
io::Error::new(io::ErrorKind::InvalidInput, "Failed to convert destination path to string")
})?;
for line in block_content.lines() {
let trimmed_line = line.trim();
if trimmed_line.starts_with(destination_str) {
let mut words = trimmed_line.split_whitespace();
if let Some(_) = words.next() {
if let Some(path_source) = words.next() {
return Ok(PathBuf::from(path_source));
}
}
}
}
Err(io::Error::new(
io::ErrorKind::NotFound,
format!(
"No matching line found for destination: {}",
destination_path.display()
),
))
}
fn read_first_line<P: AsRef<Path>>(file_path: P) -> io::Result<String> {
let file = fs::File::open(file_path)?;
let reader = io::BufReader::new(file);

73
src/utils/shell.rs Normal file
View File

@ -0,0 +1,73 @@
use std::path::Path;
use std::process::Command;
use std::env;
pub fn mount_overlay(path_repo: &Path) -> Result<(), String> {
let lowerdirs = vec![
path_repo.join("bin"),
path_repo.join("sbin"),
];
let lowerdir_str = lowerdirs.iter()
.map(|p| p.to_string_lossy())
.collect::<Vec<_>>()
.join(":");
let mounts = vec![
("/usr/bin", &lowerdir_str),
("/usr/sbin", &lowerdir_str),
("/bin", &lowerdir_str),
("/sbin", &lowerdir_str),
];
for (target, lowerdir) in mounts {
let output = Command::new("mount")
.arg("-t").arg("overlay")
.arg("overlay")
.arg("-o").arg(format!("lowerdir={}", lowerdir))
.arg(target)
.output()
.map_err(|e| format!("Failed to execute mount command: {}", e))?;
if !output.status.success() {
return Err(format!(
"Mount failed for target {}: {}",
target,
String::from_utf8_lossy(&output.stderr)
));
}
}
Ok(())
}
pub fn shell_update() -> Result<(), String> {
let shell = env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_string());
let output_hash = Command::new(&shell)
.arg("-c")
.arg("hash -r")
.output()
.map_err(|e| format!("Failed to execute hash -r with shell {}: {}", shell, e))?;
if !output_hash.status.success() {
return Err(format!(
"hash -r failed: {}",
String::from_utf8_lossy(&output_hash.stderr)
));
}
let output_ldconfig = Command::new("ldconfig")
.output()
.map_err(|e| format!("Failed to execute ldconfig: {}", e))?;
if !output_ldconfig.status.success() {
return Err(format!(
"ldconfig failed: {}",
String::from_utf8_lossy(&output_ldconfig.stderr)
));
}
Ok(())
}