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
The refactored code separates concerns into smaller, more manageable functions, improving readability, maintainability, and reducing duplication.
Key Changes:
Extracted Helper Functions:
calculate_and_cache_hash: Handles calculating a file's hash and storing it in the hash_cache. It logs errors internally and returns an empty string, consistent with the original function's error handling for source files.PortalAction and PortalDecision enums/structs: Clearly define the outcome of the decision-making process for each portal (skip, update manifest only, or create).determine_portal_decision: Encapsulates the complex logic of deciding what action to take for a given PortalMapping. This function checks if the target exists, if it matches the source, if it's managed, and handles user prompts (in non-test environments). It returns a PortalDecision struct.remove_path: A simple helper to remove a file or directory, logging errors.update_manifest_entry_for_portal: A nested helper within apply_portal_mappings to update the manifest based on the PortalMapping and FileType.Improved Main Loop Structure:
apply_portal_mappings function now has two distinct passes:
portal_list, uses determine_portal_decision to decide the action for each portal, updates the old_files list, and collects portals that need to be created into portals_to_create.portals_to_create, performs the necessary file system operations (creating parent directories, removing existing targets, symlinking/copying), and updates the manifest.Reduced Duplication:
calculate_and_cache_hash.update_manifest_entry_for_portal.remove_path.Clarity and Readability:
determine_portal_decision function clearly outlines the different scenarios for an existing target (matches, managed but out of sync, unmanaged).apply_portal_mappings function now reads like a high-level algorithm, making its overall purpose easier to grasp.use anyhow::Result;
use std::{
collections::HashMap,
path::{Path, PathBuf},
};
// Assuming these structs and functions are defined elsewhere in your crate:
// PortalMapping, Manifest, ManifestType, FileType
// is_matching_symlink, calculate_file_hash
// log (from 'log' crate)
// crate::prompt::{Prompt, PromptError} (if not in test config)
// crate::tests::{DO_NOTHING, PROMPT, OVERWRITE} (if in test config)
// Example dummy structs/functions for compilation, replace with actual ones
// if you copy this directly without the rest of your codebase.
#[derive(Debug)]
pub struct PortalMapping {
pub source: PathBuf,
pub target: PathBuf,
pub file_type: FileType,
}
#[derive(Debug)]
pub struct Manifest {
pub inner: HashMap<PathBuf, ManifestType>,
}
#[derive(Debug)]
pub enum ManifestType {
Link { source: PathBuf },
Copy { hash: String },
}
#[derive(Debug, PartialEq, Eq)]
pub enum FileType {
Link,
Copy,
}
// Dummy implementations for external functions
fn is_matching_symlink(link_path: &Path, expected_target: &Path) -> bool {
// Replace with actual symlink check logic
link_path.is_symlink() && link_path.read_link().map_or(false, |p| p == expected_target)
}
fn calculate_file_hash(path: &Path) -> Result<String> {
// Replace with actual file hash calculation logic
// For now, just return a dummy hash based on path for demonstration
Ok(format!("hash-{}", path.display()))
}
// Dummy log macro for compilation if 'log' crate is not used
#[macro_export]
macro_rules! log {
($($arg:tt)*) => {{
// println!($($arg)*); // Uncomment for console output
}};
}
// Use log::error to match the original code's calls
mod log {
pub use crate::log as error;
}
// Dummy test variables if not in test config
#[cfg(not(test))]
mod tests {
use std::sync::atomic::{AtomicBool, Ordering};
pub static DO_NOTHING: AtomicBool = AtomicBool::new(false);
pub static PROMPT: AtomicBool = AtomicBool::new(false);
pub static OVERWRITE: AtomicBool = AtomicBool::new(false);
impl tests {
pub fn set_do_nothing(value: bool) { DO_NOTHING.store(value, Ordering::SeqCst); }
pub fn set_prompt(value: bool) { PROMPT.store(value, Ordering::SeqCst); }
pub fn set_overwrite(value: bool) { OVERWRITE.store(value, Ordering::SeqCst); }
pub fn get_do_nothing() -> bool { DO_NOTHING.load(Ordering::SeqCst) }
pub fn get_prompt() -> bool { PROMPT.load(Ordering::SeqCst) }
pub fn get_overwrite() -> bool { OVERWRITE.load(Ordering::SeqCst) }
}
}
#[cfg(test)]
use crate::tests::{DO_NOTHING, PROMPT, OVERWRITE};
// --- Helper Functions ---
/// Calculates file hash and caches it. Logs error and returns empty string on failure.
fn calculate_and_cache_hash(path: &PathBuf, hash_cache: &mut HashMap<PathBuf, String>) -> String {
if let Some(cached_hash) = hash_cache.get(path) {
return cached_hash.clone();
}
match calculate_file_hash(path) {
Ok(hash) => {
hash_cache.insert(path.clone(), hash.clone());
hash
}
Err(e) => {
log::error!("Failed to calculate hash for {}: {e}", path.display());
String::new() // Return empty string on error, consistent with original
}
}
}
/// Defines the ultimate action to take for a portal mapping.
enum PortalAction {
Skip,
UpdateManifestOnly, // Target already matches source, just update manifest entry
Create, // Target needs to be created, overwritten, or updated
}
/// Represents the decision made for a portal mapping.
struct PortalDecision {
action: PortalAction,
/// Indicates if the portal's target path should be removed from `old_files`.
/// This is true if the path is being managed (created/updated) or if it already matched.
should_remove_from_old_files: bool,
}
/// Determines the action to take for a given portal mapping.
/// Handles cases where target exists, matches, is managed, or requires user prompt.
fn determine_portal_decision(
portal: &PortalMapping,
manifest: &Manifest,
hash_cache: &mut HashMap<PathBuf, String>,
) -> anyhow::Result<PortalDecision> {
// Case 1: Target does not exist. Always create.
if !matches!(portal.target.try_exists(), Ok(true)) {
return Ok(PortalDecision {
action: PortalAction::Create,
should_remove_from_old_files: true,
});
}
// Case 2: Target exists. Check if it already matches the source.
let mut target_hash_for_copy_check = String::new(); // Stored if calculated for Copy type
let already_matches_source = match portal.file_type {
FileType::Link => is_matching_symlink(&portal.target, &portal.source),
FileType::Copy => {
portal.target.is_file()
&& !portal.target.is_symlink()
&& {
// Propagate error if target cannot be hashed (critical for comparison)
target_hash_for_copy_check = calculate_file_hash(&portal.target)?;
let source_hash = calculate_and_cache_hash(&portal.source, hash_cache);
target_hash_for_copy_check == source_hash
}
}
};
if already_matches_source {
#[cfg(test)]
DO_NOTHING.set(true);
return Ok(PortalDecision {
action: PortalAction::UpdateManifestOnly,
should_remove_from_old_files: true,
});
}
// Case 3: Target exists but doesn't match source. Check if it's already managed by us.
let is_managed_by_us = match manifest.inner.get(&portal.target) {
Some(ManifestType::Link { source }) => is_matching_symlink(&portal.target, source),
Some(ManifestType::Copy { hash }) => {
let current_target_hash = if target_hash_for_copy_check.is_empty() {
// Recalculate only if not already done for `already_matches_source` check
calculate_file_hash(&portal.target)? // Propagate error
} else {
target_hash_for_copy_check
};
current_target_hash == *hash
}
_ => false, // Not in manifest or wrong type
};
if is_managed_by_us {
// Managed by us, but out of sync -> recreate/update
Ok(PortalDecision {
action: PortalAction::Create,
should_remove_from_old_files: true,
})
} else {
// Unmanaged file exists and doesn't match source. Prompt user for action.
#[cfg(test)]
{
PROMPT.set(true);
let should_overwrite = OVERWRITE.get();
Ok(PortalDecision {
action: if should_overwrite {
PortalAction::Create
} else {
PortalAction::Skip
},
should_remove_from_old_files: should_overwrite,
})
}
#[cfg(not(test))]
{
use crate::prompt::{Prompt, PromptError}; // Assuming prompt module exists
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(PortalDecision {
action: PortalAction::Create,
should_remove_from_old_files: true,
}),
"skip" => Ok(PortalDecision {
action: PortalAction::Skip,
should_remove_from_old_files: false,
}),
"quit" => anyhow::bail!(PromptError::Quit),
_ => unreachable!(), // Should not happen with defined options
}
}
}
}
/// Helper function to remove a path (file or directory). Logs error on failure.
fn remove_path(path: &Path) {
if matches!(path.try_exists(), Ok(false)) {
return; // Path doesn't exist, nothing to remove
}
let result = if path.is_dir() {
std::fs::remove_dir_all(path)
} else {
std::fs::remove_file(path)
};
if let Err(e) = result {
log::error!("Failed to remove {}: {}", path.display(), e);
};
}
// --- Main Refactored Function ---
pub fn apply_portal_mappings(
portal_list: Vec<PortalMapping>,
manifest: &mut Manifest,
old_files: &mut Vec<PathBuf>,
) -> anyhow::Result<()> {
let mut hash_cache: HashMap<PathBuf, String> = HashMap::new();
let mut portals_to_create = Vec::new();
// Nested helper for manifest updates to avoid code duplication
fn update_manifest_entry_for_portal(
manifest: &mut Manifest,
portal: &PortalMapping,
hash_cache: &mut HashMap<PathBuf, String>,
) {
match portal.file_type {
FileType::Link => {
manifest.inner.insert(
portal.target.clone(),
ManifestType::Link {
source: portal.source.clone(),
},
);
}
FileType::Copy => {
let hash = calculate_and_cache_hash(&portal.source, hash_cache);
manifest
.inner
.insert(portal.target.clone(), ManifestType::Copy { hash });
}
}
}
// First pass: Determine actions and update `old_files` list
for portal in portal_list {
let decision = determine_portal_decision(&portal, manifest, &mut hash_cache)?;
// If the target path is being managed (created/updated) or already matched,
// remove it from the list of old files that might need cleanup.
if decision.should_remove_from_old_files {
if let Some(i) = old_files.iter().position(|p| p == &portal.target) {
old_files.swap_remove(i);
}
}
match decision.action {
PortalAction::Skip => { /* Do nothing for this portal */ }
PortalAction::UpdateManifestOnly => {
// Target already matches source; just ensure manifest is correctly updated.
update_manifest_entry_for_portal(manifest, &portal, &mut hash_cache);
}
PortalAction::Create => {
// This portal needs to be created, overwritten, or updated on the filesystem.
portals_to_create.push(portal);
}
}
}
// Second pass: Perform file system operations for portals marked for creation
for portal in portals_to_create {
// Ensure parent directory exists for the target path
if let Some(parent) = portal.target.parent() {
if let Err(e) = std::fs::create_dir_all(parent) {
log::error!(
"Failed to create parent directory for {}: {}",
portal.target.display(),
e
);
continue; // Skip creating this portal if parent directory creation fails
}
}
// Always remove existing target before creating a new one (ensures clean slate)
remove_path(&portal.target);
// Perform the actual file system operation (symlink or copy)
match portal.file_type {
FileType::Link => {
if let Err(e) = std::os::unix::fs::symlink(&portal.source, &portal.target) {
log::error!(
"Failed to create symlink {}: {}",
&portal.target.display(),
e
);
} else {
// Update manifest upon successful creation
update_manifest_entry_for_portal(manifest, &portal, &mut hash_cache);
};
}
FileType::Copy => {
if let Err(e) = std::fs::copy(&portal.source, &portal.target) {
log::error!("Failed to copy file {}: {}", &portal.target.display(), e);
} else {
// Update manifest upon successful creation
update_manifest_entry_for_portal(manifest, &portal, &mut hash_cache);
}
}
}
}
Ok(())
}