fn applyportalmappings( portallist: Vec<PortalMapping>, manifest: &mut Manifest,…
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
fn apply_portal_mappings( portal_list: Vec, manifest: &mut Manifest, old_files: &mut Vec, ) -> anyhow::Result<()> { let mut hash_cache: HashMap<PathBuf, String> = HashMap::new(); let mut create_portals = Vec::new();
for portal in portal_list {
let (create, is_new) = if matches!(portal.target.try_exists(), Ok(true)) {
let mut target_hash = String::new();
let already_matches = match portal.file_type {
FileType::Link => is_matching_symlink(&portal.target, &portal.source),
FileType::Copy => {
portal.target.is_file() && !portal.target.is_symlink() && {
target_hash = calculate_file_hash(&portal.target)?;
&target_hash
} == {
if let Some(cache) = hash_cache.get(&portal.source) {
cache
} else {
calculate_file_hash(&portal.source).map(|h| {
hash_cache.insert(portal.source.clone(), h);
hash_cache.get(&portal.source).unwrap()
})?
}
}
}
};
if already_matches {
#[cfg(test)]
DO_NOTHING.set(true);
match portal.file_type {
FileType::Link => {
manifest.inner.insert(
portal.target.clone(),
ManifestType::Link {
source: portal.source.clone(),
},
);
}
FileType::Copy => {
let hash = if let Some(s) = hash_cache.get(&portal.source) {
s.to_string()
} else {
match calculate_file_hash(&portal.source) {
Ok(hash) => {
hash_cache.insert(portal.source.clone(), hash.clone());
hash
}
Err(e) => {
log::error!("{e}");
String::new()
}
}
};
manifest
.inner
.insert(portal.target.clone(), ManifestType::Copy { hash });
}
}
(false, true)
} else {
let is_managed = match manifest.inner.get(&portal.target) {
Some(ManifestType::Link { source }) => {
is_matching_symlink(&portal.target, source)
}
Some(ManifestType::Copy { hash }) => {
let h = if target_hash.is_empty() {
calculate_file_hash(&portal.target)?
} else {
target_hash
};
h == *hash
}
_ => false,
};
if is_managed {
(true, true)
} else {
#[cfg(test)]
{
PROMPT.set(true);
(OVERWRITE.get(), OVERWRITE.get())
}
#[cfg(not(test))]
{
use crate::prompt::{Prompt, PromptError};
match Prompt::new(
format!("{} already exists", &portal.target.display()),
"overwrite",
)
.options(vec![('o', "overwrite"), ('s', "skip"), ('q', "quit")])
.print()
.map_err(PromptError::Io)?
{
"overwrite" => (true, true),
"skip" => (false, false),
"quit" => anyhow::bail!(PromptError::Quit),
_ => unreachable!(),
}
}
}
}
} else {
(true, true)
};
if is_new {
if let Some(i) = old_files.iter().position(|p| p == &portal.target) {
old_files.swap_remove(i);
}
}
if create {
create_portals.push(portal);
}
}
fn remove_path(path: &Path) {
if matches!(path.try_exists(), Ok(false)) {
return;
}
let result = if path.is_dir() {
remove_dir_all(path)
} else {
remove_file(path)
};
if let Err(e) = result {
log::error!("Failed to remove {}: {}", path.display(), e);
};
}
for portal in create_portals {
if let Some(parent) = portal.target.parent() {
if let Err(e) = create_dir_all(parent) {
log::error!(
"Failed to create parent directory for {}: {}",
portal.target.display(),
e
);
continue;
}
}
match portal.file_type {
FileType::Link => {
remove_path(&portal.target);
if let Err(e) = symlink(&portal.source, &portal.target) {
log::error!(
"Failed to create symlink {}: {}",
&portal.target.display(),
e
);
} else {
manifest.inner.insert(
portal.target.clone(),
ManifestType::Link {
source: portal.source.clone(),
},
);
};
}
FileType::Copy => {
remove_path(&portal.target);
if let Err(e) = copy(&portal.source, &portal.target) {
log::error!("Failed to copy file {}: {}", &portal.target.display(), e);
} else {
let hash = if let Some(s) = hash_cache.get(&portal.source) {
s.to_string()
} else {
match calculate_file_hash(&portal.source) {
Ok(hash) => {
hash_cache.insert(portal.source, hash.clone());
hash
}
Err(e) => {
log::error!("{e}");
String::new()
}
}
};
manifest
.inner
.insert(portal.target, ManifestType::Copy { hash });
}
}
}
}
Ok(())
}
refactor
Refactoring the apply_portal_mappings function can improve readability, maintainability, and performance. Here are some key areas to focus on:
Here's a refactored version of the function:
use std::collections::HashMap;
use std::fs::{create_dir_all, remove_dir_all, remove_file, symlink, copy};
use std::path::{Path, PathBuf};
use anyhow::{Result, bail};
use log::error;
fn apply_portal_mappings(
portal_list: Vec<PortalMapping>,
manifest: &mut Manifest,
old_files: &mut Vec<PathBuf>,
) -> Result<()> {
let mut hash_cache: HashMap<PathBuf, String> = HashMap::new();
let mut create_portals = Vec::new();
for portal in portal_list {
let (create, is_new) = determine_action(&portal, &mut hash_cache, manifest, old_files)?;
if is_new {
if let Some(i) = old_files.iter().position(|p| p == &portal.target) {
old_files.swap_remove(i);
}
}
if create {
create_portals.push(portal);
}
}
for portal in create_portals {
create_portal(&portal, &mut hash_cache, manifest)?;
}
Ok(())
}
fn determine_action(
portal: &PortalMapping,
hash_cache: &mut HashMap<PathBuf, String>,
manifest: &Manifest,
old_files: &mut Vec<PathBuf>,
) -> Result<(bool, bool)> {
if portal.target.try_exists()? {
let already_matches = match portal.file_type {
FileType::Link => is_matching_symlink(&portal.target, &portal.source),
FileType::Copy => {
let target_hash = calculate_file_hash(&portal.target)?;
let source_hash = get_or_calculate_hash(&portal.source, hash_cache)?;
target_hash == source_hash
}
};
if already_matches {
update_manifest(portal, manifest);
return Ok((false, true));
}
let is_managed = match manifest.inner.get(&portal.target) {
Some(ManifestType::Link { source }) => is_matching_symlink(&portal.target, source),
Some(ManifestType::Copy { hash }) => {
let target_hash = calculate_file_hash(&portal.target)?;
target_hash == *hash
}
_ => false,
};
if is_managed {
return Ok((true, true));
}
return handle_existing_file(portal);
}
Ok((true, true))
}
fn update_manifest(portal: &PortalMapping, manifest: &mut Manifest) {
match portal.file_type {
FileType::Link => {
manifest.inner.insert(
portal.target.clone(),
ManifestType::Link {
source: portal.source.clone(),
},
);
}
FileType::Copy => {
let hash = get_or_calculate_hash(&portal.source, &mut HashMap::new()).unwrap_or_default();
manifest.inner.insert(portal.target.clone(), ManifestType::Copy { hash });
}
}
}
fn handle_existing_file(portal: &PortalMapping) -> Result<(bool, bool)> {
#[cfg(test)]
{
PROMPT.set(true);
return Ok((OVERWRITE.get(), OVERWRITE.get()));
}
#[cfg(not(test))]
{
use crate::prompt::{Prompt, PromptError};
match Prompt::new(
format!("{} already exists", &portal.target.display()),
"overwrite",
)
.options(vec![('o', "overwrite"), ('s', "skip"), ('q', "quit")])
.print()
.map_err(PromptError::Io)? {
"overwrite" => Ok((true, true)),
"skip" => Ok((false, false)),
"quit" => bail!(PromptError::Quit),
_ => unreachable!(),
}
}
}
fn get_or_calculate_hash(path: &Path, hash_cache: &mut HashMap<PathBuf, String>) -> Result<String> {
if let Some(cache) = hash_cache.get(path) {
Ok(cache.clone())
} else {
let hash = calculate_file_hash(path)?;
hash_cache.insert(path.to_path_buf(), hash.clone());
Ok(hash)
}
}
fn create_portal(portal: &PortalMapping, hash_cache: &mut HashMap<PathBuf, String>, manifest: &mut Manifest) -> Result<()> {
if let Some(parent) = portal.target.parent() {
create_dir_all(parent).map_err(|e| {
error!("Failed to create parent directory for {}: {}", portal.target.display(), e);
e
})?;
}
remove_path(&portal.target);
match portal.file_type {
FileType::Link => {
symlink(&portal.source, &portal.target).map_err(|e| {
error!("Failed to create symlink {}: {}", portal.target.display(), e);
e
})?;
manifest.inner.insert(
portal.target.clone(),
ManifestType::Link {
source: portal.source.clone(),
},
);
}
FileType::Copy => {
copy(&portal.source, &portal.target).map_err(|e| {
error!("Failed to copy file {}: {}", portal.target.display(), e);
e
})?;
let hash = get_or_calculate_hash(&portal.source, hash_cache)?;
manifest.inner.insert(portal.target.clone(), ManifestType::Copy { hash });
}
}
Ok(())
}
fn remove_path(path: &Path) {
if path.try_exists().is_ok() {
if path.is_dir() {
if let Err(e) = remove_dir_all(path) {
error!("Failed to remove directory {}: {}", path.display(), e);
}
} else {
if let Err(e) = remove_file(path) {
error!("Failed to remove file {}: {}", path.display(), e);
}
}
}
}
determine_action, update_manifest, handle_existing_file, get_or_calculate_hash, create_portal, and remove_path to make the main function more readable.This refactoring should make the code easier to understand, maintain, and extend.