{"repo_name": "sps", "file_name": "/sps/sps-core/src/pipeline/engine.rs", "inference_info": {"prefix_code": "use std::sync::atomic::{AtomicUsize, Ordering};\nuse std::sync::Arc;\n\nuse crossbeam_channel::Receiver as CrossbeamReceiver;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::error::Result as SpsResult;\nuse sps_common::pipeline::{PipelineEvent, WorkerJob};\nuse threadpool::ThreadPool;\nuse tokio::sync::broadcast;\nuse tracing::{debug, instrument};\n\nuse super::worker;\n\n#[instrument(skip_all, name = \"core_worker_manager\")]\n", "suffix_code": "\n", "middle_code": "pub fn start_worker_pool_manager(\n config: Config,\n cache: Arc,\n worker_job_rx: CrossbeamReceiver,\n event_tx: broadcast::Sender,\n success_count: Arc,\n fail_count: Arc,\n) -> SpsResult<()> {\n let num_workers = std::cmp::max(1, num_cpus::get_physical().saturating_sub(1)).min(6);\n let pool = ThreadPool::new(num_workers);\n debug!(\n \"Core worker pool manager started with {} workers.\",\n num_workers\n );\n debug!(\"Worker pool created.\");\n for worker_job in worker_job_rx {\n let job_id = worker_job.request.target_id.clone();\n debug!(\n \"[{}] Received job from channel, preparing to submit to pool.\",\n job_id\n );\n let config_clone = config.clone();\n let cache_clone = Arc::clone(&cache);\n let event_tx_clone = event_tx.clone();\n let success_count_clone = Arc::clone(&success_count);\n let fail_count_clone = Arc::clone(&fail_count);\n let _ = event_tx_clone.send(PipelineEvent::JobProcessingStarted {\n target_id: job_id.clone(),\n });\n debug!(\"[{}] Submitting job to worker pool.\", job_id);\n pool.execute(move || {\n let job_result = worker::execute_sync_job(\n worker_job,\n &config_clone,\n cache_clone,\n event_tx_clone.clone(),\n );\n let job_id_for_log = job_id.clone();\n debug!(\n \"[{}] Worker job execution finished (execute_sync_job returned), result ok: {}\",\n job_id_for_log,\n job_result.is_ok()\n );\n let job_id_for_log = job_id.clone();\n match job_result {\n Ok((final_action, pkg_type)) => {\n success_count_clone.fetch_add(1, Ordering::Relaxed);\n debug!(\"[{}] Worker finished successfully.\", job_id);\n let _ = event_tx_clone.send(PipelineEvent::JobSuccess {\n target_id: job_id,\n action: final_action,\n pkg_type,\n });\n debug!(\"[{}] Worker result event sent.\", job_id_for_log);\n }\n Err(boxed) => {\n let (final_action, err) = *boxed;\n fail_count_clone.fetch_add(1, Ordering::Relaxed);\n let _ = event_tx_clone.send(PipelineEvent::JobFailed {\n target_id: job_id,\n action: final_action,\n error: err.to_string(),\n });\n debug!(\"[{}] Worker result event sent.\", job_id_for_log);\n }\n }\n debug!(\"[{}] Worker closure scope ending.\", job_id_for_log);\n });\n }\n pool.join();\n Ok(())\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "rust", "sub_task_type": null}, "context_code": [["/sps/sps/src/pipeline/runner.rs", "// sps/src/pipeline/runner.rs\nuse std::collections::{HashMap, HashSet};\nuse std::sync::atomic::{AtomicUsize, Ordering};\nuse std::sync::{Arc, Mutex};\nuse std::time::Instant;\n\nuse colored::Colorize;\nuse crossbeam_channel::bounded as crossbeam_bounded;\nuse reqwest::Client as HttpClient;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::dependency::resolver::{ResolutionStatus, ResolvedGraph};\nuse sps_common::error::{Result as SpsResult, SpsError};\nuse sps_common::model::InstallTargetIdentifier;\nuse sps_common::pipeline::{\n DownloadOutcome, JobProcessingState, PipelineEvent, PlannedJob,\n PlannedOperations as PlannerOutputCommon, WorkerJob,\n};\nuse tokio::sync::{broadcast, mpsc};\nuse tokio::task::JoinHandle;\nuse tracing::{debug, error, instrument, warn};\n\nuse super::downloader::DownloadCoordinator;\nuse super::planner::OperationPlanner;\n\nconst WORKER_JOB_CHANNEL_SIZE: usize = 100;\nconst EVENT_CHANNEL_SIZE: usize = 100;\nconst DOWNLOAD_OUTCOME_CHANNEL_SIZE: usize = 100;\n\n#[derive(Debug, Clone, PartialEq, Eq)]\npub enum CommandType {\n Install,\n Reinstall,\n Upgrade { all: bool },\n}\n\n#[derive(Debug, Clone)]\npub struct PipelineFlags {\n pub build_from_source: bool,\n pub include_optional: bool,\n pub skip_recommended: bool,\n}\n\nstruct PropagationContext {\n all_planned_jobs: Arc>,\n job_states: Arc>>,\n resolved_graph: Arc,\n event_tx: Option>,\n final_fail_count: Arc,\n}\n\nfn err_to_string(e: &SpsError) -> String {\n e.to_string()\n}\n\npub(crate) fn get_panic_message(e: Box) -> String {\n match e.downcast_ref::<&'static str>() {\n Some(s) => (*s).to_string(),\n None => match e.downcast_ref::() {\n Some(s) => s.clone(),\n None => \"Unknown panic payload\".to_string(),\n },\n }\n}\n\n#[instrument(skip_all, fields(cmd = ?command_type, targets = ?initial_targets))]\npub async fn run_pipeline(\n initial_targets: &[String],\n command_type: CommandType,\n config: &Config,\n cache: Arc,\n flags: &PipelineFlags,\n) -> SpsResult<()> {\n debug!(\n \"Pipeline run initiated for targets: {:?}, command: {:?}\",\n initial_targets, command_type\n );\n let start_time = Instant::now();\n let final_success_count = Arc::new(AtomicUsize::new(0));\n let final_fail_count = Arc::new(AtomicUsize::new(0));\n\n debug!(\n \"Creating broadcast channel for pipeline events (EVENT_CHANNEL_SIZE={})\",\n EVENT_CHANNEL_SIZE\n );\n let (event_tx, mut event_rx_for_runner) =\n broadcast::channel::(EVENT_CHANNEL_SIZE);\n\n debug!(\"Cloning event_tx for runner_event_tx_clone\");\n let runner_event_tx_clone = event_tx.clone();\n\n debug!(\n \"Creating crossbeam worker job channel (WORKER_JOB_CHANNEL_SIZE={})\",\n WORKER_JOB_CHANNEL_SIZE\n );\n let (worker_job_tx, worker_job_rx_for_core) =\n crossbeam_bounded::(WORKER_JOB_CHANNEL_SIZE);\n\n debug!(\"Cloning event_tx for core_event_tx_for_worker_manager\");\n let core_config = config.clone();\n let core_cache_clone = cache.clone();\n let core_event_tx_for_worker_manager = event_tx.clone();\n let core_success_count_clone = Arc::clone(&final_success_count);\n let core_fail_count_clone = Arc::clone(&final_fail_count);\n debug!(\"Spawning core worker pool manager thread.\");\n let core_handle = std::thread::spawn(move || {\n debug!(\"CORE_THREAD: Core worker pool manager thread started.\");\n let result = sps_core::pipeline::engine::start_worker_pool_manager(\n core_config,\n core_cache_clone,\n worker_job_rx_for_core,\n core_event_tx_for_worker_manager,\n core_success_count_clone,\n core_fail_count_clone,\n );\n debug!(\n \"CORE_THREAD: Core worker pool manager thread finished. Result: {:?}\",\n result.is_ok()\n );\n result\n });\n\n debug!(\"Subscribing to event_tx for status_event_rx\");\n let status_config = config.clone();\n let status_event_rx = event_tx.subscribe();\n debug!(\"Spawning status handler task.\");\n let status_handle = tokio::spawn(crate::cli::status::handle_events(\n status_config,\n status_event_rx,\n ));\n\n debug!(\n \"Creating mpsc download_outcome channel (DOWNLOAD_OUTCOME_CHANNEL_SIZE={})\",\n DOWNLOAD_OUTCOME_CHANNEL_SIZE\n );\n let (download_outcome_tx, mut download_outcome_rx) =\n mpsc::channel::(DOWNLOAD_OUTCOME_CHANNEL_SIZE);\n\n debug!(\"Initializing pipeline planning phase...\");\n let planner_output: PlannerOutputCommon;\n {\n debug!(\"Cloning runner_event_tx_clone for planner_event_tx_clone\");\n let planner_event_tx_clone = runner_event_tx_clone.clone();\n debug!(\"Creating OperationPlanner.\");\n let operation_planner =\n OperationPlanner::new(config, cache.clone(), flags, planner_event_tx_clone);\n\n debug!(\"Calling plan_operations...\");\n match operation_planner\n .plan_operations(initial_targets, command_type.clone())\n .await\n {\n Ok(ops) => {\n debug!(\"plan_operations returned Ok.\");\n planner_output = ops;\n }\n Err(e) => {\n error!(\"Fatal planning error: {}\", e);\n runner_event_tx_clone\n .send(PipelineEvent::LogError {\n message: format!(\"Fatal planning error: {e}\"),\n })\n .ok();\n drop(worker_job_tx);\n if let Err(join_err) = core_handle.join() {\n error!(\n \"Core thread join error after planning failure: {:?}\",\n get_panic_message(join_err)\n );\n }\n let duration = start_time.elapsed();\n runner_event_tx_clone\n .send(PipelineEvent::PipelineFinished {\n duration_secs: duration.as_secs_f64(),\n success_count: 0,\n fail_count: initial_targets.len(),\n })\n .ok();\n\n debug!(\"Dropping runner_event_tx_clone due to planning error.\");\n drop(runner_event_tx_clone);\n debug!(\"Dropping main event_tx due to planning error.\");\n drop(event_tx);\n\n debug!(\"Awaiting status_handle after planning error.\");\n if let Err(join_err) = status_handle.await {\n error!(\n \"Status task join error after planning failure: {}\",\n join_err\n );\n }\n return Err(e);\n }\n }\n debug!(\"OperationPlanner scope ended, planner_event_tx_clone dropped.\");\n }\n\n let planned_jobs = Arc::new(planner_output.jobs);\n let resolved_graph = planner_output.resolved_graph.clone()\n .unwrap_or_else(|| {\n tracing::debug!(\"ResolvedGraph was None in planner output. Using a default empty graph. This is expected if no formulae required resolution or if planner reported errors for all formulae.\");\n Arc::new(sps_common::dependency::resolver::ResolvedGraph::default())\n });\n\n debug!(\n \"Planning finished. Total jobs in plan: {}.\",\n planned_jobs.len()\n );\n runner_event_tx_clone\n .send(PipelineEvent::PlanningFinished {\n job_count: planned_jobs.len(),\n })\n .ok();\n\n // Mark jobs with planner errors as failed and emit error events\n let job_processing_states = Arc::new(Mutex::new(HashMap::::new()));\n let mut jobs_pending_or_active = 0;\n let mut initial_fail_count_from_planner = 0;\n {\n let mut states_guard = job_processing_states.lock().unwrap();\n if !planner_output.errors.is_empty() {\n tracing::debug!(\n \"[Runner] Planner reported {} error(s). These targets will be marked as failed.\",\n planner_output.errors.len()\n );\n for (target_name, error) in &planner_output.errors {\n let msg = format!(\"✗ {}: {}\", target_name.cyan(), error);\n runner_event_tx_clone\n .send(PipelineEvent::LogError { message: msg })\n .ok();\n states_guard.insert(\n target_name.clone(),\n JobProcessingState::Failed(Arc::new(error.clone())),\n );\n initial_fail_count_from_planner += 1;\n }\n }\n for job in planned_jobs.iter() {\n if states_guard.contains_key(&job.target_id) {\n continue;\n }\n if planner_output\n .already_installed_or_up_to_date\n .contains(&job.target_id)\n {\n states_guard.insert(job.target_id.clone(), JobProcessingState::Succeeded);\n final_success_count.fetch_add(1, Ordering::Relaxed);\n debug!(\n \"[{}] Marked as Succeeded (pre-existing/up-to-date).\",\n job.target_id\n );\n } else if let Some((_, err)) = planner_output\n .errors\n .iter()\n .find(|(name, _)| name == &job.target_id)\n {\n states_guard.insert(\n job.target_id.clone(),\n JobProcessingState::Failed(Arc::new(err.clone())),\n );\n // Counted in initial_fail_count_from_planner\n debug!(\n \"[{}] Marked as Failed (planning error: {}).\",\n job.target_id, err\n );\n } else if job.use_private_store_source.is_some() {\n let path = job.use_private_store_source.clone().unwrap();\n states_guard.insert(\n job.target_id.clone(),\n JobProcessingState::Downloaded(path.clone()),\n );\n jobs_pending_or_active += 1;\n debug!(\n \"[{}] Initial state: Downloaded (private store: {}). Active jobs: {}\",\n job.target_id,\n path.display(),\n jobs_pending_or_active\n );\n } else {\n states_guard.insert(job.target_id.clone(), JobProcessingState::PendingDownload);\n jobs_pending_or_active += 1;\n debug!(\n \"[{}] Initial state: PendingDownload. Active jobs: {}\",\n job.target_id, jobs_pending_or_active\n );\n }\n }\n }\n debug!(\n \"Initial job states populated. Jobs pending/active: {}\",\n jobs_pending_or_active\n );\n\n let mut downloads_to_initiate = Vec::new();\n {\n let states_guard = job_processing_states.lock().unwrap();\n for job in planned_jobs.iter() {\n if matches!(\n states_guard.get(&job.target_id),\n Some(JobProcessingState::PendingDownload)\n ) {\n downloads_to_initiate.push(job.clone());\n }\n }\n }\n\n let mut download_coordinator_task_handle: Option>> = None;\n\n if !downloads_to_initiate.is_empty() {\n debug!(\"Cloning runner_event_tx_clone for download_coordinator_event_tx_clone\");\n let download_coordinator_event_tx_clone = runner_event_tx_clone.clone();\n let http_client = Arc::new(HttpClient::new());\n let config_for_downloader_owned = config.clone();\n\n let mut download_coordinator = DownloadCoordinator::new(\n config_for_downloader_owned,\n cache.clone(),\n http_client,\n download_coordinator_event_tx_clone,\n );\n debug!(\n \"Starting download coordination for {} jobs...\",\n downloads_to_initiate.len()\n );\n debug!(\"Cloning download_outcome_tx for tx_for_download_task\");\n let tx_for_download_task = download_outcome_tx.clone();\n\n debug!(\"Spawning DownloadCoordinator task.\");\n download_coordinator_task_handle = Some(tokio::spawn(async move {\n debug!(\"DOWNLOAD_COORD_TASK: DownloadCoordinator task started.\");\n let result = download_coordinator\n .coordinate_downloads(downloads_to_initiate, tx_for_download_task)\n .await;\n debug!(\"DOWNLOAD_COORD_TASK: DownloadCoordinator task finished. coordinate_downloads returned.\");\n result\n }));\n } else if jobs_pending_or_active > 0 {\n debug!(\n \"No downloads to initiate, but {} jobs are pending. Triggering check_and_dispatch.\",\n jobs_pending_or_active\n );\n check_and_dispatch(\n planned_jobs.clone(),\n job_processing_states.clone(),\n resolved_graph.clone(),\n &worker_job_tx,\n runner_event_tx_clone.clone(),\n config,\n flags,\n );\n } else {\n debug!(\"No downloads to initiate and no jobs pending/active. Pipeline might be empty or all pre-satisfied/failed.\");\n }\n\n drop(download_outcome_tx);\n debug!(\"Dropped main MPSC download_outcome_tx (runner's original clone).\");\n\n if !planned_jobs.is_empty() {\n runner_event_tx_clone\n .send(PipelineEvent::PipelineStarted {\n total_jobs: planned_jobs.len(),\n })\n .ok();\n }\n\n let mut propagation_ctx = PropagationContext {\n all_planned_jobs: planned_jobs.clone(),\n job_states: job_processing_states.clone(),\n resolved_graph: resolved_graph.clone(),\n event_tx: Some(runner_event_tx_clone.clone()),\n final_fail_count: final_fail_count.clone(),\n };\n\n debug!(\n \"Entering main event loop. Jobs pending/active: {}\",\n jobs_pending_or_active\n );\n\n // Robust main loop: continue while there are jobs pending/active, or downloads, or jobs in\n // states that could be dispatched\n fn has_pending_dispatchable_jobs(\n states_guard: &std::sync::MutexGuard>,\n ) -> bool {\n states_guard.values().any(|state| {\n matches!(\n state,\n JobProcessingState::Downloaded(_) | JobProcessingState::WaitingForDependencies(_)\n )\n })\n }\n\n while jobs_pending_or_active > 0\n || has_pending_dispatchable_jobs(&job_processing_states.lock().unwrap())\n {\n tokio::select! {\n biased;\n Some(download_outcome) = download_outcome_rx.recv() => {\n debug!(\"Received DownloadOutcome for '{}'.\", download_outcome.planned_job.target_id);\n process_download_outcome(\n download_outcome,\n &propagation_ctx,\n &mut jobs_pending_or_active,\n );\n debug!(\"After process_download_outcome, jobs_pending_or_active: {}. Triggering check_and_dispatch.\", jobs_pending_or_active);\n check_and_dispatch(\n planned_jobs.clone(),\n job_processing_states.clone(),\n resolved_graph.clone(),\n &worker_job_tx,\n runner_event_tx_clone.clone(),\n config,\n flags,\n );\n }\n Ok(event) = event_rx_for_runner.recv() => {\n match event {\n PipelineEvent::JobSuccess { ref target_id, .. } => {\n debug!(\"Received JobSuccess for '{}'.\", target_id);\n process_core_worker_feedback(\n target_id.clone(),\n true,\n None,\n job_processing_states.clone(),\n &mut jobs_pending_or_active,\n );\n debug!(\"After JobSuccess for '{}', jobs_pending_or_active: {}. Triggering check_and_dispatch.\", target_id, jobs_pending_or_active);\n check_and_dispatch(\n planned_jobs.clone(),\n job_processing_states.clone(),\n resolved_graph.clone(),\n &worker_job_tx,\n runner_event_tx_clone.clone(),\n config,\n flags,\n );\n }\n PipelineEvent::JobFailed { ref target_id, ref error, ref action } => {\n debug!(\"Received JobFailed for '{}' (Action: {:?}, Error: {}).\", target_id, action, error);\n process_core_worker_feedback(\n target_id.clone(),\n false,\n Some(SpsError::Generic(error.clone())),\n job_processing_states.clone(),\n &mut jobs_pending_or_active,\n );\n debug!(\"After JobFailed for '{}', jobs_pending_or_active: {}. Triggering failure propagation.\", target_id, jobs_pending_or_active);\n propagate_failure(\n target_id,\n Arc::new(SpsError::Generic(format!(\"Core worker failed for {target_id}: {error}\"))),\n &propagation_ctx,\n &mut jobs_pending_or_active,\n );\n check_and_dispatch(\n planned_jobs.clone(),\n job_processing_states.clone(),\n resolved_graph.clone(),\n &worker_job_tx,\n runner_event_tx_clone.clone(),\n config,\n flags,\n );\n }\n _ => {}\n }\n }\n else => {\n debug!(\"Main select loop 'else' branch. jobs_pending_or_active = {}. download_outcome_rx or event_rx_for_runner might be closed.\", jobs_pending_or_active);\n if jobs_pending_or_active > 0 || has_pending_dispatchable_jobs(&job_processing_states.lock().unwrap()) {\n warn!(\"Exiting main loop prematurely but still have {} jobs pending/active or dispatchable. This might indicate a stall or logic error.\", jobs_pending_or_active);\n }\n break;\n }\n }\n debug!(\n \"End of select! loop iteration. Jobs pending/active: {}\",\n jobs_pending_or_active\n );\n }\n debug!(\n \"Main event loop finished. Final jobs_pending_or_active: {}\",\n jobs_pending_or_active\n );\n\n drop(download_outcome_rx);\n debug!(\"Dropped MPSC download_outcome_rx (runner's receiver).\");\n\n if let Some(handle) = download_coordinator_task_handle {\n debug!(\"Waiting for DownloadCoordinator task to complete...\");\n match handle.await {\n Ok(critical_download_errors) => {\n if !critical_download_errors.is_empty() {\n warn!(\n \"DownloadCoordinator task reported critical errors: {:?}\",\n critical_download_errors\n );\n final_fail_count.fetch_add(critical_download_errors.len(), Ordering::Relaxed);\n }\n debug!(\"DownloadCoordinator task completed.\");\n }\n Err(e) => {\n let panic_msg = get_panic_message(Box::new(e));\n error!(\n \"DownloadCoordinator task panicked or failed to join: {}\",\n panic_msg\n );\n final_fail_count.fetch_add(1, Ordering::Relaxed);\n }\n }\n } else {\n debug!(\"No DownloadCoordinator task was spawned or it was already handled.\");\n }\n debug!(\"DownloadCoordinator task processing finished (awaited or none).\");\n\n debug!(\"Closing worker job channel (signal to core workers).\");\n drop(worker_job_tx);\n debug!(\"Waiting for core worker pool to join...\");\n match core_handle.join() {\n Ok(Ok(())) => debug!(\"Core worker pool manager thread completed successfully.\"),\n Ok(Err(e)) => {\n error!(\"Core worker pool manager thread failed: {}\", e);\n final_fail_count.fetch_add(1, Ordering::Relaxed);\n }\n Err(e) => {\n error!(\n \"Core worker pool manager thread panicked: {:?}\",\n get_panic_message(e)\n );\n final_fail_count.fetch_add(1, Ordering::Relaxed);\n }\n }\n debug!(\"Core worker pool joined. core_event_tx_for_worker_manager (broadcast sender) dropped.\");\n\n let duration = start_time.elapsed();\n let success_total = final_success_count.load(Ordering::Relaxed);\n let fail_total = final_fail_count.load(Ordering::Relaxed) + initial_fail_count_from_planner;\n\n debug!(\n \"Pipeline processing finished. Success: {}, Fail: {}. Duration: {:.2}s. Sending PipelineFinished event.\",\n success_total, fail_total, duration.as_secs_f64()\n );\n if let Err(e) = runner_event_tx_clone.send(PipelineEvent::PipelineFinished {\n duration_secs: duration.as_secs_f64(),\n success_count: success_total,\n fail_count: fail_total,\n }) {\n warn!(\n \"Failed to send PipelineFinished event: {:?}. Status handler might not receive it.\",\n e\n );\n }\n\n // Explicitly drop the event_tx inside propagation_ctx before dropping the last senders.\n propagation_ctx.event_tx = None;\n\n debug!(\"Dropping runner_event_tx_clone (broadcast sender).\");\n drop(runner_event_tx_clone);\n // event_rx_for_runner (broadcast receiver) goes out of scope here and is dropped.\n\n debug!(\"Dropping main event_tx (final broadcast sender).\");\n drop(event_tx);\n\n debug!(\"All known broadcast senders dropped. About to await status_handle.\");\n if let Err(e) = status_handle.await {\n warn!(\"Status handler task failed or panicked: {}\", e);\n } else {\n debug!(\"Status handler task completed successfully.\");\n }\n debug!(\"run_pipeline function is ending.\");\n\n if fail_total == 0 {\n Ok(())\n } else {\n let mut accumulated_errors = Vec::new();\n for (name, err_obj) in planner_output.errors {\n accumulated_errors.push(format!(\"Planning for '{name}': {err_obj}\"));\n }\n let states_guard = job_processing_states.lock().unwrap();\n for job in planned_jobs.iter() {\n if let Some(JobProcessingState::Failed(err_arc)) = states_guard.get(&job.target_id) {\n let err_str = err_to_string(err_arc);\n let job_err_msg = format!(\"Processing '{}': {}\", job.target_id, err_str);\n if !accumulated_errors.contains(&job_err_msg) {\n accumulated_errors.push(job_err_msg);\n }\n }\n }\n drop(states_guard);\n\n let specific_error_msg = if accumulated_errors.is_empty() {\n \"No specific errors logged, check core worker logs.\".to_string()\n } else {\n accumulated_errors.join(\"; \")\n };\n\n // Error details are already sent via PipelineEvent::JobFailed events\n // and will be displayed in status.rs\n Err(SpsError::InstallError(format!(\n \"Operation failed with {fail_total} total failure(s). Details: [{specific_error_msg}] (Worker errors are included in total)\"\n )))\n }\n}\n\nfn process_download_outcome(\n outcome: DownloadOutcome,\n propagation_ctx: &PropagationContext,\n jobs_pending_or_active: &mut usize,\n) {\n let job_id = outcome.planned_job.target_id.clone();\n let mut states_guard = propagation_ctx.job_states.lock().unwrap();\n\n match states_guard.get(&job_id) {\n Some(JobProcessingState::Succeeded) | Some(JobProcessingState::Failed(_)) => {\n debug!(\n \"[{}] DownloadOutcome: Job already in terminal state {:?}. Ignoring outcome.\",\n job_id,\n states_guard.get(&job_id)\n );\n return;\n }\n _ => {}\n }\n\n match outcome.result {\n Ok(path) => {\n debug!(\n \"[{}] DownloadOutcome: Success. Path: {}. Updating state to Downloaded.\",\n job_id,\n path.display()\n );\n states_guard.insert(job_id.clone(), JobProcessingState::Downloaded(path));\n }\n Err(e) => {\n warn!(\n \"[{}] DownloadOutcome: Failed. Error: {}. Updating state to Failed.\",\n job_id, e\n );\n let error_arc = Arc::new(e);\n states_guard.insert(\n job_id.clone(),\n JobProcessingState::Failed(error_arc.clone()),\n );\n\n if let Some(ref tx) = propagation_ctx.event_tx {\n tx.send(PipelineEvent::job_failed(\n job_id.clone(),\n outcome.planned_job.action.clone(),\n &error_arc,\n ))\n .ok();\n }\n propagation_ctx\n .final_fail_count\n .fetch_add(1, Ordering::Relaxed);\n\n if *jobs_pending_or_active > 0 {\n *jobs_pending_or_active -= 1;\n debug!(\"[{}] DownloadOutcome: Decremented jobs_pending_or_active to {} due to download failure.\", job_id, *jobs_pending_or_active);\n } else {\n warn!(\"[{}] DownloadOutcome: jobs_pending_or_active is already 0, cannot decrement for download failure.\", job_id);\n }\n\n drop(states_guard);\n debug!(\"[{}] DownloadOutcome: Propagating failure.\", job_id);\n propagate_failure(&job_id, error_arc, propagation_ctx, jobs_pending_or_active);\n }\n }\n}\n\nfn process_core_worker_feedback(\n target_id: String,\n success: bool,\n error: Option,\n job_states: Arc>>,\n jobs_pending_or_active: &mut usize,\n) {\n let mut states_guard = job_states.lock().unwrap();\n\n match states_guard.get(&target_id) {\n Some(JobProcessingState::Succeeded) | Some(JobProcessingState::Failed(_)) => {\n debug!(\"[{}] CoreFeedback: Job already in terminal state {:?}. Ignoring active job count update.\", target_id, states_guard.get(&target_id));\n return;\n }\n _ => {}\n }\n\n if success {\n debug!(\n \"[{}] CoreFeedback: Success. Updating state to Succeeded.\",\n target_id\n );\n states_guard.insert(target_id.clone(), JobProcessingState::Succeeded);\n } else {\n let err_msg = error.as_ref().map_or_else(\n || \"Unknown core worker error\".to_string(),\n |e| e.to_string(),\n );\n debug!(\n \"[{}] CoreFeedback: Failed. Error: {}. Updating state to Failed.\",\n target_id, err_msg\n );\n let err_arc = Arc::new(\n error.unwrap_or_else(|| SpsError::Generic(\"Unknown core worker error\".into())),\n );\n states_guard.insert(target_id.clone(), JobProcessingState::Failed(err_arc));\n }\n\n if *jobs_pending_or_active > 0 {\n *jobs_pending_or_active -= 1;\n debug!(\n \"[{}] CoreFeedback: Decremented jobs_pending_or_active to {}.\",\n target_id, *jobs_pending_or_active\n );\n } else {\n warn!(\n \"[{}] CoreFeedback: jobs_pending_or_active is already 0, cannot decrement.\",\n target_id\n );\n }\n}\n\nfn check_and_dispatch(\n planned_jobs_arc: Arc>,\n job_states: Arc>>,\n resolved_graph: Arc,\n worker_job_tx: &crossbeam_channel::Sender,\n event_tx: broadcast::Sender,\n config: &Config,\n flags: &PipelineFlags,\n) {\n debug!(\"--- Enter check_and_dispatch ---\");\n let mut states_guard = job_states.lock().unwrap();\n let mut dispatched_this_round = 0;\n\n for planned_job in planned_jobs_arc.iter() {\n let job_id = &planned_job.target_id;\n debug!(\"[{}] CheckDispatch: Evaluating job.\", job_id);\n\n let (current_state_is_dispatchable, path_for_dispatch) = {\n match states_guard.get(job_id) {\n Some(JobProcessingState::Downloaded(ref path)) => {\n debug!(\"[{}] CheckDispatch: Current state is Downloaded.\", job_id);\n (true, Some(path.clone()))\n }\n Some(JobProcessingState::WaitingForDependencies(ref path)) => {\n debug!(\n \"[{}] CheckDispatch: Current state is WaitingForDependencies.\",\n job_id\n );\n (true, Some(path.clone()))\n }\n other_state => {\n debug!(\n \"[{}] CheckDispatch: Not in a dispatchable state. Current state: {:?}.\",\n job_id,\n other_state.map(|s| format!(\"{s:?}\"))\n );\n (false, None)\n }\n }\n };\n\n if current_state_is_dispatchable {\n let path = path_for_dispatch.unwrap();\n drop(states_guard);\n debug!(\n \"[{}] CheckDispatch: Calling are_dependencies_succeeded.\",\n job_id\n );\n let dependencies_succeeded = are_dependencies_succeeded(\n job_id,\n &planned_job.target_definition,\n job_states.clone(),\n &resolved_graph,\n config,\n flags,\n );\n states_guard = job_states.lock().unwrap();\n debug!(\n \"[{}] CheckDispatch: are_dependencies_succeeded returned: {}.\",\n job_id, dependencies_succeeded\n );\n\n let current_state_after_dep_check = states_guard.get(job_id).cloned();\n if !matches!(\n current_state_after_dep_check,\n Some(JobProcessingState::Downloaded(_))\n | Some(JobProcessingState::WaitingForDependencies(_))\n ) {\n debug!(\"[{}] CheckDispatch: State changed to {:?} while checking dependencies. Skipping dispatch.\", job_id, current_state_after_dep_check);\n continue;\n }\n\n if dependencies_succeeded {\n debug!(\n \"[{}] CheckDispatch: All dependencies satisfied. Dispatching to core worker.\",\n job_id\n );\n let worker_job = WorkerJob {\n request: planned_job.clone(),\n download_path: path.clone(),\n download_size_bytes: std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0),\n is_source_from_private_store: planned_job.use_private_store_source.is_some(),\n };\n if worker_job_tx.send(worker_job).is_ok() {\n states_guard.insert(\n job_id.clone(),\n JobProcessingState::DispatchedToCore(path.clone()),\n );\n event_tx\n .send(PipelineEvent::JobDispatchedToCore {\n target_id: job_id.clone(),\n })\n .ok();\n dispatched_this_round += 1;\n debug!(\"[{}] CheckDispatch: Successfully dispatched.\", job_id);\n } else {\n error!(\"[{}] CheckDispatch: Failed to send job to worker channel (channel closed?). Marking as failed.\", job_id);\n let err = Arc::new(SpsError::Generic(\"Worker channel closed\".to_string()));\n if !matches!(\n states_guard.get(job_id),\n Some(JobProcessingState::Failed(_))\n ) {\n states_guard\n .insert(job_id.clone(), JobProcessingState::Failed(err.clone()));\n event_tx\n .send(PipelineEvent::job_failed(\n job_id.clone(),\n planned_job.action.clone(),\n &err,\n ))\n .ok();\n }\n }\n } else if matches!(\n current_state_after_dep_check,\n Some(JobProcessingState::Downloaded(_))\n ) {\n debug!(\"[{}] CheckDispatch: Dependencies not met. Updating state to WaitingForDependencies.\", job_id);\n states_guard.insert(\n job_id.clone(),\n JobProcessingState::WaitingForDependencies(path.clone()),\n );\n } else {\n debug!(\n \"[{}] CheckDispatch: Dependencies not met. State remains {:?}.\",\n job_id, current_state_after_dep_check\n );\n }\n }\n }\n if dispatched_this_round > 0 {\n debug!(\n \"Dispatched {} jobs to core workers in this round.\",\n dispatched_this_round\n );\n }\n debug!(\"--- Exit check_and_dispatch ---\");\n}\n\nfn are_dependencies_succeeded(\n target_id: &str,\n target_def: &InstallTargetIdentifier,\n job_states_arc: Arc>>,\n resolved_graph: &ResolvedGraph,\n config: &Config,\n flags: &PipelineFlags,\n) -> bool {\n debug!(\"[{}] AreDepsSucceeded: Checking dependencies...\", target_id);\n let dependencies_to_check: Vec = match target_def {\n InstallTargetIdentifier::Formula(formula_arc) => {\n if let Some(resolved_dep_info) =\n resolved_graph.resolution_details.get(formula_arc.name())\n {\n let parent_strategy = resolved_dep_info.determined_install_strategy;\n let empty_actions = std::collections::HashMap::new();\n let context = sps_common::dependency::ResolutionContext {\n formulary: &sps_common::formulary::Formulary::new(config.clone()),\n keg_registry: &sps_common::keg::KegRegistry::new(config.clone()),\n sps_prefix: config.sps_root(),\n include_optional: flags.include_optional,\n include_test: false,\n skip_recommended: flags.skip_recommended,\n initial_target_preferences: &Default::default(),\n build_all_from_source: flags.build_from_source,\n cascade_source_preference_to_dependencies: true,\n has_bottle_for_current_platform:\n sps_core::install::bottle::has_bottle_for_current_platform,\n initial_target_actions: &empty_actions,\n };\n\n let deps: Vec = formula_arc\n .dependencies()\n .unwrap_or_default()\n .iter()\n .filter(|dep_edge| {\n context.should_process_dependency_edge(\n formula_arc,\n dep_edge.tags,\n parent_strategy,\n )\n })\n .map(|dep_edge| dep_edge.name.clone())\n .collect();\n debug!(\n \"[{}] AreDepsSucceeded: Formula dependencies to check: {:?}\",\n target_id, deps\n );\n deps\n } else {\n warn!(\"[{}] AreDepsSucceeded: Formula not found in ResolvedGraph. Assuming no dependencies.\", target_id);\n Vec::new()\n }\n }\n InstallTargetIdentifier::Cask(cask_arc) => {\n let deps = if let Some(deps_on) = &cask_arc.depends_on {\n deps_on.formula.clone()\n } else {\n Vec::new()\n };\n debug!(\n \"[{}] AreDepsSucceeded: Cask formula dependencies to check: {:?}\",\n target_id, deps\n );\n deps\n }\n };\n\n if dependencies_to_check.is_empty() {\n debug!(\n \"[{}] AreDepsSucceeded: No dependencies to check. Returning true.\",\n target_id\n );\n return true;\n }\n\n let states_guard = job_states_arc.lock().unwrap();\n for dep_name in &dependencies_to_check {\n match states_guard.get(dep_name) {\n Some(JobProcessingState::Succeeded) => {\n debug!(\n \"[{}] AreDepsSucceeded: Dependency '{}' is Succeeded.\",\n target_id, dep_name\n );\n }\n Some(JobProcessingState::Failed(err)) => {\n debug!(\n \"[{}] AreDepsSucceeded: Dependency '{}' is FAILED ({}). Returning false.\",\n target_id,\n dep_name,\n err_to_string(err)\n );\n return false;\n }\n None => {\n if let Some(resolved_dep_detail) = resolved_graph.resolution_details.get(dep_name) {\n if resolved_dep_detail.status == ResolutionStatus::Installed {\n debug!(\"[{}] AreDepsSucceeded: Dependency '{}' is already installed (from ResolvedGraph).\", target_id, dep_name);\n } else {\n debug!(\"[{}] AreDepsSucceeded: Dependency '{}' has no active state and not ResolvedGraph::Installed (is {:?}). Returning false.\", target_id, dep_name, resolved_dep_detail.status);\n return false;\n }\n } else {\n warn!(\"[{}] AreDepsSucceeded: Dependency '{}' not found in job_states OR ResolvedGraph. Assuming not met. Returning false.\", target_id, dep_name);\n return false;\n }\n }\n other_state => {\n debug!(\"[{}] AreDepsSucceeded: Dependency '{}' is not yet Succeeded. Current state: {:?}. Returning false.\", target_id, dep_name, other_state.map(|s| format!(\"{s:?}\")));\n return false;\n }\n }\n }\n debug!(\n \"[{}] AreDepsSucceeded: All dependencies Succeeded or were pre-installed. Returning true.\",\n target_id\n );\n true\n}\n\nfn propagate_failure(\n failed_job_id: &str,\n failure_reason: Arc,\n ctx: &PropagationContext,\n jobs_pending_or_active: &mut usize,\n) {\n debug!(\n \"[{}] PropagateFailure: Starting for reason: {}\",\n failed_job_id, failure_reason\n );\n let mut dependents_to_fail_queue = vec![failed_job_id.to_string()];\n let mut newly_failed_dependents = HashSet::new();\n\n {\n let mut states_guard = ctx.job_states.lock().unwrap();\n if !matches!(\n states_guard.get(failed_job_id),\n Some(JobProcessingState::Failed(_))\n ) {\n states_guard.insert(\n failed_job_id.to_string(),\n JobProcessingState::Failed(failure_reason.clone()),\n );\n }\n }\n\n let mut current_idx = 0;\n while current_idx < dependents_to_fail_queue.len() {\n let current_source_of_failure = dependents_to_fail_queue[current_idx].clone();\n current_idx += 1;\n\n for job_to_check in ctx.all_planned_jobs.iter() {\n if job_to_check.target_id == failed_job_id\n || newly_failed_dependents.contains(&job_to_check.target_id)\n {\n continue;\n }\n\n let is_dependent = match &job_to_check.target_definition {\n InstallTargetIdentifier::Formula(formula_arc) => ctx\n .resolved_graph\n .resolution_details\n .get(formula_arc.name())\n .is_some_and(|res_dep_info| {\n res_dep_info\n .formula\n .dependencies()\n .unwrap_or_default()\n .iter()\n .any(|d| d.name == current_source_of_failure)\n }),\n InstallTargetIdentifier::Cask(cask_arc) => {\n cask_arc.depends_on.as_ref().is_some_and(|deps| {\n deps.formula.contains(¤t_source_of_failure)\n || deps.cask.contains(¤t_source_of_failure)\n })\n }\n };\n\n if is_dependent {\n let mut states_guard = ctx.job_states.lock().unwrap();\n let current_state_of_dependent = states_guard.get(&job_to_check.target_id).cloned();\n\n if !matches!(\n current_state_of_dependent,\n Some(JobProcessingState::Succeeded) | Some(JobProcessingState::Failed(_))\n ) {\n let propagated_error = Arc::new(SpsError::DependencyError(format!(\n \"Dependency '{}' failed: {}\",\n current_source_of_failure,\n err_to_string(&failure_reason)\n )));\n states_guard.insert(\n job_to_check.target_id.clone(),\n JobProcessingState::Failed(propagated_error.clone()),\n );\n\n if newly_failed_dependents.insert(job_to_check.target_id.clone()) {\n dependents_to_fail_queue.push(job_to_check.target_id.clone());\n ctx.final_fail_count.fetch_add(1, Ordering::Relaxed);\n\n if *jobs_pending_or_active > 0 {\n *jobs_pending_or_active -= 1;\n debug!(\"[{}] PropagateFailure: Decremented jobs_pending_or_active to {} for propagated failure.\", job_to_check.target_id, *jobs_pending_or_active);\n } else {\n warn!(\"[{}] PropagateFailure: jobs_pending_or_active is already 0, cannot decrement for propagated failure.\", job_to_check.target_id);\n }\n\n if let Some(ref tx) = ctx.event_tx {\n tx.send(PipelineEvent::job_failed(\n job_to_check.target_id.clone(),\n job_to_check.action.clone(),\n &propagated_error,\n ))\n .ok();\n }\n debug!(\"[{}] PropagateFailure: Marked as FAILED due to propagated failure from '{}'.\", job_to_check.target_id, current_source_of_failure);\n }\n }\n drop(states_guard);\n }\n }\n }\n\n if !newly_failed_dependents.is_empty() {\n debug!(\n \"[{}] PropagateFailure: Finished. Newly failed dependents: {:?}\",\n failed_job_id, newly_failed_dependents\n );\n } else {\n debug!(\n \"[{}] PropagateFailure: Finished. No new dependents marked as failed.\",\n failed_job_id\n );\n }\n}\n"], ["/sps/sps-core/src/pipeline/worker.rs", "// sps-core/src/pipeline/worker.rs\nuse std::fs;\nuse std::path::PathBuf;\nuse std::sync::Arc;\n\nuse futures::executor::block_on;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::dependency::DependencyExt;\nuse sps_common::error::{Result as SpsResult, SpsError};\nuse sps_common::keg::KegRegistry;\nuse sps_common::model::formula::FormulaDependencies;\nuse sps_common::model::InstallTargetIdentifier;\nuse sps_common::pipeline::{JobAction, PipelineEvent, PipelinePackageType, WorkerJob};\nuse tokio::sync::broadcast;\nuse tracing::{debug, error, instrument, warn};\n\nuse crate::check::installed::{InstalledPackageInfo, PackageType as CorePackageType};\nuse crate::{build, install, uninstall, upgrade};\n\npub(super) fn execute_sync_job(\n worker_job: WorkerJob,\n config: &Config,\n cache: Arc,\n event_tx: broadcast::Sender,\n) -> std::result::Result<(JobAction, PipelinePackageType), Box<(JobAction, SpsError)>> {\n let action = worker_job.request.action.clone();\n\n let result = do_execute_sync_steps(worker_job, config, cache, event_tx);\n\n result\n .map_err(|e| Box::new((action.clone(), e)))\n .map(|pkg_type| (action, pkg_type))\n}\n\n#[instrument(skip_all, fields(job_id = %worker_job.request.target_id, action = ?worker_job.request.action))]\nfn do_execute_sync_steps(\n worker_job: WorkerJob,\n config: &Config,\n _cache: Arc, // Marked as unused if cache is not directly used in this function body\n event_tx: broadcast::Sender,\n) -> SpsResult {\n let job_request = worker_job.request;\n let download_path = worker_job.download_path;\n let is_source_from_private_store = worker_job.is_source_from_private_store;\n\n let (core_pkg_type, pipeline_pkg_type) = match &job_request.target_definition {\n InstallTargetIdentifier::Formula(_) => {\n (CorePackageType::Formula, PipelinePackageType::Formula)\n }\n InstallTargetIdentifier::Cask(_) => (CorePackageType::Cask, PipelinePackageType::Cask),\n };\n\n // Check dependencies before proceeding with formula install/upgrade\n if let InstallTargetIdentifier::Formula(formula_arc) = &job_request.target_definition {\n if matches!(job_request.action, JobAction::Install)\n || matches!(job_request.action, JobAction::Upgrade { .. })\n {\n debug!(\n \"[WORKER:{}] Pre-install check for dependencies. Formula: {}, Action: {:?}\",\n job_request.target_id,\n formula_arc.name(),\n job_request.action\n );\n\n let keg_registry = KegRegistry::new(config.clone());\n match formula_arc.dependencies() {\n Ok(dependencies) => {\n for dep in dependencies.runtime() {\n debug!(\"[WORKER:{}] Checking runtime dependency: '{}'. Required by: '{}'. Configured cellar: {}\", job_request.target_id, dep.name, formula_arc.name(), config.cellar_dir().display());\n\n match keg_registry.get_installed_keg(&dep.name) {\n Ok(Some(keg_info)) => {\n debug!(\"[WORKER:{}] Dependency '{}' FOUND by KegRegistry. Path: {}, Version: {}\", job_request.target_id, dep.name, keg_info.path.display(), keg_info.version_str);\n }\n Ok(None) => {\n debug!(\"[WORKER:{}] Dependency '{}' was NOT FOUND by KegRegistry for formula '{}'. THIS IS THE ERROR POINT.\", dep.name, job_request.target_id, formula_arc.name());\n let error_msg = format!(\n \"Runtime dependency '{}' for formula '{}' is not installed. Aborting operation for '{}'.\",\n dep.name, formula_arc.name(), job_request.target_id\n );\n error!(\"{}\", error_msg);\n return Err(SpsError::DependencyError(error_msg));\n }\n Err(e) => {\n debug!(\"[WORKER:{}] Error during KegRegistry check for dependency '{}': {}. Aborting for formula '{}'.\", job_request.target_id, dep.name, e, job_request.target_id);\n return Err(SpsError::Generic(format!(\n \"Failed to check KegRegistry for {}: {}\",\n dep.name, e\n )));\n }\n }\n }\n }\n Err(e) => {\n let error_msg = format!(\n \"Could not retrieve dependency list for formula '{}': {}. Aborting operation.\",\n job_request.target_id, e\n );\n error!(\"{}\", error_msg);\n return Err(SpsError::DependencyError(error_msg));\n }\n }\n debug!(\n \"[WORKER:{}] All required formula dependencies appear to be installed for '{}'.\",\n job_request.target_id,\n formula_arc.name()\n );\n }\n }\n\n let mut formula_installed_path: Option = None;\n\n match &job_request.action {\n JobAction::Upgrade {\n from_version,\n old_install_path,\n } => {\n debug!(\n \"[{}] Upgrading from version {}\",\n job_request.target_id, from_version\n );\n let old_info = InstalledPackageInfo {\n name: job_request.target_id.clone(),\n version: from_version.clone(),\n pkg_type: core_pkg_type.clone(),\n path: old_install_path.clone(),\n };\n\n match &job_request.target_definition {\n InstallTargetIdentifier::Formula(formula) => {\n let http_client_for_bottle_upgrade = Arc::new(reqwest::Client::new());\n let installed_path = if job_request.is_source_build {\n let _ = event_tx.send(PipelineEvent::BuildStarted {\n target_id: job_request.target_id.clone(),\n });\n let all_dep_paths = Vec::new(); // TODO: Populate this correctly if needed by upgrade_source_formula\n block_on(upgrade::source::upgrade_source_formula(\n formula,\n &download_path,\n &old_info,\n config,\n &all_dep_paths,\n ))?\n } else {\n block_on(upgrade::bottle::upgrade_bottle_formula(\n formula,\n &download_path,\n &old_info,\n config,\n http_client_for_bottle_upgrade,\n ))?\n };\n formula_installed_path = Some(installed_path);\n }\n InstallTargetIdentifier::Cask(cask) => {\n block_on(upgrade::cask::upgrade_cask_package(\n cask,\n &download_path,\n &old_info,\n config,\n ))?;\n }\n }\n }\n JobAction::Install | JobAction::Reinstall { .. } => {\n if let JobAction::Reinstall {\n version: from_version,\n current_install_path: old_install_path,\n } = &job_request.action\n {\n debug!(\n \"[{}] Reinstall: Removing existing version {}...\",\n job_request.target_id, from_version\n );\n let _ = event_tx.send(PipelineEvent::UninstallStarted {\n target_id: job_request.target_id.clone(),\n version: from_version.clone(),\n });\n\n let old_info_for_reinstall = InstalledPackageInfo {\n name: job_request.target_id.clone(),\n version: from_version.clone(),\n pkg_type: core_pkg_type.clone(),\n path: old_install_path.clone(),\n };\n let uninstall_opts = uninstall::UninstallOptions { skip_zap: true };\n\n match core_pkg_type {\n CorePackageType::Formula => uninstall::uninstall_formula_artifacts(\n &old_info_for_reinstall,\n config,\n &uninstall_opts,\n )?,\n CorePackageType::Cask => {\n uninstall::uninstall_cask_artifacts(&old_info_for_reinstall, config)?\n }\n }\n debug!(\n \"[{}] Reinstall: Removed existing version {}.\",\n job_request.target_id, from_version\n );\n let _ = event_tx.send(PipelineEvent::UninstallFinished {\n target_id: job_request.target_id.clone(),\n version: from_version.clone(),\n });\n }\n\n let _ = event_tx.send(PipelineEvent::InstallStarted {\n target_id: job_request.target_id.clone(),\n pkg_type: pipeline_pkg_type,\n });\n\n match &job_request.target_definition {\n InstallTargetIdentifier::Formula(formula) => {\n let install_dir_base =\n (**formula).install_prefix(config.cellar_dir().as_path())?;\n if let Some(parent_dir) = install_dir_base.parent() {\n fs::create_dir_all(parent_dir).map_err(|e| SpsError::Io(Arc::new(e)))?;\n }\n\n if job_request.is_source_build {\n debug!(\"[{}] Building from source...\", job_request.target_id);\n let _ = event_tx.send(PipelineEvent::BuildStarted {\n target_id: job_request.target_id.clone(),\n });\n let build_dep_paths: Vec = vec![]; // TODO: Populate this from ResolvedGraph\n\n let build_future = build::compile::build_from_source(\n &download_path,\n formula,\n config,\n &build_dep_paths,\n );\n let installed_dir = block_on(build_future)?;\n formula_installed_path = Some(installed_dir);\n } else {\n debug!(\"[{}] Installing bottle...\", job_request.target_id);\n let installed_dir =\n install::bottle::exec::install_bottle(&download_path, formula, config)?;\n formula_installed_path = Some(installed_dir);\n }\n }\n InstallTargetIdentifier::Cask(cask) => {\n if is_source_from_private_store {\n debug!(\n \"[{}] Reinstalling cask from private store...\",\n job_request.target_id\n );\n\n if let Some(file_name) = download_path.file_name() {\n let app_name = file_name.to_string_lossy().to_string();\n let applications_app_path = config.applications_dir().join(&app_name);\n\n if applications_app_path.exists()\n || applications_app_path.symlink_metadata().is_ok()\n {\n debug!(\n \"Removing existing app at {}\",\n applications_app_path.display()\n );\n let _ = install::cask::helpers::remove_path_robustly(\n &applications_app_path,\n config,\n true,\n );\n }\n\n debug!(\n \"Symlinking app from private store {} to {}\",\n download_path.display(),\n applications_app_path.display()\n );\n if let Err(e) =\n std::os::unix::fs::symlink(&download_path, &applications_app_path)\n {\n return Err(SpsError::InstallError(format!(\n \"Failed to symlink app from private store to {}: {}\",\n applications_app_path.display(),\n e\n )));\n }\n\n let cask_version =\n cask.version.clone().unwrap_or_else(|| \"latest\".to_string());\n let cask_version_path =\n config.cask_room_version_path(&cask.token, &cask_version);\n\n if !cask_version_path.exists() {\n fs::create_dir_all(&cask_version_path)?;\n }\n\n let caskroom_symlink_path = cask_version_path.join(&app_name);\n if caskroom_symlink_path.exists()\n || caskroom_symlink_path.symlink_metadata().is_ok()\n {\n let _ = fs::remove_file(&caskroom_symlink_path);\n }\n\n #[cfg(unix)]\n {\n if let Err(e) = std::os::unix::fs::symlink(\n &applications_app_path,\n &caskroom_symlink_path,\n ) {\n warn!(\"Failed to create Caskroom symlink: {}\", e);\n }\n }\n\n let created_artifacts = vec![\n sps_common::model::artifact::InstalledArtifact::AppBundle {\n path: applications_app_path.clone(),\n },\n sps_common::model::artifact::InstalledArtifact::CaskroomLink {\n link_path: caskroom_symlink_path.clone(),\n target_path: applications_app_path.clone(),\n },\n ];\n\n debug!(\n \"[{}] Writing manifest for private store reinstall...\",\n job_request.target_id\n );\n if let Err(e) = install::cask::write_cask_manifest(\n cask,\n &cask_version_path,\n created_artifacts,\n ) {\n error!(\n \"[{}] Failed to write CASK_INSTALL_MANIFEST.json during private store reinstall: {}\",\n job_request.target_id, e\n );\n return Err(SpsError::InstallError(format!(\n \"Failed to write manifest during private store reinstall for {}: {}\",\n job_request.target_id, e\n )));\n }\n } else {\n return Err(SpsError::InstallError(format!(\n \"Failed to get app name from private store path: {}\",\n download_path.display()\n )));\n }\n } else {\n debug!(\"[{}] Installing cask...\", job_request.target_id);\n install::cask::install_cask(\n cask,\n &download_path,\n config,\n &job_request.action,\n )?;\n }\n }\n }\n }\n };\n\n if let Some(ref installed_path) = formula_installed_path {\n debug!(\n \"[{}] Formula operation resulted in keg path: {}\",\n job_request.target_id,\n installed_path.display()\n );\n } else if core_pkg_type == CorePackageType::Cask {\n debug!(\"[{}] Cask operation completed.\", job_request.target_id);\n }\n\n if let (InstallTargetIdentifier::Formula(formula), Some(keg_path_for_linking)) =\n (&job_request.target_definition, &formula_installed_path)\n {\n debug!(\n \"[{}] Linking artifacts for formula {}...\",\n job_request.target_id,\n (**formula).name()\n );\n let _ = event_tx.send(PipelineEvent::LinkStarted {\n target_id: job_request.target_id.clone(),\n pkg_type: pipeline_pkg_type,\n });\n install::bottle::link::link_formula_artifacts(formula, keg_path_for_linking, config)?;\n debug!(\n \"[{}] Linking complete for formula {}.\",\n job_request.target_id,\n (**formula).name()\n );\n }\n\n Ok(pipeline_pkg_type)\n}\n"], ["/sps/sps/src/pipeline/downloader.rs", "// sps/src/pipeline/downloader.rs\nuse std::fs;\nuse std::path::PathBuf;\nuse std::sync::Arc;\n\nuse reqwest::Client as HttpClient;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::model::InstallTargetIdentifier;\nuse sps_common::pipeline::{DownloadOutcome, PipelineEvent, PlannedJob};\nuse sps_common::SpsError;\nuse sps_core::{build, install};\nuse sps_net::http::ProgressCallback;\nuse sps_net::UrlField;\nuse tokio::sync::{broadcast, mpsc};\nuse tokio::task::JoinSet;\nuse tracing::{error, warn};\n\nuse super::runner::get_panic_message;\n\npub(crate) struct DownloadCoordinator {\n config: Config,\n cache: Arc,\n http_client: Arc,\n event_tx: Option>,\n}\n\nimpl DownloadCoordinator {\n pub fn new(\n config: Config,\n cache: Arc,\n http_client: Arc,\n event_tx: broadcast::Sender,\n ) -> Self {\n Self {\n config,\n cache,\n http_client,\n event_tx: Some(event_tx),\n }\n }\n\n pub async fn coordinate_downloads(\n &mut self,\n planned_jobs: Vec,\n download_outcome_tx: mpsc::Sender,\n ) -> Vec<(String, SpsError)> {\n let mut download_tasks = JoinSet::new();\n let mut critical_spawn_errors: Vec<(String, SpsError)> = Vec::new();\n\n for planned_job in planned_jobs {\n let _job_id_for_task = planned_job.target_id.clone();\n\n let task_config = self.config.clone();\n let task_cache = Arc::clone(&self.cache);\n let task_http_client = Arc::clone(&self.http_client);\n let task_event_tx = self.event_tx.as_ref().cloned();\n let outcome_tx_clone = download_outcome_tx.clone();\n let current_planned_job_for_task = planned_job.clone();\n\n download_tasks.spawn(async move {\n let job_id_in_task = current_planned_job_for_task.target_id.clone();\n let download_path_result: Result;\n\n if let Some(private_path) = current_planned_job_for_task.use_private_store_source.clone() {\n download_path_result = Ok(private_path);\n } else {\n let display_url_for_event = match ¤t_planned_job_for_task.target_definition {\n InstallTargetIdentifier::Formula(f) => {\n if !current_planned_job_for_task.is_source_build {\n sps_core::install::bottle::exec::get_bottle_for_platform(f)\n .map_or_else(|_| f.url.clone(), |(_, spec)| spec.url.clone())\n } else {\n f.url.clone()\n }\n }\n InstallTargetIdentifier::Cask(c) => match &c.url {\n Some(UrlField::Simple(s)) => s.clone(),\n Some(UrlField::WithSpec { url, .. }) => url.clone(),\n None => \"N/A (No Cask URL)\".to_string(),\n },\n };\n\n if display_url_for_event == \"N/A (No Cask URL)\"\n || (display_url_for_event.is_empty() && !current_planned_job_for_task.is_source_build)\n {\n let _err_msg = \"Download URL is missing or invalid\".to_string();\n let sps_err = SpsError::Generic(format!(\n \"Download URL is missing or invalid for job {job_id_in_task}\"\n ));\n if let Some(ref tx) = task_event_tx {\n tx.send(PipelineEvent::download_failed(\n job_id_in_task.clone(),\n display_url_for_event,\n &sps_err,\n )).ok();\n }\n download_path_result = Err(sps_err);\n } else {\n if let Some(ref tx) = task_event_tx {\n tx.send(PipelineEvent::DownloadStarted {\n target_id: job_id_in_task.clone(),\n url: display_url_for_event.clone(),\n }).ok();\n }\n\n // Create progress callback\n let progress_callback: Option = if let Some(ref tx) = task_event_tx {\n let tx_clone = tx.clone();\n let job_id_for_callback = job_id_in_task.clone();\n Some(Arc::new(move |bytes_so_far: u64, total_size: Option| {\n let _ = tx_clone.send(PipelineEvent::DownloadProgressUpdate {\n target_id: job_id_for_callback.clone(),\n bytes_so_far,\n total_size,\n });\n }))\n } else {\n None\n };\n\n let actual_download_result: Result<(PathBuf, bool), SpsError> =\n match ¤t_planned_job_for_task.target_definition {\n InstallTargetIdentifier::Formula(f) => {\n if current_planned_job_for_task.is_source_build {\n build::compile::download_source_with_progress(f, &task_config, progress_callback).await.map(|p| (p, false))\n } else {\n install::bottle::exec::download_bottle_with_progress_and_cache_info(\n f,\n &task_config,\n &task_http_client,\n progress_callback,\n )\n .await\n }\n }\n InstallTargetIdentifier::Cask(c) => {\n install::cask::download_cask_with_progress(c, task_cache.as_ref(), progress_callback).await.map(|p| (p, false))\n }\n };\n\n match actual_download_result {\n Ok((path, was_cached)) => {\n let size_bytes = fs::metadata(&path).map(|m| m.len()).unwrap_or(0);\n if let Some(ref tx) = task_event_tx {\n if was_cached {\n tx.send(PipelineEvent::DownloadCached {\n target_id: job_id_in_task.clone(),\n size_bytes,\n }).ok();\n } else {\n tx.send(PipelineEvent::DownloadFinished {\n target_id: job_id_in_task.clone(),\n path: path.clone(),\n size_bytes,\n }).ok();\n }\n }\n download_path_result = Ok(path);\n }\n Err(e) => {\n warn!(\n \"[DownloaderTask:{}] Download failed from {}: {}\",\n job_id_in_task, display_url_for_event, e\n );\n if let Some(ref tx) = task_event_tx {\n tx.send(PipelineEvent::download_failed(\n job_id_in_task.clone(),\n display_url_for_event,\n &e,\n )).ok();\n }\n download_path_result = Err(e);\n }\n }\n }\n }\n\n let outcome = DownloadOutcome {\n planned_job: current_planned_job_for_task,\n result: download_path_result,\n };\n\n if let Err(send_err) = outcome_tx_clone.send(outcome).await {\n error!(\n \"[DownloaderTask:{}] CRITICAL: Failed to send download outcome to runner: {}. Job processing will likely stall.\",\n job_id_in_task, send_err\n );\n }\n });\n }\n\n while let Some(join_result) = download_tasks.join_next().await {\n if let Err(e) = join_result {\n let panic_msg = get_panic_message(e.into_panic());\n error!(\n \"[Downloader] A download task panicked: {}. This job's outcome was not sent.\",\n panic_msg\n );\n critical_spawn_errors.push((\n \"[UnknownDownloadTaskPanic]\".to_string(),\n SpsError::Generic(format!(\"A download task panicked: {panic_msg}\")),\n ));\n }\n }\n self.event_tx = None;\n critical_spawn_errors\n }\n}\n"], ["/sps/sps/src/cli/status.rs", "// sps/src/cli/status.rs\nuse std::collections::{HashMap, HashSet};\nuse std::io::{self, Write};\nuse std::time::Instant;\n\nuse colored::*;\nuse sps_common::config::Config;\nuse sps_common::pipeline::{PipelineEvent, PipelinePackageType};\nuse tokio::sync::broadcast;\nuse tracing::debug;\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq)]\nenum JobStatus {\n Waiting,\n Downloading,\n Downloaded,\n Cached,\n Processing,\n Installing,\n Linking,\n Success,\n Failed,\n}\n\nimpl JobStatus {\n fn display_state(&self) -> &'static str {\n match self {\n JobStatus::Waiting => \"waiting\",\n JobStatus::Downloading => \"downloading\",\n JobStatus::Downloaded => \"downloaded\",\n JobStatus::Cached => \"cached\",\n JobStatus::Processing => \"processing\",\n JobStatus::Installing => \"installing\",\n JobStatus::Linking => \"linking\",\n JobStatus::Success => \"success\",\n JobStatus::Failed => \"failed\",\n }\n }\n\n fn slot_indicator(&self) -> String {\n match self {\n JobStatus::Waiting => \" ⧗\".yellow().to_string(),\n JobStatus::Downloading => \" ⬇\".blue().to_string(),\n JobStatus::Downloaded => \" ✓\".green().to_string(),\n JobStatus::Cached => \" ⌂\".cyan().to_string(),\n JobStatus::Processing => \" ⚙\".yellow().to_string(),\n JobStatus::Installing => \" ⚙\".cyan().to_string(),\n JobStatus::Linking => \" →\".magenta().to_string(),\n JobStatus::Success => \" ✓\".green().bold().to_string(),\n JobStatus::Failed => \" ✗\".red().bold().to_string(),\n }\n }\n\n fn colored_state(&self) -> ColoredString {\n match self {\n JobStatus::Waiting => self.display_state().dimmed(),\n JobStatus::Downloading => self.display_state().blue(),\n JobStatus::Downloaded => self.display_state().green(),\n JobStatus::Cached => self.display_state().cyan(),\n JobStatus::Processing => self.display_state().yellow(),\n JobStatus::Installing => self.display_state().yellow(),\n JobStatus::Linking => self.display_state().yellow(),\n JobStatus::Success => self.display_state().green(),\n JobStatus::Failed => self.display_state().red(),\n }\n }\n}\n\nstruct JobInfo {\n name: String,\n status: JobStatus,\n size_bytes: Option,\n current_bytes_downloaded: Option,\n start_time: Option,\n pool_id: usize,\n}\n\nimpl JobInfo {\n fn _elapsed_str(&self) -> String {\n match self.start_time {\n Some(start) => format!(\"{:.1}s\", start.elapsed().as_secs_f64()),\n None => \"–\".to_string(),\n }\n }\n\n fn size_str(&self) -> String {\n match self.size_bytes {\n Some(bytes) => format_bytes(bytes),\n None => \"–\".to_string(),\n }\n }\n}\n\nstruct StatusDisplay {\n jobs: HashMap,\n job_order: Vec,\n total_jobs: usize,\n next_pool_id: usize,\n _start_time: Instant,\n active_downloads: HashSet,\n total_bytes: u64,\n downloaded_bytes: u64,\n last_speed_update: Instant,\n last_aggregate_bytes_snapshot: u64,\n current_speed_bps: f64,\n _speed_history: Vec,\n header_printed: bool,\n last_line_count: usize,\n}\n\nimpl StatusDisplay {\n fn new() -> Self {\n Self {\n jobs: HashMap::new(),\n job_order: Vec::new(),\n total_jobs: 0,\n next_pool_id: 1,\n _start_time: Instant::now(),\n active_downloads: HashSet::new(),\n total_bytes: 0,\n downloaded_bytes: 0,\n last_speed_update: Instant::now(),\n last_aggregate_bytes_snapshot: 0,\n current_speed_bps: 0.0,\n _speed_history: Vec::new(),\n header_printed: false,\n last_line_count: 0,\n }\n }\n\n fn add_job(&mut self, target_id: String, status: JobStatus, size_bytes: Option) {\n if !self.jobs.contains_key(&target_id) {\n let job_info = JobInfo {\n name: target_id.clone(),\n status,\n size_bytes,\n current_bytes_downloaded: if status == JobStatus::Downloading {\n Some(0)\n } else {\n None\n },\n start_time: if status != JobStatus::Waiting {\n Some(Instant::now())\n } else {\n None\n },\n pool_id: self.next_pool_id,\n };\n\n if let Some(bytes) = size_bytes {\n self.total_bytes += bytes;\n }\n\n if status == JobStatus::Downloading {\n self.active_downloads.insert(target_id.to_string());\n }\n\n self.jobs.insert(target_id.clone(), job_info);\n self.job_order.push(target_id);\n self.next_pool_id += 1;\n }\n }\n\n fn update_job_status(&mut self, target_id: &str, status: JobStatus, size_bytes: Option) {\n if let Some(job) = self.jobs.get_mut(target_id) {\n let was_downloading = job.status == JobStatus::Downloading;\n let is_downloading = status == JobStatus::Downloading;\n\n job.status = status;\n\n if job.start_time.is_none() && status != JobStatus::Waiting {\n job.start_time = Some(Instant::now());\n }\n\n if let Some(bytes) = size_bytes {\n if job.size_bytes.is_none() {\n self.total_bytes += bytes;\n }\n job.size_bytes = Some(bytes);\n }\n\n // Update download counts\n if was_downloading && !is_downloading {\n self.active_downloads.remove(target_id);\n if let Some(bytes) = job.size_bytes {\n job.current_bytes_downloaded = Some(bytes);\n self.downloaded_bytes += bytes;\n }\n } else if !was_downloading && is_downloading {\n self.active_downloads.insert(target_id.to_string());\n job.current_bytes_downloaded = Some(0);\n }\n }\n }\n\n fn update_download_progress(\n &mut self,\n target_id: &str,\n bytes_so_far: u64,\n total_size: Option,\n ) {\n if let Some(job) = self.jobs.get_mut(target_id) {\n job.current_bytes_downloaded = Some(bytes_so_far);\n\n if let Some(total) = total_size {\n if job.size_bytes.is_none() {\n // Update total bytes estimate\n self.total_bytes += total;\n job.size_bytes = Some(total);\n } else if job.size_bytes != Some(total) {\n // Adjust total bytes if estimate changed\n if let Some(old_size) = job.size_bytes {\n self.total_bytes = self.total_bytes.saturating_sub(old_size) + total;\n }\n job.size_bytes = Some(total);\n }\n }\n }\n }\n\n fn update_speed(&mut self) {\n let now = Instant::now();\n let time_diff = now.duration_since(self.last_speed_update).as_secs_f64();\n\n if time_diff >= 0.0625 {\n // Calculate current total bytes for all jobs with current download progress\n let current_active_bytes: u64 = self\n .jobs\n .values()\n .filter(|job| matches!(job.status, JobStatus::Downloading))\n .map(|job| job.current_bytes_downloaded.unwrap_or(0))\n .sum();\n\n // Calculate bytes difference since last update\n let bytes_diff =\n current_active_bytes.saturating_sub(self.last_aggregate_bytes_snapshot);\n\n // Calculate speed\n if time_diff > 0.0 && bytes_diff > 0 {\n self.current_speed_bps = bytes_diff as f64 / time_diff;\n } else if !self\n .jobs\n .values()\n .any(|job| job.status == JobStatus::Downloading)\n {\n // No active downloads, reset speed to 0\n self.current_speed_bps = 0.0;\n }\n // If no bytes diff but still have active downloads, keep previous speed\n\n self.last_speed_update = now;\n self.last_aggregate_bytes_snapshot = current_active_bytes;\n }\n }\n\n fn render(&mut self) {\n self.update_speed();\n\n if !self.header_printed {\n // First render - print header and jobs\n self.print_header();\n let job_output = self.build_job_rows();\n print!(\"{job_output}\");\n self.header_printed = true;\n // Count lines: header + jobs + separator + summary\n let job_lines = job_output.lines().count();\n self.last_line_count = 1 + job_lines + 1 + 1;\n } else {\n // Subsequent renders - clear and reprint header, job rows and summary\n self.clear_previous_output();\n self.print_header();\n let job_output = self.build_job_rows();\n print!(\"{job_output}\");\n // Update line count (header + jobs + separator)\n let job_lines = job_output.lines().count();\n self.last_line_count = 1 + job_lines + 1;\n }\n\n // Print separator\n println!(\"{}\", \"─\".repeat(49).dimmed());\n\n // Print status summary\n let completed = self\n .jobs\n .values()\n .filter(|j| matches!(j.status, JobStatus::Success))\n .count();\n let failed = self\n .jobs\n .values()\n .filter(|j| matches!(j.status, JobStatus::Failed))\n .count();\n let _progress_chars = self.generate_progress_bar(completed, failed);\n let _speed_str = format_speed(self.current_speed_bps);\n\n io::stdout().flush().unwrap();\n }\n\n fn print_header(&self) {\n println!(\n \"{:<6} {:<12} {:<15} {:>8} {}\",\n \"IID\".bold().dimmed(),\n \"STATE\".bold().dimmed(),\n \"PKG\".bold().dimmed(),\n \"SIZE\".bold().dimmed(),\n \"SLOT\".bold().dimmed()\n );\n }\n\n fn build_job_rows(&self) -> String {\n let mut output = String::new();\n\n // Job rows\n for target_id in &self.job_order {\n if let Some(job) = self.jobs.get(target_id) {\n let progress_str = if job.status == JobStatus::Downloading {\n match (job.current_bytes_downloaded, job.size_bytes) {\n (Some(downloaded), Some(_total)) => format_bytes(downloaded).to_string(),\n (Some(downloaded), None) => format_bytes(downloaded),\n _ => job.size_str(),\n }\n } else {\n job.size_str()\n };\n\n output.push_str(&format!(\n \"{:<6} {:<12} {:<15} {:>8} {}\\n\",\n format!(\"#{:02}\", job.pool_id).cyan(),\n job.status.colored_state(),\n job.name.cyan(),\n progress_str,\n job.status.slot_indicator()\n ));\n }\n }\n\n output\n }\n\n fn clear_previous_output(&self) {\n // Move cursor up and clear lines\n for _ in 0..self.last_line_count {\n print!(\"\\x1b[1A\\x1b[2K\"); // Move up one line and clear it\n }\n io::stdout().flush().unwrap();\n }\n\n fn generate_progress_bar(&self, completed: usize, failed: usize) -> String {\n if self.total_jobs == 0 {\n return \"\".to_string();\n }\n\n let total_done = completed + failed;\n let progress_width = 8;\n let filled = (total_done * progress_width) / self.total_jobs;\n let remaining = progress_width - filled;\n\n let filled_str = \"▍\".repeat(filled).green();\n let remaining_str = \"·\".repeat(remaining).dimmed();\n\n format!(\"{filled_str}{remaining_str}\")\n }\n}\n\nfn format_bytes(bytes: u64) -> String {\n const UNITS: &[&str] = &[\"B\", \"kB\", \"MB\", \"GB\"];\n let mut value = bytes as f64;\n let mut unit_idx = 0;\n\n while value >= 1000.0 && unit_idx < UNITS.len() - 1 {\n value /= 1000.0;\n unit_idx += 1;\n }\n\n if unit_idx == 0 {\n format!(\"{bytes}B\")\n } else {\n format!(\"{:.1}{}\", value, UNITS[unit_idx])\n }\n}\n\nfn format_speed(bytes_per_sec: f64) -> String {\n if bytes_per_sec < 1.0 {\n return \"0 B/s\".to_string();\n }\n\n const UNITS: &[&str] = &[\"B/s\", \"kB/s\", \"MB/s\", \"GB/s\"];\n let mut value = bytes_per_sec;\n let mut unit_idx = 0;\n\n while value >= 1000.0 && unit_idx < UNITS.len() - 1 {\n value /= 1000.0;\n unit_idx += 1;\n }\n\n format!(\"{:.1} {}\", value, UNITS[unit_idx])\n}\n\npub async fn handle_events(_config: Config, mut event_rx: broadcast::Receiver) {\n let mut display = StatusDisplay::new();\n let mut logs_buffer = Vec::new();\n let mut pipeline_active = false;\n let mut refresh_interval = tokio::time::interval(tokio::time::Duration::from_millis(62));\n refresh_interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);\n\n loop {\n tokio::select! {\n _ = refresh_interval.tick() => {\n if pipeline_active && display.header_printed {\n display.render();\n }\n }\n event_result = event_rx.recv() => {\n match event_result {\n Ok(event) => match event {\n PipelineEvent::PipelineStarted { total_jobs } => {\n pipeline_active = true;\n display.total_jobs = total_jobs;\n println!(\"{}\", \"Starting pipeline.\".cyan().bold());\n }\n PipelineEvent::PlanningStarted => {\n debug!(\"{}\", \"Planning operations.\".cyan());\n }\n PipelineEvent::DependencyResolutionStarted => {\n println!(\"{}\", \"Resolving dependencies\".cyan());\n }\n PipelineEvent::DependencyResolutionFinished => {\n debug!(\"{}\", \"Dependency resolution complete.\".cyan());\n }\n PipelineEvent::PlanningFinished { job_count } => {\n println!(\"{} {}\", \"Planning finished. Jobs:\".bold(), job_count);\n println!();\n }\n PipelineEvent::DownloadStarted { target_id, url: _ } => {\n display.add_job(target_id.clone(), JobStatus::Downloading, None);\n if pipeline_active {\n display.render();\n }\n }\n PipelineEvent::DownloadFinished {\n target_id,\n size_bytes,\n ..\n } => {\n display.update_job_status(&target_id, JobStatus::Downloaded, Some(size_bytes));\n if pipeline_active {\n display.render();\n }\n }\n PipelineEvent::DownloadProgressUpdate {\n target_id,\n bytes_so_far,\n total_size,\n } => {\n display.update_download_progress(&target_id, bytes_so_far, total_size);\n if pipeline_active {\n display.render();\n }\n }\n PipelineEvent::DownloadCached {\n target_id,\n size_bytes,\n } => {\n display.update_job_status(&target_id, JobStatus::Cached, Some(size_bytes));\n if pipeline_active {\n display.render();\n }\n }\n PipelineEvent::DownloadFailed {\n target_id, error, ..\n } => {\n display.update_job_status(&target_id, JobStatus::Failed, None);\n logs_buffer.push(format!(\n \"{} {}: {}\",\n \"Download failed:\".red(),\n target_id.cyan(),\n error.red()\n ));\n if pipeline_active {\n display.render();\n }\n }\n PipelineEvent::JobProcessingStarted { target_id } => {\n display.update_job_status(&target_id, JobStatus::Processing, None);\n if pipeline_active {\n display.render();\n }\n }\n PipelineEvent::BuildStarted { target_id } => {\n display.update_job_status(&target_id, JobStatus::Processing, None);\n if pipeline_active {\n display.render();\n }\n }\n PipelineEvent::InstallStarted { target_id, .. } => {\n display.update_job_status(&target_id, JobStatus::Installing, None);\n if pipeline_active {\n display.render();\n }\n }\n PipelineEvent::LinkStarted { target_id, .. } => {\n display.update_job_status(&target_id, JobStatus::Linking, None);\n if pipeline_active {\n display.render();\n }\n }\n PipelineEvent::JobSuccess {\n target_id,\n action,\n pkg_type,\n } => {\n display.update_job_status(&target_id, JobStatus::Success, None);\n let type_str = match pkg_type {\n PipelinePackageType::Formula => \"Formula\",\n PipelinePackageType::Cask => \"Cask\",\n };\n let action_str = match action {\n sps_common::pipeline::JobAction::Install => \"Installed\",\n sps_common::pipeline::JobAction::Upgrade { .. } => \"Upgraded\",\n sps_common::pipeline::JobAction::Reinstall { .. } => \"Reinstalled\",\n };\n logs_buffer.push(format!(\n \"{}: {} ({})\",\n action_str.green(),\n target_id.cyan(),\n type_str,\n ));\n if pipeline_active {\n display.render();\n }\n }\n PipelineEvent::JobFailed {\n target_id, error, ..\n } => {\n display.update_job_status(&target_id, JobStatus::Failed, None);\n logs_buffer.push(format!(\n \"{} {}: {}\",\n \"✗\".red().bold(),\n target_id.cyan(),\n error.red()\n ));\n if pipeline_active {\n display.render();\n }\n }\n PipelineEvent::LogInfo { message } => {\n logs_buffer.push(message);\n }\n PipelineEvent::LogWarn { message } => {\n logs_buffer.push(message.yellow().to_string());\n }\n PipelineEvent::LogError { message } => {\n logs_buffer.push(message.red().to_string());\n }\n PipelineEvent::PipelineFinished {\n duration_secs,\n success_count,\n fail_count,\n } => {\n if display.header_printed {\n display.render();\n }\n\n println!();\n\n println!(\n \"{} in {:.2}s ({} succeeded, {} failed)\",\n \"Pipeline finished\".bold(),\n duration_secs,\n success_count,\n fail_count\n );\n\n if !logs_buffer.is_empty() {\n println!();\n for log in &logs_buffer {\n println!(\"{log}\");\n }\n }\n\n break;\n }\n _ => {}\n },\n Err(broadcast::error::RecvError::Closed) => {\n break;\n }\n Err(broadcast::error::RecvError::Lagged(_)) => {\n // Ignore lag for now\n }\n }\n }\n }\n }\n}\n"], ["/sps/sps-common/src/pipeline.rs", "// sps-common/src/pipeline.rs\nuse std::path::PathBuf;\nuse std::sync::Arc; // Required for Arc in JobProcessingState\n\nuse serde::{Deserialize, Serialize};\n\nuse crate::dependency::ResolvedGraph; // Needed for planner output\nuse crate::error::SpsError;\nuse crate::model::InstallTargetIdentifier;\n\n// --- Shared Enums / Structs ---\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]\npub enum PipelinePackageType {\n Formula,\n Cask,\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] // Added PartialEq, Eq\npub enum JobAction {\n Install,\n Upgrade {\n from_version: String,\n old_install_path: PathBuf,\n },\n Reinstall {\n version: String,\n current_install_path: PathBuf,\n },\n}\n\n#[derive(Debug, Clone)]\npub struct PlannedJob {\n pub target_id: String,\n pub target_definition: InstallTargetIdentifier,\n pub action: JobAction,\n pub is_source_build: bool,\n pub use_private_store_source: Option,\n}\n\n#[derive(Debug, Clone)]\npub struct WorkerJob {\n pub request: PlannedJob,\n pub download_path: PathBuf,\n pub download_size_bytes: u64,\n pub is_source_from_private_store: bool,\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub enum PipelineEvent {\n PipelineStarted {\n total_jobs: usize,\n },\n PipelineFinished {\n duration_secs: f64,\n success_count: usize,\n fail_count: usize,\n },\n PlanningStarted,\n DependencyResolutionStarted,\n DependencyResolutionFinished,\n PlanningFinished {\n job_count: usize,\n // Optionally, we can pass the ResolvedGraph here if the status handler needs it,\n // but it might be too large for a broadcast event.\n // resolved_graph: Option>, // Example\n },\n DownloadStarted {\n target_id: String,\n url: String,\n },\n DownloadFinished {\n target_id: String,\n path: PathBuf,\n size_bytes: u64,\n },\n DownloadProgressUpdate {\n target_id: String,\n bytes_so_far: u64,\n total_size: Option,\n },\n DownloadCached {\n target_id: String,\n size_bytes: u64,\n },\n DownloadFailed {\n target_id: String,\n url: String,\n error: String, // Keep as String for simplicity in events\n },\n JobProcessingStarted {\n // From core worker\n target_id: String,\n },\n JobDispatchedToCore {\n // New: From runner to UI when job sent to worker pool\n target_id: String,\n },\n UninstallStarted {\n target_id: String,\n version: String,\n },\n UninstallFinished {\n target_id: String,\n version: String,\n },\n BuildStarted {\n target_id: String,\n },\n InstallStarted {\n target_id: String,\n pkg_type: PipelinePackageType,\n },\n LinkStarted {\n target_id: String,\n pkg_type: PipelinePackageType,\n },\n JobSuccess {\n // From core worker\n target_id: String,\n action: JobAction,\n pkg_type: PipelinePackageType,\n },\n JobFailed {\n // From core worker or runner (propagated)\n target_id: String,\n action: JobAction, // Action that was attempted\n error: String, // Keep as String\n },\n LogInfo {\n message: String,\n },\n LogWarn {\n message: String,\n },\n LogError {\n message: String,\n },\n}\n\nimpl PipelineEvent {\n // SpsError kept for internal use, but events use String for error messages\n pub fn job_failed(target_id: String, action: JobAction, error: &SpsError) -> Self {\n PipelineEvent::JobFailed {\n target_id,\n action,\n error: error.to_string(),\n }\n }\n pub fn download_failed(target_id: String, url: String, error: &SpsError) -> Self {\n PipelineEvent::DownloadFailed {\n target_id,\n url,\n error: error.to_string(),\n }\n }\n}\n\n// --- New Structs and Enums for Refactored Runner ---\n\n/// Represents the current processing state of a job in the pipeline.\n#[derive(Debug, Clone)]\npub enum JobProcessingState {\n /// Waiting for download to be initiated.\n PendingDownload,\n /// Download is in progress (managed by DownloadCoordinator).\n Downloading,\n /// Download completed successfully, artifact at PathBuf.\n Downloaded(PathBuf),\n /// Downloaded, but waiting for dependencies to be in Succeeded state.\n WaitingForDependencies(PathBuf),\n /// Dispatched to the core worker pool for installation/processing.\n DispatchedToCore(PathBuf),\n /// Installation/processing is in progress by a core worker.\n Installing(PathBuf), // Path is still relevant\n /// Job completed successfully.\n Succeeded,\n /// Job failed. The String contains the error message. Arc for cheap cloning.\n Failed(Arc),\n}\n\n/// Outcome of a download attempt, sent from DownloadCoordinator to the main runner loop.\n#[derive(Debug)] // Clone not strictly needed if moved\npub struct DownloadOutcome {\n pub planned_job: PlannedJob, // The job this download was for\n pub result: Result, // Path to downloaded file or error\n}\n\n/// Structure returned by the planner, now including the ResolvedGraph.\n#[derive(Debug, Default)]\npub struct PlannedOperations {\n pub jobs: Vec, // Topologically sorted for formulae\n pub errors: Vec<(String, SpsError)>, // Errors from planning phase\n pub already_installed_or_up_to_date: std::collections::HashSet,\n pub resolved_graph: Option>, // Graph for dependency checking in runner\n}\n"], ["/sps/sps/src/pipeline/planner.rs", "// sps/src/pipeline/planner.rs\nuse std::collections::{HashMap, HashSet, VecDeque};\nuse std::path::{Path, PathBuf};\nuse std::sync::Arc;\n\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::dependency::resolver::{\n DependencyResolver, NodeInstallStrategy, PerTargetInstallPreferences, ResolutionContext,\n ResolutionStatus, ResolvedGraph,\n};\nuse sps_common::error::{Result as SpsResult, SpsError};\nuse sps_common::formulary::Formulary;\nuse sps_common::keg::KegRegistry;\nuse sps_common::model::{Cask, Formula, InstallTargetIdentifier};\nuse sps_common::pipeline::{JobAction, PipelineEvent, PlannedJob, PlannedOperations};\nuse sps_core::check::installed::{self, InstalledPackageInfo, PackageType as CorePackageType};\nuse sps_core::check::update::{self, UpdateInfo};\nuse tokio::sync::broadcast;\nuse tokio::task::JoinSet;\nuse tracing::{debug, error as trace_error, instrument, warn};\n\nuse super::runner::{get_panic_message, CommandType, PipelineFlags};\n\npub(crate) type PlanResult = SpsResult;\n\n#[derive(Debug, Default)]\nstruct IntermediatePlan {\n initial_ops: HashMap)>,\n errors: Vec<(String, SpsError)>,\n already_satisfied: HashSet,\n processed_globally: HashSet,\n private_store_sources: HashMap,\n}\n\n#[instrument(skip(cache))]\npub(crate) async fn fetch_target_definitions(\n names: &[String],\n cache: Arc,\n) -> HashMap> {\n let mut results = HashMap::new();\n if names.is_empty() {\n return results;\n }\n let mut futures = JoinSet::new();\n\n let formulae_map_handle = tokio::spawn(load_or_fetch_formulae_map(cache.clone()));\n let casks_map_handle = tokio::spawn(load_or_fetch_casks_map(cache.clone()));\n\n let formulae_map = match formulae_map_handle.await {\n Ok(Ok(map)) => Some(map),\n Ok(Err(e)) => {\n debug!(\"[FetchDefs] Failed to load/fetch full formulae list: {}\", e);\n None\n }\n Err(e) => {\n warn!(\n \"[FetchDefs] Formulae map loading task panicked: {}\",\n get_panic_message(e.into_panic()) // Ensure get_panic_message is accessible\n );\n None\n }\n };\n let casks_map = match casks_map_handle.await {\n Ok(Ok(map)) => Some(map),\n Ok(Err(e)) => {\n debug!(\"[FetchDefs] Failed to load/fetch full casks list: {}\", e);\n None\n }\n Err(e) => {\n warn!(\n \"[FetchDefs] Casks map loading task panicked: {}\",\n get_panic_message(e.into_panic()) // Ensure get_panic_message is accessible\n );\n None\n }\n };\n\n for name_str in names {\n let name_owned = name_str.to_string();\n let local_formulae_map = formulae_map.clone();\n let local_casks_map = casks_map.clone();\n\n futures.spawn(async move {\n if let Some(ref map) = local_formulae_map {\n if let Some(f_arc) = map.get(&name_owned) {\n return (name_owned, Ok(InstallTargetIdentifier::Formula(f_arc.clone())));\n }\n }\n if let Some(ref map) = local_casks_map {\n if let Some(c_arc) = map.get(&name_owned) {\n return (name_owned, Ok(InstallTargetIdentifier::Cask(c_arc.clone())));\n }\n }\n debug!(\"[FetchDefs] Definition for '{}' not found in cached lists, fetching directly from API...\", name_owned);\n match sps_net::api::get_formula(&name_owned).await {\n Ok(formula_obj) => return (name_owned, Ok(InstallTargetIdentifier::Formula(Arc::new(formula_obj)))),\n Err(SpsError::NotFound(_)) => {}\n Err(e) => return (name_owned, Err(e)),\n }\n match sps_net::api::get_cask(&name_owned).await {\n Ok(cask_obj) => (name_owned, Ok(InstallTargetIdentifier::Cask(Arc::new(cask_obj)))),\n Err(SpsError::NotFound(_)) => (name_owned.clone(), Err(SpsError::NotFound(format!(\"Formula or Cask '{name_owned}' not found\")))),\n Err(e) => (name_owned, Err(e)),\n }\n });\n }\n\n while let Some(res) = futures.join_next().await {\n match res {\n Ok((name, result)) => {\n results.insert(name, result);\n }\n Err(e) => {\n let panic_message = get_panic_message(e.into_panic());\n trace_error!(\n \"[FetchDefs] Task panicked during definition fetch: {}\",\n panic_message\n );\n results.insert(\n format!(\"[unknown_target_due_to_panic_{}]\", results.len()),\n Err(SpsError::Generic(format!(\n \"Definition fetching task panicked: {panic_message}\"\n ))),\n );\n }\n }\n }\n results\n}\n\nasync fn load_or_fetch_formulae_map(cache: Arc) -> SpsResult>> {\n match cache.load_raw(\"formula.json\") {\n Ok(data) => {\n let formulas: Vec = serde_json::from_str(&data)\n .map_err(|e| SpsError::Cache(format!(\"Parse cached formula.json failed: {e}\")))?;\n Ok(formulas\n .into_iter()\n .map(|f| (f.name.clone(), Arc::new(f)))\n .collect())\n }\n Err(_) => {\n debug!(\"[FetchDefs] Cache miss for formula.json, fetching from API...\");\n let raw_data = sps_net::api::fetch_all_formulas().await?;\n if let Err(e) = cache.store_raw(\"formula.json\", &raw_data) {\n warn!(\"Failed to store formula.json in cache: {}\", e);\n }\n let formulas: Vec =\n serde_json::from_str(&raw_data).map_err(|e| SpsError::Json(Arc::new(e)))?;\n Ok(formulas\n .into_iter()\n .map(|f| (f.name.clone(), Arc::new(f)))\n .collect())\n }\n }\n}\n\nasync fn load_or_fetch_casks_map(cache: Arc) -> SpsResult>> {\n match cache.load_raw(\"cask.json\") {\n Ok(data) => {\n let casks: Vec = serde_json::from_str(&data)\n .map_err(|e| SpsError::Cache(format!(\"Parse cached cask.json failed: {e}\")))?;\n Ok(casks\n .into_iter()\n .map(|c| (c.token.clone(), Arc::new(c)))\n .collect())\n }\n Err(_) => {\n debug!(\"[FetchDefs] Cache miss for cask.json, fetching from API...\");\n let raw_data = sps_net::api::fetch_all_casks().await?;\n if let Err(e) = cache.store_raw(\"cask.json\", &raw_data) {\n warn!(\"Failed to store cask.json in cache: {}\", e);\n }\n let casks: Vec =\n serde_json::from_str(&raw_data).map_err(|e| SpsError::Json(Arc::new(e)))?;\n Ok(casks\n .into_iter()\n .map(|c| (c.token.clone(), Arc::new(c)))\n .collect())\n }\n }\n}\n\npub(crate) struct OperationPlanner<'a> {\n config: &'a Config,\n cache: Arc,\n flags: &'a PipelineFlags,\n event_tx: broadcast::Sender,\n}\n\nimpl<'a> OperationPlanner<'a> {\n pub fn new(\n config: &'a Config,\n cache: Arc,\n flags: &'a PipelineFlags,\n event_tx: broadcast::Sender,\n ) -> Self {\n Self {\n config,\n cache,\n flags,\n event_tx,\n }\n }\n\n fn get_previous_installation_type(&self, old_keg_path: &Path) -> Option {\n let receipt_path = old_keg_path.join(\"INSTALL_RECEIPT.json\");\n if !receipt_path.is_file() {\n tracing::debug!(\n \"No INSTALL_RECEIPT.json found at {} for previous version.\",\n receipt_path.display()\n );\n return None;\n }\n\n match std::fs::read_to_string(&receipt_path) {\n Ok(content) => match serde_json::from_str::(&content) {\n Ok(json_value) => {\n let inst_type = json_value\n .get(\"installation_type\")\n .and_then(|it| it.as_str())\n .map(String::from);\n tracing::debug!(\n \"Previous installation type for {}: {:?}\",\n old_keg_path.display(),\n inst_type\n );\n inst_type\n }\n Err(e) => {\n tracing::warn!(\"Failed to parse INSTALL_RECEIPT.json at {}: {}. Cannot determine previous installation type.\", receipt_path.display(), e);\n None\n }\n },\n Err(e) => {\n tracing::warn!(\"Failed to read INSTALL_RECEIPT.json at {}: {}. Cannot determine previous installation type.\", receipt_path.display(), e);\n None\n }\n }\n }\n\n async fn check_installed_status(&self, name: &str) -> PlanResult> {\n installed::get_installed_package(name, self.config).await\n }\n\n async fn determine_cask_private_store_source(\n &self,\n name: &str,\n version_for_path: &str,\n ) -> Option {\n let cask_def_res = fetch_target_definitions(&[name.to_string()], self.cache.clone())\n .await\n .remove(name);\n\n if let Some(Ok(InstallTargetIdentifier::Cask(cask_arc))) = cask_def_res {\n if let Some(artifacts) = &cask_arc.artifacts {\n for artifact_entry in artifacts {\n if let Some(app_array) = artifact_entry.get(\"app\").and_then(|v| v.as_array()) {\n if let Some(app_name_val) = app_array.first() {\n if let Some(app_name_str) = app_name_val.as_str() {\n let private_path = self.config.cask_store_app_path(\n name,\n version_for_path,\n app_name_str,\n );\n if private_path.exists() && private_path.is_dir() {\n debug!(\"[Planner] Found reusable Cask private store bundle for {} version {}: {}\", name, version_for_path, private_path.display());\n return Some(private_path);\n }\n }\n }\n break;\n }\n }\n }\n }\n None\n }\n\n async fn plan_for_install(&self, targets: &[String]) -> PlanResult {\n let mut plan = IntermediatePlan::default();\n for name in targets {\n if plan.processed_globally.contains(name) {\n continue;\n }\n match self.check_installed_status(name).await {\n Ok(Some(installed_info)) => {\n let mut proceed_with_install = false;\n if installed_info.pkg_type == CorePackageType::Cask {\n let manifest_path = installed_info.path.join(\"CASK_INSTALL_MANIFEST.json\");\n if manifest_path.is_file() {\n if let Ok(manifest_str) = std::fs::read_to_string(&manifest_path) {\n if let Ok(manifest_json) =\n serde_json::from_str::(&manifest_str)\n {\n if let Some(is_installed_flag) =\n manifest_json.get(\"is_installed\").and_then(|v| v.as_bool())\n {\n if !is_installed_flag {\n debug!(\"Cask '{}' found but marked as not installed in manifest. Proceeding with install.\", name);\n proceed_with_install = true;\n }\n }\n }\n }\n } else {\n debug!(\n \"Cask '{}' found but manifest missing. Assuming needs install.\",\n name\n );\n proceed_with_install = true;\n }\n }\n if proceed_with_install {\n if let Some(private_path) = self\n .determine_cask_private_store_source(name, &installed_info.version)\n .await\n {\n plan.private_store_sources\n .insert(name.clone(), private_path);\n }\n plan.initial_ops\n .insert(name.clone(), (JobAction::Install, None));\n } else {\n debug!(\"Target '{}' already installed and manifest indicates it. Marking as satisfied.\", name);\n plan.already_satisfied.insert(name.clone());\n plan.processed_globally.insert(name.clone());\n }\n }\n Ok(None) => {\n if let Some(private_path) = self\n .determine_cask_private_store_source(name, \"latest\")\n .await\n {\n plan.private_store_sources\n .insert(name.clone(), private_path);\n }\n plan.initial_ops\n .insert(name.clone(), (JobAction::Install, None));\n }\n Err(e) => {\n plan.errors.push((\n name.clone(),\n SpsError::Generic(format!(\n \"Failed to check installed status for {name}: {e}\"\n )),\n ));\n plan.processed_globally.insert(name.clone());\n }\n }\n }\n Ok(plan)\n }\n\n async fn plan_for_reinstall(&self, targets: &[String]) -> PlanResult {\n let mut plan = IntermediatePlan::default();\n for name in targets {\n if plan.processed_globally.contains(name) {\n continue;\n }\n match self.check_installed_status(name).await {\n Ok(Some(installed_info)) => {\n if installed_info.pkg_type == CorePackageType::Cask {\n if let Some(private_path) = self\n .determine_cask_private_store_source(name, &installed_info.version)\n .await\n {\n plan.private_store_sources\n .insert(name.clone(), private_path);\n }\n }\n plan.initial_ops.insert(\n name.clone(),\n (\n JobAction::Reinstall {\n version: installed_info.version.clone(),\n current_install_path: installed_info.path.clone(),\n },\n None,\n ),\n );\n }\n Ok(None) => {\n plan.errors.push((\n name.clone(),\n SpsError::NotFound(format!(\"Cannot reinstall '{name}': not installed.\")),\n ));\n plan.processed_globally.insert(name.clone());\n }\n Err(e) => {\n plan.errors.push((\n name.clone(),\n SpsError::Generic(format!(\"Failed to check status for '{name}': {e}\")),\n ));\n plan.processed_globally.insert(name.clone());\n }\n }\n }\n Ok(plan)\n }\n\n async fn plan_for_upgrade(\n &self,\n targets: &[String],\n all: bool,\n ) -> PlanResult {\n let mut plan = IntermediatePlan::default();\n let packages_to_check = if all {\n installed::get_installed_packages(self.config)\n .await\n .map_err(|e| {\n plan.errors.push((\n \"\".to_string(),\n SpsError::Generic(format!(\"Failed to get installed packages: {e}\")),\n ));\n e\n })?\n } else {\n let mut specific = Vec::new();\n for name in targets {\n match self.check_installed_status(name).await {\n Ok(Some(info)) => {\n if info.pkg_type == CorePackageType::Cask {\n let manifest_path = info.path.join(\"CASK_INSTALL_MANIFEST.json\");\n if manifest_path.is_file() {\n if let Ok(manifest_str) = std::fs::read_to_string(&manifest_path) {\n if let Ok(manifest_json) =\n serde_json::from_str::(&manifest_str)\n {\n if !manifest_json\n .get(\"is_installed\")\n .and_then(|v| v.as_bool())\n .unwrap_or(true)\n {\n debug!(\"Skipping upgrade for Cask '{}' as its manifest indicates it's not fully installed.\", name);\n plan.processed_globally.insert(name.clone());\n continue;\n }\n }\n }\n }\n }\n specific.push(info);\n }\n Ok(None) => {\n plan.errors.push((\n name.to_string(),\n SpsError::NotFound(format!(\"Cannot upgrade '{name}': not installed.\")),\n ));\n plan.processed_globally.insert(name.clone());\n }\n Err(e) => {\n plan.errors.push((\n name.to_string(),\n SpsError::Generic(format!(\"Failed to check status for '{name}': {e}\")),\n ));\n plan.processed_globally.insert(name.clone());\n }\n }\n }\n specific\n };\n\n if packages_to_check.is_empty() {\n return Ok(plan);\n }\n\n match update::check_for_updates(&packages_to_check, &self.cache, self.config).await {\n Ok(updates) => {\n let update_map: HashMap =\n updates.into_iter().map(|u| (u.name.clone(), u)).collect();\n\n debug!(\n \"[Planner] Found {} available updates out of {} packages checked\",\n update_map.len(),\n packages_to_check.len()\n );\n debug!(\n \"[Planner] Available updates: {:?}\",\n update_map.keys().collect::>()\n );\n\n for p_info in packages_to_check {\n if plan.processed_globally.contains(&p_info.name) {\n continue;\n }\n if let Some(ui) = update_map.get(&p_info.name) {\n debug!(\n \"[Planner] Adding upgrade job for '{}': {} -> {}\",\n p_info.name, p_info.version, ui.available_version\n );\n plan.initial_ops.insert(\n p_info.name.clone(),\n (\n JobAction::Upgrade {\n from_version: p_info.version.clone(),\n old_install_path: p_info.path.clone(),\n },\n Some(ui.target_definition.clone()),\n ),\n );\n // Don't mark packages with updates as processed_globally\n // so they can be included in the final job list\n } else {\n debug!(\n \"[Planner] No update available for '{}', marking as already satisfied\",\n p_info.name\n );\n plan.already_satisfied.insert(p_info.name.clone());\n // Only mark packages without updates as processed_globally\n plan.processed_globally.insert(p_info.name.clone());\n }\n }\n }\n Err(e) => {\n plan.errors.push((\n \"[Update Check]\".to_string(),\n SpsError::Generic(format!(\"Failed to check for updates: {e}\")),\n ));\n }\n }\n Ok(plan)\n }\n\n // This now returns sps_common::pipeline::PlannedOperations\n pub async fn plan_operations(\n &self,\n initial_targets: &[String],\n command_type: CommandType,\n ) -> PlanResult {\n debug!(\n \"[Planner] Starting plan_operations with command_type: {:?}, targets: {:?}\",\n command_type, initial_targets\n );\n\n let mut intermediate_plan = match command_type {\n CommandType::Install => self.plan_for_install(initial_targets).await?,\n CommandType::Reinstall => self.plan_for_reinstall(initial_targets).await?,\n CommandType::Upgrade { all } => {\n debug!(\"[Planner] Calling plan_for_upgrade with all={}\", all);\n let plan = self.plan_for_upgrade(initial_targets, all).await?;\n debug!(\"[Planner] plan_for_upgrade returned with {} initial_ops, {} errors, {} already_satisfied\",\n plan.initial_ops.len(), plan.errors.len(), plan.already_satisfied.len());\n debug!(\n \"[Planner] Initial ops: {:?}\",\n plan.initial_ops.keys().collect::>()\n );\n debug!(\"[Planner] Already satisfied: {:?}\", plan.already_satisfied);\n plan\n }\n };\n\n let definitions_to_fetch: Vec = intermediate_plan\n .initial_ops\n .iter()\n .filter(|(name, (_, opt_def))| {\n opt_def.is_none() && !intermediate_plan.processed_globally.contains(*name)\n })\n .map(|(name, _)| name.clone())\n .collect();\n\n if !definitions_to_fetch.is_empty() {\n let fetched_defs =\n fetch_target_definitions(&definitions_to_fetch, self.cache.clone()).await;\n for (name, result) in fetched_defs {\n match result {\n Ok(target_def) => {\n if let Some((_action, opt_install_target)) =\n intermediate_plan.initial_ops.get_mut(&name)\n {\n *opt_install_target = Some(target_def);\n }\n }\n Err(e) => {\n intermediate_plan.errors.push((\n name.clone(),\n SpsError::Generic(format!(\"Failed to get definition for target: {e}\")),\n ));\n intermediate_plan.processed_globally.insert(name);\n }\n }\n }\n }\n self.event_tx\n .send(PipelineEvent::DependencyResolutionStarted)\n .ok();\n\n let mut formulae_for_resolution: HashMap = HashMap::new();\n let mut cask_deps_map: HashMap> = HashMap::new();\n let mut cask_processing_queue: VecDeque = VecDeque::new();\n\n for (name, (action, opt_def)) in &intermediate_plan.initial_ops {\n if intermediate_plan.processed_globally.contains(name) {\n continue;\n }\n\n // Handle both normal formula targets and upgrade targets\n match opt_def {\n Some(target @ InstallTargetIdentifier::Formula(_)) => {\n debug!(\n \"[Planner] Adding formula '{}' to resolution list with action {:?}\",\n name, action\n );\n formulae_for_resolution.insert(name.clone(), target.clone());\n }\n Some(InstallTargetIdentifier::Cask(c_arc)) => {\n debug!(\"[Planner] Adding cask '{}' to processing queue\", name);\n cask_processing_queue.push_back(name.clone());\n cask_deps_map.insert(name.clone(), c_arc.clone());\n }\n None => {\n if !intermediate_plan\n .errors\n .iter()\n .any(|(err_name, _)| err_name == name)\n {\n intermediate_plan.errors.push((\n name.clone(),\n SpsError::Generic(format!(\n \"Definition for '{name}' still missing after fetch attempt.\"\n )),\n ));\n intermediate_plan.processed_globally.insert(name.clone());\n }\n }\n }\n }\n\n let mut processed_casks_for_deps_pass: HashSet =\n intermediate_plan.processed_globally.clone();\n\n while let Some(cask_token) = cask_processing_queue.pop_front() {\n if processed_casks_for_deps_pass.contains(&cask_token) {\n continue;\n }\n processed_casks_for_deps_pass.insert(cask_token.clone());\n\n let cask_arc = match cask_deps_map.get(&cask_token) {\n Some(c) => c.clone(),\n None => {\n match fetch_target_definitions(\n std::slice::from_ref(&cask_token),\n self.cache.clone(),\n )\n .await\n .remove(&cask_token)\n {\n Some(Ok(InstallTargetIdentifier::Cask(c))) => {\n cask_deps_map.insert(cask_token.clone(), c.clone());\n c\n }\n Some(Err(e)) => {\n intermediate_plan.errors.push((cask_token.clone(), e));\n intermediate_plan\n .processed_globally\n .insert(cask_token.clone());\n continue;\n }\n _ => {\n intermediate_plan.errors.push((\n cask_token.clone(),\n SpsError::NotFound(format!(\n \"Cask definition for dependency '{cask_token}' not found.\"\n )),\n ));\n intermediate_plan\n .processed_globally\n .insert(cask_token.clone());\n continue;\n }\n }\n }\n };\n\n if let Some(deps) = &cask_arc.depends_on {\n for formula_dep_name in &deps.formula {\n if formulae_for_resolution.contains_key(formula_dep_name)\n || intermediate_plan\n .errors\n .iter()\n .any(|(n, _)| n == formula_dep_name)\n || intermediate_plan\n .already_satisfied\n .contains(formula_dep_name)\n {\n continue;\n }\n match fetch_target_definitions(\n std::slice::from_ref(formula_dep_name),\n self.cache.clone(),\n )\n .await\n .remove(formula_dep_name)\n {\n Some(Ok(target_def @ InstallTargetIdentifier::Formula(_))) => {\n formulae_for_resolution.insert(formula_dep_name.clone(), target_def);\n }\n Some(Ok(InstallTargetIdentifier::Cask(_))) => {\n intermediate_plan.errors.push((\n formula_dep_name.clone(),\n SpsError::Generic(format!(\n \"Dependency '{formula_dep_name}' of Cask '{cask_token}' is unexpectedly a Cask itself.\"\n )),\n ));\n intermediate_plan\n .processed_globally\n .insert(formula_dep_name.clone());\n }\n Some(Err(e)) => {\n intermediate_plan.errors.push((\n formula_dep_name.clone(),\n SpsError::Generic(format!(\n \"Failed def fetch for formula dep '{formula_dep_name}' of cask '{cask_token}': {e}\"\n )),\n ));\n intermediate_plan\n .processed_globally\n .insert(formula_dep_name.clone());\n }\n None => {\n intermediate_plan.errors.push((\n formula_dep_name.clone(),\n SpsError::NotFound(format!(\n \"Formula dep '{formula_dep_name}' for cask '{cask_token}' not found.\"\n )),\n ));\n intermediate_plan\n .processed_globally\n .insert(formula_dep_name.clone());\n }\n }\n }\n for dep_cask_token in &deps.cask {\n if !processed_casks_for_deps_pass.contains(dep_cask_token)\n && !cask_processing_queue.contains(dep_cask_token)\n {\n cask_processing_queue.push_back(dep_cask_token.clone());\n }\n }\n }\n }\n\n let mut resolved_formula_graph_opt: Option> = None;\n if !formulae_for_resolution.is_empty() {\n let targets_for_resolver: Vec<_> = formulae_for_resolution.keys().cloned().collect();\n let formulary = Formulary::new(self.config.clone());\n let keg_registry = KegRegistry::new(self.config.clone());\n\n let per_target_prefs = PerTargetInstallPreferences {\n force_source_build_targets: if self.flags.build_from_source {\n targets_for_resolver.iter().cloned().collect()\n } else {\n HashSet::new()\n },\n force_bottle_only_targets: HashSet::new(),\n };\n\n // Create map of initial target actions for the resolver\n let initial_target_actions: HashMap = intermediate_plan\n .initial_ops\n .iter()\n .filter_map(|(name, (action, _))| {\n if targets_for_resolver.contains(name) {\n Some((name.clone(), action.clone()))\n } else {\n debug!(\"[Planner] WARNING: Target '{}' with action {:?} is not in targets_for_resolver!\", name, action);\n None\n }\n })\n .collect();\n\n debug!(\n \"[Planner] Created initial_target_actions map with {} entries: {:?}\",\n initial_target_actions.len(),\n initial_target_actions\n );\n debug!(\"[Planner] Targets for resolver: {:?}\", targets_for_resolver);\n\n let ctx = ResolutionContext {\n formulary: &formulary,\n keg_registry: &keg_registry,\n sps_prefix: self.config.sps_root(),\n include_optional: self.flags.include_optional,\n include_test: false,\n skip_recommended: self.flags.skip_recommended,\n initial_target_preferences: &per_target_prefs,\n build_all_from_source: self.flags.build_from_source,\n cascade_source_preference_to_dependencies: true,\n has_bottle_for_current_platform:\n sps_core::install::bottle::has_bottle_for_current_platform,\n initial_target_actions: &initial_target_actions,\n };\n\n let mut resolver = DependencyResolver::new(ctx);\n debug!(\"[Planner] Created DependencyResolver, calling resolve_targets...\");\n match resolver.resolve_targets(&targets_for_resolver) {\n Ok(g) => {\n debug!(\n \"[Planner] Dependency resolution succeeded! Install plan has {} items\",\n g.install_plan.len()\n );\n resolved_formula_graph_opt = Some(Arc::new(g));\n }\n Err(e) => {\n debug!(\"[Planner] Dependency resolution failed: {}\", e);\n let resolver_error_msg = e.to_string(); // Capture full error\n for n in targets_for_resolver {\n if !intermediate_plan\n .errors\n .iter()\n .any(|(err_n, _)| err_n == &n)\n {\n intermediate_plan.errors.push((\n n.clone(),\n SpsError::DependencyError(resolver_error_msg.clone()),\n ));\n }\n intermediate_plan.processed_globally.insert(n);\n }\n }\n }\n }\n self.event_tx\n .send(PipelineEvent::DependencyResolutionFinished)\n .ok();\n\n let mut final_planned_jobs: Vec = Vec::new();\n let mut names_processed_from_initial_ops = HashSet::new();\n\n debug!(\n \"[Planner] Processing {} initial_ops into final jobs\",\n intermediate_plan.initial_ops.len()\n );\n for (name, (action, opt_def)) in &intermediate_plan.initial_ops {\n debug!(\n \"[Planner] Processing initial op '{}': action={:?}, has_def={}\",\n name,\n action,\n opt_def.is_some()\n );\n\n if intermediate_plan.processed_globally.contains(name) {\n debug!(\"[Planner] Skipping '{}' - already processed globally\", name);\n continue;\n }\n // If an error was recorded for this specific initial target (e.g. resolver failed for\n // it, or def missing) ensure it's marked as globally processed and not\n // added to final_planned_jobs.\n if intermediate_plan\n .errors\n .iter()\n .any(|(err_name, _)| err_name == name)\n {\n debug!(\"[Planner] Skipping job for initial op '{}' as an error was recorded for it during planning.\", name);\n intermediate_plan.processed_globally.insert(name.clone());\n continue;\n }\n if intermediate_plan.already_satisfied.contains(name) {\n debug!(\n \"[Planner] Skipping job for initial op '{}' as it's already satisfied.\",\n name\n );\n intermediate_plan.processed_globally.insert(name.clone());\n continue;\n }\n\n match opt_def {\n Some(target_def) => {\n let is_source_build = determine_build_strategy_for_job(\n target_def,\n action,\n self.flags,\n resolved_formula_graph_opt.as_deref(),\n self,\n );\n\n final_planned_jobs.push(PlannedJob {\n target_id: name.clone(),\n target_definition: target_def.clone(),\n action: action.clone(),\n is_source_build,\n use_private_store_source: intermediate_plan\n .private_store_sources\n .get(name)\n .cloned(),\n });\n names_processed_from_initial_ops.insert(name.clone());\n }\n None => {\n tracing::error!(\"[Planner] CRITICAL: Definition missing for planned operation on '{}' but no error was recorded in intermediate_plan.errors. This should not happen.\", name);\n if !intermediate_plan\n .errors\n .iter()\n .any(|(err_n, _)| err_n == name)\n {\n intermediate_plan.errors.push((\n name.clone(),\n SpsError::Generic(\"Definition missing unexpectedly.\".into()),\n ));\n }\n intermediate_plan.processed_globally.insert(name.clone());\n }\n }\n }\n\n if let Some(graph) = resolved_formula_graph_opt.as_ref() {\n for dep_detail in &graph.install_plan {\n let dep_name = dep_detail.formula.name();\n\n if names_processed_from_initial_ops.contains(dep_name)\n || intermediate_plan.processed_globally.contains(dep_name)\n || final_planned_jobs.iter().any(|j| j.target_id == dep_name)\n {\n continue;\n }\n\n if intermediate_plan\n .errors\n .iter()\n .any(|(err_name, _)| err_name == dep_name)\n {\n tracing::debug!(\"[Planner] Skipping job for dependency '{}' due to a pre-existing error recorded for it.\", dep_name);\n intermediate_plan\n .processed_globally\n .insert(dep_name.to_string());\n continue;\n }\n if dep_detail.status == ResolutionStatus::Failed {\n tracing::debug!(\"[Planner] Skipping job for dependency '{}' as its resolution status is Failed. Adding to planner errors.\", dep_name);\n // Ensure this error is also captured if not already.\n if !intermediate_plan\n .errors\n .iter()\n .any(|(err_name, _)| err_name == dep_name)\n {\n intermediate_plan.errors.push((\n dep_name.to_string(),\n SpsError::DependencyError(format!(\n \"Resolution failed for dependency {dep_name}\"\n )),\n ));\n }\n intermediate_plan\n .processed_globally\n .insert(dep_name.to_string());\n continue;\n }\n\n if matches!(\n dep_detail.status,\n ResolutionStatus::Missing | ResolutionStatus::Requested\n ) {\n let is_source_build_for_dep = determine_build_strategy_for_job(\n &InstallTargetIdentifier::Formula(dep_detail.formula.clone()),\n &JobAction::Install,\n self.flags,\n Some(graph),\n self,\n );\n debug!(\n \"Planning install for new formula dependency '{}'. Source build: {}\",\n dep_name, is_source_build_for_dep\n );\n\n final_planned_jobs.push(PlannedJob {\n target_id: dep_name.to_string(),\n target_definition: InstallTargetIdentifier::Formula(\n dep_detail.formula.clone(),\n ),\n action: JobAction::Install,\n is_source_build: is_source_build_for_dep,\n use_private_store_source: None,\n });\n } else if dep_detail.status == ResolutionStatus::Installed {\n intermediate_plan\n .already_satisfied\n .insert(dep_name.to_string());\n }\n }\n }\n\n for (cask_token, cask_arc) in cask_deps_map {\n if names_processed_from_initial_ops.contains(&cask_token)\n || intermediate_plan.processed_globally.contains(&cask_token)\n || final_planned_jobs.iter().any(|j| j.target_id == cask_token)\n {\n continue;\n }\n\n match self.check_installed_status(&cask_token).await {\n Ok(None) => {\n final_planned_jobs.push(PlannedJob {\n target_id: cask_token.clone(),\n target_definition: InstallTargetIdentifier::Cask(cask_arc.clone()),\n action: JobAction::Install,\n is_source_build: false,\n use_private_store_source: intermediate_plan\n .private_store_sources\n .get(&cask_token)\n .cloned(),\n });\n }\n Ok(Some(_installed_info)) => {\n intermediate_plan\n .already_satisfied\n .insert(cask_token.clone());\n }\n Err(e) => {\n intermediate_plan.errors.push((\n cask_token.clone(),\n SpsError::Generic(format!(\n \"Failed check install status for cask dependency {cask_token}: {e}\"\n )),\n ));\n intermediate_plan\n .processed_globally\n .insert(cask_token.clone());\n }\n }\n }\n if let Some(graph) = resolved_formula_graph_opt.as_ref() {\n if !final_planned_jobs.is_empty() {\n sort_planned_jobs(&mut final_planned_jobs, graph);\n }\n }\n\n debug!(\n \"[Planner] Finishing plan_operations with {} jobs, {} errors, {} already_satisfied\",\n final_planned_jobs.len(),\n intermediate_plan.errors.len(),\n intermediate_plan.already_satisfied.len()\n );\n debug!(\n \"[Planner] Final jobs: {:?}\",\n final_planned_jobs\n .iter()\n .map(|j| &j.target_id)\n .collect::>()\n );\n\n Ok(PlannedOperations {\n jobs: final_planned_jobs,\n errors: intermediate_plan.errors,\n already_installed_or_up_to_date: intermediate_plan.already_satisfied,\n resolved_graph: resolved_formula_graph_opt,\n })\n }\n}\n\nfn determine_build_strategy_for_job(\n target_def: &InstallTargetIdentifier,\n action: &JobAction,\n flags: &PipelineFlags,\n resolved_graph: Option<&ResolvedGraph>,\n planner: &OperationPlanner,\n) -> bool {\n match target_def {\n InstallTargetIdentifier::Formula(formula_arc) => {\n if flags.build_from_source {\n return true;\n }\n if let Some(graph) = resolved_graph {\n if let Some(resolved_detail) = graph.resolution_details.get(formula_arc.name()) {\n match resolved_detail.determined_install_strategy {\n NodeInstallStrategy::SourceOnly => return true,\n NodeInstallStrategy::BottleOrFail => return false,\n NodeInstallStrategy::BottlePreferred => {}\n }\n }\n }\n if let JobAction::Upgrade {\n old_install_path, ..\n } = action\n {\n if planner\n .get_previous_installation_type(old_install_path)\n .as_deref()\n == Some(\"source\")\n {\n return true;\n }\n }\n !sps_core::install::bottle::has_bottle_for_current_platform(formula_arc)\n }\n InstallTargetIdentifier::Cask(_) => false,\n }\n}\n\nfn sort_planned_jobs(jobs: &mut [PlannedJob], formula_graph: &ResolvedGraph) {\n let formula_order: HashMap = formula_graph\n .install_plan\n .iter()\n .enumerate()\n .map(|(idx, dep_detail)| (dep_detail.formula.name().to_string(), idx))\n .collect();\n\n jobs.sort_by_key(|job| match &job.target_definition {\n InstallTargetIdentifier::Formula(f_arc) => formula_order\n .get(f_arc.name())\n .copied()\n .unwrap_or(usize::MAX),\n InstallTargetIdentifier::Cask(_) => usize::MAX - 1,\n });\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/app.rs", "// In sps-core/src/build/cask/app.rs\n\nuse std::fs;\nuse std::path::{Path, PathBuf};\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::{debug, error, warn};\n\n#[cfg(target_os = \"macos\")]\n/// Finds the primary .app bundle in a directory. Returns an error if none or ambiguous.\n/// If multiple .app bundles are found, returns the first and logs a warning.\npub fn find_primary_app_bundle_in_dir(dir: &Path) -> Result {\n if !dir.is_dir() {\n return Err(SpsError::NotFound(format!(\n \"Directory {} not found for app bundle scan.\",\n dir.display()\n )));\n }\n let mut app_bundles = Vec::new();\n for entry_res in fs::read_dir(dir)? {\n let entry = entry_res?;\n let path = entry.path();\n if path.is_dir() && path.extension().is_some_and(|ext| ext == \"app\") {\n app_bundles.push(path);\n }\n }\n if app_bundles.is_empty() {\n Err(SpsError::NotFound(format!(\n \"No .app bundle found in {}\",\n dir.display()\n )))\n } else if app_bundles.len() == 1 {\n Ok(app_bundles.remove(0))\n } else {\n // Heuristic: return the largest .app bundle if multiple are found, or one matching a common\n // pattern. For now, error if multiple are present to force explicit handling in\n // Cask definitions if needed.\n warn!(\"Multiple .app bundles found in {}: {:?}. Returning the first one, but this might be ambiguous.\", dir.display(), app_bundles);\n Ok(app_bundles.remove(0)) // Or error out\n }\n}\n\nuse sps_common::pipeline::JobAction;\n\npub fn install_app_from_staged(\n cask: &Cask,\n staged_app_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n job_action: &JobAction,\n) -> Result> {\n if !staged_app_path.exists() || !staged_app_path.is_dir() {\n return Err(SpsError::NotFound(format!(\n \"Staged app bundle for {} not found or is not a directory: {}\",\n cask.token,\n staged_app_path.display()\n )));\n }\n\n let app_name = staged_app_path\n .file_name()\n .ok_or_else(|| {\n SpsError::Generic(format!(\n \"Invalid staged app path (no filename): {}\",\n staged_app_path.display()\n ))\n })?\n .to_string_lossy();\n\n let new_version_str = cask.version.clone().unwrap_or_else(|| \"latest\".to_string());\n let final_private_store_app_path: PathBuf;\n\n // Determine if we are upgrading and if the old private store app path exists\n let mut did_upgrade = false;\n\n if let JobAction::Upgrade {\n from_version,\n old_install_path,\n ..\n } = job_action\n {\n debug!(\n \"[{}] Processing app install as UPGRADE from version {}\",\n cask.token, from_version\n );\n\n // Try to get primary_app_file_name from the old manifest to build the old private store\n // path\n let old_manifest_path = old_install_path.join(\"CASK_INSTALL_MANIFEST.json\");\n let old_primary_app_name = if old_manifest_path.is_file() {\n fs::read_to_string(&old_manifest_path)\n .ok()\n .and_then(|s| {\n serde_json::from_str::(&s).ok()\n })\n .and_then(|m| m.primary_app_file_name)\n } else {\n // Fallback if old manifest is missing, use current app_name (less reliable if app name\n // changed)\n warn!(\"[{}] Old manifest not found at {} during upgrade. Using current app name '{}' for private store path derivation.\", cask.token, old_manifest_path.display(), app_name);\n Some(app_name.to_string())\n };\n\n if let Some(name_for_old_path) = old_primary_app_name {\n let old_private_store_app_dir_path =\n config.cask_store_version_path(&cask.token, from_version);\n let old_private_store_app_bundle_path =\n old_private_store_app_dir_path.join(&name_for_old_path);\n if old_private_store_app_bundle_path.exists()\n && old_private_store_app_bundle_path.is_dir()\n {\n debug!(\"[{}] UPGRADE: Old private store app bundle found at {}. Using Homebrew-style overwrite strategy.\", cask.token, old_private_store_app_bundle_path.display());\n\n // ========================================================================\n // CRITICAL: Homebrew-Style App Bundle Replacement Strategy\n // ========================================================================\n // WHY THIS APPROACH:\n // 1. Preserves extended attributes (quarantine, code signing, etc.)\n // 2. Maintains app bundle identity → prevents Gatekeeper reset\n // 3. Avoids breaking symlinks and file system references\n // 4. Ensures user data in ~/Library remains accessible to the app\n //\n // DO NOT CHANGE TO fs::rename() or similar - it breaks Gatekeeper!\n // ========================================================================\n\n // Step 1: Remove the old app bundle from private store\n // (This is safe because we're about to replace it with the new version)\n let rm_status = Command::new(\"rm\")\n .arg(\"-rf\")\n .arg(&old_private_store_app_bundle_path)\n .status()\n .map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n\n if !rm_status.success() {\n return Err(SpsError::InstallError(format!(\n \"Failed to remove old app bundle during upgrade: {}\",\n old_private_store_app_bundle_path.display()\n )));\n }\n\n // Step 2: Copy the new app bundle with ALL attributes preserved\n // The -pR flags are critical:\n // -p: Preserve file attributes, ownership, timestamps\n // -R: Recursive copy for directories\n // This ensures Gatekeeper approval and code signing are maintained\n let cp_status = Command::new(\"cp\")\n .arg(\"-pR\") // CRITICAL: Preserve all attributes, links, and metadata\n .arg(staged_app_path)\n .arg(&old_private_store_app_bundle_path)\n .status()\n .map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n\n if !cp_status.success() {\n return Err(SpsError::InstallError(format!(\n \"Failed to copy new app bundle during upgrade: {} -> {}\",\n staged_app_path.display(),\n old_private_store_app_bundle_path.display()\n )));\n }\n\n debug!(\n \"[{}] UPGRADE: Successfully overwrote old app bundle with new version using cp -pR\",\n cask.token\n );\n\n // Now, rename the parent version directory (e.g., .../1.0 -> .../1.1)\n let new_private_store_version_dir =\n config.cask_store_version_path(&cask.token, &new_version_str);\n if old_private_store_app_dir_path != new_private_store_version_dir {\n debug!(\n \"[{}] Renaming private store version dir from {} to {}\",\n cask.token,\n old_private_store_app_dir_path.display(),\n new_private_store_version_dir.display()\n );\n fs::rename(\n &old_private_store_app_dir_path,\n &new_private_store_version_dir,\n )\n .map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n }\n final_private_store_app_path =\n new_private_store_version_dir.join(app_name.as_ref());\n did_upgrade = true;\n } else {\n warn!(\"[{}] UPGRADE: Old private store app path {} not found or not a dir. Proceeding with fresh private store placement for new version.\", cask.token, old_private_store_app_bundle_path.display());\n // Fallback to fresh placement\n final_private_store_app_path =\n config.cask_store_app_path(&cask.token, &new_version_str, app_name.as_ref());\n }\n } else {\n warn!(\"[{}] UPGRADE: Could not determine old app bundle name. Proceeding with fresh private store placement for new version.\", cask.token);\n final_private_store_app_path =\n config.cask_store_app_path(&cask.token, &new_version_str, app_name.as_ref());\n }\n } else {\n // Not an upgrade\n final_private_store_app_path =\n config.cask_store_app_path(&cask.token, &new_version_str, app_name.as_ref());\n }\n\n let final_app_destination_in_applications = config.applications_dir().join(app_name.as_ref());\n let caskroom_symlink_to_final_app = cask_version_install_path.join(app_name.as_ref());\n\n debug!(\n \"Installing app '{}': Staged -> Private Store -> /Applications -> Caskroom Symlink\",\n app_name\n );\n debug!(\" Staged app source: {}\", staged_app_path.display());\n debug!(\n \" Private store copy target: {}\",\n final_private_store_app_path.display()\n );\n debug!(\n \" Final /Applications target: {}\",\n final_app_destination_in_applications.display()\n );\n debug!(\n \" Caskroom symlink target: {}\",\n caskroom_symlink_to_final_app.display()\n );\n\n // 1. Ensure Caskroom version path exists\n if !cask_version_install_path.exists() {\n fs::create_dir_all(cask_version_install_path).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\n \"Failed to create cask version dir {}: {}\",\n cask_version_install_path.display(),\n e\n ),\n )))\n })?;\n }\n\n // 2. Create private store directory if it doesn't exist\n if let Some(parent) = final_private_store_app_path.parent() {\n if !parent.exists() {\n debug!(\"Creating private store directory: {}\", parent.display());\n fs::create_dir_all(parent).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\n \"Failed to create private store dir {}: {}\",\n parent.display(),\n e\n ),\n )))\n })?;\n }\n }\n\n if !did_upgrade {\n // 3. Clean existing app in private store (if any from a failed prior attempt)\n if final_private_store_app_path.exists()\n || final_private_store_app_path.symlink_metadata().is_ok()\n {\n debug!(\n \"Removing existing item at private store path: {}\",\n final_private_store_app_path.display()\n );\n let _ = remove_path_robustly(&final_private_store_app_path, config, false);\n }\n\n // 4. Move from temporary stage to private store\n debug!(\n \"Moving staged app {} to private store path {}\",\n staged_app_path.display(),\n final_private_store_app_path.display()\n );\n if let Err(e) = fs::rename(staged_app_path, &final_private_store_app_path) {\n error!(\n \"Failed to move staged app to private store: {}. Source: {}, Dest: {}\",\n e,\n staged_app_path.display(),\n final_private_store_app_path.display()\n );\n return Err(SpsError::Io(std::sync::Arc::new(e)));\n }\n }\n\n // 5. Set/Verify Quarantine on private store copy (only if not already present)\n #[cfg(target_os = \"macos\")]\n {\n debug!(\n \"Setting/verifying quarantine on private store copy: {}\",\n final_private_store_app_path.display()\n );\n if let Err(e) = crate::utils::xattr::ensure_quarantine_attribute(\n &final_private_store_app_path,\n &cask.token,\n ) {\n error!(\n \"Failed to set quarantine on private store copy {}: {}. This is critical.\",\n final_private_store_app_path.display(),\n e\n );\n return Err(SpsError::InstallError(format!(\n \"Failed to set quarantine on private store copy {}: {}\",\n final_private_store_app_path.display(),\n e\n )));\n }\n }\n\n // ============================================================================\n // STEP 6: Handle /Applications Destination - THE MOST CRITICAL PART\n // ============================================================================\n // This is where we apply Homebrew's breakthrough strategy that preserves\n // user data and prevents Gatekeeper resets during upgrades.\n //\n // UPGRADE vs FRESH INSTALL Strategy:\n // - UPGRADE: Overwrite app in /Applications directly (preserves identity)\n // - FRESH INSTALL: Use symlink approach (normal installation)\n //\n // WHY THIS SPLIT MATTERS:\n // During upgrades, the app in /Applications already has:\n // 1. Gatekeeper approval and quarantine exemptions\n // 2. Extended attributes that macOS recognizes\n // 3. User trust and security context\n // 4. Associated user data in ~/Library that the app can access\n //\n // By overwriting IN PLACE with cp -pR, we maintain all of this state.\n // ============================================================================\n\n if let JobAction::Upgrade { .. } = job_action {\n // =======================================================================\n // UPGRADE PATH: Direct Overwrite Strategy (Homebrew's Approach)\n // =======================================================================\n // This is the breakthrough that prevents Gatekeeper resets and data loss.\n // We overwrite the existing app directly rather than removing and\n // re-symlinking, which would break the app's established identity.\n // =======================================================================\n\n if final_app_destination_in_applications.exists() {\n debug!(\n \"UPGRADE: Overwriting existing app at /Applications using Homebrew strategy: {}\",\n final_app_destination_in_applications.display()\n );\n\n // Step 1: Remove the old app in /Applications\n // We need sudo because /Applications requires elevated permissions\n let rm_status = Command::new(\"sudo\")\n .arg(\"rm\")\n .arg(\"-rf\")\n .arg(&final_app_destination_in_applications)\n .status()\n .map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n\n if !rm_status.success() {\n return Err(SpsError::InstallError(format!(\n \"Failed to remove existing app during upgrade: {}\",\n final_app_destination_in_applications.display()\n )));\n }\n\n // Copy the new app directly to /Applications, preserving all attributes\n let cp_status = Command::new(\"sudo\")\n .arg(\"cp\")\n .arg(\"-pR\") // Preserve all attributes, links, and metadata\n .arg(&final_private_store_app_path)\n .arg(&final_app_destination_in_applications)\n .status()\n .map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n\n if !cp_status.success() {\n return Err(SpsError::InstallError(format!(\n \"Failed to copy new app to /Applications during upgrade: {}\",\n final_app_destination_in_applications.display()\n )));\n }\n\n debug!(\n \"UPGRADE: Successfully overwrote app in /Applications, preserving identity: {}\",\n final_app_destination_in_applications.display()\n );\n } else {\n // App doesn't exist in /Applications during upgrade - fall back to symlink approach\n debug!(\n \"UPGRADE: App not found in /Applications, creating fresh symlink: {}\",\n final_app_destination_in_applications.display()\n );\n if let Err(e) = std::os::unix::fs::symlink(\n &final_private_store_app_path,\n &final_app_destination_in_applications,\n ) {\n error!(\n \"Failed to symlink app from private store to /Applications: {} -> {}: {}\",\n final_private_store_app_path.display(),\n final_app_destination_in_applications.display(),\n e\n );\n return Err(SpsError::InstallError(format!(\n \"Failed to symlink app from private store to {}: {}\",\n final_app_destination_in_applications.display(),\n e\n )));\n }\n }\n } else {\n // Fresh install: Clean existing app destination and create symlink\n if final_app_destination_in_applications.exists()\n || final_app_destination_in_applications\n .symlink_metadata()\n .is_ok()\n {\n debug!(\n \"Removing existing app at /Applications: {}\",\n final_app_destination_in_applications.display()\n );\n if !remove_path_robustly(&final_app_destination_in_applications, config, true) {\n return Err(SpsError::InstallError(format!(\n \"Failed to remove existing app at {}\",\n final_app_destination_in_applications.display()\n )));\n }\n }\n\n // 7. Symlink from /Applications to private store app bundle\n debug!(\n \"INFO: About to symlink app from private store {} to /Applications {}\",\n final_private_store_app_path.display(),\n final_app_destination_in_applications.display()\n );\n if let Err(e) = std::os::unix::fs::symlink(\n &final_private_store_app_path,\n &final_app_destination_in_applications,\n ) {\n error!(\n \"Failed to symlink app from private store to /Applications: {} -> {}: {}\",\n final_private_store_app_path.display(),\n final_app_destination_in_applications.display(),\n e\n );\n return Err(SpsError::InstallError(format!(\n \"Failed to symlink app from private store to {}: {}\",\n final_app_destination_in_applications.display(),\n e\n )));\n }\n }\n\n // Remove quarantine attributes from the app in /Applications (whether copied or symlinked)\n #[cfg(target_os = \"macos\")]\n {\n use xattr;\n let _ = xattr::remove(\n &final_app_destination_in_applications,\n \"com.apple.quarantine\",\n );\n let _ = xattr::remove(\n &final_app_destination_in_applications,\n \"com.apple.provenance\",\n );\n let _ = xattr::remove(&final_app_destination_in_applications, \"com.apple.macl\");\n }\n\n match job_action {\n JobAction::Upgrade { .. } => {\n debug!(\n \"INFO: Successfully updated app in /Applications during upgrade: {}\",\n final_app_destination_in_applications.display()\n );\n }\n _ => {\n debug!(\n \"INFO: Successfully symlinked app from private store {} to /Applications {}\",\n final_private_store_app_path.display(),\n final_app_destination_in_applications.display()\n );\n }\n }\n\n // 7. No quarantine set on the symlink in /Applications; attribute remains on private store\n // copy.\n\n // 8. Create Caskroom Symlink TO the app in /Applications\n let actual_caskroom_symlink_path = cask_version_install_path.join(app_name.as_ref());\n debug!(\n \"Creating Caskroom symlink {} -> {}\",\n actual_caskroom_symlink_path.display(),\n final_app_destination_in_applications.display()\n );\n\n if actual_caskroom_symlink_path.symlink_metadata().is_ok() {\n if let Err(e) = fs::remove_file(&actual_caskroom_symlink_path) {\n warn!(\n \"Failed to remove existing item at Caskroom symlink path {}: {}. Proceeding.\",\n actual_caskroom_symlink_path.display(),\n e\n );\n }\n }\n\n #[cfg(unix)]\n {\n if let Err(e) = std::os::unix::fs::symlink(\n &final_app_destination_in_applications,\n &actual_caskroom_symlink_path,\n ) {\n error!(\n \"Failed to create Caskroom symlink {} -> {}: {}\",\n actual_caskroom_symlink_path.display(),\n final_app_destination_in_applications.display(),\n e\n );\n let _ = remove_path_robustly(&final_app_destination_in_applications, config, true);\n return Err(SpsError::Io(std::sync::Arc::new(e)));\n }\n }\n\n let mut created_artifacts = vec![InstalledArtifact::AppBundle {\n path: final_app_destination_in_applications.clone(),\n }];\n created_artifacts.push(InstalledArtifact::CaskroomLink {\n link_path: actual_caskroom_symlink_path,\n target_path: final_app_destination_in_applications.clone(),\n });\n\n debug!(\n \"Successfully installed app artifact: {} (Cask: {})\",\n app_name, cask.token\n );\n\n // Write CASK_INSTALL_MANIFEST.json to ensure package is always detected as installed\n if let Err(e) = crate::install::cask::write_cask_manifest(\n cask,\n cask_version_install_path,\n created_artifacts.clone(),\n ) {\n error!(\n \"Failed to write CASK_INSTALL_MANIFEST.json for {}: {}\",\n cask.token, e\n );\n return Err(SpsError::InstallError(format!(\n \"Failed to write CASK_INSTALL_MANIFEST.json for {}: {}\",\n cask.token, e\n )));\n }\n\n Ok(created_artifacts)\n}\n\n/// Helper function for robust path removal (internal to app.rs or moved to a common util)\nfn remove_path_robustly(path: &Path, _config: &Config, use_sudo_if_needed: bool) -> bool {\n if !path.exists() && path.symlink_metadata().is_err() {\n debug!(\"Path {} not found for removal.\", path.display());\n return true;\n }\n let is_dir = path.is_dir()\n && !path\n .symlink_metadata()\n .is_ok_and(|m| m.file_type().is_symlink());\n let removal_op = || -> std::io::Result<()> {\n if is_dir {\n fs::remove_dir_all(path)\n } else {\n fs::remove_file(path)\n }\n };\n\n if let Err(e) = removal_op() {\n if e.kind() == std::io::ErrorKind::NotFound {\n return true;\n }\n if use_sudo_if_needed && e.kind() == std::io::ErrorKind::PermissionDenied {\n warn!(\n \"Direct removal of {} failed (Permission Denied). Trying with sudo rm -rf.\",\n path.display()\n );\n let output = Command::new(\"sudo\").arg(\"rm\").arg(\"-rf\").arg(path).output();\n match output {\n Ok(out) if out.status.success() => {\n debug!(\"Successfully removed {} with sudo.\", path.display());\n return true;\n }\n Ok(out) => {\n error!(\n \"`sudo rm -rf {}` failed ({}): {}\",\n path.display(),\n out.status,\n String::from_utf8_lossy(&out.stderr).trim()\n );\n return false;\n }\n Err(sudo_e) => {\n error!(\n \"Error executing `sudo rm -rf` for {}: {}\",\n path.display(),\n sudo_e\n );\n return false;\n }\n }\n } else {\n error!(\"Failed to remove {}: {}\", path.display(), e);\n return false;\n }\n }\n debug!(\"Successfully removed {}.\", path.display());\n true\n}\n"], ["/sps/sps-core/src/install/cask/mod.rs", "pub mod artifacts;\npub mod dmg;\npub mod helpers;\n\nuse std::fs;\nuse std::path::{Path, PathBuf};\nuse std::time::{SystemTime, SystemTimeError, UNIX_EPOCH};\n\nuse infer;\nuse reqwest::Url;\nuse serde::{Deserialize, Serialize};\nuse serde_json::json;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::{Cask, Sha256Field, UrlField};\nuse sps_net::http::ProgressCallback;\nuse tempfile::TempDir;\nuse tracing::{debug, error};\n\nuse crate::install::extract;\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub struct CaskInstallManifest {\n pub manifest_format_version: String,\n pub token: String,\n pub version: String,\n pub installed_at: u64,\n pub artifacts: Vec,\n pub primary_app_file_name: Option,\n pub is_installed: bool, // New flag for soft uninstall\n pub cask_store_path: Option, // Path to private store app, if available\n}\n\n/// Returns the path to the cask's version directory in the private store.\npub fn sps_private_cask_version_dir(cask: &Cask, config: &Config) -> PathBuf {\n let version = cask.version.clone().unwrap_or_else(|| \"latest\".to_string());\n config.cask_store_version_path(&cask.token, &version)\n}\n\n/// Returns the path to the cask's token directory in the private store.\npub fn sps_private_cask_token_dir(cask: &Cask, config: &Config) -> PathBuf {\n config.cask_store_token_path(&cask.token)\n}\n\n/// Returns the path to the main app bundle for a cask in the private store.\n/// This assumes the primary app bundle is named as specified in the cask's artifacts.\npub fn sps_private_cask_app_path(cask: &Cask, config: &Config) -> Option {\n let version = cask.version.clone().unwrap_or_else(|| \"latest\".to_string());\n if let Some(cask_artifacts) = &cask.artifacts {\n for artifact in cask_artifacts {\n if let Some(obj) = artifact.as_object() {\n if let Some(apps) = obj.get(\"app\") {\n if let Some(app_names) = apps.as_array() {\n if let Some(app_name_val) = app_names.first() {\n if let Some(app_name) = app_name_val.as_str() {\n return Some(config.cask_store_app_path(\n &cask.token,\n &version,\n app_name,\n ));\n }\n }\n }\n }\n }\n }\n }\n None\n}\n\npub async fn download_cask(cask: &Cask, cache: &Cache) -> Result {\n download_cask_with_progress(cask, cache, None).await\n}\n\npub async fn download_cask_with_progress(\n cask: &Cask,\n cache: &Cache,\n progress_callback: Option,\n) -> Result {\n let url_field = cask\n .url\n .as_ref()\n .ok_or_else(|| SpsError::Generic(format!(\"Cask {} has no URL\", cask.token)))?;\n let url_str = match url_field {\n UrlField::Simple(u) => u.as_str(),\n UrlField::WithSpec { url, .. } => url.as_str(),\n };\n\n if url_str.is_empty() {\n return Err(SpsError::Generic(format!(\n \"Cask {} has an empty URL\",\n cask.token\n )));\n }\n\n debug!(\"Downloading cask from {}\", url_str);\n let parsed = Url::parse(url_str)\n .map_err(|e| SpsError::Generic(format!(\"Invalid URL '{url_str}': {e}\")))?;\n sps_net::validation::validate_url(parsed.as_str())?;\n let file_name = parsed\n .path_segments()\n .and_then(|mut segments| segments.next_back())\n .filter(|s| !s.is_empty())\n .map(|s| s.to_string())\n .unwrap_or_else(|| {\n debug!(\"URL has no filename component, using fallback name for cache based on token.\");\n format!(\"cask-{}-download.tmp\", cask.token.replace('/', \"_\"))\n });\n let cache_key = format!(\"cask-{}-{}\", cask.token, file_name);\n let cache_path = cache.get_dir().join(\"cask_downloads\").join(&cache_key);\n\n if cache_path.exists() {\n debug!(\"Using cached download: {}\", cache_path.display());\n return Ok(cache_path);\n }\n\n use futures::StreamExt;\n use tokio::fs::File as TokioFile;\n use tokio::io::AsyncWriteExt;\n\n let client = reqwest::Client::new();\n let response = client\n .get(parsed.clone())\n .send()\n .await\n .map_err(|e| SpsError::Http(std::sync::Arc::new(e)))?;\n if !response.status().is_success() {\n return Err(SpsError::DownloadError(\n cask.token.clone(),\n url_str.to_string(),\n format!(\"HTTP status {}\", response.status()),\n ));\n }\n\n // Get total size from Content-Length header if available\n let total_size = response.content_length();\n\n if let Some(parent) = cache_path.parent() {\n fs::create_dir_all(parent)?;\n }\n\n let mut file = TokioFile::create(&cache_path)\n .await\n .map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n\n // Use bytes_stream() for chunked download with progress reporting\n let mut stream = response.bytes_stream();\n let mut bytes_downloaded = 0u64;\n\n while let Some(chunk) = stream.next().await {\n let chunk = chunk.map_err(|e| SpsError::Http(std::sync::Arc::new(e)))?;\n\n file.write_all(&chunk)\n .await\n .map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n\n bytes_downloaded += chunk.len() as u64;\n\n // Call progress callback if provided\n if let Some(ref callback) = progress_callback {\n callback(bytes_downloaded, total_size);\n }\n }\n\n drop(file);\n match cask.sha256.as_ref() {\n Some(Sha256Field::Hex(s)) => {\n if s.eq_ignore_ascii_case(\"no_check\") {\n tracing::debug!(\n \"Skipping checksum verification for cask {} due to 'no_check' string.\",\n cache_path.display()\n );\n } else if !s.is_empty() {\n match sps_net::validation::verify_checksum(&cache_path, s) {\n Ok(_) => {\n tracing::debug!(\n \"Cask download checksum verified: {}\",\n cache_path.display()\n );\n }\n Err(e) => {\n tracing::error!(\n \"Cask download checksum mismatch ({}). Deleting cached file.\",\n e\n );\n let _ = fs::remove_file(&cache_path);\n return Err(e);\n }\n }\n } else {\n tracing::warn!(\n \"Skipping checksum verification for cask {} - empty sha256 provided.\",\n cache_path.display()\n );\n }\n }\n Some(Sha256Field::NoCheck { no_check: true }) => {\n tracing::debug!(\n \"Skipping checksum verification for cask {} due to 'no_check'.\",\n cache_path.display()\n );\n }\n _ => {\n tracing::warn!(\n \"Skipping checksum verification for cask {} - none provided.\",\n cache_path.display()\n );\n }\n }\n debug!(\"Download completed: {}\", cache_path.display());\n\n // --- Set quarantine xattr on the downloaded archive (macOS only) ---\n #[cfg(target_os = \"macos\")]\n {\n if let Err(e) = crate::utils::xattr::set_quarantine_attribute(&cache_path, \"sps-downloader\")\n {\n tracing::warn!(\n \"Failed to set quarantine attribute on downloaded archive {}: {}. Extraction and installation will proceed, but Gatekeeper behavior might be affected.\",\n cache_path.display(),\n e\n );\n }\n }\n\n Ok(cache_path)\n}\n\nuse sps_common::pipeline::JobAction;\n\npub fn install_cask(\n cask: &Cask,\n download_path: &Path,\n config: &Config,\n job_action: &JobAction,\n) -> Result<()> {\n debug!(\"Installing cask: {}\", cask.token);\n // This is the path in the *actual* Caskroom (e.g., /opt/homebrew/Caskroom/token/version)\n // where metadata and symlinks to /Applications will go.\n let actual_cask_room_version_path = config.cask_room_version_path(\n &cask.token,\n &cask.version.clone().unwrap_or_else(|| \"latest\".to_string()),\n );\n\n if !actual_cask_room_version_path.exists() {\n fs::create_dir_all(&actual_cask_room_version_path).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\n \"Failed create cask_room dir {}: {}\",\n actual_cask_room_version_path.display(),\n e\n ),\n )))\n })?;\n debug!(\n \"Created actual cask_room version directory: {}\",\n actual_cask_room_version_path.display()\n );\n }\n let mut detected_extension = download_path\n .extension()\n .and_then(|e| e.to_str())\n .unwrap_or(\"\")\n .to_lowercase();\n let non_extensions = [\"stable\", \"latest\", \"download\", \"bin\", \"\"];\n if non_extensions.contains(&detected_extension.as_str()) {\n debug!(\n \"Download path '{}' has no definite extension ('{}'), attempting content detection.\",\n download_path.display(),\n detected_extension\n );\n match infer::get_from_path(download_path) {\n Ok(Some(kind)) => {\n detected_extension = kind.extension().to_string();\n debug!(\"Detected file type via content: {}\", detected_extension);\n }\n Ok(None) => {\n error!(\n \"Could not determine file type from content for: {}\",\n download_path.display()\n );\n return Err(SpsError::Generic(format!(\n \"Could not determine file type for download: {}\",\n download_path.display()\n )));\n }\n Err(e) => {\n error!(\n \"Error reading file for type detection {}: {}\",\n download_path.display(),\n e\n );\n return Err(SpsError::Io(std::sync::Arc::new(e)));\n }\n }\n } else {\n debug!(\n \"Using file extension for type detection: {}\",\n detected_extension\n );\n }\n if detected_extension == \"pkg\" || detected_extension == \"mpkg\" {\n debug!(\"Detected PKG installer, running directly\");\n match artifacts::pkg::install_pkg_from_path(\n cask,\n download_path,\n &actual_cask_room_version_path, // PKG manifest items go into the actual cask_room\n config,\n ) {\n Ok(installed_artifacts) => {\n debug!(\"Writing PKG install manifest\");\n write_cask_manifest(cask, &actual_cask_room_version_path, installed_artifacts)?;\n debug!(\"Successfully installed PKG cask: {}\", cask.token);\n return Ok(());\n }\n Err(e) => {\n debug!(\"Failed to install PKG: {}\", e);\n // Clean up cask_room on error\n let _ = fs::remove_dir_all(&actual_cask_room_version_path);\n return Err(e);\n }\n }\n }\n let stage_dir = TempDir::new().map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed to create staging directory: {e}\"),\n )))\n })?;\n let stage_path = stage_dir.path();\n debug!(\"Created staging directory: {}\", stage_path.display());\n // Determine expected extension (this might need refinement)\n // Option 1: Parse from URL\n let expected_ext_from_url = download_path\n .extension()\n .and_then(|e| e.to_str())\n .unwrap_or(\"\");\n // Option 2: A new field in Cask JSON definition (preferred)\n // let expected_ext = cask.expected_extension.as_deref().unwrap_or(expected_ext_from_url);\n let expected_ext = expected_ext_from_url; // Use URL for now\n\n if !expected_ext.is_empty()\n && crate::build::compile::RECOGNISED_SINGLE_FILE_EXTENSIONS.contains(&expected_ext)\n {\n // Check if it's an archive/installer type we handle\n tracing::debug!(\n \"Verifying content type for {} against expected extension '{}'\",\n download_path.display(),\n expected_ext\n );\n if let Err(e) = sps_net::validation::verify_content_type(download_path, expected_ext) {\n tracing::error!(\"Content type verification failed: {}\", e);\n // Attempt cleanup?\n let _ = fs::remove_dir_all(&actual_cask_room_version_path);\n return Err(e);\n }\n } else {\n tracing::debug!(\n \"Skipping content type verification for {} (unknown/no expected extension: '{}')\",\n download_path.display(),\n expected_ext\n );\n }\n match detected_extension.as_str() {\n \"dmg\" => {\n debug!(\n \"Extracting DMG {} to stage {}...\",\n download_path.display(),\n stage_path.display()\n );\n dmg::extract_dmg_to_stage(download_path, stage_path)?;\n debug!(\"Successfully extracted DMG to staging area.\");\n }\n \"zip\" => {\n debug!(\n \"Extracting ZIP {} to stage {}...\",\n download_path.display(),\n stage_path.display()\n );\n extract::extract_archive(download_path, stage_path, 0, \"zip\")?;\n debug!(\"Successfully extracted ZIP to staging area.\");\n }\n \"gz\" | \"bz2\" | \"xz\" | \"tar\" => {\n let archive_type_for_extraction = detected_extension.as_str();\n debug!(\n \"Extracting TAR archive ({}) {} to stage {}...\",\n archive_type_for_extraction,\n download_path.display(),\n stage_path.display()\n );\n extract::extract_archive(download_path, stage_path, 0, archive_type_for_extraction)?;\n debug!(\"Successfully extracted TAR archive to staging area.\");\n }\n _ => {\n error!(\n \"Unsupported container/installer type '{}' for staged installation derived from {}\",\n detected_extension,\n download_path.display()\n );\n return Err(SpsError::Generic(format!(\n \"Unsupported file type for staged installation: {detected_extension}\"\n )));\n }\n }\n let mut all_installed_artifacts: Vec = Vec::new();\n let mut artifact_install_errors = Vec::new();\n if let Some(artifacts_def) = &cask.artifacts {\n debug!(\n \"Processing {} declared artifacts from staging area...\",\n artifacts_def.len()\n );\n for artifact_value in artifacts_def.iter() {\n if let Some(artifact_obj) = artifact_value.as_object() {\n if let Some((key, value)) = artifact_obj.iter().next() {\n debug!(\"Processing artifact type: {}\", key);\n let result: Result> = match key.as_str() {\n \"app\" => {\n let mut app_artifacts = vec![];\n if let Some(app_names) = value.as_array() {\n for app_name_val in app_names {\n if let Some(app_name) = app_name_val.as_str() {\n let staged_app_path = stage_path.join(app_name);\n debug!(\n \"Attempting to install app artifact: {}\",\n staged_app_path.display()\n );\n match artifacts::app::install_app_from_staged(\n cask,\n &staged_app_path,\n &actual_cask_room_version_path,\n config,\n job_action, // Pass job_action for upgrade logic\n ) {\n Ok(mut artifacts) => {\n app_artifacts.append(&mut artifacts)\n }\n Err(e) => {\n return Err(e);\n }\n }\n } else {\n debug!(\n \"Non-string value found in 'app' artifact array: {:?}\",\n app_name_val\n );\n }\n }\n } else {\n debug!(\"'app' artifact value is not an array: {:?}\", value);\n }\n Ok(app_artifacts)\n }\n \"pkg\" => {\n let mut installed_pkgs = vec![];\n if let Some(pkg_names) = value.as_array() {\n for pkg_val in pkg_names {\n if let Some(pkg_name) = pkg_val.as_str() {\n let staged_pkg_path = stage_path.join(pkg_name);\n debug!(\n \"Attempting to install staged pkg artifact: {}\",\n staged_pkg_path.display()\n );\n match artifacts::pkg::install_pkg_from_path(\n cask,\n &staged_pkg_path,\n &actual_cask_room_version_path, /* Pass actual\n * cask_room path */\n config,\n ) {\n Ok(mut artifacts) => {\n installed_pkgs.append(&mut artifacts)\n }\n Err(e) => {\n return Err(e);\n }\n }\n } else {\n debug!(\n \"Non-string value found in 'pkg' artifact array: {:?}\",\n pkg_val\n );\n }\n }\n } else {\n debug!(\"'pkg' artifact value is not an array: {:?}\", value);\n }\n Ok(installed_pkgs)\n }\n _ => {\n debug!(\"Artifact type '{}' not supported yet — skipping.\", key);\n Ok(vec![])\n }\n };\n match result {\n Ok(installed) => {\n if !installed.is_empty() {\n debug!(\n \"Successfully processed artifact '{}', added {} items.\",\n key,\n installed.len()\n );\n all_installed_artifacts.extend(installed);\n } else {\n debug!(\n \"Artifact handler for '{}' completed successfully but returned no artifacts.\",\n key\n );\n }\n }\n Err(e) => {\n error!(\"Error processing artifact '{}': {}\", key, e);\n artifact_install_errors.push(e);\n }\n }\n } else {\n debug!(\"Empty artifact object found: {:?}\", artifact_obj);\n }\n } else {\n debug!(\n \"Unexpected non-object artifact found in list: {:?}\",\n artifact_value\n );\n }\n }\n } else {\n error!(\n \"Cask {} definition is missing the required 'artifacts' array. Cannot determine what to install.\",\n cask.token\n );\n // Clean up the created actual_caskroom_version_path if no artifacts are defined\n let _ = fs::remove_dir_all(&actual_cask_room_version_path);\n return Err(SpsError::InstallError(format!(\n \"Cask '{}' has no artifacts defined.\",\n cask.token\n )));\n }\n if !artifact_install_errors.is_empty() {\n error!(\n \"Encountered {} errors installing artifacts for cask '{}'. Installation incomplete.\",\n artifact_install_errors.len(),\n cask.token\n );\n let _ = fs::remove_dir_all(&actual_cask_room_version_path); // Clean up actual cask_room on error\n return Err(artifact_install_errors.remove(0));\n }\n let actual_install_count = all_installed_artifacts\n .iter()\n .filter(|a| {\n !matches!(\n a,\n InstalledArtifact::PkgUtilReceipt { .. } | InstalledArtifact::Launchd { .. }\n )\n })\n .count();\n if actual_install_count == 0 {\n debug!(\n \"No installable artifacts (like app, pkg, binary, etc.) were processed for cask '{}' from the staged content. Check cask definition.\",\n cask.token\n );\n write_cask_manifest(\n cask,\n &actual_cask_room_version_path,\n all_installed_artifacts,\n )?;\n } else {\n debug!(\"Writing cask installation manifest\");\n write_cask_manifest(\n cask,\n &actual_cask_room_version_path,\n all_installed_artifacts,\n )?;\n }\n debug!(\"Successfully installed cask: {}\", cask.token);\n Ok(())\n}\n\n#[deprecated(note = \"Use write_cask_manifest with detailed InstalledArtifact enum instead\")]\npub fn write_receipt(\n cask: &Cask,\n cask_version_install_path: &Path,\n artifacts: Vec,\n) -> Result<()> {\n let receipt_path = cask_version_install_path.join(\"INSTALL_RECEIPT.json\");\n debug!(\"Writing legacy cask receipt: {}\", receipt_path.display());\n let timestamp = SystemTime::now()\n .duration_since(UNIX_EPOCH)\n .map_err(|e: SystemTimeError| SpsError::Generic(format!(\"System time error: {e}\")))?\n .as_secs();\n let receipt_data = json!({\n \"token\": cask.token,\n \"name\": cask.name.as_ref().and_then(|n| n.first()).cloned(),\n \"version\": cask.version.as_ref().unwrap_or(&\"latest\".to_string()),\n \"installed_at\": timestamp,\n \"artifacts_installed\": artifacts\n });\n if let Some(parent) = receipt_path.parent() {\n fs::create_dir_all(parent).map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n }\n let mut file =\n fs::File::create(&receipt_path).map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n serde_json::to_writer_pretty(&mut file, &receipt_data)\n .map_err(|e| SpsError::Json(std::sync::Arc::new(e)))?;\n debug!(\n \"Successfully wrote legacy receipt with {} artifact entries.\",\n artifacts.len()\n );\n Ok(())\n}\n\npub fn write_cask_manifest(\n cask: &Cask,\n cask_version_install_path: &Path,\n artifacts: Vec,\n) -> Result<()> {\n let manifest_path = cask_version_install_path.join(\"CASK_INSTALL_MANIFEST.json\");\n debug!(\"Writing cask manifest: {}\", manifest_path.display());\n let timestamp = SystemTime::now()\n .duration_since(UNIX_EPOCH)\n .map_err(|e: SystemTimeError| SpsError::Generic(format!(\"System time error: {e}\")))?\n .as_secs();\n\n // Determine primary app file name from artifacts\n let primary_app_file_name = artifacts.iter().find_map(|artifact| {\n if let InstalledArtifact::AppBundle { path } = artifact {\n path.file_name()\n .map(|name| name.to_string_lossy().to_string())\n } else {\n None\n }\n });\n\n // Always set is_installed=true when writing manifest (install or reinstall)\n // Try to determine cask_store_path from artifacts (AppBundle or CaskroomLink)\n let cask_store_path = artifacts.iter().find_map(|artifact| match artifact {\n InstalledArtifact::AppBundle { path } => Some(path.to_string_lossy().to_string()),\n InstalledArtifact::CaskroomLink { target_path, .. } => {\n Some(target_path.to_string_lossy().to_string())\n }\n _ => None,\n });\n\n let manifest_data = CaskInstallManifest {\n manifest_format_version: \"1.0\".to_string(),\n token: cask.token.clone(),\n version: cask.version.clone().unwrap_or_else(|| \"latest\".to_string()),\n installed_at: timestamp,\n artifacts,\n primary_app_file_name,\n is_installed: true,\n cask_store_path,\n };\n if let Some(parent) = manifest_path.parent() {\n fs::create_dir_all(parent).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed create parent dir {}: {}\", parent.display(), e),\n )))\n })?;\n }\n let file = fs::File::create(&manifest_path).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed create manifest {}: {}\", manifest_path.display(), e),\n )))\n })?;\n let writer = std::io::BufWriter::new(file);\n serde_json::to_writer_pretty(writer, &manifest_data).map_err(|e| {\n error!(\n \"Failed to serialize cask manifest JSON for {}: {}\",\n cask.token, e\n );\n SpsError::Json(std::sync::Arc::new(e))\n })?;\n debug!(\n \"Successfully wrote cask manifest with {} artifact entries.\",\n manifest_data.artifacts.len()\n );\n Ok(())\n}\n\n/// Recursively cleans up empty parent directories in the private cask store.\n/// Starts from the given path and walks up, removing empty directories until a non-empty or root is\n/// found.\npub fn cleanup_empty_parent_dirs_in_private_store(start_path: &Path, stop_at: &Path) {\n let mut current = start_path.parent().unwrap_or(start_path).to_path_buf(); // Start from parent\n while current != *stop_at {\n if let Ok(read_dir) = fs::read_dir(¤t) {\n if read_dir.count() == 0 {\n match fs::remove_dir(¤t) {\n Ok(_) => {\n debug!(\"Removed empty directory: {}\", current.display());\n }\n Err(e) => {\n debug!(\"Failed to remove directory {}: {}\", current.display(), e);\n break;\n }\n }\n } else {\n break;\n }\n } else {\n break;\n }\n if let Some(parent) = current.parent() {\n current = parent.to_path_buf();\n } else {\n break;\n }\n }\n}\n"], ["/sps/sps-core/src/install/bottle/exec.rs", "use std::collections::{HashMap, HashSet};\nuse std::fs::{self, File};\nuse std::io::{Read, Write};\nuse std::os::unix::fs::{symlink, PermissionsExt};\nuse std::path::{Path, PathBuf};\nuse std::process::{Command as StdCommand, Stdio};\nuse std::sync::Arc;\n\nuse reqwest::Client;\nuse semver;\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::formula::{BottleFileSpec, Formula, FormulaDependencies};\nuse sps_net::http::ProgressCallback;\nuse sps_net::oci;\nuse sps_net::validation::verify_checksum;\nuse tempfile::NamedTempFile;\nuse tracing::{debug, error, warn};\nuse walkdir::WalkDir;\n\nuse super::macho;\nuse crate::install::bottle::get_current_platform;\nuse crate::install::extract::extract_archive;\n\npub async fn download_bottle(\n formula: &Formula,\n config: &Config,\n client: &Client,\n) -> Result {\n download_bottle_with_progress(formula, config, client, None).await\n}\n\npub async fn download_bottle_with_progress(\n formula: &Formula,\n config: &Config,\n client: &Client,\n progress_callback: Option,\n) -> Result {\n download_bottle_with_progress_and_cache_info(formula, config, client, progress_callback)\n .await\n .map(|(path, _)| path)\n}\n\npub async fn download_bottle_with_progress_and_cache_info(\n formula: &Formula,\n config: &Config,\n client: &Client,\n progress_callback: Option,\n) -> Result<(PathBuf, bool)> {\n debug!(\"Attempting to download bottle for {}\", formula.name);\n let (platform_tag, bottle_file_spec) = get_bottle_for_platform(formula)?;\n debug!(\n \"Selected bottle spec for platform '{}': URL={}, SHA256={}\",\n platform_tag, bottle_file_spec.url, bottle_file_spec.sha256\n );\n if bottle_file_spec.url.is_empty() {\n return Err(SpsError::DownloadError(\n formula.name.clone(),\n \"\".to_string(),\n \"Bottle spec has an empty URL.\".to_string(),\n ));\n }\n let standard_version_str = formula.version_str_full();\n let filename = format!(\n \"{}-{}.{}.bottle.tar.gz\",\n formula.name, standard_version_str, platform_tag\n );\n let cache_dir = config.cache_dir().join(\"bottles\");\n fs::create_dir_all(&cache_dir).map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n let bottle_cache_path = cache_dir.join(&filename);\n if bottle_cache_path.is_file() {\n debug!(\"Bottle found in cache: {}\", bottle_cache_path.display());\n if !bottle_file_spec.sha256.is_empty() {\n match verify_checksum(&bottle_cache_path, &bottle_file_spec.sha256) {\n Ok(_) => {\n debug!(\"Using valid cached bottle: {}\", bottle_cache_path.display());\n return Ok((bottle_cache_path, true));\n }\n Err(e) => {\n debug!(\n \"Cached bottle checksum mismatch ({}): {}. Redownloading.\",\n bottle_cache_path.display(),\n e\n );\n let _ = fs::remove_file(&bottle_cache_path);\n }\n }\n } else {\n warn!(\n \"Using cached bottle without checksum verification (checksum not specified): {}\",\n bottle_cache_path.display()\n );\n return Ok((bottle_cache_path, true));\n }\n } else {\n debug!(\"Bottle not found in cache.\");\n }\n let bottle_url_str = &bottle_file_spec.url;\n let registry_domain = config\n .artifact_domain\n .as_deref()\n .unwrap_or(oci::DEFAULT_GHCR_DOMAIN);\n let is_oci_blob_url = (bottle_url_str.contains(\"://ghcr.io/\")\n || bottle_url_str.contains(registry_domain))\n && bottle_url_str.contains(\"/blobs/sha256:\");\n debug!(\n \"Checking URL type: '{}'. Is OCI Blob URL? {}\",\n bottle_url_str, is_oci_blob_url\n );\n if is_oci_blob_url {\n let expected_digest = bottle_url_str.split(\"/blobs/sha256:\").nth(1).unwrap_or(\"\");\n if expected_digest.is_empty() {\n warn!(\n \"Could not extract expected SHA256 digest from OCI URL: {}\",\n bottle_url_str\n );\n }\n debug!(\n \"Detected OCI blob URL, initiating direct blob download: {} (Digest: {})\",\n bottle_url_str, expected_digest\n );\n match oci::download_oci_blob_with_progress(\n bottle_url_str,\n &bottle_cache_path,\n config,\n client,\n expected_digest,\n progress_callback.clone(),\n )\n .await\n {\n Ok(_) => {\n debug!(\n \"Successfully downloaded OCI blob to {}\",\n bottle_cache_path.display()\n );\n }\n Err(e) => {\n error!(\"Failed to download OCI blob from {}: {}\", bottle_url_str, e);\n let _ = fs::remove_file(&bottle_cache_path);\n return Err(SpsError::DownloadError(\n formula.name.clone(),\n bottle_url_str.to_string(),\n format!(\"Failed to download OCI blob: {e}\"),\n ));\n }\n }\n } else {\n debug!(\n \"Detected standard HTTPS URL, using direct download for: {}\",\n bottle_url_str\n );\n match sps_net::http::fetch_formula_source_or_bottle_with_progress(\n formula.name(),\n bottle_url_str,\n &bottle_file_spec.sha256,\n &[],\n config,\n progress_callback,\n )\n .await\n {\n Ok(downloaded_path) => {\n if downloaded_path != bottle_cache_path {\n debug!(\n \"fetch_formula_source_or_bottle returned path {}. Expected: {}. Assuming correct.\",\n downloaded_path.display(),\n bottle_cache_path.display()\n );\n if !bottle_cache_path.exists() {\n error!(\n \"Downloaded path {} exists, but expected final cache path {} does not!\",\n downloaded_path.display(),\n bottle_cache_path.display()\n );\n return Err(SpsError::Generic(format!(\n \"Download path mismatch and final file missing: {}\",\n bottle_cache_path.display()\n )));\n }\n }\n debug!(\n \"Successfully downloaded directly to {}\",\n bottle_cache_path.display()\n );\n }\n Err(e) => {\n error!(\"Failed to download directly from {}: {}\", bottle_url_str, e);\n return Err(e);\n }\n }\n }\n if !bottle_cache_path.exists() {\n error!(\n \"Bottle download process completed, but the final file {} does not exist.\",\n bottle_cache_path.display()\n );\n return Err(SpsError::Generic(format!(\n \"Bottle file missing after download attempt: {}\",\n bottle_cache_path.display()\n )));\n }\n debug!(\n \"Bottle download successful: {}\",\n bottle_cache_path.display()\n );\n Ok((bottle_cache_path, false))\n}\n\npub fn get_bottle_for_platform(formula: &Formula) -> Result<(String, &BottleFileSpec)> {\n let stable_spec = formula.bottle.stable.as_ref().ok_or_else(|| {\n SpsError::Generic(format!(\n \"Formula '{}' has no stable bottle specification.\",\n formula.name\n ))\n })?;\n if stable_spec.files.is_empty() {\n return Err(SpsError::Generic(format!(\n \"Formula '{}' has no bottle files listed in stable spec.\",\n formula.name\n )));\n }\n let current_platform = get_current_platform();\n if current_platform == \"unknown\" || current_platform.contains(\"unknown\") {\n debug!(\n \"Could not reliably determine current platform ('{}'). Bottle selection might be incorrect.\",\n current_platform\n );\n }\n debug!(\n \"Determining bottle for current platform: {}\",\n current_platform\n );\n debug!(\n \"Available bottle platforms in formula spec: {:?}\",\n stable_spec.files.keys().cloned().collect::>()\n );\n if let Some(spec) = stable_spec.files.get(¤t_platform) {\n debug!(\n \"Found exact bottle match for platform: {}\",\n current_platform\n );\n return Ok((current_platform.clone(), spec));\n }\n debug!(\"No exact match found for {}\", current_platform);\n const ARM_MACOS_VERSIONS: &[&str] = &[\"sequoia\", \"sonoma\", \"ventura\", \"monterey\", \"big_sur\"];\n const INTEL_MACOS_VERSIONS: &[&str] = &[\n \"sequoia\", \"sonoma\", \"ventura\", \"monterey\", \"big_sur\", \"catalina\", \"mojave\",\n ];\n if cfg!(target_os = \"macos\") {\n if let Some(current_os_name) = current_platform\n .strip_prefix(\"arm64_\")\n .or(Some(current_platform.as_str()))\n {\n let version_list = if current_platform.starts_with(\"arm64_\") {\n ARM_MACOS_VERSIONS\n } else {\n INTEL_MACOS_VERSIONS\n };\n if let Some(current_os_index) = version_list.iter().position(|&v| v == current_os_name)\n {\n for target_os_name in version_list.iter().skip(current_os_index) {\n let target_tag = if current_platform.starts_with(\"arm64_\") {\n format!(\"arm64_{target_os_name}\")\n } else {\n target_os_name.to_string()\n };\n if let Some(spec) = stable_spec.files.get(&target_tag) {\n debug!(\n \"No bottle found for exact platform '{}'. Using compatible older bottle '{}'.\",\n current_platform, target_tag\n );\n return Ok((target_tag, spec));\n }\n }\n debug!(\n \"Checked compatible older macOS versions ({:?}), no suitable bottle found.\",\n &version_list[current_os_index..]\n );\n } else {\n debug!(\n \"Current OS '{}' not found in known macOS version list.\",\n current_os_name\n );\n }\n } else {\n debug!(\n \"Could not extract OS name from platform tag '{}'\",\n current_platform\n );\n }\n }\n if current_platform.starts_with(\"arm64_\") {\n if let Some(spec) = stable_spec.files.get(\"arm64_big_sur\") {\n debug!(\n \"No specific OS bottle found for {}. Falling back to 'arm64_big_sur' bottle.\",\n current_platform\n );\n return Ok((\"arm64_big_sur\".to_string(), spec));\n }\n debug!(\"No 'arm64_big_sur' fallback bottle tag found.\");\n } else if cfg!(target_os = \"macos\") {\n if let Some(spec) = stable_spec.files.get(\"big_sur\") {\n debug!(\n \"No specific OS bottle found for {}. Falling back to 'big_sur' bottle.\",\n current_platform\n );\n return Ok((\"big_sur\".to_string(), spec));\n }\n debug!(\"No 'big_sur' fallback bottle tag found.\");\n }\n if let Some(spec) = stable_spec.files.get(\"all\") {\n debug!(\n \"No platform-specific or OS-specific bottle found for {}. Using 'all' platform bottle.\",\n current_platform\n );\n return Ok((\"all\".to_string(), spec));\n }\n debug!(\"No 'all' platform bottle found.\");\n Err(SpsError::DownloadError(\n formula.name.clone(),\n \"\".to_string(),\n format!(\n \"No compatible bottle found for platform '{}'. Available: {:?}\",\n current_platform,\n stable_spec.files.keys().collect::>()\n ),\n ))\n}\n\npub fn install_bottle(bottle_path: &Path, formula: &Formula, config: &Config) -> Result {\n let install_dir = formula.install_prefix(config.cellar_dir().as_path())?;\n if install_dir.exists() {\n debug!(\n \"Removing existing keg directory before installing: {}\",\n install_dir.display()\n );\n fs::remove_dir_all(&install_dir).map_err(|e| {\n SpsError::InstallError(format!(\n \"Failed to remove existing keg {}: {}\",\n install_dir.display(),\n e\n ))\n })?;\n }\n if let Some(parent_dir) = install_dir.parent() {\n fs::create_dir_all(parent_dir).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\n \"Failed to create parent dir {}: {}\",\n parent_dir.display(),\n e\n ),\n )))\n })?;\n } else {\n return Err(SpsError::InstallError(format!(\n \"Could not determine parent directory for install path: {}\",\n install_dir.display()\n )));\n }\n fs::create_dir_all(&install_dir).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed to create keg dir {}: {}\", install_dir.display(), e),\n )))\n })?;\n let strip_components = 2;\n debug!(\n \"Extracting bottle archive {} to {} with strip_components={}\",\n bottle_path.display(),\n install_dir.display(),\n strip_components\n );\n extract_archive(bottle_path, &install_dir, strip_components, \"gz\")?;\n debug!(\n \"Ensuring write permissions for extracted files in {}\",\n install_dir.display()\n );\n ensure_write_permissions(&install_dir)?;\n debug!(\"Performing bottle relocation in {}\", install_dir.display());\n perform_bottle_relocation(formula, &install_dir, config)?;\n ensure_llvm_symlinks(&install_dir, formula, config)?;\n crate::install::bottle::write_receipt(formula, &install_dir, \"bottle\")?;\n debug!(\n \"Bottle installation complete for {} at {}\",\n formula.name(),\n install_dir.display()\n );\n Ok(install_dir)\n}\n\nfn ensure_write_permissions(path: &Path) -> Result<()> {\n if !path.exists() {\n debug!(\n \"Path {} does not exist, cannot ensure write permissions.\",\n path.display()\n );\n return Ok(());\n }\n for entry_result in WalkDir::new(path).into_iter().filter_map(|e| e.ok()) {\n let entry_path = entry_result.path();\n if entry_path == path && entry_result.depth() == 0 {\n continue;\n }\n match fs::metadata(entry_path) {\n Ok(metadata) => {\n let mut perms = metadata.permissions();\n let _is_readonly = perms.readonly();\n #[cfg(unix)]\n {\n let current_mode = perms.mode();\n let new_mode = current_mode | 0o200;\n if new_mode != current_mode {\n perms.set_mode(new_mode);\n let _ = fs::set_permissions(entry_path, perms);\n }\n }\n #[cfg(not(unix))]\n {\n if _is_readonly {\n perms.set_readonly(false);\n let _ = fs::set_permissions(entry_path, perms);\n }\n }\n }\n Err(_e) => {}\n }\n }\n Ok(())\n}\n\nfn perform_bottle_relocation(formula: &Formula, install_dir: &Path, config: &Config) -> Result<()> {\n let mut repl: HashMap = HashMap::new();\n repl.insert(\n \"@@HOMEBREW_CELLAR@@\".into(),\n config.cellar_dir().to_string_lossy().into(),\n );\n repl.insert(\n \"@@HOMEBREW_PREFIX@@\".into(),\n config.sps_root().to_string_lossy().into(),\n );\n let _prefix_path_str = config.sps_root().to_string_lossy();\n let library_path_str = config\n .sps_root()\n .join(\"Library\")\n .to_string_lossy()\n .to_string(); // Assuming Library is under sps_root for this placeholder\n // HOMEBREW_REPOSITORY usually points to the Homebrew/brew git repo, not relevant for sps in\n // this context. If needed for a specific formula, it should point to\n // /opt/sps or similar.\n repl.insert(\n \"@@HOMEBREW_REPOSITORY@@\".into(),\n config.sps_root().to_string_lossy().into(),\n );\n repl.insert(\"@@HOMEBREW_LIBRARY@@\".into(), library_path_str.to_string());\n\n let formula_opt_path = config.formula_opt_path(formula.name());\n let formula_opt_str = formula_opt_path.to_string_lossy();\n let install_dir_str = install_dir.to_string_lossy();\n if formula_opt_str != install_dir_str {\n repl.insert(formula_opt_str.to_string(), install_dir_str.to_string());\n debug!(\n \"Adding self-opt relocation: {} -> {}\",\n formula_opt_str, install_dir_str\n );\n }\n\n if formula.name().starts_with(\"python@\") {\n let version_full = formula.version_str_full();\n let mut parts = version_full.split('.');\n if let (Some(major), Some(minor)) = (parts.next(), parts.next()) {\n let framework_version = format!(\"{major}.{minor}\");\n let framework_dir = install_dir\n .join(\"Frameworks\")\n .join(\"Python.framework\")\n .join(\"Versions\")\n .join(&framework_version);\n let python_lib = framework_dir.join(\"Python\");\n let python_bin = framework_dir\n .join(\"bin\")\n .join(format!(\"python{major}.{minor}\"));\n\n let absolute_python_lib_path_obj = install_dir\n .join(\"Frameworks\")\n .join(\"Python.framework\")\n .join(\"Versions\")\n .join(&framework_version)\n .join(\"Python\");\n let new_id_abs = absolute_python_lib_path_obj.to_str().ok_or_else(|| {\n SpsError::InstallError(format!(\n \"Failed to convert absolute Python library path to string: {}\",\n absolute_python_lib_path_obj.display()\n ))\n })?;\n\n debug!(\n \"Setting absolute ID for {}: {}\",\n python_lib.display(),\n new_id_abs\n );\n let status_id = StdCommand::new(\"install_name_tool\")\n .args([\"-id\", new_id_abs, python_lib.to_str().unwrap()])\n .stdout(Stdio::null())\n .stderr(Stdio::null())\n .status()\n .map_err(|e| SpsError::Io(Arc::new(e)))?;\n if !status_id.success() {\n error!(\"install_name_tool -id failed for {}\", python_lib.display());\n return Err(SpsError::InstallError(format!(\n \"Failed to set absolute id on Python dynamic library: {}\",\n python_lib.display()\n )));\n }\n\n debug!(\"Skipping -add_rpath as absolute paths are used for Python linkage.\");\n\n let old_load_placeholder = format!(\n \"@@HOMEBREW_CELLAR@@/{}/{}/Frameworks/Python.framework/Versions/{}/Python\",\n formula.name(),\n version_full,\n framework_version\n );\n let old_load_resource_placeholder = format!(\n \"@@HOMEBREW_CELLAR@@/{}/{}/Frameworks/Python.framework/Versions/{}/Resources/Python.app/Contents/MacOS/Python\",\n formula.name(),\n version_full,\n framework_version\n );\n let install_dir_str_ref = install_dir.to_string_lossy();\n let abs_old_load = format!(\n \"{install_dir_str_ref}/Frameworks/Python.framework/Versions/{framework_version}/Python\"\n );\n let abs_old_load_resource = format!(\n \"{install_dir_str_ref}/Frameworks/Python.framework/Versions/{framework_version}/Resources/Python.app/Contents/MacOS/Python\"\n );\n\n let run_change = |old: &str, new: &str, target: &Path| -> Result<()> {\n if !target.exists() {\n debug!(\n \"Target {} does not exist, skipping install_name_tool -change.\",\n target.display()\n );\n return Ok(());\n }\n debug!(\n \"Running install_name_tool -change {} {} {}\",\n old,\n new,\n target.display()\n );\n let output = StdCommand::new(\"install_name_tool\")\n .args([\"-change\", old, new, target.to_str().unwrap()])\n .output()\n .map_err(|e| SpsError::Io(Arc::new(e)))?;\n\n if !output.status.success() {\n let stderr = String::from_utf8_lossy(&output.stderr);\n if !stderr.contains(\"file not found\")\n && !stderr.contains(\"no LC_LOAD_DYLIB command specifying file\")\n && !stderr.contains(\"is not a Mach-O file\")\n && !stderr.contains(\"object file format invalid\")\n && !stderr.trim().is_empty()\n {\n error!(\n \"install_name_tool -change failed unexpectedly for target {}: {}\",\n target.display(),\n stderr.trim()\n );\n } else {\n debug!(\n \"install_name_tool -change: old path '{}' likely not found or target '{}' not relevant (stderr: {}).\",\n old,\n target.display(),\n stderr.trim()\n );\n }\n }\n Ok(())\n };\n\n debug!(\"Patching main executable: {}\", python_bin.display());\n run_change(&old_load_placeholder, new_id_abs, &python_bin)?;\n run_change(&old_load_resource_placeholder, new_id_abs, &python_bin)?;\n run_change(&abs_old_load, new_id_abs, &python_bin)?;\n run_change(&abs_old_load_resource, new_id_abs, &python_bin)?;\n\n let python_app = framework_dir\n .join(\"Resources\")\n .join(\"Python.app\")\n .join(\"Contents\")\n .join(\"MacOS\")\n .join(\"Python\");\n\n if python_app.exists() {\n debug!(\n \"Explicitly patching Python.app executable: {}\",\n python_app.display()\n );\n run_change(&old_load_placeholder, new_id_abs, &python_app)?;\n run_change(&abs_old_load, new_id_abs, &python_app)?;\n run_change(&old_load_resource_placeholder, new_id_abs, &python_app)?;\n run_change(&abs_old_load_resource, new_id_abs, &python_app)?;\n } else {\n warn!(\n \"Python.app executable not found at {}, skipping explicit patch.\",\n python_app.display()\n );\n }\n\n codesign_path(&python_lib)?;\n codesign_path(&python_bin)?;\n if python_app.exists() {\n codesign_path(&python_app)?;\n } else {\n debug!(\n \"Python.app binary not found at {}, skipping codesign.\",\n python_app.display()\n );\n }\n }\n }\n\n if let Some(perl_path) = find_brewed_perl(config.sps_root()).or_else(|| {\n if cfg!(target_os = \"macos\") {\n Some(PathBuf::from(\"/usr/bin/perl\"))\n } else {\n None\n }\n }) {\n repl.insert(\n \"@@HOMEBREW_PERL@@\".into(),\n perl_path.to_string_lossy().into(),\n );\n }\n\n match formula.dependencies() {\n Ok(deps) => {\n if let Some(openjdk) = deps\n .iter()\n .find(|d| d.name.starts_with(\"openjdk\"))\n .map(|d| d.name.clone())\n {\n let openjdk_opt = config.formula_opt_path(&openjdk);\n repl.insert(\n \"@@HOMEBREW_JAVA@@\".into(),\n openjdk_opt\n .join(\"libexec/openjdk.jdk/Contents/Home\")\n .to_string_lossy()\n .into(),\n );\n }\n }\n Err(e) => {\n warn!(\n \"Could not check formula dependencies during relocation for {}: {}\",\n formula.name(),\n e\n );\n }\n }\n\n repl.insert(\"HOMEBREW_RELOCATE_RPATHS\".into(), \"1\".into());\n\n let opt_placeholder = format!(\n \"@@HOMEBREW_OPT_{}@@\",\n formula.name().to_uppercase().replace(['-', '+', '.'], \"_\")\n );\n repl.insert(\n opt_placeholder,\n config\n .formula_opt_path(formula.name())\n .to_string_lossy()\n .into(),\n );\n\n match formula.dependencies() {\n Ok(deps) => {\n let llvm_dep_name = deps\n .iter()\n .find(|d| d.name.starts_with(\"llvm\"))\n .map(|d| d.name.clone());\n if let Some(name) = llvm_dep_name {\n let llvm_opt_path = config.formula_opt_path(&name);\n let llvm_lib = llvm_opt_path.join(\"lib\");\n if llvm_lib.is_dir() {\n repl.insert(\n \"@loader_path/../lib\".into(),\n llvm_lib.to_string_lossy().into(),\n );\n repl.insert(\n format!(\n \"@@HOMEBREW_OPT_{}@@/lib\",\n name.to_uppercase().replace(['-', '+', '.'], \"_\")\n ),\n llvm_lib.to_string_lossy().into(),\n );\n }\n }\n }\n Err(e) => {\n warn!(\n \"Could not check formula dependencies during LLVM relocation for {}: {}\",\n formula.name(),\n e\n );\n }\n }\n\n tracing::debug!(\"Relocation table:\");\n for (k, v) in &repl {\n tracing::debug!(\"{} → {}\", k, v);\n }\n original_relocation_scan_and_patch(formula, install_dir, config, repl)\n}\n\nfn original_relocation_scan_and_patch(\n _formula: &Formula,\n install_dir: &Path,\n _config: &Config,\n replacements: HashMap,\n) -> Result<()> {\n let mut text_replaced_count = 0;\n let mut macho_patched_count = 0;\n let mut permission_errors = 0;\n let mut macho_errors = 0;\n let mut io_errors = 0;\n let mut files_to_chmod: Vec = Vec::new();\n for entry in WalkDir::new(install_dir).into_iter().filter_map(|e| e.ok()) {\n let path = entry.path();\n let file_type = entry.file_type();\n if path\n .components()\n .any(|c| c.as_os_str().to_string_lossy().ends_with(\".app\"))\n {\n if file_type.is_file() {\n debug!(\"Skipping relocation inside .app bundle: {}\", path.display());\n }\n continue;\n }\n if file_type.is_symlink() {\n debug!(\"Checking symlink for potential chmod: {}\", path.display());\n if path\n .parent()\n .is_some_and(|p| p.ends_with(\"bin\") || p.ends_with(\"sbin\"))\n {\n files_to_chmod.push(path.to_path_buf());\n }\n continue;\n }\n if !file_type.is_file() {\n continue;\n }\n let (meta, initially_executable) = match fs::metadata(path) {\n Ok(m) => {\n #[cfg(unix)]\n let ie = m.permissions().mode() & 0o111 != 0;\n #[cfg(not(unix))]\n let ie = true;\n (m, ie)\n }\n Err(_e) => {\n debug!(\"Failed to get metadata for {}: {}\", path.display(), _e);\n io_errors += 1;\n continue;\n }\n };\n let is_in_exec_dir = path\n .parent()\n .is_some_and(|p| p.ends_with(\"bin\") || p.ends_with(\"sbin\"));\n if meta.permissions().readonly() {\n #[cfg(unix)]\n {\n let mut perms = meta.permissions();\n let current_mode = perms.mode();\n let new_mode = current_mode | 0o200;\n if new_mode != current_mode {\n perms.set_mode(new_mode);\n if fs::set_permissions(path, perms).is_err() {\n debug!(\n \"Skipping readonly file (and couldn't make writable): {}\",\n path.display()\n );\n continue;\n } else {\n debug!(\"Made readonly file writable: {}\", path.display());\n }\n }\n }\n #[cfg(not(unix))]\n {\n debug!(\n \"Skipping potentially readonly file on non-unix: {}\",\n path.display()\n );\n continue;\n }\n }\n let mut was_modified = false;\n let mut skipped_paths_for_file = Vec::new();\n if cfg!(target_os = \"macos\")\n && (initially_executable\n || is_in_exec_dir\n || path\n .extension()\n .is_some_and(|e| e == \"dylib\" || e == \"so\" || e == \"bundle\"))\n {\n match macho::patch_macho_file(path, &replacements) {\n Ok((true, skipped_paths)) => {\n macho_patched_count += 1;\n was_modified = true;\n skipped_paths_for_file = skipped_paths;\n }\n Ok((false, skipped_paths)) => {\n // Not Mach-O or no patches needed, but might have skipped paths\n skipped_paths_for_file = skipped_paths;\n }\n Err(SpsError::PathTooLongError(e)) => { // Specifically catch path too long\n error!(\n \"Mach-O patch failed (path too long) for {}: {}\",\n path.display(),\n e\n );\n macho_errors += 1;\n // Continue scanning other files even if one fails this way\n continue;\n }\n Err(SpsError::CodesignError(e)) => { // Specifically catch codesign errors\n error!(\n \"Mach-O patch failed (codesign error) for {}: {}\",\n path.display(),\n e\n );\n macho_errors += 1;\n // Continue scanning other files\n continue;\n }\n // Catch generic MachOError or Object error, treat as non-fatal for text replace\n Err(e @ SpsError::MachOError(_))\n | Err(e @ SpsError::Object(_))\n | Err(e @ SpsError::Generic(_)) // Catch Generic errors from patch_macho too\n | Err(e @ SpsError::Io(_)) => { // Catch IO errors from patch_macho\n debug!(\n \"Mach-O processing/patching failed for {}: {}. Skipping Mach-O patch for this file.\",\n path.display(),\n e\n );\n // Don't increment macho_errors here, as we fallback to text replace\n io_errors += 1; // Count as IO or generic error instead\n }\n // Catch other specific errors if needed\n Err(e) => {\n debug!(\n \"Unexpected error during Mach-O check/patch for {}: {}. Falling back to text replacer.\",\n path.display(),\n e\n );\n io_errors += 1;\n }\n }\n\n // Handle paths that were too long for Mach-O patching with install_name_tool fallback\n if !skipped_paths_for_file.is_empty() {\n debug!(\n \"Applying install_name_tool fallback for {} skipped paths in {}\",\n skipped_paths_for_file.len(),\n path.display()\n );\n debug!(\n \"Applying install_name_tool fallback for {} skipped paths in {}\",\n skipped_paths_for_file.len(),\n path.display()\n );\n for skipped in &skipped_paths_for_file {\n match apply_install_name_tool_change(&skipped.old_path, &skipped.new_path, path)\n {\n Ok(()) => {\n debug!(\n \"Successfully applied install_name_tool fallback: '{}' -> '{}' in {}\",\n skipped.old_path, skipped.new_path, path.display()\n );\n was_modified = true;\n }\n Err(e) => {\n warn!(\n \"install_name_tool fallback failed for '{}' -> '{}' in {}: {}\",\n skipped.old_path,\n skipped.new_path,\n path.display(),\n e\n );\n macho_errors += 1;\n }\n }\n }\n }\n }\n // Fallback to text replacement if not modified by Mach-O patching\n if !was_modified {\n // Heuristic check for text file (avoid reading huge binaries)\n let mut is_likely_text = false;\n if meta.len() < 5 * 1024 * 1024 {\n if let Ok(mut f) = File::open(path) {\n let mut buf = [0; 1024];\n match f.read(&mut buf) {\n Ok(n) if n > 0 => {\n if !buf[..n].contains(&0) {\n is_likely_text = true;\n }\n }\n Ok(_) => {\n is_likely_text = true;\n }\n Err(_) => {}\n }\n }\n }\n\n if is_likely_text {\n // Read the file content as string\n if let Ok(content) = fs::read_to_string(path) {\n let mut new_content = content.clone();\n let mut replacements_made = false;\n for (placeholder, replacement) in &replacements {\n if new_content.contains(placeholder) {\n new_content = new_content.replace(placeholder, replacement);\n replacements_made = true;\n }\n }\n // Write back only if changes were made\n if replacements_made {\n match write_text_file_atomic(path, &new_content) {\n Ok(_) => {\n text_replaced_count += 1;\n was_modified = true; // Mark as modified for chmod check\n }\n Err(e) => {\n error!(\n \"Failed to write replaced text to {}: {}\",\n path.display(),\n e\n );\n io_errors += 1;\n }\n }\n }\n } else if meta.len() > 0 {\n debug!(\n \"Could not read {} as string for text replacement.\",\n path.display()\n );\n io_errors += 1;\n }\n } else if meta.len() >= 5 * 1024 * 1024 {\n debug!(\n \"Skipping text replacement for large file: {}\",\n path.display()\n );\n } else {\n debug!(\n \"Skipping text replacement for likely binary file: {}\",\n path.display()\n );\n }\n }\n if was_modified || initially_executable || is_in_exec_dir {\n files_to_chmod.push(path.to_path_buf());\n }\n }\n\n #[cfg(unix)]\n {\n debug!(\n \"Ensuring execute permissions for {} potentially executable files/links\",\n files_to_chmod.len()\n );\n let unique_files_to_chmod: HashSet<_> = files_to_chmod.into_iter().collect();\n for p in &unique_files_to_chmod {\n if !p.exists() && p.symlink_metadata().is_err() {\n debug!(\"Skipping chmod for non-existent path: {}\", p.display());\n continue;\n }\n match fs::symlink_metadata(p) {\n Ok(m) => {\n if m.is_file() {\n let mut perms = m.permissions();\n let current_mode = perms.mode();\n let new_mode = current_mode | 0o111;\n if new_mode != current_mode {\n perms.set_mode(new_mode);\n if let Err(e) = fs::set_permissions(p, perms) {\n debug!(\"Failed to set +x on {}: {}\", p.display(), e);\n permission_errors += 1;\n }\n }\n }\n }\n Err(e) => {\n debug!(\n \"Could not stat {} during final chmod pass: {}\",\n p.display(),\n e\n );\n permission_errors += 1;\n }\n }\n }\n }\n\n debug!(\n \"Relocation scan complete. Text files replaced: {}, Mach-O files patched: {}\",\n text_replaced_count, macho_patched_count\n );\n if permission_errors > 0 || macho_errors > 0 || io_errors > 0 {\n debug!(\n \"Bottle relocation finished with issues: {} chmod errors, {} Mach-O errors, {} IO errors in {}.\",\n permission_errors,\n macho_errors,\n io_errors,\n install_dir.display()\n );\n if macho_errors > 0 {\n return Err(SpsError::InstallError(format!(\n \"Bottle relocation failed due to {} Mach-O errors in {}\",\n macho_errors,\n install_dir.display()\n )));\n }\n }\n Ok(())\n}\n\nfn codesign_path(target: &Path) -> Result<()> {\n debug!(\"Re‑signing: {}\", target.display());\n let status = StdCommand::new(\"codesign\")\n .args([\n \"-s\",\n \"-\",\n \"--force\",\n \"--preserve-metadata=identifier,entitlements\",\n target\n .to_str()\n .ok_or_else(|| SpsError::Generic(\"Non‑UTF8 path for codesign\".into()))?,\n ])\n .stdout(Stdio::null())\n .stderr(Stdio::null())\n .status()\n .map_err(|e| SpsError::Io(Arc::new(e)))?;\n if !status.success() {\n return Err(SpsError::CodesignError(format!(\n \"codesign failed for {}\",\n target.display()\n )));\n }\n Ok(())\n}\nfn write_text_file_atomic(original_path: &Path, content: &str) -> Result<()> {\n let dir = original_path.parent().ok_or_else(|| {\n SpsError::Generic(format!(\n \"Cannot get parent directory for {}\",\n original_path.display()\n ))\n })?;\n // Ensure the directory exists\n fs::create_dir_all(dir).map_err(|e| SpsError::Io(Arc::new(e)))?; // Use Arc::new\n\n let mut temp_file = NamedTempFile::new_in(dir)?;\n let temp_path = temp_file.path().to_path_buf(); // Store path before consuming temp_file\n\n // Write content\n temp_file.write_all(content.as_bytes())?;\n // Ensure data is flushed from application buffer to OS buffer\n temp_file.flush()?;\n // Attempt to sync data from OS buffer to disk (best effort)\n let _ = temp_file.as_file().sync_all();\n\n // Try to preserve original permissions\n let original_perms = fs::metadata(original_path).map(|m| m.permissions()).ok();\n\n // Atomically replace the original file with the temporary file\n temp_file.persist(original_path).map_err(|e| {\n error!(\n \"Failed to persist/rename temporary text file {} over {}: {}\",\n temp_path.display(), // Use stored path for logging\n original_path.display(),\n e.error // Log the underlying IO error\n );\n // Return the IO error wrapped in our error type\n SpsError::Io(Arc::new(e.error)) // Use Arc::new\n })?;\n\n // Restore original permissions if we captured them\n if let Some(perms) = original_perms {\n // Ignore errors setting permissions, best effort\n let _ = fs::set_permissions(original_path, perms);\n }\n Ok(())\n}\n\n#[cfg(unix)]\nfn find_brewed_perl(prefix: &Path) -> Option {\n let opt_dir = prefix.join(\"opt\");\n if !opt_dir.is_dir() {\n return None;\n }\n let mut best: Option<(semver::Version, PathBuf)> = None;\n match fs::read_dir(opt_dir) {\n Ok(entries) => {\n for entry_res in entries.flatten() {\n let name = entry_res.file_name();\n let s = name.to_string_lossy();\n let entry_path = entry_res.path();\n if !entry_path.is_dir() {\n continue;\n }\n if let Some(version_part) = s.strip_prefix(\"perl@\") {\n let version_str_padded = if version_part.contains('.') {\n let parts: Vec<&str> = version_part.split('.').collect();\n match parts.len() {\n 1 => format!(\"{}.0.0\", parts[0]), // e.g., perl@5 -> 5.0.0\n 2 => format!(\"{}.{}.0\", parts[0], parts[1]), /* e.g., perl@5.30 -> */\n // 5.30.0\n _ => version_part.to_string(), // Already 3+ parts\n }\n } else {\n format!(\"{version_part}.0.0\") // e.g., perl@5 -> 5.0.0 (handles case with no\n // dot)\n };\n\n if let Ok(v) = semver::Version::parse(&version_str_padded) {\n let candidate_bin = entry_path.join(\"bin/perl\");\n if candidate_bin.is_file()\n && (best.is_none() || v > best.as_ref().unwrap().0)\n {\n best = Some((v, candidate_bin));\n }\n }\n } else if s == \"perl\" {\n let candidate_bin = entry_path.join(\"bin/perl\");\n if candidate_bin.is_file() && best.is_none() {\n if let Ok(v_base) = semver::Version::parse(\"5.0.0\") {\n best = Some((v_base, candidate_bin));\n }\n }\n }\n }\n }\n Err(_e) => {\n debug!(\"Failed to read opt directory during perl search: {}\", _e);\n }\n }\n best.map(|(_, path)| path)\n}\n\n#[cfg(not(unix))]\nfn find_brewed_perl(_prefix: &Path) -> Option {\n None\n}\nfn ensure_llvm_symlinks(install_dir: &Path, formula: &Formula, config: &Config) -> Result<()> {\n let lib_dir = install_dir.join(\"lib\");\n if !lib_dir.exists() {\n debug!(\n \"Skipping LLVM symlink creation as lib dir is missing in {}\",\n install_dir.display()\n );\n return Ok(());\n }\n\n let llvm_dep_name = match formula.dependencies() {\n Ok(deps) => deps\n .iter()\n .find(|d| d.name.starts_with(\"llvm\"))\n .map(|dep| dep.name.clone()),\n Err(e) => {\n warn!(\n \"Could not check formula dependencies for LLVM symlink creation in {}: {}\",\n formula.name(),\n e\n );\n return Ok(()); // Don't error, just skip\n }\n };\n\n // Proceed only if llvm_dep_name is Some\n let llvm_dep_name = match llvm_dep_name {\n Some(name) => name,\n None => {\n debug!(\n \"Formula {} does not list an LLVM dependency.\",\n formula.name()\n );\n return Ok(());\n }\n };\n\n let llvm_opt_path = config.formula_opt_path(&llvm_dep_name);\n let llvm_lib_filename = if cfg!(target_os = \"macos\") {\n \"libLLVM.dylib\"\n } else if cfg!(target_os = \"linux\") {\n \"libLLVM.so\"\n } else {\n warn!(\"LLVM library filename unknown for target OS, skipping symlink.\");\n return Ok(());\n };\n let llvm_lib_path_in_opt = llvm_opt_path.join(\"lib\").join(llvm_lib_filename);\n if !llvm_lib_path_in_opt.exists() {\n debug!(\n \"Required LLVM library not found at {}. Cannot create symlink in {}.\",\n llvm_lib_path_in_opt.display(),\n formula.name()\n );\n return Ok(());\n }\n let symlink_target_path = lib_dir.join(llvm_lib_filename);\n if symlink_target_path.exists() || symlink_target_path.symlink_metadata().is_ok() {\n debug!(\n \"Symlink or file already exists at {}. Skipping creation.\",\n symlink_target_path.display()\n );\n return Ok(());\n }\n #[cfg(unix)]\n {\n if let Some(parent) = symlink_target_path.parent() {\n if !parent.exists() {\n fs::create_dir_all(parent)?;\n }\n }\n match symlink(&llvm_lib_path_in_opt, &symlink_target_path) {\n Ok(_) => debug!(\n \"Created symlink {} -> {}\",\n symlink_target_path.display(),\n llvm_lib_path_in_opt.display()\n ),\n Err(e) => {\n // Log as warning, don't fail install\n warn!(\n \"Failed to create LLVM symlink {} -> {}: {}\",\n symlink_target_path.display(),\n llvm_lib_path_in_opt.display(),\n e\n );\n }\n }\n\n let rustlib_dir = install_dir.join(\"lib\").join(\"rustlib\");\n if rustlib_dir.is_dir() {\n if let Ok(entries) = fs::read_dir(&rustlib_dir) {\n for entry in entries.flatten() {\n let triple_path = entry.path();\n if triple_path.is_dir() {\n let triple_lib_dir = triple_path.join(\"lib\");\n if triple_lib_dir.is_dir() {\n let nested_symlink = triple_lib_dir.join(llvm_lib_filename);\n\n if nested_symlink.exists() || nested_symlink.symlink_metadata().is_ok()\n {\n debug!(\n \"Symlink or file already exists at {}, skipping.\",\n nested_symlink.display()\n );\n continue;\n }\n\n if let Some(parent) = nested_symlink.parent() {\n let _ = fs::create_dir_all(parent);\n }\n match symlink(&llvm_lib_path_in_opt, &nested_symlink) {\n Ok(_) => debug!(\n \"Created symlink {} -> {}\",\n nested_symlink.display(),\n llvm_lib_path_in_opt.display()\n ),\n Err(e) => warn!(\n \"Failed to create LLVM symlink {} -> {}: {}\",\n nested_symlink.display(),\n llvm_lib_path_in_opt.display(),\n e\n ),\n }\n }\n }\n }\n }\n }\n }\n Ok(())\n}\n\n/// Applies a path change using install_name_tool as a fallback for Mach-O files\n/// where the path replacement is too long for direct binary patching.\nfn apply_install_name_tool_change(old_path: &str, new_path: &str, target: &Path) -> Result<()> {\n if !target.exists() {\n debug!(\n \"Target {} does not exist, skipping install_name_tool fallback.\",\n target.display()\n );\n return Ok(());\n }\n\n debug!(\n \"Running install_name_tool -change {} {} {}\",\n old_path,\n new_path,\n target.display()\n );\n\n let output = StdCommand::new(\"install_name_tool\")\n .args([\"-change\", old_path, new_path, target.to_str().unwrap()])\n .output()\n .map_err(|e| SpsError::Io(Arc::new(e)))?;\n\n if !output.status.success() {\n let stderr = String::from_utf8_lossy(&output.stderr);\n if !stderr.contains(\"file not found\")\n && !stderr.contains(\"no LC_LOAD_DYLIB command specifying file\")\n && !stderr.contains(\"is not a Mach-O file\")\n && !stderr.contains(\"object file format invalid\")\n && !stderr.trim().is_empty()\n {\n error!(\n \"install_name_tool -change failed unexpectedly for target {}: {}\",\n target.display(),\n stderr.trim()\n );\n return Err(SpsError::InstallError(format!(\n \"install_name_tool failed for {}: {}\",\n target.display(),\n stderr.trim()\n )));\n } else {\n debug!(\n \"install_name_tool -change: old path '{}' likely not found or target '{}' not relevant (stderr: {}).\",\n old_path,\n target.display(),\n stderr.trim()\n );\n return Ok(()); // No changes made, skip re-signing\n }\n }\n\n // Re-sign the binary after making changes (required on Apple Silicon)\n #[cfg(all(target_os = \"macos\", target_arch = \"aarch64\"))]\n {\n debug!(\n \"Re-signing binary after install_name_tool change: {}\",\n target.display()\n );\n codesign_path(target)?;\n }\n\n debug!(\n \"Successfully applied install_name_tool fallback for {} -> {} in {}\",\n old_path,\n new_path,\n target.display()\n );\n\n Ok(())\n}\n"], ["/sps/sps-core/src/utils/applescript.rs", "use std::path::Path;\nuse std::process::Command;\nuse std::thread;\nuse std::time::Duration;\n\nuse plist::Value as PlistValue;\nuse sps_common::error::Result;\nuse tracing::{debug, warn};\n\nfn get_bundle_identifier_from_app_path(app_path: &Path) -> Option {\n let info_plist_path = app_path.join(\"Contents/Info.plist\");\n if !info_plist_path.is_file() {\n debug!(\"Info.plist not found at {}\", info_plist_path.display());\n return None;\n }\n match PlistValue::from_file(&info_plist_path) {\n Ok(PlistValue::Dictionary(dict)) => dict\n .get(\"CFBundleIdentifier\")\n .and_then(PlistValue::as_string)\n .map(String::from),\n Ok(val) => {\n warn!(\n \"Info.plist at {} is not a dictionary. Value: {:?}\",\n info_plist_path.display(),\n val\n );\n None\n }\n Err(e) => {\n warn!(\n \"Failed to parse Info.plist at {}: {}\",\n info_plist_path.display(),\n e\n );\n None\n }\n }\n}\n\nfn is_app_running_by_bundle_id(bundle_id: &str) -> Result {\n let script = format!(\n \"tell application \\\"System Events\\\" to (exists (process 1 where bundle identifier is \\\"{bundle_id}\\\"))\"\n );\n debug!(\n \"Checking if app with bundle ID '{}' is running using script: {}\",\n bundle_id, script\n );\n\n let output = Command::new(\"osascript\").arg(\"-e\").arg(&script).output()?;\n\n if output.status.success() {\n let stdout = String::from_utf8_lossy(&output.stdout)\n .trim()\n .to_lowercase();\n debug!(\n \"is_app_running_by_bundle_id ('{}') stdout: '{}'\",\n bundle_id, stdout\n );\n Ok(stdout == \"true\")\n } else {\n let stderr = String::from_utf8_lossy(&output.stderr);\n warn!(\n \"osascript check running status for bundle ID '{}' failed. Status: {}, Stderr: {}\",\n bundle_id,\n output.status,\n stderr.trim()\n );\n Ok(false)\n }\n}\n\n/// Attempts to gracefully quit an application using its bundle identifier (preferred) or name via\n/// AppleScript. Retries several times, checking if the app is still running between attempts.\n/// Returns Ok even if the app could not be quit, as uninstall should proceed.\npub fn quit_app_gracefully(app_path: &Path) -> Result<()> {\n if !cfg!(target_os = \"macos\") {\n debug!(\"Not on macOS, skipping app quit for {}\", app_path.display());\n return Ok(());\n }\n if !app_path.exists() {\n debug!(\n \"App path {} does not exist, skipping quit attempt.\",\n app_path.display()\n );\n return Ok(());\n }\n\n let app_name_for_log = app_path\n .file_name()\n .map_or_else(|| app_path.to_string_lossy(), |name| name.to_string_lossy())\n .trim_end_matches(\".app\")\n .to_string();\n\n let bundle_identifier = get_bundle_identifier_from_app_path(app_path);\n\n let (script_target, using_bundle_id) = match &bundle_identifier {\n Some(id) => (id.clone(), true),\n None => {\n warn!(\n \"Could not get bundle identifier for {}. Will attempt to quit by name '{}'. This is less reliable.\",\n app_path.display(),\n app_name_for_log\n );\n (app_name_for_log.clone(), false)\n }\n };\n\n debug!(\n \"Attempting to quit app '{}' (script target: '{}', using bundle_id: {})\",\n app_name_for_log, script_target, using_bundle_id\n );\n\n // Initial check if app is running (only reliable if we have bundle ID)\n if using_bundle_id {\n match is_app_running_by_bundle_id(&script_target) {\n Ok(true) => debug!(\n \"App '{}' is running. Proceeding with quit attempts.\",\n script_target\n ),\n Ok(false) => {\n debug!(\"App '{}' is not running. Quit unnecessary.\", script_target);\n return Ok(());\n }\n Err(e) => {\n warn!(\n \"Could not determine if app '{}' is running (check failed: {}). Proceeding with quit attempt.\",\n script_target, e\n );\n }\n }\n }\n\n let quit_command = if using_bundle_id {\n format!(\"tell application id \\\"{script_target}\\\" to quit\")\n } else {\n format!(\"tell application \\\"{script_target}\\\" to quit\")\n };\n\n const MAX_QUIT_ATTEMPTS: usize = 4;\n const QUIT_DELAYS_SECS: [u64; MAX_QUIT_ATTEMPTS - 1] = [2, 3, 5];\n\n // Use enumerate over QUIT_DELAYS_SECS for Clippy compliance\n for (attempt, delay) in QUIT_DELAYS_SECS.iter().enumerate() {\n debug!(\n \"Quit attempt #{} for '{}' using command: {}\",\n attempt + 1,\n script_target,\n quit_command\n );\n\n let output = Command::new(\"osascript\")\n .arg(\"-e\")\n .arg(&quit_command)\n .output()?; // Propagate IO errors from osascript execution\n\n if output.status.success() {\n debug!(\n \"osascript quit command sent successfully for '{}' (attempt #{}).\",\n script_target,\n attempt + 1\n );\n } else {\n let stderr = String::from_utf8_lossy(&output.stderr);\n if stderr.contains(\"-1712\")\n || stderr.contains(\"-1728\")\n || stderr.contains(\"-600\")\n || stderr.to_lowercase().contains(\"application isn’t running\")\n || stderr.to_lowercase().contains(\"application not running\")\n {\n debug!(\n \"osascript: App '{}' reported as not running or not found (stderr: {}). Quit successful or unnecessary.\",\n script_target,\n stderr.trim()\n );\n return Ok(());\n } else {\n warn!(\n \"osascript quit command for '{}' failed (attempt #{}). Status: {}. Stderr: {}\",\n script_target,\n attempt + 1,\n output.status,\n stderr.trim()\n );\n }\n }\n\n // Wait briefly to allow the app to process the quit command\n thread::sleep(Duration::from_secs(*delay));\n\n // Check if the app is still running (if using bundle ID)\n if using_bundle_id {\n match is_app_running_by_bundle_id(&script_target) {\n Ok(true) => {\n debug!(\n \"App '{}' still running after attempt #{}. Retrying.\",\n script_target,\n attempt + 1\n );\n }\n Ok(false) => {\n debug!(\n \"App '{}' successfully quit after attempt #{}.\",\n script_target,\n attempt + 1\n );\n return Ok(());\n }\n Err(e) => {\n warn!(\n \"Could not verify if app '{}' quit after attempt #{}: {}. Assuming it might still be running.\",\n script_target,\n attempt + 1,\n e\n );\n }\n }\n }\n }\n\n // Final attempt (the fourth, not covered by QUIT_DELAYS_SECS)\n let attempt = QUIT_DELAYS_SECS.len();\n debug!(\n \"Quit attempt #{} for '{}' using command: {}\",\n attempt + 1,\n script_target,\n quit_command\n );\n\n let output = Command::new(\"osascript\")\n .arg(\"-e\")\n .arg(&quit_command)\n .output()?; // Propagate IO errors from osascript execution\n\n if output.status.success() {\n debug!(\n \"osascript quit command sent successfully for '{}' (attempt #{}).\",\n script_target,\n attempt + 1\n );\n } else {\n let stderr = String::from_utf8_lossy(&output.stderr);\n if stderr.contains(\"-1712\")\n || stderr.contains(\"-1728\")\n || stderr.contains(\"-600\")\n || stderr.to_lowercase().contains(\"application isn’t running\")\n || stderr.to_lowercase().contains(\"application not running\")\n {\n debug!(\n \"osascript: App '{}' reported as not running or not found (stderr: {}). Quit successful or unnecessary.\",\n script_target,\n stderr.trim()\n );\n return Ok(());\n } else {\n warn!(\n \"osascript quit command for '{}' failed (attempt #{}). Status: {}. Stderr: {}\",\n script_target,\n attempt + 1,\n output.status,\n stderr.trim()\n );\n }\n }\n\n // Final check if the app is still running (if using bundle ID)\n if using_bundle_id {\n match is_app_running_by_bundle_id(&script_target) {\n Ok(true) => {\n warn!(\n \"App '{}' still running after {} quit attempts.\",\n script_target, MAX_QUIT_ATTEMPTS\n );\n }\n Ok(false) => {\n debug!(\n \"App '{}' successfully quit after attempt #{}.\",\n script_target,\n attempt + 1\n );\n return Ok(());\n }\n Err(e) => {\n warn!(\n \"Could not verify if app '{}' quit after attempt #{}: {}. Assuming it might still be running.\",\n script_target,\n attempt + 1,\n e\n );\n }\n }\n } else {\n warn!(\n \"App '{}' (targeted by name) might still be running after {} quit attempts. Manual check may be needed.\",\n script_target,\n MAX_QUIT_ATTEMPTS\n );\n }\n Ok(())\n}\n"], ["/sps/sps/src/main.rs", "// sps/src/main.rs\nuse std::process::{self}; // StdCommand is used\nuse std::sync::Arc;\nuse std::time::{Duration, SystemTime};\nuse std::{env, fs};\n\nuse clap::Parser;\nuse colored::Colorize;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::error::{Result as spResult, SpsError};\nuse tracing::level_filters::LevelFilter;\nuse tracing::{debug, error, warn}; // Import all necessary tracing macros\nuse tracing_subscriber::fmt::writer::MakeWriterExt;\nuse tracing_subscriber::EnvFilter;\n\nmod cli;\nmod pipeline;\n// Correctly import InitArgs via the re-export in cli.rs or directly from its module\nuse cli::{CliArgs, Command, InitArgs};\n\n// Standalone function to handle the init command logic\nasync fn run_init_command(init_args: &InitArgs, verbose_level: u8) -> spResult<()> {\n let init_level_filter = match verbose_level {\n 0 => LevelFilter::INFO,\n 1 => LevelFilter::DEBUG,\n _ => LevelFilter::TRACE,\n };\n let _ = tracing_subscriber::fmt()\n .with_max_level(init_level_filter)\n .with_writer(std::io::stderr)\n .with_ansi(true)\n .without_time()\n .try_init();\n\n let initial_config_for_path = Config::load().map_err(|e| {\n // Handle error if even basic config loading fails for path determination\n SpsError::Config(format!(\n \"Could not determine sps_root for init (config load failed): {e}\"\n ))\n })?;\n\n // Create a minimal Config struct, primarily for sps_root() and derived paths.\n let temp_config_for_init = Config {\n sps_root: initial_config_for_path.sps_root().to_path_buf(),\n api_base_url: \"https://formulae.brew.sh/api\".to_string(),\n artifact_domain: None,\n docker_registry_token: None,\n docker_registry_basic_auth: None,\n github_api_token: None,\n };\n\n init_args.run(&temp_config_for_init).await\n}\n\n#[tokio::main]\nasync fn main() -> spResult<()> {\n let cli_args = CliArgs::parse();\n\n if let Command::Init(ref init_args_ref) = cli_args.command {\n match run_init_command(init_args_ref, cli_args.verbose).await {\n Ok(_) => {\n return Ok(());\n }\n Err(e) => {\n eprintln!(\"{}: Init command failed: {:#}\", \"Error\".red().bold(), e);\n process::exit(1);\n }\n }\n }\n\n let config = Config::load().map_err(|e| {\n SpsError::Config(format!(\n \"Could not load config (have you run 'sps init'?): {e}\"\n ))\n })?;\n\n let level_filter = match cli_args.verbose {\n 0 => LevelFilter::INFO,\n 1 => LevelFilter::DEBUG,\n _ => LevelFilter::TRACE,\n };\n let max_log_level = level_filter.into_level().unwrap_or(tracing::Level::INFO);\n\n let env_filter = EnvFilter::builder()\n .with_default_directive(level_filter.into())\n .with_env_var(\"SPS_LOG\")\n .from_env_lossy();\n\n let log_dir = config.logs_dir();\n if let Err(e) = fs::create_dir_all(&log_dir) {\n eprintln!(\n \"{} Failed to create log directory {}: {} (ensure 'sps init' was successful or try with sudo for the current command if appropriate)\",\n \"Error:\".red().bold(),\n log_dir.display(),\n e\n );\n let _ = tracing_subscriber::fmt() // Use `let _ =`\n .with_env_filter(env_filter)\n .with_writer(std::io::stderr)\n .with_ansi(true)\n .without_time()\n .try_init(); // Use try_init\n } else if cli_args.verbose > 0 {\n let file_appender = tracing_appender::rolling::daily(&log_dir, \"sps.log\");\n let (non_blocking_appender, guard) = tracing_appender::non_blocking(file_appender);\n\n // For verbose mode, show debug/trace logs on stderr too\n let stderr_writer = std::io::stderr.with_max_level(max_log_level);\n let file_writer = non_blocking_appender.with_max_level(max_log_level);\n\n let _ = tracing_subscriber::fmt() // Use `let _ =`\n .with_env_filter(env_filter)\n .with_writer(stderr_writer.and(file_writer))\n .with_ansi(true)\n .without_time()\n .try_init(); // Use try_init\n\n Box::leak(Box::new(guard)); // Keep guard alive\n\n tracing::debug!(\n // This will only work if try_init above was successful for this setup\n \"Verbose logging enabled. Writing logs to: {}/sps.log\",\n log_dir.display()\n );\n } else {\n let _ = tracing_subscriber::fmt() // Use `let _ =`\n .with_env_filter(env_filter)\n .with_writer(std::io::stderr)\n .with_ansi(true)\n .without_time()\n .try_init(); // Use try_init\n }\n\n let cache = Arc::new(Cache::new(&config).map_err(|e| {\n SpsError::Cache(format!(\n \"Could not initialize cache (ensure 'sps init' was successful): {e}\"\n ))\n })?);\n\n let needs_update_check = matches!(\n cli_args.command,\n Command::Install(_) | Command::Search { .. } | Command::Info { .. } | Command::Upgrade(_)\n );\n\n if needs_update_check {\n if let Err(e) = check_and_run_auto_update(&config, Arc::clone(&cache)).await {\n error!(\"Error during auto-update check: {}\", e); // Use `error!` macro\n }\n } else {\n debug!(\n // Use `debug!` macro\n \"Skipping auto-update check for command: {:?}\",\n cli_args.command\n );\n }\n\n // Pass config and cache to the command's run method\n let command_execution_result = match &cli_args.command {\n Command::Init(_) => {\n /* This case is handled above and main exits */\n unreachable!()\n }\n _ => cli_args.command.run(&config, cache).await,\n };\n\n if let Err(e) = command_execution_result {\n // For pipeline commands (Install, Reinstall, Upgrade), errors are already\n // displayed via the status system, so only log in verbose mode\n let is_pipeline_command = matches!(\n cli_args.command,\n Command::Install(_) | Command::Reinstall(_) | Command::Upgrade(_)\n );\n\n if is_pipeline_command {\n // Only show error details in verbose mode\n if cli_args.verbose > 0 {\n error!(\"Command failed: {:#}\", e);\n eprintln!(\"{}: {:#}\", \"Error\".red().bold(), e);\n }\n } else {\n // For non-pipeline commands, show errors normally\n error!(\"Command failed: {:#}\", e);\n eprintln!(\"{}: {:#}\", \"Error\".red().bold(), e);\n }\n process::exit(1);\n }\n\n debug!(\"Command completed successfully.\"); // Use `debug!` macro\n Ok(())\n}\n\nasync fn check_and_run_auto_update(config: &Config, cache: Arc) -> spResult<()> {\n if env::var(\"SPS_NO_AUTO_UPDATE\").is_ok_and(|v| v == \"1\") {\n debug!(\"Auto-update disabled via SPS_NO_AUTO_UPDATE=1.\");\n return Ok(());\n }\n\n let default_interval_secs: u64 = 86400;\n let update_interval_secs = env::var(\"SPS_AUTO_UPDATE_SECS\")\n .ok()\n .and_then(|s| s.parse::().ok())\n .unwrap_or(default_interval_secs);\n let update_interval = Duration::from_secs(update_interval_secs);\n debug!(\"Auto-update interval: {:?}\", update_interval);\n\n let timestamp_file = config.state_dir().join(\".sps_last_update_check\");\n debug!(\"Checking timestamp file: {}\", timestamp_file.display());\n\n if let Some(parent_dir) = timestamp_file.parent() {\n if !parent_dir.exists() {\n if let Err(e) = fs::create_dir_all(parent_dir) {\n warn!(\"Could not create state directory {} as user: {}. Auto-update might rely on 'sps init' to create this with sudo.\", parent_dir.display(), e);\n }\n }\n }\n\n let mut needs_update = true;\n if timestamp_file.exists() {\n if let Ok(metadata) = fs::metadata(×tamp_file) {\n if let Ok(modified_time) = metadata.modified() {\n match SystemTime::now().duration_since(modified_time) {\n Ok(age) => {\n debug!(\"Time since last update check: {:?}\", age);\n if age < update_interval {\n needs_update = false;\n debug!(\"Auto-update interval not yet passed.\");\n } else {\n debug!(\"Auto-update interval passed.\");\n }\n }\n Err(e) => {\n warn!(\n \"Could not get duration since last update check (system time error?): {}\",\n e\n );\n }\n }\n } else {\n warn!(\n \"Could not read modification time for timestamp file: {}\",\n timestamp_file.display()\n );\n }\n } else {\n debug!(\n \"Timestamp file {} metadata could not be read. Update needed.\",\n timestamp_file.display()\n );\n }\n } else {\n debug!(\n \"Timestamp file not found at {}. Update needed.\",\n timestamp_file.display()\n );\n }\n\n if needs_update {\n println!(\n \"{}{}\",\n \"==> \".bold().blue(),\n \"Running auto-update...\".bold()\n );\n match cli::update::Update.run(config, cache).await {\n Ok(_) => {\n println!(\n \"{}{}\",\n \"==> \".bold().blue(),\n \"Auto-update successful.\".bold()\n );\n match fs::File::create(×tamp_file) {\n Ok(_) => {\n debug!(\"Updated timestamp file: {}\", timestamp_file.display());\n }\n Err(e) => {\n warn!(\n \"Failed to create or update timestamp file '{}': {}\",\n timestamp_file.display(),\n e\n );\n }\n }\n }\n Err(e) => {\n error!(\"Auto-update failed: {}\", e);\n eprintln!(\"{} Auto-update failed: {}\", \"Warning:\".yellow(), e);\n }\n }\n } else {\n debug!(\"Skipping auto-update.\");\n }\n\n Ok(())\n}\n"], ["/sps/sps-core/src/uninstall/cask.rs", "// sps-core/src/uninstall/cask.rs\nuse std::fs;\nuse std::path::{Path, PathBuf};\nuse std::process::{Command, Stdio};\n\nuse lazy_static::lazy_static;\nuse regex::Regex;\n// serde_json is used for CaskInstallManifest deserialization\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::{Cask, ZapActionDetail};\nuse tracing::{debug, error, warn};\nuse trash; // This will be used by trash_path\n\n// Import helpers from the common module within the uninstall scope\nuse super::common::{expand_tilde, is_safe_path, remove_filesystem_artifact};\nuse crate::check::installed::InstalledPackageInfo;\n// Corrected import path if install::cask::helpers is where it lives now\nuse crate::install::cask::helpers::{\n cleanup_empty_parent_dirs_in_private_store,\n remove_path_robustly as remove_path_robustly_from_install_helpers,\n};\nuse crate::install::cask::CaskInstallManifest;\n#[cfg(target_os = \"macos\")]\nuse crate::utils::applescript;\n\nlazy_static! {\n static ref VALID_PKGID_RE: Regex = Regex::new(r\"^[a-zA-Z0-9._-]+$\").unwrap();\n static ref VALID_LABEL_RE: Regex = Regex::new(r\"^[a-zA-Z0-9._-]+$\").unwrap();\n static ref VALID_SCRIPT_PATH_RE: Regex = Regex::new(r\"^[a-zA-Z0-9/._-]+$\").unwrap();\n static ref VALID_SIGNAL_RE: Regex = Regex::new(r\"^[A-Z0-9]+$\").unwrap();\n static ref VALID_BUNDLE_ID_RE: Regex =\n Regex::new(r\"^[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)+$\").unwrap();\n}\n\n/// Performs a \"soft\" uninstall for a Cask.\n/// It processes the `CASK_INSTALL_MANIFEST.json` to remove linked artifacts\n/// and then updates the manifest to mark the cask as not currently installed.\n/// The Cask's versioned directory in the Caskroom is NOT removed.\npub fn uninstall_cask_artifacts(info: &InstalledPackageInfo, config: &Config) -> Result<()> {\n debug!(\n \"Soft uninstalling Cask artifacts for {} version {}\",\n info.name, info.version\n );\n let manifest_path = info.path.join(\"CASK_INSTALL_MANIFEST.json\");\n let mut removal_errors: Vec = Vec::new();\n\n if manifest_path.is_file() {\n debug!(\n \"Processing manifest for soft uninstall: {}\",\n manifest_path.display()\n );\n match fs::read_to_string(&manifest_path) {\n Ok(manifest_str) => match serde_json::from_str::(&manifest_str) {\n Ok(mut manifest) => {\n if !manifest.is_installed {\n debug!(\"Cask {} version {} is already marked as uninstalled in manifest. Nothing to do for soft uninstall.\", info.name, info.version);\n return Ok(());\n }\n\n debug!(\n \"Soft uninstalling {} artifacts listed in manifest for {} {}...\",\n manifest.artifacts.len(),\n info.name,\n info.version\n );\n for artifact in manifest.artifacts.iter().rev() {\n if !process_artifact_uninstall_core(artifact, config, false) {\n removal_errors.push(format!(\"Failed to remove artifact: {artifact:?}\"));\n }\n }\n\n manifest.is_installed = false;\n match fs::File::create(&manifest_path) {\n Ok(file) => {\n let writer = std::io::BufWriter::new(file);\n if let Err(e) = serde_json::to_writer_pretty(writer, &manifest) {\n warn!(\n \"Failed to update manifest {}: {}\",\n manifest_path.display(),\n e\n );\n } else {\n debug!(\n \"Manifest updated successfully for soft uninstall: {}\",\n manifest_path.display()\n );\n }\n }\n Err(e) => {\n warn!(\n \"Failed to open manifest for writing (soft uninstall) at {}: {}\",\n manifest_path.display(),\n e\n );\n }\n }\n }\n Err(e) => warn!(\n \"Failed to parse cask manifest {}: {}. Cannot perform detailed soft uninstall.\",\n manifest_path.display(),\n e\n ),\n },\n Err(e) => warn!(\n \"Failed to read cask manifest {}: {}. Cannot perform detailed soft uninstall.\",\n manifest_path.display(),\n e\n ),\n }\n } else {\n warn!(\n \"No CASK_INSTALL_MANIFEST.json found in {}. Cannot perform detailed soft uninstall for {} {}.\",\n info.path.display(),\n info.name,\n info.version\n );\n }\n\n if removal_errors.is_empty() {\n Ok(())\n } else {\n Err(SpsError::InstallError(format!(\n \"Errors during cask artifact soft removal for {}: {}\",\n info.name,\n removal_errors.join(\"; \")\n )))\n }\n}\n\n/// Performs a \"zap\" uninstall for a Cask, removing files defined in `zap` stanzas\n/// and cleaning up the private store. Also marks the cask as uninstalled in its manifest.\npub async fn zap_cask_artifacts(\n info: &InstalledPackageInfo,\n cask_def: &Cask,\n config: &Config,\n) -> Result<()> {\n debug!(\"Starting ZAP process for cask: {}\", cask_def.token);\n let home = config.home_dir();\n let cask_version_path_in_caskroom = &info.path;\n let mut zap_errors: Vec = Vec::new();\n\n let mut primary_app_name_from_manifest: Option = None;\n let manifest_path = cask_version_path_in_caskroom.join(\"CASK_INSTALL_MANIFEST.json\");\n\n if manifest_path.is_file() {\n match fs::read_to_string(&manifest_path) {\n Ok(manifest_str) => match serde_json::from_str::(&manifest_str) {\n Ok(mut manifest) => {\n primary_app_name_from_manifest = manifest.primary_app_file_name.clone();\n if manifest.is_installed {\n manifest.is_installed = false;\n if let Ok(file) = fs::File::create(&manifest_path) {\n let writer = std::io::BufWriter::new(file);\n if let Err(e) = serde_json::to_writer_pretty(writer, &manifest) {\n warn!(\n \"Failed to update manifest during zap for {}: {}\",\n manifest_path.display(),\n e\n );\n }\n } else {\n warn!(\n \"Failed to open manifest for writing during zap at {}\",\n manifest_path.display()\n );\n }\n }\n }\n Err(e) => warn!(\n \"Failed to parse manifest during zap {}: {}\",\n manifest_path.display(),\n e\n ),\n },\n Err(e) => warn!(\n \"Failed to read manifest during zap {}: {}\",\n manifest_path.display(),\n e\n ),\n }\n } else {\n warn!(\"No manifest found at {} during zap. Private store cleanup might be incomplete if app name changed.\", manifest_path.display());\n }\n\n if !cleanup_private_store(\n &cask_def.token,\n &info.version,\n primary_app_name_from_manifest.as_deref(),\n config,\n ) {\n let msg = format!(\n \"Failed to clean up private store for cask {} version {}\",\n cask_def.token, info.version\n );\n warn!(\"{}\", msg);\n zap_errors.push(msg);\n }\n\n let zap_stanzas = match &cask_def.zap {\n Some(stanzas) => stanzas,\n None => {\n debug!(\"No zap stanza found for cask {}\", cask_def.token);\n // Proceed to Caskroom cleanup even if no specific zap actions\n if !remove_filesystem_artifact(cask_version_path_in_caskroom, true) {\n // use_sudo = true for Caskroom\n if cask_version_path_in_caskroom.exists() {\n zap_errors.push(format!(\n \"Failed to remove Caskroom version directory during zap: {}\",\n cask_version_path_in_caskroom.display()\n ));\n }\n }\n if let Some(parent_token_dir) = cask_version_path_in_caskroom.parent() {\n if parent_token_dir.exists() && parent_token_dir.is_dir() {\n match fs::read_dir(parent_token_dir) {\n Ok(mut entries) => {\n if entries.next().is_none()\n && !remove_filesystem_artifact(parent_token_dir, true)\n && parent_token_dir.exists()\n {\n warn!(\"Failed to remove empty Caskroom token directory during zap: {}\", parent_token_dir.display());\n }\n }\n Err(e) => warn!(\n \"Failed to read Caskroom token dir {} during zap: {}\",\n parent_token_dir.display(),\n e\n ),\n }\n }\n }\n return if zap_errors.is_empty() {\n Ok(())\n } else {\n Err(SpsError::Generic(zap_errors.join(\"; \")))\n };\n }\n };\n\n for stanza_map in zap_stanzas {\n for (action_key, action_detail) in &stanza_map.0 {\n debug!(\n \"Processing zap action: {} = {:?}\",\n action_key, action_detail\n );\n match action_detail {\n ZapActionDetail::Trash(paths) => {\n for path_str in paths {\n let target = expand_tilde(path_str, &home);\n if is_safe_path(&target, &home, config) {\n if !trash_path(&target) {\n // Logged within trash_path\n }\n } else {\n zap_errors\n .push(format!(\"Skipped unsafe trash path {}\", target.display()));\n }\n }\n }\n ZapActionDetail::Delete(paths) | ZapActionDetail::Rmdir(paths) => {\n for path_str in paths {\n let target = expand_tilde(path_str, &home);\n if is_safe_path(&target, &home, config) {\n let use_sudo = target.starts_with(\"/Library\")\n || target.starts_with(\"/Applications\");\n let exists_before =\n target.exists() || target.symlink_metadata().is_ok();\n if exists_before {\n if action_key == \"rmdir\" && !target.is_dir() {\n warn!(\"Zap rmdir target is not a directory: {}. Attempting as file delete.\", target.display());\n }\n if !remove_filesystem_artifact(&target, use_sudo)\n && (target.exists() || target.symlink_metadata().is_ok())\n {\n zap_errors.push(format!(\n \"Failed to {} {}\",\n action_key,\n target.display()\n ));\n }\n } else {\n debug!(\n \"Zap target {} not found, skipping removal.\",\n target.display()\n );\n }\n } else {\n zap_errors.push(format!(\n \"Skipped unsafe {} path {}\",\n action_key,\n target.display()\n ));\n }\n }\n }\n ZapActionDetail::Pkgutil(ids_sv) => {\n for id in ids_sv.clone().into_vec() {\n if !VALID_PKGID_RE.is_match(&id) {\n warn!(\"Invalid pkgutil ID format for zap: '{}'. Skipping.\", id);\n zap_errors.push(format!(\"Invalid pkgutil ID: {id}\"));\n continue;\n }\n if !forget_pkgutil_receipt(&id) {\n // Error logged in helper\n }\n }\n }\n ZapActionDetail::Launchctl(labels_sv) => {\n for label in labels_sv.clone().into_vec() {\n if !VALID_LABEL_RE.is_match(&label) {\n warn!(\n \"Invalid launchctl label format for zap: '{}'. Skipping.\",\n label\n );\n zap_errors.push(format!(\"Invalid launchctl label: {label}\"));\n continue;\n }\n let potential_paths = vec![\n home.join(\"Library/LaunchAgents\")\n .join(format!(\"{label}.plist\")),\n PathBuf::from(\"/Library/LaunchAgents\").join(format!(\"{label}.plist\")),\n PathBuf::from(\"/Library/LaunchDaemons\").join(format!(\"{label}.plist\")),\n ];\n let path_to_try = potential_paths.into_iter().find(|p| p.exists());\n if !unload_and_remove_launchd(&label, path_to_try.as_deref()) {\n // Error logged in helper\n }\n }\n }\n ZapActionDetail::Script { executable, args } => {\n let script_path_str = executable;\n if !VALID_SCRIPT_PATH_RE.is_match(script_path_str) {\n error!(\n \"Zap script path contains invalid characters: '{}'. Skipping.\",\n script_path_str\n );\n zap_errors.push(format!(\"Skipped invalid script path: {script_path_str}\"));\n continue;\n }\n let script_full_path = PathBuf::from(script_path_str);\n if !script_full_path.exists() {\n if !script_full_path.is_absolute() {\n if let Ok(found_path) = which::which(&script_full_path) {\n debug!(\n \"Found zap script {} in PATH: {}\",\n script_full_path.display(),\n found_path.display()\n );\n run_zap_script(\n &found_path,\n args.as_ref().map(|v| v.as_slice()),\n &mut zap_errors,\n );\n } else {\n error!(\n \"Zap script '{}' not found (absolute or in PATH). Skipping.\",\n script_full_path.display()\n );\n zap_errors.push(format!(\n \"Zap script not found: {}\",\n script_full_path.display()\n ));\n }\n } else {\n error!(\n \"Absolute zap script path '{}' not found. Skipping.\",\n script_full_path.display()\n );\n zap_errors.push(format!(\n \"Zap script not found: {}\",\n script_full_path.display()\n ));\n }\n continue;\n }\n run_zap_script(\n &script_full_path,\n args.as_ref().map(|v| v.as_slice()),\n &mut zap_errors,\n );\n }\n ZapActionDetail::Signal(signals) => {\n for signal_spec in signals {\n let parts: Vec<&str> = signal_spec.splitn(2, '/').collect();\n if parts.len() != 2 {\n warn!(\"Invalid signal spec format '{}', expected SIGNAL/bundle.id. Skipping.\", signal_spec);\n zap_errors.push(format!(\"Invalid signal spec: {signal_spec}\"));\n continue;\n }\n let signal = parts[0].trim().to_uppercase();\n let bundle_id_or_pattern = parts[1].trim();\n\n if !VALID_SIGNAL_RE.is_match(&signal) {\n warn!(\n \"Invalid signal name '{}' in spec '{}'. Skipping.\",\n signal, signal_spec\n );\n zap_errors.push(format!(\"Invalid signal name: {signal}\"));\n continue;\n }\n\n debug!(\"Sending signal {} to processes matching ID/pattern '{}' (using pkill -f)\", signal, bundle_id_or_pattern);\n let mut cmd = Command::new(\"pkill\");\n cmd.arg(format!(\"-{signal}\")); // Standard signal format for pkill\n cmd.arg(\"-f\");\n cmd.arg(bundle_id_or_pattern);\n cmd.stdout(Stdio::null()).stderr(Stdio::piped());\n match cmd.status() {\n Ok(status) => {\n if status.success() {\n debug!(\"Successfully sent signal {} via pkill to processes matching '{}'.\", signal, bundle_id_or_pattern);\n } else if status.code() == Some(1) {\n debug!(\"No running processes found matching ID/pattern '{}' for signal {} via pkill.\", bundle_id_or_pattern, signal);\n } else {\n warn!(\"pkill command failed for signal {} / ID/pattern '{}' with status: {}\", signal, bundle_id_or_pattern, status);\n }\n }\n Err(e) => {\n error!(\n \"Failed to execute pkill for signal {} / ID/pattern '{}': {}\",\n signal, bundle_id_or_pattern, e\n );\n zap_errors.push(format!(\"Failed to run pkill for signal {signal}\"));\n }\n }\n }\n }\n }\n }\n }\n\n debug!(\n \"Zap: Removing Caskroom version directory: {}\",\n cask_version_path_in_caskroom.display()\n );\n if !remove_filesystem_artifact(cask_version_path_in_caskroom, true)\n && cask_version_path_in_caskroom.exists()\n {\n let msg = format!(\n \"Failed to remove Caskroom version directory during zap: {}\",\n cask_version_path_in_caskroom.display()\n );\n error!(\"{}\", msg);\n zap_errors.push(msg);\n }\n\n if let Some(parent_token_dir) = cask_version_path_in_caskroom.parent() {\n if parent_token_dir.exists() && parent_token_dir.is_dir() {\n match fs::read_dir(parent_token_dir) {\n Ok(mut entries) => {\n if entries.next().is_none() {\n debug!(\n \"Zap: Removing empty Caskroom token directory: {}\",\n parent_token_dir.display()\n );\n if !remove_filesystem_artifact(parent_token_dir, true)\n && parent_token_dir.exists()\n {\n warn!(\n \"Failed to remove empty Caskroom token directory during zap: {}\",\n parent_token_dir.display()\n );\n }\n }\n }\n Err(e) => warn!(\n \"Failed to read Caskroom token directory {} during zap cleanup: {}\",\n parent_token_dir.display(),\n e\n ),\n }\n }\n }\n\n if zap_errors.is_empty() {\n debug!(\n \"Zap process completed successfully for cask: {}\",\n cask_def.token\n );\n Ok(())\n } else {\n error!(\n \"Zap process for {} completed with errors: {}\",\n cask_def.token,\n zap_errors.join(\"; \")\n );\n Err(SpsError::InstallError(format!(\n \"Zap for {} failed with errors: {}\",\n cask_def.token,\n zap_errors.join(\"; \")\n )))\n }\n}\n\nfn process_artifact_uninstall_core(\n artifact: &InstalledArtifact,\n config: &Config,\n use_sudo_for_zap: bool,\n) -> bool {\n debug!(\"Processing artifact removal: {:?}\", artifact);\n match artifact {\n InstalledArtifact::AppBundle { path } => {\n debug!(\"Uninstall: Removing AppBundle at {}\", path.display());\n match path.symlink_metadata() {\n Ok(metadata) if metadata.file_type().is_symlink() => {\n debug!(\"AppBundle at {} is a symlink; unlinking.\", path.display());\n match std::fs::remove_file(path) {\n Ok(_) => true,\n Err(e) => {\n warn!(\"Failed to unlink symlink at {}: {}\", path.display(), e);\n false\n }\n }\n }\n Ok(metadata) if metadata.file_type().is_dir() => {\n #[cfg(target_os = \"macos\")]\n {\n if path.exists() {\n if let Err(e) = applescript::quit_app_gracefully(path) {\n warn!(\n \"Attempt to gracefully quit app at {} failed: {} (proceeding)\",\n path.display(),\n e\n );\n }\n } else {\n debug!(\n \"App bundle at {} does not exist, skipping quit.\",\n path.display()\n );\n }\n }\n let use_sudo = path.starts_with(config.applications_dir())\n || path.starts_with(\"/Applications\")\n || use_sudo_for_zap;\n remove_filesystem_artifact(path, use_sudo)\n }\n Ok(_) | Err(_) => {\n let use_sudo = path.starts_with(config.applications_dir())\n || path.starts_with(\"/Applications\")\n || use_sudo_for_zap;\n remove_filesystem_artifact(path, use_sudo)\n }\n }\n }\n InstalledArtifact::BinaryLink { link_path, .. }\n | InstalledArtifact::ManpageLink { link_path, .. }\n | InstalledArtifact::CaskroomLink { link_path, .. } => {\n debug!(\"Uninstall: Removing link at {}\", link_path.display());\n remove_filesystem_artifact(link_path, use_sudo_for_zap)\n }\n InstalledArtifact::PkgUtilReceipt { id } => {\n debug!(\"Uninstall: Forgetting PkgUtilReceipt {}\", id);\n forget_pkgutil_receipt(id)\n }\n InstalledArtifact::Launchd { label, path } => {\n debug!(\"Uninstall: Unloading Launchd {} (path: {:?})\", label, path);\n unload_and_remove_launchd(label, path.as_deref())\n }\n InstalledArtifact::MovedResource { path } => {\n debug!(\"Uninstall: Removing MovedResource at {}\", path.display());\n remove_filesystem_artifact(path, use_sudo_for_zap)\n }\n InstalledArtifact::CaskroomReference { path } => {\n debug!(\n \"Uninstall: Removing CaskroomReference at {}\",\n path.display()\n );\n remove_filesystem_artifact(path, use_sudo_for_zap)\n }\n }\n}\n\nfn forget_pkgutil_receipt(id: &str) -> bool {\n if !VALID_PKGID_RE.is_match(id) {\n error!(\"Invalid pkgutil ID format: '{}'. Skipping forget.\", id);\n return false;\n }\n debug!(\"Forgetting package receipt (requires sudo): {}\", id);\n let output = Command::new(\"sudo\")\n .arg(\"pkgutil\")\n .arg(\"--forget\")\n .arg(id)\n .output();\n match output {\n Ok(out) if out.status.success() => {\n debug!(\"Successfully forgot package receipt {}\", id);\n true\n }\n Ok(out) => {\n let stderr = String::from_utf8_lossy(&out.stderr);\n if !stderr.contains(\"No receipt for\") && !stderr.trim().is_empty() {\n error!(\"Failed to forget package receipt {}: {}\", id, stderr.trim());\n // Return false if pkgutil fails for a reason other than \"No receipt\"\n return false;\n } else {\n debug!(\"Package receipt {} already forgotten or never existed.\", id);\n }\n true\n }\n Err(e) => {\n error!(\"Failed to execute sudo pkgutil --forget {}: {}\", id, e);\n false\n }\n }\n}\n\nfn unload_and_remove_launchd(label: &str, path: Option<&Path>) -> bool {\n if !VALID_LABEL_RE.is_match(label) {\n error!(\n \"Invalid launchd label format: '{}'. Skipping unload/remove.\",\n label\n );\n return false;\n }\n debug!(\"Unloading launchd service (if loaded): {}\", label);\n let unload_output = Command::new(\"launchctl\")\n .arg(\"unload\")\n .arg(\"-w\")\n .arg(label)\n .stderr(Stdio::piped())\n .output();\n\n let mut unload_successful_or_not_loaded = false;\n match unload_output {\n Ok(out) if out.status.success() => {\n debug!(\"Successfully unloaded launchd service {}\", label);\n unload_successful_or_not_loaded = true;\n }\n Ok(out) => {\n let stderr = String::from_utf8_lossy(&out.stderr);\n if stderr.contains(\"Could not find specified service\")\n || stderr.contains(\"service is not loaded\")\n || stderr.trim().is_empty()\n {\n debug!(\"Launchd service {} already unloaded or not found.\", label);\n unload_successful_or_not_loaded = true;\n } else {\n warn!(\n \"launchctl unload {} failed (but proceeding with plist removal attempt): {}\",\n label,\n stderr.trim()\n );\n // Proceed to try plist removal even if unload reports other errors\n }\n }\n Err(e) => {\n warn!(\"Failed to execute launchctl unload {} (but proceeding with plist removal attempt): {}\", label, e);\n }\n }\n\n if let Some(plist_path) = path {\n if plist_path.exists() {\n debug!(\"Removing launchd plist file: {}\", plist_path.display());\n let use_sudo = plist_path.starts_with(\"/Library/LaunchDaemons\")\n || plist_path.starts_with(\"/Library/LaunchAgents\");\n if !remove_filesystem_artifact(plist_path, use_sudo) {\n warn!(\"Failed to remove launchd plist: {}\", plist_path.display());\n return false; // If plist removal fails, consider the operation failed\n }\n } else {\n debug!(\n \"Launchd plist path {} does not exist, skip removal.\",\n plist_path.display()\n );\n }\n } else {\n debug!(\n \"No path provided for launchd plist removal for label {}\",\n label\n );\n }\n unload_successful_or_not_loaded // Success depends on unload and optional plist removal\n}\n\nfn trash_path(path: &Path) -> bool {\n if !path.exists() && path.symlink_metadata().is_err() {\n debug!(\"Path for trashing not found: {}\", path.display());\n return true;\n }\n match trash::delete(path) {\n Ok(_) => {\n debug!(\"Trashed: {}\", path.display());\n true\n }\n Err(e) => {\n warn!(\"Failed to trash {} (proceeding anyway): {}. This might require manual cleanup or installing a 'trash' utility.\", path.display(), e);\n true\n }\n }\n}\n\n/// Helper for zap scripts.\nfn run_zap_script(script_path: &Path, args: Option<&[String]>, errors: &mut Vec) {\n debug!(\n \"Running zap script: {} with args {:?}\",\n script_path.display(),\n args.unwrap_or_default()\n );\n let mut cmd = Command::new(script_path);\n if let Some(script_args) = args {\n cmd.args(script_args);\n }\n cmd.stdout(Stdio::piped()).stderr(Stdio::piped());\n\n match cmd.output() {\n Ok(output) => {\n log_command_output(\n \"Zap script\",\n &script_path.display().to_string(),\n &output,\n errors,\n );\n }\n Err(e) => {\n let msg = format!(\n \"Failed to execute zap script '{}': {}\",\n script_path.display(),\n e\n );\n error!(\"{}\", msg);\n errors.push(msg);\n }\n }\n}\n\n/// Logs the output of a command and adds to error list if it failed.\nfn log_command_output(\n context: &str,\n command_str: &str,\n output: &std::process::Output,\n errors: &mut Vec,\n) {\n let stdout = String::from_utf8_lossy(&output.stdout);\n let stderr = String::from_utf8_lossy(&output.stderr);\n if !output.status.success() {\n error!(\n \"{} '{}' failed with status {}: {}\",\n context,\n command_str,\n output.status,\n stderr.trim()\n );\n if !stdout.trim().is_empty() {\n error!(\"{} stdout: {}\", context, stdout.trim());\n }\n errors.push(format!(\"{context} '{command_str}' failed\"));\n } else {\n debug!(\"{} '{}' executed successfully.\", context, command_str);\n if !stdout.trim().is_empty() {\n debug!(\"{} stdout: {}\", context, stdout.trim());\n }\n if !stderr.trim().is_empty() {\n debug!(\"{} stderr: {}\", context, stderr.trim());\n }\n }\n}\n\n// Helper function specifically for cleaning up the private store.\n// This was originally inside zap_cask_artifacts.\nfn cleanup_private_store(\n cask_token: &str,\n version: &str,\n app_name: Option<&str>, // The actual .app name, not the token\n config: &Config,\n) -> bool {\n debug!(\n \"Cleaning up private store for cask {} version {}\",\n cask_token, version\n );\n\n let private_version_dir = config.cask_store_version_path(cask_token, version);\n\n if let Some(app) = app_name {\n let app_path_in_private_store = private_version_dir.join(app);\n if app_path_in_private_store.exists()\n || app_path_in_private_store.symlink_metadata().is_ok()\n {\n debug!(\n \"Removing app from private store: {}\",\n app_path_in_private_store.display()\n );\n // Use the helper from install::cask::helpers, assuming it's correctly located and\n // public\n if !remove_path_robustly_from_install_helpers(&app_path_in_private_store, config, false)\n {\n // use_sudo=false for private store\n warn!(\n \"Failed to remove app from private store: {}\",\n app_path_in_private_store.display()\n );\n // Potentially return false or collect errors, depending on desired strictness\n }\n }\n }\n\n // After attempting to remove specific app, remove the version directory if it exists\n // This also handles cases where app_name was None.\n if private_version_dir.exists() {\n debug!(\n \"Removing private store version directory: {}\",\n private_version_dir.display()\n );\n match fs::remove_dir_all(&private_version_dir) {\n Ok(_) => debug!(\n \"Successfully removed private store version directory {}\",\n private_version_dir.display()\n ),\n Err(e) => {\n warn!(\n \"Failed to remove private store version directory {}: {}\",\n private_version_dir.display(),\n e\n );\n return false; // If the version dir removal fails, consider it a failure\n }\n }\n }\n\n // Clean up empty parent token directory.\n cleanup_empty_parent_dirs_in_private_store(\n &private_version_dir, // Start from the version dir (or its parent if it was just removed)\n &config.cask_store_dir(),\n );\n\n true\n}\n"], ["/sps/sps/src/cli/uninstall.rs", "use std::collections::{HashMap, HashSet};\nuse std::sync::Arc;\n\nuse clap::Args;\nuse colored::Colorize;\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::cask::Cask;\nuse sps_common::Cache;\nuse sps_core::check::{installed, PackageType};\nuse sps_core::{uninstall as core_uninstall, UninstallOptions};\nuse sps_net::api;\nuse tracing::{debug, error, warn};\nuse {serde_json, walkdir};\n\n#[derive(Args, Debug)]\npub struct Uninstall {\n /// The names of the formulas or casks to uninstall\n #[arg(required = true)] // Ensure at least one name is given\n pub names: Vec,\n /// Perform a deep clean for casks, removing associated user data, caches,\n /// and configuration files. Use with caution, data will be lost! Ignored for formulas.\n #[arg(\n long,\n help = \"Perform a deep clean for casks, removing associated user data, caches, and configuration files. Use with caution!\"\n )]\n pub zap: bool,\n}\n\nimpl Uninstall {\n pub async fn run(&self, config: &Config, cache: Arc) -> Result<()> {\n let names = &self.names;\n let mut errors: Vec<(String, SpsError)> = Vec::new();\n\n for name in names {\n // Basic name validation to prevent path traversal\n if name.contains('/') || name.contains(\"..\") {\n let msg = format!(\"Invalid package name '{name}' contains disallowed characters\");\n error!(\"✖ {msg}\");\n errors.push((name.to_string(), SpsError::Generic(msg)));\n continue;\n }\n\n println!(\"Uninstalling {name}...\");\n\n match installed::get_installed_package(name, config).await {\n Ok(Some(installed_info)) => {\n let (file_count, size_bytes) =\n count_files_and_size(&installed_info.path).unwrap_or((0, 0));\n let uninstall_opts = UninstallOptions { skip_zap: false };\n debug!(\n \"Attempting uninstall for {} ({:?})\",\n name, installed_info.pkg_type\n );\n let uninstall_result = match installed_info.pkg_type {\n PackageType::Formula => {\n if self.zap {\n warn!(\"--zap flag is ignored for formulas like '{}'.\", name);\n }\n core_uninstall::uninstall_formula_artifacts(\n &installed_info,\n config,\n &uninstall_opts,\n )\n }\n PackageType::Cask => {\n core_uninstall::uninstall_cask_artifacts(&installed_info, config)\n }\n };\n\n if let Err(e) = uninstall_result {\n error!(\"✖ Failed to uninstall '{}': {}\", name.cyan(), e);\n errors.push((name.to_string(), e));\n // Continue to zap anyway for casks, as per plan\n } else {\n println!(\n \"✓ Uninstalled {:?} {} ({} files, {})\",\n installed_info.pkg_type,\n name.green(),\n file_count,\n format_size(size_bytes)\n );\n }\n\n // --- Zap Uninstall (Conditional) ---\n if self.zap && installed_info.pkg_type == PackageType::Cask {\n println!(\"Zapping {name}...\");\n debug!(\n \"--zap specified for cask '{}', attempting deep clean.\",\n name\n );\n\n // Fetch the Cask definition (needed for the zap stanza)\n let cask_def_result: Result = async {\n match api::get_cask(name).await {\n Ok(cask) => Ok(cask),\n Err(e) => {\n warn!(\"Failed API fetch for zap definition for '{}' ({}), trying cache...\", name, e);\n match cache.load_raw(\"cask.json\") {\n Ok(raw_json) => {\n let casks: Vec = serde_json::from_str(&raw_json)\n .map_err(|cache_e| SpsError::Cache(format!(\"Failed parse cached cask.json: {cache_e}\")))?;\n casks.into_iter()\n .find(|c| c.token == *name)\n .ok_or_else(|| SpsError::NotFound(format!(\"Cask '{name}' def not in cache either\")))\n }\n Err(cache_e) => Err(SpsError::Cache(format!(\"Failed load cask cache for zap: {cache_e}\"))),\n }\n }\n }\n }.await;\n\n match cask_def_result {\n Ok(cask_def) => {\n match core_uninstall::zap_cask_artifacts(\n &installed_info,\n &cask_def,\n config,\n )\n .await\n {\n Ok(_) => {\n println!(\"✓ Zap complete for {}\", name.green());\n }\n Err(zap_err) => {\n error!(\"✖ Zap failed for '{}': {}\", name.cyan(), zap_err);\n errors.push((format!(\"{name} (zap)\"), zap_err));\n }\n }\n }\n Err(e) => {\n error!(\n \"✖ Could not get Cask definition for zap '{}': {}\",\n name.cyan(),\n e\n );\n errors.push((format!(\"{name} (zap definition)\"), e));\n }\n }\n }\n }\n Ok(None) => {\n let msg = format!(\"Package '{name}' is not installed.\");\n error!(\"✖ {msg}\");\n errors.push((name.to_string(), SpsError::NotFound(msg)));\n }\n Err(e) => {\n let msg = format!(\"Failed check install status for '{name}': {e}\");\n error!(\"✖ {msg}\");\n errors.push((name.clone(), SpsError::Generic(msg)));\n }\n }\n }\n\n if errors.is_empty() {\n Ok(())\n } else {\n eprintln!(\"\\n{}:\", \"Finished uninstalling with errors\".yellow());\n let mut errors_by_pkg: HashMap> = HashMap::new();\n for (pkg_name, error) in errors {\n errors_by_pkg\n .entry(pkg_name)\n .or_default()\n .push(error.to_string());\n }\n for (pkg_name, error_list) in errors_by_pkg {\n eprintln!(\"Package '{}':\", pkg_name.cyan());\n let unique_errors: HashSet<_> = error_list.into_iter().collect();\n for error_str in unique_errors {\n eprintln!(\"- {}\", error_str.red());\n }\n }\n Err(SpsError::Generic(\n \"Uninstall failed for one or more packages.\".to_string(),\n ))\n }\n }\n}\n\n// --- Unchanged Helper Functions ---\nfn count_files_and_size(path: &std::path::Path) -> Result<(usize, u64)> {\n let mut file_count = 0;\n let mut total_size = 0;\n for entry in walkdir::WalkDir::new(path) {\n match entry {\n Ok(entry_data) => {\n if entry_data.file_type().is_file() || entry_data.file_type().is_symlink() {\n match entry_data.metadata() {\n Ok(metadata) => {\n file_count += 1;\n if entry_data.file_type().is_file() {\n total_size += metadata.len();\n }\n }\n Err(e) => {\n tracing::warn!(\n \"Could not get metadata for {}: {}\",\n entry_data.path().display(),\n e\n );\n }\n }\n }\n }\n Err(e) => {\n tracing::warn!(\"Error traversing directory {}: {}\", path.display(), e);\n }\n }\n }\n Ok((file_count, total_size))\n}\n\nfn format_size(size: u64) -> String {\n const KB: u64 = 1024;\n const MB: u64 = KB * 1024;\n const GB: u64 = MB * 1024;\n if size >= GB {\n format!(\"{:.1}GB\", size as f64 / GB as f64)\n } else if size >= MB {\n format!(\"{:.1}MB\", size as f64 / MB as f64)\n } else if size >= KB {\n format!(\"{:.1}KB\", size as f64 / KB as f64)\n } else {\n format!(\"{size}B\")\n }\n}\n"], ["/sps/sps-common/src/keg.rs", "// sps-common/src/keg.rs\nuse std::fs;\nuse std::path::PathBuf;\n\n// Corrected tracing imports: added error, removed unused debug\nuse tracing::{debug, error, warn};\n\nuse super::config::Config;\nuse super::error::{Result, SpsError};\n\n/// Represents information about an installed package (Keg).\n#[derive(Debug, Clone, PartialEq, Eq)]\npub struct InstalledKeg {\n pub name: String,\n pub version_str: String,\n pub path: PathBuf,\n}\n\n/// Manages querying installed packages in the Cellar.\n#[derive(Debug)]\npub struct KegRegistry {\n config: Config,\n}\n\nimpl KegRegistry {\n pub fn new(config: Config) -> Self {\n Self { config }\n }\n\n fn formula_cellar_path(&self, name: &str) -> PathBuf {\n self.config.cellar_dir().join(name)\n }\n\n pub fn get_opt_path(&self, name: &str) -> PathBuf {\n self.config.opt_dir().join(name)\n }\n\n pub fn get_installed_keg(&self, name: &str) -> Result> {\n let formula_dir = self.formula_cellar_path(name);\n debug!(\n \"[KEG_REGISTRY:{}] get_installed_keg: Checking for formula '{}'. Path to check: {}\",\n name,\n name,\n formula_dir.display()\n );\n\n if !formula_dir.is_dir() {\n debug!(\"[KEG_REGISTRY:{}] get_installed_keg: Formula directory '{}' NOT FOUND or not a directory. Returning None.\", name, formula_dir.display());\n return Ok(None);\n }\n\n let mut latest_keg: Option = None;\n debug!(\n \"[KEG_REGISTRY:{}] get_installed_keg: Reading entries in formula directory '{}'\",\n name,\n formula_dir.display()\n );\n\n match fs::read_dir(&formula_dir) {\n Ok(entries) => {\n for entry_result in entries {\n match entry_result {\n Ok(entry) => {\n let path = entry.path();\n debug!(\n \"[KEG_REGISTRY:{}] get_installed_keg: Examining entry '{}'\",\n name,\n path.display()\n );\n\n if path.is_dir() {\n if let Some(version_str_full) =\n path.file_name().and_then(|n| n.to_str())\n {\n debug!(\"[KEG_REGISTRY:{}] get_installed_keg: Entry is a directory with name: {}\", name, version_str_full);\n\n let current_keg_candidate = InstalledKeg {\n name: name.to_string(),\n version_str: version_str_full.to_string(),\n path: path.clone(),\n };\n\n match latest_keg {\n Some(ref current_latest) => {\n // Compare &str with &str\n if version_str_full\n > current_latest.version_str.as_str()\n {\n debug!(\"[KEG_REGISTRY:{}] get_installed_keg: Updating latest keg (lexicographical) to: {}\", name, path.display());\n latest_keg = Some(current_keg_candidate);\n }\n }\n None => {\n debug!(\"[KEG_REGISTRY:{}] get_installed_keg: Setting first found keg as latest: {}\", name, path.display());\n latest_keg = Some(current_keg_candidate);\n }\n }\n } else {\n debug!(\"[KEG_REGISTRY:{}] get_installed_keg: Could not get filename as string for path '{}'\", name, path.display());\n }\n } else {\n debug!(\"[KEG_REGISTRY:{}] get_installed_keg: Entry '{}' is not a directory.\", name, path.display());\n }\n }\n Err(e) => {\n warn!(\"[KEG_REGISTRY:{}] get_installed_keg: Error reading a directory entry in '{}': {}. Skipping entry.\", name, formula_dir.display(), e);\n }\n }\n }\n }\n Err(e) => {\n // Corrected macro usage\n error!(\"[KEG_REGISTRY:{}] get_installed_keg: Failed to read_dir for formula directory '{}' (error: {}). Returning error.\", name, formula_dir.display(), e);\n return Err(SpsError::Io(std::sync::Arc::new(e)));\n }\n }\n\n if let Some(keg) = &latest_keg {\n // Corrected format string arguments\n debug!(\"[KEG_REGISTRY:{}] get_installed_keg: For formula '{}', latest keg found: path={}, version_str={}\", name, name, keg.path.display(), keg.version_str);\n } else {\n // Corrected format string arguments\n debug!(\"[KEG_REGISTRY:{}] get_installed_keg: For formula '{}', no installable keg version found in directory '{}'.\", name, name, formula_dir.display());\n }\n Ok(latest_keg)\n }\n\n pub fn list_installed_kegs(&self) -> Result> {\n let mut installed_kegs = Vec::new();\n let cellar_dir = self.cellar_path();\n debug!(\n \"[KEG_REGISTRY] list_installed_kegs: Scanning cellar: {}\",\n cellar_dir.display()\n );\n\n if !cellar_dir.is_dir() {\n debug!(\"[KEG_REGISTRY] list_installed_kegs: Cellar directory NOT FOUND. Returning empty list.\");\n return Ok(installed_kegs);\n }\n\n for formula_entry_res in fs::read_dir(cellar_dir)? {\n let formula_entry = match formula_entry_res {\n Ok(fe) => fe,\n Err(e) => {\n warn!(\"[KEG_REGISTRY] list_installed_kegs: Error reading entry in cellar: {}. Skipping.\", e);\n continue;\n }\n };\n let formula_path = formula_entry.path();\n debug!(\n \"[KEG_REGISTRY] list_installed_kegs: Examining formula path: {}\",\n formula_path.display()\n );\n\n if formula_path.is_dir() {\n if let Some(formula_name) = formula_path.file_name().and_then(|n| n.to_str()) {\n debug!(\n \"[KEG_REGISTRY] list_installed_kegs: Found formula directory: {}\",\n formula_name\n );\n match fs::read_dir(&formula_path) {\n Ok(version_entries) => {\n for version_entry_res in version_entries {\n let version_entry = match version_entry_res {\n Ok(ve) => ve,\n Err(e) => {\n warn!(\"[KEG_REGISTRY:{}] list_installed_kegs: Error reading version entry in '{}': {}. Skipping.\", formula_name, formula_path.display(), e);\n continue;\n }\n };\n let version_path = version_entry.path();\n debug!(\"[KEG_REGISTRY:{}] list_installed_kegs: Examining version path: {}\", formula_name, version_path.display());\n\n if version_path.is_dir() {\n if let Some(version_str_full) =\n version_path.file_name().and_then(|n| n.to_str())\n {\n debug!(\"[KEG_REGISTRY:{}] list_installed_kegs: Found version directory '{}' with name: {}\", formula_name, version_path.display(), version_str_full);\n installed_kegs.push(InstalledKeg {\n name: formula_name.to_string(),\n version_str: version_str_full.to_string(),\n path: version_path.clone(),\n });\n } else {\n debug!(\"[KEG_REGISTRY:{}] list_installed_kegs: Could not get filename for version path {}\", formula_name, version_path.display());\n }\n } else {\n debug!(\"[KEG_REGISTRY:{}] list_installed_kegs: Version path {} is not a directory.\", formula_name, version_path.display());\n }\n }\n }\n Err(e) => {\n warn!(\"[KEG_REGISTRY:{}] list_installed_kegs: Failed to read_dir for formula versions in '{}': {}.\", formula_name, formula_path.display(), e);\n }\n }\n } else {\n debug!(\"[KEG_REGISTRY] list_installed_kegs: Could not get filename for formula path {}\", formula_path.display());\n }\n } else {\n debug!(\n \"[KEG_REGISTRY] list_installed_kegs: Formula path {} is not a directory.\",\n formula_path.display()\n );\n }\n }\n debug!(\n \"[KEG_REGISTRY] list_installed_kegs: Found {} total installed keg versions.\",\n installed_kegs.len()\n );\n Ok(installed_kegs)\n }\n\n pub fn cellar_path(&self) -> PathBuf {\n self.config.cellar_dir()\n }\n\n pub fn get_keg_path(&self, name: &str, version_str_raw: &str) -> PathBuf {\n self.formula_cellar_path(name).join(version_str_raw)\n }\n}\n"], ["/sps/sps-core/src/install/extract.rs", "// Path: sps-core/src/install/extract.rs\nuse std::collections::HashSet;\nuse std::fs::{self, File};\nuse std::io::{self, Read, Seek};\nuse std::path::{Component, Path, PathBuf};\nuse std::process::Command;\n\nuse bzip2::read::BzDecoder;\nuse flate2::read::GzDecoder;\nuse sps_common::error::{Result, SpsError};\nuse tar::{Archive, EntryType};\nuse tracing::{debug, error, warn};\nuse zip::ZipArchive;\n\n#[cfg(target_os = \"macos\")]\nuse crate::utils::xattr;\n\npub(crate) fn infer_archive_root_dir(\n archive_path: &Path,\n archive_type: &str,\n) -> Result> {\n tracing::debug!(\n \"Inferring root directory for archive: {}\",\n archive_path.display()\n );\n let file = File::open(archive_path).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed to open archive {}: {}\", archive_path.display(), e),\n )))\n })?;\n\n match archive_type {\n \"zip\" => infer_zip_root(file, archive_path),\n \"gz\" | \"tgz\" => {\n let decompressed = GzDecoder::new(file);\n infer_tar_root(decompressed, archive_path)\n }\n \"bz2\" | \"tbz\" | \"tbz2\" => {\n let decompressed = BzDecoder::new(file);\n infer_tar_root(decompressed, archive_path)\n }\n \"xz\" | \"txz\" => {\n // Use external xz command to decompress, then read as tar\n infer_xz_tar_root(archive_path)\n }\n \"tar\" => infer_tar_root(file, archive_path),\n _ => Err(SpsError::Generic(format!(\n \"Cannot infer root dir for unsupported archive type '{}' in {}\",\n archive_type,\n archive_path.display()\n ))),\n }\n}\n\nfn infer_tar_root(reader: R, archive_path_for_log: &Path) -> Result> {\n let mut archive = Archive::new(reader);\n let mut unique_roots = HashSet::new();\n let mut non_empty_entry_found = false;\n let mut first_component_name: Option = None;\n\n for entry_result in archive.entries()? {\n let entry = entry_result.map_err(|e| {\n SpsError::Generic(format!(\n \"Error reading TAR entry from {}: {}\",\n archive_path_for_log.display(),\n e\n ))\n })?;\n let path = entry\n .path()\n .map_err(|e| {\n SpsError::Generic(format!(\n \"Invalid path in TAR entry from {}: {}\",\n archive_path_for_log.display(),\n e\n ))\n })?\n .into_owned();\n\n if path.components().next().is_none() {\n continue;\n }\n\n if let Some(first_comp) = path.components().next() {\n if let Component::Normal(name) = first_comp {\n non_empty_entry_found = true;\n let current_root = PathBuf::from(name);\n if first_component_name.is_none() {\n first_component_name = Some(current_root.clone());\n }\n unique_roots.insert(current_root);\n\n if unique_roots.len() > 1 {\n tracing::debug!(\n \"Multiple top-level items found in TAR {}, cannot infer single root.\",\n archive_path_for_log.display()\n );\n return Ok(None);\n }\n } else {\n tracing::debug!(\n \"Non-standard top-level component ({:?}) found in TAR {}, cannot infer single root.\",\n first_comp,\n archive_path_for_log.display()\n );\n return Ok(None);\n }\n } else {\n tracing::debug!(\n \"Empty or unusual path found in TAR {}, cannot infer single root.\",\n archive_path_for_log.display()\n );\n return Ok(None);\n }\n }\n\n if unique_roots.len() == 1 && non_empty_entry_found {\n let inferred_root = first_component_name.unwrap();\n tracing::debug!(\n \"Inferred single root directory in TAR {}: {}\",\n archive_path_for_log.display(),\n inferred_root.display()\n );\n Ok(Some(inferred_root))\n } else if !non_empty_entry_found {\n tracing::warn!(\n \"TAR archive {} appears to be empty or contain only metadata.\",\n archive_path_for_log.display()\n );\n Ok(None)\n } else {\n tracing::debug!(\n \"No single common root directory found in TAR {}. unique_roots count: {}\",\n archive_path_for_log.display(),\n unique_roots.len()\n );\n Ok(None)\n }\n}\n\nfn infer_xz_tar_root(archive_path: &Path) -> Result> {\n // Create a temporary file for decompressed content\n let temp_file =\n tempfile::NamedTempFile::new().map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n\n // Use external xz command to decompress\n let output = Command::new(\"xz\")\n .args([\"-dc\", archive_path.to_str().unwrap()])\n .output()\n .map_err(|e| {\n SpsError::Generic(format!(\n \"Failed to run xz command for decompression: {e}. Make sure xz is installed.\"\n ))\n })?;\n\n if !output.status.success() {\n return Err(SpsError::Generic(format!(\n \"xz decompression failed: {}\",\n String::from_utf8_lossy(&output.stderr)\n )));\n }\n\n // Write decompressed data to temp file\n std::fs::write(temp_file.path(), &output.stdout)\n .map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n\n // Read as tar\n let file = File::open(temp_file.path()).map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n infer_tar_root(file, archive_path)\n}\n\nfn infer_zip_root(reader: R, archive_path: &Path) -> Result> {\n let mut archive = ZipArchive::new(reader).map_err(|e| {\n SpsError::Generic(format!(\n \"Failed to open ZIP archive {}: {}\",\n archive_path.display(),\n e\n ))\n })?;\n\n let mut root_candidates = HashSet::new();\n\n for i in 0..archive.len() {\n let file = archive\n .by_index(i)\n .map_err(|e| SpsError::Generic(format!(\"Failed to read ZIP entry {i}: {e}\")))?;\n\n if let Some(enclosed_name) = file.enclosed_name() {\n if let Some(Component::Normal(name)) = enclosed_name.components().next() {\n root_candidates.insert(name.to_string_lossy().to_string());\n }\n }\n }\n\n if root_candidates.len() == 1 {\n let root = root_candidates.into_iter().next().unwrap();\n Ok(Some(PathBuf::from(root)))\n } else {\n Ok(None)\n }\n}\n\n#[cfg(target_os = \"macos\")]\npub fn quarantine_extracted_apps_in_stage(stage_dir: &Path, agent_name: &str) -> Result<()> {\n use std::fs;\n\n use tracing::{debug, warn};\n debug!(\n \"Searching for .app bundles in {} to apply quarantine.\",\n stage_dir.display()\n );\n if stage_dir.is_dir() {\n for entry_result in fs::read_dir(stage_dir)? {\n let entry = entry_result?;\n let entry_path = entry.path();\n if entry_path.is_dir() && entry_path.extension().is_some_and(|ext| ext == \"app\") {\n debug!(\n \"Found app bundle in stage: {}. Applying quarantine.\",\n entry_path.display()\n );\n if let Err(e) = xattr::set_quarantine_attribute(&entry_path, agent_name) {\n warn!(\n \"Failed to set quarantine attribute on staged app {}: {}. Installation will continue.\",\n entry_path.display(),\n e\n );\n }\n }\n }\n }\n Ok(())\n}\n\npub fn extract_archive(\n archive_path: &Path,\n target_dir: &Path,\n strip_components: usize,\n archive_type: &str,\n) -> Result<()> {\n debug!(\n \"Extracting archive '{}' (type: {}) to '{}' (strip_components={}) using native Rust crates.\",\n archive_path.display(),\n archive_type,\n target_dir.display(),\n strip_components\n );\n\n fs::create_dir_all(target_dir).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\n \"Failed to create target directory {}: {}\",\n target_dir.display(),\n e\n ),\n )))\n })?;\n\n let file = File::open(archive_path).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed to open archive {}: {}\", archive_path.display(), e),\n )))\n })?;\n\n let result = match archive_type {\n \"zip\" => extract_zip_archive(file, target_dir, strip_components, archive_path),\n \"gz\" | \"tgz\" => {\n let tar = GzDecoder::new(file);\n extract_tar_archive(tar, target_dir, strip_components, archive_path)\n }\n \"bz2\" | \"tbz\" | \"tbz2\" => {\n let tar = BzDecoder::new(file);\n extract_tar_archive(tar, target_dir, strip_components, archive_path)\n }\n \"xz\" | \"txz\" => extract_xz_tar_archive(archive_path, target_dir, strip_components),\n \"tar\" => extract_tar_archive(file, target_dir, strip_components, archive_path),\n _ => Err(SpsError::Generic(format!(\n \"Unsupported archive type provided for extraction: '{}' for file {}\",\n archive_type,\n archive_path.display()\n ))),\n };\n #[cfg(target_os = \"macos\")]\n {\n if result.is_ok() {\n // Only quarantine if main extraction was successful\n if let Err(e) = quarantine_extracted_apps_in_stage(target_dir, \"sps-extractor\") {\n tracing::warn!(\n \"Error during post-extraction quarantine scan for {}: {}\",\n archive_path.display(),\n e\n );\n }\n }\n }\n result\n}\n\n/// Represents a hardlink operation that was deferred.\nfn extract_xz_tar_archive(\n archive_path: &Path,\n target_dir: &Path,\n strip_components: usize,\n) -> Result<()> {\n debug!(\n \"Extracting XZ+TAR archive using external xz command: {}\",\n archive_path.display()\n );\n\n // Create a temporary file for decompressed content\n let temp_file =\n tempfile::NamedTempFile::new().map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n\n // Use external xz command to decompress\n let output = Command::new(\"xz\")\n .args([\"-dc\", archive_path.to_str().unwrap()])\n .output()\n .map_err(|e| {\n SpsError::Generic(format!(\n \"Failed to run xz command for extraction: {e}. Make sure xz is installed.\"\n ))\n })?;\n\n if !output.status.success() {\n return Err(SpsError::Generic(format!(\n \"xz decompression failed during extraction: {}\",\n String::from_utf8_lossy(&output.stderr)\n )));\n }\n\n // Write decompressed data to temp file\n std::fs::write(temp_file.path(), &output.stdout)\n .map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n\n // Extract as tar\n let file = File::open(temp_file.path()).map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n extract_tar_archive(file, target_dir, strip_components, archive_path)\n}\n\n#[cfg(unix)]\nstruct DeferredHardLink {\n link_path_in_archive: PathBuf,\n target_name_in_archive: PathBuf,\n}\n\nfn extract_tar_archive(\n reader: R,\n target_dir: &Path,\n strip_components: usize,\n archive_path_for_log: &Path,\n) -> Result<()> {\n let mut archive = Archive::new(reader);\n archive.set_preserve_permissions(true);\n archive.set_unpack_xattrs(true);\n archive.set_overwrite(true);\n\n debug!(\n \"Starting TAR extraction for {}\",\n archive_path_for_log.display()\n );\n\n #[cfg(unix)]\n let mut deferred_hardlinks: Vec = Vec::new();\n let mut errors: Vec = Vec::new();\n\n for entry_result in archive.entries()? {\n let mut entry = entry_result.map_err(|e| {\n SpsError::Generic(format!(\n \"Error reading TAR entry from {}: {}\",\n archive_path_for_log.display(),\n e\n ))\n })?;\n\n let original_path_in_archive: PathBuf = entry\n .path()\n .map_err(|e| {\n SpsError::Generic(format!(\n \"Invalid path in TAR entry from {}: {}\",\n archive_path_for_log.display(),\n e\n ))\n })?\n .into_owned();\n\n let stripped_components_iter: Vec> = original_path_in_archive\n .components()\n .skip(strip_components)\n .collect();\n\n if stripped_components_iter.is_empty() {\n debug!(\n \"Skipping entry due to strip_components: {:?}\",\n original_path_in_archive\n );\n continue;\n }\n\n let mut final_target_path_on_disk = target_dir.to_path_buf();\n for comp in stripped_components_iter {\n match comp {\n Component::Normal(p) => final_target_path_on_disk.push(p),\n Component::CurDir => {}\n Component::ParentDir => {\n let msg = format!(\n \"Unsafe '..' in TAR path {} after stripping in {}\",\n original_path_in_archive.display(),\n archive_path_for_log.display()\n );\n error!(\"{}\", msg);\n errors.push(msg);\n continue;\n }\n Component::Prefix(_) | Component::RootDir => {\n let msg = format!(\n \"Disallowed component {:?} in TAR path {}\",\n comp,\n original_path_in_archive.display()\n );\n error!(\"{}\", msg);\n errors.push(msg);\n continue;\n }\n }\n }\n\n if !final_target_path_on_disk.starts_with(target_dir) {\n let msg = format!(\n \"Path traversal {} -> {} detected in {}\",\n original_path_in_archive.display(),\n final_target_path_on_disk.display(),\n archive_path_for_log.display()\n );\n error!(\"{}\", msg);\n errors.push(msg);\n continue;\n }\n\n if let Some(parent) = final_target_path_on_disk.parent() {\n if !parent.exists() {\n fs::create_dir_all(parent).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(io::Error::new(\n e.kind(),\n format!(\"Failed create parent dir {}: {}\", parent.display(), e),\n )))\n })?;\n }\n }\n\n #[cfg(unix)]\n if entry.header().entry_type() == EntryType::Link {\n if let Ok(Some(link_name_in_archive)) = entry.link_name() {\n let deferred_link = DeferredHardLink {\n link_path_in_archive: original_path_in_archive.clone(),\n target_name_in_archive: link_name_in_archive.into_owned(),\n };\n debug!(\n \"Deferring hardlink: archive path '{}' -> archive target '{}'\",\n original_path_in_archive.display(),\n deferred_link.target_name_in_archive.display()\n );\n deferred_hardlinks.push(deferred_link);\n continue;\n } else {\n let msg = format!(\n \"Hardlink entry '{}' in {} has no link target name.\",\n original_path_in_archive.display(),\n archive_path_for_log.display()\n );\n warn!(\"{}\", msg);\n errors.push(msg);\n continue;\n }\n }\n\n match entry.unpack(&final_target_path_on_disk) {\n Ok(_) => debug!(\n \"Unpacked TAR entry to: {}\",\n final_target_path_on_disk.display()\n ),\n Err(e) => {\n if e.kind() != io::ErrorKind::AlreadyExists {\n let msg = format!(\n \"Failed to unpack entry {:?} to {}: {}. Entry type: {:?}\",\n original_path_in_archive,\n final_target_path_on_disk.display(),\n e,\n entry.header().entry_type()\n );\n error!(\"{}\", msg);\n errors.push(msg);\n } else {\n debug!(\"Entry already exists at {}, skipping unpack (tar crate overwrite=true handles this).\", final_target_path_on_disk.display());\n }\n }\n }\n }\n\n #[cfg(unix)]\n for deferred in deferred_hardlinks {\n let mut disk_link_path = target_dir.to_path_buf();\n for comp in deferred\n .link_path_in_archive\n .components()\n .skip(strip_components)\n {\n if let Component::Normal(p) = comp {\n disk_link_path.push(p);\n }\n // Other components should have been caught by safety checks above\n }\n\n let mut disk_target_path = target_dir.to_path_buf();\n // The link_name_in_archive is relative to the archive root *before* stripping.\n // We need to apply stripping to it as well to find its final disk location.\n for comp in deferred\n .target_name_in_archive\n .components()\n .skip(strip_components)\n {\n if let Component::Normal(p) = comp {\n disk_target_path.push(p);\n }\n }\n\n if !disk_target_path.starts_with(target_dir) || !disk_link_path.starts_with(target_dir) {\n let msg = format!(\"Skipping deferred hardlink due to path traversal attempt: link '{}' -> target '{}'\", disk_link_path.display(), disk_target_path.display());\n error!(\"{}\", msg);\n errors.push(msg);\n continue;\n }\n\n debug!(\n \"Attempting deferred hardlink: disk link path '{}' -> disk target path '{}'\",\n disk_link_path.display(),\n disk_target_path.display()\n );\n\n if disk_target_path.exists() {\n if let Some(parent) = disk_link_path.parent() {\n if !parent.exists() {\n if let Err(e) = fs::create_dir_all(parent) {\n let msg = format!(\n \"Failed to create parent directory for deferred hardlink {}: {}\",\n disk_link_path.display(),\n e\n );\n error!(\"{}\", msg);\n errors.push(msg);\n continue;\n }\n }\n }\n\n if disk_link_path.symlink_metadata().is_ok() {\n // Check if something (file or symlink) exists at the link creation spot\n if let Err(e) = fs::remove_file(&disk_link_path) {\n // Attempt to remove it\n warn!(\"Could not remove existing file/symlink at hardlink destination {}: {}. Hardlink creation may fail.\", disk_link_path.display(), e);\n }\n }\n\n if let Err(e) = fs::hard_link(&disk_target_path, &disk_link_path) {\n let msg = format!(\n \"Failed to create deferred hardlink '{}' -> '{}': {}. Target exists: {}\",\n disk_link_path.display(),\n disk_target_path.display(),\n e,\n disk_target_path.exists()\n );\n error!(\"{}\", msg);\n errors.push(msg);\n } else {\n debug!(\n \"Successfully created deferred hardlink: '{}' -> '{}'\",\n disk_link_path.display(),\n disk_target_path.display()\n );\n }\n } else {\n let msg = format!(\n \"Target '{}' for deferred hardlink '{}' does not exist. Hardlink not created.\",\n disk_target_path.display(),\n disk_link_path.display()\n );\n error!(\"{}\", msg);\n errors.push(msg);\n }\n }\n\n if !errors.is_empty() {\n return Err(SpsError::InstallError(format!(\n \"Failed during TAR extraction for {} with {} error(s): {}\",\n archive_path_for_log.display(),\n errors.len(),\n errors.join(\"; \")\n )));\n }\n\n debug!(\n \"Finished TAR extraction for {}\",\n archive_path_for_log.display()\n );\n #[cfg(target_os = \"macos\")]\n {\n if let Err(e) = quarantine_extracted_apps_in_stage(target_dir, \"sps-tar-extractor\") {\n tracing::warn!(\n \"Error during post-tar extraction quarantine scan for {}: {}\",\n archive_path_for_log.display(),\n e\n );\n }\n }\n Ok(())\n}\n\nfn extract_zip_archive(\n reader: R,\n target_dir: &Path,\n strip_components: usize,\n archive_path_for_log: &Path,\n) -> Result<()> {\n let mut archive = ZipArchive::new(reader).map_err(|e| {\n SpsError::Generic(format!(\n \"Failed to open ZIP {}: {}\",\n archive_path_for_log.display(),\n e\n ))\n })?;\n\n debug!(\n \"Starting ZIP extraction for {}\",\n archive_path_for_log.display()\n );\n\n for i in 0..archive.len() {\n let mut file = archive\n .by_index(i)\n .map_err(|e| SpsError::Generic(format!(\"Failed to read ZIP entry {i}: {e}\")))?;\n\n let Some(original_path_in_archive) = file.enclosed_name() else {\n debug!(\"Skipping unsafe ZIP entry (no enclosed name)\");\n continue;\n };\n\n let stripped_components_iter: Vec> = original_path_in_archive\n .components()\n .skip(strip_components)\n .collect();\n\n if stripped_components_iter.is_empty() {\n debug!(\n \"Skipping ZIP entry {} due to strip_components\",\n original_path_in_archive.display()\n );\n continue;\n }\n\n let mut final_target_path_on_disk = target_dir.to_path_buf();\n for comp in stripped_components_iter {\n match comp {\n Component::Normal(p) => final_target_path_on_disk.push(p),\n Component::CurDir => {}\n Component::ParentDir => {\n error!(\n \"Unsafe '..' in ZIP path {} after strip_components\",\n original_path_in_archive.display()\n );\n return Err(SpsError::Generic(format!(\n \"Unsafe '..' component in ZIP path {}\",\n original_path_in_archive.display()\n )));\n }\n Component::Prefix(_) | Component::RootDir => {\n error!(\n \"Disallowed component {:?} in ZIP path {}\",\n comp,\n original_path_in_archive.display()\n );\n return Err(SpsError::Generic(format!(\n \"Disallowed component in ZIP path {}\",\n original_path_in_archive.display()\n )));\n }\n }\n }\n\n if !final_target_path_on_disk.starts_with(target_dir) {\n error!(\n \"ZIP path traversal detected: {} -> {}\",\n original_path_in_archive.display(),\n final_target_path_on_disk.display()\n );\n return Err(SpsError::Generic(format!(\n \"ZIP path traversal detected in {}\",\n archive_path_for_log.display()\n )));\n }\n\n if let Some(parent) = final_target_path_on_disk.parent() {\n if !parent.exists() {\n fs::create_dir_all(parent).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(io::Error::new(\n e.kind(),\n format!(\n \"Failed to create parent directory {}: {}\",\n parent.display(),\n e\n ),\n )))\n })?;\n }\n }\n\n if file.is_dir() {\n debug!(\n \"Creating directory: {}\",\n final_target_path_on_disk.display()\n );\n fs::create_dir_all(&final_target_path_on_disk).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(io::Error::new(\n e.kind(),\n format!(\n \"Failed to create directory {}: {}\",\n final_target_path_on_disk.display(),\n e\n ),\n )))\n })?;\n } else {\n // Regular file\n if final_target_path_on_disk.exists() {\n match fs::remove_file(&final_target_path_on_disk) {\n Ok(_) => {}\n Err(e) if e.kind() == io::ErrorKind::NotFound => {}\n Err(e) => return Err(SpsError::Io(std::sync::Arc::new(e))),\n }\n }\n\n debug!(\"Extracting file: {}\", final_target_path_on_disk.display());\n let mut outfile = File::create(&final_target_path_on_disk).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(io::Error::new(\n e.kind(),\n format!(\n \"Failed to create file {}: {}\",\n final_target_path_on_disk.display(),\n e\n ),\n )))\n })?;\n\n std::io::copy(&mut file, &mut outfile).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(io::Error::new(\n e.kind(),\n format!(\n \"Failed to write file {}: {}\",\n final_target_path_on_disk.display(),\n e\n ),\n )))\n })?;\n\n // Set permissions on Unix systems\n #[cfg(unix)]\n {\n use std::os::unix::fs::PermissionsExt;\n if let Some(mode) = file.unix_mode() {\n let perms = std::fs::Permissions::from_mode(mode);\n std::fs::set_permissions(&final_target_path_on_disk, perms)\n .map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n }\n }\n }\n }\n\n debug!(\n \"Finished ZIP extraction for {}\",\n archive_path_for_log.display()\n );\n\n // Apply quarantine to extracted apps on macOS\n #[cfg(target_os = \"macos\")]\n {\n if let Err(e) = quarantine_extracted_apps_in_stage(target_dir, \"sps-zip-extractor\") {\n tracing::warn!(\n \"Error during post-zip extraction quarantine scan for {}: {}\",\n archive_path_for_log.display(),\n e\n );\n }\n }\n\n Ok(())\n}\n"], ["/sps/sps-core/src/install/bottle/macho.rs", "// sps-core/src/build/formula/macho.rs\n// Contains Mach-O specific patching logic for bottle relocation.\n// Updated to use MachOFatFile32 and MachOFatFile64 for FAT binary parsing.\n// Refactored to separate immutable analysis from mutable patching to fix borrow checker errors.\n\nuse std::collections::HashMap;\nuse std::fs;\nuse std::io::Write; // Keep for write_patched_buffer\nuse std::path::Path;\nuse std::process::{Command as StdCommand, Stdio}; // Keep for codesign\n\n// --- Imports needed for Mach-O patching (macOS only) ---\n#[cfg(target_os = \"macos\")]\nuse object::{\n self,\n macho::{MachHeader32, MachHeader64}, // Keep for Mach-O parsing\n read::macho::{\n FatArch,\n LoadCommandVariant, // Correct import path\n MachHeader,\n MachOFatFile32,\n MachOFatFile64, // Core Mach-O types + FAT types\n MachOFile,\n },\n Endianness,\n FileKind,\n ReadRef,\n};\nuse sps_common::error::{Result, SpsError};\nuse tempfile::NamedTempFile;\nuse tracing::{debug, error};\n\n// --- Platform‑specific constants for Mach‑O magic detection ---\n#[cfg(target_os = \"macos\")]\nconst MH_MAGIC: u32 = 0xfeedface;\n#[cfg(target_os = \"macos\")]\nconst MH_MAGIC_64: u32 = 0xfeedfacf;\n#[cfg(target_os = \"macos\")]\nconst MACHO_HEADER32_SIZE: usize = 28;\n#[cfg(target_os = \"macos\")]\nconst MACHO_HEADER64_SIZE: usize = 32;\n\n/// Core patch data for **one** string replacement location inside a Mach‑O file.\n#[cfg(target_os = \"macos\")]\n#[derive(Debug, Clone)]\nstruct PatchInfo {\n absolute_offset: usize, // Offset in the entire file buffer\n allocated_len: usize, // How much space was allocated for this string\n new_path: String, // The new string to write\n}\n\n/// Container for paths that couldn't be patched due to length constraints\n#[cfg(target_os = \"macos\")]\n#[derive(Debug, Clone)]\npub struct SkippedPath {\n pub old_path: String,\n pub new_path: String,\n}\n\n/// Main entry point for Mach‑O path patching (macOS only).\n/// Returns `Ok(true)` if patches were applied, `Ok(false)` if no patches needed.\n/// Returns a tuple: (patched: bool, skipped_paths: Vec)\n#[cfg(target_os = \"macos\")]\npub fn patch_macho_file(\n path: &Path,\n replacements: &HashMap,\n) -> Result<(bool, Vec)> {\n patch_macho_file_macos(path, replacements)\n}\n\n/// Container for paths that couldn't be patched due to length constraints\n#[cfg(not(target_os = \"macos\"))]\n#[derive(Debug, Clone)]\npub struct SkippedPath {\n pub old_path: String,\n pub new_path: String,\n}\n\n/// No‑op stub for non‑macOS platforms.\n#[cfg(not(target_os = \"macos\"))]\npub fn patch_macho_file(\n _path: &Path,\n _replacements: &HashMap,\n) -> Result<(bool, Vec)> {\n Ok((false, Vec::new()))\n}\n\n/// **macOS implementation**: Tries to patch Mach‑O files by replacing placeholders.\n#[cfg(target_os = \"macos\")]\nfn patch_macho_file_macos(\n path: &Path,\n replacements: &HashMap,\n) -> Result<(bool, Vec)> {\n debug!(\"Processing potential Mach-O file: {}\", path.display());\n\n // 1) Load the entire file into memory\n let buffer = match fs::read(path) {\n Ok(data) => data,\n Err(e) => {\n debug!(\"Failed to read {}: {}\", path.display(), e);\n return Ok((false, Vec::new()));\n }\n };\n if buffer.is_empty() {\n debug!(\"Empty file: {}\", path.display());\n return Ok((false, Vec::new()));\n }\n\n // 2) Identify the file type\n let kind = match object::FileKind::parse(&*buffer) {\n Ok(k) => k,\n Err(_e) => {\n debug!(\"Not an object file: {}\", path.display());\n return Ok((false, Vec::new()));\n }\n };\n\n // 3) **Analysis phase**: collect patches + skipped paths\n let (patches, skipped_paths) = collect_macho_patches(&buffer, kind, replacements, path)?;\n\n if patches.is_empty() {\n if skipped_paths.is_empty() {\n debug!(\"No patches needed for {}\", path.display());\n } else {\n debug!(\n \"No patches applied for {} ({} paths skipped due to length)\",\n path.display(),\n skipped_paths.len()\n );\n }\n return Ok((false, skipped_paths));\n }\n\n // 4) Clone buffer and apply all patches atomically\n let mut patched_buffer = buffer;\n for patch in &patches {\n patch_path_in_buffer(\n &mut patched_buffer,\n patch.absolute_offset,\n patch.allocated_len,\n &patch.new_path,\n path,\n )?;\n }\n\n // 5) Write atomically\n write_patched_buffer(path, &patched_buffer)?;\n debug!(\"Wrote patched Mach-O: {}\", path.display());\n\n // 6) Re‑sign on Apple Silicon\n #[cfg(target_arch = \"aarch64\")]\n {\n resign_binary(path)?;\n debug!(\"Re‑signed patched binary: {}\", path.display());\n }\n\n Ok((true, skipped_paths))\n}\n\n/// ASCII magic for the start of a static `ar` archive (`!\\n`)\n#[cfg(target_os = \"macos\")]\nconst AR_MAGIC: &[u8; 8] = b\"!\\n\";\n\n/// Examine a buffer (Mach‑O or FAT) and return every patch we must apply + skipped paths.\n#[cfg(target_os = \"macos\")]\nfn collect_macho_patches(\n buffer: &[u8],\n kind: FileKind,\n replacements: &HashMap,\n path_for_log: &Path,\n) -> Result<(Vec, Vec)> {\n let mut patches = Vec::::new();\n let mut skipped_paths = Vec::::new();\n\n match kind {\n /* ---------------------------------------------------------- */\n FileKind::MachO32 => {\n let m = MachOFile::, _>::parse(buffer)?;\n let (mut p, mut s) =\n find_patches_in_commands(&m, 0, MACHO_HEADER32_SIZE, replacements, path_for_log)?;\n patches.append(&mut p);\n skipped_paths.append(&mut s);\n }\n /* ---------------------------------------------------------- */\n FileKind::MachO64 => {\n let m = MachOFile::, _>::parse(buffer)?;\n let (mut p, mut s) =\n find_patches_in_commands(&m, 0, MACHO_HEADER64_SIZE, replacements, path_for_log)?;\n patches.append(&mut p);\n skipped_paths.append(&mut s);\n }\n /* ---------------------------------------------------------- */\n FileKind::MachOFat32 => {\n let fat = MachOFatFile32::parse(buffer)?;\n for (idx, arch) in fat.arches().iter().enumerate() {\n let (off, sz) = arch.file_range();\n let slice = &buffer[off as usize..(off + sz) as usize];\n\n /* short‑circuit: static .a archive inside FAT ---------- */\n if slice.starts_with(AR_MAGIC) {\n debug!(\"[slice {}] static archive – skipped\", idx);\n continue;\n }\n\n /* decide 32 / 64 by magic ------------------------------ */\n if slice.len() >= 4 {\n let magic = u32::from_le_bytes(slice[0..4].try_into().unwrap());\n if magic == MH_MAGIC_64 {\n if let Ok(m) = MachOFile::, _>::parse(slice) {\n let (mut p, mut s) = find_patches_in_commands(\n &m,\n off as usize,\n MACHO_HEADER64_SIZE,\n replacements,\n path_for_log,\n )?;\n patches.append(&mut p);\n skipped_paths.append(&mut s);\n }\n } else if magic == MH_MAGIC {\n if let Ok(m) = MachOFile::, _>::parse(slice) {\n let (mut p, mut s) = find_patches_in_commands(\n &m,\n off as usize,\n MACHO_HEADER32_SIZE,\n replacements,\n path_for_log,\n )?;\n patches.append(&mut p);\n skipped_paths.append(&mut s);\n }\n }\n }\n }\n }\n /* ---------------------------------------------------------- */\n FileKind::MachOFat64 => {\n let fat = MachOFatFile64::parse(buffer)?;\n for (idx, arch) in fat.arches().iter().enumerate() {\n let (off, sz) = arch.file_range();\n let slice = &buffer[off as usize..(off + sz) as usize];\n\n if slice.starts_with(AR_MAGIC) {\n debug!(\"[slice {}] static archive – skipped\", idx);\n continue;\n }\n\n if slice.len() >= 4 {\n let magic = u32::from_le_bytes(slice[0..4].try_into().unwrap());\n if magic == MH_MAGIC_64 {\n if let Ok(m) = MachOFile::, _>::parse(slice) {\n let (mut p, mut s) = find_patches_in_commands(\n &m,\n off as usize,\n MACHO_HEADER64_SIZE,\n replacements,\n path_for_log,\n )?;\n patches.append(&mut p);\n skipped_paths.append(&mut s);\n }\n } else if magic == MH_MAGIC {\n if let Ok(m) = MachOFile::, _>::parse(slice) {\n let (mut p, mut s) = find_patches_in_commands(\n &m,\n off as usize,\n MACHO_HEADER32_SIZE,\n replacements,\n path_for_log,\n )?;\n patches.append(&mut p);\n skipped_paths.append(&mut s);\n }\n }\n }\n }\n }\n /* ---------------------------------------------------------- */\n _ => { /* archives & unknown kinds are ignored */ }\n }\n\n Ok((patches, skipped_paths))\n}\n\n/// Iterates through load commands of a parsed MachOFile (slice) and returns\n/// patch details + skipped paths.\n#[cfg(target_os = \"macos\")]\nfn find_patches_in_commands<'data, Mach, R>(\n macho_file: &MachOFile<'data, Mach, R>,\n slice_base_offset: usize,\n header_size: usize,\n replacements: &HashMap,\n file_path_for_log: &Path,\n) -> Result<(Vec, Vec)>\nwhere\n Mach: MachHeader,\n R: ReadRef<'data>,\n{\n let endian = macho_file.endian();\n let mut patches = Vec::new();\n let mut skipped_paths = Vec::new();\n let mut cur_off = header_size;\n\n let mut it = macho_file.macho_load_commands()?;\n while let Some(cmd) = it.next()? {\n let cmd_size = cmd.cmdsize() as usize;\n let cmd_offset = cur_off; // offset *inside this slice*\n cur_off += cmd_size;\n\n let variant = match cmd.variant() {\n Ok(v) => v,\n Err(e) => {\n tracing::warn!(\n \"Malformed load‑command in {}: {}; skipping\",\n file_path_for_log.display(),\n e\n );\n continue;\n }\n };\n\n // — which commands carry path strings we might want? —\n let path_info: Option<(u32, &[u8])> = match variant {\n LoadCommandVariant::Dylib(d) | LoadCommandVariant::IdDylib(d) => cmd\n .string(endian, d.dylib.name)\n .ok()\n .map(|bytes| (d.dylib.name.offset.get(endian), bytes)),\n LoadCommandVariant::Rpath(r) => cmd\n .string(endian, r.path)\n .ok()\n .map(|bytes| (r.path.offset.get(endian), bytes)),\n _ => None,\n };\n\n if let Some((offset_in_cmd, bytes)) = path_info {\n if let Ok(old_path) = std::str::from_utf8(bytes) {\n if let Some(new_path) = find_and_replace_placeholders(old_path, replacements) {\n let allocated = cmd_size.saturating_sub(offset_in_cmd as usize);\n\n if new_path.len() + 1 > allocated {\n // would overflow – add to skipped paths instead of throwing\n tracing::debug!(\n \"Skip patch (too long): '{}' → '{}' (alloc {} B) in {}\",\n old_path,\n new_path,\n allocated,\n file_path_for_log.display()\n );\n skipped_paths.push(SkippedPath {\n old_path: old_path.to_string(),\n new_path: new_path.clone(),\n });\n continue;\n }\n\n patches.push(PatchInfo {\n absolute_offset: slice_base_offset + cmd_offset + offset_in_cmd as usize,\n allocated_len: allocated,\n new_path,\n });\n }\n }\n }\n }\n Ok((patches, skipped_paths))\n}\n\n/// Helper to replace placeholders in a string based on the replacements map.\n/// Returns `Some(String)` with replacements if any were made, `None` otherwise.\nfn find_and_replace_placeholders(\n current_path: &str,\n replacements: &HashMap,\n) -> Option {\n let mut new_path = current_path.to_string();\n let mut path_modified = false;\n // Iterate through all placeholder/replacement pairs\n for (placeholder, replacement) in replacements {\n // Check if the current path string contains the placeholder\n if new_path.contains(placeholder) {\n // Replace all occurrences of the placeholder\n new_path = new_path.replace(placeholder, replacement);\n path_modified = true; // Mark that a change was made\n debug!(\n \" Replaced '{}' with '{}' -> '{}'\",\n placeholder, replacement, new_path\n );\n }\n }\n // Return the modified string only if changes occurred\n if path_modified {\n Some(new_path)\n } else {\n None\n }\n}\n\n/// Write a new (null‑padded) path into the mutable buffer. \n/// Assumes the caller already verified the length.\n#[cfg(target_os = \"macos\")]\nfn patch_path_in_buffer(\n buf: &mut [u8],\n abs_off: usize,\n alloc_len: usize,\n new_path: &str,\n file: &Path,\n) -> Result<()> {\n if new_path.len() + 1 > alloc_len || abs_off + alloc_len > buf.len() {\n // should never happen – just log & skip\n tracing::debug!(\n \"Patch skipped (bounds) at {} in {}\",\n abs_off,\n file.display()\n );\n return Ok(());\n }\n\n // null‑padded copy\n buf[abs_off..abs_off + new_path.len()].copy_from_slice(new_path.as_bytes());\n buf[abs_off + new_path.len()..abs_off + alloc_len].fill(0);\n\n Ok(())\n}\n\n/// Writes the patched buffer to the original path atomically using a temporary file.\n#[cfg(target_os = \"macos\")]\nfn write_patched_buffer(original_path: &Path, buffer: &[u8]) -> Result<()> {\n // Get the directory containing the original file\n let dir = original_path.parent().ok_or_else(|| {\n SpsError::Generic(format!(\n \"Cannot get parent directory for {}\",\n original_path.display()\n ))\n })?;\n // Ensure the directory exists\n fs::create_dir_all(dir).map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n\n // Create a named temporary file in the same directory to facilitate atomic rename\n let mut temp_file = NamedTempFile::new_in(dir)?;\n debug!(\n \" Writing patched buffer ({} bytes) to temporary file: {:?}\",\n buffer.len(),\n temp_file.path()\n );\n // Write the entire modified buffer to the temporary file\n temp_file.write_all(buffer)?;\n // Ensure data is flushed to the OS buffer\n temp_file.flush()?;\n // Attempt to sync data to the disk\n temp_file.as_file().sync_all()?; // Ensure data is physically written\n\n // Atomically replace the original file with the temporary file\n // persist() renames the temp file over the original path.\n temp_file.persist(original_path).map_err(|e| {\n // If persist fails, the temporary file might still exist.\n // The error 'e' contains both the temp file and the underlying IO error.\n error!(\n \" Failed to persist/rename temporary file over {}: {}\",\n original_path.display(),\n e.error // Log the underlying IO error\n );\n // Return the IO error wrapped in our error type\n SpsError::Io(std::sync::Arc::new(e.error))\n })?;\n debug!(\n \" Atomically replaced {} with patched version\",\n original_path.display()\n );\n Ok(())\n}\n\n/// Re-signs the binary using the `codesign` command-line tool.\n/// This is typically necessary on Apple Silicon (aarch64) after modifying executables.\n#[cfg(all(target_os = \"macos\", target_arch = \"aarch64\"))]\nfn resign_binary(path: &Path) -> Result<()> {\n // Suppressed: debug!(\"Re-signing patched binary: {}\", path.display());\n let status = StdCommand::new(\"codesign\")\n .args([\n \"-s\",\n \"-\",\n \"--force\",\n \"--preserve-metadata=identifier,entitlements\",\n ])\n .arg(path)\n .stdout(Stdio::null())\n .stderr(Stdio::null())\n .status() // Execute the command and get its exit status\n .map_err(|e| {\n error!(\n \" Failed to execute codesign command for {}: {}\",\n path.display(),\n e\n );\n SpsError::Io(std::sync::Arc::new(e))\n })?;\n if status.success() {\n // Suppressed: debug!(\"Successfully re-signed {}\", path.display());\n Ok(())\n } else {\n error!(\n \" codesign command failed for {} with status: {}\",\n path.display(),\n status\n );\n Err(SpsError::CodesignError(format!(\n \"Failed to re-sign patched binary {}, it may not be executable. Exit status: {}\",\n path.display(),\n status\n )))\n }\n}\n\n// No-op stub for resigning on non-Apple Silicon macOS (e.g., x86_64)\n#[cfg(all(target_os = \"macos\", not(target_arch = \"aarch64\")))]\nfn resign_binary(_path: &Path) -> Result<()> {\n // No re-signing typically needed on Intel Macs after ad-hoc patching\n Ok(())\n}\n\n// No-op stub for resigning Innovations on non-macOS platforms\n#[cfg(not(target_os = \"macos\"))]\nfn resign_binary(_path: &Path) -> Result<()> {\n // Resigning is a macOS concept\n Ok(())\n}\n"], ["/sps/sps-core/src/check/update.rs", "// sps-core/src/check/update.rs\n\nuse std::collections::HashMap;\nuse std::sync::Arc;\n\n// Imports from sps-common\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::formulary::Formulary; // Using the shared Formulary\nuse sps_common::model::version::Version as PkgVersion;\nuse sps_common::model::Cask; // Using the Cask and Formula from sps-common\n// Use the Cask and Formula structs from sps_common::model\n// Ensure InstallTargetIdentifier is correctly pathed if it's also in sps_common::model\nuse sps_common::model::InstallTargetIdentifier;\n// Imports from sps-net\nuse sps_net::api;\n\n// Imports from sps-core\nuse crate::check::installed::{InstalledPackageInfo, PackageType};\n\n#[derive(Debug, Clone)]\npub struct UpdateInfo {\n pub name: String,\n pub installed_version: String,\n pub available_version: String,\n pub pkg_type: PackageType,\n pub target_definition: InstallTargetIdentifier,\n}\n\n/// Ensures that the raw JSON data for formulas and casks exists in the main disk cache,\n/// fetching from the API if necessary.\nasync fn ensure_api_data_cached(cache: &Cache) -> Result<()> {\n let formula_check = cache.load_raw(\"formula.json\");\n let cask_check = cache.load_raw(\"cask.json\");\n\n // Determine if fetches are needed\n let mut fetch_formulas = false;\n if formula_check.is_err() {\n tracing::debug!(\"Local formula.json cache missing or unreadable. Scheduling fetch.\");\n fetch_formulas = true;\n }\n\n let mut fetch_casks = false;\n if cask_check.is_err() {\n tracing::debug!(\"Local cask.json cache missing or unreadable. Scheduling fetch.\");\n fetch_casks = true;\n }\n\n // Perform fetches concurrently if needed\n match (fetch_formulas, fetch_casks) {\n (true, true) => {\n tracing::debug!(\"Populating missing formula.json and cask.json from API...\");\n let (formula_res, cask_res) = tokio::join!(\n async {\n let data = api::fetch_all_formulas().await?;\n cache.store_raw(\"formula.json\", &data)?;\n Ok::<(), SpsError>(())\n },\n async {\n let data = api::fetch_all_casks().await?;\n cache.store_raw(\"cask.json\", &data)?;\n Ok::<(), SpsError>(())\n }\n );\n formula_res?;\n cask_res?;\n tracing::debug!(\"Formula.json and cask.json populated from API.\");\n }\n (true, false) => {\n tracing::debug!(\"Populating missing formula.json from API...\");\n let data = api::fetch_all_formulas().await?;\n cache.store_raw(\"formula.json\", &data)?;\n tracing::debug!(\"Formula.json populated from API.\");\n }\n (false, true) => {\n tracing::debug!(\"Populating missing cask.json from API...\");\n let data = api::fetch_all_casks().await?;\n cache.store_raw(\"cask.json\", &data)?;\n tracing::debug!(\"Cask.json populated from API.\");\n }\n (false, false) => {\n tracing::debug!(\"Local formula.json and cask.json caches are present.\");\n }\n }\n Ok(())\n}\n\npub async fn check_for_updates(\n installed_packages: &[InstalledPackageInfo],\n cache: &Cache,\n config: &Config,\n) -> Result> {\n // 1. Ensure the underlying JSON files in the main cache are populated.\n ensure_api_data_cached(cache)\n .await\n .map_err(|e| {\n tracing::error!(\n \"Failed to ensure API data is cached for update check: {}\",\n e\n );\n // Decide if this is a fatal error for update checking or if we can proceed with\n // potentially stale/missing data. For now, let's make it non-fatal but log\n // an error, as Formulary/cask parsing might still work with older cache.\n SpsError::Generic(format!(\n \"Failed to ensure API data in cache, update check might be unreliable: {e}\"\n ))\n })\n .ok(); // Continue even if this pre-fetch step fails, rely on Formulary/cask loading to handle actual\n // errors.\n\n // 2. Instantiate Formulary. It uses the `cache` (from sps-common) to load `formula.json`.\n let formulary = Formulary::new(config.clone());\n\n // 3. For Casks: Load the entire `cask.json` from cache and parse it robustly into Vec.\n // This uses the Cask definition from sps_common::model::cask.\n let casks_map: HashMap> = match cache.load_raw(\"cask.json\") {\n Ok(json_str) => {\n // Parse directly into Vec using the definition from sps-common::model::cask\n match serde_json::from_str::>(&json_str) {\n Ok(casks) => casks\n .into_iter()\n .map(|c| (c.token.clone(), Arc::new(c)))\n .collect(),\n Err(e) => {\n tracing::warn!(\n \"Failed to parse full cask.json string into Vec (from sps-common): {}. Cask update checks may be incomplete.\",\n e\n );\n HashMap::new()\n }\n }\n }\n Err(e) => {\n tracing::warn!(\n \"Failed to load cask.json string from cache: {}. Cask update checks will be based on no remote data.\", e\n );\n HashMap::new()\n }\n };\n\n tracing::debug!(\n \"[UpdateCheck] Starting update check for {} packages\",\n installed_packages.len()\n );\n let mut updates_available = Vec::new();\n\n for installed in installed_packages {\n tracing::debug!(\n \"[UpdateCheck] Checking package '{}' version '{}'\",\n installed.name,\n installed.version\n );\n match installed.pkg_type {\n PackageType::Formula => {\n match formulary.load_formula(&installed.name) {\n // Uses sps-common::formulary::Formulary\n Ok(latest_formula_obj) => {\n // Returns sps_common::model::formula::Formula\n let latest_formula_arc = Arc::new(latest_formula_obj);\n\n let latest_version_str = latest_formula_arc.version_str_full();\n tracing::debug!(\n \"[UpdateCheck] Formula '{}': installed='{}', latest='{}'\",\n installed.name,\n installed.version,\n latest_version_str\n );\n\n let installed_v_res = PkgVersion::parse(&installed.version);\n let latest_v_res = PkgVersion::parse(&latest_version_str);\n let installed_revision = installed\n .version\n .split('_')\n .nth(1)\n .and_then(|s| s.parse::().ok())\n .unwrap_or(0);\n\n let needs_update = match (installed_v_res, latest_v_res) {\n (Ok(iv), Ok(lv)) => {\n let version_newer = lv > iv;\n let revision_newer =\n lv == iv && latest_formula_arc.revision > installed_revision;\n tracing::debug!(\"[UpdateCheck] Formula '{}': version_newer={}, revision_newer={} (installed_rev={}, latest_rev={})\", \n installed.name, version_newer, revision_newer, installed_revision, latest_formula_arc.revision);\n version_newer || revision_newer\n }\n _ => {\n let different = installed.version != latest_version_str;\n tracing::debug!(\"[UpdateCheck] Formula '{}': fallback string comparison, different={}\", \n installed.name, different);\n different\n }\n };\n\n tracing::debug!(\n \"[UpdateCheck] Formula '{}': needs_update={}\",\n installed.name,\n needs_update\n );\n if needs_update {\n updates_available.push(UpdateInfo {\n name: installed.name.clone(),\n installed_version: installed.version.clone(),\n available_version: latest_version_str,\n pkg_type: PackageType::Formula,\n target_definition: InstallTargetIdentifier::Formula(\n // From sps-common\n latest_formula_arc.clone(),\n ),\n });\n }\n }\n Err(_e) => {\n tracing::debug!(\n \"Installed formula '{}' not found via Formulary. It might have been removed from the remote. Source error: {}\",\n installed.name, _e\n );\n }\n }\n }\n PackageType::Cask => {\n if let Some(latest_cask_arc) = casks_map.get(&installed.name) {\n // latest_cask_arc is Arc\n if let Some(available_version) = latest_cask_arc.version.as_ref() {\n if &installed.version != available_version {\n updates_available.push(UpdateInfo {\n name: installed.name.clone(),\n installed_version: installed.version.clone(),\n available_version: available_version.clone(),\n pkg_type: PackageType::Cask,\n target_definition: InstallTargetIdentifier::Cask(\n // From sps-common\n latest_cask_arc.clone(),\n ),\n });\n }\n } else {\n tracing::warn!(\n \"Latest cask definition for '{}' from casks_map has no version string.\",\n installed.name\n );\n }\n } else {\n tracing::warn!(\n \"Installed cask '{}' not found in the fully parsed casks_map.\",\n installed.name\n );\n }\n }\n }\n }\n\n tracing::debug!(\n \"[UpdateCheck] Update check complete: {} updates available out of {} packages checked\",\n updates_available.len(),\n installed_packages.len()\n );\n tracing::debug!(\n \"[UpdateCheck] Updates available for: {:?}\",\n updates_available\n .iter()\n .map(|u| &u.name)\n .collect::>()\n );\n\n Ok(updates_available)\n}\n"], ["/sps/sps-common/src/dependency/resolver.rs", "// sps-common/src/dependency/resolver.rs\nuse std::collections::{HashMap, HashSet, VecDeque};\nuse std::path::{Path, PathBuf};\nuse std::sync::Arc;\n\nuse tracing::{debug, error, warn};\n\nuse crate::dependency::{Dependency, DependencyTag};\nuse crate::error::{Result, SpsError};\nuse crate::formulary::Formulary;\nuse crate::keg::KegRegistry;\nuse crate::model::formula::Formula;\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq)]\npub enum NodeInstallStrategy {\n BottlePreferred,\n SourceOnly,\n BottleOrFail,\n}\n\n#[derive(Debug, Clone, Default)]\npub struct PerTargetInstallPreferences {\n pub force_source_build_targets: HashSet,\n pub force_bottle_only_targets: HashSet,\n}\n\npub struct ResolutionContext<'a> {\n pub formulary: &'a Formulary,\n pub keg_registry: &'a KegRegistry,\n pub sps_prefix: &'a Path,\n pub include_optional: bool,\n pub include_test: bool,\n pub skip_recommended: bool,\n pub initial_target_preferences: &'a PerTargetInstallPreferences,\n pub build_all_from_source: bool,\n pub cascade_source_preference_to_dependencies: bool,\n pub has_bottle_for_current_platform: fn(&Formula) -> bool,\n pub initial_target_actions: &'a HashMap,\n}\n\n#[derive(Debug, Clone)]\npub struct ResolvedDependency {\n pub formula: Arc,\n pub keg_path: Option,\n pub opt_path: Option,\n pub status: ResolutionStatus,\n pub accumulated_tags: DependencyTag,\n pub determined_install_strategy: NodeInstallStrategy,\n pub failure_reason: Option,\n}\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq)]\npub enum ResolutionStatus {\n Installed,\n Missing,\n Requested,\n SkippedOptional,\n NotFound,\n Failed,\n}\n\n#[derive(Debug, Clone, Default)]\npub struct ResolvedGraph {\n pub install_plan: Vec,\n pub build_dependency_opt_paths: Vec,\n pub runtime_dependency_opt_paths: Vec,\n pub resolution_details: HashMap,\n}\n\n// Added empty constructor\nimpl ResolvedGraph {\n pub fn empty() -> Self {\n Default::default()\n }\n}\n\npub struct DependencyResolver<'a> {\n context: ResolutionContext<'a>,\n formula_cache: HashMap>,\n visiting: HashSet,\n resolution_details: HashMap,\n errors: HashMap>,\n}\n\nimpl<'a> DependencyResolver<'a> {\n pub fn new(context: ResolutionContext<'a>) -> Self {\n Self {\n context,\n formula_cache: HashMap::new(),\n visiting: HashSet::new(),\n resolution_details: HashMap::new(),\n errors: HashMap::new(),\n }\n }\n\n fn determine_node_install_strategy(\n &self,\n formula_name: &str,\n formula_arc: &Arc,\n is_initial_target: bool,\n requesting_parent_strategy: Option,\n ) -> NodeInstallStrategy {\n if is_initial_target {\n if self\n .context\n .initial_target_preferences\n .force_source_build_targets\n .contains(formula_name)\n {\n return NodeInstallStrategy::SourceOnly;\n }\n if self\n .context\n .initial_target_preferences\n .force_bottle_only_targets\n .contains(formula_name)\n {\n return NodeInstallStrategy::BottleOrFail;\n }\n }\n\n if self.context.build_all_from_source {\n return NodeInstallStrategy::SourceOnly;\n }\n\n if self.context.cascade_source_preference_to_dependencies\n && matches!(\n requesting_parent_strategy,\n Some(NodeInstallStrategy::SourceOnly)\n )\n {\n return NodeInstallStrategy::SourceOnly;\n }\n if matches!(\n requesting_parent_strategy,\n Some(NodeInstallStrategy::BottleOrFail)\n ) {\n return NodeInstallStrategy::BottleOrFail;\n }\n\n let strategy = if (self.context.has_bottle_for_current_platform)(formula_arc) {\n NodeInstallStrategy::BottlePreferred\n } else {\n NodeInstallStrategy::SourceOnly\n };\n\n debug!(\n \"Install strategy for '{formula_name}': {:?} (initial_target={is_initial_target}, parent={:?}, bottle_available={})\",\n strategy,\n requesting_parent_strategy,\n (self.context.has_bottle_for_current_platform)(formula_arc)\n );\n strategy\n }\n\n pub fn resolve_targets(&mut self, targets: &[String]) -> Result {\n debug!(\"Starting dependency resolution for targets: {:?}\", targets);\n self.visiting.clear();\n self.resolution_details.clear();\n self.errors.clear();\n\n for target_name in targets {\n if let Err(e) = self.resolve_recursive(target_name, DependencyTag::RUNTIME, true, None)\n {\n self.errors.insert(target_name.clone(), Arc::new(e));\n warn!(\n \"Resolution failed for target '{}', but continuing for others.\",\n target_name\n );\n }\n }\n\n debug!(\n \"Raw resolved map after initial pass: {:?}\",\n self.resolution_details\n .iter()\n .map(|(k, v)| (k.clone(), v.status, v.accumulated_tags))\n .collect::>()\n );\n\n let sorted_list = match self.topological_sort() {\n Ok(list) => list,\n Err(e @ SpsError::DependencyError(_)) => {\n error!(\"Topological sort failed due to dependency cycle: {}\", e);\n return Err(e);\n }\n Err(e) => {\n error!(\"Topological sort failed: {}\", e);\n return Err(e);\n }\n };\n\n let install_plan: Vec = sorted_list\n .into_iter()\n .filter(|dep| {\n matches!(\n dep.status,\n ResolutionStatus::Missing | ResolutionStatus::Requested\n )\n })\n .collect();\n\n let mut build_paths = Vec::new();\n let mut runtime_paths = Vec::new();\n let mut seen_build_paths = HashSet::new();\n let mut seen_runtime_paths = HashSet::new();\n\n for dep in self.resolution_details.values() {\n if matches!(\n dep.status,\n ResolutionStatus::Installed\n | ResolutionStatus::Requested\n | ResolutionStatus::Missing\n ) {\n if let Some(opt_path) = &dep.opt_path {\n if dep.accumulated_tags.contains(DependencyTag::BUILD)\n && seen_build_paths.insert(opt_path.clone())\n {\n debug!(\"Adding build dep path: {}\", opt_path.display());\n build_paths.push(opt_path.clone());\n }\n if dep.accumulated_tags.intersects(\n DependencyTag::RUNTIME\n | DependencyTag::RECOMMENDED\n | DependencyTag::OPTIONAL,\n ) && seen_runtime_paths.insert(opt_path.clone())\n {\n debug!(\"Adding runtime dep path: {}\", opt_path.display());\n runtime_paths.push(opt_path.clone());\n }\n } else if dep.status != ResolutionStatus::NotFound\n && dep.status != ResolutionStatus::Failed\n {\n debug!(\n \"Warning: No opt_path found for resolved dependency {} ({:?})\",\n dep.formula.name(),\n dep.status\n );\n }\n }\n }\n\n if !self.errors.is_empty() {\n warn!(\n \"Resolution encountered errors for specific targets: {:?}\",\n self.errors\n .iter()\n .map(|(k, v)| (k, v.to_string()))\n .collect::>()\n );\n }\n\n debug!(\n \"Final installation plan (needs install/build): {:?}\",\n install_plan\n .iter()\n .map(|d| (d.formula.name(), d.status))\n .collect::>()\n );\n debug!(\n \"Collected build dependency paths: {:?}\",\n build_paths.iter().map(|p| p.display()).collect::>()\n );\n debug!(\n \"Collected runtime dependency paths: {:?}\",\n runtime_paths\n .iter()\n .map(|p| p.display())\n .collect::>()\n );\n\n Ok(ResolvedGraph {\n install_plan,\n build_dependency_opt_paths: build_paths,\n runtime_dependency_opt_paths: runtime_paths,\n resolution_details: self.resolution_details.clone(),\n })\n }\n\n fn update_existing_resolution(\n &mut self,\n name: &str,\n tags_from_parent_edge: DependencyTag,\n is_initial_target: bool,\n ) -> Result {\n let Some(existing) = self.resolution_details.get_mut(name) else {\n return Ok(false);\n };\n\n let original_status = existing.status;\n let original_tags = existing.accumulated_tags;\n let has_keg = existing.keg_path.is_some();\n\n let mut new_status = original_status;\n if is_initial_target && new_status == ResolutionStatus::Missing {\n new_status = ResolutionStatus::Requested;\n }\n\n let skip_recommended = self.context.skip_recommended;\n let include_optional = self.context.include_optional;\n\n if Self::should_upgrade_optional_status_static(\n new_status,\n tags_from_parent_edge,\n is_initial_target,\n has_keg,\n skip_recommended,\n include_optional,\n ) {\n new_status = if has_keg {\n ResolutionStatus::Installed\n } else if is_initial_target {\n ResolutionStatus::Requested\n } else {\n ResolutionStatus::Missing\n };\n }\n\n let mut needs_revisit = false;\n if new_status != original_status {\n debug!(\n \"Updating status for '{name}' from {:?} to {:?}\",\n original_status, new_status\n );\n existing.status = new_status;\n needs_revisit = true;\n }\n\n let combined_tags = original_tags | tags_from_parent_edge;\n if combined_tags != original_tags {\n debug!(\n \"Updating tags for '{name}' from {:?} to {:?}\",\n original_tags, combined_tags\n );\n existing.accumulated_tags = combined_tags;\n needs_revisit = true;\n }\n\n if !needs_revisit {\n debug!(\"'{}' already resolved with compatible status/tags.\", name);\n } else {\n debug!(\n \"Re-evaluating dependencies for '{}' due to status/tag update\",\n name\n );\n }\n\n Ok(needs_revisit)\n }\n\n fn should_upgrade_optional_status_static(\n current_status: ResolutionStatus,\n tags_from_parent_edge: DependencyTag,\n is_initial_target: bool,\n _has_keg: bool,\n skip_recommended: bool,\n include_optional: bool,\n ) -> bool {\n current_status == ResolutionStatus::SkippedOptional\n && (tags_from_parent_edge.contains(DependencyTag::RUNTIME)\n || tags_from_parent_edge.contains(DependencyTag::BUILD)\n || (tags_from_parent_edge.contains(DependencyTag::RECOMMENDED)\n && !skip_recommended)\n || (is_initial_target && include_optional))\n }\n\n fn load_or_cache_formula(\n &mut self,\n name: &str,\n tags_from_parent_edge: DependencyTag,\n ) -> Result>> {\n if let Some(f) = self.formula_cache.get(name) {\n return Ok(Some(f.clone()));\n }\n\n debug!(\"Loading formula definition for '{}'\", name);\n match self.context.formulary.load_formula(name) {\n Ok(f) => {\n let arc = Arc::new(f);\n self.formula_cache.insert(name.to_string(), arc.clone());\n Ok(Some(arc))\n }\n Err(e) => {\n error!(\"Failed to load formula definition for '{}': {}\", name, e);\n let msg = e.to_string();\n self.resolution_details.insert(\n name.to_string(),\n ResolvedDependency {\n formula: Arc::new(Formula::placeholder(name)),\n keg_path: None,\n opt_path: None,\n status: ResolutionStatus::NotFound,\n accumulated_tags: tags_from_parent_edge,\n determined_install_strategy: NodeInstallStrategy::BottlePreferred,\n failure_reason: Some(msg.clone()),\n },\n );\n self.errors\n .insert(name.to_string(), Arc::new(SpsError::NotFound(msg)));\n Ok(None)\n }\n }\n }\n\n fn create_initial_resolution(\n &mut self,\n name: &str,\n formula_arc: Arc,\n tags_from_parent_edge: DependencyTag,\n is_initial_target: bool,\n requesting_parent_strategy: Option,\n ) -> Result<()> {\n let current_node_strategy = self.determine_node_install_strategy(\n name,\n &formula_arc,\n is_initial_target,\n requesting_parent_strategy,\n );\n\n let (status, keg_path) =\n self.determine_resolution_status(name, is_initial_target, current_node_strategy)?;\n\n debug!(\n \"Initial status for '{}': {:?}, keg: {:?}, opt: {}\",\n name,\n status,\n keg_path,\n self.context.keg_registry.get_opt_path(name).display()\n );\n\n self.resolution_details.insert(\n name.to_string(),\n ResolvedDependency {\n formula: formula_arc.clone(),\n keg_path,\n opt_path: Some(self.context.keg_registry.get_opt_path(name)),\n status,\n accumulated_tags: tags_from_parent_edge,\n determined_install_strategy: current_node_strategy,\n failure_reason: None,\n },\n );\n\n Ok(())\n }\n\n fn determine_resolution_status(\n &self,\n name: &str,\n is_initial_target: bool,\n strategy: NodeInstallStrategy,\n ) -> Result<(ResolutionStatus, Option)> {\n match strategy {\n NodeInstallStrategy::SourceOnly => Ok((\n if is_initial_target {\n ResolutionStatus::Requested\n } else {\n ResolutionStatus::Missing\n },\n None,\n )),\n NodeInstallStrategy::BottlePreferred | NodeInstallStrategy::BottleOrFail => {\n if let Some(keg) = self.context.keg_registry.get_installed_keg(name)? {\n // Check if this is an upgrade target - if so, mark as Requested even if\n // installed\n let should_request_upgrade = is_initial_target\n && self\n .context\n .initial_target_actions\n .get(name)\n .map(|action| {\n matches!(action, crate::pipeline::JobAction::Upgrade { .. })\n })\n .unwrap_or(false);\n\n debug!(\"[Resolver] Package '{}': is_initial_target={}, should_request_upgrade={}, action={:?}\",\n name, is_initial_target, should_request_upgrade,\n self.context.initial_target_actions.get(name));\n\n if should_request_upgrade {\n debug!(\n \"[Resolver] Marking upgrade target '{}' as Requested (was installed)\",\n name\n );\n Ok((ResolutionStatus::Requested, Some(keg.path)))\n } else {\n debug!(\"[Resolver] Marking '{}' as Installed (normal case)\", name);\n Ok((ResolutionStatus::Installed, Some(keg.path)))\n }\n } else {\n debug!(\n \"[Resolver] Package '{}' not installed, marking as {}\",\n name,\n if is_initial_target {\n \"Requested\"\n } else {\n \"Missing\"\n }\n );\n Ok((\n if is_initial_target {\n ResolutionStatus::Requested\n } else {\n ResolutionStatus::Missing\n },\n None,\n ))\n }\n }\n }\n }\n\n fn process_dependencies(\n &mut self,\n dep_snapshot: &ResolvedDependency,\n parent_name: &str,\n ) -> Result<()> {\n for dep in dep_snapshot.formula.dependencies()? {\n let dep_name = &dep.name;\n let dep_tags = dep.tags;\n let parent_formula_name = dep_snapshot.formula.name();\n let parent_strategy = dep_snapshot.determined_install_strategy;\n\n debug!(\n \"RESOLVER: Evaluating edge: parent='{}' ({:?}), child='{}' ({:?})\",\n parent_formula_name, parent_strategy, dep_name, dep_tags\n );\n\n if !self.should_consider_dependency(&dep) {\n if !self.resolution_details.contains_key(dep_name.as_str()) {\n debug!(\"RESOLVER: Child '{}' of '{}' globally SKIPPED (e.g. optional/test not included). Tags: {:?}\", dep_name, parent_formula_name, dep_tags);\n }\n continue;\n }\n\n let should_process = self.context.should_process_dependency_edge(\n &dep_snapshot.formula,\n dep_tags,\n parent_strategy,\n );\n\n if !should_process {\n debug!(\n \"RESOLVER: Edge from '{}' (Strategy: {:?}) to child '{}' (Tags: {:?}) was SKIPPED by should_process_dependency_edge.\",\n parent_formula_name, parent_strategy, dep_name, dep_tags\n );\n continue;\n }\n\n debug!(\n \"RESOLVER: Edge from '{}' (Strategy: {:?}) to child '{}' (Tags: {:?}) WILL BE PROCESSED. Recursing.\",\n parent_formula_name, parent_strategy, dep_name, dep_tags\n );\n\n if let Err(e) = self.resolve_recursive(dep_name, dep_tags, false, Some(parent_strategy))\n {\n // Log the error but don't necessarily stop all resolution for this branch yet\n warn!(\n \"Error resolving child dependency '{}' for parent '{}': {}\",\n dep_name, parent_name, e\n );\n // Optionally, mark parent as failed if child error is critical\n // self.errors.insert(parent_name.to_string(), Arc::new(e)); // Storing error for\n // parent if needed\n }\n }\n Ok(())\n }\n\n fn resolve_recursive(\n &mut self,\n name: &str,\n tags_from_parent_edge: DependencyTag,\n is_initial_target: bool,\n requesting_parent_strategy: Option,\n ) -> Result<()> {\n debug!(\n \"Resolving: {} (requested as {:?}, is_target: {})\",\n name, tags_from_parent_edge, is_initial_target\n );\n\n if self.visiting.contains(name) {\n error!(\"Dependency cycle detected involving: {}\", name);\n return Err(SpsError::DependencyError(format!(\n \"Dependency cycle detected involving '{name}'\"\n )));\n }\n\n if self.update_existing_resolution(name, tags_from_parent_edge, is_initial_target)? {\n // Already exists and was updated, no need to reprocess\n return Ok(());\n }\n\n if self.resolution_details.contains_key(name) {\n // Already exists but didn't need update\n return Ok(());\n }\n\n // New resolution needed\n self.visiting.insert(name.to_string());\n\n let formula_arc = match self.load_or_cache_formula(name, tags_from_parent_edge) {\n Ok(Some(formula)) => formula,\n Ok(None) => {\n self.visiting.remove(name);\n return Ok(()); // Already handled error case\n }\n Err(e) => {\n self.visiting.remove(name);\n return Err(e);\n }\n };\n\n self.create_initial_resolution(\n name,\n formula_arc,\n tags_from_parent_edge,\n is_initial_target,\n requesting_parent_strategy,\n )?;\n\n let dep_snapshot = self\n .resolution_details\n .get(name)\n .expect(\"just inserted\")\n .clone();\n\n if matches!(\n dep_snapshot.status,\n ResolutionStatus::Failed | ResolutionStatus::NotFound\n ) {\n self.visiting.remove(name);\n return Ok(());\n }\n\n self.process_dependencies(&dep_snapshot, name)?;\n\n self.visiting.remove(name);\n debug!(\"Finished resolving '{}'\", name);\n Ok(())\n }\n\n fn topological_sort(&self) -> Result> {\n let mut in_degree: HashMap = HashMap::new();\n let mut adj: HashMap> = HashMap::new();\n let mut sorted_list = Vec::new();\n let mut queue = VecDeque::new();\n\n let relevant_nodes_map: HashMap = self\n .resolution_details\n .iter()\n .filter(|(_, dep)| {\n !matches!(\n dep.status,\n ResolutionStatus::NotFound | ResolutionStatus::Failed\n )\n })\n .map(|(k, v)| (k.clone(), v))\n .collect();\n\n for (parent_name, parent_rd) in &relevant_nodes_map {\n adj.entry(parent_name.clone()).or_default();\n in_degree.entry(parent_name.clone()).or_default();\n\n let parent_strategy = parent_rd.determined_install_strategy;\n if let Ok(dependencies) = parent_rd.formula.dependencies() {\n for child_edge in dependencies {\n let child_name = &child_edge.name;\n if relevant_nodes_map.contains_key(child_name)\n && self.context.should_process_dependency_edge(\n &parent_rd.formula,\n child_edge.tags,\n parent_strategy,\n )\n && adj\n .entry(parent_name.clone())\n .or_default()\n .insert(child_name.clone())\n {\n *in_degree.entry(child_name.clone()).or_default() += 1;\n }\n }\n }\n }\n\n for name in relevant_nodes_map.keys() {\n if *in_degree.get(name).unwrap_or(&1) == 0 {\n queue.push_back(name.clone());\n }\n }\n\n while let Some(u_name) = queue.pop_front() {\n if let Some(resolved_dep) = relevant_nodes_map.get(&u_name) {\n sorted_list.push((**resolved_dep).clone()); // Deref Arc then clone\n // ResolvedDependency\n }\n if let Some(neighbors) = adj.get(&u_name) {\n for v_name in neighbors {\n if relevant_nodes_map.contains_key(v_name) {\n // Check if neighbor is relevant\n if let Some(degree) = in_degree.get_mut(v_name) {\n *degree = degree.saturating_sub(1);\n if *degree == 0 {\n queue.push_back(v_name.clone());\n }\n }\n }\n }\n }\n }\n\n // Check for cycles: if sorted_list's length doesn't match relevant_nodes_map's length\n // (excluding already installed, skipped optional if not included, etc.)\n // A more direct check is if in_degree still contains non-zero values for relevant nodes.\n let mut cycle_detected = false;\n for (name, °ree) in &in_degree {\n if degree > 0 && relevant_nodes_map.contains_key(name) {\n // Further check if this node should have been processed (not skipped globally)\n if let Some(detail) = self.resolution_details.get(name) {\n if self\n .context\n .should_consider_edge_globally(detail.accumulated_tags)\n {\n error!(\"Cycle detected or unresolved dependency: Node '{}' still has in-degree {}. Tags: {:?}\", name, degree, detail.accumulated_tags);\n cycle_detected = true;\n } else {\n debug!(\"Node '{}' has in-degree {} but was globally skipped. Tags: {:?}. Not a cycle error.\", name, degree, detail.accumulated_tags);\n }\n }\n }\n }\n\n if cycle_detected {\n return Err(SpsError::DependencyError(\n \"Circular dependency detected or graph resolution incomplete\".to_string(),\n ));\n }\n\n Ok(sorted_list) // Return the full sorted list of relevant nodes\n }\n\n fn should_consider_dependency(&self, dep: &Dependency) -> bool {\n let tags = dep.tags;\n if tags.contains(DependencyTag::TEST) && !self.context.include_test {\n return false;\n }\n if tags.contains(DependencyTag::OPTIONAL) && !self.context.include_optional {\n return false;\n }\n if tags.contains(DependencyTag::RECOMMENDED) && self.context.skip_recommended {\n return false;\n }\n true\n }\n}\n\nimpl Formula {\n fn placeholder(name: &str) -> Self {\n Self {\n name: name.to_string(),\n stable_version_str: \"0.0.0\".to_string(),\n version_semver: semver::Version::new(0, 0, 0), // Direct use\n revision: 0,\n desc: Some(\"Placeholder for unresolved formula\".to_string()),\n homepage: None,\n url: String::new(),\n sha256: String::new(),\n mirrors: Vec::new(),\n bottle: Default::default(),\n dependencies: Vec::new(),\n requirements: Vec::new(),\n resources: Vec::new(),\n install_keg_path: None,\n }\n }\n}\n\nimpl<'a> ResolutionContext<'a> {\n pub fn should_process_dependency_edge(\n &self,\n parent_formula_for_logging: &Arc,\n edge_tags: DependencyTag,\n parent_node_determined_strategy: NodeInstallStrategy,\n ) -> bool {\n if !self.should_consider_edge_globally(edge_tags) {\n debug!(\n \"Edge with tags {:?} for child of '{}' globally SKIPPED (e.g. optional/test not included).\",\n edge_tags, parent_formula_for_logging.name()\n );\n return false;\n }\n\n match parent_node_determined_strategy {\n NodeInstallStrategy::BottlePreferred | NodeInstallStrategy::BottleOrFail => {\n let is_purely_build_dependency = edge_tags.contains(DependencyTag::BUILD)\n && !edge_tags.intersects(\n DependencyTag::RUNTIME\n | DependencyTag::RECOMMENDED\n | DependencyTag::OPTIONAL,\n );\n if is_purely_build_dependency {\n debug!(\"Edge with tags {:?} SKIPPED: Pure BUILD dependency of a bottle-installed parent '{}'.\", edge_tags, parent_formula_for_logging.name());\n return false;\n }\n }\n NodeInstallStrategy::SourceOnly => {\n // Process all relevant (non-globally-skipped) dependencies for source builds\n }\n }\n debug!(\n \"Edge with tags {:?} WILL BE PROCESSED for parent '{}' (strategy {:?}).\",\n edge_tags,\n parent_formula_for_logging.name(),\n parent_node_determined_strategy\n );\n true\n }\n\n pub fn should_consider_edge_globally(&self, edge_tags: DependencyTag) -> bool {\n if edge_tags.contains(DependencyTag::TEST) && !self.include_test {\n return false;\n }\n if edge_tags.contains(DependencyTag::OPTIONAL) && !self.include_optional {\n return false;\n }\n if edge_tags.contains(DependencyTag::RECOMMENDED) && self.skip_recommended {\n return false;\n }\n true\n }\n}\n"], ["/sps/sps/src/cli/list.rs", "use std::sync::Arc;\n\nuse clap::Args;\nuse colored::Colorize;\nuse prettytable::{format, Cell, Row, Table};\nuse serde_json::Value;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::formulary::Formulary;\nuse sps_core::check::installed::{get_installed_packages, PackageType};\nuse sps_core::check::update::check_for_updates;\nuse sps_core::check::InstalledPackageInfo;\n\n#[derive(Args, Debug)]\npub struct List {\n /// Show only formulas\n #[arg(long = \"formula\")]\n pub formula_only: bool,\n /// Show only casks\n #[arg(long = \"cask\")]\n pub cask_only: bool,\n /// Show only packages with updates available\n #[arg(long = \"outdated\")]\n pub outdated_only: bool,\n}\n\nimpl List {\n pub async fn run(&self, config: &Config, cache: Arc) -> Result<()> {\n let installed = get_installed_packages(config).await?;\n // Only show the latest version for each name\n use std::collections::HashMap;\n let mut formula_map: HashMap<&str, &sps_core::check::installed::InstalledPackageInfo> =\n HashMap::new();\n let mut cask_map: HashMap<&str, &sps_core::check::installed::InstalledPackageInfo> =\n HashMap::new();\n for pkg in &installed {\n match pkg.pkg_type {\n PackageType::Formula => {\n let entry = formula_map.entry(pkg.name.as_str()).or_insert(pkg);\n if pkg.version > entry.version {\n formula_map.insert(pkg.name.as_str(), pkg);\n }\n }\n PackageType::Cask => {\n let entry = cask_map.entry(pkg.name.as_str()).or_insert(pkg);\n if pkg.version > entry.version {\n cask_map.insert(pkg.name.as_str(), pkg);\n }\n }\n }\n }\n let mut formulas: Vec<&InstalledPackageInfo> = formula_map.values().copied().collect();\n let mut casks: Vec<&InstalledPackageInfo> = cask_map.values().copied().collect();\n // Sort formulas and casks alphabetically by name, then version\n formulas.sort_by(|a, b| a.name.cmp(&b.name).then(a.version.cmp(&b.version)));\n casks.sort_by(|a, b| a.name.cmp(&b.name).then(a.version.cmp(&b.version)));\n // If Nothing Installed.\n if formulas.is_empty() && casks.is_empty() {\n println!(\"{}\", \"0 formulas and casks installed\".yellow());\n return Ok(());\n }\n // If user wants to show installed formulas only.\n if self.formula_only {\n if self.outdated_only {\n self.print_outdated_formulas_table(&formulas, config)\n .await?;\n } else {\n self.print_formulas_table(formulas, config);\n }\n return Ok(());\n }\n // If user wants to show installed casks only.\n if self.cask_only {\n if self.outdated_only {\n self.print_outdated_casks_table(&casks, cache.clone())\n .await?;\n } else {\n self.print_casks_table(casks, cache);\n }\n return Ok(());\n }\n\n // If user wants to show only outdated packages\n if self.outdated_only {\n self.print_outdated_all_table(&formulas, &casks, config, cache)\n .await?;\n return Ok(());\n }\n\n // Default Implementation\n let formulary = Formulary::new(config.clone());\n let mut table = Table::new();\n table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n table.add_row(Row::new(vec![\n Cell::new(\"Type\").style_spec(\"b\"),\n Cell::new(\"Name\").style_spec(\"b\"),\n Cell::new(\"Installed\").style_spec(\"b\"),\n Cell::new(\"New Version?\").style_spec(\"b\"),\n ]));\n let mut formula_count = 0;\n let mut cask_count = 0;\n for pkg in formulas {\n let latest = formulary.load_formula(&pkg.name).ok();\n let (has_new, _) = match latest {\n Some(ref f) => {\n let latest_version = f.version_str_full();\n (latest_version != pkg.version, latest_version)\n }\n None => (false, \"-\".to_string()),\n };\n table.add_row(Row::new(vec![\n Cell::new(\"Formula\").style_spec(\"Fg\"),\n Cell::new(&pkg.name).style_spec(\"Fb\"),\n Cell::new(&pkg.version),\n // TODO: update to display the latest version string.\n // TODO: Not showing when the using --all flag.\n Cell::new(if has_new { \"✔\" } else { \"\" }),\n ]));\n formula_count += 1;\n }\n for pkg in casks {\n // Try to load cask info from cache\n let cask_val = cache.load_raw(\"cask.json\").ok().and_then(|raw| {\n serde_json::from_str::>(&raw)\n .ok()?\n .into_iter()\n .find(|v| v.get(\"token\").and_then(|t| t.as_str()) == Some(&pkg.name))\n });\n let (has_new, _) = match cask_val {\n Some(ref v) => {\n let latest_version = v.get(\"version\").and_then(|v| v.as_str()).unwrap_or(\"-\");\n (latest_version != pkg.version, latest_version.to_string())\n }\n None => (false, \"-\".to_string()),\n };\n table.add_row(Row::new(vec![\n Cell::new(\"Cask\").style_spec(\"Fy\"),\n Cell::new(&pkg.name).style_spec(\"Fb\"),\n Cell::new(&pkg.version),\n Cell::new(if has_new { \"✔\" } else { \"\" }),\n ]));\n cask_count += 1;\n }\n table.printstd();\n if formula_count > 0 && cask_count > 0 {\n println!(\n \"{}\",\n format!(\"{formula_count} formulas, {cask_count} casks installed\").bold()\n );\n } else if formula_count > 0 {\n println!(\"{}\", format!(\"{formula_count} formulas installed\").bold());\n } else if cask_count > 0 {\n println!(\"{}\", format!(\"{cask_count} casks installed\").bold());\n }\n Ok(())\n }\n\n fn print_formulas_table(\n &self,\n formulas: Vec<&sps_core::check::installed::InstalledPackageInfo>,\n config: &Config,\n ) {\n if formulas.is_empty() {\n println!(\"No formulas installed.\");\n return;\n }\n let formulary = Formulary::new(config.clone());\n let mut table = Table::new();\n table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n // Add header row with \"Formulas\" spanning all columns, font color green\n table.add_row(Row::new(vec![Cell::new_align(\n \"Formulas\",\n format::Alignment::CENTER,\n )\n .style_spec(\"bFg\")\n .with_hspan(3)]));\n table.add_row(Row::new(vec![\n Cell::new(\"Name\").style_spec(\"b\"),\n Cell::new(\"Installed\").style_spec(\"b\"),\n Cell::new(\"New Version?\").style_spec(\"b\"),\n ]));\n let mut formula_count = 0;\n for pkg in formulas {\n let latest = formulary.load_formula(&pkg.name).ok();\n let (has_new, _) = match latest {\n Some(ref f) => {\n let latest_version = f.version_str_full();\n (latest_version != pkg.version, latest_version)\n }\n None => (false, \"-\".to_string()),\n };\n table.add_row(Row::new(vec![\n Cell::new(&pkg.name).style_spec(\"Fb\"),\n Cell::new(&pkg.version),\n Cell::new(if has_new { \"✔\" } else { \"\" }),\n ]));\n formula_count += 1;\n }\n table.printstd();\n println!(\"{}\", format!(\"{formula_count} formulas installed\").bold());\n }\n\n fn print_casks_table(\n &self,\n casks: Vec<&sps_core::check::installed::InstalledPackageInfo>,\n cache: Arc,\n ) {\n if casks.is_empty() {\n println!(\"No casks installed.\");\n return;\n }\n let mut table = Table::new();\n table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n // Add header row with \"Casks\" spanning all columns, font color green\n table.add_row(Row::new(vec![Cell::new_align(\n \"Casks\",\n format::Alignment::CENTER,\n )\n .style_spec(\"bFg\")\n .with_hspan(3)]));\n table.add_row(Row::new(vec![\n Cell::new(\"Name\").style_spec(\"b\"),\n Cell::new(\"Installed\").style_spec(\"b\"),\n Cell::new(\"New Version?\").style_spec(\"b\"),\n ]));\n let mut cask_count = 0;\n for pkg in casks {\n // Try to load cask info from cache\n let cask_val = cache.load_raw(\"cask.json\").ok().and_then(|raw| {\n serde_json::from_str::>(&raw)\n .ok()?\n .into_iter()\n .find(|v| v.get(\"token\").and_then(|t| t.as_str()) == Some(&pkg.name))\n });\n let (has_new, _) = match cask_val {\n Some(ref v) => {\n let latest_version = v.get(\"version\").and_then(|v| v.as_str()).unwrap_or(\"-\");\n (latest_version != pkg.version, latest_version.to_string())\n }\n None => (false, \"-\".to_string()),\n };\n table.add_row(Row::new(vec![\n Cell::new(&pkg.name).style_spec(\"Fb\"),\n Cell::new(&pkg.version),\n Cell::new(if has_new { \"✔\" } else { \"\" }),\n ]));\n cask_count += 1;\n }\n table.printstd();\n println!(\"{}\", format!(\"{cask_count} casks installed\").bold());\n }\n\n async fn print_outdated_formulas_table(\n &self,\n formulas: &[&InstalledPackageInfo],\n config: &Config,\n ) -> Result<()> {\n if formulas.is_empty() {\n println!(\"No formulas installed.\");\n return Ok(());\n }\n\n // Convert to owned for update checking\n let formula_packages: Vec =\n formulas.iter().map(|&f| f.clone()).collect();\n let cache = sps_common::cache::Cache::new(config)?;\n let updates = check_for_updates(&formula_packages, &cache, config).await?;\n\n if updates.is_empty() {\n println!(\"No formula updates available.\");\n return Ok(());\n }\n\n let mut table = Table::new();\n table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n table.add_row(Row::new(vec![Cell::new_align(\n \"Outdated Formulas\",\n format::Alignment::CENTER,\n )\n .style_spec(\"bFg\")\n .with_hspan(3)]));\n table.add_row(Row::new(vec![\n Cell::new(\"Name\").style_spec(\"b\"),\n Cell::new(\"Installed\").style_spec(\"b\"),\n Cell::new(\"Available\").style_spec(\"b\"),\n ]));\n\n let mut count = 0;\n for update in updates {\n table.add_row(Row::new(vec![\n Cell::new(&update.name).style_spec(\"Fb\"),\n Cell::new(&update.installed_version),\n Cell::new(&update.available_version).style_spec(\"Fg\"),\n ]));\n count += 1;\n }\n\n table.printstd();\n println!(\"{}\", format!(\"{count} outdated formulas\").bold());\n Ok(())\n }\n\n async fn print_outdated_casks_table(\n &self,\n casks: &[&InstalledPackageInfo],\n cache: Arc,\n ) -> Result<()> {\n if casks.is_empty() {\n println!(\"No casks installed.\");\n return Ok(());\n }\n\n // Convert to owned for update checking\n let cask_packages: Vec = casks.iter().map(|&c| c.clone()).collect();\n let config = cache.config();\n let updates = check_for_updates(&cask_packages, &cache, config).await?;\n\n if updates.is_empty() {\n println!(\"No cask updates available.\");\n return Ok(());\n }\n\n let mut table = Table::new();\n table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n table.add_row(Row::new(vec![Cell::new_align(\n \"Outdated Casks\",\n format::Alignment::CENTER,\n )\n .style_spec(\"bFg\")\n .with_hspan(3)]));\n table.add_row(Row::new(vec![\n Cell::new(\"Name\").style_spec(\"b\"),\n Cell::new(\"Installed\").style_spec(\"b\"),\n Cell::new(\"Available\").style_spec(\"b\"),\n ]));\n\n let mut count = 0;\n for update in updates {\n table.add_row(Row::new(vec![\n Cell::new(&update.name).style_spec(\"Fb\"),\n Cell::new(&update.installed_version),\n Cell::new(&update.available_version).style_spec(\"Fy\"),\n ]));\n count += 1;\n }\n\n table.printstd();\n println!(\"{}\", format!(\"{count} outdated casks\").bold());\n Ok(())\n }\n\n async fn print_outdated_all_table(\n &self,\n formulas: &[&InstalledPackageInfo],\n casks: &[&InstalledPackageInfo],\n config: &Config,\n cache: Arc,\n ) -> Result<()> {\n // Convert to owned for update checking\n let mut all_packages: Vec = Vec::new();\n all_packages.extend(formulas.iter().map(|&f| f.clone()));\n all_packages.extend(casks.iter().map(|&c| c.clone()));\n\n if all_packages.is_empty() {\n println!(\"{}\", \"0 formulas and casks installed\".yellow());\n return Ok(());\n }\n\n let updates = check_for_updates(&all_packages, &cache, config).await?;\n\n if updates.is_empty() {\n println!(\"No outdated packages found.\");\n return Ok(());\n }\n\n let mut table = Table::new();\n table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n table.add_row(Row::new(vec![\n Cell::new(\"Type\").style_spec(\"b\"),\n Cell::new(\"Name\").style_spec(\"b\"),\n Cell::new(\"Installed\").style_spec(\"b\"),\n Cell::new(\"Available\").style_spec(\"b\"),\n ]));\n\n let mut formula_count = 0;\n let mut cask_count = 0;\n\n for update in updates {\n let (type_name, type_style) = match update.pkg_type {\n PackageType::Formula => {\n formula_count += 1;\n (\"Formula\", \"Fg\")\n }\n PackageType::Cask => {\n cask_count += 1;\n (\"Cask\", \"Fy\")\n }\n };\n\n table.add_row(Row::new(vec![\n Cell::new(type_name).style_spec(type_style),\n Cell::new(&update.name).style_spec(\"Fb\"),\n Cell::new(&update.installed_version),\n Cell::new(&update.available_version).style_spec(\"Fg\"),\n ]));\n }\n\n table.printstd();\n if formula_count > 0 && cask_count > 0 {\n println!(\n \"{}\",\n format!(\"{formula_count} outdated formulas, {cask_count} outdated casks\").bold()\n );\n } else if formula_count > 0 {\n println!(\"{}\", format!(\"{formula_count} outdated formulas\").bold());\n } else if cask_count > 0 {\n println!(\"{}\", format!(\"{cask_count} outdated casks\").bold());\n }\n Ok(())\n }\n}\n"], ["/sps/sps/src/cli/init.rs", "// sps/src/cli/init.rs\nuse std::fs::{self, File, OpenOptions};\nuse std::io::{BufRead, BufReader, Write};\nuse std::path::{Path, PathBuf};\nuse std::process::Command as StdCommand;\nuse std::sync::Arc;\n\nuse clap::Args;\nuse colored::Colorize;\nuse sps_common::config::Config; // Assuming Config is correctly in sps_common\nuse sps_common::error::{Result as SpsResult, SpsError};\nuse tempfile;\nuse tracing::{debug, error, warn};\n\n#[derive(Args, Debug)]\npub struct InitArgs {\n /// Force initialization even if /opt/sps appears to be an sps root already.\n #[arg(long)]\n pub force: bool,\n}\n\nimpl InitArgs {\n pub async fn run(&self, config: &Config) -> SpsResult<()> {\n debug!(\n \"Initializing sps environment at {}\",\n config.sps_root().display()\n );\n\n let sps_root = config.sps_root();\n let marker_path = config.sps_root_marker_path();\n\n // 1. Initial Checks (as current user) - (No change from your existing logic)\n if sps_root.exists() {\n let is_empty = match fs::read_dir(sps_root) {\n Ok(mut entries) => entries.next().is_none(),\n Err(_) => false, // If we can't read it, assume not empty or not accessible\n };\n\n if marker_path.exists() && !self.force {\n debug!(\n \"{} already exists. sps appears to be initialized. Use --force to re-initialize.\",\n marker_path.display()\n );\n return Ok(());\n }\n if !self.force && !is_empty && !marker_path.exists() {\n warn!(\n \"Directory {} exists but does not appear to be an sps root (missing marker {}).\",\n sps_root.display(),\n marker_path.file_name().unwrap_or_default().to_string_lossy()\n );\n warn!(\n \"Run with --force to initialize anyway (this might overwrite existing data or change permissions).\"\n );\n return Err(SpsError::Config(format!(\n \"{} exists but is not a recognized sps root. Aborting.\",\n sps_root.display()\n )));\n }\n if self.force {\n debug!(\n \"--force specified. Proceeding with initialization in {}.\",\n sps_root.display()\n );\n } else if is_empty {\n debug!(\n \"Directory {} exists but is empty. Proceeding with initialization.\",\n sps_root.display()\n );\n }\n }\n\n // 2. Privileged Operations\n let current_user_name = std::env::var(\"USER\")\n .or_else(|_| std::env::var(\"LOGNAME\"))\n .map_err(|_| {\n SpsError::Generic(\n \"Failed to get current username from USER or LOGNAME environment variables.\"\n .to_string(),\n )\n })?;\n\n let target_group_name = if cfg!(target_os = \"macos\") {\n \"admin\" // Standard admin group on macOS\n } else {\n // For Linux, 'staff' might not exist or be appropriate.\n // Often, the user's primary group is used, or a dedicated 'brew' group.\n // For simplicity, let's try to use the current user's name as the group too,\n // which works if the user has a group with the same name.\n // A more robust Linux solution might involve checking for 'staff' or other common\n // groups.\n ¤t_user_name\n };\n\n debug!(\n \"Will attempt to set ownership of sps-managed directories under {} to {}:{}\",\n sps_root.display(),\n current_user_name,\n target_group_name\n );\n\n println!(\n \"{}\",\n format!(\n \"sps may require sudo to create directories and set permissions in {}.\",\n sps_root.display()\n )\n .yellow()\n );\n\n // Define directories sps needs to ensure exist and can manage.\n // These are derived from your Config struct.\n let dirs_to_create_and_manage: Vec = vec![\n config.sps_root().to_path_buf(), // The root itself\n config.bin_dir(),\n config.cellar_dir(),\n config.cask_room_dir(),\n config.cask_store_dir(), // sps-specific\n config.opt_dir(),\n config.taps_dir(), // This is now sps_root/Library/Taps\n config.cache_dir(), // sps-specific (e.g., sps_root/sps_cache)\n config.logs_dir(), // sps-specific (e.g., sps_root/sps_logs)\n config.tmp_dir(),\n config.state_dir(),\n config\n .man_base_dir()\n .parent()\n .unwrap_or(sps_root)\n .to_path_buf(), // share\n config.man_base_dir(), // share/man\n config.sps_root().join(\"etc\"),\n config.sps_root().join(\"include\"),\n config.sps_root().join(\"lib\"),\n config.sps_root().join(\"share/doc\"),\n ];\n\n // Create directories with mkdir -p (non-destructive)\n for dir_path in &dirs_to_create_and_manage {\n // Only create if it doesn't exist to avoid unnecessary sudo calls if already present\n if !dir_path.exists() {\n debug!(\n \"Ensuring directory exists with sudo: {}\",\n dir_path.display()\n );\n run_sudo_command(\"mkdir\", &[\"-p\", &dir_path.to_string_lossy()])?;\n } else {\n debug!(\n \"Directory already exists, skipping mkdir: {}\",\n dir_path.display()\n );\n }\n }\n\n // Create the marker file (non-destructive to other content)\n debug!(\n \"Creating/updating marker file with sudo: {}\",\n marker_path.display()\n );\n let marker_content = \"sps root directory version 1\";\n // Using a temporary file for sudo tee to avoid permission issues with direct pipe\n let temp_marker_file =\n tempfile::NamedTempFile::new().map_err(|e| SpsError::Io(Arc::new(e)))?;\n fs::write(temp_marker_file.path(), marker_content)\n .map_err(|e| SpsError::Io(Arc::new(e)))?;\n run_sudo_command(\n \"cp\",\n &[\n temp_marker_file.path().to_str().unwrap(),\n marker_path.to_str().unwrap(),\n ],\n )?;\n\n #[cfg(unix)]\n {\n // More targeted chown and chmod\n debug!(\n \"Setting ownership and permissions for sps-managed directories under {}...\",\n sps_root.display()\n );\n\n // Chown/Chmod the top-level sps_root directory itself (non-recursively for chmod\n // initially) This is important if sps_root is /opt/sps and was just created\n // by root. If sps_root is /opt/homebrew, this ensures the current user can\n // at least manage it.\n run_sudo_command(\n \"chown\",\n &[\n &format!(\"{current_user_name}:{target_group_name}\"),\n &sps_root.to_string_lossy(),\n ],\n )?;\n run_sudo_command(\"chmod\", &[\"ug=rwx,o=rx\", &sps_root.to_string_lossy()])?; // 755 for the root\n\n // For specific subdirectories that sps actively manages and writes into frequently,\n // ensure they are owned by the user and have appropriate permissions.\n // We apply this recursively to sps-specific dirs and key shared dirs.\n let dirs_for_recursive_chown_chmod: Vec = vec![\n config.cellar_dir(),\n config.cask_room_dir(),\n config.cask_store_dir(), // sps-specific, definitely needs full user control\n config.opt_dir(),\n config.taps_dir(),\n config.cache_dir(), // sps-specific\n config.logs_dir(), // sps-specific\n config.tmp_dir(),\n config.state_dir(),\n // bin, lib, include, share, etc are often symlink farms.\n // The top-level of these should be writable by the user to create symlinks.\n // The actual kegs in Cellar will have their own permissions.\n config.bin_dir(),\n config.sps_root().join(\"lib\"),\n config.sps_root().join(\"include\"),\n config.sps_root().join(\"share\"),\n config.sps_root().join(\"etc\"),\n ];\n\n for dir_path in dirs_for_recursive_chown_chmod {\n if dir_path.exists() {\n // Only operate on existing directories\n debug!(\"Setting ownership (recursive) for: {}\", dir_path.display());\n run_sudo_command(\n \"chown\",\n &[\n \"-R\",\n &format!(\"{current_user_name}:{target_group_name}\"),\n &dir_path.to_string_lossy(),\n ],\n )?;\n\n debug!(\n \"Setting permissions (recursive ug=rwX,o=rX) for: {}\",\n dir_path.display()\n );\n run_sudo_command(\"chmod\", &[\"-R\", \"ug=rwX,o=rX\", &dir_path.to_string_lossy()])?;\n } else {\n warn!(\n \"Directory {} was expected but not found for chown/chmod. Marker: {}\",\n dir_path.display(),\n marker_path.display()\n );\n }\n }\n\n // Ensure bin is executable by all\n if config.bin_dir().exists() {\n debug!(\n \"Ensuring execute permissions for bin_dir: {}\",\n config.bin_dir().display()\n );\n run_sudo_command(\"chmod\", &[\"a+x\", &config.bin_dir().to_string_lossy()])?;\n // Also ensure contents of bin (wrappers, symlinks) are executable if they weren't\n // caught by -R ug=rwX This might be redundant if -R ug=rwX\n // correctly sets X for existing executables, but explicit `chmod\n // a+x` on individual files might be needed if they are newly created by sps.\n // For now, relying on the recursive chmod and the a+x on the bin_dir itself.\n }\n\n // Debug listing (optional, can be verbose)\n if tracing::enabled!(tracing::Level::DEBUG) {\n debug!(\"Listing {} after permission changes:\", sps_root.display());\n let ls_output_root = StdCommand::new(\"ls\").arg(\"-ld\").arg(sps_root).output();\n if let Ok(out) = ls_output_root {\n debug!(\n \"ls -ld {}: \\nSTDOUT: {}\\nSTDERR: {}\",\n sps_root.display(),\n String::from_utf8_lossy(&out.stdout),\n String::from_utf8_lossy(&out.stderr)\n );\n }\n for dir_path in &dirs_to_create_and_manage {\n if dir_path.exists() && dir_path != sps_root {\n let ls_output_sub = StdCommand::new(\"ls\").arg(\"-ld\").arg(dir_path).output();\n if let Ok(out) = ls_output_sub {\n debug!(\n \"ls -ld {}: \\nSTDOUT: {}\\nSTDERR: {}\",\n dir_path.display(),\n String::from_utf8_lossy(&out.stdout),\n String::from_utf8_lossy(&out.stderr)\n );\n }\n }\n }\n }\n }\n\n // 3. User-Specific PATH Configuration (runs as the original user) - (No change from your\n // existing logic)\n if let Err(e) = configure_shell_path(config, ¤t_user_name) {\n warn!(\n \"Could not fully configure shell PATH: {}. Manual configuration might be needed.\",\n e\n );\n print_manual_path_instructions(&config.bin_dir().to_string_lossy());\n }\n\n debug!(\n \"{} {}\",\n \"Successfully initialized sps environment at\".green(),\n config.sps_root().display().to_string().green()\n );\n Ok(())\n }\n}\n\n// run_sudo_command helper (no change from your existing logic)\nfn run_sudo_command(command: &str, args: &[&str]) -> SpsResult<()> {\n debug!(\"Running sudo {} {:?}\", command, args);\n let output = StdCommand::new(\"sudo\")\n .arg(command)\n .args(args)\n .output()\n .map_err(|e| SpsError::Io(Arc::new(e)))?;\n\n if !output.status.success() {\n let stderr = String::from_utf8_lossy(&output.stderr);\n let stdout = String::from_utf8_lossy(&output.stdout);\n error!(\n \"sudo {} {:?} failed ({}):\\nStdout: {}\\nStderr: {}\",\n command,\n args,\n output.status,\n stdout.trim(),\n stderr.trim()\n );\n Err(SpsError::Generic(format!(\n \"Failed to execute `sudo {} {:?}`: {}\",\n command,\n args,\n stderr.trim()\n )))\n } else {\n Ok(())\n }\n}\n\n// configure_shell_path helper (no change from your existing logic)\nfn configure_shell_path(config: &Config, current_user_name_for_log: &str) -> SpsResult<()> {\n debug!(\"Attempting to configure your shell for sps PATH...\");\n\n let sps_bin_path_str = config.bin_dir().to_string_lossy().into_owned();\n let home_dir = config.home_dir();\n if home_dir == PathBuf::from(\"/\") && current_user_name_for_log != \"root\" {\n warn!(\n \"Could not reliably determine your home directory (got '/'). Please add {} to your PATH manually for user {}.\",\n sps_bin_path_str, current_user_name_for_log\n );\n print_manual_path_instructions(&sps_bin_path_str);\n return Ok(());\n }\n\n let shell_path_env = std::env::var(\"SHELL\").unwrap_or_else(|_| \"unknown\".to_string());\n let mut config_files_updated: Vec = Vec::new();\n let mut path_seems_configured = false;\n\n let sps_path_line_zsh_bash = format!(\"export PATH=\\\"{sps_bin_path_str}:$PATH\\\"\");\n let sps_path_line_fish = format!(\"fish_add_path -P \\\"{sps_bin_path_str}\\\"\");\n\n if shell_path_env.contains(\"zsh\") {\n let zshrc_path = home_dir.join(\".zshrc\");\n if update_shell_config(\n &zshrc_path,\n &sps_path_line_zsh_bash,\n &sps_bin_path_str,\n \"Zsh\",\n false,\n )? {\n config_files_updated.push(zshrc_path.display().to_string());\n } else if line_exists_in_file(&zshrc_path, &sps_bin_path_str)? {\n path_seems_configured = true;\n }\n } else if shell_path_env.contains(\"bash\") {\n let bashrc_path = home_dir.join(\".bashrc\");\n let bash_profile_path = home_dir.join(\".bash_profile\");\n let profile_path = home_dir.join(\".profile\");\n\n let mut bash_updated_by_sps = false;\n if update_shell_config(\n &bashrc_path,\n &sps_path_line_zsh_bash,\n &sps_bin_path_str,\n \"Bash (.bashrc)\",\n false,\n )? {\n config_files_updated.push(bashrc_path.display().to_string());\n bash_updated_by_sps = true;\n if bash_profile_path.exists() {\n ensure_profile_sources_rc(&bash_profile_path, &bashrc_path, \"Bash (.bash_profile)\");\n } else if profile_path.exists() {\n ensure_profile_sources_rc(&profile_path, &bashrc_path, \"Bash (.profile)\");\n } else {\n debug!(\"Neither .bash_profile nor .profile found. Creating .bash_profile to source .bashrc.\");\n ensure_profile_sources_rc(&bash_profile_path, &bashrc_path, \"Bash (.bash_profile)\");\n }\n } else if update_shell_config(\n &bash_profile_path,\n &sps_path_line_zsh_bash,\n &sps_bin_path_str,\n \"Bash (.bash_profile)\",\n false,\n )? {\n config_files_updated.push(bash_profile_path.display().to_string());\n bash_updated_by_sps = true;\n } else if update_shell_config(\n &profile_path,\n &sps_path_line_zsh_bash,\n &sps_bin_path_str,\n \"Bash (.profile)\",\n false,\n )? {\n config_files_updated.push(profile_path.display().to_string());\n bash_updated_by_sps = true;\n }\n\n if !bash_updated_by_sps\n && (line_exists_in_file(&bashrc_path, &sps_bin_path_str)?\n || line_exists_in_file(&bash_profile_path, &sps_bin_path_str)?\n || line_exists_in_file(&profile_path, &sps_bin_path_str)?)\n {\n path_seems_configured = true;\n }\n } else if shell_path_env.contains(\"fish\") {\n let fish_config_dir = home_dir.join(\".config/fish\");\n if !fish_config_dir.exists() {\n if let Err(e) = fs::create_dir_all(&fish_config_dir) {\n warn!(\n \"Could not create Fish config directory {}: {}\",\n fish_config_dir.display(),\n e\n );\n }\n }\n if fish_config_dir.exists() {\n let fish_config_path = fish_config_dir.join(\"config.fish\");\n if update_shell_config(\n &fish_config_path,\n &sps_path_line_fish,\n &sps_bin_path_str,\n \"Fish\",\n true,\n )? {\n config_files_updated.push(fish_config_path.display().to_string());\n } else if line_exists_in_file(&fish_config_path, &sps_bin_path_str)? {\n path_seems_configured = true;\n }\n }\n } else {\n warn!(\n \"Unsupported shell for automatic PATH configuration: {}. Please add {} to your PATH manually.\",\n shell_path_env, sps_bin_path_str\n );\n print_manual_path_instructions(&sps_bin_path_str);\n return Ok(());\n }\n\n if !config_files_updated.is_empty() {\n println!(\n \"{} {} has been added to your PATH by modifying: {}\",\n \"sps\".cyan(),\n sps_bin_path_str.cyan(),\n config_files_updated.join(\", \").white()\n );\n println!(\n \"{}\",\n \"Please open a new terminal session or source your shell configuration file for the changes to take effect.\"\n .yellow()\n );\n if shell_path_env.contains(\"zsh\") {\n println!(\" Run: {}\", \"source ~/.zshrc\".green());\n }\n if shell_path_env.contains(\"bash\") {\n println!(\n \" Run: {} (or {} or {})\",\n \"source ~/.bashrc\".green(),\n \"source ~/.bash_profile\".green(),\n \"source ~/.profile\".green()\n );\n }\n if shell_path_env.contains(\"fish\") {\n println!(\n \" Run (usually not needed for fish_add_path, but won't hurt): {}\",\n \"source ~/.config/fish/config.fish\".green()\n );\n }\n } else if path_seems_configured {\n debug!(\"sps path ({}) is likely already configured for your shell ({}). No configuration files were modified.\", sps_bin_path_str.cyan(), shell_path_env.yellow());\n } else if !shell_path_env.is_empty() && shell_path_env != \"unknown\" {\n warn!(\"Could not automatically update PATH for your shell: {}. Please add {} to your PATH manually.\", shell_path_env.yellow(), sps_bin_path_str.cyan());\n print_manual_path_instructions(&sps_bin_path_str);\n }\n Ok(())\n}\n\n// print_manual_path_instructions helper (no change from your existing logic)\nfn print_manual_path_instructions(sps_bin_path_str: &str) {\n println!(\"\\n{} To use sps commands and installed packages directly, please add the following line to your shell configuration file:\", \"Action Required:\".yellow().bold());\n println!(\" (e.g., ~/.zshrc, ~/.bashrc, ~/.config/fish/config.fish)\");\n println!(\"\\n For Zsh or Bash:\");\n println!(\n \" {}\",\n format!(\"export PATH=\\\"{sps_bin_path_str}:$PATH\\\"\").green()\n );\n println!(\"\\n For Fish shell:\");\n println!(\n \" {}\",\n format!(\"fish_add_path -P \\\"{sps_bin_path_str}\\\"\").green()\n );\n println!(\n \"\\nThen, open a new terminal or run: {}\",\n \"source \".green()\n );\n}\n\n// line_exists_in_file helper (no change from your existing logic)\nfn line_exists_in_file(file_path: &Path, sps_bin_path_str: &str) -> SpsResult {\n if !file_path.exists() {\n return Ok(false);\n }\n let file = File::open(file_path).map_err(|e| SpsError::Io(Arc::new(e)))?;\n let reader = BufReader::new(file);\n let escaped_sps_bin_path = regex::escape(sps_bin_path_str);\n // Regex to find lines that configure PATH, trying to be robust for different shells\n // It looks for lines that set PATH or fish_user_paths and include the sps_bin_path_str\n // while trying to avoid commented out lines.\n let pattern = format!(\n r#\"(?m)^\\s*[^#]*\\b(?:PATH\\s*=|export\\s+PATH\\s*=|set\\s*(?:-gx\\s*|-U\\s*)?\\s*fish_user_paths\\b|fish_add_path\\s*(?:-P\\s*|-p\\s*)?)?[\"']?.*{escaped_sps_bin_path}.*[\"']?\"#\n );\n let search_pattern_regex = regex::Regex::new(&pattern)\n .map_err(|e| SpsError::Generic(format!(\"Failed to compile regex for PATH check: {e}\")))?;\n\n for line_result in reader.lines() {\n let line = line_result.map_err(|e| SpsError::Io(Arc::new(e)))?;\n if search_pattern_regex.is_match(&line) {\n debug!(\n \"Found sps PATH ({}) in {}: {}\",\n sps_bin_path_str,\n file_path.display(),\n line.trim()\n );\n return Ok(true);\n }\n }\n Ok(false)\n}\n\n// update_shell_config helper (no change from your existing logic)\nfn update_shell_config(\n config_path: &PathBuf,\n line_to_add: &str,\n sps_bin_path_str: &str,\n shell_name_for_log: &str,\n is_fish_shell: bool,\n) -> SpsResult {\n let sps_comment_tag_start = \"# SPS Path Management Start\";\n let sps_comment_tag_end = \"# SPS Path Management End\";\n\n if config_path.exists() {\n match line_exists_in_file(config_path, sps_bin_path_str) {\n Ok(true) => {\n debug!(\n \"sps path ({}) already configured or managed in {} ({}). Skipping modification.\",\n sps_bin_path_str,\n config_path.display(),\n shell_name_for_log\n );\n return Ok(false); // Path already seems configured\n }\n Ok(false) => { /* Proceed to add */ }\n Err(e) => {\n warn!(\n \"Could not reliably check existing configuration in {} ({}): {}. Attempting to add PATH.\",\n config_path.display(),\n shell_name_for_log,\n e\n );\n // Proceed with caution, might add duplicate if check failed but line exists\n }\n }\n }\n\n debug!(\n \"Adding sps PATH to {} ({})\",\n config_path.display(),\n shell_name_for_log\n );\n\n // Ensure parent directory exists\n if let Some(parent_dir) = config_path.parent() {\n if !parent_dir.exists() {\n fs::create_dir_all(parent_dir).map_err(|e| {\n SpsError::Io(Arc::new(std::io::Error::new(\n e.kind(),\n format!(\n \"Failed to create parent directory {}: {}\",\n parent_dir.display(),\n e\n ),\n )))\n })?;\n }\n }\n\n let mut file = OpenOptions::new()\n .append(true)\n .create(true)\n .open(config_path)\n .map_err(|e| {\n let msg = format!(\n \"Could not open/create shell config {} ({}): {}. Please add {} to your PATH manually.\",\n config_path.display(), shell_name_for_log, e, sps_bin_path_str\n );\n error!(\"{}\", msg);\n SpsError::Io(Arc::new(std::io::Error::new(e.kind(), msg)))\n })?;\n\n // Construct the block to add, ensuring it's idempotent for fish\n let block_to_add = if is_fish_shell {\n format!(\n \"\\n{sps_comment_tag_start}\\n# Add sps to PATH if not already present\\nif not contains \\\"{sps_bin_path_str}\\\" $fish_user_paths\\n {line_to_add}\\nend\\n{sps_comment_tag_end}\\n\"\n )\n } else {\n format!(\"\\n{sps_comment_tag_start}\\n{line_to_add}\\n{sps_comment_tag_end}\\n\")\n };\n\n if let Err(e) = writeln!(file, \"{block_to_add}\") {\n warn!(\n \"Failed to write to shell config {} ({}): {}\",\n config_path.display(),\n shell_name_for_log,\n e\n );\n Ok(false) // Indicate that update was not successful\n } else {\n debug!(\n \"Successfully updated {} ({}) with sps PATH.\",\n config_path.display(),\n shell_name_for_log\n );\n Ok(true) // Indicate successful update\n }\n}\n\n// ensure_profile_sources_rc helper (no change from your existing logic)\nfn ensure_profile_sources_rc(profile_path: &PathBuf, rc_path: &Path, shell_name_for_log: &str) {\n let rc_path_str = rc_path.to_string_lossy();\n // Regex to check if the profile file already sources the rc file.\n // Looks for lines like:\n // . /path/to/.bashrc\n // source /path/to/.bashrc\n // [ -f /path/to/.bashrc ] && . /path/to/.bashrc (and similar variants)\n let source_check_pattern = format!(\n r#\"(?m)^\\s*[^#]*(\\.|source|\\bsource\\b)\\s+[\"']?{}[\"']?\"#, /* More general source command\n * matching */\n regex::escape(&rc_path_str)\n );\n let source_check_regex = match regex::Regex::new(&source_check_pattern) {\n Ok(re) => re,\n Err(e) => {\n warn!(\"Failed to compile regex for sourcing check: {}. Skipping ensure_profile_sources_rc for {}\", e, profile_path.display());\n return;\n }\n };\n\n if profile_path.exists() {\n match fs::read_to_string(profile_path) {\n Ok(existing_content) => {\n if source_check_regex.is_match(&existing_content) {\n debug!(\n \"{} ({}) already sources {}.\",\n profile_path.display(),\n shell_name_for_log,\n rc_path.display()\n );\n return; // Already configured\n }\n }\n Err(e) => {\n warn!(\n \"Could not read {} to check if it sources {}: {}. Will attempt to append.\",\n profile_path.display(),\n rc_path.display(),\n e\n );\n }\n }\n }\n\n // Block to add to .bash_profile or .profile to source .bashrc\n let source_block_to_add = format!(\n \"\\n# Source {rc_filename} if it exists and is readable\\nif [ -f \\\"{rc_path_str}\\\" ] && [ -r \\\"{rc_path_str}\\\" ]; then\\n . \\\"{rc_path_str}\\\"\\nfi\\n\",\n rc_filename = rc_path.file_name().unwrap_or_default().to_string_lossy(),\n rc_path_str = rc_path_str\n );\n\n debug!(\n \"Attempting to ensure {} ({}) sources {}\",\n profile_path.display(),\n shell_name_for_log,\n rc_path.display()\n );\n\n if let Some(parent_dir) = profile_path.parent() {\n if !parent_dir.exists() {\n if let Err(e) = fs::create_dir_all(parent_dir) {\n warn!(\n \"Failed to create parent directory for {}: {}\",\n profile_path.display(),\n e\n );\n return; // Cannot proceed if parent dir creation fails\n }\n }\n }\n\n match OpenOptions::new()\n .append(true)\n .create(true)\n .open(profile_path)\n {\n Ok(mut file) => {\n if let Err(e) = writeln!(file, \"{source_block_to_add}\") {\n warn!(\n \"Failed to write to {} ({}): {}\",\n profile_path.display(),\n shell_name_for_log,\n e\n );\n } else {\n debug!(\n \"Updated {} ({}) to source {}.\",\n profile_path.display(),\n shell_name_for_log,\n rc_path.display()\n );\n }\n }\n Err(e) => {\n warn!(\n \"Could not open or create {} ({}) for updating: {}\",\n profile_path.display(),\n shell_name_for_log,\n e\n );\n }\n }\n}\n"], ["/sps/sps-common/src/model/formula.rs", "// sps-core/src/model/formula.rs\n// *** Corrected: Removed derive Deserialize from ResourceSpec, removed unused SpsError import,\n// added ResourceSpec struct and parsing ***\n\nuse std::collections::HashMap;\nuse std::path::{Path, PathBuf};\n\nuse semver::Version;\nuse serde::{de, Deserialize, Deserializer, Serialize};\nuse serde_json::Value;\nuse tracing::{debug, error};\n\nuse crate::dependency::{Dependency, DependencyTag, Requirement};\nuse crate::error::Result; // <-- Import only Result // Use log crate imports\n\n// --- Resource Spec Struct ---\n// *** Added struct definition, REMOVED #[derive(Deserialize)] ***\n#[derive(Debug, Clone, Serialize, PartialEq, Eq)]\npub struct ResourceSpec {\n pub name: String,\n pub url: String,\n pub sha256: String,\n // Add other potential fields like version if needed later\n}\n\n// --- Bottle Related Structs (Original structure) ---\n#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]\npub struct BottleFileSpec {\n pub url: String,\n pub sha256: String,\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]\npub struct BottleSpec {\n pub stable: Option,\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]\npub struct BottleStableSpec {\n pub rebuild: u32,\n #[serde(default)]\n pub files: HashMap,\n}\n\n// --- Formula Version Struct (Original structure) ---\n#[derive(Deserialize, Serialize, Debug, Clone, Default, PartialEq, Eq)]\npub struct FormulaVersions {\n pub stable: Option,\n pub head: Option,\n #[serde(default)]\n pub bottle: bool,\n}\n\n// --- Main Formula Struct ---\n// *** Added 'resources' field ***\n#[derive(Debug, Clone, Serialize, PartialEq, Eq)]\npub struct Formula {\n pub name: String,\n pub stable_version_str: String,\n #[serde(rename = \"versions\")]\n pub version_semver: Version,\n #[serde(default)]\n pub revision: u32,\n #[serde(default)]\n pub desc: Option,\n #[serde(default)]\n pub homepage: Option,\n #[serde(default)]\n pub url: String,\n #[serde(default)]\n pub sha256: String,\n #[serde(default)]\n pub mirrors: Vec,\n #[serde(default)]\n pub bottle: BottleSpec,\n #[serde(skip_deserializing)]\n pub dependencies: Vec,\n #[serde(default, deserialize_with = \"deserialize_requirements\")]\n pub requirements: Vec,\n #[serde(skip_deserializing)] // Skip direct deserialization for this field\n pub resources: Vec, // Stores parsed resources\n #[serde(skip)]\n pub install_keg_path: Option,\n}\n\n// Custom deserialization logic for Formula\nimpl<'de> Deserialize<'de> for Formula {\n fn deserialize(deserializer: D) -> std::result::Result\n where\n D: Deserializer<'de>,\n {\n // Temporary struct reflecting the JSON structure more closely\n // *** Added 'resources' field to capture raw JSON Value ***\n #[derive(Deserialize, Debug)]\n struct RawFormulaData {\n name: String,\n #[serde(default)]\n revision: u32,\n desc: Option,\n homepage: Option,\n versions: FormulaVersions,\n #[serde(default)]\n url: String,\n #[serde(default)]\n sha256: String,\n #[serde(default)]\n mirrors: Vec,\n #[serde(default)]\n bottle: BottleSpec,\n #[serde(default)]\n dependencies: Vec,\n #[serde(default)]\n build_dependencies: Vec,\n #[serde(default)]\n test_dependencies: Vec,\n #[serde(default)]\n recommended_dependencies: Vec,\n #[serde(default)]\n optional_dependencies: Vec,\n #[serde(default, deserialize_with = \"deserialize_requirements\")]\n requirements: Vec,\n #[serde(default)]\n resources: Vec, // Capture resources as generic Value first\n #[serde(default)]\n urls: Option,\n }\n\n let raw: RawFormulaData = RawFormulaData::deserialize(deserializer)?;\n\n // --- Version Parsing (Original logic) ---\n let stable_version_str = raw\n .versions\n .stable\n .clone()\n .ok_or_else(|| de::Error::missing_field(\"versions.stable\"))?;\n let version_semver = match crate::model::version::Version::parse(&stable_version_str) {\n Ok(v) => v.into(),\n Err(_) => {\n let mut majors = 0u32;\n let mut minors = 0u32;\n let mut patches = 0u32;\n let mut part_count = 0;\n for (i, part) in stable_version_str.split('.').enumerate() {\n let numeric_part = part\n .chars()\n .take_while(|c| c.is_ascii_digit())\n .collect::();\n if numeric_part.is_empty() && i > 0 {\n break;\n }\n if numeric_part.len() < part.len() && i > 0 {\n if let Ok(num) = numeric_part.parse::() {\n match i {\n 0 => majors = num,\n 1 => minors = num,\n 2 => patches = num,\n _ => {}\n }\n part_count += 1;\n }\n break;\n }\n if let Ok(num) = numeric_part.parse::() {\n match i {\n 0 => majors = num,\n 1 => minors = num,\n 2 => patches = num,\n _ => {}\n }\n part_count += 1;\n }\n if i >= 2 {\n break;\n }\n }\n let version_str_padded = match part_count {\n 1 => format!(\"{majors}.0.0\"),\n 2 => format!(\"{majors}.{minors}.0\"),\n _ => format!(\"{majors}.{minors}.{patches}\"),\n };\n match Version::parse(&version_str_padded) {\n Ok(v) => v,\n Err(_) => {\n error!(\n \"Warning: Could not parse version '{}' (sanitized to '{}') for formula '{}'. Using 0.0.0.\",\n stable_version_str, version_str_padded, raw.name\n );\n Version::new(0, 0, 0)\n }\n }\n }\n };\n\n // --- URL/SHA256 Logic (Original logic) ---\n let mut final_url = raw.url;\n let mut final_sha256 = raw.sha256;\n if final_url.is_empty() {\n if let Some(Value::Object(urls_map)) = raw.urls {\n if let Some(Value::Object(stable_url_info)) = urls_map.get(\"stable\") {\n if let Some(Value::String(u)) = stable_url_info.get(\"url\") {\n final_url = u.clone();\n }\n if let Some(Value::String(s)) = stable_url_info\n .get(\"checksum\")\n .or_else(|| stable_url_info.get(\"sha256\"))\n {\n final_sha256 = s.clone();\n }\n }\n }\n }\n if final_url.is_empty() && raw.versions.head.is_none() {\n debug!(\"Warning: Formula '{}' has no stable URL defined.\", raw.name);\n }\n\n // --- Dependency Processing (Original logic) ---\n let mut combined_dependencies: Vec = Vec::new();\n let mut seen_deps: HashMap = HashMap::new();\n let mut process_list = |deps: &[String], tag: DependencyTag| {\n for name in deps {\n *seen_deps\n .entry(name.clone())\n .or_insert(DependencyTag::empty()) |= tag;\n }\n };\n process_list(&raw.dependencies, DependencyTag::RUNTIME);\n process_list(&raw.build_dependencies, DependencyTag::BUILD);\n process_list(&raw.test_dependencies, DependencyTag::TEST);\n process_list(\n &raw.recommended_dependencies,\n DependencyTag::RECOMMENDED | DependencyTag::RUNTIME,\n );\n process_list(\n &raw.optional_dependencies,\n DependencyTag::OPTIONAL | DependencyTag::RUNTIME,\n );\n for (name, tags) in seen_deps {\n combined_dependencies.push(Dependency::new_with_tags(name, tags));\n }\n\n // --- Resource Processing ---\n // *** Added parsing logic for the 'resources' field ***\n let mut combined_resources: Vec = Vec::new();\n for res_val in raw.resources {\n // Homebrew API JSON format puts resource spec inside a keyed object\n // e.g., { \"resource_name\": { \"url\": \"...\", \"sha256\": \"...\" } }\n if let Value::Object(map) = res_val {\n // Assume only one key-value pair per object in the array\n if let Some((res_name, res_spec_val)) = map.into_iter().next() {\n // Use the manual Deserialize impl for ResourceSpec\n match ResourceSpec::deserialize(res_spec_val.clone()) {\n // Use ::deserialize\n Ok(mut res_spec) => {\n // Inject the name from the key if missing\n if res_spec.name.is_empty() {\n res_spec.name = res_name;\n } else if res_spec.name != res_name {\n debug!(\n \"Resource name mismatch in formula '{}': key '{}' vs spec '{}'. Using key.\",\n raw.name, res_name, res_spec.name\n );\n res_spec.name = res_name; // Prefer key name\n }\n // Ensure required fields are present\n if res_spec.url.is_empty() || res_spec.sha256.is_empty() {\n debug!(\n \"Resource '{}' for formula '{}' is missing URL or SHA256. Skipping.\",\n res_spec.name, raw.name\n );\n continue;\n }\n debug!(\n \"Parsed resource '{}' for formula '{}'\",\n res_spec.name, raw.name\n );\n combined_resources.push(res_spec);\n }\n Err(e) => {\n // Use display for the error which comes from serde::de::Error::custom\n debug!(\n \"Failed to parse resource spec value for key '{}' in formula '{}': {}. Value: {:?}\",\n res_name, raw.name, e, res_spec_val\n );\n }\n }\n } else {\n debug!(\"Empty resource object found in formula '{}'.\", raw.name);\n }\n } else {\n debug!(\n \"Unexpected format for resource entry in formula '{}': expected object, got {:?}\",\n raw.name, res_val\n );\n }\n }\n\n Ok(Self {\n name: raw.name,\n stable_version_str,\n version_semver,\n revision: raw.revision,\n desc: raw.desc,\n homepage: raw.homepage,\n url: final_url,\n sha256: final_sha256,\n mirrors: raw.mirrors,\n bottle: raw.bottle,\n dependencies: combined_dependencies,\n requirements: raw.requirements,\n resources: combined_resources, // Assign parsed resources\n install_keg_path: None,\n })\n }\n}\n\n// --- Formula impl Methods ---\nimpl Formula {\n // dependencies() and requirements() are unchanged\n pub fn dependencies(&self) -> Result> {\n Ok(self.dependencies.clone())\n }\n pub fn requirements(&self) -> Result> {\n Ok(self.requirements.clone())\n }\n\n // *** Added: Returns a clone of the defined resources. ***\n pub fn resources(&self) -> Result> {\n Ok(self.resources.clone())\n }\n\n // Other methods (set_keg_path, version_str_full, accessors) are unchanged\n pub fn set_keg_path(&mut self, path: PathBuf) {\n self.install_keg_path = Some(path);\n }\n pub fn version_str_full(&self) -> String {\n if self.revision > 0 {\n format!(\"{}_{}\", self.stable_version_str, self.revision)\n } else {\n self.stable_version_str.clone()\n }\n }\n pub fn name(&self) -> &str {\n &self.name\n }\n pub fn version(&self) -> &Version {\n &self.version_semver\n }\n pub fn source_url(&self) -> &str {\n &self.url\n }\n pub fn source_sha256(&self) -> &str {\n &self.sha256\n }\n pub fn get_bottle_spec(&self, bottle_tag: &str) -> Option<&BottleFileSpec> {\n self.bottle.stable.as_ref()?.files.get(bottle_tag)\n }\n}\n\n// --- BuildEnvironment Dependency Interface (Unchanged) ---\npub trait FormulaDependencies {\n fn name(&self) -> &str;\n fn install_prefix(&self, cellar_path: &Path) -> Result;\n fn resolved_runtime_dependency_paths(&self) -> Result>;\n fn resolved_build_dependency_paths(&self) -> Result>;\n fn all_resolved_dependency_paths(&self) -> Result>;\n}\nimpl FormulaDependencies for Formula {\n fn name(&self) -> &str {\n &self.name\n }\n fn install_prefix(&self, cellar_path: &Path) -> Result {\n let version_string = self.version_str_full();\n Ok(cellar_path.join(self.name()).join(version_string))\n }\n fn resolved_runtime_dependency_paths(&self) -> Result> {\n Ok(Vec::new())\n }\n fn resolved_build_dependency_paths(&self) -> Result> {\n Ok(Vec::new())\n }\n fn all_resolved_dependency_paths(&self) -> Result> {\n Ok(Vec::new())\n }\n}\n\n// --- Deserialization Helpers ---\n// deserialize_requirements remains unchanged\nfn deserialize_requirements<'de, D>(\n deserializer: D,\n) -> std::result::Result, D::Error>\nwhere\n D: serde::Deserializer<'de>,\n{\n #[derive(Deserialize, Debug)]\n struct ReqWrapper {\n #[serde(default)]\n name: String,\n #[serde(default)]\n version: Option,\n #[serde(default)]\n cask: Option,\n #[serde(default)]\n download: Option,\n }\n let raw_reqs: Vec = Deserialize::deserialize(deserializer)?;\n let mut requirements = Vec::new();\n for req_val in raw_reqs {\n if let Ok(req_obj) = serde_json::from_value::(req_val.clone()) {\n match req_obj.name.as_str() {\n \"macos\" => {\n requirements.push(Requirement::MacOS(\n req_obj.version.unwrap_or_else(|| \"any\".to_string()),\n ));\n }\n \"xcode\" => {\n requirements.push(Requirement::Xcode(\n req_obj.version.unwrap_or_else(|| \"any\".to_string()),\n ));\n }\n \"cask\" => {\n requirements.push(Requirement::Other(format!(\n \"Cask Requirement: {}\",\n req_obj.cask.unwrap_or_else(|| \"?\".to_string())\n )));\n }\n \"download\" => {\n requirements.push(Requirement::Other(format!(\n \"Download Requirement: {}\",\n req_obj.download.unwrap_or_else(|| \"?\".to_string())\n )));\n }\n _ => requirements.push(Requirement::Other(format!(\n \"Unknown requirement type: {req_obj:?}\"\n ))),\n }\n } else if let Value::String(req_str) = req_val {\n match req_str.as_str() {\n \"macos\" => requirements.push(Requirement::MacOS(\"latest\".to_string())),\n \"xcode\" => requirements.push(Requirement::Xcode(\"latest\".to_string())),\n _ => {\n requirements.push(Requirement::Other(format!(\"Simple requirement: {req_str}\")))\n }\n }\n } else {\n debug!(\"Warning: Could not parse requirement: {:?}\", req_val);\n requirements.push(Requirement::Other(format!(\n \"Unparsed requirement: {req_val:?}\"\n )));\n }\n }\n Ok(requirements)\n}\n\n// Manual impl Deserialize for ResourceSpec (unchanged, this is needed)\nimpl<'de> Deserialize<'de> for ResourceSpec {\n fn deserialize(deserializer: D) -> std::result::Result\n where\n D: Deserializer<'de>,\n {\n #[derive(Deserialize)]\n struct Helper {\n #[serde(default)]\n name: String, // name is often the key, not in the value\n url: String,\n sha256: String,\n }\n let helper = Helper::deserialize(deserializer)?;\n // Note: The actual resource name comes from the key in the map during Formula\n // deserialization\n Ok(Self {\n name: helper.name,\n url: helper.url,\n sha256: helper.sha256,\n })\n }\n}\n"], ["/sps/sps/src/cli/search.rs", "use std::sync::Arc;\n\nuse clap::Args;\nuse colored::Colorize;\nuse prettytable::{format, Cell, Row, Table};\nuse serde_json::Value;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_net::api;\nuse terminal_size::{terminal_size, Width};\nuse unicode_width::{UnicodeWidthChar, UnicodeWidthStr};\n\n#[derive(Args, Debug)]\npub struct Search {\n pub query: String,\n #[arg(long, conflicts_with = \"cask\")]\n pub formula: bool,\n #[arg(long, conflicts_with = \"formula\")]\n pub cask: bool,\n}\n\npub enum SearchType {\n All,\n Formula,\n Cask,\n}\n\nimpl Search {\n pub async fn run(&self, config: &Config, cache: Arc) -> Result<()> {\n let search_type = if self.formula {\n SearchType::Formula\n } else if self.cask {\n SearchType::Cask\n } else {\n SearchType::All\n };\n run_search(&self.query, search_type, config, cache).await\n }\n}\n\npub async fn run_search(\n query: &str,\n search_type: SearchType,\n _config: &Config,\n cache: Arc,\n) -> Result<()> {\n tracing::debug!(\"Searching for packages matching: {}\", query);\n\n println!(\"Searching for \\\"{query}\\\"\");\n\n let mut formula_matches = Vec::new();\n let mut cask_matches = Vec::new();\n let mut formula_err = None;\n let mut cask_err = None;\n\n if matches!(search_type, SearchType::All | SearchType::Formula) {\n match search_formulas(Arc::clone(&cache), query).await {\n Ok(matches) => formula_matches = matches,\n Err(e) => {\n tracing::error!(\"Error searching formulas: {}\", e);\n formula_err = Some(e);\n }\n }\n }\n\n if matches!(search_type, SearchType::All | SearchType::Cask) {\n match search_casks(Arc::clone(&cache), query).await {\n Ok(matches) => cask_matches = matches,\n Err(e) => {\n tracing::error!(\"Error searching casks: {}\", e);\n cask_err = Some(e);\n }\n }\n }\n\n if formula_matches.is_empty() && cask_matches.is_empty() {\n if let Some(e) = formula_err.or(cask_err) {\n return Err(e);\n }\n }\n\n print_search_results(query, &formula_matches, &cask_matches);\n\n Ok(())\n}\n\nasync fn search_formulas(cache: Arc, query: &str) -> Result> {\n let query_lower = query.to_lowercase();\n let mut matches = Vec::new();\n let mut data_source_name = \"cache\";\n\n let formula_data_result = cache.load_raw(\"formula.json\");\n\n let formulas: Vec = match formula_data_result {\n Ok(formula_data) => serde_json::from_str(&formula_data)?,\n Err(e) => {\n tracing::debug!(\"Formula cache load failed ({}), fetching from API\", e);\n data_source_name = \"API\";\n let all_formulas = api::fetch_all_formulas().await?;\n\n if let Err(cache_err) = cache.store_raw(\"formula.json\", &all_formulas) {\n tracing::warn!(\"Failed to cache formula data after fetching: {}\", cache_err);\n }\n serde_json::from_str(&all_formulas)?\n }\n };\n\n for formula in formulas {\n if is_formula_match(&formula, &query_lower) {\n matches.push(formula);\n }\n }\n\n tracing::debug!(\n \"Found {} potential formula matches from {}\",\n matches.len(),\n data_source_name\n );\n tracing::debug!(\n \"Filtered down to {} formula matches with available bottles\",\n matches.len()\n );\n\n Ok(matches)\n}\n\nasync fn search_casks(cache: Arc, query: &str) -> Result> {\n let query_lower = query.to_lowercase();\n let mut matches = Vec::new();\n let mut data_source_name = \"cache\";\n\n let cask_data_result = cache.load_raw(\"cask.json\");\n\n let casks: Vec = match cask_data_result {\n Ok(cask_data) => serde_json::from_str(&cask_data)?,\n Err(e) => {\n tracing::debug!(\"Cask cache load failed ({}), fetching from API\", e);\n data_source_name = \"API\";\n let all_casks = api::fetch_all_casks().await?;\n\n if let Err(cache_err) = cache.store_raw(\"cask.json\", &all_casks) {\n tracing::warn!(\"Failed to cache cask data after fetching: {}\", cache_err);\n }\n serde_json::from_str(&all_casks)?\n }\n };\n\n for cask in casks {\n if is_cask_match(&cask, &query_lower) {\n matches.push(cask);\n }\n }\n tracing::debug!(\n \"Found {} cask matches from {}\",\n matches.len(),\n data_source_name\n );\n Ok(matches)\n}\n\nfn is_formula_match(formula: &Value, query: &str) -> bool {\n if let Some(name) = formula.get(\"name\").and_then(|n| n.as_str()) {\n if name.to_lowercase().contains(query) {\n return true;\n }\n }\n\n if let Some(full_name) = formula.get(\"full_name\").and_then(|n| n.as_str()) {\n if full_name.to_lowercase().contains(query) {\n return true;\n }\n }\n\n if let Some(desc) = formula.get(\"desc\").and_then(|d| d.as_str()) {\n if desc.to_lowercase().contains(query) {\n return true;\n }\n }\n\n if let Some(aliases) = formula.get(\"aliases\").and_then(|a| a.as_array()) {\n for alias in aliases {\n if let Some(alias_str) = alias.as_str() {\n if alias_str.to_lowercase().contains(query) {\n return true;\n }\n }\n }\n }\n\n false\n}\n\nfn is_cask_match(cask: &Value, query: &str) -> bool {\n if let Some(token) = cask.get(\"token\").and_then(|t| t.as_str()) {\n if token.to_lowercase().contains(query) {\n return true;\n }\n }\n\n if let Some(names) = cask.get(\"name\").and_then(|n| n.as_array()) {\n for name in names {\n if let Some(name_str) = name.as_str() {\n if name_str.to_lowercase().contains(query) {\n return true;\n }\n }\n }\n }\n\n if let Some(desc) = cask.get(\"desc\").and_then(|d| d.as_str()) {\n if desc.to_lowercase().contains(query) {\n return true;\n }\n }\n\n false\n}\n\nfn truncate_vis(s: &str, max: usize) -> String {\n if UnicodeWidthStr::width(s) <= max {\n return s.to_string();\n }\n let mut w = 0;\n let mut out = String::new();\n let effective_max = if max > 0 { max } else { 1 };\n\n for ch in s.chars() {\n let cw = UnicodeWidthChar::width(ch).unwrap_or(0);\n if w + cw >= effective_max.saturating_sub(1) {\n break;\n }\n out.push(ch);\n w += cw;\n }\n out.push('…');\n out\n}\n\npub fn print_search_results(query: &str, formula_matches: &[Value], cask_matches: &[Value]) {\n let total = formula_matches.len() + cask_matches.len();\n if total == 0 {\n println!(\"{}\", format!(\"No matches found for '{query}'\").yellow());\n return;\n }\n println!(\n \"{}\",\n format!(\"Found {total} result(s) for '{query}'\").bold()\n );\n\n let term_cols = terminal_size()\n .map(|(Width(w), _)| w as usize)\n .unwrap_or(120);\n\n let type_col = 7;\n let version_col = 10;\n let sep_width = 3 * 3;\n let total_fixed = type_col + version_col + sep_width;\n\n let name_min_width = 10;\n let desc_min_width = 20;\n\n let leftover = term_cols.saturating_sub(total_fixed);\n\n let name_prop_width = leftover / 3;\n\n let name_max = std::cmp::max(name_min_width, name_prop_width);\n let desc_max = std::cmp::max(desc_min_width, leftover.saturating_sub(name_max));\n\n let name_max = std::cmp::min(name_max, leftover.saturating_sub(desc_min_width));\n let desc_max = std::cmp::min(desc_max, leftover.saturating_sub(name_max));\n\n let mut tbl = Table::new();\n tbl.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n\n for formula in formula_matches {\n let raw_name = formula\n .get(\"name\")\n .and_then(|n| n.as_str())\n .unwrap_or(\"Unknown\");\n let raw_desc = formula.get(\"desc\").and_then(|d| d.as_str()).unwrap_or(\"\");\n let _name = truncate_vis(raw_name, name_max);\n let desc = truncate_vis(raw_desc, desc_max);\n\n let version = get_version(formula);\n\n tbl.add_row(Row::new(vec![\n Cell::new(\"Formula\").style_spec(\"Fg\"),\n Cell::new(&_name).style_spec(\"Fb\"),\n Cell::new(version),\n Cell::new(&desc),\n ]));\n }\n\n if !formula_matches.is_empty() && !cask_matches.is_empty() {\n tbl.add_row(Row::new(vec![Cell::new(\" \").with_hspan(4)]));\n }\n\n for cask in cask_matches {\n let raw_name = cask\n .get(\"token\")\n .and_then(|t| t.as_str())\n .unwrap_or(\"Unknown\");\n let raw_desc = cask.get(\"desc\").and_then(|d| d.as_str()).unwrap_or(\"\");\n let desc = truncate_vis(raw_desc, desc_max);\n\n let version = get_cask_version(cask);\n\n tbl.add_row(Row::new(vec![\n Cell::new(\"Cask\").style_spec(\"Fy\"),\n Cell::new(raw_name).style_spec(\"Fb\"),\n Cell::new(version),\n Cell::new(&desc),\n ]));\n }\n\n tbl.printstd();\n}\n\nfn get_version(formula: &Value) -> &str {\n formula\n .get(\"versions\")\n .and_then(|v| v.get(\"stable\"))\n .and_then(|v| v.as_str())\n .unwrap_or(\"-\")\n}\n\nfn get_cask_version(cask: &Value) -> &str {\n cask.get(\"version\").and_then(|v| v.as_str()).unwrap_or(\"-\")\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/pkg.rs", "use std::fs;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::cask::Cask;\nuse tracing::{debug, error};\n\nuse crate::install::cask::InstalledArtifact; // Artifact type alias is just Value\n\n/// Installs a PKG file and returns details of artifacts created/managed.\npub fn install_pkg_from_path(\n cask: &Cask,\n pkg_path: &Path,\n cask_version_install_path: &Path, // e.g., /opt/homebrew/Caskroom/foo/1.2.3\n _config: &Config, // Keep for potential future use\n) -> Result> {\n // <-- Return type changed\n debug!(\"Installing pkg file: {}\", pkg_path.display());\n\n if !pkg_path.exists() || !pkg_path.is_file() {\n return Err(SpsError::NotFound(format!(\n \"Package file not found or is not a file: {}\",\n pkg_path.display()\n )));\n }\n\n let pkg_name = pkg_path\n .file_name()\n .ok_or_else(|| SpsError::Generic(format!(\"Invalid pkg path: {}\", pkg_path.display())))?;\n\n // --- Prepare list for artifacts ---\n let mut installed_artifacts: Vec = Vec::new();\n\n // --- Copy PKG to Caskroom for Reference ---\n let caskroom_pkg_path = cask_version_install_path.join(pkg_name);\n debug!(\n \"Copying pkg to caskroom for reference: {}\",\n caskroom_pkg_path.display()\n );\n if let Some(parent) = caskroom_pkg_path.parent() {\n fs::create_dir_all(parent).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed create parent dir {}: {}\", parent.display(), e),\n )))\n })?;\n }\n if let Err(e) = fs::copy(pkg_path, &caskroom_pkg_path) {\n error!(\n \"Failed to copy PKG {} to {}: {}\",\n pkg_path.display(),\n caskroom_pkg_path.display(),\n e\n );\n return Err(SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed copy PKG to caskroom: {e}\"),\n ))));\n } else {\n // Record the reference copy artifact\n installed_artifacts.push(InstalledArtifact::CaskroomReference {\n path: caskroom_pkg_path.clone(),\n });\n }\n\n // --- Run Installer ---\n debug!(\"Running installer (this may require sudo)\");\n debug!(\n \"Executing: sudo installer -pkg {} -target /\",\n pkg_path.display()\n );\n let output = Command::new(\"sudo\")\n .arg(\"installer\")\n .arg(\"-pkg\")\n .arg(pkg_path)\n .arg(\"-target\")\n .arg(\"/\")\n .output()\n .map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed to execute sudo installer: {e}\"),\n )))\n })?;\n\n if !output.status.success() {\n let stderr = String::from_utf8_lossy(&output.stderr);\n error!(\"sudo installer failed ({}): {}\", output.status, stderr);\n // Don't clean up the reference copy here, let the main process handle directory removal on\n // failure\n return Err(SpsError::InstallError(format!(\n \"Package installation failed for {}: {}\",\n pkg_path.display(),\n stderr\n )));\n }\n debug!(\"Successfully ran installer command.\");\n let stdout = String::from_utf8_lossy(&output.stdout);\n if !stdout.trim().is_empty() {\n debug!(\"Installer stdout:\\n{}\", stdout);\n }\n\n // --- Record PkgUtil Receipts (based on cask definition) ---\n if let Some(artifacts) = &cask.artifacts {\n // artifacts is Option>\n for artifact_value in artifacts.iter() {\n if let Some(uninstall_array) =\n artifact_value.get(\"uninstall\").and_then(|v| v.as_array())\n {\n for stanza_value in uninstall_array {\n if let Some(stanza_obj) = stanza_value.as_object() {\n if let Some(pkgutil_id) = stanza_obj.get(\"pkgutil\").and_then(|v| v.as_str())\n {\n debug!(\"Found pkgutil ID to record: {}\", pkgutil_id);\n // Check for duplicates before adding\n let new_artifact = InstalledArtifact::PkgUtilReceipt {\n id: pkgutil_id.to_string(),\n };\n if !installed_artifacts.contains(&new_artifact) {\n // Need PartialEq for InstalledArtifact\n installed_artifacts.push(new_artifact);\n }\n }\n // Consider other uninstall keys like launchctl, delete?\n }\n }\n }\n // Optionally check \"zap\" stanzas too\n }\n }\n debug!(\"Successfully installed pkg: {}\", pkg_path.display());\n Ok(installed_artifacts) // <-- Return collected artifacts\n}\n"], ["/sps/sps-core/src/install/bottle/mod.rs", "// ===== sps-core/src/build/formula/mod.rs =====\nuse std::fs::File;\nuse std::io::Write;\nuse std::path::{Path, PathBuf};\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::formula::Formula;\nuse tracing::{debug, error};\n\n// Declare submodules\npub mod exec;\npub mod link;\npub mod macho;\n\n/// Download formula resources from the internet asynchronously.\npub async fn download_formula(\n formula: &Formula,\n config: &Config,\n client: &reqwest::Client,\n) -> Result {\n if has_bottle_for_current_platform(formula) {\n exec::download_bottle(formula, config, client).await\n } else {\n Err(SpsError::Generic(format!(\n \"No bottle available for {} on this platform\",\n formula.name()\n )))\n }\n}\n\n/// Checks if a suitable bottle exists for the current platform, considering fallbacks.\npub fn has_bottle_for_current_platform(formula: &Formula) -> bool {\n let result = crate::install::bottle::exec::get_bottle_for_platform(formula);\n debug!(\n \"has_bottle_for_current_platform check for '{}': {:?}\",\n formula.name(),\n result.is_ok()\n );\n if let Err(e) = &result {\n debug!(\"Reason for no bottle: {}\", e);\n }\n result.is_ok()\n}\n\n// *** Updated get_current_platform function ***\nfn get_current_platform() -> String {\n if cfg!(target_os = \"macos\") {\n let arch = if std::env::consts::ARCH == \"aarch64\" {\n \"arm64\"\n } else if std::env::consts::ARCH == \"x86_64\" {\n \"x86_64\"\n } else {\n std::env::consts::ARCH\n };\n\n debug!(\"Attempting to determine macOS version using /usr/bin/sw_vers -productVersion\");\n match Command::new(\"/usr/bin/sw_vers\")\n .arg(\"-productVersion\")\n .output()\n {\n Ok(output) => {\n let stdout = String::from_utf8_lossy(&output.stdout);\n let stderr = String::from_utf8_lossy(&output.stderr);\n debug!(\"sw_vers status: {}\", output.status);\n if !output.status.success() || !stderr.trim().is_empty() {\n debug!(\"sw_vers stdout:\\n{}\", stdout);\n if !stderr.trim().is_empty() {\n debug!(\"sw_vers stderr:\\n{}\", stderr);\n }\n }\n\n if output.status.success() {\n let version_str = stdout.trim();\n if !version_str.is_empty() {\n debug!(\"Extracted version string: {}\", version_str);\n let os_name = match version_str.split('.').next() {\n Some(\"15\") => \"sequoia\",\n Some(\"14\") => \"sonoma\",\n Some(\"13\") => \"ventura\",\n Some(\"12\") => \"monterey\",\n Some(\"11\") => \"big_sur\",\n Some(\"10\") => match version_str.split('.').nth(1) {\n Some(\"15\") => \"catalina\",\n Some(\"14\") => \"mojave\",\n _ => {\n debug!(\n \"Unrecognized legacy macOS 10.x version: {}\",\n version_str\n );\n \"unknown_macos\"\n }\n },\n _ => {\n debug!(\"Unrecognized macOS major version: {}\", version_str);\n \"unknown_macos\"\n }\n };\n\n if os_name != \"unknown_macos\" {\n let platform_tag = if arch == \"arm64\" {\n format!(\"{arch}_{os_name}\")\n } else {\n os_name.to_string()\n };\n debug!(\"Determined platform tag: {}\", platform_tag);\n return platform_tag;\n }\n } else {\n error!(\"sw_vers -productVersion output was empty.\");\n }\n } else {\n error!(\n \"sw_vers -productVersion command failed with status: {}. Stderr: {}\",\n output.status,\n stderr.trim()\n );\n }\n }\n Err(e) => {\n error!(\"Failed to execute /usr/bin/sw_vers -productVersion: {}\", e);\n }\n }\n\n error!(\"!!! FAILED TO DETECT MACOS VERSION VIA SW_VERS !!!\");\n debug!(\"Using UNRELIABLE fallback platform detection. Bottle selection may be incorrect.\");\n if arch == \"arm64\" {\n debug!(\"Falling back to platform tag: arm64_monterey\");\n \"arm64_monterey\".to_string()\n } else {\n debug!(\"Falling back to platform tag: monterey\");\n \"monterey\".to_string()\n }\n } else if cfg!(target_os = \"linux\") {\n if std::env::consts::ARCH == \"aarch64\" {\n \"arm64_linux\".to_string()\n } else if std::env::consts::ARCH == \"x86_64\" {\n \"x86_64_linux\".to_string()\n } else {\n \"unknown\".to_string()\n }\n } else {\n debug!(\n \"Could not determine platform tag for OS: {}\",\n std::env::consts::OS\n );\n \"unknown\".to_string()\n }\n}\n\n// REMOVED: get_cellar_path (now in Config)\n\n// --- get_formula_cellar_path uses Config ---\n// Parameter changed from formula: &Formula to formula_name: &str\n// Parameter changed from config: &Config to cellar_path: &Path for consistency where Config isn't\n// fully available If Config *is* available, call config.formula_cellar_dir(formula.name()) instead.\n// **Keeping original signature for now where Config might not be easily passed**\npub fn get_formula_cellar_path(formula: &Formula, config: &Config) -> PathBuf {\n // Use Config method\n config.formula_cellar_dir(formula.name())\n}\n\n// --- write_receipt (unchanged) ---\npub fn write_receipt(\n formula: &Formula,\n install_dir: &Path,\n installation_type: &str, // \"bottle\" or \"source\"\n) -> Result<()> {\n let receipt_path = install_dir.join(\"INSTALL_RECEIPT.json\");\n let receipt_file = File::create(&receipt_path);\n let mut receipt_file = match receipt_file {\n Ok(file) => file,\n Err(e) => {\n error!(\n \"Failed to create receipt file at {}: {}\",\n receipt_path.display(),\n e\n );\n return Err(SpsError::Io(std::sync::Arc::new(e)));\n }\n };\n\n let resources_result = formula.resources();\n let resources_installed = match resources_result {\n Ok(res) => res.iter().map(|r| r.name.clone()).collect::>(),\n Err(_) => {\n debug!(\n \"Could not retrieve resources for formula {} when writing receipt.\",\n formula.name\n );\n vec![]\n }\n };\n\n let timestamp = chrono::Utc::now().to_rfc3339();\n\n let receipt = serde_json::json!({\n \"name\": formula.name, \"version\": formula.version_str_full(), \"time\": timestamp,\n \"source\": { \"type\": \"api\", \"url\": formula.url, },\n \"built_on\": {\n \"os\": std::env::consts::OS, \"arch\": std::env::consts::ARCH,\n \"platform_tag\": get_current_platform(),\n },\n \"installation_type\": installation_type,\n \"resources_installed\": resources_installed,\n });\n\n let receipt_json = match serde_json::to_string_pretty(&receipt) {\n Ok(json) => json,\n Err(e) => {\n error!(\n \"Failed to serialize receipt JSON for {}: {}\",\n formula.name, e\n );\n return Err(SpsError::Json(std::sync::Arc::new(e)));\n }\n };\n\n if let Err(e) = receipt_file.write_all(receipt_json.as_bytes()) {\n error!(\"Failed to write receipt file for {}: {}\", formula.name, e);\n return Err(SpsError::Io(std::sync::Arc::new(e)));\n }\n\n Ok(())\n}\n\n// --- Re-exports (unchanged) ---\npub use exec::install_bottle;\npub use link::link_formula_artifacts;\n"], ["/sps/sps-core/src/install/bottle/link.rs", "// ===== sps-core/src/build/formula/link.rs =====\nuse std::fs;\nuse std::io::Write;\nuse std::os::unix::fs as unix_fs;\n#[cfg(unix)]\nuse std::os::unix::fs::PermissionsExt;\nuse std::path::{Path, PathBuf};\n\nuse serde_json;\nuse sps_common::config::Config; // Import Config\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::formula::Formula;\nuse tracing::{debug, error};\n\nconst STANDARD_KEG_DIRS: [&str; 6] = [\"bin\", \"lib\", \"share\", \"include\", \"etc\", \"Frameworks\"];\n\n/// Link all artifacts from a formula's installation directory.\n// Added Config parameter\npub fn link_formula_artifacts(\n formula: &Formula,\n installed_keg_path: &Path,\n config: &Config, // Added config\n) -> Result<()> {\n debug!(\n \"Linking artifacts for {} from {}\",\n formula.name(),\n installed_keg_path.display()\n );\n\n let formula_content_root = determine_content_root(installed_keg_path)?;\n let mut symlinks_created = Vec::::new();\n\n // Use config methods for paths\n let opt_link_path = config.formula_opt_path(formula.name());\n let target_keg_dir = &formula_content_root;\n\n remove_existing_link_target(&opt_link_path)?;\n unix_fs::symlink(target_keg_dir, &opt_link_path).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed to create opt symlink for {}: {}\", formula.name(), e),\n )))\n })?;\n symlinks_created.push(opt_link_path.to_string_lossy().to_string());\n debug!(\n \" Linked opt path: {} -> {}\",\n opt_link_path.display(),\n target_keg_dir.display()\n );\n\n if let Some((base, _version)) = formula.name().split_once('@') {\n let alias_path = config.opt_dir().join(base); // Use config.opt_dir()\n if !alias_path.exists() {\n match unix_fs::symlink(target_keg_dir, &alias_path) {\n Ok(_) => {\n debug!(\n \" Added un‑versioned opt alias: {} -> {}\",\n alias_path.display(),\n target_keg_dir.display()\n );\n symlinks_created.push(alias_path.to_string_lossy().to_string());\n }\n Err(e) => {\n debug!(\n \" Could not create opt alias {}: {}\",\n alias_path.display(),\n e\n );\n }\n }\n }\n }\n\n let standard_artifact_dirs = [\"lib\", \"include\", \"share\"];\n for dir_name in &standard_artifact_dirs {\n let source_subdir = formula_content_root.join(dir_name);\n // Use config.prefix() for target base\n let target_prefix_subdir = config.sps_root().join(dir_name);\n\n if source_subdir.is_dir() {\n fs::create_dir_all(&target_prefix_subdir)?;\n for entry in fs::read_dir(&source_subdir)? {\n let entry = entry?;\n let source_item_path = entry.path();\n let file_name = entry.file_name();\n if file_name.to_string_lossy().starts_with('.') {\n continue;\n }\n\n let target_link = target_prefix_subdir.join(&file_name);\n remove_existing_link_target(&target_link)?;\n unix_fs::symlink(&source_item_path, &target_link).ok(); // ignore errors for individual links?\n symlinks_created.push(target_link.to_string_lossy().to_string());\n debug!(\n \" Linked {} -> {}\",\n target_link.display(),\n source_item_path.display()\n );\n }\n }\n }\n\n // Use config.bin_dir() for target bin\n let target_bin_dir = config.bin_dir();\n fs::create_dir_all(&target_bin_dir).ok();\n\n let source_bin_dir = formula_content_root.join(\"bin\");\n if source_bin_dir.is_dir() {\n create_wrappers_in_dir(\n &source_bin_dir,\n &target_bin_dir,\n &formula_content_root,\n &mut symlinks_created,\n )?;\n }\n let source_libexec_dir = formula_content_root.join(\"libexec\");\n if source_libexec_dir.is_dir() {\n create_wrappers_in_dir(\n &source_libexec_dir,\n &target_bin_dir,\n &formula_content_root,\n &mut symlinks_created,\n )?;\n }\n\n write_install_manifest(installed_keg_path, &symlinks_created)?;\n\n debug!(\n \"Successfully completed linking artifacts for {}\",\n formula.name()\n );\n Ok(())\n}\n\n// remove_existing_link_target, write_install_manifest remain mostly unchanged internally) ...\nfn create_wrappers_in_dir(\n source_dir: &Path,\n target_bin_dir: &Path,\n formula_content_root: &Path,\n wrappers_created: &mut Vec,\n) -> Result<()> {\n debug!(\n \"Scanning for executables in {} to create wrappers in {}\",\n source_dir.display(),\n target_bin_dir.display()\n );\n match fs::read_dir(source_dir) {\n Ok(entries) => {\n for entry_result in entries {\n match entry_result {\n Ok(entry) => {\n let source_item_path = entry.path();\n let file_name = entry.file_name();\n\n if file_name.to_string_lossy().starts_with('.') {\n continue;\n }\n\n if source_item_path.is_dir() {\n create_wrappers_in_dir(\n &source_item_path,\n target_bin_dir,\n formula_content_root,\n wrappers_created,\n )?;\n } else if source_item_path.is_file() {\n match is_executable(&source_item_path) {\n Ok(true) => {\n let wrapper_path = target_bin_dir.join(&file_name);\n debug!(\"Found executable: {}\", source_item_path.display());\n if remove_existing_link_target(&wrapper_path).is_ok() {\n debug!(\n \" Creating wrapper script: {} -> {}\",\n wrapper_path.display(),\n source_item_path.display()\n );\n match create_wrapper_script(\n &source_item_path,\n &wrapper_path,\n formula_content_root,\n ) {\n Ok(_) => {\n debug!(\n \" Created wrapper {} -> {}\",\n wrapper_path.display(),\n source_item_path.display()\n );\n wrappers_created.push(\n wrapper_path.to_string_lossy().to_string(),\n );\n }\n Err(e) => {\n error!(\n \"Failed to create wrapper script {} -> {}: {}\",\n wrapper_path.display(),\n source_item_path.display(),\n e\n );\n }\n }\n }\n }\n Ok(false) => { /* Not executable, ignore */ }\n Err(e) => {\n debug!(\n \" Could not check executable status for {}: {}\",\n source_item_path.display(),\n e\n );\n }\n }\n }\n }\n Err(e) => {\n debug!(\n \" Failed to process directory entry in {}: {}\",\n source_dir.display(),\n e\n );\n }\n }\n }\n }\n Err(e) => {\n debug!(\n \"Failed to read source directory {}: {}\",\n source_dir.display(),\n e\n );\n }\n }\n Ok(())\n}\nfn create_wrapper_script(\n target_executable: &Path,\n wrapper_path: &Path,\n formula_content_root: &Path,\n) -> Result<()> {\n let libexec_path = formula_content_root.join(\"libexec\");\n let perl_lib_path = libexec_path.join(\"lib\").join(\"perl5\");\n let python_lib_path = libexec_path.join(\"vendor\"); // Assuming simple vendor dir\n\n let mut script_content = String::new();\n script_content.push_str(\"#!/bin/bash\\n\");\n script_content.push_str(\"# Wrapper script generated by sp\\n\");\n script_content.push_str(\"set -e\\n\\n\");\n\n if perl_lib_path.exists() && perl_lib_path.is_dir() {\n script_content.push_str(&format!(\n \"export PERL5LIB=\\\"{}:$PERL5LIB\\\"\\n\",\n perl_lib_path.display()\n ));\n debug!(\n \" (Wrapper will set PERL5LIB to {})\",\n perl_lib_path.display()\n );\n }\n if python_lib_path.exists() && python_lib_path.is_dir() {\n script_content.push_str(&format!(\n \"export PYTHONPATH=\\\"{}:$PYTHONPATH\\\"\\n\",\n python_lib_path.display()\n ));\n debug!(\n \" (Wrapper will set PYTHONPATH to {})\",\n python_lib_path.display()\n );\n }\n\n script_content.push_str(&format!(\n \"\\nexec \\\"{}\\\" \\\"$@\\\"\\n\",\n target_executable.display()\n ));\n\n let mut file = fs::File::create(wrapper_path).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed create wrapper {}: {}\", wrapper_path.display(), e),\n )))\n })?;\n file.write_all(script_content.as_bytes()).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed write wrapper {}: {}\", wrapper_path.display(), e),\n )))\n })?;\n\n #[cfg(unix)]\n {\n let metadata = file.metadata()?;\n let mut permissions = metadata.permissions();\n permissions.set_mode(0o755);\n fs::set_permissions(wrapper_path, permissions).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\n \"Failed set wrapper executable {}: {}\",\n wrapper_path.display(),\n e\n ),\n )))\n })?;\n }\n\n Ok(())\n}\n\nfn determine_content_root(installed_keg_path: &Path) -> Result {\n let mut potential_subdirs = Vec::new();\n let mut top_level_files_found = false;\n if !installed_keg_path.is_dir() {\n error!(\n \"Keg path {} does not exist or is not a directory!\",\n installed_keg_path.display()\n );\n return Err(SpsError::NotFound(format!(\n \"Keg path not found: {}\",\n installed_keg_path.display()\n )));\n }\n match fs::read_dir(installed_keg_path) {\n Ok(entries) => {\n for entry_res in entries {\n if let Ok(entry) = entry_res {\n let path = entry.path();\n let file_name = entry.file_name();\n // --- Use OsStr comparison ---\n let file_name_osstr = file_name.as_os_str();\n if file_name_osstr.to_string_lossy().starts_with('.')\n || file_name_osstr == \"INSTALL_MANIFEST.json\"\n || file_name_osstr == \"INSTALL_RECEIPT.json\"\n {\n continue;\n }\n if path.is_dir() {\n // Store both path and name for check later\n potential_subdirs.push((path, file_name.to_string_lossy().to_string()));\n } else if path.is_file() {\n top_level_files_found = true;\n debug!(\n \"Found file '{}' at top level of keg {}, assuming no intermediate dir.\",\n file_name.to_string_lossy(), // Use lossy for display\n installed_keg_path.display()\n );\n break; // Stop scanning if top-level files found\n }\n } else {\n debug!(\n \"Failed to read directory entry in {}: {}\",\n installed_keg_path.display(),\n entry_res.err().unwrap() // Safe unwrap as we are in Err path\n );\n }\n }\n }\n Err(e) => {\n debug!(\n \"Could not read keg directory {} to check for intermediate dir: {}. Assuming keg path is content root.\",\n installed_keg_path.display(),\n e\n );\n return Ok(installed_keg_path.to_path_buf());\n }\n }\n\n // --- MODIFIED LOGIC ---\n if potential_subdirs.len() == 1 && !top_level_files_found {\n // Get the single subdirectory path and name\n let (intermediate_dir_path, intermediate_dir_name) = potential_subdirs.remove(0); // Use remove\n\n // Check if the single directory name is one of the standard install dirs\n if STANDARD_KEG_DIRS.contains(&intermediate_dir_name.as_str()) {\n debug!(\n \"Single directory found ('{}') is a standard directory. Using main keg directory {} as content root.\",\n intermediate_dir_name,\n installed_keg_path.display()\n );\n Ok(installed_keg_path.to_path_buf()) // Use main keg path\n } else {\n // Single dir is NOT a standard name, assume it's an intermediate content root\n debug!(\n \"Detected single non-standard intermediate content directory: {}\",\n intermediate_dir_path.display()\n );\n Ok(intermediate_dir_path) // Use the intermediate dir\n }\n // --- END MODIFIED LOGIC ---\n } else {\n // Handle multiple subdirs or top-level files found case (no change needed here)\n if potential_subdirs.len() > 1 {\n debug!(\n \"Multiple potential content directories found under keg {}. Using main keg directory as content root.\",\n installed_keg_path.display()\n );\n } else if top_level_files_found {\n debug!(\n \"Top-level files found in keg {}. Using main keg directory as content root.\",\n installed_keg_path.display()\n );\n } else if potential_subdirs.is_empty() {\n // Changed from else if to else\n debug!(\n \"No subdirectories or files found (excluding ignored ones) in keg {}. Using main keg directory as content root.\",\n installed_keg_path.display()\n );\n }\n Ok(installed_keg_path.to_path_buf()) // Use main keg path in these cases too\n }\n}\n\nfn remove_existing_link_target(path: &Path) -> Result<()> {\n match path.symlink_metadata() {\n Ok(metadata) => {\n debug!(\n \" Removing existing item at link target: {}\",\n path.display()\n );\n let is_dir = metadata.file_type().is_dir();\n let is_symlink = metadata.file_type().is_symlink();\n let is_real_dir = is_dir && !is_symlink;\n let remove_result = if is_real_dir {\n fs::remove_dir_all(path)\n } else {\n fs::remove_file(path)\n };\n if let Err(e) = remove_result {\n debug!(\n \" Failed to remove existing item at link target {}: {}\",\n path.display(),\n e\n );\n return Err(SpsError::Io(std::sync::Arc::new(e)));\n }\n Ok(())\n }\n Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),\n Err(e) => {\n debug!(\n \" Failed to get metadata for existing item {}: {}\",\n path.display(),\n e\n );\n Err(SpsError::Io(std::sync::Arc::new(e)))\n }\n }\n}\n\nfn write_install_manifest(installed_keg_path: &Path, symlinks_created: &[String]) -> Result<()> {\n let manifest_path = installed_keg_path.join(\"INSTALL_MANIFEST.json\");\n debug!(\"Writing install manifest to: {}\", manifest_path.display());\n match serde_json::to_string_pretty(&symlinks_created) {\n Ok(manifest_json) => match fs::write(&manifest_path, manifest_json) {\n Ok(_) => {\n debug!(\n \"Wrote install manifest with {} links: {}\",\n symlinks_created.len(),\n manifest_path.display()\n );\n }\n Err(e) => {\n error!(\n \"Failed to write install manifest {}: {}\",\n manifest_path.display(),\n e\n );\n return Err(SpsError::Io(std::sync::Arc::new(e)));\n }\n },\n Err(e) => {\n error!(\"Failed to serialize install manifest data: {}\", e);\n return Err(SpsError::Json(std::sync::Arc::new(e)));\n }\n }\n Ok(())\n}\n\npub fn unlink_formula_artifacts(\n formula_name: &str,\n version_str_full: &str, // e.g., \"1.2.3_1\"\n config: &Config,\n) -> Result<()> {\n debug!(\n \"Unlinking artifacts for {} version {}\",\n formula_name, version_str_full\n );\n // Use config method to get expected keg path based on name and version string\n let expected_keg_path = config.formula_keg_path(formula_name, version_str_full);\n let manifest_path = expected_keg_path.join(\"INSTALL_MANIFEST.json\"); // Manifest *inside* the keg\n\n if manifest_path.is_file() {\n debug!(\"Reading install manifest: {}\", manifest_path.display());\n match fs::read_to_string(&manifest_path) {\n Ok(manifest_str) => {\n match serde_json::from_str::>(&manifest_str) {\n Ok(links_to_remove) => {\n let mut unlinked_count = 0;\n let mut removal_errors = 0;\n if links_to_remove.is_empty() {\n debug!(\n \"Install manifest {} is empty. Cannot perform manifest-based unlink.\",\n manifest_path.display()\n );\n } else {\n // Use Config to get base paths for checking ownership/safety\n let opt_base = config.opt_dir();\n let bin_base = config.bin_dir();\n let lib_base = config.sps_root().join(\"lib\");\n let include_base = config.sps_root().join(\"include\");\n let share_base = config.sps_root().join(\"share\");\n // Add etc, sbin etc. if needed\n\n for link_str in links_to_remove {\n let link_path = PathBuf::from(link_str);\n // Check if it's under a managed directory (safety check)\n if link_path.starts_with(&opt_base)\n || link_path.starts_with(&bin_base)\n || link_path.starts_with(&lib_base)\n || link_path.starts_with(&include_base)\n || link_path.starts_with(&share_base)\n {\n match remove_existing_link_target(&link_path) {\n // Use helper\n Ok(_) => {\n debug!(\"Removed link/wrapper: {}\", link_path.display());\n unlinked_count += 1;\n }\n Err(e) => {\n // Log error but continue trying to remove others\n debug!(\n \"Failed to remove link/wrapper {}: {}\",\n link_path.display(),\n e\n );\n removal_errors += 1;\n }\n }\n } else {\n // This indicates a potentially corrupted manifest or a link\n // outside expected areas\n error!(\n \"Manifest contains unexpected link path, skipping removal: {}\",\n link_path.display()\n );\n removal_errors += 1; // Count as an error/problem\n }\n }\n }\n debug!(\n \"Attempted to unlink {} artifacts based on manifest.\",\n unlinked_count\n );\n if removal_errors > 0 {\n error!(\n \"Encountered {} errors while removing links listed in manifest.\",\n removal_errors\n );\n // Decide if this should be a hard error - perhaps not if keg is being\n // removed anyway? For now, just log\n // warnings.\n }\n Ok(()) // Return Ok even if some links failed, keg removal will happen next\n }\n Err(e) => {\n error!(\n \"Failed to parse formula install manifest {}: {}. Proceeding without detailed unlink.\",\n manifest_path.display(),\n e\n );\n // Don't error out, allow keg removal to proceed.\n Ok(())\n }\n }\n }\n Err(e) => {\n error!(\n \"Failed to read formula install manifest {}: {}. Proceeding without detailed unlink.\",\n manifest_path.display(),\n e\n );\n // Don't error out, allow keg removal to proceed.\n Ok(())\n }\n }\n } else {\n debug!(\n \"Warning: No install manifest found at {}. Cannot perform detailed unlink.\",\n manifest_path.display()\n );\n // Don't error out, allow keg removal to proceed.\n Ok(())\n }\n}\n\nfn is_executable(path: &Path) -> Result {\n if !path.try_exists().unwrap_or(false) || !path.is_file() {\n return Ok(false);\n }\n if cfg!(unix) {\n use std::os::unix::fs::PermissionsExt;\n match fs::metadata(path) {\n Ok(metadata) => Ok(metadata.permissions().mode() & 0o111 != 0),\n Err(e) => Err(SpsError::Io(std::sync::Arc::new(e))),\n }\n } else {\n Ok(true)\n }\n}\n"], ["/sps/sps-net/src/http.rs", "use std::fs;\nuse std::path::{Path, PathBuf};\nuse std::sync::Arc;\nuse std::time::Duration;\n\nuse futures::StreamExt;\nuse reqwest::header::{HeaderMap, ACCEPT, USER_AGENT};\nuse reqwest::{Client, StatusCode};\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::formula::ResourceSpec;\nuse tokio::fs::File as TokioFile;\nuse tokio::io::AsyncWriteExt;\nuse tracing::{debug, error};\n\nuse crate::validation::{validate_url, verify_checksum};\n\npub type ProgressCallback = Arc) + Send + Sync>;\n\nconst DOWNLOAD_TIMEOUT_SECS: u64 = 300;\nconst CONNECT_TIMEOUT_SECS: u64 = 30;\nconst USER_AGENT_STRING: &str = \"sps package manager (Rust; +https://github.com/alexykn/sp)\";\n\npub async fn fetch_formula_source_or_bottle(\n formula_name: &str,\n url: &str,\n sha256_expected: &str,\n mirrors: &[String],\n config: &Config,\n) -> Result {\n fetch_formula_source_or_bottle_with_progress(\n formula_name,\n url,\n sha256_expected,\n mirrors,\n config,\n None,\n )\n .await\n}\n\npub async fn fetch_formula_source_or_bottle_with_progress(\n formula_name: &str,\n url: &str,\n sha256_expected: &str,\n mirrors: &[String],\n config: &Config,\n progress_callback: Option,\n) -> Result {\n let filename = url\n .split('/')\n .next_back()\n .map(|s| s.to_string())\n .unwrap_or_else(|| format!(\"{formula_name}-download\"));\n let cache_path = config.cache_dir().join(&filename);\n\n tracing::debug!(\n \"Preparing to fetch main resource for '{}' from URL: {}\",\n formula_name,\n url\n );\n tracing::debug!(\"Target cache path: {}\", cache_path.display());\n tracing::debug!(\"Expected SHA256: {}\", sha256_expected);\n\n if cache_path.is_file() {\n tracing::debug!(\"File exists in cache: {}\", cache_path.display());\n if !sha256_expected.is_empty() {\n match verify_checksum(&cache_path, sha256_expected) {\n Ok(_) => {\n tracing::debug!(\"Using valid cached file: {}\", cache_path.display());\n return Ok(cache_path);\n }\n Err(e) => {\n debug!(\n \"Cached file checksum mismatch ({}): {}. Redownloading.\",\n cache_path.display(),\n e\n );\n if let Err(remove_err) = fs::remove_file(&cache_path) {\n debug!(\n \"Failed to remove corrupted cached file {}: {}\",\n cache_path.display(),\n remove_err\n );\n }\n }\n }\n } else {\n tracing::debug!(\n \"Using cached file (no checksum provided): {}\",\n cache_path.display()\n );\n return Ok(cache_path);\n }\n } else {\n tracing::debug!(\"File not found in cache.\");\n }\n\n fs::create_dir_all(config.cache_dir()).map_err(|e| {\n SpsError::IoError(format!(\n \"Failed to create cache directory {}: {}\",\n config.cache_dir().display(),\n e\n ))\n })?;\n // Validate primary URL\n validate_url(url)?;\n\n let client = build_http_client()?;\n\n let urls_to_try = std::iter::once(url).chain(mirrors.iter().map(|s| s.as_str()));\n let mut last_error: Option = None;\n\n for current_url in urls_to_try {\n // Validate mirror URL\n validate_url(current_url)?;\n tracing::debug!(\"Attempting download from: {}\", current_url);\n match download_and_verify(\n &client,\n current_url,\n &cache_path,\n sha256_expected,\n progress_callback.clone(),\n )\n .await\n {\n Ok(path) => {\n tracing::debug!(\"Successfully downloaded and verified: {}\", path.display());\n return Ok(path);\n }\n Err(e) => {\n error!(\"Download attempt failed from {}: {}\", current_url, e);\n last_error = Some(e);\n }\n }\n }\n\n Err(last_error.unwrap_or_else(|| {\n SpsError::DownloadError(\n formula_name.to_string(),\n url.to_string(),\n \"All download attempts failed.\".to_string(),\n )\n }))\n}\n\npub async fn fetch_resource(\n formula_name: &str,\n resource: &ResourceSpec,\n config: &Config,\n) -> Result {\n fetch_resource_with_progress(formula_name, resource, config, None).await\n}\n\npub async fn fetch_resource_with_progress(\n formula_name: &str,\n resource: &ResourceSpec,\n config: &Config,\n progress_callback: Option,\n) -> Result {\n let resource_cache_dir = config.cache_dir().join(\"resources\");\n fs::create_dir_all(&resource_cache_dir).map_err(|e| {\n SpsError::IoError(format!(\n \"Failed to create resource cache directory {}: {}\",\n resource_cache_dir.display(),\n e\n ))\n })?;\n // Validate resource URL\n validate_url(&resource.url)?;\n\n let url_filename = resource\n .url\n .split('/')\n .next_back()\n .map(|s| s.to_string())\n .unwrap_or_else(|| format!(\"{}-download\", resource.name));\n let cache_filename = format!(\"{}-{}\", resource.name, url_filename);\n let cache_path = resource_cache_dir.join(&cache_filename);\n\n tracing::debug!(\n \"Preparing to fetch resource '{}' for formula '{}' from URL: {}\",\n resource.name,\n formula_name,\n resource.url\n );\n tracing::debug!(\"Target resource cache path: {}\", cache_path.display());\n tracing::debug!(\"Expected SHA256: {}\", resource.sha256);\n\n if cache_path.is_file() {\n tracing::debug!(\"Resource exists in cache: {}\", cache_path.display());\n match verify_checksum(&cache_path, &resource.sha256) {\n Ok(_) => {\n tracing::debug!(\"Using cached resource: {}\", cache_path.display());\n return Ok(cache_path);\n }\n Err(e) => {\n debug!(\n \"Cached resource checksum mismatch ({}): {}. Redownloading.\",\n cache_path.display(),\n e\n );\n if let Err(remove_err) = fs::remove_file(&cache_path) {\n debug!(\n \"Failed to remove corrupted cached resource file {}: {}\",\n cache_path.display(),\n remove_err\n );\n }\n }\n }\n } else {\n tracing::debug!(\"Resource not found in cache.\");\n }\n\n let client = build_http_client()?;\n match download_and_verify(\n &client,\n &resource.url,\n &cache_path,\n &resource.sha256,\n progress_callback,\n )\n .await\n {\n Ok(path) => {\n tracing::debug!(\n \"Successfully downloaded and verified resource: {}\",\n path.display()\n );\n Ok(path)\n }\n Err(e) => {\n error!(\"Resource download failed from {}: {}\", resource.url, e);\n let _ = fs::remove_file(&cache_path);\n Err(SpsError::DownloadError(\n resource.name.clone(),\n resource.url.clone(),\n format!(\"Download failed: {e}\"),\n ))\n }\n }\n}\n\nfn build_http_client() -> Result {\n let mut headers = HeaderMap::new();\n headers.insert(USER_AGENT, USER_AGENT_STRING.parse().unwrap());\n headers.insert(ACCEPT, \"*/*\".parse().unwrap());\n Client::builder()\n .timeout(Duration::from_secs(DOWNLOAD_TIMEOUT_SECS))\n .connect_timeout(Duration::from_secs(CONNECT_TIMEOUT_SECS))\n .default_headers(headers)\n .redirect(reqwest::redirect::Policy::limited(10))\n .build()\n .map_err(|e| SpsError::HttpError(format!(\"Failed to build HTTP client: {e}\")))\n}\n\nasync fn download_and_verify(\n client: &Client,\n url: &str,\n final_path: &Path,\n sha256_expected: &str,\n progress_callback: Option,\n) -> Result {\n let temp_filename = format!(\n \".{}.download\",\n final_path.file_name().unwrap_or_default().to_string_lossy()\n );\n let temp_path = final_path.with_file_name(temp_filename);\n tracing::debug!(\"Downloading to temporary path: {}\", temp_path.display());\n if temp_path.exists() {\n if let Err(e) = fs::remove_file(&temp_path) {\n tracing::warn!(\n \"Could not remove existing temporary file {}: {}\",\n temp_path.display(),\n e\n );\n }\n }\n\n let response = client.get(url).send().await.map_err(|e| {\n debug!(\"HTTP request failed for {url}: {e}\");\n SpsError::HttpError(format!(\"HTTP request failed for {url}: {e}\"))\n })?;\n let status = response.status();\n tracing::debug!(\"Received HTTP status: {} for {}\", status, url);\n\n if !status.is_success() {\n let body_text = response\n .text()\n .await\n .unwrap_or_else(|_| \"Failed to read response body\".to_string());\n tracing::error!(\"HTTP error {} for URL {}: {}\", status, url, body_text);\n return match status {\n StatusCode::NOT_FOUND => Err(SpsError::DownloadError(\n final_path\n .file_name()\n .map(|s| s.to_string_lossy().to_string())\n .unwrap_or_default(),\n url.to_string(),\n \"Resource not found (404)\".to_string(),\n )),\n StatusCode::FORBIDDEN => Err(SpsError::DownloadError(\n final_path\n .file_name()\n .map(|s| s.to_string_lossy().to_string())\n .unwrap_or_default(),\n url.to_string(),\n \"Access forbidden (403)\".to_string(),\n )),\n _ => Err(SpsError::HttpError(format!(\n \"HTTP error {status} for URL {url}: {body_text}\"\n ))),\n };\n }\n\n // Get total size from Content-Length header if available\n let total_size = response.content_length();\n\n let mut temp_file = TokioFile::create(&temp_path).await.map_err(|e| {\n SpsError::IoError(format!(\n \"Failed to create temp file {}: {}\",\n temp_path.display(),\n e\n ))\n })?;\n\n // Use bytes_stream() for chunked download with progress reporting\n let mut stream = response.bytes_stream();\n let mut bytes_downloaded = 0u64;\n\n while let Some(chunk) = stream.next().await {\n let chunk = chunk.map_err(|e| SpsError::HttpError(format!(\"Failed to read chunk: {e}\")))?;\n\n temp_file.write_all(&chunk).await.map_err(|e| {\n SpsError::IoError(format!(\n \"Failed to write chunk to {}: {}\",\n temp_path.display(),\n e\n ))\n })?;\n\n bytes_downloaded += chunk.len() as u64;\n\n // Call progress callback if provided\n if let Some(ref callback) = progress_callback {\n callback(bytes_downloaded, total_size);\n }\n }\n\n drop(temp_file);\n tracing::debug!(\"Finished writing download stream to temp file.\");\n\n if !sha256_expected.is_empty() {\n verify_checksum(&temp_path, sha256_expected)?;\n tracing::debug!(\n \"Checksum verified for temporary file: {}\",\n temp_path.display()\n );\n } else {\n tracing::warn!(\n \"Skipping checksum verification for {} - none provided.\",\n temp_path.display()\n );\n }\n\n fs::rename(&temp_path, final_path).map_err(|e| {\n SpsError::IoError(format!(\n \"Failed to move temp file {} to {}: {}\",\n temp_path.display(),\n final_path.display(),\n e\n ))\n })?;\n tracing::debug!(\n \"Moved verified file to final location: {}\",\n final_path.display()\n );\n Ok(final_path.to_path_buf())\n}\n"], ["/sps/sps-core/src/upgrade/cask.rs", "// sps-core/src/upgrade/cask.rs\n\nuse std::path::Path;\n\nuse sps_common::config::Config;\nuse sps_common::error::{Result as SpsResult, SpsError};\nuse sps_common::model::cask::Cask;\nuse sps_common::pipeline::JobAction; // Required for install_cask\nuse tracing::{debug, error};\n\nuse crate::check::installed::InstalledPackageInfo;\nuse crate::{install, uninstall};\n\n/// Upgrades a cask package using Homebrew's proven strategy.\npub async fn upgrade_cask_package(\n cask: &Cask,\n new_cask_download_path: &Path,\n old_install_info: &InstalledPackageInfo,\n config: &Config,\n) -> SpsResult<()> {\n debug!(\n \"Upgrading cask {} from {} to {}\",\n cask.token,\n old_install_info.version,\n cask.version.as_deref().unwrap_or(\"latest\")\n );\n\n // 1. Soft-uninstall the old version\n // This removes linked artifacts and updates the old manifest's is_installed flag.\n // It does not remove the old Caskroom version directory itself yet.\n debug!(\n \"Soft-uninstalling old cask version: {} at {}\",\n old_install_info.version,\n old_install_info.path.display()\n );\n uninstall::cask::uninstall_cask_artifacts(old_install_info, config).map_err(|e| {\n error!(\n \"Failed to soft-uninstall old version {} of cask {}: {}\",\n old_install_info.version, cask.token, e\n );\n SpsError::InstallError(format!(\n \"Failed to soft-uninstall old version during upgrade of {}: {e}\",\n cask.token\n ))\n })?;\n debug!(\n \"Successfully soft-uninstalled old version of {}\",\n cask.token\n );\n\n // 2. Install the new version\n // The install_cask function, particularly install_app_from_staged,\n // should handle the upgrade logic (like syncing app data) when\n // passed the JobAction::Upgrade.\n debug!(\n \"Installing new version for cask {} from {}\",\n cask.token,\n new_cask_download_path.display()\n );\n\n let job_action_for_install = JobAction::Upgrade {\n from_version: old_install_info.version.clone(),\n old_install_path: old_install_info.path.clone(),\n };\n\n install::cask::install_cask(\n cask,\n new_cask_download_path,\n config,\n &job_action_for_install,\n )\n .map_err(|e| {\n error!(\n \"Failed to install new version of cask {}: {}\",\n cask.token, e\n );\n SpsError::InstallError(format!(\n \"Failed to install new version during upgrade of {}: {e}\",\n cask.token\n ))\n })?;\n debug!(\"Successfully installed new version of cask {}\", cask.token);\n\n Ok(())\n}\n"], ["/sps/sps/src/cli/info.rs", "//! Contains the logic for the `info` command.\n\nuse std::sync::Arc;\n\nuse clap::Args;\nuse colored::Colorize;\nuse serde_json::Value;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_net::api;\n\n#[derive(Args, Debug)]\npub struct Info {\n /// Name of the formula or cask\n pub name: String,\n\n /// Show information for a cask, not a formula\n #[arg(long)]\n pub cask: bool,\n}\n\nimpl Info {\n /// Displays detailed information about a formula or cask.\n pub async fn run(&self, _config: &Config, cache: Arc) -> Result<()> {\n let name = &self.name;\n let is_cask = self.cask;\n tracing::debug!(\"Getting info for package: {name}, is_cask: {is_cask}\",);\n\n // Print loading message instead of spinner\n println!(\"Loading info for {name}\");\n\n if self.cask {\n match get_cask_info(Arc::clone(&cache), name).await {\n Ok(info) => {\n print_cask_info(name, &info);\n Ok(())\n }\n Err(e) => Err(e),\n }\n } else {\n match get_formula_info_raw(Arc::clone(&cache), name).await {\n Ok(info) => {\n // Removed bottle check logic here as it was complex and potentially racy.\n // We'll try formula first, then cask if formula fails.\n print_formula_info(name, &info);\n return Ok(());\n }\n Err(SpsError::NotFound(_)) | Err(SpsError::Generic(_)) => {\n // If formula lookup failed (not found or generic error), try cask.\n tracing::debug!(\"Formula '{}' info failed, trying cask.\", name);\n }\n Err(e) => {\n return Err(e); // Propagate other errors (API, JSON, etc.)\n }\n }\n // --- Cask Fallback ---\n match get_cask_info(Arc::clone(&cache), name).await {\n Ok(info) => {\n print_cask_info(name, &info);\n Ok(())\n }\n Err(e) => {\n Err(e) // Return the cask error if both formula and cask fail\n }\n }\n }\n }\n}\n\n/// Retrieves formula information from the cache or API as raw JSON\nasync fn get_formula_info_raw(cache: Arc, name: &str) -> Result {\n match cache.load_raw(\"formula.json\") {\n Ok(formula_data) => {\n let formulas: Vec =\n serde_json::from_str(&formula_data).map_err(SpsError::from)?;\n for formula in formulas {\n if let Some(fname) = formula.get(\"name\").and_then(Value::as_str) {\n if fname == name {\n return Ok(formula);\n }\n }\n // Also check aliases if needed\n if let Some(aliases) = formula.get(\"aliases\").and_then(|a| a.as_array()) {\n if aliases.iter().any(|a| a.as_str() == Some(name)) {\n return Ok(formula);\n }\n }\n }\n tracing::debug!(\"Formula '{}' not found within cached 'formula.json'.\", name);\n // Explicitly return NotFound if not in cache\n return Err(SpsError::NotFound(format!(\n \"Formula '{name}' not found in cache\"\n )));\n }\n Err(e) => tracing::debug!(\n \"Cache file 'formula.json' not found or failed to load ({}). Fetching from API.\",\n e\n ),\n }\n tracing::debug!(\"Fetching formula '{}' directly from API\", name);\n // api::fetch_formula returns Value directly now\n let value = api::fetch_formula(name).await?;\n // Store in cache if fetched successfully\n // Note: This might overwrite the full list cache, consider storing individual files or a map\n // cache.store_raw(&format!(\"formula/{}.json\", name), &value.to_string())?; // Example of\n // storing individually\n Ok(value)\n}\n\n/// Retrieves cask information from the cache or API\nasync fn get_cask_info(cache: Arc, name: &str) -> Result {\n match cache.load_raw(\"cask.json\") {\n Ok(cask_data) => {\n let casks: Vec = serde_json::from_str(&cask_data).map_err(SpsError::from)?;\n for cask in casks {\n if let Some(token) = cask.get(\"token\").and_then(Value::as_str) {\n if token == name {\n return Ok(cask);\n }\n }\n // Check aliases if needed\n if let Some(aliases) = cask.get(\"aliases\").and_then(|a| a.as_array()) {\n if aliases.iter().any(|a| a.as_str() == Some(name)) {\n return Ok(cask);\n }\n }\n }\n tracing::debug!(\"Cask '{}' not found within cached 'cask.json'.\", name);\n // Explicitly return NotFound if not in cache\n return Err(SpsError::NotFound(format!(\n \"Cask '{name}' not found in cache\"\n )));\n }\n Err(e) => tracing::debug!(\n \"Cache file 'cask.json' not found or failed to load ({}). Fetching from API.\",\n e\n ),\n }\n tracing::debug!(\"Fetching cask '{}' directly from API\", name);\n // api::fetch_cask returns Value directly now\n let value = api::fetch_cask(name).await?;\n // Store in cache if fetched successfully\n // cache.store_raw(&format!(\"cask/{}.json\", name), &value.to_string())?; // Example of storing\n // individually\n Ok(value)\n}\n\n/// Prints formula information in a formatted table\nfn print_formula_info(_name: &str, formula: &Value) {\n // Basic info extraction\n let full_name = formula\n .get(\"full_name\")\n .and_then(|f| f.as_str())\n .unwrap_or(\"N/A\");\n let version = formula\n .get(\"versions\")\n .and_then(|v| v.get(\"stable\"))\n .and_then(|s| s.as_str())\n .unwrap_or(\"N/A\");\n let revision = formula\n .get(\"revision\")\n .and_then(|r| r.as_u64())\n .unwrap_or(0);\n let version_str = if revision > 0 {\n format!(\"{version}_{revision}\")\n } else {\n version.to_string()\n };\n let license = formula\n .get(\"license\")\n .and_then(|l| l.as_str())\n .unwrap_or(\"N/A\");\n let homepage = formula\n .get(\"homepage\")\n .and_then(|h| h.as_str())\n .unwrap_or(\"N/A\");\n\n // Header\n println!(\"{}\", format!(\"Formula: {full_name}\").green().bold());\n\n // Summary table\n let mut table = prettytable::Table::new();\n table.set_format(*prettytable::format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n table.add_row(prettytable::row![\"Version\", version_str]);\n table.add_row(prettytable::row![\"License\", license]);\n table.add_row(prettytable::row![\"Homepage\", homepage]);\n table.printstd();\n\n // Detailed sections\n if let Some(desc) = formula.get(\"desc\").and_then(|d| d.as_str()) {\n if !desc.is_empty() {\n println!(\"\\n{}\", \"Description\".blue().bold());\n println!(\"{desc}\");\n }\n }\n if let Some(caveats) = formula.get(\"caveats\").and_then(|c| c.as_str()) {\n if !caveats.is_empty() {\n println!(\"\\n{}\", \"Caveats\".blue().bold());\n println!(\"{caveats}\");\n }\n }\n\n // Combined Dependencies Section\n let mut dep_table = prettytable::Table::new();\n dep_table.set_format(*prettytable::format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n let mut has_deps = false;\n\n let mut add_deps = |title: &str, key: &str, tag: &str| {\n if let Some(deps) = formula.get(key).and_then(|d| d.as_array()) {\n let dep_list: Vec<&str> = deps.iter().filter_map(|d| d.as_str()).collect();\n if !dep_list.is_empty() {\n has_deps = true;\n for (i, d) in dep_list.iter().enumerate() {\n let display_title = if i == 0 { title } else { \"\" };\n let display_tag = if i == 0 {\n format!(\"({tag})\")\n } else {\n \"\".to_string()\n };\n dep_table.add_row(prettytable::row![display_title, d, display_tag]);\n }\n }\n }\n };\n\n add_deps(\"Required\", \"dependencies\", \"runtime\");\n add_deps(\n \"Recommended\",\n \"recommended_dependencies\",\n \"runtime, recommended\",\n );\n add_deps(\"Optional\", \"optional_dependencies\", \"runtime, optional\");\n add_deps(\"Build\", \"build_dependencies\", \"build\");\n add_deps(\"Test\", \"test_dependencies\", \"test\");\n\n if has_deps {\n println!(\"\\n{}\", \"Dependencies\".blue().bold());\n dep_table.printstd();\n }\n\n // Installation hint\n println!(\"\\n{}\", \"Installation\".blue().bold());\n println!(\n \" {} install {}\",\n \"sps\".cyan(),\n formula\n .get(\"name\")\n .and_then(|n| n.as_str())\n .unwrap_or(full_name) // Use short name if available\n );\n}\n\n/// Prints cask information in a formatted table\nfn print_cask_info(name: &str, cask: &Value) {\n // Header\n println!(\"{}\", format!(\"Cask: {name}\").green().bold());\n\n // Summary table\n let mut table = prettytable::Table::new();\n table.set_format(*prettytable::format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n if let Some(names) = cask.get(\"name\").and_then(|n| n.as_array()) {\n if let Some(first) = names.first().and_then(|s| s.as_str()) {\n table.add_row(prettytable::row![\"Name\", first]);\n }\n }\n if let Some(desc) = cask.get(\"desc\").and_then(|d| d.as_str()) {\n table.add_row(prettytable::row![\"Description\", desc]);\n }\n if let Some(homepage) = cask.get(\"homepage\").and_then(|h| h.as_str()) {\n table.add_row(prettytable::row![\"Homepage\", homepage]);\n }\n if let Some(version) = cask.get(\"version\").and_then(|v| v.as_str()) {\n table.add_row(prettytable::row![\"Version\", version]);\n }\n if let Some(url) = cask.get(\"url\").and_then(|u| u.as_str()) {\n table.add_row(prettytable::row![\"Download URL\", url]);\n }\n // Add SHA if present\n if let Some(sha) = cask.get(\"sha256\").and_then(|s| s.as_str()) {\n if !sha.is_empty() {\n table.add_row(prettytable::row![\"SHA256\", sha]);\n }\n }\n table.printstd();\n\n // Dependencies Section\n if let Some(deps) = cask.get(\"depends_on\").and_then(|d| d.as_object()) {\n let mut dep_table = prettytable::Table::new();\n dep_table.set_format(*prettytable::format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n let mut has_deps = false;\n\n if let Some(formulas) = deps.get(\"formula\").and_then(|f| f.as_array()) {\n if !formulas.is_empty() {\n has_deps = true;\n dep_table.add_row(prettytable::row![\n \"Formula\".yellow(),\n formulas\n .iter()\n .map(|v| v.as_str().unwrap_or(\"\"))\n .collect::>()\n .join(\", \")\n ]);\n }\n }\n if let Some(casks) = deps.get(\"cask\").and_then(|c| c.as_array()) {\n if !casks.is_empty() {\n has_deps = true;\n dep_table.add_row(prettytable::row![\n \"Cask\".yellow(),\n casks\n .iter()\n .map(|v| v.as_str().unwrap_or(\"\"))\n .collect::>()\n .join(\", \")\n ]);\n }\n }\n if let Some(macos) = deps.get(\"macos\") {\n has_deps = true;\n let macos_str = match macos {\n Value::String(s) => s.clone(),\n Value::Array(arr) => arr\n .iter()\n .map(|v| v.as_str().unwrap_or(\"\"))\n .collect::>()\n .join(\" or \"),\n _ => \"Unknown\".to_string(),\n };\n dep_table.add_row(prettytable::row![\"macOS\".yellow(), macos_str]);\n }\n\n if has_deps {\n println!(\"\\n{}\", \"Dependencies\".blue().bold());\n dep_table.printstd();\n }\n }\n\n // Installation hint\n println!(\"\\n{}\", \"Installation\".blue().bold());\n println!(\n \" {} install --cask {}\", // Always use --cask for clarity\n \"sps\".cyan(),\n name // Use the token 'name' passed to the function\n );\n}\n// Removed is_bottle_available check\n"], ["/sps/sps-net/src/oci.rs", "use std::collections::HashMap;\nuse std::fs::{remove_file, File};\nuse std::path::Path;\nuse std::sync::Arc;\nuse std::time::Duration;\n\nuse futures::StreamExt;\nuse rand::rngs::SmallRng;\nuse rand::{Rng, SeedableRng};\nuse reqwest::header::{ACCEPT, AUTHORIZATION};\nuse reqwest::{Client, Response, StatusCode};\nuse serde::{Deserialize, Serialize};\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse tracing::{debug, error};\nuse url::Url;\n\nuse crate::http::ProgressCallback;\nuse crate::validation::{validate_url, verify_checksum};\n\nconst OCI_MANIFEST_V1_TYPE: &str = \"application/vnd.oci.image.index.v1+json\";\nconst OCI_LAYER_V1_TYPE: &str = \"application/vnd.oci.image.layer.v1.tar+gzip\";\nconst DEFAULT_GHCR_TOKEN_ENDPOINT: &str = \"https://ghcr.io/token\";\npub const DEFAULT_GHCR_DOMAIN: &str = \"ghcr.io\";\n\nconst CONNECT_TIMEOUT_SECS: u64 = 30;\nconst REQUEST_TIMEOUT_SECS: u64 = 300;\nconst USER_AGENT_STRING: &str = \"sps package manager (Rust; +https://github.com/alexykn/sps)\";\n\n#[derive(Deserialize, Debug)]\nstruct OciTokenResponse {\n token: String,\n}\n\n#[derive(Serialize, Deserialize, Debug, Clone)]\n#[serde(rename_all = \"camelCase\")]\npub struct OciManifestIndex {\n pub schema_version: u32,\n pub media_type: Option,\n pub manifests: Vec,\n}\n\n#[derive(Serialize, Deserialize, Debug, Clone)]\n#[serde(rename_all = \"camelCase\")]\npub struct OciManifestDescriptor {\n pub media_type: String,\n pub digest: String,\n pub size: u64,\n pub platform: Option,\n pub annotations: Option>,\n}\n\n#[derive(Serialize, Deserialize, Debug, Clone)]\n#[serde(rename_all = \"camelCase\")]\npub struct OciPlatform {\n pub architecture: String,\n pub os: String,\n #[serde(rename = \"os.version\")]\n pub os_version: Option,\n #[serde(default)]\n pub features: Vec,\n pub variant: Option,\n}\n\n#[derive(Debug, Clone)]\nenum OciAuth {\n None,\n AnonymousBearer { token: String },\n ExplicitBearer { token: String },\n Basic { encoded: String },\n}\n\nasync fn fetch_oci_resource(\n resource_url: &str,\n accept_header: &str,\n config: &Config,\n client: &Client,\n) -> Result {\n let url = Url::parse(resource_url)\n .map_err(|e| SpsError::Generic(format!(\"Invalid URL '{resource_url}': {e}\")))?;\n validate_url(url.as_str())?;\n let registry_domain = url.host_str().unwrap_or(DEFAULT_GHCR_DOMAIN);\n let repo_path = extract_repo_path_from_url(&url).unwrap_or(\"\");\n\n let auth = determine_auth(config, client, registry_domain, repo_path).await?;\n let resp = execute_oci_request(client, resource_url, accept_header, &auth).await?;\n let txt = resp.text().await.map_err(|e| SpsError::Http(Arc::new(e)))?;\n\n debug!(\"OCI response ({} bytes) from {}\", txt.len(), resource_url);\n serde_json::from_str(&txt).map_err(|e| {\n error!(\"JSON parse error from {}: {}\", resource_url, e);\n SpsError::Json(Arc::new(e))\n })\n}\n\npub async fn download_oci_blob(\n blob_url: &str,\n destination_path: &Path,\n config: &Config,\n client: &Client,\n expected_digest: &str,\n) -> Result<()> {\n download_oci_blob_with_progress(\n blob_url,\n destination_path,\n config,\n client,\n expected_digest,\n None,\n )\n .await\n}\n\npub async fn download_oci_blob_with_progress(\n blob_url: &str,\n destination_path: &Path,\n config: &Config,\n client: &Client,\n expected_digest: &str,\n progress_callback: Option,\n) -> Result<()> {\n debug!(\"Downloading OCI blob: {}\", blob_url);\n let url = Url::parse(blob_url)\n .map_err(|e| SpsError::Generic(format!(\"Invalid URL '{blob_url}': {e}\")))?;\n validate_url(url.as_str())?;\n let registry_domain = url.host_str().unwrap_or(DEFAULT_GHCR_DOMAIN);\n let repo_path = extract_repo_path_from_url(&url).unwrap_or(\"\");\n\n let auth = determine_auth(config, client, registry_domain, repo_path).await?;\n let resp = execute_oci_request(client, blob_url, OCI_LAYER_V1_TYPE, &auth).await?;\n\n // Get total size from Content-Length header if available\n let total_size = resp.content_length();\n\n let tmp = destination_path.with_file_name(format!(\n \".{}.download\",\n destination_path.file_name().unwrap().to_string_lossy()\n ));\n let mut out = File::create(&tmp).map_err(|e| SpsError::Io(Arc::new(e)))?;\n\n let mut stream = resp.bytes_stream();\n let mut bytes_downloaded = 0u64;\n\n while let Some(chunk) = stream.next().await {\n let b = chunk.map_err(|e| SpsError::Http(Arc::new(e)))?;\n std::io::Write::write_all(&mut out, &b).map_err(|e| SpsError::Io(Arc::new(e)))?;\n\n bytes_downloaded += b.len() as u64;\n\n // Call progress callback if provided\n if let Some(ref callback) = progress_callback {\n callback(bytes_downloaded, total_size);\n }\n }\n std::fs::rename(&tmp, destination_path).map_err(|e| SpsError::Io(Arc::new(e)))?;\n\n if !expected_digest.is_empty() {\n match verify_checksum(destination_path, expected_digest) {\n Ok(_) => {\n tracing::debug!(\"OCI Blob checksum verified: {}\", destination_path.display());\n }\n Err(e) => {\n tracing::error!(\n \"OCI Blob checksum mismatch ({}). Deleting downloaded file.\",\n e\n );\n let _ = remove_file(destination_path);\n return Err(e);\n }\n }\n } else {\n tracing::warn!(\n \"Skipping checksum verification for OCI blob {} - no checksum provided.\",\n destination_path.display()\n );\n }\n\n debug!(\"Blob saved to {}\", destination_path.display());\n Ok(())\n}\n\npub async fn fetch_oci_manifest_index(\n manifest_url: &str,\n config: &Config,\n client: &Client,\n) -> Result {\n fetch_oci_resource(manifest_url, OCI_MANIFEST_V1_TYPE, config, client).await\n}\n\npub fn build_oci_client() -> Result {\n Client::builder()\n .user_agent(USER_AGENT_STRING)\n .connect_timeout(Duration::from_secs(CONNECT_TIMEOUT_SECS))\n .timeout(Duration::from_secs(REQUEST_TIMEOUT_SECS))\n .redirect(reqwest::redirect::Policy::default())\n .build()\n .map_err(|e| SpsError::Http(Arc::new(e)))\n}\n\nfn extract_repo_path_from_url(url: &Url) -> Option<&str> {\n url.path()\n .trim_start_matches('/')\n .trim_start_matches(\"v2/\")\n .split(\"/manifests/\")\n .next()\n .and_then(|s| s.split(\"/blobs/\").next())\n .filter(|s| !s.is_empty())\n}\n\nasync fn determine_auth(\n config: &Config,\n client: &Client,\n registry_domain: &str,\n repo_path: &str,\n) -> Result {\n if let Some(token) = &config.docker_registry_token {\n debug!(\"Using explicit bearer for {}\", registry_domain);\n return Ok(OciAuth::ExplicitBearer {\n token: token.clone(),\n });\n }\n if let Some(basic) = &config.docker_registry_basic_auth {\n debug!(\"Using explicit basic auth for {}\", registry_domain);\n return Ok(OciAuth::Basic {\n encoded: basic.clone(),\n });\n }\n\n if registry_domain.eq_ignore_ascii_case(DEFAULT_GHCR_DOMAIN) && !repo_path.is_empty() {\n debug!(\n \"Anonymous token fetch for {} scope={}\",\n registry_domain, repo_path\n );\n match fetch_anonymous_token(client, registry_domain, repo_path).await {\n Ok(t) => return Ok(OciAuth::AnonymousBearer { token: t }),\n Err(e) => debug!(\"Anon token failed, proceeding unauthenticated: {}\", e),\n }\n }\n Ok(OciAuth::None)\n}\n\nasync fn fetch_anonymous_token(\n client: &Client,\n registry_domain: &str,\n repo_path: &str,\n) -> Result {\n let endpoint = if registry_domain.eq_ignore_ascii_case(DEFAULT_GHCR_DOMAIN) {\n DEFAULT_GHCR_TOKEN_ENDPOINT.to_string()\n } else {\n format!(\"https://{registry_domain}/token\")\n };\n let scope = format!(\"repository:{repo_path}:pull\");\n let token_url = format!(\"{endpoint}?service={registry_domain}&scope={scope}\");\n\n const MAX_RETRIES: u8 = 3;\n let base_delay = Duration::from_millis(200);\n let mut delay = base_delay;\n // Use a Sendable RNG\n let mut rng = SmallRng::from_os_rng();\n\n for attempt in 0..=MAX_RETRIES {\n debug!(\n \"Token attempt {}/{} from {}\",\n attempt + 1,\n MAX_RETRIES + 1,\n token_url\n );\n\n match client.get(&token_url).send().await {\n Ok(resp) if resp.status().is_success() => {\n let tok: OciTokenResponse = resp\n .json()\n .await\n .map_err(|e| SpsError::ApiRequestError(format!(\"Parse token response: {e}\")))?;\n return Ok(tok.token);\n }\n Ok(resp) => {\n let code = resp.status();\n let body = resp.text().await.unwrap_or_default();\n error!(\"Token fetch {}: {} – {}\", attempt + 1, code, body);\n if !code.is_server_error() || attempt == MAX_RETRIES {\n return Err(SpsError::Api(format!(\"Token endpoint {code}: {body}\")));\n }\n }\n Err(e) => {\n error!(\"Network error on token fetch {}: {}\", attempt + 1, e);\n if attempt == MAX_RETRIES {\n return Err(SpsError::Http(Arc::new(e)));\n }\n }\n }\n\n let jitter = rng.random_range(0..(base_delay.as_millis() as u64 / 2));\n tokio::time::sleep(delay + Duration::from_millis(jitter)).await;\n delay *= 2;\n }\n\n Err(SpsError::Api(format!(\n \"Failed to fetch OCI token after {} attempts\",\n MAX_RETRIES + 1\n )))\n}\n\nasync fn execute_oci_request(\n client: &Client,\n url: &str,\n accept: &str,\n auth: &OciAuth,\n) -> Result {\n debug!(\"OCI request → {} (Accept: {})\", url, accept);\n let mut req = client.get(url).header(ACCEPT, accept);\n match auth {\n OciAuth::AnonymousBearer { token } | OciAuth::ExplicitBearer { token }\n if !token.is_empty() =>\n {\n req = req.header(AUTHORIZATION, format!(\"Bearer {token}\"))\n }\n OciAuth::Basic { encoded } if !encoded.is_empty() => {\n req = req.header(AUTHORIZATION, format!(\"Basic {encoded}\"))\n }\n _ => {}\n }\n\n let resp = req.send().await.map_err(|e| SpsError::Http(Arc::new(e)))?;\n let status = resp.status();\n if status.is_success() {\n Ok(resp)\n } else {\n let body = resp.text().await.unwrap_or_default();\n error!(\"OCI {} ⇒ {} – {}\", url, status, body);\n let err = match status {\n StatusCode::UNAUTHORIZED => SpsError::Api(format!(\"Auth required: {status}\")),\n StatusCode::FORBIDDEN => SpsError::Api(format!(\"Permission denied: {status}\")),\n StatusCode::NOT_FOUND => SpsError::NotFound(format!(\"Not found: {status}\")),\n _ => SpsError::Api(format!(\"HTTP {status} – {body}\")),\n };\n Err(err)\n }\n}\n"], ["/sps/sps-common/src/formulary.rs", "use std::collections::HashMap;\nuse std::sync::Arc;\n\nuse tracing::debug;\n\nuse super::cache::Cache;\nuse super::config::Config;\nuse super::error::{Result, SpsError};\nuse super::model::formula::Formula;\n\n#[derive()]\npub struct Formulary {\n cache: Cache,\n parsed_cache: std::sync::Mutex>>,\n}\n\nimpl Formulary {\n pub fn new(config: Config) -> Self {\n let cache = Cache::new(&config).unwrap_or_else(|e| {\n panic!(\"Failed to initialize cache in Formulary: {e}\");\n });\n Self {\n cache,\n parsed_cache: std::sync::Mutex::new(HashMap::new()),\n }\n }\n\n pub fn load_formula(&self, name: &str) -> Result {\n let mut parsed_cache_guard = self.parsed_cache.lock().unwrap();\n if let Some(formula_arc) = parsed_cache_guard.get(name) {\n debug!(\"Loaded formula '{}' from parsed cache.\", name);\n return Ok(Arc::clone(formula_arc).as_ref().clone());\n }\n drop(parsed_cache_guard);\n\n let raw_data = self.cache.load_raw(\"formula.json\")?;\n let all_formulas: Vec = serde_json::from_str(&raw_data)\n .map_err(|e| SpsError::Cache(format!(\"Failed to parse cached formula data: {e}\")))?;\n debug!(\"Parsed {} formulas.\", all_formulas.len());\n\n let mut found_formula: Option = None;\n parsed_cache_guard = self.parsed_cache.lock().unwrap();\n for formula in all_formulas {\n let formula_name = formula.name.clone();\n let formula_arc = std::sync::Arc::new(formula);\n\n if formula_name == name {\n found_formula = Some(Arc::clone(&formula_arc).as_ref().clone());\n }\n\n parsed_cache_guard\n .entry(formula_name)\n .or_insert(formula_arc);\n }\n\n match found_formula {\n Some(f) => {\n debug!(\n \"Successfully loaded formula '{}' version {}\",\n f.name,\n f.version_str_full()\n );\n Ok(f)\n }\n None => {\n debug!(\n \"Formula '{}' not found within the cached formula data.\",\n name\n );\n Err(SpsError::Generic(format!(\n \"Formula '{name}' not found in cache.\"\n )))\n }\n }\n }\n}\n"], ["/sps/sps/src/cli/install.rs", "// sps-cli/src/cli/install.rs\n\nuse std::sync::Arc;\n\nuse clap::Args;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse tracing::instrument;\n\n// Import pipeline components from the new module\nuse crate::pipeline::runner::{self, CommandType, PipelineFlags};\n\n// Keep the Args struct specific to 'install' if needed, or reuse a common one\n#[derive(Debug, Args)]\npub struct InstallArgs {\n #[arg(required = true)]\n names: Vec,\n\n // Keep flags relevant to install/pipeline\n #[arg(long)]\n skip_deps: bool, // Note: May not be fully supported by core resolution yet\n #[arg(long, help = \"Force install specified targets as casks\")]\n cask: bool,\n #[arg(long, help = \"Force install specified targets as formulas\")]\n formula: bool,\n #[arg(long)]\n include_optional: bool,\n #[arg(long)]\n skip_recommended: bool,\n #[arg(\n long,\n help = \"Force building the formula from source, even if a bottle is available\"\n )]\n build_from_source: bool,\n // Worker/Queue size flags might belong here or be global CLI flags\n // #[arg(long, value_name = \"sps_WORKERS\")]\n // max_workers: Option,\n // #[arg(long, value_name = \"sps_QUEUE\")]\n // queue_size: Option,\n}\n\nimpl InstallArgs {\n #[instrument(skip(self, config, cache), fields(targets = ?self.names))]\n pub async fn run(&self, config: &Config, cache: Arc) -> Result<()> {\n // --- Argument Validation (moved from old run) ---\n if self.formula && self.cask {\n return Err(sps_common::error::SpsError::Generic(\n \"Cannot use --formula and --cask together.\".to_string(),\n ));\n }\n // Add validation for skip_deps if needed\n\n // --- Prepare Pipeline Flags ---\n let flags = PipelineFlags {\n build_from_source: self.build_from_source,\n include_optional: self.include_optional,\n skip_recommended: self.skip_recommended,\n // Add other flags...\n };\n\n // --- Determine Initial Targets based on --formula/--cask flags ---\n // (This logic might be better inside plan_package_operations based on CommandType)\n let initial_targets = self.names.clone(); // For install, all names are initial targets\n\n // --- Execute the Pipeline ---\n runner::run_pipeline(\n &initial_targets,\n CommandType::Install, // Specify the command type\n config,\n cache,\n &flags, // Pass the flags struct\n )\n .await\n }\n}\n"], ["/sps/sps-net/src/api.rs", "use std::sync::Arc;\n\nuse reqwest::header::{ACCEPT, AUTHORIZATION, USER_AGENT};\nuse reqwest::Client;\nuse serde_json::Value;\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::cask::{Cask, CaskList};\nuse sps_common::model::formula::Formula;\nuse tracing::{debug, error};\n\nconst FORMULAE_API_BASE_URL: &str = \"https://formulae.brew.sh/api\";\nconst GITHUB_API_BASE_URL: &str = \"https://api.github.com\";\nconst USER_AGENT_STRING: &str = \"sps Package Manager (Rust; +https://github.com/your/sp)\";\n\nfn build_api_client(config: &Config) -> Result {\n let mut headers = reqwest::header::HeaderMap::new();\n headers.insert(USER_AGENT, USER_AGENT_STRING.parse().unwrap());\n headers.insert(ACCEPT, \"application/vnd.github+json\".parse().unwrap());\n if let Some(token) = &config.github_api_token {\n debug!(\"Adding GitHub API token to request headers.\");\n match format!(\"Bearer {token}\").parse() {\n Ok(val) => {\n headers.insert(AUTHORIZATION, val);\n }\n Err(e) => {\n error!(\"Failed to parse GitHub API token into header value: {}\", e);\n }\n }\n } else {\n debug!(\"No GitHub API token found in config.\");\n }\n Ok(Client::builder().default_headers(headers).build()?)\n}\n\npub async fn fetch_raw_formulae_json(endpoint: &str) -> Result {\n let url = format!(\"{FORMULAE_API_BASE_URL}/{endpoint}\");\n debug!(\"Fetching data from Homebrew Formulae API: {}\", url);\n let client = reqwest::Client::builder()\n .user_agent(USER_AGENT_STRING)\n .build()?;\n let response = client.get(&url).send().await.map_err(|e| {\n debug!(\"HTTP request failed for {}: {}\", url, e);\n SpsError::Http(Arc::new(e))\n })?;\n if !response.status().is_success() {\n let status = response.status();\n let body = response\n .text()\n .await\n .unwrap_or_else(|e| format!(\"(Failed to read response body: {e})\"));\n debug!(\n \"HTTP request to {} returned non-success status: {}\",\n url, status\n );\n debug!(\"Response body for failed request to {}: {}\", url, body);\n return Err(SpsError::Api(format!(\"HTTP status {status} from {url}\")));\n }\n let body = response.text().await?;\n if body.trim().is_empty() {\n error!(\"Response body for {} was empty.\", url);\n return Err(SpsError::Api(format!(\n \"Empty response body received from {url}\"\n )));\n }\n Ok(body)\n}\n\npub async fn fetch_all_formulas() -> Result {\n fetch_raw_formulae_json(\"formula.json\").await\n}\n\npub async fn fetch_all_casks() -> Result {\n fetch_raw_formulae_json(\"cask.json\").await\n}\n\npub async fn fetch_formula(name: &str) -> Result {\n let direct_fetch_result = fetch_raw_formulae_json(&format!(\"formula/{name}.json\")).await;\n if let Ok(body) = direct_fetch_result {\n let formula: serde_json::Value = serde_json::from_str(&body)?;\n Ok(formula)\n } else {\n debug!(\n \"Direct fetch for formula '{}' failed ({:?}). Fetching full list as fallback.\",\n name,\n direct_fetch_result.err()\n );\n let all_formulas_body = fetch_all_formulas().await?;\n let formulas: Vec = serde_json::from_str(&all_formulas_body)?;\n for formula in formulas {\n if formula.get(\"name\").and_then(Value::as_str) == Some(name) {\n return Ok(formula);\n }\n if formula.get(\"full_name\").and_then(Value::as_str) == Some(name) {\n return Ok(formula);\n }\n }\n Err(SpsError::NotFound(format!(\n \"Formula '{name}' not found in API list\"\n )))\n }\n}\n\npub async fn fetch_cask(token: &str) -> Result {\n let direct_fetch_result = fetch_raw_formulae_json(&format!(\"cask/{token}.json\")).await;\n if let Ok(body) = direct_fetch_result {\n let cask: serde_json::Value = serde_json::from_str(&body)?;\n Ok(cask)\n } else {\n debug!(\n \"Direct fetch for cask '{}' failed ({:?}). Fetching full list as fallback.\",\n token,\n direct_fetch_result.err()\n );\n let all_casks_body = fetch_all_casks().await?;\n let casks: Vec = serde_json::from_str(&all_casks_body)?;\n for cask in casks {\n if cask.get(\"token\").and_then(Value::as_str) == Some(token) {\n return Ok(cask);\n }\n }\n Err(SpsError::NotFound(format!(\n \"Cask '{token}' not found in API list\"\n )))\n }\n}\n\nasync fn fetch_github_api_json(endpoint: &str, config: &Config) -> Result {\n let url = format!(\"{GITHUB_API_BASE_URL}{endpoint}\");\n debug!(\"Fetching data from GitHub API: {}\", url);\n let client = build_api_client(config)?;\n let response = client.get(&url).send().await.map_err(|e| {\n error!(\"GitHub API request failed for {}: {}\", url, e);\n SpsError::Http(Arc::new(e))\n })?;\n if !response.status().is_success() {\n let status = response.status();\n let body = response\n .text()\n .await\n .unwrap_or_else(|e| format!(\"(Failed to read response body: {e})\"));\n error!(\n \"GitHub API request to {} returned non-success status: {}\",\n url, status\n );\n debug!(\n \"Response body for failed GitHub API request to {}: {}\",\n url, body\n );\n return Err(SpsError::Api(format!(\"HTTP status {status} from {url}\")));\n }\n let value: Value = response.json::().await.map_err(|e| {\n error!(\"Failed to parse JSON response from {}: {}\", url, e);\n SpsError::ApiRequestError(e.to_string())\n })?;\n Ok(value)\n}\n\n#[allow(dead_code)]\nasync fn fetch_github_repo_info(owner: &str, repo: &str, config: &Config) -> Result {\n let endpoint = format!(\"/repos/{owner}/{repo}\");\n fetch_github_api_json(&endpoint, config).await\n}\n\npub async fn get_formula(name: &str) -> Result {\n let url = format!(\"{FORMULAE_API_BASE_URL}/formula/{name}.json\");\n debug!(\n \"Fetching and parsing formula data for '{}' from {}\",\n name, url\n );\n let client = reqwest::Client::new();\n let response = client.get(&url).send().await.map_err(|e| {\n debug!(\"HTTP request failed when fetching formula {}: {}\", name, e);\n SpsError::Http(Arc::new(e))\n })?;\n let status = response.status();\n let text = response.text().await?;\n if !status.is_success() {\n debug!(\"Failed to fetch formula {} (Status {})\", name, status);\n debug!(\"Response body for failed formula fetch {}: {}\", name, text);\n return Err(SpsError::Api(format!(\n \"Failed to fetch formula {name}: Status {status}\"\n )));\n }\n if text.trim().is_empty() {\n error!(\"Received empty body when fetching formula {}\", name);\n return Err(SpsError::Api(format!(\n \"Empty response body for formula {name}\"\n )));\n }\n match serde_json::from_str::(&text) {\n Ok(formula) => Ok(formula),\n Err(_) => match serde_json::from_str::>(&text) {\n Ok(mut formulas) if !formulas.is_empty() => {\n debug!(\n \"Parsed formula {} from a single-element array response.\",\n name\n );\n Ok(formulas.remove(0))\n }\n Ok(_) => {\n error!(\"Received empty array when fetching formula {}\", name);\n Err(SpsError::NotFound(format!(\n \"Formula '{name}' not found (empty array returned)\"\n )))\n }\n Err(e_vec) => {\n error!(\n \"Failed to parse formula {} as object or array. Error: {}. Body (sample): {}\",\n name,\n e_vec,\n text.chars().take(500).collect::()\n );\n Err(SpsError::Json(Arc::new(e_vec)))\n }\n },\n }\n}\n\npub async fn get_all_formulas() -> Result> {\n let raw_data = fetch_all_formulas().await?;\n serde_json::from_str(&raw_data).map_err(|e| {\n error!(\"Failed to parse all_formulas response: {}\", e);\n SpsError::Json(Arc::new(e))\n })\n}\n\npub async fn get_cask(name: &str) -> Result {\n let raw_json_result = fetch_cask(name).await;\n let raw_json = match raw_json_result {\n Ok(json_val) => json_val,\n Err(e) => {\n error!(\"Failed to fetch raw JSON for cask {}: {}\", name, e);\n return Err(e);\n }\n };\n match serde_json::from_value::(raw_json.clone()) {\n Ok(cask) => Ok(cask),\n Err(e) => {\n error!(\"Failed to parse cask {} JSON: {}\", name, e);\n match serde_json::to_string_pretty(&raw_json) {\n Ok(json_str) => {\n tracing::debug!(\"Problematic JSON for cask '{}':\\n{}\", name, json_str);\n }\n Err(fmt_err) => {\n tracing::debug!(\n \"Could not pretty-print problematic JSON for cask {}: {}\",\n name,\n fmt_err\n );\n tracing::debug!(\"Raw problematic value: {:?}\", raw_json);\n }\n }\n Err(SpsError::Json(Arc::new(e)))\n }\n }\n}\n\npub async fn get_all_casks() -> Result {\n let raw_data = fetch_all_casks().await?;\n let casks: Vec = serde_json::from_str(&raw_data).map_err(|e| {\n error!(\"Failed to parse all_casks response: {}\", e);\n SpsError::Json(Arc::new(e))\n })?;\n Ok(CaskList { casks })\n}\n"], ["/sps/sps-core/src/check/installed.rs", "// sps-core/src/check/installed.rs\nuse std::fs::{self}; // Removed DirEntry as it's not directly used here\nuse std::io;\nuse std::path::PathBuf;\nuse std::sync::Arc;\n\nuse serde::{Deserialize, Serialize};\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::keg::KegRegistry; // KegRegistry is used\nuse tracing::{debug, warn};\n\n#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]\npub enum PackageType {\n Formula,\n Cask,\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub struct InstalledPackageInfo {\n pub name: String,\n pub version: String, // This will now store keg.version_str\n pub pkg_type: PackageType,\n pub path: PathBuf,\n}\n\n// Helper closure to handle io::Result -> Option logging errors\n// Defined outside the functions to avoid repetition\nfn handle_dir_entry(res: io::Result, dir_path_str: &str) -> Option {\n match res {\n Ok(entry) => Some(entry),\n Err(e) => {\n warn!(\"Error reading entry in {}: {}\", dir_path_str, e);\n None\n }\n }\n}\n\npub async fn get_installed_packages(config: &Config) -> Result> {\n let mut installed = Vec::new();\n let keg_registry = KegRegistry::new(config.clone());\n\n match keg_registry.list_installed_kegs() {\n Ok(kegs) => {\n for keg in kegs {\n installed.push(InstalledPackageInfo {\n name: keg.name,\n version: keg.version_str, // Use keg.version_str\n pkg_type: PackageType::Formula,\n path: keg.path,\n });\n }\n }\n Err(e) => warn!(\"Failed to list installed formulae: {}\", e),\n }\n\n let caskroom_dir = config.cask_room_dir();\n if caskroom_dir.is_dir() {\n let caskroom_dir_str = caskroom_dir.to_str().unwrap_or(\"caskroom\").to_string();\n let cask_token_entries_iter =\n fs::read_dir(&caskroom_dir).map_err(|e| SpsError::Io(Arc::new(e)))?;\n\n for entry_res in cask_token_entries_iter {\n if let Some(entry) = handle_dir_entry(entry_res, &caskroom_dir_str) {\n let cask_token_path = entry.path();\n if !cask_token_path.is_dir() {\n continue;\n }\n let cask_token = entry.file_name().to_string_lossy().to_string();\n\n match fs::read_dir(&cask_token_path) {\n Ok(version_entries_iter) => {\n for version_entry_res in version_entries_iter {\n if let Some(version_entry) = handle_dir_entry(\n version_entry_res,\n cask_token_path.to_str().unwrap_or(\"token_path\"),\n ) {\n let version_path = version_entry.path();\n if version_path.is_dir()\n && version_path.join(\"CASK_INSTALL_MANIFEST.json\").is_file()\n {\n let version_str =\n version_entry.file_name().to_string_lossy().to_string();\n let manifest_path =\n version_path.join(\"CASK_INSTALL_MANIFEST.json\");\n let mut include = true;\n if manifest_path.is_file() {\n if let Ok(manifest_str) =\n std::fs::read_to_string(&manifest_path)\n {\n if let Ok(manifest_json) =\n serde_json::from_str::(\n &manifest_str,\n )\n {\n if let Some(is_installed) = manifest_json\n .get(\"is_installed\")\n .and_then(|v| v.as_bool())\n {\n include = is_installed;\n }\n }\n }\n }\n if include {\n installed.push(InstalledPackageInfo {\n name: cask_token.clone(),\n version: version_str,\n pkg_type: PackageType::Cask,\n path: version_path,\n });\n }\n // Assuming one actively installed version per cask token based\n // on manifest logic\n // If multiple version folders exist but only one manifest says\n // is_installed=true, this is fine.\n // If the intent is to list *all* version folders, the break\n // might be removed,\n // but then \"is_installed\" logic per version becomes more\n // important.\n // For now, finding the first \"active\" one is usually sufficient\n // for list/upgrade checks.\n }\n }\n }\n }\n Err(e) => warn!(\"Failed to read cask versions for {}: {}\", cask_token, e),\n }\n }\n }\n } else {\n debug!(\n \"Caskroom directory {} does not exist.\",\n caskroom_dir.display()\n );\n }\n Ok(installed)\n}\n\npub async fn get_installed_package(\n name: &str,\n config: &Config,\n) -> Result> {\n let keg_registry = KegRegistry::new(config.clone());\n if let Some(keg) = keg_registry.get_installed_keg(name)? {\n return Ok(Some(InstalledPackageInfo {\n name: keg.name,\n version: keg.version_str, // Use keg.version_str\n pkg_type: PackageType::Formula,\n path: keg.path,\n }));\n }\n\n let cask_token_path = config.cask_room_token_path(name);\n if cask_token_path.is_dir() {\n let version_entries_iter =\n fs::read_dir(&cask_token_path).map_err(|e| SpsError::Io(Arc::new(e)))?;\n for version_entry_res in version_entries_iter {\n if let Some(version_entry) = handle_dir_entry(\n version_entry_res,\n cask_token_path.to_str().unwrap_or(\"token_path\"),\n ) {\n let version_path = version_entry.path();\n if version_path.is_dir()\n && version_path.join(\"CASK_INSTALL_MANIFEST.json\").is_file()\n {\n let version_str = version_entry.file_name().to_string_lossy().to_string();\n let manifest_path = version_path.join(\"CASK_INSTALL_MANIFEST.json\");\n let mut include = true;\n if manifest_path.is_file() {\n if let Ok(manifest_str) = std::fs::read_to_string(&manifest_path) {\n if let Ok(manifest_json) =\n serde_json::from_str::(&manifest_str)\n {\n if let Some(is_installed) =\n manifest_json.get(\"is_installed\").and_then(|v| v.as_bool())\n {\n include = is_installed;\n }\n }\n }\n }\n if include {\n return Ok(Some(InstalledPackageInfo {\n name: name.to_string(),\n version: version_str,\n pkg_type: PackageType::Cask,\n path: version_path,\n }));\n }\n }\n }\n }\n }\n Ok(None)\n}\n"], ["/sps/sps-core/src/install/devtools.rs", "use std::env;\nuse std::path::PathBuf;\nuse std::process::{Command, Stdio};\n\nuse sps_common::error::{Result, SpsError};\nuse tracing::debug;\nuse which;\n\npub fn find_compiler(name: &str) -> Result {\n let env_var_name = match name {\n \"cc\" => \"CC\",\n \"c++\" | \"cxx\" => \"CXX\",\n _ => \"\",\n };\n if !env_var_name.is_empty() {\n if let Ok(compiler_path) = env::var(env_var_name) {\n let path = PathBuf::from(compiler_path);\n if path.is_file() {\n debug!(\n \"Using compiler from env var {}: {}\",\n env_var_name,\n path.display()\n );\n return Ok(path);\n } else {\n debug!(\n \"Env var {} points to non-existent file: {}\",\n env_var_name,\n path.display()\n );\n }\n }\n }\n\n if cfg!(target_os = \"macos\") {\n debug!(\"Attempting to find '{name}' using xcrun\");\n let output = Command::new(\"xcrun\")\n .arg(\"--find\")\n .arg(name)\n .stderr(Stdio::piped())\n .output();\n\n match output {\n Ok(out) if out.status.success() => {\n let path_str = String::from_utf8_lossy(&out.stdout).trim().to_string();\n if !path_str.is_empty() {\n let path = PathBuf::from(path_str);\n if path.is_file() {\n debug!(\"Found compiler via xcrun: {}\", path.display());\n return Ok(path);\n } else {\n debug!(\n \"xcrun found '{}' but path doesn't exist or isn't a file: {}\",\n name,\n path.display()\n );\n }\n } else {\n debug!(\"xcrun found '{name}' but returned empty path.\");\n }\n }\n Ok(out) => {\n let stderr = String::from_utf8_lossy(&out.stderr);\n debug!(\"xcrun failed to find '{}': {}\", name, stderr.trim());\n }\n Err(e) => {\n debug!(\"Failed to execute xcrun: {e}. Falling back to PATH search.\");\n }\n }\n }\n\n debug!(\"Falling back to searching PATH for '{name}'\");\n which::which(name).map_err(|e| {\n SpsError::BuildEnvError(format!(\"Failed to find compiler '{name}' on PATH: {e}\"))\n })\n}\n\npub fn find_sdk_path() -> Result {\n if cfg!(target_os = \"macos\") {\n debug!(\"Attempting to find macOS SDK path using xcrun\");\n let output = Command::new(\"xcrun\")\n .arg(\"--show-sdk-path\")\n .stderr(Stdio::piped())\n .output();\n\n match output {\n Ok(out) if out.status.success() => {\n let path_str = String::from_utf8_lossy(&out.stdout).trim().to_string();\n if path_str.is_empty() || path_str == \"/\" {\n return Err(SpsError::BuildEnvError(\n \"xcrun returned empty or invalid SDK path. Is Xcode or Command Line Tools installed correctly?\".to_string()\n ));\n }\n let sdk_path = PathBuf::from(path_str);\n if !sdk_path.exists() {\n return Err(SpsError::BuildEnvError(format!(\n \"SDK path reported by xcrun does not exist: {}\",\n sdk_path.display()\n )));\n }\n debug!(\"Found SDK path: {}\", sdk_path.display());\n Ok(sdk_path)\n }\n Ok(out) => {\n let stderr = String::from_utf8_lossy(&out.stderr);\n Err(SpsError::BuildEnvError(format!(\n \"xcrun failed to find SDK path: {}\",\n stderr.trim()\n )))\n }\n Err(e) => {\n Err(SpsError::BuildEnvError(format!(\n \"Failed to execute 'xcrun --show-sdk-path': {e}. Is Xcode or Command Line Tools installed?\"\n )))\n }\n }\n } else {\n debug!(\"Not on macOS, returning '/' as SDK path placeholder\");\n Ok(PathBuf::from(\"/\"))\n }\n}\n\npub fn get_macos_version() -> Result {\n if cfg!(target_os = \"macos\") {\n debug!(\"Attempting to get macOS version using sw_vers\");\n let output = Command::new(\"sw_vers\")\n .arg(\"-productVersion\")\n .stderr(Stdio::piped())\n .output();\n\n match output {\n Ok(out) if out.status.success() => {\n let version_full = String::from_utf8_lossy(&out.stdout).trim().to_string();\n let version_parts: Vec<&str> = version_full.split('.').collect();\n let version_short = if version_parts.len() >= 2 {\n format!(\"{}.{}\", version_parts[0], version_parts[1])\n } else {\n version_full.clone()\n };\n debug!(\"Found macOS version: {version_full} (short: {version_short})\");\n Ok(version_short)\n }\n Ok(out) => {\n let stderr = String::from_utf8_lossy(&out.stderr);\n Err(SpsError::BuildEnvError(format!(\n \"sw_vers failed to get product version: {}\",\n stderr.trim()\n )))\n }\n Err(e) => Err(SpsError::BuildEnvError(format!(\n \"Failed to execute 'sw_vers -productVersion': {e}\"\n ))),\n }\n } else {\n debug!(\"Not on macOS, returning '0.0' as version placeholder\");\n Ok(String::from(\"0.0\"))\n }\n}\n\npub fn get_arch_flag() -> String {\n if cfg!(target_os = \"macos\") {\n if cfg!(target_arch = \"x86_64\") {\n debug!(\"Detected target arch: x86_64\");\n \"-arch x86_64\".to_string()\n } else if cfg!(target_arch = \"aarch64\") {\n debug!(\"Detected target arch: aarch64 (arm64)\");\n \"-arch arm64\".to_string()\n } else {\n let arch = env::consts::ARCH;\n debug!(\n \"Unknown target architecture on macOS: {arch}, cannot determine -arch flag. Build might fail.\"\n );\n // Provide no flag in this unknown case? Or default to native?\n String::new()\n }\n } else {\n debug!(\"Not on macOS, returning empty arch flag.\");\n String::new()\n }\n}\n"], ["/sps/sps-core/src/uninstall/common.rs", "// sps-core/src/uninstall/common.rs\n\nuse std::path::{Component, Path, PathBuf};\nuse std::process::Command;\nuse std::{fs, io};\n\nuse sps_common::config::Config;\nuse tracing::{debug, error, warn};\n\n#[derive(Debug, Clone, Default)]\npub struct UninstallOptions {\n pub skip_zap: bool,\n}\n\n/// Removes a filesystem artifact (file or directory).\n///\n/// Attempts direct removal. If `use_sudo` is true and direct removal\n/// fails due to permission errors, it will attempt `sudo rm -rf`.\n///\n/// Returns `true` if the artifact is successfully removed or was already gone,\n/// `false` otherwise.\npub(crate) fn remove_filesystem_artifact(path: &Path, use_sudo: bool) -> bool {\n match path.symlink_metadata() {\n Ok(metadata) => {\n let file_type = metadata.file_type();\n // A directory is only a \"real\" directory if it's not a symlink.\n // Symlinks to directories should be removed with remove_file.\n let is_real_dir = file_type.is_dir();\n\n debug!(\n \"Removing filesystem artifact ({}) at: {}\",\n if is_real_dir {\n \"directory\"\n } else if file_type.is_symlink() {\n \"symlink\"\n } else {\n \"file\"\n },\n path.display()\n );\n\n let remove_op = || -> io::Result<()> {\n if is_real_dir {\n fs::remove_dir_all(path)\n } else {\n // This handles both files and symlinks\n fs::remove_file(path)\n }\n };\n\n if let Err(e) = remove_op() {\n if use_sudo && e.kind() == io::ErrorKind::PermissionDenied {\n warn!(\n \"Direct removal failed (Permission Denied). Trying with sudo rm -rf: {}\",\n path.display()\n );\n let output = Command::new(\"sudo\").arg(\"rm\").arg(\"-rf\").arg(path).output();\n match output {\n Ok(out) if out.status.success() => {\n debug!(\"Successfully removed {} with sudo.\", path.display());\n true\n }\n Ok(out) => {\n error!(\n \"Failed to remove {} with sudo: {}\",\n path.display(),\n String::from_utf8_lossy(&out.stderr).trim()\n );\n false\n }\n Err(sudo_err) => {\n error!(\n \"Error executing sudo rm for {}: {}\",\n path.display(),\n sudo_err\n );\n false\n }\n }\n } else if e.kind() != io::ErrorKind::NotFound {\n error!(\"Failed to remove artifact {}: {}\", path.display(), e);\n false\n } else {\n debug!(\"Artifact {} already removed.\", path.display());\n true\n }\n } else {\n debug!(\"Successfully removed artifact: {}\", path.display());\n true\n }\n }\n Err(e) if e.kind() == io::ErrorKind::NotFound => {\n debug!(\"Artifact not found (already removed?): {}\", path.display());\n true\n }\n Err(e) => {\n warn!(\n \"Failed to get metadata for artifact {}: {}\",\n path.display(),\n e\n );\n false\n }\n }\n}\n\n/// Expands a path string that may start with `~` to the user's home directory.\npub(crate) fn expand_tilde(path_str: &str, home: &Path) -> PathBuf {\n if let Some(stripped) = path_str.strip_prefix(\"~/\") {\n home.join(stripped)\n } else {\n PathBuf::from(path_str)\n }\n}\n\n/// Checks if a path is safe for zap operations.\n/// Safe paths are typically within user Library, .config, /Applications, /Library,\n/// or the sps cache directory. Root, home, /Applications, /Library themselves are not safe.\npub(crate) fn is_safe_path(path: &Path, home: &Path, config: &Config) -> bool {\n if path.components().any(|c| matches!(c, Component::ParentDir)) {\n warn!(\"Zap path rejected (contains '..'): {}\", path.display());\n return false;\n }\n let allowed_roots = [\n home.join(\"Library\"),\n home.join(\".config\"),\n PathBuf::from(\"/Applications\"),\n PathBuf::from(\"/Library\"),\n config.cache_dir().clone(),\n // Consider adding more specific allowed user dirs if necessary\n ];\n\n // Check if the path is exactly one of the top-level restricted paths\n if path == Path::new(\"/\")\n || path == home\n || path == Path::new(\"/Applications\")\n || path == Path::new(\"/Library\")\n {\n warn!(\"Zap path rejected (too broad): {}\", path.display());\n return false;\n }\n\n if allowed_roots.iter().any(|root| path.starts_with(root)) {\n return true;\n }\n\n warn!(\n \"Zap path rejected (outside allowed areas): {}\",\n path.display()\n );\n false\n}\n"], ["/sps/sps/src/cli/update.rs", "//! Contains the logic for the `update` command.\nuse std::fs;\nuse std::sync::Arc;\n\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_net::api;\n\n#[derive(clap::Args, Debug)]\npub struct Update;\n\nimpl Update {\n pub async fn run(&self, config: &Config, cache: Arc) -> Result<()> {\n tracing::debug!(\"Running manual update...\"); // Log clearly it's the manual one\n\n // Use the ui utility function to create the spinner\n println!(\"Updating package lists\"); // <-- CHANGED\n\n tracing::debug!(\"Using cache directory: {:?}\", config.cache_dir());\n\n // Fetch and store raw formula data\n match api::fetch_all_formulas().await {\n Ok(raw_data) => {\n cache.store_raw(\"formula.json\", &raw_data)?;\n tracing::debug!(\"✓ Successfully cached formulas data\");\n println!(\"Cached formulas data\");\n }\n Err(e) => {\n let err_msg = format!(\"Failed to fetch/store formulas from API: {e}\");\n tracing::error!(\"{}\", err_msg);\n println!(); // Clear spinner on error\n return Err(e);\n }\n }\n\n // Fetch and store raw cask data\n match api::fetch_all_casks().await {\n Ok(raw_data) => {\n cache.store_raw(\"cask.json\", &raw_data)?;\n tracing::debug!(\"✓ Successfully cached casks data\");\n println!(\"Cached casks data\");\n }\n Err(e) => {\n let err_msg = format!(\"Failed to fetch/store casks from API: {e}\");\n tracing::error!(\"{}\", err_msg);\n return Err(e);\n }\n }\n\n // Update timestamp file\n let timestamp_file = config.state_dir().join(\".sps_last_update_check\");\n tracing::debug!(\n \"Manual update successful. Updating timestamp file: {}\",\n timestamp_file.display()\n );\n match fs::File::create(×tamp_file) {\n Ok(_) => {\n tracing::debug!(\"Updated timestamp file successfully.\");\n }\n Err(e) => {\n tracing::warn!(\n \"Failed to create or update timestamp file '{}': {}\",\n timestamp_file.display(),\n e\n );\n }\n }\n\n println!(\"Update completed successfully!\");\n Ok(())\n }\n}\n"], ["/sps/sps-core/src/upgrade/bottle.rs", "// sps-core/src/upgrade/bottle.rs\n\nuse std::path::{Path, PathBuf};\nuse std::sync::Arc;\n\nuse sps_common::config::Config;\nuse sps_common::error::{Result as SpsResult, SpsError};\nuse sps_common::model::formula::Formula;\nuse tracing::{debug, error};\n\nuse crate::check::installed::InstalledPackageInfo;\nuse crate::{install, uninstall};\n\n/// Upgrades a formula that is installed from a bottle.\n///\n/// This involves:\n/// 1. Uninstalling the old version of the formula.\n/// 2. Installing the new bottle.\n/// 3. Linking the new version.\npub async fn upgrade_bottle_formula(\n formula: &Formula,\n new_bottle_download_path: &Path,\n old_install_info: &InstalledPackageInfo,\n config: &Config,\n http_client: Arc, /* Added for download_bottle if needed, though path is\n * pre-downloaded */\n) -> SpsResult {\n debug!(\n \"Upgrading bottle formula {} from {} to {}\",\n formula.name(),\n old_install_info.version,\n formula.version_str_full()\n );\n\n // 1. Uninstall the old version\n debug!(\n \"Uninstalling old bottle version: {} at {}\",\n old_install_info.version,\n old_install_info.path.display()\n );\n let uninstall_opts = uninstall::UninstallOptions { skip_zap: true }; // Zap is not relevant for formula upgrades\n uninstall::formula::uninstall_formula_artifacts(old_install_info, config, &uninstall_opts)\n .map_err(|e| {\n error!(\n \"Failed to uninstall old version {} of formula {}: {}\",\n old_install_info.version,\n formula.name(),\n e\n );\n SpsError::InstallError(format!(\n \"Failed to uninstall old version during upgrade of {}: {e}\",\n formula.name()\n ))\n })?;\n debug!(\"Successfully uninstalled old version of {}\", formula.name());\n\n // 2. Install the new bottle\n // The new_bottle_download_path is already provided, so we call install_bottle directly.\n // If download was part of this function, http_client would be used.\n let _ = http_client; // Mark as used if not directly needed by install_bottle\n\n debug!(\n \"Installing new bottle for {} from {}\",\n formula.name(),\n new_bottle_download_path.display()\n );\n let installed_keg_path =\n install::bottle::exec::install_bottle(new_bottle_download_path, formula, config).map_err(\n |e| {\n error!(\n \"Failed to install new bottle for formula {}: {}\",\n formula.name(),\n e\n );\n SpsError::InstallError(format!(\n \"Failed to install new bottle during upgrade of {}: {e}\",\n formula.name()\n ))\n },\n )?;\n debug!(\n \"Successfully installed new bottle for {} to {}\",\n formula.name(),\n installed_keg_path.display()\n );\n\n // 3. Link the new version (linking is handled by the worker after this function returns the\n // path)\n // The install::bottle::exec::install_bottle writes the receipt, but linking is separate.\n // The worker will call link_formula_artifacts after this.\n\n Ok(installed_keg_path)\n}\n"], ["/sps/sps-core/src/install/cask/dmg.rs", "// In sps-core/src/build/cask/dmg.rs\n\nuse std::fs;\nuse std::io::{BufRead, BufReader};\nuse std::path::{Path, PathBuf};\nuse std::process::Command;\n\nuse sps_common::error::{Result, SpsError};\nuse tracing::{debug, error}; // Added log imports\n\n// --- Keep Existing Helpers ---\npub fn mount_dmg(dmg_path: &Path) -> Result {\n debug!(\"Mounting DMG: {}\", dmg_path.display());\n let output = Command::new(\"hdiutil\")\n .arg(\"attach\")\n .arg(\"-plist\")\n .arg(\"-nobrowse\")\n .arg(\"-readonly\")\n .arg(\"-mountrandom\")\n .arg(\"/tmp\") // Consider making mount location configurable or more robust\n .arg(dmg_path)\n .output()?;\n\n if !output.status.success() {\n let stderr = String::from_utf8_lossy(&output.stderr);\n error!(\n \"hdiutil attach failed for {}: {}\",\n dmg_path.display(),\n stderr\n );\n return Err(SpsError::Generic(format!(\n \"Failed to mount DMG '{}': {}\",\n dmg_path.display(),\n stderr\n )));\n }\n\n let mount_point = parse_mount_point(&output.stdout)?;\n debug!(\"DMG mounted at: {}\", mount_point.display());\n Ok(mount_point)\n}\n\npub fn unmount_dmg(mount_point: &Path) -> Result<()> {\n debug!(\"Unmounting DMG from: {}\", mount_point.display());\n // Add logging for commands\n debug!(\"Executing: hdiutil detach -force {}\", mount_point.display());\n let output = Command::new(\"hdiutil\")\n .arg(\"detach\")\n .arg(\"-force\")\n .arg(mount_point)\n .output()?;\n\n if !output.status.success() {\n let stderr = String::from_utf8_lossy(&output.stderr);\n debug!(\n \"hdiutil detach failed ({}): {}. Trying diskutil\",\n output.status, stderr\n );\n // Add logging for fallback\n debug!(\n \"Executing: diskutil unmount force {}\",\n mount_point.display()\n );\n let diskutil_output = Command::new(\"diskutil\")\n .arg(\"unmount\")\n .arg(\"force\")\n .arg(mount_point)\n .output()?;\n\n if !diskutil_output.status.success() {\n let diskutil_stderr = String::from_utf8_lossy(&diskutil_output.stderr);\n error!(\n \"diskutil unmount force failed ({}): {}\",\n diskutil_output.status, diskutil_stderr\n );\n // Consider returning error only if both fail? Or always error on diskutil fail?\n return Err(SpsError::Generic(format!(\n \"Failed to unmount DMG '{}' using hdiutil and diskutil: {}\",\n mount_point.display(),\n diskutil_stderr\n )));\n }\n }\n debug!(\"DMG successfully unmounted\");\n Ok(())\n}\n\nfn parse_mount_point(output: &[u8]) -> Result {\n // ... (existing implementation) ...\n // Use plist crate for more robust parsing if possible in the future\n let cursor = std::io::Cursor::new(output);\n let reader = BufReader::new(cursor);\n let mut in_sys_entities = false;\n let mut in_mount_point = false;\n let mut mount_path_str: Option = None;\n\n for line_res in reader.lines() {\n let line = line_res?;\n let trimmed = line.trim();\n\n if trimmed == \"system-entities\" {\n in_sys_entities = true;\n continue;\n }\n if !in_sys_entities {\n continue;\n }\n\n if trimmed == \"mount-point\" {\n in_mount_point = true;\n continue;\n }\n\n if in_mount_point && trimmed.starts_with(\"\") && trimmed.ends_with(\"\") {\n mount_path_str = Some(\n trimmed\n .trim_start_matches(\"\")\n .trim_end_matches(\"\")\n .to_string(),\n );\n break; // Found the first mount point, assume it's the main one\n }\n\n // Reset flags if we encounter closing tags for structures containing mount-point\n if trimmed == \"\" {\n in_mount_point = false;\n }\n if trimmed == \"\" && in_sys_entities {\n // End of system-entities\n // break; // Stop searching if we leave the system-entities array\n in_sys_entities = false; // Reset this flag too\n }\n }\n\n match mount_path_str {\n Some(path_str) if !path_str.is_empty() => {\n debug!(\"Parsed mount point from plist: {}\", path_str);\n Ok(PathBuf::from(path_str))\n }\n _ => {\n error!(\"Failed to parse mount point from hdiutil plist output.\");\n // Optionally log the raw output for debugging\n // error!(\"Raw hdiutil output:\\n{}\", String::from_utf8_lossy(output));\n Err(SpsError::Generic(\n \"Failed to determine mount point from hdiutil output\".to_string(),\n ))\n }\n }\n}\n\n// --- NEW Function ---\n/// Extracts the contents of a mounted DMG to a staging directory using `ditto`.\npub fn extract_dmg_to_stage(dmg_path: &Path, stage_dir: &Path) -> Result<()> {\n let mount_point = mount_dmg(dmg_path)?;\n\n // Ensure the stage directory exists (though TempDir should handle it)\n if !stage_dir.exists() {\n fs::create_dir_all(stage_dir).map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n }\n\n debug!(\n \"Copying contents from DMG mount {} to stage {} using ditto\",\n mount_point.display(),\n stage_dir.display()\n );\n // Use ditto for robust copying, preserving metadata\n // ditto \n debug!(\n \"Executing: ditto {} {}\",\n mount_point.display(),\n stage_dir.display()\n );\n let ditto_output = Command::new(\"ditto\")\n .arg(&mount_point) // Source first\n .arg(stage_dir) // Then destination\n .output()?;\n\n let unmount_result = unmount_dmg(&mount_point); // Unmount regardless of ditto success\n\n if !ditto_output.status.success() {\n let stderr = String::from_utf8_lossy(&ditto_output.stderr);\n error!(\"ditto command failed ({}): {}\", ditto_output.status, stderr);\n // Also log stdout which might contain info on specific file errors\n let stdout = String::from_utf8_lossy(&ditto_output.stdout);\n if !stdout.trim().is_empty() {\n error!(\"ditto stdout: {}\", stdout);\n }\n unmount_result?; // Ensure we still return unmount error if it happened\n return Err(SpsError::Generic(format!(\n \"Failed to copy DMG contents using ditto: {stderr}\"\n )));\n }\n\n // After ditto, quarantine any .app bundles in the stage (macOS only)\n #[cfg(target_os = \"macos\")]\n {\n if let Err(e) = crate::install::extract::quarantine_extracted_apps_in_stage(\n stage_dir,\n \"sps-dmg-extractor\",\n ) {\n tracing::warn!(\n \"Error during post-DMG extraction quarantine scan for {}: {}\",\n dmg_path.display(),\n e\n );\n }\n }\n\n unmount_result // Return the result of unmounting\n}\n"], ["/sps/sps-core/src/install/cask/helpers.rs", "use std::fs;\nuse std::path::Path;\n\nuse sps_common::config::Config;\nuse tracing::debug;\n\n/// Robustly removes a file or directory, handling symlinks and permissions.\n/// If `use_sudo_if_needed` is true, will attempt `sudo rm -rf` on permission errors.\npub fn remove_path_robustly(path: &Path, _config: &Config, use_sudo_if_needed: bool) -> bool {\n if !path.exists() && path.symlink_metadata().is_err() {\n debug!(\"Path {} not found for removal.\", path.display());\n return true;\n }\n let is_dir = path.is_dir()\n && !path\n .symlink_metadata()\n .is_ok_and(|m| m.file_type().is_symlink());\n let removal_op = || -> std::io::Result<()> {\n if is_dir {\n fs::remove_dir_all(path)\n } else {\n fs::remove_file(path)\n }\n };\n\n if let Err(e) = removal_op() {\n if e.kind() == std::io::ErrorKind::NotFound {\n return true;\n }\n if use_sudo_if_needed && e.kind() == std::io::ErrorKind::PermissionDenied {\n debug!(\n \"Direct removal of {} failed (Permission Denied). Trying with sudo rm -rf.\",\n path.display()\n );\n let output = std::process::Command::new(\"sudo\")\n .arg(\"rm\")\n .arg(\"-rf\")\n .arg(path)\n .output();\n match output {\n Ok(out) if out.status.success() => {\n debug!(\"Successfully removed {} with sudo.\", path.display());\n return true;\n }\n Ok(out) => {\n debug!(\n \"`sudo rm -rf {}` failed ({}): {}\",\n path.display(),\n out.status,\n String::from_utf8_lossy(&out.stderr).trim()\n );\n return false;\n }\n Err(sudo_e) => {\n debug!(\n \"Error executing `sudo rm -rf` for {}: {}\",\n path.display(),\n sudo_e\n );\n return false;\n }\n }\n } else {\n debug!(\"Failed to remove {}: {}\", path.display(), e);\n return false;\n }\n }\n debug!(\"Successfully removed {}.\", path.display());\n true\n}\n\n/// Recursively cleans up empty parent directories in the private cask store.\n/// Starts from the given path and walks up, removing empty directories until a non-empty or root is\n/// found.\npub fn cleanup_empty_parent_dirs_in_private_store(start_path: &Path, stop_at: &Path) {\n let mut current = start_path.to_path_buf();\n while current != *stop_at {\n if let Ok(read_dir) = fs::read_dir(¤t) {\n if read_dir.count() == 0 {\n match fs::remove_dir(¤t) {\n Ok(_) => {\n debug!(\"Removed empty directory: {}\", current.display());\n }\n Err(e) => {\n debug!(\"Failed to remove directory {}: {}\", current.display(), e);\n break;\n }\n }\n } else {\n break;\n }\n } else {\n break;\n }\n if let Some(parent) = current.parent() {\n current = parent.to_path_buf();\n } else {\n break;\n }\n }\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/binary.rs", "// ===== sps-core/src/build/cask/artifacts/binary.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Installs `binary` artifacts, which can be declared as:\n/// - a simple string: `\"foo\"` (source and target both `\"foo\"`)\n/// - a map: `{ \"source\": \"path/in/stage\", \"target\": \"name\", \"chmod\": \"0755\" }`\n/// - a map with just `\"target\"`: automatically generate a wrapper script\n///\n/// Copies or symlinks executables into the prefix bin directory,\n/// and records both the link and caskroom reference.\npub fn install_binary(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"binary\") {\n // Normalize into an array\n let arr = if let Some(arr) = entries.as_array() {\n arr.clone()\n } else {\n vec![entries.clone()]\n };\n\n let bin_dir = config.bin_dir();\n fs::create_dir_all(&bin_dir)?;\n\n for entry in arr {\n // Determine source, target, and optional chmod\n let (source_rel, target_name, chmod) = if let Some(tgt) = entry.as_str() {\n // simple form: \"foo\"\n (tgt.to_string(), tgt.to_string(), None)\n } else if let Some(m) = entry.as_object() {\n let target = m\n .get(\"target\")\n .and_then(|v| v.as_str())\n .map(String::from)\n .ok_or_else(|| {\n SpsError::InstallError(format!(\n \"Binary artifact missing 'target': {m:?}\"\n ))\n })?;\n\n let chmod = m.get(\"chmod\").and_then(|v| v.as_str()).map(String::from);\n\n // If `source` is provided, use it; otherwise generate wrapper\n let source = if let Some(src) = m.get(\"source\").and_then(|v| v.as_str())\n {\n src.to_string()\n } else {\n // generate wrapper script in caskroom\n let wrapper_name = format!(\"{target}.wrapper.sh\");\n let wrapper_path = cask_version_install_path.join(&wrapper_name);\n\n // assume the real executable lives inside the .app bundle\n let app_name = format!(\"{}.app\", cask.display_name());\n let exe_path =\n format!(\"/Applications/{app_name}/Contents/MacOS/{target}\");\n\n let script =\n format!(\"#!/usr/bin/env bash\\nexec \\\"{exe_path}\\\" \\\"$@\\\"\\n\");\n fs::write(&wrapper_path, script)?;\n Command::new(\"chmod\")\n .arg(\"+x\")\n .arg(&wrapper_path)\n .status()?;\n\n wrapper_name\n };\n\n (source, target, chmod)\n } else {\n debug!(\"Invalid binary artifact entry: {:?}\", entry);\n continue;\n };\n\n let src_path = stage_path.join(&source_rel);\n if !src_path.exists() {\n debug!(\"Binary source '{}' not found, skipping\", src_path.display());\n continue;\n }\n\n // Link into bin_dir\n let link_path = bin_dir.join(&target_name);\n let _ = fs::remove_file(&link_path);\n debug!(\n \"Linking binary '{}' → '{}'\",\n src_path.display(),\n link_path.display()\n );\n symlink(&src_path, &link_path)?;\n\n // Apply chmod if specified\n if let Some(mode) = chmod.as_deref() {\n let _ = Command::new(\"chmod\").arg(mode).arg(&link_path).status();\n }\n\n installed.push(InstalledArtifact::BinaryLink {\n link_path: link_path.clone(),\n target_path: src_path.clone(),\n });\n\n // Also create a Caskroom symlink for reference\n let caskroom_link = cask_version_install_path.join(&target_name);\n let _ = remove_path_robustly(&caskroom_link, config, true);\n symlink(&link_path, &caskroom_link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: caskroom_link,\n target_path: link_path.clone(),\n });\n }\n\n // Only one binary stanza per cask\n break;\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/zap.rs", "// ===== sps-core/src/build/cask/artifacts/zap.rs =====\n\nuse std::fs;\nuse std::path::{Path, PathBuf}; // Import Path\nuse std::process::{Command, Stdio};\n\nuse regex::Regex;\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::InstalledArtifact;\n\n/// Implements the `zap` stanza by performing deep-clean actions\n/// such as trash, delete, rmdir, pkgutil forget, launchctl unload,\n/// and arbitrary scripts, matching Homebrew's Cask behavior.\npub fn install_zap(cask: &Cask, config: &Config) -> Result> {\n let mut artifacts: Vec = Vec::new();\n let home = config.home_dir();\n\n if let Some(entries) = &cask.artifacts {\n for entry in entries {\n if let Some(obj) = entry.as_object() {\n if let Some(zaps) = obj.get(\"zap\").and_then(|v| v.as_array()) {\n for zap_map in zaps {\n if let Some(zap_obj) = zap_map.as_object() {\n for (key, val) in zap_obj {\n match key.as_str() {\n \"trash\" => {\n if let Some(arr) = val.as_array() {\n for item in arr.iter().filter_map(|v| v.as_str()) {\n let target = expand_tilde(item, &home); // Pass &Path\n if !is_safe_path(&target, &home) {\n debug!(\n \"Unsafe trash path {}, skipping\",\n target.display()\n );\n continue;\n }\n debug!(\"Trashing {}...\", target.display());\n let _ = Command::new(\"trash\")\n .arg(&target)\n .stdout(Stdio::null())\n .stderr(Stdio::null())\n .status();\n }\n }\n }\n \"delete\" => {\n if let Some(arr) = val.as_array() {\n for item in arr.iter().filter_map(|v| v.as_str()) {\n let target = expand_tilde(item, &home); // Pass &Path\n if !is_safe_path(&target, &home) {\n debug!(\n \"Unsafe delete path {}, skipping\",\n target.display()\n );\n continue;\n }\n debug!(\"Deleting file {}...\", target.display());\n if let Err(e) = fs::remove_file(&target) {\n if e.kind() != std::io::ErrorKind::NotFound {\n debug!(\n \"Failed to delete {}: {}\",\n target.display(),\n e\n );\n }\n }\n }\n }\n }\n \"rmdir\" => {\n if let Some(arr) = val.as_array() {\n for item in arr.iter().filter_map(|v| v.as_str()) {\n let target = expand_tilde(item, &home); // Pass &Path\n if !is_safe_path(&target, &home) {\n debug!(\n \"Unsafe rmdir path {}, skipping\",\n target.display()\n );\n continue;\n }\n debug!(\n \"Removing directory {}...\",\n target.display()\n );\n if let Err(e) = fs::remove_dir_all(&target) {\n if e.kind() != std::io::ErrorKind::NotFound {\n debug!(\n \"Failed to rmdir {}: {}\",\n target.display(),\n e\n );\n }\n }\n }\n }\n }\n \"pkgutil\" => {\n if let Some(arr) = val.as_array() {\n for item in arr.iter().filter_map(|v| v.as_str()) {\n if !is_valid_pkgid(item) {\n debug!(\n \"Invalid pkgutil id '{}', skipping\",\n item\n );\n continue;\n }\n debug!(\"Forgetting pkgutil receipt {}...\", item);\n let _ = Command::new(\"pkgutil\")\n .arg(\"--forget\")\n .arg(item)\n .stdout(Stdio::null())\n .stderr(Stdio::null())\n .status();\n artifacts.push(InstalledArtifact::PkgUtilReceipt {\n id: item.to_string(),\n });\n }\n }\n }\n \"launchctl\" => {\n if let Some(arr) = val.as_array() {\n for label in arr.iter().filter_map(|v| v.as_str()) {\n if !is_valid_label(label) {\n debug!(\n \"Invalid launchctl label '{}', skipping\",\n label\n );\n continue;\n }\n let plist = home // Use expanded home\n .join(\"Library/LaunchAgents\")\n .join(format!(\"{label}.plist\"));\n if !is_safe_path(&plist, &home) {\n debug!(\n \"Unsafe plist path {} for label {}, skipping\",\n plist.display(),\n label\n );\n continue;\n }\n debug!(\n \"Unloading launchctl {}...\",\n plist.display()\n );\n let _ = Command::new(\"launchctl\")\n .arg(\"unload\")\n .arg(&plist)\n .stdout(Stdio::null())\n .stderr(Stdio::null())\n .status();\n artifacts.push(InstalledArtifact::Launchd {\n label: label.to_string(),\n path: Some(plist),\n });\n }\n }\n }\n \"script\" => {\n if let Some(cmd) = val.as_str() {\n if !is_valid_command(cmd) {\n debug!(\n \"Invalid zap script command '{}', skipping\",\n cmd\n );\n continue;\n }\n debug!(\"Running zap script: {}...\", cmd);\n let _ = Command::new(\"sh\")\n .arg(\"-c\")\n .arg(cmd)\n .stdout(Stdio::null())\n .stderr(Stdio::null())\n .status();\n }\n }\n \"signal\" => {\n if let Some(arr) = val.as_array() {\n for cmd in arr.iter().filter_map(|v| v.as_str()) {\n if !is_valid_command(cmd) {\n debug!(\n \"Invalid signal command '{}', skipping\",\n cmd\n );\n continue;\n }\n debug!(\"Running signal command: {}...\", cmd);\n let _ = Command::new(\"sh\")\n .arg(\"-c\")\n .arg(cmd)\n .stdout(Stdio::null())\n .stderr(Stdio::null())\n .status();\n }\n }\n }\n _ => debug!(\"Unsupported zap key '{}', skipping\", key),\n }\n }\n }\n }\n // Only process the first \"zap\" stanza found\n break;\n }\n }\n }\n }\n\n Ok(artifacts)\n}\n\n// New helper functions to validate paths and strings.\nfn is_safe_path(path: &Path, home: &Path) -> bool {\n if path\n .components()\n .any(|c| matches!(c, std::path::Component::ParentDir))\n {\n return false;\n }\n let path_str = path.to_string_lossy();\n if path.is_absolute()\n && (path_str.starts_with(\"/Applications\") || path_str.starts_with(\"/Library\"))\n {\n return true;\n }\n if path.starts_with(home) {\n return true;\n }\n if path_str.contains(\"Caskroom/Cellar\") {\n return true;\n }\n false\n}\n\nfn is_valid_pkgid(pkgid: &str) -> bool {\n let re = Regex::new(r\"^[a-zA-Z0-9.-]+$\").unwrap();\n re.is_match(pkgid)\n}\n\nfn is_valid_label(label: &str) -> bool {\n let re = Regex::new(r\"^[a-zA-Z0-9.-]+$\").unwrap();\n re.is_match(label)\n}\n\nfn is_valid_command(cmd: &str) -> bool {\n let re = Regex::new(r\"^[a-zA-Z0-9\\s\\-_./]+$\").unwrap();\n re.is_match(cmd)\n}\n\n/// Expand a path that may start with '~' to the user's home directory\nfn expand_tilde(path: &str, home: &Path) -> PathBuf {\n if let Some(stripped) = path.strip_prefix(\"~/\") {\n home.join(stripped)\n } else {\n PathBuf::from(path)\n }\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/installer.rs", "// ===== sps-core/src/build/cask/artifacts/installer.rs =====\n\nuse std::path::Path;\nuse std::process::{Command, Stdio};\n\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::InstalledArtifact;\n\n// Helper to validate that the executable is a filename (relative, no '/' or \"..\")\nfn validate_filename_or_relative_path(file: &str) -> Result {\n if file.starts_with(\"/\") || file.contains(\"..\") || file.contains(\"/\") {\n return Err(SpsError::Generic(format!(\n \"Invalid executable filename: {file}\"\n )));\n }\n Ok(file.to_string())\n}\n\n// Helper to validate a command argument based on allowed characters or allowed option form\nfn validate_argument(arg: &str) -> Result {\n if arg.starts_with(\"-\") {\n return Ok(arg.to_string());\n }\n if arg.starts_with(\"/\") || arg.contains(\"..\") || arg.contains(\"/\") {\n return Err(SpsError::Generic(format!(\"Invalid argument: {arg}\")));\n }\n if !arg\n .chars()\n .all(|c| c.is_alphanumeric() || c == '-' || c == '_' || c == '.')\n {\n return Err(SpsError::Generic(format!(\n \"Invalid characters in argument: {arg}\"\n )));\n }\n Ok(arg.to_string())\n}\n\n/// Implements the `installer` stanza:\n/// - `manual`: prints instructions to open the staged path.\n/// - `script`: runs the given executable with args, under sudo if requested.\n///\n/// Mirrors Homebrew’s `Cask::Artifact::Installer` behavior :contentReference[oaicite:1]{index=1}.\npub fn run_installer(\n cask: &Cask,\n stage_path: &Path,\n _cask_version_install_path: &Path,\n _config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n // Find the `installer` definitions in the raw JSON artifacts\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(insts) = obj.get(\"installer\").and_then(|v| v.as_array()) {\n for inst in insts {\n if let Some(inst_obj) = inst.as_object() {\n if let Some(man) = inst_obj.get(\"manual\").and_then(|v| v.as_str()) {\n debug!(\n \"Cask {} requires manual install. To finish:\\n open {}\",\n cask.token,\n stage_path.join(man).display()\n );\n continue;\n }\n let exe_key = if inst_obj.contains_key(\"script\") {\n \"script\"\n } else {\n \"executable\"\n };\n let executable = inst_obj\n .get(exe_key)\n .and_then(|v| v.as_str())\n .ok_or_else(|| {\n SpsError::Generic(format!(\n \"installer stanza missing '{exe_key}' field\"\n ))\n })?;\n let args: Vec = inst_obj\n .get(\"args\")\n .and_then(|v| v.as_array())\n .map(|arr| {\n arr.iter()\n .filter_map(|a| a.as_str().map(String::from))\n .collect()\n })\n .unwrap_or_default();\n let use_sudo = inst_obj\n .get(\"sudo\")\n .and_then(|v| v.as_bool())\n .unwrap_or(false);\n\n let validated_executable =\n validate_filename_or_relative_path(executable)?;\n let mut validated_args = Vec::new();\n for arg in &args {\n validated_args.push(validate_argument(arg)?);\n }\n\n let script_path = stage_path.join(&validated_executable);\n if !script_path.exists() {\n return Err(SpsError::NotFound(format!(\n \"Installer script not found: {}\",\n script_path.display()\n )));\n }\n\n debug!(\n \"Running installer script '{}' for cask {}\",\n script_path.display(),\n cask.token\n );\n let mut cmd = if use_sudo {\n let mut c = Command::new(\"sudo\");\n c.arg(script_path.clone());\n c\n } else {\n Command::new(script_path.clone())\n };\n cmd.args(&validated_args);\n cmd.stdin(Stdio::null())\n .stdout(Stdio::inherit())\n .stderr(Stdio::inherit());\n\n let status = cmd.status().map_err(|e| {\n SpsError::Generic(format!(\"Failed to spawn installer script: {e}\"))\n })?;\n if !status.success() {\n return Err(SpsError::InstallError(format!(\n \"Installer script exited with {status}\"\n )));\n }\n\n installed\n .push(InstalledArtifact::CaskroomReference { path: script_path });\n }\n }\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-common/src/model/cask.rs", "// ===== sps-common/src/model/cask.rs ===== // Corrected path\nuse std::collections::HashMap;\nuse std::fs;\n\nuse serde::{Deserialize, Serialize};\n\nuse crate::config::Config;\n\npub type Artifact = serde_json::Value;\n\n/// Represents the `url` field, which can be a simple string or a map with specs\n#[derive(Debug, Clone, Serialize, Deserialize)]\n#[serde(untagged)]\npub enum UrlField {\n Simple(String),\n WithSpec {\n url: String,\n #[serde(default)]\n verified: Option,\n #[serde(flatten)]\n other: HashMap,\n },\n}\n\n/// Represents the `sha256` field: hex, no_check, or per-architecture\n#[derive(Debug, Clone, Serialize, Deserialize)]\n#[serde(untagged)]\npub enum Sha256Field {\n Hex(String),\n #[serde(rename_all = \"snake_case\")]\n NoCheck {\n no_check: bool,\n },\n PerArch(HashMap),\n}\n\n/// Appcast metadata\n#[derive(Debug, Clone, Serialize, Deserialize)] // Ensure Serialize/Deserialize are here\npub struct Appcast {\n pub url: String,\n pub checkpoint: Option,\n}\n\n/// Represents conflicts with other casks or formulae\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub struct ConflictsWith {\n #[serde(default)]\n pub cask: Vec,\n #[serde(default)]\n pub formula: Vec,\n #[serde(flatten)]\n pub extra: HashMap,\n}\n\n/// Represents the specific architecture details found in some cask definitions\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub struct ArchSpec {\n #[serde(rename = \"type\")] // Map the JSON \"type\" field\n pub type_name: String, // e.g., \"arm\"\n pub bits: u32, // e.g., 64\n}\n\n/// Helper for architecture requirements: single string, list of strings, or list of spec objects\n#[derive(Debug, Clone, Serialize, Deserialize)]\n#[serde(untagged)]\npub enum ArchReq {\n One(String), // e.g., \"arm64\"\n Many(Vec), // e.g., [\"arm64\", \"x86_64\"]\n Specs(Vec),\n}\n\n/// Helper for macOS requirements: symbol, list, comparison, or map\n#[derive(Debug, Clone, Serialize, Deserialize)]\n#[serde(untagged)]\npub enum MacOSReq {\n Symbol(String), // \":big_sur\"\n Symbols(Vec), // [\":catalina\", \":big_sur\"]\n Comparison(String), // \">= :big_sur\"\n Map(HashMap>),\n}\n\n/// Helper to coerce string-or-list into Vec\n#[derive(Debug, Clone, Serialize, Deserialize)]\n#[serde(untagged)]\npub enum StringList {\n One(String),\n Many(Vec),\n}\n\nimpl From for Vec {\n fn from(item: StringList) -> Self {\n match item {\n StringList::One(s) => vec![s],\n StringList::Many(v) => v,\n }\n }\n}\n\n/// Represents `depends_on` block with multiple possible keys\n#[derive(Debug, Clone, Serialize, Deserialize, Default)]\npub struct DependsOn {\n #[serde(default)]\n pub cask: Vec,\n #[serde(default)]\n pub formula: Vec,\n #[serde(default)]\n pub arch: Option,\n #[serde(default)]\n pub macos: Option,\n #[serde(flatten)]\n pub extra: HashMap,\n}\n\n/// The main Cask model matching Homebrew JSON v2\n#[derive(Debug, Clone, Serialize, Deserialize, Default)]\npub struct Cask {\n pub token: String,\n\n #[serde(default)]\n pub name: Option>,\n pub version: Option,\n pub desc: Option,\n pub homepage: Option,\n\n #[serde(default)]\n pub artifacts: Option>,\n\n #[serde(default)]\n pub url: Option,\n #[serde(default)]\n pub url_specs: Option>,\n\n #[serde(default)]\n pub sha256: Option,\n\n pub appcast: Option,\n pub auto_updates: Option,\n\n #[serde(default)]\n pub depends_on: Option,\n\n #[serde(default)]\n pub conflicts_with: Option,\n\n pub caveats: Option,\n pub stage_only: Option,\n\n #[serde(default)]\n pub uninstall: Option>,\n\n #[serde(default)] // Only one default here\n pub zap: Option>,\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub struct CaskList {\n pub casks: Vec,\n}\n\n// --- ZAP STANZA SUPPORT ---\n\n/// Helper for zap: string or array of strings\n#[derive(Debug, Clone, Serialize, Deserialize)]\n#[serde(untagged)]\npub enum StringOrVec {\n String(String),\n Vec(Vec),\n}\nimpl StringOrVec {\n pub fn into_vec(self) -> Vec {\n match self {\n StringOrVec::String(s) => vec![s],\n StringOrVec::Vec(v) => v,\n }\n }\n}\n\n/// Zap action details (trash, delete, rmdir, pkgutil, launchctl, script, signal, etc)\n#[derive(Debug, Clone, Serialize, Deserialize)]\n#[serde(tag = \"action\", rename_all = \"snake_case\")]\npub enum ZapActionDetail {\n Trash(Vec),\n Delete(Vec),\n Rmdir(Vec),\n Pkgutil(StringOrVec),\n Launchctl(StringOrVec),\n Script {\n executable: String,\n args: Option>,\n },\n Signal(Vec),\n // Add more as needed\n}\n\n/// A zap stanza is a map of action -> detail\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub struct ZapStanza(pub std::collections::HashMap);\n\n// --- Cask Impl ---\n\nimpl Cask {\n /// Check if this cask is installed by looking for a manifest file\n /// in any versioned directory within the Caskroom.\n pub fn is_installed(&self, config: &Config) -> bool {\n let cask_dir = config.cask_room_token_path(&self.token); // e.g., /opt/sps/cask_room/firefox\n if !cask_dir.exists() || !cask_dir.is_dir() {\n return false;\n }\n\n // Iterate through entries (version dirs) inside the cask_dir\n match fs::read_dir(&cask_dir) {\n Ok(entries) => {\n // Clippy fix: Use flatten() to handle Result entries directly\n for entry in entries.flatten() {\n // <-- Use flatten() here\n let version_path = entry.path();\n // Check if it's a directory (representing a version)\n if version_path.is_dir() {\n // Check for the existence of the manifest file\n let manifest_path = version_path.join(\"CASK_INSTALL_MANIFEST.json\"); // <-- Correct filename\n if manifest_path.is_file() {\n // Check is_installed flag in manifest\n let mut include = true;\n if let Ok(manifest_str) = std::fs::read_to_string(&manifest_path) {\n if let Ok(manifest_json) =\n serde_json::from_str::(&manifest_str)\n {\n if let Some(is_installed) =\n manifest_json.get(\"is_installed\").and_then(|v| v.as_bool())\n {\n include = is_installed;\n }\n }\n }\n if include {\n // Found a manifest in at least one version directory, consider it\n // installed\n return true;\n }\n }\n }\n }\n // If loop completes without finding a manifest in any version dir\n false\n }\n Err(e) => {\n // Log error if reading the directory fails, but assume not installed\n tracing::warn!(\n \"Failed to read cask directory {} to check for installed versions: {}\",\n cask_dir.display(),\n e\n );\n false\n }\n }\n }\n\n /// Get the installed version of this cask by reading the directory names\n /// in the Caskroom. Returns the first version found (use cautiously if multiple\n /// versions could exist, though current install logic prevents this).\n pub fn installed_version(&self, config: &Config) -> Option {\n let cask_dir = config.cask_room_token_path(&self.token); //\n if !cask_dir.exists() {\n return None;\n }\n // Iterate through entries and return the first directory name found\n match fs::read_dir(&cask_dir) {\n Ok(entries) => {\n // Clippy fix: Use flatten()\n for entry in entries.flatten() {\n // <-- Use flatten() here\n let path = entry.path();\n // Check if it's a directory (representing a version)\n if path.is_dir() {\n if let Some(version_str) = path.file_name().and_then(|name| name.to_str()) {\n // Return the first version directory name found\n return Some(version_str.to_string());\n }\n }\n }\n // No version directories found\n None\n }\n Err(_) => None, // Error reading directory\n }\n }\n\n /// Get a friendly name for display purposes\n pub fn display_name(&self) -> String {\n self.name\n .as_ref()\n .and_then(|names| names.first().cloned())\n .unwrap_or_else(|| self.token.clone())\n }\n}\n"], ["/sps/sps-core/src/utils/xattr.rs", "use std::path::Path;\nuse std::process::Command;\n\nuse anyhow::Context;\nuse sps_common::error::{Result, SpsError};\nuse tracing::{debug, error};\nuse uuid::Uuid;\nuse xattr;\n\n// Helper to get current timestamp as hex\nfn get_timestamp_hex() -> String {\n let secs = std::time::SystemTime::now()\n .duration_since(std::time::UNIX_EPOCH)\n .unwrap_or_default() // Defaults to 0 if time is before UNIX_EPOCH\n .as_secs();\n format!(\"{secs:x}\")\n}\n\n// Helper to generate a UUID as hex string\nfn get_uuid_hex() -> String {\n Uuid::new_v4().as_hyphenated().to_string().to_uppercase()\n}\n\n/// true → file **has** a com.apple.quarantine attribute \n/// false → attribute missing\npub fn has_quarantine_attribute(path: &Path) -> anyhow::Result {\n // The `xattr` crate has both path-level and FileExt APIs.\n // Path-level is simpler here.\n match xattr::get(path, \"com.apple.quarantine\") {\n Ok(Some(_)) => Ok(true),\n Ok(None) => Ok(false),\n Err(e) => Err(anyhow::Error::new(e))\n .with_context(|| format!(\"checking xattr on {}\", path.display())),\n }\n}\n\n/// Apply our standard quarantine only *if* none exists already.\n///\n/// `agent` should be the same string you currently pass to\n/// `set_quarantine_attribute()` – usually the cask token.\npub fn ensure_quarantine_attribute(path: &Path, agent: &str) -> anyhow::Result<()> {\n if has_quarantine_attribute(path)? {\n // Already quarantined (or the user cleared it and we respect that) → done\n return Ok(());\n }\n set_quarantine_attribute(path, agent)\n .with_context(|| format!(\"adding quarantine to {}\", path.display()))\n}\n\n/// Sets the 'com.apple.quarantine' extended attribute on a file or directory.\n/// Uses flags commonly seen for user-initiated downloads (0081).\n/// Logs errors assertively, as failure is critical for correct behavior.\npub fn set_quarantine_attribute(path: &Path, agent_name: &str) -> Result<()> {\n if !cfg!(target_os = \"macos\") {\n debug!(\n \"Not on macOS, skipping quarantine attribute for {}\",\n path.display()\n );\n return Ok(());\n }\n\n if !path.exists() {\n error!(\n \"Cannot set quarantine attribute, path does not exist: {}\",\n path.display()\n );\n return Err(SpsError::NotFound(format!(\n \"Path not found for setting quarantine attribute: {}\",\n path.display()\n )));\n }\n\n let timestamp_hex = get_timestamp_hex();\n let uuid_hex = get_uuid_hex();\n // Use \"0181\" to disable translocation and quarantine mirroring (Homebrew-style).\n // Format: \"flags;timestamp_hex;agent_name;uuid_hex\"\n let quarantine_value = format!(\"0181;{timestamp_hex};{agent_name};{uuid_hex}\");\n\n debug!(\n \"Setting quarantine attribute on {}: value='{}'\",\n path.display(),\n quarantine_value\n );\n\n let output = Command::new(\"xattr\")\n .arg(\"-w\")\n .arg(\"com.apple.quarantine\")\n .arg(&quarantine_value)\n .arg(path.as_os_str())\n .output();\n\n match output {\n Ok(out) => {\n if out.status.success() {\n debug!(\n \"Successfully set quarantine attribute for {}\",\n path.display()\n );\n Ok(())\n } else {\n let stderr = String::from_utf8_lossy(&out.stderr);\n error!( // Changed from warn to error as this is critical for the bug\n \"Failed to set quarantine attribute for {} (status: {}): {}. This may lead to data loss on reinstall or Gatekeeper issues.\",\n path.display(),\n out.status,\n stderr.trim()\n );\n // Return an error because failure to set this is likely to cause the reported bug\n Err(SpsError::Generic(format!(\n \"Failed to set com.apple.quarantine on {}: {}\",\n path.display(),\n stderr.trim()\n )))\n }\n }\n Err(e) => {\n error!(\n \"Failed to execute xattr command for {}: {}. Quarantine attribute not set.\",\n path.display(),\n e\n );\n Err(SpsError::Io(std::sync::Arc::new(e)))\n }\n }\n}\n"], ["/sps/sps-net/src/validation.rs", "// sps-io/src/checksum.rs\n//use std::sync::Arc;\nuse std::fs::File;\nuse std::io;\nuse std::path::Path;\n\nuse infer;\nuse sha2::{Digest, Sha256};\nuse sps_common::error::{Result, SpsError};\nuse url::Url;\n//use tokio::fs::File;\n//use tokio::io::AsyncReadExt;\n//use tracing::debug; // Use tracing\n\n///// Asynchronously verifies the SHA256 checksum of a file.\n///// Reads the file asynchronously but performs hashing synchronously.\n//pub async fn verify_checksum_async(path: &Path, expected: &str) -> Result<()> {\n//debug!(\"Async Verifying checksum for: {}\", path.display());\n// let file = File::open(path).await;\n// let mut file = match file {\n// Ok(f) => f,\n// Err(e) => {\n// return Err(SpsError::Io(Arc::new(e))); // Wrap IO error\n// }\n// };\n//\n// let mut hasher = Sha256::new();\n// let mut buffer = Vec::with_capacity(8192); // Use a Vec as buffer for read_buf\n// let mut total_bytes_read = 0;\n//\n// loop {\n// buffer.clear();\n// match file.read_buf(&mut buffer).await {\n// Ok(0) => break, // End of file\n// Ok(n) => {\n// hasher.update(&buffer[..n]);\n// total_bytes_read += n as u64;\n// }\n// Err(e) => {\n// return Err(SpsError::Io(Arc::new(e))); // Wrap IO error\n// }\n// }\n// }\n//\n// let hash_bytes = hasher.finalize();\n// let actual = hex::encode(hash_bytes);\n//\n// debug!(\n// \"Async Calculated SHA256: {} ({} bytes read)\",\n// actual, total_bytes_read\n// );\n// debug!(\"Expected SHA256: {}\", expected);\n//\n// if actual.eq_ignore_ascii_case(expected) {\n// Ok(())\n// } else {\n// Err(SpsError::ChecksumError(format!(\n// \"Checksum mismatch for {}: expected {}, got {}\",\n// path.display(),\n// expected,\n// actual\n// )))\n// }\n//}\n\n// Keep the synchronous version for now if needed elsewhere or for comparison\npub fn verify_checksum(path: &Path, expected: &str) -> Result<()> {\n tracing::debug!(\"Verifying checksum for: {}\", path.display());\n let mut file = File::open(path)?;\n let mut hasher = Sha256::new();\n let bytes_copied = io::copy(&mut file, &mut hasher)?;\n let hash_bytes = hasher.finalize();\n let actual = hex::encode(hash_bytes);\n tracing::debug!(\n \"Calculated SHA256: {} ({} bytes read)\",\n actual,\n bytes_copied\n );\n tracing::debug!(\"Expected SHA256: {}\", expected);\n if actual.eq_ignore_ascii_case(expected) {\n Ok(())\n } else {\n Err(SpsError::ChecksumError(format!(\n \"Checksum mismatch for {}: expected {}, got {}\",\n path.display(),\n expected,\n actual\n )))\n }\n}\n\n/// Verifies that the detected content type of the file matches the expected extension.\npub fn verify_content_type(path: &Path, expected_ext: &str) -> Result<()> {\n let kind_opt = infer::get_from_path(path)?;\n if let Some(kind) = kind_opt {\n let actual_ext = kind.extension();\n if actual_ext.eq_ignore_ascii_case(expected_ext) {\n tracing::debug!(\n \"Content type verified: {} matches expected {}\",\n actual_ext,\n expected_ext\n );\n Ok(())\n } else {\n Err(SpsError::Generic(format!(\n \"Content type mismatch for {}: expected extension '{}', but detected '{}'\",\n path.display(),\n expected_ext,\n actual_ext\n )))\n }\n } else {\n Err(SpsError::Generic(format!(\n \"Could not determine content type for {}\",\n path.display()\n )))\n }\n}\n\n/// Validates a URL, ensuring it uses the HTTPS scheme.\npub fn validate_url(url_str: &str) -> Result<()> {\n let url = Url::parse(url_str)\n .map_err(|e| SpsError::Generic(format!(\"Failed to parse URL '{url_str}': {e}\")))?;\n if url.scheme() == \"https\" {\n Ok(())\n } else {\n Err(SpsError::ValidationError(format!(\n \"Invalid URL scheme for '{}': Must be https, but got '{}'\",\n url_str,\n url.scheme()\n )))\n }\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/manpage.rs", "// ===== src/build/cask/artifacts/manpage.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::sync::LazyLock;\n\nuse regex::Regex;\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n// --- Moved Regex Creation Outside ---\nstatic MANPAGE_RE: LazyLock =\n LazyLock::new(|| Regex::new(r\"\\.([1-8nl])(?:\\.gz)?$\").unwrap());\n\n/// Install any `manpage` stanzas from the Cask definition.\n/// Mirrors Homebrew’s `Cask::Artifact::Manpage < Symlinked` behavior\n/// :contentReference[oaicite:3]{index=3}.\npub fn install_manpage(\n cask: &Cask,\n stage_path: &Path,\n _cask_version_install_path: &Path, // Not needed for symlinking manpages\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n // Look up the \"manpage\" array in the raw artifacts JSON :contentReference[oaicite:4]{index=4}\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"manpage\").and_then(|v| v.as_array()) {\n for entry in entries {\n if let Some(man_file) = entry.as_str() {\n let src = stage_path.join(man_file);\n if !src.exists() {\n debug!(\n \"Manpage '{}' not found in staging area, skipping\",\n man_file\n );\n continue;\n }\n\n // Use the static regex\n let section = if let Some(caps) = MANPAGE_RE.captures(man_file) {\n caps.get(1).unwrap().as_str()\n } else {\n debug!(\n \"Filename '{}' does not look like a manpage, skipping\",\n man_file\n );\n continue;\n };\n\n // Build the target directory: e.g. /opt/sps/share/man/man1\n let man_dir = config.man_base_dir().join(format!(\"man{section}\"));\n fs::create_dir_all(&man_dir)?;\n\n // Determine the target path\n let file_name = Path::new(man_file).file_name().ok_or_else(|| {\n sps_common::error::SpsError::Generic(format!(\n \"Invalid manpage filename: {man_file}\"\n ))\n })?; // Handle potential None\n let dest = man_dir.join(file_name);\n\n // Remove any existing file or symlink\n // :contentReference[oaicite:7]{index=7}\n if dest.exists() || dest.symlink_metadata().is_ok() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\"Linking manpage '{}' → '{}'\", src.display(), dest.display());\n // Create the symlink\n symlink(&src, &dest)?;\n\n // Record it in our manifest\n installed.push(InstalledArtifact::ManpageLink {\n link_path: dest.clone(),\n target_path: src.clone(),\n });\n }\n }\n // Assume only one \"manpage\" stanza per Cask based on Homebrew structure\n break;\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-common/src/config.rs", "// sps-common/src/config.rs\nuse std::env;\nuse std::path::{Path, PathBuf};\n\nuse directories::UserDirs; // Ensure this crate is in sps-common/Cargo.toml\nuse tracing::debug;\n\nuse super::error::Result; // Assuming SpsResult is Result from super::error\n\n// This constant will serve as a fallback if HOMEBREW_PREFIX is not set or is empty.\nconst DEFAULT_FALLBACK_SPS_ROOT: &str = \"/opt/homebrew\";\nconst SPS_ROOT_MARKER_FILENAME: &str = \".sps_root_v1\";\n\n#[derive(Debug, Clone)]\npub struct Config {\n pub sps_root: PathBuf, // Public for direct construction in main for init if needed\n pub api_base_url: String,\n pub artifact_domain: Option,\n pub docker_registry_token: Option,\n pub docker_registry_basic_auth: Option,\n pub github_api_token: Option,\n}\n\nimpl Config {\n pub fn load() -> Result {\n debug!(\"Loading sps configuration\");\n\n // Try to get SPS_ROOT from HOMEBREW_PREFIX environment variable.\n // Fallback to DEFAULT_FALLBACK_SPS_ROOT if not set or empty.\n let sps_root_str = env::var(\"HOMEBREW_PREFIX\").ok().filter(|s| !s.is_empty())\n .unwrap_or_else(|| {\n debug!(\n \"HOMEBREW_PREFIX environment variable not set or empty, falling back to default: {}\",\n DEFAULT_FALLBACK_SPS_ROOT\n );\n DEFAULT_FALLBACK_SPS_ROOT.to_string()\n });\n\n let sps_root_path = PathBuf::from(&sps_root_str);\n debug!(\"Effective SPS_ROOT set to: {}\", sps_root_path.display());\n\n let api_base_url = \"https://formulae.brew.sh/api\".to_string();\n\n let artifact_domain = env::var(\"HOMEBREW_ARTIFACT_DOMAIN\").ok();\n let docker_registry_token = env::var(\"HOMEBREW_DOCKER_REGISTRY_TOKEN\").ok();\n let docker_registry_basic_auth = env::var(\"HOMEBREW_DOCKER_REGISTRY_BASIC_AUTH_TOKEN\").ok();\n let github_api_token = env::var(\"HOMEBREW_GITHUB_API_TOKEN\").ok();\n\n debug!(\"Configuration loaded successfully.\");\n Ok(Self {\n sps_root: sps_root_path,\n api_base_url,\n artifact_domain,\n docker_registry_token,\n docker_registry_basic_auth,\n github_api_token,\n })\n }\n\n pub fn sps_root(&self) -> &Path {\n &self.sps_root\n }\n\n pub fn bin_dir(&self) -> PathBuf {\n self.sps_root.join(\"bin\")\n }\n\n pub fn cellar_dir(&self) -> PathBuf {\n self.sps_root.join(\"Cellar\") // Changed from \"cellar\" to \"Cellar\" to match Homebrew\n }\n\n pub fn cask_room_dir(&self) -> PathBuf {\n self.sps_root.join(\"Caskroom\") // Changed from \"cask_room\" to \"Caskroom\"\n }\n\n pub fn cask_store_dir(&self) -> PathBuf {\n self.sps_root.join(\"sps_cask_store\")\n }\n\n pub fn opt_dir(&self) -> PathBuf {\n self.sps_root.join(\"opt\")\n }\n\n pub fn taps_dir(&self) -> PathBuf {\n self.sps_root.join(\"Library/Taps\") // Adjusted to match Homebrew structure\n }\n\n pub fn cache_dir(&self) -> PathBuf {\n self.sps_root.join(\"sps_cache\")\n }\n\n pub fn logs_dir(&self) -> PathBuf {\n self.sps_root.join(\"sps_logs\")\n }\n\n pub fn tmp_dir(&self) -> PathBuf {\n self.sps_root.join(\"tmp\")\n }\n\n pub fn state_dir(&self) -> PathBuf {\n self.sps_root.join(\"sps_state\")\n }\n\n pub fn man_base_dir(&self) -> PathBuf {\n self.sps_root.join(\"share\").join(\"man\")\n }\n\n pub fn sps_root_marker_path(&self) -> PathBuf {\n self.sps_root.join(SPS_ROOT_MARKER_FILENAME)\n }\n\n pub fn applications_dir(&self) -> PathBuf {\n if cfg!(target_os = \"macos\") {\n PathBuf::from(\"/Applications\")\n } else {\n self.home_dir().join(\"Applications\")\n }\n }\n\n pub fn formula_cellar_dir(&self, formula_name: &str) -> PathBuf {\n self.cellar_dir().join(formula_name)\n }\n\n pub fn formula_keg_path(&self, formula_name: &str, version_str: &str) -> PathBuf {\n self.formula_cellar_dir(formula_name).join(version_str)\n }\n\n pub fn formula_opt_path(&self, formula_name: &str) -> PathBuf {\n self.opt_dir().join(formula_name)\n }\n\n pub fn cask_room_token_path(&self, cask_token: &str) -> PathBuf {\n self.cask_room_dir().join(cask_token)\n }\n\n pub fn cask_store_token_path(&self, cask_token: &str) -> PathBuf {\n self.cask_store_dir().join(cask_token)\n }\n\n pub fn cask_store_version_path(&self, cask_token: &str, version_str: &str) -> PathBuf {\n self.cask_store_token_path(cask_token).join(version_str)\n }\n\n pub fn cask_store_app_path(\n &self,\n cask_token: &str,\n version_str: &str,\n app_name: &str,\n ) -> PathBuf {\n self.cask_store_version_path(cask_token, version_str)\n .join(app_name)\n }\n\n pub fn cask_room_version_path(&self, cask_token: &str, version_str: &str) -> PathBuf {\n self.cask_room_token_path(cask_token).join(version_str)\n }\n\n pub fn home_dir(&self) -> PathBuf {\n UserDirs::new().map_or_else(|| PathBuf::from(\"/\"), |ud| ud.home_dir().to_path_buf())\n }\n\n pub fn get_tap_path(&self, name: &str) -> Option {\n let parts: Vec<&str> = name.split('/').collect();\n if parts.len() == 2 {\n Some(\n self.taps_dir()\n .join(parts[0]) // user, e.g., homebrew\n .join(format!(\"homebrew-{}\", parts[1])), // repo, e.g., homebrew-core\n )\n } else {\n None\n }\n }\n\n pub fn get_formula_path_from_tap(&self, tap_name: &str, formula_name: &str) -> Option {\n self.get_tap_path(tap_name).and_then(|tap_path| {\n let json_path = tap_path\n .join(\"Formula\") // Standard Homebrew tap structure\n .join(format!(\"{formula_name}.json\"));\n if json_path.exists() {\n return Some(json_path);\n }\n // Fallback to .rb for completeness, though API primarily gives JSON\n let rb_path = tap_path.join(\"Formula\").join(format!(\"{formula_name}.rb\"));\n if rb_path.exists() {\n return Some(rb_path);\n }\n None\n })\n }\n}\n\nimpl Default for Config {\n fn default() -> Self {\n Self::load().expect(\"Failed to load default configuration\")\n }\n}\n\npub fn load_config() -> Result {\n Config::load()\n}\n"], ["/sps/sps-common/src/cache.rs", "// src/utils/cache.rs\n// Handles caching of formula data and downloads\n\nuse std::fs;\nuse std::path::{Path, PathBuf};\nuse std::time::{Duration, SystemTime};\n\nuse super::error::{Result, SpsError};\nuse crate::Config;\n\n/// Define how long cache entries are considered valid\nconst CACHE_TTL: Duration = Duration::from_secs(24 * 60 * 60); // 24 hours\n\n/// Cache struct to manage cache operations\npub struct Cache {\n cache_dir: PathBuf,\n _config: Config, // Keep a reference to config if needed for other paths or future use\n}\n\nimpl Cache {\n /// Create a new Cache using the config's cache_dir\n pub fn new(config: &Config) -> Result {\n let cache_dir = config.cache_dir();\n if !cache_dir.exists() {\n fs::create_dir_all(&cache_dir)?;\n }\n\n Ok(Self {\n cache_dir,\n _config: config.clone(),\n })\n }\n\n /// Gets the cache directory path\n pub fn get_dir(&self) -> &Path {\n &self.cache_dir\n }\n\n /// Stores raw string data in the cache\n pub fn store_raw(&self, filename: &str, data: &str) -> Result<()> {\n let path = self.cache_dir.join(filename);\n tracing::debug!(\"Saving raw data to cache file: {:?}\", path);\n fs::write(&path, data)?;\n Ok(())\n }\n\n /// Loads raw string data from the cache\n pub fn load_raw(&self, filename: &str) -> Result {\n let path = self.cache_dir.join(filename);\n tracing::debug!(\"Loading raw data from cache file: {:?}\", path);\n\n if !path.exists() {\n return Err(SpsError::Cache(format!(\n \"Cache file {filename} does not exist\"\n )));\n }\n\n fs::read_to_string(&path).map_err(|e| SpsError::Cache(format!(\"IO error: {e}\")))\n }\n\n /// Checks if a cache file exists and is valid (within TTL)\n pub fn is_cache_valid(&self, filename: &str) -> Result {\n let path = self.cache_dir.join(filename);\n if !path.exists() {\n return Ok(false);\n }\n\n let metadata = fs::metadata(&path)?;\n let modified_time = metadata.modified()?;\n let age = SystemTime::now()\n .duration_since(modified_time)\n .map_err(|e| SpsError::Cache(format!(\"System time error: {e}\")))?;\n\n Ok(age <= CACHE_TTL)\n }\n\n /// Clears a specific cache file\n pub fn clear_file(&self, filename: &str) -> Result<()> {\n let path = self.cache_dir.join(filename);\n if path.exists() {\n fs::remove_file(&path)?;\n }\n Ok(())\n }\n\n /// Clears all cache files\n pub fn clear_all(&self) -> Result<()> {\n if self.cache_dir.exists() {\n fs::remove_dir_all(&self.cache_dir)?;\n fs::create_dir_all(&self.cache_dir)?;\n }\n Ok(())\n }\n\n /// Gets a reference to the config\n pub fn config(&self) -> &Config {\n &self._config\n }\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/mdimporter.rs", "// ===== sps-core/src/build/cask/artifacts/mdimporter.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Installs `mdimporter` bundles from the staging area into\n/// `~/Library/Spotlight`, then symlinks them into the Caskroom,\n/// and reloads them via `mdimport -r` so Spotlight picks them up.\n///\n/// Mirrors Homebrew’s `Mdimporter < Moved` behavior.\npub fn install_mdimporter(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"mdimporter\").and_then(|v| v.as_array()) {\n // Target directory for user Spotlight importers\n let dest_dir = config.home_dir().join(\"Library\").join(\"Spotlight\");\n fs::create_dir_all(&dest_dir)?;\n\n for entry in entries {\n if let Some(bundle_name) = entry.as_str() {\n let src = stage_path.join(bundle_name);\n if !src.exists() {\n debug!(\n \"Mdimporter bundle '{}' not found in staging; skipping\",\n bundle_name\n );\n continue;\n }\n\n let dest = dest_dir.join(bundle_name);\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Installing mdimporter '{}' → '{}',\",\n src.display(),\n dest.display()\n );\n // Try move, fallback to copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record moved importer\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink for reference\n let link = cask_version_install_path.join(bundle_name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n\n // Reload Spotlight importer so it's picked up immediately\n debug!(\"Reloading Spotlight importer: {}\", dest.display());\n let _ = Command::new(\"/usr/bin/mdimport\")\n .arg(\"-r\")\n .arg(&dest)\n .status();\n }\n }\n break; // one stanza only\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/suite.rs", "// src/build/cask/artifacts/suite.rs\n\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Implements the `suite` stanza by moving each named directory from\n/// the staging area into `/Applications`, then symlinking it in the Caskroom.\n///\n/// Mirrors Homebrew’s Suite < Moved behavior (dirmethod :appdir)\n/// :contentReference[oaicite:3]{index=3}\npub fn install_suite(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n // Find the `suite` definition in the raw JSON artifacts\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def.iter() {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"suite\").and_then(|v| v.as_array()) {\n for entry in entries {\n if let Some(dir_name) = entry.as_str() {\n let src = stage_path.join(dir_name);\n if !src.exists() {\n debug!(\n \"Suite directory '{}' not found in staging, skipping\",\n dir_name\n );\n continue;\n }\n\n let dest_dir = config.applications_dir(); // e.g. /Applications\n let dest = dest_dir.join(dir_name); // e.g. /Applications/Foobar Suite\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n // remove old\n }\n\n debug!(\"Moving suite '{}' → '{}'\", src.display(), dest.display());\n // Try a rename (mv); fall back to recursive copy if cross‑filesystem\n let mv_status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !mv_status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record as an App artifact (a directory moved into /Applications)\n installed.push(InstalledArtifact::AppBundle { path: dest.clone() });\n\n // Then symlink it under Caskroom for reference\n let link = cask_version_install_path.join(dir_name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // only one \"suite\" stanza per cask\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/colorpicker.rs", "// ===== sps-core/src/build/cask/artifacts/colorpicker.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Installs any `colorpicker` stanzas from the Cask definition.\n///\n/// Homebrew’s `Colorpicker` artifact simply subclasses `Moved` with\n/// `dirmethod :colorpickerdir` → `~/Library/ColorPickers` :contentReference[oaicite:3]{index=3}.\npub fn install_colorpicker(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"colorpicker\").and_then(|v| v.as_array()) {\n // For each declared bundle name:\n for entry in entries {\n if let Some(bundle_name) = entry.as_str() {\n let src = stage_path.join(bundle_name);\n if !src.exists() {\n debug!(\n \"Colorpicker bundle '{}' not found in stage; skipping\",\n bundle_name\n );\n continue;\n }\n\n // Ensure ~/Library/ColorPickers exists\n // :contentReference[oaicite:4]{index=4}\n let dest_dir = config\n .home_dir() // e.g. /Users/alxknt\n .join(\"Library\")\n .join(\"ColorPickers\");\n fs::create_dir_all(&dest_dir)?;\n\n let dest = dest_dir.join(bundle_name);\n // Remove any previous copy\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Moving colorpicker '{}' → '{}'\",\n src.display(),\n dest.display()\n );\n // mv, fallback to cp -R if necessary (cross‑device)\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record as a moved artifact (bundle installed)\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink back into Caskroom for reference\n // :contentReference[oaicite:5]{index=5}\n let link = cask_version_install_path.join(bundle_name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // only one `colorpicker` stanza per cask\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/keyboard_layout.rs", "// ===== sps-core/src/build/cask/artifacts/keyboard_layout.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Mirrors Homebrew’s `KeyboardLayout < Moved` behavior.\npub fn install_keyboard_layout(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"keyboard_layout\").and_then(|v| v.as_array()) {\n // Target directory for user keyboard layouts\n let dest_dir = config.home_dir().join(\"Library\").join(\"Keyboard Layouts\");\n fs::create_dir_all(&dest_dir)?;\n\n for entry in entries {\n if let Some(bundle_name) = entry.as_str() {\n let src = stage_path.join(bundle_name);\n if !src.exists() {\n debug!(\n \"Keyboard layout '{}' not found in staging; skipping\",\n bundle_name\n );\n continue;\n }\n\n let dest = dest_dir.join(bundle_name);\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Installing keyboard layout '{}' → '{}'\",\n src.display(),\n dest.display()\n );\n // Try move, fallback to copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record moved bundle\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink into Caskroom\n let link = cask_version_install_path.join(bundle_name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // one stanza only\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/internet_plugin.rs", "// ===== sps-core/src/build/cask/artifacts/internet_plugin.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Implements the `internet_plugin` stanza by moving each declared\n/// internet plugin bundle from the staging area into\n/// `~/Library/Internet Plug-Ins`, then symlinking it in the Caskroom.\n///\n/// Mirrors Homebrew’s `InternetPlugin < Moved` pattern.\npub fn install_internet_plugin(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n // Look for \"internet_plugin\" entries in the JSON artifacts\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"internet_plugin\").and_then(|v| v.as_array()) {\n // Target directory for user internet plugins\n let dest_dir = config.home_dir().join(\"Library\").join(\"Internet Plug-Ins\");\n fs::create_dir_all(&dest_dir)?;\n\n for entry in entries {\n if let Some(name) = entry.as_str() {\n let src = stage_path.join(name);\n if !src.exists() {\n debug!(\"Internet plugin '{}' not found in staging; skipping\", name);\n continue;\n }\n\n let dest = dest_dir.join(name);\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Installing internet plugin '{}' → '{}'\",\n src.display(),\n dest.display()\n );\n // Try move, fallback to copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record moved plugin\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink into Caskroom for reference\n let link = cask_version_install_path.join(name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // single stanza\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/audio_unit_plugin.rs", "// ===== sps-core/src/build/cask/artifacts/audio_unit_plugin.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Installs `audio_unit_plugin` bundles from the staging area into\n/// `~/Library/Audio/Plug-Ins/Components`, then symlinks them into the Caskroom.\n///\n/// Mirrors Homebrew’s `AudioUnitPlugin < Moved` pattern.\npub fn install_audio_unit_plugin(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"audio_unit_plugin\").and_then(|v| v.as_array()) {\n // Target directory for Audio Unit components\n let dest_dir = config\n .home_dir()\n .join(\"Library\")\n .join(\"Audio\")\n .join(\"Plug-Ins\")\n .join(\"Components\");\n fs::create_dir_all(&dest_dir)?;\n\n for entry in entries {\n if let Some(bundle_name) = entry.as_str() {\n let src = stage_path.join(bundle_name);\n if !src.exists() {\n debug!(\n \"AudioUnit plugin '{}' not found in staging; skipping\",\n bundle_name\n );\n continue;\n }\n\n let dest = dest_dir.join(bundle_name);\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Installing AudioUnit plugin '{}' → '{}'\",\n src.display(),\n dest.display()\n );\n // Try move, fallback to copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record moved plugin\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink into Caskroom for reference\n let link = cask_version_install_path.join(bundle_name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // one stanza only\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/vst_plugin.rs", "// ===== sps-core/src/build/cask/artifacts/vst_plugin.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Installs `vst_plugin` bundles from the staging area into\n/// `~/Library/Audio/Plug-Ins/VST`, then symlinks them into the Caskroom.\n///\n/// Mirrors Homebrew’s `VstPlugin < Moved` pattern.\npub fn install_vst_plugin(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"vst_plugin\").and_then(|v| v.as_array()) {\n // Target directory for VST plugins\n let dest_dir = config\n .home_dir()\n .join(\"Library\")\n .join(\"Audio\")\n .join(\"Plug-Ins\")\n .join(\"VST\");\n fs::create_dir_all(&dest_dir)?;\n\n for entry in entries {\n if let Some(bundle_name) = entry.as_str() {\n let src = stage_path.join(bundle_name);\n if !src.exists() {\n debug!(\n \"VST plugin '{}' not found in staging; skipping\",\n bundle_name\n );\n continue;\n }\n\n let dest = dest_dir.join(bundle_name);\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Installing VST plugin '{}' → '{}'\",\n src.display(),\n dest.display()\n );\n // Try move, fallback to copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record moved plugin\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink into Caskroom for reference\n let link = cask_version_install_path.join(bundle_name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // single stanza\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/service.rs", "// ===== sps-core/src/build/cask/artifacts/service.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers;\n\n/// Installs `service` artifacts by moving each declared\n/// Automator workflow or service bundle from the staging area into\n/// `~/Library/Services`, then symlinking it in the Caskroom.\n///\n/// Mirrors Homebrew’s `Service < Moved` behavior.\npub fn install_service(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"service\").and_then(|v| v.as_array()) {\n // Target directory for user Services\n let dest_dir = config.home_dir().join(\"Library\").join(\"Services\");\n fs::create_dir_all(&dest_dir)?;\n\n for entry in entries {\n if let Some(bundle_name) = entry.as_str() {\n let src = stage_path.join(bundle_name);\n if !src.exists() {\n debug!(\n \"Service bundle '{}' not found in staging; skipping\",\n bundle_name\n );\n continue;\n }\n\n let dest = dest_dir.join(bundle_name);\n if dest.exists() {\n let _ = helpers::remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Installing service '{}' → '{}'\",\n src.display(),\n dest.display()\n );\n // Try move, fallback to copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record moved service\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink into Caskroom for reference\n let link = cask_version_install_path.join(bundle_name);\n let _ = helpers::remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // one stanza only\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/vst3_plugin.rs", "// ===== sps-core/src/build/cask/artifacts/vst3_plugin.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Installs `vst3_plugin` bundles from the staging area into\n/// `~/Library/Audio/Plug-Ins/VST3`, then symlinks them into the Caskroom.\n///\n/// Mirrors Homebrew’s `Vst3Plugin < Moved` pattern.\npub fn install_vst3_plugin(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"vst3_plugin\").and_then(|v| v.as_array()) {\n // Target directory for VST3 plugins\n let dest_dir = config\n .home_dir()\n .join(\"Library\")\n .join(\"Audio\")\n .join(\"Plug-Ins\")\n .join(\"VST3\");\n fs::create_dir_all(&dest_dir)?;\n\n for entry in entries {\n if let Some(bundle_name) = entry.as_str() {\n let src = stage_path.join(bundle_name);\n if !src.exists() {\n debug!(\n \"VST3 plugin '{}' not found in staging; skipping\",\n bundle_name\n );\n continue;\n }\n\n let dest = dest_dir.join(bundle_name);\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Installing VST3 plugin '{}' → '{}'\",\n src.display(),\n dest.display()\n );\n // Try move, fallback to copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record moved plugin\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink into Caskroom for reference\n let link = cask_version_install_path.join(bundle_name);\n let _ = crate::install::cask::helpers::remove_path_robustly(\n &link, config, true,\n );\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // single stanza\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/screen_saver.rs", "// ===== sps-core/src/build/cask/artifacts/screen_saver.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Installs `screen_saver` bundles from the staging area into\n/// `~/Library/Screen Savers`, then symlinks them into the Caskroom.\n///\n/// Mirrors Homebrew’s `ScreenSaver < Moved` pattern.\npub fn install_screen_saver(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"screen_saver\").and_then(|v| v.as_array()) {\n // Target directory for user screen savers\n let dest_dir = config.home_dir().join(\"Library\").join(\"Screen Savers\");\n fs::create_dir_all(&dest_dir)?;\n\n for entry in entries {\n if let Some(bundle_name) = entry.as_str() {\n let src = stage_path.join(bundle_name);\n if !src.exists() {\n debug!(\n \"Screen saver '{}' not found in staging; skipping\",\n bundle_name\n );\n continue;\n }\n\n let dest = dest_dir.join(bundle_name);\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Installing screen saver '{}' → '{}',\",\n src.display(),\n dest.display()\n );\n // Try move, fallback to copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record moved screen saver\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink into Caskroom for reference\n let link = cask_version_install_path.join(bundle_name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // single stanza\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/qlplugin.rs", "// ===== sps-core/src/build/cask/artifacts/qlplugin.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Installs `qlplugin` bundles from the staging area into\n/// `~/Library/QuickLook`, then symlinks them into the Caskroom.\n///\n/// Mirrors Homebrew’s `QuickLook < Moved` pattern for QuickLook plugins.\npub fn install_qlplugin(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n // Look for \"qlplugin\" entries in the JSON artifacts\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"qlplugin\").and_then(|v| v.as_array()) {\n // Target directory for QuickLook plugins\n let dest_dir = config.home_dir().join(\"Library\").join(\"QuickLook\");\n fs::create_dir_all(&dest_dir)?;\n\n for entry in entries {\n if let Some(bundle_name) = entry.as_str() {\n let src = stage_path.join(bundle_name);\n if !src.exists() {\n debug!(\n \"QuickLook plugin '{}' not found in staging; skipping\",\n bundle_name\n );\n continue;\n }\n\n let dest = dest_dir.join(bundle_name);\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Installing QuickLook plugin '{}' → '{}',\",\n src.display(),\n dest.display()\n );\n // Try move, fallback to copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record moved plugin\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink into Caskroom for reference\n let link = cask_version_install_path.join(bundle_name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // single stanza\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/prefpane.rs", "// ===== sps-core/src/build/cask/artifacts/prefpane.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Implements the `prefpane` stanza by moving each declared\n/// preference pane bundle from the staging area into\n/// `~/Library/PreferencePanes`, then symlinking it in the Caskroom.\n///\n/// Mirrors Homebrew’s `Prefpane < Moved` pattern.\npub fn install_prefpane(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n // Look for \"prefpane\" entries in the JSON artifacts\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"prefpane\").and_then(|v| v.as_array()) {\n // Target directory for user preference panes\n let dest_dir = config.home_dir().join(\"Library\").join(\"PreferencePanes\");\n fs::create_dir_all(&dest_dir)?;\n\n for entry in entries {\n if let Some(bundle_name) = entry.as_str() {\n let src = stage_path.join(bundle_name);\n if !src.exists() {\n debug!(\n \"Preference pane '{}' not found in staging; skipping\",\n bundle_name\n );\n continue;\n }\n\n let dest = dest_dir.join(bundle_name);\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Installing prefpane '{}' → '{}'\",\n src.display(),\n dest.display()\n );\n // Try move, fallback to copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record moved bundle\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink into Caskroom for reference\n let link = cask_version_install_path.join(bundle_name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // single stanza\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/upgrade/source.rs", "// sps-core/src/upgrade/source.rs\n\nuse std::path::{Path, PathBuf};\n\nuse sps_common::config::Config;\nuse sps_common::error::{Result as SpsResult, SpsError};\nuse sps_common::model::formula::Formula;\nuse tracing::{debug, error};\n\nuse crate::check::installed::InstalledPackageInfo;\nuse crate::{build, uninstall};\n\n/// Upgrades a formula that was/will be installed from source.\n///\n/// This involves:\n/// 1. Uninstalling the old version of the formula.\n/// 2. Building and installing the new version from source.\n/// 3. Linking the new version.\npub async fn upgrade_source_formula(\n formula: &Formula,\n new_source_download_path: &Path,\n old_install_info: &InstalledPackageInfo,\n config: &Config,\n all_installed_dependency_paths: &[PathBuf], // For build environment\n) -> SpsResult {\n debug!(\n \"Upgrading source-built formula {} from {} to {}\",\n formula.name(),\n old_install_info.version,\n formula.version_str_full()\n );\n\n // 1. Uninstall the old version\n debug!(\n \"Uninstalling old source-built version: {} at {}\",\n old_install_info.version,\n old_install_info.path.display()\n );\n let uninstall_opts = uninstall::UninstallOptions { skip_zap: true };\n uninstall::formula::uninstall_formula_artifacts(old_install_info, config, &uninstall_opts)\n .map_err(|e| {\n error!(\n \"Failed to uninstall old version {} of formula {}: {}\",\n old_install_info.version,\n formula.name(),\n e\n );\n SpsError::InstallError(format!(\n \"Failed to uninstall old version during source upgrade of {}: {e}\",\n formula.name()\n ))\n })?;\n debug!(\n \"Successfully uninstalled old source-built version of {}\",\n formula.name()\n );\n\n // 2. Build and install the new version from source\n debug!(\n \"Building new version of {} from source path {}\",\n formula.name(),\n new_source_download_path.display()\n );\n let installed_keg_path = build::compile::build_from_source(\n new_source_download_path,\n formula,\n config,\n all_installed_dependency_paths,\n )\n .await\n .map_err(|e| {\n error!(\n \"Failed to build new version of formula {} from source: {}\",\n formula.name(),\n e\n );\n SpsError::InstallError(format!(\n \"Failed to build new version from source during upgrade of {}: {e}\",\n formula.name()\n ))\n })?;\n debug!(\n \"Successfully built and installed new version of {} to {}\",\n formula.name(),\n installed_keg_path.display()\n );\n\n // 3. Linking is handled by the worker after this function returns the path.\n\n Ok(installed_keg_path)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/dictionary.rs", "// ===== sps-core/src/build/cask/artifacts/dictionary.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Implements the `dictionary` stanza by moving each declared\n/// `.dictionary` bundle from the staging area into `~/Library/Dictionaries`,\n/// then symlinking it in the Caskroom.\n///\n/// Homebrew’s Ruby definition is simply:\n/// ```ruby\n/// class Dictionary < Moved; end\n/// ```\n/// :contentReference[oaicite:2]{index=2}\npub fn install_dictionary(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n // Find any `dictionary` arrays in the raw JSON artifacts\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"dictionary\").and_then(|v| v.as_array()) {\n for entry in entries {\n if let Some(bundle_name) = entry.as_str() {\n let src = stage_path.join(bundle_name);\n if !src.exists() {\n debug!(\n \"Dictionary bundle '{}' not found in staging; skipping\",\n bundle_name\n );\n continue;\n }\n\n // Standard user dictionary directory: ~/Library/Dictionaries\n // :contentReference[oaicite:3]{index=3}\n let dest_dir = config\n .home_dir() // e.g. /Users/alxknt\n .join(\"Library\")\n .join(\"Dictionaries\");\n fs::create_dir_all(&dest_dir)?;\n\n let dest = dest_dir.join(bundle_name);\n // Remove any previous install\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Moving dictionary '{}' → '{}'\",\n src.display(),\n dest.display()\n );\n // Try a direct move; fall back to recursive copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record the moved bundle\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink back into Caskroom for reference\n let link = cask_version_install_path.join(bundle_name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // Only one `dictionary` stanza per cask\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/font.rs", "// ===== sps-core/src/build/cask/artifacts/font.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Implements the `font` stanza by moving each declared\n/// font file or directory from the staging area into\n/// `~/Library/Fonts`, then symlinking it in the Caskroom.\n///\n/// Mirrors Homebrew’s `Dictionary < Moved` and `Colorpicker < Moved` pattern.\npub fn install_font(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n // Look for \"font\" entries in the JSON artifacts\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"font\").and_then(|v| v.as_array()) {\n // Target directory for user fonts\n let dest_dir = config.home_dir().join(\"Library\").join(\"Fonts\");\n fs::create_dir_all(&dest_dir)?;\n\n for entry in entries {\n if let Some(name) = entry.as_str() {\n let src = stage_path.join(name);\n if !src.exists() {\n debug!(\"Font '{}' not found in staging; skipping\", name);\n continue;\n }\n\n let dest = dest_dir.join(name);\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\"Installing font '{}' → '{}'\", src.display(), dest.display());\n // Try move, fallback to copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record moved font\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink into Caskroom for reference\n let link = cask_version_install_path.join(name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // single font stanza per cask\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/uninstall/formula.rs", "// sps-core/src/uninstall/formula.rs\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse tracing::{debug, error, warn};\n\nuse crate::check::installed::InstalledPackageInfo;\nuse crate::install; // For install::bottle::link\nuse crate::uninstall::common::{remove_filesystem_artifact, UninstallOptions};\n\npub fn uninstall_formula_artifacts(\n info: &InstalledPackageInfo,\n config: &Config,\n _options: &UninstallOptions, /* options currently unused for formula but kept for signature\n * consistency */\n) -> Result<()> {\n debug!(\n \"Uninstalling Formula artifacts for {} version {}\",\n info.name, info.version\n );\n\n // 1. Unlink artifacts\n // This function should handle removal of symlinks from /opt/sps/bin, /opt/sps/lib etc.\n // and the /opt/sps/opt/formula_name link.\n install::bottle::link::unlink_formula_artifacts(&info.name, &info.version, config)?;\n\n // 2. Remove the keg directory\n if info.path.exists() {\n debug!(\"Removing formula keg directory: {}\", info.path.display());\n // For formula kegs, we generally expect them to be owned by the user or sps,\n // but sudo might be involved if permissions were changed manually or during a problematic\n // install. Setting use_sudo to true provides a fallback, though ideally it's not\n // needed for user-owned kegs.\n let use_sudo = true;\n if !remove_filesystem_artifact(&info.path, use_sudo) {\n // Check if it still exists after the removal attempt\n if info.path.exists() {\n error!(\n \"Failed remove keg {}: Check logs for sudo errors or other filesystem issues.\",\n info.path.display()\n );\n return Err(SpsError::InstallError(format!(\n \"Failed to remove keg directory: {}\",\n info.path.display()\n )));\n } else {\n // It means remove_filesystem_artifact returned false but the dir is gone\n // (possibly removed by sudo, or a race condition if another process removed it)\n debug!(\"Keg directory successfully removed (possibly with sudo).\");\n }\n }\n } else {\n warn!(\n \"Keg directory {} not found during uninstall. It might have been already removed.\",\n info.path.display()\n );\n }\n Ok(())\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/input_method.rs", "// ===== sps-core/src/build/cask/artifacts/input_method.rs =====\n\nuse std::fs;\nuse std::os::unix::fs as unix_fs;\nuse std::path::Path;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\n\nuse crate::install::cask::helpers::remove_path_robustly;\nuse crate::install::cask::write_cask_manifest;\n\n/// Install `input_method` artifacts from the staged directory into\n/// `~/Library/Input Methods` and record installed artifacts.\npub fn install_input_method(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n // Ensure we have an array of input_method names\n if let Some(artifacts_def) = &cask.artifacts {\n for artifact_value in artifacts_def {\n if let Some(obj) = artifact_value.as_object() {\n if let Some(names) = obj.get(\"input_method\").and_then(|v| v.as_array()) {\n for name_val in names {\n if let Some(name) = name_val.as_str() {\n let source = stage_path.join(name);\n if source.exists() {\n // Target directory: ~/Library/Input Methods\n let target_dir =\n config.home_dir().join(\"Library\").join(\"Input Methods\");\n if !target_dir.exists() {\n fs::create_dir_all(&target_dir)?;\n }\n let target = target_dir.join(name);\n\n // Remove existing input method if present\n if target.exists() {\n let _ = remove_path_robustly(&target, config, true);\n }\n\n // Move (or rename) the staged bundle\n fs::rename(&source, &target)\n .or_else(|_| unix_fs::symlink(&source, &target))?;\n\n // Record the main artifact\n installed.push(InstalledArtifact::MovedResource {\n path: target.clone(),\n });\n\n // Create a caskroom symlink for uninstallation\n let link_path = cask_version_install_path.join(name);\n if link_path.exists() {\n let _ = remove_path_robustly(&link_path, config, true);\n }\n #[cfg(unix)]\n std::os::unix::fs::symlink(&target, &link_path)?;\n\n installed.push(InstalledArtifact::CaskroomLink {\n link_path,\n target_path: target,\n });\n }\n }\n }\n }\n }\n }\n }\n\n // Write manifest for these artifacts\n write_cask_manifest(cask, cask_version_install_path, installed.clone())?;\n Ok(installed)\n}\n"], ["/sps/sps/src/cli/upgrade.rs", "use std::sync::Arc;\n\nuse clap::Args;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_core::check::installed;\n\nuse crate::pipeline::runner::{self, CommandType, PipelineFlags};\n\n#[derive(Args, Debug)]\npub struct UpgradeArgs {\n #[arg()]\n pub names: Vec,\n\n #[arg(long, conflicts_with = \"names\")]\n pub all: bool,\n\n #[arg(long)]\n pub build_from_source: bool,\n}\n\nimpl UpgradeArgs {\n pub async fn run(&self, config: &Config, cache: Arc) -> Result<()> {\n let targets = if self.all {\n // Get all installed package names\n let installed = installed::get_installed_packages(config).await?;\n installed.into_iter().map(|p| p.name).collect()\n } else {\n self.names.clone()\n };\n\n if targets.is_empty() {\n return Ok(());\n }\n\n let flags = PipelineFlags {\n // Populate flags from args\n build_from_source: self.build_from_source,\n // Upgrade should respect original install options ideally,\n // but for now let's default them. This could be enhanced later\n // by reading install receipts.\n include_optional: false,\n skip_recommended: false,\n // ... add other common flags if needed ...\n };\n\n runner::run_pipeline(\n &targets,\n CommandType::Upgrade { all: self.all },\n config,\n cache,\n &flags,\n )\n .await\n }\n}\n"], ["/sps/sps-common/src/model/version.rs", "// **File:** sps-core/src/model/version.rs (New file)\nuse std::fmt;\nuse std::str::FromStr;\n\nuse serde::{Deserialize, Deserializer, Serialize, Serializer};\n\nuse crate::error::{Result, SpsError};\n\n/// Wrapper around semver::Version for formula versions.\n#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]\npub struct Version(semver::Version);\n\nimpl Version {\n pub fn parse(s: &str) -> Result {\n // Attempt standard semver parse first\n semver::Version::parse(s).map(Version).or_else(|_| {\n // Homebrew often uses versions like \"1.2.3_1\" (revision) or just \"123\"\n // Try to handle these by stripping suffixes or padding\n // This is a simplified handling, Homebrew's PkgVersion is complex\n let cleaned = s.split('_').next().unwrap_or(s); // Take part before _\n let parts: Vec<&str> = cleaned.split('.').collect();\n let padded = match parts.len() {\n 1 => format!(\"{}.0.0\", parts[0]),\n 2 => format!(\"{}.{}.0\", parts[0], parts[1]),\n _ => cleaned.to_string(), // Use original if 3+ parts\n };\n semver::Version::parse(&padded).map(Version).map_err(|e| {\n SpsError::VersionError(format!(\n \"Failed to parse version '{s}' (tried '{padded}'): {e}\"\n ))\n })\n })\n }\n}\n\nimpl FromStr for Version {\n type Err = SpsError;\n fn from_str(s: &str) -> std::result::Result {\n Self::parse(s)\n }\n}\n\nimpl fmt::Display for Version {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n // TODO: Preserve original format if possible? PkgVersion complexity.\n // For now, display the parsed semver representation.\n write!(f, \"{}\", self.0)\n }\n}\n\n// Manual Serialize/Deserialize to handle the Version<->String conversion\nimpl Serialize for Version {\n fn serialize(&self, serializer: S) -> std::result::Result\n where\n S: Serializer,\n {\n serializer.serialize_str(&self.to_string())\n }\n}\n\nimpl AsRef for Version {\n fn as_ref(&self) -> &Self {\n self\n }\n}\n\n// Removed redundant ToString implementation as it conflicts with the blanket implementation in std.\n\nimpl From for semver::Version {\n fn from(version: Version) -> Self {\n version.0\n }\n}\n\nimpl<'de> Deserialize<'de> for Version {\n fn deserialize(deserializer: D) -> std::result::Result\n where\n D: Deserializer<'de>,\n {\n let s = String::deserialize(deserializer)?;\n Self::from_str(&s).map_err(serde::de::Error::custom)\n }\n}\n\n// Add to sps-core/src/utils/error.rs:\n// #[error(\"Version error: {0}\")]\n// VersionError(String),\n\n// Add to sps-core/Cargo.toml:\n// [dependencies]\n// semver = \"1.0\"\n"], ["/sps/sps/src/cli.rs", "// sps/src/cli.rs\n//! Defines the command-line argument structure using clap.\nuse std::sync::Arc;\n\nuse clap::{ArgAction, Parser, Subcommand};\nuse sps_common::error::Result;\nuse sps_common::{Cache, Config};\n\n// Module declarations\npub mod info;\npub mod init;\npub mod install;\npub mod list;\npub mod reinstall;\npub mod search;\npub mod status;\npub mod uninstall;\npub mod update;\npub mod upgrade;\n// Re-export InitArgs to make it accessible as cli::InitArgs\n// Import other command Args structs\nuse crate::cli::info::Info;\npub use crate::cli::init::InitArgs;\nuse crate::cli::install::InstallArgs;\nuse crate::cli::list::List;\nuse crate::cli::reinstall::ReinstallArgs;\nuse crate::cli::search::Search;\nuse crate::cli::uninstall::Uninstall;\nuse crate::cli::update::Update;\nuse crate::cli::upgrade::UpgradeArgs;\n\n#[derive(Parser, Debug)]\n#[command(author, version, about, long_about = None, name = \"sps\", bin_name = \"sps\")]\n#[command(propagate_version = true)]\npub struct CliArgs {\n #[arg(short, long, action = ArgAction::Count, global = true)]\n pub verbose: u8,\n\n #[command(subcommand)]\n pub command: Command,\n}\n\n#[derive(Subcommand, Debug)]\npub enum Command {\n Init(InitArgs),\n Search(Search),\n List(List),\n Info(Info),\n Update(Update),\n Install(InstallArgs),\n Uninstall(Uninstall),\n Reinstall(ReinstallArgs),\n Upgrade(UpgradeArgs),\n}\n\nimpl Command {\n pub async fn run(&self, config: &Config, cache: Arc) -> Result<()> {\n match self {\n Self::Init(command) => command.run(config).await,\n Self::Search(command) => command.run(config, cache).await,\n Self::List(command) => command.run(config, cache).await,\n Self::Info(command) => command.run(config, cache).await,\n Self::Update(command) => command.run(config, cache).await,\n // Commands that use the pipeline\n Self::Install(command) => command.run(config, cache).await,\n Self::Reinstall(command) => command.run(config, cache).await,\n Self::Upgrade(command) => command.run(config, cache).await,\n Self::Uninstall(command) => command.run(config, cache).await,\n }\n }\n}\n\n// In install.rs, reinstall.rs, upgrade.rs, their run methods will now call\n// sps::cli::pipeline_runner::run_pipeline(...)\n// e.g., in sps/src/cli/install.rs:\n// use crate::cli::pipeline_runner::{self, CommandType, PipelineFlags};\n// ...\n// pipeline_runner::run_pipeline(&initial_targets, CommandType::Install, config, cache,\n// &flags).await\n"], ["/sps/sps-common/src/model/tap.rs", "// tap/tap.rs - Basic tap functionality // Should probably be in model module\n\nuse std::path::PathBuf;\n\nuse tracing::debug;\n\nuse crate::error::{Result, SpsError};\n\n/// Represents a source of packages (formulas and casks)\npub struct Tap {\n /// The user part of the tap name (e.g., \"homebrew\" in \"homebrew/core\")\n pub user: String,\n\n /// The repository part of the tap name (e.g., \"core\" in \"homebrew/core\")\n pub repo: String,\n\n /// The full path to the tap directory\n pub path: PathBuf,\n}\n\nimpl Tap {\n /// Create a new tap from user/repo format\n pub fn new(name: &str) -> Result {\n let parts: Vec<&str> = name.split('/').collect();\n if parts.len() != 2 {\n return Err(SpsError::Generic(format!(\"Invalid tap name: {name}\")));\n }\n let user = parts[0].to_string();\n let repo = parts[1].to_string();\n let prefix = if cfg!(target_arch = \"aarch64\") {\n PathBuf::from(\"/opt/homebrew\")\n } else {\n PathBuf::from(\"/usr/local\")\n };\n let path = prefix\n .join(\"Library/Taps\")\n .join(&user)\n .join(format!(\"homebrew-{repo}\"));\n Ok(Self { user, repo, path })\n }\n\n /// Update this tap by pulling latest changes\n pub fn update(&self) -> Result<()> {\n use git2::{FetchOptions, Repository};\n\n let repo = Repository::open(&self.path)\n .map_err(|e| SpsError::Generic(format!(\"Failed to open tap repository: {e}\")))?;\n\n // Fetch updates from origin\n let mut remote = repo\n .find_remote(\"origin\")\n .map_err(|e| SpsError::Generic(format!(\"Failed to find remote 'origin': {e}\")))?;\n\n let mut fetch_options = FetchOptions::new();\n remote\n .fetch(\n &[\"refs/heads/*:refs/heads/*\"],\n Some(&mut fetch_options),\n None,\n )\n .map_err(|e| SpsError::Generic(format!(\"Failed to fetch updates: {e}\")))?;\n\n // Merge changes\n let fetch_head = repo\n .find_reference(\"FETCH_HEAD\")\n .map_err(|e| SpsError::Generic(format!(\"Failed to find FETCH_HEAD: {e}\")))?;\n\n let fetch_commit = repo\n .reference_to_annotated_commit(&fetch_head)\n .map_err(|e| SpsError::Generic(format!(\"Failed to get commit from FETCH_HEAD: {e}\")))?;\n\n let analysis = repo\n .merge_analysis(&[&fetch_commit])\n .map_err(|e| SpsError::Generic(format!(\"Failed to analyze merge: {e}\")))?;\n\n if analysis.0.is_up_to_date() {\n debug!(\"Already up-to-date\");\n return Ok(());\n }\n\n if analysis.0.is_fast_forward() {\n let mut reference = repo\n .find_reference(\"refs/heads/master\")\n .map_err(|e| SpsError::Generic(format!(\"Failed to find master branch: {e}\")))?;\n reference\n .set_target(fetch_commit.id(), \"Fast-forward\")\n .map_err(|e| SpsError::Generic(format!(\"Failed to fast-forward: {e}\")))?;\n repo.set_head(\"refs/heads/master\")\n .map_err(|e| SpsError::Generic(format!(\"Failed to set HEAD: {e}\")))?;\n repo.checkout_head(Some(git2::build::CheckoutBuilder::default().force()))\n .map_err(|e| SpsError::Generic(format!(\"Failed to checkout: {e}\")))?;\n } else {\n return Err(SpsError::Generic(\n \"Tap requires merge but automatic merging is not implemented\".to_string(),\n ));\n }\n\n Ok(())\n }\n\n /// Remove this tap by deleting its local repository\n pub fn remove(&self) -> Result<()> {\n if !self.path.exists() {\n return Err(SpsError::NotFound(format!(\n \"Tap {} is not installed\",\n self.full_name()\n )));\n }\n debug!(\"Removing tap {}\", self.full_name());\n std::fs::remove_dir_all(&self.path).map_err(|e| {\n SpsError::Generic(format!(\"Failed to remove tap {}: {}\", self.full_name(), e))\n })\n }\n\n /// Get the full name of the tap (user/repo)\n pub fn full_name(&self) -> String {\n format!(\"{}/{}\", self.user, self.repo)\n }\n\n /// Check if this tap is installed locally\n pub fn is_installed(&self) -> bool {\n self.path.exists()\n }\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/preflight.rs", "use std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::InstalledArtifact;\n\n/// Execute any `preflight` commands listed in the Cask’s JSON artifact stanza.\n/// Returns an empty Vec since preflight does not produce install artifacts.\npub fn run_preflight(\n cask: &Cask,\n stage_path: &Path,\n _config: &Config,\n) -> Result> {\n // Iterate over artifacts, look for \"preflight\" keys\n if let Some(entries) = &cask.artifacts {\n for entry in entries.iter().filter_map(|v| v.as_object()) {\n if let Some(cmds) = entry.get(\"preflight\").and_then(|v| v.as_array()) {\n for cmd_val in cmds.iter().filter_map(|v| v.as_str()) {\n // Substitute $STAGEDIR placeholder\n let cmd_str = cmd_val.replace(\"$STAGEDIR\", stage_path.to_str().unwrap());\n debug!(\"Running preflight: {}\", cmd_str);\n let status = Command::new(\"sh\").arg(\"-c\").arg(&cmd_str).status()?;\n if !status.success() {\n return Err(SpsError::InstallError(format!(\n \"preflight failed: {cmd_str}\"\n )));\n }\n }\n }\n }\n }\n\n // No install artifacts to return\n Ok(Vec::new())\n}\n"], ["/sps/sps/src/cli/reinstall.rs", "// sps-cli/src/cli/reinstall.rs\nuse std::sync::Arc;\n\nuse clap::Args;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::error::Result;\n\nuse crate::pipeline::runner::{self, CommandType, PipelineFlags};\n\n#[derive(Args, Debug)]\npub struct ReinstallArgs {\n #[arg(required = true)]\n pub names: Vec,\n\n #[arg(\n long,\n help = \"Force building the formula from source, even if a bottle is available\"\n )]\n pub build_from_source: bool,\n}\n\nimpl ReinstallArgs {\n pub async fn run(&self, config: &Config, cache: Arc) -> Result<()> {\n let flags = PipelineFlags {\n // Populate flags from args\n build_from_source: self.build_from_source,\n include_optional: false, // Reinstall usually doesn't change optional deps\n skip_recommended: true, /* Reinstall usually doesn't change recommended deps\n * ... add other common flags if needed ... */\n };\n runner::run_pipeline(&self.names, CommandType::Reinstall, config, cache, &flags).await\n }\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/uninstall.rs", "use std::path::PathBuf;\n\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\n\n/// At install time, scan the `uninstall` stanza and turn each directive\n/// into an InstalledArtifact variant, so it can later be torn down.\npub fn record_uninstall(cask: &Cask) -> Result> {\n let mut artifacts = Vec::new();\n\n if let Some(entries) = &cask.artifacts {\n for entry in entries.iter().filter_map(|v| v.as_object()) {\n if let Some(steps) = entry.get(\"uninstall\").and_then(|v| v.as_array()) {\n for step in steps.iter().filter_map(|v| v.as_object()) {\n for (key, val) in step {\n match key.as_str() {\n \"pkgutil\" => {\n if let Some(id) = val.as_str() {\n artifacts.push(InstalledArtifact::PkgUtilReceipt {\n id: id.to_string(),\n });\n }\n }\n \"delete\" => {\n if let Some(arr) = val.as_array() {\n for p in arr.iter().filter_map(|v| v.as_str()) {\n artifacts.push(InstalledArtifact::MovedResource {\n path: PathBuf::from(p),\n });\n }\n }\n }\n \"rmdir\" => {\n if let Some(arr) = val.as_array() {\n for p in arr.iter().filter_map(|v| v.as_str()) {\n artifacts.push(InstalledArtifact::MovedResource {\n path: PathBuf::from(p),\n });\n }\n }\n }\n \"launchctl\" => {\n if let Some(arr) = val.as_array() {\n for lbl in arr.iter().filter_map(|v| v.as_str()) {\n artifacts.push(InstalledArtifact::Launchd {\n label: lbl.to_string(),\n path: None,\n });\n }\n }\n }\n // Add other uninstall keys similarly...\n _ => {}\n }\n }\n }\n }\n }\n }\n\n Ok(artifacts)\n}\n"], ["/sps/sps-common/src/dependency/definition.rs", "// **File:** sps-core/src/dependency/dependency.rs // Should be in the model module\nuse std::fmt;\n\nuse bitflags::bitflags;\nuse serde::{Deserialize, Serialize};\n\nbitflags! {\n #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]\n pub struct DependencyTag: u8 {\n const RUNTIME = 0b00000001;\n const BUILD = 0b00000010;\n const TEST = 0b00000100;\n const OPTIONAL = 0b00001000;\n const RECOMMENDED = 0b00010000;\n }\n}\n\nimpl Default for DependencyTag {\n fn default() -> Self {\n Self::RUNTIME\n }\n}\n\nimpl fmt::Display for DependencyTag {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"{self:?}\")\n }\n}\n\n#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]\npub struct Dependency {\n pub name: String,\n #[serde(default)]\n pub tags: DependencyTag,\n}\n\nimpl Dependency {\n pub fn new_runtime(name: impl Into) -> Self {\n Self {\n name: name.into(),\n tags: DependencyTag::RUNTIME,\n }\n }\n\n pub fn new_with_tags(name: impl Into, tags: DependencyTag) -> Self {\n Self {\n name: name.into(),\n tags,\n }\n }\n}\n\npub trait DependencyExt {\n fn filter_by_tags(&self, include: DependencyTag, exclude: DependencyTag) -> Vec<&Dependency>;\n fn runtime(&self) -> Vec<&Dependency>;\n fn build_time(&self) -> Vec<&Dependency>;\n}\n\nimpl DependencyExt for Vec {\n fn filter_by_tags(&self, include: DependencyTag, exclude: DependencyTag) -> Vec<&Dependency> {\n self.iter()\n .filter(|dep| dep.tags.contains(include) && !dep.tags.intersects(exclude))\n .collect()\n }\n\n fn runtime(&self) -> Vec<&Dependency> {\n // A dependency is runtime if its tags indicate it's needed at runtime.\n // This includes standard runtime, recommended, or optional dependencies.\n // Build-only or Test-only dependencies (without other runtime flags) are excluded.\n self.iter()\n .filter(|dep| {\n dep.tags.intersects(\n DependencyTag::RUNTIME | DependencyTag::RECOMMENDED | DependencyTag::OPTIONAL,\n )\n })\n .collect()\n }\n\n fn build_time(&self) -> Vec<&Dependency> {\n self.filter_by_tags(DependencyTag::BUILD, DependencyTag::empty())\n }\n}\n"], ["/sps/sps-common/src/error.rs", "use std::sync::Arc;\n\nuse thiserror::Error;\n\n#[derive(Error, Debug, Clone)]\npub enum SpsError {\n #[error(\"I/O Error: {0}\")]\n Io(#[from] Arc),\n\n #[error(\"HTTP Request Error: {0}\")]\n Http(#[from] Arc),\n\n #[error(\"JSON Parsing Error: {0}\")]\n Json(#[from] Arc),\n\n #[error(\"Semantic Versioning Error: {0}\")]\n SemVer(#[from] Arc),\n\n #[error(\"Object File Error: {0}\")]\n Object(#[from] Arc),\n\n #[error(\"Configuration Error: {0}\")]\n Config(String),\n\n #[error(\"API Error: {0}\")]\n Api(String),\n\n #[error(\"API Request Error: {0}\")]\n ApiRequestError(String),\n\n #[error(\"DownloadError: Failed to download '{0}' from '{1}': {2}\")]\n DownloadError(String, String, String),\n\n #[error(\"Cache Error: {0}\")]\n Cache(String),\n\n #[error(\"Resource Not Found: {0}\")]\n NotFound(String),\n\n #[error(\"Installation Error: {0}\")]\n InstallError(String),\n\n #[error(\"Generic Error: {0}\")]\n Generic(String),\n\n #[error(\"HttpError: {0}\")]\n HttpError(String),\n\n #[error(\"Checksum Mismatch: {0}\")]\n ChecksumMismatch(String),\n\n #[error(\"Validation Error: {0}\")]\n ValidationError(String),\n\n #[error(\"Checksum Error: {0}\")]\n ChecksumError(String),\n\n #[error(\"Parsing Error in {0}: {1}\")]\n ParseError(&'static str, String),\n\n #[error(\"Version error: {0}\")]\n VersionError(String),\n\n #[error(\"Dependency Error: {0}\")]\n DependencyError(String),\n\n #[error(\"Build environment setup failed: {0}\")]\n BuildEnvError(String),\n\n #[error(\"IoError: {0}\")]\n IoError(String),\n\n #[error(\"Failed to execute command: {0}\")]\n CommandExecError(String),\n\n #[error(\"Mach-O Error: {0}\")]\n MachOError(String),\n\n #[error(\"Mach-O Modification Error: {0}\")]\n MachOModificationError(String),\n\n #[error(\"Mach-O Relocation Error: Path too long - {0}\")]\n PathTooLongError(String),\n\n #[error(\"Codesign Error: {0}\")]\n CodesignError(String),\n}\n\nimpl From for SpsError {\n fn from(err: std::io::Error) -> Self {\n SpsError::Io(Arc::new(err))\n }\n}\n\nimpl From for SpsError {\n fn from(err: reqwest::Error) -> Self {\n SpsError::Http(Arc::new(err))\n }\n}\n\nimpl From for SpsError {\n fn from(err: serde_json::Error) -> Self {\n SpsError::Json(Arc::new(err))\n }\n}\n\nimpl From for SpsError {\n fn from(err: semver::Error) -> Self {\n SpsError::SemVer(Arc::new(err))\n }\n}\n\nimpl From for SpsError {\n fn from(err: object::read::Error) -> Self {\n SpsError::Object(Arc::new(err))\n }\n}\n\npub type Result = std::result::Result;\n"], ["/sps/sps-common/src/model/artifact.rs", "// sps-common/src/model/artifact.rs\nuse std::path::PathBuf;\n\nuse serde::{Deserialize, Serialize};\n\n/// Represents an item installed or managed by sps, recorded in the manifest.\n#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)] // Added Hash\n#[serde(tag = \"type\", rename_all = \"snake_case\")]\npub enum InstalledArtifact {\n /// The main application bundle (e.g., in /Applications).\n AppBundle { path: PathBuf },\n /// A command-line binary symlinked into the prefix's bin dir.\n BinaryLink {\n link_path: PathBuf,\n target_path: PathBuf,\n },\n /// A man page symlinked into the prefix's man dir.\n ManpageLink {\n link_path: PathBuf,\n target_path: PathBuf,\n },\n /// A resource moved to a standard system/user location (e.g., Font, PrefPane).\n MovedResource { path: PathBuf },\n /// A macOS package receipt ID managed by pkgutil.\n PkgUtilReceipt { id: String },\n /// A launchd service (Agent/Daemon).\n Launchd {\n label: String,\n path: Option,\n }, // Path is the plist file\n /// A symlink created within the Caskroom pointing to the actual installed artifact.\n /// Primarily for internal reference and potentially easier cleanup if needed.\n CaskroomLink {\n link_path: PathBuf,\n target_path: PathBuf,\n },\n /// A file copied *into* the Caskroom (e.g., a .pkg installer).\n CaskroomReference { path: PathBuf },\n}\n\n// Optional: Helper methods if needed\n// impl InstalledArtifact { ... }\n"], ["/sps/sps-net/src/lib.rs", "// spm-fetch/src/lib.rs\npub mod api;\npub mod http;\npub mod oci;\npub mod validation;\n\n// Re-export necessary types from sps-core IF using Option A from Step 3\n// If using Option B (DTOs), you wouldn't depend on sps-core here for models.\n// Re-export the public fetching functions - ensure they are `pub`\npub use api::{\n fetch_all_casks, fetch_all_formulas, fetch_cask, fetch_formula, get_cask, /* ... */\n get_formula,\n};\npub use http::{fetch_formula_source_or_bottle, fetch_resource /* ... */};\npub use oci::{build_oci_client /* ... */, download_oci_blob, fetch_oci_manifest_index};\npub use sps_common::{\n model::{\n cask::{Sha256Field, UrlField},\n formula::ResourceSpec,\n Cask, Formula,\n }, // Example types needed\n {\n cache::Cache,\n error::{Result, SpsError},\n Config,\n }, // Need Config, Result, SpsError, Cache\n};\n\npub use crate::validation::{validate_url, verify_checksum, verify_content_type /* ... */};\n"], ["/sps/sps-common/src/dependency/requirement.rs", "// **File:** sps-core/src/dependency/requirement.rs (New file)\nuse std::fmt;\n\nuse serde::{Deserialize, Serialize};\n\n#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]\npub enum Requirement {\n MacOS(String),\n Xcode(String),\n Other(String),\n}\n\nimpl fmt::Display for Requirement {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n match self {\n Self::MacOS(v) => write!(f, \"macOS >= {v}\"),\n Self::Xcode(v) => write!(f, \"Xcode >= {v}\"),\n Self::Other(s) => write!(f, \"Requirement: {s}\"),\n }\n }\n}\n"], ["/sps/sps-common/src/lib.rs", "// sps-common/src/lib.rs\npub mod cache;\npub mod config;\npub mod dependency;\npub mod error;\npub mod formulary;\npub mod keg;\npub mod model;\npub mod pipeline;\n// Optional: pub mod dependency_def;\n\n// Re-export key types\npub use cache::Cache;\npub use config::Config;\npub use error::{Result, SpsError};\npub use model::{Cask, Formula, InstalledArtifact}; // etc.\n // Optional: pub use dependency_def::{Dependency, DependencyTag};\n"], ["/sps/sps-core/src/lib.rs", "// sps-core/src/lib.rs\n\n// Declare the top-level modules within the library crate\npub mod build;\npub mod check;\npub mod install;\npub mod pipeline;\npub mod uninstall;\npub mod upgrade; // New\n#[cfg(target_os = \"macos\")]\npub mod utils; // New\n //pub mod utils;\n\n// Re-export key types for easier use by the CLI crate\n// Define InstallTargetIdentifier here or ensure it's public from cli/pipeline\n// For simplicity, let's define it here for now:\n\n// New\npub use uninstall::UninstallOptions; // New\n // New\n"], ["/sps/sps-core/src/pipeline/mod.rs", "pub mod engine;\npub mod worker;\n"], ["/sps/sps-core/src/install/mod.rs", "// ===== sps-core/src/build/mod.rs =====\n// Main module for build functionality\n// Removed deprecated functions and re-exports.\n\nuse std::path::PathBuf;\n\nuse sps_common::config::Config;\nuse sps_common::model::formula::Formula;\n\n// --- Submodules ---\npub mod bottle;\npub mod cask;\npub mod devtools;\npub mod extract;\n\n// --- Path helpers using Config ---\npub fn get_formula_opt_path(formula: &Formula, config: &Config) -> PathBuf {\n // Use new Config method\n config.formula_opt_path(formula.name())\n}\n\n// --- DEPRECATED EXTRACTION FUNCTIONS REMOVED ---\n"], ["/sps/sps-common/src/model/mod.rs", "// src/model/mod.rs\n// Declares the modules within the model directory.\nuse std::sync::Arc;\n\npub mod artifact;\npub mod cask;\npub mod formula;\npub mod tap;\npub mod version;\n\n// Re-export\npub use artifact::InstalledArtifact;\npub use cask::Cask;\npub use formula::Formula;\n\n#[derive(Debug, Clone)]\npub enum InstallTargetIdentifier {\n Formula(Arc),\n Cask(Arc),\n}\n"], ["/sps/sps-common/src/dependency/mod.rs", "pub mod definition; // Renamed from 'dependency'\npub mod requirement;\npub mod resolver;\n\n// Re-export key types for easier access\npub use definition::{Dependency, DependencyExt, DependencyTag}; // Updated source module\npub use requirement::Requirement;\npub use resolver::{\n DependencyResolver, ResolutionContext, ResolutionStatus, ResolvedDependency, ResolvedGraph,\n};\n"], ["/sps/sps-core/src/utils/mod.rs", "#[cfg(target_os = \"macos\")]\npub mod applescript;\n#[cfg(target_os = \"macos\")]\npub mod xattr;\n"], ["/sps/sps-core/src/uninstall/mod.rs", "// sps-core/src/uninstall/mod.rs\n\npub mod cask;\npub mod common;\npub mod formula;\n\n// Re-export key functions and types\npub use cask::{uninstall_cask_artifacts, zap_cask_artifacts};\npub use common::UninstallOptions;\npub use formula::uninstall_formula_artifacts;\n"], ["/sps/sps-core/src/install/cask/artifacts/mod.rs", "pub mod app;\npub mod audio_unit_plugin;\npub mod binary;\npub mod colorpicker;\npub mod dictionary;\npub mod font;\npub mod input_method;\npub mod installer;\npub mod internet_plugin;\npub mod keyboard_layout;\npub mod manpage;\npub mod mdimporter;\npub mod pkg;\npub mod preflight;\npub mod prefpane;\npub mod qlplugin;\npub mod screen_saver;\npub mod service;\npub mod suite;\npub mod uninstall;\npub mod vst3_plugin;\npub mod vst_plugin;\npub mod zap;\n\n// Re‑export a single enum if you like:\npub use self::app::install_app_from_staged;\npub use self::audio_unit_plugin::install_audio_unit_plugin;\npub use self::binary::install_binary;\npub use self::colorpicker::install_colorpicker;\npub use self::dictionary::install_dictionary;\npub use self::font::install_font;\npub use self::input_method::install_input_method;\npub use self::installer::run_installer;\npub use self::internet_plugin::install_internet_plugin;\npub use self::keyboard_layout::install_keyboard_layout;\npub use self::manpage::install_manpage;\npub use self::mdimporter::install_mdimporter;\npub use self::pkg::install_pkg_from_path;\npub use self::preflight::run_preflight;\npub use self::prefpane::install_prefpane;\npub use self::qlplugin::install_qlplugin;\npub use self::screen_saver::install_screen_saver;\npub use self::service::install_service;\npub use self::suite::install_suite;\npub use self::uninstall::record_uninstall;\npub use self::vst3_plugin::install_vst3_plugin;\npub use self::vst_plugin::install_vst_plugin;\n"], ["/sps/sps-core/src/check/mod.rs", "pub mod installed;\npub mod update;\n\npub use installed::{InstalledPackageInfo, PackageType};\npub use update::UpdateInfo;\n"], ["/sps/sps-core/src/upgrade/mod.rs", "// sps-core/src/upgrade/mod.rs\n\npub mod bottle;\npub mod cask;\npub mod source;\n\n// Re-export key upgrade functions\npub use self::bottle::upgrade_bottle_formula;\npub use self::cask::upgrade_cask_package;\npub use self::source::upgrade_source_formula;\n"], ["/sps/sps/src/pipeline.rs", "pub mod downloader;\npub mod planner;\npub mod runner;\n"]], "task_instance_info": {"created_time": "2025-08-21 01:45:07", "created_task_model": "DeepSeek-R1", "function_skeleton": "pub fn start_worker_pool_manager (\n config: Config,\n cache: Arc,\n worker_job_rx: CrossbeamReceiver,\n event_tx: broadcast::Sender,\n success_count: Arc,\n fail_count: Arc,\n) -> SpsResult<()> {}", "code_description": "This code segment functions to: Coordinate parallel task processing by initializing a thread pool based on system resources, distributing incoming tasks to worker threads, managing task lifecycle events, and tracking success/failure metrics through atomic counters while propagating state changes via event notifications."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```rust\n[TASK_BEGIN]\n let pool = ThreadPool::new(config.worker_threads);\n\n loop {\n let job = match worker_job_rx.recv() {\n Ok(job) => job,\n Err(_) => break,\n };\n\n let cache = Arc::clone(&cache);\n let event_tx = event_tx.clone();\n let success_count = Arc::clone(&success_count);\n let fail_count = Arc::clone(&fail_count);\n\n pool.execute(move || {\n worker::process_job(job, cache, event_tx, success_count, fail_count);\n });\n }\n\n Ok(())\n[TASK_END]\n```", "inference_time": "2025-08-21 01-45-40"}, "editdistance_info": {"edit_distance": 14.4828, "calculate_time": "2025-08-21 01:45:40", "true_code_clean": "pub fn start_worker_pool_manager(\n config: Config,\n cache: Arc,\n worker_job_rx: CrossbeamReceiver,\n event_tx: broadcast::Sender,\n success_count: Arc,\n fail_count: Arc,\n) -> SpsResult<()> {\n let num_workers = std::cmp::max(1, num_cpus::get_physical().saturating_sub(1)).min(6);\n let pool = ThreadPool::new(num_workers);\n debug!(\n \"Core worker pool manager started with {} workers.\",\n num_workers\n );\n debug!(\"Worker pool created.\");\n for worker_job in worker_job_rx {\n let job_id = worker_job.request.target_id.clone();\n debug!(\n \"[{}] Received job from channel, preparing to submit to pool.\",\n job_id\n );\n let config_clone = config.clone();\n let cache_clone = Arc::clone(&cache);\n let event_tx_clone = event_tx.clone();\n let success_count_clone = Arc::clone(&success_count);\n let fail_count_clone = Arc::clone(&fail_count);\n let _ = event_tx_clone.send(PipelineEvent::JobProcessingStarted {\n target_id: job_id.clone(),\n });\n debug!(\"[{}] Submitting job to worker pool.\", job_id);\n pool.execute(move || {\n let job_result = worker::execute_sync_job(\n worker_job,\n &config_clone,\n cache_clone,\n event_tx_clone.clone(),\n );\n let job_id_for_log = job_id.clone();\n debug!(\n \"[{}] Worker job execution finished (execute_sync_job returned), result ok: {}\",\n job_id_for_log,\n job_result.is_ok()\n );\n let job_id_for_log = job_id.clone();\n match job_result {\n Ok((final_action, pkg_type)) => {\n success_count_clone.fetch_add(1, Ordering::Relaxed);\n debug!(\"[{}] Worker finished successfully.\", job_id);\n let _ = event_tx_clone.send(PipelineEvent::JobSuccess {\n target_id: job_id,\n action: final_action,\n pkg_type,\n });\n debug!(\"[{}] Worker result event sent.\", job_id_for_log);\n }\n Err(boxed) => {\n let (final_action, err) = *boxed;\n fail_count_clone.fetch_add(1, Ordering::Relaxed);\n let _ = event_tx_clone.send(PipelineEvent::JobFailed {\n target_id: job_id,\n action: final_action,\n error: err.to_string(),\n });\n debug!(\"[{}] Worker result event sent.\", job_id_for_log);\n }\n }\n debug!(\"[{}] Worker closure scope ending.\", job_id_for_log);\n });\n }\n pool.join();\n Ok(())\n}", "predict_code_clean": "let pool = ThreadPool::new(config.worker_threads);\n loop {\n let job = match worker_job_rx.recv() {\n Ok(job) => job,\n Err(_) => break,\n };\n let cache = Arc::clone(&cache);\n let event_tx = event_tx.clone();\n let success_count = Arc::clone(&success_count);\n let fail_count = Arc::clone(&fail_count);\n pool.execute(move || {\n worker::process_job(job, cache, event_tx, success_count, fail_count);\n });\n }\n Ok(())"}} {"repo_name": "sps", "file_name": "/sps/sps/src/pipeline/planner.rs", "inference_info": {"prefix_code": "// sps/src/pipeline/planner.rs\nuse std::collections::{HashMap, HashSet, VecDeque};\nuse std::path::{Path, PathBuf};\nuse std::sync::Arc;\n\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::dependency::resolver::{\n DependencyResolver, NodeInstallStrategy, PerTargetInstallPreferences, ResolutionContext,\n ResolutionStatus, ResolvedGraph,\n};\nuse sps_common::error::{Result as SpsResult, SpsError};\nuse sps_common::formulary::Formulary;\nuse sps_common::keg::KegRegistry;\nuse sps_common::model::{Cask, Formula, InstallTargetIdentifier};\nuse sps_common::pipeline::{JobAction, PipelineEvent, PlannedJob, PlannedOperations};\nuse sps_core::check::installed::{self, InstalledPackageInfo, PackageType as CorePackageType};\nuse sps_core::check::update::{self, UpdateInfo};\nuse tokio::sync::broadcast;\nuse tokio::task::JoinSet;\nuse tracing::{debug, error as trace_error, instrument, warn};\n\nuse super::runner::{get_panic_message, CommandType, PipelineFlags};\n\npub(crate) type PlanResult = SpsResult;\n\n#[derive(Debug, Default)]\nstruct IntermediatePlan {\n initial_ops: HashMap)>,\n errors: Vec<(String, SpsError)>,\n already_satisfied: HashSet,\n processed_globally: HashSet,\n private_store_sources: HashMap,\n}\n\n#[instrument(skip(cache))]\npub(crate) async fn fetch_target_definitions(\n names: &[String],\n cache: Arc,\n) -> HashMap> {\n let mut results = HashMap::new();\n if names.is_empty() {\n return results;\n }\n let mut futures = JoinSet::new();\n\n let formulae_map_handle = tokio::spawn(load_or_fetch_formulae_map(cache.clone()));\n let casks_map_handle = tokio::spawn(load_or_fetch_casks_map(cache.clone()));\n\n let formulae_map = match formulae_map_handle.await {\n Ok(Ok(map)) => Some(map),\n Ok(Err(e)) => {\n debug!(\"[FetchDefs] Failed to load/fetch full formulae list: {}\", e);\n None\n }\n Err(e) => {\n warn!(\n \"[FetchDefs] Formulae map loading task panicked: {}\",\n get_panic_message(e.into_panic()) // Ensure get_panic_message is accessible\n );\n None\n }\n };\n let casks_map = match casks_map_handle.await {\n Ok(Ok(map)) => Some(map),\n Ok(Err(e)) => {\n debug!(\"[FetchDefs] Failed to load/fetch full casks list: {}\", e);\n None\n }\n Err(e) => {\n warn!(\n \"[FetchDefs] Casks map loading task panicked: {}\",\n get_panic_message(e.into_panic()) // Ensure get_panic_message is accessible\n );\n None\n }\n };\n\n for name_str in names {\n let name_owned = name_str.to_string();\n let local_formulae_map = formulae_map.clone();\n let local_casks_map = casks_map.clone();\n\n futures.spawn(async move {\n if let Some(ref map) = local_formulae_map {\n if let Some(f_arc) = map.get(&name_owned) {\n return (name_owned, Ok(InstallTargetIdentifier::Formula(f_arc.clone())));\n }\n }\n if let Some(ref map) = local_casks_map {\n if let Some(c_arc) = map.get(&name_owned) {\n return (name_owned, Ok(InstallTargetIdentifier::Cask(c_arc.clone())));\n }\n }\n debug!(\"[FetchDefs] Definition for '{}' not found in cached lists, fetching directly from API...\", name_owned);\n match sps_net::api::get_formula(&name_owned).await {\n Ok(formula_obj) => return (name_owned, Ok(InstallTargetIdentifier::Formula(Arc::new(formula_obj)))),\n Err(SpsError::NotFound(_)) => {}\n Err(e) => return (name_owned, Err(e)),\n }\n match sps_net::api::get_cask(&name_owned).await {\n Ok(cask_obj) => (name_owned, Ok(InstallTargetIdentifier::Cask(Arc::new(cask_obj)))),\n Err(SpsError::NotFound(_)) => (name_owned.clone(), Err(SpsError::NotFound(format!(\"Formula or Cask '{name_owned}' not found\")))),\n Err(e) => (name_owned, Err(e)),\n }\n });\n }\n\n while let Some(res) = futures.join_next().await {\n match res {\n Ok((name, result)) => {\n results.insert(name, result);\n }\n Err(e) => {\n let panic_message = get_panic_message(e.into_panic());\n trace_error!(\n \"[FetchDefs] Task panicked during definition fetch: {}\",\n panic_message\n );\n results.insert(\n format!(\"[unknown_target_due_to_panic_{}]\", results.len()),\n Err(SpsError::Generic(format!(\n \"Definition fetching task panicked: {panic_message}\"\n ))),\n );\n }\n }\n }\n results\n}\n\nasync fn load_or_fetch_formulae_map(cache: Arc) -> SpsResult>> {\n match cache.load_raw(\"formula.json\") {\n Ok(data) => {\n let formulas: Vec = serde_json::from_str(&data)\n .map_err(|e| SpsError::Cache(format!(\"Parse cached formula.json failed: {e}\")))?;\n Ok(formulas\n .into_iter()\n .map(|f| (f.name.clone(), Arc::new(f)))\n .collect())\n }\n Err(_) => {\n debug!(\"[FetchDefs] Cache miss for formula.json, fetching from API...\");\n let raw_data = sps_net::api::fetch_all_formulas().await?;\n if let Err(e) = cache.store_raw(\"formula.json\", &raw_data) {\n warn!(\"Failed to store formula.json in cache: {}\", e);\n }\n let formulas: Vec =\n serde_json::from_str(&raw_data).map_err(|e| SpsError::Json(Arc::new(e)))?;\n Ok(formulas\n .into_iter()\n .map(|f| (f.name.clone(), Arc::new(f)))\n .collect())\n }\n }\n}\n\nasync fn load_or_fetch_casks_map(cache: Arc) -> SpsResult>> {\n match cache.load_raw(\"cask.json\") {\n Ok(data) => {\n let casks: Vec = serde_json::from_str(&data)\n .map_err(|e| SpsError::Cache(format!(\"Parse cached cask.json failed: {e}\")))?;\n Ok(casks\n .into_iter()\n .map(|c| (c.token.clone(), Arc::new(c)))\n .collect())\n }\n Err(_) => {\n debug!(\"[FetchDefs] Cache miss for cask.json, fetching from API...\");\n let raw_data = sps_net::api::fetch_all_casks().await?;\n if let Err(e) = cache.store_raw(\"cask.json\", &raw_data) {\n warn!(\"Failed to store cask.json in cache: {}\", e);\n }\n let casks: Vec =\n serde_json::from_str(&raw_data).map_err(|e| SpsError::Json(Arc::new(e)))?;\n Ok(casks\n .into_iter()\n .map(|c| (c.token.clone(), Arc::new(c)))\n .collect())\n }\n }\n}\n\npub(crate) struct OperationPlanner<'a> {\n config: &'a Config,\n cache: Arc,\n flags: &'a PipelineFlags,\n event_tx: broadcast::Sender,\n}\n\nimpl<'a> OperationPlanner<'a> {\n pub fn new(\n config: &'a Config,\n cache: Arc,\n flags: &'a PipelineFlags,\n event_tx: broadcast::Sender,\n ) -> Self {\n Self {\n config,\n cache,\n flags,\n event_tx,\n }\n }\n\n fn get_previous_installation_type(&self, old_keg_path: &Path) -> Option {\n let receipt_path = old_keg_path.join(\"INSTALL_RECEIPT.json\");\n if !receipt_path.is_file() {\n tracing::debug!(\n \"No INSTALL_RECEIPT.json found at {} for previous version.\",\n receipt_path.display()\n );\n return None;\n }\n\n match std::fs::read_to_string(&receipt_path) {\n Ok(content) => match serde_json::from_str::(&content) {\n Ok(json_value) => {\n let inst_type = json_value\n .get(\"installation_type\")\n .and_then(|it| it.as_str())\n .map(String::from);\n tracing::debug!(\n \"Previous installation type for {}: {:?}\",\n old_keg_path.display(),\n inst_type\n );\n inst_type\n }\n Err(e) => {\n tracing::warn!(\"Failed to parse INSTALL_RECEIPT.json at {}: {}. Cannot determine previous installation type.\", receipt_path.display(), e);\n None\n }\n },\n Err(e) => {\n tracing::warn!(\"Failed to read INSTALL_RECEIPT.json at {}: {}. Cannot determine previous installation type.\", receipt_path.display(), e);\n None\n }\n }\n }\n\n async fn check_installed_status(&self, name: &str) -> PlanResult> {\n installed::get_installed_package(name, self.config).await\n }\n\n async fn determine_cask_private_store_source(\n &self,\n name: &str,\n version_for_path: &str,\n ) -> Option {\n let cask_def_res = fetch_target_definitions(&[name.to_string()], self.cache.clone())\n .await\n .remove(name);\n\n if let Some(Ok(InstallTargetIdentifier::Cask(cask_arc))) = cask_def_res {\n if let Some(artifacts) = &cask_arc.artifacts {\n for artifact_entry in artifacts {\n if let Some(app_array) = artifact_entry.get(\"app\").and_then(|v| v.as_array()) {\n if let Some(app_name_val) = app_array.first() {\n if let Some(app_name_str) = app_name_val.as_str() {\n let private_path = self.config.cask_store_app_path(\n name,\n version_for_path,\n app_name_str,\n );\n if private_path.exists() && private_path.is_dir() {\n debug!(\"[Planner] Found reusable Cask private store bundle for {} version {}: {}\", name, version_for_path, private_path.display());\n return Some(private_path);\n }\n }\n }\n break;\n }\n }\n }\n }\n None\n }\n\n ", "suffix_code": "\n\n async fn plan_for_reinstall(&self, targets: &[String]) -> PlanResult {\n let mut plan = IntermediatePlan::default();\n for name in targets {\n if plan.processed_globally.contains(name) {\n continue;\n }\n match self.check_installed_status(name).await {\n Ok(Some(installed_info)) => {\n if installed_info.pkg_type == CorePackageType::Cask {\n if let Some(private_path) = self\n .determine_cask_private_store_source(name, &installed_info.version)\n .await\n {\n plan.private_store_sources\n .insert(name.clone(), private_path);\n }\n }\n plan.initial_ops.insert(\n name.clone(),\n (\n JobAction::Reinstall {\n version: installed_info.version.clone(),\n current_install_path: installed_info.path.clone(),\n },\n None,\n ),\n );\n }\n Ok(None) => {\n plan.errors.push((\n name.clone(),\n SpsError::NotFound(format!(\"Cannot reinstall '{name}': not installed.\")),\n ));\n plan.processed_globally.insert(name.clone());\n }\n Err(e) => {\n plan.errors.push((\n name.clone(),\n SpsError::Generic(format!(\"Failed to check status for '{name}': {e}\")),\n ));\n plan.processed_globally.insert(name.clone());\n }\n }\n }\n Ok(plan)\n }\n\n async fn plan_for_upgrade(\n &self,\n targets: &[String],\n all: bool,\n ) -> PlanResult {\n let mut plan = IntermediatePlan::default();\n let packages_to_check = if all {\n installed::get_installed_packages(self.config)\n .await\n .map_err(|e| {\n plan.errors.push((\n \"\".to_string(),\n SpsError::Generic(format!(\"Failed to get installed packages: {e}\")),\n ));\n e\n })?\n } else {\n let mut specific = Vec::new();\n for name in targets {\n match self.check_installed_status(name).await {\n Ok(Some(info)) => {\n if info.pkg_type == CorePackageType::Cask {\n let manifest_path = info.path.join(\"CASK_INSTALL_MANIFEST.json\");\n if manifest_path.is_file() {\n if let Ok(manifest_str) = std::fs::read_to_string(&manifest_path) {\n if let Ok(manifest_json) =\n serde_json::from_str::(&manifest_str)\n {\n if !manifest_json\n .get(\"is_installed\")\n .and_then(|v| v.as_bool())\n .unwrap_or(true)\n {\n debug!(\"Skipping upgrade for Cask '{}' as its manifest indicates it's not fully installed.\", name);\n plan.processed_globally.insert(name.clone());\n continue;\n }\n }\n }\n }\n }\n specific.push(info);\n }\n Ok(None) => {\n plan.errors.push((\n name.to_string(),\n SpsError::NotFound(format!(\"Cannot upgrade '{name}': not installed.\")),\n ));\n plan.processed_globally.insert(name.clone());\n }\n Err(e) => {\n plan.errors.push((\n name.to_string(),\n SpsError::Generic(format!(\"Failed to check status for '{name}': {e}\")),\n ));\n plan.processed_globally.insert(name.clone());\n }\n }\n }\n specific\n };\n\n if packages_to_check.is_empty() {\n return Ok(plan);\n }\n\n match update::check_for_updates(&packages_to_check, &self.cache, self.config).await {\n Ok(updates) => {\n let update_map: HashMap =\n updates.into_iter().map(|u| (u.name.clone(), u)).collect();\n\n debug!(\n \"[Planner] Found {} available updates out of {} packages checked\",\n update_map.len(),\n packages_to_check.len()\n );\n debug!(\n \"[Planner] Available updates: {:?}\",\n update_map.keys().collect::>()\n );\n\n for p_info in packages_to_check {\n if plan.processed_globally.contains(&p_info.name) {\n continue;\n }\n if let Some(ui) = update_map.get(&p_info.name) {\n debug!(\n \"[Planner] Adding upgrade job for '{}': {} -> {}\",\n p_info.name, p_info.version, ui.available_version\n );\n plan.initial_ops.insert(\n p_info.name.clone(),\n (\n JobAction::Upgrade {\n from_version: p_info.version.clone(),\n old_install_path: p_info.path.clone(),\n },\n Some(ui.target_definition.clone()),\n ),\n );\n // Don't mark packages with updates as processed_globally\n // so they can be included in the final job list\n } else {\n debug!(\n \"[Planner] No update available for '{}', marking as already satisfied\",\n p_info.name\n );\n plan.already_satisfied.insert(p_info.name.clone());\n // Only mark packages without updates as processed_globally\n plan.processed_globally.insert(p_info.name.clone());\n }\n }\n }\n Err(e) => {\n plan.errors.push((\n \"[Update Check]\".to_string(),\n SpsError::Generic(format!(\"Failed to check for updates: {e}\")),\n ));\n }\n }\n Ok(plan)\n }\n\n // This now returns sps_common::pipeline::PlannedOperations\n pub async fn plan_operations(\n &self,\n initial_targets: &[String],\n command_type: CommandType,\n ) -> PlanResult {\n debug!(\n \"[Planner] Starting plan_operations with command_type: {:?}, targets: {:?}\",\n command_type, initial_targets\n );\n\n let mut intermediate_plan = match command_type {\n CommandType::Install => self.plan_for_install(initial_targets).await?,\n CommandType::Reinstall => self.plan_for_reinstall(initial_targets).await?,\n CommandType::Upgrade { all } => {\n debug!(\"[Planner] Calling plan_for_upgrade with all={}\", all);\n let plan = self.plan_for_upgrade(initial_targets, all).await?;\n debug!(\"[Planner] plan_for_upgrade returned with {} initial_ops, {} errors, {} already_satisfied\",\n plan.initial_ops.len(), plan.errors.len(), plan.already_satisfied.len());\n debug!(\n \"[Planner] Initial ops: {:?}\",\n plan.initial_ops.keys().collect::>()\n );\n debug!(\"[Planner] Already satisfied: {:?}\", plan.already_satisfied);\n plan\n }\n };\n\n let definitions_to_fetch: Vec = intermediate_plan\n .initial_ops\n .iter()\n .filter(|(name, (_, opt_def))| {\n opt_def.is_none() && !intermediate_plan.processed_globally.contains(*name)\n })\n .map(|(name, _)| name.clone())\n .collect();\n\n if !definitions_to_fetch.is_empty() {\n let fetched_defs =\n fetch_target_definitions(&definitions_to_fetch, self.cache.clone()).await;\n for (name, result) in fetched_defs {\n match result {\n Ok(target_def) => {\n if let Some((_action, opt_install_target)) =\n intermediate_plan.initial_ops.get_mut(&name)\n {\n *opt_install_target = Some(target_def);\n }\n }\n Err(e) => {\n intermediate_plan.errors.push((\n name.clone(),\n SpsError::Generic(format!(\"Failed to get definition for target: {e}\")),\n ));\n intermediate_plan.processed_globally.insert(name);\n }\n }\n }\n }\n self.event_tx\n .send(PipelineEvent::DependencyResolutionStarted)\n .ok();\n\n let mut formulae_for_resolution: HashMap = HashMap::new();\n let mut cask_deps_map: HashMap> = HashMap::new();\n let mut cask_processing_queue: VecDeque = VecDeque::new();\n\n for (name, (action, opt_def)) in &intermediate_plan.initial_ops {\n if intermediate_plan.processed_globally.contains(name) {\n continue;\n }\n\n // Handle both normal formula targets and upgrade targets\n match opt_def {\n Some(target @ InstallTargetIdentifier::Formula(_)) => {\n debug!(\n \"[Planner] Adding formula '{}' to resolution list with action {:?}\",\n name, action\n );\n formulae_for_resolution.insert(name.clone(), target.clone());\n }\n Some(InstallTargetIdentifier::Cask(c_arc)) => {\n debug!(\"[Planner] Adding cask '{}' to processing queue\", name);\n cask_processing_queue.push_back(name.clone());\n cask_deps_map.insert(name.clone(), c_arc.clone());\n }\n None => {\n if !intermediate_plan\n .errors\n .iter()\n .any(|(err_name, _)| err_name == name)\n {\n intermediate_plan.errors.push((\n name.clone(),\n SpsError::Generic(format!(\n \"Definition for '{name}' still missing after fetch attempt.\"\n )),\n ));\n intermediate_plan.processed_globally.insert(name.clone());\n }\n }\n }\n }\n\n let mut processed_casks_for_deps_pass: HashSet =\n intermediate_plan.processed_globally.clone();\n\n while let Some(cask_token) = cask_processing_queue.pop_front() {\n if processed_casks_for_deps_pass.contains(&cask_token) {\n continue;\n }\n processed_casks_for_deps_pass.insert(cask_token.clone());\n\n let cask_arc = match cask_deps_map.get(&cask_token) {\n Some(c) => c.clone(),\n None => {\n match fetch_target_definitions(\n std::slice::from_ref(&cask_token),\n self.cache.clone(),\n )\n .await\n .remove(&cask_token)\n {\n Some(Ok(InstallTargetIdentifier::Cask(c))) => {\n cask_deps_map.insert(cask_token.clone(), c.clone());\n c\n }\n Some(Err(e)) => {\n intermediate_plan.errors.push((cask_token.clone(), e));\n intermediate_plan\n .processed_globally\n .insert(cask_token.clone());\n continue;\n }\n _ => {\n intermediate_plan.errors.push((\n cask_token.clone(),\n SpsError::NotFound(format!(\n \"Cask definition for dependency '{cask_token}' not found.\"\n )),\n ));\n intermediate_plan\n .processed_globally\n .insert(cask_token.clone());\n continue;\n }\n }\n }\n };\n\n if let Some(deps) = &cask_arc.depends_on {\n for formula_dep_name in &deps.formula {\n if formulae_for_resolution.contains_key(formula_dep_name)\n || intermediate_plan\n .errors\n .iter()\n .any(|(n, _)| n == formula_dep_name)\n || intermediate_plan\n .already_satisfied\n .contains(formula_dep_name)\n {\n continue;\n }\n match fetch_target_definitions(\n std::slice::from_ref(formula_dep_name),\n self.cache.clone(),\n )\n .await\n .remove(formula_dep_name)\n {\n Some(Ok(target_def @ InstallTargetIdentifier::Formula(_))) => {\n formulae_for_resolution.insert(formula_dep_name.clone(), target_def);\n }\n Some(Ok(InstallTargetIdentifier::Cask(_))) => {\n intermediate_plan.errors.push((\n formula_dep_name.clone(),\n SpsError::Generic(format!(\n \"Dependency '{formula_dep_name}' of Cask '{cask_token}' is unexpectedly a Cask itself.\"\n )),\n ));\n intermediate_plan\n .processed_globally\n .insert(formula_dep_name.clone());\n }\n Some(Err(e)) => {\n intermediate_plan.errors.push((\n formula_dep_name.clone(),\n SpsError::Generic(format!(\n \"Failed def fetch for formula dep '{formula_dep_name}' of cask '{cask_token}': {e}\"\n )),\n ));\n intermediate_plan\n .processed_globally\n .insert(formula_dep_name.clone());\n }\n None => {\n intermediate_plan.errors.push((\n formula_dep_name.clone(),\n SpsError::NotFound(format!(\n \"Formula dep '{formula_dep_name}' for cask '{cask_token}' not found.\"\n )),\n ));\n intermediate_plan\n .processed_globally\n .insert(formula_dep_name.clone());\n }\n }\n }\n for dep_cask_token in &deps.cask {\n if !processed_casks_for_deps_pass.contains(dep_cask_token)\n && !cask_processing_queue.contains(dep_cask_token)\n {\n cask_processing_queue.push_back(dep_cask_token.clone());\n }\n }\n }\n }\n\n let mut resolved_formula_graph_opt: Option> = None;\n if !formulae_for_resolution.is_empty() {\n let targets_for_resolver: Vec<_> = formulae_for_resolution.keys().cloned().collect();\n let formulary = Formulary::new(self.config.clone());\n let keg_registry = KegRegistry::new(self.config.clone());\n\n let per_target_prefs = PerTargetInstallPreferences {\n force_source_build_targets: if self.flags.build_from_source {\n targets_for_resolver.iter().cloned().collect()\n } else {\n HashSet::new()\n },\n force_bottle_only_targets: HashSet::new(),\n };\n\n // Create map of initial target actions for the resolver\n let initial_target_actions: HashMap = intermediate_plan\n .initial_ops\n .iter()\n .filter_map(|(name, (action, _))| {\n if targets_for_resolver.contains(name) {\n Some((name.clone(), action.clone()))\n } else {\n debug!(\"[Planner] WARNING: Target '{}' with action {:?} is not in targets_for_resolver!\", name, action);\n None\n }\n })\n .collect();\n\n debug!(\n \"[Planner] Created initial_target_actions map with {} entries: {:?}\",\n initial_target_actions.len(),\n initial_target_actions\n );\n debug!(\"[Planner] Targets for resolver: {:?}\", targets_for_resolver);\n\n let ctx = ResolutionContext {\n formulary: &formulary,\n keg_registry: &keg_registry,\n sps_prefix: self.config.sps_root(),\n include_optional: self.flags.include_optional,\n include_test: false,\n skip_recommended: self.flags.skip_recommended,\n initial_target_preferences: &per_target_prefs,\n build_all_from_source: self.flags.build_from_source,\n cascade_source_preference_to_dependencies: true,\n has_bottle_for_current_platform:\n sps_core::install::bottle::has_bottle_for_current_platform,\n initial_target_actions: &initial_target_actions,\n };\n\n let mut resolver = DependencyResolver::new(ctx);\n debug!(\"[Planner] Created DependencyResolver, calling resolve_targets...\");\n match resolver.resolve_targets(&targets_for_resolver) {\n Ok(g) => {\n debug!(\n \"[Planner] Dependency resolution succeeded! Install plan has {} items\",\n g.install_plan.len()\n );\n resolved_formula_graph_opt = Some(Arc::new(g));\n }\n Err(e) => {\n debug!(\"[Planner] Dependency resolution failed: {}\", e);\n let resolver_error_msg = e.to_string(); // Capture full error\n for n in targets_for_resolver {\n if !intermediate_plan\n .errors\n .iter()\n .any(|(err_n, _)| err_n == &n)\n {\n intermediate_plan.errors.push((\n n.clone(),\n SpsError::DependencyError(resolver_error_msg.clone()),\n ));\n }\n intermediate_plan.processed_globally.insert(n);\n }\n }\n }\n }\n self.event_tx\n .send(PipelineEvent::DependencyResolutionFinished)\n .ok();\n\n let mut final_planned_jobs: Vec = Vec::new();\n let mut names_processed_from_initial_ops = HashSet::new();\n\n debug!(\n \"[Planner] Processing {} initial_ops into final jobs\",\n intermediate_plan.initial_ops.len()\n );\n for (name, (action, opt_def)) in &intermediate_plan.initial_ops {\n debug!(\n \"[Planner] Processing initial op '{}': action={:?}, has_def={}\",\n name,\n action,\n opt_def.is_some()\n );\n\n if intermediate_plan.processed_globally.contains(name) {\n debug!(\"[Planner] Skipping '{}' - already processed globally\", name);\n continue;\n }\n // If an error was recorded for this specific initial target (e.g. resolver failed for\n // it, or def missing) ensure it's marked as globally processed and not\n // added to final_planned_jobs.\n if intermediate_plan\n .errors\n .iter()\n .any(|(err_name, _)| err_name == name)\n {\n debug!(\"[Planner] Skipping job for initial op '{}' as an error was recorded for it during planning.\", name);\n intermediate_plan.processed_globally.insert(name.clone());\n continue;\n }\n if intermediate_plan.already_satisfied.contains(name) {\n debug!(\n \"[Planner] Skipping job for initial op '{}' as it's already satisfied.\",\n name\n );\n intermediate_plan.processed_globally.insert(name.clone());\n continue;\n }\n\n match opt_def {\n Some(target_def) => {\n let is_source_build = determine_build_strategy_for_job(\n target_def,\n action,\n self.flags,\n resolved_formula_graph_opt.as_deref(),\n self,\n );\n\n final_planned_jobs.push(PlannedJob {\n target_id: name.clone(),\n target_definition: target_def.clone(),\n action: action.clone(),\n is_source_build,\n use_private_store_source: intermediate_plan\n .private_store_sources\n .get(name)\n .cloned(),\n });\n names_processed_from_initial_ops.insert(name.clone());\n }\n None => {\n tracing::error!(\"[Planner] CRITICAL: Definition missing for planned operation on '{}' but no error was recorded in intermediate_plan.errors. This should not happen.\", name);\n if !intermediate_plan\n .errors\n .iter()\n .any(|(err_n, _)| err_n == name)\n {\n intermediate_plan.errors.push((\n name.clone(),\n SpsError::Generic(\"Definition missing unexpectedly.\".into()),\n ));\n }\n intermediate_plan.processed_globally.insert(name.clone());\n }\n }\n }\n\n if let Some(graph) = resolved_formula_graph_opt.as_ref() {\n for dep_detail in &graph.install_plan {\n let dep_name = dep_detail.formula.name();\n\n if names_processed_from_initial_ops.contains(dep_name)\n || intermediate_plan.processed_globally.contains(dep_name)\n || final_planned_jobs.iter().any(|j| j.target_id == dep_name)\n {\n continue;\n }\n\n if intermediate_plan\n .errors\n .iter()\n .any(|(err_name, _)| err_name == dep_name)\n {\n tracing::debug!(\"[Planner] Skipping job for dependency '{}' due to a pre-existing error recorded for it.\", dep_name);\n intermediate_plan\n .processed_globally\n .insert(dep_name.to_string());\n continue;\n }\n if dep_detail.status == ResolutionStatus::Failed {\n tracing::debug!(\"[Planner] Skipping job for dependency '{}' as its resolution status is Failed. Adding to planner errors.\", dep_name);\n // Ensure this error is also captured if not already.\n if !intermediate_plan\n .errors\n .iter()\n .any(|(err_name, _)| err_name == dep_name)\n {\n intermediate_plan.errors.push((\n dep_name.to_string(),\n SpsError::DependencyError(format!(\n \"Resolution failed for dependency {dep_name}\"\n )),\n ));\n }\n intermediate_plan\n .processed_globally\n .insert(dep_name.to_string());\n continue;\n }\n\n if matches!(\n dep_detail.status,\n ResolutionStatus::Missing | ResolutionStatus::Requested\n ) {\n let is_source_build_for_dep = determine_build_strategy_for_job(\n &InstallTargetIdentifier::Formula(dep_detail.formula.clone()),\n &JobAction::Install,\n self.flags,\n Some(graph),\n self,\n );\n debug!(\n \"Planning install for new formula dependency '{}'. Source build: {}\",\n dep_name, is_source_build_for_dep\n );\n\n final_planned_jobs.push(PlannedJob {\n target_id: dep_name.to_string(),\n target_definition: InstallTargetIdentifier::Formula(\n dep_detail.formula.clone(),\n ),\n action: JobAction::Install,\n is_source_build: is_source_build_for_dep,\n use_private_store_source: None,\n });\n } else if dep_detail.status == ResolutionStatus::Installed {\n intermediate_plan\n .already_satisfied\n .insert(dep_name.to_string());\n }\n }\n }\n\n for (cask_token, cask_arc) in cask_deps_map {\n if names_processed_from_initial_ops.contains(&cask_token)\n || intermediate_plan.processed_globally.contains(&cask_token)\n || final_planned_jobs.iter().any(|j| j.target_id == cask_token)\n {\n continue;\n }\n\n match self.check_installed_status(&cask_token).await {\n Ok(None) => {\n final_planned_jobs.push(PlannedJob {\n target_id: cask_token.clone(),\n target_definition: InstallTargetIdentifier::Cask(cask_arc.clone()),\n action: JobAction::Install,\n is_source_build: false,\n use_private_store_source: intermediate_plan\n .private_store_sources\n .get(&cask_token)\n .cloned(),\n });\n }\n Ok(Some(_installed_info)) => {\n intermediate_plan\n .already_satisfied\n .insert(cask_token.clone());\n }\n Err(e) => {\n intermediate_plan.errors.push((\n cask_token.clone(),\n SpsError::Generic(format!(\n \"Failed check install status for cask dependency {cask_token}: {e}\"\n )),\n ));\n intermediate_plan\n .processed_globally\n .insert(cask_token.clone());\n }\n }\n }\n if let Some(graph) = resolved_formula_graph_opt.as_ref() {\n if !final_planned_jobs.is_empty() {\n sort_planned_jobs(&mut final_planned_jobs, graph);\n }\n }\n\n debug!(\n \"[Planner] Finishing plan_operations with {} jobs, {} errors, {} already_satisfied\",\n final_planned_jobs.len(),\n intermediate_plan.errors.len(),\n intermediate_plan.already_satisfied.len()\n );\n debug!(\n \"[Planner] Final jobs: {:?}\",\n final_planned_jobs\n .iter()\n .map(|j| &j.target_id)\n .collect::>()\n );\n\n Ok(PlannedOperations {\n jobs: final_planned_jobs,\n errors: intermediate_plan.errors,\n already_installed_or_up_to_date: intermediate_plan.already_satisfied,\n resolved_graph: resolved_formula_graph_opt,\n })\n }\n}\n\nfn determine_build_strategy_for_job(\n target_def: &InstallTargetIdentifier,\n action: &JobAction,\n flags: &PipelineFlags,\n resolved_graph: Option<&ResolvedGraph>,\n planner: &OperationPlanner,\n) -> bool {\n match target_def {\n InstallTargetIdentifier::Formula(formula_arc) => {\n if flags.build_from_source {\n return true;\n }\n if let Some(graph) = resolved_graph {\n if let Some(resolved_detail) = graph.resolution_details.get(formula_arc.name()) {\n match resolved_detail.determined_install_strategy {\n NodeInstallStrategy::SourceOnly => return true,\n NodeInstallStrategy::BottleOrFail => return false,\n NodeInstallStrategy::BottlePreferred => {}\n }\n }\n }\n if let JobAction::Upgrade {\n old_install_path, ..\n } = action\n {\n if planner\n .get_previous_installation_type(old_install_path)\n .as_deref()\n == Some(\"source\")\n {\n return true;\n }\n }\n !sps_core::install::bottle::has_bottle_for_current_platform(formula_arc)\n }\n InstallTargetIdentifier::Cask(_) => false,\n }\n}\n\nfn sort_planned_jobs(jobs: &mut [PlannedJob], formula_graph: &ResolvedGraph) {\n let formula_order: HashMap = formula_graph\n .install_plan\n .iter()\n .enumerate()\n .map(|(idx, dep_detail)| (dep_detail.formula.name().to_string(), idx))\n .collect();\n\n jobs.sort_by_key(|job| match &job.target_definition {\n InstallTargetIdentifier::Formula(f_arc) => formula_order\n .get(f_arc.name())\n .copied()\n .unwrap_or(usize::MAX),\n InstallTargetIdentifier::Cask(_) => usize::MAX - 1,\n });\n}\n", "middle_code": "async fn plan_for_install(&self, targets: &[String]) -> PlanResult {\n let mut plan = IntermediatePlan::default();\n for name in targets {\n if plan.processed_globally.contains(name) {\n continue;\n }\n match self.check_installed_status(name).await {\n Ok(Some(installed_info)) => {\n let mut proceed_with_install = false;\n if installed_info.pkg_type == CorePackageType::Cask {\n let manifest_path = installed_info.path.join(\"CASK_INSTALL_MANIFEST.json\");\n if manifest_path.is_file() {\n if let Ok(manifest_str) = std::fs::read_to_string(&manifest_path) {\n if let Ok(manifest_json) =\n serde_json::from_str::(&manifest_str)\n {\n if let Some(is_installed_flag) =\n manifest_json.get(\"is_installed\").and_then(|v| v.as_bool())\n {\n if !is_installed_flag {\n debug!(\"Cask '{}' found but marked as not installed in manifest. Proceeding with install.\", name);\n proceed_with_install = true;\n }\n }\n }\n }\n } else {\n debug!(\n \"Cask '{}' found but manifest missing. Assuming needs install.\",\n name\n );\n proceed_with_install = true;\n }\n }\n if proceed_with_install {\n if let Some(private_path) = self\n .determine_cask_private_store_source(name, &installed_info.version)\n .await\n {\n plan.private_store_sources\n .insert(name.clone(), private_path);\n }\n plan.initial_ops\n .insert(name.clone(), (JobAction::Install, None));\n } else {\n debug!(\"Target '{}' already installed and manifest indicates it. Marking as satisfied.\", name);\n plan.already_satisfied.insert(name.clone());\n plan.processed_globally.insert(name.clone());\n }\n }\n Ok(None) => {\n if let Some(private_path) = self\n .determine_cask_private_store_source(name, \"latest\")\n .await\n {\n plan.private_store_sources\n .insert(name.clone(), private_path);\n }\n plan.initial_ops\n .insert(name.clone(), (JobAction::Install, None));\n }\n Err(e) => {\n plan.errors.push((\n name.clone(),\n SpsError::Generic(format!(\n \"Failed to check installed status for {name}: {e}\"\n )),\n ));\n plan.processed_globally.insert(name.clone());\n }\n }\n }\n Ok(plan)\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "rust", "sub_task_type": null}, "context_code": [["/sps/sps-common/src/dependency/resolver.rs", "// sps-common/src/dependency/resolver.rs\nuse std::collections::{HashMap, HashSet, VecDeque};\nuse std::path::{Path, PathBuf};\nuse std::sync::Arc;\n\nuse tracing::{debug, error, warn};\n\nuse crate::dependency::{Dependency, DependencyTag};\nuse crate::error::{Result, SpsError};\nuse crate::formulary::Formulary;\nuse crate::keg::KegRegistry;\nuse crate::model::formula::Formula;\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq)]\npub enum NodeInstallStrategy {\n BottlePreferred,\n SourceOnly,\n BottleOrFail,\n}\n\n#[derive(Debug, Clone, Default)]\npub struct PerTargetInstallPreferences {\n pub force_source_build_targets: HashSet,\n pub force_bottle_only_targets: HashSet,\n}\n\npub struct ResolutionContext<'a> {\n pub formulary: &'a Formulary,\n pub keg_registry: &'a KegRegistry,\n pub sps_prefix: &'a Path,\n pub include_optional: bool,\n pub include_test: bool,\n pub skip_recommended: bool,\n pub initial_target_preferences: &'a PerTargetInstallPreferences,\n pub build_all_from_source: bool,\n pub cascade_source_preference_to_dependencies: bool,\n pub has_bottle_for_current_platform: fn(&Formula) -> bool,\n pub initial_target_actions: &'a HashMap,\n}\n\n#[derive(Debug, Clone)]\npub struct ResolvedDependency {\n pub formula: Arc,\n pub keg_path: Option,\n pub opt_path: Option,\n pub status: ResolutionStatus,\n pub accumulated_tags: DependencyTag,\n pub determined_install_strategy: NodeInstallStrategy,\n pub failure_reason: Option,\n}\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq)]\npub enum ResolutionStatus {\n Installed,\n Missing,\n Requested,\n SkippedOptional,\n NotFound,\n Failed,\n}\n\n#[derive(Debug, Clone, Default)]\npub struct ResolvedGraph {\n pub install_plan: Vec,\n pub build_dependency_opt_paths: Vec,\n pub runtime_dependency_opt_paths: Vec,\n pub resolution_details: HashMap,\n}\n\n// Added empty constructor\nimpl ResolvedGraph {\n pub fn empty() -> Self {\n Default::default()\n }\n}\n\npub struct DependencyResolver<'a> {\n context: ResolutionContext<'a>,\n formula_cache: HashMap>,\n visiting: HashSet,\n resolution_details: HashMap,\n errors: HashMap>,\n}\n\nimpl<'a> DependencyResolver<'a> {\n pub fn new(context: ResolutionContext<'a>) -> Self {\n Self {\n context,\n formula_cache: HashMap::new(),\n visiting: HashSet::new(),\n resolution_details: HashMap::new(),\n errors: HashMap::new(),\n }\n }\n\n fn determine_node_install_strategy(\n &self,\n formula_name: &str,\n formula_arc: &Arc,\n is_initial_target: bool,\n requesting_parent_strategy: Option,\n ) -> NodeInstallStrategy {\n if is_initial_target {\n if self\n .context\n .initial_target_preferences\n .force_source_build_targets\n .contains(formula_name)\n {\n return NodeInstallStrategy::SourceOnly;\n }\n if self\n .context\n .initial_target_preferences\n .force_bottle_only_targets\n .contains(formula_name)\n {\n return NodeInstallStrategy::BottleOrFail;\n }\n }\n\n if self.context.build_all_from_source {\n return NodeInstallStrategy::SourceOnly;\n }\n\n if self.context.cascade_source_preference_to_dependencies\n && matches!(\n requesting_parent_strategy,\n Some(NodeInstallStrategy::SourceOnly)\n )\n {\n return NodeInstallStrategy::SourceOnly;\n }\n if matches!(\n requesting_parent_strategy,\n Some(NodeInstallStrategy::BottleOrFail)\n ) {\n return NodeInstallStrategy::BottleOrFail;\n }\n\n let strategy = if (self.context.has_bottle_for_current_platform)(formula_arc) {\n NodeInstallStrategy::BottlePreferred\n } else {\n NodeInstallStrategy::SourceOnly\n };\n\n debug!(\n \"Install strategy for '{formula_name}': {:?} (initial_target={is_initial_target}, parent={:?}, bottle_available={})\",\n strategy,\n requesting_parent_strategy,\n (self.context.has_bottle_for_current_platform)(formula_arc)\n );\n strategy\n }\n\n pub fn resolve_targets(&mut self, targets: &[String]) -> Result {\n debug!(\"Starting dependency resolution for targets: {:?}\", targets);\n self.visiting.clear();\n self.resolution_details.clear();\n self.errors.clear();\n\n for target_name in targets {\n if let Err(e) = self.resolve_recursive(target_name, DependencyTag::RUNTIME, true, None)\n {\n self.errors.insert(target_name.clone(), Arc::new(e));\n warn!(\n \"Resolution failed for target '{}', but continuing for others.\",\n target_name\n );\n }\n }\n\n debug!(\n \"Raw resolved map after initial pass: {:?}\",\n self.resolution_details\n .iter()\n .map(|(k, v)| (k.clone(), v.status, v.accumulated_tags))\n .collect::>()\n );\n\n let sorted_list = match self.topological_sort() {\n Ok(list) => list,\n Err(e @ SpsError::DependencyError(_)) => {\n error!(\"Topological sort failed due to dependency cycle: {}\", e);\n return Err(e);\n }\n Err(e) => {\n error!(\"Topological sort failed: {}\", e);\n return Err(e);\n }\n };\n\n let install_plan: Vec = sorted_list\n .into_iter()\n .filter(|dep| {\n matches!(\n dep.status,\n ResolutionStatus::Missing | ResolutionStatus::Requested\n )\n })\n .collect();\n\n let mut build_paths = Vec::new();\n let mut runtime_paths = Vec::new();\n let mut seen_build_paths = HashSet::new();\n let mut seen_runtime_paths = HashSet::new();\n\n for dep in self.resolution_details.values() {\n if matches!(\n dep.status,\n ResolutionStatus::Installed\n | ResolutionStatus::Requested\n | ResolutionStatus::Missing\n ) {\n if let Some(opt_path) = &dep.opt_path {\n if dep.accumulated_tags.contains(DependencyTag::BUILD)\n && seen_build_paths.insert(opt_path.clone())\n {\n debug!(\"Adding build dep path: {}\", opt_path.display());\n build_paths.push(opt_path.clone());\n }\n if dep.accumulated_tags.intersects(\n DependencyTag::RUNTIME\n | DependencyTag::RECOMMENDED\n | DependencyTag::OPTIONAL,\n ) && seen_runtime_paths.insert(opt_path.clone())\n {\n debug!(\"Adding runtime dep path: {}\", opt_path.display());\n runtime_paths.push(opt_path.clone());\n }\n } else if dep.status != ResolutionStatus::NotFound\n && dep.status != ResolutionStatus::Failed\n {\n debug!(\n \"Warning: No opt_path found for resolved dependency {} ({:?})\",\n dep.formula.name(),\n dep.status\n );\n }\n }\n }\n\n if !self.errors.is_empty() {\n warn!(\n \"Resolution encountered errors for specific targets: {:?}\",\n self.errors\n .iter()\n .map(|(k, v)| (k, v.to_string()))\n .collect::>()\n );\n }\n\n debug!(\n \"Final installation plan (needs install/build): {:?}\",\n install_plan\n .iter()\n .map(|d| (d.formula.name(), d.status))\n .collect::>()\n );\n debug!(\n \"Collected build dependency paths: {:?}\",\n build_paths.iter().map(|p| p.display()).collect::>()\n );\n debug!(\n \"Collected runtime dependency paths: {:?}\",\n runtime_paths\n .iter()\n .map(|p| p.display())\n .collect::>()\n );\n\n Ok(ResolvedGraph {\n install_plan,\n build_dependency_opt_paths: build_paths,\n runtime_dependency_opt_paths: runtime_paths,\n resolution_details: self.resolution_details.clone(),\n })\n }\n\n fn update_existing_resolution(\n &mut self,\n name: &str,\n tags_from_parent_edge: DependencyTag,\n is_initial_target: bool,\n ) -> Result {\n let Some(existing) = self.resolution_details.get_mut(name) else {\n return Ok(false);\n };\n\n let original_status = existing.status;\n let original_tags = existing.accumulated_tags;\n let has_keg = existing.keg_path.is_some();\n\n let mut new_status = original_status;\n if is_initial_target && new_status == ResolutionStatus::Missing {\n new_status = ResolutionStatus::Requested;\n }\n\n let skip_recommended = self.context.skip_recommended;\n let include_optional = self.context.include_optional;\n\n if Self::should_upgrade_optional_status_static(\n new_status,\n tags_from_parent_edge,\n is_initial_target,\n has_keg,\n skip_recommended,\n include_optional,\n ) {\n new_status = if has_keg {\n ResolutionStatus::Installed\n } else if is_initial_target {\n ResolutionStatus::Requested\n } else {\n ResolutionStatus::Missing\n };\n }\n\n let mut needs_revisit = false;\n if new_status != original_status {\n debug!(\n \"Updating status for '{name}' from {:?} to {:?}\",\n original_status, new_status\n );\n existing.status = new_status;\n needs_revisit = true;\n }\n\n let combined_tags = original_tags | tags_from_parent_edge;\n if combined_tags != original_tags {\n debug!(\n \"Updating tags for '{name}' from {:?} to {:?}\",\n original_tags, combined_tags\n );\n existing.accumulated_tags = combined_tags;\n needs_revisit = true;\n }\n\n if !needs_revisit {\n debug!(\"'{}' already resolved with compatible status/tags.\", name);\n } else {\n debug!(\n \"Re-evaluating dependencies for '{}' due to status/tag update\",\n name\n );\n }\n\n Ok(needs_revisit)\n }\n\n fn should_upgrade_optional_status_static(\n current_status: ResolutionStatus,\n tags_from_parent_edge: DependencyTag,\n is_initial_target: bool,\n _has_keg: bool,\n skip_recommended: bool,\n include_optional: bool,\n ) -> bool {\n current_status == ResolutionStatus::SkippedOptional\n && (tags_from_parent_edge.contains(DependencyTag::RUNTIME)\n || tags_from_parent_edge.contains(DependencyTag::BUILD)\n || (tags_from_parent_edge.contains(DependencyTag::RECOMMENDED)\n && !skip_recommended)\n || (is_initial_target && include_optional))\n }\n\n fn load_or_cache_formula(\n &mut self,\n name: &str,\n tags_from_parent_edge: DependencyTag,\n ) -> Result>> {\n if let Some(f) = self.formula_cache.get(name) {\n return Ok(Some(f.clone()));\n }\n\n debug!(\"Loading formula definition for '{}'\", name);\n match self.context.formulary.load_formula(name) {\n Ok(f) => {\n let arc = Arc::new(f);\n self.formula_cache.insert(name.to_string(), arc.clone());\n Ok(Some(arc))\n }\n Err(e) => {\n error!(\"Failed to load formula definition for '{}': {}\", name, e);\n let msg = e.to_string();\n self.resolution_details.insert(\n name.to_string(),\n ResolvedDependency {\n formula: Arc::new(Formula::placeholder(name)),\n keg_path: None,\n opt_path: None,\n status: ResolutionStatus::NotFound,\n accumulated_tags: tags_from_parent_edge,\n determined_install_strategy: NodeInstallStrategy::BottlePreferred,\n failure_reason: Some(msg.clone()),\n },\n );\n self.errors\n .insert(name.to_string(), Arc::new(SpsError::NotFound(msg)));\n Ok(None)\n }\n }\n }\n\n fn create_initial_resolution(\n &mut self,\n name: &str,\n formula_arc: Arc,\n tags_from_parent_edge: DependencyTag,\n is_initial_target: bool,\n requesting_parent_strategy: Option,\n ) -> Result<()> {\n let current_node_strategy = self.determine_node_install_strategy(\n name,\n &formula_arc,\n is_initial_target,\n requesting_parent_strategy,\n );\n\n let (status, keg_path) =\n self.determine_resolution_status(name, is_initial_target, current_node_strategy)?;\n\n debug!(\n \"Initial status for '{}': {:?}, keg: {:?}, opt: {}\",\n name,\n status,\n keg_path,\n self.context.keg_registry.get_opt_path(name).display()\n );\n\n self.resolution_details.insert(\n name.to_string(),\n ResolvedDependency {\n formula: formula_arc.clone(),\n keg_path,\n opt_path: Some(self.context.keg_registry.get_opt_path(name)),\n status,\n accumulated_tags: tags_from_parent_edge,\n determined_install_strategy: current_node_strategy,\n failure_reason: None,\n },\n );\n\n Ok(())\n }\n\n fn determine_resolution_status(\n &self,\n name: &str,\n is_initial_target: bool,\n strategy: NodeInstallStrategy,\n ) -> Result<(ResolutionStatus, Option)> {\n match strategy {\n NodeInstallStrategy::SourceOnly => Ok((\n if is_initial_target {\n ResolutionStatus::Requested\n } else {\n ResolutionStatus::Missing\n },\n None,\n )),\n NodeInstallStrategy::BottlePreferred | NodeInstallStrategy::BottleOrFail => {\n if let Some(keg) = self.context.keg_registry.get_installed_keg(name)? {\n // Check if this is an upgrade target - if so, mark as Requested even if\n // installed\n let should_request_upgrade = is_initial_target\n && self\n .context\n .initial_target_actions\n .get(name)\n .map(|action| {\n matches!(action, crate::pipeline::JobAction::Upgrade { .. })\n })\n .unwrap_or(false);\n\n debug!(\"[Resolver] Package '{}': is_initial_target={}, should_request_upgrade={}, action={:?}\",\n name, is_initial_target, should_request_upgrade,\n self.context.initial_target_actions.get(name));\n\n if should_request_upgrade {\n debug!(\n \"[Resolver] Marking upgrade target '{}' as Requested (was installed)\",\n name\n );\n Ok((ResolutionStatus::Requested, Some(keg.path)))\n } else {\n debug!(\"[Resolver] Marking '{}' as Installed (normal case)\", name);\n Ok((ResolutionStatus::Installed, Some(keg.path)))\n }\n } else {\n debug!(\n \"[Resolver] Package '{}' not installed, marking as {}\",\n name,\n if is_initial_target {\n \"Requested\"\n } else {\n \"Missing\"\n }\n );\n Ok((\n if is_initial_target {\n ResolutionStatus::Requested\n } else {\n ResolutionStatus::Missing\n },\n None,\n ))\n }\n }\n }\n }\n\n fn process_dependencies(\n &mut self,\n dep_snapshot: &ResolvedDependency,\n parent_name: &str,\n ) -> Result<()> {\n for dep in dep_snapshot.formula.dependencies()? {\n let dep_name = &dep.name;\n let dep_tags = dep.tags;\n let parent_formula_name = dep_snapshot.formula.name();\n let parent_strategy = dep_snapshot.determined_install_strategy;\n\n debug!(\n \"RESOLVER: Evaluating edge: parent='{}' ({:?}), child='{}' ({:?})\",\n parent_formula_name, parent_strategy, dep_name, dep_tags\n );\n\n if !self.should_consider_dependency(&dep) {\n if !self.resolution_details.contains_key(dep_name.as_str()) {\n debug!(\"RESOLVER: Child '{}' of '{}' globally SKIPPED (e.g. optional/test not included). Tags: {:?}\", dep_name, parent_formula_name, dep_tags);\n }\n continue;\n }\n\n let should_process = self.context.should_process_dependency_edge(\n &dep_snapshot.formula,\n dep_tags,\n parent_strategy,\n );\n\n if !should_process {\n debug!(\n \"RESOLVER: Edge from '{}' (Strategy: {:?}) to child '{}' (Tags: {:?}) was SKIPPED by should_process_dependency_edge.\",\n parent_formula_name, parent_strategy, dep_name, dep_tags\n );\n continue;\n }\n\n debug!(\n \"RESOLVER: Edge from '{}' (Strategy: {:?}) to child '{}' (Tags: {:?}) WILL BE PROCESSED. Recursing.\",\n parent_formula_name, parent_strategy, dep_name, dep_tags\n );\n\n if let Err(e) = self.resolve_recursive(dep_name, dep_tags, false, Some(parent_strategy))\n {\n // Log the error but don't necessarily stop all resolution for this branch yet\n warn!(\n \"Error resolving child dependency '{}' for parent '{}': {}\",\n dep_name, parent_name, e\n );\n // Optionally, mark parent as failed if child error is critical\n // self.errors.insert(parent_name.to_string(), Arc::new(e)); // Storing error for\n // parent if needed\n }\n }\n Ok(())\n }\n\n fn resolve_recursive(\n &mut self,\n name: &str,\n tags_from_parent_edge: DependencyTag,\n is_initial_target: bool,\n requesting_parent_strategy: Option,\n ) -> Result<()> {\n debug!(\n \"Resolving: {} (requested as {:?}, is_target: {})\",\n name, tags_from_parent_edge, is_initial_target\n );\n\n if self.visiting.contains(name) {\n error!(\"Dependency cycle detected involving: {}\", name);\n return Err(SpsError::DependencyError(format!(\n \"Dependency cycle detected involving '{name}'\"\n )));\n }\n\n if self.update_existing_resolution(name, tags_from_parent_edge, is_initial_target)? {\n // Already exists and was updated, no need to reprocess\n return Ok(());\n }\n\n if self.resolution_details.contains_key(name) {\n // Already exists but didn't need update\n return Ok(());\n }\n\n // New resolution needed\n self.visiting.insert(name.to_string());\n\n let formula_arc = match self.load_or_cache_formula(name, tags_from_parent_edge) {\n Ok(Some(formula)) => formula,\n Ok(None) => {\n self.visiting.remove(name);\n return Ok(()); // Already handled error case\n }\n Err(e) => {\n self.visiting.remove(name);\n return Err(e);\n }\n };\n\n self.create_initial_resolution(\n name,\n formula_arc,\n tags_from_parent_edge,\n is_initial_target,\n requesting_parent_strategy,\n )?;\n\n let dep_snapshot = self\n .resolution_details\n .get(name)\n .expect(\"just inserted\")\n .clone();\n\n if matches!(\n dep_snapshot.status,\n ResolutionStatus::Failed | ResolutionStatus::NotFound\n ) {\n self.visiting.remove(name);\n return Ok(());\n }\n\n self.process_dependencies(&dep_snapshot, name)?;\n\n self.visiting.remove(name);\n debug!(\"Finished resolving '{}'\", name);\n Ok(())\n }\n\n fn topological_sort(&self) -> Result> {\n let mut in_degree: HashMap = HashMap::new();\n let mut adj: HashMap> = HashMap::new();\n let mut sorted_list = Vec::new();\n let mut queue = VecDeque::new();\n\n let relevant_nodes_map: HashMap = self\n .resolution_details\n .iter()\n .filter(|(_, dep)| {\n !matches!(\n dep.status,\n ResolutionStatus::NotFound | ResolutionStatus::Failed\n )\n })\n .map(|(k, v)| (k.clone(), v))\n .collect();\n\n for (parent_name, parent_rd) in &relevant_nodes_map {\n adj.entry(parent_name.clone()).or_default();\n in_degree.entry(parent_name.clone()).or_default();\n\n let parent_strategy = parent_rd.determined_install_strategy;\n if let Ok(dependencies) = parent_rd.formula.dependencies() {\n for child_edge in dependencies {\n let child_name = &child_edge.name;\n if relevant_nodes_map.contains_key(child_name)\n && self.context.should_process_dependency_edge(\n &parent_rd.formula,\n child_edge.tags,\n parent_strategy,\n )\n && adj\n .entry(parent_name.clone())\n .or_default()\n .insert(child_name.clone())\n {\n *in_degree.entry(child_name.clone()).or_default() += 1;\n }\n }\n }\n }\n\n for name in relevant_nodes_map.keys() {\n if *in_degree.get(name).unwrap_or(&1) == 0 {\n queue.push_back(name.clone());\n }\n }\n\n while let Some(u_name) = queue.pop_front() {\n if let Some(resolved_dep) = relevant_nodes_map.get(&u_name) {\n sorted_list.push((**resolved_dep).clone()); // Deref Arc then clone\n // ResolvedDependency\n }\n if let Some(neighbors) = adj.get(&u_name) {\n for v_name in neighbors {\n if relevant_nodes_map.contains_key(v_name) {\n // Check if neighbor is relevant\n if let Some(degree) = in_degree.get_mut(v_name) {\n *degree = degree.saturating_sub(1);\n if *degree == 0 {\n queue.push_back(v_name.clone());\n }\n }\n }\n }\n }\n }\n\n // Check for cycles: if sorted_list's length doesn't match relevant_nodes_map's length\n // (excluding already installed, skipped optional if not included, etc.)\n // A more direct check is if in_degree still contains non-zero values for relevant nodes.\n let mut cycle_detected = false;\n for (name, °ree) in &in_degree {\n if degree > 0 && relevant_nodes_map.contains_key(name) {\n // Further check if this node should have been processed (not skipped globally)\n if let Some(detail) = self.resolution_details.get(name) {\n if self\n .context\n .should_consider_edge_globally(detail.accumulated_tags)\n {\n error!(\"Cycle detected or unresolved dependency: Node '{}' still has in-degree {}. Tags: {:?}\", name, degree, detail.accumulated_tags);\n cycle_detected = true;\n } else {\n debug!(\"Node '{}' has in-degree {} but was globally skipped. Tags: {:?}. Not a cycle error.\", name, degree, detail.accumulated_tags);\n }\n }\n }\n }\n\n if cycle_detected {\n return Err(SpsError::DependencyError(\n \"Circular dependency detected or graph resolution incomplete\".to_string(),\n ));\n }\n\n Ok(sorted_list) // Return the full sorted list of relevant nodes\n }\n\n fn should_consider_dependency(&self, dep: &Dependency) -> bool {\n let tags = dep.tags;\n if tags.contains(DependencyTag::TEST) && !self.context.include_test {\n return false;\n }\n if tags.contains(DependencyTag::OPTIONAL) && !self.context.include_optional {\n return false;\n }\n if tags.contains(DependencyTag::RECOMMENDED) && self.context.skip_recommended {\n return false;\n }\n true\n }\n}\n\nimpl Formula {\n fn placeholder(name: &str) -> Self {\n Self {\n name: name.to_string(),\n stable_version_str: \"0.0.0\".to_string(),\n version_semver: semver::Version::new(0, 0, 0), // Direct use\n revision: 0,\n desc: Some(\"Placeholder for unresolved formula\".to_string()),\n homepage: None,\n url: String::new(),\n sha256: String::new(),\n mirrors: Vec::new(),\n bottle: Default::default(),\n dependencies: Vec::new(),\n requirements: Vec::new(),\n resources: Vec::new(),\n install_keg_path: None,\n }\n }\n}\n\nimpl<'a> ResolutionContext<'a> {\n pub fn should_process_dependency_edge(\n &self,\n parent_formula_for_logging: &Arc,\n edge_tags: DependencyTag,\n parent_node_determined_strategy: NodeInstallStrategy,\n ) -> bool {\n if !self.should_consider_edge_globally(edge_tags) {\n debug!(\n \"Edge with tags {:?} for child of '{}' globally SKIPPED (e.g. optional/test not included).\",\n edge_tags, parent_formula_for_logging.name()\n );\n return false;\n }\n\n match parent_node_determined_strategy {\n NodeInstallStrategy::BottlePreferred | NodeInstallStrategy::BottleOrFail => {\n let is_purely_build_dependency = edge_tags.contains(DependencyTag::BUILD)\n && !edge_tags.intersects(\n DependencyTag::RUNTIME\n | DependencyTag::RECOMMENDED\n | DependencyTag::OPTIONAL,\n );\n if is_purely_build_dependency {\n debug!(\"Edge with tags {:?} SKIPPED: Pure BUILD dependency of a bottle-installed parent '{}'.\", edge_tags, parent_formula_for_logging.name());\n return false;\n }\n }\n NodeInstallStrategy::SourceOnly => {\n // Process all relevant (non-globally-skipped) dependencies for source builds\n }\n }\n debug!(\n \"Edge with tags {:?} WILL BE PROCESSED for parent '{}' (strategy {:?}).\",\n edge_tags,\n parent_formula_for_logging.name(),\n parent_node_determined_strategy\n );\n true\n }\n\n pub fn should_consider_edge_globally(&self, edge_tags: DependencyTag) -> bool {\n if edge_tags.contains(DependencyTag::TEST) && !self.include_test {\n return false;\n }\n if edge_tags.contains(DependencyTag::OPTIONAL) && !self.include_optional {\n return false;\n }\n if edge_tags.contains(DependencyTag::RECOMMENDED) && self.skip_recommended {\n return false;\n }\n true\n }\n}\n"], ["/sps/sps/src/pipeline/runner.rs", "// sps/src/pipeline/runner.rs\nuse std::collections::{HashMap, HashSet};\nuse std::sync::atomic::{AtomicUsize, Ordering};\nuse std::sync::{Arc, Mutex};\nuse std::time::Instant;\n\nuse colored::Colorize;\nuse crossbeam_channel::bounded as crossbeam_bounded;\nuse reqwest::Client as HttpClient;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::dependency::resolver::{ResolutionStatus, ResolvedGraph};\nuse sps_common::error::{Result as SpsResult, SpsError};\nuse sps_common::model::InstallTargetIdentifier;\nuse sps_common::pipeline::{\n DownloadOutcome, JobProcessingState, PipelineEvent, PlannedJob,\n PlannedOperations as PlannerOutputCommon, WorkerJob,\n};\nuse tokio::sync::{broadcast, mpsc};\nuse tokio::task::JoinHandle;\nuse tracing::{debug, error, instrument, warn};\n\nuse super::downloader::DownloadCoordinator;\nuse super::planner::OperationPlanner;\n\nconst WORKER_JOB_CHANNEL_SIZE: usize = 100;\nconst EVENT_CHANNEL_SIZE: usize = 100;\nconst DOWNLOAD_OUTCOME_CHANNEL_SIZE: usize = 100;\n\n#[derive(Debug, Clone, PartialEq, Eq)]\npub enum CommandType {\n Install,\n Reinstall,\n Upgrade { all: bool },\n}\n\n#[derive(Debug, Clone)]\npub struct PipelineFlags {\n pub build_from_source: bool,\n pub include_optional: bool,\n pub skip_recommended: bool,\n}\n\nstruct PropagationContext {\n all_planned_jobs: Arc>,\n job_states: Arc>>,\n resolved_graph: Arc,\n event_tx: Option>,\n final_fail_count: Arc,\n}\n\nfn err_to_string(e: &SpsError) -> String {\n e.to_string()\n}\n\npub(crate) fn get_panic_message(e: Box) -> String {\n match e.downcast_ref::<&'static str>() {\n Some(s) => (*s).to_string(),\n None => match e.downcast_ref::() {\n Some(s) => s.clone(),\n None => \"Unknown panic payload\".to_string(),\n },\n }\n}\n\n#[instrument(skip_all, fields(cmd = ?command_type, targets = ?initial_targets))]\npub async fn run_pipeline(\n initial_targets: &[String],\n command_type: CommandType,\n config: &Config,\n cache: Arc,\n flags: &PipelineFlags,\n) -> SpsResult<()> {\n debug!(\n \"Pipeline run initiated for targets: {:?}, command: {:?}\",\n initial_targets, command_type\n );\n let start_time = Instant::now();\n let final_success_count = Arc::new(AtomicUsize::new(0));\n let final_fail_count = Arc::new(AtomicUsize::new(0));\n\n debug!(\n \"Creating broadcast channel for pipeline events (EVENT_CHANNEL_SIZE={})\",\n EVENT_CHANNEL_SIZE\n );\n let (event_tx, mut event_rx_for_runner) =\n broadcast::channel::(EVENT_CHANNEL_SIZE);\n\n debug!(\"Cloning event_tx for runner_event_tx_clone\");\n let runner_event_tx_clone = event_tx.clone();\n\n debug!(\n \"Creating crossbeam worker job channel (WORKER_JOB_CHANNEL_SIZE={})\",\n WORKER_JOB_CHANNEL_SIZE\n );\n let (worker_job_tx, worker_job_rx_for_core) =\n crossbeam_bounded::(WORKER_JOB_CHANNEL_SIZE);\n\n debug!(\"Cloning event_tx for core_event_tx_for_worker_manager\");\n let core_config = config.clone();\n let core_cache_clone = cache.clone();\n let core_event_tx_for_worker_manager = event_tx.clone();\n let core_success_count_clone = Arc::clone(&final_success_count);\n let core_fail_count_clone = Arc::clone(&final_fail_count);\n debug!(\"Spawning core worker pool manager thread.\");\n let core_handle = std::thread::spawn(move || {\n debug!(\"CORE_THREAD: Core worker pool manager thread started.\");\n let result = sps_core::pipeline::engine::start_worker_pool_manager(\n core_config,\n core_cache_clone,\n worker_job_rx_for_core,\n core_event_tx_for_worker_manager,\n core_success_count_clone,\n core_fail_count_clone,\n );\n debug!(\n \"CORE_THREAD: Core worker pool manager thread finished. Result: {:?}\",\n result.is_ok()\n );\n result\n });\n\n debug!(\"Subscribing to event_tx for status_event_rx\");\n let status_config = config.clone();\n let status_event_rx = event_tx.subscribe();\n debug!(\"Spawning status handler task.\");\n let status_handle = tokio::spawn(crate::cli::status::handle_events(\n status_config,\n status_event_rx,\n ));\n\n debug!(\n \"Creating mpsc download_outcome channel (DOWNLOAD_OUTCOME_CHANNEL_SIZE={})\",\n DOWNLOAD_OUTCOME_CHANNEL_SIZE\n );\n let (download_outcome_tx, mut download_outcome_rx) =\n mpsc::channel::(DOWNLOAD_OUTCOME_CHANNEL_SIZE);\n\n debug!(\"Initializing pipeline planning phase...\");\n let planner_output: PlannerOutputCommon;\n {\n debug!(\"Cloning runner_event_tx_clone for planner_event_tx_clone\");\n let planner_event_tx_clone = runner_event_tx_clone.clone();\n debug!(\"Creating OperationPlanner.\");\n let operation_planner =\n OperationPlanner::new(config, cache.clone(), flags, planner_event_tx_clone);\n\n debug!(\"Calling plan_operations...\");\n match operation_planner\n .plan_operations(initial_targets, command_type.clone())\n .await\n {\n Ok(ops) => {\n debug!(\"plan_operations returned Ok.\");\n planner_output = ops;\n }\n Err(e) => {\n error!(\"Fatal planning error: {}\", e);\n runner_event_tx_clone\n .send(PipelineEvent::LogError {\n message: format!(\"Fatal planning error: {e}\"),\n })\n .ok();\n drop(worker_job_tx);\n if let Err(join_err) = core_handle.join() {\n error!(\n \"Core thread join error after planning failure: {:?}\",\n get_panic_message(join_err)\n );\n }\n let duration = start_time.elapsed();\n runner_event_tx_clone\n .send(PipelineEvent::PipelineFinished {\n duration_secs: duration.as_secs_f64(),\n success_count: 0,\n fail_count: initial_targets.len(),\n })\n .ok();\n\n debug!(\"Dropping runner_event_tx_clone due to planning error.\");\n drop(runner_event_tx_clone);\n debug!(\"Dropping main event_tx due to planning error.\");\n drop(event_tx);\n\n debug!(\"Awaiting status_handle after planning error.\");\n if let Err(join_err) = status_handle.await {\n error!(\n \"Status task join error after planning failure: {}\",\n join_err\n );\n }\n return Err(e);\n }\n }\n debug!(\"OperationPlanner scope ended, planner_event_tx_clone dropped.\");\n }\n\n let planned_jobs = Arc::new(planner_output.jobs);\n let resolved_graph = planner_output.resolved_graph.clone()\n .unwrap_or_else(|| {\n tracing::debug!(\"ResolvedGraph was None in planner output. Using a default empty graph. This is expected if no formulae required resolution or if planner reported errors for all formulae.\");\n Arc::new(sps_common::dependency::resolver::ResolvedGraph::default())\n });\n\n debug!(\n \"Planning finished. Total jobs in plan: {}.\",\n planned_jobs.len()\n );\n runner_event_tx_clone\n .send(PipelineEvent::PlanningFinished {\n job_count: planned_jobs.len(),\n })\n .ok();\n\n // Mark jobs with planner errors as failed and emit error events\n let job_processing_states = Arc::new(Mutex::new(HashMap::::new()));\n let mut jobs_pending_or_active = 0;\n let mut initial_fail_count_from_planner = 0;\n {\n let mut states_guard = job_processing_states.lock().unwrap();\n if !planner_output.errors.is_empty() {\n tracing::debug!(\n \"[Runner] Planner reported {} error(s). These targets will be marked as failed.\",\n planner_output.errors.len()\n );\n for (target_name, error) in &planner_output.errors {\n let msg = format!(\"✗ {}: {}\", target_name.cyan(), error);\n runner_event_tx_clone\n .send(PipelineEvent::LogError { message: msg })\n .ok();\n states_guard.insert(\n target_name.clone(),\n JobProcessingState::Failed(Arc::new(error.clone())),\n );\n initial_fail_count_from_planner += 1;\n }\n }\n for job in planned_jobs.iter() {\n if states_guard.contains_key(&job.target_id) {\n continue;\n }\n if planner_output\n .already_installed_or_up_to_date\n .contains(&job.target_id)\n {\n states_guard.insert(job.target_id.clone(), JobProcessingState::Succeeded);\n final_success_count.fetch_add(1, Ordering::Relaxed);\n debug!(\n \"[{}] Marked as Succeeded (pre-existing/up-to-date).\",\n job.target_id\n );\n } else if let Some((_, err)) = planner_output\n .errors\n .iter()\n .find(|(name, _)| name == &job.target_id)\n {\n states_guard.insert(\n job.target_id.clone(),\n JobProcessingState::Failed(Arc::new(err.clone())),\n );\n // Counted in initial_fail_count_from_planner\n debug!(\n \"[{}] Marked as Failed (planning error: {}).\",\n job.target_id, err\n );\n } else if job.use_private_store_source.is_some() {\n let path = job.use_private_store_source.clone().unwrap();\n states_guard.insert(\n job.target_id.clone(),\n JobProcessingState::Downloaded(path.clone()),\n );\n jobs_pending_or_active += 1;\n debug!(\n \"[{}] Initial state: Downloaded (private store: {}). Active jobs: {}\",\n job.target_id,\n path.display(),\n jobs_pending_or_active\n );\n } else {\n states_guard.insert(job.target_id.clone(), JobProcessingState::PendingDownload);\n jobs_pending_or_active += 1;\n debug!(\n \"[{}] Initial state: PendingDownload. Active jobs: {}\",\n job.target_id, jobs_pending_or_active\n );\n }\n }\n }\n debug!(\n \"Initial job states populated. Jobs pending/active: {}\",\n jobs_pending_or_active\n );\n\n let mut downloads_to_initiate = Vec::new();\n {\n let states_guard = job_processing_states.lock().unwrap();\n for job in planned_jobs.iter() {\n if matches!(\n states_guard.get(&job.target_id),\n Some(JobProcessingState::PendingDownload)\n ) {\n downloads_to_initiate.push(job.clone());\n }\n }\n }\n\n let mut download_coordinator_task_handle: Option>> = None;\n\n if !downloads_to_initiate.is_empty() {\n debug!(\"Cloning runner_event_tx_clone for download_coordinator_event_tx_clone\");\n let download_coordinator_event_tx_clone = runner_event_tx_clone.clone();\n let http_client = Arc::new(HttpClient::new());\n let config_for_downloader_owned = config.clone();\n\n let mut download_coordinator = DownloadCoordinator::new(\n config_for_downloader_owned,\n cache.clone(),\n http_client,\n download_coordinator_event_tx_clone,\n );\n debug!(\n \"Starting download coordination for {} jobs...\",\n downloads_to_initiate.len()\n );\n debug!(\"Cloning download_outcome_tx for tx_for_download_task\");\n let tx_for_download_task = download_outcome_tx.clone();\n\n debug!(\"Spawning DownloadCoordinator task.\");\n download_coordinator_task_handle = Some(tokio::spawn(async move {\n debug!(\"DOWNLOAD_COORD_TASK: DownloadCoordinator task started.\");\n let result = download_coordinator\n .coordinate_downloads(downloads_to_initiate, tx_for_download_task)\n .await;\n debug!(\"DOWNLOAD_COORD_TASK: DownloadCoordinator task finished. coordinate_downloads returned.\");\n result\n }));\n } else if jobs_pending_or_active > 0 {\n debug!(\n \"No downloads to initiate, but {} jobs are pending. Triggering check_and_dispatch.\",\n jobs_pending_or_active\n );\n check_and_dispatch(\n planned_jobs.clone(),\n job_processing_states.clone(),\n resolved_graph.clone(),\n &worker_job_tx,\n runner_event_tx_clone.clone(),\n config,\n flags,\n );\n } else {\n debug!(\"No downloads to initiate and no jobs pending/active. Pipeline might be empty or all pre-satisfied/failed.\");\n }\n\n drop(download_outcome_tx);\n debug!(\"Dropped main MPSC download_outcome_tx (runner's original clone).\");\n\n if !planned_jobs.is_empty() {\n runner_event_tx_clone\n .send(PipelineEvent::PipelineStarted {\n total_jobs: planned_jobs.len(),\n })\n .ok();\n }\n\n let mut propagation_ctx = PropagationContext {\n all_planned_jobs: planned_jobs.clone(),\n job_states: job_processing_states.clone(),\n resolved_graph: resolved_graph.clone(),\n event_tx: Some(runner_event_tx_clone.clone()),\n final_fail_count: final_fail_count.clone(),\n };\n\n debug!(\n \"Entering main event loop. Jobs pending/active: {}\",\n jobs_pending_or_active\n );\n\n // Robust main loop: continue while there are jobs pending/active, or downloads, or jobs in\n // states that could be dispatched\n fn has_pending_dispatchable_jobs(\n states_guard: &std::sync::MutexGuard>,\n ) -> bool {\n states_guard.values().any(|state| {\n matches!(\n state,\n JobProcessingState::Downloaded(_) | JobProcessingState::WaitingForDependencies(_)\n )\n })\n }\n\n while jobs_pending_or_active > 0\n || has_pending_dispatchable_jobs(&job_processing_states.lock().unwrap())\n {\n tokio::select! {\n biased;\n Some(download_outcome) = download_outcome_rx.recv() => {\n debug!(\"Received DownloadOutcome for '{}'.\", download_outcome.planned_job.target_id);\n process_download_outcome(\n download_outcome,\n &propagation_ctx,\n &mut jobs_pending_or_active,\n );\n debug!(\"After process_download_outcome, jobs_pending_or_active: {}. Triggering check_and_dispatch.\", jobs_pending_or_active);\n check_and_dispatch(\n planned_jobs.clone(),\n job_processing_states.clone(),\n resolved_graph.clone(),\n &worker_job_tx,\n runner_event_tx_clone.clone(),\n config,\n flags,\n );\n }\n Ok(event) = event_rx_for_runner.recv() => {\n match event {\n PipelineEvent::JobSuccess { ref target_id, .. } => {\n debug!(\"Received JobSuccess for '{}'.\", target_id);\n process_core_worker_feedback(\n target_id.clone(),\n true,\n None,\n job_processing_states.clone(),\n &mut jobs_pending_or_active,\n );\n debug!(\"After JobSuccess for '{}', jobs_pending_or_active: {}. Triggering check_and_dispatch.\", target_id, jobs_pending_or_active);\n check_and_dispatch(\n planned_jobs.clone(),\n job_processing_states.clone(),\n resolved_graph.clone(),\n &worker_job_tx,\n runner_event_tx_clone.clone(),\n config,\n flags,\n );\n }\n PipelineEvent::JobFailed { ref target_id, ref error, ref action } => {\n debug!(\"Received JobFailed for '{}' (Action: {:?}, Error: {}).\", target_id, action, error);\n process_core_worker_feedback(\n target_id.clone(),\n false,\n Some(SpsError::Generic(error.clone())),\n job_processing_states.clone(),\n &mut jobs_pending_or_active,\n );\n debug!(\"After JobFailed for '{}', jobs_pending_or_active: {}. Triggering failure propagation.\", target_id, jobs_pending_or_active);\n propagate_failure(\n target_id,\n Arc::new(SpsError::Generic(format!(\"Core worker failed for {target_id}: {error}\"))),\n &propagation_ctx,\n &mut jobs_pending_or_active,\n );\n check_and_dispatch(\n planned_jobs.clone(),\n job_processing_states.clone(),\n resolved_graph.clone(),\n &worker_job_tx,\n runner_event_tx_clone.clone(),\n config,\n flags,\n );\n }\n _ => {}\n }\n }\n else => {\n debug!(\"Main select loop 'else' branch. jobs_pending_or_active = {}. download_outcome_rx or event_rx_for_runner might be closed.\", jobs_pending_or_active);\n if jobs_pending_or_active > 0 || has_pending_dispatchable_jobs(&job_processing_states.lock().unwrap()) {\n warn!(\"Exiting main loop prematurely but still have {} jobs pending/active or dispatchable. This might indicate a stall or logic error.\", jobs_pending_or_active);\n }\n break;\n }\n }\n debug!(\n \"End of select! loop iteration. Jobs pending/active: {}\",\n jobs_pending_or_active\n );\n }\n debug!(\n \"Main event loop finished. Final jobs_pending_or_active: {}\",\n jobs_pending_or_active\n );\n\n drop(download_outcome_rx);\n debug!(\"Dropped MPSC download_outcome_rx (runner's receiver).\");\n\n if let Some(handle) = download_coordinator_task_handle {\n debug!(\"Waiting for DownloadCoordinator task to complete...\");\n match handle.await {\n Ok(critical_download_errors) => {\n if !critical_download_errors.is_empty() {\n warn!(\n \"DownloadCoordinator task reported critical errors: {:?}\",\n critical_download_errors\n );\n final_fail_count.fetch_add(critical_download_errors.len(), Ordering::Relaxed);\n }\n debug!(\"DownloadCoordinator task completed.\");\n }\n Err(e) => {\n let panic_msg = get_panic_message(Box::new(e));\n error!(\n \"DownloadCoordinator task panicked or failed to join: {}\",\n panic_msg\n );\n final_fail_count.fetch_add(1, Ordering::Relaxed);\n }\n }\n } else {\n debug!(\"No DownloadCoordinator task was spawned or it was already handled.\");\n }\n debug!(\"DownloadCoordinator task processing finished (awaited or none).\");\n\n debug!(\"Closing worker job channel (signal to core workers).\");\n drop(worker_job_tx);\n debug!(\"Waiting for core worker pool to join...\");\n match core_handle.join() {\n Ok(Ok(())) => debug!(\"Core worker pool manager thread completed successfully.\"),\n Ok(Err(e)) => {\n error!(\"Core worker pool manager thread failed: {}\", e);\n final_fail_count.fetch_add(1, Ordering::Relaxed);\n }\n Err(e) => {\n error!(\n \"Core worker pool manager thread panicked: {:?}\",\n get_panic_message(e)\n );\n final_fail_count.fetch_add(1, Ordering::Relaxed);\n }\n }\n debug!(\"Core worker pool joined. core_event_tx_for_worker_manager (broadcast sender) dropped.\");\n\n let duration = start_time.elapsed();\n let success_total = final_success_count.load(Ordering::Relaxed);\n let fail_total = final_fail_count.load(Ordering::Relaxed) + initial_fail_count_from_planner;\n\n debug!(\n \"Pipeline processing finished. Success: {}, Fail: {}. Duration: {:.2}s. Sending PipelineFinished event.\",\n success_total, fail_total, duration.as_secs_f64()\n );\n if let Err(e) = runner_event_tx_clone.send(PipelineEvent::PipelineFinished {\n duration_secs: duration.as_secs_f64(),\n success_count: success_total,\n fail_count: fail_total,\n }) {\n warn!(\n \"Failed to send PipelineFinished event: {:?}. Status handler might not receive it.\",\n e\n );\n }\n\n // Explicitly drop the event_tx inside propagation_ctx before dropping the last senders.\n propagation_ctx.event_tx = None;\n\n debug!(\"Dropping runner_event_tx_clone (broadcast sender).\");\n drop(runner_event_tx_clone);\n // event_rx_for_runner (broadcast receiver) goes out of scope here and is dropped.\n\n debug!(\"Dropping main event_tx (final broadcast sender).\");\n drop(event_tx);\n\n debug!(\"All known broadcast senders dropped. About to await status_handle.\");\n if let Err(e) = status_handle.await {\n warn!(\"Status handler task failed or panicked: {}\", e);\n } else {\n debug!(\"Status handler task completed successfully.\");\n }\n debug!(\"run_pipeline function is ending.\");\n\n if fail_total == 0 {\n Ok(())\n } else {\n let mut accumulated_errors = Vec::new();\n for (name, err_obj) in planner_output.errors {\n accumulated_errors.push(format!(\"Planning for '{name}': {err_obj}\"));\n }\n let states_guard = job_processing_states.lock().unwrap();\n for job in planned_jobs.iter() {\n if let Some(JobProcessingState::Failed(err_arc)) = states_guard.get(&job.target_id) {\n let err_str = err_to_string(err_arc);\n let job_err_msg = format!(\"Processing '{}': {}\", job.target_id, err_str);\n if !accumulated_errors.contains(&job_err_msg) {\n accumulated_errors.push(job_err_msg);\n }\n }\n }\n drop(states_guard);\n\n let specific_error_msg = if accumulated_errors.is_empty() {\n \"No specific errors logged, check core worker logs.\".to_string()\n } else {\n accumulated_errors.join(\"; \")\n };\n\n // Error details are already sent via PipelineEvent::JobFailed events\n // and will be displayed in status.rs\n Err(SpsError::InstallError(format!(\n \"Operation failed with {fail_total} total failure(s). Details: [{specific_error_msg}] (Worker errors are included in total)\"\n )))\n }\n}\n\nfn process_download_outcome(\n outcome: DownloadOutcome,\n propagation_ctx: &PropagationContext,\n jobs_pending_or_active: &mut usize,\n) {\n let job_id = outcome.planned_job.target_id.clone();\n let mut states_guard = propagation_ctx.job_states.lock().unwrap();\n\n match states_guard.get(&job_id) {\n Some(JobProcessingState::Succeeded) | Some(JobProcessingState::Failed(_)) => {\n debug!(\n \"[{}] DownloadOutcome: Job already in terminal state {:?}. Ignoring outcome.\",\n job_id,\n states_guard.get(&job_id)\n );\n return;\n }\n _ => {}\n }\n\n match outcome.result {\n Ok(path) => {\n debug!(\n \"[{}] DownloadOutcome: Success. Path: {}. Updating state to Downloaded.\",\n job_id,\n path.display()\n );\n states_guard.insert(job_id.clone(), JobProcessingState::Downloaded(path));\n }\n Err(e) => {\n warn!(\n \"[{}] DownloadOutcome: Failed. Error: {}. Updating state to Failed.\",\n job_id, e\n );\n let error_arc = Arc::new(e);\n states_guard.insert(\n job_id.clone(),\n JobProcessingState::Failed(error_arc.clone()),\n );\n\n if let Some(ref tx) = propagation_ctx.event_tx {\n tx.send(PipelineEvent::job_failed(\n job_id.clone(),\n outcome.planned_job.action.clone(),\n &error_arc,\n ))\n .ok();\n }\n propagation_ctx\n .final_fail_count\n .fetch_add(1, Ordering::Relaxed);\n\n if *jobs_pending_or_active > 0 {\n *jobs_pending_or_active -= 1;\n debug!(\"[{}] DownloadOutcome: Decremented jobs_pending_or_active to {} due to download failure.\", job_id, *jobs_pending_or_active);\n } else {\n warn!(\"[{}] DownloadOutcome: jobs_pending_or_active is already 0, cannot decrement for download failure.\", job_id);\n }\n\n drop(states_guard);\n debug!(\"[{}] DownloadOutcome: Propagating failure.\", job_id);\n propagate_failure(&job_id, error_arc, propagation_ctx, jobs_pending_or_active);\n }\n }\n}\n\nfn process_core_worker_feedback(\n target_id: String,\n success: bool,\n error: Option,\n job_states: Arc>>,\n jobs_pending_or_active: &mut usize,\n) {\n let mut states_guard = job_states.lock().unwrap();\n\n match states_guard.get(&target_id) {\n Some(JobProcessingState::Succeeded) | Some(JobProcessingState::Failed(_)) => {\n debug!(\"[{}] CoreFeedback: Job already in terminal state {:?}. Ignoring active job count update.\", target_id, states_guard.get(&target_id));\n return;\n }\n _ => {}\n }\n\n if success {\n debug!(\n \"[{}] CoreFeedback: Success. Updating state to Succeeded.\",\n target_id\n );\n states_guard.insert(target_id.clone(), JobProcessingState::Succeeded);\n } else {\n let err_msg = error.as_ref().map_or_else(\n || \"Unknown core worker error\".to_string(),\n |e| e.to_string(),\n );\n debug!(\n \"[{}] CoreFeedback: Failed. Error: {}. Updating state to Failed.\",\n target_id, err_msg\n );\n let err_arc = Arc::new(\n error.unwrap_or_else(|| SpsError::Generic(\"Unknown core worker error\".into())),\n );\n states_guard.insert(target_id.clone(), JobProcessingState::Failed(err_arc));\n }\n\n if *jobs_pending_or_active > 0 {\n *jobs_pending_or_active -= 1;\n debug!(\n \"[{}] CoreFeedback: Decremented jobs_pending_or_active to {}.\",\n target_id, *jobs_pending_or_active\n );\n } else {\n warn!(\n \"[{}] CoreFeedback: jobs_pending_or_active is already 0, cannot decrement.\",\n target_id\n );\n }\n}\n\nfn check_and_dispatch(\n planned_jobs_arc: Arc>,\n job_states: Arc>>,\n resolved_graph: Arc,\n worker_job_tx: &crossbeam_channel::Sender,\n event_tx: broadcast::Sender,\n config: &Config,\n flags: &PipelineFlags,\n) {\n debug!(\"--- Enter check_and_dispatch ---\");\n let mut states_guard = job_states.lock().unwrap();\n let mut dispatched_this_round = 0;\n\n for planned_job in planned_jobs_arc.iter() {\n let job_id = &planned_job.target_id;\n debug!(\"[{}] CheckDispatch: Evaluating job.\", job_id);\n\n let (current_state_is_dispatchable, path_for_dispatch) = {\n match states_guard.get(job_id) {\n Some(JobProcessingState::Downloaded(ref path)) => {\n debug!(\"[{}] CheckDispatch: Current state is Downloaded.\", job_id);\n (true, Some(path.clone()))\n }\n Some(JobProcessingState::WaitingForDependencies(ref path)) => {\n debug!(\n \"[{}] CheckDispatch: Current state is WaitingForDependencies.\",\n job_id\n );\n (true, Some(path.clone()))\n }\n other_state => {\n debug!(\n \"[{}] CheckDispatch: Not in a dispatchable state. Current state: {:?}.\",\n job_id,\n other_state.map(|s| format!(\"{s:?}\"))\n );\n (false, None)\n }\n }\n };\n\n if current_state_is_dispatchable {\n let path = path_for_dispatch.unwrap();\n drop(states_guard);\n debug!(\n \"[{}] CheckDispatch: Calling are_dependencies_succeeded.\",\n job_id\n );\n let dependencies_succeeded = are_dependencies_succeeded(\n job_id,\n &planned_job.target_definition,\n job_states.clone(),\n &resolved_graph,\n config,\n flags,\n );\n states_guard = job_states.lock().unwrap();\n debug!(\n \"[{}] CheckDispatch: are_dependencies_succeeded returned: {}.\",\n job_id, dependencies_succeeded\n );\n\n let current_state_after_dep_check = states_guard.get(job_id).cloned();\n if !matches!(\n current_state_after_dep_check,\n Some(JobProcessingState::Downloaded(_))\n | Some(JobProcessingState::WaitingForDependencies(_))\n ) {\n debug!(\"[{}] CheckDispatch: State changed to {:?} while checking dependencies. Skipping dispatch.\", job_id, current_state_after_dep_check);\n continue;\n }\n\n if dependencies_succeeded {\n debug!(\n \"[{}] CheckDispatch: All dependencies satisfied. Dispatching to core worker.\",\n job_id\n );\n let worker_job = WorkerJob {\n request: planned_job.clone(),\n download_path: path.clone(),\n download_size_bytes: std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0),\n is_source_from_private_store: planned_job.use_private_store_source.is_some(),\n };\n if worker_job_tx.send(worker_job).is_ok() {\n states_guard.insert(\n job_id.clone(),\n JobProcessingState::DispatchedToCore(path.clone()),\n );\n event_tx\n .send(PipelineEvent::JobDispatchedToCore {\n target_id: job_id.clone(),\n })\n .ok();\n dispatched_this_round += 1;\n debug!(\"[{}] CheckDispatch: Successfully dispatched.\", job_id);\n } else {\n error!(\"[{}] CheckDispatch: Failed to send job to worker channel (channel closed?). Marking as failed.\", job_id);\n let err = Arc::new(SpsError::Generic(\"Worker channel closed\".to_string()));\n if !matches!(\n states_guard.get(job_id),\n Some(JobProcessingState::Failed(_))\n ) {\n states_guard\n .insert(job_id.clone(), JobProcessingState::Failed(err.clone()));\n event_tx\n .send(PipelineEvent::job_failed(\n job_id.clone(),\n planned_job.action.clone(),\n &err,\n ))\n .ok();\n }\n }\n } else if matches!(\n current_state_after_dep_check,\n Some(JobProcessingState::Downloaded(_))\n ) {\n debug!(\"[{}] CheckDispatch: Dependencies not met. Updating state to WaitingForDependencies.\", job_id);\n states_guard.insert(\n job_id.clone(),\n JobProcessingState::WaitingForDependencies(path.clone()),\n );\n } else {\n debug!(\n \"[{}] CheckDispatch: Dependencies not met. State remains {:?}.\",\n job_id, current_state_after_dep_check\n );\n }\n }\n }\n if dispatched_this_round > 0 {\n debug!(\n \"Dispatched {} jobs to core workers in this round.\",\n dispatched_this_round\n );\n }\n debug!(\"--- Exit check_and_dispatch ---\");\n}\n\nfn are_dependencies_succeeded(\n target_id: &str,\n target_def: &InstallTargetIdentifier,\n job_states_arc: Arc>>,\n resolved_graph: &ResolvedGraph,\n config: &Config,\n flags: &PipelineFlags,\n) -> bool {\n debug!(\"[{}] AreDepsSucceeded: Checking dependencies...\", target_id);\n let dependencies_to_check: Vec = match target_def {\n InstallTargetIdentifier::Formula(formula_arc) => {\n if let Some(resolved_dep_info) =\n resolved_graph.resolution_details.get(formula_arc.name())\n {\n let parent_strategy = resolved_dep_info.determined_install_strategy;\n let empty_actions = std::collections::HashMap::new();\n let context = sps_common::dependency::ResolutionContext {\n formulary: &sps_common::formulary::Formulary::new(config.clone()),\n keg_registry: &sps_common::keg::KegRegistry::new(config.clone()),\n sps_prefix: config.sps_root(),\n include_optional: flags.include_optional,\n include_test: false,\n skip_recommended: flags.skip_recommended,\n initial_target_preferences: &Default::default(),\n build_all_from_source: flags.build_from_source,\n cascade_source_preference_to_dependencies: true,\n has_bottle_for_current_platform:\n sps_core::install::bottle::has_bottle_for_current_platform,\n initial_target_actions: &empty_actions,\n };\n\n let deps: Vec = formula_arc\n .dependencies()\n .unwrap_or_default()\n .iter()\n .filter(|dep_edge| {\n context.should_process_dependency_edge(\n formula_arc,\n dep_edge.tags,\n parent_strategy,\n )\n })\n .map(|dep_edge| dep_edge.name.clone())\n .collect();\n debug!(\n \"[{}] AreDepsSucceeded: Formula dependencies to check: {:?}\",\n target_id, deps\n );\n deps\n } else {\n warn!(\"[{}] AreDepsSucceeded: Formula not found in ResolvedGraph. Assuming no dependencies.\", target_id);\n Vec::new()\n }\n }\n InstallTargetIdentifier::Cask(cask_arc) => {\n let deps = if let Some(deps_on) = &cask_arc.depends_on {\n deps_on.formula.clone()\n } else {\n Vec::new()\n };\n debug!(\n \"[{}] AreDepsSucceeded: Cask formula dependencies to check: {:?}\",\n target_id, deps\n );\n deps\n }\n };\n\n if dependencies_to_check.is_empty() {\n debug!(\n \"[{}] AreDepsSucceeded: No dependencies to check. Returning true.\",\n target_id\n );\n return true;\n }\n\n let states_guard = job_states_arc.lock().unwrap();\n for dep_name in &dependencies_to_check {\n match states_guard.get(dep_name) {\n Some(JobProcessingState::Succeeded) => {\n debug!(\n \"[{}] AreDepsSucceeded: Dependency '{}' is Succeeded.\",\n target_id, dep_name\n );\n }\n Some(JobProcessingState::Failed(err)) => {\n debug!(\n \"[{}] AreDepsSucceeded: Dependency '{}' is FAILED ({}). Returning false.\",\n target_id,\n dep_name,\n err_to_string(err)\n );\n return false;\n }\n None => {\n if let Some(resolved_dep_detail) = resolved_graph.resolution_details.get(dep_name) {\n if resolved_dep_detail.status == ResolutionStatus::Installed {\n debug!(\"[{}] AreDepsSucceeded: Dependency '{}' is already installed (from ResolvedGraph).\", target_id, dep_name);\n } else {\n debug!(\"[{}] AreDepsSucceeded: Dependency '{}' has no active state and not ResolvedGraph::Installed (is {:?}). Returning false.\", target_id, dep_name, resolved_dep_detail.status);\n return false;\n }\n } else {\n warn!(\"[{}] AreDepsSucceeded: Dependency '{}' not found in job_states OR ResolvedGraph. Assuming not met. Returning false.\", target_id, dep_name);\n return false;\n }\n }\n other_state => {\n debug!(\"[{}] AreDepsSucceeded: Dependency '{}' is not yet Succeeded. Current state: {:?}. Returning false.\", target_id, dep_name, other_state.map(|s| format!(\"{s:?}\")));\n return false;\n }\n }\n }\n debug!(\n \"[{}] AreDepsSucceeded: All dependencies Succeeded or were pre-installed. Returning true.\",\n target_id\n );\n true\n}\n\nfn propagate_failure(\n failed_job_id: &str,\n failure_reason: Arc,\n ctx: &PropagationContext,\n jobs_pending_or_active: &mut usize,\n) {\n debug!(\n \"[{}] PropagateFailure: Starting for reason: {}\",\n failed_job_id, failure_reason\n );\n let mut dependents_to_fail_queue = vec![failed_job_id.to_string()];\n let mut newly_failed_dependents = HashSet::new();\n\n {\n let mut states_guard = ctx.job_states.lock().unwrap();\n if !matches!(\n states_guard.get(failed_job_id),\n Some(JobProcessingState::Failed(_))\n ) {\n states_guard.insert(\n failed_job_id.to_string(),\n JobProcessingState::Failed(failure_reason.clone()),\n );\n }\n }\n\n let mut current_idx = 0;\n while current_idx < dependents_to_fail_queue.len() {\n let current_source_of_failure = dependents_to_fail_queue[current_idx].clone();\n current_idx += 1;\n\n for job_to_check in ctx.all_planned_jobs.iter() {\n if job_to_check.target_id == failed_job_id\n || newly_failed_dependents.contains(&job_to_check.target_id)\n {\n continue;\n }\n\n let is_dependent = match &job_to_check.target_definition {\n InstallTargetIdentifier::Formula(formula_arc) => ctx\n .resolved_graph\n .resolution_details\n .get(formula_arc.name())\n .is_some_and(|res_dep_info| {\n res_dep_info\n .formula\n .dependencies()\n .unwrap_or_default()\n .iter()\n .any(|d| d.name == current_source_of_failure)\n }),\n InstallTargetIdentifier::Cask(cask_arc) => {\n cask_arc.depends_on.as_ref().is_some_and(|deps| {\n deps.formula.contains(¤t_source_of_failure)\n || deps.cask.contains(¤t_source_of_failure)\n })\n }\n };\n\n if is_dependent {\n let mut states_guard = ctx.job_states.lock().unwrap();\n let current_state_of_dependent = states_guard.get(&job_to_check.target_id).cloned();\n\n if !matches!(\n current_state_of_dependent,\n Some(JobProcessingState::Succeeded) | Some(JobProcessingState::Failed(_))\n ) {\n let propagated_error = Arc::new(SpsError::DependencyError(format!(\n \"Dependency '{}' failed: {}\",\n current_source_of_failure,\n err_to_string(&failure_reason)\n )));\n states_guard.insert(\n job_to_check.target_id.clone(),\n JobProcessingState::Failed(propagated_error.clone()),\n );\n\n if newly_failed_dependents.insert(job_to_check.target_id.clone()) {\n dependents_to_fail_queue.push(job_to_check.target_id.clone());\n ctx.final_fail_count.fetch_add(1, Ordering::Relaxed);\n\n if *jobs_pending_or_active > 0 {\n *jobs_pending_or_active -= 1;\n debug!(\"[{}] PropagateFailure: Decremented jobs_pending_or_active to {} for propagated failure.\", job_to_check.target_id, *jobs_pending_or_active);\n } else {\n warn!(\"[{}] PropagateFailure: jobs_pending_or_active is already 0, cannot decrement for propagated failure.\", job_to_check.target_id);\n }\n\n if let Some(ref tx) = ctx.event_tx {\n tx.send(PipelineEvent::job_failed(\n job_to_check.target_id.clone(),\n job_to_check.action.clone(),\n &propagated_error,\n ))\n .ok();\n }\n debug!(\"[{}] PropagateFailure: Marked as FAILED due to propagated failure from '{}'.\", job_to_check.target_id, current_source_of_failure);\n }\n }\n drop(states_guard);\n }\n }\n }\n\n if !newly_failed_dependents.is_empty() {\n debug!(\n \"[{}] PropagateFailure: Finished. Newly failed dependents: {:?}\",\n failed_job_id, newly_failed_dependents\n );\n } else {\n debug!(\n \"[{}] PropagateFailure: Finished. No new dependents marked as failed.\",\n failed_job_id\n );\n }\n}\n"], ["/sps/sps-core/src/pipeline/worker.rs", "// sps-core/src/pipeline/worker.rs\nuse std::fs;\nuse std::path::PathBuf;\nuse std::sync::Arc;\n\nuse futures::executor::block_on;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::dependency::DependencyExt;\nuse sps_common::error::{Result as SpsResult, SpsError};\nuse sps_common::keg::KegRegistry;\nuse sps_common::model::formula::FormulaDependencies;\nuse sps_common::model::InstallTargetIdentifier;\nuse sps_common::pipeline::{JobAction, PipelineEvent, PipelinePackageType, WorkerJob};\nuse tokio::sync::broadcast;\nuse tracing::{debug, error, instrument, warn};\n\nuse crate::check::installed::{InstalledPackageInfo, PackageType as CorePackageType};\nuse crate::{build, install, uninstall, upgrade};\n\npub(super) fn execute_sync_job(\n worker_job: WorkerJob,\n config: &Config,\n cache: Arc,\n event_tx: broadcast::Sender,\n) -> std::result::Result<(JobAction, PipelinePackageType), Box<(JobAction, SpsError)>> {\n let action = worker_job.request.action.clone();\n\n let result = do_execute_sync_steps(worker_job, config, cache, event_tx);\n\n result\n .map_err(|e| Box::new((action.clone(), e)))\n .map(|pkg_type| (action, pkg_type))\n}\n\n#[instrument(skip_all, fields(job_id = %worker_job.request.target_id, action = ?worker_job.request.action))]\nfn do_execute_sync_steps(\n worker_job: WorkerJob,\n config: &Config,\n _cache: Arc, // Marked as unused if cache is not directly used in this function body\n event_tx: broadcast::Sender,\n) -> SpsResult {\n let job_request = worker_job.request;\n let download_path = worker_job.download_path;\n let is_source_from_private_store = worker_job.is_source_from_private_store;\n\n let (core_pkg_type, pipeline_pkg_type) = match &job_request.target_definition {\n InstallTargetIdentifier::Formula(_) => {\n (CorePackageType::Formula, PipelinePackageType::Formula)\n }\n InstallTargetIdentifier::Cask(_) => (CorePackageType::Cask, PipelinePackageType::Cask),\n };\n\n // Check dependencies before proceeding with formula install/upgrade\n if let InstallTargetIdentifier::Formula(formula_arc) = &job_request.target_definition {\n if matches!(job_request.action, JobAction::Install)\n || matches!(job_request.action, JobAction::Upgrade { .. })\n {\n debug!(\n \"[WORKER:{}] Pre-install check for dependencies. Formula: {}, Action: {:?}\",\n job_request.target_id,\n formula_arc.name(),\n job_request.action\n );\n\n let keg_registry = KegRegistry::new(config.clone());\n match formula_arc.dependencies() {\n Ok(dependencies) => {\n for dep in dependencies.runtime() {\n debug!(\"[WORKER:{}] Checking runtime dependency: '{}'. Required by: '{}'. Configured cellar: {}\", job_request.target_id, dep.name, formula_arc.name(), config.cellar_dir().display());\n\n match keg_registry.get_installed_keg(&dep.name) {\n Ok(Some(keg_info)) => {\n debug!(\"[WORKER:{}] Dependency '{}' FOUND by KegRegistry. Path: {}, Version: {}\", job_request.target_id, dep.name, keg_info.path.display(), keg_info.version_str);\n }\n Ok(None) => {\n debug!(\"[WORKER:{}] Dependency '{}' was NOT FOUND by KegRegistry for formula '{}'. THIS IS THE ERROR POINT.\", dep.name, job_request.target_id, formula_arc.name());\n let error_msg = format!(\n \"Runtime dependency '{}' for formula '{}' is not installed. Aborting operation for '{}'.\",\n dep.name, formula_arc.name(), job_request.target_id\n );\n error!(\"{}\", error_msg);\n return Err(SpsError::DependencyError(error_msg));\n }\n Err(e) => {\n debug!(\"[WORKER:{}] Error during KegRegistry check for dependency '{}': {}. Aborting for formula '{}'.\", job_request.target_id, dep.name, e, job_request.target_id);\n return Err(SpsError::Generic(format!(\n \"Failed to check KegRegistry for {}: {}\",\n dep.name, e\n )));\n }\n }\n }\n }\n Err(e) => {\n let error_msg = format!(\n \"Could not retrieve dependency list for formula '{}': {}. Aborting operation.\",\n job_request.target_id, e\n );\n error!(\"{}\", error_msg);\n return Err(SpsError::DependencyError(error_msg));\n }\n }\n debug!(\n \"[WORKER:{}] All required formula dependencies appear to be installed for '{}'.\",\n job_request.target_id,\n formula_arc.name()\n );\n }\n }\n\n let mut formula_installed_path: Option = None;\n\n match &job_request.action {\n JobAction::Upgrade {\n from_version,\n old_install_path,\n } => {\n debug!(\n \"[{}] Upgrading from version {}\",\n job_request.target_id, from_version\n );\n let old_info = InstalledPackageInfo {\n name: job_request.target_id.clone(),\n version: from_version.clone(),\n pkg_type: core_pkg_type.clone(),\n path: old_install_path.clone(),\n };\n\n match &job_request.target_definition {\n InstallTargetIdentifier::Formula(formula) => {\n let http_client_for_bottle_upgrade = Arc::new(reqwest::Client::new());\n let installed_path = if job_request.is_source_build {\n let _ = event_tx.send(PipelineEvent::BuildStarted {\n target_id: job_request.target_id.clone(),\n });\n let all_dep_paths = Vec::new(); // TODO: Populate this correctly if needed by upgrade_source_formula\n block_on(upgrade::source::upgrade_source_formula(\n formula,\n &download_path,\n &old_info,\n config,\n &all_dep_paths,\n ))?\n } else {\n block_on(upgrade::bottle::upgrade_bottle_formula(\n formula,\n &download_path,\n &old_info,\n config,\n http_client_for_bottle_upgrade,\n ))?\n };\n formula_installed_path = Some(installed_path);\n }\n InstallTargetIdentifier::Cask(cask) => {\n block_on(upgrade::cask::upgrade_cask_package(\n cask,\n &download_path,\n &old_info,\n config,\n ))?;\n }\n }\n }\n JobAction::Install | JobAction::Reinstall { .. } => {\n if let JobAction::Reinstall {\n version: from_version,\n current_install_path: old_install_path,\n } = &job_request.action\n {\n debug!(\n \"[{}] Reinstall: Removing existing version {}...\",\n job_request.target_id, from_version\n );\n let _ = event_tx.send(PipelineEvent::UninstallStarted {\n target_id: job_request.target_id.clone(),\n version: from_version.clone(),\n });\n\n let old_info_for_reinstall = InstalledPackageInfo {\n name: job_request.target_id.clone(),\n version: from_version.clone(),\n pkg_type: core_pkg_type.clone(),\n path: old_install_path.clone(),\n };\n let uninstall_opts = uninstall::UninstallOptions { skip_zap: true };\n\n match core_pkg_type {\n CorePackageType::Formula => uninstall::uninstall_formula_artifacts(\n &old_info_for_reinstall,\n config,\n &uninstall_opts,\n )?,\n CorePackageType::Cask => {\n uninstall::uninstall_cask_artifacts(&old_info_for_reinstall, config)?\n }\n }\n debug!(\n \"[{}] Reinstall: Removed existing version {}.\",\n job_request.target_id, from_version\n );\n let _ = event_tx.send(PipelineEvent::UninstallFinished {\n target_id: job_request.target_id.clone(),\n version: from_version.clone(),\n });\n }\n\n let _ = event_tx.send(PipelineEvent::InstallStarted {\n target_id: job_request.target_id.clone(),\n pkg_type: pipeline_pkg_type,\n });\n\n match &job_request.target_definition {\n InstallTargetIdentifier::Formula(formula) => {\n let install_dir_base =\n (**formula).install_prefix(config.cellar_dir().as_path())?;\n if let Some(parent_dir) = install_dir_base.parent() {\n fs::create_dir_all(parent_dir).map_err(|e| SpsError::Io(Arc::new(e)))?;\n }\n\n if job_request.is_source_build {\n debug!(\"[{}] Building from source...\", job_request.target_id);\n let _ = event_tx.send(PipelineEvent::BuildStarted {\n target_id: job_request.target_id.clone(),\n });\n let build_dep_paths: Vec = vec![]; // TODO: Populate this from ResolvedGraph\n\n let build_future = build::compile::build_from_source(\n &download_path,\n formula,\n config,\n &build_dep_paths,\n );\n let installed_dir = block_on(build_future)?;\n formula_installed_path = Some(installed_dir);\n } else {\n debug!(\"[{}] Installing bottle...\", job_request.target_id);\n let installed_dir =\n install::bottle::exec::install_bottle(&download_path, formula, config)?;\n formula_installed_path = Some(installed_dir);\n }\n }\n InstallTargetIdentifier::Cask(cask) => {\n if is_source_from_private_store {\n debug!(\n \"[{}] Reinstalling cask from private store...\",\n job_request.target_id\n );\n\n if let Some(file_name) = download_path.file_name() {\n let app_name = file_name.to_string_lossy().to_string();\n let applications_app_path = config.applications_dir().join(&app_name);\n\n if applications_app_path.exists()\n || applications_app_path.symlink_metadata().is_ok()\n {\n debug!(\n \"Removing existing app at {}\",\n applications_app_path.display()\n );\n let _ = install::cask::helpers::remove_path_robustly(\n &applications_app_path,\n config,\n true,\n );\n }\n\n debug!(\n \"Symlinking app from private store {} to {}\",\n download_path.display(),\n applications_app_path.display()\n );\n if let Err(e) =\n std::os::unix::fs::symlink(&download_path, &applications_app_path)\n {\n return Err(SpsError::InstallError(format!(\n \"Failed to symlink app from private store to {}: {}\",\n applications_app_path.display(),\n e\n )));\n }\n\n let cask_version =\n cask.version.clone().unwrap_or_else(|| \"latest\".to_string());\n let cask_version_path =\n config.cask_room_version_path(&cask.token, &cask_version);\n\n if !cask_version_path.exists() {\n fs::create_dir_all(&cask_version_path)?;\n }\n\n let caskroom_symlink_path = cask_version_path.join(&app_name);\n if caskroom_symlink_path.exists()\n || caskroom_symlink_path.symlink_metadata().is_ok()\n {\n let _ = fs::remove_file(&caskroom_symlink_path);\n }\n\n #[cfg(unix)]\n {\n if let Err(e) = std::os::unix::fs::symlink(\n &applications_app_path,\n &caskroom_symlink_path,\n ) {\n warn!(\"Failed to create Caskroom symlink: {}\", e);\n }\n }\n\n let created_artifacts = vec![\n sps_common::model::artifact::InstalledArtifact::AppBundle {\n path: applications_app_path.clone(),\n },\n sps_common::model::artifact::InstalledArtifact::CaskroomLink {\n link_path: caskroom_symlink_path.clone(),\n target_path: applications_app_path.clone(),\n },\n ];\n\n debug!(\n \"[{}] Writing manifest for private store reinstall...\",\n job_request.target_id\n );\n if let Err(e) = install::cask::write_cask_manifest(\n cask,\n &cask_version_path,\n created_artifacts,\n ) {\n error!(\n \"[{}] Failed to write CASK_INSTALL_MANIFEST.json during private store reinstall: {}\",\n job_request.target_id, e\n );\n return Err(SpsError::InstallError(format!(\n \"Failed to write manifest during private store reinstall for {}: {}\",\n job_request.target_id, e\n )));\n }\n } else {\n return Err(SpsError::InstallError(format!(\n \"Failed to get app name from private store path: {}\",\n download_path.display()\n )));\n }\n } else {\n debug!(\"[{}] Installing cask...\", job_request.target_id);\n install::cask::install_cask(\n cask,\n &download_path,\n config,\n &job_request.action,\n )?;\n }\n }\n }\n }\n };\n\n if let Some(ref installed_path) = formula_installed_path {\n debug!(\n \"[{}] Formula operation resulted in keg path: {}\",\n job_request.target_id,\n installed_path.display()\n );\n } else if core_pkg_type == CorePackageType::Cask {\n debug!(\"[{}] Cask operation completed.\", job_request.target_id);\n }\n\n if let (InstallTargetIdentifier::Formula(formula), Some(keg_path_for_linking)) =\n (&job_request.target_definition, &formula_installed_path)\n {\n debug!(\n \"[{}] Linking artifacts for formula {}...\",\n job_request.target_id,\n (**formula).name()\n );\n let _ = event_tx.send(PipelineEvent::LinkStarted {\n target_id: job_request.target_id.clone(),\n pkg_type: pipeline_pkg_type,\n });\n install::bottle::link::link_formula_artifacts(formula, keg_path_for_linking, config)?;\n debug!(\n \"[{}] Linking complete for formula {}.\",\n job_request.target_id,\n (**formula).name()\n );\n }\n\n Ok(pipeline_pkg_type)\n}\n"], ["/sps/sps/src/pipeline/downloader.rs", "// sps/src/pipeline/downloader.rs\nuse std::fs;\nuse std::path::PathBuf;\nuse std::sync::Arc;\n\nuse reqwest::Client as HttpClient;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::model::InstallTargetIdentifier;\nuse sps_common::pipeline::{DownloadOutcome, PipelineEvent, PlannedJob};\nuse sps_common::SpsError;\nuse sps_core::{build, install};\nuse sps_net::http::ProgressCallback;\nuse sps_net::UrlField;\nuse tokio::sync::{broadcast, mpsc};\nuse tokio::task::JoinSet;\nuse tracing::{error, warn};\n\nuse super::runner::get_panic_message;\n\npub(crate) struct DownloadCoordinator {\n config: Config,\n cache: Arc,\n http_client: Arc,\n event_tx: Option>,\n}\n\nimpl DownloadCoordinator {\n pub fn new(\n config: Config,\n cache: Arc,\n http_client: Arc,\n event_tx: broadcast::Sender,\n ) -> Self {\n Self {\n config,\n cache,\n http_client,\n event_tx: Some(event_tx),\n }\n }\n\n pub async fn coordinate_downloads(\n &mut self,\n planned_jobs: Vec,\n download_outcome_tx: mpsc::Sender,\n ) -> Vec<(String, SpsError)> {\n let mut download_tasks = JoinSet::new();\n let mut critical_spawn_errors: Vec<(String, SpsError)> = Vec::new();\n\n for planned_job in planned_jobs {\n let _job_id_for_task = planned_job.target_id.clone();\n\n let task_config = self.config.clone();\n let task_cache = Arc::clone(&self.cache);\n let task_http_client = Arc::clone(&self.http_client);\n let task_event_tx = self.event_tx.as_ref().cloned();\n let outcome_tx_clone = download_outcome_tx.clone();\n let current_planned_job_for_task = planned_job.clone();\n\n download_tasks.spawn(async move {\n let job_id_in_task = current_planned_job_for_task.target_id.clone();\n let download_path_result: Result;\n\n if let Some(private_path) = current_planned_job_for_task.use_private_store_source.clone() {\n download_path_result = Ok(private_path);\n } else {\n let display_url_for_event = match ¤t_planned_job_for_task.target_definition {\n InstallTargetIdentifier::Formula(f) => {\n if !current_planned_job_for_task.is_source_build {\n sps_core::install::bottle::exec::get_bottle_for_platform(f)\n .map_or_else(|_| f.url.clone(), |(_, spec)| spec.url.clone())\n } else {\n f.url.clone()\n }\n }\n InstallTargetIdentifier::Cask(c) => match &c.url {\n Some(UrlField::Simple(s)) => s.clone(),\n Some(UrlField::WithSpec { url, .. }) => url.clone(),\n None => \"N/A (No Cask URL)\".to_string(),\n },\n };\n\n if display_url_for_event == \"N/A (No Cask URL)\"\n || (display_url_for_event.is_empty() && !current_planned_job_for_task.is_source_build)\n {\n let _err_msg = \"Download URL is missing or invalid\".to_string();\n let sps_err = SpsError::Generic(format!(\n \"Download URL is missing or invalid for job {job_id_in_task}\"\n ));\n if let Some(ref tx) = task_event_tx {\n tx.send(PipelineEvent::download_failed(\n job_id_in_task.clone(),\n display_url_for_event,\n &sps_err,\n )).ok();\n }\n download_path_result = Err(sps_err);\n } else {\n if let Some(ref tx) = task_event_tx {\n tx.send(PipelineEvent::DownloadStarted {\n target_id: job_id_in_task.clone(),\n url: display_url_for_event.clone(),\n }).ok();\n }\n\n // Create progress callback\n let progress_callback: Option = if let Some(ref tx) = task_event_tx {\n let tx_clone = tx.clone();\n let job_id_for_callback = job_id_in_task.clone();\n Some(Arc::new(move |bytes_so_far: u64, total_size: Option| {\n let _ = tx_clone.send(PipelineEvent::DownloadProgressUpdate {\n target_id: job_id_for_callback.clone(),\n bytes_so_far,\n total_size,\n });\n }))\n } else {\n None\n };\n\n let actual_download_result: Result<(PathBuf, bool), SpsError> =\n match ¤t_planned_job_for_task.target_definition {\n InstallTargetIdentifier::Formula(f) => {\n if current_planned_job_for_task.is_source_build {\n build::compile::download_source_with_progress(f, &task_config, progress_callback).await.map(|p| (p, false))\n } else {\n install::bottle::exec::download_bottle_with_progress_and_cache_info(\n f,\n &task_config,\n &task_http_client,\n progress_callback,\n )\n .await\n }\n }\n InstallTargetIdentifier::Cask(c) => {\n install::cask::download_cask_with_progress(c, task_cache.as_ref(), progress_callback).await.map(|p| (p, false))\n }\n };\n\n match actual_download_result {\n Ok((path, was_cached)) => {\n let size_bytes = fs::metadata(&path).map(|m| m.len()).unwrap_or(0);\n if let Some(ref tx) = task_event_tx {\n if was_cached {\n tx.send(PipelineEvent::DownloadCached {\n target_id: job_id_in_task.clone(),\n size_bytes,\n }).ok();\n } else {\n tx.send(PipelineEvent::DownloadFinished {\n target_id: job_id_in_task.clone(),\n path: path.clone(),\n size_bytes,\n }).ok();\n }\n }\n download_path_result = Ok(path);\n }\n Err(e) => {\n warn!(\n \"[DownloaderTask:{}] Download failed from {}: {}\",\n job_id_in_task, display_url_for_event, e\n );\n if let Some(ref tx) = task_event_tx {\n tx.send(PipelineEvent::download_failed(\n job_id_in_task.clone(),\n display_url_for_event,\n &e,\n )).ok();\n }\n download_path_result = Err(e);\n }\n }\n }\n }\n\n let outcome = DownloadOutcome {\n planned_job: current_planned_job_for_task,\n result: download_path_result,\n };\n\n if let Err(send_err) = outcome_tx_clone.send(outcome).await {\n error!(\n \"[DownloaderTask:{}] CRITICAL: Failed to send download outcome to runner: {}. Job processing will likely stall.\",\n job_id_in_task, send_err\n );\n }\n });\n }\n\n while let Some(join_result) = download_tasks.join_next().await {\n if let Err(e) = join_result {\n let panic_msg = get_panic_message(e.into_panic());\n error!(\n \"[Downloader] A download task panicked: {}. This job's outcome was not sent.\",\n panic_msg\n );\n critical_spawn_errors.push((\n \"[UnknownDownloadTaskPanic]\".to_string(),\n SpsError::Generic(format!(\"A download task panicked: {panic_msg}\")),\n ));\n }\n }\n self.event_tx = None;\n critical_spawn_errors\n }\n}\n"], ["/sps/sps-core/src/check/update.rs", "// sps-core/src/check/update.rs\n\nuse std::collections::HashMap;\nuse std::sync::Arc;\n\n// Imports from sps-common\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::formulary::Formulary; // Using the shared Formulary\nuse sps_common::model::version::Version as PkgVersion;\nuse sps_common::model::Cask; // Using the Cask and Formula from sps-common\n// Use the Cask and Formula structs from sps_common::model\n// Ensure InstallTargetIdentifier is correctly pathed if it's also in sps_common::model\nuse sps_common::model::InstallTargetIdentifier;\n// Imports from sps-net\nuse sps_net::api;\n\n// Imports from sps-core\nuse crate::check::installed::{InstalledPackageInfo, PackageType};\n\n#[derive(Debug, Clone)]\npub struct UpdateInfo {\n pub name: String,\n pub installed_version: String,\n pub available_version: String,\n pub pkg_type: PackageType,\n pub target_definition: InstallTargetIdentifier,\n}\n\n/// Ensures that the raw JSON data for formulas and casks exists in the main disk cache,\n/// fetching from the API if necessary.\nasync fn ensure_api_data_cached(cache: &Cache) -> Result<()> {\n let formula_check = cache.load_raw(\"formula.json\");\n let cask_check = cache.load_raw(\"cask.json\");\n\n // Determine if fetches are needed\n let mut fetch_formulas = false;\n if formula_check.is_err() {\n tracing::debug!(\"Local formula.json cache missing or unreadable. Scheduling fetch.\");\n fetch_formulas = true;\n }\n\n let mut fetch_casks = false;\n if cask_check.is_err() {\n tracing::debug!(\"Local cask.json cache missing or unreadable. Scheduling fetch.\");\n fetch_casks = true;\n }\n\n // Perform fetches concurrently if needed\n match (fetch_formulas, fetch_casks) {\n (true, true) => {\n tracing::debug!(\"Populating missing formula.json and cask.json from API...\");\n let (formula_res, cask_res) = tokio::join!(\n async {\n let data = api::fetch_all_formulas().await?;\n cache.store_raw(\"formula.json\", &data)?;\n Ok::<(), SpsError>(())\n },\n async {\n let data = api::fetch_all_casks().await?;\n cache.store_raw(\"cask.json\", &data)?;\n Ok::<(), SpsError>(())\n }\n );\n formula_res?;\n cask_res?;\n tracing::debug!(\"Formula.json and cask.json populated from API.\");\n }\n (true, false) => {\n tracing::debug!(\"Populating missing formula.json from API...\");\n let data = api::fetch_all_formulas().await?;\n cache.store_raw(\"formula.json\", &data)?;\n tracing::debug!(\"Formula.json populated from API.\");\n }\n (false, true) => {\n tracing::debug!(\"Populating missing cask.json from API...\");\n let data = api::fetch_all_casks().await?;\n cache.store_raw(\"cask.json\", &data)?;\n tracing::debug!(\"Cask.json populated from API.\");\n }\n (false, false) => {\n tracing::debug!(\"Local formula.json and cask.json caches are present.\");\n }\n }\n Ok(())\n}\n\npub async fn check_for_updates(\n installed_packages: &[InstalledPackageInfo],\n cache: &Cache,\n config: &Config,\n) -> Result> {\n // 1. Ensure the underlying JSON files in the main cache are populated.\n ensure_api_data_cached(cache)\n .await\n .map_err(|e| {\n tracing::error!(\n \"Failed to ensure API data is cached for update check: {}\",\n e\n );\n // Decide if this is a fatal error for update checking or if we can proceed with\n // potentially stale/missing data. For now, let's make it non-fatal but log\n // an error, as Formulary/cask parsing might still work with older cache.\n SpsError::Generic(format!(\n \"Failed to ensure API data in cache, update check might be unreliable: {e}\"\n ))\n })\n .ok(); // Continue even if this pre-fetch step fails, rely on Formulary/cask loading to handle actual\n // errors.\n\n // 2. Instantiate Formulary. It uses the `cache` (from sps-common) to load `formula.json`.\n let formulary = Formulary::new(config.clone());\n\n // 3. For Casks: Load the entire `cask.json` from cache and parse it robustly into Vec.\n // This uses the Cask definition from sps_common::model::cask.\n let casks_map: HashMap> = match cache.load_raw(\"cask.json\") {\n Ok(json_str) => {\n // Parse directly into Vec using the definition from sps-common::model::cask\n match serde_json::from_str::>(&json_str) {\n Ok(casks) => casks\n .into_iter()\n .map(|c| (c.token.clone(), Arc::new(c)))\n .collect(),\n Err(e) => {\n tracing::warn!(\n \"Failed to parse full cask.json string into Vec (from sps-common): {}. Cask update checks may be incomplete.\",\n e\n );\n HashMap::new()\n }\n }\n }\n Err(e) => {\n tracing::warn!(\n \"Failed to load cask.json string from cache: {}. Cask update checks will be based on no remote data.\", e\n );\n HashMap::new()\n }\n };\n\n tracing::debug!(\n \"[UpdateCheck] Starting update check for {} packages\",\n installed_packages.len()\n );\n let mut updates_available = Vec::new();\n\n for installed in installed_packages {\n tracing::debug!(\n \"[UpdateCheck] Checking package '{}' version '{}'\",\n installed.name,\n installed.version\n );\n match installed.pkg_type {\n PackageType::Formula => {\n match formulary.load_formula(&installed.name) {\n // Uses sps-common::formulary::Formulary\n Ok(latest_formula_obj) => {\n // Returns sps_common::model::formula::Formula\n let latest_formula_arc = Arc::new(latest_formula_obj);\n\n let latest_version_str = latest_formula_arc.version_str_full();\n tracing::debug!(\n \"[UpdateCheck] Formula '{}': installed='{}', latest='{}'\",\n installed.name,\n installed.version,\n latest_version_str\n );\n\n let installed_v_res = PkgVersion::parse(&installed.version);\n let latest_v_res = PkgVersion::parse(&latest_version_str);\n let installed_revision = installed\n .version\n .split('_')\n .nth(1)\n .and_then(|s| s.parse::().ok())\n .unwrap_or(0);\n\n let needs_update = match (installed_v_res, latest_v_res) {\n (Ok(iv), Ok(lv)) => {\n let version_newer = lv > iv;\n let revision_newer =\n lv == iv && latest_formula_arc.revision > installed_revision;\n tracing::debug!(\"[UpdateCheck] Formula '{}': version_newer={}, revision_newer={} (installed_rev={}, latest_rev={})\", \n installed.name, version_newer, revision_newer, installed_revision, latest_formula_arc.revision);\n version_newer || revision_newer\n }\n _ => {\n let different = installed.version != latest_version_str;\n tracing::debug!(\"[UpdateCheck] Formula '{}': fallback string comparison, different={}\", \n installed.name, different);\n different\n }\n };\n\n tracing::debug!(\n \"[UpdateCheck] Formula '{}': needs_update={}\",\n installed.name,\n needs_update\n );\n if needs_update {\n updates_available.push(UpdateInfo {\n name: installed.name.clone(),\n installed_version: installed.version.clone(),\n available_version: latest_version_str,\n pkg_type: PackageType::Formula,\n target_definition: InstallTargetIdentifier::Formula(\n // From sps-common\n latest_formula_arc.clone(),\n ),\n });\n }\n }\n Err(_e) => {\n tracing::debug!(\n \"Installed formula '{}' not found via Formulary. It might have been removed from the remote. Source error: {}\",\n installed.name, _e\n );\n }\n }\n }\n PackageType::Cask => {\n if let Some(latest_cask_arc) = casks_map.get(&installed.name) {\n // latest_cask_arc is Arc\n if let Some(available_version) = latest_cask_arc.version.as_ref() {\n if &installed.version != available_version {\n updates_available.push(UpdateInfo {\n name: installed.name.clone(),\n installed_version: installed.version.clone(),\n available_version: available_version.clone(),\n pkg_type: PackageType::Cask,\n target_definition: InstallTargetIdentifier::Cask(\n // From sps-common\n latest_cask_arc.clone(),\n ),\n });\n }\n } else {\n tracing::warn!(\n \"Latest cask definition for '{}' from casks_map has no version string.\",\n installed.name\n );\n }\n } else {\n tracing::warn!(\n \"Installed cask '{}' not found in the fully parsed casks_map.\",\n installed.name\n );\n }\n }\n }\n }\n\n tracing::debug!(\n \"[UpdateCheck] Update check complete: {} updates available out of {} packages checked\",\n updates_available.len(),\n installed_packages.len()\n );\n tracing::debug!(\n \"[UpdateCheck] Updates available for: {:?}\",\n updates_available\n .iter()\n .map(|u| &u.name)\n .collect::>()\n );\n\n Ok(updates_available)\n}\n"], ["/sps/sps-core/src/install/cask/mod.rs", "pub mod artifacts;\npub mod dmg;\npub mod helpers;\n\nuse std::fs;\nuse std::path::{Path, PathBuf};\nuse std::time::{SystemTime, SystemTimeError, UNIX_EPOCH};\n\nuse infer;\nuse reqwest::Url;\nuse serde::{Deserialize, Serialize};\nuse serde_json::json;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::{Cask, Sha256Field, UrlField};\nuse sps_net::http::ProgressCallback;\nuse tempfile::TempDir;\nuse tracing::{debug, error};\n\nuse crate::install::extract;\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub struct CaskInstallManifest {\n pub manifest_format_version: String,\n pub token: String,\n pub version: String,\n pub installed_at: u64,\n pub artifacts: Vec,\n pub primary_app_file_name: Option,\n pub is_installed: bool, // New flag for soft uninstall\n pub cask_store_path: Option, // Path to private store app, if available\n}\n\n/// Returns the path to the cask's version directory in the private store.\npub fn sps_private_cask_version_dir(cask: &Cask, config: &Config) -> PathBuf {\n let version = cask.version.clone().unwrap_or_else(|| \"latest\".to_string());\n config.cask_store_version_path(&cask.token, &version)\n}\n\n/// Returns the path to the cask's token directory in the private store.\npub fn sps_private_cask_token_dir(cask: &Cask, config: &Config) -> PathBuf {\n config.cask_store_token_path(&cask.token)\n}\n\n/// Returns the path to the main app bundle for a cask in the private store.\n/// This assumes the primary app bundle is named as specified in the cask's artifacts.\npub fn sps_private_cask_app_path(cask: &Cask, config: &Config) -> Option {\n let version = cask.version.clone().unwrap_or_else(|| \"latest\".to_string());\n if let Some(cask_artifacts) = &cask.artifacts {\n for artifact in cask_artifacts {\n if let Some(obj) = artifact.as_object() {\n if let Some(apps) = obj.get(\"app\") {\n if let Some(app_names) = apps.as_array() {\n if let Some(app_name_val) = app_names.first() {\n if let Some(app_name) = app_name_val.as_str() {\n return Some(config.cask_store_app_path(\n &cask.token,\n &version,\n app_name,\n ));\n }\n }\n }\n }\n }\n }\n }\n None\n}\n\npub async fn download_cask(cask: &Cask, cache: &Cache) -> Result {\n download_cask_with_progress(cask, cache, None).await\n}\n\npub async fn download_cask_with_progress(\n cask: &Cask,\n cache: &Cache,\n progress_callback: Option,\n) -> Result {\n let url_field = cask\n .url\n .as_ref()\n .ok_or_else(|| SpsError::Generic(format!(\"Cask {} has no URL\", cask.token)))?;\n let url_str = match url_field {\n UrlField::Simple(u) => u.as_str(),\n UrlField::WithSpec { url, .. } => url.as_str(),\n };\n\n if url_str.is_empty() {\n return Err(SpsError::Generic(format!(\n \"Cask {} has an empty URL\",\n cask.token\n )));\n }\n\n debug!(\"Downloading cask from {}\", url_str);\n let parsed = Url::parse(url_str)\n .map_err(|e| SpsError::Generic(format!(\"Invalid URL '{url_str}': {e}\")))?;\n sps_net::validation::validate_url(parsed.as_str())?;\n let file_name = parsed\n .path_segments()\n .and_then(|mut segments| segments.next_back())\n .filter(|s| !s.is_empty())\n .map(|s| s.to_string())\n .unwrap_or_else(|| {\n debug!(\"URL has no filename component, using fallback name for cache based on token.\");\n format!(\"cask-{}-download.tmp\", cask.token.replace('/', \"_\"))\n });\n let cache_key = format!(\"cask-{}-{}\", cask.token, file_name);\n let cache_path = cache.get_dir().join(\"cask_downloads\").join(&cache_key);\n\n if cache_path.exists() {\n debug!(\"Using cached download: {}\", cache_path.display());\n return Ok(cache_path);\n }\n\n use futures::StreamExt;\n use tokio::fs::File as TokioFile;\n use tokio::io::AsyncWriteExt;\n\n let client = reqwest::Client::new();\n let response = client\n .get(parsed.clone())\n .send()\n .await\n .map_err(|e| SpsError::Http(std::sync::Arc::new(e)))?;\n if !response.status().is_success() {\n return Err(SpsError::DownloadError(\n cask.token.clone(),\n url_str.to_string(),\n format!(\"HTTP status {}\", response.status()),\n ));\n }\n\n // Get total size from Content-Length header if available\n let total_size = response.content_length();\n\n if let Some(parent) = cache_path.parent() {\n fs::create_dir_all(parent)?;\n }\n\n let mut file = TokioFile::create(&cache_path)\n .await\n .map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n\n // Use bytes_stream() for chunked download with progress reporting\n let mut stream = response.bytes_stream();\n let mut bytes_downloaded = 0u64;\n\n while let Some(chunk) = stream.next().await {\n let chunk = chunk.map_err(|e| SpsError::Http(std::sync::Arc::new(e)))?;\n\n file.write_all(&chunk)\n .await\n .map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n\n bytes_downloaded += chunk.len() as u64;\n\n // Call progress callback if provided\n if let Some(ref callback) = progress_callback {\n callback(bytes_downloaded, total_size);\n }\n }\n\n drop(file);\n match cask.sha256.as_ref() {\n Some(Sha256Field::Hex(s)) => {\n if s.eq_ignore_ascii_case(\"no_check\") {\n tracing::debug!(\n \"Skipping checksum verification for cask {} due to 'no_check' string.\",\n cache_path.display()\n );\n } else if !s.is_empty() {\n match sps_net::validation::verify_checksum(&cache_path, s) {\n Ok(_) => {\n tracing::debug!(\n \"Cask download checksum verified: {}\",\n cache_path.display()\n );\n }\n Err(e) => {\n tracing::error!(\n \"Cask download checksum mismatch ({}). Deleting cached file.\",\n e\n );\n let _ = fs::remove_file(&cache_path);\n return Err(e);\n }\n }\n } else {\n tracing::warn!(\n \"Skipping checksum verification for cask {} - empty sha256 provided.\",\n cache_path.display()\n );\n }\n }\n Some(Sha256Field::NoCheck { no_check: true }) => {\n tracing::debug!(\n \"Skipping checksum verification for cask {} due to 'no_check'.\",\n cache_path.display()\n );\n }\n _ => {\n tracing::warn!(\n \"Skipping checksum verification for cask {} - none provided.\",\n cache_path.display()\n );\n }\n }\n debug!(\"Download completed: {}\", cache_path.display());\n\n // --- Set quarantine xattr on the downloaded archive (macOS only) ---\n #[cfg(target_os = \"macos\")]\n {\n if let Err(e) = crate::utils::xattr::set_quarantine_attribute(&cache_path, \"sps-downloader\")\n {\n tracing::warn!(\n \"Failed to set quarantine attribute on downloaded archive {}: {}. Extraction and installation will proceed, but Gatekeeper behavior might be affected.\",\n cache_path.display(),\n e\n );\n }\n }\n\n Ok(cache_path)\n}\n\nuse sps_common::pipeline::JobAction;\n\npub fn install_cask(\n cask: &Cask,\n download_path: &Path,\n config: &Config,\n job_action: &JobAction,\n) -> Result<()> {\n debug!(\"Installing cask: {}\", cask.token);\n // This is the path in the *actual* Caskroom (e.g., /opt/homebrew/Caskroom/token/version)\n // where metadata and symlinks to /Applications will go.\n let actual_cask_room_version_path = config.cask_room_version_path(\n &cask.token,\n &cask.version.clone().unwrap_or_else(|| \"latest\".to_string()),\n );\n\n if !actual_cask_room_version_path.exists() {\n fs::create_dir_all(&actual_cask_room_version_path).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\n \"Failed create cask_room dir {}: {}\",\n actual_cask_room_version_path.display(),\n e\n ),\n )))\n })?;\n debug!(\n \"Created actual cask_room version directory: {}\",\n actual_cask_room_version_path.display()\n );\n }\n let mut detected_extension = download_path\n .extension()\n .and_then(|e| e.to_str())\n .unwrap_or(\"\")\n .to_lowercase();\n let non_extensions = [\"stable\", \"latest\", \"download\", \"bin\", \"\"];\n if non_extensions.contains(&detected_extension.as_str()) {\n debug!(\n \"Download path '{}' has no definite extension ('{}'), attempting content detection.\",\n download_path.display(),\n detected_extension\n );\n match infer::get_from_path(download_path) {\n Ok(Some(kind)) => {\n detected_extension = kind.extension().to_string();\n debug!(\"Detected file type via content: {}\", detected_extension);\n }\n Ok(None) => {\n error!(\n \"Could not determine file type from content for: {}\",\n download_path.display()\n );\n return Err(SpsError::Generic(format!(\n \"Could not determine file type for download: {}\",\n download_path.display()\n )));\n }\n Err(e) => {\n error!(\n \"Error reading file for type detection {}: {}\",\n download_path.display(),\n e\n );\n return Err(SpsError::Io(std::sync::Arc::new(e)));\n }\n }\n } else {\n debug!(\n \"Using file extension for type detection: {}\",\n detected_extension\n );\n }\n if detected_extension == \"pkg\" || detected_extension == \"mpkg\" {\n debug!(\"Detected PKG installer, running directly\");\n match artifacts::pkg::install_pkg_from_path(\n cask,\n download_path,\n &actual_cask_room_version_path, // PKG manifest items go into the actual cask_room\n config,\n ) {\n Ok(installed_artifacts) => {\n debug!(\"Writing PKG install manifest\");\n write_cask_manifest(cask, &actual_cask_room_version_path, installed_artifacts)?;\n debug!(\"Successfully installed PKG cask: {}\", cask.token);\n return Ok(());\n }\n Err(e) => {\n debug!(\"Failed to install PKG: {}\", e);\n // Clean up cask_room on error\n let _ = fs::remove_dir_all(&actual_cask_room_version_path);\n return Err(e);\n }\n }\n }\n let stage_dir = TempDir::new().map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed to create staging directory: {e}\"),\n )))\n })?;\n let stage_path = stage_dir.path();\n debug!(\"Created staging directory: {}\", stage_path.display());\n // Determine expected extension (this might need refinement)\n // Option 1: Parse from URL\n let expected_ext_from_url = download_path\n .extension()\n .and_then(|e| e.to_str())\n .unwrap_or(\"\");\n // Option 2: A new field in Cask JSON definition (preferred)\n // let expected_ext = cask.expected_extension.as_deref().unwrap_or(expected_ext_from_url);\n let expected_ext = expected_ext_from_url; // Use URL for now\n\n if !expected_ext.is_empty()\n && crate::build::compile::RECOGNISED_SINGLE_FILE_EXTENSIONS.contains(&expected_ext)\n {\n // Check if it's an archive/installer type we handle\n tracing::debug!(\n \"Verifying content type for {} against expected extension '{}'\",\n download_path.display(),\n expected_ext\n );\n if let Err(e) = sps_net::validation::verify_content_type(download_path, expected_ext) {\n tracing::error!(\"Content type verification failed: {}\", e);\n // Attempt cleanup?\n let _ = fs::remove_dir_all(&actual_cask_room_version_path);\n return Err(e);\n }\n } else {\n tracing::debug!(\n \"Skipping content type verification for {} (unknown/no expected extension: '{}')\",\n download_path.display(),\n expected_ext\n );\n }\n match detected_extension.as_str() {\n \"dmg\" => {\n debug!(\n \"Extracting DMG {} to stage {}...\",\n download_path.display(),\n stage_path.display()\n );\n dmg::extract_dmg_to_stage(download_path, stage_path)?;\n debug!(\"Successfully extracted DMG to staging area.\");\n }\n \"zip\" => {\n debug!(\n \"Extracting ZIP {} to stage {}...\",\n download_path.display(),\n stage_path.display()\n );\n extract::extract_archive(download_path, stage_path, 0, \"zip\")?;\n debug!(\"Successfully extracted ZIP to staging area.\");\n }\n \"gz\" | \"bz2\" | \"xz\" | \"tar\" => {\n let archive_type_for_extraction = detected_extension.as_str();\n debug!(\n \"Extracting TAR archive ({}) {} to stage {}...\",\n archive_type_for_extraction,\n download_path.display(),\n stage_path.display()\n );\n extract::extract_archive(download_path, stage_path, 0, archive_type_for_extraction)?;\n debug!(\"Successfully extracted TAR archive to staging area.\");\n }\n _ => {\n error!(\n \"Unsupported container/installer type '{}' for staged installation derived from {}\",\n detected_extension,\n download_path.display()\n );\n return Err(SpsError::Generic(format!(\n \"Unsupported file type for staged installation: {detected_extension}\"\n )));\n }\n }\n let mut all_installed_artifacts: Vec = Vec::new();\n let mut artifact_install_errors = Vec::new();\n if let Some(artifacts_def) = &cask.artifacts {\n debug!(\n \"Processing {} declared artifacts from staging area...\",\n artifacts_def.len()\n );\n for artifact_value in artifacts_def.iter() {\n if let Some(artifact_obj) = artifact_value.as_object() {\n if let Some((key, value)) = artifact_obj.iter().next() {\n debug!(\"Processing artifact type: {}\", key);\n let result: Result> = match key.as_str() {\n \"app\" => {\n let mut app_artifacts = vec![];\n if let Some(app_names) = value.as_array() {\n for app_name_val in app_names {\n if let Some(app_name) = app_name_val.as_str() {\n let staged_app_path = stage_path.join(app_name);\n debug!(\n \"Attempting to install app artifact: {}\",\n staged_app_path.display()\n );\n match artifacts::app::install_app_from_staged(\n cask,\n &staged_app_path,\n &actual_cask_room_version_path,\n config,\n job_action, // Pass job_action for upgrade logic\n ) {\n Ok(mut artifacts) => {\n app_artifacts.append(&mut artifacts)\n }\n Err(e) => {\n return Err(e);\n }\n }\n } else {\n debug!(\n \"Non-string value found in 'app' artifact array: {:?}\",\n app_name_val\n );\n }\n }\n } else {\n debug!(\"'app' artifact value is not an array: {:?}\", value);\n }\n Ok(app_artifacts)\n }\n \"pkg\" => {\n let mut installed_pkgs = vec![];\n if let Some(pkg_names) = value.as_array() {\n for pkg_val in pkg_names {\n if let Some(pkg_name) = pkg_val.as_str() {\n let staged_pkg_path = stage_path.join(pkg_name);\n debug!(\n \"Attempting to install staged pkg artifact: {}\",\n staged_pkg_path.display()\n );\n match artifacts::pkg::install_pkg_from_path(\n cask,\n &staged_pkg_path,\n &actual_cask_room_version_path, /* Pass actual\n * cask_room path */\n config,\n ) {\n Ok(mut artifacts) => {\n installed_pkgs.append(&mut artifacts)\n }\n Err(e) => {\n return Err(e);\n }\n }\n } else {\n debug!(\n \"Non-string value found in 'pkg' artifact array: {:?}\",\n pkg_val\n );\n }\n }\n } else {\n debug!(\"'pkg' artifact value is not an array: {:?}\", value);\n }\n Ok(installed_pkgs)\n }\n _ => {\n debug!(\"Artifact type '{}' not supported yet — skipping.\", key);\n Ok(vec![])\n }\n };\n match result {\n Ok(installed) => {\n if !installed.is_empty() {\n debug!(\n \"Successfully processed artifact '{}', added {} items.\",\n key,\n installed.len()\n );\n all_installed_artifacts.extend(installed);\n } else {\n debug!(\n \"Artifact handler for '{}' completed successfully but returned no artifacts.\",\n key\n );\n }\n }\n Err(e) => {\n error!(\"Error processing artifact '{}': {}\", key, e);\n artifact_install_errors.push(e);\n }\n }\n } else {\n debug!(\"Empty artifact object found: {:?}\", artifact_obj);\n }\n } else {\n debug!(\n \"Unexpected non-object artifact found in list: {:?}\",\n artifact_value\n );\n }\n }\n } else {\n error!(\n \"Cask {} definition is missing the required 'artifacts' array. Cannot determine what to install.\",\n cask.token\n );\n // Clean up the created actual_caskroom_version_path if no artifacts are defined\n let _ = fs::remove_dir_all(&actual_cask_room_version_path);\n return Err(SpsError::InstallError(format!(\n \"Cask '{}' has no artifacts defined.\",\n cask.token\n )));\n }\n if !artifact_install_errors.is_empty() {\n error!(\n \"Encountered {} errors installing artifacts for cask '{}'. Installation incomplete.\",\n artifact_install_errors.len(),\n cask.token\n );\n let _ = fs::remove_dir_all(&actual_cask_room_version_path); // Clean up actual cask_room on error\n return Err(artifact_install_errors.remove(0));\n }\n let actual_install_count = all_installed_artifacts\n .iter()\n .filter(|a| {\n !matches!(\n a,\n InstalledArtifact::PkgUtilReceipt { .. } | InstalledArtifact::Launchd { .. }\n )\n })\n .count();\n if actual_install_count == 0 {\n debug!(\n \"No installable artifacts (like app, pkg, binary, etc.) were processed for cask '{}' from the staged content. Check cask definition.\",\n cask.token\n );\n write_cask_manifest(\n cask,\n &actual_cask_room_version_path,\n all_installed_artifacts,\n )?;\n } else {\n debug!(\"Writing cask installation manifest\");\n write_cask_manifest(\n cask,\n &actual_cask_room_version_path,\n all_installed_artifacts,\n )?;\n }\n debug!(\"Successfully installed cask: {}\", cask.token);\n Ok(())\n}\n\n#[deprecated(note = \"Use write_cask_manifest with detailed InstalledArtifact enum instead\")]\npub fn write_receipt(\n cask: &Cask,\n cask_version_install_path: &Path,\n artifacts: Vec,\n) -> Result<()> {\n let receipt_path = cask_version_install_path.join(\"INSTALL_RECEIPT.json\");\n debug!(\"Writing legacy cask receipt: {}\", receipt_path.display());\n let timestamp = SystemTime::now()\n .duration_since(UNIX_EPOCH)\n .map_err(|e: SystemTimeError| SpsError::Generic(format!(\"System time error: {e}\")))?\n .as_secs();\n let receipt_data = json!({\n \"token\": cask.token,\n \"name\": cask.name.as_ref().and_then(|n| n.first()).cloned(),\n \"version\": cask.version.as_ref().unwrap_or(&\"latest\".to_string()),\n \"installed_at\": timestamp,\n \"artifacts_installed\": artifacts\n });\n if let Some(parent) = receipt_path.parent() {\n fs::create_dir_all(parent).map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n }\n let mut file =\n fs::File::create(&receipt_path).map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n serde_json::to_writer_pretty(&mut file, &receipt_data)\n .map_err(|e| SpsError::Json(std::sync::Arc::new(e)))?;\n debug!(\n \"Successfully wrote legacy receipt with {} artifact entries.\",\n artifacts.len()\n );\n Ok(())\n}\n\npub fn write_cask_manifest(\n cask: &Cask,\n cask_version_install_path: &Path,\n artifacts: Vec,\n) -> Result<()> {\n let manifest_path = cask_version_install_path.join(\"CASK_INSTALL_MANIFEST.json\");\n debug!(\"Writing cask manifest: {}\", manifest_path.display());\n let timestamp = SystemTime::now()\n .duration_since(UNIX_EPOCH)\n .map_err(|e: SystemTimeError| SpsError::Generic(format!(\"System time error: {e}\")))?\n .as_secs();\n\n // Determine primary app file name from artifacts\n let primary_app_file_name = artifacts.iter().find_map(|artifact| {\n if let InstalledArtifact::AppBundle { path } = artifact {\n path.file_name()\n .map(|name| name.to_string_lossy().to_string())\n } else {\n None\n }\n });\n\n // Always set is_installed=true when writing manifest (install or reinstall)\n // Try to determine cask_store_path from artifacts (AppBundle or CaskroomLink)\n let cask_store_path = artifacts.iter().find_map(|artifact| match artifact {\n InstalledArtifact::AppBundle { path } => Some(path.to_string_lossy().to_string()),\n InstalledArtifact::CaskroomLink { target_path, .. } => {\n Some(target_path.to_string_lossy().to_string())\n }\n _ => None,\n });\n\n let manifest_data = CaskInstallManifest {\n manifest_format_version: \"1.0\".to_string(),\n token: cask.token.clone(),\n version: cask.version.clone().unwrap_or_else(|| \"latest\".to_string()),\n installed_at: timestamp,\n artifacts,\n primary_app_file_name,\n is_installed: true,\n cask_store_path,\n };\n if let Some(parent) = manifest_path.parent() {\n fs::create_dir_all(parent).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed create parent dir {}: {}\", parent.display(), e),\n )))\n })?;\n }\n let file = fs::File::create(&manifest_path).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed create manifest {}: {}\", manifest_path.display(), e),\n )))\n })?;\n let writer = std::io::BufWriter::new(file);\n serde_json::to_writer_pretty(writer, &manifest_data).map_err(|e| {\n error!(\n \"Failed to serialize cask manifest JSON for {}: {}\",\n cask.token, e\n );\n SpsError::Json(std::sync::Arc::new(e))\n })?;\n debug!(\n \"Successfully wrote cask manifest with {} artifact entries.\",\n manifest_data.artifacts.len()\n );\n Ok(())\n}\n\n/// Recursively cleans up empty parent directories in the private cask store.\n/// Starts from the given path and walks up, removing empty directories until a non-empty or root is\n/// found.\npub fn cleanup_empty_parent_dirs_in_private_store(start_path: &Path, stop_at: &Path) {\n let mut current = start_path.parent().unwrap_or(start_path).to_path_buf(); // Start from parent\n while current != *stop_at {\n if let Ok(read_dir) = fs::read_dir(¤t) {\n if read_dir.count() == 0 {\n match fs::remove_dir(¤t) {\n Ok(_) => {\n debug!(\"Removed empty directory: {}\", current.display());\n }\n Err(e) => {\n debug!(\"Failed to remove directory {}: {}\", current.display(), e);\n break;\n }\n }\n } else {\n break;\n }\n } else {\n break;\n }\n if let Some(parent) = current.parent() {\n current = parent.to_path_buf();\n } else {\n break;\n }\n }\n}\n"], ["/sps/sps/src/cli/uninstall.rs", "use std::collections::{HashMap, HashSet};\nuse std::sync::Arc;\n\nuse clap::Args;\nuse colored::Colorize;\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::cask::Cask;\nuse sps_common::Cache;\nuse sps_core::check::{installed, PackageType};\nuse sps_core::{uninstall as core_uninstall, UninstallOptions};\nuse sps_net::api;\nuse tracing::{debug, error, warn};\nuse {serde_json, walkdir};\n\n#[derive(Args, Debug)]\npub struct Uninstall {\n /// The names of the formulas or casks to uninstall\n #[arg(required = true)] // Ensure at least one name is given\n pub names: Vec,\n /// Perform a deep clean for casks, removing associated user data, caches,\n /// and configuration files. Use with caution, data will be lost! Ignored for formulas.\n #[arg(\n long,\n help = \"Perform a deep clean for casks, removing associated user data, caches, and configuration files. Use with caution!\"\n )]\n pub zap: bool,\n}\n\nimpl Uninstall {\n pub async fn run(&self, config: &Config, cache: Arc) -> Result<()> {\n let names = &self.names;\n let mut errors: Vec<(String, SpsError)> = Vec::new();\n\n for name in names {\n // Basic name validation to prevent path traversal\n if name.contains('/') || name.contains(\"..\") {\n let msg = format!(\"Invalid package name '{name}' contains disallowed characters\");\n error!(\"✖ {msg}\");\n errors.push((name.to_string(), SpsError::Generic(msg)));\n continue;\n }\n\n println!(\"Uninstalling {name}...\");\n\n match installed::get_installed_package(name, config).await {\n Ok(Some(installed_info)) => {\n let (file_count, size_bytes) =\n count_files_and_size(&installed_info.path).unwrap_or((0, 0));\n let uninstall_opts = UninstallOptions { skip_zap: false };\n debug!(\n \"Attempting uninstall for {} ({:?})\",\n name, installed_info.pkg_type\n );\n let uninstall_result = match installed_info.pkg_type {\n PackageType::Formula => {\n if self.zap {\n warn!(\"--zap flag is ignored for formulas like '{}'.\", name);\n }\n core_uninstall::uninstall_formula_artifacts(\n &installed_info,\n config,\n &uninstall_opts,\n )\n }\n PackageType::Cask => {\n core_uninstall::uninstall_cask_artifacts(&installed_info, config)\n }\n };\n\n if let Err(e) = uninstall_result {\n error!(\"✖ Failed to uninstall '{}': {}\", name.cyan(), e);\n errors.push((name.to_string(), e));\n // Continue to zap anyway for casks, as per plan\n } else {\n println!(\n \"✓ Uninstalled {:?} {} ({} files, {})\",\n installed_info.pkg_type,\n name.green(),\n file_count,\n format_size(size_bytes)\n );\n }\n\n // --- Zap Uninstall (Conditional) ---\n if self.zap && installed_info.pkg_type == PackageType::Cask {\n println!(\"Zapping {name}...\");\n debug!(\n \"--zap specified for cask '{}', attempting deep clean.\",\n name\n );\n\n // Fetch the Cask definition (needed for the zap stanza)\n let cask_def_result: Result = async {\n match api::get_cask(name).await {\n Ok(cask) => Ok(cask),\n Err(e) => {\n warn!(\"Failed API fetch for zap definition for '{}' ({}), trying cache...\", name, e);\n match cache.load_raw(\"cask.json\") {\n Ok(raw_json) => {\n let casks: Vec = serde_json::from_str(&raw_json)\n .map_err(|cache_e| SpsError::Cache(format!(\"Failed parse cached cask.json: {cache_e}\")))?;\n casks.into_iter()\n .find(|c| c.token == *name)\n .ok_or_else(|| SpsError::NotFound(format!(\"Cask '{name}' def not in cache either\")))\n }\n Err(cache_e) => Err(SpsError::Cache(format!(\"Failed load cask cache for zap: {cache_e}\"))),\n }\n }\n }\n }.await;\n\n match cask_def_result {\n Ok(cask_def) => {\n match core_uninstall::zap_cask_artifacts(\n &installed_info,\n &cask_def,\n config,\n )\n .await\n {\n Ok(_) => {\n println!(\"✓ Zap complete for {}\", name.green());\n }\n Err(zap_err) => {\n error!(\"✖ Zap failed for '{}': {}\", name.cyan(), zap_err);\n errors.push((format!(\"{name} (zap)\"), zap_err));\n }\n }\n }\n Err(e) => {\n error!(\n \"✖ Could not get Cask definition for zap '{}': {}\",\n name.cyan(),\n e\n );\n errors.push((format!(\"{name} (zap definition)\"), e));\n }\n }\n }\n }\n Ok(None) => {\n let msg = format!(\"Package '{name}' is not installed.\");\n error!(\"✖ {msg}\");\n errors.push((name.to_string(), SpsError::NotFound(msg)));\n }\n Err(e) => {\n let msg = format!(\"Failed check install status for '{name}': {e}\");\n error!(\"✖ {msg}\");\n errors.push((name.clone(), SpsError::Generic(msg)));\n }\n }\n }\n\n if errors.is_empty() {\n Ok(())\n } else {\n eprintln!(\"\\n{}:\", \"Finished uninstalling with errors\".yellow());\n let mut errors_by_pkg: HashMap> = HashMap::new();\n for (pkg_name, error) in errors {\n errors_by_pkg\n .entry(pkg_name)\n .or_default()\n .push(error.to_string());\n }\n for (pkg_name, error_list) in errors_by_pkg {\n eprintln!(\"Package '{}':\", pkg_name.cyan());\n let unique_errors: HashSet<_> = error_list.into_iter().collect();\n for error_str in unique_errors {\n eprintln!(\"- {}\", error_str.red());\n }\n }\n Err(SpsError::Generic(\n \"Uninstall failed for one or more packages.\".to_string(),\n ))\n }\n }\n}\n\n// --- Unchanged Helper Functions ---\nfn count_files_and_size(path: &std::path::Path) -> Result<(usize, u64)> {\n let mut file_count = 0;\n let mut total_size = 0;\n for entry in walkdir::WalkDir::new(path) {\n match entry {\n Ok(entry_data) => {\n if entry_data.file_type().is_file() || entry_data.file_type().is_symlink() {\n match entry_data.metadata() {\n Ok(metadata) => {\n file_count += 1;\n if entry_data.file_type().is_file() {\n total_size += metadata.len();\n }\n }\n Err(e) => {\n tracing::warn!(\n \"Could not get metadata for {}: {}\",\n entry_data.path().display(),\n e\n );\n }\n }\n }\n }\n Err(e) => {\n tracing::warn!(\"Error traversing directory {}: {}\", path.display(), e);\n }\n }\n }\n Ok((file_count, total_size))\n}\n\nfn format_size(size: u64) -> String {\n const KB: u64 = 1024;\n const MB: u64 = KB * 1024;\n const GB: u64 = MB * 1024;\n if size >= GB {\n format!(\"{:.1}GB\", size as f64 / GB as f64)\n } else if size >= MB {\n format!(\"{:.1}MB\", size as f64 / MB as f64)\n } else if size >= KB {\n format!(\"{:.1}KB\", size as f64 / KB as f64)\n } else {\n format!(\"{size}B\")\n }\n}\n"], ["/sps/sps-core/src/install/bottle/exec.rs", "use std::collections::{HashMap, HashSet};\nuse std::fs::{self, File};\nuse std::io::{Read, Write};\nuse std::os::unix::fs::{symlink, PermissionsExt};\nuse std::path::{Path, PathBuf};\nuse std::process::{Command as StdCommand, Stdio};\nuse std::sync::Arc;\n\nuse reqwest::Client;\nuse semver;\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::formula::{BottleFileSpec, Formula, FormulaDependencies};\nuse sps_net::http::ProgressCallback;\nuse sps_net::oci;\nuse sps_net::validation::verify_checksum;\nuse tempfile::NamedTempFile;\nuse tracing::{debug, error, warn};\nuse walkdir::WalkDir;\n\nuse super::macho;\nuse crate::install::bottle::get_current_platform;\nuse crate::install::extract::extract_archive;\n\npub async fn download_bottle(\n formula: &Formula,\n config: &Config,\n client: &Client,\n) -> Result {\n download_bottle_with_progress(formula, config, client, None).await\n}\n\npub async fn download_bottle_with_progress(\n formula: &Formula,\n config: &Config,\n client: &Client,\n progress_callback: Option,\n) -> Result {\n download_bottle_with_progress_and_cache_info(formula, config, client, progress_callback)\n .await\n .map(|(path, _)| path)\n}\n\npub async fn download_bottle_with_progress_and_cache_info(\n formula: &Formula,\n config: &Config,\n client: &Client,\n progress_callback: Option,\n) -> Result<(PathBuf, bool)> {\n debug!(\"Attempting to download bottle for {}\", formula.name);\n let (platform_tag, bottle_file_spec) = get_bottle_for_platform(formula)?;\n debug!(\n \"Selected bottle spec for platform '{}': URL={}, SHA256={}\",\n platform_tag, bottle_file_spec.url, bottle_file_spec.sha256\n );\n if bottle_file_spec.url.is_empty() {\n return Err(SpsError::DownloadError(\n formula.name.clone(),\n \"\".to_string(),\n \"Bottle spec has an empty URL.\".to_string(),\n ));\n }\n let standard_version_str = formula.version_str_full();\n let filename = format!(\n \"{}-{}.{}.bottle.tar.gz\",\n formula.name, standard_version_str, platform_tag\n );\n let cache_dir = config.cache_dir().join(\"bottles\");\n fs::create_dir_all(&cache_dir).map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n let bottle_cache_path = cache_dir.join(&filename);\n if bottle_cache_path.is_file() {\n debug!(\"Bottle found in cache: {}\", bottle_cache_path.display());\n if !bottle_file_spec.sha256.is_empty() {\n match verify_checksum(&bottle_cache_path, &bottle_file_spec.sha256) {\n Ok(_) => {\n debug!(\"Using valid cached bottle: {}\", bottle_cache_path.display());\n return Ok((bottle_cache_path, true));\n }\n Err(e) => {\n debug!(\n \"Cached bottle checksum mismatch ({}): {}. Redownloading.\",\n bottle_cache_path.display(),\n e\n );\n let _ = fs::remove_file(&bottle_cache_path);\n }\n }\n } else {\n warn!(\n \"Using cached bottle without checksum verification (checksum not specified): {}\",\n bottle_cache_path.display()\n );\n return Ok((bottle_cache_path, true));\n }\n } else {\n debug!(\"Bottle not found in cache.\");\n }\n let bottle_url_str = &bottle_file_spec.url;\n let registry_domain = config\n .artifact_domain\n .as_deref()\n .unwrap_or(oci::DEFAULT_GHCR_DOMAIN);\n let is_oci_blob_url = (bottle_url_str.contains(\"://ghcr.io/\")\n || bottle_url_str.contains(registry_domain))\n && bottle_url_str.contains(\"/blobs/sha256:\");\n debug!(\n \"Checking URL type: '{}'. Is OCI Blob URL? {}\",\n bottle_url_str, is_oci_blob_url\n );\n if is_oci_blob_url {\n let expected_digest = bottle_url_str.split(\"/blobs/sha256:\").nth(1).unwrap_or(\"\");\n if expected_digest.is_empty() {\n warn!(\n \"Could not extract expected SHA256 digest from OCI URL: {}\",\n bottle_url_str\n );\n }\n debug!(\n \"Detected OCI blob URL, initiating direct blob download: {} (Digest: {})\",\n bottle_url_str, expected_digest\n );\n match oci::download_oci_blob_with_progress(\n bottle_url_str,\n &bottle_cache_path,\n config,\n client,\n expected_digest,\n progress_callback.clone(),\n )\n .await\n {\n Ok(_) => {\n debug!(\n \"Successfully downloaded OCI blob to {}\",\n bottle_cache_path.display()\n );\n }\n Err(e) => {\n error!(\"Failed to download OCI blob from {}: {}\", bottle_url_str, e);\n let _ = fs::remove_file(&bottle_cache_path);\n return Err(SpsError::DownloadError(\n formula.name.clone(),\n bottle_url_str.to_string(),\n format!(\"Failed to download OCI blob: {e}\"),\n ));\n }\n }\n } else {\n debug!(\n \"Detected standard HTTPS URL, using direct download for: {}\",\n bottle_url_str\n );\n match sps_net::http::fetch_formula_source_or_bottle_with_progress(\n formula.name(),\n bottle_url_str,\n &bottle_file_spec.sha256,\n &[],\n config,\n progress_callback,\n )\n .await\n {\n Ok(downloaded_path) => {\n if downloaded_path != bottle_cache_path {\n debug!(\n \"fetch_formula_source_or_bottle returned path {}. Expected: {}. Assuming correct.\",\n downloaded_path.display(),\n bottle_cache_path.display()\n );\n if !bottle_cache_path.exists() {\n error!(\n \"Downloaded path {} exists, but expected final cache path {} does not!\",\n downloaded_path.display(),\n bottle_cache_path.display()\n );\n return Err(SpsError::Generic(format!(\n \"Download path mismatch and final file missing: {}\",\n bottle_cache_path.display()\n )));\n }\n }\n debug!(\n \"Successfully downloaded directly to {}\",\n bottle_cache_path.display()\n );\n }\n Err(e) => {\n error!(\"Failed to download directly from {}: {}\", bottle_url_str, e);\n return Err(e);\n }\n }\n }\n if !bottle_cache_path.exists() {\n error!(\n \"Bottle download process completed, but the final file {} does not exist.\",\n bottle_cache_path.display()\n );\n return Err(SpsError::Generic(format!(\n \"Bottle file missing after download attempt: {}\",\n bottle_cache_path.display()\n )));\n }\n debug!(\n \"Bottle download successful: {}\",\n bottle_cache_path.display()\n );\n Ok((bottle_cache_path, false))\n}\n\npub fn get_bottle_for_platform(formula: &Formula) -> Result<(String, &BottleFileSpec)> {\n let stable_spec = formula.bottle.stable.as_ref().ok_or_else(|| {\n SpsError::Generic(format!(\n \"Formula '{}' has no stable bottle specification.\",\n formula.name\n ))\n })?;\n if stable_spec.files.is_empty() {\n return Err(SpsError::Generic(format!(\n \"Formula '{}' has no bottle files listed in stable spec.\",\n formula.name\n )));\n }\n let current_platform = get_current_platform();\n if current_platform == \"unknown\" || current_platform.contains(\"unknown\") {\n debug!(\n \"Could not reliably determine current platform ('{}'). Bottle selection might be incorrect.\",\n current_platform\n );\n }\n debug!(\n \"Determining bottle for current platform: {}\",\n current_platform\n );\n debug!(\n \"Available bottle platforms in formula spec: {:?}\",\n stable_spec.files.keys().cloned().collect::>()\n );\n if let Some(spec) = stable_spec.files.get(¤t_platform) {\n debug!(\n \"Found exact bottle match for platform: {}\",\n current_platform\n );\n return Ok((current_platform.clone(), spec));\n }\n debug!(\"No exact match found for {}\", current_platform);\n const ARM_MACOS_VERSIONS: &[&str] = &[\"sequoia\", \"sonoma\", \"ventura\", \"monterey\", \"big_sur\"];\n const INTEL_MACOS_VERSIONS: &[&str] = &[\n \"sequoia\", \"sonoma\", \"ventura\", \"monterey\", \"big_sur\", \"catalina\", \"mojave\",\n ];\n if cfg!(target_os = \"macos\") {\n if let Some(current_os_name) = current_platform\n .strip_prefix(\"arm64_\")\n .or(Some(current_platform.as_str()))\n {\n let version_list = if current_platform.starts_with(\"arm64_\") {\n ARM_MACOS_VERSIONS\n } else {\n INTEL_MACOS_VERSIONS\n };\n if let Some(current_os_index) = version_list.iter().position(|&v| v == current_os_name)\n {\n for target_os_name in version_list.iter().skip(current_os_index) {\n let target_tag = if current_platform.starts_with(\"arm64_\") {\n format!(\"arm64_{target_os_name}\")\n } else {\n target_os_name.to_string()\n };\n if let Some(spec) = stable_spec.files.get(&target_tag) {\n debug!(\n \"No bottle found for exact platform '{}'. Using compatible older bottle '{}'.\",\n current_platform, target_tag\n );\n return Ok((target_tag, spec));\n }\n }\n debug!(\n \"Checked compatible older macOS versions ({:?}), no suitable bottle found.\",\n &version_list[current_os_index..]\n );\n } else {\n debug!(\n \"Current OS '{}' not found in known macOS version list.\",\n current_os_name\n );\n }\n } else {\n debug!(\n \"Could not extract OS name from platform tag '{}'\",\n current_platform\n );\n }\n }\n if current_platform.starts_with(\"arm64_\") {\n if let Some(spec) = stable_spec.files.get(\"arm64_big_sur\") {\n debug!(\n \"No specific OS bottle found for {}. Falling back to 'arm64_big_sur' bottle.\",\n current_platform\n );\n return Ok((\"arm64_big_sur\".to_string(), spec));\n }\n debug!(\"No 'arm64_big_sur' fallback bottle tag found.\");\n } else if cfg!(target_os = \"macos\") {\n if let Some(spec) = stable_spec.files.get(\"big_sur\") {\n debug!(\n \"No specific OS bottle found for {}. Falling back to 'big_sur' bottle.\",\n current_platform\n );\n return Ok((\"big_sur\".to_string(), spec));\n }\n debug!(\"No 'big_sur' fallback bottle tag found.\");\n }\n if let Some(spec) = stable_spec.files.get(\"all\") {\n debug!(\n \"No platform-specific or OS-specific bottle found for {}. Using 'all' platform bottle.\",\n current_platform\n );\n return Ok((\"all\".to_string(), spec));\n }\n debug!(\"No 'all' platform bottle found.\");\n Err(SpsError::DownloadError(\n formula.name.clone(),\n \"\".to_string(),\n format!(\n \"No compatible bottle found for platform '{}'. Available: {:?}\",\n current_platform,\n stable_spec.files.keys().collect::>()\n ),\n ))\n}\n\npub fn install_bottle(bottle_path: &Path, formula: &Formula, config: &Config) -> Result {\n let install_dir = formula.install_prefix(config.cellar_dir().as_path())?;\n if install_dir.exists() {\n debug!(\n \"Removing existing keg directory before installing: {}\",\n install_dir.display()\n );\n fs::remove_dir_all(&install_dir).map_err(|e| {\n SpsError::InstallError(format!(\n \"Failed to remove existing keg {}: {}\",\n install_dir.display(),\n e\n ))\n })?;\n }\n if let Some(parent_dir) = install_dir.parent() {\n fs::create_dir_all(parent_dir).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\n \"Failed to create parent dir {}: {}\",\n parent_dir.display(),\n e\n ),\n )))\n })?;\n } else {\n return Err(SpsError::InstallError(format!(\n \"Could not determine parent directory for install path: {}\",\n install_dir.display()\n )));\n }\n fs::create_dir_all(&install_dir).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed to create keg dir {}: {}\", install_dir.display(), e),\n )))\n })?;\n let strip_components = 2;\n debug!(\n \"Extracting bottle archive {} to {} with strip_components={}\",\n bottle_path.display(),\n install_dir.display(),\n strip_components\n );\n extract_archive(bottle_path, &install_dir, strip_components, \"gz\")?;\n debug!(\n \"Ensuring write permissions for extracted files in {}\",\n install_dir.display()\n );\n ensure_write_permissions(&install_dir)?;\n debug!(\"Performing bottle relocation in {}\", install_dir.display());\n perform_bottle_relocation(formula, &install_dir, config)?;\n ensure_llvm_symlinks(&install_dir, formula, config)?;\n crate::install::bottle::write_receipt(formula, &install_dir, \"bottle\")?;\n debug!(\n \"Bottle installation complete for {} at {}\",\n formula.name(),\n install_dir.display()\n );\n Ok(install_dir)\n}\n\nfn ensure_write_permissions(path: &Path) -> Result<()> {\n if !path.exists() {\n debug!(\n \"Path {} does not exist, cannot ensure write permissions.\",\n path.display()\n );\n return Ok(());\n }\n for entry_result in WalkDir::new(path).into_iter().filter_map(|e| e.ok()) {\n let entry_path = entry_result.path();\n if entry_path == path && entry_result.depth() == 0 {\n continue;\n }\n match fs::metadata(entry_path) {\n Ok(metadata) => {\n let mut perms = metadata.permissions();\n let _is_readonly = perms.readonly();\n #[cfg(unix)]\n {\n let current_mode = perms.mode();\n let new_mode = current_mode | 0o200;\n if new_mode != current_mode {\n perms.set_mode(new_mode);\n let _ = fs::set_permissions(entry_path, perms);\n }\n }\n #[cfg(not(unix))]\n {\n if _is_readonly {\n perms.set_readonly(false);\n let _ = fs::set_permissions(entry_path, perms);\n }\n }\n }\n Err(_e) => {}\n }\n }\n Ok(())\n}\n\nfn perform_bottle_relocation(formula: &Formula, install_dir: &Path, config: &Config) -> Result<()> {\n let mut repl: HashMap = HashMap::new();\n repl.insert(\n \"@@HOMEBREW_CELLAR@@\".into(),\n config.cellar_dir().to_string_lossy().into(),\n );\n repl.insert(\n \"@@HOMEBREW_PREFIX@@\".into(),\n config.sps_root().to_string_lossy().into(),\n );\n let _prefix_path_str = config.sps_root().to_string_lossy();\n let library_path_str = config\n .sps_root()\n .join(\"Library\")\n .to_string_lossy()\n .to_string(); // Assuming Library is under sps_root for this placeholder\n // HOMEBREW_REPOSITORY usually points to the Homebrew/brew git repo, not relevant for sps in\n // this context. If needed for a specific formula, it should point to\n // /opt/sps or similar.\n repl.insert(\n \"@@HOMEBREW_REPOSITORY@@\".into(),\n config.sps_root().to_string_lossy().into(),\n );\n repl.insert(\"@@HOMEBREW_LIBRARY@@\".into(), library_path_str.to_string());\n\n let formula_opt_path = config.formula_opt_path(formula.name());\n let formula_opt_str = formula_opt_path.to_string_lossy();\n let install_dir_str = install_dir.to_string_lossy();\n if formula_opt_str != install_dir_str {\n repl.insert(formula_opt_str.to_string(), install_dir_str.to_string());\n debug!(\n \"Adding self-opt relocation: {} -> {}\",\n formula_opt_str, install_dir_str\n );\n }\n\n if formula.name().starts_with(\"python@\") {\n let version_full = formula.version_str_full();\n let mut parts = version_full.split('.');\n if let (Some(major), Some(minor)) = (parts.next(), parts.next()) {\n let framework_version = format!(\"{major}.{minor}\");\n let framework_dir = install_dir\n .join(\"Frameworks\")\n .join(\"Python.framework\")\n .join(\"Versions\")\n .join(&framework_version);\n let python_lib = framework_dir.join(\"Python\");\n let python_bin = framework_dir\n .join(\"bin\")\n .join(format!(\"python{major}.{minor}\"));\n\n let absolute_python_lib_path_obj = install_dir\n .join(\"Frameworks\")\n .join(\"Python.framework\")\n .join(\"Versions\")\n .join(&framework_version)\n .join(\"Python\");\n let new_id_abs = absolute_python_lib_path_obj.to_str().ok_or_else(|| {\n SpsError::InstallError(format!(\n \"Failed to convert absolute Python library path to string: {}\",\n absolute_python_lib_path_obj.display()\n ))\n })?;\n\n debug!(\n \"Setting absolute ID for {}: {}\",\n python_lib.display(),\n new_id_abs\n );\n let status_id = StdCommand::new(\"install_name_tool\")\n .args([\"-id\", new_id_abs, python_lib.to_str().unwrap()])\n .stdout(Stdio::null())\n .stderr(Stdio::null())\n .status()\n .map_err(|e| SpsError::Io(Arc::new(e)))?;\n if !status_id.success() {\n error!(\"install_name_tool -id failed for {}\", python_lib.display());\n return Err(SpsError::InstallError(format!(\n \"Failed to set absolute id on Python dynamic library: {}\",\n python_lib.display()\n )));\n }\n\n debug!(\"Skipping -add_rpath as absolute paths are used for Python linkage.\");\n\n let old_load_placeholder = format!(\n \"@@HOMEBREW_CELLAR@@/{}/{}/Frameworks/Python.framework/Versions/{}/Python\",\n formula.name(),\n version_full,\n framework_version\n );\n let old_load_resource_placeholder = format!(\n \"@@HOMEBREW_CELLAR@@/{}/{}/Frameworks/Python.framework/Versions/{}/Resources/Python.app/Contents/MacOS/Python\",\n formula.name(),\n version_full,\n framework_version\n );\n let install_dir_str_ref = install_dir.to_string_lossy();\n let abs_old_load = format!(\n \"{install_dir_str_ref}/Frameworks/Python.framework/Versions/{framework_version}/Python\"\n );\n let abs_old_load_resource = format!(\n \"{install_dir_str_ref}/Frameworks/Python.framework/Versions/{framework_version}/Resources/Python.app/Contents/MacOS/Python\"\n );\n\n let run_change = |old: &str, new: &str, target: &Path| -> Result<()> {\n if !target.exists() {\n debug!(\n \"Target {} does not exist, skipping install_name_tool -change.\",\n target.display()\n );\n return Ok(());\n }\n debug!(\n \"Running install_name_tool -change {} {} {}\",\n old,\n new,\n target.display()\n );\n let output = StdCommand::new(\"install_name_tool\")\n .args([\"-change\", old, new, target.to_str().unwrap()])\n .output()\n .map_err(|e| SpsError::Io(Arc::new(e)))?;\n\n if !output.status.success() {\n let stderr = String::from_utf8_lossy(&output.stderr);\n if !stderr.contains(\"file not found\")\n && !stderr.contains(\"no LC_LOAD_DYLIB command specifying file\")\n && !stderr.contains(\"is not a Mach-O file\")\n && !stderr.contains(\"object file format invalid\")\n && !stderr.trim().is_empty()\n {\n error!(\n \"install_name_tool -change failed unexpectedly for target {}: {}\",\n target.display(),\n stderr.trim()\n );\n } else {\n debug!(\n \"install_name_tool -change: old path '{}' likely not found or target '{}' not relevant (stderr: {}).\",\n old,\n target.display(),\n stderr.trim()\n );\n }\n }\n Ok(())\n };\n\n debug!(\"Patching main executable: {}\", python_bin.display());\n run_change(&old_load_placeholder, new_id_abs, &python_bin)?;\n run_change(&old_load_resource_placeholder, new_id_abs, &python_bin)?;\n run_change(&abs_old_load, new_id_abs, &python_bin)?;\n run_change(&abs_old_load_resource, new_id_abs, &python_bin)?;\n\n let python_app = framework_dir\n .join(\"Resources\")\n .join(\"Python.app\")\n .join(\"Contents\")\n .join(\"MacOS\")\n .join(\"Python\");\n\n if python_app.exists() {\n debug!(\n \"Explicitly patching Python.app executable: {}\",\n python_app.display()\n );\n run_change(&old_load_placeholder, new_id_abs, &python_app)?;\n run_change(&abs_old_load, new_id_abs, &python_app)?;\n run_change(&old_load_resource_placeholder, new_id_abs, &python_app)?;\n run_change(&abs_old_load_resource, new_id_abs, &python_app)?;\n } else {\n warn!(\n \"Python.app executable not found at {}, skipping explicit patch.\",\n python_app.display()\n );\n }\n\n codesign_path(&python_lib)?;\n codesign_path(&python_bin)?;\n if python_app.exists() {\n codesign_path(&python_app)?;\n } else {\n debug!(\n \"Python.app binary not found at {}, skipping codesign.\",\n python_app.display()\n );\n }\n }\n }\n\n if let Some(perl_path) = find_brewed_perl(config.sps_root()).or_else(|| {\n if cfg!(target_os = \"macos\") {\n Some(PathBuf::from(\"/usr/bin/perl\"))\n } else {\n None\n }\n }) {\n repl.insert(\n \"@@HOMEBREW_PERL@@\".into(),\n perl_path.to_string_lossy().into(),\n );\n }\n\n match formula.dependencies() {\n Ok(deps) => {\n if let Some(openjdk) = deps\n .iter()\n .find(|d| d.name.starts_with(\"openjdk\"))\n .map(|d| d.name.clone())\n {\n let openjdk_opt = config.formula_opt_path(&openjdk);\n repl.insert(\n \"@@HOMEBREW_JAVA@@\".into(),\n openjdk_opt\n .join(\"libexec/openjdk.jdk/Contents/Home\")\n .to_string_lossy()\n .into(),\n );\n }\n }\n Err(e) => {\n warn!(\n \"Could not check formula dependencies during relocation for {}: {}\",\n formula.name(),\n e\n );\n }\n }\n\n repl.insert(\"HOMEBREW_RELOCATE_RPATHS\".into(), \"1\".into());\n\n let opt_placeholder = format!(\n \"@@HOMEBREW_OPT_{}@@\",\n formula.name().to_uppercase().replace(['-', '+', '.'], \"_\")\n );\n repl.insert(\n opt_placeholder,\n config\n .formula_opt_path(formula.name())\n .to_string_lossy()\n .into(),\n );\n\n match formula.dependencies() {\n Ok(deps) => {\n let llvm_dep_name = deps\n .iter()\n .find(|d| d.name.starts_with(\"llvm\"))\n .map(|d| d.name.clone());\n if let Some(name) = llvm_dep_name {\n let llvm_opt_path = config.formula_opt_path(&name);\n let llvm_lib = llvm_opt_path.join(\"lib\");\n if llvm_lib.is_dir() {\n repl.insert(\n \"@loader_path/../lib\".into(),\n llvm_lib.to_string_lossy().into(),\n );\n repl.insert(\n format!(\n \"@@HOMEBREW_OPT_{}@@/lib\",\n name.to_uppercase().replace(['-', '+', '.'], \"_\")\n ),\n llvm_lib.to_string_lossy().into(),\n );\n }\n }\n }\n Err(e) => {\n warn!(\n \"Could not check formula dependencies during LLVM relocation for {}: {}\",\n formula.name(),\n e\n );\n }\n }\n\n tracing::debug!(\"Relocation table:\");\n for (k, v) in &repl {\n tracing::debug!(\"{} → {}\", k, v);\n }\n original_relocation_scan_and_patch(formula, install_dir, config, repl)\n}\n\nfn original_relocation_scan_and_patch(\n _formula: &Formula,\n install_dir: &Path,\n _config: &Config,\n replacements: HashMap,\n) -> Result<()> {\n let mut text_replaced_count = 0;\n let mut macho_patched_count = 0;\n let mut permission_errors = 0;\n let mut macho_errors = 0;\n let mut io_errors = 0;\n let mut files_to_chmod: Vec = Vec::new();\n for entry in WalkDir::new(install_dir).into_iter().filter_map(|e| e.ok()) {\n let path = entry.path();\n let file_type = entry.file_type();\n if path\n .components()\n .any(|c| c.as_os_str().to_string_lossy().ends_with(\".app\"))\n {\n if file_type.is_file() {\n debug!(\"Skipping relocation inside .app bundle: {}\", path.display());\n }\n continue;\n }\n if file_type.is_symlink() {\n debug!(\"Checking symlink for potential chmod: {}\", path.display());\n if path\n .parent()\n .is_some_and(|p| p.ends_with(\"bin\") || p.ends_with(\"sbin\"))\n {\n files_to_chmod.push(path.to_path_buf());\n }\n continue;\n }\n if !file_type.is_file() {\n continue;\n }\n let (meta, initially_executable) = match fs::metadata(path) {\n Ok(m) => {\n #[cfg(unix)]\n let ie = m.permissions().mode() & 0o111 != 0;\n #[cfg(not(unix))]\n let ie = true;\n (m, ie)\n }\n Err(_e) => {\n debug!(\"Failed to get metadata for {}: {}\", path.display(), _e);\n io_errors += 1;\n continue;\n }\n };\n let is_in_exec_dir = path\n .parent()\n .is_some_and(|p| p.ends_with(\"bin\") || p.ends_with(\"sbin\"));\n if meta.permissions().readonly() {\n #[cfg(unix)]\n {\n let mut perms = meta.permissions();\n let current_mode = perms.mode();\n let new_mode = current_mode | 0o200;\n if new_mode != current_mode {\n perms.set_mode(new_mode);\n if fs::set_permissions(path, perms).is_err() {\n debug!(\n \"Skipping readonly file (and couldn't make writable): {}\",\n path.display()\n );\n continue;\n } else {\n debug!(\"Made readonly file writable: {}\", path.display());\n }\n }\n }\n #[cfg(not(unix))]\n {\n debug!(\n \"Skipping potentially readonly file on non-unix: {}\",\n path.display()\n );\n continue;\n }\n }\n let mut was_modified = false;\n let mut skipped_paths_for_file = Vec::new();\n if cfg!(target_os = \"macos\")\n && (initially_executable\n || is_in_exec_dir\n || path\n .extension()\n .is_some_and(|e| e == \"dylib\" || e == \"so\" || e == \"bundle\"))\n {\n match macho::patch_macho_file(path, &replacements) {\n Ok((true, skipped_paths)) => {\n macho_patched_count += 1;\n was_modified = true;\n skipped_paths_for_file = skipped_paths;\n }\n Ok((false, skipped_paths)) => {\n // Not Mach-O or no patches needed, but might have skipped paths\n skipped_paths_for_file = skipped_paths;\n }\n Err(SpsError::PathTooLongError(e)) => { // Specifically catch path too long\n error!(\n \"Mach-O patch failed (path too long) for {}: {}\",\n path.display(),\n e\n );\n macho_errors += 1;\n // Continue scanning other files even if one fails this way\n continue;\n }\n Err(SpsError::CodesignError(e)) => { // Specifically catch codesign errors\n error!(\n \"Mach-O patch failed (codesign error) for {}: {}\",\n path.display(),\n e\n );\n macho_errors += 1;\n // Continue scanning other files\n continue;\n }\n // Catch generic MachOError or Object error, treat as non-fatal for text replace\n Err(e @ SpsError::MachOError(_))\n | Err(e @ SpsError::Object(_))\n | Err(e @ SpsError::Generic(_)) // Catch Generic errors from patch_macho too\n | Err(e @ SpsError::Io(_)) => { // Catch IO errors from patch_macho\n debug!(\n \"Mach-O processing/patching failed for {}: {}. Skipping Mach-O patch for this file.\",\n path.display(),\n e\n );\n // Don't increment macho_errors here, as we fallback to text replace\n io_errors += 1; // Count as IO or generic error instead\n }\n // Catch other specific errors if needed\n Err(e) => {\n debug!(\n \"Unexpected error during Mach-O check/patch for {}: {}. Falling back to text replacer.\",\n path.display(),\n e\n );\n io_errors += 1;\n }\n }\n\n // Handle paths that were too long for Mach-O patching with install_name_tool fallback\n if !skipped_paths_for_file.is_empty() {\n debug!(\n \"Applying install_name_tool fallback for {} skipped paths in {}\",\n skipped_paths_for_file.len(),\n path.display()\n );\n debug!(\n \"Applying install_name_tool fallback for {} skipped paths in {}\",\n skipped_paths_for_file.len(),\n path.display()\n );\n for skipped in &skipped_paths_for_file {\n match apply_install_name_tool_change(&skipped.old_path, &skipped.new_path, path)\n {\n Ok(()) => {\n debug!(\n \"Successfully applied install_name_tool fallback: '{}' -> '{}' in {}\",\n skipped.old_path, skipped.new_path, path.display()\n );\n was_modified = true;\n }\n Err(e) => {\n warn!(\n \"install_name_tool fallback failed for '{}' -> '{}' in {}: {}\",\n skipped.old_path,\n skipped.new_path,\n path.display(),\n e\n );\n macho_errors += 1;\n }\n }\n }\n }\n }\n // Fallback to text replacement if not modified by Mach-O patching\n if !was_modified {\n // Heuristic check for text file (avoid reading huge binaries)\n let mut is_likely_text = false;\n if meta.len() < 5 * 1024 * 1024 {\n if let Ok(mut f) = File::open(path) {\n let mut buf = [0; 1024];\n match f.read(&mut buf) {\n Ok(n) if n > 0 => {\n if !buf[..n].contains(&0) {\n is_likely_text = true;\n }\n }\n Ok(_) => {\n is_likely_text = true;\n }\n Err(_) => {}\n }\n }\n }\n\n if is_likely_text {\n // Read the file content as string\n if let Ok(content) = fs::read_to_string(path) {\n let mut new_content = content.clone();\n let mut replacements_made = false;\n for (placeholder, replacement) in &replacements {\n if new_content.contains(placeholder) {\n new_content = new_content.replace(placeholder, replacement);\n replacements_made = true;\n }\n }\n // Write back only if changes were made\n if replacements_made {\n match write_text_file_atomic(path, &new_content) {\n Ok(_) => {\n text_replaced_count += 1;\n was_modified = true; // Mark as modified for chmod check\n }\n Err(e) => {\n error!(\n \"Failed to write replaced text to {}: {}\",\n path.display(),\n e\n );\n io_errors += 1;\n }\n }\n }\n } else if meta.len() > 0 {\n debug!(\n \"Could not read {} as string for text replacement.\",\n path.display()\n );\n io_errors += 1;\n }\n } else if meta.len() >= 5 * 1024 * 1024 {\n debug!(\n \"Skipping text replacement for large file: {}\",\n path.display()\n );\n } else {\n debug!(\n \"Skipping text replacement for likely binary file: {}\",\n path.display()\n );\n }\n }\n if was_modified || initially_executable || is_in_exec_dir {\n files_to_chmod.push(path.to_path_buf());\n }\n }\n\n #[cfg(unix)]\n {\n debug!(\n \"Ensuring execute permissions for {} potentially executable files/links\",\n files_to_chmod.len()\n );\n let unique_files_to_chmod: HashSet<_> = files_to_chmod.into_iter().collect();\n for p in &unique_files_to_chmod {\n if !p.exists() && p.symlink_metadata().is_err() {\n debug!(\"Skipping chmod for non-existent path: {}\", p.display());\n continue;\n }\n match fs::symlink_metadata(p) {\n Ok(m) => {\n if m.is_file() {\n let mut perms = m.permissions();\n let current_mode = perms.mode();\n let new_mode = current_mode | 0o111;\n if new_mode != current_mode {\n perms.set_mode(new_mode);\n if let Err(e) = fs::set_permissions(p, perms) {\n debug!(\"Failed to set +x on {}: {}\", p.display(), e);\n permission_errors += 1;\n }\n }\n }\n }\n Err(e) => {\n debug!(\n \"Could not stat {} during final chmod pass: {}\",\n p.display(),\n e\n );\n permission_errors += 1;\n }\n }\n }\n }\n\n debug!(\n \"Relocation scan complete. Text files replaced: {}, Mach-O files patched: {}\",\n text_replaced_count, macho_patched_count\n );\n if permission_errors > 0 || macho_errors > 0 || io_errors > 0 {\n debug!(\n \"Bottle relocation finished with issues: {} chmod errors, {} Mach-O errors, {} IO errors in {}.\",\n permission_errors,\n macho_errors,\n io_errors,\n install_dir.display()\n );\n if macho_errors > 0 {\n return Err(SpsError::InstallError(format!(\n \"Bottle relocation failed due to {} Mach-O errors in {}\",\n macho_errors,\n install_dir.display()\n )));\n }\n }\n Ok(())\n}\n\nfn codesign_path(target: &Path) -> Result<()> {\n debug!(\"Re‑signing: {}\", target.display());\n let status = StdCommand::new(\"codesign\")\n .args([\n \"-s\",\n \"-\",\n \"--force\",\n \"--preserve-metadata=identifier,entitlements\",\n target\n .to_str()\n .ok_or_else(|| SpsError::Generic(\"Non‑UTF8 path for codesign\".into()))?,\n ])\n .stdout(Stdio::null())\n .stderr(Stdio::null())\n .status()\n .map_err(|e| SpsError::Io(Arc::new(e)))?;\n if !status.success() {\n return Err(SpsError::CodesignError(format!(\n \"codesign failed for {}\",\n target.display()\n )));\n }\n Ok(())\n}\nfn write_text_file_atomic(original_path: &Path, content: &str) -> Result<()> {\n let dir = original_path.parent().ok_or_else(|| {\n SpsError::Generic(format!(\n \"Cannot get parent directory for {}\",\n original_path.display()\n ))\n })?;\n // Ensure the directory exists\n fs::create_dir_all(dir).map_err(|e| SpsError::Io(Arc::new(e)))?; // Use Arc::new\n\n let mut temp_file = NamedTempFile::new_in(dir)?;\n let temp_path = temp_file.path().to_path_buf(); // Store path before consuming temp_file\n\n // Write content\n temp_file.write_all(content.as_bytes())?;\n // Ensure data is flushed from application buffer to OS buffer\n temp_file.flush()?;\n // Attempt to sync data from OS buffer to disk (best effort)\n let _ = temp_file.as_file().sync_all();\n\n // Try to preserve original permissions\n let original_perms = fs::metadata(original_path).map(|m| m.permissions()).ok();\n\n // Atomically replace the original file with the temporary file\n temp_file.persist(original_path).map_err(|e| {\n error!(\n \"Failed to persist/rename temporary text file {} over {}: {}\",\n temp_path.display(), // Use stored path for logging\n original_path.display(),\n e.error // Log the underlying IO error\n );\n // Return the IO error wrapped in our error type\n SpsError::Io(Arc::new(e.error)) // Use Arc::new\n })?;\n\n // Restore original permissions if we captured them\n if let Some(perms) = original_perms {\n // Ignore errors setting permissions, best effort\n let _ = fs::set_permissions(original_path, perms);\n }\n Ok(())\n}\n\n#[cfg(unix)]\nfn find_brewed_perl(prefix: &Path) -> Option {\n let opt_dir = prefix.join(\"opt\");\n if !opt_dir.is_dir() {\n return None;\n }\n let mut best: Option<(semver::Version, PathBuf)> = None;\n match fs::read_dir(opt_dir) {\n Ok(entries) => {\n for entry_res in entries.flatten() {\n let name = entry_res.file_name();\n let s = name.to_string_lossy();\n let entry_path = entry_res.path();\n if !entry_path.is_dir() {\n continue;\n }\n if let Some(version_part) = s.strip_prefix(\"perl@\") {\n let version_str_padded = if version_part.contains('.') {\n let parts: Vec<&str> = version_part.split('.').collect();\n match parts.len() {\n 1 => format!(\"{}.0.0\", parts[0]), // e.g., perl@5 -> 5.0.0\n 2 => format!(\"{}.{}.0\", parts[0], parts[1]), /* e.g., perl@5.30 -> */\n // 5.30.0\n _ => version_part.to_string(), // Already 3+ parts\n }\n } else {\n format!(\"{version_part}.0.0\") // e.g., perl@5 -> 5.0.0 (handles case with no\n // dot)\n };\n\n if let Ok(v) = semver::Version::parse(&version_str_padded) {\n let candidate_bin = entry_path.join(\"bin/perl\");\n if candidate_bin.is_file()\n && (best.is_none() || v > best.as_ref().unwrap().0)\n {\n best = Some((v, candidate_bin));\n }\n }\n } else if s == \"perl\" {\n let candidate_bin = entry_path.join(\"bin/perl\");\n if candidate_bin.is_file() && best.is_none() {\n if let Ok(v_base) = semver::Version::parse(\"5.0.0\") {\n best = Some((v_base, candidate_bin));\n }\n }\n }\n }\n }\n Err(_e) => {\n debug!(\"Failed to read opt directory during perl search: {}\", _e);\n }\n }\n best.map(|(_, path)| path)\n}\n\n#[cfg(not(unix))]\nfn find_brewed_perl(_prefix: &Path) -> Option {\n None\n}\nfn ensure_llvm_symlinks(install_dir: &Path, formula: &Formula, config: &Config) -> Result<()> {\n let lib_dir = install_dir.join(\"lib\");\n if !lib_dir.exists() {\n debug!(\n \"Skipping LLVM symlink creation as lib dir is missing in {}\",\n install_dir.display()\n );\n return Ok(());\n }\n\n let llvm_dep_name = match formula.dependencies() {\n Ok(deps) => deps\n .iter()\n .find(|d| d.name.starts_with(\"llvm\"))\n .map(|dep| dep.name.clone()),\n Err(e) => {\n warn!(\n \"Could not check formula dependencies for LLVM symlink creation in {}: {}\",\n formula.name(),\n e\n );\n return Ok(()); // Don't error, just skip\n }\n };\n\n // Proceed only if llvm_dep_name is Some\n let llvm_dep_name = match llvm_dep_name {\n Some(name) => name,\n None => {\n debug!(\n \"Formula {} does not list an LLVM dependency.\",\n formula.name()\n );\n return Ok(());\n }\n };\n\n let llvm_opt_path = config.formula_opt_path(&llvm_dep_name);\n let llvm_lib_filename = if cfg!(target_os = \"macos\") {\n \"libLLVM.dylib\"\n } else if cfg!(target_os = \"linux\") {\n \"libLLVM.so\"\n } else {\n warn!(\"LLVM library filename unknown for target OS, skipping symlink.\");\n return Ok(());\n };\n let llvm_lib_path_in_opt = llvm_opt_path.join(\"lib\").join(llvm_lib_filename);\n if !llvm_lib_path_in_opt.exists() {\n debug!(\n \"Required LLVM library not found at {}. Cannot create symlink in {}.\",\n llvm_lib_path_in_opt.display(),\n formula.name()\n );\n return Ok(());\n }\n let symlink_target_path = lib_dir.join(llvm_lib_filename);\n if symlink_target_path.exists() || symlink_target_path.symlink_metadata().is_ok() {\n debug!(\n \"Symlink or file already exists at {}. Skipping creation.\",\n symlink_target_path.display()\n );\n return Ok(());\n }\n #[cfg(unix)]\n {\n if let Some(parent) = symlink_target_path.parent() {\n if !parent.exists() {\n fs::create_dir_all(parent)?;\n }\n }\n match symlink(&llvm_lib_path_in_opt, &symlink_target_path) {\n Ok(_) => debug!(\n \"Created symlink {} -> {}\",\n symlink_target_path.display(),\n llvm_lib_path_in_opt.display()\n ),\n Err(e) => {\n // Log as warning, don't fail install\n warn!(\n \"Failed to create LLVM symlink {} -> {}: {}\",\n symlink_target_path.display(),\n llvm_lib_path_in_opt.display(),\n e\n );\n }\n }\n\n let rustlib_dir = install_dir.join(\"lib\").join(\"rustlib\");\n if rustlib_dir.is_dir() {\n if let Ok(entries) = fs::read_dir(&rustlib_dir) {\n for entry in entries.flatten() {\n let triple_path = entry.path();\n if triple_path.is_dir() {\n let triple_lib_dir = triple_path.join(\"lib\");\n if triple_lib_dir.is_dir() {\n let nested_symlink = triple_lib_dir.join(llvm_lib_filename);\n\n if nested_symlink.exists() || nested_symlink.symlink_metadata().is_ok()\n {\n debug!(\n \"Symlink or file already exists at {}, skipping.\",\n nested_symlink.display()\n );\n continue;\n }\n\n if let Some(parent) = nested_symlink.parent() {\n let _ = fs::create_dir_all(parent);\n }\n match symlink(&llvm_lib_path_in_opt, &nested_symlink) {\n Ok(_) => debug!(\n \"Created symlink {} -> {}\",\n nested_symlink.display(),\n llvm_lib_path_in_opt.display()\n ),\n Err(e) => warn!(\n \"Failed to create LLVM symlink {} -> {}: {}\",\n nested_symlink.display(),\n llvm_lib_path_in_opt.display(),\n e\n ),\n }\n }\n }\n }\n }\n }\n }\n Ok(())\n}\n\n/// Applies a path change using install_name_tool as a fallback for Mach-O files\n/// where the path replacement is too long for direct binary patching.\nfn apply_install_name_tool_change(old_path: &str, new_path: &str, target: &Path) -> Result<()> {\n if !target.exists() {\n debug!(\n \"Target {} does not exist, skipping install_name_tool fallback.\",\n target.display()\n );\n return Ok(());\n }\n\n debug!(\n \"Running install_name_tool -change {} {} {}\",\n old_path,\n new_path,\n target.display()\n );\n\n let output = StdCommand::new(\"install_name_tool\")\n .args([\"-change\", old_path, new_path, target.to_str().unwrap()])\n .output()\n .map_err(|e| SpsError::Io(Arc::new(e)))?;\n\n if !output.status.success() {\n let stderr = String::from_utf8_lossy(&output.stderr);\n if !stderr.contains(\"file not found\")\n && !stderr.contains(\"no LC_LOAD_DYLIB command specifying file\")\n && !stderr.contains(\"is not a Mach-O file\")\n && !stderr.contains(\"object file format invalid\")\n && !stderr.trim().is_empty()\n {\n error!(\n \"install_name_tool -change failed unexpectedly for target {}: {}\",\n target.display(),\n stderr.trim()\n );\n return Err(SpsError::InstallError(format!(\n \"install_name_tool failed for {}: {}\",\n target.display(),\n stderr.trim()\n )));\n } else {\n debug!(\n \"install_name_tool -change: old path '{}' likely not found or target '{}' not relevant (stderr: {}).\",\n old_path,\n target.display(),\n stderr.trim()\n );\n return Ok(()); // No changes made, skip re-signing\n }\n }\n\n // Re-sign the binary after making changes (required on Apple Silicon)\n #[cfg(all(target_os = \"macos\", target_arch = \"aarch64\"))]\n {\n debug!(\n \"Re-signing binary after install_name_tool change: {}\",\n target.display()\n );\n codesign_path(target)?;\n }\n\n debug!(\n \"Successfully applied install_name_tool fallback for {} -> {} in {}\",\n old_path,\n new_path,\n target.display()\n );\n\n Ok(())\n}\n"], ["/sps/sps-core/src/uninstall/cask.rs", "// sps-core/src/uninstall/cask.rs\nuse std::fs;\nuse std::path::{Path, PathBuf};\nuse std::process::{Command, Stdio};\n\nuse lazy_static::lazy_static;\nuse regex::Regex;\n// serde_json is used for CaskInstallManifest deserialization\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::{Cask, ZapActionDetail};\nuse tracing::{debug, error, warn};\nuse trash; // This will be used by trash_path\n\n// Import helpers from the common module within the uninstall scope\nuse super::common::{expand_tilde, is_safe_path, remove_filesystem_artifact};\nuse crate::check::installed::InstalledPackageInfo;\n// Corrected import path if install::cask::helpers is where it lives now\nuse crate::install::cask::helpers::{\n cleanup_empty_parent_dirs_in_private_store,\n remove_path_robustly as remove_path_robustly_from_install_helpers,\n};\nuse crate::install::cask::CaskInstallManifest;\n#[cfg(target_os = \"macos\")]\nuse crate::utils::applescript;\n\nlazy_static! {\n static ref VALID_PKGID_RE: Regex = Regex::new(r\"^[a-zA-Z0-9._-]+$\").unwrap();\n static ref VALID_LABEL_RE: Regex = Regex::new(r\"^[a-zA-Z0-9._-]+$\").unwrap();\n static ref VALID_SCRIPT_PATH_RE: Regex = Regex::new(r\"^[a-zA-Z0-9/._-]+$\").unwrap();\n static ref VALID_SIGNAL_RE: Regex = Regex::new(r\"^[A-Z0-9]+$\").unwrap();\n static ref VALID_BUNDLE_ID_RE: Regex =\n Regex::new(r\"^[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)+$\").unwrap();\n}\n\n/// Performs a \"soft\" uninstall for a Cask.\n/// It processes the `CASK_INSTALL_MANIFEST.json` to remove linked artifacts\n/// and then updates the manifest to mark the cask as not currently installed.\n/// The Cask's versioned directory in the Caskroom is NOT removed.\npub fn uninstall_cask_artifacts(info: &InstalledPackageInfo, config: &Config) -> Result<()> {\n debug!(\n \"Soft uninstalling Cask artifacts for {} version {}\",\n info.name, info.version\n );\n let manifest_path = info.path.join(\"CASK_INSTALL_MANIFEST.json\");\n let mut removal_errors: Vec = Vec::new();\n\n if manifest_path.is_file() {\n debug!(\n \"Processing manifest for soft uninstall: {}\",\n manifest_path.display()\n );\n match fs::read_to_string(&manifest_path) {\n Ok(manifest_str) => match serde_json::from_str::(&manifest_str) {\n Ok(mut manifest) => {\n if !manifest.is_installed {\n debug!(\"Cask {} version {} is already marked as uninstalled in manifest. Nothing to do for soft uninstall.\", info.name, info.version);\n return Ok(());\n }\n\n debug!(\n \"Soft uninstalling {} artifacts listed in manifest for {} {}...\",\n manifest.artifacts.len(),\n info.name,\n info.version\n );\n for artifact in manifest.artifacts.iter().rev() {\n if !process_artifact_uninstall_core(artifact, config, false) {\n removal_errors.push(format!(\"Failed to remove artifact: {artifact:?}\"));\n }\n }\n\n manifest.is_installed = false;\n match fs::File::create(&manifest_path) {\n Ok(file) => {\n let writer = std::io::BufWriter::new(file);\n if let Err(e) = serde_json::to_writer_pretty(writer, &manifest) {\n warn!(\n \"Failed to update manifest {}: {}\",\n manifest_path.display(),\n e\n );\n } else {\n debug!(\n \"Manifest updated successfully for soft uninstall: {}\",\n manifest_path.display()\n );\n }\n }\n Err(e) => {\n warn!(\n \"Failed to open manifest for writing (soft uninstall) at {}: {}\",\n manifest_path.display(),\n e\n );\n }\n }\n }\n Err(e) => warn!(\n \"Failed to parse cask manifest {}: {}. Cannot perform detailed soft uninstall.\",\n manifest_path.display(),\n e\n ),\n },\n Err(e) => warn!(\n \"Failed to read cask manifest {}: {}. Cannot perform detailed soft uninstall.\",\n manifest_path.display(),\n e\n ),\n }\n } else {\n warn!(\n \"No CASK_INSTALL_MANIFEST.json found in {}. Cannot perform detailed soft uninstall for {} {}.\",\n info.path.display(),\n info.name,\n info.version\n );\n }\n\n if removal_errors.is_empty() {\n Ok(())\n } else {\n Err(SpsError::InstallError(format!(\n \"Errors during cask artifact soft removal for {}: {}\",\n info.name,\n removal_errors.join(\"; \")\n )))\n }\n}\n\n/// Performs a \"zap\" uninstall for a Cask, removing files defined in `zap` stanzas\n/// and cleaning up the private store. Also marks the cask as uninstalled in its manifest.\npub async fn zap_cask_artifacts(\n info: &InstalledPackageInfo,\n cask_def: &Cask,\n config: &Config,\n) -> Result<()> {\n debug!(\"Starting ZAP process for cask: {}\", cask_def.token);\n let home = config.home_dir();\n let cask_version_path_in_caskroom = &info.path;\n let mut zap_errors: Vec = Vec::new();\n\n let mut primary_app_name_from_manifest: Option = None;\n let manifest_path = cask_version_path_in_caskroom.join(\"CASK_INSTALL_MANIFEST.json\");\n\n if manifest_path.is_file() {\n match fs::read_to_string(&manifest_path) {\n Ok(manifest_str) => match serde_json::from_str::(&manifest_str) {\n Ok(mut manifest) => {\n primary_app_name_from_manifest = manifest.primary_app_file_name.clone();\n if manifest.is_installed {\n manifest.is_installed = false;\n if let Ok(file) = fs::File::create(&manifest_path) {\n let writer = std::io::BufWriter::new(file);\n if let Err(e) = serde_json::to_writer_pretty(writer, &manifest) {\n warn!(\n \"Failed to update manifest during zap for {}: {}\",\n manifest_path.display(),\n e\n );\n }\n } else {\n warn!(\n \"Failed to open manifest for writing during zap at {}\",\n manifest_path.display()\n );\n }\n }\n }\n Err(e) => warn!(\n \"Failed to parse manifest during zap {}: {}\",\n manifest_path.display(),\n e\n ),\n },\n Err(e) => warn!(\n \"Failed to read manifest during zap {}: {}\",\n manifest_path.display(),\n e\n ),\n }\n } else {\n warn!(\"No manifest found at {} during zap. Private store cleanup might be incomplete if app name changed.\", manifest_path.display());\n }\n\n if !cleanup_private_store(\n &cask_def.token,\n &info.version,\n primary_app_name_from_manifest.as_deref(),\n config,\n ) {\n let msg = format!(\n \"Failed to clean up private store for cask {} version {}\",\n cask_def.token, info.version\n );\n warn!(\"{}\", msg);\n zap_errors.push(msg);\n }\n\n let zap_stanzas = match &cask_def.zap {\n Some(stanzas) => stanzas,\n None => {\n debug!(\"No zap stanza found for cask {}\", cask_def.token);\n // Proceed to Caskroom cleanup even if no specific zap actions\n if !remove_filesystem_artifact(cask_version_path_in_caskroom, true) {\n // use_sudo = true for Caskroom\n if cask_version_path_in_caskroom.exists() {\n zap_errors.push(format!(\n \"Failed to remove Caskroom version directory during zap: {}\",\n cask_version_path_in_caskroom.display()\n ));\n }\n }\n if let Some(parent_token_dir) = cask_version_path_in_caskroom.parent() {\n if parent_token_dir.exists() && parent_token_dir.is_dir() {\n match fs::read_dir(parent_token_dir) {\n Ok(mut entries) => {\n if entries.next().is_none()\n && !remove_filesystem_artifact(parent_token_dir, true)\n && parent_token_dir.exists()\n {\n warn!(\"Failed to remove empty Caskroom token directory during zap: {}\", parent_token_dir.display());\n }\n }\n Err(e) => warn!(\n \"Failed to read Caskroom token dir {} during zap: {}\",\n parent_token_dir.display(),\n e\n ),\n }\n }\n }\n return if zap_errors.is_empty() {\n Ok(())\n } else {\n Err(SpsError::Generic(zap_errors.join(\"; \")))\n };\n }\n };\n\n for stanza_map in zap_stanzas {\n for (action_key, action_detail) in &stanza_map.0 {\n debug!(\n \"Processing zap action: {} = {:?}\",\n action_key, action_detail\n );\n match action_detail {\n ZapActionDetail::Trash(paths) => {\n for path_str in paths {\n let target = expand_tilde(path_str, &home);\n if is_safe_path(&target, &home, config) {\n if !trash_path(&target) {\n // Logged within trash_path\n }\n } else {\n zap_errors\n .push(format!(\"Skipped unsafe trash path {}\", target.display()));\n }\n }\n }\n ZapActionDetail::Delete(paths) | ZapActionDetail::Rmdir(paths) => {\n for path_str in paths {\n let target = expand_tilde(path_str, &home);\n if is_safe_path(&target, &home, config) {\n let use_sudo = target.starts_with(\"/Library\")\n || target.starts_with(\"/Applications\");\n let exists_before =\n target.exists() || target.symlink_metadata().is_ok();\n if exists_before {\n if action_key == \"rmdir\" && !target.is_dir() {\n warn!(\"Zap rmdir target is not a directory: {}. Attempting as file delete.\", target.display());\n }\n if !remove_filesystem_artifact(&target, use_sudo)\n && (target.exists() || target.symlink_metadata().is_ok())\n {\n zap_errors.push(format!(\n \"Failed to {} {}\",\n action_key,\n target.display()\n ));\n }\n } else {\n debug!(\n \"Zap target {} not found, skipping removal.\",\n target.display()\n );\n }\n } else {\n zap_errors.push(format!(\n \"Skipped unsafe {} path {}\",\n action_key,\n target.display()\n ));\n }\n }\n }\n ZapActionDetail::Pkgutil(ids_sv) => {\n for id in ids_sv.clone().into_vec() {\n if !VALID_PKGID_RE.is_match(&id) {\n warn!(\"Invalid pkgutil ID format for zap: '{}'. Skipping.\", id);\n zap_errors.push(format!(\"Invalid pkgutil ID: {id}\"));\n continue;\n }\n if !forget_pkgutil_receipt(&id) {\n // Error logged in helper\n }\n }\n }\n ZapActionDetail::Launchctl(labels_sv) => {\n for label in labels_sv.clone().into_vec() {\n if !VALID_LABEL_RE.is_match(&label) {\n warn!(\n \"Invalid launchctl label format for zap: '{}'. Skipping.\",\n label\n );\n zap_errors.push(format!(\"Invalid launchctl label: {label}\"));\n continue;\n }\n let potential_paths = vec![\n home.join(\"Library/LaunchAgents\")\n .join(format!(\"{label}.plist\")),\n PathBuf::from(\"/Library/LaunchAgents\").join(format!(\"{label}.plist\")),\n PathBuf::from(\"/Library/LaunchDaemons\").join(format!(\"{label}.plist\")),\n ];\n let path_to_try = potential_paths.into_iter().find(|p| p.exists());\n if !unload_and_remove_launchd(&label, path_to_try.as_deref()) {\n // Error logged in helper\n }\n }\n }\n ZapActionDetail::Script { executable, args } => {\n let script_path_str = executable;\n if !VALID_SCRIPT_PATH_RE.is_match(script_path_str) {\n error!(\n \"Zap script path contains invalid characters: '{}'. Skipping.\",\n script_path_str\n );\n zap_errors.push(format!(\"Skipped invalid script path: {script_path_str}\"));\n continue;\n }\n let script_full_path = PathBuf::from(script_path_str);\n if !script_full_path.exists() {\n if !script_full_path.is_absolute() {\n if let Ok(found_path) = which::which(&script_full_path) {\n debug!(\n \"Found zap script {} in PATH: {}\",\n script_full_path.display(),\n found_path.display()\n );\n run_zap_script(\n &found_path,\n args.as_ref().map(|v| v.as_slice()),\n &mut zap_errors,\n );\n } else {\n error!(\n \"Zap script '{}' not found (absolute or in PATH). Skipping.\",\n script_full_path.display()\n );\n zap_errors.push(format!(\n \"Zap script not found: {}\",\n script_full_path.display()\n ));\n }\n } else {\n error!(\n \"Absolute zap script path '{}' not found. Skipping.\",\n script_full_path.display()\n );\n zap_errors.push(format!(\n \"Zap script not found: {}\",\n script_full_path.display()\n ));\n }\n continue;\n }\n run_zap_script(\n &script_full_path,\n args.as_ref().map(|v| v.as_slice()),\n &mut zap_errors,\n );\n }\n ZapActionDetail::Signal(signals) => {\n for signal_spec in signals {\n let parts: Vec<&str> = signal_spec.splitn(2, '/').collect();\n if parts.len() != 2 {\n warn!(\"Invalid signal spec format '{}', expected SIGNAL/bundle.id. Skipping.\", signal_spec);\n zap_errors.push(format!(\"Invalid signal spec: {signal_spec}\"));\n continue;\n }\n let signal = parts[0].trim().to_uppercase();\n let bundle_id_or_pattern = parts[1].trim();\n\n if !VALID_SIGNAL_RE.is_match(&signal) {\n warn!(\n \"Invalid signal name '{}' in spec '{}'. Skipping.\",\n signal, signal_spec\n );\n zap_errors.push(format!(\"Invalid signal name: {signal}\"));\n continue;\n }\n\n debug!(\"Sending signal {} to processes matching ID/pattern '{}' (using pkill -f)\", signal, bundle_id_or_pattern);\n let mut cmd = Command::new(\"pkill\");\n cmd.arg(format!(\"-{signal}\")); // Standard signal format for pkill\n cmd.arg(\"-f\");\n cmd.arg(bundle_id_or_pattern);\n cmd.stdout(Stdio::null()).stderr(Stdio::piped());\n match cmd.status() {\n Ok(status) => {\n if status.success() {\n debug!(\"Successfully sent signal {} via pkill to processes matching '{}'.\", signal, bundle_id_or_pattern);\n } else if status.code() == Some(1) {\n debug!(\"No running processes found matching ID/pattern '{}' for signal {} via pkill.\", bundle_id_or_pattern, signal);\n } else {\n warn!(\"pkill command failed for signal {} / ID/pattern '{}' with status: {}\", signal, bundle_id_or_pattern, status);\n }\n }\n Err(e) => {\n error!(\n \"Failed to execute pkill for signal {} / ID/pattern '{}': {}\",\n signal, bundle_id_or_pattern, e\n );\n zap_errors.push(format!(\"Failed to run pkill for signal {signal}\"));\n }\n }\n }\n }\n }\n }\n }\n\n debug!(\n \"Zap: Removing Caskroom version directory: {}\",\n cask_version_path_in_caskroom.display()\n );\n if !remove_filesystem_artifact(cask_version_path_in_caskroom, true)\n && cask_version_path_in_caskroom.exists()\n {\n let msg = format!(\n \"Failed to remove Caskroom version directory during zap: {}\",\n cask_version_path_in_caskroom.display()\n );\n error!(\"{}\", msg);\n zap_errors.push(msg);\n }\n\n if let Some(parent_token_dir) = cask_version_path_in_caskroom.parent() {\n if parent_token_dir.exists() && parent_token_dir.is_dir() {\n match fs::read_dir(parent_token_dir) {\n Ok(mut entries) => {\n if entries.next().is_none() {\n debug!(\n \"Zap: Removing empty Caskroom token directory: {}\",\n parent_token_dir.display()\n );\n if !remove_filesystem_artifact(parent_token_dir, true)\n && parent_token_dir.exists()\n {\n warn!(\n \"Failed to remove empty Caskroom token directory during zap: {}\",\n parent_token_dir.display()\n );\n }\n }\n }\n Err(e) => warn!(\n \"Failed to read Caskroom token directory {} during zap cleanup: {}\",\n parent_token_dir.display(),\n e\n ),\n }\n }\n }\n\n if zap_errors.is_empty() {\n debug!(\n \"Zap process completed successfully for cask: {}\",\n cask_def.token\n );\n Ok(())\n } else {\n error!(\n \"Zap process for {} completed with errors: {}\",\n cask_def.token,\n zap_errors.join(\"; \")\n );\n Err(SpsError::InstallError(format!(\n \"Zap for {} failed with errors: {}\",\n cask_def.token,\n zap_errors.join(\"; \")\n )))\n }\n}\n\nfn process_artifact_uninstall_core(\n artifact: &InstalledArtifact,\n config: &Config,\n use_sudo_for_zap: bool,\n) -> bool {\n debug!(\"Processing artifact removal: {:?}\", artifact);\n match artifact {\n InstalledArtifact::AppBundle { path } => {\n debug!(\"Uninstall: Removing AppBundle at {}\", path.display());\n match path.symlink_metadata() {\n Ok(metadata) if metadata.file_type().is_symlink() => {\n debug!(\"AppBundle at {} is a symlink; unlinking.\", path.display());\n match std::fs::remove_file(path) {\n Ok(_) => true,\n Err(e) => {\n warn!(\"Failed to unlink symlink at {}: {}\", path.display(), e);\n false\n }\n }\n }\n Ok(metadata) if metadata.file_type().is_dir() => {\n #[cfg(target_os = \"macos\")]\n {\n if path.exists() {\n if let Err(e) = applescript::quit_app_gracefully(path) {\n warn!(\n \"Attempt to gracefully quit app at {} failed: {} (proceeding)\",\n path.display(),\n e\n );\n }\n } else {\n debug!(\n \"App bundle at {} does not exist, skipping quit.\",\n path.display()\n );\n }\n }\n let use_sudo = path.starts_with(config.applications_dir())\n || path.starts_with(\"/Applications\")\n || use_sudo_for_zap;\n remove_filesystem_artifact(path, use_sudo)\n }\n Ok(_) | Err(_) => {\n let use_sudo = path.starts_with(config.applications_dir())\n || path.starts_with(\"/Applications\")\n || use_sudo_for_zap;\n remove_filesystem_artifact(path, use_sudo)\n }\n }\n }\n InstalledArtifact::BinaryLink { link_path, .. }\n | InstalledArtifact::ManpageLink { link_path, .. }\n | InstalledArtifact::CaskroomLink { link_path, .. } => {\n debug!(\"Uninstall: Removing link at {}\", link_path.display());\n remove_filesystem_artifact(link_path, use_sudo_for_zap)\n }\n InstalledArtifact::PkgUtilReceipt { id } => {\n debug!(\"Uninstall: Forgetting PkgUtilReceipt {}\", id);\n forget_pkgutil_receipt(id)\n }\n InstalledArtifact::Launchd { label, path } => {\n debug!(\"Uninstall: Unloading Launchd {} (path: {:?})\", label, path);\n unload_and_remove_launchd(label, path.as_deref())\n }\n InstalledArtifact::MovedResource { path } => {\n debug!(\"Uninstall: Removing MovedResource at {}\", path.display());\n remove_filesystem_artifact(path, use_sudo_for_zap)\n }\n InstalledArtifact::CaskroomReference { path } => {\n debug!(\n \"Uninstall: Removing CaskroomReference at {}\",\n path.display()\n );\n remove_filesystem_artifact(path, use_sudo_for_zap)\n }\n }\n}\n\nfn forget_pkgutil_receipt(id: &str) -> bool {\n if !VALID_PKGID_RE.is_match(id) {\n error!(\"Invalid pkgutil ID format: '{}'. Skipping forget.\", id);\n return false;\n }\n debug!(\"Forgetting package receipt (requires sudo): {}\", id);\n let output = Command::new(\"sudo\")\n .arg(\"pkgutil\")\n .arg(\"--forget\")\n .arg(id)\n .output();\n match output {\n Ok(out) if out.status.success() => {\n debug!(\"Successfully forgot package receipt {}\", id);\n true\n }\n Ok(out) => {\n let stderr = String::from_utf8_lossy(&out.stderr);\n if !stderr.contains(\"No receipt for\") && !stderr.trim().is_empty() {\n error!(\"Failed to forget package receipt {}: {}\", id, stderr.trim());\n // Return false if pkgutil fails for a reason other than \"No receipt\"\n return false;\n } else {\n debug!(\"Package receipt {} already forgotten or never existed.\", id);\n }\n true\n }\n Err(e) => {\n error!(\"Failed to execute sudo pkgutil --forget {}: {}\", id, e);\n false\n }\n }\n}\n\nfn unload_and_remove_launchd(label: &str, path: Option<&Path>) -> bool {\n if !VALID_LABEL_RE.is_match(label) {\n error!(\n \"Invalid launchd label format: '{}'. Skipping unload/remove.\",\n label\n );\n return false;\n }\n debug!(\"Unloading launchd service (if loaded): {}\", label);\n let unload_output = Command::new(\"launchctl\")\n .arg(\"unload\")\n .arg(\"-w\")\n .arg(label)\n .stderr(Stdio::piped())\n .output();\n\n let mut unload_successful_or_not_loaded = false;\n match unload_output {\n Ok(out) if out.status.success() => {\n debug!(\"Successfully unloaded launchd service {}\", label);\n unload_successful_or_not_loaded = true;\n }\n Ok(out) => {\n let stderr = String::from_utf8_lossy(&out.stderr);\n if stderr.contains(\"Could not find specified service\")\n || stderr.contains(\"service is not loaded\")\n || stderr.trim().is_empty()\n {\n debug!(\"Launchd service {} already unloaded or not found.\", label);\n unload_successful_or_not_loaded = true;\n } else {\n warn!(\n \"launchctl unload {} failed (but proceeding with plist removal attempt): {}\",\n label,\n stderr.trim()\n );\n // Proceed to try plist removal even if unload reports other errors\n }\n }\n Err(e) => {\n warn!(\"Failed to execute launchctl unload {} (but proceeding with plist removal attempt): {}\", label, e);\n }\n }\n\n if let Some(plist_path) = path {\n if plist_path.exists() {\n debug!(\"Removing launchd plist file: {}\", plist_path.display());\n let use_sudo = plist_path.starts_with(\"/Library/LaunchDaemons\")\n || plist_path.starts_with(\"/Library/LaunchAgents\");\n if !remove_filesystem_artifact(plist_path, use_sudo) {\n warn!(\"Failed to remove launchd plist: {}\", plist_path.display());\n return false; // If plist removal fails, consider the operation failed\n }\n } else {\n debug!(\n \"Launchd plist path {} does not exist, skip removal.\",\n plist_path.display()\n );\n }\n } else {\n debug!(\n \"No path provided for launchd plist removal for label {}\",\n label\n );\n }\n unload_successful_or_not_loaded // Success depends on unload and optional plist removal\n}\n\nfn trash_path(path: &Path) -> bool {\n if !path.exists() && path.symlink_metadata().is_err() {\n debug!(\"Path for trashing not found: {}\", path.display());\n return true;\n }\n match trash::delete(path) {\n Ok(_) => {\n debug!(\"Trashed: {}\", path.display());\n true\n }\n Err(e) => {\n warn!(\"Failed to trash {} (proceeding anyway): {}. This might require manual cleanup or installing a 'trash' utility.\", path.display(), e);\n true\n }\n }\n}\n\n/// Helper for zap scripts.\nfn run_zap_script(script_path: &Path, args: Option<&[String]>, errors: &mut Vec) {\n debug!(\n \"Running zap script: {} with args {:?}\",\n script_path.display(),\n args.unwrap_or_default()\n );\n let mut cmd = Command::new(script_path);\n if let Some(script_args) = args {\n cmd.args(script_args);\n }\n cmd.stdout(Stdio::piped()).stderr(Stdio::piped());\n\n match cmd.output() {\n Ok(output) => {\n log_command_output(\n \"Zap script\",\n &script_path.display().to_string(),\n &output,\n errors,\n );\n }\n Err(e) => {\n let msg = format!(\n \"Failed to execute zap script '{}': {}\",\n script_path.display(),\n e\n );\n error!(\"{}\", msg);\n errors.push(msg);\n }\n }\n}\n\n/// Logs the output of a command and adds to error list if it failed.\nfn log_command_output(\n context: &str,\n command_str: &str,\n output: &std::process::Output,\n errors: &mut Vec,\n) {\n let stdout = String::from_utf8_lossy(&output.stdout);\n let stderr = String::from_utf8_lossy(&output.stderr);\n if !output.status.success() {\n error!(\n \"{} '{}' failed with status {}: {}\",\n context,\n command_str,\n output.status,\n stderr.trim()\n );\n if !stdout.trim().is_empty() {\n error!(\"{} stdout: {}\", context, stdout.trim());\n }\n errors.push(format!(\"{context} '{command_str}' failed\"));\n } else {\n debug!(\"{} '{}' executed successfully.\", context, command_str);\n if !stdout.trim().is_empty() {\n debug!(\"{} stdout: {}\", context, stdout.trim());\n }\n if !stderr.trim().is_empty() {\n debug!(\"{} stderr: {}\", context, stderr.trim());\n }\n }\n}\n\n// Helper function specifically for cleaning up the private store.\n// This was originally inside zap_cask_artifacts.\nfn cleanup_private_store(\n cask_token: &str,\n version: &str,\n app_name: Option<&str>, // The actual .app name, not the token\n config: &Config,\n) -> bool {\n debug!(\n \"Cleaning up private store for cask {} version {}\",\n cask_token, version\n );\n\n let private_version_dir = config.cask_store_version_path(cask_token, version);\n\n if let Some(app) = app_name {\n let app_path_in_private_store = private_version_dir.join(app);\n if app_path_in_private_store.exists()\n || app_path_in_private_store.symlink_metadata().is_ok()\n {\n debug!(\n \"Removing app from private store: {}\",\n app_path_in_private_store.display()\n );\n // Use the helper from install::cask::helpers, assuming it's correctly located and\n // public\n if !remove_path_robustly_from_install_helpers(&app_path_in_private_store, config, false)\n {\n // use_sudo=false for private store\n warn!(\n \"Failed to remove app from private store: {}\",\n app_path_in_private_store.display()\n );\n // Potentially return false or collect errors, depending on desired strictness\n }\n }\n }\n\n // After attempting to remove specific app, remove the version directory if it exists\n // This also handles cases where app_name was None.\n if private_version_dir.exists() {\n debug!(\n \"Removing private store version directory: {}\",\n private_version_dir.display()\n );\n match fs::remove_dir_all(&private_version_dir) {\n Ok(_) => debug!(\n \"Successfully removed private store version directory {}\",\n private_version_dir.display()\n ),\n Err(e) => {\n warn!(\n \"Failed to remove private store version directory {}: {}\",\n private_version_dir.display(),\n e\n );\n return false; // If the version dir removal fails, consider it a failure\n }\n }\n }\n\n // Clean up empty parent token directory.\n cleanup_empty_parent_dirs_in_private_store(\n &private_version_dir, // Start from the version dir (or its parent if it was just removed)\n &config.cask_store_dir(),\n );\n\n true\n}\n"], ["/sps/sps/src/cli/info.rs", "//! Contains the logic for the `info` command.\n\nuse std::sync::Arc;\n\nuse clap::Args;\nuse colored::Colorize;\nuse serde_json::Value;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_net::api;\n\n#[derive(Args, Debug)]\npub struct Info {\n /// Name of the formula or cask\n pub name: String,\n\n /// Show information for a cask, not a formula\n #[arg(long)]\n pub cask: bool,\n}\n\nimpl Info {\n /// Displays detailed information about a formula or cask.\n pub async fn run(&self, _config: &Config, cache: Arc) -> Result<()> {\n let name = &self.name;\n let is_cask = self.cask;\n tracing::debug!(\"Getting info for package: {name}, is_cask: {is_cask}\",);\n\n // Print loading message instead of spinner\n println!(\"Loading info for {name}\");\n\n if self.cask {\n match get_cask_info(Arc::clone(&cache), name).await {\n Ok(info) => {\n print_cask_info(name, &info);\n Ok(())\n }\n Err(e) => Err(e),\n }\n } else {\n match get_formula_info_raw(Arc::clone(&cache), name).await {\n Ok(info) => {\n // Removed bottle check logic here as it was complex and potentially racy.\n // We'll try formula first, then cask if formula fails.\n print_formula_info(name, &info);\n return Ok(());\n }\n Err(SpsError::NotFound(_)) | Err(SpsError::Generic(_)) => {\n // If formula lookup failed (not found or generic error), try cask.\n tracing::debug!(\"Formula '{}' info failed, trying cask.\", name);\n }\n Err(e) => {\n return Err(e); // Propagate other errors (API, JSON, etc.)\n }\n }\n // --- Cask Fallback ---\n match get_cask_info(Arc::clone(&cache), name).await {\n Ok(info) => {\n print_cask_info(name, &info);\n Ok(())\n }\n Err(e) => {\n Err(e) // Return the cask error if both formula and cask fail\n }\n }\n }\n }\n}\n\n/// Retrieves formula information from the cache or API as raw JSON\nasync fn get_formula_info_raw(cache: Arc, name: &str) -> Result {\n match cache.load_raw(\"formula.json\") {\n Ok(formula_data) => {\n let formulas: Vec =\n serde_json::from_str(&formula_data).map_err(SpsError::from)?;\n for formula in formulas {\n if let Some(fname) = formula.get(\"name\").and_then(Value::as_str) {\n if fname == name {\n return Ok(formula);\n }\n }\n // Also check aliases if needed\n if let Some(aliases) = formula.get(\"aliases\").and_then(|a| a.as_array()) {\n if aliases.iter().any(|a| a.as_str() == Some(name)) {\n return Ok(formula);\n }\n }\n }\n tracing::debug!(\"Formula '{}' not found within cached 'formula.json'.\", name);\n // Explicitly return NotFound if not in cache\n return Err(SpsError::NotFound(format!(\n \"Formula '{name}' not found in cache\"\n )));\n }\n Err(e) => tracing::debug!(\n \"Cache file 'formula.json' not found or failed to load ({}). Fetching from API.\",\n e\n ),\n }\n tracing::debug!(\"Fetching formula '{}' directly from API\", name);\n // api::fetch_formula returns Value directly now\n let value = api::fetch_formula(name).await?;\n // Store in cache if fetched successfully\n // Note: This might overwrite the full list cache, consider storing individual files or a map\n // cache.store_raw(&format!(\"formula/{}.json\", name), &value.to_string())?; // Example of\n // storing individually\n Ok(value)\n}\n\n/// Retrieves cask information from the cache or API\nasync fn get_cask_info(cache: Arc, name: &str) -> Result {\n match cache.load_raw(\"cask.json\") {\n Ok(cask_data) => {\n let casks: Vec = serde_json::from_str(&cask_data).map_err(SpsError::from)?;\n for cask in casks {\n if let Some(token) = cask.get(\"token\").and_then(Value::as_str) {\n if token == name {\n return Ok(cask);\n }\n }\n // Check aliases if needed\n if let Some(aliases) = cask.get(\"aliases\").and_then(|a| a.as_array()) {\n if aliases.iter().any(|a| a.as_str() == Some(name)) {\n return Ok(cask);\n }\n }\n }\n tracing::debug!(\"Cask '{}' not found within cached 'cask.json'.\", name);\n // Explicitly return NotFound if not in cache\n return Err(SpsError::NotFound(format!(\n \"Cask '{name}' not found in cache\"\n )));\n }\n Err(e) => tracing::debug!(\n \"Cache file 'cask.json' not found or failed to load ({}). Fetching from API.\",\n e\n ),\n }\n tracing::debug!(\"Fetching cask '{}' directly from API\", name);\n // api::fetch_cask returns Value directly now\n let value = api::fetch_cask(name).await?;\n // Store in cache if fetched successfully\n // cache.store_raw(&format!(\"cask/{}.json\", name), &value.to_string())?; // Example of storing\n // individually\n Ok(value)\n}\n\n/// Prints formula information in a formatted table\nfn print_formula_info(_name: &str, formula: &Value) {\n // Basic info extraction\n let full_name = formula\n .get(\"full_name\")\n .and_then(|f| f.as_str())\n .unwrap_or(\"N/A\");\n let version = formula\n .get(\"versions\")\n .and_then(|v| v.get(\"stable\"))\n .and_then(|s| s.as_str())\n .unwrap_or(\"N/A\");\n let revision = formula\n .get(\"revision\")\n .and_then(|r| r.as_u64())\n .unwrap_or(0);\n let version_str = if revision > 0 {\n format!(\"{version}_{revision}\")\n } else {\n version.to_string()\n };\n let license = formula\n .get(\"license\")\n .and_then(|l| l.as_str())\n .unwrap_or(\"N/A\");\n let homepage = formula\n .get(\"homepage\")\n .and_then(|h| h.as_str())\n .unwrap_or(\"N/A\");\n\n // Header\n println!(\"{}\", format!(\"Formula: {full_name}\").green().bold());\n\n // Summary table\n let mut table = prettytable::Table::new();\n table.set_format(*prettytable::format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n table.add_row(prettytable::row![\"Version\", version_str]);\n table.add_row(prettytable::row![\"License\", license]);\n table.add_row(prettytable::row![\"Homepage\", homepage]);\n table.printstd();\n\n // Detailed sections\n if let Some(desc) = formula.get(\"desc\").and_then(|d| d.as_str()) {\n if !desc.is_empty() {\n println!(\"\\n{}\", \"Description\".blue().bold());\n println!(\"{desc}\");\n }\n }\n if let Some(caveats) = formula.get(\"caveats\").and_then(|c| c.as_str()) {\n if !caveats.is_empty() {\n println!(\"\\n{}\", \"Caveats\".blue().bold());\n println!(\"{caveats}\");\n }\n }\n\n // Combined Dependencies Section\n let mut dep_table = prettytable::Table::new();\n dep_table.set_format(*prettytable::format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n let mut has_deps = false;\n\n let mut add_deps = |title: &str, key: &str, tag: &str| {\n if let Some(deps) = formula.get(key).and_then(|d| d.as_array()) {\n let dep_list: Vec<&str> = deps.iter().filter_map(|d| d.as_str()).collect();\n if !dep_list.is_empty() {\n has_deps = true;\n for (i, d) in dep_list.iter().enumerate() {\n let display_title = if i == 0 { title } else { \"\" };\n let display_tag = if i == 0 {\n format!(\"({tag})\")\n } else {\n \"\".to_string()\n };\n dep_table.add_row(prettytable::row![display_title, d, display_tag]);\n }\n }\n }\n };\n\n add_deps(\"Required\", \"dependencies\", \"runtime\");\n add_deps(\n \"Recommended\",\n \"recommended_dependencies\",\n \"runtime, recommended\",\n );\n add_deps(\"Optional\", \"optional_dependencies\", \"runtime, optional\");\n add_deps(\"Build\", \"build_dependencies\", \"build\");\n add_deps(\"Test\", \"test_dependencies\", \"test\");\n\n if has_deps {\n println!(\"\\n{}\", \"Dependencies\".blue().bold());\n dep_table.printstd();\n }\n\n // Installation hint\n println!(\"\\n{}\", \"Installation\".blue().bold());\n println!(\n \" {} install {}\",\n \"sps\".cyan(),\n formula\n .get(\"name\")\n .and_then(|n| n.as_str())\n .unwrap_or(full_name) // Use short name if available\n );\n}\n\n/// Prints cask information in a formatted table\nfn print_cask_info(name: &str, cask: &Value) {\n // Header\n println!(\"{}\", format!(\"Cask: {name}\").green().bold());\n\n // Summary table\n let mut table = prettytable::Table::new();\n table.set_format(*prettytable::format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n if let Some(names) = cask.get(\"name\").and_then(|n| n.as_array()) {\n if let Some(first) = names.first().and_then(|s| s.as_str()) {\n table.add_row(prettytable::row![\"Name\", first]);\n }\n }\n if let Some(desc) = cask.get(\"desc\").and_then(|d| d.as_str()) {\n table.add_row(prettytable::row![\"Description\", desc]);\n }\n if let Some(homepage) = cask.get(\"homepage\").and_then(|h| h.as_str()) {\n table.add_row(prettytable::row![\"Homepage\", homepage]);\n }\n if let Some(version) = cask.get(\"version\").and_then(|v| v.as_str()) {\n table.add_row(prettytable::row![\"Version\", version]);\n }\n if let Some(url) = cask.get(\"url\").and_then(|u| u.as_str()) {\n table.add_row(prettytable::row![\"Download URL\", url]);\n }\n // Add SHA if present\n if let Some(sha) = cask.get(\"sha256\").and_then(|s| s.as_str()) {\n if !sha.is_empty() {\n table.add_row(prettytable::row![\"SHA256\", sha]);\n }\n }\n table.printstd();\n\n // Dependencies Section\n if let Some(deps) = cask.get(\"depends_on\").and_then(|d| d.as_object()) {\n let mut dep_table = prettytable::Table::new();\n dep_table.set_format(*prettytable::format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n let mut has_deps = false;\n\n if let Some(formulas) = deps.get(\"formula\").and_then(|f| f.as_array()) {\n if !formulas.is_empty() {\n has_deps = true;\n dep_table.add_row(prettytable::row![\n \"Formula\".yellow(),\n formulas\n .iter()\n .map(|v| v.as_str().unwrap_or(\"\"))\n .collect::>()\n .join(\", \")\n ]);\n }\n }\n if let Some(casks) = deps.get(\"cask\").and_then(|c| c.as_array()) {\n if !casks.is_empty() {\n has_deps = true;\n dep_table.add_row(prettytable::row![\n \"Cask\".yellow(),\n casks\n .iter()\n .map(|v| v.as_str().unwrap_or(\"\"))\n .collect::>()\n .join(\", \")\n ]);\n }\n }\n if let Some(macos) = deps.get(\"macos\") {\n has_deps = true;\n let macos_str = match macos {\n Value::String(s) => s.clone(),\n Value::Array(arr) => arr\n .iter()\n .map(|v| v.as_str().unwrap_or(\"\"))\n .collect::>()\n .join(\" or \"),\n _ => \"Unknown\".to_string(),\n };\n dep_table.add_row(prettytable::row![\"macOS\".yellow(), macos_str]);\n }\n\n if has_deps {\n println!(\"\\n{}\", \"Dependencies\".blue().bold());\n dep_table.printstd();\n }\n }\n\n // Installation hint\n println!(\"\\n{}\", \"Installation\".blue().bold());\n println!(\n \" {} install --cask {}\", // Always use --cask for clarity\n \"sps\".cyan(),\n name // Use the token 'name' passed to the function\n );\n}\n// Removed is_bottle_available check\n"], ["/sps/sps-core/src/install/bottle/link.rs", "// ===== sps-core/src/build/formula/link.rs =====\nuse std::fs;\nuse std::io::Write;\nuse std::os::unix::fs as unix_fs;\n#[cfg(unix)]\nuse std::os::unix::fs::PermissionsExt;\nuse std::path::{Path, PathBuf};\n\nuse serde_json;\nuse sps_common::config::Config; // Import Config\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::formula::Formula;\nuse tracing::{debug, error};\n\nconst STANDARD_KEG_DIRS: [&str; 6] = [\"bin\", \"lib\", \"share\", \"include\", \"etc\", \"Frameworks\"];\n\n/// Link all artifacts from a formula's installation directory.\n// Added Config parameter\npub fn link_formula_artifacts(\n formula: &Formula,\n installed_keg_path: &Path,\n config: &Config, // Added config\n) -> Result<()> {\n debug!(\n \"Linking artifacts for {} from {}\",\n formula.name(),\n installed_keg_path.display()\n );\n\n let formula_content_root = determine_content_root(installed_keg_path)?;\n let mut symlinks_created = Vec::::new();\n\n // Use config methods for paths\n let opt_link_path = config.formula_opt_path(formula.name());\n let target_keg_dir = &formula_content_root;\n\n remove_existing_link_target(&opt_link_path)?;\n unix_fs::symlink(target_keg_dir, &opt_link_path).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed to create opt symlink for {}: {}\", formula.name(), e),\n )))\n })?;\n symlinks_created.push(opt_link_path.to_string_lossy().to_string());\n debug!(\n \" Linked opt path: {} -> {}\",\n opt_link_path.display(),\n target_keg_dir.display()\n );\n\n if let Some((base, _version)) = formula.name().split_once('@') {\n let alias_path = config.opt_dir().join(base); // Use config.opt_dir()\n if !alias_path.exists() {\n match unix_fs::symlink(target_keg_dir, &alias_path) {\n Ok(_) => {\n debug!(\n \" Added un‑versioned opt alias: {} -> {}\",\n alias_path.display(),\n target_keg_dir.display()\n );\n symlinks_created.push(alias_path.to_string_lossy().to_string());\n }\n Err(e) => {\n debug!(\n \" Could not create opt alias {}: {}\",\n alias_path.display(),\n e\n );\n }\n }\n }\n }\n\n let standard_artifact_dirs = [\"lib\", \"include\", \"share\"];\n for dir_name in &standard_artifact_dirs {\n let source_subdir = formula_content_root.join(dir_name);\n // Use config.prefix() for target base\n let target_prefix_subdir = config.sps_root().join(dir_name);\n\n if source_subdir.is_dir() {\n fs::create_dir_all(&target_prefix_subdir)?;\n for entry in fs::read_dir(&source_subdir)? {\n let entry = entry?;\n let source_item_path = entry.path();\n let file_name = entry.file_name();\n if file_name.to_string_lossy().starts_with('.') {\n continue;\n }\n\n let target_link = target_prefix_subdir.join(&file_name);\n remove_existing_link_target(&target_link)?;\n unix_fs::symlink(&source_item_path, &target_link).ok(); // ignore errors for individual links?\n symlinks_created.push(target_link.to_string_lossy().to_string());\n debug!(\n \" Linked {} -> {}\",\n target_link.display(),\n source_item_path.display()\n );\n }\n }\n }\n\n // Use config.bin_dir() for target bin\n let target_bin_dir = config.bin_dir();\n fs::create_dir_all(&target_bin_dir).ok();\n\n let source_bin_dir = formula_content_root.join(\"bin\");\n if source_bin_dir.is_dir() {\n create_wrappers_in_dir(\n &source_bin_dir,\n &target_bin_dir,\n &formula_content_root,\n &mut symlinks_created,\n )?;\n }\n let source_libexec_dir = formula_content_root.join(\"libexec\");\n if source_libexec_dir.is_dir() {\n create_wrappers_in_dir(\n &source_libexec_dir,\n &target_bin_dir,\n &formula_content_root,\n &mut symlinks_created,\n )?;\n }\n\n write_install_manifest(installed_keg_path, &symlinks_created)?;\n\n debug!(\n \"Successfully completed linking artifacts for {}\",\n formula.name()\n );\n Ok(())\n}\n\n// remove_existing_link_target, write_install_manifest remain mostly unchanged internally) ...\nfn create_wrappers_in_dir(\n source_dir: &Path,\n target_bin_dir: &Path,\n formula_content_root: &Path,\n wrappers_created: &mut Vec,\n) -> Result<()> {\n debug!(\n \"Scanning for executables in {} to create wrappers in {}\",\n source_dir.display(),\n target_bin_dir.display()\n );\n match fs::read_dir(source_dir) {\n Ok(entries) => {\n for entry_result in entries {\n match entry_result {\n Ok(entry) => {\n let source_item_path = entry.path();\n let file_name = entry.file_name();\n\n if file_name.to_string_lossy().starts_with('.') {\n continue;\n }\n\n if source_item_path.is_dir() {\n create_wrappers_in_dir(\n &source_item_path,\n target_bin_dir,\n formula_content_root,\n wrappers_created,\n )?;\n } else if source_item_path.is_file() {\n match is_executable(&source_item_path) {\n Ok(true) => {\n let wrapper_path = target_bin_dir.join(&file_name);\n debug!(\"Found executable: {}\", source_item_path.display());\n if remove_existing_link_target(&wrapper_path).is_ok() {\n debug!(\n \" Creating wrapper script: {} -> {}\",\n wrapper_path.display(),\n source_item_path.display()\n );\n match create_wrapper_script(\n &source_item_path,\n &wrapper_path,\n formula_content_root,\n ) {\n Ok(_) => {\n debug!(\n \" Created wrapper {} -> {}\",\n wrapper_path.display(),\n source_item_path.display()\n );\n wrappers_created.push(\n wrapper_path.to_string_lossy().to_string(),\n );\n }\n Err(e) => {\n error!(\n \"Failed to create wrapper script {} -> {}: {}\",\n wrapper_path.display(),\n source_item_path.display(),\n e\n );\n }\n }\n }\n }\n Ok(false) => { /* Not executable, ignore */ }\n Err(e) => {\n debug!(\n \" Could not check executable status for {}: {}\",\n source_item_path.display(),\n e\n );\n }\n }\n }\n }\n Err(e) => {\n debug!(\n \" Failed to process directory entry in {}: {}\",\n source_dir.display(),\n e\n );\n }\n }\n }\n }\n Err(e) => {\n debug!(\n \"Failed to read source directory {}: {}\",\n source_dir.display(),\n e\n );\n }\n }\n Ok(())\n}\nfn create_wrapper_script(\n target_executable: &Path,\n wrapper_path: &Path,\n formula_content_root: &Path,\n) -> Result<()> {\n let libexec_path = formula_content_root.join(\"libexec\");\n let perl_lib_path = libexec_path.join(\"lib\").join(\"perl5\");\n let python_lib_path = libexec_path.join(\"vendor\"); // Assuming simple vendor dir\n\n let mut script_content = String::new();\n script_content.push_str(\"#!/bin/bash\\n\");\n script_content.push_str(\"# Wrapper script generated by sp\\n\");\n script_content.push_str(\"set -e\\n\\n\");\n\n if perl_lib_path.exists() && perl_lib_path.is_dir() {\n script_content.push_str(&format!(\n \"export PERL5LIB=\\\"{}:$PERL5LIB\\\"\\n\",\n perl_lib_path.display()\n ));\n debug!(\n \" (Wrapper will set PERL5LIB to {})\",\n perl_lib_path.display()\n );\n }\n if python_lib_path.exists() && python_lib_path.is_dir() {\n script_content.push_str(&format!(\n \"export PYTHONPATH=\\\"{}:$PYTHONPATH\\\"\\n\",\n python_lib_path.display()\n ));\n debug!(\n \" (Wrapper will set PYTHONPATH to {})\",\n python_lib_path.display()\n );\n }\n\n script_content.push_str(&format!(\n \"\\nexec \\\"{}\\\" \\\"$@\\\"\\n\",\n target_executable.display()\n ));\n\n let mut file = fs::File::create(wrapper_path).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed create wrapper {}: {}\", wrapper_path.display(), e),\n )))\n })?;\n file.write_all(script_content.as_bytes()).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed write wrapper {}: {}\", wrapper_path.display(), e),\n )))\n })?;\n\n #[cfg(unix)]\n {\n let metadata = file.metadata()?;\n let mut permissions = metadata.permissions();\n permissions.set_mode(0o755);\n fs::set_permissions(wrapper_path, permissions).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\n \"Failed set wrapper executable {}: {}\",\n wrapper_path.display(),\n e\n ),\n )))\n })?;\n }\n\n Ok(())\n}\n\nfn determine_content_root(installed_keg_path: &Path) -> Result {\n let mut potential_subdirs = Vec::new();\n let mut top_level_files_found = false;\n if !installed_keg_path.is_dir() {\n error!(\n \"Keg path {} does not exist or is not a directory!\",\n installed_keg_path.display()\n );\n return Err(SpsError::NotFound(format!(\n \"Keg path not found: {}\",\n installed_keg_path.display()\n )));\n }\n match fs::read_dir(installed_keg_path) {\n Ok(entries) => {\n for entry_res in entries {\n if let Ok(entry) = entry_res {\n let path = entry.path();\n let file_name = entry.file_name();\n // --- Use OsStr comparison ---\n let file_name_osstr = file_name.as_os_str();\n if file_name_osstr.to_string_lossy().starts_with('.')\n || file_name_osstr == \"INSTALL_MANIFEST.json\"\n || file_name_osstr == \"INSTALL_RECEIPT.json\"\n {\n continue;\n }\n if path.is_dir() {\n // Store both path and name for check later\n potential_subdirs.push((path, file_name.to_string_lossy().to_string()));\n } else if path.is_file() {\n top_level_files_found = true;\n debug!(\n \"Found file '{}' at top level of keg {}, assuming no intermediate dir.\",\n file_name.to_string_lossy(), // Use lossy for display\n installed_keg_path.display()\n );\n break; // Stop scanning if top-level files found\n }\n } else {\n debug!(\n \"Failed to read directory entry in {}: {}\",\n installed_keg_path.display(),\n entry_res.err().unwrap() // Safe unwrap as we are in Err path\n );\n }\n }\n }\n Err(e) => {\n debug!(\n \"Could not read keg directory {} to check for intermediate dir: {}. Assuming keg path is content root.\",\n installed_keg_path.display(),\n e\n );\n return Ok(installed_keg_path.to_path_buf());\n }\n }\n\n // --- MODIFIED LOGIC ---\n if potential_subdirs.len() == 1 && !top_level_files_found {\n // Get the single subdirectory path and name\n let (intermediate_dir_path, intermediate_dir_name) = potential_subdirs.remove(0); // Use remove\n\n // Check if the single directory name is one of the standard install dirs\n if STANDARD_KEG_DIRS.contains(&intermediate_dir_name.as_str()) {\n debug!(\n \"Single directory found ('{}') is a standard directory. Using main keg directory {} as content root.\",\n intermediate_dir_name,\n installed_keg_path.display()\n );\n Ok(installed_keg_path.to_path_buf()) // Use main keg path\n } else {\n // Single dir is NOT a standard name, assume it's an intermediate content root\n debug!(\n \"Detected single non-standard intermediate content directory: {}\",\n intermediate_dir_path.display()\n );\n Ok(intermediate_dir_path) // Use the intermediate dir\n }\n // --- END MODIFIED LOGIC ---\n } else {\n // Handle multiple subdirs or top-level files found case (no change needed here)\n if potential_subdirs.len() > 1 {\n debug!(\n \"Multiple potential content directories found under keg {}. Using main keg directory as content root.\",\n installed_keg_path.display()\n );\n } else if top_level_files_found {\n debug!(\n \"Top-level files found in keg {}. Using main keg directory as content root.\",\n installed_keg_path.display()\n );\n } else if potential_subdirs.is_empty() {\n // Changed from else if to else\n debug!(\n \"No subdirectories or files found (excluding ignored ones) in keg {}. Using main keg directory as content root.\",\n installed_keg_path.display()\n );\n }\n Ok(installed_keg_path.to_path_buf()) // Use main keg path in these cases too\n }\n}\n\nfn remove_existing_link_target(path: &Path) -> Result<()> {\n match path.symlink_metadata() {\n Ok(metadata) => {\n debug!(\n \" Removing existing item at link target: {}\",\n path.display()\n );\n let is_dir = metadata.file_type().is_dir();\n let is_symlink = metadata.file_type().is_symlink();\n let is_real_dir = is_dir && !is_symlink;\n let remove_result = if is_real_dir {\n fs::remove_dir_all(path)\n } else {\n fs::remove_file(path)\n };\n if let Err(e) = remove_result {\n debug!(\n \" Failed to remove existing item at link target {}: {}\",\n path.display(),\n e\n );\n return Err(SpsError::Io(std::sync::Arc::new(e)));\n }\n Ok(())\n }\n Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),\n Err(e) => {\n debug!(\n \" Failed to get metadata for existing item {}: {}\",\n path.display(),\n e\n );\n Err(SpsError::Io(std::sync::Arc::new(e)))\n }\n }\n}\n\nfn write_install_manifest(installed_keg_path: &Path, symlinks_created: &[String]) -> Result<()> {\n let manifest_path = installed_keg_path.join(\"INSTALL_MANIFEST.json\");\n debug!(\"Writing install manifest to: {}\", manifest_path.display());\n match serde_json::to_string_pretty(&symlinks_created) {\n Ok(manifest_json) => match fs::write(&manifest_path, manifest_json) {\n Ok(_) => {\n debug!(\n \"Wrote install manifest with {} links: {}\",\n symlinks_created.len(),\n manifest_path.display()\n );\n }\n Err(e) => {\n error!(\n \"Failed to write install manifest {}: {}\",\n manifest_path.display(),\n e\n );\n return Err(SpsError::Io(std::sync::Arc::new(e)));\n }\n },\n Err(e) => {\n error!(\"Failed to serialize install manifest data: {}\", e);\n return Err(SpsError::Json(std::sync::Arc::new(e)));\n }\n }\n Ok(())\n}\n\npub fn unlink_formula_artifacts(\n formula_name: &str,\n version_str_full: &str, // e.g., \"1.2.3_1\"\n config: &Config,\n) -> Result<()> {\n debug!(\n \"Unlinking artifacts for {} version {}\",\n formula_name, version_str_full\n );\n // Use config method to get expected keg path based on name and version string\n let expected_keg_path = config.formula_keg_path(formula_name, version_str_full);\n let manifest_path = expected_keg_path.join(\"INSTALL_MANIFEST.json\"); // Manifest *inside* the keg\n\n if manifest_path.is_file() {\n debug!(\"Reading install manifest: {}\", manifest_path.display());\n match fs::read_to_string(&manifest_path) {\n Ok(manifest_str) => {\n match serde_json::from_str::>(&manifest_str) {\n Ok(links_to_remove) => {\n let mut unlinked_count = 0;\n let mut removal_errors = 0;\n if links_to_remove.is_empty() {\n debug!(\n \"Install manifest {} is empty. Cannot perform manifest-based unlink.\",\n manifest_path.display()\n );\n } else {\n // Use Config to get base paths for checking ownership/safety\n let opt_base = config.opt_dir();\n let bin_base = config.bin_dir();\n let lib_base = config.sps_root().join(\"lib\");\n let include_base = config.sps_root().join(\"include\");\n let share_base = config.sps_root().join(\"share\");\n // Add etc, sbin etc. if needed\n\n for link_str in links_to_remove {\n let link_path = PathBuf::from(link_str);\n // Check if it's under a managed directory (safety check)\n if link_path.starts_with(&opt_base)\n || link_path.starts_with(&bin_base)\n || link_path.starts_with(&lib_base)\n || link_path.starts_with(&include_base)\n || link_path.starts_with(&share_base)\n {\n match remove_existing_link_target(&link_path) {\n // Use helper\n Ok(_) => {\n debug!(\"Removed link/wrapper: {}\", link_path.display());\n unlinked_count += 1;\n }\n Err(e) => {\n // Log error but continue trying to remove others\n debug!(\n \"Failed to remove link/wrapper {}: {}\",\n link_path.display(),\n e\n );\n removal_errors += 1;\n }\n }\n } else {\n // This indicates a potentially corrupted manifest or a link\n // outside expected areas\n error!(\n \"Manifest contains unexpected link path, skipping removal: {}\",\n link_path.display()\n );\n removal_errors += 1; // Count as an error/problem\n }\n }\n }\n debug!(\n \"Attempted to unlink {} artifacts based on manifest.\",\n unlinked_count\n );\n if removal_errors > 0 {\n error!(\n \"Encountered {} errors while removing links listed in manifest.\",\n removal_errors\n );\n // Decide if this should be a hard error - perhaps not if keg is being\n // removed anyway? For now, just log\n // warnings.\n }\n Ok(()) // Return Ok even if some links failed, keg removal will happen next\n }\n Err(e) => {\n error!(\n \"Failed to parse formula install manifest {}: {}. Proceeding without detailed unlink.\",\n manifest_path.display(),\n e\n );\n // Don't error out, allow keg removal to proceed.\n Ok(())\n }\n }\n }\n Err(e) => {\n error!(\n \"Failed to read formula install manifest {}: {}. Proceeding without detailed unlink.\",\n manifest_path.display(),\n e\n );\n // Don't error out, allow keg removal to proceed.\n Ok(())\n }\n }\n } else {\n debug!(\n \"Warning: No install manifest found at {}. Cannot perform detailed unlink.\",\n manifest_path.display()\n );\n // Don't error out, allow keg removal to proceed.\n Ok(())\n }\n}\n\nfn is_executable(path: &Path) -> Result {\n if !path.try_exists().unwrap_or(false) || !path.is_file() {\n return Ok(false);\n }\n if cfg!(unix) {\n use std::os::unix::fs::PermissionsExt;\n match fs::metadata(path) {\n Ok(metadata) => Ok(metadata.permissions().mode() & 0o111 != 0),\n Err(e) => Err(SpsError::Io(std::sync::Arc::new(e))),\n }\n } else {\n Ok(true)\n }\n}\n"], ["/sps/sps-net/src/api.rs", "use std::sync::Arc;\n\nuse reqwest::header::{ACCEPT, AUTHORIZATION, USER_AGENT};\nuse reqwest::Client;\nuse serde_json::Value;\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::cask::{Cask, CaskList};\nuse sps_common::model::formula::Formula;\nuse tracing::{debug, error};\n\nconst FORMULAE_API_BASE_URL: &str = \"https://formulae.brew.sh/api\";\nconst GITHUB_API_BASE_URL: &str = \"https://api.github.com\";\nconst USER_AGENT_STRING: &str = \"sps Package Manager (Rust; +https://github.com/your/sp)\";\n\nfn build_api_client(config: &Config) -> Result {\n let mut headers = reqwest::header::HeaderMap::new();\n headers.insert(USER_AGENT, USER_AGENT_STRING.parse().unwrap());\n headers.insert(ACCEPT, \"application/vnd.github+json\".parse().unwrap());\n if let Some(token) = &config.github_api_token {\n debug!(\"Adding GitHub API token to request headers.\");\n match format!(\"Bearer {token}\").parse() {\n Ok(val) => {\n headers.insert(AUTHORIZATION, val);\n }\n Err(e) => {\n error!(\"Failed to parse GitHub API token into header value: {}\", e);\n }\n }\n } else {\n debug!(\"No GitHub API token found in config.\");\n }\n Ok(Client::builder().default_headers(headers).build()?)\n}\n\npub async fn fetch_raw_formulae_json(endpoint: &str) -> Result {\n let url = format!(\"{FORMULAE_API_BASE_URL}/{endpoint}\");\n debug!(\"Fetching data from Homebrew Formulae API: {}\", url);\n let client = reqwest::Client::builder()\n .user_agent(USER_AGENT_STRING)\n .build()?;\n let response = client.get(&url).send().await.map_err(|e| {\n debug!(\"HTTP request failed for {}: {}\", url, e);\n SpsError::Http(Arc::new(e))\n })?;\n if !response.status().is_success() {\n let status = response.status();\n let body = response\n .text()\n .await\n .unwrap_or_else(|e| format!(\"(Failed to read response body: {e})\"));\n debug!(\n \"HTTP request to {} returned non-success status: {}\",\n url, status\n );\n debug!(\"Response body for failed request to {}: {}\", url, body);\n return Err(SpsError::Api(format!(\"HTTP status {status} from {url}\")));\n }\n let body = response.text().await?;\n if body.trim().is_empty() {\n error!(\"Response body for {} was empty.\", url);\n return Err(SpsError::Api(format!(\n \"Empty response body received from {url}\"\n )));\n }\n Ok(body)\n}\n\npub async fn fetch_all_formulas() -> Result {\n fetch_raw_formulae_json(\"formula.json\").await\n}\n\npub async fn fetch_all_casks() -> Result {\n fetch_raw_formulae_json(\"cask.json\").await\n}\n\npub async fn fetch_formula(name: &str) -> Result {\n let direct_fetch_result = fetch_raw_formulae_json(&format!(\"formula/{name}.json\")).await;\n if let Ok(body) = direct_fetch_result {\n let formula: serde_json::Value = serde_json::from_str(&body)?;\n Ok(formula)\n } else {\n debug!(\n \"Direct fetch for formula '{}' failed ({:?}). Fetching full list as fallback.\",\n name,\n direct_fetch_result.err()\n );\n let all_formulas_body = fetch_all_formulas().await?;\n let formulas: Vec = serde_json::from_str(&all_formulas_body)?;\n for formula in formulas {\n if formula.get(\"name\").and_then(Value::as_str) == Some(name) {\n return Ok(formula);\n }\n if formula.get(\"full_name\").and_then(Value::as_str) == Some(name) {\n return Ok(formula);\n }\n }\n Err(SpsError::NotFound(format!(\n \"Formula '{name}' not found in API list\"\n )))\n }\n}\n\npub async fn fetch_cask(token: &str) -> Result {\n let direct_fetch_result = fetch_raw_formulae_json(&format!(\"cask/{token}.json\")).await;\n if let Ok(body) = direct_fetch_result {\n let cask: serde_json::Value = serde_json::from_str(&body)?;\n Ok(cask)\n } else {\n debug!(\n \"Direct fetch for cask '{}' failed ({:?}). Fetching full list as fallback.\",\n token,\n direct_fetch_result.err()\n );\n let all_casks_body = fetch_all_casks().await?;\n let casks: Vec = serde_json::from_str(&all_casks_body)?;\n for cask in casks {\n if cask.get(\"token\").and_then(Value::as_str) == Some(token) {\n return Ok(cask);\n }\n }\n Err(SpsError::NotFound(format!(\n \"Cask '{token}' not found in API list\"\n )))\n }\n}\n\nasync fn fetch_github_api_json(endpoint: &str, config: &Config) -> Result {\n let url = format!(\"{GITHUB_API_BASE_URL}{endpoint}\");\n debug!(\"Fetching data from GitHub API: {}\", url);\n let client = build_api_client(config)?;\n let response = client.get(&url).send().await.map_err(|e| {\n error!(\"GitHub API request failed for {}: {}\", url, e);\n SpsError::Http(Arc::new(e))\n })?;\n if !response.status().is_success() {\n let status = response.status();\n let body = response\n .text()\n .await\n .unwrap_or_else(|e| format!(\"(Failed to read response body: {e})\"));\n error!(\n \"GitHub API request to {} returned non-success status: {}\",\n url, status\n );\n debug!(\n \"Response body for failed GitHub API request to {}: {}\",\n url, body\n );\n return Err(SpsError::Api(format!(\"HTTP status {status} from {url}\")));\n }\n let value: Value = response.json::().await.map_err(|e| {\n error!(\"Failed to parse JSON response from {}: {}\", url, e);\n SpsError::ApiRequestError(e.to_string())\n })?;\n Ok(value)\n}\n\n#[allow(dead_code)]\nasync fn fetch_github_repo_info(owner: &str, repo: &str, config: &Config) -> Result {\n let endpoint = format!(\"/repos/{owner}/{repo}\");\n fetch_github_api_json(&endpoint, config).await\n}\n\npub async fn get_formula(name: &str) -> Result {\n let url = format!(\"{FORMULAE_API_BASE_URL}/formula/{name}.json\");\n debug!(\n \"Fetching and parsing formula data for '{}' from {}\",\n name, url\n );\n let client = reqwest::Client::new();\n let response = client.get(&url).send().await.map_err(|e| {\n debug!(\"HTTP request failed when fetching formula {}: {}\", name, e);\n SpsError::Http(Arc::new(e))\n })?;\n let status = response.status();\n let text = response.text().await?;\n if !status.is_success() {\n debug!(\"Failed to fetch formula {} (Status {})\", name, status);\n debug!(\"Response body for failed formula fetch {}: {}\", name, text);\n return Err(SpsError::Api(format!(\n \"Failed to fetch formula {name}: Status {status}\"\n )));\n }\n if text.trim().is_empty() {\n error!(\"Received empty body when fetching formula {}\", name);\n return Err(SpsError::Api(format!(\n \"Empty response body for formula {name}\"\n )));\n }\n match serde_json::from_str::(&text) {\n Ok(formula) => Ok(formula),\n Err(_) => match serde_json::from_str::>(&text) {\n Ok(mut formulas) if !formulas.is_empty() => {\n debug!(\n \"Parsed formula {} from a single-element array response.\",\n name\n );\n Ok(formulas.remove(0))\n }\n Ok(_) => {\n error!(\"Received empty array when fetching formula {}\", name);\n Err(SpsError::NotFound(format!(\n \"Formula '{name}' not found (empty array returned)\"\n )))\n }\n Err(e_vec) => {\n error!(\n \"Failed to parse formula {} as object or array. Error: {}. Body (sample): {}\",\n name,\n e_vec,\n text.chars().take(500).collect::()\n );\n Err(SpsError::Json(Arc::new(e_vec)))\n }\n },\n }\n}\n\npub async fn get_all_formulas() -> Result> {\n let raw_data = fetch_all_formulas().await?;\n serde_json::from_str(&raw_data).map_err(|e| {\n error!(\"Failed to parse all_formulas response: {}\", e);\n SpsError::Json(Arc::new(e))\n })\n}\n\npub async fn get_cask(name: &str) -> Result {\n let raw_json_result = fetch_cask(name).await;\n let raw_json = match raw_json_result {\n Ok(json_val) => json_val,\n Err(e) => {\n error!(\"Failed to fetch raw JSON for cask {}: {}\", name, e);\n return Err(e);\n }\n };\n match serde_json::from_value::(raw_json.clone()) {\n Ok(cask) => Ok(cask),\n Err(e) => {\n error!(\"Failed to parse cask {} JSON: {}\", name, e);\n match serde_json::to_string_pretty(&raw_json) {\n Ok(json_str) => {\n tracing::debug!(\"Problematic JSON for cask '{}':\\n{}\", name, json_str);\n }\n Err(fmt_err) => {\n tracing::debug!(\n \"Could not pretty-print problematic JSON for cask {}: {}\",\n name,\n fmt_err\n );\n tracing::debug!(\"Raw problematic value: {:?}\", raw_json);\n }\n }\n Err(SpsError::Json(Arc::new(e)))\n }\n }\n}\n\npub async fn get_all_casks() -> Result {\n let raw_data = fetch_all_casks().await?;\n let casks: Vec = serde_json::from_str(&raw_data).map_err(|e| {\n error!(\"Failed to parse all_casks response: {}\", e);\n SpsError::Json(Arc::new(e))\n })?;\n Ok(CaskList { casks })\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/app.rs", "// In sps-core/src/build/cask/app.rs\n\nuse std::fs;\nuse std::path::{Path, PathBuf};\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::{debug, error, warn};\n\n#[cfg(target_os = \"macos\")]\n/// Finds the primary .app bundle in a directory. Returns an error if none or ambiguous.\n/// If multiple .app bundles are found, returns the first and logs a warning.\npub fn find_primary_app_bundle_in_dir(dir: &Path) -> Result {\n if !dir.is_dir() {\n return Err(SpsError::NotFound(format!(\n \"Directory {} not found for app bundle scan.\",\n dir.display()\n )));\n }\n let mut app_bundles = Vec::new();\n for entry_res in fs::read_dir(dir)? {\n let entry = entry_res?;\n let path = entry.path();\n if path.is_dir() && path.extension().is_some_and(|ext| ext == \"app\") {\n app_bundles.push(path);\n }\n }\n if app_bundles.is_empty() {\n Err(SpsError::NotFound(format!(\n \"No .app bundle found in {}\",\n dir.display()\n )))\n } else if app_bundles.len() == 1 {\n Ok(app_bundles.remove(0))\n } else {\n // Heuristic: return the largest .app bundle if multiple are found, or one matching a common\n // pattern. For now, error if multiple are present to force explicit handling in\n // Cask definitions if needed.\n warn!(\"Multiple .app bundles found in {}: {:?}. Returning the first one, but this might be ambiguous.\", dir.display(), app_bundles);\n Ok(app_bundles.remove(0)) // Or error out\n }\n}\n\nuse sps_common::pipeline::JobAction;\n\npub fn install_app_from_staged(\n cask: &Cask,\n staged_app_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n job_action: &JobAction,\n) -> Result> {\n if !staged_app_path.exists() || !staged_app_path.is_dir() {\n return Err(SpsError::NotFound(format!(\n \"Staged app bundle for {} not found or is not a directory: {}\",\n cask.token,\n staged_app_path.display()\n )));\n }\n\n let app_name = staged_app_path\n .file_name()\n .ok_or_else(|| {\n SpsError::Generic(format!(\n \"Invalid staged app path (no filename): {}\",\n staged_app_path.display()\n ))\n })?\n .to_string_lossy();\n\n let new_version_str = cask.version.clone().unwrap_or_else(|| \"latest\".to_string());\n let final_private_store_app_path: PathBuf;\n\n // Determine if we are upgrading and if the old private store app path exists\n let mut did_upgrade = false;\n\n if let JobAction::Upgrade {\n from_version,\n old_install_path,\n ..\n } = job_action\n {\n debug!(\n \"[{}] Processing app install as UPGRADE from version {}\",\n cask.token, from_version\n );\n\n // Try to get primary_app_file_name from the old manifest to build the old private store\n // path\n let old_manifest_path = old_install_path.join(\"CASK_INSTALL_MANIFEST.json\");\n let old_primary_app_name = if old_manifest_path.is_file() {\n fs::read_to_string(&old_manifest_path)\n .ok()\n .and_then(|s| {\n serde_json::from_str::(&s).ok()\n })\n .and_then(|m| m.primary_app_file_name)\n } else {\n // Fallback if old manifest is missing, use current app_name (less reliable if app name\n // changed)\n warn!(\"[{}] Old manifest not found at {} during upgrade. Using current app name '{}' for private store path derivation.\", cask.token, old_manifest_path.display(), app_name);\n Some(app_name.to_string())\n };\n\n if let Some(name_for_old_path) = old_primary_app_name {\n let old_private_store_app_dir_path =\n config.cask_store_version_path(&cask.token, from_version);\n let old_private_store_app_bundle_path =\n old_private_store_app_dir_path.join(&name_for_old_path);\n if old_private_store_app_bundle_path.exists()\n && old_private_store_app_bundle_path.is_dir()\n {\n debug!(\"[{}] UPGRADE: Old private store app bundle found at {}. Using Homebrew-style overwrite strategy.\", cask.token, old_private_store_app_bundle_path.display());\n\n // ========================================================================\n // CRITICAL: Homebrew-Style App Bundle Replacement Strategy\n // ========================================================================\n // WHY THIS APPROACH:\n // 1. Preserves extended attributes (quarantine, code signing, etc.)\n // 2. Maintains app bundle identity → prevents Gatekeeper reset\n // 3. Avoids breaking symlinks and file system references\n // 4. Ensures user data in ~/Library remains accessible to the app\n //\n // DO NOT CHANGE TO fs::rename() or similar - it breaks Gatekeeper!\n // ========================================================================\n\n // Step 1: Remove the old app bundle from private store\n // (This is safe because we're about to replace it with the new version)\n let rm_status = Command::new(\"rm\")\n .arg(\"-rf\")\n .arg(&old_private_store_app_bundle_path)\n .status()\n .map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n\n if !rm_status.success() {\n return Err(SpsError::InstallError(format!(\n \"Failed to remove old app bundle during upgrade: {}\",\n old_private_store_app_bundle_path.display()\n )));\n }\n\n // Step 2: Copy the new app bundle with ALL attributes preserved\n // The -pR flags are critical:\n // -p: Preserve file attributes, ownership, timestamps\n // -R: Recursive copy for directories\n // This ensures Gatekeeper approval and code signing are maintained\n let cp_status = Command::new(\"cp\")\n .arg(\"-pR\") // CRITICAL: Preserve all attributes, links, and metadata\n .arg(staged_app_path)\n .arg(&old_private_store_app_bundle_path)\n .status()\n .map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n\n if !cp_status.success() {\n return Err(SpsError::InstallError(format!(\n \"Failed to copy new app bundle during upgrade: {} -> {}\",\n staged_app_path.display(),\n old_private_store_app_bundle_path.display()\n )));\n }\n\n debug!(\n \"[{}] UPGRADE: Successfully overwrote old app bundle with new version using cp -pR\",\n cask.token\n );\n\n // Now, rename the parent version directory (e.g., .../1.0 -> .../1.1)\n let new_private_store_version_dir =\n config.cask_store_version_path(&cask.token, &new_version_str);\n if old_private_store_app_dir_path != new_private_store_version_dir {\n debug!(\n \"[{}] Renaming private store version dir from {} to {}\",\n cask.token,\n old_private_store_app_dir_path.display(),\n new_private_store_version_dir.display()\n );\n fs::rename(\n &old_private_store_app_dir_path,\n &new_private_store_version_dir,\n )\n .map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n }\n final_private_store_app_path =\n new_private_store_version_dir.join(app_name.as_ref());\n did_upgrade = true;\n } else {\n warn!(\"[{}] UPGRADE: Old private store app path {} not found or not a dir. Proceeding with fresh private store placement for new version.\", cask.token, old_private_store_app_bundle_path.display());\n // Fallback to fresh placement\n final_private_store_app_path =\n config.cask_store_app_path(&cask.token, &new_version_str, app_name.as_ref());\n }\n } else {\n warn!(\"[{}] UPGRADE: Could not determine old app bundle name. Proceeding with fresh private store placement for new version.\", cask.token);\n final_private_store_app_path =\n config.cask_store_app_path(&cask.token, &new_version_str, app_name.as_ref());\n }\n } else {\n // Not an upgrade\n final_private_store_app_path =\n config.cask_store_app_path(&cask.token, &new_version_str, app_name.as_ref());\n }\n\n let final_app_destination_in_applications = config.applications_dir().join(app_name.as_ref());\n let caskroom_symlink_to_final_app = cask_version_install_path.join(app_name.as_ref());\n\n debug!(\n \"Installing app '{}': Staged -> Private Store -> /Applications -> Caskroom Symlink\",\n app_name\n );\n debug!(\" Staged app source: {}\", staged_app_path.display());\n debug!(\n \" Private store copy target: {}\",\n final_private_store_app_path.display()\n );\n debug!(\n \" Final /Applications target: {}\",\n final_app_destination_in_applications.display()\n );\n debug!(\n \" Caskroom symlink target: {}\",\n caskroom_symlink_to_final_app.display()\n );\n\n // 1. Ensure Caskroom version path exists\n if !cask_version_install_path.exists() {\n fs::create_dir_all(cask_version_install_path).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\n \"Failed to create cask version dir {}: {}\",\n cask_version_install_path.display(),\n e\n ),\n )))\n })?;\n }\n\n // 2. Create private store directory if it doesn't exist\n if let Some(parent) = final_private_store_app_path.parent() {\n if !parent.exists() {\n debug!(\"Creating private store directory: {}\", parent.display());\n fs::create_dir_all(parent).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\n \"Failed to create private store dir {}: {}\",\n parent.display(),\n e\n ),\n )))\n })?;\n }\n }\n\n if !did_upgrade {\n // 3. Clean existing app in private store (if any from a failed prior attempt)\n if final_private_store_app_path.exists()\n || final_private_store_app_path.symlink_metadata().is_ok()\n {\n debug!(\n \"Removing existing item at private store path: {}\",\n final_private_store_app_path.display()\n );\n let _ = remove_path_robustly(&final_private_store_app_path, config, false);\n }\n\n // 4. Move from temporary stage to private store\n debug!(\n \"Moving staged app {} to private store path {}\",\n staged_app_path.display(),\n final_private_store_app_path.display()\n );\n if let Err(e) = fs::rename(staged_app_path, &final_private_store_app_path) {\n error!(\n \"Failed to move staged app to private store: {}. Source: {}, Dest: {}\",\n e,\n staged_app_path.display(),\n final_private_store_app_path.display()\n );\n return Err(SpsError::Io(std::sync::Arc::new(e)));\n }\n }\n\n // 5. Set/Verify Quarantine on private store copy (only if not already present)\n #[cfg(target_os = \"macos\")]\n {\n debug!(\n \"Setting/verifying quarantine on private store copy: {}\",\n final_private_store_app_path.display()\n );\n if let Err(e) = crate::utils::xattr::ensure_quarantine_attribute(\n &final_private_store_app_path,\n &cask.token,\n ) {\n error!(\n \"Failed to set quarantine on private store copy {}: {}. This is critical.\",\n final_private_store_app_path.display(),\n e\n );\n return Err(SpsError::InstallError(format!(\n \"Failed to set quarantine on private store copy {}: {}\",\n final_private_store_app_path.display(),\n e\n )));\n }\n }\n\n // ============================================================================\n // STEP 6: Handle /Applications Destination - THE MOST CRITICAL PART\n // ============================================================================\n // This is where we apply Homebrew's breakthrough strategy that preserves\n // user data and prevents Gatekeeper resets during upgrades.\n //\n // UPGRADE vs FRESH INSTALL Strategy:\n // - UPGRADE: Overwrite app in /Applications directly (preserves identity)\n // - FRESH INSTALL: Use symlink approach (normal installation)\n //\n // WHY THIS SPLIT MATTERS:\n // During upgrades, the app in /Applications already has:\n // 1. Gatekeeper approval and quarantine exemptions\n // 2. Extended attributes that macOS recognizes\n // 3. User trust and security context\n // 4. Associated user data in ~/Library that the app can access\n //\n // By overwriting IN PLACE with cp -pR, we maintain all of this state.\n // ============================================================================\n\n if let JobAction::Upgrade { .. } = job_action {\n // =======================================================================\n // UPGRADE PATH: Direct Overwrite Strategy (Homebrew's Approach)\n // =======================================================================\n // This is the breakthrough that prevents Gatekeeper resets and data loss.\n // We overwrite the existing app directly rather than removing and\n // re-symlinking, which would break the app's established identity.\n // =======================================================================\n\n if final_app_destination_in_applications.exists() {\n debug!(\n \"UPGRADE: Overwriting existing app at /Applications using Homebrew strategy: {}\",\n final_app_destination_in_applications.display()\n );\n\n // Step 1: Remove the old app in /Applications\n // We need sudo because /Applications requires elevated permissions\n let rm_status = Command::new(\"sudo\")\n .arg(\"rm\")\n .arg(\"-rf\")\n .arg(&final_app_destination_in_applications)\n .status()\n .map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n\n if !rm_status.success() {\n return Err(SpsError::InstallError(format!(\n \"Failed to remove existing app during upgrade: {}\",\n final_app_destination_in_applications.display()\n )));\n }\n\n // Copy the new app directly to /Applications, preserving all attributes\n let cp_status = Command::new(\"sudo\")\n .arg(\"cp\")\n .arg(\"-pR\") // Preserve all attributes, links, and metadata\n .arg(&final_private_store_app_path)\n .arg(&final_app_destination_in_applications)\n .status()\n .map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n\n if !cp_status.success() {\n return Err(SpsError::InstallError(format!(\n \"Failed to copy new app to /Applications during upgrade: {}\",\n final_app_destination_in_applications.display()\n )));\n }\n\n debug!(\n \"UPGRADE: Successfully overwrote app in /Applications, preserving identity: {}\",\n final_app_destination_in_applications.display()\n );\n } else {\n // App doesn't exist in /Applications during upgrade - fall back to symlink approach\n debug!(\n \"UPGRADE: App not found in /Applications, creating fresh symlink: {}\",\n final_app_destination_in_applications.display()\n );\n if let Err(e) = std::os::unix::fs::symlink(\n &final_private_store_app_path,\n &final_app_destination_in_applications,\n ) {\n error!(\n \"Failed to symlink app from private store to /Applications: {} -> {}: {}\",\n final_private_store_app_path.display(),\n final_app_destination_in_applications.display(),\n e\n );\n return Err(SpsError::InstallError(format!(\n \"Failed to symlink app from private store to {}: {}\",\n final_app_destination_in_applications.display(),\n e\n )));\n }\n }\n } else {\n // Fresh install: Clean existing app destination and create symlink\n if final_app_destination_in_applications.exists()\n || final_app_destination_in_applications\n .symlink_metadata()\n .is_ok()\n {\n debug!(\n \"Removing existing app at /Applications: {}\",\n final_app_destination_in_applications.display()\n );\n if !remove_path_robustly(&final_app_destination_in_applications, config, true) {\n return Err(SpsError::InstallError(format!(\n \"Failed to remove existing app at {}\",\n final_app_destination_in_applications.display()\n )));\n }\n }\n\n // 7. Symlink from /Applications to private store app bundle\n debug!(\n \"INFO: About to symlink app from private store {} to /Applications {}\",\n final_private_store_app_path.display(),\n final_app_destination_in_applications.display()\n );\n if let Err(e) = std::os::unix::fs::symlink(\n &final_private_store_app_path,\n &final_app_destination_in_applications,\n ) {\n error!(\n \"Failed to symlink app from private store to /Applications: {} -> {}: {}\",\n final_private_store_app_path.display(),\n final_app_destination_in_applications.display(),\n e\n );\n return Err(SpsError::InstallError(format!(\n \"Failed to symlink app from private store to {}: {}\",\n final_app_destination_in_applications.display(),\n e\n )));\n }\n }\n\n // Remove quarantine attributes from the app in /Applications (whether copied or symlinked)\n #[cfg(target_os = \"macos\")]\n {\n use xattr;\n let _ = xattr::remove(\n &final_app_destination_in_applications,\n \"com.apple.quarantine\",\n );\n let _ = xattr::remove(\n &final_app_destination_in_applications,\n \"com.apple.provenance\",\n );\n let _ = xattr::remove(&final_app_destination_in_applications, \"com.apple.macl\");\n }\n\n match job_action {\n JobAction::Upgrade { .. } => {\n debug!(\n \"INFO: Successfully updated app in /Applications during upgrade: {}\",\n final_app_destination_in_applications.display()\n );\n }\n _ => {\n debug!(\n \"INFO: Successfully symlinked app from private store {} to /Applications {}\",\n final_private_store_app_path.display(),\n final_app_destination_in_applications.display()\n );\n }\n }\n\n // 7. No quarantine set on the symlink in /Applications; attribute remains on private store\n // copy.\n\n // 8. Create Caskroom Symlink TO the app in /Applications\n let actual_caskroom_symlink_path = cask_version_install_path.join(app_name.as_ref());\n debug!(\n \"Creating Caskroom symlink {} -> {}\",\n actual_caskroom_symlink_path.display(),\n final_app_destination_in_applications.display()\n );\n\n if actual_caskroom_symlink_path.symlink_metadata().is_ok() {\n if let Err(e) = fs::remove_file(&actual_caskroom_symlink_path) {\n warn!(\n \"Failed to remove existing item at Caskroom symlink path {}: {}. Proceeding.\",\n actual_caskroom_symlink_path.display(),\n e\n );\n }\n }\n\n #[cfg(unix)]\n {\n if let Err(e) = std::os::unix::fs::symlink(\n &final_app_destination_in_applications,\n &actual_caskroom_symlink_path,\n ) {\n error!(\n \"Failed to create Caskroom symlink {} -> {}: {}\",\n actual_caskroom_symlink_path.display(),\n final_app_destination_in_applications.display(),\n e\n );\n let _ = remove_path_robustly(&final_app_destination_in_applications, config, true);\n return Err(SpsError::Io(std::sync::Arc::new(e)));\n }\n }\n\n let mut created_artifacts = vec![InstalledArtifact::AppBundle {\n path: final_app_destination_in_applications.clone(),\n }];\n created_artifacts.push(InstalledArtifact::CaskroomLink {\n link_path: actual_caskroom_symlink_path,\n target_path: final_app_destination_in_applications.clone(),\n });\n\n debug!(\n \"Successfully installed app artifact: {} (Cask: {})\",\n app_name, cask.token\n );\n\n // Write CASK_INSTALL_MANIFEST.json to ensure package is always detected as installed\n if let Err(e) = crate::install::cask::write_cask_manifest(\n cask,\n cask_version_install_path,\n created_artifacts.clone(),\n ) {\n error!(\n \"Failed to write CASK_INSTALL_MANIFEST.json for {}: {}\",\n cask.token, e\n );\n return Err(SpsError::InstallError(format!(\n \"Failed to write CASK_INSTALL_MANIFEST.json for {}: {}\",\n cask.token, e\n )));\n }\n\n Ok(created_artifacts)\n}\n\n/// Helper function for robust path removal (internal to app.rs or moved to a common util)\nfn remove_path_robustly(path: &Path, _config: &Config, use_sudo_if_needed: bool) -> bool {\n if !path.exists() && path.symlink_metadata().is_err() {\n debug!(\"Path {} not found for removal.\", path.display());\n return true;\n }\n let is_dir = path.is_dir()\n && !path\n .symlink_metadata()\n .is_ok_and(|m| m.file_type().is_symlink());\n let removal_op = || -> std::io::Result<()> {\n if is_dir {\n fs::remove_dir_all(path)\n } else {\n fs::remove_file(path)\n }\n };\n\n if let Err(e) = removal_op() {\n if e.kind() == std::io::ErrorKind::NotFound {\n return true;\n }\n if use_sudo_if_needed && e.kind() == std::io::ErrorKind::PermissionDenied {\n warn!(\n \"Direct removal of {} failed (Permission Denied). Trying with sudo rm -rf.\",\n path.display()\n );\n let output = Command::new(\"sudo\").arg(\"rm\").arg(\"-rf\").arg(path).output();\n match output {\n Ok(out) if out.status.success() => {\n debug!(\"Successfully removed {} with sudo.\", path.display());\n return true;\n }\n Ok(out) => {\n error!(\n \"`sudo rm -rf {}` failed ({}): {}\",\n path.display(),\n out.status,\n String::from_utf8_lossy(&out.stderr).trim()\n );\n return false;\n }\n Err(sudo_e) => {\n error!(\n \"Error executing `sudo rm -rf` for {}: {}\",\n path.display(),\n sudo_e\n );\n return false;\n }\n }\n } else {\n error!(\"Failed to remove {}: {}\", path.display(), e);\n return false;\n }\n }\n debug!(\"Successfully removed {}.\", path.display());\n true\n}\n"], ["/sps/sps-core/src/check/installed.rs", "// sps-core/src/check/installed.rs\nuse std::fs::{self}; // Removed DirEntry as it's not directly used here\nuse std::io;\nuse std::path::PathBuf;\nuse std::sync::Arc;\n\nuse serde::{Deserialize, Serialize};\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::keg::KegRegistry; // KegRegistry is used\nuse tracing::{debug, warn};\n\n#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]\npub enum PackageType {\n Formula,\n Cask,\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub struct InstalledPackageInfo {\n pub name: String,\n pub version: String, // This will now store keg.version_str\n pub pkg_type: PackageType,\n pub path: PathBuf,\n}\n\n// Helper closure to handle io::Result -> Option logging errors\n// Defined outside the functions to avoid repetition\nfn handle_dir_entry(res: io::Result, dir_path_str: &str) -> Option {\n match res {\n Ok(entry) => Some(entry),\n Err(e) => {\n warn!(\"Error reading entry in {}: {}\", dir_path_str, e);\n None\n }\n }\n}\n\npub async fn get_installed_packages(config: &Config) -> Result> {\n let mut installed = Vec::new();\n let keg_registry = KegRegistry::new(config.clone());\n\n match keg_registry.list_installed_kegs() {\n Ok(kegs) => {\n for keg in kegs {\n installed.push(InstalledPackageInfo {\n name: keg.name,\n version: keg.version_str, // Use keg.version_str\n pkg_type: PackageType::Formula,\n path: keg.path,\n });\n }\n }\n Err(e) => warn!(\"Failed to list installed formulae: {}\", e),\n }\n\n let caskroom_dir = config.cask_room_dir();\n if caskroom_dir.is_dir() {\n let caskroom_dir_str = caskroom_dir.to_str().unwrap_or(\"caskroom\").to_string();\n let cask_token_entries_iter =\n fs::read_dir(&caskroom_dir).map_err(|e| SpsError::Io(Arc::new(e)))?;\n\n for entry_res in cask_token_entries_iter {\n if let Some(entry) = handle_dir_entry(entry_res, &caskroom_dir_str) {\n let cask_token_path = entry.path();\n if !cask_token_path.is_dir() {\n continue;\n }\n let cask_token = entry.file_name().to_string_lossy().to_string();\n\n match fs::read_dir(&cask_token_path) {\n Ok(version_entries_iter) => {\n for version_entry_res in version_entries_iter {\n if let Some(version_entry) = handle_dir_entry(\n version_entry_res,\n cask_token_path.to_str().unwrap_or(\"token_path\"),\n ) {\n let version_path = version_entry.path();\n if version_path.is_dir()\n && version_path.join(\"CASK_INSTALL_MANIFEST.json\").is_file()\n {\n let version_str =\n version_entry.file_name().to_string_lossy().to_string();\n let manifest_path =\n version_path.join(\"CASK_INSTALL_MANIFEST.json\");\n let mut include = true;\n if manifest_path.is_file() {\n if let Ok(manifest_str) =\n std::fs::read_to_string(&manifest_path)\n {\n if let Ok(manifest_json) =\n serde_json::from_str::(\n &manifest_str,\n )\n {\n if let Some(is_installed) = manifest_json\n .get(\"is_installed\")\n .and_then(|v| v.as_bool())\n {\n include = is_installed;\n }\n }\n }\n }\n if include {\n installed.push(InstalledPackageInfo {\n name: cask_token.clone(),\n version: version_str,\n pkg_type: PackageType::Cask,\n path: version_path,\n });\n }\n // Assuming one actively installed version per cask token based\n // on manifest logic\n // If multiple version folders exist but only one manifest says\n // is_installed=true, this is fine.\n // If the intent is to list *all* version folders, the break\n // might be removed,\n // but then \"is_installed\" logic per version becomes more\n // important.\n // For now, finding the first \"active\" one is usually sufficient\n // for list/upgrade checks.\n }\n }\n }\n }\n Err(e) => warn!(\"Failed to read cask versions for {}: {}\", cask_token, e),\n }\n }\n }\n } else {\n debug!(\n \"Caskroom directory {} does not exist.\",\n caskroom_dir.display()\n );\n }\n Ok(installed)\n}\n\npub async fn get_installed_package(\n name: &str,\n config: &Config,\n) -> Result> {\n let keg_registry = KegRegistry::new(config.clone());\n if let Some(keg) = keg_registry.get_installed_keg(name)? {\n return Ok(Some(InstalledPackageInfo {\n name: keg.name,\n version: keg.version_str, // Use keg.version_str\n pkg_type: PackageType::Formula,\n path: keg.path,\n }));\n }\n\n let cask_token_path = config.cask_room_token_path(name);\n if cask_token_path.is_dir() {\n let version_entries_iter =\n fs::read_dir(&cask_token_path).map_err(|e| SpsError::Io(Arc::new(e)))?;\n for version_entry_res in version_entries_iter {\n if let Some(version_entry) = handle_dir_entry(\n version_entry_res,\n cask_token_path.to_str().unwrap_or(\"token_path\"),\n ) {\n let version_path = version_entry.path();\n if version_path.is_dir()\n && version_path.join(\"CASK_INSTALL_MANIFEST.json\").is_file()\n {\n let version_str = version_entry.file_name().to_string_lossy().to_string();\n let manifest_path = version_path.join(\"CASK_INSTALL_MANIFEST.json\");\n let mut include = true;\n if manifest_path.is_file() {\n if let Ok(manifest_str) = std::fs::read_to_string(&manifest_path) {\n if let Ok(manifest_json) =\n serde_json::from_str::(&manifest_str)\n {\n if let Some(is_installed) =\n manifest_json.get(\"is_installed\").and_then(|v| v.as_bool())\n {\n include = is_installed;\n }\n }\n }\n }\n if include {\n return Ok(Some(InstalledPackageInfo {\n name: name.to_string(),\n version: version_str,\n pkg_type: PackageType::Cask,\n path: version_path,\n }));\n }\n }\n }\n }\n }\n Ok(None)\n}\n"], ["/sps/sps-common/src/model/formula.rs", "// sps-core/src/model/formula.rs\n// *** Corrected: Removed derive Deserialize from ResourceSpec, removed unused SpsError import,\n// added ResourceSpec struct and parsing ***\n\nuse std::collections::HashMap;\nuse std::path::{Path, PathBuf};\n\nuse semver::Version;\nuse serde::{de, Deserialize, Deserializer, Serialize};\nuse serde_json::Value;\nuse tracing::{debug, error};\n\nuse crate::dependency::{Dependency, DependencyTag, Requirement};\nuse crate::error::Result; // <-- Import only Result // Use log crate imports\n\n// --- Resource Spec Struct ---\n// *** Added struct definition, REMOVED #[derive(Deserialize)] ***\n#[derive(Debug, Clone, Serialize, PartialEq, Eq)]\npub struct ResourceSpec {\n pub name: String,\n pub url: String,\n pub sha256: String,\n // Add other potential fields like version if needed later\n}\n\n// --- Bottle Related Structs (Original structure) ---\n#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]\npub struct BottleFileSpec {\n pub url: String,\n pub sha256: String,\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]\npub struct BottleSpec {\n pub stable: Option,\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]\npub struct BottleStableSpec {\n pub rebuild: u32,\n #[serde(default)]\n pub files: HashMap,\n}\n\n// --- Formula Version Struct (Original structure) ---\n#[derive(Deserialize, Serialize, Debug, Clone, Default, PartialEq, Eq)]\npub struct FormulaVersions {\n pub stable: Option,\n pub head: Option,\n #[serde(default)]\n pub bottle: bool,\n}\n\n// --- Main Formula Struct ---\n// *** Added 'resources' field ***\n#[derive(Debug, Clone, Serialize, PartialEq, Eq)]\npub struct Formula {\n pub name: String,\n pub stable_version_str: String,\n #[serde(rename = \"versions\")]\n pub version_semver: Version,\n #[serde(default)]\n pub revision: u32,\n #[serde(default)]\n pub desc: Option,\n #[serde(default)]\n pub homepage: Option,\n #[serde(default)]\n pub url: String,\n #[serde(default)]\n pub sha256: String,\n #[serde(default)]\n pub mirrors: Vec,\n #[serde(default)]\n pub bottle: BottleSpec,\n #[serde(skip_deserializing)]\n pub dependencies: Vec,\n #[serde(default, deserialize_with = \"deserialize_requirements\")]\n pub requirements: Vec,\n #[serde(skip_deserializing)] // Skip direct deserialization for this field\n pub resources: Vec, // Stores parsed resources\n #[serde(skip)]\n pub install_keg_path: Option,\n}\n\n// Custom deserialization logic for Formula\nimpl<'de> Deserialize<'de> for Formula {\n fn deserialize(deserializer: D) -> std::result::Result\n where\n D: Deserializer<'de>,\n {\n // Temporary struct reflecting the JSON structure more closely\n // *** Added 'resources' field to capture raw JSON Value ***\n #[derive(Deserialize, Debug)]\n struct RawFormulaData {\n name: String,\n #[serde(default)]\n revision: u32,\n desc: Option,\n homepage: Option,\n versions: FormulaVersions,\n #[serde(default)]\n url: String,\n #[serde(default)]\n sha256: String,\n #[serde(default)]\n mirrors: Vec,\n #[serde(default)]\n bottle: BottleSpec,\n #[serde(default)]\n dependencies: Vec,\n #[serde(default)]\n build_dependencies: Vec,\n #[serde(default)]\n test_dependencies: Vec,\n #[serde(default)]\n recommended_dependencies: Vec,\n #[serde(default)]\n optional_dependencies: Vec,\n #[serde(default, deserialize_with = \"deserialize_requirements\")]\n requirements: Vec,\n #[serde(default)]\n resources: Vec, // Capture resources as generic Value first\n #[serde(default)]\n urls: Option,\n }\n\n let raw: RawFormulaData = RawFormulaData::deserialize(deserializer)?;\n\n // --- Version Parsing (Original logic) ---\n let stable_version_str = raw\n .versions\n .stable\n .clone()\n .ok_or_else(|| de::Error::missing_field(\"versions.stable\"))?;\n let version_semver = match crate::model::version::Version::parse(&stable_version_str) {\n Ok(v) => v.into(),\n Err(_) => {\n let mut majors = 0u32;\n let mut minors = 0u32;\n let mut patches = 0u32;\n let mut part_count = 0;\n for (i, part) in stable_version_str.split('.').enumerate() {\n let numeric_part = part\n .chars()\n .take_while(|c| c.is_ascii_digit())\n .collect::();\n if numeric_part.is_empty() && i > 0 {\n break;\n }\n if numeric_part.len() < part.len() && i > 0 {\n if let Ok(num) = numeric_part.parse::() {\n match i {\n 0 => majors = num,\n 1 => minors = num,\n 2 => patches = num,\n _ => {}\n }\n part_count += 1;\n }\n break;\n }\n if let Ok(num) = numeric_part.parse::() {\n match i {\n 0 => majors = num,\n 1 => minors = num,\n 2 => patches = num,\n _ => {}\n }\n part_count += 1;\n }\n if i >= 2 {\n break;\n }\n }\n let version_str_padded = match part_count {\n 1 => format!(\"{majors}.0.0\"),\n 2 => format!(\"{majors}.{minors}.0\"),\n _ => format!(\"{majors}.{minors}.{patches}\"),\n };\n match Version::parse(&version_str_padded) {\n Ok(v) => v,\n Err(_) => {\n error!(\n \"Warning: Could not parse version '{}' (sanitized to '{}') for formula '{}'. Using 0.0.0.\",\n stable_version_str, version_str_padded, raw.name\n );\n Version::new(0, 0, 0)\n }\n }\n }\n };\n\n // --- URL/SHA256 Logic (Original logic) ---\n let mut final_url = raw.url;\n let mut final_sha256 = raw.sha256;\n if final_url.is_empty() {\n if let Some(Value::Object(urls_map)) = raw.urls {\n if let Some(Value::Object(stable_url_info)) = urls_map.get(\"stable\") {\n if let Some(Value::String(u)) = stable_url_info.get(\"url\") {\n final_url = u.clone();\n }\n if let Some(Value::String(s)) = stable_url_info\n .get(\"checksum\")\n .or_else(|| stable_url_info.get(\"sha256\"))\n {\n final_sha256 = s.clone();\n }\n }\n }\n }\n if final_url.is_empty() && raw.versions.head.is_none() {\n debug!(\"Warning: Formula '{}' has no stable URL defined.\", raw.name);\n }\n\n // --- Dependency Processing (Original logic) ---\n let mut combined_dependencies: Vec = Vec::new();\n let mut seen_deps: HashMap = HashMap::new();\n let mut process_list = |deps: &[String], tag: DependencyTag| {\n for name in deps {\n *seen_deps\n .entry(name.clone())\n .or_insert(DependencyTag::empty()) |= tag;\n }\n };\n process_list(&raw.dependencies, DependencyTag::RUNTIME);\n process_list(&raw.build_dependencies, DependencyTag::BUILD);\n process_list(&raw.test_dependencies, DependencyTag::TEST);\n process_list(\n &raw.recommended_dependencies,\n DependencyTag::RECOMMENDED | DependencyTag::RUNTIME,\n );\n process_list(\n &raw.optional_dependencies,\n DependencyTag::OPTIONAL | DependencyTag::RUNTIME,\n );\n for (name, tags) in seen_deps {\n combined_dependencies.push(Dependency::new_with_tags(name, tags));\n }\n\n // --- Resource Processing ---\n // *** Added parsing logic for the 'resources' field ***\n let mut combined_resources: Vec = Vec::new();\n for res_val in raw.resources {\n // Homebrew API JSON format puts resource spec inside a keyed object\n // e.g., { \"resource_name\": { \"url\": \"...\", \"sha256\": \"...\" } }\n if let Value::Object(map) = res_val {\n // Assume only one key-value pair per object in the array\n if let Some((res_name, res_spec_val)) = map.into_iter().next() {\n // Use the manual Deserialize impl for ResourceSpec\n match ResourceSpec::deserialize(res_spec_val.clone()) {\n // Use ::deserialize\n Ok(mut res_spec) => {\n // Inject the name from the key if missing\n if res_spec.name.is_empty() {\n res_spec.name = res_name;\n } else if res_spec.name != res_name {\n debug!(\n \"Resource name mismatch in formula '{}': key '{}' vs spec '{}'. Using key.\",\n raw.name, res_name, res_spec.name\n );\n res_spec.name = res_name; // Prefer key name\n }\n // Ensure required fields are present\n if res_spec.url.is_empty() || res_spec.sha256.is_empty() {\n debug!(\n \"Resource '{}' for formula '{}' is missing URL or SHA256. Skipping.\",\n res_spec.name, raw.name\n );\n continue;\n }\n debug!(\n \"Parsed resource '{}' for formula '{}'\",\n res_spec.name, raw.name\n );\n combined_resources.push(res_spec);\n }\n Err(e) => {\n // Use display for the error which comes from serde::de::Error::custom\n debug!(\n \"Failed to parse resource spec value for key '{}' in formula '{}': {}. Value: {:?}\",\n res_name, raw.name, e, res_spec_val\n );\n }\n }\n } else {\n debug!(\"Empty resource object found in formula '{}'.\", raw.name);\n }\n } else {\n debug!(\n \"Unexpected format for resource entry in formula '{}': expected object, got {:?}\",\n raw.name, res_val\n );\n }\n }\n\n Ok(Self {\n name: raw.name,\n stable_version_str,\n version_semver,\n revision: raw.revision,\n desc: raw.desc,\n homepage: raw.homepage,\n url: final_url,\n sha256: final_sha256,\n mirrors: raw.mirrors,\n bottle: raw.bottle,\n dependencies: combined_dependencies,\n requirements: raw.requirements,\n resources: combined_resources, // Assign parsed resources\n install_keg_path: None,\n })\n }\n}\n\n// --- Formula impl Methods ---\nimpl Formula {\n // dependencies() and requirements() are unchanged\n pub fn dependencies(&self) -> Result> {\n Ok(self.dependencies.clone())\n }\n pub fn requirements(&self) -> Result> {\n Ok(self.requirements.clone())\n }\n\n // *** Added: Returns a clone of the defined resources. ***\n pub fn resources(&self) -> Result> {\n Ok(self.resources.clone())\n }\n\n // Other methods (set_keg_path, version_str_full, accessors) are unchanged\n pub fn set_keg_path(&mut self, path: PathBuf) {\n self.install_keg_path = Some(path);\n }\n pub fn version_str_full(&self) -> String {\n if self.revision > 0 {\n format!(\"{}_{}\", self.stable_version_str, self.revision)\n } else {\n self.stable_version_str.clone()\n }\n }\n pub fn name(&self) -> &str {\n &self.name\n }\n pub fn version(&self) -> &Version {\n &self.version_semver\n }\n pub fn source_url(&self) -> &str {\n &self.url\n }\n pub fn source_sha256(&self) -> &str {\n &self.sha256\n }\n pub fn get_bottle_spec(&self, bottle_tag: &str) -> Option<&BottleFileSpec> {\n self.bottle.stable.as_ref()?.files.get(bottle_tag)\n }\n}\n\n// --- BuildEnvironment Dependency Interface (Unchanged) ---\npub trait FormulaDependencies {\n fn name(&self) -> &str;\n fn install_prefix(&self, cellar_path: &Path) -> Result;\n fn resolved_runtime_dependency_paths(&self) -> Result>;\n fn resolved_build_dependency_paths(&self) -> Result>;\n fn all_resolved_dependency_paths(&self) -> Result>;\n}\nimpl FormulaDependencies for Formula {\n fn name(&self) -> &str {\n &self.name\n }\n fn install_prefix(&self, cellar_path: &Path) -> Result {\n let version_string = self.version_str_full();\n Ok(cellar_path.join(self.name()).join(version_string))\n }\n fn resolved_runtime_dependency_paths(&self) -> Result> {\n Ok(Vec::new())\n }\n fn resolved_build_dependency_paths(&self) -> Result> {\n Ok(Vec::new())\n }\n fn all_resolved_dependency_paths(&self) -> Result> {\n Ok(Vec::new())\n }\n}\n\n// --- Deserialization Helpers ---\n// deserialize_requirements remains unchanged\nfn deserialize_requirements<'de, D>(\n deserializer: D,\n) -> std::result::Result, D::Error>\nwhere\n D: serde::Deserializer<'de>,\n{\n #[derive(Deserialize, Debug)]\n struct ReqWrapper {\n #[serde(default)]\n name: String,\n #[serde(default)]\n version: Option,\n #[serde(default)]\n cask: Option,\n #[serde(default)]\n download: Option,\n }\n let raw_reqs: Vec = Deserialize::deserialize(deserializer)?;\n let mut requirements = Vec::new();\n for req_val in raw_reqs {\n if let Ok(req_obj) = serde_json::from_value::(req_val.clone()) {\n match req_obj.name.as_str() {\n \"macos\" => {\n requirements.push(Requirement::MacOS(\n req_obj.version.unwrap_or_else(|| \"any\".to_string()),\n ));\n }\n \"xcode\" => {\n requirements.push(Requirement::Xcode(\n req_obj.version.unwrap_or_else(|| \"any\".to_string()),\n ));\n }\n \"cask\" => {\n requirements.push(Requirement::Other(format!(\n \"Cask Requirement: {}\",\n req_obj.cask.unwrap_or_else(|| \"?\".to_string())\n )));\n }\n \"download\" => {\n requirements.push(Requirement::Other(format!(\n \"Download Requirement: {}\",\n req_obj.download.unwrap_or_else(|| \"?\".to_string())\n )));\n }\n _ => requirements.push(Requirement::Other(format!(\n \"Unknown requirement type: {req_obj:?}\"\n ))),\n }\n } else if let Value::String(req_str) = req_val {\n match req_str.as_str() {\n \"macos\" => requirements.push(Requirement::MacOS(\"latest\".to_string())),\n \"xcode\" => requirements.push(Requirement::Xcode(\"latest\".to_string())),\n _ => {\n requirements.push(Requirement::Other(format!(\"Simple requirement: {req_str}\")))\n }\n }\n } else {\n debug!(\"Warning: Could not parse requirement: {:?}\", req_val);\n requirements.push(Requirement::Other(format!(\n \"Unparsed requirement: {req_val:?}\"\n )));\n }\n }\n Ok(requirements)\n}\n\n// Manual impl Deserialize for ResourceSpec (unchanged, this is needed)\nimpl<'de> Deserialize<'de> for ResourceSpec {\n fn deserialize(deserializer: D) -> std::result::Result\n where\n D: Deserializer<'de>,\n {\n #[derive(Deserialize)]\n struct Helper {\n #[serde(default)]\n name: String, // name is often the key, not in the value\n url: String,\n sha256: String,\n }\n let helper = Helper::deserialize(deserializer)?;\n // Note: The actual resource name comes from the key in the map during Formula\n // deserialization\n Ok(Self {\n name: helper.name,\n url: helper.url,\n sha256: helper.sha256,\n })\n }\n}\n"], ["/sps/sps/src/cli/list.rs", "use std::sync::Arc;\n\nuse clap::Args;\nuse colored::Colorize;\nuse prettytable::{format, Cell, Row, Table};\nuse serde_json::Value;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::formulary::Formulary;\nuse sps_core::check::installed::{get_installed_packages, PackageType};\nuse sps_core::check::update::check_for_updates;\nuse sps_core::check::InstalledPackageInfo;\n\n#[derive(Args, Debug)]\npub struct List {\n /// Show only formulas\n #[arg(long = \"formula\")]\n pub formula_only: bool,\n /// Show only casks\n #[arg(long = \"cask\")]\n pub cask_only: bool,\n /// Show only packages with updates available\n #[arg(long = \"outdated\")]\n pub outdated_only: bool,\n}\n\nimpl List {\n pub async fn run(&self, config: &Config, cache: Arc) -> Result<()> {\n let installed = get_installed_packages(config).await?;\n // Only show the latest version for each name\n use std::collections::HashMap;\n let mut formula_map: HashMap<&str, &sps_core::check::installed::InstalledPackageInfo> =\n HashMap::new();\n let mut cask_map: HashMap<&str, &sps_core::check::installed::InstalledPackageInfo> =\n HashMap::new();\n for pkg in &installed {\n match pkg.pkg_type {\n PackageType::Formula => {\n let entry = formula_map.entry(pkg.name.as_str()).or_insert(pkg);\n if pkg.version > entry.version {\n formula_map.insert(pkg.name.as_str(), pkg);\n }\n }\n PackageType::Cask => {\n let entry = cask_map.entry(pkg.name.as_str()).or_insert(pkg);\n if pkg.version > entry.version {\n cask_map.insert(pkg.name.as_str(), pkg);\n }\n }\n }\n }\n let mut formulas: Vec<&InstalledPackageInfo> = formula_map.values().copied().collect();\n let mut casks: Vec<&InstalledPackageInfo> = cask_map.values().copied().collect();\n // Sort formulas and casks alphabetically by name, then version\n formulas.sort_by(|a, b| a.name.cmp(&b.name).then(a.version.cmp(&b.version)));\n casks.sort_by(|a, b| a.name.cmp(&b.name).then(a.version.cmp(&b.version)));\n // If Nothing Installed.\n if formulas.is_empty() && casks.is_empty() {\n println!(\"{}\", \"0 formulas and casks installed\".yellow());\n return Ok(());\n }\n // If user wants to show installed formulas only.\n if self.formula_only {\n if self.outdated_only {\n self.print_outdated_formulas_table(&formulas, config)\n .await?;\n } else {\n self.print_formulas_table(formulas, config);\n }\n return Ok(());\n }\n // If user wants to show installed casks only.\n if self.cask_only {\n if self.outdated_only {\n self.print_outdated_casks_table(&casks, cache.clone())\n .await?;\n } else {\n self.print_casks_table(casks, cache);\n }\n return Ok(());\n }\n\n // If user wants to show only outdated packages\n if self.outdated_only {\n self.print_outdated_all_table(&formulas, &casks, config, cache)\n .await?;\n return Ok(());\n }\n\n // Default Implementation\n let formulary = Formulary::new(config.clone());\n let mut table = Table::new();\n table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n table.add_row(Row::new(vec![\n Cell::new(\"Type\").style_spec(\"b\"),\n Cell::new(\"Name\").style_spec(\"b\"),\n Cell::new(\"Installed\").style_spec(\"b\"),\n Cell::new(\"New Version?\").style_spec(\"b\"),\n ]));\n let mut formula_count = 0;\n let mut cask_count = 0;\n for pkg in formulas {\n let latest = formulary.load_formula(&pkg.name).ok();\n let (has_new, _) = match latest {\n Some(ref f) => {\n let latest_version = f.version_str_full();\n (latest_version != pkg.version, latest_version)\n }\n None => (false, \"-\".to_string()),\n };\n table.add_row(Row::new(vec![\n Cell::new(\"Formula\").style_spec(\"Fg\"),\n Cell::new(&pkg.name).style_spec(\"Fb\"),\n Cell::new(&pkg.version),\n // TODO: update to display the latest version string.\n // TODO: Not showing when the using --all flag.\n Cell::new(if has_new { \"✔\" } else { \"\" }),\n ]));\n formula_count += 1;\n }\n for pkg in casks {\n // Try to load cask info from cache\n let cask_val = cache.load_raw(\"cask.json\").ok().and_then(|raw| {\n serde_json::from_str::>(&raw)\n .ok()?\n .into_iter()\n .find(|v| v.get(\"token\").and_then(|t| t.as_str()) == Some(&pkg.name))\n });\n let (has_new, _) = match cask_val {\n Some(ref v) => {\n let latest_version = v.get(\"version\").and_then(|v| v.as_str()).unwrap_or(\"-\");\n (latest_version != pkg.version, latest_version.to_string())\n }\n None => (false, \"-\".to_string()),\n };\n table.add_row(Row::new(vec![\n Cell::new(\"Cask\").style_spec(\"Fy\"),\n Cell::new(&pkg.name).style_spec(\"Fb\"),\n Cell::new(&pkg.version),\n Cell::new(if has_new { \"✔\" } else { \"\" }),\n ]));\n cask_count += 1;\n }\n table.printstd();\n if formula_count > 0 && cask_count > 0 {\n println!(\n \"{}\",\n format!(\"{formula_count} formulas, {cask_count} casks installed\").bold()\n );\n } else if formula_count > 0 {\n println!(\"{}\", format!(\"{formula_count} formulas installed\").bold());\n } else if cask_count > 0 {\n println!(\"{}\", format!(\"{cask_count} casks installed\").bold());\n }\n Ok(())\n }\n\n fn print_formulas_table(\n &self,\n formulas: Vec<&sps_core::check::installed::InstalledPackageInfo>,\n config: &Config,\n ) {\n if formulas.is_empty() {\n println!(\"No formulas installed.\");\n return;\n }\n let formulary = Formulary::new(config.clone());\n let mut table = Table::new();\n table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n // Add header row with \"Formulas\" spanning all columns, font color green\n table.add_row(Row::new(vec![Cell::new_align(\n \"Formulas\",\n format::Alignment::CENTER,\n )\n .style_spec(\"bFg\")\n .with_hspan(3)]));\n table.add_row(Row::new(vec![\n Cell::new(\"Name\").style_spec(\"b\"),\n Cell::new(\"Installed\").style_spec(\"b\"),\n Cell::new(\"New Version?\").style_spec(\"b\"),\n ]));\n let mut formula_count = 0;\n for pkg in formulas {\n let latest = formulary.load_formula(&pkg.name).ok();\n let (has_new, _) = match latest {\n Some(ref f) => {\n let latest_version = f.version_str_full();\n (latest_version != pkg.version, latest_version)\n }\n None => (false, \"-\".to_string()),\n };\n table.add_row(Row::new(vec![\n Cell::new(&pkg.name).style_spec(\"Fb\"),\n Cell::new(&pkg.version),\n Cell::new(if has_new { \"✔\" } else { \"\" }),\n ]));\n formula_count += 1;\n }\n table.printstd();\n println!(\"{}\", format!(\"{formula_count} formulas installed\").bold());\n }\n\n fn print_casks_table(\n &self,\n casks: Vec<&sps_core::check::installed::InstalledPackageInfo>,\n cache: Arc,\n ) {\n if casks.is_empty() {\n println!(\"No casks installed.\");\n return;\n }\n let mut table = Table::new();\n table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n // Add header row with \"Casks\" spanning all columns, font color green\n table.add_row(Row::new(vec![Cell::new_align(\n \"Casks\",\n format::Alignment::CENTER,\n )\n .style_spec(\"bFg\")\n .with_hspan(3)]));\n table.add_row(Row::new(vec![\n Cell::new(\"Name\").style_spec(\"b\"),\n Cell::new(\"Installed\").style_spec(\"b\"),\n Cell::new(\"New Version?\").style_spec(\"b\"),\n ]));\n let mut cask_count = 0;\n for pkg in casks {\n // Try to load cask info from cache\n let cask_val = cache.load_raw(\"cask.json\").ok().and_then(|raw| {\n serde_json::from_str::>(&raw)\n .ok()?\n .into_iter()\n .find(|v| v.get(\"token\").and_then(|t| t.as_str()) == Some(&pkg.name))\n });\n let (has_new, _) = match cask_val {\n Some(ref v) => {\n let latest_version = v.get(\"version\").and_then(|v| v.as_str()).unwrap_or(\"-\");\n (latest_version != pkg.version, latest_version.to_string())\n }\n None => (false, \"-\".to_string()),\n };\n table.add_row(Row::new(vec![\n Cell::new(&pkg.name).style_spec(\"Fb\"),\n Cell::new(&pkg.version),\n Cell::new(if has_new { \"✔\" } else { \"\" }),\n ]));\n cask_count += 1;\n }\n table.printstd();\n println!(\"{}\", format!(\"{cask_count} casks installed\").bold());\n }\n\n async fn print_outdated_formulas_table(\n &self,\n formulas: &[&InstalledPackageInfo],\n config: &Config,\n ) -> Result<()> {\n if formulas.is_empty() {\n println!(\"No formulas installed.\");\n return Ok(());\n }\n\n // Convert to owned for update checking\n let formula_packages: Vec =\n formulas.iter().map(|&f| f.clone()).collect();\n let cache = sps_common::cache::Cache::new(config)?;\n let updates = check_for_updates(&formula_packages, &cache, config).await?;\n\n if updates.is_empty() {\n println!(\"No formula updates available.\");\n return Ok(());\n }\n\n let mut table = Table::new();\n table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n table.add_row(Row::new(vec![Cell::new_align(\n \"Outdated Formulas\",\n format::Alignment::CENTER,\n )\n .style_spec(\"bFg\")\n .with_hspan(3)]));\n table.add_row(Row::new(vec![\n Cell::new(\"Name\").style_spec(\"b\"),\n Cell::new(\"Installed\").style_spec(\"b\"),\n Cell::new(\"Available\").style_spec(\"b\"),\n ]));\n\n let mut count = 0;\n for update in updates {\n table.add_row(Row::new(vec![\n Cell::new(&update.name).style_spec(\"Fb\"),\n Cell::new(&update.installed_version),\n Cell::new(&update.available_version).style_spec(\"Fg\"),\n ]));\n count += 1;\n }\n\n table.printstd();\n println!(\"{}\", format!(\"{count} outdated formulas\").bold());\n Ok(())\n }\n\n async fn print_outdated_casks_table(\n &self,\n casks: &[&InstalledPackageInfo],\n cache: Arc,\n ) -> Result<()> {\n if casks.is_empty() {\n println!(\"No casks installed.\");\n return Ok(());\n }\n\n // Convert to owned for update checking\n let cask_packages: Vec = casks.iter().map(|&c| c.clone()).collect();\n let config = cache.config();\n let updates = check_for_updates(&cask_packages, &cache, config).await?;\n\n if updates.is_empty() {\n println!(\"No cask updates available.\");\n return Ok(());\n }\n\n let mut table = Table::new();\n table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n table.add_row(Row::new(vec![Cell::new_align(\n \"Outdated Casks\",\n format::Alignment::CENTER,\n )\n .style_spec(\"bFg\")\n .with_hspan(3)]));\n table.add_row(Row::new(vec![\n Cell::new(\"Name\").style_spec(\"b\"),\n Cell::new(\"Installed\").style_spec(\"b\"),\n Cell::new(\"Available\").style_spec(\"b\"),\n ]));\n\n let mut count = 0;\n for update in updates {\n table.add_row(Row::new(vec![\n Cell::new(&update.name).style_spec(\"Fb\"),\n Cell::new(&update.installed_version),\n Cell::new(&update.available_version).style_spec(\"Fy\"),\n ]));\n count += 1;\n }\n\n table.printstd();\n println!(\"{}\", format!(\"{count} outdated casks\").bold());\n Ok(())\n }\n\n async fn print_outdated_all_table(\n &self,\n formulas: &[&InstalledPackageInfo],\n casks: &[&InstalledPackageInfo],\n config: &Config,\n cache: Arc,\n ) -> Result<()> {\n // Convert to owned for update checking\n let mut all_packages: Vec = Vec::new();\n all_packages.extend(formulas.iter().map(|&f| f.clone()));\n all_packages.extend(casks.iter().map(|&c| c.clone()));\n\n if all_packages.is_empty() {\n println!(\"{}\", \"0 formulas and casks installed\".yellow());\n return Ok(());\n }\n\n let updates = check_for_updates(&all_packages, &cache, config).await?;\n\n if updates.is_empty() {\n println!(\"No outdated packages found.\");\n return Ok(());\n }\n\n let mut table = Table::new();\n table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n table.add_row(Row::new(vec![\n Cell::new(\"Type\").style_spec(\"b\"),\n Cell::new(\"Name\").style_spec(\"b\"),\n Cell::new(\"Installed\").style_spec(\"b\"),\n Cell::new(\"Available\").style_spec(\"b\"),\n ]));\n\n let mut formula_count = 0;\n let mut cask_count = 0;\n\n for update in updates {\n let (type_name, type_style) = match update.pkg_type {\n PackageType::Formula => {\n formula_count += 1;\n (\"Formula\", \"Fg\")\n }\n PackageType::Cask => {\n cask_count += 1;\n (\"Cask\", \"Fy\")\n }\n };\n\n table.add_row(Row::new(vec![\n Cell::new(type_name).style_spec(type_style),\n Cell::new(&update.name).style_spec(\"Fb\"),\n Cell::new(&update.installed_version),\n Cell::new(&update.available_version).style_spec(\"Fg\"),\n ]));\n }\n\n table.printstd();\n if formula_count > 0 && cask_count > 0 {\n println!(\n \"{}\",\n format!(\"{formula_count} outdated formulas, {cask_count} outdated casks\").bold()\n );\n } else if formula_count > 0 {\n println!(\"{}\", format!(\"{formula_count} outdated formulas\").bold());\n } else if cask_count > 0 {\n println!(\"{}\", format!(\"{cask_count} outdated casks\").bold());\n }\n Ok(())\n }\n}\n"], ["/sps/sps-common/src/keg.rs", "// sps-common/src/keg.rs\nuse std::fs;\nuse std::path::PathBuf;\n\n// Corrected tracing imports: added error, removed unused debug\nuse tracing::{debug, error, warn};\n\nuse super::config::Config;\nuse super::error::{Result, SpsError};\n\n/// Represents information about an installed package (Keg).\n#[derive(Debug, Clone, PartialEq, Eq)]\npub struct InstalledKeg {\n pub name: String,\n pub version_str: String,\n pub path: PathBuf,\n}\n\n/// Manages querying installed packages in the Cellar.\n#[derive(Debug)]\npub struct KegRegistry {\n config: Config,\n}\n\nimpl KegRegistry {\n pub fn new(config: Config) -> Self {\n Self { config }\n }\n\n fn formula_cellar_path(&self, name: &str) -> PathBuf {\n self.config.cellar_dir().join(name)\n }\n\n pub fn get_opt_path(&self, name: &str) -> PathBuf {\n self.config.opt_dir().join(name)\n }\n\n pub fn get_installed_keg(&self, name: &str) -> Result> {\n let formula_dir = self.formula_cellar_path(name);\n debug!(\n \"[KEG_REGISTRY:{}] get_installed_keg: Checking for formula '{}'. Path to check: {}\",\n name,\n name,\n formula_dir.display()\n );\n\n if !formula_dir.is_dir() {\n debug!(\"[KEG_REGISTRY:{}] get_installed_keg: Formula directory '{}' NOT FOUND or not a directory. Returning None.\", name, formula_dir.display());\n return Ok(None);\n }\n\n let mut latest_keg: Option = None;\n debug!(\n \"[KEG_REGISTRY:{}] get_installed_keg: Reading entries in formula directory '{}'\",\n name,\n formula_dir.display()\n );\n\n match fs::read_dir(&formula_dir) {\n Ok(entries) => {\n for entry_result in entries {\n match entry_result {\n Ok(entry) => {\n let path = entry.path();\n debug!(\n \"[KEG_REGISTRY:{}] get_installed_keg: Examining entry '{}'\",\n name,\n path.display()\n );\n\n if path.is_dir() {\n if let Some(version_str_full) =\n path.file_name().and_then(|n| n.to_str())\n {\n debug!(\"[KEG_REGISTRY:{}] get_installed_keg: Entry is a directory with name: {}\", name, version_str_full);\n\n let current_keg_candidate = InstalledKeg {\n name: name.to_string(),\n version_str: version_str_full.to_string(),\n path: path.clone(),\n };\n\n match latest_keg {\n Some(ref current_latest) => {\n // Compare &str with &str\n if version_str_full\n > current_latest.version_str.as_str()\n {\n debug!(\"[KEG_REGISTRY:{}] get_installed_keg: Updating latest keg (lexicographical) to: {}\", name, path.display());\n latest_keg = Some(current_keg_candidate);\n }\n }\n None => {\n debug!(\"[KEG_REGISTRY:{}] get_installed_keg: Setting first found keg as latest: {}\", name, path.display());\n latest_keg = Some(current_keg_candidate);\n }\n }\n } else {\n debug!(\"[KEG_REGISTRY:{}] get_installed_keg: Could not get filename as string for path '{}'\", name, path.display());\n }\n } else {\n debug!(\"[KEG_REGISTRY:{}] get_installed_keg: Entry '{}' is not a directory.\", name, path.display());\n }\n }\n Err(e) => {\n warn!(\"[KEG_REGISTRY:{}] get_installed_keg: Error reading a directory entry in '{}': {}. Skipping entry.\", name, formula_dir.display(), e);\n }\n }\n }\n }\n Err(e) => {\n // Corrected macro usage\n error!(\"[KEG_REGISTRY:{}] get_installed_keg: Failed to read_dir for formula directory '{}' (error: {}). Returning error.\", name, formula_dir.display(), e);\n return Err(SpsError::Io(std::sync::Arc::new(e)));\n }\n }\n\n if let Some(keg) = &latest_keg {\n // Corrected format string arguments\n debug!(\"[KEG_REGISTRY:{}] get_installed_keg: For formula '{}', latest keg found: path={}, version_str={}\", name, name, keg.path.display(), keg.version_str);\n } else {\n // Corrected format string arguments\n debug!(\"[KEG_REGISTRY:{}] get_installed_keg: For formula '{}', no installable keg version found in directory '{}'.\", name, name, formula_dir.display());\n }\n Ok(latest_keg)\n }\n\n pub fn list_installed_kegs(&self) -> Result> {\n let mut installed_kegs = Vec::new();\n let cellar_dir = self.cellar_path();\n debug!(\n \"[KEG_REGISTRY] list_installed_kegs: Scanning cellar: {}\",\n cellar_dir.display()\n );\n\n if !cellar_dir.is_dir() {\n debug!(\"[KEG_REGISTRY] list_installed_kegs: Cellar directory NOT FOUND. Returning empty list.\");\n return Ok(installed_kegs);\n }\n\n for formula_entry_res in fs::read_dir(cellar_dir)? {\n let formula_entry = match formula_entry_res {\n Ok(fe) => fe,\n Err(e) => {\n warn!(\"[KEG_REGISTRY] list_installed_kegs: Error reading entry in cellar: {}. Skipping.\", e);\n continue;\n }\n };\n let formula_path = formula_entry.path();\n debug!(\n \"[KEG_REGISTRY] list_installed_kegs: Examining formula path: {}\",\n formula_path.display()\n );\n\n if formula_path.is_dir() {\n if let Some(formula_name) = formula_path.file_name().and_then(|n| n.to_str()) {\n debug!(\n \"[KEG_REGISTRY] list_installed_kegs: Found formula directory: {}\",\n formula_name\n );\n match fs::read_dir(&formula_path) {\n Ok(version_entries) => {\n for version_entry_res in version_entries {\n let version_entry = match version_entry_res {\n Ok(ve) => ve,\n Err(e) => {\n warn!(\"[KEG_REGISTRY:{}] list_installed_kegs: Error reading version entry in '{}': {}. Skipping.\", formula_name, formula_path.display(), e);\n continue;\n }\n };\n let version_path = version_entry.path();\n debug!(\"[KEG_REGISTRY:{}] list_installed_kegs: Examining version path: {}\", formula_name, version_path.display());\n\n if version_path.is_dir() {\n if let Some(version_str_full) =\n version_path.file_name().and_then(|n| n.to_str())\n {\n debug!(\"[KEG_REGISTRY:{}] list_installed_kegs: Found version directory '{}' with name: {}\", formula_name, version_path.display(), version_str_full);\n installed_kegs.push(InstalledKeg {\n name: formula_name.to_string(),\n version_str: version_str_full.to_string(),\n path: version_path.clone(),\n });\n } else {\n debug!(\"[KEG_REGISTRY:{}] list_installed_kegs: Could not get filename for version path {}\", formula_name, version_path.display());\n }\n } else {\n debug!(\"[KEG_REGISTRY:{}] list_installed_kegs: Version path {} is not a directory.\", formula_name, version_path.display());\n }\n }\n }\n Err(e) => {\n warn!(\"[KEG_REGISTRY:{}] list_installed_kegs: Failed to read_dir for formula versions in '{}': {}.\", formula_name, formula_path.display(), e);\n }\n }\n } else {\n debug!(\"[KEG_REGISTRY] list_installed_kegs: Could not get filename for formula path {}\", formula_path.display());\n }\n } else {\n debug!(\n \"[KEG_REGISTRY] list_installed_kegs: Formula path {} is not a directory.\",\n formula_path.display()\n );\n }\n }\n debug!(\n \"[KEG_REGISTRY] list_installed_kegs: Found {} total installed keg versions.\",\n installed_kegs.len()\n );\n Ok(installed_kegs)\n }\n\n pub fn cellar_path(&self) -> PathBuf {\n self.config.cellar_dir()\n }\n\n pub fn get_keg_path(&self, name: &str, version_str_raw: &str) -> PathBuf {\n self.formula_cellar_path(name).join(version_str_raw)\n }\n}\n"], ["/sps/sps-core/src/install/extract.rs", "// Path: sps-core/src/install/extract.rs\nuse std::collections::HashSet;\nuse std::fs::{self, File};\nuse std::io::{self, Read, Seek};\nuse std::path::{Component, Path, PathBuf};\nuse std::process::Command;\n\nuse bzip2::read::BzDecoder;\nuse flate2::read::GzDecoder;\nuse sps_common::error::{Result, SpsError};\nuse tar::{Archive, EntryType};\nuse tracing::{debug, error, warn};\nuse zip::ZipArchive;\n\n#[cfg(target_os = \"macos\")]\nuse crate::utils::xattr;\n\npub(crate) fn infer_archive_root_dir(\n archive_path: &Path,\n archive_type: &str,\n) -> Result> {\n tracing::debug!(\n \"Inferring root directory for archive: {}\",\n archive_path.display()\n );\n let file = File::open(archive_path).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed to open archive {}: {}\", archive_path.display(), e),\n )))\n })?;\n\n match archive_type {\n \"zip\" => infer_zip_root(file, archive_path),\n \"gz\" | \"tgz\" => {\n let decompressed = GzDecoder::new(file);\n infer_tar_root(decompressed, archive_path)\n }\n \"bz2\" | \"tbz\" | \"tbz2\" => {\n let decompressed = BzDecoder::new(file);\n infer_tar_root(decompressed, archive_path)\n }\n \"xz\" | \"txz\" => {\n // Use external xz command to decompress, then read as tar\n infer_xz_tar_root(archive_path)\n }\n \"tar\" => infer_tar_root(file, archive_path),\n _ => Err(SpsError::Generic(format!(\n \"Cannot infer root dir for unsupported archive type '{}' in {}\",\n archive_type,\n archive_path.display()\n ))),\n }\n}\n\nfn infer_tar_root(reader: R, archive_path_for_log: &Path) -> Result> {\n let mut archive = Archive::new(reader);\n let mut unique_roots = HashSet::new();\n let mut non_empty_entry_found = false;\n let mut first_component_name: Option = None;\n\n for entry_result in archive.entries()? {\n let entry = entry_result.map_err(|e| {\n SpsError::Generic(format!(\n \"Error reading TAR entry from {}: {}\",\n archive_path_for_log.display(),\n e\n ))\n })?;\n let path = entry\n .path()\n .map_err(|e| {\n SpsError::Generic(format!(\n \"Invalid path in TAR entry from {}: {}\",\n archive_path_for_log.display(),\n e\n ))\n })?\n .into_owned();\n\n if path.components().next().is_none() {\n continue;\n }\n\n if let Some(first_comp) = path.components().next() {\n if let Component::Normal(name) = first_comp {\n non_empty_entry_found = true;\n let current_root = PathBuf::from(name);\n if first_component_name.is_none() {\n first_component_name = Some(current_root.clone());\n }\n unique_roots.insert(current_root);\n\n if unique_roots.len() > 1 {\n tracing::debug!(\n \"Multiple top-level items found in TAR {}, cannot infer single root.\",\n archive_path_for_log.display()\n );\n return Ok(None);\n }\n } else {\n tracing::debug!(\n \"Non-standard top-level component ({:?}) found in TAR {}, cannot infer single root.\",\n first_comp,\n archive_path_for_log.display()\n );\n return Ok(None);\n }\n } else {\n tracing::debug!(\n \"Empty or unusual path found in TAR {}, cannot infer single root.\",\n archive_path_for_log.display()\n );\n return Ok(None);\n }\n }\n\n if unique_roots.len() == 1 && non_empty_entry_found {\n let inferred_root = first_component_name.unwrap();\n tracing::debug!(\n \"Inferred single root directory in TAR {}: {}\",\n archive_path_for_log.display(),\n inferred_root.display()\n );\n Ok(Some(inferred_root))\n } else if !non_empty_entry_found {\n tracing::warn!(\n \"TAR archive {} appears to be empty or contain only metadata.\",\n archive_path_for_log.display()\n );\n Ok(None)\n } else {\n tracing::debug!(\n \"No single common root directory found in TAR {}. unique_roots count: {}\",\n archive_path_for_log.display(),\n unique_roots.len()\n );\n Ok(None)\n }\n}\n\nfn infer_xz_tar_root(archive_path: &Path) -> Result> {\n // Create a temporary file for decompressed content\n let temp_file =\n tempfile::NamedTempFile::new().map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n\n // Use external xz command to decompress\n let output = Command::new(\"xz\")\n .args([\"-dc\", archive_path.to_str().unwrap()])\n .output()\n .map_err(|e| {\n SpsError::Generic(format!(\n \"Failed to run xz command for decompression: {e}. Make sure xz is installed.\"\n ))\n })?;\n\n if !output.status.success() {\n return Err(SpsError::Generic(format!(\n \"xz decompression failed: {}\",\n String::from_utf8_lossy(&output.stderr)\n )));\n }\n\n // Write decompressed data to temp file\n std::fs::write(temp_file.path(), &output.stdout)\n .map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n\n // Read as tar\n let file = File::open(temp_file.path()).map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n infer_tar_root(file, archive_path)\n}\n\nfn infer_zip_root(reader: R, archive_path: &Path) -> Result> {\n let mut archive = ZipArchive::new(reader).map_err(|e| {\n SpsError::Generic(format!(\n \"Failed to open ZIP archive {}: {}\",\n archive_path.display(),\n e\n ))\n })?;\n\n let mut root_candidates = HashSet::new();\n\n for i in 0..archive.len() {\n let file = archive\n .by_index(i)\n .map_err(|e| SpsError::Generic(format!(\"Failed to read ZIP entry {i}: {e}\")))?;\n\n if let Some(enclosed_name) = file.enclosed_name() {\n if let Some(Component::Normal(name)) = enclosed_name.components().next() {\n root_candidates.insert(name.to_string_lossy().to_string());\n }\n }\n }\n\n if root_candidates.len() == 1 {\n let root = root_candidates.into_iter().next().unwrap();\n Ok(Some(PathBuf::from(root)))\n } else {\n Ok(None)\n }\n}\n\n#[cfg(target_os = \"macos\")]\npub fn quarantine_extracted_apps_in_stage(stage_dir: &Path, agent_name: &str) -> Result<()> {\n use std::fs;\n\n use tracing::{debug, warn};\n debug!(\n \"Searching for .app bundles in {} to apply quarantine.\",\n stage_dir.display()\n );\n if stage_dir.is_dir() {\n for entry_result in fs::read_dir(stage_dir)? {\n let entry = entry_result?;\n let entry_path = entry.path();\n if entry_path.is_dir() && entry_path.extension().is_some_and(|ext| ext == \"app\") {\n debug!(\n \"Found app bundle in stage: {}. Applying quarantine.\",\n entry_path.display()\n );\n if let Err(e) = xattr::set_quarantine_attribute(&entry_path, agent_name) {\n warn!(\n \"Failed to set quarantine attribute on staged app {}: {}. Installation will continue.\",\n entry_path.display(),\n e\n );\n }\n }\n }\n }\n Ok(())\n}\n\npub fn extract_archive(\n archive_path: &Path,\n target_dir: &Path,\n strip_components: usize,\n archive_type: &str,\n) -> Result<()> {\n debug!(\n \"Extracting archive '{}' (type: {}) to '{}' (strip_components={}) using native Rust crates.\",\n archive_path.display(),\n archive_type,\n target_dir.display(),\n strip_components\n );\n\n fs::create_dir_all(target_dir).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\n \"Failed to create target directory {}: {}\",\n target_dir.display(),\n e\n ),\n )))\n })?;\n\n let file = File::open(archive_path).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed to open archive {}: {}\", archive_path.display(), e),\n )))\n })?;\n\n let result = match archive_type {\n \"zip\" => extract_zip_archive(file, target_dir, strip_components, archive_path),\n \"gz\" | \"tgz\" => {\n let tar = GzDecoder::new(file);\n extract_tar_archive(tar, target_dir, strip_components, archive_path)\n }\n \"bz2\" | \"tbz\" | \"tbz2\" => {\n let tar = BzDecoder::new(file);\n extract_tar_archive(tar, target_dir, strip_components, archive_path)\n }\n \"xz\" | \"txz\" => extract_xz_tar_archive(archive_path, target_dir, strip_components),\n \"tar\" => extract_tar_archive(file, target_dir, strip_components, archive_path),\n _ => Err(SpsError::Generic(format!(\n \"Unsupported archive type provided for extraction: '{}' for file {}\",\n archive_type,\n archive_path.display()\n ))),\n };\n #[cfg(target_os = \"macos\")]\n {\n if result.is_ok() {\n // Only quarantine if main extraction was successful\n if let Err(e) = quarantine_extracted_apps_in_stage(target_dir, \"sps-extractor\") {\n tracing::warn!(\n \"Error during post-extraction quarantine scan for {}: {}\",\n archive_path.display(),\n e\n );\n }\n }\n }\n result\n}\n\n/// Represents a hardlink operation that was deferred.\nfn extract_xz_tar_archive(\n archive_path: &Path,\n target_dir: &Path,\n strip_components: usize,\n) -> Result<()> {\n debug!(\n \"Extracting XZ+TAR archive using external xz command: {}\",\n archive_path.display()\n );\n\n // Create a temporary file for decompressed content\n let temp_file =\n tempfile::NamedTempFile::new().map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n\n // Use external xz command to decompress\n let output = Command::new(\"xz\")\n .args([\"-dc\", archive_path.to_str().unwrap()])\n .output()\n .map_err(|e| {\n SpsError::Generic(format!(\n \"Failed to run xz command for extraction: {e}. Make sure xz is installed.\"\n ))\n })?;\n\n if !output.status.success() {\n return Err(SpsError::Generic(format!(\n \"xz decompression failed during extraction: {}\",\n String::from_utf8_lossy(&output.stderr)\n )));\n }\n\n // Write decompressed data to temp file\n std::fs::write(temp_file.path(), &output.stdout)\n .map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n\n // Extract as tar\n let file = File::open(temp_file.path()).map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n extract_tar_archive(file, target_dir, strip_components, archive_path)\n}\n\n#[cfg(unix)]\nstruct DeferredHardLink {\n link_path_in_archive: PathBuf,\n target_name_in_archive: PathBuf,\n}\n\nfn extract_tar_archive(\n reader: R,\n target_dir: &Path,\n strip_components: usize,\n archive_path_for_log: &Path,\n) -> Result<()> {\n let mut archive = Archive::new(reader);\n archive.set_preserve_permissions(true);\n archive.set_unpack_xattrs(true);\n archive.set_overwrite(true);\n\n debug!(\n \"Starting TAR extraction for {}\",\n archive_path_for_log.display()\n );\n\n #[cfg(unix)]\n let mut deferred_hardlinks: Vec = Vec::new();\n let mut errors: Vec = Vec::new();\n\n for entry_result in archive.entries()? {\n let mut entry = entry_result.map_err(|e| {\n SpsError::Generic(format!(\n \"Error reading TAR entry from {}: {}\",\n archive_path_for_log.display(),\n e\n ))\n })?;\n\n let original_path_in_archive: PathBuf = entry\n .path()\n .map_err(|e| {\n SpsError::Generic(format!(\n \"Invalid path in TAR entry from {}: {}\",\n archive_path_for_log.display(),\n e\n ))\n })?\n .into_owned();\n\n let stripped_components_iter: Vec> = original_path_in_archive\n .components()\n .skip(strip_components)\n .collect();\n\n if stripped_components_iter.is_empty() {\n debug!(\n \"Skipping entry due to strip_components: {:?}\",\n original_path_in_archive\n );\n continue;\n }\n\n let mut final_target_path_on_disk = target_dir.to_path_buf();\n for comp in stripped_components_iter {\n match comp {\n Component::Normal(p) => final_target_path_on_disk.push(p),\n Component::CurDir => {}\n Component::ParentDir => {\n let msg = format!(\n \"Unsafe '..' in TAR path {} after stripping in {}\",\n original_path_in_archive.display(),\n archive_path_for_log.display()\n );\n error!(\"{}\", msg);\n errors.push(msg);\n continue;\n }\n Component::Prefix(_) | Component::RootDir => {\n let msg = format!(\n \"Disallowed component {:?} in TAR path {}\",\n comp,\n original_path_in_archive.display()\n );\n error!(\"{}\", msg);\n errors.push(msg);\n continue;\n }\n }\n }\n\n if !final_target_path_on_disk.starts_with(target_dir) {\n let msg = format!(\n \"Path traversal {} -> {} detected in {}\",\n original_path_in_archive.display(),\n final_target_path_on_disk.display(),\n archive_path_for_log.display()\n );\n error!(\"{}\", msg);\n errors.push(msg);\n continue;\n }\n\n if let Some(parent) = final_target_path_on_disk.parent() {\n if !parent.exists() {\n fs::create_dir_all(parent).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(io::Error::new(\n e.kind(),\n format!(\"Failed create parent dir {}: {}\", parent.display(), e),\n )))\n })?;\n }\n }\n\n #[cfg(unix)]\n if entry.header().entry_type() == EntryType::Link {\n if let Ok(Some(link_name_in_archive)) = entry.link_name() {\n let deferred_link = DeferredHardLink {\n link_path_in_archive: original_path_in_archive.clone(),\n target_name_in_archive: link_name_in_archive.into_owned(),\n };\n debug!(\n \"Deferring hardlink: archive path '{}' -> archive target '{}'\",\n original_path_in_archive.display(),\n deferred_link.target_name_in_archive.display()\n );\n deferred_hardlinks.push(deferred_link);\n continue;\n } else {\n let msg = format!(\n \"Hardlink entry '{}' in {} has no link target name.\",\n original_path_in_archive.display(),\n archive_path_for_log.display()\n );\n warn!(\"{}\", msg);\n errors.push(msg);\n continue;\n }\n }\n\n match entry.unpack(&final_target_path_on_disk) {\n Ok(_) => debug!(\n \"Unpacked TAR entry to: {}\",\n final_target_path_on_disk.display()\n ),\n Err(e) => {\n if e.kind() != io::ErrorKind::AlreadyExists {\n let msg = format!(\n \"Failed to unpack entry {:?} to {}: {}. Entry type: {:?}\",\n original_path_in_archive,\n final_target_path_on_disk.display(),\n e,\n entry.header().entry_type()\n );\n error!(\"{}\", msg);\n errors.push(msg);\n } else {\n debug!(\"Entry already exists at {}, skipping unpack (tar crate overwrite=true handles this).\", final_target_path_on_disk.display());\n }\n }\n }\n }\n\n #[cfg(unix)]\n for deferred in deferred_hardlinks {\n let mut disk_link_path = target_dir.to_path_buf();\n for comp in deferred\n .link_path_in_archive\n .components()\n .skip(strip_components)\n {\n if let Component::Normal(p) = comp {\n disk_link_path.push(p);\n }\n // Other components should have been caught by safety checks above\n }\n\n let mut disk_target_path = target_dir.to_path_buf();\n // The link_name_in_archive is relative to the archive root *before* stripping.\n // We need to apply stripping to it as well to find its final disk location.\n for comp in deferred\n .target_name_in_archive\n .components()\n .skip(strip_components)\n {\n if let Component::Normal(p) = comp {\n disk_target_path.push(p);\n }\n }\n\n if !disk_target_path.starts_with(target_dir) || !disk_link_path.starts_with(target_dir) {\n let msg = format!(\"Skipping deferred hardlink due to path traversal attempt: link '{}' -> target '{}'\", disk_link_path.display(), disk_target_path.display());\n error!(\"{}\", msg);\n errors.push(msg);\n continue;\n }\n\n debug!(\n \"Attempting deferred hardlink: disk link path '{}' -> disk target path '{}'\",\n disk_link_path.display(),\n disk_target_path.display()\n );\n\n if disk_target_path.exists() {\n if let Some(parent) = disk_link_path.parent() {\n if !parent.exists() {\n if let Err(e) = fs::create_dir_all(parent) {\n let msg = format!(\n \"Failed to create parent directory for deferred hardlink {}: {}\",\n disk_link_path.display(),\n e\n );\n error!(\"{}\", msg);\n errors.push(msg);\n continue;\n }\n }\n }\n\n if disk_link_path.symlink_metadata().is_ok() {\n // Check if something (file or symlink) exists at the link creation spot\n if let Err(e) = fs::remove_file(&disk_link_path) {\n // Attempt to remove it\n warn!(\"Could not remove existing file/symlink at hardlink destination {}: {}. Hardlink creation may fail.\", disk_link_path.display(), e);\n }\n }\n\n if let Err(e) = fs::hard_link(&disk_target_path, &disk_link_path) {\n let msg = format!(\n \"Failed to create deferred hardlink '{}' -> '{}': {}. Target exists: {}\",\n disk_link_path.display(),\n disk_target_path.display(),\n e,\n disk_target_path.exists()\n );\n error!(\"{}\", msg);\n errors.push(msg);\n } else {\n debug!(\n \"Successfully created deferred hardlink: '{}' -> '{}'\",\n disk_link_path.display(),\n disk_target_path.display()\n );\n }\n } else {\n let msg = format!(\n \"Target '{}' for deferred hardlink '{}' does not exist. Hardlink not created.\",\n disk_target_path.display(),\n disk_link_path.display()\n );\n error!(\"{}\", msg);\n errors.push(msg);\n }\n }\n\n if !errors.is_empty() {\n return Err(SpsError::InstallError(format!(\n \"Failed during TAR extraction for {} with {} error(s): {}\",\n archive_path_for_log.display(),\n errors.len(),\n errors.join(\"; \")\n )));\n }\n\n debug!(\n \"Finished TAR extraction for {}\",\n archive_path_for_log.display()\n );\n #[cfg(target_os = \"macos\")]\n {\n if let Err(e) = quarantine_extracted_apps_in_stage(target_dir, \"sps-tar-extractor\") {\n tracing::warn!(\n \"Error during post-tar extraction quarantine scan for {}: {}\",\n archive_path_for_log.display(),\n e\n );\n }\n }\n Ok(())\n}\n\nfn extract_zip_archive(\n reader: R,\n target_dir: &Path,\n strip_components: usize,\n archive_path_for_log: &Path,\n) -> Result<()> {\n let mut archive = ZipArchive::new(reader).map_err(|e| {\n SpsError::Generic(format!(\n \"Failed to open ZIP {}: {}\",\n archive_path_for_log.display(),\n e\n ))\n })?;\n\n debug!(\n \"Starting ZIP extraction for {}\",\n archive_path_for_log.display()\n );\n\n for i in 0..archive.len() {\n let mut file = archive\n .by_index(i)\n .map_err(|e| SpsError::Generic(format!(\"Failed to read ZIP entry {i}: {e}\")))?;\n\n let Some(original_path_in_archive) = file.enclosed_name() else {\n debug!(\"Skipping unsafe ZIP entry (no enclosed name)\");\n continue;\n };\n\n let stripped_components_iter: Vec> = original_path_in_archive\n .components()\n .skip(strip_components)\n .collect();\n\n if stripped_components_iter.is_empty() {\n debug!(\n \"Skipping ZIP entry {} due to strip_components\",\n original_path_in_archive.display()\n );\n continue;\n }\n\n let mut final_target_path_on_disk = target_dir.to_path_buf();\n for comp in stripped_components_iter {\n match comp {\n Component::Normal(p) => final_target_path_on_disk.push(p),\n Component::CurDir => {}\n Component::ParentDir => {\n error!(\n \"Unsafe '..' in ZIP path {} after strip_components\",\n original_path_in_archive.display()\n );\n return Err(SpsError::Generic(format!(\n \"Unsafe '..' component in ZIP path {}\",\n original_path_in_archive.display()\n )));\n }\n Component::Prefix(_) | Component::RootDir => {\n error!(\n \"Disallowed component {:?} in ZIP path {}\",\n comp,\n original_path_in_archive.display()\n );\n return Err(SpsError::Generic(format!(\n \"Disallowed component in ZIP path {}\",\n original_path_in_archive.display()\n )));\n }\n }\n }\n\n if !final_target_path_on_disk.starts_with(target_dir) {\n error!(\n \"ZIP path traversal detected: {} -> {}\",\n original_path_in_archive.display(),\n final_target_path_on_disk.display()\n );\n return Err(SpsError::Generic(format!(\n \"ZIP path traversal detected in {}\",\n archive_path_for_log.display()\n )));\n }\n\n if let Some(parent) = final_target_path_on_disk.parent() {\n if !parent.exists() {\n fs::create_dir_all(parent).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(io::Error::new(\n e.kind(),\n format!(\n \"Failed to create parent directory {}: {}\",\n parent.display(),\n e\n ),\n )))\n })?;\n }\n }\n\n if file.is_dir() {\n debug!(\n \"Creating directory: {}\",\n final_target_path_on_disk.display()\n );\n fs::create_dir_all(&final_target_path_on_disk).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(io::Error::new(\n e.kind(),\n format!(\n \"Failed to create directory {}: {}\",\n final_target_path_on_disk.display(),\n e\n ),\n )))\n })?;\n } else {\n // Regular file\n if final_target_path_on_disk.exists() {\n match fs::remove_file(&final_target_path_on_disk) {\n Ok(_) => {}\n Err(e) if e.kind() == io::ErrorKind::NotFound => {}\n Err(e) => return Err(SpsError::Io(std::sync::Arc::new(e))),\n }\n }\n\n debug!(\"Extracting file: {}\", final_target_path_on_disk.display());\n let mut outfile = File::create(&final_target_path_on_disk).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(io::Error::new(\n e.kind(),\n format!(\n \"Failed to create file {}: {}\",\n final_target_path_on_disk.display(),\n e\n ),\n )))\n })?;\n\n std::io::copy(&mut file, &mut outfile).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(io::Error::new(\n e.kind(),\n format!(\n \"Failed to write file {}: {}\",\n final_target_path_on_disk.display(),\n e\n ),\n )))\n })?;\n\n // Set permissions on Unix systems\n #[cfg(unix)]\n {\n use std::os::unix::fs::PermissionsExt;\n if let Some(mode) = file.unix_mode() {\n let perms = std::fs::Permissions::from_mode(mode);\n std::fs::set_permissions(&final_target_path_on_disk, perms)\n .map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n }\n }\n }\n }\n\n debug!(\n \"Finished ZIP extraction for {}\",\n archive_path_for_log.display()\n );\n\n // Apply quarantine to extracted apps on macOS\n #[cfg(target_os = \"macos\")]\n {\n if let Err(e) = quarantine_extracted_apps_in_stage(target_dir, \"sps-zip-extractor\") {\n tracing::warn!(\n \"Error during post-zip extraction quarantine scan for {}: {}\",\n archive_path_for_log.display(),\n e\n );\n }\n }\n\n Ok(())\n}\n"], ["/sps/sps/src/cli/status.rs", "// sps/src/cli/status.rs\nuse std::collections::{HashMap, HashSet};\nuse std::io::{self, Write};\nuse std::time::Instant;\n\nuse colored::*;\nuse sps_common::config::Config;\nuse sps_common::pipeline::{PipelineEvent, PipelinePackageType};\nuse tokio::sync::broadcast;\nuse tracing::debug;\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq)]\nenum JobStatus {\n Waiting,\n Downloading,\n Downloaded,\n Cached,\n Processing,\n Installing,\n Linking,\n Success,\n Failed,\n}\n\nimpl JobStatus {\n fn display_state(&self) -> &'static str {\n match self {\n JobStatus::Waiting => \"waiting\",\n JobStatus::Downloading => \"downloading\",\n JobStatus::Downloaded => \"downloaded\",\n JobStatus::Cached => \"cached\",\n JobStatus::Processing => \"processing\",\n JobStatus::Installing => \"installing\",\n JobStatus::Linking => \"linking\",\n JobStatus::Success => \"success\",\n JobStatus::Failed => \"failed\",\n }\n }\n\n fn slot_indicator(&self) -> String {\n match self {\n JobStatus::Waiting => \" ⧗\".yellow().to_string(),\n JobStatus::Downloading => \" ⬇\".blue().to_string(),\n JobStatus::Downloaded => \" ✓\".green().to_string(),\n JobStatus::Cached => \" ⌂\".cyan().to_string(),\n JobStatus::Processing => \" ⚙\".yellow().to_string(),\n JobStatus::Installing => \" ⚙\".cyan().to_string(),\n JobStatus::Linking => \" →\".magenta().to_string(),\n JobStatus::Success => \" ✓\".green().bold().to_string(),\n JobStatus::Failed => \" ✗\".red().bold().to_string(),\n }\n }\n\n fn colored_state(&self) -> ColoredString {\n match self {\n JobStatus::Waiting => self.display_state().dimmed(),\n JobStatus::Downloading => self.display_state().blue(),\n JobStatus::Downloaded => self.display_state().green(),\n JobStatus::Cached => self.display_state().cyan(),\n JobStatus::Processing => self.display_state().yellow(),\n JobStatus::Installing => self.display_state().yellow(),\n JobStatus::Linking => self.display_state().yellow(),\n JobStatus::Success => self.display_state().green(),\n JobStatus::Failed => self.display_state().red(),\n }\n }\n}\n\nstruct JobInfo {\n name: String,\n status: JobStatus,\n size_bytes: Option,\n current_bytes_downloaded: Option,\n start_time: Option,\n pool_id: usize,\n}\n\nimpl JobInfo {\n fn _elapsed_str(&self) -> String {\n match self.start_time {\n Some(start) => format!(\"{:.1}s\", start.elapsed().as_secs_f64()),\n None => \"–\".to_string(),\n }\n }\n\n fn size_str(&self) -> String {\n match self.size_bytes {\n Some(bytes) => format_bytes(bytes),\n None => \"–\".to_string(),\n }\n }\n}\n\nstruct StatusDisplay {\n jobs: HashMap,\n job_order: Vec,\n total_jobs: usize,\n next_pool_id: usize,\n _start_time: Instant,\n active_downloads: HashSet,\n total_bytes: u64,\n downloaded_bytes: u64,\n last_speed_update: Instant,\n last_aggregate_bytes_snapshot: u64,\n current_speed_bps: f64,\n _speed_history: Vec,\n header_printed: bool,\n last_line_count: usize,\n}\n\nimpl StatusDisplay {\n fn new() -> Self {\n Self {\n jobs: HashMap::new(),\n job_order: Vec::new(),\n total_jobs: 0,\n next_pool_id: 1,\n _start_time: Instant::now(),\n active_downloads: HashSet::new(),\n total_bytes: 0,\n downloaded_bytes: 0,\n last_speed_update: Instant::now(),\n last_aggregate_bytes_snapshot: 0,\n current_speed_bps: 0.0,\n _speed_history: Vec::new(),\n header_printed: false,\n last_line_count: 0,\n }\n }\n\n fn add_job(&mut self, target_id: String, status: JobStatus, size_bytes: Option) {\n if !self.jobs.contains_key(&target_id) {\n let job_info = JobInfo {\n name: target_id.clone(),\n status,\n size_bytes,\n current_bytes_downloaded: if status == JobStatus::Downloading {\n Some(0)\n } else {\n None\n },\n start_time: if status != JobStatus::Waiting {\n Some(Instant::now())\n } else {\n None\n },\n pool_id: self.next_pool_id,\n };\n\n if let Some(bytes) = size_bytes {\n self.total_bytes += bytes;\n }\n\n if status == JobStatus::Downloading {\n self.active_downloads.insert(target_id.to_string());\n }\n\n self.jobs.insert(target_id.clone(), job_info);\n self.job_order.push(target_id);\n self.next_pool_id += 1;\n }\n }\n\n fn update_job_status(&mut self, target_id: &str, status: JobStatus, size_bytes: Option) {\n if let Some(job) = self.jobs.get_mut(target_id) {\n let was_downloading = job.status == JobStatus::Downloading;\n let is_downloading = status == JobStatus::Downloading;\n\n job.status = status;\n\n if job.start_time.is_none() && status != JobStatus::Waiting {\n job.start_time = Some(Instant::now());\n }\n\n if let Some(bytes) = size_bytes {\n if job.size_bytes.is_none() {\n self.total_bytes += bytes;\n }\n job.size_bytes = Some(bytes);\n }\n\n // Update download counts\n if was_downloading && !is_downloading {\n self.active_downloads.remove(target_id);\n if let Some(bytes) = job.size_bytes {\n job.current_bytes_downloaded = Some(bytes);\n self.downloaded_bytes += bytes;\n }\n } else if !was_downloading && is_downloading {\n self.active_downloads.insert(target_id.to_string());\n job.current_bytes_downloaded = Some(0);\n }\n }\n }\n\n fn update_download_progress(\n &mut self,\n target_id: &str,\n bytes_so_far: u64,\n total_size: Option,\n ) {\n if let Some(job) = self.jobs.get_mut(target_id) {\n job.current_bytes_downloaded = Some(bytes_so_far);\n\n if let Some(total) = total_size {\n if job.size_bytes.is_none() {\n // Update total bytes estimate\n self.total_bytes += total;\n job.size_bytes = Some(total);\n } else if job.size_bytes != Some(total) {\n // Adjust total bytes if estimate changed\n if let Some(old_size) = job.size_bytes {\n self.total_bytes = self.total_bytes.saturating_sub(old_size) + total;\n }\n job.size_bytes = Some(total);\n }\n }\n }\n }\n\n fn update_speed(&mut self) {\n let now = Instant::now();\n let time_diff = now.duration_since(self.last_speed_update).as_secs_f64();\n\n if time_diff >= 0.0625 {\n // Calculate current total bytes for all jobs with current download progress\n let current_active_bytes: u64 = self\n .jobs\n .values()\n .filter(|job| matches!(job.status, JobStatus::Downloading))\n .map(|job| job.current_bytes_downloaded.unwrap_or(0))\n .sum();\n\n // Calculate bytes difference since last update\n let bytes_diff =\n current_active_bytes.saturating_sub(self.last_aggregate_bytes_snapshot);\n\n // Calculate speed\n if time_diff > 0.0 && bytes_diff > 0 {\n self.current_speed_bps = bytes_diff as f64 / time_diff;\n } else if !self\n .jobs\n .values()\n .any(|job| job.status == JobStatus::Downloading)\n {\n // No active downloads, reset speed to 0\n self.current_speed_bps = 0.0;\n }\n // If no bytes diff but still have active downloads, keep previous speed\n\n self.last_speed_update = now;\n self.last_aggregate_bytes_snapshot = current_active_bytes;\n }\n }\n\n fn render(&mut self) {\n self.update_speed();\n\n if !self.header_printed {\n // First render - print header and jobs\n self.print_header();\n let job_output = self.build_job_rows();\n print!(\"{job_output}\");\n self.header_printed = true;\n // Count lines: header + jobs + separator + summary\n let job_lines = job_output.lines().count();\n self.last_line_count = 1 + job_lines + 1 + 1;\n } else {\n // Subsequent renders - clear and reprint header, job rows and summary\n self.clear_previous_output();\n self.print_header();\n let job_output = self.build_job_rows();\n print!(\"{job_output}\");\n // Update line count (header + jobs + separator)\n let job_lines = job_output.lines().count();\n self.last_line_count = 1 + job_lines + 1;\n }\n\n // Print separator\n println!(\"{}\", \"─\".repeat(49).dimmed());\n\n // Print status summary\n let completed = self\n .jobs\n .values()\n .filter(|j| matches!(j.status, JobStatus::Success))\n .count();\n let failed = self\n .jobs\n .values()\n .filter(|j| matches!(j.status, JobStatus::Failed))\n .count();\n let _progress_chars = self.generate_progress_bar(completed, failed);\n let _speed_str = format_speed(self.current_speed_bps);\n\n io::stdout().flush().unwrap();\n }\n\n fn print_header(&self) {\n println!(\n \"{:<6} {:<12} {:<15} {:>8} {}\",\n \"IID\".bold().dimmed(),\n \"STATE\".bold().dimmed(),\n \"PKG\".bold().dimmed(),\n \"SIZE\".bold().dimmed(),\n \"SLOT\".bold().dimmed()\n );\n }\n\n fn build_job_rows(&self) -> String {\n let mut output = String::new();\n\n // Job rows\n for target_id in &self.job_order {\n if let Some(job) = self.jobs.get(target_id) {\n let progress_str = if job.status == JobStatus::Downloading {\n match (job.current_bytes_downloaded, job.size_bytes) {\n (Some(downloaded), Some(_total)) => format_bytes(downloaded).to_string(),\n (Some(downloaded), None) => format_bytes(downloaded),\n _ => job.size_str(),\n }\n } else {\n job.size_str()\n };\n\n output.push_str(&format!(\n \"{:<6} {:<12} {:<15} {:>8} {}\\n\",\n format!(\"#{:02}\", job.pool_id).cyan(),\n job.status.colored_state(),\n job.name.cyan(),\n progress_str,\n job.status.slot_indicator()\n ));\n }\n }\n\n output\n }\n\n fn clear_previous_output(&self) {\n // Move cursor up and clear lines\n for _ in 0..self.last_line_count {\n print!(\"\\x1b[1A\\x1b[2K\"); // Move up one line and clear it\n }\n io::stdout().flush().unwrap();\n }\n\n fn generate_progress_bar(&self, completed: usize, failed: usize) -> String {\n if self.total_jobs == 0 {\n return \"\".to_string();\n }\n\n let total_done = completed + failed;\n let progress_width = 8;\n let filled = (total_done * progress_width) / self.total_jobs;\n let remaining = progress_width - filled;\n\n let filled_str = \"▍\".repeat(filled).green();\n let remaining_str = \"·\".repeat(remaining).dimmed();\n\n format!(\"{filled_str}{remaining_str}\")\n }\n}\n\nfn format_bytes(bytes: u64) -> String {\n const UNITS: &[&str] = &[\"B\", \"kB\", \"MB\", \"GB\"];\n let mut value = bytes as f64;\n let mut unit_idx = 0;\n\n while value >= 1000.0 && unit_idx < UNITS.len() - 1 {\n value /= 1000.0;\n unit_idx += 1;\n }\n\n if unit_idx == 0 {\n format!(\"{bytes}B\")\n } else {\n format!(\"{:.1}{}\", value, UNITS[unit_idx])\n }\n}\n\nfn format_speed(bytes_per_sec: f64) -> String {\n if bytes_per_sec < 1.0 {\n return \"0 B/s\".to_string();\n }\n\n const UNITS: &[&str] = &[\"B/s\", \"kB/s\", \"MB/s\", \"GB/s\"];\n let mut value = bytes_per_sec;\n let mut unit_idx = 0;\n\n while value >= 1000.0 && unit_idx < UNITS.len() - 1 {\n value /= 1000.0;\n unit_idx += 1;\n }\n\n format!(\"{:.1} {}\", value, UNITS[unit_idx])\n}\n\npub async fn handle_events(_config: Config, mut event_rx: broadcast::Receiver) {\n let mut display = StatusDisplay::new();\n let mut logs_buffer = Vec::new();\n let mut pipeline_active = false;\n let mut refresh_interval = tokio::time::interval(tokio::time::Duration::from_millis(62));\n refresh_interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);\n\n loop {\n tokio::select! {\n _ = refresh_interval.tick() => {\n if pipeline_active && display.header_printed {\n display.render();\n }\n }\n event_result = event_rx.recv() => {\n match event_result {\n Ok(event) => match event {\n PipelineEvent::PipelineStarted { total_jobs } => {\n pipeline_active = true;\n display.total_jobs = total_jobs;\n println!(\"{}\", \"Starting pipeline.\".cyan().bold());\n }\n PipelineEvent::PlanningStarted => {\n debug!(\"{}\", \"Planning operations.\".cyan());\n }\n PipelineEvent::DependencyResolutionStarted => {\n println!(\"{}\", \"Resolving dependencies\".cyan());\n }\n PipelineEvent::DependencyResolutionFinished => {\n debug!(\"{}\", \"Dependency resolution complete.\".cyan());\n }\n PipelineEvent::PlanningFinished { job_count } => {\n println!(\"{} {}\", \"Planning finished. Jobs:\".bold(), job_count);\n println!();\n }\n PipelineEvent::DownloadStarted { target_id, url: _ } => {\n display.add_job(target_id.clone(), JobStatus::Downloading, None);\n if pipeline_active {\n display.render();\n }\n }\n PipelineEvent::DownloadFinished {\n target_id,\n size_bytes,\n ..\n } => {\n display.update_job_status(&target_id, JobStatus::Downloaded, Some(size_bytes));\n if pipeline_active {\n display.render();\n }\n }\n PipelineEvent::DownloadProgressUpdate {\n target_id,\n bytes_so_far,\n total_size,\n } => {\n display.update_download_progress(&target_id, bytes_so_far, total_size);\n if pipeline_active {\n display.render();\n }\n }\n PipelineEvent::DownloadCached {\n target_id,\n size_bytes,\n } => {\n display.update_job_status(&target_id, JobStatus::Cached, Some(size_bytes));\n if pipeline_active {\n display.render();\n }\n }\n PipelineEvent::DownloadFailed {\n target_id, error, ..\n } => {\n display.update_job_status(&target_id, JobStatus::Failed, None);\n logs_buffer.push(format!(\n \"{} {}: {}\",\n \"Download failed:\".red(),\n target_id.cyan(),\n error.red()\n ));\n if pipeline_active {\n display.render();\n }\n }\n PipelineEvent::JobProcessingStarted { target_id } => {\n display.update_job_status(&target_id, JobStatus::Processing, None);\n if pipeline_active {\n display.render();\n }\n }\n PipelineEvent::BuildStarted { target_id } => {\n display.update_job_status(&target_id, JobStatus::Processing, None);\n if pipeline_active {\n display.render();\n }\n }\n PipelineEvent::InstallStarted { target_id, .. } => {\n display.update_job_status(&target_id, JobStatus::Installing, None);\n if pipeline_active {\n display.render();\n }\n }\n PipelineEvent::LinkStarted { target_id, .. } => {\n display.update_job_status(&target_id, JobStatus::Linking, None);\n if pipeline_active {\n display.render();\n }\n }\n PipelineEvent::JobSuccess {\n target_id,\n action,\n pkg_type,\n } => {\n display.update_job_status(&target_id, JobStatus::Success, None);\n let type_str = match pkg_type {\n PipelinePackageType::Formula => \"Formula\",\n PipelinePackageType::Cask => \"Cask\",\n };\n let action_str = match action {\n sps_common::pipeline::JobAction::Install => \"Installed\",\n sps_common::pipeline::JobAction::Upgrade { .. } => \"Upgraded\",\n sps_common::pipeline::JobAction::Reinstall { .. } => \"Reinstalled\",\n };\n logs_buffer.push(format!(\n \"{}: {} ({})\",\n action_str.green(),\n target_id.cyan(),\n type_str,\n ));\n if pipeline_active {\n display.render();\n }\n }\n PipelineEvent::JobFailed {\n target_id, error, ..\n } => {\n display.update_job_status(&target_id, JobStatus::Failed, None);\n logs_buffer.push(format!(\n \"{} {}: {}\",\n \"✗\".red().bold(),\n target_id.cyan(),\n error.red()\n ));\n if pipeline_active {\n display.render();\n }\n }\n PipelineEvent::LogInfo { message } => {\n logs_buffer.push(message);\n }\n PipelineEvent::LogWarn { message } => {\n logs_buffer.push(message.yellow().to_string());\n }\n PipelineEvent::LogError { message } => {\n logs_buffer.push(message.red().to_string());\n }\n PipelineEvent::PipelineFinished {\n duration_secs,\n success_count,\n fail_count,\n } => {\n if display.header_printed {\n display.render();\n }\n\n println!();\n\n println!(\n \"{} in {:.2}s ({} succeeded, {} failed)\",\n \"Pipeline finished\".bold(),\n duration_secs,\n success_count,\n fail_count\n );\n\n if !logs_buffer.is_empty() {\n println!();\n for log in &logs_buffer {\n println!(\"{log}\");\n }\n }\n\n break;\n }\n _ => {}\n },\n Err(broadcast::error::RecvError::Closed) => {\n break;\n }\n Err(broadcast::error::RecvError::Lagged(_)) => {\n // Ignore lag for now\n }\n }\n }\n }\n }\n}\n"], ["/sps/sps/src/cli/search.rs", "use std::sync::Arc;\n\nuse clap::Args;\nuse colored::Colorize;\nuse prettytable::{format, Cell, Row, Table};\nuse serde_json::Value;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_net::api;\nuse terminal_size::{terminal_size, Width};\nuse unicode_width::{UnicodeWidthChar, UnicodeWidthStr};\n\n#[derive(Args, Debug)]\npub struct Search {\n pub query: String,\n #[arg(long, conflicts_with = \"cask\")]\n pub formula: bool,\n #[arg(long, conflicts_with = \"formula\")]\n pub cask: bool,\n}\n\npub enum SearchType {\n All,\n Formula,\n Cask,\n}\n\nimpl Search {\n pub async fn run(&self, config: &Config, cache: Arc) -> Result<()> {\n let search_type = if self.formula {\n SearchType::Formula\n } else if self.cask {\n SearchType::Cask\n } else {\n SearchType::All\n };\n run_search(&self.query, search_type, config, cache).await\n }\n}\n\npub async fn run_search(\n query: &str,\n search_type: SearchType,\n _config: &Config,\n cache: Arc,\n) -> Result<()> {\n tracing::debug!(\"Searching for packages matching: {}\", query);\n\n println!(\"Searching for \\\"{query}\\\"\");\n\n let mut formula_matches = Vec::new();\n let mut cask_matches = Vec::new();\n let mut formula_err = None;\n let mut cask_err = None;\n\n if matches!(search_type, SearchType::All | SearchType::Formula) {\n match search_formulas(Arc::clone(&cache), query).await {\n Ok(matches) => formula_matches = matches,\n Err(e) => {\n tracing::error!(\"Error searching formulas: {}\", e);\n formula_err = Some(e);\n }\n }\n }\n\n if matches!(search_type, SearchType::All | SearchType::Cask) {\n match search_casks(Arc::clone(&cache), query).await {\n Ok(matches) => cask_matches = matches,\n Err(e) => {\n tracing::error!(\"Error searching casks: {}\", e);\n cask_err = Some(e);\n }\n }\n }\n\n if formula_matches.is_empty() && cask_matches.is_empty() {\n if let Some(e) = formula_err.or(cask_err) {\n return Err(e);\n }\n }\n\n print_search_results(query, &formula_matches, &cask_matches);\n\n Ok(())\n}\n\nasync fn search_formulas(cache: Arc, query: &str) -> Result> {\n let query_lower = query.to_lowercase();\n let mut matches = Vec::new();\n let mut data_source_name = \"cache\";\n\n let formula_data_result = cache.load_raw(\"formula.json\");\n\n let formulas: Vec = match formula_data_result {\n Ok(formula_data) => serde_json::from_str(&formula_data)?,\n Err(e) => {\n tracing::debug!(\"Formula cache load failed ({}), fetching from API\", e);\n data_source_name = \"API\";\n let all_formulas = api::fetch_all_formulas().await?;\n\n if let Err(cache_err) = cache.store_raw(\"formula.json\", &all_formulas) {\n tracing::warn!(\"Failed to cache formula data after fetching: {}\", cache_err);\n }\n serde_json::from_str(&all_formulas)?\n }\n };\n\n for formula in formulas {\n if is_formula_match(&formula, &query_lower) {\n matches.push(formula);\n }\n }\n\n tracing::debug!(\n \"Found {} potential formula matches from {}\",\n matches.len(),\n data_source_name\n );\n tracing::debug!(\n \"Filtered down to {} formula matches with available bottles\",\n matches.len()\n );\n\n Ok(matches)\n}\n\nasync fn search_casks(cache: Arc, query: &str) -> Result> {\n let query_lower = query.to_lowercase();\n let mut matches = Vec::new();\n let mut data_source_name = \"cache\";\n\n let cask_data_result = cache.load_raw(\"cask.json\");\n\n let casks: Vec = match cask_data_result {\n Ok(cask_data) => serde_json::from_str(&cask_data)?,\n Err(e) => {\n tracing::debug!(\"Cask cache load failed ({}), fetching from API\", e);\n data_source_name = \"API\";\n let all_casks = api::fetch_all_casks().await?;\n\n if let Err(cache_err) = cache.store_raw(\"cask.json\", &all_casks) {\n tracing::warn!(\"Failed to cache cask data after fetching: {}\", cache_err);\n }\n serde_json::from_str(&all_casks)?\n }\n };\n\n for cask in casks {\n if is_cask_match(&cask, &query_lower) {\n matches.push(cask);\n }\n }\n tracing::debug!(\n \"Found {} cask matches from {}\",\n matches.len(),\n data_source_name\n );\n Ok(matches)\n}\n\nfn is_formula_match(formula: &Value, query: &str) -> bool {\n if let Some(name) = formula.get(\"name\").and_then(|n| n.as_str()) {\n if name.to_lowercase().contains(query) {\n return true;\n }\n }\n\n if let Some(full_name) = formula.get(\"full_name\").and_then(|n| n.as_str()) {\n if full_name.to_lowercase().contains(query) {\n return true;\n }\n }\n\n if let Some(desc) = formula.get(\"desc\").and_then(|d| d.as_str()) {\n if desc.to_lowercase().contains(query) {\n return true;\n }\n }\n\n if let Some(aliases) = formula.get(\"aliases\").and_then(|a| a.as_array()) {\n for alias in aliases {\n if let Some(alias_str) = alias.as_str() {\n if alias_str.to_lowercase().contains(query) {\n return true;\n }\n }\n }\n }\n\n false\n}\n\nfn is_cask_match(cask: &Value, query: &str) -> bool {\n if let Some(token) = cask.get(\"token\").and_then(|t| t.as_str()) {\n if token.to_lowercase().contains(query) {\n return true;\n }\n }\n\n if let Some(names) = cask.get(\"name\").and_then(|n| n.as_array()) {\n for name in names {\n if let Some(name_str) = name.as_str() {\n if name_str.to_lowercase().contains(query) {\n return true;\n }\n }\n }\n }\n\n if let Some(desc) = cask.get(\"desc\").and_then(|d| d.as_str()) {\n if desc.to_lowercase().contains(query) {\n return true;\n }\n }\n\n false\n}\n\nfn truncate_vis(s: &str, max: usize) -> String {\n if UnicodeWidthStr::width(s) <= max {\n return s.to_string();\n }\n let mut w = 0;\n let mut out = String::new();\n let effective_max = if max > 0 { max } else { 1 };\n\n for ch in s.chars() {\n let cw = UnicodeWidthChar::width(ch).unwrap_or(0);\n if w + cw >= effective_max.saturating_sub(1) {\n break;\n }\n out.push(ch);\n w += cw;\n }\n out.push('…');\n out\n}\n\npub fn print_search_results(query: &str, formula_matches: &[Value], cask_matches: &[Value]) {\n let total = formula_matches.len() + cask_matches.len();\n if total == 0 {\n println!(\"{}\", format!(\"No matches found for '{query}'\").yellow());\n return;\n }\n println!(\n \"{}\",\n format!(\"Found {total} result(s) for '{query}'\").bold()\n );\n\n let term_cols = terminal_size()\n .map(|(Width(w), _)| w as usize)\n .unwrap_or(120);\n\n let type_col = 7;\n let version_col = 10;\n let sep_width = 3 * 3;\n let total_fixed = type_col + version_col + sep_width;\n\n let name_min_width = 10;\n let desc_min_width = 20;\n\n let leftover = term_cols.saturating_sub(total_fixed);\n\n let name_prop_width = leftover / 3;\n\n let name_max = std::cmp::max(name_min_width, name_prop_width);\n let desc_max = std::cmp::max(desc_min_width, leftover.saturating_sub(name_max));\n\n let name_max = std::cmp::min(name_max, leftover.saturating_sub(desc_min_width));\n let desc_max = std::cmp::min(desc_max, leftover.saturating_sub(name_max));\n\n let mut tbl = Table::new();\n tbl.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n\n for formula in formula_matches {\n let raw_name = formula\n .get(\"name\")\n .and_then(|n| n.as_str())\n .unwrap_or(\"Unknown\");\n let raw_desc = formula.get(\"desc\").and_then(|d| d.as_str()).unwrap_or(\"\");\n let _name = truncate_vis(raw_name, name_max);\n let desc = truncate_vis(raw_desc, desc_max);\n\n let version = get_version(formula);\n\n tbl.add_row(Row::new(vec![\n Cell::new(\"Formula\").style_spec(\"Fg\"),\n Cell::new(&_name).style_spec(\"Fb\"),\n Cell::new(version),\n Cell::new(&desc),\n ]));\n }\n\n if !formula_matches.is_empty() && !cask_matches.is_empty() {\n tbl.add_row(Row::new(vec![Cell::new(\" \").with_hspan(4)]));\n }\n\n for cask in cask_matches {\n let raw_name = cask\n .get(\"token\")\n .and_then(|t| t.as_str())\n .unwrap_or(\"Unknown\");\n let raw_desc = cask.get(\"desc\").and_then(|d| d.as_str()).unwrap_or(\"\");\n let desc = truncate_vis(raw_desc, desc_max);\n\n let version = get_cask_version(cask);\n\n tbl.add_row(Row::new(vec![\n Cell::new(\"Cask\").style_spec(\"Fy\"),\n Cell::new(raw_name).style_spec(\"Fb\"),\n Cell::new(version),\n Cell::new(&desc),\n ]));\n }\n\n tbl.printstd();\n}\n\nfn get_version(formula: &Value) -> &str {\n formula\n .get(\"versions\")\n .and_then(|v| v.get(\"stable\"))\n .and_then(|v| v.as_str())\n .unwrap_or(\"-\")\n}\n\nfn get_cask_version(cask: &Value) -> &str {\n cask.get(\"version\").and_then(|v| v.as_str()).unwrap_or(\"-\")\n}\n"], ["/sps/sps-core/src/install/bottle/mod.rs", "// ===== sps-core/src/build/formula/mod.rs =====\nuse std::fs::File;\nuse std::io::Write;\nuse std::path::{Path, PathBuf};\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::formula::Formula;\nuse tracing::{debug, error};\n\n// Declare submodules\npub mod exec;\npub mod link;\npub mod macho;\n\n/// Download formula resources from the internet asynchronously.\npub async fn download_formula(\n formula: &Formula,\n config: &Config,\n client: &reqwest::Client,\n) -> Result {\n if has_bottle_for_current_platform(formula) {\n exec::download_bottle(formula, config, client).await\n } else {\n Err(SpsError::Generic(format!(\n \"No bottle available for {} on this platform\",\n formula.name()\n )))\n }\n}\n\n/// Checks if a suitable bottle exists for the current platform, considering fallbacks.\npub fn has_bottle_for_current_platform(formula: &Formula) -> bool {\n let result = crate::install::bottle::exec::get_bottle_for_platform(formula);\n debug!(\n \"has_bottle_for_current_platform check for '{}': {:?}\",\n formula.name(),\n result.is_ok()\n );\n if let Err(e) = &result {\n debug!(\"Reason for no bottle: {}\", e);\n }\n result.is_ok()\n}\n\n// *** Updated get_current_platform function ***\nfn get_current_platform() -> String {\n if cfg!(target_os = \"macos\") {\n let arch = if std::env::consts::ARCH == \"aarch64\" {\n \"arm64\"\n } else if std::env::consts::ARCH == \"x86_64\" {\n \"x86_64\"\n } else {\n std::env::consts::ARCH\n };\n\n debug!(\"Attempting to determine macOS version using /usr/bin/sw_vers -productVersion\");\n match Command::new(\"/usr/bin/sw_vers\")\n .arg(\"-productVersion\")\n .output()\n {\n Ok(output) => {\n let stdout = String::from_utf8_lossy(&output.stdout);\n let stderr = String::from_utf8_lossy(&output.stderr);\n debug!(\"sw_vers status: {}\", output.status);\n if !output.status.success() || !stderr.trim().is_empty() {\n debug!(\"sw_vers stdout:\\n{}\", stdout);\n if !stderr.trim().is_empty() {\n debug!(\"sw_vers stderr:\\n{}\", stderr);\n }\n }\n\n if output.status.success() {\n let version_str = stdout.trim();\n if !version_str.is_empty() {\n debug!(\"Extracted version string: {}\", version_str);\n let os_name = match version_str.split('.').next() {\n Some(\"15\") => \"sequoia\",\n Some(\"14\") => \"sonoma\",\n Some(\"13\") => \"ventura\",\n Some(\"12\") => \"monterey\",\n Some(\"11\") => \"big_sur\",\n Some(\"10\") => match version_str.split('.').nth(1) {\n Some(\"15\") => \"catalina\",\n Some(\"14\") => \"mojave\",\n _ => {\n debug!(\n \"Unrecognized legacy macOS 10.x version: {}\",\n version_str\n );\n \"unknown_macos\"\n }\n },\n _ => {\n debug!(\"Unrecognized macOS major version: {}\", version_str);\n \"unknown_macos\"\n }\n };\n\n if os_name != \"unknown_macos\" {\n let platform_tag = if arch == \"arm64\" {\n format!(\"{arch}_{os_name}\")\n } else {\n os_name.to_string()\n };\n debug!(\"Determined platform tag: {}\", platform_tag);\n return platform_tag;\n }\n } else {\n error!(\"sw_vers -productVersion output was empty.\");\n }\n } else {\n error!(\n \"sw_vers -productVersion command failed with status: {}. Stderr: {}\",\n output.status,\n stderr.trim()\n );\n }\n }\n Err(e) => {\n error!(\"Failed to execute /usr/bin/sw_vers -productVersion: {}\", e);\n }\n }\n\n error!(\"!!! FAILED TO DETECT MACOS VERSION VIA SW_VERS !!!\");\n debug!(\"Using UNRELIABLE fallback platform detection. Bottle selection may be incorrect.\");\n if arch == \"arm64\" {\n debug!(\"Falling back to platform tag: arm64_monterey\");\n \"arm64_monterey\".to_string()\n } else {\n debug!(\"Falling back to platform tag: monterey\");\n \"monterey\".to_string()\n }\n } else if cfg!(target_os = \"linux\") {\n if std::env::consts::ARCH == \"aarch64\" {\n \"arm64_linux\".to_string()\n } else if std::env::consts::ARCH == \"x86_64\" {\n \"x86_64_linux\".to_string()\n } else {\n \"unknown\".to_string()\n }\n } else {\n debug!(\n \"Could not determine platform tag for OS: {}\",\n std::env::consts::OS\n );\n \"unknown\".to_string()\n }\n}\n\n// REMOVED: get_cellar_path (now in Config)\n\n// --- get_formula_cellar_path uses Config ---\n// Parameter changed from formula: &Formula to formula_name: &str\n// Parameter changed from config: &Config to cellar_path: &Path for consistency where Config isn't\n// fully available If Config *is* available, call config.formula_cellar_dir(formula.name()) instead.\n// **Keeping original signature for now where Config might not be easily passed**\npub fn get_formula_cellar_path(formula: &Formula, config: &Config) -> PathBuf {\n // Use Config method\n config.formula_cellar_dir(formula.name())\n}\n\n// --- write_receipt (unchanged) ---\npub fn write_receipt(\n formula: &Formula,\n install_dir: &Path,\n installation_type: &str, // \"bottle\" or \"source\"\n) -> Result<()> {\n let receipt_path = install_dir.join(\"INSTALL_RECEIPT.json\");\n let receipt_file = File::create(&receipt_path);\n let mut receipt_file = match receipt_file {\n Ok(file) => file,\n Err(e) => {\n error!(\n \"Failed to create receipt file at {}: {}\",\n receipt_path.display(),\n e\n );\n return Err(SpsError::Io(std::sync::Arc::new(e)));\n }\n };\n\n let resources_result = formula.resources();\n let resources_installed = match resources_result {\n Ok(res) => res.iter().map(|r| r.name.clone()).collect::>(),\n Err(_) => {\n debug!(\n \"Could not retrieve resources for formula {} when writing receipt.\",\n formula.name\n );\n vec![]\n }\n };\n\n let timestamp = chrono::Utc::now().to_rfc3339();\n\n let receipt = serde_json::json!({\n \"name\": formula.name, \"version\": formula.version_str_full(), \"time\": timestamp,\n \"source\": { \"type\": \"api\", \"url\": formula.url, },\n \"built_on\": {\n \"os\": std::env::consts::OS, \"arch\": std::env::consts::ARCH,\n \"platform_tag\": get_current_platform(),\n },\n \"installation_type\": installation_type,\n \"resources_installed\": resources_installed,\n });\n\n let receipt_json = match serde_json::to_string_pretty(&receipt) {\n Ok(json) => json,\n Err(e) => {\n error!(\n \"Failed to serialize receipt JSON for {}: {}\",\n formula.name, e\n );\n return Err(SpsError::Json(std::sync::Arc::new(e)));\n }\n };\n\n if let Err(e) = receipt_file.write_all(receipt_json.as_bytes()) {\n error!(\"Failed to write receipt file for {}: {}\", formula.name, e);\n return Err(SpsError::Io(std::sync::Arc::new(e)));\n }\n\n Ok(())\n}\n\n// --- Re-exports (unchanged) ---\npub use exec::install_bottle;\npub use link::link_formula_artifacts;\n"], ["/sps/sps-core/src/install/bottle/macho.rs", "// sps-core/src/build/formula/macho.rs\n// Contains Mach-O specific patching logic for bottle relocation.\n// Updated to use MachOFatFile32 and MachOFatFile64 for FAT binary parsing.\n// Refactored to separate immutable analysis from mutable patching to fix borrow checker errors.\n\nuse std::collections::HashMap;\nuse std::fs;\nuse std::io::Write; // Keep for write_patched_buffer\nuse std::path::Path;\nuse std::process::{Command as StdCommand, Stdio}; // Keep for codesign\n\n// --- Imports needed for Mach-O patching (macOS only) ---\n#[cfg(target_os = \"macos\")]\nuse object::{\n self,\n macho::{MachHeader32, MachHeader64}, // Keep for Mach-O parsing\n read::macho::{\n FatArch,\n LoadCommandVariant, // Correct import path\n MachHeader,\n MachOFatFile32,\n MachOFatFile64, // Core Mach-O types + FAT types\n MachOFile,\n },\n Endianness,\n FileKind,\n ReadRef,\n};\nuse sps_common::error::{Result, SpsError};\nuse tempfile::NamedTempFile;\nuse tracing::{debug, error};\n\n// --- Platform‑specific constants for Mach‑O magic detection ---\n#[cfg(target_os = \"macos\")]\nconst MH_MAGIC: u32 = 0xfeedface;\n#[cfg(target_os = \"macos\")]\nconst MH_MAGIC_64: u32 = 0xfeedfacf;\n#[cfg(target_os = \"macos\")]\nconst MACHO_HEADER32_SIZE: usize = 28;\n#[cfg(target_os = \"macos\")]\nconst MACHO_HEADER64_SIZE: usize = 32;\n\n/// Core patch data for **one** string replacement location inside a Mach‑O file.\n#[cfg(target_os = \"macos\")]\n#[derive(Debug, Clone)]\nstruct PatchInfo {\n absolute_offset: usize, // Offset in the entire file buffer\n allocated_len: usize, // How much space was allocated for this string\n new_path: String, // The new string to write\n}\n\n/// Container for paths that couldn't be patched due to length constraints\n#[cfg(target_os = \"macos\")]\n#[derive(Debug, Clone)]\npub struct SkippedPath {\n pub old_path: String,\n pub new_path: String,\n}\n\n/// Main entry point for Mach‑O path patching (macOS only).\n/// Returns `Ok(true)` if patches were applied, `Ok(false)` if no patches needed.\n/// Returns a tuple: (patched: bool, skipped_paths: Vec)\n#[cfg(target_os = \"macos\")]\npub fn patch_macho_file(\n path: &Path,\n replacements: &HashMap,\n) -> Result<(bool, Vec)> {\n patch_macho_file_macos(path, replacements)\n}\n\n/// Container for paths that couldn't be patched due to length constraints\n#[cfg(not(target_os = \"macos\"))]\n#[derive(Debug, Clone)]\npub struct SkippedPath {\n pub old_path: String,\n pub new_path: String,\n}\n\n/// No‑op stub for non‑macOS platforms.\n#[cfg(not(target_os = \"macos\"))]\npub fn patch_macho_file(\n _path: &Path,\n _replacements: &HashMap,\n) -> Result<(bool, Vec)> {\n Ok((false, Vec::new()))\n}\n\n/// **macOS implementation**: Tries to patch Mach‑O files by replacing placeholders.\n#[cfg(target_os = \"macos\")]\nfn patch_macho_file_macos(\n path: &Path,\n replacements: &HashMap,\n) -> Result<(bool, Vec)> {\n debug!(\"Processing potential Mach-O file: {}\", path.display());\n\n // 1) Load the entire file into memory\n let buffer = match fs::read(path) {\n Ok(data) => data,\n Err(e) => {\n debug!(\"Failed to read {}: {}\", path.display(), e);\n return Ok((false, Vec::new()));\n }\n };\n if buffer.is_empty() {\n debug!(\"Empty file: {}\", path.display());\n return Ok((false, Vec::new()));\n }\n\n // 2) Identify the file type\n let kind = match object::FileKind::parse(&*buffer) {\n Ok(k) => k,\n Err(_e) => {\n debug!(\"Not an object file: {}\", path.display());\n return Ok((false, Vec::new()));\n }\n };\n\n // 3) **Analysis phase**: collect patches + skipped paths\n let (patches, skipped_paths) = collect_macho_patches(&buffer, kind, replacements, path)?;\n\n if patches.is_empty() {\n if skipped_paths.is_empty() {\n debug!(\"No patches needed for {}\", path.display());\n } else {\n debug!(\n \"No patches applied for {} ({} paths skipped due to length)\",\n path.display(),\n skipped_paths.len()\n );\n }\n return Ok((false, skipped_paths));\n }\n\n // 4) Clone buffer and apply all patches atomically\n let mut patched_buffer = buffer;\n for patch in &patches {\n patch_path_in_buffer(\n &mut patched_buffer,\n patch.absolute_offset,\n patch.allocated_len,\n &patch.new_path,\n path,\n )?;\n }\n\n // 5) Write atomically\n write_patched_buffer(path, &patched_buffer)?;\n debug!(\"Wrote patched Mach-O: {}\", path.display());\n\n // 6) Re‑sign on Apple Silicon\n #[cfg(target_arch = \"aarch64\")]\n {\n resign_binary(path)?;\n debug!(\"Re‑signed patched binary: {}\", path.display());\n }\n\n Ok((true, skipped_paths))\n}\n\n/// ASCII magic for the start of a static `ar` archive (`!\\n`)\n#[cfg(target_os = \"macos\")]\nconst AR_MAGIC: &[u8; 8] = b\"!\\n\";\n\n/// Examine a buffer (Mach‑O or FAT) and return every patch we must apply + skipped paths.\n#[cfg(target_os = \"macos\")]\nfn collect_macho_patches(\n buffer: &[u8],\n kind: FileKind,\n replacements: &HashMap,\n path_for_log: &Path,\n) -> Result<(Vec, Vec)> {\n let mut patches = Vec::::new();\n let mut skipped_paths = Vec::::new();\n\n match kind {\n /* ---------------------------------------------------------- */\n FileKind::MachO32 => {\n let m = MachOFile::, _>::parse(buffer)?;\n let (mut p, mut s) =\n find_patches_in_commands(&m, 0, MACHO_HEADER32_SIZE, replacements, path_for_log)?;\n patches.append(&mut p);\n skipped_paths.append(&mut s);\n }\n /* ---------------------------------------------------------- */\n FileKind::MachO64 => {\n let m = MachOFile::, _>::parse(buffer)?;\n let (mut p, mut s) =\n find_patches_in_commands(&m, 0, MACHO_HEADER64_SIZE, replacements, path_for_log)?;\n patches.append(&mut p);\n skipped_paths.append(&mut s);\n }\n /* ---------------------------------------------------------- */\n FileKind::MachOFat32 => {\n let fat = MachOFatFile32::parse(buffer)?;\n for (idx, arch) in fat.arches().iter().enumerate() {\n let (off, sz) = arch.file_range();\n let slice = &buffer[off as usize..(off + sz) as usize];\n\n /* short‑circuit: static .a archive inside FAT ---------- */\n if slice.starts_with(AR_MAGIC) {\n debug!(\"[slice {}] static archive – skipped\", idx);\n continue;\n }\n\n /* decide 32 / 64 by magic ------------------------------ */\n if slice.len() >= 4 {\n let magic = u32::from_le_bytes(slice[0..4].try_into().unwrap());\n if magic == MH_MAGIC_64 {\n if let Ok(m) = MachOFile::, _>::parse(slice) {\n let (mut p, mut s) = find_patches_in_commands(\n &m,\n off as usize,\n MACHO_HEADER64_SIZE,\n replacements,\n path_for_log,\n )?;\n patches.append(&mut p);\n skipped_paths.append(&mut s);\n }\n } else if magic == MH_MAGIC {\n if let Ok(m) = MachOFile::, _>::parse(slice) {\n let (mut p, mut s) = find_patches_in_commands(\n &m,\n off as usize,\n MACHO_HEADER32_SIZE,\n replacements,\n path_for_log,\n )?;\n patches.append(&mut p);\n skipped_paths.append(&mut s);\n }\n }\n }\n }\n }\n /* ---------------------------------------------------------- */\n FileKind::MachOFat64 => {\n let fat = MachOFatFile64::parse(buffer)?;\n for (idx, arch) in fat.arches().iter().enumerate() {\n let (off, sz) = arch.file_range();\n let slice = &buffer[off as usize..(off + sz) as usize];\n\n if slice.starts_with(AR_MAGIC) {\n debug!(\"[slice {}] static archive – skipped\", idx);\n continue;\n }\n\n if slice.len() >= 4 {\n let magic = u32::from_le_bytes(slice[0..4].try_into().unwrap());\n if magic == MH_MAGIC_64 {\n if let Ok(m) = MachOFile::, _>::parse(slice) {\n let (mut p, mut s) = find_patches_in_commands(\n &m,\n off as usize,\n MACHO_HEADER64_SIZE,\n replacements,\n path_for_log,\n )?;\n patches.append(&mut p);\n skipped_paths.append(&mut s);\n }\n } else if magic == MH_MAGIC {\n if let Ok(m) = MachOFile::, _>::parse(slice) {\n let (mut p, mut s) = find_patches_in_commands(\n &m,\n off as usize,\n MACHO_HEADER32_SIZE,\n replacements,\n path_for_log,\n )?;\n patches.append(&mut p);\n skipped_paths.append(&mut s);\n }\n }\n }\n }\n }\n /* ---------------------------------------------------------- */\n _ => { /* archives & unknown kinds are ignored */ }\n }\n\n Ok((patches, skipped_paths))\n}\n\n/// Iterates through load commands of a parsed MachOFile (slice) and returns\n/// patch details + skipped paths.\n#[cfg(target_os = \"macos\")]\nfn find_patches_in_commands<'data, Mach, R>(\n macho_file: &MachOFile<'data, Mach, R>,\n slice_base_offset: usize,\n header_size: usize,\n replacements: &HashMap,\n file_path_for_log: &Path,\n) -> Result<(Vec, Vec)>\nwhere\n Mach: MachHeader,\n R: ReadRef<'data>,\n{\n let endian = macho_file.endian();\n let mut patches = Vec::new();\n let mut skipped_paths = Vec::new();\n let mut cur_off = header_size;\n\n let mut it = macho_file.macho_load_commands()?;\n while let Some(cmd) = it.next()? {\n let cmd_size = cmd.cmdsize() as usize;\n let cmd_offset = cur_off; // offset *inside this slice*\n cur_off += cmd_size;\n\n let variant = match cmd.variant() {\n Ok(v) => v,\n Err(e) => {\n tracing::warn!(\n \"Malformed load‑command in {}: {}; skipping\",\n file_path_for_log.display(),\n e\n );\n continue;\n }\n };\n\n // — which commands carry path strings we might want? —\n let path_info: Option<(u32, &[u8])> = match variant {\n LoadCommandVariant::Dylib(d) | LoadCommandVariant::IdDylib(d) => cmd\n .string(endian, d.dylib.name)\n .ok()\n .map(|bytes| (d.dylib.name.offset.get(endian), bytes)),\n LoadCommandVariant::Rpath(r) => cmd\n .string(endian, r.path)\n .ok()\n .map(|bytes| (r.path.offset.get(endian), bytes)),\n _ => None,\n };\n\n if let Some((offset_in_cmd, bytes)) = path_info {\n if let Ok(old_path) = std::str::from_utf8(bytes) {\n if let Some(new_path) = find_and_replace_placeholders(old_path, replacements) {\n let allocated = cmd_size.saturating_sub(offset_in_cmd as usize);\n\n if new_path.len() + 1 > allocated {\n // would overflow – add to skipped paths instead of throwing\n tracing::debug!(\n \"Skip patch (too long): '{}' → '{}' (alloc {} B) in {}\",\n old_path,\n new_path,\n allocated,\n file_path_for_log.display()\n );\n skipped_paths.push(SkippedPath {\n old_path: old_path.to_string(),\n new_path: new_path.clone(),\n });\n continue;\n }\n\n patches.push(PatchInfo {\n absolute_offset: slice_base_offset + cmd_offset + offset_in_cmd as usize,\n allocated_len: allocated,\n new_path,\n });\n }\n }\n }\n }\n Ok((patches, skipped_paths))\n}\n\n/// Helper to replace placeholders in a string based on the replacements map.\n/// Returns `Some(String)` with replacements if any were made, `None` otherwise.\nfn find_and_replace_placeholders(\n current_path: &str,\n replacements: &HashMap,\n) -> Option {\n let mut new_path = current_path.to_string();\n let mut path_modified = false;\n // Iterate through all placeholder/replacement pairs\n for (placeholder, replacement) in replacements {\n // Check if the current path string contains the placeholder\n if new_path.contains(placeholder) {\n // Replace all occurrences of the placeholder\n new_path = new_path.replace(placeholder, replacement);\n path_modified = true; // Mark that a change was made\n debug!(\n \" Replaced '{}' with '{}' -> '{}'\",\n placeholder, replacement, new_path\n );\n }\n }\n // Return the modified string only if changes occurred\n if path_modified {\n Some(new_path)\n } else {\n None\n }\n}\n\n/// Write a new (null‑padded) path into the mutable buffer. \n/// Assumes the caller already verified the length.\n#[cfg(target_os = \"macos\")]\nfn patch_path_in_buffer(\n buf: &mut [u8],\n abs_off: usize,\n alloc_len: usize,\n new_path: &str,\n file: &Path,\n) -> Result<()> {\n if new_path.len() + 1 > alloc_len || abs_off + alloc_len > buf.len() {\n // should never happen – just log & skip\n tracing::debug!(\n \"Patch skipped (bounds) at {} in {}\",\n abs_off,\n file.display()\n );\n return Ok(());\n }\n\n // null‑padded copy\n buf[abs_off..abs_off + new_path.len()].copy_from_slice(new_path.as_bytes());\n buf[abs_off + new_path.len()..abs_off + alloc_len].fill(0);\n\n Ok(())\n}\n\n/// Writes the patched buffer to the original path atomically using a temporary file.\n#[cfg(target_os = \"macos\")]\nfn write_patched_buffer(original_path: &Path, buffer: &[u8]) -> Result<()> {\n // Get the directory containing the original file\n let dir = original_path.parent().ok_or_else(|| {\n SpsError::Generic(format!(\n \"Cannot get parent directory for {}\",\n original_path.display()\n ))\n })?;\n // Ensure the directory exists\n fs::create_dir_all(dir).map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n\n // Create a named temporary file in the same directory to facilitate atomic rename\n let mut temp_file = NamedTempFile::new_in(dir)?;\n debug!(\n \" Writing patched buffer ({} bytes) to temporary file: {:?}\",\n buffer.len(),\n temp_file.path()\n );\n // Write the entire modified buffer to the temporary file\n temp_file.write_all(buffer)?;\n // Ensure data is flushed to the OS buffer\n temp_file.flush()?;\n // Attempt to sync data to the disk\n temp_file.as_file().sync_all()?; // Ensure data is physically written\n\n // Atomically replace the original file with the temporary file\n // persist() renames the temp file over the original path.\n temp_file.persist(original_path).map_err(|e| {\n // If persist fails, the temporary file might still exist.\n // The error 'e' contains both the temp file and the underlying IO error.\n error!(\n \" Failed to persist/rename temporary file over {}: {}\",\n original_path.display(),\n e.error // Log the underlying IO error\n );\n // Return the IO error wrapped in our error type\n SpsError::Io(std::sync::Arc::new(e.error))\n })?;\n debug!(\n \" Atomically replaced {} with patched version\",\n original_path.display()\n );\n Ok(())\n}\n\n/// Re-signs the binary using the `codesign` command-line tool.\n/// This is typically necessary on Apple Silicon (aarch64) after modifying executables.\n#[cfg(all(target_os = \"macos\", target_arch = \"aarch64\"))]\nfn resign_binary(path: &Path) -> Result<()> {\n // Suppressed: debug!(\"Re-signing patched binary: {}\", path.display());\n let status = StdCommand::new(\"codesign\")\n .args([\n \"-s\",\n \"-\",\n \"--force\",\n \"--preserve-metadata=identifier,entitlements\",\n ])\n .arg(path)\n .stdout(Stdio::null())\n .stderr(Stdio::null())\n .status() // Execute the command and get its exit status\n .map_err(|e| {\n error!(\n \" Failed to execute codesign command for {}: {}\",\n path.display(),\n e\n );\n SpsError::Io(std::sync::Arc::new(e))\n })?;\n if status.success() {\n // Suppressed: debug!(\"Successfully re-signed {}\", path.display());\n Ok(())\n } else {\n error!(\n \" codesign command failed for {} with status: {}\",\n path.display(),\n status\n );\n Err(SpsError::CodesignError(format!(\n \"Failed to re-sign patched binary {}, it may not be executable. Exit status: {}\",\n path.display(),\n status\n )))\n }\n}\n\n// No-op stub for resigning on non-Apple Silicon macOS (e.g., x86_64)\n#[cfg(all(target_os = \"macos\", not(target_arch = \"aarch64\")))]\nfn resign_binary(_path: &Path) -> Result<()> {\n // No re-signing typically needed on Intel Macs after ad-hoc patching\n Ok(())\n}\n\n// No-op stub for resigning Innovations on non-macOS platforms\n#[cfg(not(target_os = \"macos\"))]\nfn resign_binary(_path: &Path) -> Result<()> {\n // Resigning is a macOS concept\n Ok(())\n}\n"], ["/sps/sps/src/cli/init.rs", "// sps/src/cli/init.rs\nuse std::fs::{self, File, OpenOptions};\nuse std::io::{BufRead, BufReader, Write};\nuse std::path::{Path, PathBuf};\nuse std::process::Command as StdCommand;\nuse std::sync::Arc;\n\nuse clap::Args;\nuse colored::Colorize;\nuse sps_common::config::Config; // Assuming Config is correctly in sps_common\nuse sps_common::error::{Result as SpsResult, SpsError};\nuse tempfile;\nuse tracing::{debug, error, warn};\n\n#[derive(Args, Debug)]\npub struct InitArgs {\n /// Force initialization even if /opt/sps appears to be an sps root already.\n #[arg(long)]\n pub force: bool,\n}\n\nimpl InitArgs {\n pub async fn run(&self, config: &Config) -> SpsResult<()> {\n debug!(\n \"Initializing sps environment at {}\",\n config.sps_root().display()\n );\n\n let sps_root = config.sps_root();\n let marker_path = config.sps_root_marker_path();\n\n // 1. Initial Checks (as current user) - (No change from your existing logic)\n if sps_root.exists() {\n let is_empty = match fs::read_dir(sps_root) {\n Ok(mut entries) => entries.next().is_none(),\n Err(_) => false, // If we can't read it, assume not empty or not accessible\n };\n\n if marker_path.exists() && !self.force {\n debug!(\n \"{} already exists. sps appears to be initialized. Use --force to re-initialize.\",\n marker_path.display()\n );\n return Ok(());\n }\n if !self.force && !is_empty && !marker_path.exists() {\n warn!(\n \"Directory {} exists but does not appear to be an sps root (missing marker {}).\",\n sps_root.display(),\n marker_path.file_name().unwrap_or_default().to_string_lossy()\n );\n warn!(\n \"Run with --force to initialize anyway (this might overwrite existing data or change permissions).\"\n );\n return Err(SpsError::Config(format!(\n \"{} exists but is not a recognized sps root. Aborting.\",\n sps_root.display()\n )));\n }\n if self.force {\n debug!(\n \"--force specified. Proceeding with initialization in {}.\",\n sps_root.display()\n );\n } else if is_empty {\n debug!(\n \"Directory {} exists but is empty. Proceeding with initialization.\",\n sps_root.display()\n );\n }\n }\n\n // 2. Privileged Operations\n let current_user_name = std::env::var(\"USER\")\n .or_else(|_| std::env::var(\"LOGNAME\"))\n .map_err(|_| {\n SpsError::Generic(\n \"Failed to get current username from USER or LOGNAME environment variables.\"\n .to_string(),\n )\n })?;\n\n let target_group_name = if cfg!(target_os = \"macos\") {\n \"admin\" // Standard admin group on macOS\n } else {\n // For Linux, 'staff' might not exist or be appropriate.\n // Often, the user's primary group is used, or a dedicated 'brew' group.\n // For simplicity, let's try to use the current user's name as the group too,\n // which works if the user has a group with the same name.\n // A more robust Linux solution might involve checking for 'staff' or other common\n // groups.\n ¤t_user_name\n };\n\n debug!(\n \"Will attempt to set ownership of sps-managed directories under {} to {}:{}\",\n sps_root.display(),\n current_user_name,\n target_group_name\n );\n\n println!(\n \"{}\",\n format!(\n \"sps may require sudo to create directories and set permissions in {}.\",\n sps_root.display()\n )\n .yellow()\n );\n\n // Define directories sps needs to ensure exist and can manage.\n // These are derived from your Config struct.\n let dirs_to_create_and_manage: Vec = vec![\n config.sps_root().to_path_buf(), // The root itself\n config.bin_dir(),\n config.cellar_dir(),\n config.cask_room_dir(),\n config.cask_store_dir(), // sps-specific\n config.opt_dir(),\n config.taps_dir(), // This is now sps_root/Library/Taps\n config.cache_dir(), // sps-specific (e.g., sps_root/sps_cache)\n config.logs_dir(), // sps-specific (e.g., sps_root/sps_logs)\n config.tmp_dir(),\n config.state_dir(),\n config\n .man_base_dir()\n .parent()\n .unwrap_or(sps_root)\n .to_path_buf(), // share\n config.man_base_dir(), // share/man\n config.sps_root().join(\"etc\"),\n config.sps_root().join(\"include\"),\n config.sps_root().join(\"lib\"),\n config.sps_root().join(\"share/doc\"),\n ];\n\n // Create directories with mkdir -p (non-destructive)\n for dir_path in &dirs_to_create_and_manage {\n // Only create if it doesn't exist to avoid unnecessary sudo calls if already present\n if !dir_path.exists() {\n debug!(\n \"Ensuring directory exists with sudo: {}\",\n dir_path.display()\n );\n run_sudo_command(\"mkdir\", &[\"-p\", &dir_path.to_string_lossy()])?;\n } else {\n debug!(\n \"Directory already exists, skipping mkdir: {}\",\n dir_path.display()\n );\n }\n }\n\n // Create the marker file (non-destructive to other content)\n debug!(\n \"Creating/updating marker file with sudo: {}\",\n marker_path.display()\n );\n let marker_content = \"sps root directory version 1\";\n // Using a temporary file for sudo tee to avoid permission issues with direct pipe\n let temp_marker_file =\n tempfile::NamedTempFile::new().map_err(|e| SpsError::Io(Arc::new(e)))?;\n fs::write(temp_marker_file.path(), marker_content)\n .map_err(|e| SpsError::Io(Arc::new(e)))?;\n run_sudo_command(\n \"cp\",\n &[\n temp_marker_file.path().to_str().unwrap(),\n marker_path.to_str().unwrap(),\n ],\n )?;\n\n #[cfg(unix)]\n {\n // More targeted chown and chmod\n debug!(\n \"Setting ownership and permissions for sps-managed directories under {}...\",\n sps_root.display()\n );\n\n // Chown/Chmod the top-level sps_root directory itself (non-recursively for chmod\n // initially) This is important if sps_root is /opt/sps and was just created\n // by root. If sps_root is /opt/homebrew, this ensures the current user can\n // at least manage it.\n run_sudo_command(\n \"chown\",\n &[\n &format!(\"{current_user_name}:{target_group_name}\"),\n &sps_root.to_string_lossy(),\n ],\n )?;\n run_sudo_command(\"chmod\", &[\"ug=rwx,o=rx\", &sps_root.to_string_lossy()])?; // 755 for the root\n\n // For specific subdirectories that sps actively manages and writes into frequently,\n // ensure they are owned by the user and have appropriate permissions.\n // We apply this recursively to sps-specific dirs and key shared dirs.\n let dirs_for_recursive_chown_chmod: Vec = vec![\n config.cellar_dir(),\n config.cask_room_dir(),\n config.cask_store_dir(), // sps-specific, definitely needs full user control\n config.opt_dir(),\n config.taps_dir(),\n config.cache_dir(), // sps-specific\n config.logs_dir(), // sps-specific\n config.tmp_dir(),\n config.state_dir(),\n // bin, lib, include, share, etc are often symlink farms.\n // The top-level of these should be writable by the user to create symlinks.\n // The actual kegs in Cellar will have their own permissions.\n config.bin_dir(),\n config.sps_root().join(\"lib\"),\n config.sps_root().join(\"include\"),\n config.sps_root().join(\"share\"),\n config.sps_root().join(\"etc\"),\n ];\n\n for dir_path in dirs_for_recursive_chown_chmod {\n if dir_path.exists() {\n // Only operate on existing directories\n debug!(\"Setting ownership (recursive) for: {}\", dir_path.display());\n run_sudo_command(\n \"chown\",\n &[\n \"-R\",\n &format!(\"{current_user_name}:{target_group_name}\"),\n &dir_path.to_string_lossy(),\n ],\n )?;\n\n debug!(\n \"Setting permissions (recursive ug=rwX,o=rX) for: {}\",\n dir_path.display()\n );\n run_sudo_command(\"chmod\", &[\"-R\", \"ug=rwX,o=rX\", &dir_path.to_string_lossy()])?;\n } else {\n warn!(\n \"Directory {} was expected but not found for chown/chmod. Marker: {}\",\n dir_path.display(),\n marker_path.display()\n );\n }\n }\n\n // Ensure bin is executable by all\n if config.bin_dir().exists() {\n debug!(\n \"Ensuring execute permissions for bin_dir: {}\",\n config.bin_dir().display()\n );\n run_sudo_command(\"chmod\", &[\"a+x\", &config.bin_dir().to_string_lossy()])?;\n // Also ensure contents of bin (wrappers, symlinks) are executable if they weren't\n // caught by -R ug=rwX This might be redundant if -R ug=rwX\n // correctly sets X for existing executables, but explicit `chmod\n // a+x` on individual files might be needed if they are newly created by sps.\n // For now, relying on the recursive chmod and the a+x on the bin_dir itself.\n }\n\n // Debug listing (optional, can be verbose)\n if tracing::enabled!(tracing::Level::DEBUG) {\n debug!(\"Listing {} after permission changes:\", sps_root.display());\n let ls_output_root = StdCommand::new(\"ls\").arg(\"-ld\").arg(sps_root).output();\n if let Ok(out) = ls_output_root {\n debug!(\n \"ls -ld {}: \\nSTDOUT: {}\\nSTDERR: {}\",\n sps_root.display(),\n String::from_utf8_lossy(&out.stdout),\n String::from_utf8_lossy(&out.stderr)\n );\n }\n for dir_path in &dirs_to_create_and_manage {\n if dir_path.exists() && dir_path != sps_root {\n let ls_output_sub = StdCommand::new(\"ls\").arg(\"-ld\").arg(dir_path).output();\n if let Ok(out) = ls_output_sub {\n debug!(\n \"ls -ld {}: \\nSTDOUT: {}\\nSTDERR: {}\",\n dir_path.display(),\n String::from_utf8_lossy(&out.stdout),\n String::from_utf8_lossy(&out.stderr)\n );\n }\n }\n }\n }\n }\n\n // 3. User-Specific PATH Configuration (runs as the original user) - (No change from your\n // existing logic)\n if let Err(e) = configure_shell_path(config, ¤t_user_name) {\n warn!(\n \"Could not fully configure shell PATH: {}. Manual configuration might be needed.\",\n e\n );\n print_manual_path_instructions(&config.bin_dir().to_string_lossy());\n }\n\n debug!(\n \"{} {}\",\n \"Successfully initialized sps environment at\".green(),\n config.sps_root().display().to_string().green()\n );\n Ok(())\n }\n}\n\n// run_sudo_command helper (no change from your existing logic)\nfn run_sudo_command(command: &str, args: &[&str]) -> SpsResult<()> {\n debug!(\"Running sudo {} {:?}\", command, args);\n let output = StdCommand::new(\"sudo\")\n .arg(command)\n .args(args)\n .output()\n .map_err(|e| SpsError::Io(Arc::new(e)))?;\n\n if !output.status.success() {\n let stderr = String::from_utf8_lossy(&output.stderr);\n let stdout = String::from_utf8_lossy(&output.stdout);\n error!(\n \"sudo {} {:?} failed ({}):\\nStdout: {}\\nStderr: {}\",\n command,\n args,\n output.status,\n stdout.trim(),\n stderr.trim()\n );\n Err(SpsError::Generic(format!(\n \"Failed to execute `sudo {} {:?}`: {}\",\n command,\n args,\n stderr.trim()\n )))\n } else {\n Ok(())\n }\n}\n\n// configure_shell_path helper (no change from your existing logic)\nfn configure_shell_path(config: &Config, current_user_name_for_log: &str) -> SpsResult<()> {\n debug!(\"Attempting to configure your shell for sps PATH...\");\n\n let sps_bin_path_str = config.bin_dir().to_string_lossy().into_owned();\n let home_dir = config.home_dir();\n if home_dir == PathBuf::from(\"/\") && current_user_name_for_log != \"root\" {\n warn!(\n \"Could not reliably determine your home directory (got '/'). Please add {} to your PATH manually for user {}.\",\n sps_bin_path_str, current_user_name_for_log\n );\n print_manual_path_instructions(&sps_bin_path_str);\n return Ok(());\n }\n\n let shell_path_env = std::env::var(\"SHELL\").unwrap_or_else(|_| \"unknown\".to_string());\n let mut config_files_updated: Vec = Vec::new();\n let mut path_seems_configured = false;\n\n let sps_path_line_zsh_bash = format!(\"export PATH=\\\"{sps_bin_path_str}:$PATH\\\"\");\n let sps_path_line_fish = format!(\"fish_add_path -P \\\"{sps_bin_path_str}\\\"\");\n\n if shell_path_env.contains(\"zsh\") {\n let zshrc_path = home_dir.join(\".zshrc\");\n if update_shell_config(\n &zshrc_path,\n &sps_path_line_zsh_bash,\n &sps_bin_path_str,\n \"Zsh\",\n false,\n )? {\n config_files_updated.push(zshrc_path.display().to_string());\n } else if line_exists_in_file(&zshrc_path, &sps_bin_path_str)? {\n path_seems_configured = true;\n }\n } else if shell_path_env.contains(\"bash\") {\n let bashrc_path = home_dir.join(\".bashrc\");\n let bash_profile_path = home_dir.join(\".bash_profile\");\n let profile_path = home_dir.join(\".profile\");\n\n let mut bash_updated_by_sps = false;\n if update_shell_config(\n &bashrc_path,\n &sps_path_line_zsh_bash,\n &sps_bin_path_str,\n \"Bash (.bashrc)\",\n false,\n )? {\n config_files_updated.push(bashrc_path.display().to_string());\n bash_updated_by_sps = true;\n if bash_profile_path.exists() {\n ensure_profile_sources_rc(&bash_profile_path, &bashrc_path, \"Bash (.bash_profile)\");\n } else if profile_path.exists() {\n ensure_profile_sources_rc(&profile_path, &bashrc_path, \"Bash (.profile)\");\n } else {\n debug!(\"Neither .bash_profile nor .profile found. Creating .bash_profile to source .bashrc.\");\n ensure_profile_sources_rc(&bash_profile_path, &bashrc_path, \"Bash (.bash_profile)\");\n }\n } else if update_shell_config(\n &bash_profile_path,\n &sps_path_line_zsh_bash,\n &sps_bin_path_str,\n \"Bash (.bash_profile)\",\n false,\n )? {\n config_files_updated.push(bash_profile_path.display().to_string());\n bash_updated_by_sps = true;\n } else if update_shell_config(\n &profile_path,\n &sps_path_line_zsh_bash,\n &sps_bin_path_str,\n \"Bash (.profile)\",\n false,\n )? {\n config_files_updated.push(profile_path.display().to_string());\n bash_updated_by_sps = true;\n }\n\n if !bash_updated_by_sps\n && (line_exists_in_file(&bashrc_path, &sps_bin_path_str)?\n || line_exists_in_file(&bash_profile_path, &sps_bin_path_str)?\n || line_exists_in_file(&profile_path, &sps_bin_path_str)?)\n {\n path_seems_configured = true;\n }\n } else if shell_path_env.contains(\"fish\") {\n let fish_config_dir = home_dir.join(\".config/fish\");\n if !fish_config_dir.exists() {\n if let Err(e) = fs::create_dir_all(&fish_config_dir) {\n warn!(\n \"Could not create Fish config directory {}: {}\",\n fish_config_dir.display(),\n e\n );\n }\n }\n if fish_config_dir.exists() {\n let fish_config_path = fish_config_dir.join(\"config.fish\");\n if update_shell_config(\n &fish_config_path,\n &sps_path_line_fish,\n &sps_bin_path_str,\n \"Fish\",\n true,\n )? {\n config_files_updated.push(fish_config_path.display().to_string());\n } else if line_exists_in_file(&fish_config_path, &sps_bin_path_str)? {\n path_seems_configured = true;\n }\n }\n } else {\n warn!(\n \"Unsupported shell for automatic PATH configuration: {}. Please add {} to your PATH manually.\",\n shell_path_env, sps_bin_path_str\n );\n print_manual_path_instructions(&sps_bin_path_str);\n return Ok(());\n }\n\n if !config_files_updated.is_empty() {\n println!(\n \"{} {} has been added to your PATH by modifying: {}\",\n \"sps\".cyan(),\n sps_bin_path_str.cyan(),\n config_files_updated.join(\", \").white()\n );\n println!(\n \"{}\",\n \"Please open a new terminal session or source your shell configuration file for the changes to take effect.\"\n .yellow()\n );\n if shell_path_env.contains(\"zsh\") {\n println!(\" Run: {}\", \"source ~/.zshrc\".green());\n }\n if shell_path_env.contains(\"bash\") {\n println!(\n \" Run: {} (or {} or {})\",\n \"source ~/.bashrc\".green(),\n \"source ~/.bash_profile\".green(),\n \"source ~/.profile\".green()\n );\n }\n if shell_path_env.contains(\"fish\") {\n println!(\n \" Run (usually not needed for fish_add_path, but won't hurt): {}\",\n \"source ~/.config/fish/config.fish\".green()\n );\n }\n } else if path_seems_configured {\n debug!(\"sps path ({}) is likely already configured for your shell ({}). No configuration files were modified.\", sps_bin_path_str.cyan(), shell_path_env.yellow());\n } else if !shell_path_env.is_empty() && shell_path_env != \"unknown\" {\n warn!(\"Could not automatically update PATH for your shell: {}. Please add {} to your PATH manually.\", shell_path_env.yellow(), sps_bin_path_str.cyan());\n print_manual_path_instructions(&sps_bin_path_str);\n }\n Ok(())\n}\n\n// print_manual_path_instructions helper (no change from your existing logic)\nfn print_manual_path_instructions(sps_bin_path_str: &str) {\n println!(\"\\n{} To use sps commands and installed packages directly, please add the following line to your shell configuration file:\", \"Action Required:\".yellow().bold());\n println!(\" (e.g., ~/.zshrc, ~/.bashrc, ~/.config/fish/config.fish)\");\n println!(\"\\n For Zsh or Bash:\");\n println!(\n \" {}\",\n format!(\"export PATH=\\\"{sps_bin_path_str}:$PATH\\\"\").green()\n );\n println!(\"\\n For Fish shell:\");\n println!(\n \" {}\",\n format!(\"fish_add_path -P \\\"{sps_bin_path_str}\\\"\").green()\n );\n println!(\n \"\\nThen, open a new terminal or run: {}\",\n \"source \".green()\n );\n}\n\n// line_exists_in_file helper (no change from your existing logic)\nfn line_exists_in_file(file_path: &Path, sps_bin_path_str: &str) -> SpsResult {\n if !file_path.exists() {\n return Ok(false);\n }\n let file = File::open(file_path).map_err(|e| SpsError::Io(Arc::new(e)))?;\n let reader = BufReader::new(file);\n let escaped_sps_bin_path = regex::escape(sps_bin_path_str);\n // Regex to find lines that configure PATH, trying to be robust for different shells\n // It looks for lines that set PATH or fish_user_paths and include the sps_bin_path_str\n // while trying to avoid commented out lines.\n let pattern = format!(\n r#\"(?m)^\\s*[^#]*\\b(?:PATH\\s*=|export\\s+PATH\\s*=|set\\s*(?:-gx\\s*|-U\\s*)?\\s*fish_user_paths\\b|fish_add_path\\s*(?:-P\\s*|-p\\s*)?)?[\"']?.*{escaped_sps_bin_path}.*[\"']?\"#\n );\n let search_pattern_regex = regex::Regex::new(&pattern)\n .map_err(|e| SpsError::Generic(format!(\"Failed to compile regex for PATH check: {e}\")))?;\n\n for line_result in reader.lines() {\n let line = line_result.map_err(|e| SpsError::Io(Arc::new(e)))?;\n if search_pattern_regex.is_match(&line) {\n debug!(\n \"Found sps PATH ({}) in {}: {}\",\n sps_bin_path_str,\n file_path.display(),\n line.trim()\n );\n return Ok(true);\n }\n }\n Ok(false)\n}\n\n// update_shell_config helper (no change from your existing logic)\nfn update_shell_config(\n config_path: &PathBuf,\n line_to_add: &str,\n sps_bin_path_str: &str,\n shell_name_for_log: &str,\n is_fish_shell: bool,\n) -> SpsResult {\n let sps_comment_tag_start = \"# SPS Path Management Start\";\n let sps_comment_tag_end = \"# SPS Path Management End\";\n\n if config_path.exists() {\n match line_exists_in_file(config_path, sps_bin_path_str) {\n Ok(true) => {\n debug!(\n \"sps path ({}) already configured or managed in {} ({}). Skipping modification.\",\n sps_bin_path_str,\n config_path.display(),\n shell_name_for_log\n );\n return Ok(false); // Path already seems configured\n }\n Ok(false) => { /* Proceed to add */ }\n Err(e) => {\n warn!(\n \"Could not reliably check existing configuration in {} ({}): {}. Attempting to add PATH.\",\n config_path.display(),\n shell_name_for_log,\n e\n );\n // Proceed with caution, might add duplicate if check failed but line exists\n }\n }\n }\n\n debug!(\n \"Adding sps PATH to {} ({})\",\n config_path.display(),\n shell_name_for_log\n );\n\n // Ensure parent directory exists\n if let Some(parent_dir) = config_path.parent() {\n if !parent_dir.exists() {\n fs::create_dir_all(parent_dir).map_err(|e| {\n SpsError::Io(Arc::new(std::io::Error::new(\n e.kind(),\n format!(\n \"Failed to create parent directory {}: {}\",\n parent_dir.display(),\n e\n ),\n )))\n })?;\n }\n }\n\n let mut file = OpenOptions::new()\n .append(true)\n .create(true)\n .open(config_path)\n .map_err(|e| {\n let msg = format!(\n \"Could not open/create shell config {} ({}): {}. Please add {} to your PATH manually.\",\n config_path.display(), shell_name_for_log, e, sps_bin_path_str\n );\n error!(\"{}\", msg);\n SpsError::Io(Arc::new(std::io::Error::new(e.kind(), msg)))\n })?;\n\n // Construct the block to add, ensuring it's idempotent for fish\n let block_to_add = if is_fish_shell {\n format!(\n \"\\n{sps_comment_tag_start}\\n# Add sps to PATH if not already present\\nif not contains \\\"{sps_bin_path_str}\\\" $fish_user_paths\\n {line_to_add}\\nend\\n{sps_comment_tag_end}\\n\"\n )\n } else {\n format!(\"\\n{sps_comment_tag_start}\\n{line_to_add}\\n{sps_comment_tag_end}\\n\")\n };\n\n if let Err(e) = writeln!(file, \"{block_to_add}\") {\n warn!(\n \"Failed to write to shell config {} ({}): {}\",\n config_path.display(),\n shell_name_for_log,\n e\n );\n Ok(false) // Indicate that update was not successful\n } else {\n debug!(\n \"Successfully updated {} ({}) with sps PATH.\",\n config_path.display(),\n shell_name_for_log\n );\n Ok(true) // Indicate successful update\n }\n}\n\n// ensure_profile_sources_rc helper (no change from your existing logic)\nfn ensure_profile_sources_rc(profile_path: &PathBuf, rc_path: &Path, shell_name_for_log: &str) {\n let rc_path_str = rc_path.to_string_lossy();\n // Regex to check if the profile file already sources the rc file.\n // Looks for lines like:\n // . /path/to/.bashrc\n // source /path/to/.bashrc\n // [ -f /path/to/.bashrc ] && . /path/to/.bashrc (and similar variants)\n let source_check_pattern = format!(\n r#\"(?m)^\\s*[^#]*(\\.|source|\\bsource\\b)\\s+[\"']?{}[\"']?\"#, /* More general source command\n * matching */\n regex::escape(&rc_path_str)\n );\n let source_check_regex = match regex::Regex::new(&source_check_pattern) {\n Ok(re) => re,\n Err(e) => {\n warn!(\"Failed to compile regex for sourcing check: {}. Skipping ensure_profile_sources_rc for {}\", e, profile_path.display());\n return;\n }\n };\n\n if profile_path.exists() {\n match fs::read_to_string(profile_path) {\n Ok(existing_content) => {\n if source_check_regex.is_match(&existing_content) {\n debug!(\n \"{} ({}) already sources {}.\",\n profile_path.display(),\n shell_name_for_log,\n rc_path.display()\n );\n return; // Already configured\n }\n }\n Err(e) => {\n warn!(\n \"Could not read {} to check if it sources {}: {}. Will attempt to append.\",\n profile_path.display(),\n rc_path.display(),\n e\n );\n }\n }\n }\n\n // Block to add to .bash_profile or .profile to source .bashrc\n let source_block_to_add = format!(\n \"\\n# Source {rc_filename} if it exists and is readable\\nif [ -f \\\"{rc_path_str}\\\" ] && [ -r \\\"{rc_path_str}\\\" ]; then\\n . \\\"{rc_path_str}\\\"\\nfi\\n\",\n rc_filename = rc_path.file_name().unwrap_or_default().to_string_lossy(),\n rc_path_str = rc_path_str\n );\n\n debug!(\n \"Attempting to ensure {} ({}) sources {}\",\n profile_path.display(),\n shell_name_for_log,\n rc_path.display()\n );\n\n if let Some(parent_dir) = profile_path.parent() {\n if !parent_dir.exists() {\n if let Err(e) = fs::create_dir_all(parent_dir) {\n warn!(\n \"Failed to create parent directory for {}: {}\",\n profile_path.display(),\n e\n );\n return; // Cannot proceed if parent dir creation fails\n }\n }\n }\n\n match OpenOptions::new()\n .append(true)\n .create(true)\n .open(profile_path)\n {\n Ok(mut file) => {\n if let Err(e) = writeln!(file, \"{source_block_to_add}\") {\n warn!(\n \"Failed to write to {} ({}): {}\",\n profile_path.display(),\n shell_name_for_log,\n e\n );\n } else {\n debug!(\n \"Updated {} ({}) to source {}.\",\n profile_path.display(),\n shell_name_for_log,\n rc_path.display()\n );\n }\n }\n Err(e) => {\n warn!(\n \"Could not open or create {} ({}) for updating: {}\",\n profile_path.display(),\n shell_name_for_log,\n e\n );\n }\n }\n}\n"], ["/sps/sps-net/src/http.rs", "use std::fs;\nuse std::path::{Path, PathBuf};\nuse std::sync::Arc;\nuse std::time::Duration;\n\nuse futures::StreamExt;\nuse reqwest::header::{HeaderMap, ACCEPT, USER_AGENT};\nuse reqwest::{Client, StatusCode};\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::formula::ResourceSpec;\nuse tokio::fs::File as TokioFile;\nuse tokio::io::AsyncWriteExt;\nuse tracing::{debug, error};\n\nuse crate::validation::{validate_url, verify_checksum};\n\npub type ProgressCallback = Arc) + Send + Sync>;\n\nconst DOWNLOAD_TIMEOUT_SECS: u64 = 300;\nconst CONNECT_TIMEOUT_SECS: u64 = 30;\nconst USER_AGENT_STRING: &str = \"sps package manager (Rust; +https://github.com/alexykn/sp)\";\n\npub async fn fetch_formula_source_or_bottle(\n formula_name: &str,\n url: &str,\n sha256_expected: &str,\n mirrors: &[String],\n config: &Config,\n) -> Result {\n fetch_formula_source_or_bottle_with_progress(\n formula_name,\n url,\n sha256_expected,\n mirrors,\n config,\n None,\n )\n .await\n}\n\npub async fn fetch_formula_source_or_bottle_with_progress(\n formula_name: &str,\n url: &str,\n sha256_expected: &str,\n mirrors: &[String],\n config: &Config,\n progress_callback: Option,\n) -> Result {\n let filename = url\n .split('/')\n .next_back()\n .map(|s| s.to_string())\n .unwrap_or_else(|| format!(\"{formula_name}-download\"));\n let cache_path = config.cache_dir().join(&filename);\n\n tracing::debug!(\n \"Preparing to fetch main resource for '{}' from URL: {}\",\n formula_name,\n url\n );\n tracing::debug!(\"Target cache path: {}\", cache_path.display());\n tracing::debug!(\"Expected SHA256: {}\", sha256_expected);\n\n if cache_path.is_file() {\n tracing::debug!(\"File exists in cache: {}\", cache_path.display());\n if !sha256_expected.is_empty() {\n match verify_checksum(&cache_path, sha256_expected) {\n Ok(_) => {\n tracing::debug!(\"Using valid cached file: {}\", cache_path.display());\n return Ok(cache_path);\n }\n Err(e) => {\n debug!(\n \"Cached file checksum mismatch ({}): {}. Redownloading.\",\n cache_path.display(),\n e\n );\n if let Err(remove_err) = fs::remove_file(&cache_path) {\n debug!(\n \"Failed to remove corrupted cached file {}: {}\",\n cache_path.display(),\n remove_err\n );\n }\n }\n }\n } else {\n tracing::debug!(\n \"Using cached file (no checksum provided): {}\",\n cache_path.display()\n );\n return Ok(cache_path);\n }\n } else {\n tracing::debug!(\"File not found in cache.\");\n }\n\n fs::create_dir_all(config.cache_dir()).map_err(|e| {\n SpsError::IoError(format!(\n \"Failed to create cache directory {}: {}\",\n config.cache_dir().display(),\n e\n ))\n })?;\n // Validate primary URL\n validate_url(url)?;\n\n let client = build_http_client()?;\n\n let urls_to_try = std::iter::once(url).chain(mirrors.iter().map(|s| s.as_str()));\n let mut last_error: Option = None;\n\n for current_url in urls_to_try {\n // Validate mirror URL\n validate_url(current_url)?;\n tracing::debug!(\"Attempting download from: {}\", current_url);\n match download_and_verify(\n &client,\n current_url,\n &cache_path,\n sha256_expected,\n progress_callback.clone(),\n )\n .await\n {\n Ok(path) => {\n tracing::debug!(\"Successfully downloaded and verified: {}\", path.display());\n return Ok(path);\n }\n Err(e) => {\n error!(\"Download attempt failed from {}: {}\", current_url, e);\n last_error = Some(e);\n }\n }\n }\n\n Err(last_error.unwrap_or_else(|| {\n SpsError::DownloadError(\n formula_name.to_string(),\n url.to_string(),\n \"All download attempts failed.\".to_string(),\n )\n }))\n}\n\npub async fn fetch_resource(\n formula_name: &str,\n resource: &ResourceSpec,\n config: &Config,\n) -> Result {\n fetch_resource_with_progress(formula_name, resource, config, None).await\n}\n\npub async fn fetch_resource_with_progress(\n formula_name: &str,\n resource: &ResourceSpec,\n config: &Config,\n progress_callback: Option,\n) -> Result {\n let resource_cache_dir = config.cache_dir().join(\"resources\");\n fs::create_dir_all(&resource_cache_dir).map_err(|e| {\n SpsError::IoError(format!(\n \"Failed to create resource cache directory {}: {}\",\n resource_cache_dir.display(),\n e\n ))\n })?;\n // Validate resource URL\n validate_url(&resource.url)?;\n\n let url_filename = resource\n .url\n .split('/')\n .next_back()\n .map(|s| s.to_string())\n .unwrap_or_else(|| format!(\"{}-download\", resource.name));\n let cache_filename = format!(\"{}-{}\", resource.name, url_filename);\n let cache_path = resource_cache_dir.join(&cache_filename);\n\n tracing::debug!(\n \"Preparing to fetch resource '{}' for formula '{}' from URL: {}\",\n resource.name,\n formula_name,\n resource.url\n );\n tracing::debug!(\"Target resource cache path: {}\", cache_path.display());\n tracing::debug!(\"Expected SHA256: {}\", resource.sha256);\n\n if cache_path.is_file() {\n tracing::debug!(\"Resource exists in cache: {}\", cache_path.display());\n match verify_checksum(&cache_path, &resource.sha256) {\n Ok(_) => {\n tracing::debug!(\"Using cached resource: {}\", cache_path.display());\n return Ok(cache_path);\n }\n Err(e) => {\n debug!(\n \"Cached resource checksum mismatch ({}): {}. Redownloading.\",\n cache_path.display(),\n e\n );\n if let Err(remove_err) = fs::remove_file(&cache_path) {\n debug!(\n \"Failed to remove corrupted cached resource file {}: {}\",\n cache_path.display(),\n remove_err\n );\n }\n }\n }\n } else {\n tracing::debug!(\"Resource not found in cache.\");\n }\n\n let client = build_http_client()?;\n match download_and_verify(\n &client,\n &resource.url,\n &cache_path,\n &resource.sha256,\n progress_callback,\n )\n .await\n {\n Ok(path) => {\n tracing::debug!(\n \"Successfully downloaded and verified resource: {}\",\n path.display()\n );\n Ok(path)\n }\n Err(e) => {\n error!(\"Resource download failed from {}: {}\", resource.url, e);\n let _ = fs::remove_file(&cache_path);\n Err(SpsError::DownloadError(\n resource.name.clone(),\n resource.url.clone(),\n format!(\"Download failed: {e}\"),\n ))\n }\n }\n}\n\nfn build_http_client() -> Result {\n let mut headers = HeaderMap::new();\n headers.insert(USER_AGENT, USER_AGENT_STRING.parse().unwrap());\n headers.insert(ACCEPT, \"*/*\".parse().unwrap());\n Client::builder()\n .timeout(Duration::from_secs(DOWNLOAD_TIMEOUT_SECS))\n .connect_timeout(Duration::from_secs(CONNECT_TIMEOUT_SECS))\n .default_headers(headers)\n .redirect(reqwest::redirect::Policy::limited(10))\n .build()\n .map_err(|e| SpsError::HttpError(format!(\"Failed to build HTTP client: {e}\")))\n}\n\nasync fn download_and_verify(\n client: &Client,\n url: &str,\n final_path: &Path,\n sha256_expected: &str,\n progress_callback: Option,\n) -> Result {\n let temp_filename = format!(\n \".{}.download\",\n final_path.file_name().unwrap_or_default().to_string_lossy()\n );\n let temp_path = final_path.with_file_name(temp_filename);\n tracing::debug!(\"Downloading to temporary path: {}\", temp_path.display());\n if temp_path.exists() {\n if let Err(e) = fs::remove_file(&temp_path) {\n tracing::warn!(\n \"Could not remove existing temporary file {}: {}\",\n temp_path.display(),\n e\n );\n }\n }\n\n let response = client.get(url).send().await.map_err(|e| {\n debug!(\"HTTP request failed for {url}: {e}\");\n SpsError::HttpError(format!(\"HTTP request failed for {url}: {e}\"))\n })?;\n let status = response.status();\n tracing::debug!(\"Received HTTP status: {} for {}\", status, url);\n\n if !status.is_success() {\n let body_text = response\n .text()\n .await\n .unwrap_or_else(|_| \"Failed to read response body\".to_string());\n tracing::error!(\"HTTP error {} for URL {}: {}\", status, url, body_text);\n return match status {\n StatusCode::NOT_FOUND => Err(SpsError::DownloadError(\n final_path\n .file_name()\n .map(|s| s.to_string_lossy().to_string())\n .unwrap_or_default(),\n url.to_string(),\n \"Resource not found (404)\".to_string(),\n )),\n StatusCode::FORBIDDEN => Err(SpsError::DownloadError(\n final_path\n .file_name()\n .map(|s| s.to_string_lossy().to_string())\n .unwrap_or_default(),\n url.to_string(),\n \"Access forbidden (403)\".to_string(),\n )),\n _ => Err(SpsError::HttpError(format!(\n \"HTTP error {status} for URL {url}: {body_text}\"\n ))),\n };\n }\n\n // Get total size from Content-Length header if available\n let total_size = response.content_length();\n\n let mut temp_file = TokioFile::create(&temp_path).await.map_err(|e| {\n SpsError::IoError(format!(\n \"Failed to create temp file {}: {}\",\n temp_path.display(),\n e\n ))\n })?;\n\n // Use bytes_stream() for chunked download with progress reporting\n let mut stream = response.bytes_stream();\n let mut bytes_downloaded = 0u64;\n\n while let Some(chunk) = stream.next().await {\n let chunk = chunk.map_err(|e| SpsError::HttpError(format!(\"Failed to read chunk: {e}\")))?;\n\n temp_file.write_all(&chunk).await.map_err(|e| {\n SpsError::IoError(format!(\n \"Failed to write chunk to {}: {}\",\n temp_path.display(),\n e\n ))\n })?;\n\n bytes_downloaded += chunk.len() as u64;\n\n // Call progress callback if provided\n if let Some(ref callback) = progress_callback {\n callback(bytes_downloaded, total_size);\n }\n }\n\n drop(temp_file);\n tracing::debug!(\"Finished writing download stream to temp file.\");\n\n if !sha256_expected.is_empty() {\n verify_checksum(&temp_path, sha256_expected)?;\n tracing::debug!(\n \"Checksum verified for temporary file: {}\",\n temp_path.display()\n );\n } else {\n tracing::warn!(\n \"Skipping checksum verification for {} - none provided.\",\n temp_path.display()\n );\n }\n\n fs::rename(&temp_path, final_path).map_err(|e| {\n SpsError::IoError(format!(\n \"Failed to move temp file {} to {}: {}\",\n temp_path.display(),\n final_path.display(),\n e\n ))\n })?;\n tracing::debug!(\n \"Moved verified file to final location: {}\",\n final_path.display()\n );\n Ok(final_path.to_path_buf())\n}\n"], ["/sps/sps-common/src/model/cask.rs", "// ===== sps-common/src/model/cask.rs ===== // Corrected path\nuse std::collections::HashMap;\nuse std::fs;\n\nuse serde::{Deserialize, Serialize};\n\nuse crate::config::Config;\n\npub type Artifact = serde_json::Value;\n\n/// Represents the `url` field, which can be a simple string or a map with specs\n#[derive(Debug, Clone, Serialize, Deserialize)]\n#[serde(untagged)]\npub enum UrlField {\n Simple(String),\n WithSpec {\n url: String,\n #[serde(default)]\n verified: Option,\n #[serde(flatten)]\n other: HashMap,\n },\n}\n\n/// Represents the `sha256` field: hex, no_check, or per-architecture\n#[derive(Debug, Clone, Serialize, Deserialize)]\n#[serde(untagged)]\npub enum Sha256Field {\n Hex(String),\n #[serde(rename_all = \"snake_case\")]\n NoCheck {\n no_check: bool,\n },\n PerArch(HashMap),\n}\n\n/// Appcast metadata\n#[derive(Debug, Clone, Serialize, Deserialize)] // Ensure Serialize/Deserialize are here\npub struct Appcast {\n pub url: String,\n pub checkpoint: Option,\n}\n\n/// Represents conflicts with other casks or formulae\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub struct ConflictsWith {\n #[serde(default)]\n pub cask: Vec,\n #[serde(default)]\n pub formula: Vec,\n #[serde(flatten)]\n pub extra: HashMap,\n}\n\n/// Represents the specific architecture details found in some cask definitions\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub struct ArchSpec {\n #[serde(rename = \"type\")] // Map the JSON \"type\" field\n pub type_name: String, // e.g., \"arm\"\n pub bits: u32, // e.g., 64\n}\n\n/// Helper for architecture requirements: single string, list of strings, or list of spec objects\n#[derive(Debug, Clone, Serialize, Deserialize)]\n#[serde(untagged)]\npub enum ArchReq {\n One(String), // e.g., \"arm64\"\n Many(Vec), // e.g., [\"arm64\", \"x86_64\"]\n Specs(Vec),\n}\n\n/// Helper for macOS requirements: symbol, list, comparison, or map\n#[derive(Debug, Clone, Serialize, Deserialize)]\n#[serde(untagged)]\npub enum MacOSReq {\n Symbol(String), // \":big_sur\"\n Symbols(Vec), // [\":catalina\", \":big_sur\"]\n Comparison(String), // \">= :big_sur\"\n Map(HashMap>),\n}\n\n/// Helper to coerce string-or-list into Vec\n#[derive(Debug, Clone, Serialize, Deserialize)]\n#[serde(untagged)]\npub enum StringList {\n One(String),\n Many(Vec),\n}\n\nimpl From for Vec {\n fn from(item: StringList) -> Self {\n match item {\n StringList::One(s) => vec![s],\n StringList::Many(v) => v,\n }\n }\n}\n\n/// Represents `depends_on` block with multiple possible keys\n#[derive(Debug, Clone, Serialize, Deserialize, Default)]\npub struct DependsOn {\n #[serde(default)]\n pub cask: Vec,\n #[serde(default)]\n pub formula: Vec,\n #[serde(default)]\n pub arch: Option,\n #[serde(default)]\n pub macos: Option,\n #[serde(flatten)]\n pub extra: HashMap,\n}\n\n/// The main Cask model matching Homebrew JSON v2\n#[derive(Debug, Clone, Serialize, Deserialize, Default)]\npub struct Cask {\n pub token: String,\n\n #[serde(default)]\n pub name: Option>,\n pub version: Option,\n pub desc: Option,\n pub homepage: Option,\n\n #[serde(default)]\n pub artifacts: Option>,\n\n #[serde(default)]\n pub url: Option,\n #[serde(default)]\n pub url_specs: Option>,\n\n #[serde(default)]\n pub sha256: Option,\n\n pub appcast: Option,\n pub auto_updates: Option,\n\n #[serde(default)]\n pub depends_on: Option,\n\n #[serde(default)]\n pub conflicts_with: Option,\n\n pub caveats: Option,\n pub stage_only: Option,\n\n #[serde(default)]\n pub uninstall: Option>,\n\n #[serde(default)] // Only one default here\n pub zap: Option>,\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub struct CaskList {\n pub casks: Vec,\n}\n\n// --- ZAP STANZA SUPPORT ---\n\n/// Helper for zap: string or array of strings\n#[derive(Debug, Clone, Serialize, Deserialize)]\n#[serde(untagged)]\npub enum StringOrVec {\n String(String),\n Vec(Vec),\n}\nimpl StringOrVec {\n pub fn into_vec(self) -> Vec {\n match self {\n StringOrVec::String(s) => vec![s],\n StringOrVec::Vec(v) => v,\n }\n }\n}\n\n/// Zap action details (trash, delete, rmdir, pkgutil, launchctl, script, signal, etc)\n#[derive(Debug, Clone, Serialize, Deserialize)]\n#[serde(tag = \"action\", rename_all = \"snake_case\")]\npub enum ZapActionDetail {\n Trash(Vec),\n Delete(Vec),\n Rmdir(Vec),\n Pkgutil(StringOrVec),\n Launchctl(StringOrVec),\n Script {\n executable: String,\n args: Option>,\n },\n Signal(Vec),\n // Add more as needed\n}\n\n/// A zap stanza is a map of action -> detail\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub struct ZapStanza(pub std::collections::HashMap);\n\n// --- Cask Impl ---\n\nimpl Cask {\n /// Check if this cask is installed by looking for a manifest file\n /// in any versioned directory within the Caskroom.\n pub fn is_installed(&self, config: &Config) -> bool {\n let cask_dir = config.cask_room_token_path(&self.token); // e.g., /opt/sps/cask_room/firefox\n if !cask_dir.exists() || !cask_dir.is_dir() {\n return false;\n }\n\n // Iterate through entries (version dirs) inside the cask_dir\n match fs::read_dir(&cask_dir) {\n Ok(entries) => {\n // Clippy fix: Use flatten() to handle Result entries directly\n for entry in entries.flatten() {\n // <-- Use flatten() here\n let version_path = entry.path();\n // Check if it's a directory (representing a version)\n if version_path.is_dir() {\n // Check for the existence of the manifest file\n let manifest_path = version_path.join(\"CASK_INSTALL_MANIFEST.json\"); // <-- Correct filename\n if manifest_path.is_file() {\n // Check is_installed flag in manifest\n let mut include = true;\n if let Ok(manifest_str) = std::fs::read_to_string(&manifest_path) {\n if let Ok(manifest_json) =\n serde_json::from_str::(&manifest_str)\n {\n if let Some(is_installed) =\n manifest_json.get(\"is_installed\").and_then(|v| v.as_bool())\n {\n include = is_installed;\n }\n }\n }\n if include {\n // Found a manifest in at least one version directory, consider it\n // installed\n return true;\n }\n }\n }\n }\n // If loop completes without finding a manifest in any version dir\n false\n }\n Err(e) => {\n // Log error if reading the directory fails, but assume not installed\n tracing::warn!(\n \"Failed to read cask directory {} to check for installed versions: {}\",\n cask_dir.display(),\n e\n );\n false\n }\n }\n }\n\n /// Get the installed version of this cask by reading the directory names\n /// in the Caskroom. Returns the first version found (use cautiously if multiple\n /// versions could exist, though current install logic prevents this).\n pub fn installed_version(&self, config: &Config) -> Option {\n let cask_dir = config.cask_room_token_path(&self.token); //\n if !cask_dir.exists() {\n return None;\n }\n // Iterate through entries and return the first directory name found\n match fs::read_dir(&cask_dir) {\n Ok(entries) => {\n // Clippy fix: Use flatten()\n for entry in entries.flatten() {\n // <-- Use flatten() here\n let path = entry.path();\n // Check if it's a directory (representing a version)\n if path.is_dir() {\n if let Some(version_str) = path.file_name().and_then(|name| name.to_str()) {\n // Return the first version directory name found\n return Some(version_str.to_string());\n }\n }\n }\n // No version directories found\n None\n }\n Err(_) => None, // Error reading directory\n }\n }\n\n /// Get a friendly name for display purposes\n pub fn display_name(&self) -> String {\n self.name\n .as_ref()\n .and_then(|names| names.first().cloned())\n .unwrap_or_else(|| self.token.clone())\n }\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/installer.rs", "// ===== sps-core/src/build/cask/artifacts/installer.rs =====\n\nuse std::path::Path;\nuse std::process::{Command, Stdio};\n\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::InstalledArtifact;\n\n// Helper to validate that the executable is a filename (relative, no '/' or \"..\")\nfn validate_filename_or_relative_path(file: &str) -> Result {\n if file.starts_with(\"/\") || file.contains(\"..\") || file.contains(\"/\") {\n return Err(SpsError::Generic(format!(\n \"Invalid executable filename: {file}\"\n )));\n }\n Ok(file.to_string())\n}\n\n// Helper to validate a command argument based on allowed characters or allowed option form\nfn validate_argument(arg: &str) -> Result {\n if arg.starts_with(\"-\") {\n return Ok(arg.to_string());\n }\n if arg.starts_with(\"/\") || arg.contains(\"..\") || arg.contains(\"/\") {\n return Err(SpsError::Generic(format!(\"Invalid argument: {arg}\")));\n }\n if !arg\n .chars()\n .all(|c| c.is_alphanumeric() || c == '-' || c == '_' || c == '.')\n {\n return Err(SpsError::Generic(format!(\n \"Invalid characters in argument: {arg}\"\n )));\n }\n Ok(arg.to_string())\n}\n\n/// Implements the `installer` stanza:\n/// - `manual`: prints instructions to open the staged path.\n/// - `script`: runs the given executable with args, under sudo if requested.\n///\n/// Mirrors Homebrew’s `Cask::Artifact::Installer` behavior :contentReference[oaicite:1]{index=1}.\npub fn run_installer(\n cask: &Cask,\n stage_path: &Path,\n _cask_version_install_path: &Path,\n _config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n // Find the `installer` definitions in the raw JSON artifacts\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(insts) = obj.get(\"installer\").and_then(|v| v.as_array()) {\n for inst in insts {\n if let Some(inst_obj) = inst.as_object() {\n if let Some(man) = inst_obj.get(\"manual\").and_then(|v| v.as_str()) {\n debug!(\n \"Cask {} requires manual install. To finish:\\n open {}\",\n cask.token,\n stage_path.join(man).display()\n );\n continue;\n }\n let exe_key = if inst_obj.contains_key(\"script\") {\n \"script\"\n } else {\n \"executable\"\n };\n let executable = inst_obj\n .get(exe_key)\n .and_then(|v| v.as_str())\n .ok_or_else(|| {\n SpsError::Generic(format!(\n \"installer stanza missing '{exe_key}' field\"\n ))\n })?;\n let args: Vec = inst_obj\n .get(\"args\")\n .and_then(|v| v.as_array())\n .map(|arr| {\n arr.iter()\n .filter_map(|a| a.as_str().map(String::from))\n .collect()\n })\n .unwrap_or_default();\n let use_sudo = inst_obj\n .get(\"sudo\")\n .and_then(|v| v.as_bool())\n .unwrap_or(false);\n\n let validated_executable =\n validate_filename_or_relative_path(executable)?;\n let mut validated_args = Vec::new();\n for arg in &args {\n validated_args.push(validate_argument(arg)?);\n }\n\n let script_path = stage_path.join(&validated_executable);\n if !script_path.exists() {\n return Err(SpsError::NotFound(format!(\n \"Installer script not found: {}\",\n script_path.display()\n )));\n }\n\n debug!(\n \"Running installer script '{}' for cask {}\",\n script_path.display(),\n cask.token\n );\n let mut cmd = if use_sudo {\n let mut c = Command::new(\"sudo\");\n c.arg(script_path.clone());\n c\n } else {\n Command::new(script_path.clone())\n };\n cmd.args(&validated_args);\n cmd.stdin(Stdio::null())\n .stdout(Stdio::inherit())\n .stderr(Stdio::inherit());\n\n let status = cmd.status().map_err(|e| {\n SpsError::Generic(format!(\"Failed to spawn installer script: {e}\"))\n })?;\n if !status.success() {\n return Err(SpsError::InstallError(format!(\n \"Installer script exited with {status}\"\n )));\n }\n\n installed\n .push(InstalledArtifact::CaskroomReference { path: script_path });\n }\n }\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/utils/applescript.rs", "use std::path::Path;\nuse std::process::Command;\nuse std::thread;\nuse std::time::Duration;\n\nuse plist::Value as PlistValue;\nuse sps_common::error::Result;\nuse tracing::{debug, warn};\n\nfn get_bundle_identifier_from_app_path(app_path: &Path) -> Option {\n let info_plist_path = app_path.join(\"Contents/Info.plist\");\n if !info_plist_path.is_file() {\n debug!(\"Info.plist not found at {}\", info_plist_path.display());\n return None;\n }\n match PlistValue::from_file(&info_plist_path) {\n Ok(PlistValue::Dictionary(dict)) => dict\n .get(\"CFBundleIdentifier\")\n .and_then(PlistValue::as_string)\n .map(String::from),\n Ok(val) => {\n warn!(\n \"Info.plist at {} is not a dictionary. Value: {:?}\",\n info_plist_path.display(),\n val\n );\n None\n }\n Err(e) => {\n warn!(\n \"Failed to parse Info.plist at {}: {}\",\n info_plist_path.display(),\n e\n );\n None\n }\n }\n}\n\nfn is_app_running_by_bundle_id(bundle_id: &str) -> Result {\n let script = format!(\n \"tell application \\\"System Events\\\" to (exists (process 1 where bundle identifier is \\\"{bundle_id}\\\"))\"\n );\n debug!(\n \"Checking if app with bundle ID '{}' is running using script: {}\",\n bundle_id, script\n );\n\n let output = Command::new(\"osascript\").arg(\"-e\").arg(&script).output()?;\n\n if output.status.success() {\n let stdout = String::from_utf8_lossy(&output.stdout)\n .trim()\n .to_lowercase();\n debug!(\n \"is_app_running_by_bundle_id ('{}') stdout: '{}'\",\n bundle_id, stdout\n );\n Ok(stdout == \"true\")\n } else {\n let stderr = String::from_utf8_lossy(&output.stderr);\n warn!(\n \"osascript check running status for bundle ID '{}' failed. Status: {}, Stderr: {}\",\n bundle_id,\n output.status,\n stderr.trim()\n );\n Ok(false)\n }\n}\n\n/// Attempts to gracefully quit an application using its bundle identifier (preferred) or name via\n/// AppleScript. Retries several times, checking if the app is still running between attempts.\n/// Returns Ok even if the app could not be quit, as uninstall should proceed.\npub fn quit_app_gracefully(app_path: &Path) -> Result<()> {\n if !cfg!(target_os = \"macos\") {\n debug!(\"Not on macOS, skipping app quit for {}\", app_path.display());\n return Ok(());\n }\n if !app_path.exists() {\n debug!(\n \"App path {} does not exist, skipping quit attempt.\",\n app_path.display()\n );\n return Ok(());\n }\n\n let app_name_for_log = app_path\n .file_name()\n .map_or_else(|| app_path.to_string_lossy(), |name| name.to_string_lossy())\n .trim_end_matches(\".app\")\n .to_string();\n\n let bundle_identifier = get_bundle_identifier_from_app_path(app_path);\n\n let (script_target, using_bundle_id) = match &bundle_identifier {\n Some(id) => (id.clone(), true),\n None => {\n warn!(\n \"Could not get bundle identifier for {}. Will attempt to quit by name '{}'. This is less reliable.\",\n app_path.display(),\n app_name_for_log\n );\n (app_name_for_log.clone(), false)\n }\n };\n\n debug!(\n \"Attempting to quit app '{}' (script target: '{}', using bundle_id: {})\",\n app_name_for_log, script_target, using_bundle_id\n );\n\n // Initial check if app is running (only reliable if we have bundle ID)\n if using_bundle_id {\n match is_app_running_by_bundle_id(&script_target) {\n Ok(true) => debug!(\n \"App '{}' is running. Proceeding with quit attempts.\",\n script_target\n ),\n Ok(false) => {\n debug!(\"App '{}' is not running. Quit unnecessary.\", script_target);\n return Ok(());\n }\n Err(e) => {\n warn!(\n \"Could not determine if app '{}' is running (check failed: {}). Proceeding with quit attempt.\",\n script_target, e\n );\n }\n }\n }\n\n let quit_command = if using_bundle_id {\n format!(\"tell application id \\\"{script_target}\\\" to quit\")\n } else {\n format!(\"tell application \\\"{script_target}\\\" to quit\")\n };\n\n const MAX_QUIT_ATTEMPTS: usize = 4;\n const QUIT_DELAYS_SECS: [u64; MAX_QUIT_ATTEMPTS - 1] = [2, 3, 5];\n\n // Use enumerate over QUIT_DELAYS_SECS for Clippy compliance\n for (attempt, delay) in QUIT_DELAYS_SECS.iter().enumerate() {\n debug!(\n \"Quit attempt #{} for '{}' using command: {}\",\n attempt + 1,\n script_target,\n quit_command\n );\n\n let output = Command::new(\"osascript\")\n .arg(\"-e\")\n .arg(&quit_command)\n .output()?; // Propagate IO errors from osascript execution\n\n if output.status.success() {\n debug!(\n \"osascript quit command sent successfully for '{}' (attempt #{}).\",\n script_target,\n attempt + 1\n );\n } else {\n let stderr = String::from_utf8_lossy(&output.stderr);\n if stderr.contains(\"-1712\")\n || stderr.contains(\"-1728\")\n || stderr.contains(\"-600\")\n || stderr.to_lowercase().contains(\"application isn’t running\")\n || stderr.to_lowercase().contains(\"application not running\")\n {\n debug!(\n \"osascript: App '{}' reported as not running or not found (stderr: {}). Quit successful or unnecessary.\",\n script_target,\n stderr.trim()\n );\n return Ok(());\n } else {\n warn!(\n \"osascript quit command for '{}' failed (attempt #{}). Status: {}. Stderr: {}\",\n script_target,\n attempt + 1,\n output.status,\n stderr.trim()\n );\n }\n }\n\n // Wait briefly to allow the app to process the quit command\n thread::sleep(Duration::from_secs(*delay));\n\n // Check if the app is still running (if using bundle ID)\n if using_bundle_id {\n match is_app_running_by_bundle_id(&script_target) {\n Ok(true) => {\n debug!(\n \"App '{}' still running after attempt #{}. Retrying.\",\n script_target,\n attempt + 1\n );\n }\n Ok(false) => {\n debug!(\n \"App '{}' successfully quit after attempt #{}.\",\n script_target,\n attempt + 1\n );\n return Ok(());\n }\n Err(e) => {\n warn!(\n \"Could not verify if app '{}' quit after attempt #{}: {}. Assuming it might still be running.\",\n script_target,\n attempt + 1,\n e\n );\n }\n }\n }\n }\n\n // Final attempt (the fourth, not covered by QUIT_DELAYS_SECS)\n let attempt = QUIT_DELAYS_SECS.len();\n debug!(\n \"Quit attempt #{} for '{}' using command: {}\",\n attempt + 1,\n script_target,\n quit_command\n );\n\n let output = Command::new(\"osascript\")\n .arg(\"-e\")\n .arg(&quit_command)\n .output()?; // Propagate IO errors from osascript execution\n\n if output.status.success() {\n debug!(\n \"osascript quit command sent successfully for '{}' (attempt #{}).\",\n script_target,\n attempt + 1\n );\n } else {\n let stderr = String::from_utf8_lossy(&output.stderr);\n if stderr.contains(\"-1712\")\n || stderr.contains(\"-1728\")\n || stderr.contains(\"-600\")\n || stderr.to_lowercase().contains(\"application isn’t running\")\n || stderr.to_lowercase().contains(\"application not running\")\n {\n debug!(\n \"osascript: App '{}' reported as not running or not found (stderr: {}). Quit successful or unnecessary.\",\n script_target,\n stderr.trim()\n );\n return Ok(());\n } else {\n warn!(\n \"osascript quit command for '{}' failed (attempt #{}). Status: {}. Stderr: {}\",\n script_target,\n attempt + 1,\n output.status,\n stderr.trim()\n );\n }\n }\n\n // Final check if the app is still running (if using bundle ID)\n if using_bundle_id {\n match is_app_running_by_bundle_id(&script_target) {\n Ok(true) => {\n warn!(\n \"App '{}' still running after {} quit attempts.\",\n script_target, MAX_QUIT_ATTEMPTS\n );\n }\n Ok(false) => {\n debug!(\n \"App '{}' successfully quit after attempt #{}.\",\n script_target,\n attempt + 1\n );\n return Ok(());\n }\n Err(e) => {\n warn!(\n \"Could not verify if app '{}' quit after attempt #{}: {}. Assuming it might still be running.\",\n script_target,\n attempt + 1,\n e\n );\n }\n }\n } else {\n warn!(\n \"App '{}' (targeted by name) might still be running after {} quit attempts. Manual check may be needed.\",\n script_target,\n MAX_QUIT_ATTEMPTS\n );\n }\n Ok(())\n}\n"], ["/sps/sps/src/main.rs", "// sps/src/main.rs\nuse std::process::{self}; // StdCommand is used\nuse std::sync::Arc;\nuse std::time::{Duration, SystemTime};\nuse std::{env, fs};\n\nuse clap::Parser;\nuse colored::Colorize;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::error::{Result as spResult, SpsError};\nuse tracing::level_filters::LevelFilter;\nuse tracing::{debug, error, warn}; // Import all necessary tracing macros\nuse tracing_subscriber::fmt::writer::MakeWriterExt;\nuse tracing_subscriber::EnvFilter;\n\nmod cli;\nmod pipeline;\n// Correctly import InitArgs via the re-export in cli.rs or directly from its module\nuse cli::{CliArgs, Command, InitArgs};\n\n// Standalone function to handle the init command logic\nasync fn run_init_command(init_args: &InitArgs, verbose_level: u8) -> spResult<()> {\n let init_level_filter = match verbose_level {\n 0 => LevelFilter::INFO,\n 1 => LevelFilter::DEBUG,\n _ => LevelFilter::TRACE,\n };\n let _ = tracing_subscriber::fmt()\n .with_max_level(init_level_filter)\n .with_writer(std::io::stderr)\n .with_ansi(true)\n .without_time()\n .try_init();\n\n let initial_config_for_path = Config::load().map_err(|e| {\n // Handle error if even basic config loading fails for path determination\n SpsError::Config(format!(\n \"Could not determine sps_root for init (config load failed): {e}\"\n ))\n })?;\n\n // Create a minimal Config struct, primarily for sps_root() and derived paths.\n let temp_config_for_init = Config {\n sps_root: initial_config_for_path.sps_root().to_path_buf(),\n api_base_url: \"https://formulae.brew.sh/api\".to_string(),\n artifact_domain: None,\n docker_registry_token: None,\n docker_registry_basic_auth: None,\n github_api_token: None,\n };\n\n init_args.run(&temp_config_for_init).await\n}\n\n#[tokio::main]\nasync fn main() -> spResult<()> {\n let cli_args = CliArgs::parse();\n\n if let Command::Init(ref init_args_ref) = cli_args.command {\n match run_init_command(init_args_ref, cli_args.verbose).await {\n Ok(_) => {\n return Ok(());\n }\n Err(e) => {\n eprintln!(\"{}: Init command failed: {:#}\", \"Error\".red().bold(), e);\n process::exit(1);\n }\n }\n }\n\n let config = Config::load().map_err(|e| {\n SpsError::Config(format!(\n \"Could not load config (have you run 'sps init'?): {e}\"\n ))\n })?;\n\n let level_filter = match cli_args.verbose {\n 0 => LevelFilter::INFO,\n 1 => LevelFilter::DEBUG,\n _ => LevelFilter::TRACE,\n };\n let max_log_level = level_filter.into_level().unwrap_or(tracing::Level::INFO);\n\n let env_filter = EnvFilter::builder()\n .with_default_directive(level_filter.into())\n .with_env_var(\"SPS_LOG\")\n .from_env_lossy();\n\n let log_dir = config.logs_dir();\n if let Err(e) = fs::create_dir_all(&log_dir) {\n eprintln!(\n \"{} Failed to create log directory {}: {} (ensure 'sps init' was successful or try with sudo for the current command if appropriate)\",\n \"Error:\".red().bold(),\n log_dir.display(),\n e\n );\n let _ = tracing_subscriber::fmt() // Use `let _ =`\n .with_env_filter(env_filter)\n .with_writer(std::io::stderr)\n .with_ansi(true)\n .without_time()\n .try_init(); // Use try_init\n } else if cli_args.verbose > 0 {\n let file_appender = tracing_appender::rolling::daily(&log_dir, \"sps.log\");\n let (non_blocking_appender, guard) = tracing_appender::non_blocking(file_appender);\n\n // For verbose mode, show debug/trace logs on stderr too\n let stderr_writer = std::io::stderr.with_max_level(max_log_level);\n let file_writer = non_blocking_appender.with_max_level(max_log_level);\n\n let _ = tracing_subscriber::fmt() // Use `let _ =`\n .with_env_filter(env_filter)\n .with_writer(stderr_writer.and(file_writer))\n .with_ansi(true)\n .without_time()\n .try_init(); // Use try_init\n\n Box::leak(Box::new(guard)); // Keep guard alive\n\n tracing::debug!(\n // This will only work if try_init above was successful for this setup\n \"Verbose logging enabled. Writing logs to: {}/sps.log\",\n log_dir.display()\n );\n } else {\n let _ = tracing_subscriber::fmt() // Use `let _ =`\n .with_env_filter(env_filter)\n .with_writer(std::io::stderr)\n .with_ansi(true)\n .without_time()\n .try_init(); // Use try_init\n }\n\n let cache = Arc::new(Cache::new(&config).map_err(|e| {\n SpsError::Cache(format!(\n \"Could not initialize cache (ensure 'sps init' was successful): {e}\"\n ))\n })?);\n\n let needs_update_check = matches!(\n cli_args.command,\n Command::Install(_) | Command::Search { .. } | Command::Info { .. } | Command::Upgrade(_)\n );\n\n if needs_update_check {\n if let Err(e) = check_and_run_auto_update(&config, Arc::clone(&cache)).await {\n error!(\"Error during auto-update check: {}\", e); // Use `error!` macro\n }\n } else {\n debug!(\n // Use `debug!` macro\n \"Skipping auto-update check for command: {:?}\",\n cli_args.command\n );\n }\n\n // Pass config and cache to the command's run method\n let command_execution_result = match &cli_args.command {\n Command::Init(_) => {\n /* This case is handled above and main exits */\n unreachable!()\n }\n _ => cli_args.command.run(&config, cache).await,\n };\n\n if let Err(e) = command_execution_result {\n // For pipeline commands (Install, Reinstall, Upgrade), errors are already\n // displayed via the status system, so only log in verbose mode\n let is_pipeline_command = matches!(\n cli_args.command,\n Command::Install(_) | Command::Reinstall(_) | Command::Upgrade(_)\n );\n\n if is_pipeline_command {\n // Only show error details in verbose mode\n if cli_args.verbose > 0 {\n error!(\"Command failed: {:#}\", e);\n eprintln!(\"{}: {:#}\", \"Error\".red().bold(), e);\n }\n } else {\n // For non-pipeline commands, show errors normally\n error!(\"Command failed: {:#}\", e);\n eprintln!(\"{}: {:#}\", \"Error\".red().bold(), e);\n }\n process::exit(1);\n }\n\n debug!(\"Command completed successfully.\"); // Use `debug!` macro\n Ok(())\n}\n\nasync fn check_and_run_auto_update(config: &Config, cache: Arc) -> spResult<()> {\n if env::var(\"SPS_NO_AUTO_UPDATE\").is_ok_and(|v| v == \"1\") {\n debug!(\"Auto-update disabled via SPS_NO_AUTO_UPDATE=1.\");\n return Ok(());\n }\n\n let default_interval_secs: u64 = 86400;\n let update_interval_secs = env::var(\"SPS_AUTO_UPDATE_SECS\")\n .ok()\n .and_then(|s| s.parse::().ok())\n .unwrap_or(default_interval_secs);\n let update_interval = Duration::from_secs(update_interval_secs);\n debug!(\"Auto-update interval: {:?}\", update_interval);\n\n let timestamp_file = config.state_dir().join(\".sps_last_update_check\");\n debug!(\"Checking timestamp file: {}\", timestamp_file.display());\n\n if let Some(parent_dir) = timestamp_file.parent() {\n if !parent_dir.exists() {\n if let Err(e) = fs::create_dir_all(parent_dir) {\n warn!(\"Could not create state directory {} as user: {}. Auto-update might rely on 'sps init' to create this with sudo.\", parent_dir.display(), e);\n }\n }\n }\n\n let mut needs_update = true;\n if timestamp_file.exists() {\n if let Ok(metadata) = fs::metadata(×tamp_file) {\n if let Ok(modified_time) = metadata.modified() {\n match SystemTime::now().duration_since(modified_time) {\n Ok(age) => {\n debug!(\"Time since last update check: {:?}\", age);\n if age < update_interval {\n needs_update = false;\n debug!(\"Auto-update interval not yet passed.\");\n } else {\n debug!(\"Auto-update interval passed.\");\n }\n }\n Err(e) => {\n warn!(\n \"Could not get duration since last update check (system time error?): {}\",\n e\n );\n }\n }\n } else {\n warn!(\n \"Could not read modification time for timestamp file: {}\",\n timestamp_file.display()\n );\n }\n } else {\n debug!(\n \"Timestamp file {} metadata could not be read. Update needed.\",\n timestamp_file.display()\n );\n }\n } else {\n debug!(\n \"Timestamp file not found at {}. Update needed.\",\n timestamp_file.display()\n );\n }\n\n if needs_update {\n println!(\n \"{}{}\",\n \"==> \".bold().blue(),\n \"Running auto-update...\".bold()\n );\n match cli::update::Update.run(config, cache).await {\n Ok(_) => {\n println!(\n \"{}{}\",\n \"==> \".bold().blue(),\n \"Auto-update successful.\".bold()\n );\n match fs::File::create(×tamp_file) {\n Ok(_) => {\n debug!(\"Updated timestamp file: {}\", timestamp_file.display());\n }\n Err(e) => {\n warn!(\n \"Failed to create or update timestamp file '{}': {}\",\n timestamp_file.display(),\n e\n );\n }\n }\n }\n Err(e) => {\n error!(\"Auto-update failed: {}\", e);\n eprintln!(\"{} Auto-update failed: {}\", \"Warning:\".yellow(), e);\n }\n }\n } else {\n debug!(\"Skipping auto-update.\");\n }\n\n Ok(())\n}\n"], ["/sps/sps-common/src/formulary.rs", "use std::collections::HashMap;\nuse std::sync::Arc;\n\nuse tracing::debug;\n\nuse super::cache::Cache;\nuse super::config::Config;\nuse super::error::{Result, SpsError};\nuse super::model::formula::Formula;\n\n#[derive()]\npub struct Formulary {\n cache: Cache,\n parsed_cache: std::sync::Mutex>>,\n}\n\nimpl Formulary {\n pub fn new(config: Config) -> Self {\n let cache = Cache::new(&config).unwrap_or_else(|e| {\n panic!(\"Failed to initialize cache in Formulary: {e}\");\n });\n Self {\n cache,\n parsed_cache: std::sync::Mutex::new(HashMap::new()),\n }\n }\n\n pub fn load_formula(&self, name: &str) -> Result {\n let mut parsed_cache_guard = self.parsed_cache.lock().unwrap();\n if let Some(formula_arc) = parsed_cache_guard.get(name) {\n debug!(\"Loaded formula '{}' from parsed cache.\", name);\n return Ok(Arc::clone(formula_arc).as_ref().clone());\n }\n drop(parsed_cache_guard);\n\n let raw_data = self.cache.load_raw(\"formula.json\")?;\n let all_formulas: Vec = serde_json::from_str(&raw_data)\n .map_err(|e| SpsError::Cache(format!(\"Failed to parse cached formula data: {e}\")))?;\n debug!(\"Parsed {} formulas.\", all_formulas.len());\n\n let mut found_formula: Option = None;\n parsed_cache_guard = self.parsed_cache.lock().unwrap();\n for formula in all_formulas {\n let formula_name = formula.name.clone();\n let formula_arc = std::sync::Arc::new(formula);\n\n if formula_name == name {\n found_formula = Some(Arc::clone(&formula_arc).as_ref().clone());\n }\n\n parsed_cache_guard\n .entry(formula_name)\n .or_insert(formula_arc);\n }\n\n match found_formula {\n Some(f) => {\n debug!(\n \"Successfully loaded formula '{}' version {}\",\n f.name,\n f.version_str_full()\n );\n Ok(f)\n }\n None => {\n debug!(\n \"Formula '{}' not found within the cached formula data.\",\n name\n );\n Err(SpsError::Generic(format!(\n \"Formula '{name}' not found in cache.\"\n )))\n }\n }\n }\n}\n"], ["/sps/sps-net/src/oci.rs", "use std::collections::HashMap;\nuse std::fs::{remove_file, File};\nuse std::path::Path;\nuse std::sync::Arc;\nuse std::time::Duration;\n\nuse futures::StreamExt;\nuse rand::rngs::SmallRng;\nuse rand::{Rng, SeedableRng};\nuse reqwest::header::{ACCEPT, AUTHORIZATION};\nuse reqwest::{Client, Response, StatusCode};\nuse serde::{Deserialize, Serialize};\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse tracing::{debug, error};\nuse url::Url;\n\nuse crate::http::ProgressCallback;\nuse crate::validation::{validate_url, verify_checksum};\n\nconst OCI_MANIFEST_V1_TYPE: &str = \"application/vnd.oci.image.index.v1+json\";\nconst OCI_LAYER_V1_TYPE: &str = \"application/vnd.oci.image.layer.v1.tar+gzip\";\nconst DEFAULT_GHCR_TOKEN_ENDPOINT: &str = \"https://ghcr.io/token\";\npub const DEFAULT_GHCR_DOMAIN: &str = \"ghcr.io\";\n\nconst CONNECT_TIMEOUT_SECS: u64 = 30;\nconst REQUEST_TIMEOUT_SECS: u64 = 300;\nconst USER_AGENT_STRING: &str = \"sps package manager (Rust; +https://github.com/alexykn/sps)\";\n\n#[derive(Deserialize, Debug)]\nstruct OciTokenResponse {\n token: String,\n}\n\n#[derive(Serialize, Deserialize, Debug, Clone)]\n#[serde(rename_all = \"camelCase\")]\npub struct OciManifestIndex {\n pub schema_version: u32,\n pub media_type: Option,\n pub manifests: Vec,\n}\n\n#[derive(Serialize, Deserialize, Debug, Clone)]\n#[serde(rename_all = \"camelCase\")]\npub struct OciManifestDescriptor {\n pub media_type: String,\n pub digest: String,\n pub size: u64,\n pub platform: Option,\n pub annotations: Option>,\n}\n\n#[derive(Serialize, Deserialize, Debug, Clone)]\n#[serde(rename_all = \"camelCase\")]\npub struct OciPlatform {\n pub architecture: String,\n pub os: String,\n #[serde(rename = \"os.version\")]\n pub os_version: Option,\n #[serde(default)]\n pub features: Vec,\n pub variant: Option,\n}\n\n#[derive(Debug, Clone)]\nenum OciAuth {\n None,\n AnonymousBearer { token: String },\n ExplicitBearer { token: String },\n Basic { encoded: String },\n}\n\nasync fn fetch_oci_resource(\n resource_url: &str,\n accept_header: &str,\n config: &Config,\n client: &Client,\n) -> Result {\n let url = Url::parse(resource_url)\n .map_err(|e| SpsError::Generic(format!(\"Invalid URL '{resource_url}': {e}\")))?;\n validate_url(url.as_str())?;\n let registry_domain = url.host_str().unwrap_or(DEFAULT_GHCR_DOMAIN);\n let repo_path = extract_repo_path_from_url(&url).unwrap_or(\"\");\n\n let auth = determine_auth(config, client, registry_domain, repo_path).await?;\n let resp = execute_oci_request(client, resource_url, accept_header, &auth).await?;\n let txt = resp.text().await.map_err(|e| SpsError::Http(Arc::new(e)))?;\n\n debug!(\"OCI response ({} bytes) from {}\", txt.len(), resource_url);\n serde_json::from_str(&txt).map_err(|e| {\n error!(\"JSON parse error from {}: {}\", resource_url, e);\n SpsError::Json(Arc::new(e))\n })\n}\n\npub async fn download_oci_blob(\n blob_url: &str,\n destination_path: &Path,\n config: &Config,\n client: &Client,\n expected_digest: &str,\n) -> Result<()> {\n download_oci_blob_with_progress(\n blob_url,\n destination_path,\n config,\n client,\n expected_digest,\n None,\n )\n .await\n}\n\npub async fn download_oci_blob_with_progress(\n blob_url: &str,\n destination_path: &Path,\n config: &Config,\n client: &Client,\n expected_digest: &str,\n progress_callback: Option,\n) -> Result<()> {\n debug!(\"Downloading OCI blob: {}\", blob_url);\n let url = Url::parse(blob_url)\n .map_err(|e| SpsError::Generic(format!(\"Invalid URL '{blob_url}': {e}\")))?;\n validate_url(url.as_str())?;\n let registry_domain = url.host_str().unwrap_or(DEFAULT_GHCR_DOMAIN);\n let repo_path = extract_repo_path_from_url(&url).unwrap_or(\"\");\n\n let auth = determine_auth(config, client, registry_domain, repo_path).await?;\n let resp = execute_oci_request(client, blob_url, OCI_LAYER_V1_TYPE, &auth).await?;\n\n // Get total size from Content-Length header if available\n let total_size = resp.content_length();\n\n let tmp = destination_path.with_file_name(format!(\n \".{}.download\",\n destination_path.file_name().unwrap().to_string_lossy()\n ));\n let mut out = File::create(&tmp).map_err(|e| SpsError::Io(Arc::new(e)))?;\n\n let mut stream = resp.bytes_stream();\n let mut bytes_downloaded = 0u64;\n\n while let Some(chunk) = stream.next().await {\n let b = chunk.map_err(|e| SpsError::Http(Arc::new(e)))?;\n std::io::Write::write_all(&mut out, &b).map_err(|e| SpsError::Io(Arc::new(e)))?;\n\n bytes_downloaded += b.len() as u64;\n\n // Call progress callback if provided\n if let Some(ref callback) = progress_callback {\n callback(bytes_downloaded, total_size);\n }\n }\n std::fs::rename(&tmp, destination_path).map_err(|e| SpsError::Io(Arc::new(e)))?;\n\n if !expected_digest.is_empty() {\n match verify_checksum(destination_path, expected_digest) {\n Ok(_) => {\n tracing::debug!(\"OCI Blob checksum verified: {}\", destination_path.display());\n }\n Err(e) => {\n tracing::error!(\n \"OCI Blob checksum mismatch ({}). Deleting downloaded file.\",\n e\n );\n let _ = remove_file(destination_path);\n return Err(e);\n }\n }\n } else {\n tracing::warn!(\n \"Skipping checksum verification for OCI blob {} - no checksum provided.\",\n destination_path.display()\n );\n }\n\n debug!(\"Blob saved to {}\", destination_path.display());\n Ok(())\n}\n\npub async fn fetch_oci_manifest_index(\n manifest_url: &str,\n config: &Config,\n client: &Client,\n) -> Result {\n fetch_oci_resource(manifest_url, OCI_MANIFEST_V1_TYPE, config, client).await\n}\n\npub fn build_oci_client() -> Result {\n Client::builder()\n .user_agent(USER_AGENT_STRING)\n .connect_timeout(Duration::from_secs(CONNECT_TIMEOUT_SECS))\n .timeout(Duration::from_secs(REQUEST_TIMEOUT_SECS))\n .redirect(reqwest::redirect::Policy::default())\n .build()\n .map_err(|e| SpsError::Http(Arc::new(e)))\n}\n\nfn extract_repo_path_from_url(url: &Url) -> Option<&str> {\n url.path()\n .trim_start_matches('/')\n .trim_start_matches(\"v2/\")\n .split(\"/manifests/\")\n .next()\n .and_then(|s| s.split(\"/blobs/\").next())\n .filter(|s| !s.is_empty())\n}\n\nasync fn determine_auth(\n config: &Config,\n client: &Client,\n registry_domain: &str,\n repo_path: &str,\n) -> Result {\n if let Some(token) = &config.docker_registry_token {\n debug!(\"Using explicit bearer for {}\", registry_domain);\n return Ok(OciAuth::ExplicitBearer {\n token: token.clone(),\n });\n }\n if let Some(basic) = &config.docker_registry_basic_auth {\n debug!(\"Using explicit basic auth for {}\", registry_domain);\n return Ok(OciAuth::Basic {\n encoded: basic.clone(),\n });\n }\n\n if registry_domain.eq_ignore_ascii_case(DEFAULT_GHCR_DOMAIN) && !repo_path.is_empty() {\n debug!(\n \"Anonymous token fetch for {} scope={}\",\n registry_domain, repo_path\n );\n match fetch_anonymous_token(client, registry_domain, repo_path).await {\n Ok(t) => return Ok(OciAuth::AnonymousBearer { token: t }),\n Err(e) => debug!(\"Anon token failed, proceeding unauthenticated: {}\", e),\n }\n }\n Ok(OciAuth::None)\n}\n\nasync fn fetch_anonymous_token(\n client: &Client,\n registry_domain: &str,\n repo_path: &str,\n) -> Result {\n let endpoint = if registry_domain.eq_ignore_ascii_case(DEFAULT_GHCR_DOMAIN) {\n DEFAULT_GHCR_TOKEN_ENDPOINT.to_string()\n } else {\n format!(\"https://{registry_domain}/token\")\n };\n let scope = format!(\"repository:{repo_path}:pull\");\n let token_url = format!(\"{endpoint}?service={registry_domain}&scope={scope}\");\n\n const MAX_RETRIES: u8 = 3;\n let base_delay = Duration::from_millis(200);\n let mut delay = base_delay;\n // Use a Sendable RNG\n let mut rng = SmallRng::from_os_rng();\n\n for attempt in 0..=MAX_RETRIES {\n debug!(\n \"Token attempt {}/{} from {}\",\n attempt + 1,\n MAX_RETRIES + 1,\n token_url\n );\n\n match client.get(&token_url).send().await {\n Ok(resp) if resp.status().is_success() => {\n let tok: OciTokenResponse = resp\n .json()\n .await\n .map_err(|e| SpsError::ApiRequestError(format!(\"Parse token response: {e}\")))?;\n return Ok(tok.token);\n }\n Ok(resp) => {\n let code = resp.status();\n let body = resp.text().await.unwrap_or_default();\n error!(\"Token fetch {}: {} – {}\", attempt + 1, code, body);\n if !code.is_server_error() || attempt == MAX_RETRIES {\n return Err(SpsError::Api(format!(\"Token endpoint {code}: {body}\")));\n }\n }\n Err(e) => {\n error!(\"Network error on token fetch {}: {}\", attempt + 1, e);\n if attempt == MAX_RETRIES {\n return Err(SpsError::Http(Arc::new(e)));\n }\n }\n }\n\n let jitter = rng.random_range(0..(base_delay.as_millis() as u64 / 2));\n tokio::time::sleep(delay + Duration::from_millis(jitter)).await;\n delay *= 2;\n }\n\n Err(SpsError::Api(format!(\n \"Failed to fetch OCI token after {} attempts\",\n MAX_RETRIES + 1\n )))\n}\n\nasync fn execute_oci_request(\n client: &Client,\n url: &str,\n accept: &str,\n auth: &OciAuth,\n) -> Result {\n debug!(\"OCI request → {} (Accept: {})\", url, accept);\n let mut req = client.get(url).header(ACCEPT, accept);\n match auth {\n OciAuth::AnonymousBearer { token } | OciAuth::ExplicitBearer { token }\n if !token.is_empty() =>\n {\n req = req.header(AUTHORIZATION, format!(\"Bearer {token}\"))\n }\n OciAuth::Basic { encoded } if !encoded.is_empty() => {\n req = req.header(AUTHORIZATION, format!(\"Basic {encoded}\"))\n }\n _ => {}\n }\n\n let resp = req.send().await.map_err(|e| SpsError::Http(Arc::new(e)))?;\n let status = resp.status();\n if status.is_success() {\n Ok(resp)\n } else {\n let body = resp.text().await.unwrap_or_default();\n error!(\"OCI {} ⇒ {} – {}\", url, status, body);\n let err = match status {\n StatusCode::UNAUTHORIZED => SpsError::Api(format!(\"Auth required: {status}\")),\n StatusCode::FORBIDDEN => SpsError::Api(format!(\"Permission denied: {status}\")),\n StatusCode::NOT_FOUND => SpsError::NotFound(format!(\"Not found: {status}\")),\n _ => SpsError::Api(format!(\"HTTP {status} – {body}\")),\n };\n Err(err)\n }\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/pkg.rs", "use std::fs;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::cask::Cask;\nuse tracing::{debug, error};\n\nuse crate::install::cask::InstalledArtifact; // Artifact type alias is just Value\n\n/// Installs a PKG file and returns details of artifacts created/managed.\npub fn install_pkg_from_path(\n cask: &Cask,\n pkg_path: &Path,\n cask_version_install_path: &Path, // e.g., /opt/homebrew/Caskroom/foo/1.2.3\n _config: &Config, // Keep for potential future use\n) -> Result> {\n // <-- Return type changed\n debug!(\"Installing pkg file: {}\", pkg_path.display());\n\n if !pkg_path.exists() || !pkg_path.is_file() {\n return Err(SpsError::NotFound(format!(\n \"Package file not found or is not a file: {}\",\n pkg_path.display()\n )));\n }\n\n let pkg_name = pkg_path\n .file_name()\n .ok_or_else(|| SpsError::Generic(format!(\"Invalid pkg path: {}\", pkg_path.display())))?;\n\n // --- Prepare list for artifacts ---\n let mut installed_artifacts: Vec = Vec::new();\n\n // --- Copy PKG to Caskroom for Reference ---\n let caskroom_pkg_path = cask_version_install_path.join(pkg_name);\n debug!(\n \"Copying pkg to caskroom for reference: {}\",\n caskroom_pkg_path.display()\n );\n if let Some(parent) = caskroom_pkg_path.parent() {\n fs::create_dir_all(parent).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed create parent dir {}: {}\", parent.display(), e),\n )))\n })?;\n }\n if let Err(e) = fs::copy(pkg_path, &caskroom_pkg_path) {\n error!(\n \"Failed to copy PKG {} to {}: {}\",\n pkg_path.display(),\n caskroom_pkg_path.display(),\n e\n );\n return Err(SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed copy PKG to caskroom: {e}\"),\n ))));\n } else {\n // Record the reference copy artifact\n installed_artifacts.push(InstalledArtifact::CaskroomReference {\n path: caskroom_pkg_path.clone(),\n });\n }\n\n // --- Run Installer ---\n debug!(\"Running installer (this may require sudo)\");\n debug!(\n \"Executing: sudo installer -pkg {} -target /\",\n pkg_path.display()\n );\n let output = Command::new(\"sudo\")\n .arg(\"installer\")\n .arg(\"-pkg\")\n .arg(pkg_path)\n .arg(\"-target\")\n .arg(\"/\")\n .output()\n .map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed to execute sudo installer: {e}\"),\n )))\n })?;\n\n if !output.status.success() {\n let stderr = String::from_utf8_lossy(&output.stderr);\n error!(\"sudo installer failed ({}): {}\", output.status, stderr);\n // Don't clean up the reference copy here, let the main process handle directory removal on\n // failure\n return Err(SpsError::InstallError(format!(\n \"Package installation failed for {}: {}\",\n pkg_path.display(),\n stderr\n )));\n }\n debug!(\"Successfully ran installer command.\");\n let stdout = String::from_utf8_lossy(&output.stdout);\n if !stdout.trim().is_empty() {\n debug!(\"Installer stdout:\\n{}\", stdout);\n }\n\n // --- Record PkgUtil Receipts (based on cask definition) ---\n if let Some(artifacts) = &cask.artifacts {\n // artifacts is Option>\n for artifact_value in artifacts.iter() {\n if let Some(uninstall_array) =\n artifact_value.get(\"uninstall\").and_then(|v| v.as_array())\n {\n for stanza_value in uninstall_array {\n if let Some(stanza_obj) = stanza_value.as_object() {\n if let Some(pkgutil_id) = stanza_obj.get(\"pkgutil\").and_then(|v| v.as_str())\n {\n debug!(\"Found pkgutil ID to record: {}\", pkgutil_id);\n // Check for duplicates before adding\n let new_artifact = InstalledArtifact::PkgUtilReceipt {\n id: pkgutil_id.to_string(),\n };\n if !installed_artifacts.contains(&new_artifact) {\n // Need PartialEq for InstalledArtifact\n installed_artifacts.push(new_artifact);\n }\n }\n // Consider other uninstall keys like launchctl, delete?\n }\n }\n }\n // Optionally check \"zap\" stanzas too\n }\n }\n debug!(\"Successfully installed pkg: {}\", pkg_path.display());\n Ok(installed_artifacts) // <-- Return collected artifacts\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/binary.rs", "// ===== sps-core/src/build/cask/artifacts/binary.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Installs `binary` artifacts, which can be declared as:\n/// - a simple string: `\"foo\"` (source and target both `\"foo\"`)\n/// - a map: `{ \"source\": \"path/in/stage\", \"target\": \"name\", \"chmod\": \"0755\" }`\n/// - a map with just `\"target\"`: automatically generate a wrapper script\n///\n/// Copies or symlinks executables into the prefix bin directory,\n/// and records both the link and caskroom reference.\npub fn install_binary(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"binary\") {\n // Normalize into an array\n let arr = if let Some(arr) = entries.as_array() {\n arr.clone()\n } else {\n vec![entries.clone()]\n };\n\n let bin_dir = config.bin_dir();\n fs::create_dir_all(&bin_dir)?;\n\n for entry in arr {\n // Determine source, target, and optional chmod\n let (source_rel, target_name, chmod) = if let Some(tgt) = entry.as_str() {\n // simple form: \"foo\"\n (tgt.to_string(), tgt.to_string(), None)\n } else if let Some(m) = entry.as_object() {\n let target = m\n .get(\"target\")\n .and_then(|v| v.as_str())\n .map(String::from)\n .ok_or_else(|| {\n SpsError::InstallError(format!(\n \"Binary artifact missing 'target': {m:?}\"\n ))\n })?;\n\n let chmod = m.get(\"chmod\").and_then(|v| v.as_str()).map(String::from);\n\n // If `source` is provided, use it; otherwise generate wrapper\n let source = if let Some(src) = m.get(\"source\").and_then(|v| v.as_str())\n {\n src.to_string()\n } else {\n // generate wrapper script in caskroom\n let wrapper_name = format!(\"{target}.wrapper.sh\");\n let wrapper_path = cask_version_install_path.join(&wrapper_name);\n\n // assume the real executable lives inside the .app bundle\n let app_name = format!(\"{}.app\", cask.display_name());\n let exe_path =\n format!(\"/Applications/{app_name}/Contents/MacOS/{target}\");\n\n let script =\n format!(\"#!/usr/bin/env bash\\nexec \\\"{exe_path}\\\" \\\"$@\\\"\\n\");\n fs::write(&wrapper_path, script)?;\n Command::new(\"chmod\")\n .arg(\"+x\")\n .arg(&wrapper_path)\n .status()?;\n\n wrapper_name\n };\n\n (source, target, chmod)\n } else {\n debug!(\"Invalid binary artifact entry: {:?}\", entry);\n continue;\n };\n\n let src_path = stage_path.join(&source_rel);\n if !src_path.exists() {\n debug!(\"Binary source '{}' not found, skipping\", src_path.display());\n continue;\n }\n\n // Link into bin_dir\n let link_path = bin_dir.join(&target_name);\n let _ = fs::remove_file(&link_path);\n debug!(\n \"Linking binary '{}' → '{}'\",\n src_path.display(),\n link_path.display()\n );\n symlink(&src_path, &link_path)?;\n\n // Apply chmod if specified\n if let Some(mode) = chmod.as_deref() {\n let _ = Command::new(\"chmod\").arg(mode).arg(&link_path).status();\n }\n\n installed.push(InstalledArtifact::BinaryLink {\n link_path: link_path.clone(),\n target_path: src_path.clone(),\n });\n\n // Also create a Caskroom symlink for reference\n let caskroom_link = cask_version_install_path.join(&target_name);\n let _ = remove_path_robustly(&caskroom_link, config, true);\n symlink(&link_path, &caskroom_link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: caskroom_link,\n target_path: link_path.clone(),\n });\n }\n\n // Only one binary stanza per cask\n break;\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/devtools.rs", "use std::env;\nuse std::path::PathBuf;\nuse std::process::{Command, Stdio};\n\nuse sps_common::error::{Result, SpsError};\nuse tracing::debug;\nuse which;\n\npub fn find_compiler(name: &str) -> Result {\n let env_var_name = match name {\n \"cc\" => \"CC\",\n \"c++\" | \"cxx\" => \"CXX\",\n _ => \"\",\n };\n if !env_var_name.is_empty() {\n if let Ok(compiler_path) = env::var(env_var_name) {\n let path = PathBuf::from(compiler_path);\n if path.is_file() {\n debug!(\n \"Using compiler from env var {}: {}\",\n env_var_name,\n path.display()\n );\n return Ok(path);\n } else {\n debug!(\n \"Env var {} points to non-existent file: {}\",\n env_var_name,\n path.display()\n );\n }\n }\n }\n\n if cfg!(target_os = \"macos\") {\n debug!(\"Attempting to find '{name}' using xcrun\");\n let output = Command::new(\"xcrun\")\n .arg(\"--find\")\n .arg(name)\n .stderr(Stdio::piped())\n .output();\n\n match output {\n Ok(out) if out.status.success() => {\n let path_str = String::from_utf8_lossy(&out.stdout).trim().to_string();\n if !path_str.is_empty() {\n let path = PathBuf::from(path_str);\n if path.is_file() {\n debug!(\"Found compiler via xcrun: {}\", path.display());\n return Ok(path);\n } else {\n debug!(\n \"xcrun found '{}' but path doesn't exist or isn't a file: {}\",\n name,\n path.display()\n );\n }\n } else {\n debug!(\"xcrun found '{name}' but returned empty path.\");\n }\n }\n Ok(out) => {\n let stderr = String::from_utf8_lossy(&out.stderr);\n debug!(\"xcrun failed to find '{}': {}\", name, stderr.trim());\n }\n Err(e) => {\n debug!(\"Failed to execute xcrun: {e}. Falling back to PATH search.\");\n }\n }\n }\n\n debug!(\"Falling back to searching PATH for '{name}'\");\n which::which(name).map_err(|e| {\n SpsError::BuildEnvError(format!(\"Failed to find compiler '{name}' on PATH: {e}\"))\n })\n}\n\npub fn find_sdk_path() -> Result {\n if cfg!(target_os = \"macos\") {\n debug!(\"Attempting to find macOS SDK path using xcrun\");\n let output = Command::new(\"xcrun\")\n .arg(\"--show-sdk-path\")\n .stderr(Stdio::piped())\n .output();\n\n match output {\n Ok(out) if out.status.success() => {\n let path_str = String::from_utf8_lossy(&out.stdout).trim().to_string();\n if path_str.is_empty() || path_str == \"/\" {\n return Err(SpsError::BuildEnvError(\n \"xcrun returned empty or invalid SDK path. Is Xcode or Command Line Tools installed correctly?\".to_string()\n ));\n }\n let sdk_path = PathBuf::from(path_str);\n if !sdk_path.exists() {\n return Err(SpsError::BuildEnvError(format!(\n \"SDK path reported by xcrun does not exist: {}\",\n sdk_path.display()\n )));\n }\n debug!(\"Found SDK path: {}\", sdk_path.display());\n Ok(sdk_path)\n }\n Ok(out) => {\n let stderr = String::from_utf8_lossy(&out.stderr);\n Err(SpsError::BuildEnvError(format!(\n \"xcrun failed to find SDK path: {}\",\n stderr.trim()\n )))\n }\n Err(e) => {\n Err(SpsError::BuildEnvError(format!(\n \"Failed to execute 'xcrun --show-sdk-path': {e}. Is Xcode or Command Line Tools installed?\"\n )))\n }\n }\n } else {\n debug!(\"Not on macOS, returning '/' as SDK path placeholder\");\n Ok(PathBuf::from(\"/\"))\n }\n}\n\npub fn get_macos_version() -> Result {\n if cfg!(target_os = \"macos\") {\n debug!(\"Attempting to get macOS version using sw_vers\");\n let output = Command::new(\"sw_vers\")\n .arg(\"-productVersion\")\n .stderr(Stdio::piped())\n .output();\n\n match output {\n Ok(out) if out.status.success() => {\n let version_full = String::from_utf8_lossy(&out.stdout).trim().to_string();\n let version_parts: Vec<&str> = version_full.split('.').collect();\n let version_short = if version_parts.len() >= 2 {\n format!(\"{}.{}\", version_parts[0], version_parts[1])\n } else {\n version_full.clone()\n };\n debug!(\"Found macOS version: {version_full} (short: {version_short})\");\n Ok(version_short)\n }\n Ok(out) => {\n let stderr = String::from_utf8_lossy(&out.stderr);\n Err(SpsError::BuildEnvError(format!(\n \"sw_vers failed to get product version: {}\",\n stderr.trim()\n )))\n }\n Err(e) => Err(SpsError::BuildEnvError(format!(\n \"Failed to execute 'sw_vers -productVersion': {e}\"\n ))),\n }\n } else {\n debug!(\"Not on macOS, returning '0.0' as version placeholder\");\n Ok(String::from(\"0.0\"))\n }\n}\n\npub fn get_arch_flag() -> String {\n if cfg!(target_os = \"macos\") {\n if cfg!(target_arch = \"x86_64\") {\n debug!(\"Detected target arch: x86_64\");\n \"-arch x86_64\".to_string()\n } else if cfg!(target_arch = \"aarch64\") {\n debug!(\"Detected target arch: aarch64 (arm64)\");\n \"-arch arm64\".to_string()\n } else {\n let arch = env::consts::ARCH;\n debug!(\n \"Unknown target architecture on macOS: {arch}, cannot determine -arch flag. Build might fail.\"\n );\n // Provide no flag in this unknown case? Or default to native?\n String::new()\n }\n } else {\n debug!(\"Not on macOS, returning empty arch flag.\");\n String::new()\n }\n}\n"], ["/sps/sps-common/src/config.rs", "// sps-common/src/config.rs\nuse std::env;\nuse std::path::{Path, PathBuf};\n\nuse directories::UserDirs; // Ensure this crate is in sps-common/Cargo.toml\nuse tracing::debug;\n\nuse super::error::Result; // Assuming SpsResult is Result from super::error\n\n// This constant will serve as a fallback if HOMEBREW_PREFIX is not set or is empty.\nconst DEFAULT_FALLBACK_SPS_ROOT: &str = \"/opt/homebrew\";\nconst SPS_ROOT_MARKER_FILENAME: &str = \".sps_root_v1\";\n\n#[derive(Debug, Clone)]\npub struct Config {\n pub sps_root: PathBuf, // Public for direct construction in main for init if needed\n pub api_base_url: String,\n pub artifact_domain: Option,\n pub docker_registry_token: Option,\n pub docker_registry_basic_auth: Option,\n pub github_api_token: Option,\n}\n\nimpl Config {\n pub fn load() -> Result {\n debug!(\"Loading sps configuration\");\n\n // Try to get SPS_ROOT from HOMEBREW_PREFIX environment variable.\n // Fallback to DEFAULT_FALLBACK_SPS_ROOT if not set or empty.\n let sps_root_str = env::var(\"HOMEBREW_PREFIX\").ok().filter(|s| !s.is_empty())\n .unwrap_or_else(|| {\n debug!(\n \"HOMEBREW_PREFIX environment variable not set or empty, falling back to default: {}\",\n DEFAULT_FALLBACK_SPS_ROOT\n );\n DEFAULT_FALLBACK_SPS_ROOT.to_string()\n });\n\n let sps_root_path = PathBuf::from(&sps_root_str);\n debug!(\"Effective SPS_ROOT set to: {}\", sps_root_path.display());\n\n let api_base_url = \"https://formulae.brew.sh/api\".to_string();\n\n let artifact_domain = env::var(\"HOMEBREW_ARTIFACT_DOMAIN\").ok();\n let docker_registry_token = env::var(\"HOMEBREW_DOCKER_REGISTRY_TOKEN\").ok();\n let docker_registry_basic_auth = env::var(\"HOMEBREW_DOCKER_REGISTRY_BASIC_AUTH_TOKEN\").ok();\n let github_api_token = env::var(\"HOMEBREW_GITHUB_API_TOKEN\").ok();\n\n debug!(\"Configuration loaded successfully.\");\n Ok(Self {\n sps_root: sps_root_path,\n api_base_url,\n artifact_domain,\n docker_registry_token,\n docker_registry_basic_auth,\n github_api_token,\n })\n }\n\n pub fn sps_root(&self) -> &Path {\n &self.sps_root\n }\n\n pub fn bin_dir(&self) -> PathBuf {\n self.sps_root.join(\"bin\")\n }\n\n pub fn cellar_dir(&self) -> PathBuf {\n self.sps_root.join(\"Cellar\") // Changed from \"cellar\" to \"Cellar\" to match Homebrew\n }\n\n pub fn cask_room_dir(&self) -> PathBuf {\n self.sps_root.join(\"Caskroom\") // Changed from \"cask_room\" to \"Caskroom\"\n }\n\n pub fn cask_store_dir(&self) -> PathBuf {\n self.sps_root.join(\"sps_cask_store\")\n }\n\n pub fn opt_dir(&self) -> PathBuf {\n self.sps_root.join(\"opt\")\n }\n\n pub fn taps_dir(&self) -> PathBuf {\n self.sps_root.join(\"Library/Taps\") // Adjusted to match Homebrew structure\n }\n\n pub fn cache_dir(&self) -> PathBuf {\n self.sps_root.join(\"sps_cache\")\n }\n\n pub fn logs_dir(&self) -> PathBuf {\n self.sps_root.join(\"sps_logs\")\n }\n\n pub fn tmp_dir(&self) -> PathBuf {\n self.sps_root.join(\"tmp\")\n }\n\n pub fn state_dir(&self) -> PathBuf {\n self.sps_root.join(\"sps_state\")\n }\n\n pub fn man_base_dir(&self) -> PathBuf {\n self.sps_root.join(\"share\").join(\"man\")\n }\n\n pub fn sps_root_marker_path(&self) -> PathBuf {\n self.sps_root.join(SPS_ROOT_MARKER_FILENAME)\n }\n\n pub fn applications_dir(&self) -> PathBuf {\n if cfg!(target_os = \"macos\") {\n PathBuf::from(\"/Applications\")\n } else {\n self.home_dir().join(\"Applications\")\n }\n }\n\n pub fn formula_cellar_dir(&self, formula_name: &str) -> PathBuf {\n self.cellar_dir().join(formula_name)\n }\n\n pub fn formula_keg_path(&self, formula_name: &str, version_str: &str) -> PathBuf {\n self.formula_cellar_dir(formula_name).join(version_str)\n }\n\n pub fn formula_opt_path(&self, formula_name: &str) -> PathBuf {\n self.opt_dir().join(formula_name)\n }\n\n pub fn cask_room_token_path(&self, cask_token: &str) -> PathBuf {\n self.cask_room_dir().join(cask_token)\n }\n\n pub fn cask_store_token_path(&self, cask_token: &str) -> PathBuf {\n self.cask_store_dir().join(cask_token)\n }\n\n pub fn cask_store_version_path(&self, cask_token: &str, version_str: &str) -> PathBuf {\n self.cask_store_token_path(cask_token).join(version_str)\n }\n\n pub fn cask_store_app_path(\n &self,\n cask_token: &str,\n version_str: &str,\n app_name: &str,\n ) -> PathBuf {\n self.cask_store_version_path(cask_token, version_str)\n .join(app_name)\n }\n\n pub fn cask_room_version_path(&self, cask_token: &str, version_str: &str) -> PathBuf {\n self.cask_room_token_path(cask_token).join(version_str)\n }\n\n pub fn home_dir(&self) -> PathBuf {\n UserDirs::new().map_or_else(|| PathBuf::from(\"/\"), |ud| ud.home_dir().to_path_buf())\n }\n\n pub fn get_tap_path(&self, name: &str) -> Option {\n let parts: Vec<&str> = name.split('/').collect();\n if parts.len() == 2 {\n Some(\n self.taps_dir()\n .join(parts[0]) // user, e.g., homebrew\n .join(format!(\"homebrew-{}\", parts[1])), // repo, e.g., homebrew-core\n )\n } else {\n None\n }\n }\n\n pub fn get_formula_path_from_tap(&self, tap_name: &str, formula_name: &str) -> Option {\n self.get_tap_path(tap_name).and_then(|tap_path| {\n let json_path = tap_path\n .join(\"Formula\") // Standard Homebrew tap structure\n .join(format!(\"{formula_name}.json\"));\n if json_path.exists() {\n return Some(json_path);\n }\n // Fallback to .rb for completeness, though API primarily gives JSON\n let rb_path = tap_path.join(\"Formula\").join(format!(\"{formula_name}.rb\"));\n if rb_path.exists() {\n return Some(rb_path);\n }\n None\n })\n }\n}\n\nimpl Default for Config {\n fn default() -> Self {\n Self::load().expect(\"Failed to load default configuration\")\n }\n}\n\npub fn load_config() -> Result {\n Config::load()\n}\n"], ["/sps/sps-core/src/pipeline/engine.rs", "use std::sync::atomic::{AtomicUsize, Ordering};\nuse std::sync::Arc;\n\nuse crossbeam_channel::Receiver as CrossbeamReceiver;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::error::Result as SpsResult;\nuse sps_common::pipeline::{PipelineEvent, WorkerJob};\nuse threadpool::ThreadPool;\nuse tokio::sync::broadcast;\nuse tracing::{debug, instrument};\n\nuse super::worker;\n\n#[instrument(skip_all, name = \"core_worker_manager\")]\npub fn start_worker_pool_manager(\n config: Config,\n cache: Arc,\n worker_job_rx: CrossbeamReceiver,\n event_tx: broadcast::Sender,\n success_count: Arc,\n fail_count: Arc,\n) -> SpsResult<()> {\n let num_workers = std::cmp::max(1, num_cpus::get_physical().saturating_sub(1)).min(6);\n let pool = ThreadPool::new(num_workers);\n debug!(\n \"Core worker pool manager started with {} workers.\",\n num_workers\n );\n debug!(\"Worker pool created.\");\n\n for worker_job in worker_job_rx {\n let job_id = worker_job.request.target_id.clone();\n debug!(\n \"[{}] Received job from channel, preparing to submit to pool.\",\n job_id\n );\n\n let config_clone = config.clone();\n let cache_clone = Arc::clone(&cache);\n let event_tx_clone = event_tx.clone();\n let success_count_clone = Arc::clone(&success_count);\n let fail_count_clone = Arc::clone(&fail_count);\n\n let _ = event_tx_clone.send(PipelineEvent::JobProcessingStarted {\n target_id: job_id.clone(),\n });\n\n debug!(\"[{}] Submitting job to worker pool.\", job_id);\n\n pool.execute(move || {\n let job_result = worker::execute_sync_job(\n worker_job,\n &config_clone,\n cache_clone,\n event_tx_clone.clone(),\n );\n let job_id_for_log = job_id.clone();\n debug!(\n \"[{}] Worker job execution finished (execute_sync_job returned), result ok: {}\",\n job_id_for_log,\n job_result.is_ok()\n );\n\n let job_id_for_log = job_id.clone();\n match job_result {\n Ok((final_action, pkg_type)) => {\n success_count_clone.fetch_add(1, Ordering::Relaxed);\n debug!(\"[{}] Worker finished successfully.\", job_id);\n let _ = event_tx_clone.send(PipelineEvent::JobSuccess {\n target_id: job_id,\n action: final_action,\n pkg_type,\n });\n debug!(\"[{}] Worker result event sent.\", job_id_for_log);\n }\n Err(boxed) => {\n let (final_action, err) = *boxed;\n fail_count_clone.fetch_add(1, Ordering::Relaxed);\n // Error is sent via JobFailed event and displayed in status.rs\n let _ = event_tx_clone.send(PipelineEvent::JobFailed {\n target_id: job_id,\n action: final_action,\n error: err.to_string(),\n });\n debug!(\"[{}] Worker result event sent.\", job_id_for_log);\n }\n }\n debug!(\"[{}] Worker closure scope ending.\", job_id_for_log);\n });\n }\n pool.join();\n Ok(())\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/zap.rs", "// ===== sps-core/src/build/cask/artifacts/zap.rs =====\n\nuse std::fs;\nuse std::path::{Path, PathBuf}; // Import Path\nuse std::process::{Command, Stdio};\n\nuse regex::Regex;\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::InstalledArtifact;\n\n/// Implements the `zap` stanza by performing deep-clean actions\n/// such as trash, delete, rmdir, pkgutil forget, launchctl unload,\n/// and arbitrary scripts, matching Homebrew's Cask behavior.\npub fn install_zap(cask: &Cask, config: &Config) -> Result> {\n let mut artifacts: Vec = Vec::new();\n let home = config.home_dir();\n\n if let Some(entries) = &cask.artifacts {\n for entry in entries {\n if let Some(obj) = entry.as_object() {\n if let Some(zaps) = obj.get(\"zap\").and_then(|v| v.as_array()) {\n for zap_map in zaps {\n if let Some(zap_obj) = zap_map.as_object() {\n for (key, val) in zap_obj {\n match key.as_str() {\n \"trash\" => {\n if let Some(arr) = val.as_array() {\n for item in arr.iter().filter_map(|v| v.as_str()) {\n let target = expand_tilde(item, &home); // Pass &Path\n if !is_safe_path(&target, &home) {\n debug!(\n \"Unsafe trash path {}, skipping\",\n target.display()\n );\n continue;\n }\n debug!(\"Trashing {}...\", target.display());\n let _ = Command::new(\"trash\")\n .arg(&target)\n .stdout(Stdio::null())\n .stderr(Stdio::null())\n .status();\n }\n }\n }\n \"delete\" => {\n if let Some(arr) = val.as_array() {\n for item in arr.iter().filter_map(|v| v.as_str()) {\n let target = expand_tilde(item, &home); // Pass &Path\n if !is_safe_path(&target, &home) {\n debug!(\n \"Unsafe delete path {}, skipping\",\n target.display()\n );\n continue;\n }\n debug!(\"Deleting file {}...\", target.display());\n if let Err(e) = fs::remove_file(&target) {\n if e.kind() != std::io::ErrorKind::NotFound {\n debug!(\n \"Failed to delete {}: {}\",\n target.display(),\n e\n );\n }\n }\n }\n }\n }\n \"rmdir\" => {\n if let Some(arr) = val.as_array() {\n for item in arr.iter().filter_map(|v| v.as_str()) {\n let target = expand_tilde(item, &home); // Pass &Path\n if !is_safe_path(&target, &home) {\n debug!(\n \"Unsafe rmdir path {}, skipping\",\n target.display()\n );\n continue;\n }\n debug!(\n \"Removing directory {}...\",\n target.display()\n );\n if let Err(e) = fs::remove_dir_all(&target) {\n if e.kind() != std::io::ErrorKind::NotFound {\n debug!(\n \"Failed to rmdir {}: {}\",\n target.display(),\n e\n );\n }\n }\n }\n }\n }\n \"pkgutil\" => {\n if let Some(arr) = val.as_array() {\n for item in arr.iter().filter_map(|v| v.as_str()) {\n if !is_valid_pkgid(item) {\n debug!(\n \"Invalid pkgutil id '{}', skipping\",\n item\n );\n continue;\n }\n debug!(\"Forgetting pkgutil receipt {}...\", item);\n let _ = Command::new(\"pkgutil\")\n .arg(\"--forget\")\n .arg(item)\n .stdout(Stdio::null())\n .stderr(Stdio::null())\n .status();\n artifacts.push(InstalledArtifact::PkgUtilReceipt {\n id: item.to_string(),\n });\n }\n }\n }\n \"launchctl\" => {\n if let Some(arr) = val.as_array() {\n for label in arr.iter().filter_map(|v| v.as_str()) {\n if !is_valid_label(label) {\n debug!(\n \"Invalid launchctl label '{}', skipping\",\n label\n );\n continue;\n }\n let plist = home // Use expanded home\n .join(\"Library/LaunchAgents\")\n .join(format!(\"{label}.plist\"));\n if !is_safe_path(&plist, &home) {\n debug!(\n \"Unsafe plist path {} for label {}, skipping\",\n plist.display(),\n label\n );\n continue;\n }\n debug!(\n \"Unloading launchctl {}...\",\n plist.display()\n );\n let _ = Command::new(\"launchctl\")\n .arg(\"unload\")\n .arg(&plist)\n .stdout(Stdio::null())\n .stderr(Stdio::null())\n .status();\n artifacts.push(InstalledArtifact::Launchd {\n label: label.to_string(),\n path: Some(plist),\n });\n }\n }\n }\n \"script\" => {\n if let Some(cmd) = val.as_str() {\n if !is_valid_command(cmd) {\n debug!(\n \"Invalid zap script command '{}', skipping\",\n cmd\n );\n continue;\n }\n debug!(\"Running zap script: {}...\", cmd);\n let _ = Command::new(\"sh\")\n .arg(\"-c\")\n .arg(cmd)\n .stdout(Stdio::null())\n .stderr(Stdio::null())\n .status();\n }\n }\n \"signal\" => {\n if let Some(arr) = val.as_array() {\n for cmd in arr.iter().filter_map(|v| v.as_str()) {\n if !is_valid_command(cmd) {\n debug!(\n \"Invalid signal command '{}', skipping\",\n cmd\n );\n continue;\n }\n debug!(\"Running signal command: {}...\", cmd);\n let _ = Command::new(\"sh\")\n .arg(\"-c\")\n .arg(cmd)\n .stdout(Stdio::null())\n .stderr(Stdio::null())\n .status();\n }\n }\n }\n _ => debug!(\"Unsupported zap key '{}', skipping\", key),\n }\n }\n }\n }\n // Only process the first \"zap\" stanza found\n break;\n }\n }\n }\n }\n\n Ok(artifacts)\n}\n\n// New helper functions to validate paths and strings.\nfn is_safe_path(path: &Path, home: &Path) -> bool {\n if path\n .components()\n .any(|c| matches!(c, std::path::Component::ParentDir))\n {\n return false;\n }\n let path_str = path.to_string_lossy();\n if path.is_absolute()\n && (path_str.starts_with(\"/Applications\") || path_str.starts_with(\"/Library\"))\n {\n return true;\n }\n if path.starts_with(home) {\n return true;\n }\n if path_str.contains(\"Caskroom/Cellar\") {\n return true;\n }\n false\n}\n\nfn is_valid_pkgid(pkgid: &str) -> bool {\n let re = Regex::new(r\"^[a-zA-Z0-9.-]+$\").unwrap();\n re.is_match(pkgid)\n}\n\nfn is_valid_label(label: &str) -> bool {\n let re = Regex::new(r\"^[a-zA-Z0-9.-]+$\").unwrap();\n re.is_match(label)\n}\n\nfn is_valid_command(cmd: &str) -> bool {\n let re = Regex::new(r\"^[a-zA-Z0-9\\s\\-_./]+$\").unwrap();\n re.is_match(cmd)\n}\n\n/// Expand a path that may start with '~' to the user's home directory\nfn expand_tilde(path: &str, home: &Path) -> PathBuf {\n if let Some(stripped) = path.strip_prefix(\"~/\") {\n home.join(stripped)\n } else {\n PathBuf::from(path)\n }\n}\n"], ["/sps/sps-common/src/model/tap.rs", "// tap/tap.rs - Basic tap functionality // Should probably be in model module\n\nuse std::path::PathBuf;\n\nuse tracing::debug;\n\nuse crate::error::{Result, SpsError};\n\n/// Represents a source of packages (formulas and casks)\npub struct Tap {\n /// The user part of the tap name (e.g., \"homebrew\" in \"homebrew/core\")\n pub user: String,\n\n /// The repository part of the tap name (e.g., \"core\" in \"homebrew/core\")\n pub repo: String,\n\n /// The full path to the tap directory\n pub path: PathBuf,\n}\n\nimpl Tap {\n /// Create a new tap from user/repo format\n pub fn new(name: &str) -> Result {\n let parts: Vec<&str> = name.split('/').collect();\n if parts.len() != 2 {\n return Err(SpsError::Generic(format!(\"Invalid tap name: {name}\")));\n }\n let user = parts[0].to_string();\n let repo = parts[1].to_string();\n let prefix = if cfg!(target_arch = \"aarch64\") {\n PathBuf::from(\"/opt/homebrew\")\n } else {\n PathBuf::from(\"/usr/local\")\n };\n let path = prefix\n .join(\"Library/Taps\")\n .join(&user)\n .join(format!(\"homebrew-{repo}\"));\n Ok(Self { user, repo, path })\n }\n\n /// Update this tap by pulling latest changes\n pub fn update(&self) -> Result<()> {\n use git2::{FetchOptions, Repository};\n\n let repo = Repository::open(&self.path)\n .map_err(|e| SpsError::Generic(format!(\"Failed to open tap repository: {e}\")))?;\n\n // Fetch updates from origin\n let mut remote = repo\n .find_remote(\"origin\")\n .map_err(|e| SpsError::Generic(format!(\"Failed to find remote 'origin': {e}\")))?;\n\n let mut fetch_options = FetchOptions::new();\n remote\n .fetch(\n &[\"refs/heads/*:refs/heads/*\"],\n Some(&mut fetch_options),\n None,\n )\n .map_err(|e| SpsError::Generic(format!(\"Failed to fetch updates: {e}\")))?;\n\n // Merge changes\n let fetch_head = repo\n .find_reference(\"FETCH_HEAD\")\n .map_err(|e| SpsError::Generic(format!(\"Failed to find FETCH_HEAD: {e}\")))?;\n\n let fetch_commit = repo\n .reference_to_annotated_commit(&fetch_head)\n .map_err(|e| SpsError::Generic(format!(\"Failed to get commit from FETCH_HEAD: {e}\")))?;\n\n let analysis = repo\n .merge_analysis(&[&fetch_commit])\n .map_err(|e| SpsError::Generic(format!(\"Failed to analyze merge: {e}\")))?;\n\n if analysis.0.is_up_to_date() {\n debug!(\"Already up-to-date\");\n return Ok(());\n }\n\n if analysis.0.is_fast_forward() {\n let mut reference = repo\n .find_reference(\"refs/heads/master\")\n .map_err(|e| SpsError::Generic(format!(\"Failed to find master branch: {e}\")))?;\n reference\n .set_target(fetch_commit.id(), \"Fast-forward\")\n .map_err(|e| SpsError::Generic(format!(\"Failed to fast-forward: {e}\")))?;\n repo.set_head(\"refs/heads/master\")\n .map_err(|e| SpsError::Generic(format!(\"Failed to set HEAD: {e}\")))?;\n repo.checkout_head(Some(git2::build::CheckoutBuilder::default().force()))\n .map_err(|e| SpsError::Generic(format!(\"Failed to checkout: {e}\")))?;\n } else {\n return Err(SpsError::Generic(\n \"Tap requires merge but automatic merging is not implemented\".to_string(),\n ));\n }\n\n Ok(())\n }\n\n /// Remove this tap by deleting its local repository\n pub fn remove(&self) -> Result<()> {\n if !self.path.exists() {\n return Err(SpsError::NotFound(format!(\n \"Tap {} is not installed\",\n self.full_name()\n )));\n }\n debug!(\"Removing tap {}\", self.full_name());\n std::fs::remove_dir_all(&self.path).map_err(|e| {\n SpsError::Generic(format!(\"Failed to remove tap {}: {}\", self.full_name(), e))\n })\n }\n\n /// Get the full name of the tap (user/repo)\n pub fn full_name(&self) -> String {\n format!(\"{}/{}\", self.user, self.repo)\n }\n\n /// Check if this tap is installed locally\n pub fn is_installed(&self) -> bool {\n self.path.exists()\n }\n}\n"], ["/sps/sps-core/src/uninstall/common.rs", "// sps-core/src/uninstall/common.rs\n\nuse std::path::{Component, Path, PathBuf};\nuse std::process::Command;\nuse std::{fs, io};\n\nuse sps_common::config::Config;\nuse tracing::{debug, error, warn};\n\n#[derive(Debug, Clone, Default)]\npub struct UninstallOptions {\n pub skip_zap: bool,\n}\n\n/// Removes a filesystem artifact (file or directory).\n///\n/// Attempts direct removal. If `use_sudo` is true and direct removal\n/// fails due to permission errors, it will attempt `sudo rm -rf`.\n///\n/// Returns `true` if the artifact is successfully removed or was already gone,\n/// `false` otherwise.\npub(crate) fn remove_filesystem_artifact(path: &Path, use_sudo: bool) -> bool {\n match path.symlink_metadata() {\n Ok(metadata) => {\n let file_type = metadata.file_type();\n // A directory is only a \"real\" directory if it's not a symlink.\n // Symlinks to directories should be removed with remove_file.\n let is_real_dir = file_type.is_dir();\n\n debug!(\n \"Removing filesystem artifact ({}) at: {}\",\n if is_real_dir {\n \"directory\"\n } else if file_type.is_symlink() {\n \"symlink\"\n } else {\n \"file\"\n },\n path.display()\n );\n\n let remove_op = || -> io::Result<()> {\n if is_real_dir {\n fs::remove_dir_all(path)\n } else {\n // This handles both files and symlinks\n fs::remove_file(path)\n }\n };\n\n if let Err(e) = remove_op() {\n if use_sudo && e.kind() == io::ErrorKind::PermissionDenied {\n warn!(\n \"Direct removal failed (Permission Denied). Trying with sudo rm -rf: {}\",\n path.display()\n );\n let output = Command::new(\"sudo\").arg(\"rm\").arg(\"-rf\").arg(path).output();\n match output {\n Ok(out) if out.status.success() => {\n debug!(\"Successfully removed {} with sudo.\", path.display());\n true\n }\n Ok(out) => {\n error!(\n \"Failed to remove {} with sudo: {}\",\n path.display(),\n String::from_utf8_lossy(&out.stderr).trim()\n );\n false\n }\n Err(sudo_err) => {\n error!(\n \"Error executing sudo rm for {}: {}\",\n path.display(),\n sudo_err\n );\n false\n }\n }\n } else if e.kind() != io::ErrorKind::NotFound {\n error!(\"Failed to remove artifact {}: {}\", path.display(), e);\n false\n } else {\n debug!(\"Artifact {} already removed.\", path.display());\n true\n }\n } else {\n debug!(\"Successfully removed artifact: {}\", path.display());\n true\n }\n }\n Err(e) if e.kind() == io::ErrorKind::NotFound => {\n debug!(\"Artifact not found (already removed?): {}\", path.display());\n true\n }\n Err(e) => {\n warn!(\n \"Failed to get metadata for artifact {}: {}\",\n path.display(),\n e\n );\n false\n }\n }\n}\n\n/// Expands a path string that may start with `~` to the user's home directory.\npub(crate) fn expand_tilde(path_str: &str, home: &Path) -> PathBuf {\n if let Some(stripped) = path_str.strip_prefix(\"~/\") {\n home.join(stripped)\n } else {\n PathBuf::from(path_str)\n }\n}\n\n/// Checks if a path is safe for zap operations.\n/// Safe paths are typically within user Library, .config, /Applications, /Library,\n/// or the sps cache directory. Root, home, /Applications, /Library themselves are not safe.\npub(crate) fn is_safe_path(path: &Path, home: &Path, config: &Config) -> bool {\n if path.components().any(|c| matches!(c, Component::ParentDir)) {\n warn!(\"Zap path rejected (contains '..'): {}\", path.display());\n return false;\n }\n let allowed_roots = [\n home.join(\"Library\"),\n home.join(\".config\"),\n PathBuf::from(\"/Applications\"),\n PathBuf::from(\"/Library\"),\n config.cache_dir().clone(),\n // Consider adding more specific allowed user dirs if necessary\n ];\n\n // Check if the path is exactly one of the top-level restricted paths\n if path == Path::new(\"/\")\n || path == home\n || path == Path::new(\"/Applications\")\n || path == Path::new(\"/Library\")\n {\n warn!(\"Zap path rejected (too broad): {}\", path.display());\n return false;\n }\n\n if allowed_roots.iter().any(|root| path.starts_with(root)) {\n return true;\n }\n\n warn!(\n \"Zap path rejected (outside allowed areas): {}\",\n path.display()\n );\n false\n}\n"], ["/sps/sps-common/src/pipeline.rs", "// sps-common/src/pipeline.rs\nuse std::path::PathBuf;\nuse std::sync::Arc; // Required for Arc in JobProcessingState\n\nuse serde::{Deserialize, Serialize};\n\nuse crate::dependency::ResolvedGraph; // Needed for planner output\nuse crate::error::SpsError;\nuse crate::model::InstallTargetIdentifier;\n\n// --- Shared Enums / Structs ---\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]\npub enum PipelinePackageType {\n Formula,\n Cask,\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] // Added PartialEq, Eq\npub enum JobAction {\n Install,\n Upgrade {\n from_version: String,\n old_install_path: PathBuf,\n },\n Reinstall {\n version: String,\n current_install_path: PathBuf,\n },\n}\n\n#[derive(Debug, Clone)]\npub struct PlannedJob {\n pub target_id: String,\n pub target_definition: InstallTargetIdentifier,\n pub action: JobAction,\n pub is_source_build: bool,\n pub use_private_store_source: Option,\n}\n\n#[derive(Debug, Clone)]\npub struct WorkerJob {\n pub request: PlannedJob,\n pub download_path: PathBuf,\n pub download_size_bytes: u64,\n pub is_source_from_private_store: bool,\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub enum PipelineEvent {\n PipelineStarted {\n total_jobs: usize,\n },\n PipelineFinished {\n duration_secs: f64,\n success_count: usize,\n fail_count: usize,\n },\n PlanningStarted,\n DependencyResolutionStarted,\n DependencyResolutionFinished,\n PlanningFinished {\n job_count: usize,\n // Optionally, we can pass the ResolvedGraph here if the status handler needs it,\n // but it might be too large for a broadcast event.\n // resolved_graph: Option>, // Example\n },\n DownloadStarted {\n target_id: String,\n url: String,\n },\n DownloadFinished {\n target_id: String,\n path: PathBuf,\n size_bytes: u64,\n },\n DownloadProgressUpdate {\n target_id: String,\n bytes_so_far: u64,\n total_size: Option,\n },\n DownloadCached {\n target_id: String,\n size_bytes: u64,\n },\n DownloadFailed {\n target_id: String,\n url: String,\n error: String, // Keep as String for simplicity in events\n },\n JobProcessingStarted {\n // From core worker\n target_id: String,\n },\n JobDispatchedToCore {\n // New: From runner to UI when job sent to worker pool\n target_id: String,\n },\n UninstallStarted {\n target_id: String,\n version: String,\n },\n UninstallFinished {\n target_id: String,\n version: String,\n },\n BuildStarted {\n target_id: String,\n },\n InstallStarted {\n target_id: String,\n pkg_type: PipelinePackageType,\n },\n LinkStarted {\n target_id: String,\n pkg_type: PipelinePackageType,\n },\n JobSuccess {\n // From core worker\n target_id: String,\n action: JobAction,\n pkg_type: PipelinePackageType,\n },\n JobFailed {\n // From core worker or runner (propagated)\n target_id: String,\n action: JobAction, // Action that was attempted\n error: String, // Keep as String\n },\n LogInfo {\n message: String,\n },\n LogWarn {\n message: String,\n },\n LogError {\n message: String,\n },\n}\n\nimpl PipelineEvent {\n // SpsError kept for internal use, but events use String for error messages\n pub fn job_failed(target_id: String, action: JobAction, error: &SpsError) -> Self {\n PipelineEvent::JobFailed {\n target_id,\n action,\n error: error.to_string(),\n }\n }\n pub fn download_failed(target_id: String, url: String, error: &SpsError) -> Self {\n PipelineEvent::DownloadFailed {\n target_id,\n url,\n error: error.to_string(),\n }\n }\n}\n\n// --- New Structs and Enums for Refactored Runner ---\n\n/// Represents the current processing state of a job in the pipeline.\n#[derive(Debug, Clone)]\npub enum JobProcessingState {\n /// Waiting for download to be initiated.\n PendingDownload,\n /// Download is in progress (managed by DownloadCoordinator).\n Downloading,\n /// Download completed successfully, artifact at PathBuf.\n Downloaded(PathBuf),\n /// Downloaded, but waiting for dependencies to be in Succeeded state.\n WaitingForDependencies(PathBuf),\n /// Dispatched to the core worker pool for installation/processing.\n DispatchedToCore(PathBuf),\n /// Installation/processing is in progress by a core worker.\n Installing(PathBuf), // Path is still relevant\n /// Job completed successfully.\n Succeeded,\n /// Job failed. The String contains the error message. Arc for cheap cloning.\n Failed(Arc),\n}\n\n/// Outcome of a download attempt, sent from DownloadCoordinator to the main runner loop.\n#[derive(Debug)] // Clone not strictly needed if moved\npub struct DownloadOutcome {\n pub planned_job: PlannedJob, // The job this download was for\n pub result: Result, // Path to downloaded file or error\n}\n\n/// Structure returned by the planner, now including the ResolvedGraph.\n#[derive(Debug, Default)]\npub struct PlannedOperations {\n pub jobs: Vec, // Topologically sorted for formulae\n pub errors: Vec<(String, SpsError)>, // Errors from planning phase\n pub already_installed_or_up_to_date: std::collections::HashSet,\n pub resolved_graph: Option>, // Graph for dependency checking in runner\n}\n"], ["/sps/sps/src/cli/install.rs", "// sps-cli/src/cli/install.rs\n\nuse std::sync::Arc;\n\nuse clap::Args;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse tracing::instrument;\n\n// Import pipeline components from the new module\nuse crate::pipeline::runner::{self, CommandType, PipelineFlags};\n\n// Keep the Args struct specific to 'install' if needed, or reuse a common one\n#[derive(Debug, Args)]\npub struct InstallArgs {\n #[arg(required = true)]\n names: Vec,\n\n // Keep flags relevant to install/pipeline\n #[arg(long)]\n skip_deps: bool, // Note: May not be fully supported by core resolution yet\n #[arg(long, help = \"Force install specified targets as casks\")]\n cask: bool,\n #[arg(long, help = \"Force install specified targets as formulas\")]\n formula: bool,\n #[arg(long)]\n include_optional: bool,\n #[arg(long)]\n skip_recommended: bool,\n #[arg(\n long,\n help = \"Force building the formula from source, even if a bottle is available\"\n )]\n build_from_source: bool,\n // Worker/Queue size flags might belong here or be global CLI flags\n // #[arg(long, value_name = \"sps_WORKERS\")]\n // max_workers: Option,\n // #[arg(long, value_name = \"sps_QUEUE\")]\n // queue_size: Option,\n}\n\nimpl InstallArgs {\n #[instrument(skip(self, config, cache), fields(targets = ?self.names))]\n pub async fn run(&self, config: &Config, cache: Arc) -> Result<()> {\n // --- Argument Validation (moved from old run) ---\n if self.formula && self.cask {\n return Err(sps_common::error::SpsError::Generic(\n \"Cannot use --formula and --cask together.\".to_string(),\n ));\n }\n // Add validation for skip_deps if needed\n\n // --- Prepare Pipeline Flags ---\n let flags = PipelineFlags {\n build_from_source: self.build_from_source,\n include_optional: self.include_optional,\n skip_recommended: self.skip_recommended,\n // Add other flags...\n };\n\n // --- Determine Initial Targets based on --formula/--cask flags ---\n // (This logic might be better inside plan_package_operations based on CommandType)\n let initial_targets = self.names.clone(); // For install, all names are initial targets\n\n // --- Execute the Pipeline ---\n runner::run_pipeline(\n &initial_targets,\n CommandType::Install, // Specify the command type\n config,\n cache,\n &flags, // Pass the flags struct\n )\n .await\n }\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/manpage.rs", "// ===== src/build/cask/artifacts/manpage.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::sync::LazyLock;\n\nuse regex::Regex;\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n// --- Moved Regex Creation Outside ---\nstatic MANPAGE_RE: LazyLock =\n LazyLock::new(|| Regex::new(r\"\\.([1-8nl])(?:\\.gz)?$\").unwrap());\n\n/// Install any `manpage` stanzas from the Cask definition.\n/// Mirrors Homebrew’s `Cask::Artifact::Manpage < Symlinked` behavior\n/// :contentReference[oaicite:3]{index=3}.\npub fn install_manpage(\n cask: &Cask,\n stage_path: &Path,\n _cask_version_install_path: &Path, // Not needed for symlinking manpages\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n // Look up the \"manpage\" array in the raw artifacts JSON :contentReference[oaicite:4]{index=4}\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"manpage\").and_then(|v| v.as_array()) {\n for entry in entries {\n if let Some(man_file) = entry.as_str() {\n let src = stage_path.join(man_file);\n if !src.exists() {\n debug!(\n \"Manpage '{}' not found in staging area, skipping\",\n man_file\n );\n continue;\n }\n\n // Use the static regex\n let section = if let Some(caps) = MANPAGE_RE.captures(man_file) {\n caps.get(1).unwrap().as_str()\n } else {\n debug!(\n \"Filename '{}' does not look like a manpage, skipping\",\n man_file\n );\n continue;\n };\n\n // Build the target directory: e.g. /opt/sps/share/man/man1\n let man_dir = config.man_base_dir().join(format!(\"man{section}\"));\n fs::create_dir_all(&man_dir)?;\n\n // Determine the target path\n let file_name = Path::new(man_file).file_name().ok_or_else(|| {\n sps_common::error::SpsError::Generic(format!(\n \"Invalid manpage filename: {man_file}\"\n ))\n })?; // Handle potential None\n let dest = man_dir.join(file_name);\n\n // Remove any existing file or symlink\n // :contentReference[oaicite:7]{index=7}\n if dest.exists() || dest.symlink_metadata().is_ok() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\"Linking manpage '{}' → '{}'\", src.display(), dest.display());\n // Create the symlink\n symlink(&src, &dest)?;\n\n // Record it in our manifest\n installed.push(InstalledArtifact::ManpageLink {\n link_path: dest.clone(),\n target_path: src.clone(),\n });\n }\n }\n // Assume only one \"manpage\" stanza per Cask based on Homebrew structure\n break;\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/input_method.rs", "// ===== sps-core/src/build/cask/artifacts/input_method.rs =====\n\nuse std::fs;\nuse std::os::unix::fs as unix_fs;\nuse std::path::Path;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\n\nuse crate::install::cask::helpers::remove_path_robustly;\nuse crate::install::cask::write_cask_manifest;\n\n/// Install `input_method` artifacts from the staged directory into\n/// `~/Library/Input Methods` and record installed artifacts.\npub fn install_input_method(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n // Ensure we have an array of input_method names\n if let Some(artifacts_def) = &cask.artifacts {\n for artifact_value in artifacts_def {\n if let Some(obj) = artifact_value.as_object() {\n if let Some(names) = obj.get(\"input_method\").and_then(|v| v.as_array()) {\n for name_val in names {\n if let Some(name) = name_val.as_str() {\n let source = stage_path.join(name);\n if source.exists() {\n // Target directory: ~/Library/Input Methods\n let target_dir =\n config.home_dir().join(\"Library\").join(\"Input Methods\");\n if !target_dir.exists() {\n fs::create_dir_all(&target_dir)?;\n }\n let target = target_dir.join(name);\n\n // Remove existing input method if present\n if target.exists() {\n let _ = remove_path_robustly(&target, config, true);\n }\n\n // Move (or rename) the staged bundle\n fs::rename(&source, &target)\n .or_else(|_| unix_fs::symlink(&source, &target))?;\n\n // Record the main artifact\n installed.push(InstalledArtifact::MovedResource {\n path: target.clone(),\n });\n\n // Create a caskroom symlink for uninstallation\n let link_path = cask_version_install_path.join(name);\n if link_path.exists() {\n let _ = remove_path_robustly(&link_path, config, true);\n }\n #[cfg(unix)]\n std::os::unix::fs::symlink(&target, &link_path)?;\n\n installed.push(InstalledArtifact::CaskroomLink {\n link_path,\n target_path: target,\n });\n }\n }\n }\n }\n }\n }\n }\n\n // Write manifest for these artifacts\n write_cask_manifest(cask, cask_version_install_path, installed.clone())?;\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/helpers.rs", "use std::fs;\nuse std::path::Path;\n\nuse sps_common::config::Config;\nuse tracing::debug;\n\n/// Robustly removes a file or directory, handling symlinks and permissions.\n/// If `use_sudo_if_needed` is true, will attempt `sudo rm -rf` on permission errors.\npub fn remove_path_robustly(path: &Path, _config: &Config, use_sudo_if_needed: bool) -> bool {\n if !path.exists() && path.symlink_metadata().is_err() {\n debug!(\"Path {} not found for removal.\", path.display());\n return true;\n }\n let is_dir = path.is_dir()\n && !path\n .symlink_metadata()\n .is_ok_and(|m| m.file_type().is_symlink());\n let removal_op = || -> std::io::Result<()> {\n if is_dir {\n fs::remove_dir_all(path)\n } else {\n fs::remove_file(path)\n }\n };\n\n if let Err(e) = removal_op() {\n if e.kind() == std::io::ErrorKind::NotFound {\n return true;\n }\n if use_sudo_if_needed && e.kind() == std::io::ErrorKind::PermissionDenied {\n debug!(\n \"Direct removal of {} failed (Permission Denied). Trying with sudo rm -rf.\",\n path.display()\n );\n let output = std::process::Command::new(\"sudo\")\n .arg(\"rm\")\n .arg(\"-rf\")\n .arg(path)\n .output();\n match output {\n Ok(out) if out.status.success() => {\n debug!(\"Successfully removed {} with sudo.\", path.display());\n return true;\n }\n Ok(out) => {\n debug!(\n \"`sudo rm -rf {}` failed ({}): {}\",\n path.display(),\n out.status,\n String::from_utf8_lossy(&out.stderr).trim()\n );\n return false;\n }\n Err(sudo_e) => {\n debug!(\n \"Error executing `sudo rm -rf` for {}: {}\",\n path.display(),\n sudo_e\n );\n return false;\n }\n }\n } else {\n debug!(\"Failed to remove {}: {}\", path.display(), e);\n return false;\n }\n }\n debug!(\"Successfully removed {}.\", path.display());\n true\n}\n\n/// Recursively cleans up empty parent directories in the private cask store.\n/// Starts from the given path and walks up, removing empty directories until a non-empty or root is\n/// found.\npub fn cleanup_empty_parent_dirs_in_private_store(start_path: &Path, stop_at: &Path) {\n let mut current = start_path.to_path_buf();\n while current != *stop_at {\n if let Ok(read_dir) = fs::read_dir(¤t) {\n if read_dir.count() == 0 {\n match fs::remove_dir(¤t) {\n Ok(_) => {\n debug!(\"Removed empty directory: {}\", current.display());\n }\n Err(e) => {\n debug!(\"Failed to remove directory {}: {}\", current.display(), e);\n break;\n }\n }\n } else {\n break;\n }\n } else {\n break;\n }\n if let Some(parent) = current.parent() {\n current = parent.to_path_buf();\n } else {\n break;\n }\n }\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/colorpicker.rs", "// ===== sps-core/src/build/cask/artifacts/colorpicker.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Installs any `colorpicker` stanzas from the Cask definition.\n///\n/// Homebrew’s `Colorpicker` artifact simply subclasses `Moved` with\n/// `dirmethod :colorpickerdir` → `~/Library/ColorPickers` :contentReference[oaicite:3]{index=3}.\npub fn install_colorpicker(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"colorpicker\").and_then(|v| v.as_array()) {\n // For each declared bundle name:\n for entry in entries {\n if let Some(bundle_name) = entry.as_str() {\n let src = stage_path.join(bundle_name);\n if !src.exists() {\n debug!(\n \"Colorpicker bundle '{}' not found in stage; skipping\",\n bundle_name\n );\n continue;\n }\n\n // Ensure ~/Library/ColorPickers exists\n // :contentReference[oaicite:4]{index=4}\n let dest_dir = config\n .home_dir() // e.g. /Users/alxknt\n .join(\"Library\")\n .join(\"ColorPickers\");\n fs::create_dir_all(&dest_dir)?;\n\n let dest = dest_dir.join(bundle_name);\n // Remove any previous copy\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Moving colorpicker '{}' → '{}'\",\n src.display(),\n dest.display()\n );\n // mv, fallback to cp -R if necessary (cross‑device)\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record as a moved artifact (bundle installed)\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink back into Caskroom for reference\n // :contentReference[oaicite:5]{index=5}\n let link = cask_version_install_path.join(bundle_name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // only one `colorpicker` stanza per cask\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/dmg.rs", "// In sps-core/src/build/cask/dmg.rs\n\nuse std::fs;\nuse std::io::{BufRead, BufReader};\nuse std::path::{Path, PathBuf};\nuse std::process::Command;\n\nuse sps_common::error::{Result, SpsError};\nuse tracing::{debug, error}; // Added log imports\n\n// --- Keep Existing Helpers ---\npub fn mount_dmg(dmg_path: &Path) -> Result {\n debug!(\"Mounting DMG: {}\", dmg_path.display());\n let output = Command::new(\"hdiutil\")\n .arg(\"attach\")\n .arg(\"-plist\")\n .arg(\"-nobrowse\")\n .arg(\"-readonly\")\n .arg(\"-mountrandom\")\n .arg(\"/tmp\") // Consider making mount location configurable or more robust\n .arg(dmg_path)\n .output()?;\n\n if !output.status.success() {\n let stderr = String::from_utf8_lossy(&output.stderr);\n error!(\n \"hdiutil attach failed for {}: {}\",\n dmg_path.display(),\n stderr\n );\n return Err(SpsError::Generic(format!(\n \"Failed to mount DMG '{}': {}\",\n dmg_path.display(),\n stderr\n )));\n }\n\n let mount_point = parse_mount_point(&output.stdout)?;\n debug!(\"DMG mounted at: {}\", mount_point.display());\n Ok(mount_point)\n}\n\npub fn unmount_dmg(mount_point: &Path) -> Result<()> {\n debug!(\"Unmounting DMG from: {}\", mount_point.display());\n // Add logging for commands\n debug!(\"Executing: hdiutil detach -force {}\", mount_point.display());\n let output = Command::new(\"hdiutil\")\n .arg(\"detach\")\n .arg(\"-force\")\n .arg(mount_point)\n .output()?;\n\n if !output.status.success() {\n let stderr = String::from_utf8_lossy(&output.stderr);\n debug!(\n \"hdiutil detach failed ({}): {}. Trying diskutil\",\n output.status, stderr\n );\n // Add logging for fallback\n debug!(\n \"Executing: diskutil unmount force {}\",\n mount_point.display()\n );\n let diskutil_output = Command::new(\"diskutil\")\n .arg(\"unmount\")\n .arg(\"force\")\n .arg(mount_point)\n .output()?;\n\n if !diskutil_output.status.success() {\n let diskutil_stderr = String::from_utf8_lossy(&diskutil_output.stderr);\n error!(\n \"diskutil unmount force failed ({}): {}\",\n diskutil_output.status, diskutil_stderr\n );\n // Consider returning error only if both fail? Or always error on diskutil fail?\n return Err(SpsError::Generic(format!(\n \"Failed to unmount DMG '{}' using hdiutil and diskutil: {}\",\n mount_point.display(),\n diskutil_stderr\n )));\n }\n }\n debug!(\"DMG successfully unmounted\");\n Ok(())\n}\n\nfn parse_mount_point(output: &[u8]) -> Result {\n // ... (existing implementation) ...\n // Use plist crate for more robust parsing if possible in the future\n let cursor = std::io::Cursor::new(output);\n let reader = BufReader::new(cursor);\n let mut in_sys_entities = false;\n let mut in_mount_point = false;\n let mut mount_path_str: Option = None;\n\n for line_res in reader.lines() {\n let line = line_res?;\n let trimmed = line.trim();\n\n if trimmed == \"system-entities\" {\n in_sys_entities = true;\n continue;\n }\n if !in_sys_entities {\n continue;\n }\n\n if trimmed == \"mount-point\" {\n in_mount_point = true;\n continue;\n }\n\n if in_mount_point && trimmed.starts_with(\"\") && trimmed.ends_with(\"\") {\n mount_path_str = Some(\n trimmed\n .trim_start_matches(\"\")\n .trim_end_matches(\"\")\n .to_string(),\n );\n break; // Found the first mount point, assume it's the main one\n }\n\n // Reset flags if we encounter closing tags for structures containing mount-point\n if trimmed == \"\" {\n in_mount_point = false;\n }\n if trimmed == \"\" && in_sys_entities {\n // End of system-entities\n // break; // Stop searching if we leave the system-entities array\n in_sys_entities = false; // Reset this flag too\n }\n }\n\n match mount_path_str {\n Some(path_str) if !path_str.is_empty() => {\n debug!(\"Parsed mount point from plist: {}\", path_str);\n Ok(PathBuf::from(path_str))\n }\n _ => {\n error!(\"Failed to parse mount point from hdiutil plist output.\");\n // Optionally log the raw output for debugging\n // error!(\"Raw hdiutil output:\\n{}\", String::from_utf8_lossy(output));\n Err(SpsError::Generic(\n \"Failed to determine mount point from hdiutil output\".to_string(),\n ))\n }\n }\n}\n\n// --- NEW Function ---\n/// Extracts the contents of a mounted DMG to a staging directory using `ditto`.\npub fn extract_dmg_to_stage(dmg_path: &Path, stage_dir: &Path) -> Result<()> {\n let mount_point = mount_dmg(dmg_path)?;\n\n // Ensure the stage directory exists (though TempDir should handle it)\n if !stage_dir.exists() {\n fs::create_dir_all(stage_dir).map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n }\n\n debug!(\n \"Copying contents from DMG mount {} to stage {} using ditto\",\n mount_point.display(),\n stage_dir.display()\n );\n // Use ditto for robust copying, preserving metadata\n // ditto \n debug!(\n \"Executing: ditto {} {}\",\n mount_point.display(),\n stage_dir.display()\n );\n let ditto_output = Command::new(\"ditto\")\n .arg(&mount_point) // Source first\n .arg(stage_dir) // Then destination\n .output()?;\n\n let unmount_result = unmount_dmg(&mount_point); // Unmount regardless of ditto success\n\n if !ditto_output.status.success() {\n let stderr = String::from_utf8_lossy(&ditto_output.stderr);\n error!(\"ditto command failed ({}): {}\", ditto_output.status, stderr);\n // Also log stdout which might contain info on specific file errors\n let stdout = String::from_utf8_lossy(&ditto_output.stdout);\n if !stdout.trim().is_empty() {\n error!(\"ditto stdout: {}\", stdout);\n }\n unmount_result?; // Ensure we still return unmount error if it happened\n return Err(SpsError::Generic(format!(\n \"Failed to copy DMG contents using ditto: {stderr}\"\n )));\n }\n\n // After ditto, quarantine any .app bundles in the stage (macOS only)\n #[cfg(target_os = \"macos\")]\n {\n if let Err(e) = crate::install::extract::quarantine_extracted_apps_in_stage(\n stage_dir,\n \"sps-dmg-extractor\",\n ) {\n tracing::warn!(\n \"Error during post-DMG extraction quarantine scan for {}: {}\",\n dmg_path.display(),\n e\n );\n }\n }\n\n unmount_result // Return the result of unmounting\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/mdimporter.rs", "// ===== sps-core/src/build/cask/artifacts/mdimporter.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Installs `mdimporter` bundles from the staging area into\n/// `~/Library/Spotlight`, then symlinks them into the Caskroom,\n/// and reloads them via `mdimport -r` so Spotlight picks them up.\n///\n/// Mirrors Homebrew’s `Mdimporter < Moved` behavior.\npub fn install_mdimporter(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"mdimporter\").and_then(|v| v.as_array()) {\n // Target directory for user Spotlight importers\n let dest_dir = config.home_dir().join(\"Library\").join(\"Spotlight\");\n fs::create_dir_all(&dest_dir)?;\n\n for entry in entries {\n if let Some(bundle_name) = entry.as_str() {\n let src = stage_path.join(bundle_name);\n if !src.exists() {\n debug!(\n \"Mdimporter bundle '{}' not found in staging; skipping\",\n bundle_name\n );\n continue;\n }\n\n let dest = dest_dir.join(bundle_name);\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Installing mdimporter '{}' → '{}',\",\n src.display(),\n dest.display()\n );\n // Try move, fallback to copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record moved importer\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink for reference\n let link = cask_version_install_path.join(bundle_name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n\n // Reload Spotlight importer so it's picked up immediately\n debug!(\"Reloading Spotlight importer: {}\", dest.display());\n let _ = Command::new(\"/usr/bin/mdimport\")\n .arg(\"-r\")\n .arg(&dest)\n .status();\n }\n }\n break; // one stanza only\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/suite.rs", "// src/build/cask/artifacts/suite.rs\n\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Implements the `suite` stanza by moving each named directory from\n/// the staging area into `/Applications`, then symlinking it in the Caskroom.\n///\n/// Mirrors Homebrew’s Suite < Moved behavior (dirmethod :appdir)\n/// :contentReference[oaicite:3]{index=3}\npub fn install_suite(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n // Find the `suite` definition in the raw JSON artifacts\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def.iter() {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"suite\").and_then(|v| v.as_array()) {\n for entry in entries {\n if let Some(dir_name) = entry.as_str() {\n let src = stage_path.join(dir_name);\n if !src.exists() {\n debug!(\n \"Suite directory '{}' not found in staging, skipping\",\n dir_name\n );\n continue;\n }\n\n let dest_dir = config.applications_dir(); // e.g. /Applications\n let dest = dest_dir.join(dir_name); // e.g. /Applications/Foobar Suite\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n // remove old\n }\n\n debug!(\"Moving suite '{}' → '{}'\", src.display(), dest.display());\n // Try a rename (mv); fall back to recursive copy if cross‑filesystem\n let mv_status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !mv_status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record as an App artifact (a directory moved into /Applications)\n installed.push(InstalledArtifact::AppBundle { path: dest.clone() });\n\n // Then symlink it under Caskroom for reference\n let link = cask_version_install_path.join(dir_name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // only one \"suite\" stanza per cask\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/vst3_plugin.rs", "// ===== sps-core/src/build/cask/artifacts/vst3_plugin.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Installs `vst3_plugin` bundles from the staging area into\n/// `~/Library/Audio/Plug-Ins/VST3`, then symlinks them into the Caskroom.\n///\n/// Mirrors Homebrew’s `Vst3Plugin < Moved` pattern.\npub fn install_vst3_plugin(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"vst3_plugin\").and_then(|v| v.as_array()) {\n // Target directory for VST3 plugins\n let dest_dir = config\n .home_dir()\n .join(\"Library\")\n .join(\"Audio\")\n .join(\"Plug-Ins\")\n .join(\"VST3\");\n fs::create_dir_all(&dest_dir)?;\n\n for entry in entries {\n if let Some(bundle_name) = entry.as_str() {\n let src = stage_path.join(bundle_name);\n if !src.exists() {\n debug!(\n \"VST3 plugin '{}' not found in staging; skipping\",\n bundle_name\n );\n continue;\n }\n\n let dest = dest_dir.join(bundle_name);\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Installing VST3 plugin '{}' → '{}'\",\n src.display(),\n dest.display()\n );\n // Try move, fallback to copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record moved plugin\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink into Caskroom for reference\n let link = cask_version_install_path.join(bundle_name);\n let _ = crate::install::cask::helpers::remove_path_robustly(\n &link, config, true,\n );\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // single stanza\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/vst_plugin.rs", "// ===== sps-core/src/build/cask/artifacts/vst_plugin.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Installs `vst_plugin` bundles from the staging area into\n/// `~/Library/Audio/Plug-Ins/VST`, then symlinks them into the Caskroom.\n///\n/// Mirrors Homebrew’s `VstPlugin < Moved` pattern.\npub fn install_vst_plugin(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"vst_plugin\").and_then(|v| v.as_array()) {\n // Target directory for VST plugins\n let dest_dir = config\n .home_dir()\n .join(\"Library\")\n .join(\"Audio\")\n .join(\"Plug-Ins\")\n .join(\"VST\");\n fs::create_dir_all(&dest_dir)?;\n\n for entry in entries {\n if let Some(bundle_name) = entry.as_str() {\n let src = stage_path.join(bundle_name);\n if !src.exists() {\n debug!(\n \"VST plugin '{}' not found in staging; skipping\",\n bundle_name\n );\n continue;\n }\n\n let dest = dest_dir.join(bundle_name);\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Installing VST plugin '{}' → '{}'\",\n src.display(),\n dest.display()\n );\n // Try move, fallback to copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record moved plugin\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink into Caskroom for reference\n let link = cask_version_install_path.join(bundle_name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // single stanza\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/audio_unit_plugin.rs", "// ===== sps-core/src/build/cask/artifacts/audio_unit_plugin.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Installs `audio_unit_plugin` bundles from the staging area into\n/// `~/Library/Audio/Plug-Ins/Components`, then symlinks them into the Caskroom.\n///\n/// Mirrors Homebrew’s `AudioUnitPlugin < Moved` pattern.\npub fn install_audio_unit_plugin(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"audio_unit_plugin\").and_then(|v| v.as_array()) {\n // Target directory for Audio Unit components\n let dest_dir = config\n .home_dir()\n .join(\"Library\")\n .join(\"Audio\")\n .join(\"Plug-Ins\")\n .join(\"Components\");\n fs::create_dir_all(&dest_dir)?;\n\n for entry in entries {\n if let Some(bundle_name) = entry.as_str() {\n let src = stage_path.join(bundle_name);\n if !src.exists() {\n debug!(\n \"AudioUnit plugin '{}' not found in staging; skipping\",\n bundle_name\n );\n continue;\n }\n\n let dest = dest_dir.join(bundle_name);\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Installing AudioUnit plugin '{}' → '{}'\",\n src.display(),\n dest.display()\n );\n // Try move, fallback to copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record moved plugin\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink into Caskroom for reference\n let link = cask_version_install_path.join(bundle_name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // one stanza only\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/dictionary.rs", "// ===== sps-core/src/build/cask/artifacts/dictionary.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Implements the `dictionary` stanza by moving each declared\n/// `.dictionary` bundle from the staging area into `~/Library/Dictionaries`,\n/// then symlinking it in the Caskroom.\n///\n/// Homebrew’s Ruby definition is simply:\n/// ```ruby\n/// class Dictionary < Moved; end\n/// ```\n/// :contentReference[oaicite:2]{index=2}\npub fn install_dictionary(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n // Find any `dictionary` arrays in the raw JSON artifacts\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"dictionary\").and_then(|v| v.as_array()) {\n for entry in entries {\n if let Some(bundle_name) = entry.as_str() {\n let src = stage_path.join(bundle_name);\n if !src.exists() {\n debug!(\n \"Dictionary bundle '{}' not found in staging; skipping\",\n bundle_name\n );\n continue;\n }\n\n // Standard user dictionary directory: ~/Library/Dictionaries\n // :contentReference[oaicite:3]{index=3}\n let dest_dir = config\n .home_dir() // e.g. /Users/alxknt\n .join(\"Library\")\n .join(\"Dictionaries\");\n fs::create_dir_all(&dest_dir)?;\n\n let dest = dest_dir.join(bundle_name);\n // Remove any previous install\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Moving dictionary '{}' → '{}'\",\n src.display(),\n dest.display()\n );\n // Try a direct move; fall back to recursive copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record the moved bundle\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink back into Caskroom for reference\n let link = cask_version_install_path.join(bundle_name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // Only one `dictionary` stanza per cask\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/font.rs", "// ===== sps-core/src/build/cask/artifacts/font.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Implements the `font` stanza by moving each declared\n/// font file or directory from the staging area into\n/// `~/Library/Fonts`, then symlinking it in the Caskroom.\n///\n/// Mirrors Homebrew’s `Dictionary < Moved` and `Colorpicker < Moved` pattern.\npub fn install_font(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n // Look for \"font\" entries in the JSON artifacts\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"font\").and_then(|v| v.as_array()) {\n // Target directory for user fonts\n let dest_dir = config.home_dir().join(\"Library\").join(\"Fonts\");\n fs::create_dir_all(&dest_dir)?;\n\n for entry in entries {\n if let Some(name) = entry.as_str() {\n let src = stage_path.join(name);\n if !src.exists() {\n debug!(\"Font '{}' not found in staging; skipping\", name);\n continue;\n }\n\n let dest = dest_dir.join(name);\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\"Installing font '{}' → '{}'\", src.display(), dest.display());\n // Try move, fallback to copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record moved font\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink into Caskroom for reference\n let link = cask_version_install_path.join(name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // single font stanza per cask\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/utils/xattr.rs", "use std::path::Path;\nuse std::process::Command;\n\nuse anyhow::Context;\nuse sps_common::error::{Result, SpsError};\nuse tracing::{debug, error};\nuse uuid::Uuid;\nuse xattr;\n\n// Helper to get current timestamp as hex\nfn get_timestamp_hex() -> String {\n let secs = std::time::SystemTime::now()\n .duration_since(std::time::UNIX_EPOCH)\n .unwrap_or_default() // Defaults to 0 if time is before UNIX_EPOCH\n .as_secs();\n format!(\"{secs:x}\")\n}\n\n// Helper to generate a UUID as hex string\nfn get_uuid_hex() -> String {\n Uuid::new_v4().as_hyphenated().to_string().to_uppercase()\n}\n\n/// true → file **has** a com.apple.quarantine attribute \n/// false → attribute missing\npub fn has_quarantine_attribute(path: &Path) -> anyhow::Result {\n // The `xattr` crate has both path-level and FileExt APIs.\n // Path-level is simpler here.\n match xattr::get(path, \"com.apple.quarantine\") {\n Ok(Some(_)) => Ok(true),\n Ok(None) => Ok(false),\n Err(e) => Err(anyhow::Error::new(e))\n .with_context(|| format!(\"checking xattr on {}\", path.display())),\n }\n}\n\n/// Apply our standard quarantine only *if* none exists already.\n///\n/// `agent` should be the same string you currently pass to\n/// `set_quarantine_attribute()` – usually the cask token.\npub fn ensure_quarantine_attribute(path: &Path, agent: &str) -> anyhow::Result<()> {\n if has_quarantine_attribute(path)? {\n // Already quarantined (or the user cleared it and we respect that) → done\n return Ok(());\n }\n set_quarantine_attribute(path, agent)\n .with_context(|| format!(\"adding quarantine to {}\", path.display()))\n}\n\n/// Sets the 'com.apple.quarantine' extended attribute on a file or directory.\n/// Uses flags commonly seen for user-initiated downloads (0081).\n/// Logs errors assertively, as failure is critical for correct behavior.\npub fn set_quarantine_attribute(path: &Path, agent_name: &str) -> Result<()> {\n if !cfg!(target_os = \"macos\") {\n debug!(\n \"Not on macOS, skipping quarantine attribute for {}\",\n path.display()\n );\n return Ok(());\n }\n\n if !path.exists() {\n error!(\n \"Cannot set quarantine attribute, path does not exist: {}\",\n path.display()\n );\n return Err(SpsError::NotFound(format!(\n \"Path not found for setting quarantine attribute: {}\",\n path.display()\n )));\n }\n\n let timestamp_hex = get_timestamp_hex();\n let uuid_hex = get_uuid_hex();\n // Use \"0181\" to disable translocation and quarantine mirroring (Homebrew-style).\n // Format: \"flags;timestamp_hex;agent_name;uuid_hex\"\n let quarantine_value = format!(\"0181;{timestamp_hex};{agent_name};{uuid_hex}\");\n\n debug!(\n \"Setting quarantine attribute on {}: value='{}'\",\n path.display(),\n quarantine_value\n );\n\n let output = Command::new(\"xattr\")\n .arg(\"-w\")\n .arg(\"com.apple.quarantine\")\n .arg(&quarantine_value)\n .arg(path.as_os_str())\n .output();\n\n match output {\n Ok(out) => {\n if out.status.success() {\n debug!(\n \"Successfully set quarantine attribute for {}\",\n path.display()\n );\n Ok(())\n } else {\n let stderr = String::from_utf8_lossy(&out.stderr);\n error!( // Changed from warn to error as this is critical for the bug\n \"Failed to set quarantine attribute for {} (status: {}): {}. This may lead to data loss on reinstall or Gatekeeper issues.\",\n path.display(),\n out.status,\n stderr.trim()\n );\n // Return an error because failure to set this is likely to cause the reported bug\n Err(SpsError::Generic(format!(\n \"Failed to set com.apple.quarantine on {}: {}\",\n path.display(),\n stderr.trim()\n )))\n }\n }\n Err(e) => {\n error!(\n \"Failed to execute xattr command for {}: {}. Quarantine attribute not set.\",\n path.display(),\n e\n );\n Err(SpsError::Io(std::sync::Arc::new(e)))\n }\n }\n}\n"], ["/sps/sps-core/src/upgrade/cask.rs", "// sps-core/src/upgrade/cask.rs\n\nuse std::path::Path;\n\nuse sps_common::config::Config;\nuse sps_common::error::{Result as SpsResult, SpsError};\nuse sps_common::model::cask::Cask;\nuse sps_common::pipeline::JobAction; // Required for install_cask\nuse tracing::{debug, error};\n\nuse crate::check::installed::InstalledPackageInfo;\nuse crate::{install, uninstall};\n\n/// Upgrades a cask package using Homebrew's proven strategy.\npub async fn upgrade_cask_package(\n cask: &Cask,\n new_cask_download_path: &Path,\n old_install_info: &InstalledPackageInfo,\n config: &Config,\n) -> SpsResult<()> {\n debug!(\n \"Upgrading cask {} from {} to {}\",\n cask.token,\n old_install_info.version,\n cask.version.as_deref().unwrap_or(\"latest\")\n );\n\n // 1. Soft-uninstall the old version\n // This removes linked artifacts and updates the old manifest's is_installed flag.\n // It does not remove the old Caskroom version directory itself yet.\n debug!(\n \"Soft-uninstalling old cask version: {} at {}\",\n old_install_info.version,\n old_install_info.path.display()\n );\n uninstall::cask::uninstall_cask_artifacts(old_install_info, config).map_err(|e| {\n error!(\n \"Failed to soft-uninstall old version {} of cask {}: {}\",\n old_install_info.version, cask.token, e\n );\n SpsError::InstallError(format!(\n \"Failed to soft-uninstall old version during upgrade of {}: {e}\",\n cask.token\n ))\n })?;\n debug!(\n \"Successfully soft-uninstalled old version of {}\",\n cask.token\n );\n\n // 2. Install the new version\n // The install_cask function, particularly install_app_from_staged,\n // should handle the upgrade logic (like syncing app data) when\n // passed the JobAction::Upgrade.\n debug!(\n \"Installing new version for cask {} from {}\",\n cask.token,\n new_cask_download_path.display()\n );\n\n let job_action_for_install = JobAction::Upgrade {\n from_version: old_install_info.version.clone(),\n old_install_path: old_install_info.path.clone(),\n };\n\n install::cask::install_cask(\n cask,\n new_cask_download_path,\n config,\n &job_action_for_install,\n )\n .map_err(|e| {\n error!(\n \"Failed to install new version of cask {}: {}\",\n cask.token, e\n );\n SpsError::InstallError(format!(\n \"Failed to install new version during upgrade of {}: {e}\",\n cask.token\n ))\n })?;\n debug!(\"Successfully installed new version of cask {}\", cask.token);\n\n Ok(())\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/internet_plugin.rs", "// ===== sps-core/src/build/cask/artifacts/internet_plugin.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Implements the `internet_plugin` stanza by moving each declared\n/// internet plugin bundle from the staging area into\n/// `~/Library/Internet Plug-Ins`, then symlinking it in the Caskroom.\n///\n/// Mirrors Homebrew’s `InternetPlugin < Moved` pattern.\npub fn install_internet_plugin(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n // Look for \"internet_plugin\" entries in the JSON artifacts\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"internet_plugin\").and_then(|v| v.as_array()) {\n // Target directory for user internet plugins\n let dest_dir = config.home_dir().join(\"Library\").join(\"Internet Plug-Ins\");\n fs::create_dir_all(&dest_dir)?;\n\n for entry in entries {\n if let Some(name) = entry.as_str() {\n let src = stage_path.join(name);\n if !src.exists() {\n debug!(\"Internet plugin '{}' not found in staging; skipping\", name);\n continue;\n }\n\n let dest = dest_dir.join(name);\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Installing internet plugin '{}' → '{}'\",\n src.display(),\n dest.display()\n );\n // Try move, fallback to copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record moved plugin\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink into Caskroom for reference\n let link = cask_version_install_path.join(name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // single stanza\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/upgrade/bottle.rs", "// sps-core/src/upgrade/bottle.rs\n\nuse std::path::{Path, PathBuf};\nuse std::sync::Arc;\n\nuse sps_common::config::Config;\nuse sps_common::error::{Result as SpsResult, SpsError};\nuse sps_common::model::formula::Formula;\nuse tracing::{debug, error};\n\nuse crate::check::installed::InstalledPackageInfo;\nuse crate::{install, uninstall};\n\n/// Upgrades a formula that is installed from a bottle.\n///\n/// This involves:\n/// 1. Uninstalling the old version of the formula.\n/// 2. Installing the new bottle.\n/// 3. Linking the new version.\npub async fn upgrade_bottle_formula(\n formula: &Formula,\n new_bottle_download_path: &Path,\n old_install_info: &InstalledPackageInfo,\n config: &Config,\n http_client: Arc, /* Added for download_bottle if needed, though path is\n * pre-downloaded */\n) -> SpsResult {\n debug!(\n \"Upgrading bottle formula {} from {} to {}\",\n formula.name(),\n old_install_info.version,\n formula.version_str_full()\n );\n\n // 1. Uninstall the old version\n debug!(\n \"Uninstalling old bottle version: {} at {}\",\n old_install_info.version,\n old_install_info.path.display()\n );\n let uninstall_opts = uninstall::UninstallOptions { skip_zap: true }; // Zap is not relevant for formula upgrades\n uninstall::formula::uninstall_formula_artifacts(old_install_info, config, &uninstall_opts)\n .map_err(|e| {\n error!(\n \"Failed to uninstall old version {} of formula {}: {}\",\n old_install_info.version,\n formula.name(),\n e\n );\n SpsError::InstallError(format!(\n \"Failed to uninstall old version during upgrade of {}: {e}\",\n formula.name()\n ))\n })?;\n debug!(\"Successfully uninstalled old version of {}\", formula.name());\n\n // 2. Install the new bottle\n // The new_bottle_download_path is already provided, so we call install_bottle directly.\n // If download was part of this function, http_client would be used.\n let _ = http_client; // Mark as used if not directly needed by install_bottle\n\n debug!(\n \"Installing new bottle for {} from {}\",\n formula.name(),\n new_bottle_download_path.display()\n );\n let installed_keg_path =\n install::bottle::exec::install_bottle(new_bottle_download_path, formula, config).map_err(\n |e| {\n error!(\n \"Failed to install new bottle for formula {}: {}\",\n formula.name(),\n e\n );\n SpsError::InstallError(format!(\n \"Failed to install new bottle during upgrade of {}: {e}\",\n formula.name()\n ))\n },\n )?;\n debug!(\n \"Successfully installed new bottle for {} to {}\",\n formula.name(),\n installed_keg_path.display()\n );\n\n // 3. Link the new version (linking is handled by the worker after this function returns the\n // path)\n // The install::bottle::exec::install_bottle writes the receipt, but linking is separate.\n // The worker will call link_formula_artifacts after this.\n\n Ok(installed_keg_path)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/screen_saver.rs", "// ===== sps-core/src/build/cask/artifacts/screen_saver.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Installs `screen_saver` bundles from the staging area into\n/// `~/Library/Screen Savers`, then symlinks them into the Caskroom.\n///\n/// Mirrors Homebrew’s `ScreenSaver < Moved` pattern.\npub fn install_screen_saver(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"screen_saver\").and_then(|v| v.as_array()) {\n // Target directory for user screen savers\n let dest_dir = config.home_dir().join(\"Library\").join(\"Screen Savers\");\n fs::create_dir_all(&dest_dir)?;\n\n for entry in entries {\n if let Some(bundle_name) = entry.as_str() {\n let src = stage_path.join(bundle_name);\n if !src.exists() {\n debug!(\n \"Screen saver '{}' not found in staging; skipping\",\n bundle_name\n );\n continue;\n }\n\n let dest = dest_dir.join(bundle_name);\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Installing screen saver '{}' → '{}',\",\n src.display(),\n dest.display()\n );\n // Try move, fallback to copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record moved screen saver\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink into Caskroom for reference\n let link = cask_version_install_path.join(bundle_name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // single stanza\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps/src/cli/update.rs", "//! Contains the logic for the `update` command.\nuse std::fs;\nuse std::sync::Arc;\n\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_net::api;\n\n#[derive(clap::Args, Debug)]\npub struct Update;\n\nimpl Update {\n pub async fn run(&self, config: &Config, cache: Arc) -> Result<()> {\n tracing::debug!(\"Running manual update...\"); // Log clearly it's the manual one\n\n // Use the ui utility function to create the spinner\n println!(\"Updating package lists\"); // <-- CHANGED\n\n tracing::debug!(\"Using cache directory: {:?}\", config.cache_dir());\n\n // Fetch and store raw formula data\n match api::fetch_all_formulas().await {\n Ok(raw_data) => {\n cache.store_raw(\"formula.json\", &raw_data)?;\n tracing::debug!(\"✓ Successfully cached formulas data\");\n println!(\"Cached formulas data\");\n }\n Err(e) => {\n let err_msg = format!(\"Failed to fetch/store formulas from API: {e}\");\n tracing::error!(\"{}\", err_msg);\n println!(); // Clear spinner on error\n return Err(e);\n }\n }\n\n // Fetch and store raw cask data\n match api::fetch_all_casks().await {\n Ok(raw_data) => {\n cache.store_raw(\"cask.json\", &raw_data)?;\n tracing::debug!(\"✓ Successfully cached casks data\");\n println!(\"Cached casks data\");\n }\n Err(e) => {\n let err_msg = format!(\"Failed to fetch/store casks from API: {e}\");\n tracing::error!(\"{}\", err_msg);\n return Err(e);\n }\n }\n\n // Update timestamp file\n let timestamp_file = config.state_dir().join(\".sps_last_update_check\");\n tracing::debug!(\n \"Manual update successful. Updating timestamp file: {}\",\n timestamp_file.display()\n );\n match fs::File::create(×tamp_file) {\n Ok(_) => {\n tracing::debug!(\"Updated timestamp file successfully.\");\n }\n Err(e) => {\n tracing::warn!(\n \"Failed to create or update timestamp file '{}': {}\",\n timestamp_file.display(),\n e\n );\n }\n }\n\n println!(\"Update completed successfully!\");\n Ok(())\n }\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/service.rs", "// ===== sps-core/src/build/cask/artifacts/service.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers;\n\n/// Installs `service` artifacts by moving each declared\n/// Automator workflow or service bundle from the staging area into\n/// `~/Library/Services`, then symlinking it in the Caskroom.\n///\n/// Mirrors Homebrew’s `Service < Moved` behavior.\npub fn install_service(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"service\").and_then(|v| v.as_array()) {\n // Target directory for user Services\n let dest_dir = config.home_dir().join(\"Library\").join(\"Services\");\n fs::create_dir_all(&dest_dir)?;\n\n for entry in entries {\n if let Some(bundle_name) = entry.as_str() {\n let src = stage_path.join(bundle_name);\n if !src.exists() {\n debug!(\n \"Service bundle '{}' not found in staging; skipping\",\n bundle_name\n );\n continue;\n }\n\n let dest = dest_dir.join(bundle_name);\n if dest.exists() {\n let _ = helpers::remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Installing service '{}' → '{}'\",\n src.display(),\n dest.display()\n );\n // Try move, fallback to copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record moved service\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink into Caskroom for reference\n let link = cask_version_install_path.join(bundle_name);\n let _ = helpers::remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // one stanza only\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/keyboard_layout.rs", "// ===== sps-core/src/build/cask/artifacts/keyboard_layout.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Mirrors Homebrew’s `KeyboardLayout < Moved` behavior.\npub fn install_keyboard_layout(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"keyboard_layout\").and_then(|v| v.as_array()) {\n // Target directory for user keyboard layouts\n let dest_dir = config.home_dir().join(\"Library\").join(\"Keyboard Layouts\");\n fs::create_dir_all(&dest_dir)?;\n\n for entry in entries {\n if let Some(bundle_name) = entry.as_str() {\n let src = stage_path.join(bundle_name);\n if !src.exists() {\n debug!(\n \"Keyboard layout '{}' not found in staging; skipping\",\n bundle_name\n );\n continue;\n }\n\n let dest = dest_dir.join(bundle_name);\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Installing keyboard layout '{}' → '{}'\",\n src.display(),\n dest.display()\n );\n // Try move, fallback to copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record moved bundle\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink into Caskroom\n let link = cask_version_install_path.join(bundle_name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // one stanza only\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/prefpane.rs", "// ===== sps-core/src/build/cask/artifacts/prefpane.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Implements the `prefpane` stanza by moving each declared\n/// preference pane bundle from the staging area into\n/// `~/Library/PreferencePanes`, then symlinking it in the Caskroom.\n///\n/// Mirrors Homebrew’s `Prefpane < Moved` pattern.\npub fn install_prefpane(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n // Look for \"prefpane\" entries in the JSON artifacts\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"prefpane\").and_then(|v| v.as_array()) {\n // Target directory for user preference panes\n let dest_dir = config.home_dir().join(\"Library\").join(\"PreferencePanes\");\n fs::create_dir_all(&dest_dir)?;\n\n for entry in entries {\n if let Some(bundle_name) = entry.as_str() {\n let src = stage_path.join(bundle_name);\n if !src.exists() {\n debug!(\n \"Preference pane '{}' not found in staging; skipping\",\n bundle_name\n );\n continue;\n }\n\n let dest = dest_dir.join(bundle_name);\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Installing prefpane '{}' → '{}'\",\n src.display(),\n dest.display()\n );\n // Try move, fallback to copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record moved bundle\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink into Caskroom for reference\n let link = cask_version_install_path.join(bundle_name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // single stanza\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/qlplugin.rs", "// ===== sps-core/src/build/cask/artifacts/qlplugin.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Installs `qlplugin` bundles from the staging area into\n/// `~/Library/QuickLook`, then symlinks them into the Caskroom.\n///\n/// Mirrors Homebrew’s `QuickLook < Moved` pattern for QuickLook plugins.\npub fn install_qlplugin(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n // Look for \"qlplugin\" entries in the JSON artifacts\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"qlplugin\").and_then(|v| v.as_array()) {\n // Target directory for QuickLook plugins\n let dest_dir = config.home_dir().join(\"Library\").join(\"QuickLook\");\n fs::create_dir_all(&dest_dir)?;\n\n for entry in entries {\n if let Some(bundle_name) = entry.as_str() {\n let src = stage_path.join(bundle_name);\n if !src.exists() {\n debug!(\n \"QuickLook plugin '{}' not found in staging; skipping\",\n bundle_name\n );\n continue;\n }\n\n let dest = dest_dir.join(bundle_name);\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Installing QuickLook plugin '{}' → '{}',\",\n src.display(),\n dest.display()\n );\n // Try move, fallback to copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record moved plugin\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink into Caskroom for reference\n let link = cask_version_install_path.join(bundle_name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // single stanza\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/uninstall.rs", "use std::path::PathBuf;\n\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\n\n/// At install time, scan the `uninstall` stanza and turn each directive\n/// into an InstalledArtifact variant, so it can later be torn down.\npub fn record_uninstall(cask: &Cask) -> Result> {\n let mut artifacts = Vec::new();\n\n if let Some(entries) = &cask.artifacts {\n for entry in entries.iter().filter_map(|v| v.as_object()) {\n if let Some(steps) = entry.get(\"uninstall\").and_then(|v| v.as_array()) {\n for step in steps.iter().filter_map(|v| v.as_object()) {\n for (key, val) in step {\n match key.as_str() {\n \"pkgutil\" => {\n if let Some(id) = val.as_str() {\n artifacts.push(InstalledArtifact::PkgUtilReceipt {\n id: id.to_string(),\n });\n }\n }\n \"delete\" => {\n if let Some(arr) = val.as_array() {\n for p in arr.iter().filter_map(|v| v.as_str()) {\n artifacts.push(InstalledArtifact::MovedResource {\n path: PathBuf::from(p),\n });\n }\n }\n }\n \"rmdir\" => {\n if let Some(arr) = val.as_array() {\n for p in arr.iter().filter_map(|v| v.as_str()) {\n artifacts.push(InstalledArtifact::MovedResource {\n path: PathBuf::from(p),\n });\n }\n }\n }\n \"launchctl\" => {\n if let Some(arr) = val.as_array() {\n for lbl in arr.iter().filter_map(|v| v.as_str()) {\n artifacts.push(InstalledArtifact::Launchd {\n label: lbl.to_string(),\n path: None,\n });\n }\n }\n }\n // Add other uninstall keys similarly...\n _ => {}\n }\n }\n }\n }\n }\n }\n\n Ok(artifacts)\n}\n"], ["/sps/sps-net/src/validation.rs", "// sps-io/src/checksum.rs\n//use std::sync::Arc;\nuse std::fs::File;\nuse std::io;\nuse std::path::Path;\n\nuse infer;\nuse sha2::{Digest, Sha256};\nuse sps_common::error::{Result, SpsError};\nuse url::Url;\n//use tokio::fs::File;\n//use tokio::io::AsyncReadExt;\n//use tracing::debug; // Use tracing\n\n///// Asynchronously verifies the SHA256 checksum of a file.\n///// Reads the file asynchronously but performs hashing synchronously.\n//pub async fn verify_checksum_async(path: &Path, expected: &str) -> Result<()> {\n//debug!(\"Async Verifying checksum for: {}\", path.display());\n// let file = File::open(path).await;\n// let mut file = match file {\n// Ok(f) => f,\n// Err(e) => {\n// return Err(SpsError::Io(Arc::new(e))); // Wrap IO error\n// }\n// };\n//\n// let mut hasher = Sha256::new();\n// let mut buffer = Vec::with_capacity(8192); // Use a Vec as buffer for read_buf\n// let mut total_bytes_read = 0;\n//\n// loop {\n// buffer.clear();\n// match file.read_buf(&mut buffer).await {\n// Ok(0) => break, // End of file\n// Ok(n) => {\n// hasher.update(&buffer[..n]);\n// total_bytes_read += n as u64;\n// }\n// Err(e) => {\n// return Err(SpsError::Io(Arc::new(e))); // Wrap IO error\n// }\n// }\n// }\n//\n// let hash_bytes = hasher.finalize();\n// let actual = hex::encode(hash_bytes);\n//\n// debug!(\n// \"Async Calculated SHA256: {} ({} bytes read)\",\n// actual, total_bytes_read\n// );\n// debug!(\"Expected SHA256: {}\", expected);\n//\n// if actual.eq_ignore_ascii_case(expected) {\n// Ok(())\n// } else {\n// Err(SpsError::ChecksumError(format!(\n// \"Checksum mismatch for {}: expected {}, got {}\",\n// path.display(),\n// expected,\n// actual\n// )))\n// }\n//}\n\n// Keep the synchronous version for now if needed elsewhere or for comparison\npub fn verify_checksum(path: &Path, expected: &str) -> Result<()> {\n tracing::debug!(\"Verifying checksum for: {}\", path.display());\n let mut file = File::open(path)?;\n let mut hasher = Sha256::new();\n let bytes_copied = io::copy(&mut file, &mut hasher)?;\n let hash_bytes = hasher.finalize();\n let actual = hex::encode(hash_bytes);\n tracing::debug!(\n \"Calculated SHA256: {} ({} bytes read)\",\n actual,\n bytes_copied\n );\n tracing::debug!(\"Expected SHA256: {}\", expected);\n if actual.eq_ignore_ascii_case(expected) {\n Ok(())\n } else {\n Err(SpsError::ChecksumError(format!(\n \"Checksum mismatch for {}: expected {}, got {}\",\n path.display(),\n expected,\n actual\n )))\n }\n}\n\n/// Verifies that the detected content type of the file matches the expected extension.\npub fn verify_content_type(path: &Path, expected_ext: &str) -> Result<()> {\n let kind_opt = infer::get_from_path(path)?;\n if let Some(kind) = kind_opt {\n let actual_ext = kind.extension();\n if actual_ext.eq_ignore_ascii_case(expected_ext) {\n tracing::debug!(\n \"Content type verified: {} matches expected {}\",\n actual_ext,\n expected_ext\n );\n Ok(())\n } else {\n Err(SpsError::Generic(format!(\n \"Content type mismatch for {}: expected extension '{}', but detected '{}'\",\n path.display(),\n expected_ext,\n actual_ext\n )))\n }\n } else {\n Err(SpsError::Generic(format!(\n \"Could not determine content type for {}\",\n path.display()\n )))\n }\n}\n\n/// Validates a URL, ensuring it uses the HTTPS scheme.\npub fn validate_url(url_str: &str) -> Result<()> {\n let url = Url::parse(url_str)\n .map_err(|e| SpsError::Generic(format!(\"Failed to parse URL '{url_str}': {e}\")))?;\n if url.scheme() == \"https\" {\n Ok(())\n } else {\n Err(SpsError::ValidationError(format!(\n \"Invalid URL scheme for '{}': Must be https, but got '{}'\",\n url_str,\n url.scheme()\n )))\n }\n}\n"], ["/sps/sps-core/src/upgrade/source.rs", "// sps-core/src/upgrade/source.rs\n\nuse std::path::{Path, PathBuf};\n\nuse sps_common::config::Config;\nuse sps_common::error::{Result as SpsResult, SpsError};\nuse sps_common::model::formula::Formula;\nuse tracing::{debug, error};\n\nuse crate::check::installed::InstalledPackageInfo;\nuse crate::{build, uninstall};\n\n/// Upgrades a formula that was/will be installed from source.\n///\n/// This involves:\n/// 1. Uninstalling the old version of the formula.\n/// 2. Building and installing the new version from source.\n/// 3. Linking the new version.\npub async fn upgrade_source_formula(\n formula: &Formula,\n new_source_download_path: &Path,\n old_install_info: &InstalledPackageInfo,\n config: &Config,\n all_installed_dependency_paths: &[PathBuf], // For build environment\n) -> SpsResult {\n debug!(\n \"Upgrading source-built formula {} from {} to {}\",\n formula.name(),\n old_install_info.version,\n formula.version_str_full()\n );\n\n // 1. Uninstall the old version\n debug!(\n \"Uninstalling old source-built version: {} at {}\",\n old_install_info.version,\n old_install_info.path.display()\n );\n let uninstall_opts = uninstall::UninstallOptions { skip_zap: true };\n uninstall::formula::uninstall_formula_artifacts(old_install_info, config, &uninstall_opts)\n .map_err(|e| {\n error!(\n \"Failed to uninstall old version {} of formula {}: {}\",\n old_install_info.version,\n formula.name(),\n e\n );\n SpsError::InstallError(format!(\n \"Failed to uninstall old version during source upgrade of {}: {e}\",\n formula.name()\n ))\n })?;\n debug!(\n \"Successfully uninstalled old source-built version of {}\",\n formula.name()\n );\n\n // 2. Build and install the new version from source\n debug!(\n \"Building new version of {} from source path {}\",\n formula.name(),\n new_source_download_path.display()\n );\n let installed_keg_path = build::compile::build_from_source(\n new_source_download_path,\n formula,\n config,\n all_installed_dependency_paths,\n )\n .await\n .map_err(|e| {\n error!(\n \"Failed to build new version of formula {} from source: {}\",\n formula.name(),\n e\n );\n SpsError::InstallError(format!(\n \"Failed to build new version from source during upgrade of {}: {e}\",\n formula.name()\n ))\n })?;\n debug!(\n \"Successfully built and installed new version of {} to {}\",\n formula.name(),\n installed_keg_path.display()\n );\n\n // 3. Linking is handled by the worker after this function returns the path.\n\n Ok(installed_keg_path)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/preflight.rs", "use std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::InstalledArtifact;\n\n/// Execute any `preflight` commands listed in the Cask’s JSON artifact stanza.\n/// Returns an empty Vec since preflight does not produce install artifacts.\npub fn run_preflight(\n cask: &Cask,\n stage_path: &Path,\n _config: &Config,\n) -> Result> {\n // Iterate over artifacts, look for \"preflight\" keys\n if let Some(entries) = &cask.artifacts {\n for entry in entries.iter().filter_map(|v| v.as_object()) {\n if let Some(cmds) = entry.get(\"preflight\").and_then(|v| v.as_array()) {\n for cmd_val in cmds.iter().filter_map(|v| v.as_str()) {\n // Substitute $STAGEDIR placeholder\n let cmd_str = cmd_val.replace(\"$STAGEDIR\", stage_path.to_str().unwrap());\n debug!(\"Running preflight: {}\", cmd_str);\n let status = Command::new(\"sh\").arg(\"-c\").arg(&cmd_str).status()?;\n if !status.success() {\n return Err(SpsError::InstallError(format!(\n \"preflight failed: {cmd_str}\"\n )));\n }\n }\n }\n }\n }\n\n // No install artifacts to return\n Ok(Vec::new())\n}\n"], ["/sps/sps-common/src/model/version.rs", "// **File:** sps-core/src/model/version.rs (New file)\nuse std::fmt;\nuse std::str::FromStr;\n\nuse serde::{Deserialize, Deserializer, Serialize, Serializer};\n\nuse crate::error::{Result, SpsError};\n\n/// Wrapper around semver::Version for formula versions.\n#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]\npub struct Version(semver::Version);\n\nimpl Version {\n pub fn parse(s: &str) -> Result {\n // Attempt standard semver parse first\n semver::Version::parse(s).map(Version).or_else(|_| {\n // Homebrew often uses versions like \"1.2.3_1\" (revision) or just \"123\"\n // Try to handle these by stripping suffixes or padding\n // This is a simplified handling, Homebrew's PkgVersion is complex\n let cleaned = s.split('_').next().unwrap_or(s); // Take part before _\n let parts: Vec<&str> = cleaned.split('.').collect();\n let padded = match parts.len() {\n 1 => format!(\"{}.0.0\", parts[0]),\n 2 => format!(\"{}.{}.0\", parts[0], parts[1]),\n _ => cleaned.to_string(), // Use original if 3+ parts\n };\n semver::Version::parse(&padded).map(Version).map_err(|e| {\n SpsError::VersionError(format!(\n \"Failed to parse version '{s}' (tried '{padded}'): {e}\"\n ))\n })\n })\n }\n}\n\nimpl FromStr for Version {\n type Err = SpsError;\n fn from_str(s: &str) -> std::result::Result {\n Self::parse(s)\n }\n}\n\nimpl fmt::Display for Version {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n // TODO: Preserve original format if possible? PkgVersion complexity.\n // For now, display the parsed semver representation.\n write!(f, \"{}\", self.0)\n }\n}\n\n// Manual Serialize/Deserialize to handle the Version<->String conversion\nimpl Serialize for Version {\n fn serialize(&self, serializer: S) -> std::result::Result\n where\n S: Serializer,\n {\n serializer.serialize_str(&self.to_string())\n }\n}\n\nimpl AsRef for Version {\n fn as_ref(&self) -> &Self {\n self\n }\n}\n\n// Removed redundant ToString implementation as it conflicts with the blanket implementation in std.\n\nimpl From for semver::Version {\n fn from(version: Version) -> Self {\n version.0\n }\n}\n\nimpl<'de> Deserialize<'de> for Version {\n fn deserialize(deserializer: D) -> std::result::Result\n where\n D: Deserializer<'de>,\n {\n let s = String::deserialize(deserializer)?;\n Self::from_str(&s).map_err(serde::de::Error::custom)\n }\n}\n\n// Add to sps-core/src/utils/error.rs:\n// #[error(\"Version error: {0}\")]\n// VersionError(String),\n\n// Add to sps-core/Cargo.toml:\n// [dependencies]\n// semver = \"1.0\"\n"], ["/sps/sps-core/src/uninstall/formula.rs", "// sps-core/src/uninstall/formula.rs\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse tracing::{debug, error, warn};\n\nuse crate::check::installed::InstalledPackageInfo;\nuse crate::install; // For install::bottle::link\nuse crate::uninstall::common::{remove_filesystem_artifact, UninstallOptions};\n\npub fn uninstall_formula_artifacts(\n info: &InstalledPackageInfo,\n config: &Config,\n _options: &UninstallOptions, /* options currently unused for formula but kept for signature\n * consistency */\n) -> Result<()> {\n debug!(\n \"Uninstalling Formula artifacts for {} version {}\",\n info.name, info.version\n );\n\n // 1. Unlink artifacts\n // This function should handle removal of symlinks from /opt/sps/bin, /opt/sps/lib etc.\n // and the /opt/sps/opt/formula_name link.\n install::bottle::link::unlink_formula_artifacts(&info.name, &info.version, config)?;\n\n // 2. Remove the keg directory\n if info.path.exists() {\n debug!(\"Removing formula keg directory: {}\", info.path.display());\n // For formula kegs, we generally expect them to be owned by the user or sps,\n // but sudo might be involved if permissions were changed manually or during a problematic\n // install. Setting use_sudo to true provides a fallback, though ideally it's not\n // needed for user-owned kegs.\n let use_sudo = true;\n if !remove_filesystem_artifact(&info.path, use_sudo) {\n // Check if it still exists after the removal attempt\n if info.path.exists() {\n error!(\n \"Failed remove keg {}: Check logs for sudo errors or other filesystem issues.\",\n info.path.display()\n );\n return Err(SpsError::InstallError(format!(\n \"Failed to remove keg directory: {}\",\n info.path.display()\n )));\n } else {\n // It means remove_filesystem_artifact returned false but the dir is gone\n // (possibly removed by sudo, or a race condition if another process removed it)\n debug!(\"Keg directory successfully removed (possibly with sudo).\");\n }\n }\n } else {\n warn!(\n \"Keg directory {} not found during uninstall. It might have been already removed.\",\n info.path.display()\n );\n }\n Ok(())\n}\n"], ["/sps/sps/src/cli/upgrade.rs", "use std::sync::Arc;\n\nuse clap::Args;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_core::check::installed;\n\nuse crate::pipeline::runner::{self, CommandType, PipelineFlags};\n\n#[derive(Args, Debug)]\npub struct UpgradeArgs {\n #[arg()]\n pub names: Vec,\n\n #[arg(long, conflicts_with = \"names\")]\n pub all: bool,\n\n #[arg(long)]\n pub build_from_source: bool,\n}\n\nimpl UpgradeArgs {\n pub async fn run(&self, config: &Config, cache: Arc) -> Result<()> {\n let targets = if self.all {\n // Get all installed package names\n let installed = installed::get_installed_packages(config).await?;\n installed.into_iter().map(|p| p.name).collect()\n } else {\n self.names.clone()\n };\n\n if targets.is_empty() {\n return Ok(());\n }\n\n let flags = PipelineFlags {\n // Populate flags from args\n build_from_source: self.build_from_source,\n // Upgrade should respect original install options ideally,\n // but for now let's default them. This could be enhanced later\n // by reading install receipts.\n include_optional: false,\n skip_recommended: false,\n // ... add other common flags if needed ...\n };\n\n runner::run_pipeline(\n &targets,\n CommandType::Upgrade { all: self.all },\n config,\n cache,\n &flags,\n )\n .await\n }\n}\n"], ["/sps/sps-common/src/cache.rs", "// src/utils/cache.rs\n// Handles caching of formula data and downloads\n\nuse std::fs;\nuse std::path::{Path, PathBuf};\nuse std::time::{Duration, SystemTime};\n\nuse super::error::{Result, SpsError};\nuse crate::Config;\n\n/// Define how long cache entries are considered valid\nconst CACHE_TTL: Duration = Duration::from_secs(24 * 60 * 60); // 24 hours\n\n/// Cache struct to manage cache operations\npub struct Cache {\n cache_dir: PathBuf,\n _config: Config, // Keep a reference to config if needed for other paths or future use\n}\n\nimpl Cache {\n /// Create a new Cache using the config's cache_dir\n pub fn new(config: &Config) -> Result {\n let cache_dir = config.cache_dir();\n if !cache_dir.exists() {\n fs::create_dir_all(&cache_dir)?;\n }\n\n Ok(Self {\n cache_dir,\n _config: config.clone(),\n })\n }\n\n /// Gets the cache directory path\n pub fn get_dir(&self) -> &Path {\n &self.cache_dir\n }\n\n /// Stores raw string data in the cache\n pub fn store_raw(&self, filename: &str, data: &str) -> Result<()> {\n let path = self.cache_dir.join(filename);\n tracing::debug!(\"Saving raw data to cache file: {:?}\", path);\n fs::write(&path, data)?;\n Ok(())\n }\n\n /// Loads raw string data from the cache\n pub fn load_raw(&self, filename: &str) -> Result {\n let path = self.cache_dir.join(filename);\n tracing::debug!(\"Loading raw data from cache file: {:?}\", path);\n\n if !path.exists() {\n return Err(SpsError::Cache(format!(\n \"Cache file {filename} does not exist\"\n )));\n }\n\n fs::read_to_string(&path).map_err(|e| SpsError::Cache(format!(\"IO error: {e}\")))\n }\n\n /// Checks if a cache file exists and is valid (within TTL)\n pub fn is_cache_valid(&self, filename: &str) -> Result {\n let path = self.cache_dir.join(filename);\n if !path.exists() {\n return Ok(false);\n }\n\n let metadata = fs::metadata(&path)?;\n let modified_time = metadata.modified()?;\n let age = SystemTime::now()\n .duration_since(modified_time)\n .map_err(|e| SpsError::Cache(format!(\"System time error: {e}\")))?;\n\n Ok(age <= CACHE_TTL)\n }\n\n /// Clears a specific cache file\n pub fn clear_file(&self, filename: &str) -> Result<()> {\n let path = self.cache_dir.join(filename);\n if path.exists() {\n fs::remove_file(&path)?;\n }\n Ok(())\n }\n\n /// Clears all cache files\n pub fn clear_all(&self) -> Result<()> {\n if self.cache_dir.exists() {\n fs::remove_dir_all(&self.cache_dir)?;\n fs::create_dir_all(&self.cache_dir)?;\n }\n Ok(())\n }\n\n /// Gets a reference to the config\n pub fn config(&self) -> &Config {\n &self._config\n }\n}\n"], ["/sps/sps-common/src/dependency/definition.rs", "// **File:** sps-core/src/dependency/dependency.rs // Should be in the model module\nuse std::fmt;\n\nuse bitflags::bitflags;\nuse serde::{Deserialize, Serialize};\n\nbitflags! {\n #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]\n pub struct DependencyTag: u8 {\n const RUNTIME = 0b00000001;\n const BUILD = 0b00000010;\n const TEST = 0b00000100;\n const OPTIONAL = 0b00001000;\n const RECOMMENDED = 0b00010000;\n }\n}\n\nimpl Default for DependencyTag {\n fn default() -> Self {\n Self::RUNTIME\n }\n}\n\nimpl fmt::Display for DependencyTag {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"{self:?}\")\n }\n}\n\n#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]\npub struct Dependency {\n pub name: String,\n #[serde(default)]\n pub tags: DependencyTag,\n}\n\nimpl Dependency {\n pub fn new_runtime(name: impl Into) -> Self {\n Self {\n name: name.into(),\n tags: DependencyTag::RUNTIME,\n }\n }\n\n pub fn new_with_tags(name: impl Into, tags: DependencyTag) -> Self {\n Self {\n name: name.into(),\n tags,\n }\n }\n}\n\npub trait DependencyExt {\n fn filter_by_tags(&self, include: DependencyTag, exclude: DependencyTag) -> Vec<&Dependency>;\n fn runtime(&self) -> Vec<&Dependency>;\n fn build_time(&self) -> Vec<&Dependency>;\n}\n\nimpl DependencyExt for Vec {\n fn filter_by_tags(&self, include: DependencyTag, exclude: DependencyTag) -> Vec<&Dependency> {\n self.iter()\n .filter(|dep| dep.tags.contains(include) && !dep.tags.intersects(exclude))\n .collect()\n }\n\n fn runtime(&self) -> Vec<&Dependency> {\n // A dependency is runtime if its tags indicate it's needed at runtime.\n // This includes standard runtime, recommended, or optional dependencies.\n // Build-only or Test-only dependencies (without other runtime flags) are excluded.\n self.iter()\n .filter(|dep| {\n dep.tags.intersects(\n DependencyTag::RUNTIME | DependencyTag::RECOMMENDED | DependencyTag::OPTIONAL,\n )\n })\n .collect()\n }\n\n fn build_time(&self) -> Vec<&Dependency> {\n self.filter_by_tags(DependencyTag::BUILD, DependencyTag::empty())\n }\n}\n"], ["/sps/sps/src/cli.rs", "// sps/src/cli.rs\n//! Defines the command-line argument structure using clap.\nuse std::sync::Arc;\n\nuse clap::{ArgAction, Parser, Subcommand};\nuse sps_common::error::Result;\nuse sps_common::{Cache, Config};\n\n// Module declarations\npub mod info;\npub mod init;\npub mod install;\npub mod list;\npub mod reinstall;\npub mod search;\npub mod status;\npub mod uninstall;\npub mod update;\npub mod upgrade;\n// Re-export InitArgs to make it accessible as cli::InitArgs\n// Import other command Args structs\nuse crate::cli::info::Info;\npub use crate::cli::init::InitArgs;\nuse crate::cli::install::InstallArgs;\nuse crate::cli::list::List;\nuse crate::cli::reinstall::ReinstallArgs;\nuse crate::cli::search::Search;\nuse crate::cli::uninstall::Uninstall;\nuse crate::cli::update::Update;\nuse crate::cli::upgrade::UpgradeArgs;\n\n#[derive(Parser, Debug)]\n#[command(author, version, about, long_about = None, name = \"sps\", bin_name = \"sps\")]\n#[command(propagate_version = true)]\npub struct CliArgs {\n #[arg(short, long, action = ArgAction::Count, global = true)]\n pub verbose: u8,\n\n #[command(subcommand)]\n pub command: Command,\n}\n\n#[derive(Subcommand, Debug)]\npub enum Command {\n Init(InitArgs),\n Search(Search),\n List(List),\n Info(Info),\n Update(Update),\n Install(InstallArgs),\n Uninstall(Uninstall),\n Reinstall(ReinstallArgs),\n Upgrade(UpgradeArgs),\n}\n\nimpl Command {\n pub async fn run(&self, config: &Config, cache: Arc) -> Result<()> {\n match self {\n Self::Init(command) => command.run(config).await,\n Self::Search(command) => command.run(config, cache).await,\n Self::List(command) => command.run(config, cache).await,\n Self::Info(command) => command.run(config, cache).await,\n Self::Update(command) => command.run(config, cache).await,\n // Commands that use the pipeline\n Self::Install(command) => command.run(config, cache).await,\n Self::Reinstall(command) => command.run(config, cache).await,\n Self::Upgrade(command) => command.run(config, cache).await,\n Self::Uninstall(command) => command.run(config, cache).await,\n }\n }\n}\n\n// In install.rs, reinstall.rs, upgrade.rs, their run methods will now call\n// sps::cli::pipeline_runner::run_pipeline(...)\n// e.g., in sps/src/cli/install.rs:\n// use crate::cli::pipeline_runner::{self, CommandType, PipelineFlags};\n// ...\n// pipeline_runner::run_pipeline(&initial_targets, CommandType::Install, config, cache,\n// &flags).await\n"], ["/sps/sps-common/src/error.rs", "use std::sync::Arc;\n\nuse thiserror::Error;\n\n#[derive(Error, Debug, Clone)]\npub enum SpsError {\n #[error(\"I/O Error: {0}\")]\n Io(#[from] Arc),\n\n #[error(\"HTTP Request Error: {0}\")]\n Http(#[from] Arc),\n\n #[error(\"JSON Parsing Error: {0}\")]\n Json(#[from] Arc),\n\n #[error(\"Semantic Versioning Error: {0}\")]\n SemVer(#[from] Arc),\n\n #[error(\"Object File Error: {0}\")]\n Object(#[from] Arc),\n\n #[error(\"Configuration Error: {0}\")]\n Config(String),\n\n #[error(\"API Error: {0}\")]\n Api(String),\n\n #[error(\"API Request Error: {0}\")]\n ApiRequestError(String),\n\n #[error(\"DownloadError: Failed to download '{0}' from '{1}': {2}\")]\n DownloadError(String, String, String),\n\n #[error(\"Cache Error: {0}\")]\n Cache(String),\n\n #[error(\"Resource Not Found: {0}\")]\n NotFound(String),\n\n #[error(\"Installation Error: {0}\")]\n InstallError(String),\n\n #[error(\"Generic Error: {0}\")]\n Generic(String),\n\n #[error(\"HttpError: {0}\")]\n HttpError(String),\n\n #[error(\"Checksum Mismatch: {0}\")]\n ChecksumMismatch(String),\n\n #[error(\"Validation Error: {0}\")]\n ValidationError(String),\n\n #[error(\"Checksum Error: {0}\")]\n ChecksumError(String),\n\n #[error(\"Parsing Error in {0}: {1}\")]\n ParseError(&'static str, String),\n\n #[error(\"Version error: {0}\")]\n VersionError(String),\n\n #[error(\"Dependency Error: {0}\")]\n DependencyError(String),\n\n #[error(\"Build environment setup failed: {0}\")]\n BuildEnvError(String),\n\n #[error(\"IoError: {0}\")]\n IoError(String),\n\n #[error(\"Failed to execute command: {0}\")]\n CommandExecError(String),\n\n #[error(\"Mach-O Error: {0}\")]\n MachOError(String),\n\n #[error(\"Mach-O Modification Error: {0}\")]\n MachOModificationError(String),\n\n #[error(\"Mach-O Relocation Error: Path too long - {0}\")]\n PathTooLongError(String),\n\n #[error(\"Codesign Error: {0}\")]\n CodesignError(String),\n}\n\nimpl From for SpsError {\n fn from(err: std::io::Error) -> Self {\n SpsError::Io(Arc::new(err))\n }\n}\n\nimpl From for SpsError {\n fn from(err: reqwest::Error) -> Self {\n SpsError::Http(Arc::new(err))\n }\n}\n\nimpl From for SpsError {\n fn from(err: serde_json::Error) -> Self {\n SpsError::Json(Arc::new(err))\n }\n}\n\nimpl From for SpsError {\n fn from(err: semver::Error) -> Self {\n SpsError::SemVer(Arc::new(err))\n }\n}\n\nimpl From for SpsError {\n fn from(err: object::read::Error) -> Self {\n SpsError::Object(Arc::new(err))\n }\n}\n\npub type Result = std::result::Result;\n"], ["/sps/sps/src/cli/reinstall.rs", "// sps-cli/src/cli/reinstall.rs\nuse std::sync::Arc;\n\nuse clap::Args;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::error::Result;\n\nuse crate::pipeline::runner::{self, CommandType, PipelineFlags};\n\n#[derive(Args, Debug)]\npub struct ReinstallArgs {\n #[arg(required = true)]\n pub names: Vec,\n\n #[arg(\n long,\n help = \"Force building the formula from source, even if a bottle is available\"\n )]\n pub build_from_source: bool,\n}\n\nimpl ReinstallArgs {\n pub async fn run(&self, config: &Config, cache: Arc) -> Result<()> {\n let flags = PipelineFlags {\n // Populate flags from args\n build_from_source: self.build_from_source,\n include_optional: false, // Reinstall usually doesn't change optional deps\n skip_recommended: true, /* Reinstall usually doesn't change recommended deps\n * ... add other common flags if needed ... */\n };\n runner::run_pipeline(&self.names, CommandType::Reinstall, config, cache, &flags).await\n }\n}\n"], ["/sps/sps-common/src/model/artifact.rs", "// sps-common/src/model/artifact.rs\nuse std::path::PathBuf;\n\nuse serde::{Deserialize, Serialize};\n\n/// Represents an item installed or managed by sps, recorded in the manifest.\n#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)] // Added Hash\n#[serde(tag = \"type\", rename_all = \"snake_case\")]\npub enum InstalledArtifact {\n /// The main application bundle (e.g., in /Applications).\n AppBundle { path: PathBuf },\n /// A command-line binary symlinked into the prefix's bin dir.\n BinaryLink {\n link_path: PathBuf,\n target_path: PathBuf,\n },\n /// A man page symlinked into the prefix's man dir.\n ManpageLink {\n link_path: PathBuf,\n target_path: PathBuf,\n },\n /// A resource moved to a standard system/user location (e.g., Font, PrefPane).\n MovedResource { path: PathBuf },\n /// A macOS package receipt ID managed by pkgutil.\n PkgUtilReceipt { id: String },\n /// A launchd service (Agent/Daemon).\n Launchd {\n label: String,\n path: Option,\n }, // Path is the plist file\n /// A symlink created within the Caskroom pointing to the actual installed artifact.\n /// Primarily for internal reference and potentially easier cleanup if needed.\n CaskroomLink {\n link_path: PathBuf,\n target_path: PathBuf,\n },\n /// A file copied *into* the Caskroom (e.g., a .pkg installer).\n CaskroomReference { path: PathBuf },\n}\n\n// Optional: Helper methods if needed\n// impl InstalledArtifact { ... }\n"], ["/sps/sps-net/src/lib.rs", "// spm-fetch/src/lib.rs\npub mod api;\npub mod http;\npub mod oci;\npub mod validation;\n\n// Re-export necessary types from sps-core IF using Option A from Step 3\n// If using Option B (DTOs), you wouldn't depend on sps-core here for models.\n// Re-export the public fetching functions - ensure they are `pub`\npub use api::{\n fetch_all_casks, fetch_all_formulas, fetch_cask, fetch_formula, get_cask, /* ... */\n get_formula,\n};\npub use http::{fetch_formula_source_or_bottle, fetch_resource /* ... */};\npub use oci::{build_oci_client /* ... */, download_oci_blob, fetch_oci_manifest_index};\npub use sps_common::{\n model::{\n cask::{Sha256Field, UrlField},\n formula::ResourceSpec,\n Cask, Formula,\n }, // Example types needed\n {\n cache::Cache,\n error::{Result, SpsError},\n Config,\n }, // Need Config, Result, SpsError, Cache\n};\n\npub use crate::validation::{validate_url, verify_checksum, verify_content_type /* ... */};\n"], ["/sps/sps-common/src/dependency/requirement.rs", "// **File:** sps-core/src/dependency/requirement.rs (New file)\nuse std::fmt;\n\nuse serde::{Deserialize, Serialize};\n\n#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]\npub enum Requirement {\n MacOS(String),\n Xcode(String),\n Other(String),\n}\n\nimpl fmt::Display for Requirement {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n match self {\n Self::MacOS(v) => write!(f, \"macOS >= {v}\"),\n Self::Xcode(v) => write!(f, \"Xcode >= {v}\"),\n Self::Other(s) => write!(f, \"Requirement: {s}\"),\n }\n }\n}\n"], ["/sps/sps-common/src/model/mod.rs", "// src/model/mod.rs\n// Declares the modules within the model directory.\nuse std::sync::Arc;\n\npub mod artifact;\npub mod cask;\npub mod formula;\npub mod tap;\npub mod version;\n\n// Re-export\npub use artifact::InstalledArtifact;\npub use cask::Cask;\npub use formula::Formula;\n\n#[derive(Debug, Clone)]\npub enum InstallTargetIdentifier {\n Formula(Arc),\n Cask(Arc),\n}\n"], ["/sps/sps-core/src/install/mod.rs", "// ===== sps-core/src/build/mod.rs =====\n// Main module for build functionality\n// Removed deprecated functions and re-exports.\n\nuse std::path::PathBuf;\n\nuse sps_common::config::Config;\nuse sps_common::model::formula::Formula;\n\n// --- Submodules ---\npub mod bottle;\npub mod cask;\npub mod devtools;\npub mod extract;\n\n// --- Path helpers using Config ---\npub fn get_formula_opt_path(formula: &Formula, config: &Config) -> PathBuf {\n // Use new Config method\n config.formula_opt_path(formula.name())\n}\n\n// --- DEPRECATED EXTRACTION FUNCTIONS REMOVED ---\n"], ["/sps/sps-common/src/lib.rs", "// sps-common/src/lib.rs\npub mod cache;\npub mod config;\npub mod dependency;\npub mod error;\npub mod formulary;\npub mod keg;\npub mod model;\npub mod pipeline;\n// Optional: pub mod dependency_def;\n\n// Re-export key types\npub use cache::Cache;\npub use config::Config;\npub use error::{Result, SpsError};\npub use model::{Cask, Formula, InstalledArtifact}; // etc.\n // Optional: pub use dependency_def::{Dependency, DependencyTag};\n"], ["/sps/sps-core/src/upgrade/mod.rs", "// sps-core/src/upgrade/mod.rs\n\npub mod bottle;\npub mod cask;\npub mod source;\n\n// Re-export key upgrade functions\npub use self::bottle::upgrade_bottle_formula;\npub use self::cask::upgrade_cask_package;\npub use self::source::upgrade_source_formula;\n"], ["/sps/sps-core/src/lib.rs", "// sps-core/src/lib.rs\n\n// Declare the top-level modules within the library crate\npub mod build;\npub mod check;\npub mod install;\npub mod pipeline;\npub mod uninstall;\npub mod upgrade; // New\n#[cfg(target_os = \"macos\")]\npub mod utils; // New\n //pub mod utils;\n\n// Re-export key types for easier use by the CLI crate\n// Define InstallTargetIdentifier here or ensure it's public from cli/pipeline\n// For simplicity, let's define it here for now:\n\n// New\npub use uninstall::UninstallOptions; // New\n // New\n"], ["/sps/sps-core/src/uninstall/mod.rs", "// sps-core/src/uninstall/mod.rs\n\npub mod cask;\npub mod common;\npub mod formula;\n\n// Re-export key functions and types\npub use cask::{uninstall_cask_artifacts, zap_cask_artifacts};\npub use common::UninstallOptions;\npub use formula::uninstall_formula_artifacts;\n"], ["/sps/sps-common/src/dependency/mod.rs", "pub mod definition; // Renamed from 'dependency'\npub mod requirement;\npub mod resolver;\n\n// Re-export key types for easier access\npub use definition::{Dependency, DependencyExt, DependencyTag}; // Updated source module\npub use requirement::Requirement;\npub use resolver::{\n DependencyResolver, ResolutionContext, ResolutionStatus, ResolvedDependency, ResolvedGraph,\n};\n"], ["/sps/sps-core/src/install/cask/artifacts/mod.rs", "pub mod app;\npub mod audio_unit_plugin;\npub mod binary;\npub mod colorpicker;\npub mod dictionary;\npub mod font;\npub mod input_method;\npub mod installer;\npub mod internet_plugin;\npub mod keyboard_layout;\npub mod manpage;\npub mod mdimporter;\npub mod pkg;\npub mod preflight;\npub mod prefpane;\npub mod qlplugin;\npub mod screen_saver;\npub mod service;\npub mod suite;\npub mod uninstall;\npub mod vst3_plugin;\npub mod vst_plugin;\npub mod zap;\n\n// Re‑export a single enum if you like:\npub use self::app::install_app_from_staged;\npub use self::audio_unit_plugin::install_audio_unit_plugin;\npub use self::binary::install_binary;\npub use self::colorpicker::install_colorpicker;\npub use self::dictionary::install_dictionary;\npub use self::font::install_font;\npub use self::input_method::install_input_method;\npub use self::installer::run_installer;\npub use self::internet_plugin::install_internet_plugin;\npub use self::keyboard_layout::install_keyboard_layout;\npub use self::manpage::install_manpage;\npub use self::mdimporter::install_mdimporter;\npub use self::pkg::install_pkg_from_path;\npub use self::preflight::run_preflight;\npub use self::prefpane::install_prefpane;\npub use self::qlplugin::install_qlplugin;\npub use self::screen_saver::install_screen_saver;\npub use self::service::install_service;\npub use self::suite::install_suite;\npub use self::uninstall::record_uninstall;\npub use self::vst3_plugin::install_vst3_plugin;\npub use self::vst_plugin::install_vst_plugin;\n"], ["/sps/sps-core/src/check/mod.rs", "pub mod installed;\npub mod update;\n\npub use installed::{InstalledPackageInfo, PackageType};\npub use update::UpdateInfo;\n"], ["/sps/sps-core/src/utils/mod.rs", "#[cfg(target_os = \"macos\")]\npub mod applescript;\n#[cfg(target_os = \"macos\")]\npub mod xattr;\n"], ["/sps/sps/src/pipeline.rs", "pub mod downloader;\npub mod planner;\npub mod runner;\n"], ["/sps/sps-core/src/pipeline/mod.rs", "pub mod engine;\npub mod worker;\n"]], "task_instance_info": {"created_time": "2025-08-21 01:45:07", "created_task_model": "DeepSeek-R1", "function_skeleton": "async fn plan_for_install (&self, targets: &[String]) -> PlanResult {}", "code_description": "This code segment functions to: Assess installation requirements for specified targets by verifying current installation status, checking manifest validity for existing entries, and preparing installation operations while tracking pre-existing satisfied conditions and errors."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```rust\n[TASK_BEGIN]\n async fn plan_for_install(&self, targets: &[String]) -> PlanResult {\n let mut plan = IntermediatePlan::default();\n for name in targets {\n if plan.processed_globally.contains(name) {\n continue;\n }\n \n match self.check_installed_status(name).await {\n Ok(Some(installed_info)) => {\n plan.already_satisfied.insert(name.clone());\n plan.processed_globally.insert(name.clone());\n \n if installed_info.pkg_type == CorePackageType::Cask {\n if let Some(private_path) = self\n .determine_cask_private_store_source(name, &installed_info.version)\n .await\n {\n plan.private_store_sources\n .insert(name.clone(), private_path);\n }\n }\n }\n Ok(None) => {\n plan.initial_ops.insert(\n name.clone(),\n (JobAction::Install, None),\n );\n }\n Err(e) => {\n plan.errors.push((\n name.clone(),\n SpsError::Generic(format!(\"Failed to check status for '{name}': {e}\")),\n ));\n plan.processed_globally.insert(name.clone());\n }\n }\n }\n Ok(plan)\n }\n[TASK_END]\n```", "inference_time": "2025-08-21 01-45-56"}, "editdistance_info": {"edit_distance": 37.8277, "calculate_time": "2025-08-21 01:45:56", "true_code_clean": "async fn plan_for_install(&self, targets: &[String]) -> PlanResult {\n let mut plan = IntermediatePlan::default();\n for name in targets {\n if plan.processed_globally.contains(name) {\n continue;\n }\n match self.check_installed_status(name).await {\n Ok(Some(installed_info)) => {\n let mut proceed_with_install = false;\n if installed_info.pkg_type == CorePackageType::Cask {\n let manifest_path = installed_info.path.join(\"CASK_INSTALL_MANIFEST.json\");\n if manifest_path.is_file() {\n if let Ok(manifest_str) = std::fs::read_to_string(&manifest_path) {\n if let Ok(manifest_json) =\n serde_json::from_str::(&manifest_str)\n {\n if let Some(is_installed_flag) =\n manifest_json.get(\"is_installed\").and_then(|v| v.as_bool())\n {\n if !is_installed_flag {\n debug!(\"Cask '{}' found but marked as not installed in manifest. Proceeding with install.\", name);\n proceed_with_install = true;\n }\n }\n }\n }\n } else {\n debug!(\n \"Cask '{}' found but manifest missing. Assuming needs install.\",\n name\n );\n proceed_with_install = true;\n }\n }\n if proceed_with_install {\n if let Some(private_path) = self\n .determine_cask_private_store_source(name, &installed_info.version)\n .await\n {\n plan.private_store_sources\n .insert(name.clone(), private_path);\n }\n plan.initial_ops\n .insert(name.clone(), (JobAction::Install, None));\n } else {\n debug!(\"Target '{}' already installed and manifest indicates it. Marking as satisfied.\", name);\n plan.already_satisfied.insert(name.clone());\n plan.processed_globally.insert(name.clone());\n }\n }\n Ok(None) => {\n if let Some(private_path) = self\n .determine_cask_private_store_source(name, \"latest\")\n .await\n {\n plan.private_store_sources\n .insert(name.clone(), private_path);\n }\n plan.initial_ops\n .insert(name.clone(), (JobAction::Install, None));\n }\n Err(e) => {\n plan.errors.push((\n name.clone(),\n SpsError::Generic(format!(\n \"Failed to check installed status for {name}: {e}\"\n )),\n ));\n plan.processed_globally.insert(name.clone());\n }\n }\n }\n Ok(plan)\n }", "predict_code_clean": "async fn plan_for_install(&self, targets: &[String]) -> PlanResult {\n let mut plan = IntermediatePlan::default();\n for name in targets {\n if plan.processed_globally.contains(name) {\n continue;\n }\n match self.check_installed_status(name).await {\n Ok(Some(installed_info)) => {\n plan.already_satisfied.insert(name.clone());\n plan.processed_globally.insert(name.clone());\n if installed_info.pkg_type == CorePackageType::Cask {\n if let Some(private_path) = self\n .determine_cask_private_store_source(name, &installed_info.version)\n .await\n {\n plan.private_store_sources\n .insert(name.clone(), private_path);\n }\n }\n }\n Ok(None) => {\n plan.initial_ops.insert(\n name.clone(),\n (JobAction::Install, None),\n );\n }\n Err(e) => {\n plan.errors.push((\n name.clone(),\n SpsError::Generic(format!(\"Failed to check status for '{name}': {e}\")),\n ));\n plan.processed_globally.insert(name.clone());\n }\n }\n }\n Ok(plan)\n }"}} {"repo_name": "sps", "file_name": "/sps/sps/src/cli/info.rs", "inference_info": {"prefix_code": "//! Contains the logic for the `info` command.\n\nuse std::sync::Arc;\n\nuse clap::Args;\nuse colored::Colorize;\nuse serde_json::Value;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_net::api;\n\n#[derive(Args, Debug)]\npub struct Info {\n /// Name of the formula or cask\n pub name: String,\n\n /// Show information for a cask, not a formula\n #[arg(long)]\n pub cask: bool,\n}\n\nimpl Info {\n /// Displays detailed information about a formula or cask.\n pub async fn run(&self, _config: &Config, cache: Arc) -> Result<()> {\n let name = &self.name;\n let is_cask = self.cask;\n tracing::debug!(\"Getting info for package: {name}, is_cask: {is_cask}\",);\n\n // Print loading message instead of spinner\n println!(\"Loading info for {name}\");\n\n if self.cask {\n match get_cask_info(Arc::clone(&cache), name).await {\n Ok(info) => {\n print_cask_info(name, &info);\n Ok(())\n }\n Err(e) => Err(e),\n }\n } else {\n match get_formula_info_raw(Arc::clone(&cache), name).await {\n Ok(info) => {\n // Removed bottle check logic here as it was complex and potentially racy.\n // We'll try formula first, then cask if formula fails.\n print_formula_info(name, &info);\n return Ok(());\n }\n Err(SpsError::NotFound(_)) | Err(SpsError::Generic(_)) => {\n // If formula lookup failed (not found or generic error), try cask.\n tracing::debug!(\"Formula '{}' info failed, trying cask.\", name);\n }\n Err(e) => {\n return Err(e); // Propagate other errors (API, JSON, etc.)\n }\n }\n // --- Cask Fallback ---\n match get_cask_info(Arc::clone(&cache), name).await {\n Ok(info) => {\n print_cask_info(name, &info);\n Ok(())\n }\n Err(e) => {\n Err(e) // Return the cask error if both formula and cask fail\n }\n }\n }\n }\n}\n\n/// Retrieves formula information from the cache or API as raw JSON\nasync fn get_formula_info_raw(cache: Arc, name: &str) -> Result {\n match cache.load_raw(\"formula.json\") {\n Ok(formula_data) => {\n let formulas: Vec =\n serde_json::from_str(&formula_data).map_err(SpsError::from)?;\n for formula in formulas {\n if let Some(fname) = formula.get(\"name\").and_then(Value::as_str) {\n if fname == name {\n return Ok(formula);\n }\n }\n // Also check aliases if needed\n if let Some(aliases) = formula.get(\"aliases\").and_then(|a| a.as_array()) {\n if aliases.iter().any(|a| a.as_str() == Some(name)) {\n return Ok(formula);\n }\n }\n }\n tracing::debug!(\"Formula '{}' not found within cached 'formula.json'.\", name);\n // Explicitly return NotFound if not in cache\n return Err(SpsError::NotFound(format!(\n \"Formula '{name}' not found in cache\"\n )));\n }\n Err(e) => tracing::debug!(\n \"Cache file 'formula.json' not found or failed to load ({}). Fetching from API.\",\n e\n ),\n }\n tracing::debug!(\"Fetching formula '{}' directly from API\", name);\n // api::fetch_formula returns Value directly now\n let value = api::fetch_formula(name).await?;\n // Store in cache if fetched successfully\n // Note: This might overwrite the full list cache, consider storing individual files or a map\n // cache.store_raw(&format!(\"formula/{}.json\", name), &value.to_string())?; // Example of\n // storing individually\n Ok(value)\n}\n\n/// Retrieves cask information from the cache or API\nasync fn get_cask_info(cache: Arc, name: &str) -> Result {\n match cache.load_raw(\"cask.json\") {\n Ok(cask_data) => {\n let casks: Vec = serde_json::from_str(&cask_data).map_err(SpsError::from)?;\n for cask in casks {\n if let Some(token) = cask.get(\"token\").and_then(Value::as_str) {\n if token == name {\n return Ok(cask);\n }\n }\n // Check aliases if needed\n if let Some(aliases) = cask.get(\"aliases\").and_then(|a| a.as_array()) {\n if aliases.iter().any(|a| a.as_str() == Some(name)) {\n return Ok(cask);\n }\n }\n }\n tracing::debug!(\"Cask '{}' not found within cached 'cask.json'.\", name);\n // Explicitly return NotFound if not in cache\n return Err(SpsError::NotFound(format!(\n \"Cask '{name}' not found in cache\"\n )));\n }\n Err(e) => tracing::debug!(\n \"Cache file 'cask.json' not found or failed to load ({}). Fetching from API.\",\n e\n ),\n }\n tracing::debug!(\"Fetching cask '{}' directly from API\", name);\n // api::fetch_cask returns Value directly now\n let value = api::fetch_cask(name).await?;\n // Store in cache if fetched successfully\n // cache.store_raw(&format!(\"cask/{}.json\", name), &value.to_string())?; // Example of storing\n // individually\n Ok(value)\n}\n\n/// Prints formula information in a formatted table\n", "suffix_code": "\n\n/// Prints cask information in a formatted table\nfn print_cask_info(name: &str, cask: &Value) {\n // Header\n println!(\"{}\", format!(\"Cask: {name}\").green().bold());\n\n // Summary table\n let mut table = prettytable::Table::new();\n table.set_format(*prettytable::format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n if let Some(names) = cask.get(\"name\").and_then(|n| n.as_array()) {\n if let Some(first) = names.first().and_then(|s| s.as_str()) {\n table.add_row(prettytable::row![\"Name\", first]);\n }\n }\n if let Some(desc) = cask.get(\"desc\").and_then(|d| d.as_str()) {\n table.add_row(prettytable::row![\"Description\", desc]);\n }\n if let Some(homepage) = cask.get(\"homepage\").and_then(|h| h.as_str()) {\n table.add_row(prettytable::row![\"Homepage\", homepage]);\n }\n if let Some(version) = cask.get(\"version\").and_then(|v| v.as_str()) {\n table.add_row(prettytable::row![\"Version\", version]);\n }\n if let Some(url) = cask.get(\"url\").and_then(|u| u.as_str()) {\n table.add_row(prettytable::row![\"Download URL\", url]);\n }\n // Add SHA if present\n if let Some(sha) = cask.get(\"sha256\").and_then(|s| s.as_str()) {\n if !sha.is_empty() {\n table.add_row(prettytable::row![\"SHA256\", sha]);\n }\n }\n table.printstd();\n\n // Dependencies Section\n if let Some(deps) = cask.get(\"depends_on\").and_then(|d| d.as_object()) {\n let mut dep_table = prettytable::Table::new();\n dep_table.set_format(*prettytable::format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n let mut has_deps = false;\n\n if let Some(formulas) = deps.get(\"formula\").and_then(|f| f.as_array()) {\n if !formulas.is_empty() {\n has_deps = true;\n dep_table.add_row(prettytable::row![\n \"Formula\".yellow(),\n formulas\n .iter()\n .map(|v| v.as_str().unwrap_or(\"\"))\n .collect::>()\n .join(\", \")\n ]);\n }\n }\n if let Some(casks) = deps.get(\"cask\").and_then(|c| c.as_array()) {\n if !casks.is_empty() {\n has_deps = true;\n dep_table.add_row(prettytable::row![\n \"Cask\".yellow(),\n casks\n .iter()\n .map(|v| v.as_str().unwrap_or(\"\"))\n .collect::>()\n .join(\", \")\n ]);\n }\n }\n if let Some(macos) = deps.get(\"macos\") {\n has_deps = true;\n let macos_str = match macos {\n Value::String(s) => s.clone(),\n Value::Array(arr) => arr\n .iter()\n .map(|v| v.as_str().unwrap_or(\"\"))\n .collect::>()\n .join(\" or \"),\n _ => \"Unknown\".to_string(),\n };\n dep_table.add_row(prettytable::row![\"macOS\".yellow(), macos_str]);\n }\n\n if has_deps {\n println!(\"\\n{}\", \"Dependencies\".blue().bold());\n dep_table.printstd();\n }\n }\n\n // Installation hint\n println!(\"\\n{}\", \"Installation\".blue().bold());\n println!(\n \" {} install --cask {}\", // Always use --cask for clarity\n \"sps\".cyan(),\n name // Use the token 'name' passed to the function\n );\n}\n// Removed is_bottle_available check\n", "middle_code": "fn print_formula_info(_name: &str, formula: &Value) {\n let full_name = formula\n .get(\"full_name\")\n .and_then(|f| f.as_str())\n .unwrap_or(\"N/A\");\n let version = formula\n .get(\"versions\")\n .and_then(|v| v.get(\"stable\"))\n .and_then(|s| s.as_str())\n .unwrap_or(\"N/A\");\n let revision = formula\n .get(\"revision\")\n .and_then(|r| r.as_u64())\n .unwrap_or(0);\n let version_str = if revision > 0 {\n format!(\"{version}_{revision}\")\n } else {\n version.to_string()\n };\n let license = formula\n .get(\"license\")\n .and_then(|l| l.as_str())\n .unwrap_or(\"N/A\");\n let homepage = formula\n .get(\"homepage\")\n .and_then(|h| h.as_str())\n .unwrap_or(\"N/A\");\n println!(\"{}\", format!(\"Formula: {full_name}\").green().bold());\n let mut table = prettytable::Table::new();\n table.set_format(*prettytable::format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n table.add_row(prettytable::row![\"Version\", version_str]);\n table.add_row(prettytable::row![\"License\", license]);\n table.add_row(prettytable::row![\"Homepage\", homepage]);\n table.printstd();\n if let Some(desc) = formula.get(\"desc\").and_then(|d| d.as_str()) {\n if !desc.is_empty() {\n println!(\"\\n{}\", \"Description\".blue().bold());\n println!(\"{desc}\");\n }\n }\n if let Some(caveats) = formula.get(\"caveats\").and_then(|c| c.as_str()) {\n if !caveats.is_empty() {\n println!(\"\\n{}\", \"Caveats\".blue().bold());\n println!(\"{caveats}\");\n }\n }\n let mut dep_table = prettytable::Table::new();\n dep_table.set_format(*prettytable::format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n let mut has_deps = false;\n let mut add_deps = |title: &str, key: &str, tag: &str| {\n if let Some(deps) = formula.get(key).and_then(|d| d.as_array()) {\n let dep_list: Vec<&str> = deps.iter().filter_map(|d| d.as_str()).collect();\n if !dep_list.is_empty() {\n has_deps = true;\n for (i, d) in dep_list.iter().enumerate() {\n let display_title = if i == 0 { title } else { \"\" };\n let display_tag = if i == 0 {\n format!(\"({tag})\")\n } else {\n \"\".to_string()\n };\n dep_table.add_row(prettytable::row![display_title, d, display_tag]);\n }\n }\n }\n };\n add_deps(\"Required\", \"dependencies\", \"runtime\");\n add_deps(\n \"Recommended\",\n \"recommended_dependencies\",\n \"runtime, recommended\",\n );\n add_deps(\"Optional\", \"optional_dependencies\", \"runtime, optional\");\n add_deps(\"Build\", \"build_dependencies\", \"build\");\n add_deps(\"Test\", \"test_dependencies\", \"test\");\n if has_deps {\n println!(\"\\n{}\", \"Dependencies\".blue().bold());\n dep_table.printstd();\n }\n println!(\"\\n{}\", \"Installation\".blue().bold());\n println!(\n \" {} install {}\",\n \"sps\".cyan(),\n formula\n .get(\"name\")\n .and_then(|n| n.as_str())\n .unwrap_or(full_name) \n );\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "rust", "sub_task_type": null}, "context_code": [["/sps/sps/src/cli/search.rs", "use std::sync::Arc;\n\nuse clap::Args;\nuse colored::Colorize;\nuse prettytable::{format, Cell, Row, Table};\nuse serde_json::Value;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_net::api;\nuse terminal_size::{terminal_size, Width};\nuse unicode_width::{UnicodeWidthChar, UnicodeWidthStr};\n\n#[derive(Args, Debug)]\npub struct Search {\n pub query: String,\n #[arg(long, conflicts_with = \"cask\")]\n pub formula: bool,\n #[arg(long, conflicts_with = \"formula\")]\n pub cask: bool,\n}\n\npub enum SearchType {\n All,\n Formula,\n Cask,\n}\n\nimpl Search {\n pub async fn run(&self, config: &Config, cache: Arc) -> Result<()> {\n let search_type = if self.formula {\n SearchType::Formula\n } else if self.cask {\n SearchType::Cask\n } else {\n SearchType::All\n };\n run_search(&self.query, search_type, config, cache).await\n }\n}\n\npub async fn run_search(\n query: &str,\n search_type: SearchType,\n _config: &Config,\n cache: Arc,\n) -> Result<()> {\n tracing::debug!(\"Searching for packages matching: {}\", query);\n\n println!(\"Searching for \\\"{query}\\\"\");\n\n let mut formula_matches = Vec::new();\n let mut cask_matches = Vec::new();\n let mut formula_err = None;\n let mut cask_err = None;\n\n if matches!(search_type, SearchType::All | SearchType::Formula) {\n match search_formulas(Arc::clone(&cache), query).await {\n Ok(matches) => formula_matches = matches,\n Err(e) => {\n tracing::error!(\"Error searching formulas: {}\", e);\n formula_err = Some(e);\n }\n }\n }\n\n if matches!(search_type, SearchType::All | SearchType::Cask) {\n match search_casks(Arc::clone(&cache), query).await {\n Ok(matches) => cask_matches = matches,\n Err(e) => {\n tracing::error!(\"Error searching casks: {}\", e);\n cask_err = Some(e);\n }\n }\n }\n\n if formula_matches.is_empty() && cask_matches.is_empty() {\n if let Some(e) = formula_err.or(cask_err) {\n return Err(e);\n }\n }\n\n print_search_results(query, &formula_matches, &cask_matches);\n\n Ok(())\n}\n\nasync fn search_formulas(cache: Arc, query: &str) -> Result> {\n let query_lower = query.to_lowercase();\n let mut matches = Vec::new();\n let mut data_source_name = \"cache\";\n\n let formula_data_result = cache.load_raw(\"formula.json\");\n\n let formulas: Vec = match formula_data_result {\n Ok(formula_data) => serde_json::from_str(&formula_data)?,\n Err(e) => {\n tracing::debug!(\"Formula cache load failed ({}), fetching from API\", e);\n data_source_name = \"API\";\n let all_formulas = api::fetch_all_formulas().await?;\n\n if let Err(cache_err) = cache.store_raw(\"formula.json\", &all_formulas) {\n tracing::warn!(\"Failed to cache formula data after fetching: {}\", cache_err);\n }\n serde_json::from_str(&all_formulas)?\n }\n };\n\n for formula in formulas {\n if is_formula_match(&formula, &query_lower) {\n matches.push(formula);\n }\n }\n\n tracing::debug!(\n \"Found {} potential formula matches from {}\",\n matches.len(),\n data_source_name\n );\n tracing::debug!(\n \"Filtered down to {} formula matches with available bottles\",\n matches.len()\n );\n\n Ok(matches)\n}\n\nasync fn search_casks(cache: Arc, query: &str) -> Result> {\n let query_lower = query.to_lowercase();\n let mut matches = Vec::new();\n let mut data_source_name = \"cache\";\n\n let cask_data_result = cache.load_raw(\"cask.json\");\n\n let casks: Vec = match cask_data_result {\n Ok(cask_data) => serde_json::from_str(&cask_data)?,\n Err(e) => {\n tracing::debug!(\"Cask cache load failed ({}), fetching from API\", e);\n data_source_name = \"API\";\n let all_casks = api::fetch_all_casks().await?;\n\n if let Err(cache_err) = cache.store_raw(\"cask.json\", &all_casks) {\n tracing::warn!(\"Failed to cache cask data after fetching: {}\", cache_err);\n }\n serde_json::from_str(&all_casks)?\n }\n };\n\n for cask in casks {\n if is_cask_match(&cask, &query_lower) {\n matches.push(cask);\n }\n }\n tracing::debug!(\n \"Found {} cask matches from {}\",\n matches.len(),\n data_source_name\n );\n Ok(matches)\n}\n\nfn is_formula_match(formula: &Value, query: &str) -> bool {\n if let Some(name) = formula.get(\"name\").and_then(|n| n.as_str()) {\n if name.to_lowercase().contains(query) {\n return true;\n }\n }\n\n if let Some(full_name) = formula.get(\"full_name\").and_then(|n| n.as_str()) {\n if full_name.to_lowercase().contains(query) {\n return true;\n }\n }\n\n if let Some(desc) = formula.get(\"desc\").and_then(|d| d.as_str()) {\n if desc.to_lowercase().contains(query) {\n return true;\n }\n }\n\n if let Some(aliases) = formula.get(\"aliases\").and_then(|a| a.as_array()) {\n for alias in aliases {\n if let Some(alias_str) = alias.as_str() {\n if alias_str.to_lowercase().contains(query) {\n return true;\n }\n }\n }\n }\n\n false\n}\n\nfn is_cask_match(cask: &Value, query: &str) -> bool {\n if let Some(token) = cask.get(\"token\").and_then(|t| t.as_str()) {\n if token.to_lowercase().contains(query) {\n return true;\n }\n }\n\n if let Some(names) = cask.get(\"name\").and_then(|n| n.as_array()) {\n for name in names {\n if let Some(name_str) = name.as_str() {\n if name_str.to_lowercase().contains(query) {\n return true;\n }\n }\n }\n }\n\n if let Some(desc) = cask.get(\"desc\").and_then(|d| d.as_str()) {\n if desc.to_lowercase().contains(query) {\n return true;\n }\n }\n\n false\n}\n\nfn truncate_vis(s: &str, max: usize) -> String {\n if UnicodeWidthStr::width(s) <= max {\n return s.to_string();\n }\n let mut w = 0;\n let mut out = String::new();\n let effective_max = if max > 0 { max } else { 1 };\n\n for ch in s.chars() {\n let cw = UnicodeWidthChar::width(ch).unwrap_or(0);\n if w + cw >= effective_max.saturating_sub(1) {\n break;\n }\n out.push(ch);\n w += cw;\n }\n out.push('…');\n out\n}\n\npub fn print_search_results(query: &str, formula_matches: &[Value], cask_matches: &[Value]) {\n let total = formula_matches.len() + cask_matches.len();\n if total == 0 {\n println!(\"{}\", format!(\"No matches found for '{query}'\").yellow());\n return;\n }\n println!(\n \"{}\",\n format!(\"Found {total} result(s) for '{query}'\").bold()\n );\n\n let term_cols = terminal_size()\n .map(|(Width(w), _)| w as usize)\n .unwrap_or(120);\n\n let type_col = 7;\n let version_col = 10;\n let sep_width = 3 * 3;\n let total_fixed = type_col + version_col + sep_width;\n\n let name_min_width = 10;\n let desc_min_width = 20;\n\n let leftover = term_cols.saturating_sub(total_fixed);\n\n let name_prop_width = leftover / 3;\n\n let name_max = std::cmp::max(name_min_width, name_prop_width);\n let desc_max = std::cmp::max(desc_min_width, leftover.saturating_sub(name_max));\n\n let name_max = std::cmp::min(name_max, leftover.saturating_sub(desc_min_width));\n let desc_max = std::cmp::min(desc_max, leftover.saturating_sub(name_max));\n\n let mut tbl = Table::new();\n tbl.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n\n for formula in formula_matches {\n let raw_name = formula\n .get(\"name\")\n .and_then(|n| n.as_str())\n .unwrap_or(\"Unknown\");\n let raw_desc = formula.get(\"desc\").and_then(|d| d.as_str()).unwrap_or(\"\");\n let _name = truncate_vis(raw_name, name_max);\n let desc = truncate_vis(raw_desc, desc_max);\n\n let version = get_version(formula);\n\n tbl.add_row(Row::new(vec![\n Cell::new(\"Formula\").style_spec(\"Fg\"),\n Cell::new(&_name).style_spec(\"Fb\"),\n Cell::new(version),\n Cell::new(&desc),\n ]));\n }\n\n if !formula_matches.is_empty() && !cask_matches.is_empty() {\n tbl.add_row(Row::new(vec![Cell::new(\" \").with_hspan(4)]));\n }\n\n for cask in cask_matches {\n let raw_name = cask\n .get(\"token\")\n .and_then(|t| t.as_str())\n .unwrap_or(\"Unknown\");\n let raw_desc = cask.get(\"desc\").and_then(|d| d.as_str()).unwrap_or(\"\");\n let desc = truncate_vis(raw_desc, desc_max);\n\n let version = get_cask_version(cask);\n\n tbl.add_row(Row::new(vec![\n Cell::new(\"Cask\").style_spec(\"Fy\"),\n Cell::new(raw_name).style_spec(\"Fb\"),\n Cell::new(version),\n Cell::new(&desc),\n ]));\n }\n\n tbl.printstd();\n}\n\nfn get_version(formula: &Value) -> &str {\n formula\n .get(\"versions\")\n .and_then(|v| v.get(\"stable\"))\n .and_then(|v| v.as_str())\n .unwrap_or(\"-\")\n}\n\nfn get_cask_version(cask: &Value) -> &str {\n cask.get(\"version\").and_then(|v| v.as_str()).unwrap_or(\"-\")\n}\n"], ["/sps/sps/src/cli/list.rs", "use std::sync::Arc;\n\nuse clap::Args;\nuse colored::Colorize;\nuse prettytable::{format, Cell, Row, Table};\nuse serde_json::Value;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::formulary::Formulary;\nuse sps_core::check::installed::{get_installed_packages, PackageType};\nuse sps_core::check::update::check_for_updates;\nuse sps_core::check::InstalledPackageInfo;\n\n#[derive(Args, Debug)]\npub struct List {\n /// Show only formulas\n #[arg(long = \"formula\")]\n pub formula_only: bool,\n /// Show only casks\n #[arg(long = \"cask\")]\n pub cask_only: bool,\n /// Show only packages with updates available\n #[arg(long = \"outdated\")]\n pub outdated_only: bool,\n}\n\nimpl List {\n pub async fn run(&self, config: &Config, cache: Arc) -> Result<()> {\n let installed = get_installed_packages(config).await?;\n // Only show the latest version for each name\n use std::collections::HashMap;\n let mut formula_map: HashMap<&str, &sps_core::check::installed::InstalledPackageInfo> =\n HashMap::new();\n let mut cask_map: HashMap<&str, &sps_core::check::installed::InstalledPackageInfo> =\n HashMap::new();\n for pkg in &installed {\n match pkg.pkg_type {\n PackageType::Formula => {\n let entry = formula_map.entry(pkg.name.as_str()).or_insert(pkg);\n if pkg.version > entry.version {\n formula_map.insert(pkg.name.as_str(), pkg);\n }\n }\n PackageType::Cask => {\n let entry = cask_map.entry(pkg.name.as_str()).or_insert(pkg);\n if pkg.version > entry.version {\n cask_map.insert(pkg.name.as_str(), pkg);\n }\n }\n }\n }\n let mut formulas: Vec<&InstalledPackageInfo> = formula_map.values().copied().collect();\n let mut casks: Vec<&InstalledPackageInfo> = cask_map.values().copied().collect();\n // Sort formulas and casks alphabetically by name, then version\n formulas.sort_by(|a, b| a.name.cmp(&b.name).then(a.version.cmp(&b.version)));\n casks.sort_by(|a, b| a.name.cmp(&b.name).then(a.version.cmp(&b.version)));\n // If Nothing Installed.\n if formulas.is_empty() && casks.is_empty() {\n println!(\"{}\", \"0 formulas and casks installed\".yellow());\n return Ok(());\n }\n // If user wants to show installed formulas only.\n if self.formula_only {\n if self.outdated_only {\n self.print_outdated_formulas_table(&formulas, config)\n .await?;\n } else {\n self.print_formulas_table(formulas, config);\n }\n return Ok(());\n }\n // If user wants to show installed casks only.\n if self.cask_only {\n if self.outdated_only {\n self.print_outdated_casks_table(&casks, cache.clone())\n .await?;\n } else {\n self.print_casks_table(casks, cache);\n }\n return Ok(());\n }\n\n // If user wants to show only outdated packages\n if self.outdated_only {\n self.print_outdated_all_table(&formulas, &casks, config, cache)\n .await?;\n return Ok(());\n }\n\n // Default Implementation\n let formulary = Formulary::new(config.clone());\n let mut table = Table::new();\n table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n table.add_row(Row::new(vec![\n Cell::new(\"Type\").style_spec(\"b\"),\n Cell::new(\"Name\").style_spec(\"b\"),\n Cell::new(\"Installed\").style_spec(\"b\"),\n Cell::new(\"New Version?\").style_spec(\"b\"),\n ]));\n let mut formula_count = 0;\n let mut cask_count = 0;\n for pkg in formulas {\n let latest = formulary.load_formula(&pkg.name).ok();\n let (has_new, _) = match latest {\n Some(ref f) => {\n let latest_version = f.version_str_full();\n (latest_version != pkg.version, latest_version)\n }\n None => (false, \"-\".to_string()),\n };\n table.add_row(Row::new(vec![\n Cell::new(\"Formula\").style_spec(\"Fg\"),\n Cell::new(&pkg.name).style_spec(\"Fb\"),\n Cell::new(&pkg.version),\n // TODO: update to display the latest version string.\n // TODO: Not showing when the using --all flag.\n Cell::new(if has_new { \"✔\" } else { \"\" }),\n ]));\n formula_count += 1;\n }\n for pkg in casks {\n // Try to load cask info from cache\n let cask_val = cache.load_raw(\"cask.json\").ok().and_then(|raw| {\n serde_json::from_str::>(&raw)\n .ok()?\n .into_iter()\n .find(|v| v.get(\"token\").and_then(|t| t.as_str()) == Some(&pkg.name))\n });\n let (has_new, _) = match cask_val {\n Some(ref v) => {\n let latest_version = v.get(\"version\").and_then(|v| v.as_str()).unwrap_or(\"-\");\n (latest_version != pkg.version, latest_version.to_string())\n }\n None => (false, \"-\".to_string()),\n };\n table.add_row(Row::new(vec![\n Cell::new(\"Cask\").style_spec(\"Fy\"),\n Cell::new(&pkg.name).style_spec(\"Fb\"),\n Cell::new(&pkg.version),\n Cell::new(if has_new { \"✔\" } else { \"\" }),\n ]));\n cask_count += 1;\n }\n table.printstd();\n if formula_count > 0 && cask_count > 0 {\n println!(\n \"{}\",\n format!(\"{formula_count} formulas, {cask_count} casks installed\").bold()\n );\n } else if formula_count > 0 {\n println!(\"{}\", format!(\"{formula_count} formulas installed\").bold());\n } else if cask_count > 0 {\n println!(\"{}\", format!(\"{cask_count} casks installed\").bold());\n }\n Ok(())\n }\n\n fn print_formulas_table(\n &self,\n formulas: Vec<&sps_core::check::installed::InstalledPackageInfo>,\n config: &Config,\n ) {\n if formulas.is_empty() {\n println!(\"No formulas installed.\");\n return;\n }\n let formulary = Formulary::new(config.clone());\n let mut table = Table::new();\n table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n // Add header row with \"Formulas\" spanning all columns, font color green\n table.add_row(Row::new(vec![Cell::new_align(\n \"Formulas\",\n format::Alignment::CENTER,\n )\n .style_spec(\"bFg\")\n .with_hspan(3)]));\n table.add_row(Row::new(vec![\n Cell::new(\"Name\").style_spec(\"b\"),\n Cell::new(\"Installed\").style_spec(\"b\"),\n Cell::new(\"New Version?\").style_spec(\"b\"),\n ]));\n let mut formula_count = 0;\n for pkg in formulas {\n let latest = formulary.load_formula(&pkg.name).ok();\n let (has_new, _) = match latest {\n Some(ref f) => {\n let latest_version = f.version_str_full();\n (latest_version != pkg.version, latest_version)\n }\n None => (false, \"-\".to_string()),\n };\n table.add_row(Row::new(vec![\n Cell::new(&pkg.name).style_spec(\"Fb\"),\n Cell::new(&pkg.version),\n Cell::new(if has_new { \"✔\" } else { \"\" }),\n ]));\n formula_count += 1;\n }\n table.printstd();\n println!(\"{}\", format!(\"{formula_count} formulas installed\").bold());\n }\n\n fn print_casks_table(\n &self,\n casks: Vec<&sps_core::check::installed::InstalledPackageInfo>,\n cache: Arc,\n ) {\n if casks.is_empty() {\n println!(\"No casks installed.\");\n return;\n }\n let mut table = Table::new();\n table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n // Add header row with \"Casks\" spanning all columns, font color green\n table.add_row(Row::new(vec![Cell::new_align(\n \"Casks\",\n format::Alignment::CENTER,\n )\n .style_spec(\"bFg\")\n .with_hspan(3)]));\n table.add_row(Row::new(vec![\n Cell::new(\"Name\").style_spec(\"b\"),\n Cell::new(\"Installed\").style_spec(\"b\"),\n Cell::new(\"New Version?\").style_spec(\"b\"),\n ]));\n let mut cask_count = 0;\n for pkg in casks {\n // Try to load cask info from cache\n let cask_val = cache.load_raw(\"cask.json\").ok().and_then(|raw| {\n serde_json::from_str::>(&raw)\n .ok()?\n .into_iter()\n .find(|v| v.get(\"token\").and_then(|t| t.as_str()) == Some(&pkg.name))\n });\n let (has_new, _) = match cask_val {\n Some(ref v) => {\n let latest_version = v.get(\"version\").and_then(|v| v.as_str()).unwrap_or(\"-\");\n (latest_version != pkg.version, latest_version.to_string())\n }\n None => (false, \"-\".to_string()),\n };\n table.add_row(Row::new(vec![\n Cell::new(&pkg.name).style_spec(\"Fb\"),\n Cell::new(&pkg.version),\n Cell::new(if has_new { \"✔\" } else { \"\" }),\n ]));\n cask_count += 1;\n }\n table.printstd();\n println!(\"{}\", format!(\"{cask_count} casks installed\").bold());\n }\n\n async fn print_outdated_formulas_table(\n &self,\n formulas: &[&InstalledPackageInfo],\n config: &Config,\n ) -> Result<()> {\n if formulas.is_empty() {\n println!(\"No formulas installed.\");\n return Ok(());\n }\n\n // Convert to owned for update checking\n let formula_packages: Vec =\n formulas.iter().map(|&f| f.clone()).collect();\n let cache = sps_common::cache::Cache::new(config)?;\n let updates = check_for_updates(&formula_packages, &cache, config).await?;\n\n if updates.is_empty() {\n println!(\"No formula updates available.\");\n return Ok(());\n }\n\n let mut table = Table::new();\n table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n table.add_row(Row::new(vec![Cell::new_align(\n \"Outdated Formulas\",\n format::Alignment::CENTER,\n )\n .style_spec(\"bFg\")\n .with_hspan(3)]));\n table.add_row(Row::new(vec![\n Cell::new(\"Name\").style_spec(\"b\"),\n Cell::new(\"Installed\").style_spec(\"b\"),\n Cell::new(\"Available\").style_spec(\"b\"),\n ]));\n\n let mut count = 0;\n for update in updates {\n table.add_row(Row::new(vec![\n Cell::new(&update.name).style_spec(\"Fb\"),\n Cell::new(&update.installed_version),\n Cell::new(&update.available_version).style_spec(\"Fg\"),\n ]));\n count += 1;\n }\n\n table.printstd();\n println!(\"{}\", format!(\"{count} outdated formulas\").bold());\n Ok(())\n }\n\n async fn print_outdated_casks_table(\n &self,\n casks: &[&InstalledPackageInfo],\n cache: Arc,\n ) -> Result<()> {\n if casks.is_empty() {\n println!(\"No casks installed.\");\n return Ok(());\n }\n\n // Convert to owned for update checking\n let cask_packages: Vec = casks.iter().map(|&c| c.clone()).collect();\n let config = cache.config();\n let updates = check_for_updates(&cask_packages, &cache, config).await?;\n\n if updates.is_empty() {\n println!(\"No cask updates available.\");\n return Ok(());\n }\n\n let mut table = Table::new();\n table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n table.add_row(Row::new(vec![Cell::new_align(\n \"Outdated Casks\",\n format::Alignment::CENTER,\n )\n .style_spec(\"bFg\")\n .with_hspan(3)]));\n table.add_row(Row::new(vec![\n Cell::new(\"Name\").style_spec(\"b\"),\n Cell::new(\"Installed\").style_spec(\"b\"),\n Cell::new(\"Available\").style_spec(\"b\"),\n ]));\n\n let mut count = 0;\n for update in updates {\n table.add_row(Row::new(vec![\n Cell::new(&update.name).style_spec(\"Fb\"),\n Cell::new(&update.installed_version),\n Cell::new(&update.available_version).style_spec(\"Fy\"),\n ]));\n count += 1;\n }\n\n table.printstd();\n println!(\"{}\", format!(\"{count} outdated casks\").bold());\n Ok(())\n }\n\n async fn print_outdated_all_table(\n &self,\n formulas: &[&InstalledPackageInfo],\n casks: &[&InstalledPackageInfo],\n config: &Config,\n cache: Arc,\n ) -> Result<()> {\n // Convert to owned for update checking\n let mut all_packages: Vec = Vec::new();\n all_packages.extend(formulas.iter().map(|&f| f.clone()));\n all_packages.extend(casks.iter().map(|&c| c.clone()));\n\n if all_packages.is_empty() {\n println!(\"{}\", \"0 formulas and casks installed\".yellow());\n return Ok(());\n }\n\n let updates = check_for_updates(&all_packages, &cache, config).await?;\n\n if updates.is_empty() {\n println!(\"No outdated packages found.\");\n return Ok(());\n }\n\n let mut table = Table::new();\n table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n table.add_row(Row::new(vec![\n Cell::new(\"Type\").style_spec(\"b\"),\n Cell::new(\"Name\").style_spec(\"b\"),\n Cell::new(\"Installed\").style_spec(\"b\"),\n Cell::new(\"Available\").style_spec(\"b\"),\n ]));\n\n let mut formula_count = 0;\n let mut cask_count = 0;\n\n for update in updates {\n let (type_name, type_style) = match update.pkg_type {\n PackageType::Formula => {\n formula_count += 1;\n (\"Formula\", \"Fg\")\n }\n PackageType::Cask => {\n cask_count += 1;\n (\"Cask\", \"Fy\")\n }\n };\n\n table.add_row(Row::new(vec![\n Cell::new(type_name).style_spec(type_style),\n Cell::new(&update.name).style_spec(\"Fb\"),\n Cell::new(&update.installed_version),\n Cell::new(&update.available_version).style_spec(\"Fg\"),\n ]));\n }\n\n table.printstd();\n if formula_count > 0 && cask_count > 0 {\n println!(\n \"{}\",\n format!(\"{formula_count} outdated formulas, {cask_count} outdated casks\").bold()\n );\n } else if formula_count > 0 {\n println!(\"{}\", format!(\"{formula_count} outdated formulas\").bold());\n } else if cask_count > 0 {\n println!(\"{}\", format!(\"{cask_count} outdated casks\").bold());\n }\n Ok(())\n }\n}\n"], ["/sps/sps/src/pipeline/planner.rs", "// sps/src/pipeline/planner.rs\nuse std::collections::{HashMap, HashSet, VecDeque};\nuse std::path::{Path, PathBuf};\nuse std::sync::Arc;\n\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::dependency::resolver::{\n DependencyResolver, NodeInstallStrategy, PerTargetInstallPreferences, ResolutionContext,\n ResolutionStatus, ResolvedGraph,\n};\nuse sps_common::error::{Result as SpsResult, SpsError};\nuse sps_common::formulary::Formulary;\nuse sps_common::keg::KegRegistry;\nuse sps_common::model::{Cask, Formula, InstallTargetIdentifier};\nuse sps_common::pipeline::{JobAction, PipelineEvent, PlannedJob, PlannedOperations};\nuse sps_core::check::installed::{self, InstalledPackageInfo, PackageType as CorePackageType};\nuse sps_core::check::update::{self, UpdateInfo};\nuse tokio::sync::broadcast;\nuse tokio::task::JoinSet;\nuse tracing::{debug, error as trace_error, instrument, warn};\n\nuse super::runner::{get_panic_message, CommandType, PipelineFlags};\n\npub(crate) type PlanResult = SpsResult;\n\n#[derive(Debug, Default)]\nstruct IntermediatePlan {\n initial_ops: HashMap)>,\n errors: Vec<(String, SpsError)>,\n already_satisfied: HashSet,\n processed_globally: HashSet,\n private_store_sources: HashMap,\n}\n\n#[instrument(skip(cache))]\npub(crate) async fn fetch_target_definitions(\n names: &[String],\n cache: Arc,\n) -> HashMap> {\n let mut results = HashMap::new();\n if names.is_empty() {\n return results;\n }\n let mut futures = JoinSet::new();\n\n let formulae_map_handle = tokio::spawn(load_or_fetch_formulae_map(cache.clone()));\n let casks_map_handle = tokio::spawn(load_or_fetch_casks_map(cache.clone()));\n\n let formulae_map = match formulae_map_handle.await {\n Ok(Ok(map)) => Some(map),\n Ok(Err(e)) => {\n debug!(\"[FetchDefs] Failed to load/fetch full formulae list: {}\", e);\n None\n }\n Err(e) => {\n warn!(\n \"[FetchDefs] Formulae map loading task panicked: {}\",\n get_panic_message(e.into_panic()) // Ensure get_panic_message is accessible\n );\n None\n }\n };\n let casks_map = match casks_map_handle.await {\n Ok(Ok(map)) => Some(map),\n Ok(Err(e)) => {\n debug!(\"[FetchDefs] Failed to load/fetch full casks list: {}\", e);\n None\n }\n Err(e) => {\n warn!(\n \"[FetchDefs] Casks map loading task panicked: {}\",\n get_panic_message(e.into_panic()) // Ensure get_panic_message is accessible\n );\n None\n }\n };\n\n for name_str in names {\n let name_owned = name_str.to_string();\n let local_formulae_map = formulae_map.clone();\n let local_casks_map = casks_map.clone();\n\n futures.spawn(async move {\n if let Some(ref map) = local_formulae_map {\n if let Some(f_arc) = map.get(&name_owned) {\n return (name_owned, Ok(InstallTargetIdentifier::Formula(f_arc.clone())));\n }\n }\n if let Some(ref map) = local_casks_map {\n if let Some(c_arc) = map.get(&name_owned) {\n return (name_owned, Ok(InstallTargetIdentifier::Cask(c_arc.clone())));\n }\n }\n debug!(\"[FetchDefs] Definition for '{}' not found in cached lists, fetching directly from API...\", name_owned);\n match sps_net::api::get_formula(&name_owned).await {\n Ok(formula_obj) => return (name_owned, Ok(InstallTargetIdentifier::Formula(Arc::new(formula_obj)))),\n Err(SpsError::NotFound(_)) => {}\n Err(e) => return (name_owned, Err(e)),\n }\n match sps_net::api::get_cask(&name_owned).await {\n Ok(cask_obj) => (name_owned, Ok(InstallTargetIdentifier::Cask(Arc::new(cask_obj)))),\n Err(SpsError::NotFound(_)) => (name_owned.clone(), Err(SpsError::NotFound(format!(\"Formula or Cask '{name_owned}' not found\")))),\n Err(e) => (name_owned, Err(e)),\n }\n });\n }\n\n while let Some(res) = futures.join_next().await {\n match res {\n Ok((name, result)) => {\n results.insert(name, result);\n }\n Err(e) => {\n let panic_message = get_panic_message(e.into_panic());\n trace_error!(\n \"[FetchDefs] Task panicked during definition fetch: {}\",\n panic_message\n );\n results.insert(\n format!(\"[unknown_target_due_to_panic_{}]\", results.len()),\n Err(SpsError::Generic(format!(\n \"Definition fetching task panicked: {panic_message}\"\n ))),\n );\n }\n }\n }\n results\n}\n\nasync fn load_or_fetch_formulae_map(cache: Arc) -> SpsResult>> {\n match cache.load_raw(\"formula.json\") {\n Ok(data) => {\n let formulas: Vec = serde_json::from_str(&data)\n .map_err(|e| SpsError::Cache(format!(\"Parse cached formula.json failed: {e}\")))?;\n Ok(formulas\n .into_iter()\n .map(|f| (f.name.clone(), Arc::new(f)))\n .collect())\n }\n Err(_) => {\n debug!(\"[FetchDefs] Cache miss for formula.json, fetching from API...\");\n let raw_data = sps_net::api::fetch_all_formulas().await?;\n if let Err(e) = cache.store_raw(\"formula.json\", &raw_data) {\n warn!(\"Failed to store formula.json in cache: {}\", e);\n }\n let formulas: Vec =\n serde_json::from_str(&raw_data).map_err(|e| SpsError::Json(Arc::new(e)))?;\n Ok(formulas\n .into_iter()\n .map(|f| (f.name.clone(), Arc::new(f)))\n .collect())\n }\n }\n}\n\nasync fn load_or_fetch_casks_map(cache: Arc) -> SpsResult>> {\n match cache.load_raw(\"cask.json\") {\n Ok(data) => {\n let casks: Vec = serde_json::from_str(&data)\n .map_err(|e| SpsError::Cache(format!(\"Parse cached cask.json failed: {e}\")))?;\n Ok(casks\n .into_iter()\n .map(|c| (c.token.clone(), Arc::new(c)))\n .collect())\n }\n Err(_) => {\n debug!(\"[FetchDefs] Cache miss for cask.json, fetching from API...\");\n let raw_data = sps_net::api::fetch_all_casks().await?;\n if let Err(e) = cache.store_raw(\"cask.json\", &raw_data) {\n warn!(\"Failed to store cask.json in cache: {}\", e);\n }\n let casks: Vec =\n serde_json::from_str(&raw_data).map_err(|e| SpsError::Json(Arc::new(e)))?;\n Ok(casks\n .into_iter()\n .map(|c| (c.token.clone(), Arc::new(c)))\n .collect())\n }\n }\n}\n\npub(crate) struct OperationPlanner<'a> {\n config: &'a Config,\n cache: Arc,\n flags: &'a PipelineFlags,\n event_tx: broadcast::Sender,\n}\n\nimpl<'a> OperationPlanner<'a> {\n pub fn new(\n config: &'a Config,\n cache: Arc,\n flags: &'a PipelineFlags,\n event_tx: broadcast::Sender,\n ) -> Self {\n Self {\n config,\n cache,\n flags,\n event_tx,\n }\n }\n\n fn get_previous_installation_type(&self, old_keg_path: &Path) -> Option {\n let receipt_path = old_keg_path.join(\"INSTALL_RECEIPT.json\");\n if !receipt_path.is_file() {\n tracing::debug!(\n \"No INSTALL_RECEIPT.json found at {} for previous version.\",\n receipt_path.display()\n );\n return None;\n }\n\n match std::fs::read_to_string(&receipt_path) {\n Ok(content) => match serde_json::from_str::(&content) {\n Ok(json_value) => {\n let inst_type = json_value\n .get(\"installation_type\")\n .and_then(|it| it.as_str())\n .map(String::from);\n tracing::debug!(\n \"Previous installation type for {}: {:?}\",\n old_keg_path.display(),\n inst_type\n );\n inst_type\n }\n Err(e) => {\n tracing::warn!(\"Failed to parse INSTALL_RECEIPT.json at {}: {}. Cannot determine previous installation type.\", receipt_path.display(), e);\n None\n }\n },\n Err(e) => {\n tracing::warn!(\"Failed to read INSTALL_RECEIPT.json at {}: {}. Cannot determine previous installation type.\", receipt_path.display(), e);\n None\n }\n }\n }\n\n async fn check_installed_status(&self, name: &str) -> PlanResult> {\n installed::get_installed_package(name, self.config).await\n }\n\n async fn determine_cask_private_store_source(\n &self,\n name: &str,\n version_for_path: &str,\n ) -> Option {\n let cask_def_res = fetch_target_definitions(&[name.to_string()], self.cache.clone())\n .await\n .remove(name);\n\n if let Some(Ok(InstallTargetIdentifier::Cask(cask_arc))) = cask_def_res {\n if let Some(artifacts) = &cask_arc.artifacts {\n for artifact_entry in artifacts {\n if let Some(app_array) = artifact_entry.get(\"app\").and_then(|v| v.as_array()) {\n if let Some(app_name_val) = app_array.first() {\n if let Some(app_name_str) = app_name_val.as_str() {\n let private_path = self.config.cask_store_app_path(\n name,\n version_for_path,\n app_name_str,\n );\n if private_path.exists() && private_path.is_dir() {\n debug!(\"[Planner] Found reusable Cask private store bundle for {} version {}: {}\", name, version_for_path, private_path.display());\n return Some(private_path);\n }\n }\n }\n break;\n }\n }\n }\n }\n None\n }\n\n async fn plan_for_install(&self, targets: &[String]) -> PlanResult {\n let mut plan = IntermediatePlan::default();\n for name in targets {\n if plan.processed_globally.contains(name) {\n continue;\n }\n match self.check_installed_status(name).await {\n Ok(Some(installed_info)) => {\n let mut proceed_with_install = false;\n if installed_info.pkg_type == CorePackageType::Cask {\n let manifest_path = installed_info.path.join(\"CASK_INSTALL_MANIFEST.json\");\n if manifest_path.is_file() {\n if let Ok(manifest_str) = std::fs::read_to_string(&manifest_path) {\n if let Ok(manifest_json) =\n serde_json::from_str::(&manifest_str)\n {\n if let Some(is_installed_flag) =\n manifest_json.get(\"is_installed\").and_then(|v| v.as_bool())\n {\n if !is_installed_flag {\n debug!(\"Cask '{}' found but marked as not installed in manifest. Proceeding with install.\", name);\n proceed_with_install = true;\n }\n }\n }\n }\n } else {\n debug!(\n \"Cask '{}' found but manifest missing. Assuming needs install.\",\n name\n );\n proceed_with_install = true;\n }\n }\n if proceed_with_install {\n if let Some(private_path) = self\n .determine_cask_private_store_source(name, &installed_info.version)\n .await\n {\n plan.private_store_sources\n .insert(name.clone(), private_path);\n }\n plan.initial_ops\n .insert(name.clone(), (JobAction::Install, None));\n } else {\n debug!(\"Target '{}' already installed and manifest indicates it. Marking as satisfied.\", name);\n plan.already_satisfied.insert(name.clone());\n plan.processed_globally.insert(name.clone());\n }\n }\n Ok(None) => {\n if let Some(private_path) = self\n .determine_cask_private_store_source(name, \"latest\")\n .await\n {\n plan.private_store_sources\n .insert(name.clone(), private_path);\n }\n plan.initial_ops\n .insert(name.clone(), (JobAction::Install, None));\n }\n Err(e) => {\n plan.errors.push((\n name.clone(),\n SpsError::Generic(format!(\n \"Failed to check installed status for {name}: {e}\"\n )),\n ));\n plan.processed_globally.insert(name.clone());\n }\n }\n }\n Ok(plan)\n }\n\n async fn plan_for_reinstall(&self, targets: &[String]) -> PlanResult {\n let mut plan = IntermediatePlan::default();\n for name in targets {\n if plan.processed_globally.contains(name) {\n continue;\n }\n match self.check_installed_status(name).await {\n Ok(Some(installed_info)) => {\n if installed_info.pkg_type == CorePackageType::Cask {\n if let Some(private_path) = self\n .determine_cask_private_store_source(name, &installed_info.version)\n .await\n {\n plan.private_store_sources\n .insert(name.clone(), private_path);\n }\n }\n plan.initial_ops.insert(\n name.clone(),\n (\n JobAction::Reinstall {\n version: installed_info.version.clone(),\n current_install_path: installed_info.path.clone(),\n },\n None,\n ),\n );\n }\n Ok(None) => {\n plan.errors.push((\n name.clone(),\n SpsError::NotFound(format!(\"Cannot reinstall '{name}': not installed.\")),\n ));\n plan.processed_globally.insert(name.clone());\n }\n Err(e) => {\n plan.errors.push((\n name.clone(),\n SpsError::Generic(format!(\"Failed to check status for '{name}': {e}\")),\n ));\n plan.processed_globally.insert(name.clone());\n }\n }\n }\n Ok(plan)\n }\n\n async fn plan_for_upgrade(\n &self,\n targets: &[String],\n all: bool,\n ) -> PlanResult {\n let mut plan = IntermediatePlan::default();\n let packages_to_check = if all {\n installed::get_installed_packages(self.config)\n .await\n .map_err(|e| {\n plan.errors.push((\n \"\".to_string(),\n SpsError::Generic(format!(\"Failed to get installed packages: {e}\")),\n ));\n e\n })?\n } else {\n let mut specific = Vec::new();\n for name in targets {\n match self.check_installed_status(name).await {\n Ok(Some(info)) => {\n if info.pkg_type == CorePackageType::Cask {\n let manifest_path = info.path.join(\"CASK_INSTALL_MANIFEST.json\");\n if manifest_path.is_file() {\n if let Ok(manifest_str) = std::fs::read_to_string(&manifest_path) {\n if let Ok(manifest_json) =\n serde_json::from_str::(&manifest_str)\n {\n if !manifest_json\n .get(\"is_installed\")\n .and_then(|v| v.as_bool())\n .unwrap_or(true)\n {\n debug!(\"Skipping upgrade for Cask '{}' as its manifest indicates it's not fully installed.\", name);\n plan.processed_globally.insert(name.clone());\n continue;\n }\n }\n }\n }\n }\n specific.push(info);\n }\n Ok(None) => {\n plan.errors.push((\n name.to_string(),\n SpsError::NotFound(format!(\"Cannot upgrade '{name}': not installed.\")),\n ));\n plan.processed_globally.insert(name.clone());\n }\n Err(e) => {\n plan.errors.push((\n name.to_string(),\n SpsError::Generic(format!(\"Failed to check status for '{name}': {e}\")),\n ));\n plan.processed_globally.insert(name.clone());\n }\n }\n }\n specific\n };\n\n if packages_to_check.is_empty() {\n return Ok(plan);\n }\n\n match update::check_for_updates(&packages_to_check, &self.cache, self.config).await {\n Ok(updates) => {\n let update_map: HashMap =\n updates.into_iter().map(|u| (u.name.clone(), u)).collect();\n\n debug!(\n \"[Planner] Found {} available updates out of {} packages checked\",\n update_map.len(),\n packages_to_check.len()\n );\n debug!(\n \"[Planner] Available updates: {:?}\",\n update_map.keys().collect::>()\n );\n\n for p_info in packages_to_check {\n if plan.processed_globally.contains(&p_info.name) {\n continue;\n }\n if let Some(ui) = update_map.get(&p_info.name) {\n debug!(\n \"[Planner] Adding upgrade job for '{}': {} -> {}\",\n p_info.name, p_info.version, ui.available_version\n );\n plan.initial_ops.insert(\n p_info.name.clone(),\n (\n JobAction::Upgrade {\n from_version: p_info.version.clone(),\n old_install_path: p_info.path.clone(),\n },\n Some(ui.target_definition.clone()),\n ),\n );\n // Don't mark packages with updates as processed_globally\n // so they can be included in the final job list\n } else {\n debug!(\n \"[Planner] No update available for '{}', marking as already satisfied\",\n p_info.name\n );\n plan.already_satisfied.insert(p_info.name.clone());\n // Only mark packages without updates as processed_globally\n plan.processed_globally.insert(p_info.name.clone());\n }\n }\n }\n Err(e) => {\n plan.errors.push((\n \"[Update Check]\".to_string(),\n SpsError::Generic(format!(\"Failed to check for updates: {e}\")),\n ));\n }\n }\n Ok(plan)\n }\n\n // This now returns sps_common::pipeline::PlannedOperations\n pub async fn plan_operations(\n &self,\n initial_targets: &[String],\n command_type: CommandType,\n ) -> PlanResult {\n debug!(\n \"[Planner] Starting plan_operations with command_type: {:?}, targets: {:?}\",\n command_type, initial_targets\n );\n\n let mut intermediate_plan = match command_type {\n CommandType::Install => self.plan_for_install(initial_targets).await?,\n CommandType::Reinstall => self.plan_for_reinstall(initial_targets).await?,\n CommandType::Upgrade { all } => {\n debug!(\"[Planner] Calling plan_for_upgrade with all={}\", all);\n let plan = self.plan_for_upgrade(initial_targets, all).await?;\n debug!(\"[Planner] plan_for_upgrade returned with {} initial_ops, {} errors, {} already_satisfied\",\n plan.initial_ops.len(), plan.errors.len(), plan.already_satisfied.len());\n debug!(\n \"[Planner] Initial ops: {:?}\",\n plan.initial_ops.keys().collect::>()\n );\n debug!(\"[Planner] Already satisfied: {:?}\", plan.already_satisfied);\n plan\n }\n };\n\n let definitions_to_fetch: Vec = intermediate_plan\n .initial_ops\n .iter()\n .filter(|(name, (_, opt_def))| {\n opt_def.is_none() && !intermediate_plan.processed_globally.contains(*name)\n })\n .map(|(name, _)| name.clone())\n .collect();\n\n if !definitions_to_fetch.is_empty() {\n let fetched_defs =\n fetch_target_definitions(&definitions_to_fetch, self.cache.clone()).await;\n for (name, result) in fetched_defs {\n match result {\n Ok(target_def) => {\n if let Some((_action, opt_install_target)) =\n intermediate_plan.initial_ops.get_mut(&name)\n {\n *opt_install_target = Some(target_def);\n }\n }\n Err(e) => {\n intermediate_plan.errors.push((\n name.clone(),\n SpsError::Generic(format!(\"Failed to get definition for target: {e}\")),\n ));\n intermediate_plan.processed_globally.insert(name);\n }\n }\n }\n }\n self.event_tx\n .send(PipelineEvent::DependencyResolutionStarted)\n .ok();\n\n let mut formulae_for_resolution: HashMap = HashMap::new();\n let mut cask_deps_map: HashMap> = HashMap::new();\n let mut cask_processing_queue: VecDeque = VecDeque::new();\n\n for (name, (action, opt_def)) in &intermediate_plan.initial_ops {\n if intermediate_plan.processed_globally.contains(name) {\n continue;\n }\n\n // Handle both normal formula targets and upgrade targets\n match opt_def {\n Some(target @ InstallTargetIdentifier::Formula(_)) => {\n debug!(\n \"[Planner] Adding formula '{}' to resolution list with action {:?}\",\n name, action\n );\n formulae_for_resolution.insert(name.clone(), target.clone());\n }\n Some(InstallTargetIdentifier::Cask(c_arc)) => {\n debug!(\"[Planner] Adding cask '{}' to processing queue\", name);\n cask_processing_queue.push_back(name.clone());\n cask_deps_map.insert(name.clone(), c_arc.clone());\n }\n None => {\n if !intermediate_plan\n .errors\n .iter()\n .any(|(err_name, _)| err_name == name)\n {\n intermediate_plan.errors.push((\n name.clone(),\n SpsError::Generic(format!(\n \"Definition for '{name}' still missing after fetch attempt.\"\n )),\n ));\n intermediate_plan.processed_globally.insert(name.clone());\n }\n }\n }\n }\n\n let mut processed_casks_for_deps_pass: HashSet =\n intermediate_plan.processed_globally.clone();\n\n while let Some(cask_token) = cask_processing_queue.pop_front() {\n if processed_casks_for_deps_pass.contains(&cask_token) {\n continue;\n }\n processed_casks_for_deps_pass.insert(cask_token.clone());\n\n let cask_arc = match cask_deps_map.get(&cask_token) {\n Some(c) => c.clone(),\n None => {\n match fetch_target_definitions(\n std::slice::from_ref(&cask_token),\n self.cache.clone(),\n )\n .await\n .remove(&cask_token)\n {\n Some(Ok(InstallTargetIdentifier::Cask(c))) => {\n cask_deps_map.insert(cask_token.clone(), c.clone());\n c\n }\n Some(Err(e)) => {\n intermediate_plan.errors.push((cask_token.clone(), e));\n intermediate_plan\n .processed_globally\n .insert(cask_token.clone());\n continue;\n }\n _ => {\n intermediate_plan.errors.push((\n cask_token.clone(),\n SpsError::NotFound(format!(\n \"Cask definition for dependency '{cask_token}' not found.\"\n )),\n ));\n intermediate_plan\n .processed_globally\n .insert(cask_token.clone());\n continue;\n }\n }\n }\n };\n\n if let Some(deps) = &cask_arc.depends_on {\n for formula_dep_name in &deps.formula {\n if formulae_for_resolution.contains_key(formula_dep_name)\n || intermediate_plan\n .errors\n .iter()\n .any(|(n, _)| n == formula_dep_name)\n || intermediate_plan\n .already_satisfied\n .contains(formula_dep_name)\n {\n continue;\n }\n match fetch_target_definitions(\n std::slice::from_ref(formula_dep_name),\n self.cache.clone(),\n )\n .await\n .remove(formula_dep_name)\n {\n Some(Ok(target_def @ InstallTargetIdentifier::Formula(_))) => {\n formulae_for_resolution.insert(formula_dep_name.clone(), target_def);\n }\n Some(Ok(InstallTargetIdentifier::Cask(_))) => {\n intermediate_plan.errors.push((\n formula_dep_name.clone(),\n SpsError::Generic(format!(\n \"Dependency '{formula_dep_name}' of Cask '{cask_token}' is unexpectedly a Cask itself.\"\n )),\n ));\n intermediate_plan\n .processed_globally\n .insert(formula_dep_name.clone());\n }\n Some(Err(e)) => {\n intermediate_plan.errors.push((\n formula_dep_name.clone(),\n SpsError::Generic(format!(\n \"Failed def fetch for formula dep '{formula_dep_name}' of cask '{cask_token}': {e}\"\n )),\n ));\n intermediate_plan\n .processed_globally\n .insert(formula_dep_name.clone());\n }\n None => {\n intermediate_plan.errors.push((\n formula_dep_name.clone(),\n SpsError::NotFound(format!(\n \"Formula dep '{formula_dep_name}' for cask '{cask_token}' not found.\"\n )),\n ));\n intermediate_plan\n .processed_globally\n .insert(formula_dep_name.clone());\n }\n }\n }\n for dep_cask_token in &deps.cask {\n if !processed_casks_for_deps_pass.contains(dep_cask_token)\n && !cask_processing_queue.contains(dep_cask_token)\n {\n cask_processing_queue.push_back(dep_cask_token.clone());\n }\n }\n }\n }\n\n let mut resolved_formula_graph_opt: Option> = None;\n if !formulae_for_resolution.is_empty() {\n let targets_for_resolver: Vec<_> = formulae_for_resolution.keys().cloned().collect();\n let formulary = Formulary::new(self.config.clone());\n let keg_registry = KegRegistry::new(self.config.clone());\n\n let per_target_prefs = PerTargetInstallPreferences {\n force_source_build_targets: if self.flags.build_from_source {\n targets_for_resolver.iter().cloned().collect()\n } else {\n HashSet::new()\n },\n force_bottle_only_targets: HashSet::new(),\n };\n\n // Create map of initial target actions for the resolver\n let initial_target_actions: HashMap = intermediate_plan\n .initial_ops\n .iter()\n .filter_map(|(name, (action, _))| {\n if targets_for_resolver.contains(name) {\n Some((name.clone(), action.clone()))\n } else {\n debug!(\"[Planner] WARNING: Target '{}' with action {:?} is not in targets_for_resolver!\", name, action);\n None\n }\n })\n .collect();\n\n debug!(\n \"[Planner] Created initial_target_actions map with {} entries: {:?}\",\n initial_target_actions.len(),\n initial_target_actions\n );\n debug!(\"[Planner] Targets for resolver: {:?}\", targets_for_resolver);\n\n let ctx = ResolutionContext {\n formulary: &formulary,\n keg_registry: &keg_registry,\n sps_prefix: self.config.sps_root(),\n include_optional: self.flags.include_optional,\n include_test: false,\n skip_recommended: self.flags.skip_recommended,\n initial_target_preferences: &per_target_prefs,\n build_all_from_source: self.flags.build_from_source,\n cascade_source_preference_to_dependencies: true,\n has_bottle_for_current_platform:\n sps_core::install::bottle::has_bottle_for_current_platform,\n initial_target_actions: &initial_target_actions,\n };\n\n let mut resolver = DependencyResolver::new(ctx);\n debug!(\"[Planner] Created DependencyResolver, calling resolve_targets...\");\n match resolver.resolve_targets(&targets_for_resolver) {\n Ok(g) => {\n debug!(\n \"[Planner] Dependency resolution succeeded! Install plan has {} items\",\n g.install_plan.len()\n );\n resolved_formula_graph_opt = Some(Arc::new(g));\n }\n Err(e) => {\n debug!(\"[Planner] Dependency resolution failed: {}\", e);\n let resolver_error_msg = e.to_string(); // Capture full error\n for n in targets_for_resolver {\n if !intermediate_plan\n .errors\n .iter()\n .any(|(err_n, _)| err_n == &n)\n {\n intermediate_plan.errors.push((\n n.clone(),\n SpsError::DependencyError(resolver_error_msg.clone()),\n ));\n }\n intermediate_plan.processed_globally.insert(n);\n }\n }\n }\n }\n self.event_tx\n .send(PipelineEvent::DependencyResolutionFinished)\n .ok();\n\n let mut final_planned_jobs: Vec = Vec::new();\n let mut names_processed_from_initial_ops = HashSet::new();\n\n debug!(\n \"[Planner] Processing {} initial_ops into final jobs\",\n intermediate_plan.initial_ops.len()\n );\n for (name, (action, opt_def)) in &intermediate_plan.initial_ops {\n debug!(\n \"[Planner] Processing initial op '{}': action={:?}, has_def={}\",\n name,\n action,\n opt_def.is_some()\n );\n\n if intermediate_plan.processed_globally.contains(name) {\n debug!(\"[Planner] Skipping '{}' - already processed globally\", name);\n continue;\n }\n // If an error was recorded for this specific initial target (e.g. resolver failed for\n // it, or def missing) ensure it's marked as globally processed and not\n // added to final_planned_jobs.\n if intermediate_plan\n .errors\n .iter()\n .any(|(err_name, _)| err_name == name)\n {\n debug!(\"[Planner] Skipping job for initial op '{}' as an error was recorded for it during planning.\", name);\n intermediate_plan.processed_globally.insert(name.clone());\n continue;\n }\n if intermediate_plan.already_satisfied.contains(name) {\n debug!(\n \"[Planner] Skipping job for initial op '{}' as it's already satisfied.\",\n name\n );\n intermediate_plan.processed_globally.insert(name.clone());\n continue;\n }\n\n match opt_def {\n Some(target_def) => {\n let is_source_build = determine_build_strategy_for_job(\n target_def,\n action,\n self.flags,\n resolved_formula_graph_opt.as_deref(),\n self,\n );\n\n final_planned_jobs.push(PlannedJob {\n target_id: name.clone(),\n target_definition: target_def.clone(),\n action: action.clone(),\n is_source_build,\n use_private_store_source: intermediate_plan\n .private_store_sources\n .get(name)\n .cloned(),\n });\n names_processed_from_initial_ops.insert(name.clone());\n }\n None => {\n tracing::error!(\"[Planner] CRITICAL: Definition missing for planned operation on '{}' but no error was recorded in intermediate_plan.errors. This should not happen.\", name);\n if !intermediate_plan\n .errors\n .iter()\n .any(|(err_n, _)| err_n == name)\n {\n intermediate_plan.errors.push((\n name.clone(),\n SpsError::Generic(\"Definition missing unexpectedly.\".into()),\n ));\n }\n intermediate_plan.processed_globally.insert(name.clone());\n }\n }\n }\n\n if let Some(graph) = resolved_formula_graph_opt.as_ref() {\n for dep_detail in &graph.install_plan {\n let dep_name = dep_detail.formula.name();\n\n if names_processed_from_initial_ops.contains(dep_name)\n || intermediate_plan.processed_globally.contains(dep_name)\n || final_planned_jobs.iter().any(|j| j.target_id == dep_name)\n {\n continue;\n }\n\n if intermediate_plan\n .errors\n .iter()\n .any(|(err_name, _)| err_name == dep_name)\n {\n tracing::debug!(\"[Planner] Skipping job for dependency '{}' due to a pre-existing error recorded for it.\", dep_name);\n intermediate_plan\n .processed_globally\n .insert(dep_name.to_string());\n continue;\n }\n if dep_detail.status == ResolutionStatus::Failed {\n tracing::debug!(\"[Planner] Skipping job for dependency '{}' as its resolution status is Failed. Adding to planner errors.\", dep_name);\n // Ensure this error is also captured if not already.\n if !intermediate_plan\n .errors\n .iter()\n .any(|(err_name, _)| err_name == dep_name)\n {\n intermediate_plan.errors.push((\n dep_name.to_string(),\n SpsError::DependencyError(format!(\n \"Resolution failed for dependency {dep_name}\"\n )),\n ));\n }\n intermediate_plan\n .processed_globally\n .insert(dep_name.to_string());\n continue;\n }\n\n if matches!(\n dep_detail.status,\n ResolutionStatus::Missing | ResolutionStatus::Requested\n ) {\n let is_source_build_for_dep = determine_build_strategy_for_job(\n &InstallTargetIdentifier::Formula(dep_detail.formula.clone()),\n &JobAction::Install,\n self.flags,\n Some(graph),\n self,\n );\n debug!(\n \"Planning install for new formula dependency '{}'. Source build: {}\",\n dep_name, is_source_build_for_dep\n );\n\n final_planned_jobs.push(PlannedJob {\n target_id: dep_name.to_string(),\n target_definition: InstallTargetIdentifier::Formula(\n dep_detail.formula.clone(),\n ),\n action: JobAction::Install,\n is_source_build: is_source_build_for_dep,\n use_private_store_source: None,\n });\n } else if dep_detail.status == ResolutionStatus::Installed {\n intermediate_plan\n .already_satisfied\n .insert(dep_name.to_string());\n }\n }\n }\n\n for (cask_token, cask_arc) in cask_deps_map {\n if names_processed_from_initial_ops.contains(&cask_token)\n || intermediate_plan.processed_globally.contains(&cask_token)\n || final_planned_jobs.iter().any(|j| j.target_id == cask_token)\n {\n continue;\n }\n\n match self.check_installed_status(&cask_token).await {\n Ok(None) => {\n final_planned_jobs.push(PlannedJob {\n target_id: cask_token.clone(),\n target_definition: InstallTargetIdentifier::Cask(cask_arc.clone()),\n action: JobAction::Install,\n is_source_build: false,\n use_private_store_source: intermediate_plan\n .private_store_sources\n .get(&cask_token)\n .cloned(),\n });\n }\n Ok(Some(_installed_info)) => {\n intermediate_plan\n .already_satisfied\n .insert(cask_token.clone());\n }\n Err(e) => {\n intermediate_plan.errors.push((\n cask_token.clone(),\n SpsError::Generic(format!(\n \"Failed check install status for cask dependency {cask_token}: {e}\"\n )),\n ));\n intermediate_plan\n .processed_globally\n .insert(cask_token.clone());\n }\n }\n }\n if let Some(graph) = resolved_formula_graph_opt.as_ref() {\n if !final_planned_jobs.is_empty() {\n sort_planned_jobs(&mut final_planned_jobs, graph);\n }\n }\n\n debug!(\n \"[Planner] Finishing plan_operations with {} jobs, {} errors, {} already_satisfied\",\n final_planned_jobs.len(),\n intermediate_plan.errors.len(),\n intermediate_plan.already_satisfied.len()\n );\n debug!(\n \"[Planner] Final jobs: {:?}\",\n final_planned_jobs\n .iter()\n .map(|j| &j.target_id)\n .collect::>()\n );\n\n Ok(PlannedOperations {\n jobs: final_planned_jobs,\n errors: intermediate_plan.errors,\n already_installed_or_up_to_date: intermediate_plan.already_satisfied,\n resolved_graph: resolved_formula_graph_opt,\n })\n }\n}\n\nfn determine_build_strategy_for_job(\n target_def: &InstallTargetIdentifier,\n action: &JobAction,\n flags: &PipelineFlags,\n resolved_graph: Option<&ResolvedGraph>,\n planner: &OperationPlanner,\n) -> bool {\n match target_def {\n InstallTargetIdentifier::Formula(formula_arc) => {\n if flags.build_from_source {\n return true;\n }\n if let Some(graph) = resolved_graph {\n if let Some(resolved_detail) = graph.resolution_details.get(formula_arc.name()) {\n match resolved_detail.determined_install_strategy {\n NodeInstallStrategy::SourceOnly => return true,\n NodeInstallStrategy::BottleOrFail => return false,\n NodeInstallStrategy::BottlePreferred => {}\n }\n }\n }\n if let JobAction::Upgrade {\n old_install_path, ..\n } = action\n {\n if planner\n .get_previous_installation_type(old_install_path)\n .as_deref()\n == Some(\"source\")\n {\n return true;\n }\n }\n !sps_core::install::bottle::has_bottle_for_current_platform(formula_arc)\n }\n InstallTargetIdentifier::Cask(_) => false,\n }\n}\n\nfn sort_planned_jobs(jobs: &mut [PlannedJob], formula_graph: &ResolvedGraph) {\n let formula_order: HashMap = formula_graph\n .install_plan\n .iter()\n .enumerate()\n .map(|(idx, dep_detail)| (dep_detail.formula.name().to_string(), idx))\n .collect();\n\n jobs.sort_by_key(|job| match &job.target_definition {\n InstallTargetIdentifier::Formula(f_arc) => formula_order\n .get(f_arc.name())\n .copied()\n .unwrap_or(usize::MAX),\n InstallTargetIdentifier::Cask(_) => usize::MAX - 1,\n });\n}\n"], ["/sps/sps-net/src/api.rs", "use std::sync::Arc;\n\nuse reqwest::header::{ACCEPT, AUTHORIZATION, USER_AGENT};\nuse reqwest::Client;\nuse serde_json::Value;\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::cask::{Cask, CaskList};\nuse sps_common::model::formula::Formula;\nuse tracing::{debug, error};\n\nconst FORMULAE_API_BASE_URL: &str = \"https://formulae.brew.sh/api\";\nconst GITHUB_API_BASE_URL: &str = \"https://api.github.com\";\nconst USER_AGENT_STRING: &str = \"sps Package Manager (Rust; +https://github.com/your/sp)\";\n\nfn build_api_client(config: &Config) -> Result {\n let mut headers = reqwest::header::HeaderMap::new();\n headers.insert(USER_AGENT, USER_AGENT_STRING.parse().unwrap());\n headers.insert(ACCEPT, \"application/vnd.github+json\".parse().unwrap());\n if let Some(token) = &config.github_api_token {\n debug!(\"Adding GitHub API token to request headers.\");\n match format!(\"Bearer {token}\").parse() {\n Ok(val) => {\n headers.insert(AUTHORIZATION, val);\n }\n Err(e) => {\n error!(\"Failed to parse GitHub API token into header value: {}\", e);\n }\n }\n } else {\n debug!(\"No GitHub API token found in config.\");\n }\n Ok(Client::builder().default_headers(headers).build()?)\n}\n\npub async fn fetch_raw_formulae_json(endpoint: &str) -> Result {\n let url = format!(\"{FORMULAE_API_BASE_URL}/{endpoint}\");\n debug!(\"Fetching data from Homebrew Formulae API: {}\", url);\n let client = reqwest::Client::builder()\n .user_agent(USER_AGENT_STRING)\n .build()?;\n let response = client.get(&url).send().await.map_err(|e| {\n debug!(\"HTTP request failed for {}: {}\", url, e);\n SpsError::Http(Arc::new(e))\n })?;\n if !response.status().is_success() {\n let status = response.status();\n let body = response\n .text()\n .await\n .unwrap_or_else(|e| format!(\"(Failed to read response body: {e})\"));\n debug!(\n \"HTTP request to {} returned non-success status: {}\",\n url, status\n );\n debug!(\"Response body for failed request to {}: {}\", url, body);\n return Err(SpsError::Api(format!(\"HTTP status {status} from {url}\")));\n }\n let body = response.text().await?;\n if body.trim().is_empty() {\n error!(\"Response body for {} was empty.\", url);\n return Err(SpsError::Api(format!(\n \"Empty response body received from {url}\"\n )));\n }\n Ok(body)\n}\n\npub async fn fetch_all_formulas() -> Result {\n fetch_raw_formulae_json(\"formula.json\").await\n}\n\npub async fn fetch_all_casks() -> Result {\n fetch_raw_formulae_json(\"cask.json\").await\n}\n\npub async fn fetch_formula(name: &str) -> Result {\n let direct_fetch_result = fetch_raw_formulae_json(&format!(\"formula/{name}.json\")).await;\n if let Ok(body) = direct_fetch_result {\n let formula: serde_json::Value = serde_json::from_str(&body)?;\n Ok(formula)\n } else {\n debug!(\n \"Direct fetch for formula '{}' failed ({:?}). Fetching full list as fallback.\",\n name,\n direct_fetch_result.err()\n );\n let all_formulas_body = fetch_all_formulas().await?;\n let formulas: Vec = serde_json::from_str(&all_formulas_body)?;\n for formula in formulas {\n if formula.get(\"name\").and_then(Value::as_str) == Some(name) {\n return Ok(formula);\n }\n if formula.get(\"full_name\").and_then(Value::as_str) == Some(name) {\n return Ok(formula);\n }\n }\n Err(SpsError::NotFound(format!(\n \"Formula '{name}' not found in API list\"\n )))\n }\n}\n\npub async fn fetch_cask(token: &str) -> Result {\n let direct_fetch_result = fetch_raw_formulae_json(&format!(\"cask/{token}.json\")).await;\n if let Ok(body) = direct_fetch_result {\n let cask: serde_json::Value = serde_json::from_str(&body)?;\n Ok(cask)\n } else {\n debug!(\n \"Direct fetch for cask '{}' failed ({:?}). Fetching full list as fallback.\",\n token,\n direct_fetch_result.err()\n );\n let all_casks_body = fetch_all_casks().await?;\n let casks: Vec = serde_json::from_str(&all_casks_body)?;\n for cask in casks {\n if cask.get(\"token\").and_then(Value::as_str) == Some(token) {\n return Ok(cask);\n }\n }\n Err(SpsError::NotFound(format!(\n \"Cask '{token}' not found in API list\"\n )))\n }\n}\n\nasync fn fetch_github_api_json(endpoint: &str, config: &Config) -> Result {\n let url = format!(\"{GITHUB_API_BASE_URL}{endpoint}\");\n debug!(\"Fetching data from GitHub API: {}\", url);\n let client = build_api_client(config)?;\n let response = client.get(&url).send().await.map_err(|e| {\n error!(\"GitHub API request failed for {}: {}\", url, e);\n SpsError::Http(Arc::new(e))\n })?;\n if !response.status().is_success() {\n let status = response.status();\n let body = response\n .text()\n .await\n .unwrap_or_else(|e| format!(\"(Failed to read response body: {e})\"));\n error!(\n \"GitHub API request to {} returned non-success status: {}\",\n url, status\n );\n debug!(\n \"Response body for failed GitHub API request to {}: {}\",\n url, body\n );\n return Err(SpsError::Api(format!(\"HTTP status {status} from {url}\")));\n }\n let value: Value = response.json::().await.map_err(|e| {\n error!(\"Failed to parse JSON response from {}: {}\", url, e);\n SpsError::ApiRequestError(e.to_string())\n })?;\n Ok(value)\n}\n\n#[allow(dead_code)]\nasync fn fetch_github_repo_info(owner: &str, repo: &str, config: &Config) -> Result {\n let endpoint = format!(\"/repos/{owner}/{repo}\");\n fetch_github_api_json(&endpoint, config).await\n}\n\npub async fn get_formula(name: &str) -> Result {\n let url = format!(\"{FORMULAE_API_BASE_URL}/formula/{name}.json\");\n debug!(\n \"Fetching and parsing formula data for '{}' from {}\",\n name, url\n );\n let client = reqwest::Client::new();\n let response = client.get(&url).send().await.map_err(|e| {\n debug!(\"HTTP request failed when fetching formula {}: {}\", name, e);\n SpsError::Http(Arc::new(e))\n })?;\n let status = response.status();\n let text = response.text().await?;\n if !status.is_success() {\n debug!(\"Failed to fetch formula {} (Status {})\", name, status);\n debug!(\"Response body for failed formula fetch {}: {}\", name, text);\n return Err(SpsError::Api(format!(\n \"Failed to fetch formula {name}: Status {status}\"\n )));\n }\n if text.trim().is_empty() {\n error!(\"Received empty body when fetching formula {}\", name);\n return Err(SpsError::Api(format!(\n \"Empty response body for formula {name}\"\n )));\n }\n match serde_json::from_str::(&text) {\n Ok(formula) => Ok(formula),\n Err(_) => match serde_json::from_str::>(&text) {\n Ok(mut formulas) if !formulas.is_empty() => {\n debug!(\n \"Parsed formula {} from a single-element array response.\",\n name\n );\n Ok(formulas.remove(0))\n }\n Ok(_) => {\n error!(\"Received empty array when fetching formula {}\", name);\n Err(SpsError::NotFound(format!(\n \"Formula '{name}' not found (empty array returned)\"\n )))\n }\n Err(e_vec) => {\n error!(\n \"Failed to parse formula {} as object or array. Error: {}. Body (sample): {}\",\n name,\n e_vec,\n text.chars().take(500).collect::()\n );\n Err(SpsError::Json(Arc::new(e_vec)))\n }\n },\n }\n}\n\npub async fn get_all_formulas() -> Result> {\n let raw_data = fetch_all_formulas().await?;\n serde_json::from_str(&raw_data).map_err(|e| {\n error!(\"Failed to parse all_formulas response: {}\", e);\n SpsError::Json(Arc::new(e))\n })\n}\n\npub async fn get_cask(name: &str) -> Result {\n let raw_json_result = fetch_cask(name).await;\n let raw_json = match raw_json_result {\n Ok(json_val) => json_val,\n Err(e) => {\n error!(\"Failed to fetch raw JSON for cask {}: {}\", name, e);\n return Err(e);\n }\n };\n match serde_json::from_value::(raw_json.clone()) {\n Ok(cask) => Ok(cask),\n Err(e) => {\n error!(\"Failed to parse cask {} JSON: {}\", name, e);\n match serde_json::to_string_pretty(&raw_json) {\n Ok(json_str) => {\n tracing::debug!(\"Problematic JSON for cask '{}':\\n{}\", name, json_str);\n }\n Err(fmt_err) => {\n tracing::debug!(\n \"Could not pretty-print problematic JSON for cask {}: {}\",\n name,\n fmt_err\n );\n tracing::debug!(\"Raw problematic value: {:?}\", raw_json);\n }\n }\n Err(SpsError::Json(Arc::new(e)))\n }\n }\n}\n\npub async fn get_all_casks() -> Result {\n let raw_data = fetch_all_casks().await?;\n let casks: Vec = serde_json::from_str(&raw_data).map_err(|e| {\n error!(\"Failed to parse all_casks response: {}\", e);\n SpsError::Json(Arc::new(e))\n })?;\n Ok(CaskList { casks })\n}\n"], ["/sps/sps/src/cli/uninstall.rs", "use std::collections::{HashMap, HashSet};\nuse std::sync::Arc;\n\nuse clap::Args;\nuse colored::Colorize;\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::cask::Cask;\nuse sps_common::Cache;\nuse sps_core::check::{installed, PackageType};\nuse sps_core::{uninstall as core_uninstall, UninstallOptions};\nuse sps_net::api;\nuse tracing::{debug, error, warn};\nuse {serde_json, walkdir};\n\n#[derive(Args, Debug)]\npub struct Uninstall {\n /// The names of the formulas or casks to uninstall\n #[arg(required = true)] // Ensure at least one name is given\n pub names: Vec,\n /// Perform a deep clean for casks, removing associated user data, caches,\n /// and configuration files. Use with caution, data will be lost! Ignored for formulas.\n #[arg(\n long,\n help = \"Perform a deep clean for casks, removing associated user data, caches, and configuration files. Use with caution!\"\n )]\n pub zap: bool,\n}\n\nimpl Uninstall {\n pub async fn run(&self, config: &Config, cache: Arc) -> Result<()> {\n let names = &self.names;\n let mut errors: Vec<(String, SpsError)> = Vec::new();\n\n for name in names {\n // Basic name validation to prevent path traversal\n if name.contains('/') || name.contains(\"..\") {\n let msg = format!(\"Invalid package name '{name}' contains disallowed characters\");\n error!(\"✖ {msg}\");\n errors.push((name.to_string(), SpsError::Generic(msg)));\n continue;\n }\n\n println!(\"Uninstalling {name}...\");\n\n match installed::get_installed_package(name, config).await {\n Ok(Some(installed_info)) => {\n let (file_count, size_bytes) =\n count_files_and_size(&installed_info.path).unwrap_or((0, 0));\n let uninstall_opts = UninstallOptions { skip_zap: false };\n debug!(\n \"Attempting uninstall for {} ({:?})\",\n name, installed_info.pkg_type\n );\n let uninstall_result = match installed_info.pkg_type {\n PackageType::Formula => {\n if self.zap {\n warn!(\"--zap flag is ignored for formulas like '{}'.\", name);\n }\n core_uninstall::uninstall_formula_artifacts(\n &installed_info,\n config,\n &uninstall_opts,\n )\n }\n PackageType::Cask => {\n core_uninstall::uninstall_cask_artifacts(&installed_info, config)\n }\n };\n\n if let Err(e) = uninstall_result {\n error!(\"✖ Failed to uninstall '{}': {}\", name.cyan(), e);\n errors.push((name.to_string(), e));\n // Continue to zap anyway for casks, as per plan\n } else {\n println!(\n \"✓ Uninstalled {:?} {} ({} files, {})\",\n installed_info.pkg_type,\n name.green(),\n file_count,\n format_size(size_bytes)\n );\n }\n\n // --- Zap Uninstall (Conditional) ---\n if self.zap && installed_info.pkg_type == PackageType::Cask {\n println!(\"Zapping {name}...\");\n debug!(\n \"--zap specified for cask '{}', attempting deep clean.\",\n name\n );\n\n // Fetch the Cask definition (needed for the zap stanza)\n let cask_def_result: Result = async {\n match api::get_cask(name).await {\n Ok(cask) => Ok(cask),\n Err(e) => {\n warn!(\"Failed API fetch for zap definition for '{}' ({}), trying cache...\", name, e);\n match cache.load_raw(\"cask.json\") {\n Ok(raw_json) => {\n let casks: Vec = serde_json::from_str(&raw_json)\n .map_err(|cache_e| SpsError::Cache(format!(\"Failed parse cached cask.json: {cache_e}\")))?;\n casks.into_iter()\n .find(|c| c.token == *name)\n .ok_or_else(|| SpsError::NotFound(format!(\"Cask '{name}' def not in cache either\")))\n }\n Err(cache_e) => Err(SpsError::Cache(format!(\"Failed load cask cache for zap: {cache_e}\"))),\n }\n }\n }\n }.await;\n\n match cask_def_result {\n Ok(cask_def) => {\n match core_uninstall::zap_cask_artifacts(\n &installed_info,\n &cask_def,\n config,\n )\n .await\n {\n Ok(_) => {\n println!(\"✓ Zap complete for {}\", name.green());\n }\n Err(zap_err) => {\n error!(\"✖ Zap failed for '{}': {}\", name.cyan(), zap_err);\n errors.push((format!(\"{name} (zap)\"), zap_err));\n }\n }\n }\n Err(e) => {\n error!(\n \"✖ Could not get Cask definition for zap '{}': {}\",\n name.cyan(),\n e\n );\n errors.push((format!(\"{name} (zap definition)\"), e));\n }\n }\n }\n }\n Ok(None) => {\n let msg = format!(\"Package '{name}' is not installed.\");\n error!(\"✖ {msg}\");\n errors.push((name.to_string(), SpsError::NotFound(msg)));\n }\n Err(e) => {\n let msg = format!(\"Failed check install status for '{name}': {e}\");\n error!(\"✖ {msg}\");\n errors.push((name.clone(), SpsError::Generic(msg)));\n }\n }\n }\n\n if errors.is_empty() {\n Ok(())\n } else {\n eprintln!(\"\\n{}:\", \"Finished uninstalling with errors\".yellow());\n let mut errors_by_pkg: HashMap> = HashMap::new();\n for (pkg_name, error) in errors {\n errors_by_pkg\n .entry(pkg_name)\n .or_default()\n .push(error.to_string());\n }\n for (pkg_name, error_list) in errors_by_pkg {\n eprintln!(\"Package '{}':\", pkg_name.cyan());\n let unique_errors: HashSet<_> = error_list.into_iter().collect();\n for error_str in unique_errors {\n eprintln!(\"- {}\", error_str.red());\n }\n }\n Err(SpsError::Generic(\n \"Uninstall failed for one or more packages.\".to_string(),\n ))\n }\n }\n}\n\n// --- Unchanged Helper Functions ---\nfn count_files_and_size(path: &std::path::Path) -> Result<(usize, u64)> {\n let mut file_count = 0;\n let mut total_size = 0;\n for entry in walkdir::WalkDir::new(path) {\n match entry {\n Ok(entry_data) => {\n if entry_data.file_type().is_file() || entry_data.file_type().is_symlink() {\n match entry_data.metadata() {\n Ok(metadata) => {\n file_count += 1;\n if entry_data.file_type().is_file() {\n total_size += metadata.len();\n }\n }\n Err(e) => {\n tracing::warn!(\n \"Could not get metadata for {}: {}\",\n entry_data.path().display(),\n e\n );\n }\n }\n }\n }\n Err(e) => {\n tracing::warn!(\"Error traversing directory {}: {}\", path.display(), e);\n }\n }\n }\n Ok((file_count, total_size))\n}\n\nfn format_size(size: u64) -> String {\n const KB: u64 = 1024;\n const MB: u64 = KB * 1024;\n const GB: u64 = MB * 1024;\n if size >= GB {\n format!(\"{:.1}GB\", size as f64 / GB as f64)\n } else if size >= MB {\n format!(\"{:.1}MB\", size as f64 / MB as f64)\n } else if size >= KB {\n format!(\"{:.1}KB\", size as f64 / KB as f64)\n } else {\n format!(\"{size}B\")\n }\n}\n"], ["/sps/sps-core/src/install/cask/mod.rs", "pub mod artifacts;\npub mod dmg;\npub mod helpers;\n\nuse std::fs;\nuse std::path::{Path, PathBuf};\nuse std::time::{SystemTime, SystemTimeError, UNIX_EPOCH};\n\nuse infer;\nuse reqwest::Url;\nuse serde::{Deserialize, Serialize};\nuse serde_json::json;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::{Cask, Sha256Field, UrlField};\nuse sps_net::http::ProgressCallback;\nuse tempfile::TempDir;\nuse tracing::{debug, error};\n\nuse crate::install::extract;\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub struct CaskInstallManifest {\n pub manifest_format_version: String,\n pub token: String,\n pub version: String,\n pub installed_at: u64,\n pub artifacts: Vec,\n pub primary_app_file_name: Option,\n pub is_installed: bool, // New flag for soft uninstall\n pub cask_store_path: Option, // Path to private store app, if available\n}\n\n/// Returns the path to the cask's version directory in the private store.\npub fn sps_private_cask_version_dir(cask: &Cask, config: &Config) -> PathBuf {\n let version = cask.version.clone().unwrap_or_else(|| \"latest\".to_string());\n config.cask_store_version_path(&cask.token, &version)\n}\n\n/// Returns the path to the cask's token directory in the private store.\npub fn sps_private_cask_token_dir(cask: &Cask, config: &Config) -> PathBuf {\n config.cask_store_token_path(&cask.token)\n}\n\n/// Returns the path to the main app bundle for a cask in the private store.\n/// This assumes the primary app bundle is named as specified in the cask's artifacts.\npub fn sps_private_cask_app_path(cask: &Cask, config: &Config) -> Option {\n let version = cask.version.clone().unwrap_or_else(|| \"latest\".to_string());\n if let Some(cask_artifacts) = &cask.artifacts {\n for artifact in cask_artifacts {\n if let Some(obj) = artifact.as_object() {\n if let Some(apps) = obj.get(\"app\") {\n if let Some(app_names) = apps.as_array() {\n if let Some(app_name_val) = app_names.first() {\n if let Some(app_name) = app_name_val.as_str() {\n return Some(config.cask_store_app_path(\n &cask.token,\n &version,\n app_name,\n ));\n }\n }\n }\n }\n }\n }\n }\n None\n}\n\npub async fn download_cask(cask: &Cask, cache: &Cache) -> Result {\n download_cask_with_progress(cask, cache, None).await\n}\n\npub async fn download_cask_with_progress(\n cask: &Cask,\n cache: &Cache,\n progress_callback: Option,\n) -> Result {\n let url_field = cask\n .url\n .as_ref()\n .ok_or_else(|| SpsError::Generic(format!(\"Cask {} has no URL\", cask.token)))?;\n let url_str = match url_field {\n UrlField::Simple(u) => u.as_str(),\n UrlField::WithSpec { url, .. } => url.as_str(),\n };\n\n if url_str.is_empty() {\n return Err(SpsError::Generic(format!(\n \"Cask {} has an empty URL\",\n cask.token\n )));\n }\n\n debug!(\"Downloading cask from {}\", url_str);\n let parsed = Url::parse(url_str)\n .map_err(|e| SpsError::Generic(format!(\"Invalid URL '{url_str}': {e}\")))?;\n sps_net::validation::validate_url(parsed.as_str())?;\n let file_name = parsed\n .path_segments()\n .and_then(|mut segments| segments.next_back())\n .filter(|s| !s.is_empty())\n .map(|s| s.to_string())\n .unwrap_or_else(|| {\n debug!(\"URL has no filename component, using fallback name for cache based on token.\");\n format!(\"cask-{}-download.tmp\", cask.token.replace('/', \"_\"))\n });\n let cache_key = format!(\"cask-{}-{}\", cask.token, file_name);\n let cache_path = cache.get_dir().join(\"cask_downloads\").join(&cache_key);\n\n if cache_path.exists() {\n debug!(\"Using cached download: {}\", cache_path.display());\n return Ok(cache_path);\n }\n\n use futures::StreamExt;\n use tokio::fs::File as TokioFile;\n use tokio::io::AsyncWriteExt;\n\n let client = reqwest::Client::new();\n let response = client\n .get(parsed.clone())\n .send()\n .await\n .map_err(|e| SpsError::Http(std::sync::Arc::new(e)))?;\n if !response.status().is_success() {\n return Err(SpsError::DownloadError(\n cask.token.clone(),\n url_str.to_string(),\n format!(\"HTTP status {}\", response.status()),\n ));\n }\n\n // Get total size from Content-Length header if available\n let total_size = response.content_length();\n\n if let Some(parent) = cache_path.parent() {\n fs::create_dir_all(parent)?;\n }\n\n let mut file = TokioFile::create(&cache_path)\n .await\n .map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n\n // Use bytes_stream() for chunked download with progress reporting\n let mut stream = response.bytes_stream();\n let mut bytes_downloaded = 0u64;\n\n while let Some(chunk) = stream.next().await {\n let chunk = chunk.map_err(|e| SpsError::Http(std::sync::Arc::new(e)))?;\n\n file.write_all(&chunk)\n .await\n .map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n\n bytes_downloaded += chunk.len() as u64;\n\n // Call progress callback if provided\n if let Some(ref callback) = progress_callback {\n callback(bytes_downloaded, total_size);\n }\n }\n\n drop(file);\n match cask.sha256.as_ref() {\n Some(Sha256Field::Hex(s)) => {\n if s.eq_ignore_ascii_case(\"no_check\") {\n tracing::debug!(\n \"Skipping checksum verification for cask {} due to 'no_check' string.\",\n cache_path.display()\n );\n } else if !s.is_empty() {\n match sps_net::validation::verify_checksum(&cache_path, s) {\n Ok(_) => {\n tracing::debug!(\n \"Cask download checksum verified: {}\",\n cache_path.display()\n );\n }\n Err(e) => {\n tracing::error!(\n \"Cask download checksum mismatch ({}). Deleting cached file.\",\n e\n );\n let _ = fs::remove_file(&cache_path);\n return Err(e);\n }\n }\n } else {\n tracing::warn!(\n \"Skipping checksum verification for cask {} - empty sha256 provided.\",\n cache_path.display()\n );\n }\n }\n Some(Sha256Field::NoCheck { no_check: true }) => {\n tracing::debug!(\n \"Skipping checksum verification for cask {} due to 'no_check'.\",\n cache_path.display()\n );\n }\n _ => {\n tracing::warn!(\n \"Skipping checksum verification for cask {} - none provided.\",\n cache_path.display()\n );\n }\n }\n debug!(\"Download completed: {}\", cache_path.display());\n\n // --- Set quarantine xattr on the downloaded archive (macOS only) ---\n #[cfg(target_os = \"macos\")]\n {\n if let Err(e) = crate::utils::xattr::set_quarantine_attribute(&cache_path, \"sps-downloader\")\n {\n tracing::warn!(\n \"Failed to set quarantine attribute on downloaded archive {}: {}. Extraction and installation will proceed, but Gatekeeper behavior might be affected.\",\n cache_path.display(),\n e\n );\n }\n }\n\n Ok(cache_path)\n}\n\nuse sps_common::pipeline::JobAction;\n\npub fn install_cask(\n cask: &Cask,\n download_path: &Path,\n config: &Config,\n job_action: &JobAction,\n) -> Result<()> {\n debug!(\"Installing cask: {}\", cask.token);\n // This is the path in the *actual* Caskroom (e.g., /opt/homebrew/Caskroom/token/version)\n // where metadata and symlinks to /Applications will go.\n let actual_cask_room_version_path = config.cask_room_version_path(\n &cask.token,\n &cask.version.clone().unwrap_or_else(|| \"latest\".to_string()),\n );\n\n if !actual_cask_room_version_path.exists() {\n fs::create_dir_all(&actual_cask_room_version_path).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\n \"Failed create cask_room dir {}: {}\",\n actual_cask_room_version_path.display(),\n e\n ),\n )))\n })?;\n debug!(\n \"Created actual cask_room version directory: {}\",\n actual_cask_room_version_path.display()\n );\n }\n let mut detected_extension = download_path\n .extension()\n .and_then(|e| e.to_str())\n .unwrap_or(\"\")\n .to_lowercase();\n let non_extensions = [\"stable\", \"latest\", \"download\", \"bin\", \"\"];\n if non_extensions.contains(&detected_extension.as_str()) {\n debug!(\n \"Download path '{}' has no definite extension ('{}'), attempting content detection.\",\n download_path.display(),\n detected_extension\n );\n match infer::get_from_path(download_path) {\n Ok(Some(kind)) => {\n detected_extension = kind.extension().to_string();\n debug!(\"Detected file type via content: {}\", detected_extension);\n }\n Ok(None) => {\n error!(\n \"Could not determine file type from content for: {}\",\n download_path.display()\n );\n return Err(SpsError::Generic(format!(\n \"Could not determine file type for download: {}\",\n download_path.display()\n )));\n }\n Err(e) => {\n error!(\n \"Error reading file for type detection {}: {}\",\n download_path.display(),\n e\n );\n return Err(SpsError::Io(std::sync::Arc::new(e)));\n }\n }\n } else {\n debug!(\n \"Using file extension for type detection: {}\",\n detected_extension\n );\n }\n if detected_extension == \"pkg\" || detected_extension == \"mpkg\" {\n debug!(\"Detected PKG installer, running directly\");\n match artifacts::pkg::install_pkg_from_path(\n cask,\n download_path,\n &actual_cask_room_version_path, // PKG manifest items go into the actual cask_room\n config,\n ) {\n Ok(installed_artifacts) => {\n debug!(\"Writing PKG install manifest\");\n write_cask_manifest(cask, &actual_cask_room_version_path, installed_artifacts)?;\n debug!(\"Successfully installed PKG cask: {}\", cask.token);\n return Ok(());\n }\n Err(e) => {\n debug!(\"Failed to install PKG: {}\", e);\n // Clean up cask_room on error\n let _ = fs::remove_dir_all(&actual_cask_room_version_path);\n return Err(e);\n }\n }\n }\n let stage_dir = TempDir::new().map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed to create staging directory: {e}\"),\n )))\n })?;\n let stage_path = stage_dir.path();\n debug!(\"Created staging directory: {}\", stage_path.display());\n // Determine expected extension (this might need refinement)\n // Option 1: Parse from URL\n let expected_ext_from_url = download_path\n .extension()\n .and_then(|e| e.to_str())\n .unwrap_or(\"\");\n // Option 2: A new field in Cask JSON definition (preferred)\n // let expected_ext = cask.expected_extension.as_deref().unwrap_or(expected_ext_from_url);\n let expected_ext = expected_ext_from_url; // Use URL for now\n\n if !expected_ext.is_empty()\n && crate::build::compile::RECOGNISED_SINGLE_FILE_EXTENSIONS.contains(&expected_ext)\n {\n // Check if it's an archive/installer type we handle\n tracing::debug!(\n \"Verifying content type for {} against expected extension '{}'\",\n download_path.display(),\n expected_ext\n );\n if let Err(e) = sps_net::validation::verify_content_type(download_path, expected_ext) {\n tracing::error!(\"Content type verification failed: {}\", e);\n // Attempt cleanup?\n let _ = fs::remove_dir_all(&actual_cask_room_version_path);\n return Err(e);\n }\n } else {\n tracing::debug!(\n \"Skipping content type verification for {} (unknown/no expected extension: '{}')\",\n download_path.display(),\n expected_ext\n );\n }\n match detected_extension.as_str() {\n \"dmg\" => {\n debug!(\n \"Extracting DMG {} to stage {}...\",\n download_path.display(),\n stage_path.display()\n );\n dmg::extract_dmg_to_stage(download_path, stage_path)?;\n debug!(\"Successfully extracted DMG to staging area.\");\n }\n \"zip\" => {\n debug!(\n \"Extracting ZIP {} to stage {}...\",\n download_path.display(),\n stage_path.display()\n );\n extract::extract_archive(download_path, stage_path, 0, \"zip\")?;\n debug!(\"Successfully extracted ZIP to staging area.\");\n }\n \"gz\" | \"bz2\" | \"xz\" | \"tar\" => {\n let archive_type_for_extraction = detected_extension.as_str();\n debug!(\n \"Extracting TAR archive ({}) {} to stage {}...\",\n archive_type_for_extraction,\n download_path.display(),\n stage_path.display()\n );\n extract::extract_archive(download_path, stage_path, 0, archive_type_for_extraction)?;\n debug!(\"Successfully extracted TAR archive to staging area.\");\n }\n _ => {\n error!(\n \"Unsupported container/installer type '{}' for staged installation derived from {}\",\n detected_extension,\n download_path.display()\n );\n return Err(SpsError::Generic(format!(\n \"Unsupported file type for staged installation: {detected_extension}\"\n )));\n }\n }\n let mut all_installed_artifacts: Vec = Vec::new();\n let mut artifact_install_errors = Vec::new();\n if let Some(artifacts_def) = &cask.artifacts {\n debug!(\n \"Processing {} declared artifacts from staging area...\",\n artifacts_def.len()\n );\n for artifact_value in artifacts_def.iter() {\n if let Some(artifact_obj) = artifact_value.as_object() {\n if let Some((key, value)) = artifact_obj.iter().next() {\n debug!(\"Processing artifact type: {}\", key);\n let result: Result> = match key.as_str() {\n \"app\" => {\n let mut app_artifacts = vec![];\n if let Some(app_names) = value.as_array() {\n for app_name_val in app_names {\n if let Some(app_name) = app_name_val.as_str() {\n let staged_app_path = stage_path.join(app_name);\n debug!(\n \"Attempting to install app artifact: {}\",\n staged_app_path.display()\n );\n match artifacts::app::install_app_from_staged(\n cask,\n &staged_app_path,\n &actual_cask_room_version_path,\n config,\n job_action, // Pass job_action for upgrade logic\n ) {\n Ok(mut artifacts) => {\n app_artifacts.append(&mut artifacts)\n }\n Err(e) => {\n return Err(e);\n }\n }\n } else {\n debug!(\n \"Non-string value found in 'app' artifact array: {:?}\",\n app_name_val\n );\n }\n }\n } else {\n debug!(\"'app' artifact value is not an array: {:?}\", value);\n }\n Ok(app_artifacts)\n }\n \"pkg\" => {\n let mut installed_pkgs = vec![];\n if let Some(pkg_names) = value.as_array() {\n for pkg_val in pkg_names {\n if let Some(pkg_name) = pkg_val.as_str() {\n let staged_pkg_path = stage_path.join(pkg_name);\n debug!(\n \"Attempting to install staged pkg artifact: {}\",\n staged_pkg_path.display()\n );\n match artifacts::pkg::install_pkg_from_path(\n cask,\n &staged_pkg_path,\n &actual_cask_room_version_path, /* Pass actual\n * cask_room path */\n config,\n ) {\n Ok(mut artifacts) => {\n installed_pkgs.append(&mut artifacts)\n }\n Err(e) => {\n return Err(e);\n }\n }\n } else {\n debug!(\n \"Non-string value found in 'pkg' artifact array: {:?}\",\n pkg_val\n );\n }\n }\n } else {\n debug!(\"'pkg' artifact value is not an array: {:?}\", value);\n }\n Ok(installed_pkgs)\n }\n _ => {\n debug!(\"Artifact type '{}' not supported yet — skipping.\", key);\n Ok(vec![])\n }\n };\n match result {\n Ok(installed) => {\n if !installed.is_empty() {\n debug!(\n \"Successfully processed artifact '{}', added {} items.\",\n key,\n installed.len()\n );\n all_installed_artifacts.extend(installed);\n } else {\n debug!(\n \"Artifact handler for '{}' completed successfully but returned no artifacts.\",\n key\n );\n }\n }\n Err(e) => {\n error!(\"Error processing artifact '{}': {}\", key, e);\n artifact_install_errors.push(e);\n }\n }\n } else {\n debug!(\"Empty artifact object found: {:?}\", artifact_obj);\n }\n } else {\n debug!(\n \"Unexpected non-object artifact found in list: {:?}\",\n artifact_value\n );\n }\n }\n } else {\n error!(\n \"Cask {} definition is missing the required 'artifacts' array. Cannot determine what to install.\",\n cask.token\n );\n // Clean up the created actual_caskroom_version_path if no artifacts are defined\n let _ = fs::remove_dir_all(&actual_cask_room_version_path);\n return Err(SpsError::InstallError(format!(\n \"Cask '{}' has no artifacts defined.\",\n cask.token\n )));\n }\n if !artifact_install_errors.is_empty() {\n error!(\n \"Encountered {} errors installing artifacts for cask '{}'. Installation incomplete.\",\n artifact_install_errors.len(),\n cask.token\n );\n let _ = fs::remove_dir_all(&actual_cask_room_version_path); // Clean up actual cask_room on error\n return Err(artifact_install_errors.remove(0));\n }\n let actual_install_count = all_installed_artifacts\n .iter()\n .filter(|a| {\n !matches!(\n a,\n InstalledArtifact::PkgUtilReceipt { .. } | InstalledArtifact::Launchd { .. }\n )\n })\n .count();\n if actual_install_count == 0 {\n debug!(\n \"No installable artifacts (like app, pkg, binary, etc.) were processed for cask '{}' from the staged content. Check cask definition.\",\n cask.token\n );\n write_cask_manifest(\n cask,\n &actual_cask_room_version_path,\n all_installed_artifacts,\n )?;\n } else {\n debug!(\"Writing cask installation manifest\");\n write_cask_manifest(\n cask,\n &actual_cask_room_version_path,\n all_installed_artifacts,\n )?;\n }\n debug!(\"Successfully installed cask: {}\", cask.token);\n Ok(())\n}\n\n#[deprecated(note = \"Use write_cask_manifest with detailed InstalledArtifact enum instead\")]\npub fn write_receipt(\n cask: &Cask,\n cask_version_install_path: &Path,\n artifacts: Vec,\n) -> Result<()> {\n let receipt_path = cask_version_install_path.join(\"INSTALL_RECEIPT.json\");\n debug!(\"Writing legacy cask receipt: {}\", receipt_path.display());\n let timestamp = SystemTime::now()\n .duration_since(UNIX_EPOCH)\n .map_err(|e: SystemTimeError| SpsError::Generic(format!(\"System time error: {e}\")))?\n .as_secs();\n let receipt_data = json!({\n \"token\": cask.token,\n \"name\": cask.name.as_ref().and_then(|n| n.first()).cloned(),\n \"version\": cask.version.as_ref().unwrap_or(&\"latest\".to_string()),\n \"installed_at\": timestamp,\n \"artifacts_installed\": artifacts\n });\n if let Some(parent) = receipt_path.parent() {\n fs::create_dir_all(parent).map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n }\n let mut file =\n fs::File::create(&receipt_path).map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n serde_json::to_writer_pretty(&mut file, &receipt_data)\n .map_err(|e| SpsError::Json(std::sync::Arc::new(e)))?;\n debug!(\n \"Successfully wrote legacy receipt with {} artifact entries.\",\n artifacts.len()\n );\n Ok(())\n}\n\npub fn write_cask_manifest(\n cask: &Cask,\n cask_version_install_path: &Path,\n artifacts: Vec,\n) -> Result<()> {\n let manifest_path = cask_version_install_path.join(\"CASK_INSTALL_MANIFEST.json\");\n debug!(\"Writing cask manifest: {}\", manifest_path.display());\n let timestamp = SystemTime::now()\n .duration_since(UNIX_EPOCH)\n .map_err(|e: SystemTimeError| SpsError::Generic(format!(\"System time error: {e}\")))?\n .as_secs();\n\n // Determine primary app file name from artifacts\n let primary_app_file_name = artifacts.iter().find_map(|artifact| {\n if let InstalledArtifact::AppBundle { path } = artifact {\n path.file_name()\n .map(|name| name.to_string_lossy().to_string())\n } else {\n None\n }\n });\n\n // Always set is_installed=true when writing manifest (install or reinstall)\n // Try to determine cask_store_path from artifacts (AppBundle or CaskroomLink)\n let cask_store_path = artifacts.iter().find_map(|artifact| match artifact {\n InstalledArtifact::AppBundle { path } => Some(path.to_string_lossy().to_string()),\n InstalledArtifact::CaskroomLink { target_path, .. } => {\n Some(target_path.to_string_lossy().to_string())\n }\n _ => None,\n });\n\n let manifest_data = CaskInstallManifest {\n manifest_format_version: \"1.0\".to_string(),\n token: cask.token.clone(),\n version: cask.version.clone().unwrap_or_else(|| \"latest\".to_string()),\n installed_at: timestamp,\n artifacts,\n primary_app_file_name,\n is_installed: true,\n cask_store_path,\n };\n if let Some(parent) = manifest_path.parent() {\n fs::create_dir_all(parent).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed create parent dir {}: {}\", parent.display(), e),\n )))\n })?;\n }\n let file = fs::File::create(&manifest_path).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed create manifest {}: {}\", manifest_path.display(), e),\n )))\n })?;\n let writer = std::io::BufWriter::new(file);\n serde_json::to_writer_pretty(writer, &manifest_data).map_err(|e| {\n error!(\n \"Failed to serialize cask manifest JSON for {}: {}\",\n cask.token, e\n );\n SpsError::Json(std::sync::Arc::new(e))\n })?;\n debug!(\n \"Successfully wrote cask manifest with {} artifact entries.\",\n manifest_data.artifacts.len()\n );\n Ok(())\n}\n\n/// Recursively cleans up empty parent directories in the private cask store.\n/// Starts from the given path and walks up, removing empty directories until a non-empty or root is\n/// found.\npub fn cleanup_empty_parent_dirs_in_private_store(start_path: &Path, stop_at: &Path) {\n let mut current = start_path.parent().unwrap_or(start_path).to_path_buf(); // Start from parent\n while current != *stop_at {\n if let Ok(read_dir) = fs::read_dir(¤t) {\n if read_dir.count() == 0 {\n match fs::remove_dir(¤t) {\n Ok(_) => {\n debug!(\"Removed empty directory: {}\", current.display());\n }\n Err(e) => {\n debug!(\"Failed to remove directory {}: {}\", current.display(), e);\n break;\n }\n }\n } else {\n break;\n }\n } else {\n break;\n }\n if let Some(parent) = current.parent() {\n current = parent.to_path_buf();\n } else {\n break;\n }\n }\n}\n"], ["/sps/sps-core/src/check/update.rs", "// sps-core/src/check/update.rs\n\nuse std::collections::HashMap;\nuse std::sync::Arc;\n\n// Imports from sps-common\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::formulary::Formulary; // Using the shared Formulary\nuse sps_common::model::version::Version as PkgVersion;\nuse sps_common::model::Cask; // Using the Cask and Formula from sps-common\n// Use the Cask and Formula structs from sps_common::model\n// Ensure InstallTargetIdentifier is correctly pathed if it's also in sps_common::model\nuse sps_common::model::InstallTargetIdentifier;\n// Imports from sps-net\nuse sps_net::api;\n\n// Imports from sps-core\nuse crate::check::installed::{InstalledPackageInfo, PackageType};\n\n#[derive(Debug, Clone)]\npub struct UpdateInfo {\n pub name: String,\n pub installed_version: String,\n pub available_version: String,\n pub pkg_type: PackageType,\n pub target_definition: InstallTargetIdentifier,\n}\n\n/// Ensures that the raw JSON data for formulas and casks exists in the main disk cache,\n/// fetching from the API if necessary.\nasync fn ensure_api_data_cached(cache: &Cache) -> Result<()> {\n let formula_check = cache.load_raw(\"formula.json\");\n let cask_check = cache.load_raw(\"cask.json\");\n\n // Determine if fetches are needed\n let mut fetch_formulas = false;\n if formula_check.is_err() {\n tracing::debug!(\"Local formula.json cache missing or unreadable. Scheduling fetch.\");\n fetch_formulas = true;\n }\n\n let mut fetch_casks = false;\n if cask_check.is_err() {\n tracing::debug!(\"Local cask.json cache missing or unreadable. Scheduling fetch.\");\n fetch_casks = true;\n }\n\n // Perform fetches concurrently if needed\n match (fetch_formulas, fetch_casks) {\n (true, true) => {\n tracing::debug!(\"Populating missing formula.json and cask.json from API...\");\n let (formula_res, cask_res) = tokio::join!(\n async {\n let data = api::fetch_all_formulas().await?;\n cache.store_raw(\"formula.json\", &data)?;\n Ok::<(), SpsError>(())\n },\n async {\n let data = api::fetch_all_casks().await?;\n cache.store_raw(\"cask.json\", &data)?;\n Ok::<(), SpsError>(())\n }\n );\n formula_res?;\n cask_res?;\n tracing::debug!(\"Formula.json and cask.json populated from API.\");\n }\n (true, false) => {\n tracing::debug!(\"Populating missing formula.json from API...\");\n let data = api::fetch_all_formulas().await?;\n cache.store_raw(\"formula.json\", &data)?;\n tracing::debug!(\"Formula.json populated from API.\");\n }\n (false, true) => {\n tracing::debug!(\"Populating missing cask.json from API...\");\n let data = api::fetch_all_casks().await?;\n cache.store_raw(\"cask.json\", &data)?;\n tracing::debug!(\"Cask.json populated from API.\");\n }\n (false, false) => {\n tracing::debug!(\"Local formula.json and cask.json caches are present.\");\n }\n }\n Ok(())\n}\n\npub async fn check_for_updates(\n installed_packages: &[InstalledPackageInfo],\n cache: &Cache,\n config: &Config,\n) -> Result> {\n // 1. Ensure the underlying JSON files in the main cache are populated.\n ensure_api_data_cached(cache)\n .await\n .map_err(|e| {\n tracing::error!(\n \"Failed to ensure API data is cached for update check: {}\",\n e\n );\n // Decide if this is a fatal error for update checking or if we can proceed with\n // potentially stale/missing data. For now, let's make it non-fatal but log\n // an error, as Formulary/cask parsing might still work with older cache.\n SpsError::Generic(format!(\n \"Failed to ensure API data in cache, update check might be unreliable: {e}\"\n ))\n })\n .ok(); // Continue even if this pre-fetch step fails, rely on Formulary/cask loading to handle actual\n // errors.\n\n // 2. Instantiate Formulary. It uses the `cache` (from sps-common) to load `formula.json`.\n let formulary = Formulary::new(config.clone());\n\n // 3. For Casks: Load the entire `cask.json` from cache and parse it robustly into Vec.\n // This uses the Cask definition from sps_common::model::cask.\n let casks_map: HashMap> = match cache.load_raw(\"cask.json\") {\n Ok(json_str) => {\n // Parse directly into Vec using the definition from sps-common::model::cask\n match serde_json::from_str::>(&json_str) {\n Ok(casks) => casks\n .into_iter()\n .map(|c| (c.token.clone(), Arc::new(c)))\n .collect(),\n Err(e) => {\n tracing::warn!(\n \"Failed to parse full cask.json string into Vec (from sps-common): {}. Cask update checks may be incomplete.\",\n e\n );\n HashMap::new()\n }\n }\n }\n Err(e) => {\n tracing::warn!(\n \"Failed to load cask.json string from cache: {}. Cask update checks will be based on no remote data.\", e\n );\n HashMap::new()\n }\n };\n\n tracing::debug!(\n \"[UpdateCheck] Starting update check for {} packages\",\n installed_packages.len()\n );\n let mut updates_available = Vec::new();\n\n for installed in installed_packages {\n tracing::debug!(\n \"[UpdateCheck] Checking package '{}' version '{}'\",\n installed.name,\n installed.version\n );\n match installed.pkg_type {\n PackageType::Formula => {\n match formulary.load_formula(&installed.name) {\n // Uses sps-common::formulary::Formulary\n Ok(latest_formula_obj) => {\n // Returns sps_common::model::formula::Formula\n let latest_formula_arc = Arc::new(latest_formula_obj);\n\n let latest_version_str = latest_formula_arc.version_str_full();\n tracing::debug!(\n \"[UpdateCheck] Formula '{}': installed='{}', latest='{}'\",\n installed.name,\n installed.version,\n latest_version_str\n );\n\n let installed_v_res = PkgVersion::parse(&installed.version);\n let latest_v_res = PkgVersion::parse(&latest_version_str);\n let installed_revision = installed\n .version\n .split('_')\n .nth(1)\n .and_then(|s| s.parse::().ok())\n .unwrap_or(0);\n\n let needs_update = match (installed_v_res, latest_v_res) {\n (Ok(iv), Ok(lv)) => {\n let version_newer = lv > iv;\n let revision_newer =\n lv == iv && latest_formula_arc.revision > installed_revision;\n tracing::debug!(\"[UpdateCheck] Formula '{}': version_newer={}, revision_newer={} (installed_rev={}, latest_rev={})\", \n installed.name, version_newer, revision_newer, installed_revision, latest_formula_arc.revision);\n version_newer || revision_newer\n }\n _ => {\n let different = installed.version != latest_version_str;\n tracing::debug!(\"[UpdateCheck] Formula '{}': fallback string comparison, different={}\", \n installed.name, different);\n different\n }\n };\n\n tracing::debug!(\n \"[UpdateCheck] Formula '{}': needs_update={}\",\n installed.name,\n needs_update\n );\n if needs_update {\n updates_available.push(UpdateInfo {\n name: installed.name.clone(),\n installed_version: installed.version.clone(),\n available_version: latest_version_str,\n pkg_type: PackageType::Formula,\n target_definition: InstallTargetIdentifier::Formula(\n // From sps-common\n latest_formula_arc.clone(),\n ),\n });\n }\n }\n Err(_e) => {\n tracing::debug!(\n \"Installed formula '{}' not found via Formulary. It might have been removed from the remote. Source error: {}\",\n installed.name, _e\n );\n }\n }\n }\n PackageType::Cask => {\n if let Some(latest_cask_arc) = casks_map.get(&installed.name) {\n // latest_cask_arc is Arc\n if let Some(available_version) = latest_cask_arc.version.as_ref() {\n if &installed.version != available_version {\n updates_available.push(UpdateInfo {\n name: installed.name.clone(),\n installed_version: installed.version.clone(),\n available_version: available_version.clone(),\n pkg_type: PackageType::Cask,\n target_definition: InstallTargetIdentifier::Cask(\n // From sps-common\n latest_cask_arc.clone(),\n ),\n });\n }\n } else {\n tracing::warn!(\n \"Latest cask definition for '{}' from casks_map has no version string.\",\n installed.name\n );\n }\n } else {\n tracing::warn!(\n \"Installed cask '{}' not found in the fully parsed casks_map.\",\n installed.name\n );\n }\n }\n }\n }\n\n tracing::debug!(\n \"[UpdateCheck] Update check complete: {} updates available out of {} packages checked\",\n updates_available.len(),\n installed_packages.len()\n );\n tracing::debug!(\n \"[UpdateCheck] Updates available for: {:?}\",\n updates_available\n .iter()\n .map(|u| &u.name)\n .collect::>()\n );\n\n Ok(updates_available)\n}\n"], ["/sps/sps-core/src/install/bottle/exec.rs", "use std::collections::{HashMap, HashSet};\nuse std::fs::{self, File};\nuse std::io::{Read, Write};\nuse std::os::unix::fs::{symlink, PermissionsExt};\nuse std::path::{Path, PathBuf};\nuse std::process::{Command as StdCommand, Stdio};\nuse std::sync::Arc;\n\nuse reqwest::Client;\nuse semver;\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::formula::{BottleFileSpec, Formula, FormulaDependencies};\nuse sps_net::http::ProgressCallback;\nuse sps_net::oci;\nuse sps_net::validation::verify_checksum;\nuse tempfile::NamedTempFile;\nuse tracing::{debug, error, warn};\nuse walkdir::WalkDir;\n\nuse super::macho;\nuse crate::install::bottle::get_current_platform;\nuse crate::install::extract::extract_archive;\n\npub async fn download_bottle(\n formula: &Formula,\n config: &Config,\n client: &Client,\n) -> Result {\n download_bottle_with_progress(formula, config, client, None).await\n}\n\npub async fn download_bottle_with_progress(\n formula: &Formula,\n config: &Config,\n client: &Client,\n progress_callback: Option,\n) -> Result {\n download_bottle_with_progress_and_cache_info(formula, config, client, progress_callback)\n .await\n .map(|(path, _)| path)\n}\n\npub async fn download_bottle_with_progress_and_cache_info(\n formula: &Formula,\n config: &Config,\n client: &Client,\n progress_callback: Option,\n) -> Result<(PathBuf, bool)> {\n debug!(\"Attempting to download bottle for {}\", formula.name);\n let (platform_tag, bottle_file_spec) = get_bottle_for_platform(formula)?;\n debug!(\n \"Selected bottle spec for platform '{}': URL={}, SHA256={}\",\n platform_tag, bottle_file_spec.url, bottle_file_spec.sha256\n );\n if bottle_file_spec.url.is_empty() {\n return Err(SpsError::DownloadError(\n formula.name.clone(),\n \"\".to_string(),\n \"Bottle spec has an empty URL.\".to_string(),\n ));\n }\n let standard_version_str = formula.version_str_full();\n let filename = format!(\n \"{}-{}.{}.bottle.tar.gz\",\n formula.name, standard_version_str, platform_tag\n );\n let cache_dir = config.cache_dir().join(\"bottles\");\n fs::create_dir_all(&cache_dir).map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n let bottle_cache_path = cache_dir.join(&filename);\n if bottle_cache_path.is_file() {\n debug!(\"Bottle found in cache: {}\", bottle_cache_path.display());\n if !bottle_file_spec.sha256.is_empty() {\n match verify_checksum(&bottle_cache_path, &bottle_file_spec.sha256) {\n Ok(_) => {\n debug!(\"Using valid cached bottle: {}\", bottle_cache_path.display());\n return Ok((bottle_cache_path, true));\n }\n Err(e) => {\n debug!(\n \"Cached bottle checksum mismatch ({}): {}. Redownloading.\",\n bottle_cache_path.display(),\n e\n );\n let _ = fs::remove_file(&bottle_cache_path);\n }\n }\n } else {\n warn!(\n \"Using cached bottle without checksum verification (checksum not specified): {}\",\n bottle_cache_path.display()\n );\n return Ok((bottle_cache_path, true));\n }\n } else {\n debug!(\"Bottle not found in cache.\");\n }\n let bottle_url_str = &bottle_file_spec.url;\n let registry_domain = config\n .artifact_domain\n .as_deref()\n .unwrap_or(oci::DEFAULT_GHCR_DOMAIN);\n let is_oci_blob_url = (bottle_url_str.contains(\"://ghcr.io/\")\n || bottle_url_str.contains(registry_domain))\n && bottle_url_str.contains(\"/blobs/sha256:\");\n debug!(\n \"Checking URL type: '{}'. Is OCI Blob URL? {}\",\n bottle_url_str, is_oci_blob_url\n );\n if is_oci_blob_url {\n let expected_digest = bottle_url_str.split(\"/blobs/sha256:\").nth(1).unwrap_or(\"\");\n if expected_digest.is_empty() {\n warn!(\n \"Could not extract expected SHA256 digest from OCI URL: {}\",\n bottle_url_str\n );\n }\n debug!(\n \"Detected OCI blob URL, initiating direct blob download: {} (Digest: {})\",\n bottle_url_str, expected_digest\n );\n match oci::download_oci_blob_with_progress(\n bottle_url_str,\n &bottle_cache_path,\n config,\n client,\n expected_digest,\n progress_callback.clone(),\n )\n .await\n {\n Ok(_) => {\n debug!(\n \"Successfully downloaded OCI blob to {}\",\n bottle_cache_path.display()\n );\n }\n Err(e) => {\n error!(\"Failed to download OCI blob from {}: {}\", bottle_url_str, e);\n let _ = fs::remove_file(&bottle_cache_path);\n return Err(SpsError::DownloadError(\n formula.name.clone(),\n bottle_url_str.to_string(),\n format!(\"Failed to download OCI blob: {e}\"),\n ));\n }\n }\n } else {\n debug!(\n \"Detected standard HTTPS URL, using direct download for: {}\",\n bottle_url_str\n );\n match sps_net::http::fetch_formula_source_or_bottle_with_progress(\n formula.name(),\n bottle_url_str,\n &bottle_file_spec.sha256,\n &[],\n config,\n progress_callback,\n )\n .await\n {\n Ok(downloaded_path) => {\n if downloaded_path != bottle_cache_path {\n debug!(\n \"fetch_formula_source_or_bottle returned path {}. Expected: {}. Assuming correct.\",\n downloaded_path.display(),\n bottle_cache_path.display()\n );\n if !bottle_cache_path.exists() {\n error!(\n \"Downloaded path {} exists, but expected final cache path {} does not!\",\n downloaded_path.display(),\n bottle_cache_path.display()\n );\n return Err(SpsError::Generic(format!(\n \"Download path mismatch and final file missing: {}\",\n bottle_cache_path.display()\n )));\n }\n }\n debug!(\n \"Successfully downloaded directly to {}\",\n bottle_cache_path.display()\n );\n }\n Err(e) => {\n error!(\"Failed to download directly from {}: {}\", bottle_url_str, e);\n return Err(e);\n }\n }\n }\n if !bottle_cache_path.exists() {\n error!(\n \"Bottle download process completed, but the final file {} does not exist.\",\n bottle_cache_path.display()\n );\n return Err(SpsError::Generic(format!(\n \"Bottle file missing after download attempt: {}\",\n bottle_cache_path.display()\n )));\n }\n debug!(\n \"Bottle download successful: {}\",\n bottle_cache_path.display()\n );\n Ok((bottle_cache_path, false))\n}\n\npub fn get_bottle_for_platform(formula: &Formula) -> Result<(String, &BottleFileSpec)> {\n let stable_spec = formula.bottle.stable.as_ref().ok_or_else(|| {\n SpsError::Generic(format!(\n \"Formula '{}' has no stable bottle specification.\",\n formula.name\n ))\n })?;\n if stable_spec.files.is_empty() {\n return Err(SpsError::Generic(format!(\n \"Formula '{}' has no bottle files listed in stable spec.\",\n formula.name\n )));\n }\n let current_platform = get_current_platform();\n if current_platform == \"unknown\" || current_platform.contains(\"unknown\") {\n debug!(\n \"Could not reliably determine current platform ('{}'). Bottle selection might be incorrect.\",\n current_platform\n );\n }\n debug!(\n \"Determining bottle for current platform: {}\",\n current_platform\n );\n debug!(\n \"Available bottle platforms in formula spec: {:?}\",\n stable_spec.files.keys().cloned().collect::>()\n );\n if let Some(spec) = stable_spec.files.get(¤t_platform) {\n debug!(\n \"Found exact bottle match for platform: {}\",\n current_platform\n );\n return Ok((current_platform.clone(), spec));\n }\n debug!(\"No exact match found for {}\", current_platform);\n const ARM_MACOS_VERSIONS: &[&str] = &[\"sequoia\", \"sonoma\", \"ventura\", \"monterey\", \"big_sur\"];\n const INTEL_MACOS_VERSIONS: &[&str] = &[\n \"sequoia\", \"sonoma\", \"ventura\", \"monterey\", \"big_sur\", \"catalina\", \"mojave\",\n ];\n if cfg!(target_os = \"macos\") {\n if let Some(current_os_name) = current_platform\n .strip_prefix(\"arm64_\")\n .or(Some(current_platform.as_str()))\n {\n let version_list = if current_platform.starts_with(\"arm64_\") {\n ARM_MACOS_VERSIONS\n } else {\n INTEL_MACOS_VERSIONS\n };\n if let Some(current_os_index) = version_list.iter().position(|&v| v == current_os_name)\n {\n for target_os_name in version_list.iter().skip(current_os_index) {\n let target_tag = if current_platform.starts_with(\"arm64_\") {\n format!(\"arm64_{target_os_name}\")\n } else {\n target_os_name.to_string()\n };\n if let Some(spec) = stable_spec.files.get(&target_tag) {\n debug!(\n \"No bottle found for exact platform '{}'. Using compatible older bottle '{}'.\",\n current_platform, target_tag\n );\n return Ok((target_tag, spec));\n }\n }\n debug!(\n \"Checked compatible older macOS versions ({:?}), no suitable bottle found.\",\n &version_list[current_os_index..]\n );\n } else {\n debug!(\n \"Current OS '{}' not found in known macOS version list.\",\n current_os_name\n );\n }\n } else {\n debug!(\n \"Could not extract OS name from platform tag '{}'\",\n current_platform\n );\n }\n }\n if current_platform.starts_with(\"arm64_\") {\n if let Some(spec) = stable_spec.files.get(\"arm64_big_sur\") {\n debug!(\n \"No specific OS bottle found for {}. Falling back to 'arm64_big_sur' bottle.\",\n current_platform\n );\n return Ok((\"arm64_big_sur\".to_string(), spec));\n }\n debug!(\"No 'arm64_big_sur' fallback bottle tag found.\");\n } else if cfg!(target_os = \"macos\") {\n if let Some(spec) = stable_spec.files.get(\"big_sur\") {\n debug!(\n \"No specific OS bottle found for {}. Falling back to 'big_sur' bottle.\",\n current_platform\n );\n return Ok((\"big_sur\".to_string(), spec));\n }\n debug!(\"No 'big_sur' fallback bottle tag found.\");\n }\n if let Some(spec) = stable_spec.files.get(\"all\") {\n debug!(\n \"No platform-specific or OS-specific bottle found for {}. Using 'all' platform bottle.\",\n current_platform\n );\n return Ok((\"all\".to_string(), spec));\n }\n debug!(\"No 'all' platform bottle found.\");\n Err(SpsError::DownloadError(\n formula.name.clone(),\n \"\".to_string(),\n format!(\n \"No compatible bottle found for platform '{}'. Available: {:?}\",\n current_platform,\n stable_spec.files.keys().collect::>()\n ),\n ))\n}\n\npub fn install_bottle(bottle_path: &Path, formula: &Formula, config: &Config) -> Result {\n let install_dir = formula.install_prefix(config.cellar_dir().as_path())?;\n if install_dir.exists() {\n debug!(\n \"Removing existing keg directory before installing: {}\",\n install_dir.display()\n );\n fs::remove_dir_all(&install_dir).map_err(|e| {\n SpsError::InstallError(format!(\n \"Failed to remove existing keg {}: {}\",\n install_dir.display(),\n e\n ))\n })?;\n }\n if let Some(parent_dir) = install_dir.parent() {\n fs::create_dir_all(parent_dir).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\n \"Failed to create parent dir {}: {}\",\n parent_dir.display(),\n e\n ),\n )))\n })?;\n } else {\n return Err(SpsError::InstallError(format!(\n \"Could not determine parent directory for install path: {}\",\n install_dir.display()\n )));\n }\n fs::create_dir_all(&install_dir).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed to create keg dir {}: {}\", install_dir.display(), e),\n )))\n })?;\n let strip_components = 2;\n debug!(\n \"Extracting bottle archive {} to {} with strip_components={}\",\n bottle_path.display(),\n install_dir.display(),\n strip_components\n );\n extract_archive(bottle_path, &install_dir, strip_components, \"gz\")?;\n debug!(\n \"Ensuring write permissions for extracted files in {}\",\n install_dir.display()\n );\n ensure_write_permissions(&install_dir)?;\n debug!(\"Performing bottle relocation in {}\", install_dir.display());\n perform_bottle_relocation(formula, &install_dir, config)?;\n ensure_llvm_symlinks(&install_dir, formula, config)?;\n crate::install::bottle::write_receipt(formula, &install_dir, \"bottle\")?;\n debug!(\n \"Bottle installation complete for {} at {}\",\n formula.name(),\n install_dir.display()\n );\n Ok(install_dir)\n}\n\nfn ensure_write_permissions(path: &Path) -> Result<()> {\n if !path.exists() {\n debug!(\n \"Path {} does not exist, cannot ensure write permissions.\",\n path.display()\n );\n return Ok(());\n }\n for entry_result in WalkDir::new(path).into_iter().filter_map(|e| e.ok()) {\n let entry_path = entry_result.path();\n if entry_path == path && entry_result.depth() == 0 {\n continue;\n }\n match fs::metadata(entry_path) {\n Ok(metadata) => {\n let mut perms = metadata.permissions();\n let _is_readonly = perms.readonly();\n #[cfg(unix)]\n {\n let current_mode = perms.mode();\n let new_mode = current_mode | 0o200;\n if new_mode != current_mode {\n perms.set_mode(new_mode);\n let _ = fs::set_permissions(entry_path, perms);\n }\n }\n #[cfg(not(unix))]\n {\n if _is_readonly {\n perms.set_readonly(false);\n let _ = fs::set_permissions(entry_path, perms);\n }\n }\n }\n Err(_e) => {}\n }\n }\n Ok(())\n}\n\nfn perform_bottle_relocation(formula: &Formula, install_dir: &Path, config: &Config) -> Result<()> {\n let mut repl: HashMap = HashMap::new();\n repl.insert(\n \"@@HOMEBREW_CELLAR@@\".into(),\n config.cellar_dir().to_string_lossy().into(),\n );\n repl.insert(\n \"@@HOMEBREW_PREFIX@@\".into(),\n config.sps_root().to_string_lossy().into(),\n );\n let _prefix_path_str = config.sps_root().to_string_lossy();\n let library_path_str = config\n .sps_root()\n .join(\"Library\")\n .to_string_lossy()\n .to_string(); // Assuming Library is under sps_root for this placeholder\n // HOMEBREW_REPOSITORY usually points to the Homebrew/brew git repo, not relevant for sps in\n // this context. If needed for a specific formula, it should point to\n // /opt/sps or similar.\n repl.insert(\n \"@@HOMEBREW_REPOSITORY@@\".into(),\n config.sps_root().to_string_lossy().into(),\n );\n repl.insert(\"@@HOMEBREW_LIBRARY@@\".into(), library_path_str.to_string());\n\n let formula_opt_path = config.formula_opt_path(formula.name());\n let formula_opt_str = formula_opt_path.to_string_lossy();\n let install_dir_str = install_dir.to_string_lossy();\n if formula_opt_str != install_dir_str {\n repl.insert(formula_opt_str.to_string(), install_dir_str.to_string());\n debug!(\n \"Adding self-opt relocation: {} -> {}\",\n formula_opt_str, install_dir_str\n );\n }\n\n if formula.name().starts_with(\"python@\") {\n let version_full = formula.version_str_full();\n let mut parts = version_full.split('.');\n if let (Some(major), Some(minor)) = (parts.next(), parts.next()) {\n let framework_version = format!(\"{major}.{minor}\");\n let framework_dir = install_dir\n .join(\"Frameworks\")\n .join(\"Python.framework\")\n .join(\"Versions\")\n .join(&framework_version);\n let python_lib = framework_dir.join(\"Python\");\n let python_bin = framework_dir\n .join(\"bin\")\n .join(format!(\"python{major}.{minor}\"));\n\n let absolute_python_lib_path_obj = install_dir\n .join(\"Frameworks\")\n .join(\"Python.framework\")\n .join(\"Versions\")\n .join(&framework_version)\n .join(\"Python\");\n let new_id_abs = absolute_python_lib_path_obj.to_str().ok_or_else(|| {\n SpsError::InstallError(format!(\n \"Failed to convert absolute Python library path to string: {}\",\n absolute_python_lib_path_obj.display()\n ))\n })?;\n\n debug!(\n \"Setting absolute ID for {}: {}\",\n python_lib.display(),\n new_id_abs\n );\n let status_id = StdCommand::new(\"install_name_tool\")\n .args([\"-id\", new_id_abs, python_lib.to_str().unwrap()])\n .stdout(Stdio::null())\n .stderr(Stdio::null())\n .status()\n .map_err(|e| SpsError::Io(Arc::new(e)))?;\n if !status_id.success() {\n error!(\"install_name_tool -id failed for {}\", python_lib.display());\n return Err(SpsError::InstallError(format!(\n \"Failed to set absolute id on Python dynamic library: {}\",\n python_lib.display()\n )));\n }\n\n debug!(\"Skipping -add_rpath as absolute paths are used for Python linkage.\");\n\n let old_load_placeholder = format!(\n \"@@HOMEBREW_CELLAR@@/{}/{}/Frameworks/Python.framework/Versions/{}/Python\",\n formula.name(),\n version_full,\n framework_version\n );\n let old_load_resource_placeholder = format!(\n \"@@HOMEBREW_CELLAR@@/{}/{}/Frameworks/Python.framework/Versions/{}/Resources/Python.app/Contents/MacOS/Python\",\n formula.name(),\n version_full,\n framework_version\n );\n let install_dir_str_ref = install_dir.to_string_lossy();\n let abs_old_load = format!(\n \"{install_dir_str_ref}/Frameworks/Python.framework/Versions/{framework_version}/Python\"\n );\n let abs_old_load_resource = format!(\n \"{install_dir_str_ref}/Frameworks/Python.framework/Versions/{framework_version}/Resources/Python.app/Contents/MacOS/Python\"\n );\n\n let run_change = |old: &str, new: &str, target: &Path| -> Result<()> {\n if !target.exists() {\n debug!(\n \"Target {} does not exist, skipping install_name_tool -change.\",\n target.display()\n );\n return Ok(());\n }\n debug!(\n \"Running install_name_tool -change {} {} {}\",\n old,\n new,\n target.display()\n );\n let output = StdCommand::new(\"install_name_tool\")\n .args([\"-change\", old, new, target.to_str().unwrap()])\n .output()\n .map_err(|e| SpsError::Io(Arc::new(e)))?;\n\n if !output.status.success() {\n let stderr = String::from_utf8_lossy(&output.stderr);\n if !stderr.contains(\"file not found\")\n && !stderr.contains(\"no LC_LOAD_DYLIB command specifying file\")\n && !stderr.contains(\"is not a Mach-O file\")\n && !stderr.contains(\"object file format invalid\")\n && !stderr.trim().is_empty()\n {\n error!(\n \"install_name_tool -change failed unexpectedly for target {}: {}\",\n target.display(),\n stderr.trim()\n );\n } else {\n debug!(\n \"install_name_tool -change: old path '{}' likely not found or target '{}' not relevant (stderr: {}).\",\n old,\n target.display(),\n stderr.trim()\n );\n }\n }\n Ok(())\n };\n\n debug!(\"Patching main executable: {}\", python_bin.display());\n run_change(&old_load_placeholder, new_id_abs, &python_bin)?;\n run_change(&old_load_resource_placeholder, new_id_abs, &python_bin)?;\n run_change(&abs_old_load, new_id_abs, &python_bin)?;\n run_change(&abs_old_load_resource, new_id_abs, &python_bin)?;\n\n let python_app = framework_dir\n .join(\"Resources\")\n .join(\"Python.app\")\n .join(\"Contents\")\n .join(\"MacOS\")\n .join(\"Python\");\n\n if python_app.exists() {\n debug!(\n \"Explicitly patching Python.app executable: {}\",\n python_app.display()\n );\n run_change(&old_load_placeholder, new_id_abs, &python_app)?;\n run_change(&abs_old_load, new_id_abs, &python_app)?;\n run_change(&old_load_resource_placeholder, new_id_abs, &python_app)?;\n run_change(&abs_old_load_resource, new_id_abs, &python_app)?;\n } else {\n warn!(\n \"Python.app executable not found at {}, skipping explicit patch.\",\n python_app.display()\n );\n }\n\n codesign_path(&python_lib)?;\n codesign_path(&python_bin)?;\n if python_app.exists() {\n codesign_path(&python_app)?;\n } else {\n debug!(\n \"Python.app binary not found at {}, skipping codesign.\",\n python_app.display()\n );\n }\n }\n }\n\n if let Some(perl_path) = find_brewed_perl(config.sps_root()).or_else(|| {\n if cfg!(target_os = \"macos\") {\n Some(PathBuf::from(\"/usr/bin/perl\"))\n } else {\n None\n }\n }) {\n repl.insert(\n \"@@HOMEBREW_PERL@@\".into(),\n perl_path.to_string_lossy().into(),\n );\n }\n\n match formula.dependencies() {\n Ok(deps) => {\n if let Some(openjdk) = deps\n .iter()\n .find(|d| d.name.starts_with(\"openjdk\"))\n .map(|d| d.name.clone())\n {\n let openjdk_opt = config.formula_opt_path(&openjdk);\n repl.insert(\n \"@@HOMEBREW_JAVA@@\".into(),\n openjdk_opt\n .join(\"libexec/openjdk.jdk/Contents/Home\")\n .to_string_lossy()\n .into(),\n );\n }\n }\n Err(e) => {\n warn!(\n \"Could not check formula dependencies during relocation for {}: {}\",\n formula.name(),\n e\n );\n }\n }\n\n repl.insert(\"HOMEBREW_RELOCATE_RPATHS\".into(), \"1\".into());\n\n let opt_placeholder = format!(\n \"@@HOMEBREW_OPT_{}@@\",\n formula.name().to_uppercase().replace(['-', '+', '.'], \"_\")\n );\n repl.insert(\n opt_placeholder,\n config\n .formula_opt_path(formula.name())\n .to_string_lossy()\n .into(),\n );\n\n match formula.dependencies() {\n Ok(deps) => {\n let llvm_dep_name = deps\n .iter()\n .find(|d| d.name.starts_with(\"llvm\"))\n .map(|d| d.name.clone());\n if let Some(name) = llvm_dep_name {\n let llvm_opt_path = config.formula_opt_path(&name);\n let llvm_lib = llvm_opt_path.join(\"lib\");\n if llvm_lib.is_dir() {\n repl.insert(\n \"@loader_path/../lib\".into(),\n llvm_lib.to_string_lossy().into(),\n );\n repl.insert(\n format!(\n \"@@HOMEBREW_OPT_{}@@/lib\",\n name.to_uppercase().replace(['-', '+', '.'], \"_\")\n ),\n llvm_lib.to_string_lossy().into(),\n );\n }\n }\n }\n Err(e) => {\n warn!(\n \"Could not check formula dependencies during LLVM relocation for {}: {}\",\n formula.name(),\n e\n );\n }\n }\n\n tracing::debug!(\"Relocation table:\");\n for (k, v) in &repl {\n tracing::debug!(\"{} → {}\", k, v);\n }\n original_relocation_scan_and_patch(formula, install_dir, config, repl)\n}\n\nfn original_relocation_scan_and_patch(\n _formula: &Formula,\n install_dir: &Path,\n _config: &Config,\n replacements: HashMap,\n) -> Result<()> {\n let mut text_replaced_count = 0;\n let mut macho_patched_count = 0;\n let mut permission_errors = 0;\n let mut macho_errors = 0;\n let mut io_errors = 0;\n let mut files_to_chmod: Vec = Vec::new();\n for entry in WalkDir::new(install_dir).into_iter().filter_map(|e| e.ok()) {\n let path = entry.path();\n let file_type = entry.file_type();\n if path\n .components()\n .any(|c| c.as_os_str().to_string_lossy().ends_with(\".app\"))\n {\n if file_type.is_file() {\n debug!(\"Skipping relocation inside .app bundle: {}\", path.display());\n }\n continue;\n }\n if file_type.is_symlink() {\n debug!(\"Checking symlink for potential chmod: {}\", path.display());\n if path\n .parent()\n .is_some_and(|p| p.ends_with(\"bin\") || p.ends_with(\"sbin\"))\n {\n files_to_chmod.push(path.to_path_buf());\n }\n continue;\n }\n if !file_type.is_file() {\n continue;\n }\n let (meta, initially_executable) = match fs::metadata(path) {\n Ok(m) => {\n #[cfg(unix)]\n let ie = m.permissions().mode() & 0o111 != 0;\n #[cfg(not(unix))]\n let ie = true;\n (m, ie)\n }\n Err(_e) => {\n debug!(\"Failed to get metadata for {}: {}\", path.display(), _e);\n io_errors += 1;\n continue;\n }\n };\n let is_in_exec_dir = path\n .parent()\n .is_some_and(|p| p.ends_with(\"bin\") || p.ends_with(\"sbin\"));\n if meta.permissions().readonly() {\n #[cfg(unix)]\n {\n let mut perms = meta.permissions();\n let current_mode = perms.mode();\n let new_mode = current_mode | 0o200;\n if new_mode != current_mode {\n perms.set_mode(new_mode);\n if fs::set_permissions(path, perms).is_err() {\n debug!(\n \"Skipping readonly file (and couldn't make writable): {}\",\n path.display()\n );\n continue;\n } else {\n debug!(\"Made readonly file writable: {}\", path.display());\n }\n }\n }\n #[cfg(not(unix))]\n {\n debug!(\n \"Skipping potentially readonly file on non-unix: {}\",\n path.display()\n );\n continue;\n }\n }\n let mut was_modified = false;\n let mut skipped_paths_for_file = Vec::new();\n if cfg!(target_os = \"macos\")\n && (initially_executable\n || is_in_exec_dir\n || path\n .extension()\n .is_some_and(|e| e == \"dylib\" || e == \"so\" || e == \"bundle\"))\n {\n match macho::patch_macho_file(path, &replacements) {\n Ok((true, skipped_paths)) => {\n macho_patched_count += 1;\n was_modified = true;\n skipped_paths_for_file = skipped_paths;\n }\n Ok((false, skipped_paths)) => {\n // Not Mach-O or no patches needed, but might have skipped paths\n skipped_paths_for_file = skipped_paths;\n }\n Err(SpsError::PathTooLongError(e)) => { // Specifically catch path too long\n error!(\n \"Mach-O patch failed (path too long) for {}: {}\",\n path.display(),\n e\n );\n macho_errors += 1;\n // Continue scanning other files even if one fails this way\n continue;\n }\n Err(SpsError::CodesignError(e)) => { // Specifically catch codesign errors\n error!(\n \"Mach-O patch failed (codesign error) for {}: {}\",\n path.display(),\n e\n );\n macho_errors += 1;\n // Continue scanning other files\n continue;\n }\n // Catch generic MachOError or Object error, treat as non-fatal for text replace\n Err(e @ SpsError::MachOError(_))\n | Err(e @ SpsError::Object(_))\n | Err(e @ SpsError::Generic(_)) // Catch Generic errors from patch_macho too\n | Err(e @ SpsError::Io(_)) => { // Catch IO errors from patch_macho\n debug!(\n \"Mach-O processing/patching failed for {}: {}. Skipping Mach-O patch for this file.\",\n path.display(),\n e\n );\n // Don't increment macho_errors here, as we fallback to text replace\n io_errors += 1; // Count as IO or generic error instead\n }\n // Catch other specific errors if needed\n Err(e) => {\n debug!(\n \"Unexpected error during Mach-O check/patch for {}: {}. Falling back to text replacer.\",\n path.display(),\n e\n );\n io_errors += 1;\n }\n }\n\n // Handle paths that were too long for Mach-O patching with install_name_tool fallback\n if !skipped_paths_for_file.is_empty() {\n debug!(\n \"Applying install_name_tool fallback for {} skipped paths in {}\",\n skipped_paths_for_file.len(),\n path.display()\n );\n debug!(\n \"Applying install_name_tool fallback for {} skipped paths in {}\",\n skipped_paths_for_file.len(),\n path.display()\n );\n for skipped in &skipped_paths_for_file {\n match apply_install_name_tool_change(&skipped.old_path, &skipped.new_path, path)\n {\n Ok(()) => {\n debug!(\n \"Successfully applied install_name_tool fallback: '{}' -> '{}' in {}\",\n skipped.old_path, skipped.new_path, path.display()\n );\n was_modified = true;\n }\n Err(e) => {\n warn!(\n \"install_name_tool fallback failed for '{}' -> '{}' in {}: {}\",\n skipped.old_path,\n skipped.new_path,\n path.display(),\n e\n );\n macho_errors += 1;\n }\n }\n }\n }\n }\n // Fallback to text replacement if not modified by Mach-O patching\n if !was_modified {\n // Heuristic check for text file (avoid reading huge binaries)\n let mut is_likely_text = false;\n if meta.len() < 5 * 1024 * 1024 {\n if let Ok(mut f) = File::open(path) {\n let mut buf = [0; 1024];\n match f.read(&mut buf) {\n Ok(n) if n > 0 => {\n if !buf[..n].contains(&0) {\n is_likely_text = true;\n }\n }\n Ok(_) => {\n is_likely_text = true;\n }\n Err(_) => {}\n }\n }\n }\n\n if is_likely_text {\n // Read the file content as string\n if let Ok(content) = fs::read_to_string(path) {\n let mut new_content = content.clone();\n let mut replacements_made = false;\n for (placeholder, replacement) in &replacements {\n if new_content.contains(placeholder) {\n new_content = new_content.replace(placeholder, replacement);\n replacements_made = true;\n }\n }\n // Write back only if changes were made\n if replacements_made {\n match write_text_file_atomic(path, &new_content) {\n Ok(_) => {\n text_replaced_count += 1;\n was_modified = true; // Mark as modified for chmod check\n }\n Err(e) => {\n error!(\n \"Failed to write replaced text to {}: {}\",\n path.display(),\n e\n );\n io_errors += 1;\n }\n }\n }\n } else if meta.len() > 0 {\n debug!(\n \"Could not read {} as string for text replacement.\",\n path.display()\n );\n io_errors += 1;\n }\n } else if meta.len() >= 5 * 1024 * 1024 {\n debug!(\n \"Skipping text replacement for large file: {}\",\n path.display()\n );\n } else {\n debug!(\n \"Skipping text replacement for likely binary file: {}\",\n path.display()\n );\n }\n }\n if was_modified || initially_executable || is_in_exec_dir {\n files_to_chmod.push(path.to_path_buf());\n }\n }\n\n #[cfg(unix)]\n {\n debug!(\n \"Ensuring execute permissions for {} potentially executable files/links\",\n files_to_chmod.len()\n );\n let unique_files_to_chmod: HashSet<_> = files_to_chmod.into_iter().collect();\n for p in &unique_files_to_chmod {\n if !p.exists() && p.symlink_metadata().is_err() {\n debug!(\"Skipping chmod for non-existent path: {}\", p.display());\n continue;\n }\n match fs::symlink_metadata(p) {\n Ok(m) => {\n if m.is_file() {\n let mut perms = m.permissions();\n let current_mode = perms.mode();\n let new_mode = current_mode | 0o111;\n if new_mode != current_mode {\n perms.set_mode(new_mode);\n if let Err(e) = fs::set_permissions(p, perms) {\n debug!(\"Failed to set +x on {}: {}\", p.display(), e);\n permission_errors += 1;\n }\n }\n }\n }\n Err(e) => {\n debug!(\n \"Could not stat {} during final chmod pass: {}\",\n p.display(),\n e\n );\n permission_errors += 1;\n }\n }\n }\n }\n\n debug!(\n \"Relocation scan complete. Text files replaced: {}, Mach-O files patched: {}\",\n text_replaced_count, macho_patched_count\n );\n if permission_errors > 0 || macho_errors > 0 || io_errors > 0 {\n debug!(\n \"Bottle relocation finished with issues: {} chmod errors, {} Mach-O errors, {} IO errors in {}.\",\n permission_errors,\n macho_errors,\n io_errors,\n install_dir.display()\n );\n if macho_errors > 0 {\n return Err(SpsError::InstallError(format!(\n \"Bottle relocation failed due to {} Mach-O errors in {}\",\n macho_errors,\n install_dir.display()\n )));\n }\n }\n Ok(())\n}\n\nfn codesign_path(target: &Path) -> Result<()> {\n debug!(\"Re‑signing: {}\", target.display());\n let status = StdCommand::new(\"codesign\")\n .args([\n \"-s\",\n \"-\",\n \"--force\",\n \"--preserve-metadata=identifier,entitlements\",\n target\n .to_str()\n .ok_or_else(|| SpsError::Generic(\"Non‑UTF8 path for codesign\".into()))?,\n ])\n .stdout(Stdio::null())\n .stderr(Stdio::null())\n .status()\n .map_err(|e| SpsError::Io(Arc::new(e)))?;\n if !status.success() {\n return Err(SpsError::CodesignError(format!(\n \"codesign failed for {}\",\n target.display()\n )));\n }\n Ok(())\n}\nfn write_text_file_atomic(original_path: &Path, content: &str) -> Result<()> {\n let dir = original_path.parent().ok_or_else(|| {\n SpsError::Generic(format!(\n \"Cannot get parent directory for {}\",\n original_path.display()\n ))\n })?;\n // Ensure the directory exists\n fs::create_dir_all(dir).map_err(|e| SpsError::Io(Arc::new(e)))?; // Use Arc::new\n\n let mut temp_file = NamedTempFile::new_in(dir)?;\n let temp_path = temp_file.path().to_path_buf(); // Store path before consuming temp_file\n\n // Write content\n temp_file.write_all(content.as_bytes())?;\n // Ensure data is flushed from application buffer to OS buffer\n temp_file.flush()?;\n // Attempt to sync data from OS buffer to disk (best effort)\n let _ = temp_file.as_file().sync_all();\n\n // Try to preserve original permissions\n let original_perms = fs::metadata(original_path).map(|m| m.permissions()).ok();\n\n // Atomically replace the original file with the temporary file\n temp_file.persist(original_path).map_err(|e| {\n error!(\n \"Failed to persist/rename temporary text file {} over {}: {}\",\n temp_path.display(), // Use stored path for logging\n original_path.display(),\n e.error // Log the underlying IO error\n );\n // Return the IO error wrapped in our error type\n SpsError::Io(Arc::new(e.error)) // Use Arc::new\n })?;\n\n // Restore original permissions if we captured them\n if let Some(perms) = original_perms {\n // Ignore errors setting permissions, best effort\n let _ = fs::set_permissions(original_path, perms);\n }\n Ok(())\n}\n\n#[cfg(unix)]\nfn find_brewed_perl(prefix: &Path) -> Option {\n let opt_dir = prefix.join(\"opt\");\n if !opt_dir.is_dir() {\n return None;\n }\n let mut best: Option<(semver::Version, PathBuf)> = None;\n match fs::read_dir(opt_dir) {\n Ok(entries) => {\n for entry_res in entries.flatten() {\n let name = entry_res.file_name();\n let s = name.to_string_lossy();\n let entry_path = entry_res.path();\n if !entry_path.is_dir() {\n continue;\n }\n if let Some(version_part) = s.strip_prefix(\"perl@\") {\n let version_str_padded = if version_part.contains('.') {\n let parts: Vec<&str> = version_part.split('.').collect();\n match parts.len() {\n 1 => format!(\"{}.0.0\", parts[0]), // e.g., perl@5 -> 5.0.0\n 2 => format!(\"{}.{}.0\", parts[0], parts[1]), /* e.g., perl@5.30 -> */\n // 5.30.0\n _ => version_part.to_string(), // Already 3+ parts\n }\n } else {\n format!(\"{version_part}.0.0\") // e.g., perl@5 -> 5.0.0 (handles case with no\n // dot)\n };\n\n if let Ok(v) = semver::Version::parse(&version_str_padded) {\n let candidate_bin = entry_path.join(\"bin/perl\");\n if candidate_bin.is_file()\n && (best.is_none() || v > best.as_ref().unwrap().0)\n {\n best = Some((v, candidate_bin));\n }\n }\n } else if s == \"perl\" {\n let candidate_bin = entry_path.join(\"bin/perl\");\n if candidate_bin.is_file() && best.is_none() {\n if let Ok(v_base) = semver::Version::parse(\"5.0.0\") {\n best = Some((v_base, candidate_bin));\n }\n }\n }\n }\n }\n Err(_e) => {\n debug!(\"Failed to read opt directory during perl search: {}\", _e);\n }\n }\n best.map(|(_, path)| path)\n}\n\n#[cfg(not(unix))]\nfn find_brewed_perl(_prefix: &Path) -> Option {\n None\n}\nfn ensure_llvm_symlinks(install_dir: &Path, formula: &Formula, config: &Config) -> Result<()> {\n let lib_dir = install_dir.join(\"lib\");\n if !lib_dir.exists() {\n debug!(\n \"Skipping LLVM symlink creation as lib dir is missing in {}\",\n install_dir.display()\n );\n return Ok(());\n }\n\n let llvm_dep_name = match formula.dependencies() {\n Ok(deps) => deps\n .iter()\n .find(|d| d.name.starts_with(\"llvm\"))\n .map(|dep| dep.name.clone()),\n Err(e) => {\n warn!(\n \"Could not check formula dependencies for LLVM symlink creation in {}: {}\",\n formula.name(),\n e\n );\n return Ok(()); // Don't error, just skip\n }\n };\n\n // Proceed only if llvm_dep_name is Some\n let llvm_dep_name = match llvm_dep_name {\n Some(name) => name,\n None => {\n debug!(\n \"Formula {} does not list an LLVM dependency.\",\n formula.name()\n );\n return Ok(());\n }\n };\n\n let llvm_opt_path = config.formula_opt_path(&llvm_dep_name);\n let llvm_lib_filename = if cfg!(target_os = \"macos\") {\n \"libLLVM.dylib\"\n } else if cfg!(target_os = \"linux\") {\n \"libLLVM.so\"\n } else {\n warn!(\"LLVM library filename unknown for target OS, skipping symlink.\");\n return Ok(());\n };\n let llvm_lib_path_in_opt = llvm_opt_path.join(\"lib\").join(llvm_lib_filename);\n if !llvm_lib_path_in_opt.exists() {\n debug!(\n \"Required LLVM library not found at {}. Cannot create symlink in {}.\",\n llvm_lib_path_in_opt.display(),\n formula.name()\n );\n return Ok(());\n }\n let symlink_target_path = lib_dir.join(llvm_lib_filename);\n if symlink_target_path.exists() || symlink_target_path.symlink_metadata().is_ok() {\n debug!(\n \"Symlink or file already exists at {}. Skipping creation.\",\n symlink_target_path.display()\n );\n return Ok(());\n }\n #[cfg(unix)]\n {\n if let Some(parent) = symlink_target_path.parent() {\n if !parent.exists() {\n fs::create_dir_all(parent)?;\n }\n }\n match symlink(&llvm_lib_path_in_opt, &symlink_target_path) {\n Ok(_) => debug!(\n \"Created symlink {} -> {}\",\n symlink_target_path.display(),\n llvm_lib_path_in_opt.display()\n ),\n Err(e) => {\n // Log as warning, don't fail install\n warn!(\n \"Failed to create LLVM symlink {} -> {}: {}\",\n symlink_target_path.display(),\n llvm_lib_path_in_opt.display(),\n e\n );\n }\n }\n\n let rustlib_dir = install_dir.join(\"lib\").join(\"rustlib\");\n if rustlib_dir.is_dir() {\n if let Ok(entries) = fs::read_dir(&rustlib_dir) {\n for entry in entries.flatten() {\n let triple_path = entry.path();\n if triple_path.is_dir() {\n let triple_lib_dir = triple_path.join(\"lib\");\n if triple_lib_dir.is_dir() {\n let nested_symlink = triple_lib_dir.join(llvm_lib_filename);\n\n if nested_symlink.exists() || nested_symlink.symlink_metadata().is_ok()\n {\n debug!(\n \"Symlink or file already exists at {}, skipping.\",\n nested_symlink.display()\n );\n continue;\n }\n\n if let Some(parent) = nested_symlink.parent() {\n let _ = fs::create_dir_all(parent);\n }\n match symlink(&llvm_lib_path_in_opt, &nested_symlink) {\n Ok(_) => debug!(\n \"Created symlink {} -> {}\",\n nested_symlink.display(),\n llvm_lib_path_in_opt.display()\n ),\n Err(e) => warn!(\n \"Failed to create LLVM symlink {} -> {}: {}\",\n nested_symlink.display(),\n llvm_lib_path_in_opt.display(),\n e\n ),\n }\n }\n }\n }\n }\n }\n }\n Ok(())\n}\n\n/// Applies a path change using install_name_tool as a fallback for Mach-O files\n/// where the path replacement is too long for direct binary patching.\nfn apply_install_name_tool_change(old_path: &str, new_path: &str, target: &Path) -> Result<()> {\n if !target.exists() {\n debug!(\n \"Target {} does not exist, skipping install_name_tool fallback.\",\n target.display()\n );\n return Ok(());\n }\n\n debug!(\n \"Running install_name_tool -change {} {} {}\",\n old_path,\n new_path,\n target.display()\n );\n\n let output = StdCommand::new(\"install_name_tool\")\n .args([\"-change\", old_path, new_path, target.to_str().unwrap()])\n .output()\n .map_err(|e| SpsError::Io(Arc::new(e)))?;\n\n if !output.status.success() {\n let stderr = String::from_utf8_lossy(&output.stderr);\n if !stderr.contains(\"file not found\")\n && !stderr.contains(\"no LC_LOAD_DYLIB command specifying file\")\n && !stderr.contains(\"is not a Mach-O file\")\n && !stderr.contains(\"object file format invalid\")\n && !stderr.trim().is_empty()\n {\n error!(\n \"install_name_tool -change failed unexpectedly for target {}: {}\",\n target.display(),\n stderr.trim()\n );\n return Err(SpsError::InstallError(format!(\n \"install_name_tool failed for {}: {}\",\n target.display(),\n stderr.trim()\n )));\n } else {\n debug!(\n \"install_name_tool -change: old path '{}' likely not found or target '{}' not relevant (stderr: {}).\",\n old_path,\n target.display(),\n stderr.trim()\n );\n return Ok(()); // No changes made, skip re-signing\n }\n }\n\n // Re-sign the binary after making changes (required on Apple Silicon)\n #[cfg(all(target_os = \"macos\", target_arch = \"aarch64\"))]\n {\n debug!(\n \"Re-signing binary after install_name_tool change: {}\",\n target.display()\n );\n codesign_path(target)?;\n }\n\n debug!(\n \"Successfully applied install_name_tool fallback for {} -> {} in {}\",\n old_path,\n new_path,\n target.display()\n );\n\n Ok(())\n}\n"], ["/sps/sps-common/src/model/formula.rs", "// sps-core/src/model/formula.rs\n// *** Corrected: Removed derive Deserialize from ResourceSpec, removed unused SpsError import,\n// added ResourceSpec struct and parsing ***\n\nuse std::collections::HashMap;\nuse std::path::{Path, PathBuf};\n\nuse semver::Version;\nuse serde::{de, Deserialize, Deserializer, Serialize};\nuse serde_json::Value;\nuse tracing::{debug, error};\n\nuse crate::dependency::{Dependency, DependencyTag, Requirement};\nuse crate::error::Result; // <-- Import only Result // Use log crate imports\n\n// --- Resource Spec Struct ---\n// *** Added struct definition, REMOVED #[derive(Deserialize)] ***\n#[derive(Debug, Clone, Serialize, PartialEq, Eq)]\npub struct ResourceSpec {\n pub name: String,\n pub url: String,\n pub sha256: String,\n // Add other potential fields like version if needed later\n}\n\n// --- Bottle Related Structs (Original structure) ---\n#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]\npub struct BottleFileSpec {\n pub url: String,\n pub sha256: String,\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]\npub struct BottleSpec {\n pub stable: Option,\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]\npub struct BottleStableSpec {\n pub rebuild: u32,\n #[serde(default)]\n pub files: HashMap,\n}\n\n// --- Formula Version Struct (Original structure) ---\n#[derive(Deserialize, Serialize, Debug, Clone, Default, PartialEq, Eq)]\npub struct FormulaVersions {\n pub stable: Option,\n pub head: Option,\n #[serde(default)]\n pub bottle: bool,\n}\n\n// --- Main Formula Struct ---\n// *** Added 'resources' field ***\n#[derive(Debug, Clone, Serialize, PartialEq, Eq)]\npub struct Formula {\n pub name: String,\n pub stable_version_str: String,\n #[serde(rename = \"versions\")]\n pub version_semver: Version,\n #[serde(default)]\n pub revision: u32,\n #[serde(default)]\n pub desc: Option,\n #[serde(default)]\n pub homepage: Option,\n #[serde(default)]\n pub url: String,\n #[serde(default)]\n pub sha256: String,\n #[serde(default)]\n pub mirrors: Vec,\n #[serde(default)]\n pub bottle: BottleSpec,\n #[serde(skip_deserializing)]\n pub dependencies: Vec,\n #[serde(default, deserialize_with = \"deserialize_requirements\")]\n pub requirements: Vec,\n #[serde(skip_deserializing)] // Skip direct deserialization for this field\n pub resources: Vec, // Stores parsed resources\n #[serde(skip)]\n pub install_keg_path: Option,\n}\n\n// Custom deserialization logic for Formula\nimpl<'de> Deserialize<'de> for Formula {\n fn deserialize(deserializer: D) -> std::result::Result\n where\n D: Deserializer<'de>,\n {\n // Temporary struct reflecting the JSON structure more closely\n // *** Added 'resources' field to capture raw JSON Value ***\n #[derive(Deserialize, Debug)]\n struct RawFormulaData {\n name: String,\n #[serde(default)]\n revision: u32,\n desc: Option,\n homepage: Option,\n versions: FormulaVersions,\n #[serde(default)]\n url: String,\n #[serde(default)]\n sha256: String,\n #[serde(default)]\n mirrors: Vec,\n #[serde(default)]\n bottle: BottleSpec,\n #[serde(default)]\n dependencies: Vec,\n #[serde(default)]\n build_dependencies: Vec,\n #[serde(default)]\n test_dependencies: Vec,\n #[serde(default)]\n recommended_dependencies: Vec,\n #[serde(default)]\n optional_dependencies: Vec,\n #[serde(default, deserialize_with = \"deserialize_requirements\")]\n requirements: Vec,\n #[serde(default)]\n resources: Vec, // Capture resources as generic Value first\n #[serde(default)]\n urls: Option,\n }\n\n let raw: RawFormulaData = RawFormulaData::deserialize(deserializer)?;\n\n // --- Version Parsing (Original logic) ---\n let stable_version_str = raw\n .versions\n .stable\n .clone()\n .ok_or_else(|| de::Error::missing_field(\"versions.stable\"))?;\n let version_semver = match crate::model::version::Version::parse(&stable_version_str) {\n Ok(v) => v.into(),\n Err(_) => {\n let mut majors = 0u32;\n let mut minors = 0u32;\n let mut patches = 0u32;\n let mut part_count = 0;\n for (i, part) in stable_version_str.split('.').enumerate() {\n let numeric_part = part\n .chars()\n .take_while(|c| c.is_ascii_digit())\n .collect::();\n if numeric_part.is_empty() && i > 0 {\n break;\n }\n if numeric_part.len() < part.len() && i > 0 {\n if let Ok(num) = numeric_part.parse::() {\n match i {\n 0 => majors = num,\n 1 => minors = num,\n 2 => patches = num,\n _ => {}\n }\n part_count += 1;\n }\n break;\n }\n if let Ok(num) = numeric_part.parse::() {\n match i {\n 0 => majors = num,\n 1 => minors = num,\n 2 => patches = num,\n _ => {}\n }\n part_count += 1;\n }\n if i >= 2 {\n break;\n }\n }\n let version_str_padded = match part_count {\n 1 => format!(\"{majors}.0.0\"),\n 2 => format!(\"{majors}.{minors}.0\"),\n _ => format!(\"{majors}.{minors}.{patches}\"),\n };\n match Version::parse(&version_str_padded) {\n Ok(v) => v,\n Err(_) => {\n error!(\n \"Warning: Could not parse version '{}' (sanitized to '{}') for formula '{}'. Using 0.0.0.\",\n stable_version_str, version_str_padded, raw.name\n );\n Version::new(0, 0, 0)\n }\n }\n }\n };\n\n // --- URL/SHA256 Logic (Original logic) ---\n let mut final_url = raw.url;\n let mut final_sha256 = raw.sha256;\n if final_url.is_empty() {\n if let Some(Value::Object(urls_map)) = raw.urls {\n if let Some(Value::Object(stable_url_info)) = urls_map.get(\"stable\") {\n if let Some(Value::String(u)) = stable_url_info.get(\"url\") {\n final_url = u.clone();\n }\n if let Some(Value::String(s)) = stable_url_info\n .get(\"checksum\")\n .or_else(|| stable_url_info.get(\"sha256\"))\n {\n final_sha256 = s.clone();\n }\n }\n }\n }\n if final_url.is_empty() && raw.versions.head.is_none() {\n debug!(\"Warning: Formula '{}' has no stable URL defined.\", raw.name);\n }\n\n // --- Dependency Processing (Original logic) ---\n let mut combined_dependencies: Vec = Vec::new();\n let mut seen_deps: HashMap = HashMap::new();\n let mut process_list = |deps: &[String], tag: DependencyTag| {\n for name in deps {\n *seen_deps\n .entry(name.clone())\n .or_insert(DependencyTag::empty()) |= tag;\n }\n };\n process_list(&raw.dependencies, DependencyTag::RUNTIME);\n process_list(&raw.build_dependencies, DependencyTag::BUILD);\n process_list(&raw.test_dependencies, DependencyTag::TEST);\n process_list(\n &raw.recommended_dependencies,\n DependencyTag::RECOMMENDED | DependencyTag::RUNTIME,\n );\n process_list(\n &raw.optional_dependencies,\n DependencyTag::OPTIONAL | DependencyTag::RUNTIME,\n );\n for (name, tags) in seen_deps {\n combined_dependencies.push(Dependency::new_with_tags(name, tags));\n }\n\n // --- Resource Processing ---\n // *** Added parsing logic for the 'resources' field ***\n let mut combined_resources: Vec = Vec::new();\n for res_val in raw.resources {\n // Homebrew API JSON format puts resource spec inside a keyed object\n // e.g., { \"resource_name\": { \"url\": \"...\", \"sha256\": \"...\" } }\n if let Value::Object(map) = res_val {\n // Assume only one key-value pair per object in the array\n if let Some((res_name, res_spec_val)) = map.into_iter().next() {\n // Use the manual Deserialize impl for ResourceSpec\n match ResourceSpec::deserialize(res_spec_val.clone()) {\n // Use ::deserialize\n Ok(mut res_spec) => {\n // Inject the name from the key if missing\n if res_spec.name.is_empty() {\n res_spec.name = res_name;\n } else if res_spec.name != res_name {\n debug!(\n \"Resource name mismatch in formula '{}': key '{}' vs spec '{}'. Using key.\",\n raw.name, res_name, res_spec.name\n );\n res_spec.name = res_name; // Prefer key name\n }\n // Ensure required fields are present\n if res_spec.url.is_empty() || res_spec.sha256.is_empty() {\n debug!(\n \"Resource '{}' for formula '{}' is missing URL or SHA256. Skipping.\",\n res_spec.name, raw.name\n );\n continue;\n }\n debug!(\n \"Parsed resource '{}' for formula '{}'\",\n res_spec.name, raw.name\n );\n combined_resources.push(res_spec);\n }\n Err(e) => {\n // Use display for the error which comes from serde::de::Error::custom\n debug!(\n \"Failed to parse resource spec value for key '{}' in formula '{}': {}. Value: {:?}\",\n res_name, raw.name, e, res_spec_val\n );\n }\n }\n } else {\n debug!(\"Empty resource object found in formula '{}'.\", raw.name);\n }\n } else {\n debug!(\n \"Unexpected format for resource entry in formula '{}': expected object, got {:?}\",\n raw.name, res_val\n );\n }\n }\n\n Ok(Self {\n name: raw.name,\n stable_version_str,\n version_semver,\n revision: raw.revision,\n desc: raw.desc,\n homepage: raw.homepage,\n url: final_url,\n sha256: final_sha256,\n mirrors: raw.mirrors,\n bottle: raw.bottle,\n dependencies: combined_dependencies,\n requirements: raw.requirements,\n resources: combined_resources, // Assign parsed resources\n install_keg_path: None,\n })\n }\n}\n\n// --- Formula impl Methods ---\nimpl Formula {\n // dependencies() and requirements() are unchanged\n pub fn dependencies(&self) -> Result> {\n Ok(self.dependencies.clone())\n }\n pub fn requirements(&self) -> Result> {\n Ok(self.requirements.clone())\n }\n\n // *** Added: Returns a clone of the defined resources. ***\n pub fn resources(&self) -> Result> {\n Ok(self.resources.clone())\n }\n\n // Other methods (set_keg_path, version_str_full, accessors) are unchanged\n pub fn set_keg_path(&mut self, path: PathBuf) {\n self.install_keg_path = Some(path);\n }\n pub fn version_str_full(&self) -> String {\n if self.revision > 0 {\n format!(\"{}_{}\", self.stable_version_str, self.revision)\n } else {\n self.stable_version_str.clone()\n }\n }\n pub fn name(&self) -> &str {\n &self.name\n }\n pub fn version(&self) -> &Version {\n &self.version_semver\n }\n pub fn source_url(&self) -> &str {\n &self.url\n }\n pub fn source_sha256(&self) -> &str {\n &self.sha256\n }\n pub fn get_bottle_spec(&self, bottle_tag: &str) -> Option<&BottleFileSpec> {\n self.bottle.stable.as_ref()?.files.get(bottle_tag)\n }\n}\n\n// --- BuildEnvironment Dependency Interface (Unchanged) ---\npub trait FormulaDependencies {\n fn name(&self) -> &str;\n fn install_prefix(&self, cellar_path: &Path) -> Result;\n fn resolved_runtime_dependency_paths(&self) -> Result>;\n fn resolved_build_dependency_paths(&self) -> Result>;\n fn all_resolved_dependency_paths(&self) -> Result>;\n}\nimpl FormulaDependencies for Formula {\n fn name(&self) -> &str {\n &self.name\n }\n fn install_prefix(&self, cellar_path: &Path) -> Result {\n let version_string = self.version_str_full();\n Ok(cellar_path.join(self.name()).join(version_string))\n }\n fn resolved_runtime_dependency_paths(&self) -> Result> {\n Ok(Vec::new())\n }\n fn resolved_build_dependency_paths(&self) -> Result> {\n Ok(Vec::new())\n }\n fn all_resolved_dependency_paths(&self) -> Result> {\n Ok(Vec::new())\n }\n}\n\n// --- Deserialization Helpers ---\n// deserialize_requirements remains unchanged\nfn deserialize_requirements<'de, D>(\n deserializer: D,\n) -> std::result::Result, D::Error>\nwhere\n D: serde::Deserializer<'de>,\n{\n #[derive(Deserialize, Debug)]\n struct ReqWrapper {\n #[serde(default)]\n name: String,\n #[serde(default)]\n version: Option,\n #[serde(default)]\n cask: Option,\n #[serde(default)]\n download: Option,\n }\n let raw_reqs: Vec = Deserialize::deserialize(deserializer)?;\n let mut requirements = Vec::new();\n for req_val in raw_reqs {\n if let Ok(req_obj) = serde_json::from_value::(req_val.clone()) {\n match req_obj.name.as_str() {\n \"macos\" => {\n requirements.push(Requirement::MacOS(\n req_obj.version.unwrap_or_else(|| \"any\".to_string()),\n ));\n }\n \"xcode\" => {\n requirements.push(Requirement::Xcode(\n req_obj.version.unwrap_or_else(|| \"any\".to_string()),\n ));\n }\n \"cask\" => {\n requirements.push(Requirement::Other(format!(\n \"Cask Requirement: {}\",\n req_obj.cask.unwrap_or_else(|| \"?\".to_string())\n )));\n }\n \"download\" => {\n requirements.push(Requirement::Other(format!(\n \"Download Requirement: {}\",\n req_obj.download.unwrap_or_else(|| \"?\".to_string())\n )));\n }\n _ => requirements.push(Requirement::Other(format!(\n \"Unknown requirement type: {req_obj:?}\"\n ))),\n }\n } else if let Value::String(req_str) = req_val {\n match req_str.as_str() {\n \"macos\" => requirements.push(Requirement::MacOS(\"latest\".to_string())),\n \"xcode\" => requirements.push(Requirement::Xcode(\"latest\".to_string())),\n _ => {\n requirements.push(Requirement::Other(format!(\"Simple requirement: {req_str}\")))\n }\n }\n } else {\n debug!(\"Warning: Could not parse requirement: {:?}\", req_val);\n requirements.push(Requirement::Other(format!(\n \"Unparsed requirement: {req_val:?}\"\n )));\n }\n }\n Ok(requirements)\n}\n\n// Manual impl Deserialize for ResourceSpec (unchanged, this is needed)\nimpl<'de> Deserialize<'de> for ResourceSpec {\n fn deserialize(deserializer: D) -> std::result::Result\n where\n D: Deserializer<'de>,\n {\n #[derive(Deserialize)]\n struct Helper {\n #[serde(default)]\n name: String, // name is often the key, not in the value\n url: String,\n sha256: String,\n }\n let helper = Helper::deserialize(deserializer)?;\n // Note: The actual resource name comes from the key in the map during Formula\n // deserialization\n Ok(Self {\n name: helper.name,\n url: helper.url,\n sha256: helper.sha256,\n })\n }\n}\n"], ["/sps/sps/src/cli/init.rs", "// sps/src/cli/init.rs\nuse std::fs::{self, File, OpenOptions};\nuse std::io::{BufRead, BufReader, Write};\nuse std::path::{Path, PathBuf};\nuse std::process::Command as StdCommand;\nuse std::sync::Arc;\n\nuse clap::Args;\nuse colored::Colorize;\nuse sps_common::config::Config; // Assuming Config is correctly in sps_common\nuse sps_common::error::{Result as SpsResult, SpsError};\nuse tempfile;\nuse tracing::{debug, error, warn};\n\n#[derive(Args, Debug)]\npub struct InitArgs {\n /// Force initialization even if /opt/sps appears to be an sps root already.\n #[arg(long)]\n pub force: bool,\n}\n\nimpl InitArgs {\n pub async fn run(&self, config: &Config) -> SpsResult<()> {\n debug!(\n \"Initializing sps environment at {}\",\n config.sps_root().display()\n );\n\n let sps_root = config.sps_root();\n let marker_path = config.sps_root_marker_path();\n\n // 1. Initial Checks (as current user) - (No change from your existing logic)\n if sps_root.exists() {\n let is_empty = match fs::read_dir(sps_root) {\n Ok(mut entries) => entries.next().is_none(),\n Err(_) => false, // If we can't read it, assume not empty or not accessible\n };\n\n if marker_path.exists() && !self.force {\n debug!(\n \"{} already exists. sps appears to be initialized. Use --force to re-initialize.\",\n marker_path.display()\n );\n return Ok(());\n }\n if !self.force && !is_empty && !marker_path.exists() {\n warn!(\n \"Directory {} exists but does not appear to be an sps root (missing marker {}).\",\n sps_root.display(),\n marker_path.file_name().unwrap_or_default().to_string_lossy()\n );\n warn!(\n \"Run with --force to initialize anyway (this might overwrite existing data or change permissions).\"\n );\n return Err(SpsError::Config(format!(\n \"{} exists but is not a recognized sps root. Aborting.\",\n sps_root.display()\n )));\n }\n if self.force {\n debug!(\n \"--force specified. Proceeding with initialization in {}.\",\n sps_root.display()\n );\n } else if is_empty {\n debug!(\n \"Directory {} exists but is empty. Proceeding with initialization.\",\n sps_root.display()\n );\n }\n }\n\n // 2. Privileged Operations\n let current_user_name = std::env::var(\"USER\")\n .or_else(|_| std::env::var(\"LOGNAME\"))\n .map_err(|_| {\n SpsError::Generic(\n \"Failed to get current username from USER or LOGNAME environment variables.\"\n .to_string(),\n )\n })?;\n\n let target_group_name = if cfg!(target_os = \"macos\") {\n \"admin\" // Standard admin group on macOS\n } else {\n // For Linux, 'staff' might not exist or be appropriate.\n // Often, the user's primary group is used, or a dedicated 'brew' group.\n // For simplicity, let's try to use the current user's name as the group too,\n // which works if the user has a group with the same name.\n // A more robust Linux solution might involve checking for 'staff' or other common\n // groups.\n ¤t_user_name\n };\n\n debug!(\n \"Will attempt to set ownership of sps-managed directories under {} to {}:{}\",\n sps_root.display(),\n current_user_name,\n target_group_name\n );\n\n println!(\n \"{}\",\n format!(\n \"sps may require sudo to create directories and set permissions in {}.\",\n sps_root.display()\n )\n .yellow()\n );\n\n // Define directories sps needs to ensure exist and can manage.\n // These are derived from your Config struct.\n let dirs_to_create_and_manage: Vec = vec![\n config.sps_root().to_path_buf(), // The root itself\n config.bin_dir(),\n config.cellar_dir(),\n config.cask_room_dir(),\n config.cask_store_dir(), // sps-specific\n config.opt_dir(),\n config.taps_dir(), // This is now sps_root/Library/Taps\n config.cache_dir(), // sps-specific (e.g., sps_root/sps_cache)\n config.logs_dir(), // sps-specific (e.g., sps_root/sps_logs)\n config.tmp_dir(),\n config.state_dir(),\n config\n .man_base_dir()\n .parent()\n .unwrap_or(sps_root)\n .to_path_buf(), // share\n config.man_base_dir(), // share/man\n config.sps_root().join(\"etc\"),\n config.sps_root().join(\"include\"),\n config.sps_root().join(\"lib\"),\n config.sps_root().join(\"share/doc\"),\n ];\n\n // Create directories with mkdir -p (non-destructive)\n for dir_path in &dirs_to_create_and_manage {\n // Only create if it doesn't exist to avoid unnecessary sudo calls if already present\n if !dir_path.exists() {\n debug!(\n \"Ensuring directory exists with sudo: {}\",\n dir_path.display()\n );\n run_sudo_command(\"mkdir\", &[\"-p\", &dir_path.to_string_lossy()])?;\n } else {\n debug!(\n \"Directory already exists, skipping mkdir: {}\",\n dir_path.display()\n );\n }\n }\n\n // Create the marker file (non-destructive to other content)\n debug!(\n \"Creating/updating marker file with sudo: {}\",\n marker_path.display()\n );\n let marker_content = \"sps root directory version 1\";\n // Using a temporary file for sudo tee to avoid permission issues with direct pipe\n let temp_marker_file =\n tempfile::NamedTempFile::new().map_err(|e| SpsError::Io(Arc::new(e)))?;\n fs::write(temp_marker_file.path(), marker_content)\n .map_err(|e| SpsError::Io(Arc::new(e)))?;\n run_sudo_command(\n \"cp\",\n &[\n temp_marker_file.path().to_str().unwrap(),\n marker_path.to_str().unwrap(),\n ],\n )?;\n\n #[cfg(unix)]\n {\n // More targeted chown and chmod\n debug!(\n \"Setting ownership and permissions for sps-managed directories under {}...\",\n sps_root.display()\n );\n\n // Chown/Chmod the top-level sps_root directory itself (non-recursively for chmod\n // initially) This is important if sps_root is /opt/sps and was just created\n // by root. If sps_root is /opt/homebrew, this ensures the current user can\n // at least manage it.\n run_sudo_command(\n \"chown\",\n &[\n &format!(\"{current_user_name}:{target_group_name}\"),\n &sps_root.to_string_lossy(),\n ],\n )?;\n run_sudo_command(\"chmod\", &[\"ug=rwx,o=rx\", &sps_root.to_string_lossy()])?; // 755 for the root\n\n // For specific subdirectories that sps actively manages and writes into frequently,\n // ensure they are owned by the user and have appropriate permissions.\n // We apply this recursively to sps-specific dirs and key shared dirs.\n let dirs_for_recursive_chown_chmod: Vec = vec![\n config.cellar_dir(),\n config.cask_room_dir(),\n config.cask_store_dir(), // sps-specific, definitely needs full user control\n config.opt_dir(),\n config.taps_dir(),\n config.cache_dir(), // sps-specific\n config.logs_dir(), // sps-specific\n config.tmp_dir(),\n config.state_dir(),\n // bin, lib, include, share, etc are often symlink farms.\n // The top-level of these should be writable by the user to create symlinks.\n // The actual kegs in Cellar will have their own permissions.\n config.bin_dir(),\n config.sps_root().join(\"lib\"),\n config.sps_root().join(\"include\"),\n config.sps_root().join(\"share\"),\n config.sps_root().join(\"etc\"),\n ];\n\n for dir_path in dirs_for_recursive_chown_chmod {\n if dir_path.exists() {\n // Only operate on existing directories\n debug!(\"Setting ownership (recursive) for: {}\", dir_path.display());\n run_sudo_command(\n \"chown\",\n &[\n \"-R\",\n &format!(\"{current_user_name}:{target_group_name}\"),\n &dir_path.to_string_lossy(),\n ],\n )?;\n\n debug!(\n \"Setting permissions (recursive ug=rwX,o=rX) for: {}\",\n dir_path.display()\n );\n run_sudo_command(\"chmod\", &[\"-R\", \"ug=rwX,o=rX\", &dir_path.to_string_lossy()])?;\n } else {\n warn!(\n \"Directory {} was expected but not found for chown/chmod. Marker: {}\",\n dir_path.display(),\n marker_path.display()\n );\n }\n }\n\n // Ensure bin is executable by all\n if config.bin_dir().exists() {\n debug!(\n \"Ensuring execute permissions for bin_dir: {}\",\n config.bin_dir().display()\n );\n run_sudo_command(\"chmod\", &[\"a+x\", &config.bin_dir().to_string_lossy()])?;\n // Also ensure contents of bin (wrappers, symlinks) are executable if they weren't\n // caught by -R ug=rwX This might be redundant if -R ug=rwX\n // correctly sets X for existing executables, but explicit `chmod\n // a+x` on individual files might be needed if they are newly created by sps.\n // For now, relying on the recursive chmod and the a+x on the bin_dir itself.\n }\n\n // Debug listing (optional, can be verbose)\n if tracing::enabled!(tracing::Level::DEBUG) {\n debug!(\"Listing {} after permission changes:\", sps_root.display());\n let ls_output_root = StdCommand::new(\"ls\").arg(\"-ld\").arg(sps_root).output();\n if let Ok(out) = ls_output_root {\n debug!(\n \"ls -ld {}: \\nSTDOUT: {}\\nSTDERR: {}\",\n sps_root.display(),\n String::from_utf8_lossy(&out.stdout),\n String::from_utf8_lossy(&out.stderr)\n );\n }\n for dir_path in &dirs_to_create_and_manage {\n if dir_path.exists() && dir_path != sps_root {\n let ls_output_sub = StdCommand::new(\"ls\").arg(\"-ld\").arg(dir_path).output();\n if let Ok(out) = ls_output_sub {\n debug!(\n \"ls -ld {}: \\nSTDOUT: {}\\nSTDERR: {}\",\n dir_path.display(),\n String::from_utf8_lossy(&out.stdout),\n String::from_utf8_lossy(&out.stderr)\n );\n }\n }\n }\n }\n }\n\n // 3. User-Specific PATH Configuration (runs as the original user) - (No change from your\n // existing logic)\n if let Err(e) = configure_shell_path(config, ¤t_user_name) {\n warn!(\n \"Could not fully configure shell PATH: {}. Manual configuration might be needed.\",\n e\n );\n print_manual_path_instructions(&config.bin_dir().to_string_lossy());\n }\n\n debug!(\n \"{} {}\",\n \"Successfully initialized sps environment at\".green(),\n config.sps_root().display().to_string().green()\n );\n Ok(())\n }\n}\n\n// run_sudo_command helper (no change from your existing logic)\nfn run_sudo_command(command: &str, args: &[&str]) -> SpsResult<()> {\n debug!(\"Running sudo {} {:?}\", command, args);\n let output = StdCommand::new(\"sudo\")\n .arg(command)\n .args(args)\n .output()\n .map_err(|e| SpsError::Io(Arc::new(e)))?;\n\n if !output.status.success() {\n let stderr = String::from_utf8_lossy(&output.stderr);\n let stdout = String::from_utf8_lossy(&output.stdout);\n error!(\n \"sudo {} {:?} failed ({}):\\nStdout: {}\\nStderr: {}\",\n command,\n args,\n output.status,\n stdout.trim(),\n stderr.trim()\n );\n Err(SpsError::Generic(format!(\n \"Failed to execute `sudo {} {:?}`: {}\",\n command,\n args,\n stderr.trim()\n )))\n } else {\n Ok(())\n }\n}\n\n// configure_shell_path helper (no change from your existing logic)\nfn configure_shell_path(config: &Config, current_user_name_for_log: &str) -> SpsResult<()> {\n debug!(\"Attempting to configure your shell for sps PATH...\");\n\n let sps_bin_path_str = config.bin_dir().to_string_lossy().into_owned();\n let home_dir = config.home_dir();\n if home_dir == PathBuf::from(\"/\") && current_user_name_for_log != \"root\" {\n warn!(\n \"Could not reliably determine your home directory (got '/'). Please add {} to your PATH manually for user {}.\",\n sps_bin_path_str, current_user_name_for_log\n );\n print_manual_path_instructions(&sps_bin_path_str);\n return Ok(());\n }\n\n let shell_path_env = std::env::var(\"SHELL\").unwrap_or_else(|_| \"unknown\".to_string());\n let mut config_files_updated: Vec = Vec::new();\n let mut path_seems_configured = false;\n\n let sps_path_line_zsh_bash = format!(\"export PATH=\\\"{sps_bin_path_str}:$PATH\\\"\");\n let sps_path_line_fish = format!(\"fish_add_path -P \\\"{sps_bin_path_str}\\\"\");\n\n if shell_path_env.contains(\"zsh\") {\n let zshrc_path = home_dir.join(\".zshrc\");\n if update_shell_config(\n &zshrc_path,\n &sps_path_line_zsh_bash,\n &sps_bin_path_str,\n \"Zsh\",\n false,\n )? {\n config_files_updated.push(zshrc_path.display().to_string());\n } else if line_exists_in_file(&zshrc_path, &sps_bin_path_str)? {\n path_seems_configured = true;\n }\n } else if shell_path_env.contains(\"bash\") {\n let bashrc_path = home_dir.join(\".bashrc\");\n let bash_profile_path = home_dir.join(\".bash_profile\");\n let profile_path = home_dir.join(\".profile\");\n\n let mut bash_updated_by_sps = false;\n if update_shell_config(\n &bashrc_path,\n &sps_path_line_zsh_bash,\n &sps_bin_path_str,\n \"Bash (.bashrc)\",\n false,\n )? {\n config_files_updated.push(bashrc_path.display().to_string());\n bash_updated_by_sps = true;\n if bash_profile_path.exists() {\n ensure_profile_sources_rc(&bash_profile_path, &bashrc_path, \"Bash (.bash_profile)\");\n } else if profile_path.exists() {\n ensure_profile_sources_rc(&profile_path, &bashrc_path, \"Bash (.profile)\");\n } else {\n debug!(\"Neither .bash_profile nor .profile found. Creating .bash_profile to source .bashrc.\");\n ensure_profile_sources_rc(&bash_profile_path, &bashrc_path, \"Bash (.bash_profile)\");\n }\n } else if update_shell_config(\n &bash_profile_path,\n &sps_path_line_zsh_bash,\n &sps_bin_path_str,\n \"Bash (.bash_profile)\",\n false,\n )? {\n config_files_updated.push(bash_profile_path.display().to_string());\n bash_updated_by_sps = true;\n } else if update_shell_config(\n &profile_path,\n &sps_path_line_zsh_bash,\n &sps_bin_path_str,\n \"Bash (.profile)\",\n false,\n )? {\n config_files_updated.push(profile_path.display().to_string());\n bash_updated_by_sps = true;\n }\n\n if !bash_updated_by_sps\n && (line_exists_in_file(&bashrc_path, &sps_bin_path_str)?\n || line_exists_in_file(&bash_profile_path, &sps_bin_path_str)?\n || line_exists_in_file(&profile_path, &sps_bin_path_str)?)\n {\n path_seems_configured = true;\n }\n } else if shell_path_env.contains(\"fish\") {\n let fish_config_dir = home_dir.join(\".config/fish\");\n if !fish_config_dir.exists() {\n if let Err(e) = fs::create_dir_all(&fish_config_dir) {\n warn!(\n \"Could not create Fish config directory {}: {}\",\n fish_config_dir.display(),\n e\n );\n }\n }\n if fish_config_dir.exists() {\n let fish_config_path = fish_config_dir.join(\"config.fish\");\n if update_shell_config(\n &fish_config_path,\n &sps_path_line_fish,\n &sps_bin_path_str,\n \"Fish\",\n true,\n )? {\n config_files_updated.push(fish_config_path.display().to_string());\n } else if line_exists_in_file(&fish_config_path, &sps_bin_path_str)? {\n path_seems_configured = true;\n }\n }\n } else {\n warn!(\n \"Unsupported shell for automatic PATH configuration: {}. Please add {} to your PATH manually.\",\n shell_path_env, sps_bin_path_str\n );\n print_manual_path_instructions(&sps_bin_path_str);\n return Ok(());\n }\n\n if !config_files_updated.is_empty() {\n println!(\n \"{} {} has been added to your PATH by modifying: {}\",\n \"sps\".cyan(),\n sps_bin_path_str.cyan(),\n config_files_updated.join(\", \").white()\n );\n println!(\n \"{}\",\n \"Please open a new terminal session or source your shell configuration file for the changes to take effect.\"\n .yellow()\n );\n if shell_path_env.contains(\"zsh\") {\n println!(\" Run: {}\", \"source ~/.zshrc\".green());\n }\n if shell_path_env.contains(\"bash\") {\n println!(\n \" Run: {} (or {} or {})\",\n \"source ~/.bashrc\".green(),\n \"source ~/.bash_profile\".green(),\n \"source ~/.profile\".green()\n );\n }\n if shell_path_env.contains(\"fish\") {\n println!(\n \" Run (usually not needed for fish_add_path, but won't hurt): {}\",\n \"source ~/.config/fish/config.fish\".green()\n );\n }\n } else if path_seems_configured {\n debug!(\"sps path ({}) is likely already configured for your shell ({}). No configuration files were modified.\", sps_bin_path_str.cyan(), shell_path_env.yellow());\n } else if !shell_path_env.is_empty() && shell_path_env != \"unknown\" {\n warn!(\"Could not automatically update PATH for your shell: {}. Please add {} to your PATH manually.\", shell_path_env.yellow(), sps_bin_path_str.cyan());\n print_manual_path_instructions(&sps_bin_path_str);\n }\n Ok(())\n}\n\n// print_manual_path_instructions helper (no change from your existing logic)\nfn print_manual_path_instructions(sps_bin_path_str: &str) {\n println!(\"\\n{} To use sps commands and installed packages directly, please add the following line to your shell configuration file:\", \"Action Required:\".yellow().bold());\n println!(\" (e.g., ~/.zshrc, ~/.bashrc, ~/.config/fish/config.fish)\");\n println!(\"\\n For Zsh or Bash:\");\n println!(\n \" {}\",\n format!(\"export PATH=\\\"{sps_bin_path_str}:$PATH\\\"\").green()\n );\n println!(\"\\n For Fish shell:\");\n println!(\n \" {}\",\n format!(\"fish_add_path -P \\\"{sps_bin_path_str}\\\"\").green()\n );\n println!(\n \"\\nThen, open a new terminal or run: {}\",\n \"source \".green()\n );\n}\n\n// line_exists_in_file helper (no change from your existing logic)\nfn line_exists_in_file(file_path: &Path, sps_bin_path_str: &str) -> SpsResult {\n if !file_path.exists() {\n return Ok(false);\n }\n let file = File::open(file_path).map_err(|e| SpsError::Io(Arc::new(e)))?;\n let reader = BufReader::new(file);\n let escaped_sps_bin_path = regex::escape(sps_bin_path_str);\n // Regex to find lines that configure PATH, trying to be robust for different shells\n // It looks for lines that set PATH or fish_user_paths and include the sps_bin_path_str\n // while trying to avoid commented out lines.\n let pattern = format!(\n r#\"(?m)^\\s*[^#]*\\b(?:PATH\\s*=|export\\s+PATH\\s*=|set\\s*(?:-gx\\s*|-U\\s*)?\\s*fish_user_paths\\b|fish_add_path\\s*(?:-P\\s*|-p\\s*)?)?[\"']?.*{escaped_sps_bin_path}.*[\"']?\"#\n );\n let search_pattern_regex = regex::Regex::new(&pattern)\n .map_err(|e| SpsError::Generic(format!(\"Failed to compile regex for PATH check: {e}\")))?;\n\n for line_result in reader.lines() {\n let line = line_result.map_err(|e| SpsError::Io(Arc::new(e)))?;\n if search_pattern_regex.is_match(&line) {\n debug!(\n \"Found sps PATH ({}) in {}: {}\",\n sps_bin_path_str,\n file_path.display(),\n line.trim()\n );\n return Ok(true);\n }\n }\n Ok(false)\n}\n\n// update_shell_config helper (no change from your existing logic)\nfn update_shell_config(\n config_path: &PathBuf,\n line_to_add: &str,\n sps_bin_path_str: &str,\n shell_name_for_log: &str,\n is_fish_shell: bool,\n) -> SpsResult {\n let sps_comment_tag_start = \"# SPS Path Management Start\";\n let sps_comment_tag_end = \"# SPS Path Management End\";\n\n if config_path.exists() {\n match line_exists_in_file(config_path, sps_bin_path_str) {\n Ok(true) => {\n debug!(\n \"sps path ({}) already configured or managed in {} ({}). Skipping modification.\",\n sps_bin_path_str,\n config_path.display(),\n shell_name_for_log\n );\n return Ok(false); // Path already seems configured\n }\n Ok(false) => { /* Proceed to add */ }\n Err(e) => {\n warn!(\n \"Could not reliably check existing configuration in {} ({}): {}. Attempting to add PATH.\",\n config_path.display(),\n shell_name_for_log,\n e\n );\n // Proceed with caution, might add duplicate if check failed but line exists\n }\n }\n }\n\n debug!(\n \"Adding sps PATH to {} ({})\",\n config_path.display(),\n shell_name_for_log\n );\n\n // Ensure parent directory exists\n if let Some(parent_dir) = config_path.parent() {\n if !parent_dir.exists() {\n fs::create_dir_all(parent_dir).map_err(|e| {\n SpsError::Io(Arc::new(std::io::Error::new(\n e.kind(),\n format!(\n \"Failed to create parent directory {}: {}\",\n parent_dir.display(),\n e\n ),\n )))\n })?;\n }\n }\n\n let mut file = OpenOptions::new()\n .append(true)\n .create(true)\n .open(config_path)\n .map_err(|e| {\n let msg = format!(\n \"Could not open/create shell config {} ({}): {}. Please add {} to your PATH manually.\",\n config_path.display(), shell_name_for_log, e, sps_bin_path_str\n );\n error!(\"{}\", msg);\n SpsError::Io(Arc::new(std::io::Error::new(e.kind(), msg)))\n })?;\n\n // Construct the block to add, ensuring it's idempotent for fish\n let block_to_add = if is_fish_shell {\n format!(\n \"\\n{sps_comment_tag_start}\\n# Add sps to PATH if not already present\\nif not contains \\\"{sps_bin_path_str}\\\" $fish_user_paths\\n {line_to_add}\\nend\\n{sps_comment_tag_end}\\n\"\n )\n } else {\n format!(\"\\n{sps_comment_tag_start}\\n{line_to_add}\\n{sps_comment_tag_end}\\n\")\n };\n\n if let Err(e) = writeln!(file, \"{block_to_add}\") {\n warn!(\n \"Failed to write to shell config {} ({}): {}\",\n config_path.display(),\n shell_name_for_log,\n e\n );\n Ok(false) // Indicate that update was not successful\n } else {\n debug!(\n \"Successfully updated {} ({}) with sps PATH.\",\n config_path.display(),\n shell_name_for_log\n );\n Ok(true) // Indicate successful update\n }\n}\n\n// ensure_profile_sources_rc helper (no change from your existing logic)\nfn ensure_profile_sources_rc(profile_path: &PathBuf, rc_path: &Path, shell_name_for_log: &str) {\n let rc_path_str = rc_path.to_string_lossy();\n // Regex to check if the profile file already sources the rc file.\n // Looks for lines like:\n // . /path/to/.bashrc\n // source /path/to/.bashrc\n // [ -f /path/to/.bashrc ] && . /path/to/.bashrc (and similar variants)\n let source_check_pattern = format!(\n r#\"(?m)^\\s*[^#]*(\\.|source|\\bsource\\b)\\s+[\"']?{}[\"']?\"#, /* More general source command\n * matching */\n regex::escape(&rc_path_str)\n );\n let source_check_regex = match regex::Regex::new(&source_check_pattern) {\n Ok(re) => re,\n Err(e) => {\n warn!(\"Failed to compile regex for sourcing check: {}. Skipping ensure_profile_sources_rc for {}\", e, profile_path.display());\n return;\n }\n };\n\n if profile_path.exists() {\n match fs::read_to_string(profile_path) {\n Ok(existing_content) => {\n if source_check_regex.is_match(&existing_content) {\n debug!(\n \"{} ({}) already sources {}.\",\n profile_path.display(),\n shell_name_for_log,\n rc_path.display()\n );\n return; // Already configured\n }\n }\n Err(e) => {\n warn!(\n \"Could not read {} to check if it sources {}: {}. Will attempt to append.\",\n profile_path.display(),\n rc_path.display(),\n e\n );\n }\n }\n }\n\n // Block to add to .bash_profile or .profile to source .bashrc\n let source_block_to_add = format!(\n \"\\n# Source {rc_filename} if it exists and is readable\\nif [ -f \\\"{rc_path_str}\\\" ] && [ -r \\\"{rc_path_str}\\\" ]; then\\n . \\\"{rc_path_str}\\\"\\nfi\\n\",\n rc_filename = rc_path.file_name().unwrap_or_default().to_string_lossy(),\n rc_path_str = rc_path_str\n );\n\n debug!(\n \"Attempting to ensure {} ({}) sources {}\",\n profile_path.display(),\n shell_name_for_log,\n rc_path.display()\n );\n\n if let Some(parent_dir) = profile_path.parent() {\n if !parent_dir.exists() {\n if let Err(e) = fs::create_dir_all(parent_dir) {\n warn!(\n \"Failed to create parent directory for {}: {}\",\n profile_path.display(),\n e\n );\n return; // Cannot proceed if parent dir creation fails\n }\n }\n }\n\n match OpenOptions::new()\n .append(true)\n .create(true)\n .open(profile_path)\n {\n Ok(mut file) => {\n if let Err(e) = writeln!(file, \"{source_block_to_add}\") {\n warn!(\n \"Failed to write to {} ({}): {}\",\n profile_path.display(),\n shell_name_for_log,\n e\n );\n } else {\n debug!(\n \"Updated {} ({}) to source {}.\",\n profile_path.display(),\n shell_name_for_log,\n rc_path.display()\n );\n }\n }\n Err(e) => {\n warn!(\n \"Could not open or create {} ({}) for updating: {}\",\n profile_path.display(),\n shell_name_for_log,\n e\n );\n }\n }\n}\n"], ["/sps/sps-common/src/dependency/resolver.rs", "// sps-common/src/dependency/resolver.rs\nuse std::collections::{HashMap, HashSet, VecDeque};\nuse std::path::{Path, PathBuf};\nuse std::sync::Arc;\n\nuse tracing::{debug, error, warn};\n\nuse crate::dependency::{Dependency, DependencyTag};\nuse crate::error::{Result, SpsError};\nuse crate::formulary::Formulary;\nuse crate::keg::KegRegistry;\nuse crate::model::formula::Formula;\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq)]\npub enum NodeInstallStrategy {\n BottlePreferred,\n SourceOnly,\n BottleOrFail,\n}\n\n#[derive(Debug, Clone, Default)]\npub struct PerTargetInstallPreferences {\n pub force_source_build_targets: HashSet,\n pub force_bottle_only_targets: HashSet,\n}\n\npub struct ResolutionContext<'a> {\n pub formulary: &'a Formulary,\n pub keg_registry: &'a KegRegistry,\n pub sps_prefix: &'a Path,\n pub include_optional: bool,\n pub include_test: bool,\n pub skip_recommended: bool,\n pub initial_target_preferences: &'a PerTargetInstallPreferences,\n pub build_all_from_source: bool,\n pub cascade_source_preference_to_dependencies: bool,\n pub has_bottle_for_current_platform: fn(&Formula) -> bool,\n pub initial_target_actions: &'a HashMap,\n}\n\n#[derive(Debug, Clone)]\npub struct ResolvedDependency {\n pub formula: Arc,\n pub keg_path: Option,\n pub opt_path: Option,\n pub status: ResolutionStatus,\n pub accumulated_tags: DependencyTag,\n pub determined_install_strategy: NodeInstallStrategy,\n pub failure_reason: Option,\n}\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq)]\npub enum ResolutionStatus {\n Installed,\n Missing,\n Requested,\n SkippedOptional,\n NotFound,\n Failed,\n}\n\n#[derive(Debug, Clone, Default)]\npub struct ResolvedGraph {\n pub install_plan: Vec,\n pub build_dependency_opt_paths: Vec,\n pub runtime_dependency_opt_paths: Vec,\n pub resolution_details: HashMap,\n}\n\n// Added empty constructor\nimpl ResolvedGraph {\n pub fn empty() -> Self {\n Default::default()\n }\n}\n\npub struct DependencyResolver<'a> {\n context: ResolutionContext<'a>,\n formula_cache: HashMap>,\n visiting: HashSet,\n resolution_details: HashMap,\n errors: HashMap>,\n}\n\nimpl<'a> DependencyResolver<'a> {\n pub fn new(context: ResolutionContext<'a>) -> Self {\n Self {\n context,\n formula_cache: HashMap::new(),\n visiting: HashSet::new(),\n resolution_details: HashMap::new(),\n errors: HashMap::new(),\n }\n }\n\n fn determine_node_install_strategy(\n &self,\n formula_name: &str,\n formula_arc: &Arc,\n is_initial_target: bool,\n requesting_parent_strategy: Option,\n ) -> NodeInstallStrategy {\n if is_initial_target {\n if self\n .context\n .initial_target_preferences\n .force_source_build_targets\n .contains(formula_name)\n {\n return NodeInstallStrategy::SourceOnly;\n }\n if self\n .context\n .initial_target_preferences\n .force_bottle_only_targets\n .contains(formula_name)\n {\n return NodeInstallStrategy::BottleOrFail;\n }\n }\n\n if self.context.build_all_from_source {\n return NodeInstallStrategy::SourceOnly;\n }\n\n if self.context.cascade_source_preference_to_dependencies\n && matches!(\n requesting_parent_strategy,\n Some(NodeInstallStrategy::SourceOnly)\n )\n {\n return NodeInstallStrategy::SourceOnly;\n }\n if matches!(\n requesting_parent_strategy,\n Some(NodeInstallStrategy::BottleOrFail)\n ) {\n return NodeInstallStrategy::BottleOrFail;\n }\n\n let strategy = if (self.context.has_bottle_for_current_platform)(formula_arc) {\n NodeInstallStrategy::BottlePreferred\n } else {\n NodeInstallStrategy::SourceOnly\n };\n\n debug!(\n \"Install strategy for '{formula_name}': {:?} (initial_target={is_initial_target}, parent={:?}, bottle_available={})\",\n strategy,\n requesting_parent_strategy,\n (self.context.has_bottle_for_current_platform)(formula_arc)\n );\n strategy\n }\n\n pub fn resolve_targets(&mut self, targets: &[String]) -> Result {\n debug!(\"Starting dependency resolution for targets: {:?}\", targets);\n self.visiting.clear();\n self.resolution_details.clear();\n self.errors.clear();\n\n for target_name in targets {\n if let Err(e) = self.resolve_recursive(target_name, DependencyTag::RUNTIME, true, None)\n {\n self.errors.insert(target_name.clone(), Arc::new(e));\n warn!(\n \"Resolution failed for target '{}', but continuing for others.\",\n target_name\n );\n }\n }\n\n debug!(\n \"Raw resolved map after initial pass: {:?}\",\n self.resolution_details\n .iter()\n .map(|(k, v)| (k.clone(), v.status, v.accumulated_tags))\n .collect::>()\n );\n\n let sorted_list = match self.topological_sort() {\n Ok(list) => list,\n Err(e @ SpsError::DependencyError(_)) => {\n error!(\"Topological sort failed due to dependency cycle: {}\", e);\n return Err(e);\n }\n Err(e) => {\n error!(\"Topological sort failed: {}\", e);\n return Err(e);\n }\n };\n\n let install_plan: Vec = sorted_list\n .into_iter()\n .filter(|dep| {\n matches!(\n dep.status,\n ResolutionStatus::Missing | ResolutionStatus::Requested\n )\n })\n .collect();\n\n let mut build_paths = Vec::new();\n let mut runtime_paths = Vec::new();\n let mut seen_build_paths = HashSet::new();\n let mut seen_runtime_paths = HashSet::new();\n\n for dep in self.resolution_details.values() {\n if matches!(\n dep.status,\n ResolutionStatus::Installed\n | ResolutionStatus::Requested\n | ResolutionStatus::Missing\n ) {\n if let Some(opt_path) = &dep.opt_path {\n if dep.accumulated_tags.contains(DependencyTag::BUILD)\n && seen_build_paths.insert(opt_path.clone())\n {\n debug!(\"Adding build dep path: {}\", opt_path.display());\n build_paths.push(opt_path.clone());\n }\n if dep.accumulated_tags.intersects(\n DependencyTag::RUNTIME\n | DependencyTag::RECOMMENDED\n | DependencyTag::OPTIONAL,\n ) && seen_runtime_paths.insert(opt_path.clone())\n {\n debug!(\"Adding runtime dep path: {}\", opt_path.display());\n runtime_paths.push(opt_path.clone());\n }\n } else if dep.status != ResolutionStatus::NotFound\n && dep.status != ResolutionStatus::Failed\n {\n debug!(\n \"Warning: No opt_path found for resolved dependency {} ({:?})\",\n dep.formula.name(),\n dep.status\n );\n }\n }\n }\n\n if !self.errors.is_empty() {\n warn!(\n \"Resolution encountered errors for specific targets: {:?}\",\n self.errors\n .iter()\n .map(|(k, v)| (k, v.to_string()))\n .collect::>()\n );\n }\n\n debug!(\n \"Final installation plan (needs install/build): {:?}\",\n install_plan\n .iter()\n .map(|d| (d.formula.name(), d.status))\n .collect::>()\n );\n debug!(\n \"Collected build dependency paths: {:?}\",\n build_paths.iter().map(|p| p.display()).collect::>()\n );\n debug!(\n \"Collected runtime dependency paths: {:?}\",\n runtime_paths\n .iter()\n .map(|p| p.display())\n .collect::>()\n );\n\n Ok(ResolvedGraph {\n install_plan,\n build_dependency_opt_paths: build_paths,\n runtime_dependency_opt_paths: runtime_paths,\n resolution_details: self.resolution_details.clone(),\n })\n }\n\n fn update_existing_resolution(\n &mut self,\n name: &str,\n tags_from_parent_edge: DependencyTag,\n is_initial_target: bool,\n ) -> Result {\n let Some(existing) = self.resolution_details.get_mut(name) else {\n return Ok(false);\n };\n\n let original_status = existing.status;\n let original_tags = existing.accumulated_tags;\n let has_keg = existing.keg_path.is_some();\n\n let mut new_status = original_status;\n if is_initial_target && new_status == ResolutionStatus::Missing {\n new_status = ResolutionStatus::Requested;\n }\n\n let skip_recommended = self.context.skip_recommended;\n let include_optional = self.context.include_optional;\n\n if Self::should_upgrade_optional_status_static(\n new_status,\n tags_from_parent_edge,\n is_initial_target,\n has_keg,\n skip_recommended,\n include_optional,\n ) {\n new_status = if has_keg {\n ResolutionStatus::Installed\n } else if is_initial_target {\n ResolutionStatus::Requested\n } else {\n ResolutionStatus::Missing\n };\n }\n\n let mut needs_revisit = false;\n if new_status != original_status {\n debug!(\n \"Updating status for '{name}' from {:?} to {:?}\",\n original_status, new_status\n );\n existing.status = new_status;\n needs_revisit = true;\n }\n\n let combined_tags = original_tags | tags_from_parent_edge;\n if combined_tags != original_tags {\n debug!(\n \"Updating tags for '{name}' from {:?} to {:?}\",\n original_tags, combined_tags\n );\n existing.accumulated_tags = combined_tags;\n needs_revisit = true;\n }\n\n if !needs_revisit {\n debug!(\"'{}' already resolved with compatible status/tags.\", name);\n } else {\n debug!(\n \"Re-evaluating dependencies for '{}' due to status/tag update\",\n name\n );\n }\n\n Ok(needs_revisit)\n }\n\n fn should_upgrade_optional_status_static(\n current_status: ResolutionStatus,\n tags_from_parent_edge: DependencyTag,\n is_initial_target: bool,\n _has_keg: bool,\n skip_recommended: bool,\n include_optional: bool,\n ) -> bool {\n current_status == ResolutionStatus::SkippedOptional\n && (tags_from_parent_edge.contains(DependencyTag::RUNTIME)\n || tags_from_parent_edge.contains(DependencyTag::BUILD)\n || (tags_from_parent_edge.contains(DependencyTag::RECOMMENDED)\n && !skip_recommended)\n || (is_initial_target && include_optional))\n }\n\n fn load_or_cache_formula(\n &mut self,\n name: &str,\n tags_from_parent_edge: DependencyTag,\n ) -> Result>> {\n if let Some(f) = self.formula_cache.get(name) {\n return Ok(Some(f.clone()));\n }\n\n debug!(\"Loading formula definition for '{}'\", name);\n match self.context.formulary.load_formula(name) {\n Ok(f) => {\n let arc = Arc::new(f);\n self.formula_cache.insert(name.to_string(), arc.clone());\n Ok(Some(arc))\n }\n Err(e) => {\n error!(\"Failed to load formula definition for '{}': {}\", name, e);\n let msg = e.to_string();\n self.resolution_details.insert(\n name.to_string(),\n ResolvedDependency {\n formula: Arc::new(Formula::placeholder(name)),\n keg_path: None,\n opt_path: None,\n status: ResolutionStatus::NotFound,\n accumulated_tags: tags_from_parent_edge,\n determined_install_strategy: NodeInstallStrategy::BottlePreferred,\n failure_reason: Some(msg.clone()),\n },\n );\n self.errors\n .insert(name.to_string(), Arc::new(SpsError::NotFound(msg)));\n Ok(None)\n }\n }\n }\n\n fn create_initial_resolution(\n &mut self,\n name: &str,\n formula_arc: Arc,\n tags_from_parent_edge: DependencyTag,\n is_initial_target: bool,\n requesting_parent_strategy: Option,\n ) -> Result<()> {\n let current_node_strategy = self.determine_node_install_strategy(\n name,\n &formula_arc,\n is_initial_target,\n requesting_parent_strategy,\n );\n\n let (status, keg_path) =\n self.determine_resolution_status(name, is_initial_target, current_node_strategy)?;\n\n debug!(\n \"Initial status for '{}': {:?}, keg: {:?}, opt: {}\",\n name,\n status,\n keg_path,\n self.context.keg_registry.get_opt_path(name).display()\n );\n\n self.resolution_details.insert(\n name.to_string(),\n ResolvedDependency {\n formula: formula_arc.clone(),\n keg_path,\n opt_path: Some(self.context.keg_registry.get_opt_path(name)),\n status,\n accumulated_tags: tags_from_parent_edge,\n determined_install_strategy: current_node_strategy,\n failure_reason: None,\n },\n );\n\n Ok(())\n }\n\n fn determine_resolution_status(\n &self,\n name: &str,\n is_initial_target: bool,\n strategy: NodeInstallStrategy,\n ) -> Result<(ResolutionStatus, Option)> {\n match strategy {\n NodeInstallStrategy::SourceOnly => Ok((\n if is_initial_target {\n ResolutionStatus::Requested\n } else {\n ResolutionStatus::Missing\n },\n None,\n )),\n NodeInstallStrategy::BottlePreferred | NodeInstallStrategy::BottleOrFail => {\n if let Some(keg) = self.context.keg_registry.get_installed_keg(name)? {\n // Check if this is an upgrade target - if so, mark as Requested even if\n // installed\n let should_request_upgrade = is_initial_target\n && self\n .context\n .initial_target_actions\n .get(name)\n .map(|action| {\n matches!(action, crate::pipeline::JobAction::Upgrade { .. })\n })\n .unwrap_or(false);\n\n debug!(\"[Resolver] Package '{}': is_initial_target={}, should_request_upgrade={}, action={:?}\",\n name, is_initial_target, should_request_upgrade,\n self.context.initial_target_actions.get(name));\n\n if should_request_upgrade {\n debug!(\n \"[Resolver] Marking upgrade target '{}' as Requested (was installed)\",\n name\n );\n Ok((ResolutionStatus::Requested, Some(keg.path)))\n } else {\n debug!(\"[Resolver] Marking '{}' as Installed (normal case)\", name);\n Ok((ResolutionStatus::Installed, Some(keg.path)))\n }\n } else {\n debug!(\n \"[Resolver] Package '{}' not installed, marking as {}\",\n name,\n if is_initial_target {\n \"Requested\"\n } else {\n \"Missing\"\n }\n );\n Ok((\n if is_initial_target {\n ResolutionStatus::Requested\n } else {\n ResolutionStatus::Missing\n },\n None,\n ))\n }\n }\n }\n }\n\n fn process_dependencies(\n &mut self,\n dep_snapshot: &ResolvedDependency,\n parent_name: &str,\n ) -> Result<()> {\n for dep in dep_snapshot.formula.dependencies()? {\n let dep_name = &dep.name;\n let dep_tags = dep.tags;\n let parent_formula_name = dep_snapshot.formula.name();\n let parent_strategy = dep_snapshot.determined_install_strategy;\n\n debug!(\n \"RESOLVER: Evaluating edge: parent='{}' ({:?}), child='{}' ({:?})\",\n parent_formula_name, parent_strategy, dep_name, dep_tags\n );\n\n if !self.should_consider_dependency(&dep) {\n if !self.resolution_details.contains_key(dep_name.as_str()) {\n debug!(\"RESOLVER: Child '{}' of '{}' globally SKIPPED (e.g. optional/test not included). Tags: {:?}\", dep_name, parent_formula_name, dep_tags);\n }\n continue;\n }\n\n let should_process = self.context.should_process_dependency_edge(\n &dep_snapshot.formula,\n dep_tags,\n parent_strategy,\n );\n\n if !should_process {\n debug!(\n \"RESOLVER: Edge from '{}' (Strategy: {:?}) to child '{}' (Tags: {:?}) was SKIPPED by should_process_dependency_edge.\",\n parent_formula_name, parent_strategy, dep_name, dep_tags\n );\n continue;\n }\n\n debug!(\n \"RESOLVER: Edge from '{}' (Strategy: {:?}) to child '{}' (Tags: {:?}) WILL BE PROCESSED. Recursing.\",\n parent_formula_name, parent_strategy, dep_name, dep_tags\n );\n\n if let Err(e) = self.resolve_recursive(dep_name, dep_tags, false, Some(parent_strategy))\n {\n // Log the error but don't necessarily stop all resolution for this branch yet\n warn!(\n \"Error resolving child dependency '{}' for parent '{}': {}\",\n dep_name, parent_name, e\n );\n // Optionally, mark parent as failed if child error is critical\n // self.errors.insert(parent_name.to_string(), Arc::new(e)); // Storing error for\n // parent if needed\n }\n }\n Ok(())\n }\n\n fn resolve_recursive(\n &mut self,\n name: &str,\n tags_from_parent_edge: DependencyTag,\n is_initial_target: bool,\n requesting_parent_strategy: Option,\n ) -> Result<()> {\n debug!(\n \"Resolving: {} (requested as {:?}, is_target: {})\",\n name, tags_from_parent_edge, is_initial_target\n );\n\n if self.visiting.contains(name) {\n error!(\"Dependency cycle detected involving: {}\", name);\n return Err(SpsError::DependencyError(format!(\n \"Dependency cycle detected involving '{name}'\"\n )));\n }\n\n if self.update_existing_resolution(name, tags_from_parent_edge, is_initial_target)? {\n // Already exists and was updated, no need to reprocess\n return Ok(());\n }\n\n if self.resolution_details.contains_key(name) {\n // Already exists but didn't need update\n return Ok(());\n }\n\n // New resolution needed\n self.visiting.insert(name.to_string());\n\n let formula_arc = match self.load_or_cache_formula(name, tags_from_parent_edge) {\n Ok(Some(formula)) => formula,\n Ok(None) => {\n self.visiting.remove(name);\n return Ok(()); // Already handled error case\n }\n Err(e) => {\n self.visiting.remove(name);\n return Err(e);\n }\n };\n\n self.create_initial_resolution(\n name,\n formula_arc,\n tags_from_parent_edge,\n is_initial_target,\n requesting_parent_strategy,\n )?;\n\n let dep_snapshot = self\n .resolution_details\n .get(name)\n .expect(\"just inserted\")\n .clone();\n\n if matches!(\n dep_snapshot.status,\n ResolutionStatus::Failed | ResolutionStatus::NotFound\n ) {\n self.visiting.remove(name);\n return Ok(());\n }\n\n self.process_dependencies(&dep_snapshot, name)?;\n\n self.visiting.remove(name);\n debug!(\"Finished resolving '{}'\", name);\n Ok(())\n }\n\n fn topological_sort(&self) -> Result> {\n let mut in_degree: HashMap = HashMap::new();\n let mut adj: HashMap> = HashMap::new();\n let mut sorted_list = Vec::new();\n let mut queue = VecDeque::new();\n\n let relevant_nodes_map: HashMap = self\n .resolution_details\n .iter()\n .filter(|(_, dep)| {\n !matches!(\n dep.status,\n ResolutionStatus::NotFound | ResolutionStatus::Failed\n )\n })\n .map(|(k, v)| (k.clone(), v))\n .collect();\n\n for (parent_name, parent_rd) in &relevant_nodes_map {\n adj.entry(parent_name.clone()).or_default();\n in_degree.entry(parent_name.clone()).or_default();\n\n let parent_strategy = parent_rd.determined_install_strategy;\n if let Ok(dependencies) = parent_rd.formula.dependencies() {\n for child_edge in dependencies {\n let child_name = &child_edge.name;\n if relevant_nodes_map.contains_key(child_name)\n && self.context.should_process_dependency_edge(\n &parent_rd.formula,\n child_edge.tags,\n parent_strategy,\n )\n && adj\n .entry(parent_name.clone())\n .or_default()\n .insert(child_name.clone())\n {\n *in_degree.entry(child_name.clone()).or_default() += 1;\n }\n }\n }\n }\n\n for name in relevant_nodes_map.keys() {\n if *in_degree.get(name).unwrap_or(&1) == 0 {\n queue.push_back(name.clone());\n }\n }\n\n while let Some(u_name) = queue.pop_front() {\n if let Some(resolved_dep) = relevant_nodes_map.get(&u_name) {\n sorted_list.push((**resolved_dep).clone()); // Deref Arc then clone\n // ResolvedDependency\n }\n if let Some(neighbors) = adj.get(&u_name) {\n for v_name in neighbors {\n if relevant_nodes_map.contains_key(v_name) {\n // Check if neighbor is relevant\n if let Some(degree) = in_degree.get_mut(v_name) {\n *degree = degree.saturating_sub(1);\n if *degree == 0 {\n queue.push_back(v_name.clone());\n }\n }\n }\n }\n }\n }\n\n // Check for cycles: if sorted_list's length doesn't match relevant_nodes_map's length\n // (excluding already installed, skipped optional if not included, etc.)\n // A more direct check is if in_degree still contains non-zero values for relevant nodes.\n let mut cycle_detected = false;\n for (name, °ree) in &in_degree {\n if degree > 0 && relevant_nodes_map.contains_key(name) {\n // Further check if this node should have been processed (not skipped globally)\n if let Some(detail) = self.resolution_details.get(name) {\n if self\n .context\n .should_consider_edge_globally(detail.accumulated_tags)\n {\n error!(\"Cycle detected or unresolved dependency: Node '{}' still has in-degree {}. Tags: {:?}\", name, degree, detail.accumulated_tags);\n cycle_detected = true;\n } else {\n debug!(\"Node '{}' has in-degree {} but was globally skipped. Tags: {:?}. Not a cycle error.\", name, degree, detail.accumulated_tags);\n }\n }\n }\n }\n\n if cycle_detected {\n return Err(SpsError::DependencyError(\n \"Circular dependency detected or graph resolution incomplete\".to_string(),\n ));\n }\n\n Ok(sorted_list) // Return the full sorted list of relevant nodes\n }\n\n fn should_consider_dependency(&self, dep: &Dependency) -> bool {\n let tags = dep.tags;\n if tags.contains(DependencyTag::TEST) && !self.context.include_test {\n return false;\n }\n if tags.contains(DependencyTag::OPTIONAL) && !self.context.include_optional {\n return false;\n }\n if tags.contains(DependencyTag::RECOMMENDED) && self.context.skip_recommended {\n return false;\n }\n true\n }\n}\n\nimpl Formula {\n fn placeholder(name: &str) -> Self {\n Self {\n name: name.to_string(),\n stable_version_str: \"0.0.0\".to_string(),\n version_semver: semver::Version::new(0, 0, 0), // Direct use\n revision: 0,\n desc: Some(\"Placeholder for unresolved formula\".to_string()),\n homepage: None,\n url: String::new(),\n sha256: String::new(),\n mirrors: Vec::new(),\n bottle: Default::default(),\n dependencies: Vec::new(),\n requirements: Vec::new(),\n resources: Vec::new(),\n install_keg_path: None,\n }\n }\n}\n\nimpl<'a> ResolutionContext<'a> {\n pub fn should_process_dependency_edge(\n &self,\n parent_formula_for_logging: &Arc,\n edge_tags: DependencyTag,\n parent_node_determined_strategy: NodeInstallStrategy,\n ) -> bool {\n if !self.should_consider_edge_globally(edge_tags) {\n debug!(\n \"Edge with tags {:?} for child of '{}' globally SKIPPED (e.g. optional/test not included).\",\n edge_tags, parent_formula_for_logging.name()\n );\n return false;\n }\n\n match parent_node_determined_strategy {\n NodeInstallStrategy::BottlePreferred | NodeInstallStrategy::BottleOrFail => {\n let is_purely_build_dependency = edge_tags.contains(DependencyTag::BUILD)\n && !edge_tags.intersects(\n DependencyTag::RUNTIME\n | DependencyTag::RECOMMENDED\n | DependencyTag::OPTIONAL,\n );\n if is_purely_build_dependency {\n debug!(\"Edge with tags {:?} SKIPPED: Pure BUILD dependency of a bottle-installed parent '{}'.\", edge_tags, parent_formula_for_logging.name());\n return false;\n }\n }\n NodeInstallStrategy::SourceOnly => {\n // Process all relevant (non-globally-skipped) dependencies for source builds\n }\n }\n debug!(\n \"Edge with tags {:?} WILL BE PROCESSED for parent '{}' (strategy {:?}).\",\n edge_tags,\n parent_formula_for_logging.name(),\n parent_node_determined_strategy\n );\n true\n }\n\n pub fn should_consider_edge_globally(&self, edge_tags: DependencyTag) -> bool {\n if edge_tags.contains(DependencyTag::TEST) && !self.include_test {\n return false;\n }\n if edge_tags.contains(DependencyTag::OPTIONAL) && !self.include_optional {\n return false;\n }\n if edge_tags.contains(DependencyTag::RECOMMENDED) && self.skip_recommended {\n return false;\n }\n true\n }\n}\n"], ["/sps/sps/src/pipeline/runner.rs", "// sps/src/pipeline/runner.rs\nuse std::collections::{HashMap, HashSet};\nuse std::sync::atomic::{AtomicUsize, Ordering};\nuse std::sync::{Arc, Mutex};\nuse std::time::Instant;\n\nuse colored::Colorize;\nuse crossbeam_channel::bounded as crossbeam_bounded;\nuse reqwest::Client as HttpClient;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::dependency::resolver::{ResolutionStatus, ResolvedGraph};\nuse sps_common::error::{Result as SpsResult, SpsError};\nuse sps_common::model::InstallTargetIdentifier;\nuse sps_common::pipeline::{\n DownloadOutcome, JobProcessingState, PipelineEvent, PlannedJob,\n PlannedOperations as PlannerOutputCommon, WorkerJob,\n};\nuse tokio::sync::{broadcast, mpsc};\nuse tokio::task::JoinHandle;\nuse tracing::{debug, error, instrument, warn};\n\nuse super::downloader::DownloadCoordinator;\nuse super::planner::OperationPlanner;\n\nconst WORKER_JOB_CHANNEL_SIZE: usize = 100;\nconst EVENT_CHANNEL_SIZE: usize = 100;\nconst DOWNLOAD_OUTCOME_CHANNEL_SIZE: usize = 100;\n\n#[derive(Debug, Clone, PartialEq, Eq)]\npub enum CommandType {\n Install,\n Reinstall,\n Upgrade { all: bool },\n}\n\n#[derive(Debug, Clone)]\npub struct PipelineFlags {\n pub build_from_source: bool,\n pub include_optional: bool,\n pub skip_recommended: bool,\n}\n\nstruct PropagationContext {\n all_planned_jobs: Arc>,\n job_states: Arc>>,\n resolved_graph: Arc,\n event_tx: Option>,\n final_fail_count: Arc,\n}\n\nfn err_to_string(e: &SpsError) -> String {\n e.to_string()\n}\n\npub(crate) fn get_panic_message(e: Box) -> String {\n match e.downcast_ref::<&'static str>() {\n Some(s) => (*s).to_string(),\n None => match e.downcast_ref::() {\n Some(s) => s.clone(),\n None => \"Unknown panic payload\".to_string(),\n },\n }\n}\n\n#[instrument(skip_all, fields(cmd = ?command_type, targets = ?initial_targets))]\npub async fn run_pipeline(\n initial_targets: &[String],\n command_type: CommandType,\n config: &Config,\n cache: Arc,\n flags: &PipelineFlags,\n) -> SpsResult<()> {\n debug!(\n \"Pipeline run initiated for targets: {:?}, command: {:?}\",\n initial_targets, command_type\n );\n let start_time = Instant::now();\n let final_success_count = Arc::new(AtomicUsize::new(0));\n let final_fail_count = Arc::new(AtomicUsize::new(0));\n\n debug!(\n \"Creating broadcast channel for pipeline events (EVENT_CHANNEL_SIZE={})\",\n EVENT_CHANNEL_SIZE\n );\n let (event_tx, mut event_rx_for_runner) =\n broadcast::channel::(EVENT_CHANNEL_SIZE);\n\n debug!(\"Cloning event_tx for runner_event_tx_clone\");\n let runner_event_tx_clone = event_tx.clone();\n\n debug!(\n \"Creating crossbeam worker job channel (WORKER_JOB_CHANNEL_SIZE={})\",\n WORKER_JOB_CHANNEL_SIZE\n );\n let (worker_job_tx, worker_job_rx_for_core) =\n crossbeam_bounded::(WORKER_JOB_CHANNEL_SIZE);\n\n debug!(\"Cloning event_tx for core_event_tx_for_worker_manager\");\n let core_config = config.clone();\n let core_cache_clone = cache.clone();\n let core_event_tx_for_worker_manager = event_tx.clone();\n let core_success_count_clone = Arc::clone(&final_success_count);\n let core_fail_count_clone = Arc::clone(&final_fail_count);\n debug!(\"Spawning core worker pool manager thread.\");\n let core_handle = std::thread::spawn(move || {\n debug!(\"CORE_THREAD: Core worker pool manager thread started.\");\n let result = sps_core::pipeline::engine::start_worker_pool_manager(\n core_config,\n core_cache_clone,\n worker_job_rx_for_core,\n core_event_tx_for_worker_manager,\n core_success_count_clone,\n core_fail_count_clone,\n );\n debug!(\n \"CORE_THREAD: Core worker pool manager thread finished. Result: {:?}\",\n result.is_ok()\n );\n result\n });\n\n debug!(\"Subscribing to event_tx for status_event_rx\");\n let status_config = config.clone();\n let status_event_rx = event_tx.subscribe();\n debug!(\"Spawning status handler task.\");\n let status_handle = tokio::spawn(crate::cli::status::handle_events(\n status_config,\n status_event_rx,\n ));\n\n debug!(\n \"Creating mpsc download_outcome channel (DOWNLOAD_OUTCOME_CHANNEL_SIZE={})\",\n DOWNLOAD_OUTCOME_CHANNEL_SIZE\n );\n let (download_outcome_tx, mut download_outcome_rx) =\n mpsc::channel::(DOWNLOAD_OUTCOME_CHANNEL_SIZE);\n\n debug!(\"Initializing pipeline planning phase...\");\n let planner_output: PlannerOutputCommon;\n {\n debug!(\"Cloning runner_event_tx_clone for planner_event_tx_clone\");\n let planner_event_tx_clone = runner_event_tx_clone.clone();\n debug!(\"Creating OperationPlanner.\");\n let operation_planner =\n OperationPlanner::new(config, cache.clone(), flags, planner_event_tx_clone);\n\n debug!(\"Calling plan_operations...\");\n match operation_planner\n .plan_operations(initial_targets, command_type.clone())\n .await\n {\n Ok(ops) => {\n debug!(\"plan_operations returned Ok.\");\n planner_output = ops;\n }\n Err(e) => {\n error!(\"Fatal planning error: {}\", e);\n runner_event_tx_clone\n .send(PipelineEvent::LogError {\n message: format!(\"Fatal planning error: {e}\"),\n })\n .ok();\n drop(worker_job_tx);\n if let Err(join_err) = core_handle.join() {\n error!(\n \"Core thread join error after planning failure: {:?}\",\n get_panic_message(join_err)\n );\n }\n let duration = start_time.elapsed();\n runner_event_tx_clone\n .send(PipelineEvent::PipelineFinished {\n duration_secs: duration.as_secs_f64(),\n success_count: 0,\n fail_count: initial_targets.len(),\n })\n .ok();\n\n debug!(\"Dropping runner_event_tx_clone due to planning error.\");\n drop(runner_event_tx_clone);\n debug!(\"Dropping main event_tx due to planning error.\");\n drop(event_tx);\n\n debug!(\"Awaiting status_handle after planning error.\");\n if let Err(join_err) = status_handle.await {\n error!(\n \"Status task join error after planning failure: {}\",\n join_err\n );\n }\n return Err(e);\n }\n }\n debug!(\"OperationPlanner scope ended, planner_event_tx_clone dropped.\");\n }\n\n let planned_jobs = Arc::new(planner_output.jobs);\n let resolved_graph = planner_output.resolved_graph.clone()\n .unwrap_or_else(|| {\n tracing::debug!(\"ResolvedGraph was None in planner output. Using a default empty graph. This is expected if no formulae required resolution or if planner reported errors for all formulae.\");\n Arc::new(sps_common::dependency::resolver::ResolvedGraph::default())\n });\n\n debug!(\n \"Planning finished. Total jobs in plan: {}.\",\n planned_jobs.len()\n );\n runner_event_tx_clone\n .send(PipelineEvent::PlanningFinished {\n job_count: planned_jobs.len(),\n })\n .ok();\n\n // Mark jobs with planner errors as failed and emit error events\n let job_processing_states = Arc::new(Mutex::new(HashMap::::new()));\n let mut jobs_pending_or_active = 0;\n let mut initial_fail_count_from_planner = 0;\n {\n let mut states_guard = job_processing_states.lock().unwrap();\n if !planner_output.errors.is_empty() {\n tracing::debug!(\n \"[Runner] Planner reported {} error(s). These targets will be marked as failed.\",\n planner_output.errors.len()\n );\n for (target_name, error) in &planner_output.errors {\n let msg = format!(\"✗ {}: {}\", target_name.cyan(), error);\n runner_event_tx_clone\n .send(PipelineEvent::LogError { message: msg })\n .ok();\n states_guard.insert(\n target_name.clone(),\n JobProcessingState::Failed(Arc::new(error.clone())),\n );\n initial_fail_count_from_planner += 1;\n }\n }\n for job in planned_jobs.iter() {\n if states_guard.contains_key(&job.target_id) {\n continue;\n }\n if planner_output\n .already_installed_or_up_to_date\n .contains(&job.target_id)\n {\n states_guard.insert(job.target_id.clone(), JobProcessingState::Succeeded);\n final_success_count.fetch_add(1, Ordering::Relaxed);\n debug!(\n \"[{}] Marked as Succeeded (pre-existing/up-to-date).\",\n job.target_id\n );\n } else if let Some((_, err)) = planner_output\n .errors\n .iter()\n .find(|(name, _)| name == &job.target_id)\n {\n states_guard.insert(\n job.target_id.clone(),\n JobProcessingState::Failed(Arc::new(err.clone())),\n );\n // Counted in initial_fail_count_from_planner\n debug!(\n \"[{}] Marked as Failed (planning error: {}).\",\n job.target_id, err\n );\n } else if job.use_private_store_source.is_some() {\n let path = job.use_private_store_source.clone().unwrap();\n states_guard.insert(\n job.target_id.clone(),\n JobProcessingState::Downloaded(path.clone()),\n );\n jobs_pending_or_active += 1;\n debug!(\n \"[{}] Initial state: Downloaded (private store: {}). Active jobs: {}\",\n job.target_id,\n path.display(),\n jobs_pending_or_active\n );\n } else {\n states_guard.insert(job.target_id.clone(), JobProcessingState::PendingDownload);\n jobs_pending_or_active += 1;\n debug!(\n \"[{}] Initial state: PendingDownload. Active jobs: {}\",\n job.target_id, jobs_pending_or_active\n );\n }\n }\n }\n debug!(\n \"Initial job states populated. Jobs pending/active: {}\",\n jobs_pending_or_active\n );\n\n let mut downloads_to_initiate = Vec::new();\n {\n let states_guard = job_processing_states.lock().unwrap();\n for job in planned_jobs.iter() {\n if matches!(\n states_guard.get(&job.target_id),\n Some(JobProcessingState::PendingDownload)\n ) {\n downloads_to_initiate.push(job.clone());\n }\n }\n }\n\n let mut download_coordinator_task_handle: Option>> = None;\n\n if !downloads_to_initiate.is_empty() {\n debug!(\"Cloning runner_event_tx_clone for download_coordinator_event_tx_clone\");\n let download_coordinator_event_tx_clone = runner_event_tx_clone.clone();\n let http_client = Arc::new(HttpClient::new());\n let config_for_downloader_owned = config.clone();\n\n let mut download_coordinator = DownloadCoordinator::new(\n config_for_downloader_owned,\n cache.clone(),\n http_client,\n download_coordinator_event_tx_clone,\n );\n debug!(\n \"Starting download coordination for {} jobs...\",\n downloads_to_initiate.len()\n );\n debug!(\"Cloning download_outcome_tx for tx_for_download_task\");\n let tx_for_download_task = download_outcome_tx.clone();\n\n debug!(\"Spawning DownloadCoordinator task.\");\n download_coordinator_task_handle = Some(tokio::spawn(async move {\n debug!(\"DOWNLOAD_COORD_TASK: DownloadCoordinator task started.\");\n let result = download_coordinator\n .coordinate_downloads(downloads_to_initiate, tx_for_download_task)\n .await;\n debug!(\"DOWNLOAD_COORD_TASK: DownloadCoordinator task finished. coordinate_downloads returned.\");\n result\n }));\n } else if jobs_pending_or_active > 0 {\n debug!(\n \"No downloads to initiate, but {} jobs are pending. Triggering check_and_dispatch.\",\n jobs_pending_or_active\n );\n check_and_dispatch(\n planned_jobs.clone(),\n job_processing_states.clone(),\n resolved_graph.clone(),\n &worker_job_tx,\n runner_event_tx_clone.clone(),\n config,\n flags,\n );\n } else {\n debug!(\"No downloads to initiate and no jobs pending/active. Pipeline might be empty or all pre-satisfied/failed.\");\n }\n\n drop(download_outcome_tx);\n debug!(\"Dropped main MPSC download_outcome_tx (runner's original clone).\");\n\n if !planned_jobs.is_empty() {\n runner_event_tx_clone\n .send(PipelineEvent::PipelineStarted {\n total_jobs: planned_jobs.len(),\n })\n .ok();\n }\n\n let mut propagation_ctx = PropagationContext {\n all_planned_jobs: planned_jobs.clone(),\n job_states: job_processing_states.clone(),\n resolved_graph: resolved_graph.clone(),\n event_tx: Some(runner_event_tx_clone.clone()),\n final_fail_count: final_fail_count.clone(),\n };\n\n debug!(\n \"Entering main event loop. Jobs pending/active: {}\",\n jobs_pending_or_active\n );\n\n // Robust main loop: continue while there are jobs pending/active, or downloads, or jobs in\n // states that could be dispatched\n fn has_pending_dispatchable_jobs(\n states_guard: &std::sync::MutexGuard>,\n ) -> bool {\n states_guard.values().any(|state| {\n matches!(\n state,\n JobProcessingState::Downloaded(_) | JobProcessingState::WaitingForDependencies(_)\n )\n })\n }\n\n while jobs_pending_or_active > 0\n || has_pending_dispatchable_jobs(&job_processing_states.lock().unwrap())\n {\n tokio::select! {\n biased;\n Some(download_outcome) = download_outcome_rx.recv() => {\n debug!(\"Received DownloadOutcome for '{}'.\", download_outcome.planned_job.target_id);\n process_download_outcome(\n download_outcome,\n &propagation_ctx,\n &mut jobs_pending_or_active,\n );\n debug!(\"After process_download_outcome, jobs_pending_or_active: {}. Triggering check_and_dispatch.\", jobs_pending_or_active);\n check_and_dispatch(\n planned_jobs.clone(),\n job_processing_states.clone(),\n resolved_graph.clone(),\n &worker_job_tx,\n runner_event_tx_clone.clone(),\n config,\n flags,\n );\n }\n Ok(event) = event_rx_for_runner.recv() => {\n match event {\n PipelineEvent::JobSuccess { ref target_id, .. } => {\n debug!(\"Received JobSuccess for '{}'.\", target_id);\n process_core_worker_feedback(\n target_id.clone(),\n true,\n None,\n job_processing_states.clone(),\n &mut jobs_pending_or_active,\n );\n debug!(\"After JobSuccess for '{}', jobs_pending_or_active: {}. Triggering check_and_dispatch.\", target_id, jobs_pending_or_active);\n check_and_dispatch(\n planned_jobs.clone(),\n job_processing_states.clone(),\n resolved_graph.clone(),\n &worker_job_tx,\n runner_event_tx_clone.clone(),\n config,\n flags,\n );\n }\n PipelineEvent::JobFailed { ref target_id, ref error, ref action } => {\n debug!(\"Received JobFailed for '{}' (Action: {:?}, Error: {}).\", target_id, action, error);\n process_core_worker_feedback(\n target_id.clone(),\n false,\n Some(SpsError::Generic(error.clone())),\n job_processing_states.clone(),\n &mut jobs_pending_or_active,\n );\n debug!(\"After JobFailed for '{}', jobs_pending_or_active: {}. Triggering failure propagation.\", target_id, jobs_pending_or_active);\n propagate_failure(\n target_id,\n Arc::new(SpsError::Generic(format!(\"Core worker failed for {target_id}: {error}\"))),\n &propagation_ctx,\n &mut jobs_pending_or_active,\n );\n check_and_dispatch(\n planned_jobs.clone(),\n job_processing_states.clone(),\n resolved_graph.clone(),\n &worker_job_tx,\n runner_event_tx_clone.clone(),\n config,\n flags,\n );\n }\n _ => {}\n }\n }\n else => {\n debug!(\"Main select loop 'else' branch. jobs_pending_or_active = {}. download_outcome_rx or event_rx_for_runner might be closed.\", jobs_pending_or_active);\n if jobs_pending_or_active > 0 || has_pending_dispatchable_jobs(&job_processing_states.lock().unwrap()) {\n warn!(\"Exiting main loop prematurely but still have {} jobs pending/active or dispatchable. This might indicate a stall or logic error.\", jobs_pending_or_active);\n }\n break;\n }\n }\n debug!(\n \"End of select! loop iteration. Jobs pending/active: {}\",\n jobs_pending_or_active\n );\n }\n debug!(\n \"Main event loop finished. Final jobs_pending_or_active: {}\",\n jobs_pending_or_active\n );\n\n drop(download_outcome_rx);\n debug!(\"Dropped MPSC download_outcome_rx (runner's receiver).\");\n\n if let Some(handle) = download_coordinator_task_handle {\n debug!(\"Waiting for DownloadCoordinator task to complete...\");\n match handle.await {\n Ok(critical_download_errors) => {\n if !critical_download_errors.is_empty() {\n warn!(\n \"DownloadCoordinator task reported critical errors: {:?}\",\n critical_download_errors\n );\n final_fail_count.fetch_add(critical_download_errors.len(), Ordering::Relaxed);\n }\n debug!(\"DownloadCoordinator task completed.\");\n }\n Err(e) => {\n let panic_msg = get_panic_message(Box::new(e));\n error!(\n \"DownloadCoordinator task panicked or failed to join: {}\",\n panic_msg\n );\n final_fail_count.fetch_add(1, Ordering::Relaxed);\n }\n }\n } else {\n debug!(\"No DownloadCoordinator task was spawned or it was already handled.\");\n }\n debug!(\"DownloadCoordinator task processing finished (awaited or none).\");\n\n debug!(\"Closing worker job channel (signal to core workers).\");\n drop(worker_job_tx);\n debug!(\"Waiting for core worker pool to join...\");\n match core_handle.join() {\n Ok(Ok(())) => debug!(\"Core worker pool manager thread completed successfully.\"),\n Ok(Err(e)) => {\n error!(\"Core worker pool manager thread failed: {}\", e);\n final_fail_count.fetch_add(1, Ordering::Relaxed);\n }\n Err(e) => {\n error!(\n \"Core worker pool manager thread panicked: {:?}\",\n get_panic_message(e)\n );\n final_fail_count.fetch_add(1, Ordering::Relaxed);\n }\n }\n debug!(\"Core worker pool joined. core_event_tx_for_worker_manager (broadcast sender) dropped.\");\n\n let duration = start_time.elapsed();\n let success_total = final_success_count.load(Ordering::Relaxed);\n let fail_total = final_fail_count.load(Ordering::Relaxed) + initial_fail_count_from_planner;\n\n debug!(\n \"Pipeline processing finished. Success: {}, Fail: {}. Duration: {:.2}s. Sending PipelineFinished event.\",\n success_total, fail_total, duration.as_secs_f64()\n );\n if let Err(e) = runner_event_tx_clone.send(PipelineEvent::PipelineFinished {\n duration_secs: duration.as_secs_f64(),\n success_count: success_total,\n fail_count: fail_total,\n }) {\n warn!(\n \"Failed to send PipelineFinished event: {:?}. Status handler might not receive it.\",\n e\n );\n }\n\n // Explicitly drop the event_tx inside propagation_ctx before dropping the last senders.\n propagation_ctx.event_tx = None;\n\n debug!(\"Dropping runner_event_tx_clone (broadcast sender).\");\n drop(runner_event_tx_clone);\n // event_rx_for_runner (broadcast receiver) goes out of scope here and is dropped.\n\n debug!(\"Dropping main event_tx (final broadcast sender).\");\n drop(event_tx);\n\n debug!(\"All known broadcast senders dropped. About to await status_handle.\");\n if let Err(e) = status_handle.await {\n warn!(\"Status handler task failed or panicked: {}\", e);\n } else {\n debug!(\"Status handler task completed successfully.\");\n }\n debug!(\"run_pipeline function is ending.\");\n\n if fail_total == 0 {\n Ok(())\n } else {\n let mut accumulated_errors = Vec::new();\n for (name, err_obj) in planner_output.errors {\n accumulated_errors.push(format!(\"Planning for '{name}': {err_obj}\"));\n }\n let states_guard = job_processing_states.lock().unwrap();\n for job in planned_jobs.iter() {\n if let Some(JobProcessingState::Failed(err_arc)) = states_guard.get(&job.target_id) {\n let err_str = err_to_string(err_arc);\n let job_err_msg = format!(\"Processing '{}': {}\", job.target_id, err_str);\n if !accumulated_errors.contains(&job_err_msg) {\n accumulated_errors.push(job_err_msg);\n }\n }\n }\n drop(states_guard);\n\n let specific_error_msg = if accumulated_errors.is_empty() {\n \"No specific errors logged, check core worker logs.\".to_string()\n } else {\n accumulated_errors.join(\"; \")\n };\n\n // Error details are already sent via PipelineEvent::JobFailed events\n // and will be displayed in status.rs\n Err(SpsError::InstallError(format!(\n \"Operation failed with {fail_total} total failure(s). Details: [{specific_error_msg}] (Worker errors are included in total)\"\n )))\n }\n}\n\nfn process_download_outcome(\n outcome: DownloadOutcome,\n propagation_ctx: &PropagationContext,\n jobs_pending_or_active: &mut usize,\n) {\n let job_id = outcome.planned_job.target_id.clone();\n let mut states_guard = propagation_ctx.job_states.lock().unwrap();\n\n match states_guard.get(&job_id) {\n Some(JobProcessingState::Succeeded) | Some(JobProcessingState::Failed(_)) => {\n debug!(\n \"[{}] DownloadOutcome: Job already in terminal state {:?}. Ignoring outcome.\",\n job_id,\n states_guard.get(&job_id)\n );\n return;\n }\n _ => {}\n }\n\n match outcome.result {\n Ok(path) => {\n debug!(\n \"[{}] DownloadOutcome: Success. Path: {}. Updating state to Downloaded.\",\n job_id,\n path.display()\n );\n states_guard.insert(job_id.clone(), JobProcessingState::Downloaded(path));\n }\n Err(e) => {\n warn!(\n \"[{}] DownloadOutcome: Failed. Error: {}. Updating state to Failed.\",\n job_id, e\n );\n let error_arc = Arc::new(e);\n states_guard.insert(\n job_id.clone(),\n JobProcessingState::Failed(error_arc.clone()),\n );\n\n if let Some(ref tx) = propagation_ctx.event_tx {\n tx.send(PipelineEvent::job_failed(\n job_id.clone(),\n outcome.planned_job.action.clone(),\n &error_arc,\n ))\n .ok();\n }\n propagation_ctx\n .final_fail_count\n .fetch_add(1, Ordering::Relaxed);\n\n if *jobs_pending_or_active > 0 {\n *jobs_pending_or_active -= 1;\n debug!(\"[{}] DownloadOutcome: Decremented jobs_pending_or_active to {} due to download failure.\", job_id, *jobs_pending_or_active);\n } else {\n warn!(\"[{}] DownloadOutcome: jobs_pending_or_active is already 0, cannot decrement for download failure.\", job_id);\n }\n\n drop(states_guard);\n debug!(\"[{}] DownloadOutcome: Propagating failure.\", job_id);\n propagate_failure(&job_id, error_arc, propagation_ctx, jobs_pending_or_active);\n }\n }\n}\n\nfn process_core_worker_feedback(\n target_id: String,\n success: bool,\n error: Option,\n job_states: Arc>>,\n jobs_pending_or_active: &mut usize,\n) {\n let mut states_guard = job_states.lock().unwrap();\n\n match states_guard.get(&target_id) {\n Some(JobProcessingState::Succeeded) | Some(JobProcessingState::Failed(_)) => {\n debug!(\"[{}] CoreFeedback: Job already in terminal state {:?}. Ignoring active job count update.\", target_id, states_guard.get(&target_id));\n return;\n }\n _ => {}\n }\n\n if success {\n debug!(\n \"[{}] CoreFeedback: Success. Updating state to Succeeded.\",\n target_id\n );\n states_guard.insert(target_id.clone(), JobProcessingState::Succeeded);\n } else {\n let err_msg = error.as_ref().map_or_else(\n || \"Unknown core worker error\".to_string(),\n |e| e.to_string(),\n );\n debug!(\n \"[{}] CoreFeedback: Failed. Error: {}. Updating state to Failed.\",\n target_id, err_msg\n );\n let err_arc = Arc::new(\n error.unwrap_or_else(|| SpsError::Generic(\"Unknown core worker error\".into())),\n );\n states_guard.insert(target_id.clone(), JobProcessingState::Failed(err_arc));\n }\n\n if *jobs_pending_or_active > 0 {\n *jobs_pending_or_active -= 1;\n debug!(\n \"[{}] CoreFeedback: Decremented jobs_pending_or_active to {}.\",\n target_id, *jobs_pending_or_active\n );\n } else {\n warn!(\n \"[{}] CoreFeedback: jobs_pending_or_active is already 0, cannot decrement.\",\n target_id\n );\n }\n}\n\nfn check_and_dispatch(\n planned_jobs_arc: Arc>,\n job_states: Arc>>,\n resolved_graph: Arc,\n worker_job_tx: &crossbeam_channel::Sender,\n event_tx: broadcast::Sender,\n config: &Config,\n flags: &PipelineFlags,\n) {\n debug!(\"--- Enter check_and_dispatch ---\");\n let mut states_guard = job_states.lock().unwrap();\n let mut dispatched_this_round = 0;\n\n for planned_job in planned_jobs_arc.iter() {\n let job_id = &planned_job.target_id;\n debug!(\"[{}] CheckDispatch: Evaluating job.\", job_id);\n\n let (current_state_is_dispatchable, path_for_dispatch) = {\n match states_guard.get(job_id) {\n Some(JobProcessingState::Downloaded(ref path)) => {\n debug!(\"[{}] CheckDispatch: Current state is Downloaded.\", job_id);\n (true, Some(path.clone()))\n }\n Some(JobProcessingState::WaitingForDependencies(ref path)) => {\n debug!(\n \"[{}] CheckDispatch: Current state is WaitingForDependencies.\",\n job_id\n );\n (true, Some(path.clone()))\n }\n other_state => {\n debug!(\n \"[{}] CheckDispatch: Not in a dispatchable state. Current state: {:?}.\",\n job_id,\n other_state.map(|s| format!(\"{s:?}\"))\n );\n (false, None)\n }\n }\n };\n\n if current_state_is_dispatchable {\n let path = path_for_dispatch.unwrap();\n drop(states_guard);\n debug!(\n \"[{}] CheckDispatch: Calling are_dependencies_succeeded.\",\n job_id\n );\n let dependencies_succeeded = are_dependencies_succeeded(\n job_id,\n &planned_job.target_definition,\n job_states.clone(),\n &resolved_graph,\n config,\n flags,\n );\n states_guard = job_states.lock().unwrap();\n debug!(\n \"[{}] CheckDispatch: are_dependencies_succeeded returned: {}.\",\n job_id, dependencies_succeeded\n );\n\n let current_state_after_dep_check = states_guard.get(job_id).cloned();\n if !matches!(\n current_state_after_dep_check,\n Some(JobProcessingState::Downloaded(_))\n | Some(JobProcessingState::WaitingForDependencies(_))\n ) {\n debug!(\"[{}] CheckDispatch: State changed to {:?} while checking dependencies. Skipping dispatch.\", job_id, current_state_after_dep_check);\n continue;\n }\n\n if dependencies_succeeded {\n debug!(\n \"[{}] CheckDispatch: All dependencies satisfied. Dispatching to core worker.\",\n job_id\n );\n let worker_job = WorkerJob {\n request: planned_job.clone(),\n download_path: path.clone(),\n download_size_bytes: std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0),\n is_source_from_private_store: planned_job.use_private_store_source.is_some(),\n };\n if worker_job_tx.send(worker_job).is_ok() {\n states_guard.insert(\n job_id.clone(),\n JobProcessingState::DispatchedToCore(path.clone()),\n );\n event_tx\n .send(PipelineEvent::JobDispatchedToCore {\n target_id: job_id.clone(),\n })\n .ok();\n dispatched_this_round += 1;\n debug!(\"[{}] CheckDispatch: Successfully dispatched.\", job_id);\n } else {\n error!(\"[{}] CheckDispatch: Failed to send job to worker channel (channel closed?). Marking as failed.\", job_id);\n let err = Arc::new(SpsError::Generic(\"Worker channel closed\".to_string()));\n if !matches!(\n states_guard.get(job_id),\n Some(JobProcessingState::Failed(_))\n ) {\n states_guard\n .insert(job_id.clone(), JobProcessingState::Failed(err.clone()));\n event_tx\n .send(PipelineEvent::job_failed(\n job_id.clone(),\n planned_job.action.clone(),\n &err,\n ))\n .ok();\n }\n }\n } else if matches!(\n current_state_after_dep_check,\n Some(JobProcessingState::Downloaded(_))\n ) {\n debug!(\"[{}] CheckDispatch: Dependencies not met. Updating state to WaitingForDependencies.\", job_id);\n states_guard.insert(\n job_id.clone(),\n JobProcessingState::WaitingForDependencies(path.clone()),\n );\n } else {\n debug!(\n \"[{}] CheckDispatch: Dependencies not met. State remains {:?}.\",\n job_id, current_state_after_dep_check\n );\n }\n }\n }\n if dispatched_this_round > 0 {\n debug!(\n \"Dispatched {} jobs to core workers in this round.\",\n dispatched_this_round\n );\n }\n debug!(\"--- Exit check_and_dispatch ---\");\n}\n\nfn are_dependencies_succeeded(\n target_id: &str,\n target_def: &InstallTargetIdentifier,\n job_states_arc: Arc>>,\n resolved_graph: &ResolvedGraph,\n config: &Config,\n flags: &PipelineFlags,\n) -> bool {\n debug!(\"[{}] AreDepsSucceeded: Checking dependencies...\", target_id);\n let dependencies_to_check: Vec = match target_def {\n InstallTargetIdentifier::Formula(formula_arc) => {\n if let Some(resolved_dep_info) =\n resolved_graph.resolution_details.get(formula_arc.name())\n {\n let parent_strategy = resolved_dep_info.determined_install_strategy;\n let empty_actions = std::collections::HashMap::new();\n let context = sps_common::dependency::ResolutionContext {\n formulary: &sps_common::formulary::Formulary::new(config.clone()),\n keg_registry: &sps_common::keg::KegRegistry::new(config.clone()),\n sps_prefix: config.sps_root(),\n include_optional: flags.include_optional,\n include_test: false,\n skip_recommended: flags.skip_recommended,\n initial_target_preferences: &Default::default(),\n build_all_from_source: flags.build_from_source,\n cascade_source_preference_to_dependencies: true,\n has_bottle_for_current_platform:\n sps_core::install::bottle::has_bottle_for_current_platform,\n initial_target_actions: &empty_actions,\n };\n\n let deps: Vec = formula_arc\n .dependencies()\n .unwrap_or_default()\n .iter()\n .filter(|dep_edge| {\n context.should_process_dependency_edge(\n formula_arc,\n dep_edge.tags,\n parent_strategy,\n )\n })\n .map(|dep_edge| dep_edge.name.clone())\n .collect();\n debug!(\n \"[{}] AreDepsSucceeded: Formula dependencies to check: {:?}\",\n target_id, deps\n );\n deps\n } else {\n warn!(\"[{}] AreDepsSucceeded: Formula not found in ResolvedGraph. Assuming no dependencies.\", target_id);\n Vec::new()\n }\n }\n InstallTargetIdentifier::Cask(cask_arc) => {\n let deps = if let Some(deps_on) = &cask_arc.depends_on {\n deps_on.formula.clone()\n } else {\n Vec::new()\n };\n debug!(\n \"[{}] AreDepsSucceeded: Cask formula dependencies to check: {:?}\",\n target_id, deps\n );\n deps\n }\n };\n\n if dependencies_to_check.is_empty() {\n debug!(\n \"[{}] AreDepsSucceeded: No dependencies to check. Returning true.\",\n target_id\n );\n return true;\n }\n\n let states_guard = job_states_arc.lock().unwrap();\n for dep_name in &dependencies_to_check {\n match states_guard.get(dep_name) {\n Some(JobProcessingState::Succeeded) => {\n debug!(\n \"[{}] AreDepsSucceeded: Dependency '{}' is Succeeded.\",\n target_id, dep_name\n );\n }\n Some(JobProcessingState::Failed(err)) => {\n debug!(\n \"[{}] AreDepsSucceeded: Dependency '{}' is FAILED ({}). Returning false.\",\n target_id,\n dep_name,\n err_to_string(err)\n );\n return false;\n }\n None => {\n if let Some(resolved_dep_detail) = resolved_graph.resolution_details.get(dep_name) {\n if resolved_dep_detail.status == ResolutionStatus::Installed {\n debug!(\"[{}] AreDepsSucceeded: Dependency '{}' is already installed (from ResolvedGraph).\", target_id, dep_name);\n } else {\n debug!(\"[{}] AreDepsSucceeded: Dependency '{}' has no active state and not ResolvedGraph::Installed (is {:?}). Returning false.\", target_id, dep_name, resolved_dep_detail.status);\n return false;\n }\n } else {\n warn!(\"[{}] AreDepsSucceeded: Dependency '{}' not found in job_states OR ResolvedGraph. Assuming not met. Returning false.\", target_id, dep_name);\n return false;\n }\n }\n other_state => {\n debug!(\"[{}] AreDepsSucceeded: Dependency '{}' is not yet Succeeded. Current state: {:?}. Returning false.\", target_id, dep_name, other_state.map(|s| format!(\"{s:?}\")));\n return false;\n }\n }\n }\n debug!(\n \"[{}] AreDepsSucceeded: All dependencies Succeeded or were pre-installed. Returning true.\",\n target_id\n );\n true\n}\n\nfn propagate_failure(\n failed_job_id: &str,\n failure_reason: Arc,\n ctx: &PropagationContext,\n jobs_pending_or_active: &mut usize,\n) {\n debug!(\n \"[{}] PropagateFailure: Starting for reason: {}\",\n failed_job_id, failure_reason\n );\n let mut dependents_to_fail_queue = vec![failed_job_id.to_string()];\n let mut newly_failed_dependents = HashSet::new();\n\n {\n let mut states_guard = ctx.job_states.lock().unwrap();\n if !matches!(\n states_guard.get(failed_job_id),\n Some(JobProcessingState::Failed(_))\n ) {\n states_guard.insert(\n failed_job_id.to_string(),\n JobProcessingState::Failed(failure_reason.clone()),\n );\n }\n }\n\n let mut current_idx = 0;\n while current_idx < dependents_to_fail_queue.len() {\n let current_source_of_failure = dependents_to_fail_queue[current_idx].clone();\n current_idx += 1;\n\n for job_to_check in ctx.all_planned_jobs.iter() {\n if job_to_check.target_id == failed_job_id\n || newly_failed_dependents.contains(&job_to_check.target_id)\n {\n continue;\n }\n\n let is_dependent = match &job_to_check.target_definition {\n InstallTargetIdentifier::Formula(formula_arc) => ctx\n .resolved_graph\n .resolution_details\n .get(formula_arc.name())\n .is_some_and(|res_dep_info| {\n res_dep_info\n .formula\n .dependencies()\n .unwrap_or_default()\n .iter()\n .any(|d| d.name == current_source_of_failure)\n }),\n InstallTargetIdentifier::Cask(cask_arc) => {\n cask_arc.depends_on.as_ref().is_some_and(|deps| {\n deps.formula.contains(¤t_source_of_failure)\n || deps.cask.contains(¤t_source_of_failure)\n })\n }\n };\n\n if is_dependent {\n let mut states_guard = ctx.job_states.lock().unwrap();\n let current_state_of_dependent = states_guard.get(&job_to_check.target_id).cloned();\n\n if !matches!(\n current_state_of_dependent,\n Some(JobProcessingState::Succeeded) | Some(JobProcessingState::Failed(_))\n ) {\n let propagated_error = Arc::new(SpsError::DependencyError(format!(\n \"Dependency '{}' failed: {}\",\n current_source_of_failure,\n err_to_string(&failure_reason)\n )));\n states_guard.insert(\n job_to_check.target_id.clone(),\n JobProcessingState::Failed(propagated_error.clone()),\n );\n\n if newly_failed_dependents.insert(job_to_check.target_id.clone()) {\n dependents_to_fail_queue.push(job_to_check.target_id.clone());\n ctx.final_fail_count.fetch_add(1, Ordering::Relaxed);\n\n if *jobs_pending_or_active > 0 {\n *jobs_pending_or_active -= 1;\n debug!(\"[{}] PropagateFailure: Decremented jobs_pending_or_active to {} for propagated failure.\", job_to_check.target_id, *jobs_pending_or_active);\n } else {\n warn!(\"[{}] PropagateFailure: jobs_pending_or_active is already 0, cannot decrement for propagated failure.\", job_to_check.target_id);\n }\n\n if let Some(ref tx) = ctx.event_tx {\n tx.send(PipelineEvent::job_failed(\n job_to_check.target_id.clone(),\n job_to_check.action.clone(),\n &propagated_error,\n ))\n .ok();\n }\n debug!(\"[{}] PropagateFailure: Marked as FAILED due to propagated failure from '{}'.\", job_to_check.target_id, current_source_of_failure);\n }\n }\n drop(states_guard);\n }\n }\n }\n\n if !newly_failed_dependents.is_empty() {\n debug!(\n \"[{}] PropagateFailure: Finished. Newly failed dependents: {:?}\",\n failed_job_id, newly_failed_dependents\n );\n } else {\n debug!(\n \"[{}] PropagateFailure: Finished. No new dependents marked as failed.\",\n failed_job_id\n );\n }\n}\n"], ["/sps/sps-core/src/install/bottle/mod.rs", "// ===== sps-core/src/build/formula/mod.rs =====\nuse std::fs::File;\nuse std::io::Write;\nuse std::path::{Path, PathBuf};\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::formula::Formula;\nuse tracing::{debug, error};\n\n// Declare submodules\npub mod exec;\npub mod link;\npub mod macho;\n\n/// Download formula resources from the internet asynchronously.\npub async fn download_formula(\n formula: &Formula,\n config: &Config,\n client: &reqwest::Client,\n) -> Result {\n if has_bottle_for_current_platform(formula) {\n exec::download_bottle(formula, config, client).await\n } else {\n Err(SpsError::Generic(format!(\n \"No bottle available for {} on this platform\",\n formula.name()\n )))\n }\n}\n\n/// Checks if a suitable bottle exists for the current platform, considering fallbacks.\npub fn has_bottle_for_current_platform(formula: &Formula) -> bool {\n let result = crate::install::bottle::exec::get_bottle_for_platform(formula);\n debug!(\n \"has_bottle_for_current_platform check for '{}': {:?}\",\n formula.name(),\n result.is_ok()\n );\n if let Err(e) = &result {\n debug!(\"Reason for no bottle: {}\", e);\n }\n result.is_ok()\n}\n\n// *** Updated get_current_platform function ***\nfn get_current_platform() -> String {\n if cfg!(target_os = \"macos\") {\n let arch = if std::env::consts::ARCH == \"aarch64\" {\n \"arm64\"\n } else if std::env::consts::ARCH == \"x86_64\" {\n \"x86_64\"\n } else {\n std::env::consts::ARCH\n };\n\n debug!(\"Attempting to determine macOS version using /usr/bin/sw_vers -productVersion\");\n match Command::new(\"/usr/bin/sw_vers\")\n .arg(\"-productVersion\")\n .output()\n {\n Ok(output) => {\n let stdout = String::from_utf8_lossy(&output.stdout);\n let stderr = String::from_utf8_lossy(&output.stderr);\n debug!(\"sw_vers status: {}\", output.status);\n if !output.status.success() || !stderr.trim().is_empty() {\n debug!(\"sw_vers stdout:\\n{}\", stdout);\n if !stderr.trim().is_empty() {\n debug!(\"sw_vers stderr:\\n{}\", stderr);\n }\n }\n\n if output.status.success() {\n let version_str = stdout.trim();\n if !version_str.is_empty() {\n debug!(\"Extracted version string: {}\", version_str);\n let os_name = match version_str.split('.').next() {\n Some(\"15\") => \"sequoia\",\n Some(\"14\") => \"sonoma\",\n Some(\"13\") => \"ventura\",\n Some(\"12\") => \"monterey\",\n Some(\"11\") => \"big_sur\",\n Some(\"10\") => match version_str.split('.').nth(1) {\n Some(\"15\") => \"catalina\",\n Some(\"14\") => \"mojave\",\n _ => {\n debug!(\n \"Unrecognized legacy macOS 10.x version: {}\",\n version_str\n );\n \"unknown_macos\"\n }\n },\n _ => {\n debug!(\"Unrecognized macOS major version: {}\", version_str);\n \"unknown_macos\"\n }\n };\n\n if os_name != \"unknown_macos\" {\n let platform_tag = if arch == \"arm64\" {\n format!(\"{arch}_{os_name}\")\n } else {\n os_name.to_string()\n };\n debug!(\"Determined platform tag: {}\", platform_tag);\n return platform_tag;\n }\n } else {\n error!(\"sw_vers -productVersion output was empty.\");\n }\n } else {\n error!(\n \"sw_vers -productVersion command failed with status: {}. Stderr: {}\",\n output.status,\n stderr.trim()\n );\n }\n }\n Err(e) => {\n error!(\"Failed to execute /usr/bin/sw_vers -productVersion: {}\", e);\n }\n }\n\n error!(\"!!! FAILED TO DETECT MACOS VERSION VIA SW_VERS !!!\");\n debug!(\"Using UNRELIABLE fallback platform detection. Bottle selection may be incorrect.\");\n if arch == \"arm64\" {\n debug!(\"Falling back to platform tag: arm64_monterey\");\n \"arm64_monterey\".to_string()\n } else {\n debug!(\"Falling back to platform tag: monterey\");\n \"monterey\".to_string()\n }\n } else if cfg!(target_os = \"linux\") {\n if std::env::consts::ARCH == \"aarch64\" {\n \"arm64_linux\".to_string()\n } else if std::env::consts::ARCH == \"x86_64\" {\n \"x86_64_linux\".to_string()\n } else {\n \"unknown\".to_string()\n }\n } else {\n debug!(\n \"Could not determine platform tag for OS: {}\",\n std::env::consts::OS\n );\n \"unknown\".to_string()\n }\n}\n\n// REMOVED: get_cellar_path (now in Config)\n\n// --- get_formula_cellar_path uses Config ---\n// Parameter changed from formula: &Formula to formula_name: &str\n// Parameter changed from config: &Config to cellar_path: &Path for consistency where Config isn't\n// fully available If Config *is* available, call config.formula_cellar_dir(formula.name()) instead.\n// **Keeping original signature for now where Config might not be easily passed**\npub fn get_formula_cellar_path(formula: &Formula, config: &Config) -> PathBuf {\n // Use Config method\n config.formula_cellar_dir(formula.name())\n}\n\n// --- write_receipt (unchanged) ---\npub fn write_receipt(\n formula: &Formula,\n install_dir: &Path,\n installation_type: &str, // \"bottle\" or \"source\"\n) -> Result<()> {\n let receipt_path = install_dir.join(\"INSTALL_RECEIPT.json\");\n let receipt_file = File::create(&receipt_path);\n let mut receipt_file = match receipt_file {\n Ok(file) => file,\n Err(e) => {\n error!(\n \"Failed to create receipt file at {}: {}\",\n receipt_path.display(),\n e\n );\n return Err(SpsError::Io(std::sync::Arc::new(e)));\n }\n };\n\n let resources_result = formula.resources();\n let resources_installed = match resources_result {\n Ok(res) => res.iter().map(|r| r.name.clone()).collect::>(),\n Err(_) => {\n debug!(\n \"Could not retrieve resources for formula {} when writing receipt.\",\n formula.name\n );\n vec![]\n }\n };\n\n let timestamp = chrono::Utc::now().to_rfc3339();\n\n let receipt = serde_json::json!({\n \"name\": formula.name, \"version\": formula.version_str_full(), \"time\": timestamp,\n \"source\": { \"type\": \"api\", \"url\": formula.url, },\n \"built_on\": {\n \"os\": std::env::consts::OS, \"arch\": std::env::consts::ARCH,\n \"platform_tag\": get_current_platform(),\n },\n \"installation_type\": installation_type,\n \"resources_installed\": resources_installed,\n });\n\n let receipt_json = match serde_json::to_string_pretty(&receipt) {\n Ok(json) => json,\n Err(e) => {\n error!(\n \"Failed to serialize receipt JSON for {}: {}\",\n formula.name, e\n );\n return Err(SpsError::Json(std::sync::Arc::new(e)));\n }\n };\n\n if let Err(e) = receipt_file.write_all(receipt_json.as_bytes()) {\n error!(\"Failed to write receipt file for {}: {}\", formula.name, e);\n return Err(SpsError::Io(std::sync::Arc::new(e)));\n }\n\n Ok(())\n}\n\n// --- Re-exports (unchanged) ---\npub use exec::install_bottle;\npub use link::link_formula_artifacts;\n"], ["/sps/sps-core/src/uninstall/cask.rs", "// sps-core/src/uninstall/cask.rs\nuse std::fs;\nuse std::path::{Path, PathBuf};\nuse std::process::{Command, Stdio};\n\nuse lazy_static::lazy_static;\nuse regex::Regex;\n// serde_json is used for CaskInstallManifest deserialization\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::{Cask, ZapActionDetail};\nuse tracing::{debug, error, warn};\nuse trash; // This will be used by trash_path\n\n// Import helpers from the common module within the uninstall scope\nuse super::common::{expand_tilde, is_safe_path, remove_filesystem_artifact};\nuse crate::check::installed::InstalledPackageInfo;\n// Corrected import path if install::cask::helpers is where it lives now\nuse crate::install::cask::helpers::{\n cleanup_empty_parent_dirs_in_private_store,\n remove_path_robustly as remove_path_robustly_from_install_helpers,\n};\nuse crate::install::cask::CaskInstallManifest;\n#[cfg(target_os = \"macos\")]\nuse crate::utils::applescript;\n\nlazy_static! {\n static ref VALID_PKGID_RE: Regex = Regex::new(r\"^[a-zA-Z0-9._-]+$\").unwrap();\n static ref VALID_LABEL_RE: Regex = Regex::new(r\"^[a-zA-Z0-9._-]+$\").unwrap();\n static ref VALID_SCRIPT_PATH_RE: Regex = Regex::new(r\"^[a-zA-Z0-9/._-]+$\").unwrap();\n static ref VALID_SIGNAL_RE: Regex = Regex::new(r\"^[A-Z0-9]+$\").unwrap();\n static ref VALID_BUNDLE_ID_RE: Regex =\n Regex::new(r\"^[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)+$\").unwrap();\n}\n\n/// Performs a \"soft\" uninstall for a Cask.\n/// It processes the `CASK_INSTALL_MANIFEST.json` to remove linked artifacts\n/// and then updates the manifest to mark the cask as not currently installed.\n/// The Cask's versioned directory in the Caskroom is NOT removed.\npub fn uninstall_cask_artifacts(info: &InstalledPackageInfo, config: &Config) -> Result<()> {\n debug!(\n \"Soft uninstalling Cask artifacts for {} version {}\",\n info.name, info.version\n );\n let manifest_path = info.path.join(\"CASK_INSTALL_MANIFEST.json\");\n let mut removal_errors: Vec = Vec::new();\n\n if manifest_path.is_file() {\n debug!(\n \"Processing manifest for soft uninstall: {}\",\n manifest_path.display()\n );\n match fs::read_to_string(&manifest_path) {\n Ok(manifest_str) => match serde_json::from_str::(&manifest_str) {\n Ok(mut manifest) => {\n if !manifest.is_installed {\n debug!(\"Cask {} version {} is already marked as uninstalled in manifest. Nothing to do for soft uninstall.\", info.name, info.version);\n return Ok(());\n }\n\n debug!(\n \"Soft uninstalling {} artifacts listed in manifest for {} {}...\",\n manifest.artifacts.len(),\n info.name,\n info.version\n );\n for artifact in manifest.artifacts.iter().rev() {\n if !process_artifact_uninstall_core(artifact, config, false) {\n removal_errors.push(format!(\"Failed to remove artifact: {artifact:?}\"));\n }\n }\n\n manifest.is_installed = false;\n match fs::File::create(&manifest_path) {\n Ok(file) => {\n let writer = std::io::BufWriter::new(file);\n if let Err(e) = serde_json::to_writer_pretty(writer, &manifest) {\n warn!(\n \"Failed to update manifest {}: {}\",\n manifest_path.display(),\n e\n );\n } else {\n debug!(\n \"Manifest updated successfully for soft uninstall: {}\",\n manifest_path.display()\n );\n }\n }\n Err(e) => {\n warn!(\n \"Failed to open manifest for writing (soft uninstall) at {}: {}\",\n manifest_path.display(),\n e\n );\n }\n }\n }\n Err(e) => warn!(\n \"Failed to parse cask manifest {}: {}. Cannot perform detailed soft uninstall.\",\n manifest_path.display(),\n e\n ),\n },\n Err(e) => warn!(\n \"Failed to read cask manifest {}: {}. Cannot perform detailed soft uninstall.\",\n manifest_path.display(),\n e\n ),\n }\n } else {\n warn!(\n \"No CASK_INSTALL_MANIFEST.json found in {}. Cannot perform detailed soft uninstall for {} {}.\",\n info.path.display(),\n info.name,\n info.version\n );\n }\n\n if removal_errors.is_empty() {\n Ok(())\n } else {\n Err(SpsError::InstallError(format!(\n \"Errors during cask artifact soft removal for {}: {}\",\n info.name,\n removal_errors.join(\"; \")\n )))\n }\n}\n\n/// Performs a \"zap\" uninstall for a Cask, removing files defined in `zap` stanzas\n/// and cleaning up the private store. Also marks the cask as uninstalled in its manifest.\npub async fn zap_cask_artifacts(\n info: &InstalledPackageInfo,\n cask_def: &Cask,\n config: &Config,\n) -> Result<()> {\n debug!(\"Starting ZAP process for cask: {}\", cask_def.token);\n let home = config.home_dir();\n let cask_version_path_in_caskroom = &info.path;\n let mut zap_errors: Vec = Vec::new();\n\n let mut primary_app_name_from_manifest: Option = None;\n let manifest_path = cask_version_path_in_caskroom.join(\"CASK_INSTALL_MANIFEST.json\");\n\n if manifest_path.is_file() {\n match fs::read_to_string(&manifest_path) {\n Ok(manifest_str) => match serde_json::from_str::(&manifest_str) {\n Ok(mut manifest) => {\n primary_app_name_from_manifest = manifest.primary_app_file_name.clone();\n if manifest.is_installed {\n manifest.is_installed = false;\n if let Ok(file) = fs::File::create(&manifest_path) {\n let writer = std::io::BufWriter::new(file);\n if let Err(e) = serde_json::to_writer_pretty(writer, &manifest) {\n warn!(\n \"Failed to update manifest during zap for {}: {}\",\n manifest_path.display(),\n e\n );\n }\n } else {\n warn!(\n \"Failed to open manifest for writing during zap at {}\",\n manifest_path.display()\n );\n }\n }\n }\n Err(e) => warn!(\n \"Failed to parse manifest during zap {}: {}\",\n manifest_path.display(),\n e\n ),\n },\n Err(e) => warn!(\n \"Failed to read manifest during zap {}: {}\",\n manifest_path.display(),\n e\n ),\n }\n } else {\n warn!(\"No manifest found at {} during zap. Private store cleanup might be incomplete if app name changed.\", manifest_path.display());\n }\n\n if !cleanup_private_store(\n &cask_def.token,\n &info.version,\n primary_app_name_from_manifest.as_deref(),\n config,\n ) {\n let msg = format!(\n \"Failed to clean up private store for cask {} version {}\",\n cask_def.token, info.version\n );\n warn!(\"{}\", msg);\n zap_errors.push(msg);\n }\n\n let zap_stanzas = match &cask_def.zap {\n Some(stanzas) => stanzas,\n None => {\n debug!(\"No zap stanza found for cask {}\", cask_def.token);\n // Proceed to Caskroom cleanup even if no specific zap actions\n if !remove_filesystem_artifact(cask_version_path_in_caskroom, true) {\n // use_sudo = true for Caskroom\n if cask_version_path_in_caskroom.exists() {\n zap_errors.push(format!(\n \"Failed to remove Caskroom version directory during zap: {}\",\n cask_version_path_in_caskroom.display()\n ));\n }\n }\n if let Some(parent_token_dir) = cask_version_path_in_caskroom.parent() {\n if parent_token_dir.exists() && parent_token_dir.is_dir() {\n match fs::read_dir(parent_token_dir) {\n Ok(mut entries) => {\n if entries.next().is_none()\n && !remove_filesystem_artifact(parent_token_dir, true)\n && parent_token_dir.exists()\n {\n warn!(\"Failed to remove empty Caskroom token directory during zap: {}\", parent_token_dir.display());\n }\n }\n Err(e) => warn!(\n \"Failed to read Caskroom token dir {} during zap: {}\",\n parent_token_dir.display(),\n e\n ),\n }\n }\n }\n return if zap_errors.is_empty() {\n Ok(())\n } else {\n Err(SpsError::Generic(zap_errors.join(\"; \")))\n };\n }\n };\n\n for stanza_map in zap_stanzas {\n for (action_key, action_detail) in &stanza_map.0 {\n debug!(\n \"Processing zap action: {} = {:?}\",\n action_key, action_detail\n );\n match action_detail {\n ZapActionDetail::Trash(paths) => {\n for path_str in paths {\n let target = expand_tilde(path_str, &home);\n if is_safe_path(&target, &home, config) {\n if !trash_path(&target) {\n // Logged within trash_path\n }\n } else {\n zap_errors\n .push(format!(\"Skipped unsafe trash path {}\", target.display()));\n }\n }\n }\n ZapActionDetail::Delete(paths) | ZapActionDetail::Rmdir(paths) => {\n for path_str in paths {\n let target = expand_tilde(path_str, &home);\n if is_safe_path(&target, &home, config) {\n let use_sudo = target.starts_with(\"/Library\")\n || target.starts_with(\"/Applications\");\n let exists_before =\n target.exists() || target.symlink_metadata().is_ok();\n if exists_before {\n if action_key == \"rmdir\" && !target.is_dir() {\n warn!(\"Zap rmdir target is not a directory: {}. Attempting as file delete.\", target.display());\n }\n if !remove_filesystem_artifact(&target, use_sudo)\n && (target.exists() || target.symlink_metadata().is_ok())\n {\n zap_errors.push(format!(\n \"Failed to {} {}\",\n action_key,\n target.display()\n ));\n }\n } else {\n debug!(\n \"Zap target {} not found, skipping removal.\",\n target.display()\n );\n }\n } else {\n zap_errors.push(format!(\n \"Skipped unsafe {} path {}\",\n action_key,\n target.display()\n ));\n }\n }\n }\n ZapActionDetail::Pkgutil(ids_sv) => {\n for id in ids_sv.clone().into_vec() {\n if !VALID_PKGID_RE.is_match(&id) {\n warn!(\"Invalid pkgutil ID format for zap: '{}'. Skipping.\", id);\n zap_errors.push(format!(\"Invalid pkgutil ID: {id}\"));\n continue;\n }\n if !forget_pkgutil_receipt(&id) {\n // Error logged in helper\n }\n }\n }\n ZapActionDetail::Launchctl(labels_sv) => {\n for label in labels_sv.clone().into_vec() {\n if !VALID_LABEL_RE.is_match(&label) {\n warn!(\n \"Invalid launchctl label format for zap: '{}'. Skipping.\",\n label\n );\n zap_errors.push(format!(\"Invalid launchctl label: {label}\"));\n continue;\n }\n let potential_paths = vec![\n home.join(\"Library/LaunchAgents\")\n .join(format!(\"{label}.plist\")),\n PathBuf::from(\"/Library/LaunchAgents\").join(format!(\"{label}.plist\")),\n PathBuf::from(\"/Library/LaunchDaemons\").join(format!(\"{label}.plist\")),\n ];\n let path_to_try = potential_paths.into_iter().find(|p| p.exists());\n if !unload_and_remove_launchd(&label, path_to_try.as_deref()) {\n // Error logged in helper\n }\n }\n }\n ZapActionDetail::Script { executable, args } => {\n let script_path_str = executable;\n if !VALID_SCRIPT_PATH_RE.is_match(script_path_str) {\n error!(\n \"Zap script path contains invalid characters: '{}'. Skipping.\",\n script_path_str\n );\n zap_errors.push(format!(\"Skipped invalid script path: {script_path_str}\"));\n continue;\n }\n let script_full_path = PathBuf::from(script_path_str);\n if !script_full_path.exists() {\n if !script_full_path.is_absolute() {\n if let Ok(found_path) = which::which(&script_full_path) {\n debug!(\n \"Found zap script {} in PATH: {}\",\n script_full_path.display(),\n found_path.display()\n );\n run_zap_script(\n &found_path,\n args.as_ref().map(|v| v.as_slice()),\n &mut zap_errors,\n );\n } else {\n error!(\n \"Zap script '{}' not found (absolute or in PATH). Skipping.\",\n script_full_path.display()\n );\n zap_errors.push(format!(\n \"Zap script not found: {}\",\n script_full_path.display()\n ));\n }\n } else {\n error!(\n \"Absolute zap script path '{}' not found. Skipping.\",\n script_full_path.display()\n );\n zap_errors.push(format!(\n \"Zap script not found: {}\",\n script_full_path.display()\n ));\n }\n continue;\n }\n run_zap_script(\n &script_full_path,\n args.as_ref().map(|v| v.as_slice()),\n &mut zap_errors,\n );\n }\n ZapActionDetail::Signal(signals) => {\n for signal_spec in signals {\n let parts: Vec<&str> = signal_spec.splitn(2, '/').collect();\n if parts.len() != 2 {\n warn!(\"Invalid signal spec format '{}', expected SIGNAL/bundle.id. Skipping.\", signal_spec);\n zap_errors.push(format!(\"Invalid signal spec: {signal_spec}\"));\n continue;\n }\n let signal = parts[0].trim().to_uppercase();\n let bundle_id_or_pattern = parts[1].trim();\n\n if !VALID_SIGNAL_RE.is_match(&signal) {\n warn!(\n \"Invalid signal name '{}' in spec '{}'. Skipping.\",\n signal, signal_spec\n );\n zap_errors.push(format!(\"Invalid signal name: {signal}\"));\n continue;\n }\n\n debug!(\"Sending signal {} to processes matching ID/pattern '{}' (using pkill -f)\", signal, bundle_id_or_pattern);\n let mut cmd = Command::new(\"pkill\");\n cmd.arg(format!(\"-{signal}\")); // Standard signal format for pkill\n cmd.arg(\"-f\");\n cmd.arg(bundle_id_or_pattern);\n cmd.stdout(Stdio::null()).stderr(Stdio::piped());\n match cmd.status() {\n Ok(status) => {\n if status.success() {\n debug!(\"Successfully sent signal {} via pkill to processes matching '{}'.\", signal, bundle_id_or_pattern);\n } else if status.code() == Some(1) {\n debug!(\"No running processes found matching ID/pattern '{}' for signal {} via pkill.\", bundle_id_or_pattern, signal);\n } else {\n warn!(\"pkill command failed for signal {} / ID/pattern '{}' with status: {}\", signal, bundle_id_or_pattern, status);\n }\n }\n Err(e) => {\n error!(\n \"Failed to execute pkill for signal {} / ID/pattern '{}': {}\",\n signal, bundle_id_or_pattern, e\n );\n zap_errors.push(format!(\"Failed to run pkill for signal {signal}\"));\n }\n }\n }\n }\n }\n }\n }\n\n debug!(\n \"Zap: Removing Caskroom version directory: {}\",\n cask_version_path_in_caskroom.display()\n );\n if !remove_filesystem_artifact(cask_version_path_in_caskroom, true)\n && cask_version_path_in_caskroom.exists()\n {\n let msg = format!(\n \"Failed to remove Caskroom version directory during zap: {}\",\n cask_version_path_in_caskroom.display()\n );\n error!(\"{}\", msg);\n zap_errors.push(msg);\n }\n\n if let Some(parent_token_dir) = cask_version_path_in_caskroom.parent() {\n if parent_token_dir.exists() && parent_token_dir.is_dir() {\n match fs::read_dir(parent_token_dir) {\n Ok(mut entries) => {\n if entries.next().is_none() {\n debug!(\n \"Zap: Removing empty Caskroom token directory: {}\",\n parent_token_dir.display()\n );\n if !remove_filesystem_artifact(parent_token_dir, true)\n && parent_token_dir.exists()\n {\n warn!(\n \"Failed to remove empty Caskroom token directory during zap: {}\",\n parent_token_dir.display()\n );\n }\n }\n }\n Err(e) => warn!(\n \"Failed to read Caskroom token directory {} during zap cleanup: {}\",\n parent_token_dir.display(),\n e\n ),\n }\n }\n }\n\n if zap_errors.is_empty() {\n debug!(\n \"Zap process completed successfully for cask: {}\",\n cask_def.token\n );\n Ok(())\n } else {\n error!(\n \"Zap process for {} completed with errors: {}\",\n cask_def.token,\n zap_errors.join(\"; \")\n );\n Err(SpsError::InstallError(format!(\n \"Zap for {} failed with errors: {}\",\n cask_def.token,\n zap_errors.join(\"; \")\n )))\n }\n}\n\nfn process_artifact_uninstall_core(\n artifact: &InstalledArtifact,\n config: &Config,\n use_sudo_for_zap: bool,\n) -> bool {\n debug!(\"Processing artifact removal: {:?}\", artifact);\n match artifact {\n InstalledArtifact::AppBundle { path } => {\n debug!(\"Uninstall: Removing AppBundle at {}\", path.display());\n match path.symlink_metadata() {\n Ok(metadata) if metadata.file_type().is_symlink() => {\n debug!(\"AppBundle at {} is a symlink; unlinking.\", path.display());\n match std::fs::remove_file(path) {\n Ok(_) => true,\n Err(e) => {\n warn!(\"Failed to unlink symlink at {}: {}\", path.display(), e);\n false\n }\n }\n }\n Ok(metadata) if metadata.file_type().is_dir() => {\n #[cfg(target_os = \"macos\")]\n {\n if path.exists() {\n if let Err(e) = applescript::quit_app_gracefully(path) {\n warn!(\n \"Attempt to gracefully quit app at {} failed: {} (proceeding)\",\n path.display(),\n e\n );\n }\n } else {\n debug!(\n \"App bundle at {} does not exist, skipping quit.\",\n path.display()\n );\n }\n }\n let use_sudo = path.starts_with(config.applications_dir())\n || path.starts_with(\"/Applications\")\n || use_sudo_for_zap;\n remove_filesystem_artifact(path, use_sudo)\n }\n Ok(_) | Err(_) => {\n let use_sudo = path.starts_with(config.applications_dir())\n || path.starts_with(\"/Applications\")\n || use_sudo_for_zap;\n remove_filesystem_artifact(path, use_sudo)\n }\n }\n }\n InstalledArtifact::BinaryLink { link_path, .. }\n | InstalledArtifact::ManpageLink { link_path, .. }\n | InstalledArtifact::CaskroomLink { link_path, .. } => {\n debug!(\"Uninstall: Removing link at {}\", link_path.display());\n remove_filesystem_artifact(link_path, use_sudo_for_zap)\n }\n InstalledArtifact::PkgUtilReceipt { id } => {\n debug!(\"Uninstall: Forgetting PkgUtilReceipt {}\", id);\n forget_pkgutil_receipt(id)\n }\n InstalledArtifact::Launchd { label, path } => {\n debug!(\"Uninstall: Unloading Launchd {} (path: {:?})\", label, path);\n unload_and_remove_launchd(label, path.as_deref())\n }\n InstalledArtifact::MovedResource { path } => {\n debug!(\"Uninstall: Removing MovedResource at {}\", path.display());\n remove_filesystem_artifact(path, use_sudo_for_zap)\n }\n InstalledArtifact::CaskroomReference { path } => {\n debug!(\n \"Uninstall: Removing CaskroomReference at {}\",\n path.display()\n );\n remove_filesystem_artifact(path, use_sudo_for_zap)\n }\n }\n}\n\nfn forget_pkgutil_receipt(id: &str) -> bool {\n if !VALID_PKGID_RE.is_match(id) {\n error!(\"Invalid pkgutil ID format: '{}'. Skipping forget.\", id);\n return false;\n }\n debug!(\"Forgetting package receipt (requires sudo): {}\", id);\n let output = Command::new(\"sudo\")\n .arg(\"pkgutil\")\n .arg(\"--forget\")\n .arg(id)\n .output();\n match output {\n Ok(out) if out.status.success() => {\n debug!(\"Successfully forgot package receipt {}\", id);\n true\n }\n Ok(out) => {\n let stderr = String::from_utf8_lossy(&out.stderr);\n if !stderr.contains(\"No receipt for\") && !stderr.trim().is_empty() {\n error!(\"Failed to forget package receipt {}: {}\", id, stderr.trim());\n // Return false if pkgutil fails for a reason other than \"No receipt\"\n return false;\n } else {\n debug!(\"Package receipt {} already forgotten or never existed.\", id);\n }\n true\n }\n Err(e) => {\n error!(\"Failed to execute sudo pkgutil --forget {}: {}\", id, e);\n false\n }\n }\n}\n\nfn unload_and_remove_launchd(label: &str, path: Option<&Path>) -> bool {\n if !VALID_LABEL_RE.is_match(label) {\n error!(\n \"Invalid launchd label format: '{}'. Skipping unload/remove.\",\n label\n );\n return false;\n }\n debug!(\"Unloading launchd service (if loaded): {}\", label);\n let unload_output = Command::new(\"launchctl\")\n .arg(\"unload\")\n .arg(\"-w\")\n .arg(label)\n .stderr(Stdio::piped())\n .output();\n\n let mut unload_successful_or_not_loaded = false;\n match unload_output {\n Ok(out) if out.status.success() => {\n debug!(\"Successfully unloaded launchd service {}\", label);\n unload_successful_or_not_loaded = true;\n }\n Ok(out) => {\n let stderr = String::from_utf8_lossy(&out.stderr);\n if stderr.contains(\"Could not find specified service\")\n || stderr.contains(\"service is not loaded\")\n || stderr.trim().is_empty()\n {\n debug!(\"Launchd service {} already unloaded or not found.\", label);\n unload_successful_or_not_loaded = true;\n } else {\n warn!(\n \"launchctl unload {} failed (but proceeding with plist removal attempt): {}\",\n label,\n stderr.trim()\n );\n // Proceed to try plist removal even if unload reports other errors\n }\n }\n Err(e) => {\n warn!(\"Failed to execute launchctl unload {} (but proceeding with plist removal attempt): {}\", label, e);\n }\n }\n\n if let Some(plist_path) = path {\n if plist_path.exists() {\n debug!(\"Removing launchd plist file: {}\", plist_path.display());\n let use_sudo = plist_path.starts_with(\"/Library/LaunchDaemons\")\n || plist_path.starts_with(\"/Library/LaunchAgents\");\n if !remove_filesystem_artifact(plist_path, use_sudo) {\n warn!(\"Failed to remove launchd plist: {}\", plist_path.display());\n return false; // If plist removal fails, consider the operation failed\n }\n } else {\n debug!(\n \"Launchd plist path {} does not exist, skip removal.\",\n plist_path.display()\n );\n }\n } else {\n debug!(\n \"No path provided for launchd plist removal for label {}\",\n label\n );\n }\n unload_successful_or_not_loaded // Success depends on unload and optional plist removal\n}\n\nfn trash_path(path: &Path) -> bool {\n if !path.exists() && path.symlink_metadata().is_err() {\n debug!(\"Path for trashing not found: {}\", path.display());\n return true;\n }\n match trash::delete(path) {\n Ok(_) => {\n debug!(\"Trashed: {}\", path.display());\n true\n }\n Err(e) => {\n warn!(\"Failed to trash {} (proceeding anyway): {}. This might require manual cleanup or installing a 'trash' utility.\", path.display(), e);\n true\n }\n }\n}\n\n/// Helper for zap scripts.\nfn run_zap_script(script_path: &Path, args: Option<&[String]>, errors: &mut Vec) {\n debug!(\n \"Running zap script: {} with args {:?}\",\n script_path.display(),\n args.unwrap_or_default()\n );\n let mut cmd = Command::new(script_path);\n if let Some(script_args) = args {\n cmd.args(script_args);\n }\n cmd.stdout(Stdio::piped()).stderr(Stdio::piped());\n\n match cmd.output() {\n Ok(output) => {\n log_command_output(\n \"Zap script\",\n &script_path.display().to_string(),\n &output,\n errors,\n );\n }\n Err(e) => {\n let msg = format!(\n \"Failed to execute zap script '{}': {}\",\n script_path.display(),\n e\n );\n error!(\"{}\", msg);\n errors.push(msg);\n }\n }\n}\n\n/// Logs the output of a command and adds to error list if it failed.\nfn log_command_output(\n context: &str,\n command_str: &str,\n output: &std::process::Output,\n errors: &mut Vec,\n) {\n let stdout = String::from_utf8_lossy(&output.stdout);\n let stderr = String::from_utf8_lossy(&output.stderr);\n if !output.status.success() {\n error!(\n \"{} '{}' failed with status {}: {}\",\n context,\n command_str,\n output.status,\n stderr.trim()\n );\n if !stdout.trim().is_empty() {\n error!(\"{} stdout: {}\", context, stdout.trim());\n }\n errors.push(format!(\"{context} '{command_str}' failed\"));\n } else {\n debug!(\"{} '{}' executed successfully.\", context, command_str);\n if !stdout.trim().is_empty() {\n debug!(\"{} stdout: {}\", context, stdout.trim());\n }\n if !stderr.trim().is_empty() {\n debug!(\"{} stderr: {}\", context, stderr.trim());\n }\n }\n}\n\n// Helper function specifically for cleaning up the private store.\n// This was originally inside zap_cask_artifacts.\nfn cleanup_private_store(\n cask_token: &str,\n version: &str,\n app_name: Option<&str>, // The actual .app name, not the token\n config: &Config,\n) -> bool {\n debug!(\n \"Cleaning up private store for cask {} version {}\",\n cask_token, version\n );\n\n let private_version_dir = config.cask_store_version_path(cask_token, version);\n\n if let Some(app) = app_name {\n let app_path_in_private_store = private_version_dir.join(app);\n if app_path_in_private_store.exists()\n || app_path_in_private_store.symlink_metadata().is_ok()\n {\n debug!(\n \"Removing app from private store: {}\",\n app_path_in_private_store.display()\n );\n // Use the helper from install::cask::helpers, assuming it's correctly located and\n // public\n if !remove_path_robustly_from_install_helpers(&app_path_in_private_store, config, false)\n {\n // use_sudo=false for private store\n warn!(\n \"Failed to remove app from private store: {}\",\n app_path_in_private_store.display()\n );\n // Potentially return false or collect errors, depending on desired strictness\n }\n }\n }\n\n // After attempting to remove specific app, remove the version directory if it exists\n // This also handles cases where app_name was None.\n if private_version_dir.exists() {\n debug!(\n \"Removing private store version directory: {}\",\n private_version_dir.display()\n );\n match fs::remove_dir_all(&private_version_dir) {\n Ok(_) => debug!(\n \"Successfully removed private store version directory {}\",\n private_version_dir.display()\n ),\n Err(e) => {\n warn!(\n \"Failed to remove private store version directory {}: {}\",\n private_version_dir.display(),\n e\n );\n return false; // If the version dir removal fails, consider it a failure\n }\n }\n }\n\n // Clean up empty parent token directory.\n cleanup_empty_parent_dirs_in_private_store(\n &private_version_dir, // Start from the version dir (or its parent if it was just removed)\n &config.cask_store_dir(),\n );\n\n true\n}\n"], ["/sps/sps-core/src/pipeline/worker.rs", "// sps-core/src/pipeline/worker.rs\nuse std::fs;\nuse std::path::PathBuf;\nuse std::sync::Arc;\n\nuse futures::executor::block_on;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::dependency::DependencyExt;\nuse sps_common::error::{Result as SpsResult, SpsError};\nuse sps_common::keg::KegRegistry;\nuse sps_common::model::formula::FormulaDependencies;\nuse sps_common::model::InstallTargetIdentifier;\nuse sps_common::pipeline::{JobAction, PipelineEvent, PipelinePackageType, WorkerJob};\nuse tokio::sync::broadcast;\nuse tracing::{debug, error, instrument, warn};\n\nuse crate::check::installed::{InstalledPackageInfo, PackageType as CorePackageType};\nuse crate::{build, install, uninstall, upgrade};\n\npub(super) fn execute_sync_job(\n worker_job: WorkerJob,\n config: &Config,\n cache: Arc,\n event_tx: broadcast::Sender,\n) -> std::result::Result<(JobAction, PipelinePackageType), Box<(JobAction, SpsError)>> {\n let action = worker_job.request.action.clone();\n\n let result = do_execute_sync_steps(worker_job, config, cache, event_tx);\n\n result\n .map_err(|e| Box::new((action.clone(), e)))\n .map(|pkg_type| (action, pkg_type))\n}\n\n#[instrument(skip_all, fields(job_id = %worker_job.request.target_id, action = ?worker_job.request.action))]\nfn do_execute_sync_steps(\n worker_job: WorkerJob,\n config: &Config,\n _cache: Arc, // Marked as unused if cache is not directly used in this function body\n event_tx: broadcast::Sender,\n) -> SpsResult {\n let job_request = worker_job.request;\n let download_path = worker_job.download_path;\n let is_source_from_private_store = worker_job.is_source_from_private_store;\n\n let (core_pkg_type, pipeline_pkg_type) = match &job_request.target_definition {\n InstallTargetIdentifier::Formula(_) => {\n (CorePackageType::Formula, PipelinePackageType::Formula)\n }\n InstallTargetIdentifier::Cask(_) => (CorePackageType::Cask, PipelinePackageType::Cask),\n };\n\n // Check dependencies before proceeding with formula install/upgrade\n if let InstallTargetIdentifier::Formula(formula_arc) = &job_request.target_definition {\n if matches!(job_request.action, JobAction::Install)\n || matches!(job_request.action, JobAction::Upgrade { .. })\n {\n debug!(\n \"[WORKER:{}] Pre-install check for dependencies. Formula: {}, Action: {:?}\",\n job_request.target_id,\n formula_arc.name(),\n job_request.action\n );\n\n let keg_registry = KegRegistry::new(config.clone());\n match formula_arc.dependencies() {\n Ok(dependencies) => {\n for dep in dependencies.runtime() {\n debug!(\"[WORKER:{}] Checking runtime dependency: '{}'. Required by: '{}'. Configured cellar: {}\", job_request.target_id, dep.name, formula_arc.name(), config.cellar_dir().display());\n\n match keg_registry.get_installed_keg(&dep.name) {\n Ok(Some(keg_info)) => {\n debug!(\"[WORKER:{}] Dependency '{}' FOUND by KegRegistry. Path: {}, Version: {}\", job_request.target_id, dep.name, keg_info.path.display(), keg_info.version_str);\n }\n Ok(None) => {\n debug!(\"[WORKER:{}] Dependency '{}' was NOT FOUND by KegRegistry for formula '{}'. THIS IS THE ERROR POINT.\", dep.name, job_request.target_id, formula_arc.name());\n let error_msg = format!(\n \"Runtime dependency '{}' for formula '{}' is not installed. Aborting operation for '{}'.\",\n dep.name, formula_arc.name(), job_request.target_id\n );\n error!(\"{}\", error_msg);\n return Err(SpsError::DependencyError(error_msg));\n }\n Err(e) => {\n debug!(\"[WORKER:{}] Error during KegRegistry check for dependency '{}': {}. Aborting for formula '{}'.\", job_request.target_id, dep.name, e, job_request.target_id);\n return Err(SpsError::Generic(format!(\n \"Failed to check KegRegistry for {}: {}\",\n dep.name, e\n )));\n }\n }\n }\n }\n Err(e) => {\n let error_msg = format!(\n \"Could not retrieve dependency list for formula '{}': {}. Aborting operation.\",\n job_request.target_id, e\n );\n error!(\"{}\", error_msg);\n return Err(SpsError::DependencyError(error_msg));\n }\n }\n debug!(\n \"[WORKER:{}] All required formula dependencies appear to be installed for '{}'.\",\n job_request.target_id,\n formula_arc.name()\n );\n }\n }\n\n let mut formula_installed_path: Option = None;\n\n match &job_request.action {\n JobAction::Upgrade {\n from_version,\n old_install_path,\n } => {\n debug!(\n \"[{}] Upgrading from version {}\",\n job_request.target_id, from_version\n );\n let old_info = InstalledPackageInfo {\n name: job_request.target_id.clone(),\n version: from_version.clone(),\n pkg_type: core_pkg_type.clone(),\n path: old_install_path.clone(),\n };\n\n match &job_request.target_definition {\n InstallTargetIdentifier::Formula(formula) => {\n let http_client_for_bottle_upgrade = Arc::new(reqwest::Client::new());\n let installed_path = if job_request.is_source_build {\n let _ = event_tx.send(PipelineEvent::BuildStarted {\n target_id: job_request.target_id.clone(),\n });\n let all_dep_paths = Vec::new(); // TODO: Populate this correctly if needed by upgrade_source_formula\n block_on(upgrade::source::upgrade_source_formula(\n formula,\n &download_path,\n &old_info,\n config,\n &all_dep_paths,\n ))?\n } else {\n block_on(upgrade::bottle::upgrade_bottle_formula(\n formula,\n &download_path,\n &old_info,\n config,\n http_client_for_bottle_upgrade,\n ))?\n };\n formula_installed_path = Some(installed_path);\n }\n InstallTargetIdentifier::Cask(cask) => {\n block_on(upgrade::cask::upgrade_cask_package(\n cask,\n &download_path,\n &old_info,\n config,\n ))?;\n }\n }\n }\n JobAction::Install | JobAction::Reinstall { .. } => {\n if let JobAction::Reinstall {\n version: from_version,\n current_install_path: old_install_path,\n } = &job_request.action\n {\n debug!(\n \"[{}] Reinstall: Removing existing version {}...\",\n job_request.target_id, from_version\n );\n let _ = event_tx.send(PipelineEvent::UninstallStarted {\n target_id: job_request.target_id.clone(),\n version: from_version.clone(),\n });\n\n let old_info_for_reinstall = InstalledPackageInfo {\n name: job_request.target_id.clone(),\n version: from_version.clone(),\n pkg_type: core_pkg_type.clone(),\n path: old_install_path.clone(),\n };\n let uninstall_opts = uninstall::UninstallOptions { skip_zap: true };\n\n match core_pkg_type {\n CorePackageType::Formula => uninstall::uninstall_formula_artifacts(\n &old_info_for_reinstall,\n config,\n &uninstall_opts,\n )?,\n CorePackageType::Cask => {\n uninstall::uninstall_cask_artifacts(&old_info_for_reinstall, config)?\n }\n }\n debug!(\n \"[{}] Reinstall: Removed existing version {}.\",\n job_request.target_id, from_version\n );\n let _ = event_tx.send(PipelineEvent::UninstallFinished {\n target_id: job_request.target_id.clone(),\n version: from_version.clone(),\n });\n }\n\n let _ = event_tx.send(PipelineEvent::InstallStarted {\n target_id: job_request.target_id.clone(),\n pkg_type: pipeline_pkg_type,\n });\n\n match &job_request.target_definition {\n InstallTargetIdentifier::Formula(formula) => {\n let install_dir_base =\n (**formula).install_prefix(config.cellar_dir().as_path())?;\n if let Some(parent_dir) = install_dir_base.parent() {\n fs::create_dir_all(parent_dir).map_err(|e| SpsError::Io(Arc::new(e)))?;\n }\n\n if job_request.is_source_build {\n debug!(\"[{}] Building from source...\", job_request.target_id);\n let _ = event_tx.send(PipelineEvent::BuildStarted {\n target_id: job_request.target_id.clone(),\n });\n let build_dep_paths: Vec = vec![]; // TODO: Populate this from ResolvedGraph\n\n let build_future = build::compile::build_from_source(\n &download_path,\n formula,\n config,\n &build_dep_paths,\n );\n let installed_dir = block_on(build_future)?;\n formula_installed_path = Some(installed_dir);\n } else {\n debug!(\"[{}] Installing bottle...\", job_request.target_id);\n let installed_dir =\n install::bottle::exec::install_bottle(&download_path, formula, config)?;\n formula_installed_path = Some(installed_dir);\n }\n }\n InstallTargetIdentifier::Cask(cask) => {\n if is_source_from_private_store {\n debug!(\n \"[{}] Reinstalling cask from private store...\",\n job_request.target_id\n );\n\n if let Some(file_name) = download_path.file_name() {\n let app_name = file_name.to_string_lossy().to_string();\n let applications_app_path = config.applications_dir().join(&app_name);\n\n if applications_app_path.exists()\n || applications_app_path.symlink_metadata().is_ok()\n {\n debug!(\n \"Removing existing app at {}\",\n applications_app_path.display()\n );\n let _ = install::cask::helpers::remove_path_robustly(\n &applications_app_path,\n config,\n true,\n );\n }\n\n debug!(\n \"Symlinking app from private store {} to {}\",\n download_path.display(),\n applications_app_path.display()\n );\n if let Err(e) =\n std::os::unix::fs::symlink(&download_path, &applications_app_path)\n {\n return Err(SpsError::InstallError(format!(\n \"Failed to symlink app from private store to {}: {}\",\n applications_app_path.display(),\n e\n )));\n }\n\n let cask_version =\n cask.version.clone().unwrap_or_else(|| \"latest\".to_string());\n let cask_version_path =\n config.cask_room_version_path(&cask.token, &cask_version);\n\n if !cask_version_path.exists() {\n fs::create_dir_all(&cask_version_path)?;\n }\n\n let caskroom_symlink_path = cask_version_path.join(&app_name);\n if caskroom_symlink_path.exists()\n || caskroom_symlink_path.symlink_metadata().is_ok()\n {\n let _ = fs::remove_file(&caskroom_symlink_path);\n }\n\n #[cfg(unix)]\n {\n if let Err(e) = std::os::unix::fs::symlink(\n &applications_app_path,\n &caskroom_symlink_path,\n ) {\n warn!(\"Failed to create Caskroom symlink: {}\", e);\n }\n }\n\n let created_artifacts = vec![\n sps_common::model::artifact::InstalledArtifact::AppBundle {\n path: applications_app_path.clone(),\n },\n sps_common::model::artifact::InstalledArtifact::CaskroomLink {\n link_path: caskroom_symlink_path.clone(),\n target_path: applications_app_path.clone(),\n },\n ];\n\n debug!(\n \"[{}] Writing manifest for private store reinstall...\",\n job_request.target_id\n );\n if let Err(e) = install::cask::write_cask_manifest(\n cask,\n &cask_version_path,\n created_artifacts,\n ) {\n error!(\n \"[{}] Failed to write CASK_INSTALL_MANIFEST.json during private store reinstall: {}\",\n job_request.target_id, e\n );\n return Err(SpsError::InstallError(format!(\n \"Failed to write manifest during private store reinstall for {}: {}\",\n job_request.target_id, e\n )));\n }\n } else {\n return Err(SpsError::InstallError(format!(\n \"Failed to get app name from private store path: {}\",\n download_path.display()\n )));\n }\n } else {\n debug!(\"[{}] Installing cask...\", job_request.target_id);\n install::cask::install_cask(\n cask,\n &download_path,\n config,\n &job_request.action,\n )?;\n }\n }\n }\n }\n };\n\n if let Some(ref installed_path) = formula_installed_path {\n debug!(\n \"[{}] Formula operation resulted in keg path: {}\",\n job_request.target_id,\n installed_path.display()\n );\n } else if core_pkg_type == CorePackageType::Cask {\n debug!(\"[{}] Cask operation completed.\", job_request.target_id);\n }\n\n if let (InstallTargetIdentifier::Formula(formula), Some(keg_path_for_linking)) =\n (&job_request.target_definition, &formula_installed_path)\n {\n debug!(\n \"[{}] Linking artifacts for formula {}...\",\n job_request.target_id,\n (**formula).name()\n );\n let _ = event_tx.send(PipelineEvent::LinkStarted {\n target_id: job_request.target_id.clone(),\n pkg_type: pipeline_pkg_type,\n });\n install::bottle::link::link_formula_artifacts(formula, keg_path_for_linking, config)?;\n debug!(\n \"[{}] Linking complete for formula {}.\",\n job_request.target_id,\n (**formula).name()\n );\n }\n\n Ok(pipeline_pkg_type)\n}\n"], ["/sps/sps-common/src/model/cask.rs", "// ===== sps-common/src/model/cask.rs ===== // Corrected path\nuse std::collections::HashMap;\nuse std::fs;\n\nuse serde::{Deserialize, Serialize};\n\nuse crate::config::Config;\n\npub type Artifact = serde_json::Value;\n\n/// Represents the `url` field, which can be a simple string or a map with specs\n#[derive(Debug, Clone, Serialize, Deserialize)]\n#[serde(untagged)]\npub enum UrlField {\n Simple(String),\n WithSpec {\n url: String,\n #[serde(default)]\n verified: Option,\n #[serde(flatten)]\n other: HashMap,\n },\n}\n\n/// Represents the `sha256` field: hex, no_check, or per-architecture\n#[derive(Debug, Clone, Serialize, Deserialize)]\n#[serde(untagged)]\npub enum Sha256Field {\n Hex(String),\n #[serde(rename_all = \"snake_case\")]\n NoCheck {\n no_check: bool,\n },\n PerArch(HashMap),\n}\n\n/// Appcast metadata\n#[derive(Debug, Clone, Serialize, Deserialize)] // Ensure Serialize/Deserialize are here\npub struct Appcast {\n pub url: String,\n pub checkpoint: Option,\n}\n\n/// Represents conflicts with other casks or formulae\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub struct ConflictsWith {\n #[serde(default)]\n pub cask: Vec,\n #[serde(default)]\n pub formula: Vec,\n #[serde(flatten)]\n pub extra: HashMap,\n}\n\n/// Represents the specific architecture details found in some cask definitions\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub struct ArchSpec {\n #[serde(rename = \"type\")] // Map the JSON \"type\" field\n pub type_name: String, // e.g., \"arm\"\n pub bits: u32, // e.g., 64\n}\n\n/// Helper for architecture requirements: single string, list of strings, or list of spec objects\n#[derive(Debug, Clone, Serialize, Deserialize)]\n#[serde(untagged)]\npub enum ArchReq {\n One(String), // e.g., \"arm64\"\n Many(Vec), // e.g., [\"arm64\", \"x86_64\"]\n Specs(Vec),\n}\n\n/// Helper for macOS requirements: symbol, list, comparison, or map\n#[derive(Debug, Clone, Serialize, Deserialize)]\n#[serde(untagged)]\npub enum MacOSReq {\n Symbol(String), // \":big_sur\"\n Symbols(Vec), // [\":catalina\", \":big_sur\"]\n Comparison(String), // \">= :big_sur\"\n Map(HashMap>),\n}\n\n/// Helper to coerce string-or-list into Vec\n#[derive(Debug, Clone, Serialize, Deserialize)]\n#[serde(untagged)]\npub enum StringList {\n One(String),\n Many(Vec),\n}\n\nimpl From for Vec {\n fn from(item: StringList) -> Self {\n match item {\n StringList::One(s) => vec![s],\n StringList::Many(v) => v,\n }\n }\n}\n\n/// Represents `depends_on` block with multiple possible keys\n#[derive(Debug, Clone, Serialize, Deserialize, Default)]\npub struct DependsOn {\n #[serde(default)]\n pub cask: Vec,\n #[serde(default)]\n pub formula: Vec,\n #[serde(default)]\n pub arch: Option,\n #[serde(default)]\n pub macos: Option,\n #[serde(flatten)]\n pub extra: HashMap,\n}\n\n/// The main Cask model matching Homebrew JSON v2\n#[derive(Debug, Clone, Serialize, Deserialize, Default)]\npub struct Cask {\n pub token: String,\n\n #[serde(default)]\n pub name: Option>,\n pub version: Option,\n pub desc: Option,\n pub homepage: Option,\n\n #[serde(default)]\n pub artifacts: Option>,\n\n #[serde(default)]\n pub url: Option,\n #[serde(default)]\n pub url_specs: Option>,\n\n #[serde(default)]\n pub sha256: Option,\n\n pub appcast: Option,\n pub auto_updates: Option,\n\n #[serde(default)]\n pub depends_on: Option,\n\n #[serde(default)]\n pub conflicts_with: Option,\n\n pub caveats: Option,\n pub stage_only: Option,\n\n #[serde(default)]\n pub uninstall: Option>,\n\n #[serde(default)] // Only one default here\n pub zap: Option>,\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub struct CaskList {\n pub casks: Vec,\n}\n\n// --- ZAP STANZA SUPPORT ---\n\n/// Helper for zap: string or array of strings\n#[derive(Debug, Clone, Serialize, Deserialize)]\n#[serde(untagged)]\npub enum StringOrVec {\n String(String),\n Vec(Vec),\n}\nimpl StringOrVec {\n pub fn into_vec(self) -> Vec {\n match self {\n StringOrVec::String(s) => vec![s],\n StringOrVec::Vec(v) => v,\n }\n }\n}\n\n/// Zap action details (trash, delete, rmdir, pkgutil, launchctl, script, signal, etc)\n#[derive(Debug, Clone, Serialize, Deserialize)]\n#[serde(tag = \"action\", rename_all = \"snake_case\")]\npub enum ZapActionDetail {\n Trash(Vec),\n Delete(Vec),\n Rmdir(Vec),\n Pkgutil(StringOrVec),\n Launchctl(StringOrVec),\n Script {\n executable: String,\n args: Option>,\n },\n Signal(Vec),\n // Add more as needed\n}\n\n/// A zap stanza is a map of action -> detail\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub struct ZapStanza(pub std::collections::HashMap);\n\n// --- Cask Impl ---\n\nimpl Cask {\n /// Check if this cask is installed by looking for a manifest file\n /// in any versioned directory within the Caskroom.\n pub fn is_installed(&self, config: &Config) -> bool {\n let cask_dir = config.cask_room_token_path(&self.token); // e.g., /opt/sps/cask_room/firefox\n if !cask_dir.exists() || !cask_dir.is_dir() {\n return false;\n }\n\n // Iterate through entries (version dirs) inside the cask_dir\n match fs::read_dir(&cask_dir) {\n Ok(entries) => {\n // Clippy fix: Use flatten() to handle Result entries directly\n for entry in entries.flatten() {\n // <-- Use flatten() here\n let version_path = entry.path();\n // Check if it's a directory (representing a version)\n if version_path.is_dir() {\n // Check for the existence of the manifest file\n let manifest_path = version_path.join(\"CASK_INSTALL_MANIFEST.json\"); // <-- Correct filename\n if manifest_path.is_file() {\n // Check is_installed flag in manifest\n let mut include = true;\n if let Ok(manifest_str) = std::fs::read_to_string(&manifest_path) {\n if let Ok(manifest_json) =\n serde_json::from_str::(&manifest_str)\n {\n if let Some(is_installed) =\n manifest_json.get(\"is_installed\").and_then(|v| v.as_bool())\n {\n include = is_installed;\n }\n }\n }\n if include {\n // Found a manifest in at least one version directory, consider it\n // installed\n return true;\n }\n }\n }\n }\n // If loop completes without finding a manifest in any version dir\n false\n }\n Err(e) => {\n // Log error if reading the directory fails, but assume not installed\n tracing::warn!(\n \"Failed to read cask directory {} to check for installed versions: {}\",\n cask_dir.display(),\n e\n );\n false\n }\n }\n }\n\n /// Get the installed version of this cask by reading the directory names\n /// in the Caskroom. Returns the first version found (use cautiously if multiple\n /// versions could exist, though current install logic prevents this).\n pub fn installed_version(&self, config: &Config) -> Option {\n let cask_dir = config.cask_room_token_path(&self.token); //\n if !cask_dir.exists() {\n return None;\n }\n // Iterate through entries and return the first directory name found\n match fs::read_dir(&cask_dir) {\n Ok(entries) => {\n // Clippy fix: Use flatten()\n for entry in entries.flatten() {\n // <-- Use flatten() here\n let path = entry.path();\n // Check if it's a directory (representing a version)\n if path.is_dir() {\n if let Some(version_str) = path.file_name().and_then(|name| name.to_str()) {\n // Return the first version directory name found\n return Some(version_str.to_string());\n }\n }\n }\n // No version directories found\n None\n }\n Err(_) => None, // Error reading directory\n }\n }\n\n /// Get a friendly name for display purposes\n pub fn display_name(&self) -> String {\n self.name\n .as_ref()\n .and_then(|names| names.first().cloned())\n .unwrap_or_else(|| self.token.clone())\n }\n}\n"], ["/sps/sps/src/cli/status.rs", "// sps/src/cli/status.rs\nuse std::collections::{HashMap, HashSet};\nuse std::io::{self, Write};\nuse std::time::Instant;\n\nuse colored::*;\nuse sps_common::config::Config;\nuse sps_common::pipeline::{PipelineEvent, PipelinePackageType};\nuse tokio::sync::broadcast;\nuse tracing::debug;\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq)]\nenum JobStatus {\n Waiting,\n Downloading,\n Downloaded,\n Cached,\n Processing,\n Installing,\n Linking,\n Success,\n Failed,\n}\n\nimpl JobStatus {\n fn display_state(&self) -> &'static str {\n match self {\n JobStatus::Waiting => \"waiting\",\n JobStatus::Downloading => \"downloading\",\n JobStatus::Downloaded => \"downloaded\",\n JobStatus::Cached => \"cached\",\n JobStatus::Processing => \"processing\",\n JobStatus::Installing => \"installing\",\n JobStatus::Linking => \"linking\",\n JobStatus::Success => \"success\",\n JobStatus::Failed => \"failed\",\n }\n }\n\n fn slot_indicator(&self) -> String {\n match self {\n JobStatus::Waiting => \" ⧗\".yellow().to_string(),\n JobStatus::Downloading => \" ⬇\".blue().to_string(),\n JobStatus::Downloaded => \" ✓\".green().to_string(),\n JobStatus::Cached => \" ⌂\".cyan().to_string(),\n JobStatus::Processing => \" ⚙\".yellow().to_string(),\n JobStatus::Installing => \" ⚙\".cyan().to_string(),\n JobStatus::Linking => \" →\".magenta().to_string(),\n JobStatus::Success => \" ✓\".green().bold().to_string(),\n JobStatus::Failed => \" ✗\".red().bold().to_string(),\n }\n }\n\n fn colored_state(&self) -> ColoredString {\n match self {\n JobStatus::Waiting => self.display_state().dimmed(),\n JobStatus::Downloading => self.display_state().blue(),\n JobStatus::Downloaded => self.display_state().green(),\n JobStatus::Cached => self.display_state().cyan(),\n JobStatus::Processing => self.display_state().yellow(),\n JobStatus::Installing => self.display_state().yellow(),\n JobStatus::Linking => self.display_state().yellow(),\n JobStatus::Success => self.display_state().green(),\n JobStatus::Failed => self.display_state().red(),\n }\n }\n}\n\nstruct JobInfo {\n name: String,\n status: JobStatus,\n size_bytes: Option,\n current_bytes_downloaded: Option,\n start_time: Option,\n pool_id: usize,\n}\n\nimpl JobInfo {\n fn _elapsed_str(&self) -> String {\n match self.start_time {\n Some(start) => format!(\"{:.1}s\", start.elapsed().as_secs_f64()),\n None => \"–\".to_string(),\n }\n }\n\n fn size_str(&self) -> String {\n match self.size_bytes {\n Some(bytes) => format_bytes(bytes),\n None => \"–\".to_string(),\n }\n }\n}\n\nstruct StatusDisplay {\n jobs: HashMap,\n job_order: Vec,\n total_jobs: usize,\n next_pool_id: usize,\n _start_time: Instant,\n active_downloads: HashSet,\n total_bytes: u64,\n downloaded_bytes: u64,\n last_speed_update: Instant,\n last_aggregate_bytes_snapshot: u64,\n current_speed_bps: f64,\n _speed_history: Vec,\n header_printed: bool,\n last_line_count: usize,\n}\n\nimpl StatusDisplay {\n fn new() -> Self {\n Self {\n jobs: HashMap::new(),\n job_order: Vec::new(),\n total_jobs: 0,\n next_pool_id: 1,\n _start_time: Instant::now(),\n active_downloads: HashSet::new(),\n total_bytes: 0,\n downloaded_bytes: 0,\n last_speed_update: Instant::now(),\n last_aggregate_bytes_snapshot: 0,\n current_speed_bps: 0.0,\n _speed_history: Vec::new(),\n header_printed: false,\n last_line_count: 0,\n }\n }\n\n fn add_job(&mut self, target_id: String, status: JobStatus, size_bytes: Option) {\n if !self.jobs.contains_key(&target_id) {\n let job_info = JobInfo {\n name: target_id.clone(),\n status,\n size_bytes,\n current_bytes_downloaded: if status == JobStatus::Downloading {\n Some(0)\n } else {\n None\n },\n start_time: if status != JobStatus::Waiting {\n Some(Instant::now())\n } else {\n None\n },\n pool_id: self.next_pool_id,\n };\n\n if let Some(bytes) = size_bytes {\n self.total_bytes += bytes;\n }\n\n if status == JobStatus::Downloading {\n self.active_downloads.insert(target_id.to_string());\n }\n\n self.jobs.insert(target_id.clone(), job_info);\n self.job_order.push(target_id);\n self.next_pool_id += 1;\n }\n }\n\n fn update_job_status(&mut self, target_id: &str, status: JobStatus, size_bytes: Option) {\n if let Some(job) = self.jobs.get_mut(target_id) {\n let was_downloading = job.status == JobStatus::Downloading;\n let is_downloading = status == JobStatus::Downloading;\n\n job.status = status;\n\n if job.start_time.is_none() && status != JobStatus::Waiting {\n job.start_time = Some(Instant::now());\n }\n\n if let Some(bytes) = size_bytes {\n if job.size_bytes.is_none() {\n self.total_bytes += bytes;\n }\n job.size_bytes = Some(bytes);\n }\n\n // Update download counts\n if was_downloading && !is_downloading {\n self.active_downloads.remove(target_id);\n if let Some(bytes) = job.size_bytes {\n job.current_bytes_downloaded = Some(bytes);\n self.downloaded_bytes += bytes;\n }\n } else if !was_downloading && is_downloading {\n self.active_downloads.insert(target_id.to_string());\n job.current_bytes_downloaded = Some(0);\n }\n }\n }\n\n fn update_download_progress(\n &mut self,\n target_id: &str,\n bytes_so_far: u64,\n total_size: Option,\n ) {\n if let Some(job) = self.jobs.get_mut(target_id) {\n job.current_bytes_downloaded = Some(bytes_so_far);\n\n if let Some(total) = total_size {\n if job.size_bytes.is_none() {\n // Update total bytes estimate\n self.total_bytes += total;\n job.size_bytes = Some(total);\n } else if job.size_bytes != Some(total) {\n // Adjust total bytes if estimate changed\n if let Some(old_size) = job.size_bytes {\n self.total_bytes = self.total_bytes.saturating_sub(old_size) + total;\n }\n job.size_bytes = Some(total);\n }\n }\n }\n }\n\n fn update_speed(&mut self) {\n let now = Instant::now();\n let time_diff = now.duration_since(self.last_speed_update).as_secs_f64();\n\n if time_diff >= 0.0625 {\n // Calculate current total bytes for all jobs with current download progress\n let current_active_bytes: u64 = self\n .jobs\n .values()\n .filter(|job| matches!(job.status, JobStatus::Downloading))\n .map(|job| job.current_bytes_downloaded.unwrap_or(0))\n .sum();\n\n // Calculate bytes difference since last update\n let bytes_diff =\n current_active_bytes.saturating_sub(self.last_aggregate_bytes_snapshot);\n\n // Calculate speed\n if time_diff > 0.0 && bytes_diff > 0 {\n self.current_speed_bps = bytes_diff as f64 / time_diff;\n } else if !self\n .jobs\n .values()\n .any(|job| job.status == JobStatus::Downloading)\n {\n // No active downloads, reset speed to 0\n self.current_speed_bps = 0.0;\n }\n // If no bytes diff but still have active downloads, keep previous speed\n\n self.last_speed_update = now;\n self.last_aggregate_bytes_snapshot = current_active_bytes;\n }\n }\n\n fn render(&mut self) {\n self.update_speed();\n\n if !self.header_printed {\n // First render - print header and jobs\n self.print_header();\n let job_output = self.build_job_rows();\n print!(\"{job_output}\");\n self.header_printed = true;\n // Count lines: header + jobs + separator + summary\n let job_lines = job_output.lines().count();\n self.last_line_count = 1 + job_lines + 1 + 1;\n } else {\n // Subsequent renders - clear and reprint header, job rows and summary\n self.clear_previous_output();\n self.print_header();\n let job_output = self.build_job_rows();\n print!(\"{job_output}\");\n // Update line count (header + jobs + separator)\n let job_lines = job_output.lines().count();\n self.last_line_count = 1 + job_lines + 1;\n }\n\n // Print separator\n println!(\"{}\", \"─\".repeat(49).dimmed());\n\n // Print status summary\n let completed = self\n .jobs\n .values()\n .filter(|j| matches!(j.status, JobStatus::Success))\n .count();\n let failed = self\n .jobs\n .values()\n .filter(|j| matches!(j.status, JobStatus::Failed))\n .count();\n let _progress_chars = self.generate_progress_bar(completed, failed);\n let _speed_str = format_speed(self.current_speed_bps);\n\n io::stdout().flush().unwrap();\n }\n\n fn print_header(&self) {\n println!(\n \"{:<6} {:<12} {:<15} {:>8} {}\",\n \"IID\".bold().dimmed(),\n \"STATE\".bold().dimmed(),\n \"PKG\".bold().dimmed(),\n \"SIZE\".bold().dimmed(),\n \"SLOT\".bold().dimmed()\n );\n }\n\n fn build_job_rows(&self) -> String {\n let mut output = String::new();\n\n // Job rows\n for target_id in &self.job_order {\n if let Some(job) = self.jobs.get(target_id) {\n let progress_str = if job.status == JobStatus::Downloading {\n match (job.current_bytes_downloaded, job.size_bytes) {\n (Some(downloaded), Some(_total)) => format_bytes(downloaded).to_string(),\n (Some(downloaded), None) => format_bytes(downloaded),\n _ => job.size_str(),\n }\n } else {\n job.size_str()\n };\n\n output.push_str(&format!(\n \"{:<6} {:<12} {:<15} {:>8} {}\\n\",\n format!(\"#{:02}\", job.pool_id).cyan(),\n job.status.colored_state(),\n job.name.cyan(),\n progress_str,\n job.status.slot_indicator()\n ));\n }\n }\n\n output\n }\n\n fn clear_previous_output(&self) {\n // Move cursor up and clear lines\n for _ in 0..self.last_line_count {\n print!(\"\\x1b[1A\\x1b[2K\"); // Move up one line and clear it\n }\n io::stdout().flush().unwrap();\n }\n\n fn generate_progress_bar(&self, completed: usize, failed: usize) -> String {\n if self.total_jobs == 0 {\n return \"\".to_string();\n }\n\n let total_done = completed + failed;\n let progress_width = 8;\n let filled = (total_done * progress_width) / self.total_jobs;\n let remaining = progress_width - filled;\n\n let filled_str = \"▍\".repeat(filled).green();\n let remaining_str = \"·\".repeat(remaining).dimmed();\n\n format!(\"{filled_str}{remaining_str}\")\n }\n}\n\nfn format_bytes(bytes: u64) -> String {\n const UNITS: &[&str] = &[\"B\", \"kB\", \"MB\", \"GB\"];\n let mut value = bytes as f64;\n let mut unit_idx = 0;\n\n while value >= 1000.0 && unit_idx < UNITS.len() - 1 {\n value /= 1000.0;\n unit_idx += 1;\n }\n\n if unit_idx == 0 {\n format!(\"{bytes}B\")\n } else {\n format!(\"{:.1}{}\", value, UNITS[unit_idx])\n }\n}\n\nfn format_speed(bytes_per_sec: f64) -> String {\n if bytes_per_sec < 1.0 {\n return \"0 B/s\".to_string();\n }\n\n const UNITS: &[&str] = &[\"B/s\", \"kB/s\", \"MB/s\", \"GB/s\"];\n let mut value = bytes_per_sec;\n let mut unit_idx = 0;\n\n while value >= 1000.0 && unit_idx < UNITS.len() - 1 {\n value /= 1000.0;\n unit_idx += 1;\n }\n\n format!(\"{:.1} {}\", value, UNITS[unit_idx])\n}\n\npub async fn handle_events(_config: Config, mut event_rx: broadcast::Receiver) {\n let mut display = StatusDisplay::new();\n let mut logs_buffer = Vec::new();\n let mut pipeline_active = false;\n let mut refresh_interval = tokio::time::interval(tokio::time::Duration::from_millis(62));\n refresh_interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);\n\n loop {\n tokio::select! {\n _ = refresh_interval.tick() => {\n if pipeline_active && display.header_printed {\n display.render();\n }\n }\n event_result = event_rx.recv() => {\n match event_result {\n Ok(event) => match event {\n PipelineEvent::PipelineStarted { total_jobs } => {\n pipeline_active = true;\n display.total_jobs = total_jobs;\n println!(\"{}\", \"Starting pipeline.\".cyan().bold());\n }\n PipelineEvent::PlanningStarted => {\n debug!(\"{}\", \"Planning operations.\".cyan());\n }\n PipelineEvent::DependencyResolutionStarted => {\n println!(\"{}\", \"Resolving dependencies\".cyan());\n }\n PipelineEvent::DependencyResolutionFinished => {\n debug!(\"{}\", \"Dependency resolution complete.\".cyan());\n }\n PipelineEvent::PlanningFinished { job_count } => {\n println!(\"{} {}\", \"Planning finished. Jobs:\".bold(), job_count);\n println!();\n }\n PipelineEvent::DownloadStarted { target_id, url: _ } => {\n display.add_job(target_id.clone(), JobStatus::Downloading, None);\n if pipeline_active {\n display.render();\n }\n }\n PipelineEvent::DownloadFinished {\n target_id,\n size_bytes,\n ..\n } => {\n display.update_job_status(&target_id, JobStatus::Downloaded, Some(size_bytes));\n if pipeline_active {\n display.render();\n }\n }\n PipelineEvent::DownloadProgressUpdate {\n target_id,\n bytes_so_far,\n total_size,\n } => {\n display.update_download_progress(&target_id, bytes_so_far, total_size);\n if pipeline_active {\n display.render();\n }\n }\n PipelineEvent::DownloadCached {\n target_id,\n size_bytes,\n } => {\n display.update_job_status(&target_id, JobStatus::Cached, Some(size_bytes));\n if pipeline_active {\n display.render();\n }\n }\n PipelineEvent::DownloadFailed {\n target_id, error, ..\n } => {\n display.update_job_status(&target_id, JobStatus::Failed, None);\n logs_buffer.push(format!(\n \"{} {}: {}\",\n \"Download failed:\".red(),\n target_id.cyan(),\n error.red()\n ));\n if pipeline_active {\n display.render();\n }\n }\n PipelineEvent::JobProcessingStarted { target_id } => {\n display.update_job_status(&target_id, JobStatus::Processing, None);\n if pipeline_active {\n display.render();\n }\n }\n PipelineEvent::BuildStarted { target_id } => {\n display.update_job_status(&target_id, JobStatus::Processing, None);\n if pipeline_active {\n display.render();\n }\n }\n PipelineEvent::InstallStarted { target_id, .. } => {\n display.update_job_status(&target_id, JobStatus::Installing, None);\n if pipeline_active {\n display.render();\n }\n }\n PipelineEvent::LinkStarted { target_id, .. } => {\n display.update_job_status(&target_id, JobStatus::Linking, None);\n if pipeline_active {\n display.render();\n }\n }\n PipelineEvent::JobSuccess {\n target_id,\n action,\n pkg_type,\n } => {\n display.update_job_status(&target_id, JobStatus::Success, None);\n let type_str = match pkg_type {\n PipelinePackageType::Formula => \"Formula\",\n PipelinePackageType::Cask => \"Cask\",\n };\n let action_str = match action {\n sps_common::pipeline::JobAction::Install => \"Installed\",\n sps_common::pipeline::JobAction::Upgrade { .. } => \"Upgraded\",\n sps_common::pipeline::JobAction::Reinstall { .. } => \"Reinstalled\",\n };\n logs_buffer.push(format!(\n \"{}: {} ({})\",\n action_str.green(),\n target_id.cyan(),\n type_str,\n ));\n if pipeline_active {\n display.render();\n }\n }\n PipelineEvent::JobFailed {\n target_id, error, ..\n } => {\n display.update_job_status(&target_id, JobStatus::Failed, None);\n logs_buffer.push(format!(\n \"{} {}: {}\",\n \"✗\".red().bold(),\n target_id.cyan(),\n error.red()\n ));\n if pipeline_active {\n display.render();\n }\n }\n PipelineEvent::LogInfo { message } => {\n logs_buffer.push(message);\n }\n PipelineEvent::LogWarn { message } => {\n logs_buffer.push(message.yellow().to_string());\n }\n PipelineEvent::LogError { message } => {\n logs_buffer.push(message.red().to_string());\n }\n PipelineEvent::PipelineFinished {\n duration_secs,\n success_count,\n fail_count,\n } => {\n if display.header_printed {\n display.render();\n }\n\n println!();\n\n println!(\n \"{} in {:.2}s ({} succeeded, {} failed)\",\n \"Pipeline finished\".bold(),\n duration_secs,\n success_count,\n fail_count\n );\n\n if !logs_buffer.is_empty() {\n println!();\n for log in &logs_buffer {\n println!(\"{log}\");\n }\n }\n\n break;\n }\n _ => {}\n },\n Err(broadcast::error::RecvError::Closed) => {\n break;\n }\n Err(broadcast::error::RecvError::Lagged(_)) => {\n // Ignore lag for now\n }\n }\n }\n }\n }\n}\n"], ["/sps/sps/src/main.rs", "// sps/src/main.rs\nuse std::process::{self}; // StdCommand is used\nuse std::sync::Arc;\nuse std::time::{Duration, SystemTime};\nuse std::{env, fs};\n\nuse clap::Parser;\nuse colored::Colorize;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::error::{Result as spResult, SpsError};\nuse tracing::level_filters::LevelFilter;\nuse tracing::{debug, error, warn}; // Import all necessary tracing macros\nuse tracing_subscriber::fmt::writer::MakeWriterExt;\nuse tracing_subscriber::EnvFilter;\n\nmod cli;\nmod pipeline;\n// Correctly import InitArgs via the re-export in cli.rs or directly from its module\nuse cli::{CliArgs, Command, InitArgs};\n\n// Standalone function to handle the init command logic\nasync fn run_init_command(init_args: &InitArgs, verbose_level: u8) -> spResult<()> {\n let init_level_filter = match verbose_level {\n 0 => LevelFilter::INFO,\n 1 => LevelFilter::DEBUG,\n _ => LevelFilter::TRACE,\n };\n let _ = tracing_subscriber::fmt()\n .with_max_level(init_level_filter)\n .with_writer(std::io::stderr)\n .with_ansi(true)\n .without_time()\n .try_init();\n\n let initial_config_for_path = Config::load().map_err(|e| {\n // Handle error if even basic config loading fails for path determination\n SpsError::Config(format!(\n \"Could not determine sps_root for init (config load failed): {e}\"\n ))\n })?;\n\n // Create a minimal Config struct, primarily for sps_root() and derived paths.\n let temp_config_for_init = Config {\n sps_root: initial_config_for_path.sps_root().to_path_buf(),\n api_base_url: \"https://formulae.brew.sh/api\".to_string(),\n artifact_domain: None,\n docker_registry_token: None,\n docker_registry_basic_auth: None,\n github_api_token: None,\n };\n\n init_args.run(&temp_config_for_init).await\n}\n\n#[tokio::main]\nasync fn main() -> spResult<()> {\n let cli_args = CliArgs::parse();\n\n if let Command::Init(ref init_args_ref) = cli_args.command {\n match run_init_command(init_args_ref, cli_args.verbose).await {\n Ok(_) => {\n return Ok(());\n }\n Err(e) => {\n eprintln!(\"{}: Init command failed: {:#}\", \"Error\".red().bold(), e);\n process::exit(1);\n }\n }\n }\n\n let config = Config::load().map_err(|e| {\n SpsError::Config(format!(\n \"Could not load config (have you run 'sps init'?): {e}\"\n ))\n })?;\n\n let level_filter = match cli_args.verbose {\n 0 => LevelFilter::INFO,\n 1 => LevelFilter::DEBUG,\n _ => LevelFilter::TRACE,\n };\n let max_log_level = level_filter.into_level().unwrap_or(tracing::Level::INFO);\n\n let env_filter = EnvFilter::builder()\n .with_default_directive(level_filter.into())\n .with_env_var(\"SPS_LOG\")\n .from_env_lossy();\n\n let log_dir = config.logs_dir();\n if let Err(e) = fs::create_dir_all(&log_dir) {\n eprintln!(\n \"{} Failed to create log directory {}: {} (ensure 'sps init' was successful or try with sudo for the current command if appropriate)\",\n \"Error:\".red().bold(),\n log_dir.display(),\n e\n );\n let _ = tracing_subscriber::fmt() // Use `let _ =`\n .with_env_filter(env_filter)\n .with_writer(std::io::stderr)\n .with_ansi(true)\n .without_time()\n .try_init(); // Use try_init\n } else if cli_args.verbose > 0 {\n let file_appender = tracing_appender::rolling::daily(&log_dir, \"sps.log\");\n let (non_blocking_appender, guard) = tracing_appender::non_blocking(file_appender);\n\n // For verbose mode, show debug/trace logs on stderr too\n let stderr_writer = std::io::stderr.with_max_level(max_log_level);\n let file_writer = non_blocking_appender.with_max_level(max_log_level);\n\n let _ = tracing_subscriber::fmt() // Use `let _ =`\n .with_env_filter(env_filter)\n .with_writer(stderr_writer.and(file_writer))\n .with_ansi(true)\n .without_time()\n .try_init(); // Use try_init\n\n Box::leak(Box::new(guard)); // Keep guard alive\n\n tracing::debug!(\n // This will only work if try_init above was successful for this setup\n \"Verbose logging enabled. Writing logs to: {}/sps.log\",\n log_dir.display()\n );\n } else {\n let _ = tracing_subscriber::fmt() // Use `let _ =`\n .with_env_filter(env_filter)\n .with_writer(std::io::stderr)\n .with_ansi(true)\n .without_time()\n .try_init(); // Use try_init\n }\n\n let cache = Arc::new(Cache::new(&config).map_err(|e| {\n SpsError::Cache(format!(\n \"Could not initialize cache (ensure 'sps init' was successful): {e}\"\n ))\n })?);\n\n let needs_update_check = matches!(\n cli_args.command,\n Command::Install(_) | Command::Search { .. } | Command::Info { .. } | Command::Upgrade(_)\n );\n\n if needs_update_check {\n if let Err(e) = check_and_run_auto_update(&config, Arc::clone(&cache)).await {\n error!(\"Error during auto-update check: {}\", e); // Use `error!` macro\n }\n } else {\n debug!(\n // Use `debug!` macro\n \"Skipping auto-update check for command: {:?}\",\n cli_args.command\n );\n }\n\n // Pass config and cache to the command's run method\n let command_execution_result = match &cli_args.command {\n Command::Init(_) => {\n /* This case is handled above and main exits */\n unreachable!()\n }\n _ => cli_args.command.run(&config, cache).await,\n };\n\n if let Err(e) = command_execution_result {\n // For pipeline commands (Install, Reinstall, Upgrade), errors are already\n // displayed via the status system, so only log in verbose mode\n let is_pipeline_command = matches!(\n cli_args.command,\n Command::Install(_) | Command::Reinstall(_) | Command::Upgrade(_)\n );\n\n if is_pipeline_command {\n // Only show error details in verbose mode\n if cli_args.verbose > 0 {\n error!(\"Command failed: {:#}\", e);\n eprintln!(\"{}: {:#}\", \"Error\".red().bold(), e);\n }\n } else {\n // For non-pipeline commands, show errors normally\n error!(\"Command failed: {:#}\", e);\n eprintln!(\"{}: {:#}\", \"Error\".red().bold(), e);\n }\n process::exit(1);\n }\n\n debug!(\"Command completed successfully.\"); // Use `debug!` macro\n Ok(())\n}\n\nasync fn check_and_run_auto_update(config: &Config, cache: Arc) -> spResult<()> {\n if env::var(\"SPS_NO_AUTO_UPDATE\").is_ok_and(|v| v == \"1\") {\n debug!(\"Auto-update disabled via SPS_NO_AUTO_UPDATE=1.\");\n return Ok(());\n }\n\n let default_interval_secs: u64 = 86400;\n let update_interval_secs = env::var(\"SPS_AUTO_UPDATE_SECS\")\n .ok()\n .and_then(|s| s.parse::().ok())\n .unwrap_or(default_interval_secs);\n let update_interval = Duration::from_secs(update_interval_secs);\n debug!(\"Auto-update interval: {:?}\", update_interval);\n\n let timestamp_file = config.state_dir().join(\".sps_last_update_check\");\n debug!(\"Checking timestamp file: {}\", timestamp_file.display());\n\n if let Some(parent_dir) = timestamp_file.parent() {\n if !parent_dir.exists() {\n if let Err(e) = fs::create_dir_all(parent_dir) {\n warn!(\"Could not create state directory {} as user: {}. Auto-update might rely on 'sps init' to create this with sudo.\", parent_dir.display(), e);\n }\n }\n }\n\n let mut needs_update = true;\n if timestamp_file.exists() {\n if let Ok(metadata) = fs::metadata(×tamp_file) {\n if let Ok(modified_time) = metadata.modified() {\n match SystemTime::now().duration_since(modified_time) {\n Ok(age) => {\n debug!(\"Time since last update check: {:?}\", age);\n if age < update_interval {\n needs_update = false;\n debug!(\"Auto-update interval not yet passed.\");\n } else {\n debug!(\"Auto-update interval passed.\");\n }\n }\n Err(e) => {\n warn!(\n \"Could not get duration since last update check (system time error?): {}\",\n e\n );\n }\n }\n } else {\n warn!(\n \"Could not read modification time for timestamp file: {}\",\n timestamp_file.display()\n );\n }\n } else {\n debug!(\n \"Timestamp file {} metadata could not be read. Update needed.\",\n timestamp_file.display()\n );\n }\n } else {\n debug!(\n \"Timestamp file not found at {}. Update needed.\",\n timestamp_file.display()\n );\n }\n\n if needs_update {\n println!(\n \"{}{}\",\n \"==> \".bold().blue(),\n \"Running auto-update...\".bold()\n );\n match cli::update::Update.run(config, cache).await {\n Ok(_) => {\n println!(\n \"{}{}\",\n \"==> \".bold().blue(),\n \"Auto-update successful.\".bold()\n );\n match fs::File::create(×tamp_file) {\n Ok(_) => {\n debug!(\"Updated timestamp file: {}\", timestamp_file.display());\n }\n Err(e) => {\n warn!(\n \"Failed to create or update timestamp file '{}': {}\",\n timestamp_file.display(),\n e\n );\n }\n }\n }\n Err(e) => {\n error!(\"Auto-update failed: {}\", e);\n eprintln!(\"{} Auto-update failed: {}\", \"Warning:\".yellow(), e);\n }\n }\n } else {\n debug!(\"Skipping auto-update.\");\n }\n\n Ok(())\n}\n"], ["/sps/sps-core/src/check/installed.rs", "// sps-core/src/check/installed.rs\nuse std::fs::{self}; // Removed DirEntry as it's not directly used here\nuse std::io;\nuse std::path::PathBuf;\nuse std::sync::Arc;\n\nuse serde::{Deserialize, Serialize};\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::keg::KegRegistry; // KegRegistry is used\nuse tracing::{debug, warn};\n\n#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]\npub enum PackageType {\n Formula,\n Cask,\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub struct InstalledPackageInfo {\n pub name: String,\n pub version: String, // This will now store keg.version_str\n pub pkg_type: PackageType,\n pub path: PathBuf,\n}\n\n// Helper closure to handle io::Result -> Option logging errors\n// Defined outside the functions to avoid repetition\nfn handle_dir_entry(res: io::Result, dir_path_str: &str) -> Option {\n match res {\n Ok(entry) => Some(entry),\n Err(e) => {\n warn!(\"Error reading entry in {}: {}\", dir_path_str, e);\n None\n }\n }\n}\n\npub async fn get_installed_packages(config: &Config) -> Result> {\n let mut installed = Vec::new();\n let keg_registry = KegRegistry::new(config.clone());\n\n match keg_registry.list_installed_kegs() {\n Ok(kegs) => {\n for keg in kegs {\n installed.push(InstalledPackageInfo {\n name: keg.name,\n version: keg.version_str, // Use keg.version_str\n pkg_type: PackageType::Formula,\n path: keg.path,\n });\n }\n }\n Err(e) => warn!(\"Failed to list installed formulae: {}\", e),\n }\n\n let caskroom_dir = config.cask_room_dir();\n if caskroom_dir.is_dir() {\n let caskroom_dir_str = caskroom_dir.to_str().unwrap_or(\"caskroom\").to_string();\n let cask_token_entries_iter =\n fs::read_dir(&caskroom_dir).map_err(|e| SpsError::Io(Arc::new(e)))?;\n\n for entry_res in cask_token_entries_iter {\n if let Some(entry) = handle_dir_entry(entry_res, &caskroom_dir_str) {\n let cask_token_path = entry.path();\n if !cask_token_path.is_dir() {\n continue;\n }\n let cask_token = entry.file_name().to_string_lossy().to_string();\n\n match fs::read_dir(&cask_token_path) {\n Ok(version_entries_iter) => {\n for version_entry_res in version_entries_iter {\n if let Some(version_entry) = handle_dir_entry(\n version_entry_res,\n cask_token_path.to_str().unwrap_or(\"token_path\"),\n ) {\n let version_path = version_entry.path();\n if version_path.is_dir()\n && version_path.join(\"CASK_INSTALL_MANIFEST.json\").is_file()\n {\n let version_str =\n version_entry.file_name().to_string_lossy().to_string();\n let manifest_path =\n version_path.join(\"CASK_INSTALL_MANIFEST.json\");\n let mut include = true;\n if manifest_path.is_file() {\n if let Ok(manifest_str) =\n std::fs::read_to_string(&manifest_path)\n {\n if let Ok(manifest_json) =\n serde_json::from_str::(\n &manifest_str,\n )\n {\n if let Some(is_installed) = manifest_json\n .get(\"is_installed\")\n .and_then(|v| v.as_bool())\n {\n include = is_installed;\n }\n }\n }\n }\n if include {\n installed.push(InstalledPackageInfo {\n name: cask_token.clone(),\n version: version_str,\n pkg_type: PackageType::Cask,\n path: version_path,\n });\n }\n // Assuming one actively installed version per cask token based\n // on manifest logic\n // If multiple version folders exist but only one manifest says\n // is_installed=true, this is fine.\n // If the intent is to list *all* version folders, the break\n // might be removed,\n // but then \"is_installed\" logic per version becomes more\n // important.\n // For now, finding the first \"active\" one is usually sufficient\n // for list/upgrade checks.\n }\n }\n }\n }\n Err(e) => warn!(\"Failed to read cask versions for {}: {}\", cask_token, e),\n }\n }\n }\n } else {\n debug!(\n \"Caskroom directory {} does not exist.\",\n caskroom_dir.display()\n );\n }\n Ok(installed)\n}\n\npub async fn get_installed_package(\n name: &str,\n config: &Config,\n) -> Result> {\n let keg_registry = KegRegistry::new(config.clone());\n if let Some(keg) = keg_registry.get_installed_keg(name)? {\n return Ok(Some(InstalledPackageInfo {\n name: keg.name,\n version: keg.version_str, // Use keg.version_str\n pkg_type: PackageType::Formula,\n path: keg.path,\n }));\n }\n\n let cask_token_path = config.cask_room_token_path(name);\n if cask_token_path.is_dir() {\n let version_entries_iter =\n fs::read_dir(&cask_token_path).map_err(|e| SpsError::Io(Arc::new(e)))?;\n for version_entry_res in version_entries_iter {\n if let Some(version_entry) = handle_dir_entry(\n version_entry_res,\n cask_token_path.to_str().unwrap_or(\"token_path\"),\n ) {\n let version_path = version_entry.path();\n if version_path.is_dir()\n && version_path.join(\"CASK_INSTALL_MANIFEST.json\").is_file()\n {\n let version_str = version_entry.file_name().to_string_lossy().to_string();\n let manifest_path = version_path.join(\"CASK_INSTALL_MANIFEST.json\");\n let mut include = true;\n if manifest_path.is_file() {\n if let Ok(manifest_str) = std::fs::read_to_string(&manifest_path) {\n if let Ok(manifest_json) =\n serde_json::from_str::(&manifest_str)\n {\n if let Some(is_installed) =\n manifest_json.get(\"is_installed\").and_then(|v| v.as_bool())\n {\n include = is_installed;\n }\n }\n }\n }\n if include {\n return Ok(Some(InstalledPackageInfo {\n name: name.to_string(),\n version: version_str,\n pkg_type: PackageType::Cask,\n path: version_path,\n }));\n }\n }\n }\n }\n }\n Ok(None)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/app.rs", "// In sps-core/src/build/cask/app.rs\n\nuse std::fs;\nuse std::path::{Path, PathBuf};\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::{debug, error, warn};\n\n#[cfg(target_os = \"macos\")]\n/// Finds the primary .app bundle in a directory. Returns an error if none or ambiguous.\n/// If multiple .app bundles are found, returns the first and logs a warning.\npub fn find_primary_app_bundle_in_dir(dir: &Path) -> Result {\n if !dir.is_dir() {\n return Err(SpsError::NotFound(format!(\n \"Directory {} not found for app bundle scan.\",\n dir.display()\n )));\n }\n let mut app_bundles = Vec::new();\n for entry_res in fs::read_dir(dir)? {\n let entry = entry_res?;\n let path = entry.path();\n if path.is_dir() && path.extension().is_some_and(|ext| ext == \"app\") {\n app_bundles.push(path);\n }\n }\n if app_bundles.is_empty() {\n Err(SpsError::NotFound(format!(\n \"No .app bundle found in {}\",\n dir.display()\n )))\n } else if app_bundles.len() == 1 {\n Ok(app_bundles.remove(0))\n } else {\n // Heuristic: return the largest .app bundle if multiple are found, or one matching a common\n // pattern. For now, error if multiple are present to force explicit handling in\n // Cask definitions if needed.\n warn!(\"Multiple .app bundles found in {}: {:?}. Returning the first one, but this might be ambiguous.\", dir.display(), app_bundles);\n Ok(app_bundles.remove(0)) // Or error out\n }\n}\n\nuse sps_common::pipeline::JobAction;\n\npub fn install_app_from_staged(\n cask: &Cask,\n staged_app_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n job_action: &JobAction,\n) -> Result> {\n if !staged_app_path.exists() || !staged_app_path.is_dir() {\n return Err(SpsError::NotFound(format!(\n \"Staged app bundle for {} not found or is not a directory: {}\",\n cask.token,\n staged_app_path.display()\n )));\n }\n\n let app_name = staged_app_path\n .file_name()\n .ok_or_else(|| {\n SpsError::Generic(format!(\n \"Invalid staged app path (no filename): {}\",\n staged_app_path.display()\n ))\n })?\n .to_string_lossy();\n\n let new_version_str = cask.version.clone().unwrap_or_else(|| \"latest\".to_string());\n let final_private_store_app_path: PathBuf;\n\n // Determine if we are upgrading and if the old private store app path exists\n let mut did_upgrade = false;\n\n if let JobAction::Upgrade {\n from_version,\n old_install_path,\n ..\n } = job_action\n {\n debug!(\n \"[{}] Processing app install as UPGRADE from version {}\",\n cask.token, from_version\n );\n\n // Try to get primary_app_file_name from the old manifest to build the old private store\n // path\n let old_manifest_path = old_install_path.join(\"CASK_INSTALL_MANIFEST.json\");\n let old_primary_app_name = if old_manifest_path.is_file() {\n fs::read_to_string(&old_manifest_path)\n .ok()\n .and_then(|s| {\n serde_json::from_str::(&s).ok()\n })\n .and_then(|m| m.primary_app_file_name)\n } else {\n // Fallback if old manifest is missing, use current app_name (less reliable if app name\n // changed)\n warn!(\"[{}] Old manifest not found at {} during upgrade. Using current app name '{}' for private store path derivation.\", cask.token, old_manifest_path.display(), app_name);\n Some(app_name.to_string())\n };\n\n if let Some(name_for_old_path) = old_primary_app_name {\n let old_private_store_app_dir_path =\n config.cask_store_version_path(&cask.token, from_version);\n let old_private_store_app_bundle_path =\n old_private_store_app_dir_path.join(&name_for_old_path);\n if old_private_store_app_bundle_path.exists()\n && old_private_store_app_bundle_path.is_dir()\n {\n debug!(\"[{}] UPGRADE: Old private store app bundle found at {}. Using Homebrew-style overwrite strategy.\", cask.token, old_private_store_app_bundle_path.display());\n\n // ========================================================================\n // CRITICAL: Homebrew-Style App Bundle Replacement Strategy\n // ========================================================================\n // WHY THIS APPROACH:\n // 1. Preserves extended attributes (quarantine, code signing, etc.)\n // 2. Maintains app bundle identity → prevents Gatekeeper reset\n // 3. Avoids breaking symlinks and file system references\n // 4. Ensures user data in ~/Library remains accessible to the app\n //\n // DO NOT CHANGE TO fs::rename() or similar - it breaks Gatekeeper!\n // ========================================================================\n\n // Step 1: Remove the old app bundle from private store\n // (This is safe because we're about to replace it with the new version)\n let rm_status = Command::new(\"rm\")\n .arg(\"-rf\")\n .arg(&old_private_store_app_bundle_path)\n .status()\n .map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n\n if !rm_status.success() {\n return Err(SpsError::InstallError(format!(\n \"Failed to remove old app bundle during upgrade: {}\",\n old_private_store_app_bundle_path.display()\n )));\n }\n\n // Step 2: Copy the new app bundle with ALL attributes preserved\n // The -pR flags are critical:\n // -p: Preserve file attributes, ownership, timestamps\n // -R: Recursive copy for directories\n // This ensures Gatekeeper approval and code signing are maintained\n let cp_status = Command::new(\"cp\")\n .arg(\"-pR\") // CRITICAL: Preserve all attributes, links, and metadata\n .arg(staged_app_path)\n .arg(&old_private_store_app_bundle_path)\n .status()\n .map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n\n if !cp_status.success() {\n return Err(SpsError::InstallError(format!(\n \"Failed to copy new app bundle during upgrade: {} -> {}\",\n staged_app_path.display(),\n old_private_store_app_bundle_path.display()\n )));\n }\n\n debug!(\n \"[{}] UPGRADE: Successfully overwrote old app bundle with new version using cp -pR\",\n cask.token\n );\n\n // Now, rename the parent version directory (e.g., .../1.0 -> .../1.1)\n let new_private_store_version_dir =\n config.cask_store_version_path(&cask.token, &new_version_str);\n if old_private_store_app_dir_path != new_private_store_version_dir {\n debug!(\n \"[{}] Renaming private store version dir from {} to {}\",\n cask.token,\n old_private_store_app_dir_path.display(),\n new_private_store_version_dir.display()\n );\n fs::rename(\n &old_private_store_app_dir_path,\n &new_private_store_version_dir,\n )\n .map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n }\n final_private_store_app_path =\n new_private_store_version_dir.join(app_name.as_ref());\n did_upgrade = true;\n } else {\n warn!(\"[{}] UPGRADE: Old private store app path {} not found or not a dir. Proceeding with fresh private store placement for new version.\", cask.token, old_private_store_app_bundle_path.display());\n // Fallback to fresh placement\n final_private_store_app_path =\n config.cask_store_app_path(&cask.token, &new_version_str, app_name.as_ref());\n }\n } else {\n warn!(\"[{}] UPGRADE: Could not determine old app bundle name. Proceeding with fresh private store placement for new version.\", cask.token);\n final_private_store_app_path =\n config.cask_store_app_path(&cask.token, &new_version_str, app_name.as_ref());\n }\n } else {\n // Not an upgrade\n final_private_store_app_path =\n config.cask_store_app_path(&cask.token, &new_version_str, app_name.as_ref());\n }\n\n let final_app_destination_in_applications = config.applications_dir().join(app_name.as_ref());\n let caskroom_symlink_to_final_app = cask_version_install_path.join(app_name.as_ref());\n\n debug!(\n \"Installing app '{}': Staged -> Private Store -> /Applications -> Caskroom Symlink\",\n app_name\n );\n debug!(\" Staged app source: {}\", staged_app_path.display());\n debug!(\n \" Private store copy target: {}\",\n final_private_store_app_path.display()\n );\n debug!(\n \" Final /Applications target: {}\",\n final_app_destination_in_applications.display()\n );\n debug!(\n \" Caskroom symlink target: {}\",\n caskroom_symlink_to_final_app.display()\n );\n\n // 1. Ensure Caskroom version path exists\n if !cask_version_install_path.exists() {\n fs::create_dir_all(cask_version_install_path).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\n \"Failed to create cask version dir {}: {}\",\n cask_version_install_path.display(),\n e\n ),\n )))\n })?;\n }\n\n // 2. Create private store directory if it doesn't exist\n if let Some(parent) = final_private_store_app_path.parent() {\n if !parent.exists() {\n debug!(\"Creating private store directory: {}\", parent.display());\n fs::create_dir_all(parent).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\n \"Failed to create private store dir {}: {}\",\n parent.display(),\n e\n ),\n )))\n })?;\n }\n }\n\n if !did_upgrade {\n // 3. Clean existing app in private store (if any from a failed prior attempt)\n if final_private_store_app_path.exists()\n || final_private_store_app_path.symlink_metadata().is_ok()\n {\n debug!(\n \"Removing existing item at private store path: {}\",\n final_private_store_app_path.display()\n );\n let _ = remove_path_robustly(&final_private_store_app_path, config, false);\n }\n\n // 4. Move from temporary stage to private store\n debug!(\n \"Moving staged app {} to private store path {}\",\n staged_app_path.display(),\n final_private_store_app_path.display()\n );\n if let Err(e) = fs::rename(staged_app_path, &final_private_store_app_path) {\n error!(\n \"Failed to move staged app to private store: {}. Source: {}, Dest: {}\",\n e,\n staged_app_path.display(),\n final_private_store_app_path.display()\n );\n return Err(SpsError::Io(std::sync::Arc::new(e)));\n }\n }\n\n // 5. Set/Verify Quarantine on private store copy (only if not already present)\n #[cfg(target_os = \"macos\")]\n {\n debug!(\n \"Setting/verifying quarantine on private store copy: {}\",\n final_private_store_app_path.display()\n );\n if let Err(e) = crate::utils::xattr::ensure_quarantine_attribute(\n &final_private_store_app_path,\n &cask.token,\n ) {\n error!(\n \"Failed to set quarantine on private store copy {}: {}. This is critical.\",\n final_private_store_app_path.display(),\n e\n );\n return Err(SpsError::InstallError(format!(\n \"Failed to set quarantine on private store copy {}: {}\",\n final_private_store_app_path.display(),\n e\n )));\n }\n }\n\n // ============================================================================\n // STEP 6: Handle /Applications Destination - THE MOST CRITICAL PART\n // ============================================================================\n // This is where we apply Homebrew's breakthrough strategy that preserves\n // user data and prevents Gatekeeper resets during upgrades.\n //\n // UPGRADE vs FRESH INSTALL Strategy:\n // - UPGRADE: Overwrite app in /Applications directly (preserves identity)\n // - FRESH INSTALL: Use symlink approach (normal installation)\n //\n // WHY THIS SPLIT MATTERS:\n // During upgrades, the app in /Applications already has:\n // 1. Gatekeeper approval and quarantine exemptions\n // 2. Extended attributes that macOS recognizes\n // 3. User trust and security context\n // 4. Associated user data in ~/Library that the app can access\n //\n // By overwriting IN PLACE with cp -pR, we maintain all of this state.\n // ============================================================================\n\n if let JobAction::Upgrade { .. } = job_action {\n // =======================================================================\n // UPGRADE PATH: Direct Overwrite Strategy (Homebrew's Approach)\n // =======================================================================\n // This is the breakthrough that prevents Gatekeeper resets and data loss.\n // We overwrite the existing app directly rather than removing and\n // re-symlinking, which would break the app's established identity.\n // =======================================================================\n\n if final_app_destination_in_applications.exists() {\n debug!(\n \"UPGRADE: Overwriting existing app at /Applications using Homebrew strategy: {}\",\n final_app_destination_in_applications.display()\n );\n\n // Step 1: Remove the old app in /Applications\n // We need sudo because /Applications requires elevated permissions\n let rm_status = Command::new(\"sudo\")\n .arg(\"rm\")\n .arg(\"-rf\")\n .arg(&final_app_destination_in_applications)\n .status()\n .map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n\n if !rm_status.success() {\n return Err(SpsError::InstallError(format!(\n \"Failed to remove existing app during upgrade: {}\",\n final_app_destination_in_applications.display()\n )));\n }\n\n // Copy the new app directly to /Applications, preserving all attributes\n let cp_status = Command::new(\"sudo\")\n .arg(\"cp\")\n .arg(\"-pR\") // Preserve all attributes, links, and metadata\n .arg(&final_private_store_app_path)\n .arg(&final_app_destination_in_applications)\n .status()\n .map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n\n if !cp_status.success() {\n return Err(SpsError::InstallError(format!(\n \"Failed to copy new app to /Applications during upgrade: {}\",\n final_app_destination_in_applications.display()\n )));\n }\n\n debug!(\n \"UPGRADE: Successfully overwrote app in /Applications, preserving identity: {}\",\n final_app_destination_in_applications.display()\n );\n } else {\n // App doesn't exist in /Applications during upgrade - fall back to symlink approach\n debug!(\n \"UPGRADE: App not found in /Applications, creating fresh symlink: {}\",\n final_app_destination_in_applications.display()\n );\n if let Err(e) = std::os::unix::fs::symlink(\n &final_private_store_app_path,\n &final_app_destination_in_applications,\n ) {\n error!(\n \"Failed to symlink app from private store to /Applications: {} -> {}: {}\",\n final_private_store_app_path.display(),\n final_app_destination_in_applications.display(),\n e\n );\n return Err(SpsError::InstallError(format!(\n \"Failed to symlink app from private store to {}: {}\",\n final_app_destination_in_applications.display(),\n e\n )));\n }\n }\n } else {\n // Fresh install: Clean existing app destination and create symlink\n if final_app_destination_in_applications.exists()\n || final_app_destination_in_applications\n .symlink_metadata()\n .is_ok()\n {\n debug!(\n \"Removing existing app at /Applications: {}\",\n final_app_destination_in_applications.display()\n );\n if !remove_path_robustly(&final_app_destination_in_applications, config, true) {\n return Err(SpsError::InstallError(format!(\n \"Failed to remove existing app at {}\",\n final_app_destination_in_applications.display()\n )));\n }\n }\n\n // 7. Symlink from /Applications to private store app bundle\n debug!(\n \"INFO: About to symlink app from private store {} to /Applications {}\",\n final_private_store_app_path.display(),\n final_app_destination_in_applications.display()\n );\n if let Err(e) = std::os::unix::fs::symlink(\n &final_private_store_app_path,\n &final_app_destination_in_applications,\n ) {\n error!(\n \"Failed to symlink app from private store to /Applications: {} -> {}: {}\",\n final_private_store_app_path.display(),\n final_app_destination_in_applications.display(),\n e\n );\n return Err(SpsError::InstallError(format!(\n \"Failed to symlink app from private store to {}: {}\",\n final_app_destination_in_applications.display(),\n e\n )));\n }\n }\n\n // Remove quarantine attributes from the app in /Applications (whether copied or symlinked)\n #[cfg(target_os = \"macos\")]\n {\n use xattr;\n let _ = xattr::remove(\n &final_app_destination_in_applications,\n \"com.apple.quarantine\",\n );\n let _ = xattr::remove(\n &final_app_destination_in_applications,\n \"com.apple.provenance\",\n );\n let _ = xattr::remove(&final_app_destination_in_applications, \"com.apple.macl\");\n }\n\n match job_action {\n JobAction::Upgrade { .. } => {\n debug!(\n \"INFO: Successfully updated app in /Applications during upgrade: {}\",\n final_app_destination_in_applications.display()\n );\n }\n _ => {\n debug!(\n \"INFO: Successfully symlinked app from private store {} to /Applications {}\",\n final_private_store_app_path.display(),\n final_app_destination_in_applications.display()\n );\n }\n }\n\n // 7. No quarantine set on the symlink in /Applications; attribute remains on private store\n // copy.\n\n // 8. Create Caskroom Symlink TO the app in /Applications\n let actual_caskroom_symlink_path = cask_version_install_path.join(app_name.as_ref());\n debug!(\n \"Creating Caskroom symlink {} -> {}\",\n actual_caskroom_symlink_path.display(),\n final_app_destination_in_applications.display()\n );\n\n if actual_caskroom_symlink_path.symlink_metadata().is_ok() {\n if let Err(e) = fs::remove_file(&actual_caskroom_symlink_path) {\n warn!(\n \"Failed to remove existing item at Caskroom symlink path {}: {}. Proceeding.\",\n actual_caskroom_symlink_path.display(),\n e\n );\n }\n }\n\n #[cfg(unix)]\n {\n if let Err(e) = std::os::unix::fs::symlink(\n &final_app_destination_in_applications,\n &actual_caskroom_symlink_path,\n ) {\n error!(\n \"Failed to create Caskroom symlink {} -> {}: {}\",\n actual_caskroom_symlink_path.display(),\n final_app_destination_in_applications.display(),\n e\n );\n let _ = remove_path_robustly(&final_app_destination_in_applications, config, true);\n return Err(SpsError::Io(std::sync::Arc::new(e)));\n }\n }\n\n let mut created_artifacts = vec![InstalledArtifact::AppBundle {\n path: final_app_destination_in_applications.clone(),\n }];\n created_artifacts.push(InstalledArtifact::CaskroomLink {\n link_path: actual_caskroom_symlink_path,\n target_path: final_app_destination_in_applications.clone(),\n });\n\n debug!(\n \"Successfully installed app artifact: {} (Cask: {})\",\n app_name, cask.token\n );\n\n // Write CASK_INSTALL_MANIFEST.json to ensure package is always detected as installed\n if let Err(e) = crate::install::cask::write_cask_manifest(\n cask,\n cask_version_install_path,\n created_artifacts.clone(),\n ) {\n error!(\n \"Failed to write CASK_INSTALL_MANIFEST.json for {}: {}\",\n cask.token, e\n );\n return Err(SpsError::InstallError(format!(\n \"Failed to write CASK_INSTALL_MANIFEST.json for {}: {}\",\n cask.token, e\n )));\n }\n\n Ok(created_artifacts)\n}\n\n/// Helper function for robust path removal (internal to app.rs or moved to a common util)\nfn remove_path_robustly(path: &Path, _config: &Config, use_sudo_if_needed: bool) -> bool {\n if !path.exists() && path.symlink_metadata().is_err() {\n debug!(\"Path {} not found for removal.\", path.display());\n return true;\n }\n let is_dir = path.is_dir()\n && !path\n .symlink_metadata()\n .is_ok_and(|m| m.file_type().is_symlink());\n let removal_op = || -> std::io::Result<()> {\n if is_dir {\n fs::remove_dir_all(path)\n } else {\n fs::remove_file(path)\n }\n };\n\n if let Err(e) = removal_op() {\n if e.kind() == std::io::ErrorKind::NotFound {\n return true;\n }\n if use_sudo_if_needed && e.kind() == std::io::ErrorKind::PermissionDenied {\n warn!(\n \"Direct removal of {} failed (Permission Denied). Trying with sudo rm -rf.\",\n path.display()\n );\n let output = Command::new(\"sudo\").arg(\"rm\").arg(\"-rf\").arg(path).output();\n match output {\n Ok(out) if out.status.success() => {\n debug!(\"Successfully removed {} with sudo.\", path.display());\n return true;\n }\n Ok(out) => {\n error!(\n \"`sudo rm -rf {}` failed ({}): {}\",\n path.display(),\n out.status,\n String::from_utf8_lossy(&out.stderr).trim()\n );\n return false;\n }\n Err(sudo_e) => {\n error!(\n \"Error executing `sudo rm -rf` for {}: {}\",\n path.display(),\n sudo_e\n );\n return false;\n }\n }\n } else {\n error!(\"Failed to remove {}: {}\", path.display(), e);\n return false;\n }\n }\n debug!(\"Successfully removed {}.\", path.display());\n true\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/installer.rs", "// ===== sps-core/src/build/cask/artifacts/installer.rs =====\n\nuse std::path::Path;\nuse std::process::{Command, Stdio};\n\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::InstalledArtifact;\n\n// Helper to validate that the executable is a filename (relative, no '/' or \"..\")\nfn validate_filename_or_relative_path(file: &str) -> Result {\n if file.starts_with(\"/\") || file.contains(\"..\") || file.contains(\"/\") {\n return Err(SpsError::Generic(format!(\n \"Invalid executable filename: {file}\"\n )));\n }\n Ok(file.to_string())\n}\n\n// Helper to validate a command argument based on allowed characters or allowed option form\nfn validate_argument(arg: &str) -> Result {\n if arg.starts_with(\"-\") {\n return Ok(arg.to_string());\n }\n if arg.starts_with(\"/\") || arg.contains(\"..\") || arg.contains(\"/\") {\n return Err(SpsError::Generic(format!(\"Invalid argument: {arg}\")));\n }\n if !arg\n .chars()\n .all(|c| c.is_alphanumeric() || c == '-' || c == '_' || c == '.')\n {\n return Err(SpsError::Generic(format!(\n \"Invalid characters in argument: {arg}\"\n )));\n }\n Ok(arg.to_string())\n}\n\n/// Implements the `installer` stanza:\n/// - `manual`: prints instructions to open the staged path.\n/// - `script`: runs the given executable with args, under sudo if requested.\n///\n/// Mirrors Homebrew’s `Cask::Artifact::Installer` behavior :contentReference[oaicite:1]{index=1}.\npub fn run_installer(\n cask: &Cask,\n stage_path: &Path,\n _cask_version_install_path: &Path,\n _config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n // Find the `installer` definitions in the raw JSON artifacts\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(insts) = obj.get(\"installer\").and_then(|v| v.as_array()) {\n for inst in insts {\n if let Some(inst_obj) = inst.as_object() {\n if let Some(man) = inst_obj.get(\"manual\").and_then(|v| v.as_str()) {\n debug!(\n \"Cask {} requires manual install. To finish:\\n open {}\",\n cask.token,\n stage_path.join(man).display()\n );\n continue;\n }\n let exe_key = if inst_obj.contains_key(\"script\") {\n \"script\"\n } else {\n \"executable\"\n };\n let executable = inst_obj\n .get(exe_key)\n .and_then(|v| v.as_str())\n .ok_or_else(|| {\n SpsError::Generic(format!(\n \"installer stanza missing '{exe_key}' field\"\n ))\n })?;\n let args: Vec = inst_obj\n .get(\"args\")\n .and_then(|v| v.as_array())\n .map(|arr| {\n arr.iter()\n .filter_map(|a| a.as_str().map(String::from))\n .collect()\n })\n .unwrap_or_default();\n let use_sudo = inst_obj\n .get(\"sudo\")\n .and_then(|v| v.as_bool())\n .unwrap_or(false);\n\n let validated_executable =\n validate_filename_or_relative_path(executable)?;\n let mut validated_args = Vec::new();\n for arg in &args {\n validated_args.push(validate_argument(arg)?);\n }\n\n let script_path = stage_path.join(&validated_executable);\n if !script_path.exists() {\n return Err(SpsError::NotFound(format!(\n \"Installer script not found: {}\",\n script_path.display()\n )));\n }\n\n debug!(\n \"Running installer script '{}' for cask {}\",\n script_path.display(),\n cask.token\n );\n let mut cmd = if use_sudo {\n let mut c = Command::new(\"sudo\");\n c.arg(script_path.clone());\n c\n } else {\n Command::new(script_path.clone())\n };\n cmd.args(&validated_args);\n cmd.stdin(Stdio::null())\n .stdout(Stdio::inherit())\n .stderr(Stdio::inherit());\n\n let status = cmd.status().map_err(|e| {\n SpsError::Generic(format!(\"Failed to spawn installer script: {e}\"))\n })?;\n if !status.success() {\n return Err(SpsError::InstallError(format!(\n \"Installer script exited with {status}\"\n )));\n }\n\n installed\n .push(InstalledArtifact::CaskroomReference { path: script_path });\n }\n }\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/bottle/link.rs", "// ===== sps-core/src/build/formula/link.rs =====\nuse std::fs;\nuse std::io::Write;\nuse std::os::unix::fs as unix_fs;\n#[cfg(unix)]\nuse std::os::unix::fs::PermissionsExt;\nuse std::path::{Path, PathBuf};\n\nuse serde_json;\nuse sps_common::config::Config; // Import Config\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::formula::Formula;\nuse tracing::{debug, error};\n\nconst STANDARD_KEG_DIRS: [&str; 6] = [\"bin\", \"lib\", \"share\", \"include\", \"etc\", \"Frameworks\"];\n\n/// Link all artifacts from a formula's installation directory.\n// Added Config parameter\npub fn link_formula_artifacts(\n formula: &Formula,\n installed_keg_path: &Path,\n config: &Config, // Added config\n) -> Result<()> {\n debug!(\n \"Linking artifacts for {} from {}\",\n formula.name(),\n installed_keg_path.display()\n );\n\n let formula_content_root = determine_content_root(installed_keg_path)?;\n let mut symlinks_created = Vec::::new();\n\n // Use config methods for paths\n let opt_link_path = config.formula_opt_path(formula.name());\n let target_keg_dir = &formula_content_root;\n\n remove_existing_link_target(&opt_link_path)?;\n unix_fs::symlink(target_keg_dir, &opt_link_path).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed to create opt symlink for {}: {}\", formula.name(), e),\n )))\n })?;\n symlinks_created.push(opt_link_path.to_string_lossy().to_string());\n debug!(\n \" Linked opt path: {} -> {}\",\n opt_link_path.display(),\n target_keg_dir.display()\n );\n\n if let Some((base, _version)) = formula.name().split_once('@') {\n let alias_path = config.opt_dir().join(base); // Use config.opt_dir()\n if !alias_path.exists() {\n match unix_fs::symlink(target_keg_dir, &alias_path) {\n Ok(_) => {\n debug!(\n \" Added un‑versioned opt alias: {} -> {}\",\n alias_path.display(),\n target_keg_dir.display()\n );\n symlinks_created.push(alias_path.to_string_lossy().to_string());\n }\n Err(e) => {\n debug!(\n \" Could not create opt alias {}: {}\",\n alias_path.display(),\n e\n );\n }\n }\n }\n }\n\n let standard_artifact_dirs = [\"lib\", \"include\", \"share\"];\n for dir_name in &standard_artifact_dirs {\n let source_subdir = formula_content_root.join(dir_name);\n // Use config.prefix() for target base\n let target_prefix_subdir = config.sps_root().join(dir_name);\n\n if source_subdir.is_dir() {\n fs::create_dir_all(&target_prefix_subdir)?;\n for entry in fs::read_dir(&source_subdir)? {\n let entry = entry?;\n let source_item_path = entry.path();\n let file_name = entry.file_name();\n if file_name.to_string_lossy().starts_with('.') {\n continue;\n }\n\n let target_link = target_prefix_subdir.join(&file_name);\n remove_existing_link_target(&target_link)?;\n unix_fs::symlink(&source_item_path, &target_link).ok(); // ignore errors for individual links?\n symlinks_created.push(target_link.to_string_lossy().to_string());\n debug!(\n \" Linked {} -> {}\",\n target_link.display(),\n source_item_path.display()\n );\n }\n }\n }\n\n // Use config.bin_dir() for target bin\n let target_bin_dir = config.bin_dir();\n fs::create_dir_all(&target_bin_dir).ok();\n\n let source_bin_dir = formula_content_root.join(\"bin\");\n if source_bin_dir.is_dir() {\n create_wrappers_in_dir(\n &source_bin_dir,\n &target_bin_dir,\n &formula_content_root,\n &mut symlinks_created,\n )?;\n }\n let source_libexec_dir = formula_content_root.join(\"libexec\");\n if source_libexec_dir.is_dir() {\n create_wrappers_in_dir(\n &source_libexec_dir,\n &target_bin_dir,\n &formula_content_root,\n &mut symlinks_created,\n )?;\n }\n\n write_install_manifest(installed_keg_path, &symlinks_created)?;\n\n debug!(\n \"Successfully completed linking artifacts for {}\",\n formula.name()\n );\n Ok(())\n}\n\n// remove_existing_link_target, write_install_manifest remain mostly unchanged internally) ...\nfn create_wrappers_in_dir(\n source_dir: &Path,\n target_bin_dir: &Path,\n formula_content_root: &Path,\n wrappers_created: &mut Vec,\n) -> Result<()> {\n debug!(\n \"Scanning for executables in {} to create wrappers in {}\",\n source_dir.display(),\n target_bin_dir.display()\n );\n match fs::read_dir(source_dir) {\n Ok(entries) => {\n for entry_result in entries {\n match entry_result {\n Ok(entry) => {\n let source_item_path = entry.path();\n let file_name = entry.file_name();\n\n if file_name.to_string_lossy().starts_with('.') {\n continue;\n }\n\n if source_item_path.is_dir() {\n create_wrappers_in_dir(\n &source_item_path,\n target_bin_dir,\n formula_content_root,\n wrappers_created,\n )?;\n } else if source_item_path.is_file() {\n match is_executable(&source_item_path) {\n Ok(true) => {\n let wrapper_path = target_bin_dir.join(&file_name);\n debug!(\"Found executable: {}\", source_item_path.display());\n if remove_existing_link_target(&wrapper_path).is_ok() {\n debug!(\n \" Creating wrapper script: {} -> {}\",\n wrapper_path.display(),\n source_item_path.display()\n );\n match create_wrapper_script(\n &source_item_path,\n &wrapper_path,\n formula_content_root,\n ) {\n Ok(_) => {\n debug!(\n \" Created wrapper {} -> {}\",\n wrapper_path.display(),\n source_item_path.display()\n );\n wrappers_created.push(\n wrapper_path.to_string_lossy().to_string(),\n );\n }\n Err(e) => {\n error!(\n \"Failed to create wrapper script {} -> {}: {}\",\n wrapper_path.display(),\n source_item_path.display(),\n e\n );\n }\n }\n }\n }\n Ok(false) => { /* Not executable, ignore */ }\n Err(e) => {\n debug!(\n \" Could not check executable status for {}: {}\",\n source_item_path.display(),\n e\n );\n }\n }\n }\n }\n Err(e) => {\n debug!(\n \" Failed to process directory entry in {}: {}\",\n source_dir.display(),\n e\n );\n }\n }\n }\n }\n Err(e) => {\n debug!(\n \"Failed to read source directory {}: {}\",\n source_dir.display(),\n e\n );\n }\n }\n Ok(())\n}\nfn create_wrapper_script(\n target_executable: &Path,\n wrapper_path: &Path,\n formula_content_root: &Path,\n) -> Result<()> {\n let libexec_path = formula_content_root.join(\"libexec\");\n let perl_lib_path = libexec_path.join(\"lib\").join(\"perl5\");\n let python_lib_path = libexec_path.join(\"vendor\"); // Assuming simple vendor dir\n\n let mut script_content = String::new();\n script_content.push_str(\"#!/bin/bash\\n\");\n script_content.push_str(\"# Wrapper script generated by sp\\n\");\n script_content.push_str(\"set -e\\n\\n\");\n\n if perl_lib_path.exists() && perl_lib_path.is_dir() {\n script_content.push_str(&format!(\n \"export PERL5LIB=\\\"{}:$PERL5LIB\\\"\\n\",\n perl_lib_path.display()\n ));\n debug!(\n \" (Wrapper will set PERL5LIB to {})\",\n perl_lib_path.display()\n );\n }\n if python_lib_path.exists() && python_lib_path.is_dir() {\n script_content.push_str(&format!(\n \"export PYTHONPATH=\\\"{}:$PYTHONPATH\\\"\\n\",\n python_lib_path.display()\n ));\n debug!(\n \" (Wrapper will set PYTHONPATH to {})\",\n python_lib_path.display()\n );\n }\n\n script_content.push_str(&format!(\n \"\\nexec \\\"{}\\\" \\\"$@\\\"\\n\",\n target_executable.display()\n ));\n\n let mut file = fs::File::create(wrapper_path).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed create wrapper {}: {}\", wrapper_path.display(), e),\n )))\n })?;\n file.write_all(script_content.as_bytes()).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed write wrapper {}: {}\", wrapper_path.display(), e),\n )))\n })?;\n\n #[cfg(unix)]\n {\n let metadata = file.metadata()?;\n let mut permissions = metadata.permissions();\n permissions.set_mode(0o755);\n fs::set_permissions(wrapper_path, permissions).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\n \"Failed set wrapper executable {}: {}\",\n wrapper_path.display(),\n e\n ),\n )))\n })?;\n }\n\n Ok(())\n}\n\nfn determine_content_root(installed_keg_path: &Path) -> Result {\n let mut potential_subdirs = Vec::new();\n let mut top_level_files_found = false;\n if !installed_keg_path.is_dir() {\n error!(\n \"Keg path {} does not exist or is not a directory!\",\n installed_keg_path.display()\n );\n return Err(SpsError::NotFound(format!(\n \"Keg path not found: {}\",\n installed_keg_path.display()\n )));\n }\n match fs::read_dir(installed_keg_path) {\n Ok(entries) => {\n for entry_res in entries {\n if let Ok(entry) = entry_res {\n let path = entry.path();\n let file_name = entry.file_name();\n // --- Use OsStr comparison ---\n let file_name_osstr = file_name.as_os_str();\n if file_name_osstr.to_string_lossy().starts_with('.')\n || file_name_osstr == \"INSTALL_MANIFEST.json\"\n || file_name_osstr == \"INSTALL_RECEIPT.json\"\n {\n continue;\n }\n if path.is_dir() {\n // Store both path and name for check later\n potential_subdirs.push((path, file_name.to_string_lossy().to_string()));\n } else if path.is_file() {\n top_level_files_found = true;\n debug!(\n \"Found file '{}' at top level of keg {}, assuming no intermediate dir.\",\n file_name.to_string_lossy(), // Use lossy for display\n installed_keg_path.display()\n );\n break; // Stop scanning if top-level files found\n }\n } else {\n debug!(\n \"Failed to read directory entry in {}: {}\",\n installed_keg_path.display(),\n entry_res.err().unwrap() // Safe unwrap as we are in Err path\n );\n }\n }\n }\n Err(e) => {\n debug!(\n \"Could not read keg directory {} to check for intermediate dir: {}. Assuming keg path is content root.\",\n installed_keg_path.display(),\n e\n );\n return Ok(installed_keg_path.to_path_buf());\n }\n }\n\n // --- MODIFIED LOGIC ---\n if potential_subdirs.len() == 1 && !top_level_files_found {\n // Get the single subdirectory path and name\n let (intermediate_dir_path, intermediate_dir_name) = potential_subdirs.remove(0); // Use remove\n\n // Check if the single directory name is one of the standard install dirs\n if STANDARD_KEG_DIRS.contains(&intermediate_dir_name.as_str()) {\n debug!(\n \"Single directory found ('{}') is a standard directory. Using main keg directory {} as content root.\",\n intermediate_dir_name,\n installed_keg_path.display()\n );\n Ok(installed_keg_path.to_path_buf()) // Use main keg path\n } else {\n // Single dir is NOT a standard name, assume it's an intermediate content root\n debug!(\n \"Detected single non-standard intermediate content directory: {}\",\n intermediate_dir_path.display()\n );\n Ok(intermediate_dir_path) // Use the intermediate dir\n }\n // --- END MODIFIED LOGIC ---\n } else {\n // Handle multiple subdirs or top-level files found case (no change needed here)\n if potential_subdirs.len() > 1 {\n debug!(\n \"Multiple potential content directories found under keg {}. Using main keg directory as content root.\",\n installed_keg_path.display()\n );\n } else if top_level_files_found {\n debug!(\n \"Top-level files found in keg {}. Using main keg directory as content root.\",\n installed_keg_path.display()\n );\n } else if potential_subdirs.is_empty() {\n // Changed from else if to else\n debug!(\n \"No subdirectories or files found (excluding ignored ones) in keg {}. Using main keg directory as content root.\",\n installed_keg_path.display()\n );\n }\n Ok(installed_keg_path.to_path_buf()) // Use main keg path in these cases too\n }\n}\n\nfn remove_existing_link_target(path: &Path) -> Result<()> {\n match path.symlink_metadata() {\n Ok(metadata) => {\n debug!(\n \" Removing existing item at link target: {}\",\n path.display()\n );\n let is_dir = metadata.file_type().is_dir();\n let is_symlink = metadata.file_type().is_symlink();\n let is_real_dir = is_dir && !is_symlink;\n let remove_result = if is_real_dir {\n fs::remove_dir_all(path)\n } else {\n fs::remove_file(path)\n };\n if let Err(e) = remove_result {\n debug!(\n \" Failed to remove existing item at link target {}: {}\",\n path.display(),\n e\n );\n return Err(SpsError::Io(std::sync::Arc::new(e)));\n }\n Ok(())\n }\n Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),\n Err(e) => {\n debug!(\n \" Failed to get metadata for existing item {}: {}\",\n path.display(),\n e\n );\n Err(SpsError::Io(std::sync::Arc::new(e)))\n }\n }\n}\n\nfn write_install_manifest(installed_keg_path: &Path, symlinks_created: &[String]) -> Result<()> {\n let manifest_path = installed_keg_path.join(\"INSTALL_MANIFEST.json\");\n debug!(\"Writing install manifest to: {}\", manifest_path.display());\n match serde_json::to_string_pretty(&symlinks_created) {\n Ok(manifest_json) => match fs::write(&manifest_path, manifest_json) {\n Ok(_) => {\n debug!(\n \"Wrote install manifest with {} links: {}\",\n symlinks_created.len(),\n manifest_path.display()\n );\n }\n Err(e) => {\n error!(\n \"Failed to write install manifest {}: {}\",\n manifest_path.display(),\n e\n );\n return Err(SpsError::Io(std::sync::Arc::new(e)));\n }\n },\n Err(e) => {\n error!(\"Failed to serialize install manifest data: {}\", e);\n return Err(SpsError::Json(std::sync::Arc::new(e)));\n }\n }\n Ok(())\n}\n\npub fn unlink_formula_artifacts(\n formula_name: &str,\n version_str_full: &str, // e.g., \"1.2.3_1\"\n config: &Config,\n) -> Result<()> {\n debug!(\n \"Unlinking artifacts for {} version {}\",\n formula_name, version_str_full\n );\n // Use config method to get expected keg path based on name and version string\n let expected_keg_path = config.formula_keg_path(formula_name, version_str_full);\n let manifest_path = expected_keg_path.join(\"INSTALL_MANIFEST.json\"); // Manifest *inside* the keg\n\n if manifest_path.is_file() {\n debug!(\"Reading install manifest: {}\", manifest_path.display());\n match fs::read_to_string(&manifest_path) {\n Ok(manifest_str) => {\n match serde_json::from_str::>(&manifest_str) {\n Ok(links_to_remove) => {\n let mut unlinked_count = 0;\n let mut removal_errors = 0;\n if links_to_remove.is_empty() {\n debug!(\n \"Install manifest {} is empty. Cannot perform manifest-based unlink.\",\n manifest_path.display()\n );\n } else {\n // Use Config to get base paths for checking ownership/safety\n let opt_base = config.opt_dir();\n let bin_base = config.bin_dir();\n let lib_base = config.sps_root().join(\"lib\");\n let include_base = config.sps_root().join(\"include\");\n let share_base = config.sps_root().join(\"share\");\n // Add etc, sbin etc. if needed\n\n for link_str in links_to_remove {\n let link_path = PathBuf::from(link_str);\n // Check if it's under a managed directory (safety check)\n if link_path.starts_with(&opt_base)\n || link_path.starts_with(&bin_base)\n || link_path.starts_with(&lib_base)\n || link_path.starts_with(&include_base)\n || link_path.starts_with(&share_base)\n {\n match remove_existing_link_target(&link_path) {\n // Use helper\n Ok(_) => {\n debug!(\"Removed link/wrapper: {}\", link_path.display());\n unlinked_count += 1;\n }\n Err(e) => {\n // Log error but continue trying to remove others\n debug!(\n \"Failed to remove link/wrapper {}: {}\",\n link_path.display(),\n e\n );\n removal_errors += 1;\n }\n }\n } else {\n // This indicates a potentially corrupted manifest or a link\n // outside expected areas\n error!(\n \"Manifest contains unexpected link path, skipping removal: {}\",\n link_path.display()\n );\n removal_errors += 1; // Count as an error/problem\n }\n }\n }\n debug!(\n \"Attempted to unlink {} artifacts based on manifest.\",\n unlinked_count\n );\n if removal_errors > 0 {\n error!(\n \"Encountered {} errors while removing links listed in manifest.\",\n removal_errors\n );\n // Decide if this should be a hard error - perhaps not if keg is being\n // removed anyway? For now, just log\n // warnings.\n }\n Ok(()) // Return Ok even if some links failed, keg removal will happen next\n }\n Err(e) => {\n error!(\n \"Failed to parse formula install manifest {}: {}. Proceeding without detailed unlink.\",\n manifest_path.display(),\n e\n );\n // Don't error out, allow keg removal to proceed.\n Ok(())\n }\n }\n }\n Err(e) => {\n error!(\n \"Failed to read formula install manifest {}: {}. Proceeding without detailed unlink.\",\n manifest_path.display(),\n e\n );\n // Don't error out, allow keg removal to proceed.\n Ok(())\n }\n }\n } else {\n debug!(\n \"Warning: No install manifest found at {}. Cannot perform detailed unlink.\",\n manifest_path.display()\n );\n // Don't error out, allow keg removal to proceed.\n Ok(())\n }\n}\n\nfn is_executable(path: &Path) -> Result {\n if !path.try_exists().unwrap_or(false) || !path.is_file() {\n return Ok(false);\n }\n if cfg!(unix) {\n use std::os::unix::fs::PermissionsExt;\n match fs::metadata(path) {\n Ok(metadata) => Ok(metadata.permissions().mode() & 0o111 != 0),\n Err(e) => Err(SpsError::Io(std::sync::Arc::new(e))),\n }\n } else {\n Ok(true)\n }\n}\n"], ["/sps/sps-net/src/http.rs", "use std::fs;\nuse std::path::{Path, PathBuf};\nuse std::sync::Arc;\nuse std::time::Duration;\n\nuse futures::StreamExt;\nuse reqwest::header::{HeaderMap, ACCEPT, USER_AGENT};\nuse reqwest::{Client, StatusCode};\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::formula::ResourceSpec;\nuse tokio::fs::File as TokioFile;\nuse tokio::io::AsyncWriteExt;\nuse tracing::{debug, error};\n\nuse crate::validation::{validate_url, verify_checksum};\n\npub type ProgressCallback = Arc) + Send + Sync>;\n\nconst DOWNLOAD_TIMEOUT_SECS: u64 = 300;\nconst CONNECT_TIMEOUT_SECS: u64 = 30;\nconst USER_AGENT_STRING: &str = \"sps package manager (Rust; +https://github.com/alexykn/sp)\";\n\npub async fn fetch_formula_source_or_bottle(\n formula_name: &str,\n url: &str,\n sha256_expected: &str,\n mirrors: &[String],\n config: &Config,\n) -> Result {\n fetch_formula_source_or_bottle_with_progress(\n formula_name,\n url,\n sha256_expected,\n mirrors,\n config,\n None,\n )\n .await\n}\n\npub async fn fetch_formula_source_or_bottle_with_progress(\n formula_name: &str,\n url: &str,\n sha256_expected: &str,\n mirrors: &[String],\n config: &Config,\n progress_callback: Option,\n) -> Result {\n let filename = url\n .split('/')\n .next_back()\n .map(|s| s.to_string())\n .unwrap_or_else(|| format!(\"{formula_name}-download\"));\n let cache_path = config.cache_dir().join(&filename);\n\n tracing::debug!(\n \"Preparing to fetch main resource for '{}' from URL: {}\",\n formula_name,\n url\n );\n tracing::debug!(\"Target cache path: {}\", cache_path.display());\n tracing::debug!(\"Expected SHA256: {}\", sha256_expected);\n\n if cache_path.is_file() {\n tracing::debug!(\"File exists in cache: {}\", cache_path.display());\n if !sha256_expected.is_empty() {\n match verify_checksum(&cache_path, sha256_expected) {\n Ok(_) => {\n tracing::debug!(\"Using valid cached file: {}\", cache_path.display());\n return Ok(cache_path);\n }\n Err(e) => {\n debug!(\n \"Cached file checksum mismatch ({}): {}. Redownloading.\",\n cache_path.display(),\n e\n );\n if let Err(remove_err) = fs::remove_file(&cache_path) {\n debug!(\n \"Failed to remove corrupted cached file {}: {}\",\n cache_path.display(),\n remove_err\n );\n }\n }\n }\n } else {\n tracing::debug!(\n \"Using cached file (no checksum provided): {}\",\n cache_path.display()\n );\n return Ok(cache_path);\n }\n } else {\n tracing::debug!(\"File not found in cache.\");\n }\n\n fs::create_dir_all(config.cache_dir()).map_err(|e| {\n SpsError::IoError(format!(\n \"Failed to create cache directory {}: {}\",\n config.cache_dir().display(),\n e\n ))\n })?;\n // Validate primary URL\n validate_url(url)?;\n\n let client = build_http_client()?;\n\n let urls_to_try = std::iter::once(url).chain(mirrors.iter().map(|s| s.as_str()));\n let mut last_error: Option = None;\n\n for current_url in urls_to_try {\n // Validate mirror URL\n validate_url(current_url)?;\n tracing::debug!(\"Attempting download from: {}\", current_url);\n match download_and_verify(\n &client,\n current_url,\n &cache_path,\n sha256_expected,\n progress_callback.clone(),\n )\n .await\n {\n Ok(path) => {\n tracing::debug!(\"Successfully downloaded and verified: {}\", path.display());\n return Ok(path);\n }\n Err(e) => {\n error!(\"Download attempt failed from {}: {}\", current_url, e);\n last_error = Some(e);\n }\n }\n }\n\n Err(last_error.unwrap_or_else(|| {\n SpsError::DownloadError(\n formula_name.to_string(),\n url.to_string(),\n \"All download attempts failed.\".to_string(),\n )\n }))\n}\n\npub async fn fetch_resource(\n formula_name: &str,\n resource: &ResourceSpec,\n config: &Config,\n) -> Result {\n fetch_resource_with_progress(formula_name, resource, config, None).await\n}\n\npub async fn fetch_resource_with_progress(\n formula_name: &str,\n resource: &ResourceSpec,\n config: &Config,\n progress_callback: Option,\n) -> Result {\n let resource_cache_dir = config.cache_dir().join(\"resources\");\n fs::create_dir_all(&resource_cache_dir).map_err(|e| {\n SpsError::IoError(format!(\n \"Failed to create resource cache directory {}: {}\",\n resource_cache_dir.display(),\n e\n ))\n })?;\n // Validate resource URL\n validate_url(&resource.url)?;\n\n let url_filename = resource\n .url\n .split('/')\n .next_back()\n .map(|s| s.to_string())\n .unwrap_or_else(|| format!(\"{}-download\", resource.name));\n let cache_filename = format!(\"{}-{}\", resource.name, url_filename);\n let cache_path = resource_cache_dir.join(&cache_filename);\n\n tracing::debug!(\n \"Preparing to fetch resource '{}' for formula '{}' from URL: {}\",\n resource.name,\n formula_name,\n resource.url\n );\n tracing::debug!(\"Target resource cache path: {}\", cache_path.display());\n tracing::debug!(\"Expected SHA256: {}\", resource.sha256);\n\n if cache_path.is_file() {\n tracing::debug!(\"Resource exists in cache: {}\", cache_path.display());\n match verify_checksum(&cache_path, &resource.sha256) {\n Ok(_) => {\n tracing::debug!(\"Using cached resource: {}\", cache_path.display());\n return Ok(cache_path);\n }\n Err(e) => {\n debug!(\n \"Cached resource checksum mismatch ({}): {}. Redownloading.\",\n cache_path.display(),\n e\n );\n if let Err(remove_err) = fs::remove_file(&cache_path) {\n debug!(\n \"Failed to remove corrupted cached resource file {}: {}\",\n cache_path.display(),\n remove_err\n );\n }\n }\n }\n } else {\n tracing::debug!(\"Resource not found in cache.\");\n }\n\n let client = build_http_client()?;\n match download_and_verify(\n &client,\n &resource.url,\n &cache_path,\n &resource.sha256,\n progress_callback,\n )\n .await\n {\n Ok(path) => {\n tracing::debug!(\n \"Successfully downloaded and verified resource: {}\",\n path.display()\n );\n Ok(path)\n }\n Err(e) => {\n error!(\"Resource download failed from {}: {}\", resource.url, e);\n let _ = fs::remove_file(&cache_path);\n Err(SpsError::DownloadError(\n resource.name.clone(),\n resource.url.clone(),\n format!(\"Download failed: {e}\"),\n ))\n }\n }\n}\n\nfn build_http_client() -> Result {\n let mut headers = HeaderMap::new();\n headers.insert(USER_AGENT, USER_AGENT_STRING.parse().unwrap());\n headers.insert(ACCEPT, \"*/*\".parse().unwrap());\n Client::builder()\n .timeout(Duration::from_secs(DOWNLOAD_TIMEOUT_SECS))\n .connect_timeout(Duration::from_secs(CONNECT_TIMEOUT_SECS))\n .default_headers(headers)\n .redirect(reqwest::redirect::Policy::limited(10))\n .build()\n .map_err(|e| SpsError::HttpError(format!(\"Failed to build HTTP client: {e}\")))\n}\n\nasync fn download_and_verify(\n client: &Client,\n url: &str,\n final_path: &Path,\n sha256_expected: &str,\n progress_callback: Option,\n) -> Result {\n let temp_filename = format!(\n \".{}.download\",\n final_path.file_name().unwrap_or_default().to_string_lossy()\n );\n let temp_path = final_path.with_file_name(temp_filename);\n tracing::debug!(\"Downloading to temporary path: {}\", temp_path.display());\n if temp_path.exists() {\n if let Err(e) = fs::remove_file(&temp_path) {\n tracing::warn!(\n \"Could not remove existing temporary file {}: {}\",\n temp_path.display(),\n e\n );\n }\n }\n\n let response = client.get(url).send().await.map_err(|e| {\n debug!(\"HTTP request failed for {url}: {e}\");\n SpsError::HttpError(format!(\"HTTP request failed for {url}: {e}\"))\n })?;\n let status = response.status();\n tracing::debug!(\"Received HTTP status: {} for {}\", status, url);\n\n if !status.is_success() {\n let body_text = response\n .text()\n .await\n .unwrap_or_else(|_| \"Failed to read response body\".to_string());\n tracing::error!(\"HTTP error {} for URL {}: {}\", status, url, body_text);\n return match status {\n StatusCode::NOT_FOUND => Err(SpsError::DownloadError(\n final_path\n .file_name()\n .map(|s| s.to_string_lossy().to_string())\n .unwrap_or_default(),\n url.to_string(),\n \"Resource not found (404)\".to_string(),\n )),\n StatusCode::FORBIDDEN => Err(SpsError::DownloadError(\n final_path\n .file_name()\n .map(|s| s.to_string_lossy().to_string())\n .unwrap_or_default(),\n url.to_string(),\n \"Access forbidden (403)\".to_string(),\n )),\n _ => Err(SpsError::HttpError(format!(\n \"HTTP error {status} for URL {url}: {body_text}\"\n ))),\n };\n }\n\n // Get total size from Content-Length header if available\n let total_size = response.content_length();\n\n let mut temp_file = TokioFile::create(&temp_path).await.map_err(|e| {\n SpsError::IoError(format!(\n \"Failed to create temp file {}: {}\",\n temp_path.display(),\n e\n ))\n })?;\n\n // Use bytes_stream() for chunked download with progress reporting\n let mut stream = response.bytes_stream();\n let mut bytes_downloaded = 0u64;\n\n while let Some(chunk) = stream.next().await {\n let chunk = chunk.map_err(|e| SpsError::HttpError(format!(\"Failed to read chunk: {e}\")))?;\n\n temp_file.write_all(&chunk).await.map_err(|e| {\n SpsError::IoError(format!(\n \"Failed to write chunk to {}: {}\",\n temp_path.display(),\n e\n ))\n })?;\n\n bytes_downloaded += chunk.len() as u64;\n\n // Call progress callback if provided\n if let Some(ref callback) = progress_callback {\n callback(bytes_downloaded, total_size);\n }\n }\n\n drop(temp_file);\n tracing::debug!(\"Finished writing download stream to temp file.\");\n\n if !sha256_expected.is_empty() {\n verify_checksum(&temp_path, sha256_expected)?;\n tracing::debug!(\n \"Checksum verified for temporary file: {}\",\n temp_path.display()\n );\n } else {\n tracing::warn!(\n \"Skipping checksum verification for {} - none provided.\",\n temp_path.display()\n );\n }\n\n fs::rename(&temp_path, final_path).map_err(|e| {\n SpsError::IoError(format!(\n \"Failed to move temp file {} to {}: {}\",\n temp_path.display(),\n final_path.display(),\n e\n ))\n })?;\n tracing::debug!(\n \"Moved verified file to final location: {}\",\n final_path.display()\n );\n Ok(final_path.to_path_buf())\n}\n"], ["/sps/sps-common/src/config.rs", "// sps-common/src/config.rs\nuse std::env;\nuse std::path::{Path, PathBuf};\n\nuse directories::UserDirs; // Ensure this crate is in sps-common/Cargo.toml\nuse tracing::debug;\n\nuse super::error::Result; // Assuming SpsResult is Result from super::error\n\n// This constant will serve as a fallback if HOMEBREW_PREFIX is not set or is empty.\nconst DEFAULT_FALLBACK_SPS_ROOT: &str = \"/opt/homebrew\";\nconst SPS_ROOT_MARKER_FILENAME: &str = \".sps_root_v1\";\n\n#[derive(Debug, Clone)]\npub struct Config {\n pub sps_root: PathBuf, // Public for direct construction in main for init if needed\n pub api_base_url: String,\n pub artifact_domain: Option,\n pub docker_registry_token: Option,\n pub docker_registry_basic_auth: Option,\n pub github_api_token: Option,\n}\n\nimpl Config {\n pub fn load() -> Result {\n debug!(\"Loading sps configuration\");\n\n // Try to get SPS_ROOT from HOMEBREW_PREFIX environment variable.\n // Fallback to DEFAULT_FALLBACK_SPS_ROOT if not set or empty.\n let sps_root_str = env::var(\"HOMEBREW_PREFIX\").ok().filter(|s| !s.is_empty())\n .unwrap_or_else(|| {\n debug!(\n \"HOMEBREW_PREFIX environment variable not set or empty, falling back to default: {}\",\n DEFAULT_FALLBACK_SPS_ROOT\n );\n DEFAULT_FALLBACK_SPS_ROOT.to_string()\n });\n\n let sps_root_path = PathBuf::from(&sps_root_str);\n debug!(\"Effective SPS_ROOT set to: {}\", sps_root_path.display());\n\n let api_base_url = \"https://formulae.brew.sh/api\".to_string();\n\n let artifact_domain = env::var(\"HOMEBREW_ARTIFACT_DOMAIN\").ok();\n let docker_registry_token = env::var(\"HOMEBREW_DOCKER_REGISTRY_TOKEN\").ok();\n let docker_registry_basic_auth = env::var(\"HOMEBREW_DOCKER_REGISTRY_BASIC_AUTH_TOKEN\").ok();\n let github_api_token = env::var(\"HOMEBREW_GITHUB_API_TOKEN\").ok();\n\n debug!(\"Configuration loaded successfully.\");\n Ok(Self {\n sps_root: sps_root_path,\n api_base_url,\n artifact_domain,\n docker_registry_token,\n docker_registry_basic_auth,\n github_api_token,\n })\n }\n\n pub fn sps_root(&self) -> &Path {\n &self.sps_root\n }\n\n pub fn bin_dir(&self) -> PathBuf {\n self.sps_root.join(\"bin\")\n }\n\n pub fn cellar_dir(&self) -> PathBuf {\n self.sps_root.join(\"Cellar\") // Changed from \"cellar\" to \"Cellar\" to match Homebrew\n }\n\n pub fn cask_room_dir(&self) -> PathBuf {\n self.sps_root.join(\"Caskroom\") // Changed from \"cask_room\" to \"Caskroom\"\n }\n\n pub fn cask_store_dir(&self) -> PathBuf {\n self.sps_root.join(\"sps_cask_store\")\n }\n\n pub fn opt_dir(&self) -> PathBuf {\n self.sps_root.join(\"opt\")\n }\n\n pub fn taps_dir(&self) -> PathBuf {\n self.sps_root.join(\"Library/Taps\") // Adjusted to match Homebrew structure\n }\n\n pub fn cache_dir(&self) -> PathBuf {\n self.sps_root.join(\"sps_cache\")\n }\n\n pub fn logs_dir(&self) -> PathBuf {\n self.sps_root.join(\"sps_logs\")\n }\n\n pub fn tmp_dir(&self) -> PathBuf {\n self.sps_root.join(\"tmp\")\n }\n\n pub fn state_dir(&self) -> PathBuf {\n self.sps_root.join(\"sps_state\")\n }\n\n pub fn man_base_dir(&self) -> PathBuf {\n self.sps_root.join(\"share\").join(\"man\")\n }\n\n pub fn sps_root_marker_path(&self) -> PathBuf {\n self.sps_root.join(SPS_ROOT_MARKER_FILENAME)\n }\n\n pub fn applications_dir(&self) -> PathBuf {\n if cfg!(target_os = \"macos\") {\n PathBuf::from(\"/Applications\")\n } else {\n self.home_dir().join(\"Applications\")\n }\n }\n\n pub fn formula_cellar_dir(&self, formula_name: &str) -> PathBuf {\n self.cellar_dir().join(formula_name)\n }\n\n pub fn formula_keg_path(&self, formula_name: &str, version_str: &str) -> PathBuf {\n self.formula_cellar_dir(formula_name).join(version_str)\n }\n\n pub fn formula_opt_path(&self, formula_name: &str) -> PathBuf {\n self.opt_dir().join(formula_name)\n }\n\n pub fn cask_room_token_path(&self, cask_token: &str) -> PathBuf {\n self.cask_room_dir().join(cask_token)\n }\n\n pub fn cask_store_token_path(&self, cask_token: &str) -> PathBuf {\n self.cask_store_dir().join(cask_token)\n }\n\n pub fn cask_store_version_path(&self, cask_token: &str, version_str: &str) -> PathBuf {\n self.cask_store_token_path(cask_token).join(version_str)\n }\n\n pub fn cask_store_app_path(\n &self,\n cask_token: &str,\n version_str: &str,\n app_name: &str,\n ) -> PathBuf {\n self.cask_store_version_path(cask_token, version_str)\n .join(app_name)\n }\n\n pub fn cask_room_version_path(&self, cask_token: &str, version_str: &str) -> PathBuf {\n self.cask_room_token_path(cask_token).join(version_str)\n }\n\n pub fn home_dir(&self) -> PathBuf {\n UserDirs::new().map_or_else(|| PathBuf::from(\"/\"), |ud| ud.home_dir().to_path_buf())\n }\n\n pub fn get_tap_path(&self, name: &str) -> Option {\n let parts: Vec<&str> = name.split('/').collect();\n if parts.len() == 2 {\n Some(\n self.taps_dir()\n .join(parts[0]) // user, e.g., homebrew\n .join(format!(\"homebrew-{}\", parts[1])), // repo, e.g., homebrew-core\n )\n } else {\n None\n }\n }\n\n pub fn get_formula_path_from_tap(&self, tap_name: &str, formula_name: &str) -> Option {\n self.get_tap_path(tap_name).and_then(|tap_path| {\n let json_path = tap_path\n .join(\"Formula\") // Standard Homebrew tap structure\n .join(format!(\"{formula_name}.json\"));\n if json_path.exists() {\n return Some(json_path);\n }\n // Fallback to .rb for completeness, though API primarily gives JSON\n let rb_path = tap_path.join(\"Formula\").join(format!(\"{formula_name}.rb\"));\n if rb_path.exists() {\n return Some(rb_path);\n }\n None\n })\n }\n}\n\nimpl Default for Config {\n fn default() -> Self {\n Self::load().expect(\"Failed to load default configuration\")\n }\n}\n\npub fn load_config() -> Result {\n Config::load()\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/binary.rs", "// ===== sps-core/src/build/cask/artifacts/binary.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Installs `binary` artifacts, which can be declared as:\n/// - a simple string: `\"foo\"` (source and target both `\"foo\"`)\n/// - a map: `{ \"source\": \"path/in/stage\", \"target\": \"name\", \"chmod\": \"0755\" }`\n/// - a map with just `\"target\"`: automatically generate a wrapper script\n///\n/// Copies or symlinks executables into the prefix bin directory,\n/// and records both the link and caskroom reference.\npub fn install_binary(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"binary\") {\n // Normalize into an array\n let arr = if let Some(arr) = entries.as_array() {\n arr.clone()\n } else {\n vec![entries.clone()]\n };\n\n let bin_dir = config.bin_dir();\n fs::create_dir_all(&bin_dir)?;\n\n for entry in arr {\n // Determine source, target, and optional chmod\n let (source_rel, target_name, chmod) = if let Some(tgt) = entry.as_str() {\n // simple form: \"foo\"\n (tgt.to_string(), tgt.to_string(), None)\n } else if let Some(m) = entry.as_object() {\n let target = m\n .get(\"target\")\n .and_then(|v| v.as_str())\n .map(String::from)\n .ok_or_else(|| {\n SpsError::InstallError(format!(\n \"Binary artifact missing 'target': {m:?}\"\n ))\n })?;\n\n let chmod = m.get(\"chmod\").and_then(|v| v.as_str()).map(String::from);\n\n // If `source` is provided, use it; otherwise generate wrapper\n let source = if let Some(src) = m.get(\"source\").and_then(|v| v.as_str())\n {\n src.to_string()\n } else {\n // generate wrapper script in caskroom\n let wrapper_name = format!(\"{target}.wrapper.sh\");\n let wrapper_path = cask_version_install_path.join(&wrapper_name);\n\n // assume the real executable lives inside the .app bundle\n let app_name = format!(\"{}.app\", cask.display_name());\n let exe_path =\n format!(\"/Applications/{app_name}/Contents/MacOS/{target}\");\n\n let script =\n format!(\"#!/usr/bin/env bash\\nexec \\\"{exe_path}\\\" \\\"$@\\\"\\n\");\n fs::write(&wrapper_path, script)?;\n Command::new(\"chmod\")\n .arg(\"+x\")\n .arg(&wrapper_path)\n .status()?;\n\n wrapper_name\n };\n\n (source, target, chmod)\n } else {\n debug!(\"Invalid binary artifact entry: {:?}\", entry);\n continue;\n };\n\n let src_path = stage_path.join(&source_rel);\n if !src_path.exists() {\n debug!(\"Binary source '{}' not found, skipping\", src_path.display());\n continue;\n }\n\n // Link into bin_dir\n let link_path = bin_dir.join(&target_name);\n let _ = fs::remove_file(&link_path);\n debug!(\n \"Linking binary '{}' → '{}'\",\n src_path.display(),\n link_path.display()\n );\n symlink(&src_path, &link_path)?;\n\n // Apply chmod if specified\n if let Some(mode) = chmod.as_deref() {\n let _ = Command::new(\"chmod\").arg(mode).arg(&link_path).status();\n }\n\n installed.push(InstalledArtifact::BinaryLink {\n link_path: link_path.clone(),\n target_path: src_path.clone(),\n });\n\n // Also create a Caskroom symlink for reference\n let caskroom_link = cask_version_install_path.join(&target_name);\n let _ = remove_path_robustly(&caskroom_link, config, true);\n symlink(&link_path, &caskroom_link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: caskroom_link,\n target_path: link_path.clone(),\n });\n }\n\n // Only one binary stanza per cask\n break;\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-common/src/formulary.rs", "use std::collections::HashMap;\nuse std::sync::Arc;\n\nuse tracing::debug;\n\nuse super::cache::Cache;\nuse super::config::Config;\nuse super::error::{Result, SpsError};\nuse super::model::formula::Formula;\n\n#[derive()]\npub struct Formulary {\n cache: Cache,\n parsed_cache: std::sync::Mutex>>,\n}\n\nimpl Formulary {\n pub fn new(config: Config) -> Self {\n let cache = Cache::new(&config).unwrap_or_else(|e| {\n panic!(\"Failed to initialize cache in Formulary: {e}\");\n });\n Self {\n cache,\n parsed_cache: std::sync::Mutex::new(HashMap::new()),\n }\n }\n\n pub fn load_formula(&self, name: &str) -> Result {\n let mut parsed_cache_guard = self.parsed_cache.lock().unwrap();\n if let Some(formula_arc) = parsed_cache_guard.get(name) {\n debug!(\"Loaded formula '{}' from parsed cache.\", name);\n return Ok(Arc::clone(formula_arc).as_ref().clone());\n }\n drop(parsed_cache_guard);\n\n let raw_data = self.cache.load_raw(\"formula.json\")?;\n let all_formulas: Vec = serde_json::from_str(&raw_data)\n .map_err(|e| SpsError::Cache(format!(\"Failed to parse cached formula data: {e}\")))?;\n debug!(\"Parsed {} formulas.\", all_formulas.len());\n\n let mut found_formula: Option = None;\n parsed_cache_guard = self.parsed_cache.lock().unwrap();\n for formula in all_formulas {\n let formula_name = formula.name.clone();\n let formula_arc = std::sync::Arc::new(formula);\n\n if formula_name == name {\n found_formula = Some(Arc::clone(&formula_arc).as_ref().clone());\n }\n\n parsed_cache_guard\n .entry(formula_name)\n .or_insert(formula_arc);\n }\n\n match found_formula {\n Some(f) => {\n debug!(\n \"Successfully loaded formula '{}' version {}\",\n f.name,\n f.version_str_full()\n );\n Ok(f)\n }\n None => {\n debug!(\n \"Formula '{}' not found within the cached formula data.\",\n name\n );\n Err(SpsError::Generic(format!(\n \"Formula '{name}' not found in cache.\"\n )))\n }\n }\n }\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/pkg.rs", "use std::fs;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::cask::Cask;\nuse tracing::{debug, error};\n\nuse crate::install::cask::InstalledArtifact; // Artifact type alias is just Value\n\n/// Installs a PKG file and returns details of artifacts created/managed.\npub fn install_pkg_from_path(\n cask: &Cask,\n pkg_path: &Path,\n cask_version_install_path: &Path, // e.g., /opt/homebrew/Caskroom/foo/1.2.3\n _config: &Config, // Keep for potential future use\n) -> Result> {\n // <-- Return type changed\n debug!(\"Installing pkg file: {}\", pkg_path.display());\n\n if !pkg_path.exists() || !pkg_path.is_file() {\n return Err(SpsError::NotFound(format!(\n \"Package file not found or is not a file: {}\",\n pkg_path.display()\n )));\n }\n\n let pkg_name = pkg_path\n .file_name()\n .ok_or_else(|| SpsError::Generic(format!(\"Invalid pkg path: {}\", pkg_path.display())))?;\n\n // --- Prepare list for artifacts ---\n let mut installed_artifacts: Vec = Vec::new();\n\n // --- Copy PKG to Caskroom for Reference ---\n let caskroom_pkg_path = cask_version_install_path.join(pkg_name);\n debug!(\n \"Copying pkg to caskroom for reference: {}\",\n caskroom_pkg_path.display()\n );\n if let Some(parent) = caskroom_pkg_path.parent() {\n fs::create_dir_all(parent).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed create parent dir {}: {}\", parent.display(), e),\n )))\n })?;\n }\n if let Err(e) = fs::copy(pkg_path, &caskroom_pkg_path) {\n error!(\n \"Failed to copy PKG {} to {}: {}\",\n pkg_path.display(),\n caskroom_pkg_path.display(),\n e\n );\n return Err(SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed copy PKG to caskroom: {e}\"),\n ))));\n } else {\n // Record the reference copy artifact\n installed_artifacts.push(InstalledArtifact::CaskroomReference {\n path: caskroom_pkg_path.clone(),\n });\n }\n\n // --- Run Installer ---\n debug!(\"Running installer (this may require sudo)\");\n debug!(\n \"Executing: sudo installer -pkg {} -target /\",\n pkg_path.display()\n );\n let output = Command::new(\"sudo\")\n .arg(\"installer\")\n .arg(\"-pkg\")\n .arg(pkg_path)\n .arg(\"-target\")\n .arg(\"/\")\n .output()\n .map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed to execute sudo installer: {e}\"),\n )))\n })?;\n\n if !output.status.success() {\n let stderr = String::from_utf8_lossy(&output.stderr);\n error!(\"sudo installer failed ({}): {}\", output.status, stderr);\n // Don't clean up the reference copy here, let the main process handle directory removal on\n // failure\n return Err(SpsError::InstallError(format!(\n \"Package installation failed for {}: {}\",\n pkg_path.display(),\n stderr\n )));\n }\n debug!(\"Successfully ran installer command.\");\n let stdout = String::from_utf8_lossy(&output.stdout);\n if !stdout.trim().is_empty() {\n debug!(\"Installer stdout:\\n{}\", stdout);\n }\n\n // --- Record PkgUtil Receipts (based on cask definition) ---\n if let Some(artifacts) = &cask.artifacts {\n // artifacts is Option>\n for artifact_value in artifacts.iter() {\n if let Some(uninstall_array) =\n artifact_value.get(\"uninstall\").and_then(|v| v.as_array())\n {\n for stanza_value in uninstall_array {\n if let Some(stanza_obj) = stanza_value.as_object() {\n if let Some(pkgutil_id) = stanza_obj.get(\"pkgutil\").and_then(|v| v.as_str())\n {\n debug!(\"Found pkgutil ID to record: {}\", pkgutil_id);\n // Check for duplicates before adding\n let new_artifact = InstalledArtifact::PkgUtilReceipt {\n id: pkgutil_id.to_string(),\n };\n if !installed_artifacts.contains(&new_artifact) {\n // Need PartialEq for InstalledArtifact\n installed_artifacts.push(new_artifact);\n }\n }\n // Consider other uninstall keys like launchctl, delete?\n }\n }\n }\n // Optionally check \"zap\" stanzas too\n }\n }\n debug!(\"Successfully installed pkg: {}\", pkg_path.display());\n Ok(installed_artifacts) // <-- Return collected artifacts\n}\n"], ["/sps/sps-common/src/keg.rs", "// sps-common/src/keg.rs\nuse std::fs;\nuse std::path::PathBuf;\n\n// Corrected tracing imports: added error, removed unused debug\nuse tracing::{debug, error, warn};\n\nuse super::config::Config;\nuse super::error::{Result, SpsError};\n\n/// Represents information about an installed package (Keg).\n#[derive(Debug, Clone, PartialEq, Eq)]\npub struct InstalledKeg {\n pub name: String,\n pub version_str: String,\n pub path: PathBuf,\n}\n\n/// Manages querying installed packages in the Cellar.\n#[derive(Debug)]\npub struct KegRegistry {\n config: Config,\n}\n\nimpl KegRegistry {\n pub fn new(config: Config) -> Self {\n Self { config }\n }\n\n fn formula_cellar_path(&self, name: &str) -> PathBuf {\n self.config.cellar_dir().join(name)\n }\n\n pub fn get_opt_path(&self, name: &str) -> PathBuf {\n self.config.opt_dir().join(name)\n }\n\n pub fn get_installed_keg(&self, name: &str) -> Result> {\n let formula_dir = self.formula_cellar_path(name);\n debug!(\n \"[KEG_REGISTRY:{}] get_installed_keg: Checking for formula '{}'. Path to check: {}\",\n name,\n name,\n formula_dir.display()\n );\n\n if !formula_dir.is_dir() {\n debug!(\"[KEG_REGISTRY:{}] get_installed_keg: Formula directory '{}' NOT FOUND or not a directory. Returning None.\", name, formula_dir.display());\n return Ok(None);\n }\n\n let mut latest_keg: Option = None;\n debug!(\n \"[KEG_REGISTRY:{}] get_installed_keg: Reading entries in formula directory '{}'\",\n name,\n formula_dir.display()\n );\n\n match fs::read_dir(&formula_dir) {\n Ok(entries) => {\n for entry_result in entries {\n match entry_result {\n Ok(entry) => {\n let path = entry.path();\n debug!(\n \"[KEG_REGISTRY:{}] get_installed_keg: Examining entry '{}'\",\n name,\n path.display()\n );\n\n if path.is_dir() {\n if let Some(version_str_full) =\n path.file_name().and_then(|n| n.to_str())\n {\n debug!(\"[KEG_REGISTRY:{}] get_installed_keg: Entry is a directory with name: {}\", name, version_str_full);\n\n let current_keg_candidate = InstalledKeg {\n name: name.to_string(),\n version_str: version_str_full.to_string(),\n path: path.clone(),\n };\n\n match latest_keg {\n Some(ref current_latest) => {\n // Compare &str with &str\n if version_str_full\n > current_latest.version_str.as_str()\n {\n debug!(\"[KEG_REGISTRY:{}] get_installed_keg: Updating latest keg (lexicographical) to: {}\", name, path.display());\n latest_keg = Some(current_keg_candidate);\n }\n }\n None => {\n debug!(\"[KEG_REGISTRY:{}] get_installed_keg: Setting first found keg as latest: {}\", name, path.display());\n latest_keg = Some(current_keg_candidate);\n }\n }\n } else {\n debug!(\"[KEG_REGISTRY:{}] get_installed_keg: Could not get filename as string for path '{}'\", name, path.display());\n }\n } else {\n debug!(\"[KEG_REGISTRY:{}] get_installed_keg: Entry '{}' is not a directory.\", name, path.display());\n }\n }\n Err(e) => {\n warn!(\"[KEG_REGISTRY:{}] get_installed_keg: Error reading a directory entry in '{}': {}. Skipping entry.\", name, formula_dir.display(), e);\n }\n }\n }\n }\n Err(e) => {\n // Corrected macro usage\n error!(\"[KEG_REGISTRY:{}] get_installed_keg: Failed to read_dir for formula directory '{}' (error: {}). Returning error.\", name, formula_dir.display(), e);\n return Err(SpsError::Io(std::sync::Arc::new(e)));\n }\n }\n\n if let Some(keg) = &latest_keg {\n // Corrected format string arguments\n debug!(\"[KEG_REGISTRY:{}] get_installed_keg: For formula '{}', latest keg found: path={}, version_str={}\", name, name, keg.path.display(), keg.version_str);\n } else {\n // Corrected format string arguments\n debug!(\"[KEG_REGISTRY:{}] get_installed_keg: For formula '{}', no installable keg version found in directory '{}'.\", name, name, formula_dir.display());\n }\n Ok(latest_keg)\n }\n\n pub fn list_installed_kegs(&self) -> Result> {\n let mut installed_kegs = Vec::new();\n let cellar_dir = self.cellar_path();\n debug!(\n \"[KEG_REGISTRY] list_installed_kegs: Scanning cellar: {}\",\n cellar_dir.display()\n );\n\n if !cellar_dir.is_dir() {\n debug!(\"[KEG_REGISTRY] list_installed_kegs: Cellar directory NOT FOUND. Returning empty list.\");\n return Ok(installed_kegs);\n }\n\n for formula_entry_res in fs::read_dir(cellar_dir)? {\n let formula_entry = match formula_entry_res {\n Ok(fe) => fe,\n Err(e) => {\n warn!(\"[KEG_REGISTRY] list_installed_kegs: Error reading entry in cellar: {}. Skipping.\", e);\n continue;\n }\n };\n let formula_path = formula_entry.path();\n debug!(\n \"[KEG_REGISTRY] list_installed_kegs: Examining formula path: {}\",\n formula_path.display()\n );\n\n if formula_path.is_dir() {\n if let Some(formula_name) = formula_path.file_name().and_then(|n| n.to_str()) {\n debug!(\n \"[KEG_REGISTRY] list_installed_kegs: Found formula directory: {}\",\n formula_name\n );\n match fs::read_dir(&formula_path) {\n Ok(version_entries) => {\n for version_entry_res in version_entries {\n let version_entry = match version_entry_res {\n Ok(ve) => ve,\n Err(e) => {\n warn!(\"[KEG_REGISTRY:{}] list_installed_kegs: Error reading version entry in '{}': {}. Skipping.\", formula_name, formula_path.display(), e);\n continue;\n }\n };\n let version_path = version_entry.path();\n debug!(\"[KEG_REGISTRY:{}] list_installed_kegs: Examining version path: {}\", formula_name, version_path.display());\n\n if version_path.is_dir() {\n if let Some(version_str_full) =\n version_path.file_name().and_then(|n| n.to_str())\n {\n debug!(\"[KEG_REGISTRY:{}] list_installed_kegs: Found version directory '{}' with name: {}\", formula_name, version_path.display(), version_str_full);\n installed_kegs.push(InstalledKeg {\n name: formula_name.to_string(),\n version_str: version_str_full.to_string(),\n path: version_path.clone(),\n });\n } else {\n debug!(\"[KEG_REGISTRY:{}] list_installed_kegs: Could not get filename for version path {}\", formula_name, version_path.display());\n }\n } else {\n debug!(\"[KEG_REGISTRY:{}] list_installed_kegs: Version path {} is not a directory.\", formula_name, version_path.display());\n }\n }\n }\n Err(e) => {\n warn!(\"[KEG_REGISTRY:{}] list_installed_kegs: Failed to read_dir for formula versions in '{}': {}.\", formula_name, formula_path.display(), e);\n }\n }\n } else {\n debug!(\"[KEG_REGISTRY] list_installed_kegs: Could not get filename for formula path {}\", formula_path.display());\n }\n } else {\n debug!(\n \"[KEG_REGISTRY] list_installed_kegs: Formula path {} is not a directory.\",\n formula_path.display()\n );\n }\n }\n debug!(\n \"[KEG_REGISTRY] list_installed_kegs: Found {} total installed keg versions.\",\n installed_kegs.len()\n );\n Ok(installed_kegs)\n }\n\n pub fn cellar_path(&self) -> PathBuf {\n self.config.cellar_dir()\n }\n\n pub fn get_keg_path(&self, name: &str, version_str_raw: &str) -> PathBuf {\n self.formula_cellar_path(name).join(version_str_raw)\n }\n}\n"], ["/sps/sps/src/cli/update.rs", "//! Contains the logic for the `update` command.\nuse std::fs;\nuse std::sync::Arc;\n\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_net::api;\n\n#[derive(clap::Args, Debug)]\npub struct Update;\n\nimpl Update {\n pub async fn run(&self, config: &Config, cache: Arc) -> Result<()> {\n tracing::debug!(\"Running manual update...\"); // Log clearly it's the manual one\n\n // Use the ui utility function to create the spinner\n println!(\"Updating package lists\"); // <-- CHANGED\n\n tracing::debug!(\"Using cache directory: {:?}\", config.cache_dir());\n\n // Fetch and store raw formula data\n match api::fetch_all_formulas().await {\n Ok(raw_data) => {\n cache.store_raw(\"formula.json\", &raw_data)?;\n tracing::debug!(\"✓ Successfully cached formulas data\");\n println!(\"Cached formulas data\");\n }\n Err(e) => {\n let err_msg = format!(\"Failed to fetch/store formulas from API: {e}\");\n tracing::error!(\"{}\", err_msg);\n println!(); // Clear spinner on error\n return Err(e);\n }\n }\n\n // Fetch and store raw cask data\n match api::fetch_all_casks().await {\n Ok(raw_data) => {\n cache.store_raw(\"cask.json\", &raw_data)?;\n tracing::debug!(\"✓ Successfully cached casks data\");\n println!(\"Cached casks data\");\n }\n Err(e) => {\n let err_msg = format!(\"Failed to fetch/store casks from API: {e}\");\n tracing::error!(\"{}\", err_msg);\n return Err(e);\n }\n }\n\n // Update timestamp file\n let timestamp_file = config.state_dir().join(\".sps_last_update_check\");\n tracing::debug!(\n \"Manual update successful. Updating timestamp file: {}\",\n timestamp_file.display()\n );\n match fs::File::create(×tamp_file) {\n Ok(_) => {\n tracing::debug!(\"Updated timestamp file successfully.\");\n }\n Err(e) => {\n tracing::warn!(\n \"Failed to create or update timestamp file '{}': {}\",\n timestamp_file.display(),\n e\n );\n }\n }\n\n println!(\"Update completed successfully!\");\n Ok(())\n }\n}\n"], ["/sps/sps-core/src/install/bottle/macho.rs", "// sps-core/src/build/formula/macho.rs\n// Contains Mach-O specific patching logic for bottle relocation.\n// Updated to use MachOFatFile32 and MachOFatFile64 for FAT binary parsing.\n// Refactored to separate immutable analysis from mutable patching to fix borrow checker errors.\n\nuse std::collections::HashMap;\nuse std::fs;\nuse std::io::Write; // Keep for write_patched_buffer\nuse std::path::Path;\nuse std::process::{Command as StdCommand, Stdio}; // Keep for codesign\n\n// --- Imports needed for Mach-O patching (macOS only) ---\n#[cfg(target_os = \"macos\")]\nuse object::{\n self,\n macho::{MachHeader32, MachHeader64}, // Keep for Mach-O parsing\n read::macho::{\n FatArch,\n LoadCommandVariant, // Correct import path\n MachHeader,\n MachOFatFile32,\n MachOFatFile64, // Core Mach-O types + FAT types\n MachOFile,\n },\n Endianness,\n FileKind,\n ReadRef,\n};\nuse sps_common::error::{Result, SpsError};\nuse tempfile::NamedTempFile;\nuse tracing::{debug, error};\n\n// --- Platform‑specific constants for Mach‑O magic detection ---\n#[cfg(target_os = \"macos\")]\nconst MH_MAGIC: u32 = 0xfeedface;\n#[cfg(target_os = \"macos\")]\nconst MH_MAGIC_64: u32 = 0xfeedfacf;\n#[cfg(target_os = \"macos\")]\nconst MACHO_HEADER32_SIZE: usize = 28;\n#[cfg(target_os = \"macos\")]\nconst MACHO_HEADER64_SIZE: usize = 32;\n\n/// Core patch data for **one** string replacement location inside a Mach‑O file.\n#[cfg(target_os = \"macos\")]\n#[derive(Debug, Clone)]\nstruct PatchInfo {\n absolute_offset: usize, // Offset in the entire file buffer\n allocated_len: usize, // How much space was allocated for this string\n new_path: String, // The new string to write\n}\n\n/// Container for paths that couldn't be patched due to length constraints\n#[cfg(target_os = \"macos\")]\n#[derive(Debug, Clone)]\npub struct SkippedPath {\n pub old_path: String,\n pub new_path: String,\n}\n\n/// Main entry point for Mach‑O path patching (macOS only).\n/// Returns `Ok(true)` if patches were applied, `Ok(false)` if no patches needed.\n/// Returns a tuple: (patched: bool, skipped_paths: Vec)\n#[cfg(target_os = \"macos\")]\npub fn patch_macho_file(\n path: &Path,\n replacements: &HashMap,\n) -> Result<(bool, Vec)> {\n patch_macho_file_macos(path, replacements)\n}\n\n/// Container for paths that couldn't be patched due to length constraints\n#[cfg(not(target_os = \"macos\"))]\n#[derive(Debug, Clone)]\npub struct SkippedPath {\n pub old_path: String,\n pub new_path: String,\n}\n\n/// No‑op stub for non‑macOS platforms.\n#[cfg(not(target_os = \"macos\"))]\npub fn patch_macho_file(\n _path: &Path,\n _replacements: &HashMap,\n) -> Result<(bool, Vec)> {\n Ok((false, Vec::new()))\n}\n\n/// **macOS implementation**: Tries to patch Mach‑O files by replacing placeholders.\n#[cfg(target_os = \"macos\")]\nfn patch_macho_file_macos(\n path: &Path,\n replacements: &HashMap,\n) -> Result<(bool, Vec)> {\n debug!(\"Processing potential Mach-O file: {}\", path.display());\n\n // 1) Load the entire file into memory\n let buffer = match fs::read(path) {\n Ok(data) => data,\n Err(e) => {\n debug!(\"Failed to read {}: {}\", path.display(), e);\n return Ok((false, Vec::new()));\n }\n };\n if buffer.is_empty() {\n debug!(\"Empty file: {}\", path.display());\n return Ok((false, Vec::new()));\n }\n\n // 2) Identify the file type\n let kind = match object::FileKind::parse(&*buffer) {\n Ok(k) => k,\n Err(_e) => {\n debug!(\"Not an object file: {}\", path.display());\n return Ok((false, Vec::new()));\n }\n };\n\n // 3) **Analysis phase**: collect patches + skipped paths\n let (patches, skipped_paths) = collect_macho_patches(&buffer, kind, replacements, path)?;\n\n if patches.is_empty() {\n if skipped_paths.is_empty() {\n debug!(\"No patches needed for {}\", path.display());\n } else {\n debug!(\n \"No patches applied for {} ({} paths skipped due to length)\",\n path.display(),\n skipped_paths.len()\n );\n }\n return Ok((false, skipped_paths));\n }\n\n // 4) Clone buffer and apply all patches atomically\n let mut patched_buffer = buffer;\n for patch in &patches {\n patch_path_in_buffer(\n &mut patched_buffer,\n patch.absolute_offset,\n patch.allocated_len,\n &patch.new_path,\n path,\n )?;\n }\n\n // 5) Write atomically\n write_patched_buffer(path, &patched_buffer)?;\n debug!(\"Wrote patched Mach-O: {}\", path.display());\n\n // 6) Re‑sign on Apple Silicon\n #[cfg(target_arch = \"aarch64\")]\n {\n resign_binary(path)?;\n debug!(\"Re‑signed patched binary: {}\", path.display());\n }\n\n Ok((true, skipped_paths))\n}\n\n/// ASCII magic for the start of a static `ar` archive (`!\\n`)\n#[cfg(target_os = \"macos\")]\nconst AR_MAGIC: &[u8; 8] = b\"!\\n\";\n\n/// Examine a buffer (Mach‑O or FAT) and return every patch we must apply + skipped paths.\n#[cfg(target_os = \"macos\")]\nfn collect_macho_patches(\n buffer: &[u8],\n kind: FileKind,\n replacements: &HashMap,\n path_for_log: &Path,\n) -> Result<(Vec, Vec)> {\n let mut patches = Vec::::new();\n let mut skipped_paths = Vec::::new();\n\n match kind {\n /* ---------------------------------------------------------- */\n FileKind::MachO32 => {\n let m = MachOFile::, _>::parse(buffer)?;\n let (mut p, mut s) =\n find_patches_in_commands(&m, 0, MACHO_HEADER32_SIZE, replacements, path_for_log)?;\n patches.append(&mut p);\n skipped_paths.append(&mut s);\n }\n /* ---------------------------------------------------------- */\n FileKind::MachO64 => {\n let m = MachOFile::, _>::parse(buffer)?;\n let (mut p, mut s) =\n find_patches_in_commands(&m, 0, MACHO_HEADER64_SIZE, replacements, path_for_log)?;\n patches.append(&mut p);\n skipped_paths.append(&mut s);\n }\n /* ---------------------------------------------------------- */\n FileKind::MachOFat32 => {\n let fat = MachOFatFile32::parse(buffer)?;\n for (idx, arch) in fat.arches().iter().enumerate() {\n let (off, sz) = arch.file_range();\n let slice = &buffer[off as usize..(off + sz) as usize];\n\n /* short‑circuit: static .a archive inside FAT ---------- */\n if slice.starts_with(AR_MAGIC) {\n debug!(\"[slice {}] static archive – skipped\", idx);\n continue;\n }\n\n /* decide 32 / 64 by magic ------------------------------ */\n if slice.len() >= 4 {\n let magic = u32::from_le_bytes(slice[0..4].try_into().unwrap());\n if magic == MH_MAGIC_64 {\n if let Ok(m) = MachOFile::, _>::parse(slice) {\n let (mut p, mut s) = find_patches_in_commands(\n &m,\n off as usize,\n MACHO_HEADER64_SIZE,\n replacements,\n path_for_log,\n )?;\n patches.append(&mut p);\n skipped_paths.append(&mut s);\n }\n } else if magic == MH_MAGIC {\n if let Ok(m) = MachOFile::, _>::parse(slice) {\n let (mut p, mut s) = find_patches_in_commands(\n &m,\n off as usize,\n MACHO_HEADER32_SIZE,\n replacements,\n path_for_log,\n )?;\n patches.append(&mut p);\n skipped_paths.append(&mut s);\n }\n }\n }\n }\n }\n /* ---------------------------------------------------------- */\n FileKind::MachOFat64 => {\n let fat = MachOFatFile64::parse(buffer)?;\n for (idx, arch) in fat.arches().iter().enumerate() {\n let (off, sz) = arch.file_range();\n let slice = &buffer[off as usize..(off + sz) as usize];\n\n if slice.starts_with(AR_MAGIC) {\n debug!(\"[slice {}] static archive – skipped\", idx);\n continue;\n }\n\n if slice.len() >= 4 {\n let magic = u32::from_le_bytes(slice[0..4].try_into().unwrap());\n if magic == MH_MAGIC_64 {\n if let Ok(m) = MachOFile::, _>::parse(slice) {\n let (mut p, mut s) = find_patches_in_commands(\n &m,\n off as usize,\n MACHO_HEADER64_SIZE,\n replacements,\n path_for_log,\n )?;\n patches.append(&mut p);\n skipped_paths.append(&mut s);\n }\n } else if magic == MH_MAGIC {\n if let Ok(m) = MachOFile::, _>::parse(slice) {\n let (mut p, mut s) = find_patches_in_commands(\n &m,\n off as usize,\n MACHO_HEADER32_SIZE,\n replacements,\n path_for_log,\n )?;\n patches.append(&mut p);\n skipped_paths.append(&mut s);\n }\n }\n }\n }\n }\n /* ---------------------------------------------------------- */\n _ => { /* archives & unknown kinds are ignored */ }\n }\n\n Ok((patches, skipped_paths))\n}\n\n/// Iterates through load commands of a parsed MachOFile (slice) and returns\n/// patch details + skipped paths.\n#[cfg(target_os = \"macos\")]\nfn find_patches_in_commands<'data, Mach, R>(\n macho_file: &MachOFile<'data, Mach, R>,\n slice_base_offset: usize,\n header_size: usize,\n replacements: &HashMap,\n file_path_for_log: &Path,\n) -> Result<(Vec, Vec)>\nwhere\n Mach: MachHeader,\n R: ReadRef<'data>,\n{\n let endian = macho_file.endian();\n let mut patches = Vec::new();\n let mut skipped_paths = Vec::new();\n let mut cur_off = header_size;\n\n let mut it = macho_file.macho_load_commands()?;\n while let Some(cmd) = it.next()? {\n let cmd_size = cmd.cmdsize() as usize;\n let cmd_offset = cur_off; // offset *inside this slice*\n cur_off += cmd_size;\n\n let variant = match cmd.variant() {\n Ok(v) => v,\n Err(e) => {\n tracing::warn!(\n \"Malformed load‑command in {}: {}; skipping\",\n file_path_for_log.display(),\n e\n );\n continue;\n }\n };\n\n // — which commands carry path strings we might want? —\n let path_info: Option<(u32, &[u8])> = match variant {\n LoadCommandVariant::Dylib(d) | LoadCommandVariant::IdDylib(d) => cmd\n .string(endian, d.dylib.name)\n .ok()\n .map(|bytes| (d.dylib.name.offset.get(endian), bytes)),\n LoadCommandVariant::Rpath(r) => cmd\n .string(endian, r.path)\n .ok()\n .map(|bytes| (r.path.offset.get(endian), bytes)),\n _ => None,\n };\n\n if let Some((offset_in_cmd, bytes)) = path_info {\n if let Ok(old_path) = std::str::from_utf8(bytes) {\n if let Some(new_path) = find_and_replace_placeholders(old_path, replacements) {\n let allocated = cmd_size.saturating_sub(offset_in_cmd as usize);\n\n if new_path.len() + 1 > allocated {\n // would overflow – add to skipped paths instead of throwing\n tracing::debug!(\n \"Skip patch (too long): '{}' → '{}' (alloc {} B) in {}\",\n old_path,\n new_path,\n allocated,\n file_path_for_log.display()\n );\n skipped_paths.push(SkippedPath {\n old_path: old_path.to_string(),\n new_path: new_path.clone(),\n });\n continue;\n }\n\n patches.push(PatchInfo {\n absolute_offset: slice_base_offset + cmd_offset + offset_in_cmd as usize,\n allocated_len: allocated,\n new_path,\n });\n }\n }\n }\n }\n Ok((patches, skipped_paths))\n}\n\n/// Helper to replace placeholders in a string based on the replacements map.\n/// Returns `Some(String)` with replacements if any were made, `None` otherwise.\nfn find_and_replace_placeholders(\n current_path: &str,\n replacements: &HashMap,\n) -> Option {\n let mut new_path = current_path.to_string();\n let mut path_modified = false;\n // Iterate through all placeholder/replacement pairs\n for (placeholder, replacement) in replacements {\n // Check if the current path string contains the placeholder\n if new_path.contains(placeholder) {\n // Replace all occurrences of the placeholder\n new_path = new_path.replace(placeholder, replacement);\n path_modified = true; // Mark that a change was made\n debug!(\n \" Replaced '{}' with '{}' -> '{}'\",\n placeholder, replacement, new_path\n );\n }\n }\n // Return the modified string only if changes occurred\n if path_modified {\n Some(new_path)\n } else {\n None\n }\n}\n\n/// Write a new (null‑padded) path into the mutable buffer. \n/// Assumes the caller already verified the length.\n#[cfg(target_os = \"macos\")]\nfn patch_path_in_buffer(\n buf: &mut [u8],\n abs_off: usize,\n alloc_len: usize,\n new_path: &str,\n file: &Path,\n) -> Result<()> {\n if new_path.len() + 1 > alloc_len || abs_off + alloc_len > buf.len() {\n // should never happen – just log & skip\n tracing::debug!(\n \"Patch skipped (bounds) at {} in {}\",\n abs_off,\n file.display()\n );\n return Ok(());\n }\n\n // null‑padded copy\n buf[abs_off..abs_off + new_path.len()].copy_from_slice(new_path.as_bytes());\n buf[abs_off + new_path.len()..abs_off + alloc_len].fill(0);\n\n Ok(())\n}\n\n/// Writes the patched buffer to the original path atomically using a temporary file.\n#[cfg(target_os = \"macos\")]\nfn write_patched_buffer(original_path: &Path, buffer: &[u8]) -> Result<()> {\n // Get the directory containing the original file\n let dir = original_path.parent().ok_or_else(|| {\n SpsError::Generic(format!(\n \"Cannot get parent directory for {}\",\n original_path.display()\n ))\n })?;\n // Ensure the directory exists\n fs::create_dir_all(dir).map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n\n // Create a named temporary file in the same directory to facilitate atomic rename\n let mut temp_file = NamedTempFile::new_in(dir)?;\n debug!(\n \" Writing patched buffer ({} bytes) to temporary file: {:?}\",\n buffer.len(),\n temp_file.path()\n );\n // Write the entire modified buffer to the temporary file\n temp_file.write_all(buffer)?;\n // Ensure data is flushed to the OS buffer\n temp_file.flush()?;\n // Attempt to sync data to the disk\n temp_file.as_file().sync_all()?; // Ensure data is physically written\n\n // Atomically replace the original file with the temporary file\n // persist() renames the temp file over the original path.\n temp_file.persist(original_path).map_err(|e| {\n // If persist fails, the temporary file might still exist.\n // The error 'e' contains both the temp file and the underlying IO error.\n error!(\n \" Failed to persist/rename temporary file over {}: {}\",\n original_path.display(),\n e.error // Log the underlying IO error\n );\n // Return the IO error wrapped in our error type\n SpsError::Io(std::sync::Arc::new(e.error))\n })?;\n debug!(\n \" Atomically replaced {} with patched version\",\n original_path.display()\n );\n Ok(())\n}\n\n/// Re-signs the binary using the `codesign` command-line tool.\n/// This is typically necessary on Apple Silicon (aarch64) after modifying executables.\n#[cfg(all(target_os = \"macos\", target_arch = \"aarch64\"))]\nfn resign_binary(path: &Path) -> Result<()> {\n // Suppressed: debug!(\"Re-signing patched binary: {}\", path.display());\n let status = StdCommand::new(\"codesign\")\n .args([\n \"-s\",\n \"-\",\n \"--force\",\n \"--preserve-metadata=identifier,entitlements\",\n ])\n .arg(path)\n .stdout(Stdio::null())\n .stderr(Stdio::null())\n .status() // Execute the command and get its exit status\n .map_err(|e| {\n error!(\n \" Failed to execute codesign command for {}: {}\",\n path.display(),\n e\n );\n SpsError::Io(std::sync::Arc::new(e))\n })?;\n if status.success() {\n // Suppressed: debug!(\"Successfully re-signed {}\", path.display());\n Ok(())\n } else {\n error!(\n \" codesign command failed for {} with status: {}\",\n path.display(),\n status\n );\n Err(SpsError::CodesignError(format!(\n \"Failed to re-sign patched binary {}, it may not be executable. Exit status: {}\",\n path.display(),\n status\n )))\n }\n}\n\n// No-op stub for resigning on non-Apple Silicon macOS (e.g., x86_64)\n#[cfg(all(target_os = \"macos\", not(target_arch = \"aarch64\")))]\nfn resign_binary(_path: &Path) -> Result<()> {\n // No re-signing typically needed on Intel Macs after ad-hoc patching\n Ok(())\n}\n\n// No-op stub for resigning Innovations on non-macOS platforms\n#[cfg(not(target_os = \"macos\"))]\nfn resign_binary(_path: &Path) -> Result<()> {\n // Resigning is a macOS concept\n Ok(())\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/zap.rs", "// ===== sps-core/src/build/cask/artifacts/zap.rs =====\n\nuse std::fs;\nuse std::path::{Path, PathBuf}; // Import Path\nuse std::process::{Command, Stdio};\n\nuse regex::Regex;\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::InstalledArtifact;\n\n/// Implements the `zap` stanza by performing deep-clean actions\n/// such as trash, delete, rmdir, pkgutil forget, launchctl unload,\n/// and arbitrary scripts, matching Homebrew's Cask behavior.\npub fn install_zap(cask: &Cask, config: &Config) -> Result> {\n let mut artifacts: Vec = Vec::new();\n let home = config.home_dir();\n\n if let Some(entries) = &cask.artifacts {\n for entry in entries {\n if let Some(obj) = entry.as_object() {\n if let Some(zaps) = obj.get(\"zap\").and_then(|v| v.as_array()) {\n for zap_map in zaps {\n if let Some(zap_obj) = zap_map.as_object() {\n for (key, val) in zap_obj {\n match key.as_str() {\n \"trash\" => {\n if let Some(arr) = val.as_array() {\n for item in arr.iter().filter_map(|v| v.as_str()) {\n let target = expand_tilde(item, &home); // Pass &Path\n if !is_safe_path(&target, &home) {\n debug!(\n \"Unsafe trash path {}, skipping\",\n target.display()\n );\n continue;\n }\n debug!(\"Trashing {}...\", target.display());\n let _ = Command::new(\"trash\")\n .arg(&target)\n .stdout(Stdio::null())\n .stderr(Stdio::null())\n .status();\n }\n }\n }\n \"delete\" => {\n if let Some(arr) = val.as_array() {\n for item in arr.iter().filter_map(|v| v.as_str()) {\n let target = expand_tilde(item, &home); // Pass &Path\n if !is_safe_path(&target, &home) {\n debug!(\n \"Unsafe delete path {}, skipping\",\n target.display()\n );\n continue;\n }\n debug!(\"Deleting file {}...\", target.display());\n if let Err(e) = fs::remove_file(&target) {\n if e.kind() != std::io::ErrorKind::NotFound {\n debug!(\n \"Failed to delete {}: {}\",\n target.display(),\n e\n );\n }\n }\n }\n }\n }\n \"rmdir\" => {\n if let Some(arr) = val.as_array() {\n for item in arr.iter().filter_map(|v| v.as_str()) {\n let target = expand_tilde(item, &home); // Pass &Path\n if !is_safe_path(&target, &home) {\n debug!(\n \"Unsafe rmdir path {}, skipping\",\n target.display()\n );\n continue;\n }\n debug!(\n \"Removing directory {}...\",\n target.display()\n );\n if let Err(e) = fs::remove_dir_all(&target) {\n if e.kind() != std::io::ErrorKind::NotFound {\n debug!(\n \"Failed to rmdir {}: {}\",\n target.display(),\n e\n );\n }\n }\n }\n }\n }\n \"pkgutil\" => {\n if let Some(arr) = val.as_array() {\n for item in arr.iter().filter_map(|v| v.as_str()) {\n if !is_valid_pkgid(item) {\n debug!(\n \"Invalid pkgutil id '{}', skipping\",\n item\n );\n continue;\n }\n debug!(\"Forgetting pkgutil receipt {}...\", item);\n let _ = Command::new(\"pkgutil\")\n .arg(\"--forget\")\n .arg(item)\n .stdout(Stdio::null())\n .stderr(Stdio::null())\n .status();\n artifacts.push(InstalledArtifact::PkgUtilReceipt {\n id: item.to_string(),\n });\n }\n }\n }\n \"launchctl\" => {\n if let Some(arr) = val.as_array() {\n for label in arr.iter().filter_map(|v| v.as_str()) {\n if !is_valid_label(label) {\n debug!(\n \"Invalid launchctl label '{}', skipping\",\n label\n );\n continue;\n }\n let plist = home // Use expanded home\n .join(\"Library/LaunchAgents\")\n .join(format!(\"{label}.plist\"));\n if !is_safe_path(&plist, &home) {\n debug!(\n \"Unsafe plist path {} for label {}, skipping\",\n plist.display(),\n label\n );\n continue;\n }\n debug!(\n \"Unloading launchctl {}...\",\n plist.display()\n );\n let _ = Command::new(\"launchctl\")\n .arg(\"unload\")\n .arg(&plist)\n .stdout(Stdio::null())\n .stderr(Stdio::null())\n .status();\n artifacts.push(InstalledArtifact::Launchd {\n label: label.to_string(),\n path: Some(plist),\n });\n }\n }\n }\n \"script\" => {\n if let Some(cmd) = val.as_str() {\n if !is_valid_command(cmd) {\n debug!(\n \"Invalid zap script command '{}', skipping\",\n cmd\n );\n continue;\n }\n debug!(\"Running zap script: {}...\", cmd);\n let _ = Command::new(\"sh\")\n .arg(\"-c\")\n .arg(cmd)\n .stdout(Stdio::null())\n .stderr(Stdio::null())\n .status();\n }\n }\n \"signal\" => {\n if let Some(arr) = val.as_array() {\n for cmd in arr.iter().filter_map(|v| v.as_str()) {\n if !is_valid_command(cmd) {\n debug!(\n \"Invalid signal command '{}', skipping\",\n cmd\n );\n continue;\n }\n debug!(\"Running signal command: {}...\", cmd);\n let _ = Command::new(\"sh\")\n .arg(\"-c\")\n .arg(cmd)\n .stdout(Stdio::null())\n .stderr(Stdio::null())\n .status();\n }\n }\n }\n _ => debug!(\"Unsupported zap key '{}', skipping\", key),\n }\n }\n }\n }\n // Only process the first \"zap\" stanza found\n break;\n }\n }\n }\n }\n\n Ok(artifacts)\n}\n\n// New helper functions to validate paths and strings.\nfn is_safe_path(path: &Path, home: &Path) -> bool {\n if path\n .components()\n .any(|c| matches!(c, std::path::Component::ParentDir))\n {\n return false;\n }\n let path_str = path.to_string_lossy();\n if path.is_absolute()\n && (path_str.starts_with(\"/Applications\") || path_str.starts_with(\"/Library\"))\n {\n return true;\n }\n if path.starts_with(home) {\n return true;\n }\n if path_str.contains(\"Caskroom/Cellar\") {\n return true;\n }\n false\n}\n\nfn is_valid_pkgid(pkgid: &str) -> bool {\n let re = Regex::new(r\"^[a-zA-Z0-9.-]+$\").unwrap();\n re.is_match(pkgid)\n}\n\nfn is_valid_label(label: &str) -> bool {\n let re = Regex::new(r\"^[a-zA-Z0-9.-]+$\").unwrap();\n re.is_match(label)\n}\n\nfn is_valid_command(cmd: &str) -> bool {\n let re = Regex::new(r\"^[a-zA-Z0-9\\s\\-_./]+$\").unwrap();\n re.is_match(cmd)\n}\n\n/// Expand a path that may start with '~' to the user's home directory\nfn expand_tilde(path: &str, home: &Path) -> PathBuf {\n if let Some(stripped) = path.strip_prefix(\"~/\") {\n home.join(stripped)\n } else {\n PathBuf::from(path)\n }\n}\n"], ["/sps/sps-core/src/install/devtools.rs", "use std::env;\nuse std::path::PathBuf;\nuse std::process::{Command, Stdio};\n\nuse sps_common::error::{Result, SpsError};\nuse tracing::debug;\nuse which;\n\npub fn find_compiler(name: &str) -> Result {\n let env_var_name = match name {\n \"cc\" => \"CC\",\n \"c++\" | \"cxx\" => \"CXX\",\n _ => \"\",\n };\n if !env_var_name.is_empty() {\n if let Ok(compiler_path) = env::var(env_var_name) {\n let path = PathBuf::from(compiler_path);\n if path.is_file() {\n debug!(\n \"Using compiler from env var {}: {}\",\n env_var_name,\n path.display()\n );\n return Ok(path);\n } else {\n debug!(\n \"Env var {} points to non-existent file: {}\",\n env_var_name,\n path.display()\n );\n }\n }\n }\n\n if cfg!(target_os = \"macos\") {\n debug!(\"Attempting to find '{name}' using xcrun\");\n let output = Command::new(\"xcrun\")\n .arg(\"--find\")\n .arg(name)\n .stderr(Stdio::piped())\n .output();\n\n match output {\n Ok(out) if out.status.success() => {\n let path_str = String::from_utf8_lossy(&out.stdout).trim().to_string();\n if !path_str.is_empty() {\n let path = PathBuf::from(path_str);\n if path.is_file() {\n debug!(\"Found compiler via xcrun: {}\", path.display());\n return Ok(path);\n } else {\n debug!(\n \"xcrun found '{}' but path doesn't exist or isn't a file: {}\",\n name,\n path.display()\n );\n }\n } else {\n debug!(\"xcrun found '{name}' but returned empty path.\");\n }\n }\n Ok(out) => {\n let stderr = String::from_utf8_lossy(&out.stderr);\n debug!(\"xcrun failed to find '{}': {}\", name, stderr.trim());\n }\n Err(e) => {\n debug!(\"Failed to execute xcrun: {e}. Falling back to PATH search.\");\n }\n }\n }\n\n debug!(\"Falling back to searching PATH for '{name}'\");\n which::which(name).map_err(|e| {\n SpsError::BuildEnvError(format!(\"Failed to find compiler '{name}' on PATH: {e}\"))\n })\n}\n\npub fn find_sdk_path() -> Result {\n if cfg!(target_os = \"macos\") {\n debug!(\"Attempting to find macOS SDK path using xcrun\");\n let output = Command::new(\"xcrun\")\n .arg(\"--show-sdk-path\")\n .stderr(Stdio::piped())\n .output();\n\n match output {\n Ok(out) if out.status.success() => {\n let path_str = String::from_utf8_lossy(&out.stdout).trim().to_string();\n if path_str.is_empty() || path_str == \"/\" {\n return Err(SpsError::BuildEnvError(\n \"xcrun returned empty or invalid SDK path. Is Xcode or Command Line Tools installed correctly?\".to_string()\n ));\n }\n let sdk_path = PathBuf::from(path_str);\n if !sdk_path.exists() {\n return Err(SpsError::BuildEnvError(format!(\n \"SDK path reported by xcrun does not exist: {}\",\n sdk_path.display()\n )));\n }\n debug!(\"Found SDK path: {}\", sdk_path.display());\n Ok(sdk_path)\n }\n Ok(out) => {\n let stderr = String::from_utf8_lossy(&out.stderr);\n Err(SpsError::BuildEnvError(format!(\n \"xcrun failed to find SDK path: {}\",\n stderr.trim()\n )))\n }\n Err(e) => {\n Err(SpsError::BuildEnvError(format!(\n \"Failed to execute 'xcrun --show-sdk-path': {e}. Is Xcode or Command Line Tools installed?\"\n )))\n }\n }\n } else {\n debug!(\"Not on macOS, returning '/' as SDK path placeholder\");\n Ok(PathBuf::from(\"/\"))\n }\n}\n\npub fn get_macos_version() -> Result {\n if cfg!(target_os = \"macos\") {\n debug!(\"Attempting to get macOS version using sw_vers\");\n let output = Command::new(\"sw_vers\")\n .arg(\"-productVersion\")\n .stderr(Stdio::piped())\n .output();\n\n match output {\n Ok(out) if out.status.success() => {\n let version_full = String::from_utf8_lossy(&out.stdout).trim().to_string();\n let version_parts: Vec<&str> = version_full.split('.').collect();\n let version_short = if version_parts.len() >= 2 {\n format!(\"{}.{}\", version_parts[0], version_parts[1])\n } else {\n version_full.clone()\n };\n debug!(\"Found macOS version: {version_full} (short: {version_short})\");\n Ok(version_short)\n }\n Ok(out) => {\n let stderr = String::from_utf8_lossy(&out.stderr);\n Err(SpsError::BuildEnvError(format!(\n \"sw_vers failed to get product version: {}\",\n stderr.trim()\n )))\n }\n Err(e) => Err(SpsError::BuildEnvError(format!(\n \"Failed to execute 'sw_vers -productVersion': {e}\"\n ))),\n }\n } else {\n debug!(\"Not on macOS, returning '0.0' as version placeholder\");\n Ok(String::from(\"0.0\"))\n }\n}\n\npub fn get_arch_flag() -> String {\n if cfg!(target_os = \"macos\") {\n if cfg!(target_arch = \"x86_64\") {\n debug!(\"Detected target arch: x86_64\");\n \"-arch x86_64\".to_string()\n } else if cfg!(target_arch = \"aarch64\") {\n debug!(\"Detected target arch: aarch64 (arm64)\");\n \"-arch arm64\".to_string()\n } else {\n let arch = env::consts::ARCH;\n debug!(\n \"Unknown target architecture on macOS: {arch}, cannot determine -arch flag. Build might fail.\"\n );\n // Provide no flag in this unknown case? Or default to native?\n String::new()\n }\n } else {\n debug!(\"Not on macOS, returning empty arch flag.\");\n String::new()\n }\n}\n"], ["/sps/sps-net/src/oci.rs", "use std::collections::HashMap;\nuse std::fs::{remove_file, File};\nuse std::path::Path;\nuse std::sync::Arc;\nuse std::time::Duration;\n\nuse futures::StreamExt;\nuse rand::rngs::SmallRng;\nuse rand::{Rng, SeedableRng};\nuse reqwest::header::{ACCEPT, AUTHORIZATION};\nuse reqwest::{Client, Response, StatusCode};\nuse serde::{Deserialize, Serialize};\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse tracing::{debug, error};\nuse url::Url;\n\nuse crate::http::ProgressCallback;\nuse crate::validation::{validate_url, verify_checksum};\n\nconst OCI_MANIFEST_V1_TYPE: &str = \"application/vnd.oci.image.index.v1+json\";\nconst OCI_LAYER_V1_TYPE: &str = \"application/vnd.oci.image.layer.v1.tar+gzip\";\nconst DEFAULT_GHCR_TOKEN_ENDPOINT: &str = \"https://ghcr.io/token\";\npub const DEFAULT_GHCR_DOMAIN: &str = \"ghcr.io\";\n\nconst CONNECT_TIMEOUT_SECS: u64 = 30;\nconst REQUEST_TIMEOUT_SECS: u64 = 300;\nconst USER_AGENT_STRING: &str = \"sps package manager (Rust; +https://github.com/alexykn/sps)\";\n\n#[derive(Deserialize, Debug)]\nstruct OciTokenResponse {\n token: String,\n}\n\n#[derive(Serialize, Deserialize, Debug, Clone)]\n#[serde(rename_all = \"camelCase\")]\npub struct OciManifestIndex {\n pub schema_version: u32,\n pub media_type: Option,\n pub manifests: Vec,\n}\n\n#[derive(Serialize, Deserialize, Debug, Clone)]\n#[serde(rename_all = \"camelCase\")]\npub struct OciManifestDescriptor {\n pub media_type: String,\n pub digest: String,\n pub size: u64,\n pub platform: Option,\n pub annotations: Option>,\n}\n\n#[derive(Serialize, Deserialize, Debug, Clone)]\n#[serde(rename_all = \"camelCase\")]\npub struct OciPlatform {\n pub architecture: String,\n pub os: String,\n #[serde(rename = \"os.version\")]\n pub os_version: Option,\n #[serde(default)]\n pub features: Vec,\n pub variant: Option,\n}\n\n#[derive(Debug, Clone)]\nenum OciAuth {\n None,\n AnonymousBearer { token: String },\n ExplicitBearer { token: String },\n Basic { encoded: String },\n}\n\nasync fn fetch_oci_resource(\n resource_url: &str,\n accept_header: &str,\n config: &Config,\n client: &Client,\n) -> Result {\n let url = Url::parse(resource_url)\n .map_err(|e| SpsError::Generic(format!(\"Invalid URL '{resource_url}': {e}\")))?;\n validate_url(url.as_str())?;\n let registry_domain = url.host_str().unwrap_or(DEFAULT_GHCR_DOMAIN);\n let repo_path = extract_repo_path_from_url(&url).unwrap_or(\"\");\n\n let auth = determine_auth(config, client, registry_domain, repo_path).await?;\n let resp = execute_oci_request(client, resource_url, accept_header, &auth).await?;\n let txt = resp.text().await.map_err(|e| SpsError::Http(Arc::new(e)))?;\n\n debug!(\"OCI response ({} bytes) from {}\", txt.len(), resource_url);\n serde_json::from_str(&txt).map_err(|e| {\n error!(\"JSON parse error from {}: {}\", resource_url, e);\n SpsError::Json(Arc::new(e))\n })\n}\n\npub async fn download_oci_blob(\n blob_url: &str,\n destination_path: &Path,\n config: &Config,\n client: &Client,\n expected_digest: &str,\n) -> Result<()> {\n download_oci_blob_with_progress(\n blob_url,\n destination_path,\n config,\n client,\n expected_digest,\n None,\n )\n .await\n}\n\npub async fn download_oci_blob_with_progress(\n blob_url: &str,\n destination_path: &Path,\n config: &Config,\n client: &Client,\n expected_digest: &str,\n progress_callback: Option,\n) -> Result<()> {\n debug!(\"Downloading OCI blob: {}\", blob_url);\n let url = Url::parse(blob_url)\n .map_err(|e| SpsError::Generic(format!(\"Invalid URL '{blob_url}': {e}\")))?;\n validate_url(url.as_str())?;\n let registry_domain = url.host_str().unwrap_or(DEFAULT_GHCR_DOMAIN);\n let repo_path = extract_repo_path_from_url(&url).unwrap_or(\"\");\n\n let auth = determine_auth(config, client, registry_domain, repo_path).await?;\n let resp = execute_oci_request(client, blob_url, OCI_LAYER_V1_TYPE, &auth).await?;\n\n // Get total size from Content-Length header if available\n let total_size = resp.content_length();\n\n let tmp = destination_path.with_file_name(format!(\n \".{}.download\",\n destination_path.file_name().unwrap().to_string_lossy()\n ));\n let mut out = File::create(&tmp).map_err(|e| SpsError::Io(Arc::new(e)))?;\n\n let mut stream = resp.bytes_stream();\n let mut bytes_downloaded = 0u64;\n\n while let Some(chunk) = stream.next().await {\n let b = chunk.map_err(|e| SpsError::Http(Arc::new(e)))?;\n std::io::Write::write_all(&mut out, &b).map_err(|e| SpsError::Io(Arc::new(e)))?;\n\n bytes_downloaded += b.len() as u64;\n\n // Call progress callback if provided\n if let Some(ref callback) = progress_callback {\n callback(bytes_downloaded, total_size);\n }\n }\n std::fs::rename(&tmp, destination_path).map_err(|e| SpsError::Io(Arc::new(e)))?;\n\n if !expected_digest.is_empty() {\n match verify_checksum(destination_path, expected_digest) {\n Ok(_) => {\n tracing::debug!(\"OCI Blob checksum verified: {}\", destination_path.display());\n }\n Err(e) => {\n tracing::error!(\n \"OCI Blob checksum mismatch ({}). Deleting downloaded file.\",\n e\n );\n let _ = remove_file(destination_path);\n return Err(e);\n }\n }\n } else {\n tracing::warn!(\n \"Skipping checksum verification for OCI blob {} - no checksum provided.\",\n destination_path.display()\n );\n }\n\n debug!(\"Blob saved to {}\", destination_path.display());\n Ok(())\n}\n\npub async fn fetch_oci_manifest_index(\n manifest_url: &str,\n config: &Config,\n client: &Client,\n) -> Result {\n fetch_oci_resource(manifest_url, OCI_MANIFEST_V1_TYPE, config, client).await\n}\n\npub fn build_oci_client() -> Result {\n Client::builder()\n .user_agent(USER_AGENT_STRING)\n .connect_timeout(Duration::from_secs(CONNECT_TIMEOUT_SECS))\n .timeout(Duration::from_secs(REQUEST_TIMEOUT_SECS))\n .redirect(reqwest::redirect::Policy::default())\n .build()\n .map_err(|e| SpsError::Http(Arc::new(e)))\n}\n\nfn extract_repo_path_from_url(url: &Url) -> Option<&str> {\n url.path()\n .trim_start_matches('/')\n .trim_start_matches(\"v2/\")\n .split(\"/manifests/\")\n .next()\n .and_then(|s| s.split(\"/blobs/\").next())\n .filter(|s| !s.is_empty())\n}\n\nasync fn determine_auth(\n config: &Config,\n client: &Client,\n registry_domain: &str,\n repo_path: &str,\n) -> Result {\n if let Some(token) = &config.docker_registry_token {\n debug!(\"Using explicit bearer for {}\", registry_domain);\n return Ok(OciAuth::ExplicitBearer {\n token: token.clone(),\n });\n }\n if let Some(basic) = &config.docker_registry_basic_auth {\n debug!(\"Using explicit basic auth for {}\", registry_domain);\n return Ok(OciAuth::Basic {\n encoded: basic.clone(),\n });\n }\n\n if registry_domain.eq_ignore_ascii_case(DEFAULT_GHCR_DOMAIN) && !repo_path.is_empty() {\n debug!(\n \"Anonymous token fetch for {} scope={}\",\n registry_domain, repo_path\n );\n match fetch_anonymous_token(client, registry_domain, repo_path).await {\n Ok(t) => return Ok(OciAuth::AnonymousBearer { token: t }),\n Err(e) => debug!(\"Anon token failed, proceeding unauthenticated: {}\", e),\n }\n }\n Ok(OciAuth::None)\n}\n\nasync fn fetch_anonymous_token(\n client: &Client,\n registry_domain: &str,\n repo_path: &str,\n) -> Result {\n let endpoint = if registry_domain.eq_ignore_ascii_case(DEFAULT_GHCR_DOMAIN) {\n DEFAULT_GHCR_TOKEN_ENDPOINT.to_string()\n } else {\n format!(\"https://{registry_domain}/token\")\n };\n let scope = format!(\"repository:{repo_path}:pull\");\n let token_url = format!(\"{endpoint}?service={registry_domain}&scope={scope}\");\n\n const MAX_RETRIES: u8 = 3;\n let base_delay = Duration::from_millis(200);\n let mut delay = base_delay;\n // Use a Sendable RNG\n let mut rng = SmallRng::from_os_rng();\n\n for attempt in 0..=MAX_RETRIES {\n debug!(\n \"Token attempt {}/{} from {}\",\n attempt + 1,\n MAX_RETRIES + 1,\n token_url\n );\n\n match client.get(&token_url).send().await {\n Ok(resp) if resp.status().is_success() => {\n let tok: OciTokenResponse = resp\n .json()\n .await\n .map_err(|e| SpsError::ApiRequestError(format!(\"Parse token response: {e}\")))?;\n return Ok(tok.token);\n }\n Ok(resp) => {\n let code = resp.status();\n let body = resp.text().await.unwrap_or_default();\n error!(\"Token fetch {}: {} – {}\", attempt + 1, code, body);\n if !code.is_server_error() || attempt == MAX_RETRIES {\n return Err(SpsError::Api(format!(\"Token endpoint {code}: {body}\")));\n }\n }\n Err(e) => {\n error!(\"Network error on token fetch {}: {}\", attempt + 1, e);\n if attempt == MAX_RETRIES {\n return Err(SpsError::Http(Arc::new(e)));\n }\n }\n }\n\n let jitter = rng.random_range(0..(base_delay.as_millis() as u64 / 2));\n tokio::time::sleep(delay + Duration::from_millis(jitter)).await;\n delay *= 2;\n }\n\n Err(SpsError::Api(format!(\n \"Failed to fetch OCI token after {} attempts\",\n MAX_RETRIES + 1\n )))\n}\n\nasync fn execute_oci_request(\n client: &Client,\n url: &str,\n accept: &str,\n auth: &OciAuth,\n) -> Result {\n debug!(\"OCI request → {} (Accept: {})\", url, accept);\n let mut req = client.get(url).header(ACCEPT, accept);\n match auth {\n OciAuth::AnonymousBearer { token } | OciAuth::ExplicitBearer { token }\n if !token.is_empty() =>\n {\n req = req.header(AUTHORIZATION, format!(\"Bearer {token}\"))\n }\n OciAuth::Basic { encoded } if !encoded.is_empty() => {\n req = req.header(AUTHORIZATION, format!(\"Basic {encoded}\"))\n }\n _ => {}\n }\n\n let resp = req.send().await.map_err(|e| SpsError::Http(Arc::new(e)))?;\n let status = resp.status();\n if status.is_success() {\n Ok(resp)\n } else {\n let body = resp.text().await.unwrap_or_default();\n error!(\"OCI {} ⇒ {} – {}\", url, status, body);\n let err = match status {\n StatusCode::UNAUTHORIZED => SpsError::Api(format!(\"Auth required: {status}\")),\n StatusCode::FORBIDDEN => SpsError::Api(format!(\"Permission denied: {status}\")),\n StatusCode::NOT_FOUND => SpsError::NotFound(format!(\"Not found: {status}\")),\n _ => SpsError::Api(format!(\"HTTP {status} – {body}\")),\n };\n Err(err)\n }\n}\n"], ["/sps/sps/src/pipeline/downloader.rs", "// sps/src/pipeline/downloader.rs\nuse std::fs;\nuse std::path::PathBuf;\nuse std::sync::Arc;\n\nuse reqwest::Client as HttpClient;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::model::InstallTargetIdentifier;\nuse sps_common::pipeline::{DownloadOutcome, PipelineEvent, PlannedJob};\nuse sps_common::SpsError;\nuse sps_core::{build, install};\nuse sps_net::http::ProgressCallback;\nuse sps_net::UrlField;\nuse tokio::sync::{broadcast, mpsc};\nuse tokio::task::JoinSet;\nuse tracing::{error, warn};\n\nuse super::runner::get_panic_message;\n\npub(crate) struct DownloadCoordinator {\n config: Config,\n cache: Arc,\n http_client: Arc,\n event_tx: Option>,\n}\n\nimpl DownloadCoordinator {\n pub fn new(\n config: Config,\n cache: Arc,\n http_client: Arc,\n event_tx: broadcast::Sender,\n ) -> Self {\n Self {\n config,\n cache,\n http_client,\n event_tx: Some(event_tx),\n }\n }\n\n pub async fn coordinate_downloads(\n &mut self,\n planned_jobs: Vec,\n download_outcome_tx: mpsc::Sender,\n ) -> Vec<(String, SpsError)> {\n let mut download_tasks = JoinSet::new();\n let mut critical_spawn_errors: Vec<(String, SpsError)> = Vec::new();\n\n for planned_job in planned_jobs {\n let _job_id_for_task = planned_job.target_id.clone();\n\n let task_config = self.config.clone();\n let task_cache = Arc::clone(&self.cache);\n let task_http_client = Arc::clone(&self.http_client);\n let task_event_tx = self.event_tx.as_ref().cloned();\n let outcome_tx_clone = download_outcome_tx.clone();\n let current_planned_job_for_task = planned_job.clone();\n\n download_tasks.spawn(async move {\n let job_id_in_task = current_planned_job_for_task.target_id.clone();\n let download_path_result: Result;\n\n if let Some(private_path) = current_planned_job_for_task.use_private_store_source.clone() {\n download_path_result = Ok(private_path);\n } else {\n let display_url_for_event = match ¤t_planned_job_for_task.target_definition {\n InstallTargetIdentifier::Formula(f) => {\n if !current_planned_job_for_task.is_source_build {\n sps_core::install::bottle::exec::get_bottle_for_platform(f)\n .map_or_else(|_| f.url.clone(), |(_, spec)| spec.url.clone())\n } else {\n f.url.clone()\n }\n }\n InstallTargetIdentifier::Cask(c) => match &c.url {\n Some(UrlField::Simple(s)) => s.clone(),\n Some(UrlField::WithSpec { url, .. }) => url.clone(),\n None => \"N/A (No Cask URL)\".to_string(),\n },\n };\n\n if display_url_for_event == \"N/A (No Cask URL)\"\n || (display_url_for_event.is_empty() && !current_planned_job_for_task.is_source_build)\n {\n let _err_msg = \"Download URL is missing or invalid\".to_string();\n let sps_err = SpsError::Generic(format!(\n \"Download URL is missing or invalid for job {job_id_in_task}\"\n ));\n if let Some(ref tx) = task_event_tx {\n tx.send(PipelineEvent::download_failed(\n job_id_in_task.clone(),\n display_url_for_event,\n &sps_err,\n )).ok();\n }\n download_path_result = Err(sps_err);\n } else {\n if let Some(ref tx) = task_event_tx {\n tx.send(PipelineEvent::DownloadStarted {\n target_id: job_id_in_task.clone(),\n url: display_url_for_event.clone(),\n }).ok();\n }\n\n // Create progress callback\n let progress_callback: Option = if let Some(ref tx) = task_event_tx {\n let tx_clone = tx.clone();\n let job_id_for_callback = job_id_in_task.clone();\n Some(Arc::new(move |bytes_so_far: u64, total_size: Option| {\n let _ = tx_clone.send(PipelineEvent::DownloadProgressUpdate {\n target_id: job_id_for_callback.clone(),\n bytes_so_far,\n total_size,\n });\n }))\n } else {\n None\n };\n\n let actual_download_result: Result<(PathBuf, bool), SpsError> =\n match ¤t_planned_job_for_task.target_definition {\n InstallTargetIdentifier::Formula(f) => {\n if current_planned_job_for_task.is_source_build {\n build::compile::download_source_with_progress(f, &task_config, progress_callback).await.map(|p| (p, false))\n } else {\n install::bottle::exec::download_bottle_with_progress_and_cache_info(\n f,\n &task_config,\n &task_http_client,\n progress_callback,\n )\n .await\n }\n }\n InstallTargetIdentifier::Cask(c) => {\n install::cask::download_cask_with_progress(c, task_cache.as_ref(), progress_callback).await.map(|p| (p, false))\n }\n };\n\n match actual_download_result {\n Ok((path, was_cached)) => {\n let size_bytes = fs::metadata(&path).map(|m| m.len()).unwrap_or(0);\n if let Some(ref tx) = task_event_tx {\n if was_cached {\n tx.send(PipelineEvent::DownloadCached {\n target_id: job_id_in_task.clone(),\n size_bytes,\n }).ok();\n } else {\n tx.send(PipelineEvent::DownloadFinished {\n target_id: job_id_in_task.clone(),\n path: path.clone(),\n size_bytes,\n }).ok();\n }\n }\n download_path_result = Ok(path);\n }\n Err(e) => {\n warn!(\n \"[DownloaderTask:{}] Download failed from {}: {}\",\n job_id_in_task, display_url_for_event, e\n );\n if let Some(ref tx) = task_event_tx {\n tx.send(PipelineEvent::download_failed(\n job_id_in_task.clone(),\n display_url_for_event,\n &e,\n )).ok();\n }\n download_path_result = Err(e);\n }\n }\n }\n }\n\n let outcome = DownloadOutcome {\n planned_job: current_planned_job_for_task,\n result: download_path_result,\n };\n\n if let Err(send_err) = outcome_tx_clone.send(outcome).await {\n error!(\n \"[DownloaderTask:{}] CRITICAL: Failed to send download outcome to runner: {}. Job processing will likely stall.\",\n job_id_in_task, send_err\n );\n }\n });\n }\n\n while let Some(join_result) = download_tasks.join_next().await {\n if let Err(e) = join_result {\n let panic_msg = get_panic_message(e.into_panic());\n error!(\n \"[Downloader] A download task panicked: {}. This job's outcome was not sent.\",\n panic_msg\n );\n critical_spawn_errors.push((\n \"[UnknownDownloadTaskPanic]\".to_string(),\n SpsError::Generic(format!(\"A download task panicked: {panic_msg}\")),\n ));\n }\n }\n self.event_tx = None;\n critical_spawn_errors\n }\n}\n"], ["/sps/sps-core/src/install/extract.rs", "// Path: sps-core/src/install/extract.rs\nuse std::collections::HashSet;\nuse std::fs::{self, File};\nuse std::io::{self, Read, Seek};\nuse std::path::{Component, Path, PathBuf};\nuse std::process::Command;\n\nuse bzip2::read::BzDecoder;\nuse flate2::read::GzDecoder;\nuse sps_common::error::{Result, SpsError};\nuse tar::{Archive, EntryType};\nuse tracing::{debug, error, warn};\nuse zip::ZipArchive;\n\n#[cfg(target_os = \"macos\")]\nuse crate::utils::xattr;\n\npub(crate) fn infer_archive_root_dir(\n archive_path: &Path,\n archive_type: &str,\n) -> Result> {\n tracing::debug!(\n \"Inferring root directory for archive: {}\",\n archive_path.display()\n );\n let file = File::open(archive_path).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed to open archive {}: {}\", archive_path.display(), e),\n )))\n })?;\n\n match archive_type {\n \"zip\" => infer_zip_root(file, archive_path),\n \"gz\" | \"tgz\" => {\n let decompressed = GzDecoder::new(file);\n infer_tar_root(decompressed, archive_path)\n }\n \"bz2\" | \"tbz\" | \"tbz2\" => {\n let decompressed = BzDecoder::new(file);\n infer_tar_root(decompressed, archive_path)\n }\n \"xz\" | \"txz\" => {\n // Use external xz command to decompress, then read as tar\n infer_xz_tar_root(archive_path)\n }\n \"tar\" => infer_tar_root(file, archive_path),\n _ => Err(SpsError::Generic(format!(\n \"Cannot infer root dir for unsupported archive type '{}' in {}\",\n archive_type,\n archive_path.display()\n ))),\n }\n}\n\nfn infer_tar_root(reader: R, archive_path_for_log: &Path) -> Result> {\n let mut archive = Archive::new(reader);\n let mut unique_roots = HashSet::new();\n let mut non_empty_entry_found = false;\n let mut first_component_name: Option = None;\n\n for entry_result in archive.entries()? {\n let entry = entry_result.map_err(|e| {\n SpsError::Generic(format!(\n \"Error reading TAR entry from {}: {}\",\n archive_path_for_log.display(),\n e\n ))\n })?;\n let path = entry\n .path()\n .map_err(|e| {\n SpsError::Generic(format!(\n \"Invalid path in TAR entry from {}: {}\",\n archive_path_for_log.display(),\n e\n ))\n })?\n .into_owned();\n\n if path.components().next().is_none() {\n continue;\n }\n\n if let Some(first_comp) = path.components().next() {\n if let Component::Normal(name) = first_comp {\n non_empty_entry_found = true;\n let current_root = PathBuf::from(name);\n if first_component_name.is_none() {\n first_component_name = Some(current_root.clone());\n }\n unique_roots.insert(current_root);\n\n if unique_roots.len() > 1 {\n tracing::debug!(\n \"Multiple top-level items found in TAR {}, cannot infer single root.\",\n archive_path_for_log.display()\n );\n return Ok(None);\n }\n } else {\n tracing::debug!(\n \"Non-standard top-level component ({:?}) found in TAR {}, cannot infer single root.\",\n first_comp,\n archive_path_for_log.display()\n );\n return Ok(None);\n }\n } else {\n tracing::debug!(\n \"Empty or unusual path found in TAR {}, cannot infer single root.\",\n archive_path_for_log.display()\n );\n return Ok(None);\n }\n }\n\n if unique_roots.len() == 1 && non_empty_entry_found {\n let inferred_root = first_component_name.unwrap();\n tracing::debug!(\n \"Inferred single root directory in TAR {}: {}\",\n archive_path_for_log.display(),\n inferred_root.display()\n );\n Ok(Some(inferred_root))\n } else if !non_empty_entry_found {\n tracing::warn!(\n \"TAR archive {} appears to be empty or contain only metadata.\",\n archive_path_for_log.display()\n );\n Ok(None)\n } else {\n tracing::debug!(\n \"No single common root directory found in TAR {}. unique_roots count: {}\",\n archive_path_for_log.display(),\n unique_roots.len()\n );\n Ok(None)\n }\n}\n\nfn infer_xz_tar_root(archive_path: &Path) -> Result> {\n // Create a temporary file for decompressed content\n let temp_file =\n tempfile::NamedTempFile::new().map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n\n // Use external xz command to decompress\n let output = Command::new(\"xz\")\n .args([\"-dc\", archive_path.to_str().unwrap()])\n .output()\n .map_err(|e| {\n SpsError::Generic(format!(\n \"Failed to run xz command for decompression: {e}. Make sure xz is installed.\"\n ))\n })?;\n\n if !output.status.success() {\n return Err(SpsError::Generic(format!(\n \"xz decompression failed: {}\",\n String::from_utf8_lossy(&output.stderr)\n )));\n }\n\n // Write decompressed data to temp file\n std::fs::write(temp_file.path(), &output.stdout)\n .map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n\n // Read as tar\n let file = File::open(temp_file.path()).map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n infer_tar_root(file, archive_path)\n}\n\nfn infer_zip_root(reader: R, archive_path: &Path) -> Result> {\n let mut archive = ZipArchive::new(reader).map_err(|e| {\n SpsError::Generic(format!(\n \"Failed to open ZIP archive {}: {}\",\n archive_path.display(),\n e\n ))\n })?;\n\n let mut root_candidates = HashSet::new();\n\n for i in 0..archive.len() {\n let file = archive\n .by_index(i)\n .map_err(|e| SpsError::Generic(format!(\"Failed to read ZIP entry {i}: {e}\")))?;\n\n if let Some(enclosed_name) = file.enclosed_name() {\n if let Some(Component::Normal(name)) = enclosed_name.components().next() {\n root_candidates.insert(name.to_string_lossy().to_string());\n }\n }\n }\n\n if root_candidates.len() == 1 {\n let root = root_candidates.into_iter().next().unwrap();\n Ok(Some(PathBuf::from(root)))\n } else {\n Ok(None)\n }\n}\n\n#[cfg(target_os = \"macos\")]\npub fn quarantine_extracted_apps_in_stage(stage_dir: &Path, agent_name: &str) -> Result<()> {\n use std::fs;\n\n use tracing::{debug, warn};\n debug!(\n \"Searching for .app bundles in {} to apply quarantine.\",\n stage_dir.display()\n );\n if stage_dir.is_dir() {\n for entry_result in fs::read_dir(stage_dir)? {\n let entry = entry_result?;\n let entry_path = entry.path();\n if entry_path.is_dir() && entry_path.extension().is_some_and(|ext| ext == \"app\") {\n debug!(\n \"Found app bundle in stage: {}. Applying quarantine.\",\n entry_path.display()\n );\n if let Err(e) = xattr::set_quarantine_attribute(&entry_path, agent_name) {\n warn!(\n \"Failed to set quarantine attribute on staged app {}: {}. Installation will continue.\",\n entry_path.display(),\n e\n );\n }\n }\n }\n }\n Ok(())\n}\n\npub fn extract_archive(\n archive_path: &Path,\n target_dir: &Path,\n strip_components: usize,\n archive_type: &str,\n) -> Result<()> {\n debug!(\n \"Extracting archive '{}' (type: {}) to '{}' (strip_components={}) using native Rust crates.\",\n archive_path.display(),\n archive_type,\n target_dir.display(),\n strip_components\n );\n\n fs::create_dir_all(target_dir).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\n \"Failed to create target directory {}: {}\",\n target_dir.display(),\n e\n ),\n )))\n })?;\n\n let file = File::open(archive_path).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed to open archive {}: {}\", archive_path.display(), e),\n )))\n })?;\n\n let result = match archive_type {\n \"zip\" => extract_zip_archive(file, target_dir, strip_components, archive_path),\n \"gz\" | \"tgz\" => {\n let tar = GzDecoder::new(file);\n extract_tar_archive(tar, target_dir, strip_components, archive_path)\n }\n \"bz2\" | \"tbz\" | \"tbz2\" => {\n let tar = BzDecoder::new(file);\n extract_tar_archive(tar, target_dir, strip_components, archive_path)\n }\n \"xz\" | \"txz\" => extract_xz_tar_archive(archive_path, target_dir, strip_components),\n \"tar\" => extract_tar_archive(file, target_dir, strip_components, archive_path),\n _ => Err(SpsError::Generic(format!(\n \"Unsupported archive type provided for extraction: '{}' for file {}\",\n archive_type,\n archive_path.display()\n ))),\n };\n #[cfg(target_os = \"macos\")]\n {\n if result.is_ok() {\n // Only quarantine if main extraction was successful\n if let Err(e) = quarantine_extracted_apps_in_stage(target_dir, \"sps-extractor\") {\n tracing::warn!(\n \"Error during post-extraction quarantine scan for {}: {}\",\n archive_path.display(),\n e\n );\n }\n }\n }\n result\n}\n\n/// Represents a hardlink operation that was deferred.\nfn extract_xz_tar_archive(\n archive_path: &Path,\n target_dir: &Path,\n strip_components: usize,\n) -> Result<()> {\n debug!(\n \"Extracting XZ+TAR archive using external xz command: {}\",\n archive_path.display()\n );\n\n // Create a temporary file for decompressed content\n let temp_file =\n tempfile::NamedTempFile::new().map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n\n // Use external xz command to decompress\n let output = Command::new(\"xz\")\n .args([\"-dc\", archive_path.to_str().unwrap()])\n .output()\n .map_err(|e| {\n SpsError::Generic(format!(\n \"Failed to run xz command for extraction: {e}. Make sure xz is installed.\"\n ))\n })?;\n\n if !output.status.success() {\n return Err(SpsError::Generic(format!(\n \"xz decompression failed during extraction: {}\",\n String::from_utf8_lossy(&output.stderr)\n )));\n }\n\n // Write decompressed data to temp file\n std::fs::write(temp_file.path(), &output.stdout)\n .map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n\n // Extract as tar\n let file = File::open(temp_file.path()).map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n extract_tar_archive(file, target_dir, strip_components, archive_path)\n}\n\n#[cfg(unix)]\nstruct DeferredHardLink {\n link_path_in_archive: PathBuf,\n target_name_in_archive: PathBuf,\n}\n\nfn extract_tar_archive(\n reader: R,\n target_dir: &Path,\n strip_components: usize,\n archive_path_for_log: &Path,\n) -> Result<()> {\n let mut archive = Archive::new(reader);\n archive.set_preserve_permissions(true);\n archive.set_unpack_xattrs(true);\n archive.set_overwrite(true);\n\n debug!(\n \"Starting TAR extraction for {}\",\n archive_path_for_log.display()\n );\n\n #[cfg(unix)]\n let mut deferred_hardlinks: Vec = Vec::new();\n let mut errors: Vec = Vec::new();\n\n for entry_result in archive.entries()? {\n let mut entry = entry_result.map_err(|e| {\n SpsError::Generic(format!(\n \"Error reading TAR entry from {}: {}\",\n archive_path_for_log.display(),\n e\n ))\n })?;\n\n let original_path_in_archive: PathBuf = entry\n .path()\n .map_err(|e| {\n SpsError::Generic(format!(\n \"Invalid path in TAR entry from {}: {}\",\n archive_path_for_log.display(),\n e\n ))\n })?\n .into_owned();\n\n let stripped_components_iter: Vec> = original_path_in_archive\n .components()\n .skip(strip_components)\n .collect();\n\n if stripped_components_iter.is_empty() {\n debug!(\n \"Skipping entry due to strip_components: {:?}\",\n original_path_in_archive\n );\n continue;\n }\n\n let mut final_target_path_on_disk = target_dir.to_path_buf();\n for comp in stripped_components_iter {\n match comp {\n Component::Normal(p) => final_target_path_on_disk.push(p),\n Component::CurDir => {}\n Component::ParentDir => {\n let msg = format!(\n \"Unsafe '..' in TAR path {} after stripping in {}\",\n original_path_in_archive.display(),\n archive_path_for_log.display()\n );\n error!(\"{}\", msg);\n errors.push(msg);\n continue;\n }\n Component::Prefix(_) | Component::RootDir => {\n let msg = format!(\n \"Disallowed component {:?} in TAR path {}\",\n comp,\n original_path_in_archive.display()\n );\n error!(\"{}\", msg);\n errors.push(msg);\n continue;\n }\n }\n }\n\n if !final_target_path_on_disk.starts_with(target_dir) {\n let msg = format!(\n \"Path traversal {} -> {} detected in {}\",\n original_path_in_archive.display(),\n final_target_path_on_disk.display(),\n archive_path_for_log.display()\n );\n error!(\"{}\", msg);\n errors.push(msg);\n continue;\n }\n\n if let Some(parent) = final_target_path_on_disk.parent() {\n if !parent.exists() {\n fs::create_dir_all(parent).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(io::Error::new(\n e.kind(),\n format!(\"Failed create parent dir {}: {}\", parent.display(), e),\n )))\n })?;\n }\n }\n\n #[cfg(unix)]\n if entry.header().entry_type() == EntryType::Link {\n if let Ok(Some(link_name_in_archive)) = entry.link_name() {\n let deferred_link = DeferredHardLink {\n link_path_in_archive: original_path_in_archive.clone(),\n target_name_in_archive: link_name_in_archive.into_owned(),\n };\n debug!(\n \"Deferring hardlink: archive path '{}' -> archive target '{}'\",\n original_path_in_archive.display(),\n deferred_link.target_name_in_archive.display()\n );\n deferred_hardlinks.push(deferred_link);\n continue;\n } else {\n let msg = format!(\n \"Hardlink entry '{}' in {} has no link target name.\",\n original_path_in_archive.display(),\n archive_path_for_log.display()\n );\n warn!(\"{}\", msg);\n errors.push(msg);\n continue;\n }\n }\n\n match entry.unpack(&final_target_path_on_disk) {\n Ok(_) => debug!(\n \"Unpacked TAR entry to: {}\",\n final_target_path_on_disk.display()\n ),\n Err(e) => {\n if e.kind() != io::ErrorKind::AlreadyExists {\n let msg = format!(\n \"Failed to unpack entry {:?} to {}: {}. Entry type: {:?}\",\n original_path_in_archive,\n final_target_path_on_disk.display(),\n e,\n entry.header().entry_type()\n );\n error!(\"{}\", msg);\n errors.push(msg);\n } else {\n debug!(\"Entry already exists at {}, skipping unpack (tar crate overwrite=true handles this).\", final_target_path_on_disk.display());\n }\n }\n }\n }\n\n #[cfg(unix)]\n for deferred in deferred_hardlinks {\n let mut disk_link_path = target_dir.to_path_buf();\n for comp in deferred\n .link_path_in_archive\n .components()\n .skip(strip_components)\n {\n if let Component::Normal(p) = comp {\n disk_link_path.push(p);\n }\n // Other components should have been caught by safety checks above\n }\n\n let mut disk_target_path = target_dir.to_path_buf();\n // The link_name_in_archive is relative to the archive root *before* stripping.\n // We need to apply stripping to it as well to find its final disk location.\n for comp in deferred\n .target_name_in_archive\n .components()\n .skip(strip_components)\n {\n if let Component::Normal(p) = comp {\n disk_target_path.push(p);\n }\n }\n\n if !disk_target_path.starts_with(target_dir) || !disk_link_path.starts_with(target_dir) {\n let msg = format!(\"Skipping deferred hardlink due to path traversal attempt: link '{}' -> target '{}'\", disk_link_path.display(), disk_target_path.display());\n error!(\"{}\", msg);\n errors.push(msg);\n continue;\n }\n\n debug!(\n \"Attempting deferred hardlink: disk link path '{}' -> disk target path '{}'\",\n disk_link_path.display(),\n disk_target_path.display()\n );\n\n if disk_target_path.exists() {\n if let Some(parent) = disk_link_path.parent() {\n if !parent.exists() {\n if let Err(e) = fs::create_dir_all(parent) {\n let msg = format!(\n \"Failed to create parent directory for deferred hardlink {}: {}\",\n disk_link_path.display(),\n e\n );\n error!(\"{}\", msg);\n errors.push(msg);\n continue;\n }\n }\n }\n\n if disk_link_path.symlink_metadata().is_ok() {\n // Check if something (file or symlink) exists at the link creation spot\n if let Err(e) = fs::remove_file(&disk_link_path) {\n // Attempt to remove it\n warn!(\"Could not remove existing file/symlink at hardlink destination {}: {}. Hardlink creation may fail.\", disk_link_path.display(), e);\n }\n }\n\n if let Err(e) = fs::hard_link(&disk_target_path, &disk_link_path) {\n let msg = format!(\n \"Failed to create deferred hardlink '{}' -> '{}': {}. Target exists: {}\",\n disk_link_path.display(),\n disk_target_path.display(),\n e,\n disk_target_path.exists()\n );\n error!(\"{}\", msg);\n errors.push(msg);\n } else {\n debug!(\n \"Successfully created deferred hardlink: '{}' -> '{}'\",\n disk_link_path.display(),\n disk_target_path.display()\n );\n }\n } else {\n let msg = format!(\n \"Target '{}' for deferred hardlink '{}' does not exist. Hardlink not created.\",\n disk_target_path.display(),\n disk_link_path.display()\n );\n error!(\"{}\", msg);\n errors.push(msg);\n }\n }\n\n if !errors.is_empty() {\n return Err(SpsError::InstallError(format!(\n \"Failed during TAR extraction for {} with {} error(s): {}\",\n archive_path_for_log.display(),\n errors.len(),\n errors.join(\"; \")\n )));\n }\n\n debug!(\n \"Finished TAR extraction for {}\",\n archive_path_for_log.display()\n );\n #[cfg(target_os = \"macos\")]\n {\n if let Err(e) = quarantine_extracted_apps_in_stage(target_dir, \"sps-tar-extractor\") {\n tracing::warn!(\n \"Error during post-tar extraction quarantine scan for {}: {}\",\n archive_path_for_log.display(),\n e\n );\n }\n }\n Ok(())\n}\n\nfn extract_zip_archive(\n reader: R,\n target_dir: &Path,\n strip_components: usize,\n archive_path_for_log: &Path,\n) -> Result<()> {\n let mut archive = ZipArchive::new(reader).map_err(|e| {\n SpsError::Generic(format!(\n \"Failed to open ZIP {}: {}\",\n archive_path_for_log.display(),\n e\n ))\n })?;\n\n debug!(\n \"Starting ZIP extraction for {}\",\n archive_path_for_log.display()\n );\n\n for i in 0..archive.len() {\n let mut file = archive\n .by_index(i)\n .map_err(|e| SpsError::Generic(format!(\"Failed to read ZIP entry {i}: {e}\")))?;\n\n let Some(original_path_in_archive) = file.enclosed_name() else {\n debug!(\"Skipping unsafe ZIP entry (no enclosed name)\");\n continue;\n };\n\n let stripped_components_iter: Vec> = original_path_in_archive\n .components()\n .skip(strip_components)\n .collect();\n\n if stripped_components_iter.is_empty() {\n debug!(\n \"Skipping ZIP entry {} due to strip_components\",\n original_path_in_archive.display()\n );\n continue;\n }\n\n let mut final_target_path_on_disk = target_dir.to_path_buf();\n for comp in stripped_components_iter {\n match comp {\n Component::Normal(p) => final_target_path_on_disk.push(p),\n Component::CurDir => {}\n Component::ParentDir => {\n error!(\n \"Unsafe '..' in ZIP path {} after strip_components\",\n original_path_in_archive.display()\n );\n return Err(SpsError::Generic(format!(\n \"Unsafe '..' component in ZIP path {}\",\n original_path_in_archive.display()\n )));\n }\n Component::Prefix(_) | Component::RootDir => {\n error!(\n \"Disallowed component {:?} in ZIP path {}\",\n comp,\n original_path_in_archive.display()\n );\n return Err(SpsError::Generic(format!(\n \"Disallowed component in ZIP path {}\",\n original_path_in_archive.display()\n )));\n }\n }\n }\n\n if !final_target_path_on_disk.starts_with(target_dir) {\n error!(\n \"ZIP path traversal detected: {} -> {}\",\n original_path_in_archive.display(),\n final_target_path_on_disk.display()\n );\n return Err(SpsError::Generic(format!(\n \"ZIP path traversal detected in {}\",\n archive_path_for_log.display()\n )));\n }\n\n if let Some(parent) = final_target_path_on_disk.parent() {\n if !parent.exists() {\n fs::create_dir_all(parent).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(io::Error::new(\n e.kind(),\n format!(\n \"Failed to create parent directory {}: {}\",\n parent.display(),\n e\n ),\n )))\n })?;\n }\n }\n\n if file.is_dir() {\n debug!(\n \"Creating directory: {}\",\n final_target_path_on_disk.display()\n );\n fs::create_dir_all(&final_target_path_on_disk).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(io::Error::new(\n e.kind(),\n format!(\n \"Failed to create directory {}: {}\",\n final_target_path_on_disk.display(),\n e\n ),\n )))\n })?;\n } else {\n // Regular file\n if final_target_path_on_disk.exists() {\n match fs::remove_file(&final_target_path_on_disk) {\n Ok(_) => {}\n Err(e) if e.kind() == io::ErrorKind::NotFound => {}\n Err(e) => return Err(SpsError::Io(std::sync::Arc::new(e))),\n }\n }\n\n debug!(\"Extracting file: {}\", final_target_path_on_disk.display());\n let mut outfile = File::create(&final_target_path_on_disk).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(io::Error::new(\n e.kind(),\n format!(\n \"Failed to create file {}: {}\",\n final_target_path_on_disk.display(),\n e\n ),\n )))\n })?;\n\n std::io::copy(&mut file, &mut outfile).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(io::Error::new(\n e.kind(),\n format!(\n \"Failed to write file {}: {}\",\n final_target_path_on_disk.display(),\n e\n ),\n )))\n })?;\n\n // Set permissions on Unix systems\n #[cfg(unix)]\n {\n use std::os::unix::fs::PermissionsExt;\n if let Some(mode) = file.unix_mode() {\n let perms = std::fs::Permissions::from_mode(mode);\n std::fs::set_permissions(&final_target_path_on_disk, perms)\n .map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n }\n }\n }\n }\n\n debug!(\n \"Finished ZIP extraction for {}\",\n archive_path_for_log.display()\n );\n\n // Apply quarantine to extracted apps on macOS\n #[cfg(target_os = \"macos\")]\n {\n if let Err(e) = quarantine_extracted_apps_in_stage(target_dir, \"sps-zip-extractor\") {\n tracing::warn!(\n \"Error during post-zip extraction quarantine scan for {}: {}\",\n archive_path_for_log.display(),\n e\n );\n }\n }\n\n Ok(())\n}\n"], ["/sps/sps-core/src/utils/applescript.rs", "use std::path::Path;\nuse std::process::Command;\nuse std::thread;\nuse std::time::Duration;\n\nuse plist::Value as PlistValue;\nuse sps_common::error::Result;\nuse tracing::{debug, warn};\n\nfn get_bundle_identifier_from_app_path(app_path: &Path) -> Option {\n let info_plist_path = app_path.join(\"Contents/Info.plist\");\n if !info_plist_path.is_file() {\n debug!(\"Info.plist not found at {}\", info_plist_path.display());\n return None;\n }\n match PlistValue::from_file(&info_plist_path) {\n Ok(PlistValue::Dictionary(dict)) => dict\n .get(\"CFBundleIdentifier\")\n .and_then(PlistValue::as_string)\n .map(String::from),\n Ok(val) => {\n warn!(\n \"Info.plist at {} is not a dictionary. Value: {:?}\",\n info_plist_path.display(),\n val\n );\n None\n }\n Err(e) => {\n warn!(\n \"Failed to parse Info.plist at {}: {}\",\n info_plist_path.display(),\n e\n );\n None\n }\n }\n}\n\nfn is_app_running_by_bundle_id(bundle_id: &str) -> Result {\n let script = format!(\n \"tell application \\\"System Events\\\" to (exists (process 1 where bundle identifier is \\\"{bundle_id}\\\"))\"\n );\n debug!(\n \"Checking if app with bundle ID '{}' is running using script: {}\",\n bundle_id, script\n );\n\n let output = Command::new(\"osascript\").arg(\"-e\").arg(&script).output()?;\n\n if output.status.success() {\n let stdout = String::from_utf8_lossy(&output.stdout)\n .trim()\n .to_lowercase();\n debug!(\n \"is_app_running_by_bundle_id ('{}') stdout: '{}'\",\n bundle_id, stdout\n );\n Ok(stdout == \"true\")\n } else {\n let stderr = String::from_utf8_lossy(&output.stderr);\n warn!(\n \"osascript check running status for bundle ID '{}' failed. Status: {}, Stderr: {}\",\n bundle_id,\n output.status,\n stderr.trim()\n );\n Ok(false)\n }\n}\n\n/// Attempts to gracefully quit an application using its bundle identifier (preferred) or name via\n/// AppleScript. Retries several times, checking if the app is still running between attempts.\n/// Returns Ok even if the app could not be quit, as uninstall should proceed.\npub fn quit_app_gracefully(app_path: &Path) -> Result<()> {\n if !cfg!(target_os = \"macos\") {\n debug!(\"Not on macOS, skipping app quit for {}\", app_path.display());\n return Ok(());\n }\n if !app_path.exists() {\n debug!(\n \"App path {} does not exist, skipping quit attempt.\",\n app_path.display()\n );\n return Ok(());\n }\n\n let app_name_for_log = app_path\n .file_name()\n .map_or_else(|| app_path.to_string_lossy(), |name| name.to_string_lossy())\n .trim_end_matches(\".app\")\n .to_string();\n\n let bundle_identifier = get_bundle_identifier_from_app_path(app_path);\n\n let (script_target, using_bundle_id) = match &bundle_identifier {\n Some(id) => (id.clone(), true),\n None => {\n warn!(\n \"Could not get bundle identifier for {}. Will attempt to quit by name '{}'. This is less reliable.\",\n app_path.display(),\n app_name_for_log\n );\n (app_name_for_log.clone(), false)\n }\n };\n\n debug!(\n \"Attempting to quit app '{}' (script target: '{}', using bundle_id: {})\",\n app_name_for_log, script_target, using_bundle_id\n );\n\n // Initial check if app is running (only reliable if we have bundle ID)\n if using_bundle_id {\n match is_app_running_by_bundle_id(&script_target) {\n Ok(true) => debug!(\n \"App '{}' is running. Proceeding with quit attempts.\",\n script_target\n ),\n Ok(false) => {\n debug!(\"App '{}' is not running. Quit unnecessary.\", script_target);\n return Ok(());\n }\n Err(e) => {\n warn!(\n \"Could not determine if app '{}' is running (check failed: {}). Proceeding with quit attempt.\",\n script_target, e\n );\n }\n }\n }\n\n let quit_command = if using_bundle_id {\n format!(\"tell application id \\\"{script_target}\\\" to quit\")\n } else {\n format!(\"tell application \\\"{script_target}\\\" to quit\")\n };\n\n const MAX_QUIT_ATTEMPTS: usize = 4;\n const QUIT_DELAYS_SECS: [u64; MAX_QUIT_ATTEMPTS - 1] = [2, 3, 5];\n\n // Use enumerate over QUIT_DELAYS_SECS for Clippy compliance\n for (attempt, delay) in QUIT_DELAYS_SECS.iter().enumerate() {\n debug!(\n \"Quit attempt #{} for '{}' using command: {}\",\n attempt + 1,\n script_target,\n quit_command\n );\n\n let output = Command::new(\"osascript\")\n .arg(\"-e\")\n .arg(&quit_command)\n .output()?; // Propagate IO errors from osascript execution\n\n if output.status.success() {\n debug!(\n \"osascript quit command sent successfully for '{}' (attempt #{}).\",\n script_target,\n attempt + 1\n );\n } else {\n let stderr = String::from_utf8_lossy(&output.stderr);\n if stderr.contains(\"-1712\")\n || stderr.contains(\"-1728\")\n || stderr.contains(\"-600\")\n || stderr.to_lowercase().contains(\"application isn’t running\")\n || stderr.to_lowercase().contains(\"application not running\")\n {\n debug!(\n \"osascript: App '{}' reported as not running or not found (stderr: {}). Quit successful or unnecessary.\",\n script_target,\n stderr.trim()\n );\n return Ok(());\n } else {\n warn!(\n \"osascript quit command for '{}' failed (attempt #{}). Status: {}. Stderr: {}\",\n script_target,\n attempt + 1,\n output.status,\n stderr.trim()\n );\n }\n }\n\n // Wait briefly to allow the app to process the quit command\n thread::sleep(Duration::from_secs(*delay));\n\n // Check if the app is still running (if using bundle ID)\n if using_bundle_id {\n match is_app_running_by_bundle_id(&script_target) {\n Ok(true) => {\n debug!(\n \"App '{}' still running after attempt #{}. Retrying.\",\n script_target,\n attempt + 1\n );\n }\n Ok(false) => {\n debug!(\n \"App '{}' successfully quit after attempt #{}.\",\n script_target,\n attempt + 1\n );\n return Ok(());\n }\n Err(e) => {\n warn!(\n \"Could not verify if app '{}' quit after attempt #{}: {}. Assuming it might still be running.\",\n script_target,\n attempt + 1,\n e\n );\n }\n }\n }\n }\n\n // Final attempt (the fourth, not covered by QUIT_DELAYS_SECS)\n let attempt = QUIT_DELAYS_SECS.len();\n debug!(\n \"Quit attempt #{} for '{}' using command: {}\",\n attempt + 1,\n script_target,\n quit_command\n );\n\n let output = Command::new(\"osascript\")\n .arg(\"-e\")\n .arg(&quit_command)\n .output()?; // Propagate IO errors from osascript execution\n\n if output.status.success() {\n debug!(\n \"osascript quit command sent successfully for '{}' (attempt #{}).\",\n script_target,\n attempt + 1\n );\n } else {\n let stderr = String::from_utf8_lossy(&output.stderr);\n if stderr.contains(\"-1712\")\n || stderr.contains(\"-1728\")\n || stderr.contains(\"-600\")\n || stderr.to_lowercase().contains(\"application isn’t running\")\n || stderr.to_lowercase().contains(\"application not running\")\n {\n debug!(\n \"osascript: App '{}' reported as not running or not found (stderr: {}). Quit successful or unnecessary.\",\n script_target,\n stderr.trim()\n );\n return Ok(());\n } else {\n warn!(\n \"osascript quit command for '{}' failed (attempt #{}). Status: {}. Stderr: {}\",\n script_target,\n attempt + 1,\n output.status,\n stderr.trim()\n );\n }\n }\n\n // Final check if the app is still running (if using bundle ID)\n if using_bundle_id {\n match is_app_running_by_bundle_id(&script_target) {\n Ok(true) => {\n warn!(\n \"App '{}' still running after {} quit attempts.\",\n script_target, MAX_QUIT_ATTEMPTS\n );\n }\n Ok(false) => {\n debug!(\n \"App '{}' successfully quit after attempt #{}.\",\n script_target,\n attempt + 1\n );\n return Ok(());\n }\n Err(e) => {\n warn!(\n \"Could not verify if app '{}' quit after attempt #{}: {}. Assuming it might still be running.\",\n script_target,\n attempt + 1,\n e\n );\n }\n }\n } else {\n warn!(\n \"App '{}' (targeted by name) might still be running after {} quit attempts. Manual check may be needed.\",\n script_target,\n MAX_QUIT_ATTEMPTS\n );\n }\n Ok(())\n}\n"], ["/sps/sps-common/src/model/tap.rs", "// tap/tap.rs - Basic tap functionality // Should probably be in model module\n\nuse std::path::PathBuf;\n\nuse tracing::debug;\n\nuse crate::error::{Result, SpsError};\n\n/// Represents a source of packages (formulas and casks)\npub struct Tap {\n /// The user part of the tap name (e.g., \"homebrew\" in \"homebrew/core\")\n pub user: String,\n\n /// The repository part of the tap name (e.g., \"core\" in \"homebrew/core\")\n pub repo: String,\n\n /// The full path to the tap directory\n pub path: PathBuf,\n}\n\nimpl Tap {\n /// Create a new tap from user/repo format\n pub fn new(name: &str) -> Result {\n let parts: Vec<&str> = name.split('/').collect();\n if parts.len() != 2 {\n return Err(SpsError::Generic(format!(\"Invalid tap name: {name}\")));\n }\n let user = parts[0].to_string();\n let repo = parts[1].to_string();\n let prefix = if cfg!(target_arch = \"aarch64\") {\n PathBuf::from(\"/opt/homebrew\")\n } else {\n PathBuf::from(\"/usr/local\")\n };\n let path = prefix\n .join(\"Library/Taps\")\n .join(&user)\n .join(format!(\"homebrew-{repo}\"));\n Ok(Self { user, repo, path })\n }\n\n /// Update this tap by pulling latest changes\n pub fn update(&self) -> Result<()> {\n use git2::{FetchOptions, Repository};\n\n let repo = Repository::open(&self.path)\n .map_err(|e| SpsError::Generic(format!(\"Failed to open tap repository: {e}\")))?;\n\n // Fetch updates from origin\n let mut remote = repo\n .find_remote(\"origin\")\n .map_err(|e| SpsError::Generic(format!(\"Failed to find remote 'origin': {e}\")))?;\n\n let mut fetch_options = FetchOptions::new();\n remote\n .fetch(\n &[\"refs/heads/*:refs/heads/*\"],\n Some(&mut fetch_options),\n None,\n )\n .map_err(|e| SpsError::Generic(format!(\"Failed to fetch updates: {e}\")))?;\n\n // Merge changes\n let fetch_head = repo\n .find_reference(\"FETCH_HEAD\")\n .map_err(|e| SpsError::Generic(format!(\"Failed to find FETCH_HEAD: {e}\")))?;\n\n let fetch_commit = repo\n .reference_to_annotated_commit(&fetch_head)\n .map_err(|e| SpsError::Generic(format!(\"Failed to get commit from FETCH_HEAD: {e}\")))?;\n\n let analysis = repo\n .merge_analysis(&[&fetch_commit])\n .map_err(|e| SpsError::Generic(format!(\"Failed to analyze merge: {e}\")))?;\n\n if analysis.0.is_up_to_date() {\n debug!(\"Already up-to-date\");\n return Ok(());\n }\n\n if analysis.0.is_fast_forward() {\n let mut reference = repo\n .find_reference(\"refs/heads/master\")\n .map_err(|e| SpsError::Generic(format!(\"Failed to find master branch: {e}\")))?;\n reference\n .set_target(fetch_commit.id(), \"Fast-forward\")\n .map_err(|e| SpsError::Generic(format!(\"Failed to fast-forward: {e}\")))?;\n repo.set_head(\"refs/heads/master\")\n .map_err(|e| SpsError::Generic(format!(\"Failed to set HEAD: {e}\")))?;\n repo.checkout_head(Some(git2::build::CheckoutBuilder::default().force()))\n .map_err(|e| SpsError::Generic(format!(\"Failed to checkout: {e}\")))?;\n } else {\n return Err(SpsError::Generic(\n \"Tap requires merge but automatic merging is not implemented\".to_string(),\n ));\n }\n\n Ok(())\n }\n\n /// Remove this tap by deleting its local repository\n pub fn remove(&self) -> Result<()> {\n if !self.path.exists() {\n return Err(SpsError::NotFound(format!(\n \"Tap {} is not installed\",\n self.full_name()\n )));\n }\n debug!(\"Removing tap {}\", self.full_name());\n std::fs::remove_dir_all(&self.path).map_err(|e| {\n SpsError::Generic(format!(\"Failed to remove tap {}: {}\", self.full_name(), e))\n })\n }\n\n /// Get the full name of the tap (user/repo)\n pub fn full_name(&self) -> String {\n format!(\"{}/{}\", self.user, self.repo)\n }\n\n /// Check if this tap is installed locally\n pub fn is_installed(&self) -> bool {\n self.path.exists()\n }\n}\n"], ["/sps/sps-core/src/utils/xattr.rs", "use std::path::Path;\nuse std::process::Command;\n\nuse anyhow::Context;\nuse sps_common::error::{Result, SpsError};\nuse tracing::{debug, error};\nuse uuid::Uuid;\nuse xattr;\n\n// Helper to get current timestamp as hex\nfn get_timestamp_hex() -> String {\n let secs = std::time::SystemTime::now()\n .duration_since(std::time::UNIX_EPOCH)\n .unwrap_or_default() // Defaults to 0 if time is before UNIX_EPOCH\n .as_secs();\n format!(\"{secs:x}\")\n}\n\n// Helper to generate a UUID as hex string\nfn get_uuid_hex() -> String {\n Uuid::new_v4().as_hyphenated().to_string().to_uppercase()\n}\n\n/// true → file **has** a com.apple.quarantine attribute \n/// false → attribute missing\npub fn has_quarantine_attribute(path: &Path) -> anyhow::Result {\n // The `xattr` crate has both path-level and FileExt APIs.\n // Path-level is simpler here.\n match xattr::get(path, \"com.apple.quarantine\") {\n Ok(Some(_)) => Ok(true),\n Ok(None) => Ok(false),\n Err(e) => Err(anyhow::Error::new(e))\n .with_context(|| format!(\"checking xattr on {}\", path.display())),\n }\n}\n\n/// Apply our standard quarantine only *if* none exists already.\n///\n/// `agent` should be the same string you currently pass to\n/// `set_quarantine_attribute()` – usually the cask token.\npub fn ensure_quarantine_attribute(path: &Path, agent: &str) -> anyhow::Result<()> {\n if has_quarantine_attribute(path)? {\n // Already quarantined (or the user cleared it and we respect that) → done\n return Ok(());\n }\n set_quarantine_attribute(path, agent)\n .with_context(|| format!(\"adding quarantine to {}\", path.display()))\n}\n\n/// Sets the 'com.apple.quarantine' extended attribute on a file or directory.\n/// Uses flags commonly seen for user-initiated downloads (0081).\n/// Logs errors assertively, as failure is critical for correct behavior.\npub fn set_quarantine_attribute(path: &Path, agent_name: &str) -> Result<()> {\n if !cfg!(target_os = \"macos\") {\n debug!(\n \"Not on macOS, skipping quarantine attribute for {}\",\n path.display()\n );\n return Ok(());\n }\n\n if !path.exists() {\n error!(\n \"Cannot set quarantine attribute, path does not exist: {}\",\n path.display()\n );\n return Err(SpsError::NotFound(format!(\n \"Path not found for setting quarantine attribute: {}\",\n path.display()\n )));\n }\n\n let timestamp_hex = get_timestamp_hex();\n let uuid_hex = get_uuid_hex();\n // Use \"0181\" to disable translocation and quarantine mirroring (Homebrew-style).\n // Format: \"flags;timestamp_hex;agent_name;uuid_hex\"\n let quarantine_value = format!(\"0181;{timestamp_hex};{agent_name};{uuid_hex}\");\n\n debug!(\n \"Setting quarantine attribute on {}: value='{}'\",\n path.display(),\n quarantine_value\n );\n\n let output = Command::new(\"xattr\")\n .arg(\"-w\")\n .arg(\"com.apple.quarantine\")\n .arg(&quarantine_value)\n .arg(path.as_os_str())\n .output();\n\n match output {\n Ok(out) => {\n if out.status.success() {\n debug!(\n \"Successfully set quarantine attribute for {}\",\n path.display()\n );\n Ok(())\n } else {\n let stderr = String::from_utf8_lossy(&out.stderr);\n error!( // Changed from warn to error as this is critical for the bug\n \"Failed to set quarantine attribute for {} (status: {}): {}. This may lead to data loss on reinstall or Gatekeeper issues.\",\n path.display(),\n out.status,\n stderr.trim()\n );\n // Return an error because failure to set this is likely to cause the reported bug\n Err(SpsError::Generic(format!(\n \"Failed to set com.apple.quarantine on {}: {}\",\n path.display(),\n stderr.trim()\n )))\n }\n }\n Err(e) => {\n error!(\n \"Failed to execute xattr command for {}: {}. Quarantine attribute not set.\",\n path.display(),\n e\n );\n Err(SpsError::Io(std::sync::Arc::new(e)))\n }\n }\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/preflight.rs", "use std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::InstalledArtifact;\n\n/// Execute any `preflight` commands listed in the Cask’s JSON artifact stanza.\n/// Returns an empty Vec since preflight does not produce install artifacts.\npub fn run_preflight(\n cask: &Cask,\n stage_path: &Path,\n _config: &Config,\n) -> Result> {\n // Iterate over artifacts, look for \"preflight\" keys\n if let Some(entries) = &cask.artifacts {\n for entry in entries.iter().filter_map(|v| v.as_object()) {\n if let Some(cmds) = entry.get(\"preflight\").and_then(|v| v.as_array()) {\n for cmd_val in cmds.iter().filter_map(|v| v.as_str()) {\n // Substitute $STAGEDIR placeholder\n let cmd_str = cmd_val.replace(\"$STAGEDIR\", stage_path.to_str().unwrap());\n debug!(\"Running preflight: {}\", cmd_str);\n let status = Command::new(\"sh\").arg(\"-c\").arg(&cmd_str).status()?;\n if !status.success() {\n return Err(SpsError::InstallError(format!(\n \"preflight failed: {cmd_str}\"\n )));\n }\n }\n }\n }\n }\n\n // No install artifacts to return\n Ok(Vec::new())\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/font.rs", "// ===== sps-core/src/build/cask/artifacts/font.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Implements the `font` stanza by moving each declared\n/// font file or directory from the staging area into\n/// `~/Library/Fonts`, then symlinking it in the Caskroom.\n///\n/// Mirrors Homebrew’s `Dictionary < Moved` and `Colorpicker < Moved` pattern.\npub fn install_font(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n // Look for \"font\" entries in the JSON artifacts\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"font\").and_then(|v| v.as_array()) {\n // Target directory for user fonts\n let dest_dir = config.home_dir().join(\"Library\").join(\"Fonts\");\n fs::create_dir_all(&dest_dir)?;\n\n for entry in entries {\n if let Some(name) = entry.as_str() {\n let src = stage_path.join(name);\n if !src.exists() {\n debug!(\"Font '{}' not found in staging; skipping\", name);\n continue;\n }\n\n let dest = dest_dir.join(name);\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\"Installing font '{}' → '{}'\", src.display(), dest.display());\n // Try move, fallback to copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record moved font\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink into Caskroom for reference\n let link = cask_version_install_path.join(name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // single font stanza per cask\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/dmg.rs", "// In sps-core/src/build/cask/dmg.rs\n\nuse std::fs;\nuse std::io::{BufRead, BufReader};\nuse std::path::{Path, PathBuf};\nuse std::process::Command;\n\nuse sps_common::error::{Result, SpsError};\nuse tracing::{debug, error}; // Added log imports\n\n// --- Keep Existing Helpers ---\npub fn mount_dmg(dmg_path: &Path) -> Result {\n debug!(\"Mounting DMG: {}\", dmg_path.display());\n let output = Command::new(\"hdiutil\")\n .arg(\"attach\")\n .arg(\"-plist\")\n .arg(\"-nobrowse\")\n .arg(\"-readonly\")\n .arg(\"-mountrandom\")\n .arg(\"/tmp\") // Consider making mount location configurable or more robust\n .arg(dmg_path)\n .output()?;\n\n if !output.status.success() {\n let stderr = String::from_utf8_lossy(&output.stderr);\n error!(\n \"hdiutil attach failed for {}: {}\",\n dmg_path.display(),\n stderr\n );\n return Err(SpsError::Generic(format!(\n \"Failed to mount DMG '{}': {}\",\n dmg_path.display(),\n stderr\n )));\n }\n\n let mount_point = parse_mount_point(&output.stdout)?;\n debug!(\"DMG mounted at: {}\", mount_point.display());\n Ok(mount_point)\n}\n\npub fn unmount_dmg(mount_point: &Path) -> Result<()> {\n debug!(\"Unmounting DMG from: {}\", mount_point.display());\n // Add logging for commands\n debug!(\"Executing: hdiutil detach -force {}\", mount_point.display());\n let output = Command::new(\"hdiutil\")\n .arg(\"detach\")\n .arg(\"-force\")\n .arg(mount_point)\n .output()?;\n\n if !output.status.success() {\n let stderr = String::from_utf8_lossy(&output.stderr);\n debug!(\n \"hdiutil detach failed ({}): {}. Trying diskutil\",\n output.status, stderr\n );\n // Add logging for fallback\n debug!(\n \"Executing: diskutil unmount force {}\",\n mount_point.display()\n );\n let diskutil_output = Command::new(\"diskutil\")\n .arg(\"unmount\")\n .arg(\"force\")\n .arg(mount_point)\n .output()?;\n\n if !diskutil_output.status.success() {\n let diskutil_stderr = String::from_utf8_lossy(&diskutil_output.stderr);\n error!(\n \"diskutil unmount force failed ({}): {}\",\n diskutil_output.status, diskutil_stderr\n );\n // Consider returning error only if both fail? Or always error on diskutil fail?\n return Err(SpsError::Generic(format!(\n \"Failed to unmount DMG '{}' using hdiutil and diskutil: {}\",\n mount_point.display(),\n diskutil_stderr\n )));\n }\n }\n debug!(\"DMG successfully unmounted\");\n Ok(())\n}\n\nfn parse_mount_point(output: &[u8]) -> Result {\n // ... (existing implementation) ...\n // Use plist crate for more robust parsing if possible in the future\n let cursor = std::io::Cursor::new(output);\n let reader = BufReader::new(cursor);\n let mut in_sys_entities = false;\n let mut in_mount_point = false;\n let mut mount_path_str: Option = None;\n\n for line_res in reader.lines() {\n let line = line_res?;\n let trimmed = line.trim();\n\n if trimmed == \"system-entities\" {\n in_sys_entities = true;\n continue;\n }\n if !in_sys_entities {\n continue;\n }\n\n if trimmed == \"mount-point\" {\n in_mount_point = true;\n continue;\n }\n\n if in_mount_point && trimmed.starts_with(\"\") && trimmed.ends_with(\"\") {\n mount_path_str = Some(\n trimmed\n .trim_start_matches(\"\")\n .trim_end_matches(\"\")\n .to_string(),\n );\n break; // Found the first mount point, assume it's the main one\n }\n\n // Reset flags if we encounter closing tags for structures containing mount-point\n if trimmed == \"\" {\n in_mount_point = false;\n }\n if trimmed == \"\" && in_sys_entities {\n // End of system-entities\n // break; // Stop searching if we leave the system-entities array\n in_sys_entities = false; // Reset this flag too\n }\n }\n\n match mount_path_str {\n Some(path_str) if !path_str.is_empty() => {\n debug!(\"Parsed mount point from plist: {}\", path_str);\n Ok(PathBuf::from(path_str))\n }\n _ => {\n error!(\"Failed to parse mount point from hdiutil plist output.\");\n // Optionally log the raw output for debugging\n // error!(\"Raw hdiutil output:\\n{}\", String::from_utf8_lossy(output));\n Err(SpsError::Generic(\n \"Failed to determine mount point from hdiutil output\".to_string(),\n ))\n }\n }\n}\n\n// --- NEW Function ---\n/// Extracts the contents of a mounted DMG to a staging directory using `ditto`.\npub fn extract_dmg_to_stage(dmg_path: &Path, stage_dir: &Path) -> Result<()> {\n let mount_point = mount_dmg(dmg_path)?;\n\n // Ensure the stage directory exists (though TempDir should handle it)\n if !stage_dir.exists() {\n fs::create_dir_all(stage_dir).map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n }\n\n debug!(\n \"Copying contents from DMG mount {} to stage {} using ditto\",\n mount_point.display(),\n stage_dir.display()\n );\n // Use ditto for robust copying, preserving metadata\n // ditto \n debug!(\n \"Executing: ditto {} {}\",\n mount_point.display(),\n stage_dir.display()\n );\n let ditto_output = Command::new(\"ditto\")\n .arg(&mount_point) // Source first\n .arg(stage_dir) // Then destination\n .output()?;\n\n let unmount_result = unmount_dmg(&mount_point); // Unmount regardless of ditto success\n\n if !ditto_output.status.success() {\n let stderr = String::from_utf8_lossy(&ditto_output.stderr);\n error!(\"ditto command failed ({}): {}\", ditto_output.status, stderr);\n // Also log stdout which might contain info on specific file errors\n let stdout = String::from_utf8_lossy(&ditto_output.stdout);\n if !stdout.trim().is_empty() {\n error!(\"ditto stdout: {}\", stdout);\n }\n unmount_result?; // Ensure we still return unmount error if it happened\n return Err(SpsError::Generic(format!(\n \"Failed to copy DMG contents using ditto: {stderr}\"\n )));\n }\n\n // After ditto, quarantine any .app bundles in the stage (macOS only)\n #[cfg(target_os = \"macos\")]\n {\n if let Err(e) = crate::install::extract::quarantine_extracted_apps_in_stage(\n stage_dir,\n \"sps-dmg-extractor\",\n ) {\n tracing::warn!(\n \"Error during post-DMG extraction quarantine scan for {}: {}\",\n dmg_path.display(),\n e\n );\n }\n }\n\n unmount_result // Return the result of unmounting\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/manpage.rs", "// ===== src/build/cask/artifacts/manpage.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::sync::LazyLock;\n\nuse regex::Regex;\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n// --- Moved Regex Creation Outside ---\nstatic MANPAGE_RE: LazyLock =\n LazyLock::new(|| Regex::new(r\"\\.([1-8nl])(?:\\.gz)?$\").unwrap());\n\n/// Install any `manpage` stanzas from the Cask definition.\n/// Mirrors Homebrew’s `Cask::Artifact::Manpage < Symlinked` behavior\n/// :contentReference[oaicite:3]{index=3}.\npub fn install_manpage(\n cask: &Cask,\n stage_path: &Path,\n _cask_version_install_path: &Path, // Not needed for symlinking manpages\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n // Look up the \"manpage\" array in the raw artifacts JSON :contentReference[oaicite:4]{index=4}\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"manpage\").and_then(|v| v.as_array()) {\n for entry in entries {\n if let Some(man_file) = entry.as_str() {\n let src = stage_path.join(man_file);\n if !src.exists() {\n debug!(\n \"Manpage '{}' not found in staging area, skipping\",\n man_file\n );\n continue;\n }\n\n // Use the static regex\n let section = if let Some(caps) = MANPAGE_RE.captures(man_file) {\n caps.get(1).unwrap().as_str()\n } else {\n debug!(\n \"Filename '{}' does not look like a manpage, skipping\",\n man_file\n );\n continue;\n };\n\n // Build the target directory: e.g. /opt/sps/share/man/man1\n let man_dir = config.man_base_dir().join(format!(\"man{section}\"));\n fs::create_dir_all(&man_dir)?;\n\n // Determine the target path\n let file_name = Path::new(man_file).file_name().ok_or_else(|| {\n sps_common::error::SpsError::Generic(format!(\n \"Invalid manpage filename: {man_file}\"\n ))\n })?; // Handle potential None\n let dest = man_dir.join(file_name);\n\n // Remove any existing file or symlink\n // :contentReference[oaicite:7]{index=7}\n if dest.exists() || dest.symlink_metadata().is_ok() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\"Linking manpage '{}' → '{}'\", src.display(), dest.display());\n // Create the symlink\n symlink(&src, &dest)?;\n\n // Record it in our manifest\n installed.push(InstalledArtifact::ManpageLink {\n link_path: dest.clone(),\n target_path: src.clone(),\n });\n }\n }\n // Assume only one \"manpage\" stanza per Cask based on Homebrew structure\n break;\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/input_method.rs", "// ===== sps-core/src/build/cask/artifacts/input_method.rs =====\n\nuse std::fs;\nuse std::os::unix::fs as unix_fs;\nuse std::path::Path;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\n\nuse crate::install::cask::helpers::remove_path_robustly;\nuse crate::install::cask::write_cask_manifest;\n\n/// Install `input_method` artifacts from the staged directory into\n/// `~/Library/Input Methods` and record installed artifacts.\npub fn install_input_method(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n // Ensure we have an array of input_method names\n if let Some(artifacts_def) = &cask.artifacts {\n for artifact_value in artifacts_def {\n if let Some(obj) = artifact_value.as_object() {\n if let Some(names) = obj.get(\"input_method\").and_then(|v| v.as_array()) {\n for name_val in names {\n if let Some(name) = name_val.as_str() {\n let source = stage_path.join(name);\n if source.exists() {\n // Target directory: ~/Library/Input Methods\n let target_dir =\n config.home_dir().join(\"Library\").join(\"Input Methods\");\n if !target_dir.exists() {\n fs::create_dir_all(&target_dir)?;\n }\n let target = target_dir.join(name);\n\n // Remove existing input method if present\n if target.exists() {\n let _ = remove_path_robustly(&target, config, true);\n }\n\n // Move (or rename) the staged bundle\n fs::rename(&source, &target)\n .or_else(|_| unix_fs::symlink(&source, &target))?;\n\n // Record the main artifact\n installed.push(InstalledArtifact::MovedResource {\n path: target.clone(),\n });\n\n // Create a caskroom symlink for uninstallation\n let link_path = cask_version_install_path.join(name);\n if link_path.exists() {\n let _ = remove_path_robustly(&link_path, config, true);\n }\n #[cfg(unix)]\n std::os::unix::fs::symlink(&target, &link_path)?;\n\n installed.push(InstalledArtifact::CaskroomLink {\n link_path,\n target_path: target,\n });\n }\n }\n }\n }\n }\n }\n }\n\n // Write manifest for these artifacts\n write_cask_manifest(cask, cask_version_install_path, installed.clone())?;\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/internet_plugin.rs", "// ===== sps-core/src/build/cask/artifacts/internet_plugin.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Implements the `internet_plugin` stanza by moving each declared\n/// internet plugin bundle from the staging area into\n/// `~/Library/Internet Plug-Ins`, then symlinking it in the Caskroom.\n///\n/// Mirrors Homebrew’s `InternetPlugin < Moved` pattern.\npub fn install_internet_plugin(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n // Look for \"internet_plugin\" entries in the JSON artifacts\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"internet_plugin\").and_then(|v| v.as_array()) {\n // Target directory for user internet plugins\n let dest_dir = config.home_dir().join(\"Library\").join(\"Internet Plug-Ins\");\n fs::create_dir_all(&dest_dir)?;\n\n for entry in entries {\n if let Some(name) = entry.as_str() {\n let src = stage_path.join(name);\n if !src.exists() {\n debug!(\"Internet plugin '{}' not found in staging; skipping\", name);\n continue;\n }\n\n let dest = dest_dir.join(name);\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Installing internet plugin '{}' → '{}'\",\n src.display(),\n dest.display()\n );\n // Try move, fallback to copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record moved plugin\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink into Caskroom for reference\n let link = cask_version_install_path.join(name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // single stanza\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/colorpicker.rs", "// ===== sps-core/src/build/cask/artifacts/colorpicker.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Installs any `colorpicker` stanzas from the Cask definition.\n///\n/// Homebrew’s `Colorpicker` artifact simply subclasses `Moved` with\n/// `dirmethod :colorpickerdir` → `~/Library/ColorPickers` :contentReference[oaicite:3]{index=3}.\npub fn install_colorpicker(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"colorpicker\").and_then(|v| v.as_array()) {\n // For each declared bundle name:\n for entry in entries {\n if let Some(bundle_name) = entry.as_str() {\n let src = stage_path.join(bundle_name);\n if !src.exists() {\n debug!(\n \"Colorpicker bundle '{}' not found in stage; skipping\",\n bundle_name\n );\n continue;\n }\n\n // Ensure ~/Library/ColorPickers exists\n // :contentReference[oaicite:4]{index=4}\n let dest_dir = config\n .home_dir() // e.g. /Users/alxknt\n .join(\"Library\")\n .join(\"ColorPickers\");\n fs::create_dir_all(&dest_dir)?;\n\n let dest = dest_dir.join(bundle_name);\n // Remove any previous copy\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Moving colorpicker '{}' → '{}'\",\n src.display(),\n dest.display()\n );\n // mv, fallback to cp -R if necessary (cross‑device)\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record as a moved artifact (bundle installed)\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink back into Caskroom for reference\n // :contentReference[oaicite:5]{index=5}\n let link = cask_version_install_path.join(bundle_name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // only one `colorpicker` stanza per cask\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/uninstall.rs", "use std::path::PathBuf;\n\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\n\n/// At install time, scan the `uninstall` stanza and turn each directive\n/// into an InstalledArtifact variant, so it can later be torn down.\npub fn record_uninstall(cask: &Cask) -> Result> {\n let mut artifacts = Vec::new();\n\n if let Some(entries) = &cask.artifacts {\n for entry in entries.iter().filter_map(|v| v.as_object()) {\n if let Some(steps) = entry.get(\"uninstall\").and_then(|v| v.as_array()) {\n for step in steps.iter().filter_map(|v| v.as_object()) {\n for (key, val) in step {\n match key.as_str() {\n \"pkgutil\" => {\n if let Some(id) = val.as_str() {\n artifacts.push(InstalledArtifact::PkgUtilReceipt {\n id: id.to_string(),\n });\n }\n }\n \"delete\" => {\n if let Some(arr) = val.as_array() {\n for p in arr.iter().filter_map(|v| v.as_str()) {\n artifacts.push(InstalledArtifact::MovedResource {\n path: PathBuf::from(p),\n });\n }\n }\n }\n \"rmdir\" => {\n if let Some(arr) = val.as_array() {\n for p in arr.iter().filter_map(|v| v.as_str()) {\n artifacts.push(InstalledArtifact::MovedResource {\n path: PathBuf::from(p),\n });\n }\n }\n }\n \"launchctl\" => {\n if let Some(arr) = val.as_array() {\n for lbl in arr.iter().filter_map(|v| v.as_str()) {\n artifacts.push(InstalledArtifact::Launchd {\n label: lbl.to_string(),\n path: None,\n });\n }\n }\n }\n // Add other uninstall keys similarly...\n _ => {}\n }\n }\n }\n }\n }\n }\n\n Ok(artifacts)\n}\n"], ["/sps/sps-core/src/uninstall/common.rs", "// sps-core/src/uninstall/common.rs\n\nuse std::path::{Component, Path, PathBuf};\nuse std::process::Command;\nuse std::{fs, io};\n\nuse sps_common::config::Config;\nuse tracing::{debug, error, warn};\n\n#[derive(Debug, Clone, Default)]\npub struct UninstallOptions {\n pub skip_zap: bool,\n}\n\n/// Removes a filesystem artifact (file or directory).\n///\n/// Attempts direct removal. If `use_sudo` is true and direct removal\n/// fails due to permission errors, it will attempt `sudo rm -rf`.\n///\n/// Returns `true` if the artifact is successfully removed or was already gone,\n/// `false` otherwise.\npub(crate) fn remove_filesystem_artifact(path: &Path, use_sudo: bool) -> bool {\n match path.symlink_metadata() {\n Ok(metadata) => {\n let file_type = metadata.file_type();\n // A directory is only a \"real\" directory if it's not a symlink.\n // Symlinks to directories should be removed with remove_file.\n let is_real_dir = file_type.is_dir();\n\n debug!(\n \"Removing filesystem artifact ({}) at: {}\",\n if is_real_dir {\n \"directory\"\n } else if file_type.is_symlink() {\n \"symlink\"\n } else {\n \"file\"\n },\n path.display()\n );\n\n let remove_op = || -> io::Result<()> {\n if is_real_dir {\n fs::remove_dir_all(path)\n } else {\n // This handles both files and symlinks\n fs::remove_file(path)\n }\n };\n\n if let Err(e) = remove_op() {\n if use_sudo && e.kind() == io::ErrorKind::PermissionDenied {\n warn!(\n \"Direct removal failed (Permission Denied). Trying with sudo rm -rf: {}\",\n path.display()\n );\n let output = Command::new(\"sudo\").arg(\"rm\").arg(\"-rf\").arg(path).output();\n match output {\n Ok(out) if out.status.success() => {\n debug!(\"Successfully removed {} with sudo.\", path.display());\n true\n }\n Ok(out) => {\n error!(\n \"Failed to remove {} with sudo: {}\",\n path.display(),\n String::from_utf8_lossy(&out.stderr).trim()\n );\n false\n }\n Err(sudo_err) => {\n error!(\n \"Error executing sudo rm for {}: {}\",\n path.display(),\n sudo_err\n );\n false\n }\n }\n } else if e.kind() != io::ErrorKind::NotFound {\n error!(\"Failed to remove artifact {}: {}\", path.display(), e);\n false\n } else {\n debug!(\"Artifact {} already removed.\", path.display());\n true\n }\n } else {\n debug!(\"Successfully removed artifact: {}\", path.display());\n true\n }\n }\n Err(e) if e.kind() == io::ErrorKind::NotFound => {\n debug!(\"Artifact not found (already removed?): {}\", path.display());\n true\n }\n Err(e) => {\n warn!(\n \"Failed to get metadata for artifact {}: {}\",\n path.display(),\n e\n );\n false\n }\n }\n}\n\n/// Expands a path string that may start with `~` to the user's home directory.\npub(crate) fn expand_tilde(path_str: &str, home: &Path) -> PathBuf {\n if let Some(stripped) = path_str.strip_prefix(\"~/\") {\n home.join(stripped)\n } else {\n PathBuf::from(path_str)\n }\n}\n\n/// Checks if a path is safe for zap operations.\n/// Safe paths are typically within user Library, .config, /Applications, /Library,\n/// or the sps cache directory. Root, home, /Applications, /Library themselves are not safe.\npub(crate) fn is_safe_path(path: &Path, home: &Path, config: &Config) -> bool {\n if path.components().any(|c| matches!(c, Component::ParentDir)) {\n warn!(\"Zap path rejected (contains '..'): {}\", path.display());\n return false;\n }\n let allowed_roots = [\n home.join(\"Library\"),\n home.join(\".config\"),\n PathBuf::from(\"/Applications\"),\n PathBuf::from(\"/Library\"),\n config.cache_dir().clone(),\n // Consider adding more specific allowed user dirs if necessary\n ];\n\n // Check if the path is exactly one of the top-level restricted paths\n if path == Path::new(\"/\")\n || path == home\n || path == Path::new(\"/Applications\")\n || path == Path::new(\"/Library\")\n {\n warn!(\"Zap path rejected (too broad): {}\", path.display());\n return false;\n }\n\n if allowed_roots.iter().any(|root| path.starts_with(root)) {\n return true;\n }\n\n warn!(\n \"Zap path rejected (outside allowed areas): {}\",\n path.display()\n );\n false\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/mdimporter.rs", "// ===== sps-core/src/build/cask/artifacts/mdimporter.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Installs `mdimporter` bundles from the staging area into\n/// `~/Library/Spotlight`, then symlinks them into the Caskroom,\n/// and reloads them via `mdimport -r` so Spotlight picks them up.\n///\n/// Mirrors Homebrew’s `Mdimporter < Moved` behavior.\npub fn install_mdimporter(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"mdimporter\").and_then(|v| v.as_array()) {\n // Target directory for user Spotlight importers\n let dest_dir = config.home_dir().join(\"Library\").join(\"Spotlight\");\n fs::create_dir_all(&dest_dir)?;\n\n for entry in entries {\n if let Some(bundle_name) = entry.as_str() {\n let src = stage_path.join(bundle_name);\n if !src.exists() {\n debug!(\n \"Mdimporter bundle '{}' not found in staging; skipping\",\n bundle_name\n );\n continue;\n }\n\n let dest = dest_dir.join(bundle_name);\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Installing mdimporter '{}' → '{}',\",\n src.display(),\n dest.display()\n );\n // Try move, fallback to copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record moved importer\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink for reference\n let link = cask_version_install_path.join(bundle_name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n\n // Reload Spotlight importer so it's picked up immediately\n debug!(\"Reloading Spotlight importer: {}\", dest.display());\n let _ = Command::new(\"/usr/bin/mdimport\")\n .arg(\"-r\")\n .arg(&dest)\n .status();\n }\n }\n break; // one stanza only\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-net/src/validation.rs", "// sps-io/src/checksum.rs\n//use std::sync::Arc;\nuse std::fs::File;\nuse std::io;\nuse std::path::Path;\n\nuse infer;\nuse sha2::{Digest, Sha256};\nuse sps_common::error::{Result, SpsError};\nuse url::Url;\n//use tokio::fs::File;\n//use tokio::io::AsyncReadExt;\n//use tracing::debug; // Use tracing\n\n///// Asynchronously verifies the SHA256 checksum of a file.\n///// Reads the file asynchronously but performs hashing synchronously.\n//pub async fn verify_checksum_async(path: &Path, expected: &str) -> Result<()> {\n//debug!(\"Async Verifying checksum for: {}\", path.display());\n// let file = File::open(path).await;\n// let mut file = match file {\n// Ok(f) => f,\n// Err(e) => {\n// return Err(SpsError::Io(Arc::new(e))); // Wrap IO error\n// }\n// };\n//\n// let mut hasher = Sha256::new();\n// let mut buffer = Vec::with_capacity(8192); // Use a Vec as buffer for read_buf\n// let mut total_bytes_read = 0;\n//\n// loop {\n// buffer.clear();\n// match file.read_buf(&mut buffer).await {\n// Ok(0) => break, // End of file\n// Ok(n) => {\n// hasher.update(&buffer[..n]);\n// total_bytes_read += n as u64;\n// }\n// Err(e) => {\n// return Err(SpsError::Io(Arc::new(e))); // Wrap IO error\n// }\n// }\n// }\n//\n// let hash_bytes = hasher.finalize();\n// let actual = hex::encode(hash_bytes);\n//\n// debug!(\n// \"Async Calculated SHA256: {} ({} bytes read)\",\n// actual, total_bytes_read\n// );\n// debug!(\"Expected SHA256: {}\", expected);\n//\n// if actual.eq_ignore_ascii_case(expected) {\n// Ok(())\n// } else {\n// Err(SpsError::ChecksumError(format!(\n// \"Checksum mismatch for {}: expected {}, got {}\",\n// path.display(),\n// expected,\n// actual\n// )))\n// }\n//}\n\n// Keep the synchronous version for now if needed elsewhere or for comparison\npub fn verify_checksum(path: &Path, expected: &str) -> Result<()> {\n tracing::debug!(\"Verifying checksum for: {}\", path.display());\n let mut file = File::open(path)?;\n let mut hasher = Sha256::new();\n let bytes_copied = io::copy(&mut file, &mut hasher)?;\n let hash_bytes = hasher.finalize();\n let actual = hex::encode(hash_bytes);\n tracing::debug!(\n \"Calculated SHA256: {} ({} bytes read)\",\n actual,\n bytes_copied\n );\n tracing::debug!(\"Expected SHA256: {}\", expected);\n if actual.eq_ignore_ascii_case(expected) {\n Ok(())\n } else {\n Err(SpsError::ChecksumError(format!(\n \"Checksum mismatch for {}: expected {}, got {}\",\n path.display(),\n expected,\n actual\n )))\n }\n}\n\n/// Verifies that the detected content type of the file matches the expected extension.\npub fn verify_content_type(path: &Path, expected_ext: &str) -> Result<()> {\n let kind_opt = infer::get_from_path(path)?;\n if let Some(kind) = kind_opt {\n let actual_ext = kind.extension();\n if actual_ext.eq_ignore_ascii_case(expected_ext) {\n tracing::debug!(\n \"Content type verified: {} matches expected {}\",\n actual_ext,\n expected_ext\n );\n Ok(())\n } else {\n Err(SpsError::Generic(format!(\n \"Content type mismatch for {}: expected extension '{}', but detected '{}'\",\n path.display(),\n expected_ext,\n actual_ext\n )))\n }\n } else {\n Err(SpsError::Generic(format!(\n \"Could not determine content type for {}\",\n path.display()\n )))\n }\n}\n\n/// Validates a URL, ensuring it uses the HTTPS scheme.\npub fn validate_url(url_str: &str) -> Result<()> {\n let url = Url::parse(url_str)\n .map_err(|e| SpsError::Generic(format!(\"Failed to parse URL '{url_str}': {e}\")))?;\n if url.scheme() == \"https\" {\n Ok(())\n } else {\n Err(SpsError::ValidationError(format!(\n \"Invalid URL scheme for '{}': Must be https, but got '{}'\",\n url_str,\n url.scheme()\n )))\n }\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/vst_plugin.rs", "// ===== sps-core/src/build/cask/artifacts/vst_plugin.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Installs `vst_plugin` bundles from the staging area into\n/// `~/Library/Audio/Plug-Ins/VST`, then symlinks them into the Caskroom.\n///\n/// Mirrors Homebrew’s `VstPlugin < Moved` pattern.\npub fn install_vst_plugin(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"vst_plugin\").and_then(|v| v.as_array()) {\n // Target directory for VST plugins\n let dest_dir = config\n .home_dir()\n .join(\"Library\")\n .join(\"Audio\")\n .join(\"Plug-Ins\")\n .join(\"VST\");\n fs::create_dir_all(&dest_dir)?;\n\n for entry in entries {\n if let Some(bundle_name) = entry.as_str() {\n let src = stage_path.join(bundle_name);\n if !src.exists() {\n debug!(\n \"VST plugin '{}' not found in staging; skipping\",\n bundle_name\n );\n continue;\n }\n\n let dest = dest_dir.join(bundle_name);\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Installing VST plugin '{}' → '{}'\",\n src.display(),\n dest.display()\n );\n // Try move, fallback to copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record moved plugin\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink into Caskroom for reference\n let link = cask_version_install_path.join(bundle_name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // single stanza\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/audio_unit_plugin.rs", "// ===== sps-core/src/build/cask/artifacts/audio_unit_plugin.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Installs `audio_unit_plugin` bundles from the staging area into\n/// `~/Library/Audio/Plug-Ins/Components`, then symlinks them into the Caskroom.\n///\n/// Mirrors Homebrew’s `AudioUnitPlugin < Moved` pattern.\npub fn install_audio_unit_plugin(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"audio_unit_plugin\").and_then(|v| v.as_array()) {\n // Target directory for Audio Unit components\n let dest_dir = config\n .home_dir()\n .join(\"Library\")\n .join(\"Audio\")\n .join(\"Plug-Ins\")\n .join(\"Components\");\n fs::create_dir_all(&dest_dir)?;\n\n for entry in entries {\n if let Some(bundle_name) = entry.as_str() {\n let src = stage_path.join(bundle_name);\n if !src.exists() {\n debug!(\n \"AudioUnit plugin '{}' not found in staging; skipping\",\n bundle_name\n );\n continue;\n }\n\n let dest = dest_dir.join(bundle_name);\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Installing AudioUnit plugin '{}' → '{}'\",\n src.display(),\n dest.display()\n );\n // Try move, fallback to copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record moved plugin\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink into Caskroom for reference\n let link = cask_version_install_path.join(bundle_name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // one stanza only\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/vst3_plugin.rs", "// ===== sps-core/src/build/cask/artifacts/vst3_plugin.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Installs `vst3_plugin` bundles from the staging area into\n/// `~/Library/Audio/Plug-Ins/VST3`, then symlinks them into the Caskroom.\n///\n/// Mirrors Homebrew’s `Vst3Plugin < Moved` pattern.\npub fn install_vst3_plugin(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"vst3_plugin\").and_then(|v| v.as_array()) {\n // Target directory for VST3 plugins\n let dest_dir = config\n .home_dir()\n .join(\"Library\")\n .join(\"Audio\")\n .join(\"Plug-Ins\")\n .join(\"VST3\");\n fs::create_dir_all(&dest_dir)?;\n\n for entry in entries {\n if let Some(bundle_name) = entry.as_str() {\n let src = stage_path.join(bundle_name);\n if !src.exists() {\n debug!(\n \"VST3 plugin '{}' not found in staging; skipping\",\n bundle_name\n );\n continue;\n }\n\n let dest = dest_dir.join(bundle_name);\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Installing VST3 plugin '{}' → '{}'\",\n src.display(),\n dest.display()\n );\n // Try move, fallback to copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record moved plugin\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink into Caskroom for reference\n let link = cask_version_install_path.join(bundle_name);\n let _ = crate::install::cask::helpers::remove_path_robustly(\n &link, config, true,\n );\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // single stanza\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/dictionary.rs", "// ===== sps-core/src/build/cask/artifacts/dictionary.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Implements the `dictionary` stanza by moving each declared\n/// `.dictionary` bundle from the staging area into `~/Library/Dictionaries`,\n/// then symlinking it in the Caskroom.\n///\n/// Homebrew’s Ruby definition is simply:\n/// ```ruby\n/// class Dictionary < Moved; end\n/// ```\n/// :contentReference[oaicite:2]{index=2}\npub fn install_dictionary(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n // Find any `dictionary` arrays in the raw JSON artifacts\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"dictionary\").and_then(|v| v.as_array()) {\n for entry in entries {\n if let Some(bundle_name) = entry.as_str() {\n let src = stage_path.join(bundle_name);\n if !src.exists() {\n debug!(\n \"Dictionary bundle '{}' not found in staging; skipping\",\n bundle_name\n );\n continue;\n }\n\n // Standard user dictionary directory: ~/Library/Dictionaries\n // :contentReference[oaicite:3]{index=3}\n let dest_dir = config\n .home_dir() // e.g. /Users/alxknt\n .join(\"Library\")\n .join(\"Dictionaries\");\n fs::create_dir_all(&dest_dir)?;\n\n let dest = dest_dir.join(bundle_name);\n // Remove any previous install\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Moving dictionary '{}' → '{}'\",\n src.display(),\n dest.display()\n );\n // Try a direct move; fall back to recursive copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record the moved bundle\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink back into Caskroom for reference\n let link = cask_version_install_path.join(bundle_name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // Only one `dictionary` stanza per cask\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/suite.rs", "// src/build/cask/artifacts/suite.rs\n\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Implements the `suite` stanza by moving each named directory from\n/// the staging area into `/Applications`, then symlinking it in the Caskroom.\n///\n/// Mirrors Homebrew’s Suite < Moved behavior (dirmethod :appdir)\n/// :contentReference[oaicite:3]{index=3}\npub fn install_suite(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n // Find the `suite` definition in the raw JSON artifacts\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def.iter() {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"suite\").and_then(|v| v.as_array()) {\n for entry in entries {\n if let Some(dir_name) = entry.as_str() {\n let src = stage_path.join(dir_name);\n if !src.exists() {\n debug!(\n \"Suite directory '{}' not found in staging, skipping\",\n dir_name\n );\n continue;\n }\n\n let dest_dir = config.applications_dir(); // e.g. /Applications\n let dest = dest_dir.join(dir_name); // e.g. /Applications/Foobar Suite\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n // remove old\n }\n\n debug!(\"Moving suite '{}' → '{}'\", src.display(), dest.display());\n // Try a rename (mv); fall back to recursive copy if cross‑filesystem\n let mv_status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !mv_status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record as an App artifact (a directory moved into /Applications)\n installed.push(InstalledArtifact::AppBundle { path: dest.clone() });\n\n // Then symlink it under Caskroom for reference\n let link = cask_version_install_path.join(dir_name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // only one \"suite\" stanza per cask\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-common/src/model/version.rs", "// **File:** sps-core/src/model/version.rs (New file)\nuse std::fmt;\nuse std::str::FromStr;\n\nuse serde::{Deserialize, Deserializer, Serialize, Serializer};\n\nuse crate::error::{Result, SpsError};\n\n/// Wrapper around semver::Version for formula versions.\n#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]\npub struct Version(semver::Version);\n\nimpl Version {\n pub fn parse(s: &str) -> Result {\n // Attempt standard semver parse first\n semver::Version::parse(s).map(Version).or_else(|_| {\n // Homebrew often uses versions like \"1.2.3_1\" (revision) or just \"123\"\n // Try to handle these by stripping suffixes or padding\n // This is a simplified handling, Homebrew's PkgVersion is complex\n let cleaned = s.split('_').next().unwrap_or(s); // Take part before _\n let parts: Vec<&str> = cleaned.split('.').collect();\n let padded = match parts.len() {\n 1 => format!(\"{}.0.0\", parts[0]),\n 2 => format!(\"{}.{}.0\", parts[0], parts[1]),\n _ => cleaned.to_string(), // Use original if 3+ parts\n };\n semver::Version::parse(&padded).map(Version).map_err(|e| {\n SpsError::VersionError(format!(\n \"Failed to parse version '{s}' (tried '{padded}'): {e}\"\n ))\n })\n })\n }\n}\n\nimpl FromStr for Version {\n type Err = SpsError;\n fn from_str(s: &str) -> std::result::Result {\n Self::parse(s)\n }\n}\n\nimpl fmt::Display for Version {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n // TODO: Preserve original format if possible? PkgVersion complexity.\n // For now, display the parsed semver representation.\n write!(f, \"{}\", self.0)\n }\n}\n\n// Manual Serialize/Deserialize to handle the Version<->String conversion\nimpl Serialize for Version {\n fn serialize(&self, serializer: S) -> std::result::Result\n where\n S: Serializer,\n {\n serializer.serialize_str(&self.to_string())\n }\n}\n\nimpl AsRef for Version {\n fn as_ref(&self) -> &Self {\n self\n }\n}\n\n// Removed redundant ToString implementation as it conflicts with the blanket implementation in std.\n\nimpl From for semver::Version {\n fn from(version: Version) -> Self {\n version.0\n }\n}\n\nimpl<'de> Deserialize<'de> for Version {\n fn deserialize(deserializer: D) -> std::result::Result\n where\n D: Deserializer<'de>,\n {\n let s = String::deserialize(deserializer)?;\n Self::from_str(&s).map_err(serde::de::Error::custom)\n }\n}\n\n// Add to sps-core/src/utils/error.rs:\n// #[error(\"Version error: {0}\")]\n// VersionError(String),\n\n// Add to sps-core/Cargo.toml:\n// [dependencies]\n// semver = \"1.0\"\n"], ["/sps/sps/src/cli/install.rs", "// sps-cli/src/cli/install.rs\n\nuse std::sync::Arc;\n\nuse clap::Args;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse tracing::instrument;\n\n// Import pipeline components from the new module\nuse crate::pipeline::runner::{self, CommandType, PipelineFlags};\n\n// Keep the Args struct specific to 'install' if needed, or reuse a common one\n#[derive(Debug, Args)]\npub struct InstallArgs {\n #[arg(required = true)]\n names: Vec,\n\n // Keep flags relevant to install/pipeline\n #[arg(long)]\n skip_deps: bool, // Note: May not be fully supported by core resolution yet\n #[arg(long, help = \"Force install specified targets as casks\")]\n cask: bool,\n #[arg(long, help = \"Force install specified targets as formulas\")]\n formula: bool,\n #[arg(long)]\n include_optional: bool,\n #[arg(long)]\n skip_recommended: bool,\n #[arg(\n long,\n help = \"Force building the formula from source, even if a bottle is available\"\n )]\n build_from_source: bool,\n // Worker/Queue size flags might belong here or be global CLI flags\n // #[arg(long, value_name = \"sps_WORKERS\")]\n // max_workers: Option,\n // #[arg(long, value_name = \"sps_QUEUE\")]\n // queue_size: Option,\n}\n\nimpl InstallArgs {\n #[instrument(skip(self, config, cache), fields(targets = ?self.names))]\n pub async fn run(&self, config: &Config, cache: Arc) -> Result<()> {\n // --- Argument Validation (moved from old run) ---\n if self.formula && self.cask {\n return Err(sps_common::error::SpsError::Generic(\n \"Cannot use --formula and --cask together.\".to_string(),\n ));\n }\n // Add validation for skip_deps if needed\n\n // --- Prepare Pipeline Flags ---\n let flags = PipelineFlags {\n build_from_source: self.build_from_source,\n include_optional: self.include_optional,\n skip_recommended: self.skip_recommended,\n // Add other flags...\n };\n\n // --- Determine Initial Targets based on --formula/--cask flags ---\n // (This logic might be better inside plan_package_operations based on CommandType)\n let initial_targets = self.names.clone(); // For install, all names are initial targets\n\n // --- Execute the Pipeline ---\n runner::run_pipeline(\n &initial_targets,\n CommandType::Install, // Specify the command type\n config,\n cache,\n &flags, // Pass the flags struct\n )\n .await\n }\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/service.rs", "// ===== sps-core/src/build/cask/artifacts/service.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers;\n\n/// Installs `service` artifacts by moving each declared\n/// Automator workflow or service bundle from the staging area into\n/// `~/Library/Services`, then symlinking it in the Caskroom.\n///\n/// Mirrors Homebrew’s `Service < Moved` behavior.\npub fn install_service(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"service\").and_then(|v| v.as_array()) {\n // Target directory for user Services\n let dest_dir = config.home_dir().join(\"Library\").join(\"Services\");\n fs::create_dir_all(&dest_dir)?;\n\n for entry in entries {\n if let Some(bundle_name) = entry.as_str() {\n let src = stage_path.join(bundle_name);\n if !src.exists() {\n debug!(\n \"Service bundle '{}' not found in staging; skipping\",\n bundle_name\n );\n continue;\n }\n\n let dest = dest_dir.join(bundle_name);\n if dest.exists() {\n let _ = helpers::remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Installing service '{}' → '{}'\",\n src.display(),\n dest.display()\n );\n // Try move, fallback to copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record moved service\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink into Caskroom for reference\n let link = cask_version_install_path.join(bundle_name);\n let _ = helpers::remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // one stanza only\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/prefpane.rs", "// ===== sps-core/src/build/cask/artifacts/prefpane.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Implements the `prefpane` stanza by moving each declared\n/// preference pane bundle from the staging area into\n/// `~/Library/PreferencePanes`, then symlinking it in the Caskroom.\n///\n/// Mirrors Homebrew’s `Prefpane < Moved` pattern.\npub fn install_prefpane(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n // Look for \"prefpane\" entries in the JSON artifacts\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"prefpane\").and_then(|v| v.as_array()) {\n // Target directory for user preference panes\n let dest_dir = config.home_dir().join(\"Library\").join(\"PreferencePanes\");\n fs::create_dir_all(&dest_dir)?;\n\n for entry in entries {\n if let Some(bundle_name) = entry.as_str() {\n let src = stage_path.join(bundle_name);\n if !src.exists() {\n debug!(\n \"Preference pane '{}' not found in staging; skipping\",\n bundle_name\n );\n continue;\n }\n\n let dest = dest_dir.join(bundle_name);\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Installing prefpane '{}' → '{}'\",\n src.display(),\n dest.display()\n );\n // Try move, fallback to copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record moved bundle\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink into Caskroom for reference\n let link = cask_version_install_path.join(bundle_name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // single stanza\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/qlplugin.rs", "// ===== sps-core/src/build/cask/artifacts/qlplugin.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Installs `qlplugin` bundles from the staging area into\n/// `~/Library/QuickLook`, then symlinks them into the Caskroom.\n///\n/// Mirrors Homebrew’s `QuickLook < Moved` pattern for QuickLook plugins.\npub fn install_qlplugin(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n // Look for \"qlplugin\" entries in the JSON artifacts\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"qlplugin\").and_then(|v| v.as_array()) {\n // Target directory for QuickLook plugins\n let dest_dir = config.home_dir().join(\"Library\").join(\"QuickLook\");\n fs::create_dir_all(&dest_dir)?;\n\n for entry in entries {\n if let Some(bundle_name) = entry.as_str() {\n let src = stage_path.join(bundle_name);\n if !src.exists() {\n debug!(\n \"QuickLook plugin '{}' not found in staging; skipping\",\n bundle_name\n );\n continue;\n }\n\n let dest = dest_dir.join(bundle_name);\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Installing QuickLook plugin '{}' → '{}',\",\n src.display(),\n dest.display()\n );\n // Try move, fallback to copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record moved plugin\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink into Caskroom for reference\n let link = cask_version_install_path.join(bundle_name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // single stanza\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/screen_saver.rs", "// ===== sps-core/src/build/cask/artifacts/screen_saver.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Installs `screen_saver` bundles from the staging area into\n/// `~/Library/Screen Savers`, then symlinks them into the Caskroom.\n///\n/// Mirrors Homebrew’s `ScreenSaver < Moved` pattern.\npub fn install_screen_saver(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"screen_saver\").and_then(|v| v.as_array()) {\n // Target directory for user screen savers\n let dest_dir = config.home_dir().join(\"Library\").join(\"Screen Savers\");\n fs::create_dir_all(&dest_dir)?;\n\n for entry in entries {\n if let Some(bundle_name) = entry.as_str() {\n let src = stage_path.join(bundle_name);\n if !src.exists() {\n debug!(\n \"Screen saver '{}' not found in staging; skipping\",\n bundle_name\n );\n continue;\n }\n\n let dest = dest_dir.join(bundle_name);\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Installing screen saver '{}' → '{}',\",\n src.display(),\n dest.display()\n );\n // Try move, fallback to copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record moved screen saver\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink into Caskroom for reference\n let link = cask_version_install_path.join(bundle_name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // single stanza\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/helpers.rs", "use std::fs;\nuse std::path::Path;\n\nuse sps_common::config::Config;\nuse tracing::debug;\n\n/// Robustly removes a file or directory, handling symlinks and permissions.\n/// If `use_sudo_if_needed` is true, will attempt `sudo rm -rf` on permission errors.\npub fn remove_path_robustly(path: &Path, _config: &Config, use_sudo_if_needed: bool) -> bool {\n if !path.exists() && path.symlink_metadata().is_err() {\n debug!(\"Path {} not found for removal.\", path.display());\n return true;\n }\n let is_dir = path.is_dir()\n && !path\n .symlink_metadata()\n .is_ok_and(|m| m.file_type().is_symlink());\n let removal_op = || -> std::io::Result<()> {\n if is_dir {\n fs::remove_dir_all(path)\n } else {\n fs::remove_file(path)\n }\n };\n\n if let Err(e) = removal_op() {\n if e.kind() == std::io::ErrorKind::NotFound {\n return true;\n }\n if use_sudo_if_needed && e.kind() == std::io::ErrorKind::PermissionDenied {\n debug!(\n \"Direct removal of {} failed (Permission Denied). Trying with sudo rm -rf.\",\n path.display()\n );\n let output = std::process::Command::new(\"sudo\")\n .arg(\"rm\")\n .arg(\"-rf\")\n .arg(path)\n .output();\n match output {\n Ok(out) if out.status.success() => {\n debug!(\"Successfully removed {} with sudo.\", path.display());\n return true;\n }\n Ok(out) => {\n debug!(\n \"`sudo rm -rf {}` failed ({}): {}\",\n path.display(),\n out.status,\n String::from_utf8_lossy(&out.stderr).trim()\n );\n return false;\n }\n Err(sudo_e) => {\n debug!(\n \"Error executing `sudo rm -rf` for {}: {}\",\n path.display(),\n sudo_e\n );\n return false;\n }\n }\n } else {\n debug!(\"Failed to remove {}: {}\", path.display(), e);\n return false;\n }\n }\n debug!(\"Successfully removed {}.\", path.display());\n true\n}\n\n/// Recursively cleans up empty parent directories in the private cask store.\n/// Starts from the given path and walks up, removing empty directories until a non-empty or root is\n/// found.\npub fn cleanup_empty_parent_dirs_in_private_store(start_path: &Path, stop_at: &Path) {\n let mut current = start_path.to_path_buf();\n while current != *stop_at {\n if let Ok(read_dir) = fs::read_dir(¤t) {\n if read_dir.count() == 0 {\n match fs::remove_dir(¤t) {\n Ok(_) => {\n debug!(\"Removed empty directory: {}\", current.display());\n }\n Err(e) => {\n debug!(\"Failed to remove directory {}: {}\", current.display(), e);\n break;\n }\n }\n } else {\n break;\n }\n } else {\n break;\n }\n if let Some(parent) = current.parent() {\n current = parent.to_path_buf();\n } else {\n break;\n }\n }\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/keyboard_layout.rs", "// ===== sps-core/src/build/cask/artifacts/keyboard_layout.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Mirrors Homebrew’s `KeyboardLayout < Moved` behavior.\npub fn install_keyboard_layout(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"keyboard_layout\").and_then(|v| v.as_array()) {\n // Target directory for user keyboard layouts\n let dest_dir = config.home_dir().join(\"Library\").join(\"Keyboard Layouts\");\n fs::create_dir_all(&dest_dir)?;\n\n for entry in entries {\n if let Some(bundle_name) = entry.as_str() {\n let src = stage_path.join(bundle_name);\n if !src.exists() {\n debug!(\n \"Keyboard layout '{}' not found in staging; skipping\",\n bundle_name\n );\n continue;\n }\n\n let dest = dest_dir.join(bundle_name);\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Installing keyboard layout '{}' → '{}'\",\n src.display(),\n dest.display()\n );\n // Try move, fallback to copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record moved bundle\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink into Caskroom\n let link = cask_version_install_path.join(bundle_name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // one stanza only\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-common/src/cache.rs", "// src/utils/cache.rs\n// Handles caching of formula data and downloads\n\nuse std::fs;\nuse std::path::{Path, PathBuf};\nuse std::time::{Duration, SystemTime};\n\nuse super::error::{Result, SpsError};\nuse crate::Config;\n\n/// Define how long cache entries are considered valid\nconst CACHE_TTL: Duration = Duration::from_secs(24 * 60 * 60); // 24 hours\n\n/// Cache struct to manage cache operations\npub struct Cache {\n cache_dir: PathBuf,\n _config: Config, // Keep a reference to config if needed for other paths or future use\n}\n\nimpl Cache {\n /// Create a new Cache using the config's cache_dir\n pub fn new(config: &Config) -> Result {\n let cache_dir = config.cache_dir();\n if !cache_dir.exists() {\n fs::create_dir_all(&cache_dir)?;\n }\n\n Ok(Self {\n cache_dir,\n _config: config.clone(),\n })\n }\n\n /// Gets the cache directory path\n pub fn get_dir(&self) -> &Path {\n &self.cache_dir\n }\n\n /// Stores raw string data in the cache\n pub fn store_raw(&self, filename: &str, data: &str) -> Result<()> {\n let path = self.cache_dir.join(filename);\n tracing::debug!(\"Saving raw data to cache file: {:?}\", path);\n fs::write(&path, data)?;\n Ok(())\n }\n\n /// Loads raw string data from the cache\n pub fn load_raw(&self, filename: &str) -> Result {\n let path = self.cache_dir.join(filename);\n tracing::debug!(\"Loading raw data from cache file: {:?}\", path);\n\n if !path.exists() {\n return Err(SpsError::Cache(format!(\n \"Cache file {filename} does not exist\"\n )));\n }\n\n fs::read_to_string(&path).map_err(|e| SpsError::Cache(format!(\"IO error: {e}\")))\n }\n\n /// Checks if a cache file exists and is valid (within TTL)\n pub fn is_cache_valid(&self, filename: &str) -> Result {\n let path = self.cache_dir.join(filename);\n if !path.exists() {\n return Ok(false);\n }\n\n let metadata = fs::metadata(&path)?;\n let modified_time = metadata.modified()?;\n let age = SystemTime::now()\n .duration_since(modified_time)\n .map_err(|e| SpsError::Cache(format!(\"System time error: {e}\")))?;\n\n Ok(age <= CACHE_TTL)\n }\n\n /// Clears a specific cache file\n pub fn clear_file(&self, filename: &str) -> Result<()> {\n let path = self.cache_dir.join(filename);\n if path.exists() {\n fs::remove_file(&path)?;\n }\n Ok(())\n }\n\n /// Clears all cache files\n pub fn clear_all(&self) -> Result<()> {\n if self.cache_dir.exists() {\n fs::remove_dir_all(&self.cache_dir)?;\n fs::create_dir_all(&self.cache_dir)?;\n }\n Ok(())\n }\n\n /// Gets a reference to the config\n pub fn config(&self) -> &Config {\n &self._config\n }\n}\n"], ["/sps/sps-core/src/upgrade/cask.rs", "// sps-core/src/upgrade/cask.rs\n\nuse std::path::Path;\n\nuse sps_common::config::Config;\nuse sps_common::error::{Result as SpsResult, SpsError};\nuse sps_common::model::cask::Cask;\nuse sps_common::pipeline::JobAction; // Required for install_cask\nuse tracing::{debug, error};\n\nuse crate::check::installed::InstalledPackageInfo;\nuse crate::{install, uninstall};\n\n/// Upgrades a cask package using Homebrew's proven strategy.\npub async fn upgrade_cask_package(\n cask: &Cask,\n new_cask_download_path: &Path,\n old_install_info: &InstalledPackageInfo,\n config: &Config,\n) -> SpsResult<()> {\n debug!(\n \"Upgrading cask {} from {} to {}\",\n cask.token,\n old_install_info.version,\n cask.version.as_deref().unwrap_or(\"latest\")\n );\n\n // 1. Soft-uninstall the old version\n // This removes linked artifacts and updates the old manifest's is_installed flag.\n // It does not remove the old Caskroom version directory itself yet.\n debug!(\n \"Soft-uninstalling old cask version: {} at {}\",\n old_install_info.version,\n old_install_info.path.display()\n );\n uninstall::cask::uninstall_cask_artifacts(old_install_info, config).map_err(|e| {\n error!(\n \"Failed to soft-uninstall old version {} of cask {}: {}\",\n old_install_info.version, cask.token, e\n );\n SpsError::InstallError(format!(\n \"Failed to soft-uninstall old version during upgrade of {}: {e}\",\n cask.token\n ))\n })?;\n debug!(\n \"Successfully soft-uninstalled old version of {}\",\n cask.token\n );\n\n // 2. Install the new version\n // The install_cask function, particularly install_app_from_staged,\n // should handle the upgrade logic (like syncing app data) when\n // passed the JobAction::Upgrade.\n debug!(\n \"Installing new version for cask {} from {}\",\n cask.token,\n new_cask_download_path.display()\n );\n\n let job_action_for_install = JobAction::Upgrade {\n from_version: old_install_info.version.clone(),\n old_install_path: old_install_info.path.clone(),\n };\n\n install::cask::install_cask(\n cask,\n new_cask_download_path,\n config,\n &job_action_for_install,\n )\n .map_err(|e| {\n error!(\n \"Failed to install new version of cask {}: {}\",\n cask.token, e\n );\n SpsError::InstallError(format!(\n \"Failed to install new version during upgrade of {}: {e}\",\n cask.token\n ))\n })?;\n debug!(\"Successfully installed new version of cask {}\", cask.token);\n\n Ok(())\n}\n"], ["/sps/sps-core/src/upgrade/bottle.rs", "// sps-core/src/upgrade/bottle.rs\n\nuse std::path::{Path, PathBuf};\nuse std::sync::Arc;\n\nuse sps_common::config::Config;\nuse sps_common::error::{Result as SpsResult, SpsError};\nuse sps_common::model::formula::Formula;\nuse tracing::{debug, error};\n\nuse crate::check::installed::InstalledPackageInfo;\nuse crate::{install, uninstall};\n\n/// Upgrades a formula that is installed from a bottle.\n///\n/// This involves:\n/// 1. Uninstalling the old version of the formula.\n/// 2. Installing the new bottle.\n/// 3. Linking the new version.\npub async fn upgrade_bottle_formula(\n formula: &Formula,\n new_bottle_download_path: &Path,\n old_install_info: &InstalledPackageInfo,\n config: &Config,\n http_client: Arc, /* Added for download_bottle if needed, though path is\n * pre-downloaded */\n) -> SpsResult {\n debug!(\n \"Upgrading bottle formula {} from {} to {}\",\n formula.name(),\n old_install_info.version,\n formula.version_str_full()\n );\n\n // 1. Uninstall the old version\n debug!(\n \"Uninstalling old bottle version: {} at {}\",\n old_install_info.version,\n old_install_info.path.display()\n );\n let uninstall_opts = uninstall::UninstallOptions { skip_zap: true }; // Zap is not relevant for formula upgrades\n uninstall::formula::uninstall_formula_artifacts(old_install_info, config, &uninstall_opts)\n .map_err(|e| {\n error!(\n \"Failed to uninstall old version {} of formula {}: {}\",\n old_install_info.version,\n formula.name(),\n e\n );\n SpsError::InstallError(format!(\n \"Failed to uninstall old version during upgrade of {}: {e}\",\n formula.name()\n ))\n })?;\n debug!(\"Successfully uninstalled old version of {}\", formula.name());\n\n // 2. Install the new bottle\n // The new_bottle_download_path is already provided, so we call install_bottle directly.\n // If download was part of this function, http_client would be used.\n let _ = http_client; // Mark as used if not directly needed by install_bottle\n\n debug!(\n \"Installing new bottle for {} from {}\",\n formula.name(),\n new_bottle_download_path.display()\n );\n let installed_keg_path =\n install::bottle::exec::install_bottle(new_bottle_download_path, formula, config).map_err(\n |e| {\n error!(\n \"Failed to install new bottle for formula {}: {}\",\n formula.name(),\n e\n );\n SpsError::InstallError(format!(\n \"Failed to install new bottle during upgrade of {}: {e}\",\n formula.name()\n ))\n },\n )?;\n debug!(\n \"Successfully installed new bottle for {} to {}\",\n formula.name(),\n installed_keg_path.display()\n );\n\n // 3. Link the new version (linking is handled by the worker after this function returns the\n // path)\n // The install::bottle::exec::install_bottle writes the receipt, but linking is separate.\n // The worker will call link_formula_artifacts after this.\n\n Ok(installed_keg_path)\n}\n"], ["/sps/sps-core/src/uninstall/formula.rs", "// sps-core/src/uninstall/formula.rs\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse tracing::{debug, error, warn};\n\nuse crate::check::installed::InstalledPackageInfo;\nuse crate::install; // For install::bottle::link\nuse crate::uninstall::common::{remove_filesystem_artifact, UninstallOptions};\n\npub fn uninstall_formula_artifacts(\n info: &InstalledPackageInfo,\n config: &Config,\n _options: &UninstallOptions, /* options currently unused for formula but kept for signature\n * consistency */\n) -> Result<()> {\n debug!(\n \"Uninstalling Formula artifacts for {} version {}\",\n info.name, info.version\n );\n\n // 1. Unlink artifacts\n // This function should handle removal of symlinks from /opt/sps/bin, /opt/sps/lib etc.\n // and the /opt/sps/opt/formula_name link.\n install::bottle::link::unlink_formula_artifacts(&info.name, &info.version, config)?;\n\n // 2. Remove the keg directory\n if info.path.exists() {\n debug!(\"Removing formula keg directory: {}\", info.path.display());\n // For formula kegs, we generally expect them to be owned by the user or sps,\n // but sudo might be involved if permissions were changed manually or during a problematic\n // install. Setting use_sudo to true provides a fallback, though ideally it's not\n // needed for user-owned kegs.\n let use_sudo = true;\n if !remove_filesystem_artifact(&info.path, use_sudo) {\n // Check if it still exists after the removal attempt\n if info.path.exists() {\n error!(\n \"Failed remove keg {}: Check logs for sudo errors or other filesystem issues.\",\n info.path.display()\n );\n return Err(SpsError::InstallError(format!(\n \"Failed to remove keg directory: {}\",\n info.path.display()\n )));\n } else {\n // It means remove_filesystem_artifact returned false but the dir is gone\n // (possibly removed by sudo, or a race condition if another process removed it)\n debug!(\"Keg directory successfully removed (possibly with sudo).\");\n }\n }\n } else {\n warn!(\n \"Keg directory {} not found during uninstall. It might have been already removed.\",\n info.path.display()\n );\n }\n Ok(())\n}\n"], ["/sps/sps-core/src/pipeline/engine.rs", "use std::sync::atomic::{AtomicUsize, Ordering};\nuse std::sync::Arc;\n\nuse crossbeam_channel::Receiver as CrossbeamReceiver;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::error::Result as SpsResult;\nuse sps_common::pipeline::{PipelineEvent, WorkerJob};\nuse threadpool::ThreadPool;\nuse tokio::sync::broadcast;\nuse tracing::{debug, instrument};\n\nuse super::worker;\n\n#[instrument(skip_all, name = \"core_worker_manager\")]\npub fn start_worker_pool_manager(\n config: Config,\n cache: Arc,\n worker_job_rx: CrossbeamReceiver,\n event_tx: broadcast::Sender,\n success_count: Arc,\n fail_count: Arc,\n) -> SpsResult<()> {\n let num_workers = std::cmp::max(1, num_cpus::get_physical().saturating_sub(1)).min(6);\n let pool = ThreadPool::new(num_workers);\n debug!(\n \"Core worker pool manager started with {} workers.\",\n num_workers\n );\n debug!(\"Worker pool created.\");\n\n for worker_job in worker_job_rx {\n let job_id = worker_job.request.target_id.clone();\n debug!(\n \"[{}] Received job from channel, preparing to submit to pool.\",\n job_id\n );\n\n let config_clone = config.clone();\n let cache_clone = Arc::clone(&cache);\n let event_tx_clone = event_tx.clone();\n let success_count_clone = Arc::clone(&success_count);\n let fail_count_clone = Arc::clone(&fail_count);\n\n let _ = event_tx_clone.send(PipelineEvent::JobProcessingStarted {\n target_id: job_id.clone(),\n });\n\n debug!(\"[{}] Submitting job to worker pool.\", job_id);\n\n pool.execute(move || {\n let job_result = worker::execute_sync_job(\n worker_job,\n &config_clone,\n cache_clone,\n event_tx_clone.clone(),\n );\n let job_id_for_log = job_id.clone();\n debug!(\n \"[{}] Worker job execution finished (execute_sync_job returned), result ok: {}\",\n job_id_for_log,\n job_result.is_ok()\n );\n\n let job_id_for_log = job_id.clone();\n match job_result {\n Ok((final_action, pkg_type)) => {\n success_count_clone.fetch_add(1, Ordering::Relaxed);\n debug!(\"[{}] Worker finished successfully.\", job_id);\n let _ = event_tx_clone.send(PipelineEvent::JobSuccess {\n target_id: job_id,\n action: final_action,\n pkg_type,\n });\n debug!(\"[{}] Worker result event sent.\", job_id_for_log);\n }\n Err(boxed) => {\n let (final_action, err) = *boxed;\n fail_count_clone.fetch_add(1, Ordering::Relaxed);\n // Error is sent via JobFailed event and displayed in status.rs\n let _ = event_tx_clone.send(PipelineEvent::JobFailed {\n target_id: job_id,\n action: final_action,\n error: err.to_string(),\n });\n debug!(\"[{}] Worker result event sent.\", job_id_for_log);\n }\n }\n debug!(\"[{}] Worker closure scope ending.\", job_id_for_log);\n });\n }\n pool.join();\n Ok(())\n}\n"], ["/sps/sps-common/src/dependency/definition.rs", "// **File:** sps-core/src/dependency/dependency.rs // Should be in the model module\nuse std::fmt;\n\nuse bitflags::bitflags;\nuse serde::{Deserialize, Serialize};\n\nbitflags! {\n #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]\n pub struct DependencyTag: u8 {\n const RUNTIME = 0b00000001;\n const BUILD = 0b00000010;\n const TEST = 0b00000100;\n const OPTIONAL = 0b00001000;\n const RECOMMENDED = 0b00010000;\n }\n}\n\nimpl Default for DependencyTag {\n fn default() -> Self {\n Self::RUNTIME\n }\n}\n\nimpl fmt::Display for DependencyTag {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"{self:?}\")\n }\n}\n\n#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]\npub struct Dependency {\n pub name: String,\n #[serde(default)]\n pub tags: DependencyTag,\n}\n\nimpl Dependency {\n pub fn new_runtime(name: impl Into) -> Self {\n Self {\n name: name.into(),\n tags: DependencyTag::RUNTIME,\n }\n }\n\n pub fn new_with_tags(name: impl Into, tags: DependencyTag) -> Self {\n Self {\n name: name.into(),\n tags,\n }\n }\n}\n\npub trait DependencyExt {\n fn filter_by_tags(&self, include: DependencyTag, exclude: DependencyTag) -> Vec<&Dependency>;\n fn runtime(&self) -> Vec<&Dependency>;\n fn build_time(&self) -> Vec<&Dependency>;\n}\n\nimpl DependencyExt for Vec {\n fn filter_by_tags(&self, include: DependencyTag, exclude: DependencyTag) -> Vec<&Dependency> {\n self.iter()\n .filter(|dep| dep.tags.contains(include) && !dep.tags.intersects(exclude))\n .collect()\n }\n\n fn runtime(&self) -> Vec<&Dependency> {\n // A dependency is runtime if its tags indicate it's needed at runtime.\n // This includes standard runtime, recommended, or optional dependencies.\n // Build-only or Test-only dependencies (without other runtime flags) are excluded.\n self.iter()\n .filter(|dep| {\n dep.tags.intersects(\n DependencyTag::RUNTIME | DependencyTag::RECOMMENDED | DependencyTag::OPTIONAL,\n )\n })\n .collect()\n }\n\n fn build_time(&self) -> Vec<&Dependency> {\n self.filter_by_tags(DependencyTag::BUILD, DependencyTag::empty())\n }\n}\n"], ["/sps/sps-core/src/upgrade/source.rs", "// sps-core/src/upgrade/source.rs\n\nuse std::path::{Path, PathBuf};\n\nuse sps_common::config::Config;\nuse sps_common::error::{Result as SpsResult, SpsError};\nuse sps_common::model::formula::Formula;\nuse tracing::{debug, error};\n\nuse crate::check::installed::InstalledPackageInfo;\nuse crate::{build, uninstall};\n\n/// Upgrades a formula that was/will be installed from source.\n///\n/// This involves:\n/// 1. Uninstalling the old version of the formula.\n/// 2. Building and installing the new version from source.\n/// 3. Linking the new version.\npub async fn upgrade_source_formula(\n formula: &Formula,\n new_source_download_path: &Path,\n old_install_info: &InstalledPackageInfo,\n config: &Config,\n all_installed_dependency_paths: &[PathBuf], // For build environment\n) -> SpsResult {\n debug!(\n \"Upgrading source-built formula {} from {} to {}\",\n formula.name(),\n old_install_info.version,\n formula.version_str_full()\n );\n\n // 1. Uninstall the old version\n debug!(\n \"Uninstalling old source-built version: {} at {}\",\n old_install_info.version,\n old_install_info.path.display()\n );\n let uninstall_opts = uninstall::UninstallOptions { skip_zap: true };\n uninstall::formula::uninstall_formula_artifacts(old_install_info, config, &uninstall_opts)\n .map_err(|e| {\n error!(\n \"Failed to uninstall old version {} of formula {}: {}\",\n old_install_info.version,\n formula.name(),\n e\n );\n SpsError::InstallError(format!(\n \"Failed to uninstall old version during source upgrade of {}: {e}\",\n formula.name()\n ))\n })?;\n debug!(\n \"Successfully uninstalled old source-built version of {}\",\n formula.name()\n );\n\n // 2. Build and install the new version from source\n debug!(\n \"Building new version of {} from source path {}\",\n formula.name(),\n new_source_download_path.display()\n );\n let installed_keg_path = build::compile::build_from_source(\n new_source_download_path,\n formula,\n config,\n all_installed_dependency_paths,\n )\n .await\n .map_err(|e| {\n error!(\n \"Failed to build new version of formula {} from source: {}\",\n formula.name(),\n e\n );\n SpsError::InstallError(format!(\n \"Failed to build new version from source during upgrade of {}: {e}\",\n formula.name()\n ))\n })?;\n debug!(\n \"Successfully built and installed new version of {} to {}\",\n formula.name(),\n installed_keg_path.display()\n );\n\n // 3. Linking is handled by the worker after this function returns the path.\n\n Ok(installed_keg_path)\n}\n"], ["/sps/sps/src/cli/upgrade.rs", "use std::sync::Arc;\n\nuse clap::Args;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_core::check::installed;\n\nuse crate::pipeline::runner::{self, CommandType, PipelineFlags};\n\n#[derive(Args, Debug)]\npub struct UpgradeArgs {\n #[arg()]\n pub names: Vec,\n\n #[arg(long, conflicts_with = \"names\")]\n pub all: bool,\n\n #[arg(long)]\n pub build_from_source: bool,\n}\n\nimpl UpgradeArgs {\n pub async fn run(&self, config: &Config, cache: Arc) -> Result<()> {\n let targets = if self.all {\n // Get all installed package names\n let installed = installed::get_installed_packages(config).await?;\n installed.into_iter().map(|p| p.name).collect()\n } else {\n self.names.clone()\n };\n\n if targets.is_empty() {\n return Ok(());\n }\n\n let flags = PipelineFlags {\n // Populate flags from args\n build_from_source: self.build_from_source,\n // Upgrade should respect original install options ideally,\n // but for now let's default them. This could be enhanced later\n // by reading install receipts.\n include_optional: false,\n skip_recommended: false,\n // ... add other common flags if needed ...\n };\n\n runner::run_pipeline(\n &targets,\n CommandType::Upgrade { all: self.all },\n config,\n cache,\n &flags,\n )\n .await\n }\n}\n"], ["/sps/sps-common/src/pipeline.rs", "// sps-common/src/pipeline.rs\nuse std::path::PathBuf;\nuse std::sync::Arc; // Required for Arc in JobProcessingState\n\nuse serde::{Deserialize, Serialize};\n\nuse crate::dependency::ResolvedGraph; // Needed for planner output\nuse crate::error::SpsError;\nuse crate::model::InstallTargetIdentifier;\n\n// --- Shared Enums / Structs ---\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]\npub enum PipelinePackageType {\n Formula,\n Cask,\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] // Added PartialEq, Eq\npub enum JobAction {\n Install,\n Upgrade {\n from_version: String,\n old_install_path: PathBuf,\n },\n Reinstall {\n version: String,\n current_install_path: PathBuf,\n },\n}\n\n#[derive(Debug, Clone)]\npub struct PlannedJob {\n pub target_id: String,\n pub target_definition: InstallTargetIdentifier,\n pub action: JobAction,\n pub is_source_build: bool,\n pub use_private_store_source: Option,\n}\n\n#[derive(Debug, Clone)]\npub struct WorkerJob {\n pub request: PlannedJob,\n pub download_path: PathBuf,\n pub download_size_bytes: u64,\n pub is_source_from_private_store: bool,\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub enum PipelineEvent {\n PipelineStarted {\n total_jobs: usize,\n },\n PipelineFinished {\n duration_secs: f64,\n success_count: usize,\n fail_count: usize,\n },\n PlanningStarted,\n DependencyResolutionStarted,\n DependencyResolutionFinished,\n PlanningFinished {\n job_count: usize,\n // Optionally, we can pass the ResolvedGraph here if the status handler needs it,\n // but it might be too large for a broadcast event.\n // resolved_graph: Option>, // Example\n },\n DownloadStarted {\n target_id: String,\n url: String,\n },\n DownloadFinished {\n target_id: String,\n path: PathBuf,\n size_bytes: u64,\n },\n DownloadProgressUpdate {\n target_id: String,\n bytes_so_far: u64,\n total_size: Option,\n },\n DownloadCached {\n target_id: String,\n size_bytes: u64,\n },\n DownloadFailed {\n target_id: String,\n url: String,\n error: String, // Keep as String for simplicity in events\n },\n JobProcessingStarted {\n // From core worker\n target_id: String,\n },\n JobDispatchedToCore {\n // New: From runner to UI when job sent to worker pool\n target_id: String,\n },\n UninstallStarted {\n target_id: String,\n version: String,\n },\n UninstallFinished {\n target_id: String,\n version: String,\n },\n BuildStarted {\n target_id: String,\n },\n InstallStarted {\n target_id: String,\n pkg_type: PipelinePackageType,\n },\n LinkStarted {\n target_id: String,\n pkg_type: PipelinePackageType,\n },\n JobSuccess {\n // From core worker\n target_id: String,\n action: JobAction,\n pkg_type: PipelinePackageType,\n },\n JobFailed {\n // From core worker or runner (propagated)\n target_id: String,\n action: JobAction, // Action that was attempted\n error: String, // Keep as String\n },\n LogInfo {\n message: String,\n },\n LogWarn {\n message: String,\n },\n LogError {\n message: String,\n },\n}\n\nimpl PipelineEvent {\n // SpsError kept for internal use, but events use String for error messages\n pub fn job_failed(target_id: String, action: JobAction, error: &SpsError) -> Self {\n PipelineEvent::JobFailed {\n target_id,\n action,\n error: error.to_string(),\n }\n }\n pub fn download_failed(target_id: String, url: String, error: &SpsError) -> Self {\n PipelineEvent::DownloadFailed {\n target_id,\n url,\n error: error.to_string(),\n }\n }\n}\n\n// --- New Structs and Enums for Refactored Runner ---\n\n/// Represents the current processing state of a job in the pipeline.\n#[derive(Debug, Clone)]\npub enum JobProcessingState {\n /// Waiting for download to be initiated.\n PendingDownload,\n /// Download is in progress (managed by DownloadCoordinator).\n Downloading,\n /// Download completed successfully, artifact at PathBuf.\n Downloaded(PathBuf),\n /// Downloaded, but waiting for dependencies to be in Succeeded state.\n WaitingForDependencies(PathBuf),\n /// Dispatched to the core worker pool for installation/processing.\n DispatchedToCore(PathBuf),\n /// Installation/processing is in progress by a core worker.\n Installing(PathBuf), // Path is still relevant\n /// Job completed successfully.\n Succeeded,\n /// Job failed. The String contains the error message. Arc for cheap cloning.\n Failed(Arc),\n}\n\n/// Outcome of a download attempt, sent from DownloadCoordinator to the main runner loop.\n#[derive(Debug)] // Clone not strictly needed if moved\npub struct DownloadOutcome {\n pub planned_job: PlannedJob, // The job this download was for\n pub result: Result, // Path to downloaded file or error\n}\n\n/// Structure returned by the planner, now including the ResolvedGraph.\n#[derive(Debug, Default)]\npub struct PlannedOperations {\n pub jobs: Vec, // Topologically sorted for formulae\n pub errors: Vec<(String, SpsError)>, // Errors from planning phase\n pub already_installed_or_up_to_date: std::collections::HashSet,\n pub resolved_graph: Option>, // Graph for dependency checking in runner\n}\n"], ["/sps/sps/src/cli.rs", "// sps/src/cli.rs\n//! Defines the command-line argument structure using clap.\nuse std::sync::Arc;\n\nuse clap::{ArgAction, Parser, Subcommand};\nuse sps_common::error::Result;\nuse sps_common::{Cache, Config};\n\n// Module declarations\npub mod info;\npub mod init;\npub mod install;\npub mod list;\npub mod reinstall;\npub mod search;\npub mod status;\npub mod uninstall;\npub mod update;\npub mod upgrade;\n// Re-export InitArgs to make it accessible as cli::InitArgs\n// Import other command Args structs\nuse crate::cli::info::Info;\npub use crate::cli::init::InitArgs;\nuse crate::cli::install::InstallArgs;\nuse crate::cli::list::List;\nuse crate::cli::reinstall::ReinstallArgs;\nuse crate::cli::search::Search;\nuse crate::cli::uninstall::Uninstall;\nuse crate::cli::update::Update;\nuse crate::cli::upgrade::UpgradeArgs;\n\n#[derive(Parser, Debug)]\n#[command(author, version, about, long_about = None, name = \"sps\", bin_name = \"sps\")]\n#[command(propagate_version = true)]\npub struct CliArgs {\n #[arg(short, long, action = ArgAction::Count, global = true)]\n pub verbose: u8,\n\n #[command(subcommand)]\n pub command: Command,\n}\n\n#[derive(Subcommand, Debug)]\npub enum Command {\n Init(InitArgs),\n Search(Search),\n List(List),\n Info(Info),\n Update(Update),\n Install(InstallArgs),\n Uninstall(Uninstall),\n Reinstall(ReinstallArgs),\n Upgrade(UpgradeArgs),\n}\n\nimpl Command {\n pub async fn run(&self, config: &Config, cache: Arc) -> Result<()> {\n match self {\n Self::Init(command) => command.run(config).await,\n Self::Search(command) => command.run(config, cache).await,\n Self::List(command) => command.run(config, cache).await,\n Self::Info(command) => command.run(config, cache).await,\n Self::Update(command) => command.run(config, cache).await,\n // Commands that use the pipeline\n Self::Install(command) => command.run(config, cache).await,\n Self::Reinstall(command) => command.run(config, cache).await,\n Self::Upgrade(command) => command.run(config, cache).await,\n Self::Uninstall(command) => command.run(config, cache).await,\n }\n }\n}\n\n// In install.rs, reinstall.rs, upgrade.rs, their run methods will now call\n// sps::cli::pipeline_runner::run_pipeline(...)\n// e.g., in sps/src/cli/install.rs:\n// use crate::cli::pipeline_runner::{self, CommandType, PipelineFlags};\n// ...\n// pipeline_runner::run_pipeline(&initial_targets, CommandType::Install, config, cache,\n// &flags).await\n"], ["/sps/sps/src/cli/reinstall.rs", "// sps-cli/src/cli/reinstall.rs\nuse std::sync::Arc;\n\nuse clap::Args;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::error::Result;\n\nuse crate::pipeline::runner::{self, CommandType, PipelineFlags};\n\n#[derive(Args, Debug)]\npub struct ReinstallArgs {\n #[arg(required = true)]\n pub names: Vec,\n\n #[arg(\n long,\n help = \"Force building the formula from source, even if a bottle is available\"\n )]\n pub build_from_source: bool,\n}\n\nimpl ReinstallArgs {\n pub async fn run(&self, config: &Config, cache: Arc) -> Result<()> {\n let flags = PipelineFlags {\n // Populate flags from args\n build_from_source: self.build_from_source,\n include_optional: false, // Reinstall usually doesn't change optional deps\n skip_recommended: true, /* Reinstall usually doesn't change recommended deps\n * ... add other common flags if needed ... */\n };\n runner::run_pipeline(&self.names, CommandType::Reinstall, config, cache, &flags).await\n }\n}\n"], ["/sps/sps-net/src/lib.rs", "// spm-fetch/src/lib.rs\npub mod api;\npub mod http;\npub mod oci;\npub mod validation;\n\n// Re-export necessary types from sps-core IF using Option A from Step 3\n// If using Option B (DTOs), you wouldn't depend on sps-core here for models.\n// Re-export the public fetching functions - ensure they are `pub`\npub use api::{\n fetch_all_casks, fetch_all_formulas, fetch_cask, fetch_formula, get_cask, /* ... */\n get_formula,\n};\npub use http::{fetch_formula_source_or_bottle, fetch_resource /* ... */};\npub use oci::{build_oci_client /* ... */, download_oci_blob, fetch_oci_manifest_index};\npub use sps_common::{\n model::{\n cask::{Sha256Field, UrlField},\n formula::ResourceSpec,\n Cask, Formula,\n }, // Example types needed\n {\n cache::Cache,\n error::{Result, SpsError},\n Config,\n }, // Need Config, Result, SpsError, Cache\n};\n\npub use crate::validation::{validate_url, verify_checksum, verify_content_type /* ... */};\n"], ["/sps/sps-common/src/model/artifact.rs", "// sps-common/src/model/artifact.rs\nuse std::path::PathBuf;\n\nuse serde::{Deserialize, Serialize};\n\n/// Represents an item installed or managed by sps, recorded in the manifest.\n#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)] // Added Hash\n#[serde(tag = \"type\", rename_all = \"snake_case\")]\npub enum InstalledArtifact {\n /// The main application bundle (e.g., in /Applications).\n AppBundle { path: PathBuf },\n /// A command-line binary symlinked into the prefix's bin dir.\n BinaryLink {\n link_path: PathBuf,\n target_path: PathBuf,\n },\n /// A man page symlinked into the prefix's man dir.\n ManpageLink {\n link_path: PathBuf,\n target_path: PathBuf,\n },\n /// A resource moved to a standard system/user location (e.g., Font, PrefPane).\n MovedResource { path: PathBuf },\n /// A macOS package receipt ID managed by pkgutil.\n PkgUtilReceipt { id: String },\n /// A launchd service (Agent/Daemon).\n Launchd {\n label: String,\n path: Option,\n }, // Path is the plist file\n /// A symlink created within the Caskroom pointing to the actual installed artifact.\n /// Primarily for internal reference and potentially easier cleanup if needed.\n CaskroomLink {\n link_path: PathBuf,\n target_path: PathBuf,\n },\n /// A file copied *into* the Caskroom (e.g., a .pkg installer).\n CaskroomReference { path: PathBuf },\n}\n\n// Optional: Helper methods if needed\n// impl InstalledArtifact { ... }\n"], ["/sps/sps-common/src/error.rs", "use std::sync::Arc;\n\nuse thiserror::Error;\n\n#[derive(Error, Debug, Clone)]\npub enum SpsError {\n #[error(\"I/O Error: {0}\")]\n Io(#[from] Arc),\n\n #[error(\"HTTP Request Error: {0}\")]\n Http(#[from] Arc),\n\n #[error(\"JSON Parsing Error: {0}\")]\n Json(#[from] Arc),\n\n #[error(\"Semantic Versioning Error: {0}\")]\n SemVer(#[from] Arc),\n\n #[error(\"Object File Error: {0}\")]\n Object(#[from] Arc),\n\n #[error(\"Configuration Error: {0}\")]\n Config(String),\n\n #[error(\"API Error: {0}\")]\n Api(String),\n\n #[error(\"API Request Error: {0}\")]\n ApiRequestError(String),\n\n #[error(\"DownloadError: Failed to download '{0}' from '{1}': {2}\")]\n DownloadError(String, String, String),\n\n #[error(\"Cache Error: {0}\")]\n Cache(String),\n\n #[error(\"Resource Not Found: {0}\")]\n NotFound(String),\n\n #[error(\"Installation Error: {0}\")]\n InstallError(String),\n\n #[error(\"Generic Error: {0}\")]\n Generic(String),\n\n #[error(\"HttpError: {0}\")]\n HttpError(String),\n\n #[error(\"Checksum Mismatch: {0}\")]\n ChecksumMismatch(String),\n\n #[error(\"Validation Error: {0}\")]\n ValidationError(String),\n\n #[error(\"Checksum Error: {0}\")]\n ChecksumError(String),\n\n #[error(\"Parsing Error in {0}: {1}\")]\n ParseError(&'static str, String),\n\n #[error(\"Version error: {0}\")]\n VersionError(String),\n\n #[error(\"Dependency Error: {0}\")]\n DependencyError(String),\n\n #[error(\"Build environment setup failed: {0}\")]\n BuildEnvError(String),\n\n #[error(\"IoError: {0}\")]\n IoError(String),\n\n #[error(\"Failed to execute command: {0}\")]\n CommandExecError(String),\n\n #[error(\"Mach-O Error: {0}\")]\n MachOError(String),\n\n #[error(\"Mach-O Modification Error: {0}\")]\n MachOModificationError(String),\n\n #[error(\"Mach-O Relocation Error: Path too long - {0}\")]\n PathTooLongError(String),\n\n #[error(\"Codesign Error: {0}\")]\n CodesignError(String),\n}\n\nimpl From for SpsError {\n fn from(err: std::io::Error) -> Self {\n SpsError::Io(Arc::new(err))\n }\n}\n\nimpl From for SpsError {\n fn from(err: reqwest::Error) -> Self {\n SpsError::Http(Arc::new(err))\n }\n}\n\nimpl From for SpsError {\n fn from(err: serde_json::Error) -> Self {\n SpsError::Json(Arc::new(err))\n }\n}\n\nimpl From for SpsError {\n fn from(err: semver::Error) -> Self {\n SpsError::SemVer(Arc::new(err))\n }\n}\n\nimpl From for SpsError {\n fn from(err: object::read::Error) -> Self {\n SpsError::Object(Arc::new(err))\n }\n}\n\npub type Result = std::result::Result;\n"], ["/sps/sps-core/src/install/mod.rs", "// ===== sps-core/src/build/mod.rs =====\n// Main module for build functionality\n// Removed deprecated functions and re-exports.\n\nuse std::path::PathBuf;\n\nuse sps_common::config::Config;\nuse sps_common::model::formula::Formula;\n\n// --- Submodules ---\npub mod bottle;\npub mod cask;\npub mod devtools;\npub mod extract;\n\n// --- Path helpers using Config ---\npub fn get_formula_opt_path(formula: &Formula, config: &Config) -> PathBuf {\n // Use new Config method\n config.formula_opt_path(formula.name())\n}\n\n// --- DEPRECATED EXTRACTION FUNCTIONS REMOVED ---\n"], ["/sps/sps-common/src/model/mod.rs", "// src/model/mod.rs\n// Declares the modules within the model directory.\nuse std::sync::Arc;\n\npub mod artifact;\npub mod cask;\npub mod formula;\npub mod tap;\npub mod version;\n\n// Re-export\npub use artifact::InstalledArtifact;\npub use cask::Cask;\npub use formula::Formula;\n\n#[derive(Debug, Clone)]\npub enum InstallTargetIdentifier {\n Formula(Arc),\n Cask(Arc),\n}\n"], ["/sps/sps-common/src/dependency/requirement.rs", "// **File:** sps-core/src/dependency/requirement.rs (New file)\nuse std::fmt;\n\nuse serde::{Deserialize, Serialize};\n\n#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]\npub enum Requirement {\n MacOS(String),\n Xcode(String),\n Other(String),\n}\n\nimpl fmt::Display for Requirement {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n match self {\n Self::MacOS(v) => write!(f, \"macOS >= {v}\"),\n Self::Xcode(v) => write!(f, \"Xcode >= {v}\"),\n Self::Other(s) => write!(f, \"Requirement: {s}\"),\n }\n }\n}\n"], ["/sps/sps-core/src/uninstall/mod.rs", "// sps-core/src/uninstall/mod.rs\n\npub mod cask;\npub mod common;\npub mod formula;\n\n// Re-export key functions and types\npub use cask::{uninstall_cask_artifacts, zap_cask_artifacts};\npub use common::UninstallOptions;\npub use formula::uninstall_formula_artifacts;\n"], ["/sps/sps-core/src/upgrade/mod.rs", "// sps-core/src/upgrade/mod.rs\n\npub mod bottle;\npub mod cask;\npub mod source;\n\n// Re-export key upgrade functions\npub use self::bottle::upgrade_bottle_formula;\npub use self::cask::upgrade_cask_package;\npub use self::source::upgrade_source_formula;\n"], ["/sps/sps-common/src/lib.rs", "// sps-common/src/lib.rs\npub mod cache;\npub mod config;\npub mod dependency;\npub mod error;\npub mod formulary;\npub mod keg;\npub mod model;\npub mod pipeline;\n// Optional: pub mod dependency_def;\n\n// Re-export key types\npub use cache::Cache;\npub use config::Config;\npub use error::{Result, SpsError};\npub use model::{Cask, Formula, InstalledArtifact}; // etc.\n // Optional: pub use dependency_def::{Dependency, DependencyTag};\n"], ["/sps/sps-core/src/lib.rs", "// sps-core/src/lib.rs\n\n// Declare the top-level modules within the library crate\npub mod build;\npub mod check;\npub mod install;\npub mod pipeline;\npub mod uninstall;\npub mod upgrade; // New\n#[cfg(target_os = \"macos\")]\npub mod utils; // New\n //pub mod utils;\n\n// Re-export key types for easier use by the CLI crate\n// Define InstallTargetIdentifier here or ensure it's public from cli/pipeline\n// For simplicity, let's define it here for now:\n\n// New\npub use uninstall::UninstallOptions; // New\n // New\n"], ["/sps/sps-common/src/dependency/mod.rs", "pub mod definition; // Renamed from 'dependency'\npub mod requirement;\npub mod resolver;\n\n// Re-export key types for easier access\npub use definition::{Dependency, DependencyExt, DependencyTag}; // Updated source module\npub use requirement::Requirement;\npub use resolver::{\n DependencyResolver, ResolutionContext, ResolutionStatus, ResolvedDependency, ResolvedGraph,\n};\n"], ["/sps/sps-core/src/install/cask/artifacts/mod.rs", "pub mod app;\npub mod audio_unit_plugin;\npub mod binary;\npub mod colorpicker;\npub mod dictionary;\npub mod font;\npub mod input_method;\npub mod installer;\npub mod internet_plugin;\npub mod keyboard_layout;\npub mod manpage;\npub mod mdimporter;\npub mod pkg;\npub mod preflight;\npub mod prefpane;\npub mod qlplugin;\npub mod screen_saver;\npub mod service;\npub mod suite;\npub mod uninstall;\npub mod vst3_plugin;\npub mod vst_plugin;\npub mod zap;\n\n// Re‑export a single enum if you like:\npub use self::app::install_app_from_staged;\npub use self::audio_unit_plugin::install_audio_unit_plugin;\npub use self::binary::install_binary;\npub use self::colorpicker::install_colorpicker;\npub use self::dictionary::install_dictionary;\npub use self::font::install_font;\npub use self::input_method::install_input_method;\npub use self::installer::run_installer;\npub use self::internet_plugin::install_internet_plugin;\npub use self::keyboard_layout::install_keyboard_layout;\npub use self::manpage::install_manpage;\npub use self::mdimporter::install_mdimporter;\npub use self::pkg::install_pkg_from_path;\npub use self::preflight::run_preflight;\npub use self::prefpane::install_prefpane;\npub use self::qlplugin::install_qlplugin;\npub use self::screen_saver::install_screen_saver;\npub use self::service::install_service;\npub use self::suite::install_suite;\npub use self::uninstall::record_uninstall;\npub use self::vst3_plugin::install_vst3_plugin;\npub use self::vst_plugin::install_vst_plugin;\n"], ["/sps/sps-core/src/utils/mod.rs", "#[cfg(target_os = \"macos\")]\npub mod applescript;\n#[cfg(target_os = \"macos\")]\npub mod xattr;\n"], ["/sps/sps-core/src/check/mod.rs", "pub mod installed;\npub mod update;\n\npub use installed::{InstalledPackageInfo, PackageType};\npub use update::UpdateInfo;\n"], ["/sps/sps/src/pipeline.rs", "pub mod downloader;\npub mod planner;\npub mod runner;\n"], ["/sps/sps-core/src/pipeline/mod.rs", "pub mod engine;\npub mod worker;\n"]], "task_instance_info": {"created_time": "2025-08-21 01:45:07", "created_task_model": "DeepSeek-R1", "function_skeleton": "fn print_formula_info (_name: &str, formula: &Value) {}", "code_description": "This code segment functions to: Format and display structured package metadata by extracting key attributes, organizing them into categorized tables, and generating human-readable output with visual emphasis on section headers and dependency relationships."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```rust\n[TASK_BEGIN]\nfn print_formula_info(name: &str, formula: &Value) {\n // Header\n println!(\"{}\", format!(\"Formula: {name}\").green().bold());\n\n // Main info table\n let mut table = prettytable::Table::new();\n table.set_format(*prettytable::format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n\n if let Some(formula_name) = formula.get(\"name\").and_then(Value::as_str) {\n table.add_row(prettytable::row![\"Name\", formula_name]);\n }\n\n if let Some(desc) = formula.get(\"desc\").and_then(|d| d.as_str()) {\n table.add_row(prettytable::row![\"Description\", desc]);\n }\n\n if let Some(homepage) = formula.get(\"homepage\").and_then(|h| h.as_str()) {\n table.add_row(prettytable::row![\"Homepage\", homepage]);\n }\n\n if let Some(version) = formula.get(\"versions\")\n .and_then(|v| v.get(\"stable\"))\n .and_then(Value::as_str) \n {\n table.add_row(prettytable::row![\"Stable Version\", version]);\n }\n\n if let Some(url) = formula.get(\"url\").and_then(|u| u.as_str()) {\n table.add_row(prettytable::row![\"URL\", url]);\n }\n\n if let Some(license) = formula.get(\"license\").and_then(|l| l.as_str()) {\n table.add_row(prettytable::row![\"License\", license]);\n }\n\n if formula.get(\"bottle\").is_some() {\n table.add_row(prettytable::row![\"Bottled\", \"Yes\".green()]);\n }\n\n table.printstd();\n\n // Dependencies Section\n if let Some(deps) = formula.get(\"dependencies\").and_then(|d| d.as_array()) {\n if !deps.is_empty() {\n println!(\"\\n{}\", \"Dependencies\".blue().bold());\n let dep_list = deps\n .iter()\n .filter_map(|v| v.as_str())\n .collect::>()\n .join(\", \");\n println!(\" {}\", dep_list);\n }\n }\n\n // Installation hint\n println!(\"\\n{}\", \"Installation\".blue().bold());\n println!(\" {} install {}\", \"sps\".cyan(), name);\n}\n[TASK_END]\n```", "inference_time": "2025-08-21 01-46-04"}, "editdistance_info": {"edit_distance": 22.403, "calculate_time": "2025-08-21 01:46:04", "true_code_clean": "fn print_formula_info(_name: &str, formula: &Value) {\n let full_name = formula\n .get(\"full_name\")\n .and_then(|f| f.as_str())\n .unwrap_or(\"N/A\");\n let version = formula\n .get(\"versions\")\n .and_then(|v| v.get(\"stable\"))\n .and_then(|s| s.as_str())\n .unwrap_or(\"N/A\");\n let revision = formula\n .get(\"revision\")\n .and_then(|r| r.as_u64())\n .unwrap_or(0);\n let version_str = if revision > 0 {\n format!(\"{version}_{revision}\")\n } else {\n version.to_string()\n };\n let license = formula\n .get(\"license\")\n .and_then(|l| l.as_str())\n .unwrap_or(\"N/A\");\n let homepage = formula\n .get(\"homepage\")\n .and_then(|h| h.as_str())\n .unwrap_or(\"N/A\");\n println!(\"{}\", format!(\"Formula: {full_name}\").green().bold());\n let mut table = prettytable::Table::new();\n table.set_format(*prettytable::format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n table.add_row(prettytable::row![\"Version\", version_str]);\n table.add_row(prettytable::row![\"License\", license]);\n table.add_row(prettytable::row![\"Homepage\", homepage]);\n table.printstd();\n if let Some(desc) = formula.get(\"desc\").and_then(|d| d.as_str()) {\n if !desc.is_empty() {\n println!(\"\\n{}\", \"Description\".blue().bold());\n println!(\"{desc}\");\n }\n }\n if let Some(caveats) = formula.get(\"caveats\").and_then(|c| c.as_str()) {\n if !caveats.is_empty() {\n println!(\"\\n{}\", \"Caveats\".blue().bold());\n println!(\"{caveats}\");\n }\n }\n let mut dep_table = prettytable::Table::new();\n dep_table.set_format(*prettytable::format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n let mut has_deps = false;\n let mut add_deps = |title: &str, key: &str, tag: &str| {\n if let Some(deps) = formula.get(key).and_then(|d| d.as_array()) {\n let dep_list: Vec<&str> = deps.iter().filter_map(|d| d.as_str()).collect();\n if !dep_list.is_empty() {\n has_deps = true;\n for (i, d) in dep_list.iter().enumerate() {\n let display_title = if i == 0 { title } else { \"\" };\n let display_tag = if i == 0 {\n format!(\"({tag})\")\n } else {\n \"\".to_string()\n };\n dep_table.add_row(prettytable::row![display_title, d, display_tag]);\n }\n }\n }\n };\n add_deps(\"Required\", \"dependencies\", \"runtime\");\n add_deps(\n \"Recommended\",\n \"recommended_dependencies\",\n \"runtime, recommended\",\n );\n add_deps(\"Optional\", \"optional_dependencies\", \"runtime, optional\");\n add_deps(\"Build\", \"build_dependencies\", \"build\");\n add_deps(\"Test\", \"test_dependencies\", \"test\");\n if has_deps {\n println!(\"\\n{}\", \"Dependencies\".blue().bold());\n dep_table.printstd();\n }\n println!(\"\\n{}\", \"Installation\".blue().bold());\n println!(\n \" {} install {}\",\n \"sps\".cyan(),\n formula\n .get(\"name\")\n .and_then(|n| n.as_str())\n .unwrap_or(full_name) \n );\n}", "predict_code_clean": "fn print_formula_info(name: &str, formula: &Value) {\n println!(\"{}\", format!(\"Formula: {name}\").green().bold());\n let mut table = prettytable::Table::new();\n table.set_format(*prettytable::format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n if let Some(formula_name) = formula.get(\"name\").and_then(Value::as_str) {\n table.add_row(prettytable::row![\"Name\", formula_name]);\n }\n if let Some(desc) = formula.get(\"desc\").and_then(|d| d.as_str()) {\n table.add_row(prettytable::row![\"Description\", desc]);\n }\n if let Some(homepage) = formula.get(\"homepage\").and_then(|h| h.as_str()) {\n table.add_row(prettytable::row![\"Homepage\", homepage]);\n }\n if let Some(version) = formula.get(\"versions\")\n .and_then(|v| v.get(\"stable\"))\n .and_then(Value::as_str) \n {\n table.add_row(prettytable::row![\"Stable Version\", version]);\n }\n if let Some(url) = formula.get(\"url\").and_then(|u| u.as_str()) {\n table.add_row(prettytable::row![\"URL\", url]);\n }\n if let Some(license) = formula.get(\"license\").and_then(|l| l.as_str()) {\n table.add_row(prettytable::row![\"License\", license]);\n }\n if formula.get(\"bottle\").is_some() {\n table.add_row(prettytable::row![\"Bottled\", \"Yes\".green()]);\n }\n table.printstd();\n if let Some(deps) = formula.get(\"dependencies\").and_then(|d| d.as_array()) {\n if !deps.is_empty() {\n println!(\"\\n{}\", \"Dependencies\".blue().bold());\n let dep_list = deps\n .iter()\n .filter_map(|v| v.as_str())\n .collect::>()\n .join(\", \");\n println!(\" {}\", dep_list);\n }\n }\n println!(\"\\n{}\", \"Installation\".blue().bold());\n println!(\" {} install {}\", \"sps\".cyan(), name);\n}"}} {"repo_name": "sps", "file_name": "/sps/sps-core/src/install/cask/artifacts/suite.rs", "inference_info": {"prefix_code": "// src/build/cask/artifacts/suite.rs\n\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Implements the `suite` stanza by moving each named directory from\n/// the staging area into `/Applications`, then symlinking it in the Caskroom.\n///\n/// Mirrors Homebrew’s Suite < Moved behavior (dirmethod :appdir)\n/// :contentReference[oaicite:3]{index=3}\n", "suffix_code": "\n", "middle_code": "pub fn install_suite(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def.iter() {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"suite\").and_then(|v| v.as_array()) {\n for entry in entries {\n if let Some(dir_name) = entry.as_str() {\n let src = stage_path.join(dir_name);\n if !src.exists() {\n debug!(\n \"Suite directory '{}' not found in staging, skipping\",\n dir_name\n );\n continue;\n }\n let dest_dir = config.applications_dir(); \n let dest = dest_dir.join(dir_name); \n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n debug!(\"Moving suite '{}' → '{}'\", src.display(), dest.display());\n let mv_status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !mv_status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n installed.push(InstalledArtifact::AppBundle { path: dest.clone() });\n let link = cask_version_install_path.join(dir_name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; \n }\n }\n }\n }\n Ok(installed)\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "rust", "sub_task_type": null}, "context_code": [["/sps/sps-core/src/install/cask/artifacts/dictionary.rs", "// ===== sps-core/src/build/cask/artifacts/dictionary.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Implements the `dictionary` stanza by moving each declared\n/// `.dictionary` bundle from the staging area into `~/Library/Dictionaries`,\n/// then symlinking it in the Caskroom.\n///\n/// Homebrew’s Ruby definition is simply:\n/// ```ruby\n/// class Dictionary < Moved; end\n/// ```\n/// :contentReference[oaicite:2]{index=2}\npub fn install_dictionary(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n // Find any `dictionary` arrays in the raw JSON artifacts\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"dictionary\").and_then(|v| v.as_array()) {\n for entry in entries {\n if let Some(bundle_name) = entry.as_str() {\n let src = stage_path.join(bundle_name);\n if !src.exists() {\n debug!(\n \"Dictionary bundle '{}' not found in staging; skipping\",\n bundle_name\n );\n continue;\n }\n\n // Standard user dictionary directory: ~/Library/Dictionaries\n // :contentReference[oaicite:3]{index=3}\n let dest_dir = config\n .home_dir() // e.g. /Users/alxknt\n .join(\"Library\")\n .join(\"Dictionaries\");\n fs::create_dir_all(&dest_dir)?;\n\n let dest = dest_dir.join(bundle_name);\n // Remove any previous install\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Moving dictionary '{}' → '{}'\",\n src.display(),\n dest.display()\n );\n // Try a direct move; fall back to recursive copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record the moved bundle\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink back into Caskroom for reference\n let link = cask_version_install_path.join(bundle_name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // Only one `dictionary` stanza per cask\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/colorpicker.rs", "// ===== sps-core/src/build/cask/artifacts/colorpicker.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Installs any `colorpicker` stanzas from the Cask definition.\n///\n/// Homebrew’s `Colorpicker` artifact simply subclasses `Moved` with\n/// `dirmethod :colorpickerdir` → `~/Library/ColorPickers` :contentReference[oaicite:3]{index=3}.\npub fn install_colorpicker(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"colorpicker\").and_then(|v| v.as_array()) {\n // For each declared bundle name:\n for entry in entries {\n if let Some(bundle_name) = entry.as_str() {\n let src = stage_path.join(bundle_name);\n if !src.exists() {\n debug!(\n \"Colorpicker bundle '{}' not found in stage; skipping\",\n bundle_name\n );\n continue;\n }\n\n // Ensure ~/Library/ColorPickers exists\n // :contentReference[oaicite:4]{index=4}\n let dest_dir = config\n .home_dir() // e.g. /Users/alxknt\n .join(\"Library\")\n .join(\"ColorPickers\");\n fs::create_dir_all(&dest_dir)?;\n\n let dest = dest_dir.join(bundle_name);\n // Remove any previous copy\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Moving colorpicker '{}' → '{}'\",\n src.display(),\n dest.display()\n );\n // mv, fallback to cp -R if necessary (cross‑device)\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record as a moved artifact (bundle installed)\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink back into Caskroom for reference\n // :contentReference[oaicite:5]{index=5}\n let link = cask_version_install_path.join(bundle_name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // only one `colorpicker` stanza per cask\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/prefpane.rs", "// ===== sps-core/src/build/cask/artifacts/prefpane.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Implements the `prefpane` stanza by moving each declared\n/// preference pane bundle from the staging area into\n/// `~/Library/PreferencePanes`, then symlinking it in the Caskroom.\n///\n/// Mirrors Homebrew’s `Prefpane < Moved` pattern.\npub fn install_prefpane(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n // Look for \"prefpane\" entries in the JSON artifacts\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"prefpane\").and_then(|v| v.as_array()) {\n // Target directory for user preference panes\n let dest_dir = config.home_dir().join(\"Library\").join(\"PreferencePanes\");\n fs::create_dir_all(&dest_dir)?;\n\n for entry in entries {\n if let Some(bundle_name) = entry.as_str() {\n let src = stage_path.join(bundle_name);\n if !src.exists() {\n debug!(\n \"Preference pane '{}' not found in staging; skipping\",\n bundle_name\n );\n continue;\n }\n\n let dest = dest_dir.join(bundle_name);\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Installing prefpane '{}' → '{}'\",\n src.display(),\n dest.display()\n );\n // Try move, fallback to copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record moved bundle\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink into Caskroom for reference\n let link = cask_version_install_path.join(bundle_name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // single stanza\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/font.rs", "// ===== sps-core/src/build/cask/artifacts/font.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Implements the `font` stanza by moving each declared\n/// font file or directory from the staging area into\n/// `~/Library/Fonts`, then symlinking it in the Caskroom.\n///\n/// Mirrors Homebrew’s `Dictionary < Moved` and `Colorpicker < Moved` pattern.\npub fn install_font(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n // Look for \"font\" entries in the JSON artifacts\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"font\").and_then(|v| v.as_array()) {\n // Target directory for user fonts\n let dest_dir = config.home_dir().join(\"Library\").join(\"Fonts\");\n fs::create_dir_all(&dest_dir)?;\n\n for entry in entries {\n if let Some(name) = entry.as_str() {\n let src = stage_path.join(name);\n if !src.exists() {\n debug!(\"Font '{}' not found in staging; skipping\", name);\n continue;\n }\n\n let dest = dest_dir.join(name);\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\"Installing font '{}' → '{}'\", src.display(), dest.display());\n // Try move, fallback to copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record moved font\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink into Caskroom for reference\n let link = cask_version_install_path.join(name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // single font stanza per cask\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/service.rs", "// ===== sps-core/src/build/cask/artifacts/service.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers;\n\n/// Installs `service` artifacts by moving each declared\n/// Automator workflow or service bundle from the staging area into\n/// `~/Library/Services`, then symlinking it in the Caskroom.\n///\n/// Mirrors Homebrew’s `Service < Moved` behavior.\npub fn install_service(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"service\").and_then(|v| v.as_array()) {\n // Target directory for user Services\n let dest_dir = config.home_dir().join(\"Library\").join(\"Services\");\n fs::create_dir_all(&dest_dir)?;\n\n for entry in entries {\n if let Some(bundle_name) = entry.as_str() {\n let src = stage_path.join(bundle_name);\n if !src.exists() {\n debug!(\n \"Service bundle '{}' not found in staging; skipping\",\n bundle_name\n );\n continue;\n }\n\n let dest = dest_dir.join(bundle_name);\n if dest.exists() {\n let _ = helpers::remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Installing service '{}' → '{}'\",\n src.display(),\n dest.display()\n );\n // Try move, fallback to copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record moved service\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink into Caskroom for reference\n let link = cask_version_install_path.join(bundle_name);\n let _ = helpers::remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // one stanza only\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/internet_plugin.rs", "// ===== sps-core/src/build/cask/artifacts/internet_plugin.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Implements the `internet_plugin` stanza by moving each declared\n/// internet plugin bundle from the staging area into\n/// `~/Library/Internet Plug-Ins`, then symlinking it in the Caskroom.\n///\n/// Mirrors Homebrew’s `InternetPlugin < Moved` pattern.\npub fn install_internet_plugin(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n // Look for \"internet_plugin\" entries in the JSON artifacts\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"internet_plugin\").and_then(|v| v.as_array()) {\n // Target directory for user internet plugins\n let dest_dir = config.home_dir().join(\"Library\").join(\"Internet Plug-Ins\");\n fs::create_dir_all(&dest_dir)?;\n\n for entry in entries {\n if let Some(name) = entry.as_str() {\n let src = stage_path.join(name);\n if !src.exists() {\n debug!(\"Internet plugin '{}' not found in staging; skipping\", name);\n continue;\n }\n\n let dest = dest_dir.join(name);\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Installing internet plugin '{}' → '{}'\",\n src.display(),\n dest.display()\n );\n // Try move, fallback to copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record moved plugin\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink into Caskroom for reference\n let link = cask_version_install_path.join(name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // single stanza\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/vst3_plugin.rs", "// ===== sps-core/src/build/cask/artifacts/vst3_plugin.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Installs `vst3_plugin` bundles from the staging area into\n/// `~/Library/Audio/Plug-Ins/VST3`, then symlinks them into the Caskroom.\n///\n/// Mirrors Homebrew’s `Vst3Plugin < Moved` pattern.\npub fn install_vst3_plugin(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"vst3_plugin\").and_then(|v| v.as_array()) {\n // Target directory for VST3 plugins\n let dest_dir = config\n .home_dir()\n .join(\"Library\")\n .join(\"Audio\")\n .join(\"Plug-Ins\")\n .join(\"VST3\");\n fs::create_dir_all(&dest_dir)?;\n\n for entry in entries {\n if let Some(bundle_name) = entry.as_str() {\n let src = stage_path.join(bundle_name);\n if !src.exists() {\n debug!(\n \"VST3 plugin '{}' not found in staging; skipping\",\n bundle_name\n );\n continue;\n }\n\n let dest = dest_dir.join(bundle_name);\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Installing VST3 plugin '{}' → '{}'\",\n src.display(),\n dest.display()\n );\n // Try move, fallback to copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record moved plugin\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink into Caskroom for reference\n let link = cask_version_install_path.join(bundle_name);\n let _ = crate::install::cask::helpers::remove_path_robustly(\n &link, config, true,\n );\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // single stanza\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/qlplugin.rs", "// ===== sps-core/src/build/cask/artifacts/qlplugin.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Installs `qlplugin` bundles from the staging area into\n/// `~/Library/QuickLook`, then symlinks them into the Caskroom.\n///\n/// Mirrors Homebrew’s `QuickLook < Moved` pattern for QuickLook plugins.\npub fn install_qlplugin(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n // Look for \"qlplugin\" entries in the JSON artifacts\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"qlplugin\").and_then(|v| v.as_array()) {\n // Target directory for QuickLook plugins\n let dest_dir = config.home_dir().join(\"Library\").join(\"QuickLook\");\n fs::create_dir_all(&dest_dir)?;\n\n for entry in entries {\n if let Some(bundle_name) = entry.as_str() {\n let src = stage_path.join(bundle_name);\n if !src.exists() {\n debug!(\n \"QuickLook plugin '{}' not found in staging; skipping\",\n bundle_name\n );\n continue;\n }\n\n let dest = dest_dir.join(bundle_name);\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Installing QuickLook plugin '{}' → '{}',\",\n src.display(),\n dest.display()\n );\n // Try move, fallback to copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record moved plugin\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink into Caskroom for reference\n let link = cask_version_install_path.join(bundle_name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // single stanza\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/screen_saver.rs", "// ===== sps-core/src/build/cask/artifacts/screen_saver.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Installs `screen_saver` bundles from the staging area into\n/// `~/Library/Screen Savers`, then symlinks them into the Caskroom.\n///\n/// Mirrors Homebrew’s `ScreenSaver < Moved` pattern.\npub fn install_screen_saver(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"screen_saver\").and_then(|v| v.as_array()) {\n // Target directory for user screen savers\n let dest_dir = config.home_dir().join(\"Library\").join(\"Screen Savers\");\n fs::create_dir_all(&dest_dir)?;\n\n for entry in entries {\n if let Some(bundle_name) = entry.as_str() {\n let src = stage_path.join(bundle_name);\n if !src.exists() {\n debug!(\n \"Screen saver '{}' not found in staging; skipping\",\n bundle_name\n );\n continue;\n }\n\n let dest = dest_dir.join(bundle_name);\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Installing screen saver '{}' → '{}',\",\n src.display(),\n dest.display()\n );\n // Try move, fallback to copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record moved screen saver\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink into Caskroom for reference\n let link = cask_version_install_path.join(bundle_name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // single stanza\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/mdimporter.rs", "// ===== sps-core/src/build/cask/artifacts/mdimporter.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Installs `mdimporter` bundles from the staging area into\n/// `~/Library/Spotlight`, then symlinks them into the Caskroom,\n/// and reloads them via `mdimport -r` so Spotlight picks them up.\n///\n/// Mirrors Homebrew’s `Mdimporter < Moved` behavior.\npub fn install_mdimporter(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"mdimporter\").and_then(|v| v.as_array()) {\n // Target directory for user Spotlight importers\n let dest_dir = config.home_dir().join(\"Library\").join(\"Spotlight\");\n fs::create_dir_all(&dest_dir)?;\n\n for entry in entries {\n if let Some(bundle_name) = entry.as_str() {\n let src = stage_path.join(bundle_name);\n if !src.exists() {\n debug!(\n \"Mdimporter bundle '{}' not found in staging; skipping\",\n bundle_name\n );\n continue;\n }\n\n let dest = dest_dir.join(bundle_name);\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Installing mdimporter '{}' → '{}',\",\n src.display(),\n dest.display()\n );\n // Try move, fallback to copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record moved importer\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink for reference\n let link = cask_version_install_path.join(bundle_name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n\n // Reload Spotlight importer so it's picked up immediately\n debug!(\"Reloading Spotlight importer: {}\", dest.display());\n let _ = Command::new(\"/usr/bin/mdimport\")\n .arg(\"-r\")\n .arg(&dest)\n .status();\n }\n }\n break; // one stanza only\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/vst_plugin.rs", "// ===== sps-core/src/build/cask/artifacts/vst_plugin.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Installs `vst_plugin` bundles from the staging area into\n/// `~/Library/Audio/Plug-Ins/VST`, then symlinks them into the Caskroom.\n///\n/// Mirrors Homebrew’s `VstPlugin < Moved` pattern.\npub fn install_vst_plugin(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"vst_plugin\").and_then(|v| v.as_array()) {\n // Target directory for VST plugins\n let dest_dir = config\n .home_dir()\n .join(\"Library\")\n .join(\"Audio\")\n .join(\"Plug-Ins\")\n .join(\"VST\");\n fs::create_dir_all(&dest_dir)?;\n\n for entry in entries {\n if let Some(bundle_name) = entry.as_str() {\n let src = stage_path.join(bundle_name);\n if !src.exists() {\n debug!(\n \"VST plugin '{}' not found in staging; skipping\",\n bundle_name\n );\n continue;\n }\n\n let dest = dest_dir.join(bundle_name);\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Installing VST plugin '{}' → '{}'\",\n src.display(),\n dest.display()\n );\n // Try move, fallback to copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record moved plugin\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink into Caskroom for reference\n let link = cask_version_install_path.join(bundle_name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // single stanza\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/audio_unit_plugin.rs", "// ===== sps-core/src/build/cask/artifacts/audio_unit_plugin.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Installs `audio_unit_plugin` bundles from the staging area into\n/// `~/Library/Audio/Plug-Ins/Components`, then symlinks them into the Caskroom.\n///\n/// Mirrors Homebrew’s `AudioUnitPlugin < Moved` pattern.\npub fn install_audio_unit_plugin(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"audio_unit_plugin\").and_then(|v| v.as_array()) {\n // Target directory for Audio Unit components\n let dest_dir = config\n .home_dir()\n .join(\"Library\")\n .join(\"Audio\")\n .join(\"Plug-Ins\")\n .join(\"Components\");\n fs::create_dir_all(&dest_dir)?;\n\n for entry in entries {\n if let Some(bundle_name) = entry.as_str() {\n let src = stage_path.join(bundle_name);\n if !src.exists() {\n debug!(\n \"AudioUnit plugin '{}' not found in staging; skipping\",\n bundle_name\n );\n continue;\n }\n\n let dest = dest_dir.join(bundle_name);\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Installing AudioUnit plugin '{}' → '{}'\",\n src.display(),\n dest.display()\n );\n // Try move, fallback to copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record moved plugin\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink into Caskroom for reference\n let link = cask_version_install_path.join(bundle_name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // one stanza only\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/manpage.rs", "// ===== src/build/cask/artifacts/manpage.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::sync::LazyLock;\n\nuse regex::Regex;\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n// --- Moved Regex Creation Outside ---\nstatic MANPAGE_RE: LazyLock =\n LazyLock::new(|| Regex::new(r\"\\.([1-8nl])(?:\\.gz)?$\").unwrap());\n\n/// Install any `manpage` stanzas from the Cask definition.\n/// Mirrors Homebrew’s `Cask::Artifact::Manpage < Symlinked` behavior\n/// :contentReference[oaicite:3]{index=3}.\npub fn install_manpage(\n cask: &Cask,\n stage_path: &Path,\n _cask_version_install_path: &Path, // Not needed for symlinking manpages\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n // Look up the \"manpage\" array in the raw artifacts JSON :contentReference[oaicite:4]{index=4}\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"manpage\").and_then(|v| v.as_array()) {\n for entry in entries {\n if let Some(man_file) = entry.as_str() {\n let src = stage_path.join(man_file);\n if !src.exists() {\n debug!(\n \"Manpage '{}' not found in staging area, skipping\",\n man_file\n );\n continue;\n }\n\n // Use the static regex\n let section = if let Some(caps) = MANPAGE_RE.captures(man_file) {\n caps.get(1).unwrap().as_str()\n } else {\n debug!(\n \"Filename '{}' does not look like a manpage, skipping\",\n man_file\n );\n continue;\n };\n\n // Build the target directory: e.g. /opt/sps/share/man/man1\n let man_dir = config.man_base_dir().join(format!(\"man{section}\"));\n fs::create_dir_all(&man_dir)?;\n\n // Determine the target path\n let file_name = Path::new(man_file).file_name().ok_or_else(|| {\n sps_common::error::SpsError::Generic(format!(\n \"Invalid manpage filename: {man_file}\"\n ))\n })?; // Handle potential None\n let dest = man_dir.join(file_name);\n\n // Remove any existing file or symlink\n // :contentReference[oaicite:7]{index=7}\n if dest.exists() || dest.symlink_metadata().is_ok() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\"Linking manpage '{}' → '{}'\", src.display(), dest.display());\n // Create the symlink\n symlink(&src, &dest)?;\n\n // Record it in our manifest\n installed.push(InstalledArtifact::ManpageLink {\n link_path: dest.clone(),\n target_path: src.clone(),\n });\n }\n }\n // Assume only one \"manpage\" stanza per Cask based on Homebrew structure\n break;\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/keyboard_layout.rs", "// ===== sps-core/src/build/cask/artifacts/keyboard_layout.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Mirrors Homebrew’s `KeyboardLayout < Moved` behavior.\npub fn install_keyboard_layout(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"keyboard_layout\").and_then(|v| v.as_array()) {\n // Target directory for user keyboard layouts\n let dest_dir = config.home_dir().join(\"Library\").join(\"Keyboard Layouts\");\n fs::create_dir_all(&dest_dir)?;\n\n for entry in entries {\n if let Some(bundle_name) = entry.as_str() {\n let src = stage_path.join(bundle_name);\n if !src.exists() {\n debug!(\n \"Keyboard layout '{}' not found in staging; skipping\",\n bundle_name\n );\n continue;\n }\n\n let dest = dest_dir.join(bundle_name);\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Installing keyboard layout '{}' → '{}'\",\n src.display(),\n dest.display()\n );\n // Try move, fallback to copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record moved bundle\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink into Caskroom\n let link = cask_version_install_path.join(bundle_name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // one stanza only\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/binary.rs", "// ===== sps-core/src/build/cask/artifacts/binary.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Installs `binary` artifacts, which can be declared as:\n/// - a simple string: `\"foo\"` (source and target both `\"foo\"`)\n/// - a map: `{ \"source\": \"path/in/stage\", \"target\": \"name\", \"chmod\": \"0755\" }`\n/// - a map with just `\"target\"`: automatically generate a wrapper script\n///\n/// Copies or symlinks executables into the prefix bin directory,\n/// and records both the link and caskroom reference.\npub fn install_binary(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"binary\") {\n // Normalize into an array\n let arr = if let Some(arr) = entries.as_array() {\n arr.clone()\n } else {\n vec![entries.clone()]\n };\n\n let bin_dir = config.bin_dir();\n fs::create_dir_all(&bin_dir)?;\n\n for entry in arr {\n // Determine source, target, and optional chmod\n let (source_rel, target_name, chmod) = if let Some(tgt) = entry.as_str() {\n // simple form: \"foo\"\n (tgt.to_string(), tgt.to_string(), None)\n } else if let Some(m) = entry.as_object() {\n let target = m\n .get(\"target\")\n .and_then(|v| v.as_str())\n .map(String::from)\n .ok_or_else(|| {\n SpsError::InstallError(format!(\n \"Binary artifact missing 'target': {m:?}\"\n ))\n })?;\n\n let chmod = m.get(\"chmod\").and_then(|v| v.as_str()).map(String::from);\n\n // If `source` is provided, use it; otherwise generate wrapper\n let source = if let Some(src) = m.get(\"source\").and_then(|v| v.as_str())\n {\n src.to_string()\n } else {\n // generate wrapper script in caskroom\n let wrapper_name = format!(\"{target}.wrapper.sh\");\n let wrapper_path = cask_version_install_path.join(&wrapper_name);\n\n // assume the real executable lives inside the .app bundle\n let app_name = format!(\"{}.app\", cask.display_name());\n let exe_path =\n format!(\"/Applications/{app_name}/Contents/MacOS/{target}\");\n\n let script =\n format!(\"#!/usr/bin/env bash\\nexec \\\"{exe_path}\\\" \\\"$@\\\"\\n\");\n fs::write(&wrapper_path, script)?;\n Command::new(\"chmod\")\n .arg(\"+x\")\n .arg(&wrapper_path)\n .status()?;\n\n wrapper_name\n };\n\n (source, target, chmod)\n } else {\n debug!(\"Invalid binary artifact entry: {:?}\", entry);\n continue;\n };\n\n let src_path = stage_path.join(&source_rel);\n if !src_path.exists() {\n debug!(\"Binary source '{}' not found, skipping\", src_path.display());\n continue;\n }\n\n // Link into bin_dir\n let link_path = bin_dir.join(&target_name);\n let _ = fs::remove_file(&link_path);\n debug!(\n \"Linking binary '{}' → '{}'\",\n src_path.display(),\n link_path.display()\n );\n symlink(&src_path, &link_path)?;\n\n // Apply chmod if specified\n if let Some(mode) = chmod.as_deref() {\n let _ = Command::new(\"chmod\").arg(mode).arg(&link_path).status();\n }\n\n installed.push(InstalledArtifact::BinaryLink {\n link_path: link_path.clone(),\n target_path: src_path.clone(),\n });\n\n // Also create a Caskroom symlink for reference\n let caskroom_link = cask_version_install_path.join(&target_name);\n let _ = remove_path_robustly(&caskroom_link, config, true);\n symlink(&link_path, &caskroom_link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: caskroom_link,\n target_path: link_path.clone(),\n });\n }\n\n // Only one binary stanza per cask\n break;\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/installer.rs", "// ===== sps-core/src/build/cask/artifacts/installer.rs =====\n\nuse std::path::Path;\nuse std::process::{Command, Stdio};\n\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::InstalledArtifact;\n\n// Helper to validate that the executable is a filename (relative, no '/' or \"..\")\nfn validate_filename_or_relative_path(file: &str) -> Result {\n if file.starts_with(\"/\") || file.contains(\"..\") || file.contains(\"/\") {\n return Err(SpsError::Generic(format!(\n \"Invalid executable filename: {file}\"\n )));\n }\n Ok(file.to_string())\n}\n\n// Helper to validate a command argument based on allowed characters or allowed option form\nfn validate_argument(arg: &str) -> Result {\n if arg.starts_with(\"-\") {\n return Ok(arg.to_string());\n }\n if arg.starts_with(\"/\") || arg.contains(\"..\") || arg.contains(\"/\") {\n return Err(SpsError::Generic(format!(\"Invalid argument: {arg}\")));\n }\n if !arg\n .chars()\n .all(|c| c.is_alphanumeric() || c == '-' || c == '_' || c == '.')\n {\n return Err(SpsError::Generic(format!(\n \"Invalid characters in argument: {arg}\"\n )));\n }\n Ok(arg.to_string())\n}\n\n/// Implements the `installer` stanza:\n/// - `manual`: prints instructions to open the staged path.\n/// - `script`: runs the given executable with args, under sudo if requested.\n///\n/// Mirrors Homebrew’s `Cask::Artifact::Installer` behavior :contentReference[oaicite:1]{index=1}.\npub fn run_installer(\n cask: &Cask,\n stage_path: &Path,\n _cask_version_install_path: &Path,\n _config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n // Find the `installer` definitions in the raw JSON artifacts\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(insts) = obj.get(\"installer\").and_then(|v| v.as_array()) {\n for inst in insts {\n if let Some(inst_obj) = inst.as_object() {\n if let Some(man) = inst_obj.get(\"manual\").and_then(|v| v.as_str()) {\n debug!(\n \"Cask {} requires manual install. To finish:\\n open {}\",\n cask.token,\n stage_path.join(man).display()\n );\n continue;\n }\n let exe_key = if inst_obj.contains_key(\"script\") {\n \"script\"\n } else {\n \"executable\"\n };\n let executable = inst_obj\n .get(exe_key)\n .and_then(|v| v.as_str())\n .ok_or_else(|| {\n SpsError::Generic(format!(\n \"installer stanza missing '{exe_key}' field\"\n ))\n })?;\n let args: Vec = inst_obj\n .get(\"args\")\n .and_then(|v| v.as_array())\n .map(|arr| {\n arr.iter()\n .filter_map(|a| a.as_str().map(String::from))\n .collect()\n })\n .unwrap_or_default();\n let use_sudo = inst_obj\n .get(\"sudo\")\n .and_then(|v| v.as_bool())\n .unwrap_or(false);\n\n let validated_executable =\n validate_filename_or_relative_path(executable)?;\n let mut validated_args = Vec::new();\n for arg in &args {\n validated_args.push(validate_argument(arg)?);\n }\n\n let script_path = stage_path.join(&validated_executable);\n if !script_path.exists() {\n return Err(SpsError::NotFound(format!(\n \"Installer script not found: {}\",\n script_path.display()\n )));\n }\n\n debug!(\n \"Running installer script '{}' for cask {}\",\n script_path.display(),\n cask.token\n );\n let mut cmd = if use_sudo {\n let mut c = Command::new(\"sudo\");\n c.arg(script_path.clone());\n c\n } else {\n Command::new(script_path.clone())\n };\n cmd.args(&validated_args);\n cmd.stdin(Stdio::null())\n .stdout(Stdio::inherit())\n .stderr(Stdio::inherit());\n\n let status = cmd.status().map_err(|e| {\n SpsError::Generic(format!(\"Failed to spawn installer script: {e}\"))\n })?;\n if !status.success() {\n return Err(SpsError::InstallError(format!(\n \"Installer script exited with {status}\"\n )));\n }\n\n installed\n .push(InstalledArtifact::CaskroomReference { path: script_path });\n }\n }\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/input_method.rs", "// ===== sps-core/src/build/cask/artifacts/input_method.rs =====\n\nuse std::fs;\nuse std::os::unix::fs as unix_fs;\nuse std::path::Path;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\n\nuse crate::install::cask::helpers::remove_path_robustly;\nuse crate::install::cask::write_cask_manifest;\n\n/// Install `input_method` artifacts from the staged directory into\n/// `~/Library/Input Methods` and record installed artifacts.\npub fn install_input_method(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n // Ensure we have an array of input_method names\n if let Some(artifacts_def) = &cask.artifacts {\n for artifact_value in artifacts_def {\n if let Some(obj) = artifact_value.as_object() {\n if let Some(names) = obj.get(\"input_method\").and_then(|v| v.as_array()) {\n for name_val in names {\n if let Some(name) = name_val.as_str() {\n let source = stage_path.join(name);\n if source.exists() {\n // Target directory: ~/Library/Input Methods\n let target_dir =\n config.home_dir().join(\"Library\").join(\"Input Methods\");\n if !target_dir.exists() {\n fs::create_dir_all(&target_dir)?;\n }\n let target = target_dir.join(name);\n\n // Remove existing input method if present\n if target.exists() {\n let _ = remove_path_robustly(&target, config, true);\n }\n\n // Move (or rename) the staged bundle\n fs::rename(&source, &target)\n .or_else(|_| unix_fs::symlink(&source, &target))?;\n\n // Record the main artifact\n installed.push(InstalledArtifact::MovedResource {\n path: target.clone(),\n });\n\n // Create a caskroom symlink for uninstallation\n let link_path = cask_version_install_path.join(name);\n if link_path.exists() {\n let _ = remove_path_robustly(&link_path, config, true);\n }\n #[cfg(unix)]\n std::os::unix::fs::symlink(&target, &link_path)?;\n\n installed.push(InstalledArtifact::CaskroomLink {\n link_path,\n target_path: target,\n });\n }\n }\n }\n }\n }\n }\n }\n\n // Write manifest for these artifacts\n write_cask_manifest(cask, cask_version_install_path, installed.clone())?;\n Ok(installed)\n}\n"], ["/sps/sps-core/src/uninstall/cask.rs", "// sps-core/src/uninstall/cask.rs\nuse std::fs;\nuse std::path::{Path, PathBuf};\nuse std::process::{Command, Stdio};\n\nuse lazy_static::lazy_static;\nuse regex::Regex;\n// serde_json is used for CaskInstallManifest deserialization\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::{Cask, ZapActionDetail};\nuse tracing::{debug, error, warn};\nuse trash; // This will be used by trash_path\n\n// Import helpers from the common module within the uninstall scope\nuse super::common::{expand_tilde, is_safe_path, remove_filesystem_artifact};\nuse crate::check::installed::InstalledPackageInfo;\n// Corrected import path if install::cask::helpers is where it lives now\nuse crate::install::cask::helpers::{\n cleanup_empty_parent_dirs_in_private_store,\n remove_path_robustly as remove_path_robustly_from_install_helpers,\n};\nuse crate::install::cask::CaskInstallManifest;\n#[cfg(target_os = \"macos\")]\nuse crate::utils::applescript;\n\nlazy_static! {\n static ref VALID_PKGID_RE: Regex = Regex::new(r\"^[a-zA-Z0-9._-]+$\").unwrap();\n static ref VALID_LABEL_RE: Regex = Regex::new(r\"^[a-zA-Z0-9._-]+$\").unwrap();\n static ref VALID_SCRIPT_PATH_RE: Regex = Regex::new(r\"^[a-zA-Z0-9/._-]+$\").unwrap();\n static ref VALID_SIGNAL_RE: Regex = Regex::new(r\"^[A-Z0-9]+$\").unwrap();\n static ref VALID_BUNDLE_ID_RE: Regex =\n Regex::new(r\"^[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)+$\").unwrap();\n}\n\n/// Performs a \"soft\" uninstall for a Cask.\n/// It processes the `CASK_INSTALL_MANIFEST.json` to remove linked artifacts\n/// and then updates the manifest to mark the cask as not currently installed.\n/// The Cask's versioned directory in the Caskroom is NOT removed.\npub fn uninstall_cask_artifacts(info: &InstalledPackageInfo, config: &Config) -> Result<()> {\n debug!(\n \"Soft uninstalling Cask artifacts for {} version {}\",\n info.name, info.version\n );\n let manifest_path = info.path.join(\"CASK_INSTALL_MANIFEST.json\");\n let mut removal_errors: Vec = Vec::new();\n\n if manifest_path.is_file() {\n debug!(\n \"Processing manifest for soft uninstall: {}\",\n manifest_path.display()\n );\n match fs::read_to_string(&manifest_path) {\n Ok(manifest_str) => match serde_json::from_str::(&manifest_str) {\n Ok(mut manifest) => {\n if !manifest.is_installed {\n debug!(\"Cask {} version {} is already marked as uninstalled in manifest. Nothing to do for soft uninstall.\", info.name, info.version);\n return Ok(());\n }\n\n debug!(\n \"Soft uninstalling {} artifacts listed in manifest for {} {}...\",\n manifest.artifacts.len(),\n info.name,\n info.version\n );\n for artifact in manifest.artifacts.iter().rev() {\n if !process_artifact_uninstall_core(artifact, config, false) {\n removal_errors.push(format!(\"Failed to remove artifact: {artifact:?}\"));\n }\n }\n\n manifest.is_installed = false;\n match fs::File::create(&manifest_path) {\n Ok(file) => {\n let writer = std::io::BufWriter::new(file);\n if let Err(e) = serde_json::to_writer_pretty(writer, &manifest) {\n warn!(\n \"Failed to update manifest {}: {}\",\n manifest_path.display(),\n e\n );\n } else {\n debug!(\n \"Manifest updated successfully for soft uninstall: {}\",\n manifest_path.display()\n );\n }\n }\n Err(e) => {\n warn!(\n \"Failed to open manifest for writing (soft uninstall) at {}: {}\",\n manifest_path.display(),\n e\n );\n }\n }\n }\n Err(e) => warn!(\n \"Failed to parse cask manifest {}: {}. Cannot perform detailed soft uninstall.\",\n manifest_path.display(),\n e\n ),\n },\n Err(e) => warn!(\n \"Failed to read cask manifest {}: {}. Cannot perform detailed soft uninstall.\",\n manifest_path.display(),\n e\n ),\n }\n } else {\n warn!(\n \"No CASK_INSTALL_MANIFEST.json found in {}. Cannot perform detailed soft uninstall for {} {}.\",\n info.path.display(),\n info.name,\n info.version\n );\n }\n\n if removal_errors.is_empty() {\n Ok(())\n } else {\n Err(SpsError::InstallError(format!(\n \"Errors during cask artifact soft removal for {}: {}\",\n info.name,\n removal_errors.join(\"; \")\n )))\n }\n}\n\n/// Performs a \"zap\" uninstall for a Cask, removing files defined in `zap` stanzas\n/// and cleaning up the private store. Also marks the cask as uninstalled in its manifest.\npub async fn zap_cask_artifacts(\n info: &InstalledPackageInfo,\n cask_def: &Cask,\n config: &Config,\n) -> Result<()> {\n debug!(\"Starting ZAP process for cask: {}\", cask_def.token);\n let home = config.home_dir();\n let cask_version_path_in_caskroom = &info.path;\n let mut zap_errors: Vec = Vec::new();\n\n let mut primary_app_name_from_manifest: Option = None;\n let manifest_path = cask_version_path_in_caskroom.join(\"CASK_INSTALL_MANIFEST.json\");\n\n if manifest_path.is_file() {\n match fs::read_to_string(&manifest_path) {\n Ok(manifest_str) => match serde_json::from_str::(&manifest_str) {\n Ok(mut manifest) => {\n primary_app_name_from_manifest = manifest.primary_app_file_name.clone();\n if manifest.is_installed {\n manifest.is_installed = false;\n if let Ok(file) = fs::File::create(&manifest_path) {\n let writer = std::io::BufWriter::new(file);\n if let Err(e) = serde_json::to_writer_pretty(writer, &manifest) {\n warn!(\n \"Failed to update manifest during zap for {}: {}\",\n manifest_path.display(),\n e\n );\n }\n } else {\n warn!(\n \"Failed to open manifest for writing during zap at {}\",\n manifest_path.display()\n );\n }\n }\n }\n Err(e) => warn!(\n \"Failed to parse manifest during zap {}: {}\",\n manifest_path.display(),\n e\n ),\n },\n Err(e) => warn!(\n \"Failed to read manifest during zap {}: {}\",\n manifest_path.display(),\n e\n ),\n }\n } else {\n warn!(\"No manifest found at {} during zap. Private store cleanup might be incomplete if app name changed.\", manifest_path.display());\n }\n\n if !cleanup_private_store(\n &cask_def.token,\n &info.version,\n primary_app_name_from_manifest.as_deref(),\n config,\n ) {\n let msg = format!(\n \"Failed to clean up private store for cask {} version {}\",\n cask_def.token, info.version\n );\n warn!(\"{}\", msg);\n zap_errors.push(msg);\n }\n\n let zap_stanzas = match &cask_def.zap {\n Some(stanzas) => stanzas,\n None => {\n debug!(\"No zap stanza found for cask {}\", cask_def.token);\n // Proceed to Caskroom cleanup even if no specific zap actions\n if !remove_filesystem_artifact(cask_version_path_in_caskroom, true) {\n // use_sudo = true for Caskroom\n if cask_version_path_in_caskroom.exists() {\n zap_errors.push(format!(\n \"Failed to remove Caskroom version directory during zap: {}\",\n cask_version_path_in_caskroom.display()\n ));\n }\n }\n if let Some(parent_token_dir) = cask_version_path_in_caskroom.parent() {\n if parent_token_dir.exists() && parent_token_dir.is_dir() {\n match fs::read_dir(parent_token_dir) {\n Ok(mut entries) => {\n if entries.next().is_none()\n && !remove_filesystem_artifact(parent_token_dir, true)\n && parent_token_dir.exists()\n {\n warn!(\"Failed to remove empty Caskroom token directory during zap: {}\", parent_token_dir.display());\n }\n }\n Err(e) => warn!(\n \"Failed to read Caskroom token dir {} during zap: {}\",\n parent_token_dir.display(),\n e\n ),\n }\n }\n }\n return if zap_errors.is_empty() {\n Ok(())\n } else {\n Err(SpsError::Generic(zap_errors.join(\"; \")))\n };\n }\n };\n\n for stanza_map in zap_stanzas {\n for (action_key, action_detail) in &stanza_map.0 {\n debug!(\n \"Processing zap action: {} = {:?}\",\n action_key, action_detail\n );\n match action_detail {\n ZapActionDetail::Trash(paths) => {\n for path_str in paths {\n let target = expand_tilde(path_str, &home);\n if is_safe_path(&target, &home, config) {\n if !trash_path(&target) {\n // Logged within trash_path\n }\n } else {\n zap_errors\n .push(format!(\"Skipped unsafe trash path {}\", target.display()));\n }\n }\n }\n ZapActionDetail::Delete(paths) | ZapActionDetail::Rmdir(paths) => {\n for path_str in paths {\n let target = expand_tilde(path_str, &home);\n if is_safe_path(&target, &home, config) {\n let use_sudo = target.starts_with(\"/Library\")\n || target.starts_with(\"/Applications\");\n let exists_before =\n target.exists() || target.symlink_metadata().is_ok();\n if exists_before {\n if action_key == \"rmdir\" && !target.is_dir() {\n warn!(\"Zap rmdir target is not a directory: {}. Attempting as file delete.\", target.display());\n }\n if !remove_filesystem_artifact(&target, use_sudo)\n && (target.exists() || target.symlink_metadata().is_ok())\n {\n zap_errors.push(format!(\n \"Failed to {} {}\",\n action_key,\n target.display()\n ));\n }\n } else {\n debug!(\n \"Zap target {} not found, skipping removal.\",\n target.display()\n );\n }\n } else {\n zap_errors.push(format!(\n \"Skipped unsafe {} path {}\",\n action_key,\n target.display()\n ));\n }\n }\n }\n ZapActionDetail::Pkgutil(ids_sv) => {\n for id in ids_sv.clone().into_vec() {\n if !VALID_PKGID_RE.is_match(&id) {\n warn!(\"Invalid pkgutil ID format for zap: '{}'. Skipping.\", id);\n zap_errors.push(format!(\"Invalid pkgutil ID: {id}\"));\n continue;\n }\n if !forget_pkgutil_receipt(&id) {\n // Error logged in helper\n }\n }\n }\n ZapActionDetail::Launchctl(labels_sv) => {\n for label in labels_sv.clone().into_vec() {\n if !VALID_LABEL_RE.is_match(&label) {\n warn!(\n \"Invalid launchctl label format for zap: '{}'. Skipping.\",\n label\n );\n zap_errors.push(format!(\"Invalid launchctl label: {label}\"));\n continue;\n }\n let potential_paths = vec![\n home.join(\"Library/LaunchAgents\")\n .join(format!(\"{label}.plist\")),\n PathBuf::from(\"/Library/LaunchAgents\").join(format!(\"{label}.plist\")),\n PathBuf::from(\"/Library/LaunchDaemons\").join(format!(\"{label}.plist\")),\n ];\n let path_to_try = potential_paths.into_iter().find(|p| p.exists());\n if !unload_and_remove_launchd(&label, path_to_try.as_deref()) {\n // Error logged in helper\n }\n }\n }\n ZapActionDetail::Script { executable, args } => {\n let script_path_str = executable;\n if !VALID_SCRIPT_PATH_RE.is_match(script_path_str) {\n error!(\n \"Zap script path contains invalid characters: '{}'. Skipping.\",\n script_path_str\n );\n zap_errors.push(format!(\"Skipped invalid script path: {script_path_str}\"));\n continue;\n }\n let script_full_path = PathBuf::from(script_path_str);\n if !script_full_path.exists() {\n if !script_full_path.is_absolute() {\n if let Ok(found_path) = which::which(&script_full_path) {\n debug!(\n \"Found zap script {} in PATH: {}\",\n script_full_path.display(),\n found_path.display()\n );\n run_zap_script(\n &found_path,\n args.as_ref().map(|v| v.as_slice()),\n &mut zap_errors,\n );\n } else {\n error!(\n \"Zap script '{}' not found (absolute or in PATH). Skipping.\",\n script_full_path.display()\n );\n zap_errors.push(format!(\n \"Zap script not found: {}\",\n script_full_path.display()\n ));\n }\n } else {\n error!(\n \"Absolute zap script path '{}' not found. Skipping.\",\n script_full_path.display()\n );\n zap_errors.push(format!(\n \"Zap script not found: {}\",\n script_full_path.display()\n ));\n }\n continue;\n }\n run_zap_script(\n &script_full_path,\n args.as_ref().map(|v| v.as_slice()),\n &mut zap_errors,\n );\n }\n ZapActionDetail::Signal(signals) => {\n for signal_spec in signals {\n let parts: Vec<&str> = signal_spec.splitn(2, '/').collect();\n if parts.len() != 2 {\n warn!(\"Invalid signal spec format '{}', expected SIGNAL/bundle.id. Skipping.\", signal_spec);\n zap_errors.push(format!(\"Invalid signal spec: {signal_spec}\"));\n continue;\n }\n let signal = parts[0].trim().to_uppercase();\n let bundle_id_or_pattern = parts[1].trim();\n\n if !VALID_SIGNAL_RE.is_match(&signal) {\n warn!(\n \"Invalid signal name '{}' in spec '{}'. Skipping.\",\n signal, signal_spec\n );\n zap_errors.push(format!(\"Invalid signal name: {signal}\"));\n continue;\n }\n\n debug!(\"Sending signal {} to processes matching ID/pattern '{}' (using pkill -f)\", signal, bundle_id_or_pattern);\n let mut cmd = Command::new(\"pkill\");\n cmd.arg(format!(\"-{signal}\")); // Standard signal format for pkill\n cmd.arg(\"-f\");\n cmd.arg(bundle_id_or_pattern);\n cmd.stdout(Stdio::null()).stderr(Stdio::piped());\n match cmd.status() {\n Ok(status) => {\n if status.success() {\n debug!(\"Successfully sent signal {} via pkill to processes matching '{}'.\", signal, bundle_id_or_pattern);\n } else if status.code() == Some(1) {\n debug!(\"No running processes found matching ID/pattern '{}' for signal {} via pkill.\", bundle_id_or_pattern, signal);\n } else {\n warn!(\"pkill command failed for signal {} / ID/pattern '{}' with status: {}\", signal, bundle_id_or_pattern, status);\n }\n }\n Err(e) => {\n error!(\n \"Failed to execute pkill for signal {} / ID/pattern '{}': {}\",\n signal, bundle_id_or_pattern, e\n );\n zap_errors.push(format!(\"Failed to run pkill for signal {signal}\"));\n }\n }\n }\n }\n }\n }\n }\n\n debug!(\n \"Zap: Removing Caskroom version directory: {}\",\n cask_version_path_in_caskroom.display()\n );\n if !remove_filesystem_artifact(cask_version_path_in_caskroom, true)\n && cask_version_path_in_caskroom.exists()\n {\n let msg = format!(\n \"Failed to remove Caskroom version directory during zap: {}\",\n cask_version_path_in_caskroom.display()\n );\n error!(\"{}\", msg);\n zap_errors.push(msg);\n }\n\n if let Some(parent_token_dir) = cask_version_path_in_caskroom.parent() {\n if parent_token_dir.exists() && parent_token_dir.is_dir() {\n match fs::read_dir(parent_token_dir) {\n Ok(mut entries) => {\n if entries.next().is_none() {\n debug!(\n \"Zap: Removing empty Caskroom token directory: {}\",\n parent_token_dir.display()\n );\n if !remove_filesystem_artifact(parent_token_dir, true)\n && parent_token_dir.exists()\n {\n warn!(\n \"Failed to remove empty Caskroom token directory during zap: {}\",\n parent_token_dir.display()\n );\n }\n }\n }\n Err(e) => warn!(\n \"Failed to read Caskroom token directory {} during zap cleanup: {}\",\n parent_token_dir.display(),\n e\n ),\n }\n }\n }\n\n if zap_errors.is_empty() {\n debug!(\n \"Zap process completed successfully for cask: {}\",\n cask_def.token\n );\n Ok(())\n } else {\n error!(\n \"Zap process for {} completed with errors: {}\",\n cask_def.token,\n zap_errors.join(\"; \")\n );\n Err(SpsError::InstallError(format!(\n \"Zap for {} failed with errors: {}\",\n cask_def.token,\n zap_errors.join(\"; \")\n )))\n }\n}\n\nfn process_artifact_uninstall_core(\n artifact: &InstalledArtifact,\n config: &Config,\n use_sudo_for_zap: bool,\n) -> bool {\n debug!(\"Processing artifact removal: {:?}\", artifact);\n match artifact {\n InstalledArtifact::AppBundle { path } => {\n debug!(\"Uninstall: Removing AppBundle at {}\", path.display());\n match path.symlink_metadata() {\n Ok(metadata) if metadata.file_type().is_symlink() => {\n debug!(\"AppBundle at {} is a symlink; unlinking.\", path.display());\n match std::fs::remove_file(path) {\n Ok(_) => true,\n Err(e) => {\n warn!(\"Failed to unlink symlink at {}: {}\", path.display(), e);\n false\n }\n }\n }\n Ok(metadata) if metadata.file_type().is_dir() => {\n #[cfg(target_os = \"macos\")]\n {\n if path.exists() {\n if let Err(e) = applescript::quit_app_gracefully(path) {\n warn!(\n \"Attempt to gracefully quit app at {} failed: {} (proceeding)\",\n path.display(),\n e\n );\n }\n } else {\n debug!(\n \"App bundle at {} does not exist, skipping quit.\",\n path.display()\n );\n }\n }\n let use_sudo = path.starts_with(config.applications_dir())\n || path.starts_with(\"/Applications\")\n || use_sudo_for_zap;\n remove_filesystem_artifact(path, use_sudo)\n }\n Ok(_) | Err(_) => {\n let use_sudo = path.starts_with(config.applications_dir())\n || path.starts_with(\"/Applications\")\n || use_sudo_for_zap;\n remove_filesystem_artifact(path, use_sudo)\n }\n }\n }\n InstalledArtifact::BinaryLink { link_path, .. }\n | InstalledArtifact::ManpageLink { link_path, .. }\n | InstalledArtifact::CaskroomLink { link_path, .. } => {\n debug!(\"Uninstall: Removing link at {}\", link_path.display());\n remove_filesystem_artifact(link_path, use_sudo_for_zap)\n }\n InstalledArtifact::PkgUtilReceipt { id } => {\n debug!(\"Uninstall: Forgetting PkgUtilReceipt {}\", id);\n forget_pkgutil_receipt(id)\n }\n InstalledArtifact::Launchd { label, path } => {\n debug!(\"Uninstall: Unloading Launchd {} (path: {:?})\", label, path);\n unload_and_remove_launchd(label, path.as_deref())\n }\n InstalledArtifact::MovedResource { path } => {\n debug!(\"Uninstall: Removing MovedResource at {}\", path.display());\n remove_filesystem_artifact(path, use_sudo_for_zap)\n }\n InstalledArtifact::CaskroomReference { path } => {\n debug!(\n \"Uninstall: Removing CaskroomReference at {}\",\n path.display()\n );\n remove_filesystem_artifact(path, use_sudo_for_zap)\n }\n }\n}\n\nfn forget_pkgutil_receipt(id: &str) -> bool {\n if !VALID_PKGID_RE.is_match(id) {\n error!(\"Invalid pkgutil ID format: '{}'. Skipping forget.\", id);\n return false;\n }\n debug!(\"Forgetting package receipt (requires sudo): {}\", id);\n let output = Command::new(\"sudo\")\n .arg(\"pkgutil\")\n .arg(\"--forget\")\n .arg(id)\n .output();\n match output {\n Ok(out) if out.status.success() => {\n debug!(\"Successfully forgot package receipt {}\", id);\n true\n }\n Ok(out) => {\n let stderr = String::from_utf8_lossy(&out.stderr);\n if !stderr.contains(\"No receipt for\") && !stderr.trim().is_empty() {\n error!(\"Failed to forget package receipt {}: {}\", id, stderr.trim());\n // Return false if pkgutil fails for a reason other than \"No receipt\"\n return false;\n } else {\n debug!(\"Package receipt {} already forgotten or never existed.\", id);\n }\n true\n }\n Err(e) => {\n error!(\"Failed to execute sudo pkgutil --forget {}: {}\", id, e);\n false\n }\n }\n}\n\nfn unload_and_remove_launchd(label: &str, path: Option<&Path>) -> bool {\n if !VALID_LABEL_RE.is_match(label) {\n error!(\n \"Invalid launchd label format: '{}'. Skipping unload/remove.\",\n label\n );\n return false;\n }\n debug!(\"Unloading launchd service (if loaded): {}\", label);\n let unload_output = Command::new(\"launchctl\")\n .arg(\"unload\")\n .arg(\"-w\")\n .arg(label)\n .stderr(Stdio::piped())\n .output();\n\n let mut unload_successful_or_not_loaded = false;\n match unload_output {\n Ok(out) if out.status.success() => {\n debug!(\"Successfully unloaded launchd service {}\", label);\n unload_successful_or_not_loaded = true;\n }\n Ok(out) => {\n let stderr = String::from_utf8_lossy(&out.stderr);\n if stderr.contains(\"Could not find specified service\")\n || stderr.contains(\"service is not loaded\")\n || stderr.trim().is_empty()\n {\n debug!(\"Launchd service {} already unloaded or not found.\", label);\n unload_successful_or_not_loaded = true;\n } else {\n warn!(\n \"launchctl unload {} failed (but proceeding with plist removal attempt): {}\",\n label,\n stderr.trim()\n );\n // Proceed to try plist removal even if unload reports other errors\n }\n }\n Err(e) => {\n warn!(\"Failed to execute launchctl unload {} (but proceeding with plist removal attempt): {}\", label, e);\n }\n }\n\n if let Some(plist_path) = path {\n if plist_path.exists() {\n debug!(\"Removing launchd plist file: {}\", plist_path.display());\n let use_sudo = plist_path.starts_with(\"/Library/LaunchDaemons\")\n || plist_path.starts_with(\"/Library/LaunchAgents\");\n if !remove_filesystem_artifact(plist_path, use_sudo) {\n warn!(\"Failed to remove launchd plist: {}\", plist_path.display());\n return false; // If plist removal fails, consider the operation failed\n }\n } else {\n debug!(\n \"Launchd plist path {} does not exist, skip removal.\",\n plist_path.display()\n );\n }\n } else {\n debug!(\n \"No path provided for launchd plist removal for label {}\",\n label\n );\n }\n unload_successful_or_not_loaded // Success depends on unload and optional plist removal\n}\n\nfn trash_path(path: &Path) -> bool {\n if !path.exists() && path.symlink_metadata().is_err() {\n debug!(\"Path for trashing not found: {}\", path.display());\n return true;\n }\n match trash::delete(path) {\n Ok(_) => {\n debug!(\"Trashed: {}\", path.display());\n true\n }\n Err(e) => {\n warn!(\"Failed to trash {} (proceeding anyway): {}. This might require manual cleanup or installing a 'trash' utility.\", path.display(), e);\n true\n }\n }\n}\n\n/// Helper for zap scripts.\nfn run_zap_script(script_path: &Path, args: Option<&[String]>, errors: &mut Vec) {\n debug!(\n \"Running zap script: {} with args {:?}\",\n script_path.display(),\n args.unwrap_or_default()\n );\n let mut cmd = Command::new(script_path);\n if let Some(script_args) = args {\n cmd.args(script_args);\n }\n cmd.stdout(Stdio::piped()).stderr(Stdio::piped());\n\n match cmd.output() {\n Ok(output) => {\n log_command_output(\n \"Zap script\",\n &script_path.display().to_string(),\n &output,\n errors,\n );\n }\n Err(e) => {\n let msg = format!(\n \"Failed to execute zap script '{}': {}\",\n script_path.display(),\n e\n );\n error!(\"{}\", msg);\n errors.push(msg);\n }\n }\n}\n\n/// Logs the output of a command and adds to error list if it failed.\nfn log_command_output(\n context: &str,\n command_str: &str,\n output: &std::process::Output,\n errors: &mut Vec,\n) {\n let stdout = String::from_utf8_lossy(&output.stdout);\n let stderr = String::from_utf8_lossy(&output.stderr);\n if !output.status.success() {\n error!(\n \"{} '{}' failed with status {}: {}\",\n context,\n command_str,\n output.status,\n stderr.trim()\n );\n if !stdout.trim().is_empty() {\n error!(\"{} stdout: {}\", context, stdout.trim());\n }\n errors.push(format!(\"{context} '{command_str}' failed\"));\n } else {\n debug!(\"{} '{}' executed successfully.\", context, command_str);\n if !stdout.trim().is_empty() {\n debug!(\"{} stdout: {}\", context, stdout.trim());\n }\n if !stderr.trim().is_empty() {\n debug!(\"{} stderr: {}\", context, stderr.trim());\n }\n }\n}\n\n// Helper function specifically for cleaning up the private store.\n// This was originally inside zap_cask_artifacts.\nfn cleanup_private_store(\n cask_token: &str,\n version: &str,\n app_name: Option<&str>, // The actual .app name, not the token\n config: &Config,\n) -> bool {\n debug!(\n \"Cleaning up private store for cask {} version {}\",\n cask_token, version\n );\n\n let private_version_dir = config.cask_store_version_path(cask_token, version);\n\n if let Some(app) = app_name {\n let app_path_in_private_store = private_version_dir.join(app);\n if app_path_in_private_store.exists()\n || app_path_in_private_store.symlink_metadata().is_ok()\n {\n debug!(\n \"Removing app from private store: {}\",\n app_path_in_private_store.display()\n );\n // Use the helper from install::cask::helpers, assuming it's correctly located and\n // public\n if !remove_path_robustly_from_install_helpers(&app_path_in_private_store, config, false)\n {\n // use_sudo=false for private store\n warn!(\n \"Failed to remove app from private store: {}\",\n app_path_in_private_store.display()\n );\n // Potentially return false or collect errors, depending on desired strictness\n }\n }\n }\n\n // After attempting to remove specific app, remove the version directory if it exists\n // This also handles cases where app_name was None.\n if private_version_dir.exists() {\n debug!(\n \"Removing private store version directory: {}\",\n private_version_dir.display()\n );\n match fs::remove_dir_all(&private_version_dir) {\n Ok(_) => debug!(\n \"Successfully removed private store version directory {}\",\n private_version_dir.display()\n ),\n Err(e) => {\n warn!(\n \"Failed to remove private store version directory {}: {}\",\n private_version_dir.display(),\n e\n );\n return false; // If the version dir removal fails, consider it a failure\n }\n }\n }\n\n // Clean up empty parent token directory.\n cleanup_empty_parent_dirs_in_private_store(\n &private_version_dir, // Start from the version dir (or its parent if it was just removed)\n &config.cask_store_dir(),\n );\n\n true\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/app.rs", "// In sps-core/src/build/cask/app.rs\n\nuse std::fs;\nuse std::path::{Path, PathBuf};\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::{debug, error, warn};\n\n#[cfg(target_os = \"macos\")]\n/// Finds the primary .app bundle in a directory. Returns an error if none or ambiguous.\n/// If multiple .app bundles are found, returns the first and logs a warning.\npub fn find_primary_app_bundle_in_dir(dir: &Path) -> Result {\n if !dir.is_dir() {\n return Err(SpsError::NotFound(format!(\n \"Directory {} not found for app bundle scan.\",\n dir.display()\n )));\n }\n let mut app_bundles = Vec::new();\n for entry_res in fs::read_dir(dir)? {\n let entry = entry_res?;\n let path = entry.path();\n if path.is_dir() && path.extension().is_some_and(|ext| ext == \"app\") {\n app_bundles.push(path);\n }\n }\n if app_bundles.is_empty() {\n Err(SpsError::NotFound(format!(\n \"No .app bundle found in {}\",\n dir.display()\n )))\n } else if app_bundles.len() == 1 {\n Ok(app_bundles.remove(0))\n } else {\n // Heuristic: return the largest .app bundle if multiple are found, or one matching a common\n // pattern. For now, error if multiple are present to force explicit handling in\n // Cask definitions if needed.\n warn!(\"Multiple .app bundles found in {}: {:?}. Returning the first one, but this might be ambiguous.\", dir.display(), app_bundles);\n Ok(app_bundles.remove(0)) // Or error out\n }\n}\n\nuse sps_common::pipeline::JobAction;\n\npub fn install_app_from_staged(\n cask: &Cask,\n staged_app_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n job_action: &JobAction,\n) -> Result> {\n if !staged_app_path.exists() || !staged_app_path.is_dir() {\n return Err(SpsError::NotFound(format!(\n \"Staged app bundle for {} not found or is not a directory: {}\",\n cask.token,\n staged_app_path.display()\n )));\n }\n\n let app_name = staged_app_path\n .file_name()\n .ok_or_else(|| {\n SpsError::Generic(format!(\n \"Invalid staged app path (no filename): {}\",\n staged_app_path.display()\n ))\n })?\n .to_string_lossy();\n\n let new_version_str = cask.version.clone().unwrap_or_else(|| \"latest\".to_string());\n let final_private_store_app_path: PathBuf;\n\n // Determine if we are upgrading and if the old private store app path exists\n let mut did_upgrade = false;\n\n if let JobAction::Upgrade {\n from_version,\n old_install_path,\n ..\n } = job_action\n {\n debug!(\n \"[{}] Processing app install as UPGRADE from version {}\",\n cask.token, from_version\n );\n\n // Try to get primary_app_file_name from the old manifest to build the old private store\n // path\n let old_manifest_path = old_install_path.join(\"CASK_INSTALL_MANIFEST.json\");\n let old_primary_app_name = if old_manifest_path.is_file() {\n fs::read_to_string(&old_manifest_path)\n .ok()\n .and_then(|s| {\n serde_json::from_str::(&s).ok()\n })\n .and_then(|m| m.primary_app_file_name)\n } else {\n // Fallback if old manifest is missing, use current app_name (less reliable if app name\n // changed)\n warn!(\"[{}] Old manifest not found at {} during upgrade. Using current app name '{}' for private store path derivation.\", cask.token, old_manifest_path.display(), app_name);\n Some(app_name.to_string())\n };\n\n if let Some(name_for_old_path) = old_primary_app_name {\n let old_private_store_app_dir_path =\n config.cask_store_version_path(&cask.token, from_version);\n let old_private_store_app_bundle_path =\n old_private_store_app_dir_path.join(&name_for_old_path);\n if old_private_store_app_bundle_path.exists()\n && old_private_store_app_bundle_path.is_dir()\n {\n debug!(\"[{}] UPGRADE: Old private store app bundle found at {}. Using Homebrew-style overwrite strategy.\", cask.token, old_private_store_app_bundle_path.display());\n\n // ========================================================================\n // CRITICAL: Homebrew-Style App Bundle Replacement Strategy\n // ========================================================================\n // WHY THIS APPROACH:\n // 1. Preserves extended attributes (quarantine, code signing, etc.)\n // 2. Maintains app bundle identity → prevents Gatekeeper reset\n // 3. Avoids breaking symlinks and file system references\n // 4. Ensures user data in ~/Library remains accessible to the app\n //\n // DO NOT CHANGE TO fs::rename() or similar - it breaks Gatekeeper!\n // ========================================================================\n\n // Step 1: Remove the old app bundle from private store\n // (This is safe because we're about to replace it with the new version)\n let rm_status = Command::new(\"rm\")\n .arg(\"-rf\")\n .arg(&old_private_store_app_bundle_path)\n .status()\n .map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n\n if !rm_status.success() {\n return Err(SpsError::InstallError(format!(\n \"Failed to remove old app bundle during upgrade: {}\",\n old_private_store_app_bundle_path.display()\n )));\n }\n\n // Step 2: Copy the new app bundle with ALL attributes preserved\n // The -pR flags are critical:\n // -p: Preserve file attributes, ownership, timestamps\n // -R: Recursive copy for directories\n // This ensures Gatekeeper approval and code signing are maintained\n let cp_status = Command::new(\"cp\")\n .arg(\"-pR\") // CRITICAL: Preserve all attributes, links, and metadata\n .arg(staged_app_path)\n .arg(&old_private_store_app_bundle_path)\n .status()\n .map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n\n if !cp_status.success() {\n return Err(SpsError::InstallError(format!(\n \"Failed to copy new app bundle during upgrade: {} -> {}\",\n staged_app_path.display(),\n old_private_store_app_bundle_path.display()\n )));\n }\n\n debug!(\n \"[{}] UPGRADE: Successfully overwrote old app bundle with new version using cp -pR\",\n cask.token\n );\n\n // Now, rename the parent version directory (e.g., .../1.0 -> .../1.1)\n let new_private_store_version_dir =\n config.cask_store_version_path(&cask.token, &new_version_str);\n if old_private_store_app_dir_path != new_private_store_version_dir {\n debug!(\n \"[{}] Renaming private store version dir from {} to {}\",\n cask.token,\n old_private_store_app_dir_path.display(),\n new_private_store_version_dir.display()\n );\n fs::rename(\n &old_private_store_app_dir_path,\n &new_private_store_version_dir,\n )\n .map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n }\n final_private_store_app_path =\n new_private_store_version_dir.join(app_name.as_ref());\n did_upgrade = true;\n } else {\n warn!(\"[{}] UPGRADE: Old private store app path {} not found or not a dir. Proceeding with fresh private store placement for new version.\", cask.token, old_private_store_app_bundle_path.display());\n // Fallback to fresh placement\n final_private_store_app_path =\n config.cask_store_app_path(&cask.token, &new_version_str, app_name.as_ref());\n }\n } else {\n warn!(\"[{}] UPGRADE: Could not determine old app bundle name. Proceeding with fresh private store placement for new version.\", cask.token);\n final_private_store_app_path =\n config.cask_store_app_path(&cask.token, &new_version_str, app_name.as_ref());\n }\n } else {\n // Not an upgrade\n final_private_store_app_path =\n config.cask_store_app_path(&cask.token, &new_version_str, app_name.as_ref());\n }\n\n let final_app_destination_in_applications = config.applications_dir().join(app_name.as_ref());\n let caskroom_symlink_to_final_app = cask_version_install_path.join(app_name.as_ref());\n\n debug!(\n \"Installing app '{}': Staged -> Private Store -> /Applications -> Caskroom Symlink\",\n app_name\n );\n debug!(\" Staged app source: {}\", staged_app_path.display());\n debug!(\n \" Private store copy target: {}\",\n final_private_store_app_path.display()\n );\n debug!(\n \" Final /Applications target: {}\",\n final_app_destination_in_applications.display()\n );\n debug!(\n \" Caskroom symlink target: {}\",\n caskroom_symlink_to_final_app.display()\n );\n\n // 1. Ensure Caskroom version path exists\n if !cask_version_install_path.exists() {\n fs::create_dir_all(cask_version_install_path).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\n \"Failed to create cask version dir {}: {}\",\n cask_version_install_path.display(),\n e\n ),\n )))\n })?;\n }\n\n // 2. Create private store directory if it doesn't exist\n if let Some(parent) = final_private_store_app_path.parent() {\n if !parent.exists() {\n debug!(\"Creating private store directory: {}\", parent.display());\n fs::create_dir_all(parent).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\n \"Failed to create private store dir {}: {}\",\n parent.display(),\n e\n ),\n )))\n })?;\n }\n }\n\n if !did_upgrade {\n // 3. Clean existing app in private store (if any from a failed prior attempt)\n if final_private_store_app_path.exists()\n || final_private_store_app_path.symlink_metadata().is_ok()\n {\n debug!(\n \"Removing existing item at private store path: {}\",\n final_private_store_app_path.display()\n );\n let _ = remove_path_robustly(&final_private_store_app_path, config, false);\n }\n\n // 4. Move from temporary stage to private store\n debug!(\n \"Moving staged app {} to private store path {}\",\n staged_app_path.display(),\n final_private_store_app_path.display()\n );\n if let Err(e) = fs::rename(staged_app_path, &final_private_store_app_path) {\n error!(\n \"Failed to move staged app to private store: {}. Source: {}, Dest: {}\",\n e,\n staged_app_path.display(),\n final_private_store_app_path.display()\n );\n return Err(SpsError::Io(std::sync::Arc::new(e)));\n }\n }\n\n // 5. Set/Verify Quarantine on private store copy (only if not already present)\n #[cfg(target_os = \"macos\")]\n {\n debug!(\n \"Setting/verifying quarantine on private store copy: {}\",\n final_private_store_app_path.display()\n );\n if let Err(e) = crate::utils::xattr::ensure_quarantine_attribute(\n &final_private_store_app_path,\n &cask.token,\n ) {\n error!(\n \"Failed to set quarantine on private store copy {}: {}. This is critical.\",\n final_private_store_app_path.display(),\n e\n );\n return Err(SpsError::InstallError(format!(\n \"Failed to set quarantine on private store copy {}: {}\",\n final_private_store_app_path.display(),\n e\n )));\n }\n }\n\n // ============================================================================\n // STEP 6: Handle /Applications Destination - THE MOST CRITICAL PART\n // ============================================================================\n // This is where we apply Homebrew's breakthrough strategy that preserves\n // user data and prevents Gatekeeper resets during upgrades.\n //\n // UPGRADE vs FRESH INSTALL Strategy:\n // - UPGRADE: Overwrite app in /Applications directly (preserves identity)\n // - FRESH INSTALL: Use symlink approach (normal installation)\n //\n // WHY THIS SPLIT MATTERS:\n // During upgrades, the app in /Applications already has:\n // 1. Gatekeeper approval and quarantine exemptions\n // 2. Extended attributes that macOS recognizes\n // 3. User trust and security context\n // 4. Associated user data in ~/Library that the app can access\n //\n // By overwriting IN PLACE with cp -pR, we maintain all of this state.\n // ============================================================================\n\n if let JobAction::Upgrade { .. } = job_action {\n // =======================================================================\n // UPGRADE PATH: Direct Overwrite Strategy (Homebrew's Approach)\n // =======================================================================\n // This is the breakthrough that prevents Gatekeeper resets and data loss.\n // We overwrite the existing app directly rather than removing and\n // re-symlinking, which would break the app's established identity.\n // =======================================================================\n\n if final_app_destination_in_applications.exists() {\n debug!(\n \"UPGRADE: Overwriting existing app at /Applications using Homebrew strategy: {}\",\n final_app_destination_in_applications.display()\n );\n\n // Step 1: Remove the old app in /Applications\n // We need sudo because /Applications requires elevated permissions\n let rm_status = Command::new(\"sudo\")\n .arg(\"rm\")\n .arg(\"-rf\")\n .arg(&final_app_destination_in_applications)\n .status()\n .map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n\n if !rm_status.success() {\n return Err(SpsError::InstallError(format!(\n \"Failed to remove existing app during upgrade: {}\",\n final_app_destination_in_applications.display()\n )));\n }\n\n // Copy the new app directly to /Applications, preserving all attributes\n let cp_status = Command::new(\"sudo\")\n .arg(\"cp\")\n .arg(\"-pR\") // Preserve all attributes, links, and metadata\n .arg(&final_private_store_app_path)\n .arg(&final_app_destination_in_applications)\n .status()\n .map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n\n if !cp_status.success() {\n return Err(SpsError::InstallError(format!(\n \"Failed to copy new app to /Applications during upgrade: {}\",\n final_app_destination_in_applications.display()\n )));\n }\n\n debug!(\n \"UPGRADE: Successfully overwrote app in /Applications, preserving identity: {}\",\n final_app_destination_in_applications.display()\n );\n } else {\n // App doesn't exist in /Applications during upgrade - fall back to symlink approach\n debug!(\n \"UPGRADE: App not found in /Applications, creating fresh symlink: {}\",\n final_app_destination_in_applications.display()\n );\n if let Err(e) = std::os::unix::fs::symlink(\n &final_private_store_app_path,\n &final_app_destination_in_applications,\n ) {\n error!(\n \"Failed to symlink app from private store to /Applications: {} -> {}: {}\",\n final_private_store_app_path.display(),\n final_app_destination_in_applications.display(),\n e\n );\n return Err(SpsError::InstallError(format!(\n \"Failed to symlink app from private store to {}: {}\",\n final_app_destination_in_applications.display(),\n e\n )));\n }\n }\n } else {\n // Fresh install: Clean existing app destination and create symlink\n if final_app_destination_in_applications.exists()\n || final_app_destination_in_applications\n .symlink_metadata()\n .is_ok()\n {\n debug!(\n \"Removing existing app at /Applications: {}\",\n final_app_destination_in_applications.display()\n );\n if !remove_path_robustly(&final_app_destination_in_applications, config, true) {\n return Err(SpsError::InstallError(format!(\n \"Failed to remove existing app at {}\",\n final_app_destination_in_applications.display()\n )));\n }\n }\n\n // 7. Symlink from /Applications to private store app bundle\n debug!(\n \"INFO: About to symlink app from private store {} to /Applications {}\",\n final_private_store_app_path.display(),\n final_app_destination_in_applications.display()\n );\n if let Err(e) = std::os::unix::fs::symlink(\n &final_private_store_app_path,\n &final_app_destination_in_applications,\n ) {\n error!(\n \"Failed to symlink app from private store to /Applications: {} -> {}: {}\",\n final_private_store_app_path.display(),\n final_app_destination_in_applications.display(),\n e\n );\n return Err(SpsError::InstallError(format!(\n \"Failed to symlink app from private store to {}: {}\",\n final_app_destination_in_applications.display(),\n e\n )));\n }\n }\n\n // Remove quarantine attributes from the app in /Applications (whether copied or symlinked)\n #[cfg(target_os = \"macos\")]\n {\n use xattr;\n let _ = xattr::remove(\n &final_app_destination_in_applications,\n \"com.apple.quarantine\",\n );\n let _ = xattr::remove(\n &final_app_destination_in_applications,\n \"com.apple.provenance\",\n );\n let _ = xattr::remove(&final_app_destination_in_applications, \"com.apple.macl\");\n }\n\n match job_action {\n JobAction::Upgrade { .. } => {\n debug!(\n \"INFO: Successfully updated app in /Applications during upgrade: {}\",\n final_app_destination_in_applications.display()\n );\n }\n _ => {\n debug!(\n \"INFO: Successfully symlinked app from private store {} to /Applications {}\",\n final_private_store_app_path.display(),\n final_app_destination_in_applications.display()\n );\n }\n }\n\n // 7. No quarantine set on the symlink in /Applications; attribute remains on private store\n // copy.\n\n // 8. Create Caskroom Symlink TO the app in /Applications\n let actual_caskroom_symlink_path = cask_version_install_path.join(app_name.as_ref());\n debug!(\n \"Creating Caskroom symlink {} -> {}\",\n actual_caskroom_symlink_path.display(),\n final_app_destination_in_applications.display()\n );\n\n if actual_caskroom_symlink_path.symlink_metadata().is_ok() {\n if let Err(e) = fs::remove_file(&actual_caskroom_symlink_path) {\n warn!(\n \"Failed to remove existing item at Caskroom symlink path {}: {}. Proceeding.\",\n actual_caskroom_symlink_path.display(),\n e\n );\n }\n }\n\n #[cfg(unix)]\n {\n if let Err(e) = std::os::unix::fs::symlink(\n &final_app_destination_in_applications,\n &actual_caskroom_symlink_path,\n ) {\n error!(\n \"Failed to create Caskroom symlink {} -> {}: {}\",\n actual_caskroom_symlink_path.display(),\n final_app_destination_in_applications.display(),\n e\n );\n let _ = remove_path_robustly(&final_app_destination_in_applications, config, true);\n return Err(SpsError::Io(std::sync::Arc::new(e)));\n }\n }\n\n let mut created_artifacts = vec![InstalledArtifact::AppBundle {\n path: final_app_destination_in_applications.clone(),\n }];\n created_artifacts.push(InstalledArtifact::CaskroomLink {\n link_path: actual_caskroom_symlink_path,\n target_path: final_app_destination_in_applications.clone(),\n });\n\n debug!(\n \"Successfully installed app artifact: {} (Cask: {})\",\n app_name, cask.token\n );\n\n // Write CASK_INSTALL_MANIFEST.json to ensure package is always detected as installed\n if let Err(e) = crate::install::cask::write_cask_manifest(\n cask,\n cask_version_install_path,\n created_artifacts.clone(),\n ) {\n error!(\n \"Failed to write CASK_INSTALL_MANIFEST.json for {}: {}\",\n cask.token, e\n );\n return Err(SpsError::InstallError(format!(\n \"Failed to write CASK_INSTALL_MANIFEST.json for {}: {}\",\n cask.token, e\n )));\n }\n\n Ok(created_artifacts)\n}\n\n/// Helper function for robust path removal (internal to app.rs or moved to a common util)\nfn remove_path_robustly(path: &Path, _config: &Config, use_sudo_if_needed: bool) -> bool {\n if !path.exists() && path.symlink_metadata().is_err() {\n debug!(\"Path {} not found for removal.\", path.display());\n return true;\n }\n let is_dir = path.is_dir()\n && !path\n .symlink_metadata()\n .is_ok_and(|m| m.file_type().is_symlink());\n let removal_op = || -> std::io::Result<()> {\n if is_dir {\n fs::remove_dir_all(path)\n } else {\n fs::remove_file(path)\n }\n };\n\n if let Err(e) = removal_op() {\n if e.kind() == std::io::ErrorKind::NotFound {\n return true;\n }\n if use_sudo_if_needed && e.kind() == std::io::ErrorKind::PermissionDenied {\n warn!(\n \"Direct removal of {} failed (Permission Denied). Trying with sudo rm -rf.\",\n path.display()\n );\n let output = Command::new(\"sudo\").arg(\"rm\").arg(\"-rf\").arg(path).output();\n match output {\n Ok(out) if out.status.success() => {\n debug!(\"Successfully removed {} with sudo.\", path.display());\n return true;\n }\n Ok(out) => {\n error!(\n \"`sudo rm -rf {}` failed ({}): {}\",\n path.display(),\n out.status,\n String::from_utf8_lossy(&out.stderr).trim()\n );\n return false;\n }\n Err(sudo_e) => {\n error!(\n \"Error executing `sudo rm -rf` for {}: {}\",\n path.display(),\n sudo_e\n );\n return false;\n }\n }\n } else {\n error!(\"Failed to remove {}: {}\", path.display(), e);\n return false;\n }\n }\n debug!(\"Successfully removed {}.\", path.display());\n true\n}\n"], ["/sps/sps-core/src/install/cask/mod.rs", "pub mod artifacts;\npub mod dmg;\npub mod helpers;\n\nuse std::fs;\nuse std::path::{Path, PathBuf};\nuse std::time::{SystemTime, SystemTimeError, UNIX_EPOCH};\n\nuse infer;\nuse reqwest::Url;\nuse serde::{Deserialize, Serialize};\nuse serde_json::json;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::{Cask, Sha256Field, UrlField};\nuse sps_net::http::ProgressCallback;\nuse tempfile::TempDir;\nuse tracing::{debug, error};\n\nuse crate::install::extract;\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub struct CaskInstallManifest {\n pub manifest_format_version: String,\n pub token: String,\n pub version: String,\n pub installed_at: u64,\n pub artifacts: Vec,\n pub primary_app_file_name: Option,\n pub is_installed: bool, // New flag for soft uninstall\n pub cask_store_path: Option, // Path to private store app, if available\n}\n\n/// Returns the path to the cask's version directory in the private store.\npub fn sps_private_cask_version_dir(cask: &Cask, config: &Config) -> PathBuf {\n let version = cask.version.clone().unwrap_or_else(|| \"latest\".to_string());\n config.cask_store_version_path(&cask.token, &version)\n}\n\n/// Returns the path to the cask's token directory in the private store.\npub fn sps_private_cask_token_dir(cask: &Cask, config: &Config) -> PathBuf {\n config.cask_store_token_path(&cask.token)\n}\n\n/// Returns the path to the main app bundle for a cask in the private store.\n/// This assumes the primary app bundle is named as specified in the cask's artifacts.\npub fn sps_private_cask_app_path(cask: &Cask, config: &Config) -> Option {\n let version = cask.version.clone().unwrap_or_else(|| \"latest\".to_string());\n if let Some(cask_artifacts) = &cask.artifacts {\n for artifact in cask_artifacts {\n if let Some(obj) = artifact.as_object() {\n if let Some(apps) = obj.get(\"app\") {\n if let Some(app_names) = apps.as_array() {\n if let Some(app_name_val) = app_names.first() {\n if let Some(app_name) = app_name_val.as_str() {\n return Some(config.cask_store_app_path(\n &cask.token,\n &version,\n app_name,\n ));\n }\n }\n }\n }\n }\n }\n }\n None\n}\n\npub async fn download_cask(cask: &Cask, cache: &Cache) -> Result {\n download_cask_with_progress(cask, cache, None).await\n}\n\npub async fn download_cask_with_progress(\n cask: &Cask,\n cache: &Cache,\n progress_callback: Option,\n) -> Result {\n let url_field = cask\n .url\n .as_ref()\n .ok_or_else(|| SpsError::Generic(format!(\"Cask {} has no URL\", cask.token)))?;\n let url_str = match url_field {\n UrlField::Simple(u) => u.as_str(),\n UrlField::WithSpec { url, .. } => url.as_str(),\n };\n\n if url_str.is_empty() {\n return Err(SpsError::Generic(format!(\n \"Cask {} has an empty URL\",\n cask.token\n )));\n }\n\n debug!(\"Downloading cask from {}\", url_str);\n let parsed = Url::parse(url_str)\n .map_err(|e| SpsError::Generic(format!(\"Invalid URL '{url_str}': {e}\")))?;\n sps_net::validation::validate_url(parsed.as_str())?;\n let file_name = parsed\n .path_segments()\n .and_then(|mut segments| segments.next_back())\n .filter(|s| !s.is_empty())\n .map(|s| s.to_string())\n .unwrap_or_else(|| {\n debug!(\"URL has no filename component, using fallback name for cache based on token.\");\n format!(\"cask-{}-download.tmp\", cask.token.replace('/', \"_\"))\n });\n let cache_key = format!(\"cask-{}-{}\", cask.token, file_name);\n let cache_path = cache.get_dir().join(\"cask_downloads\").join(&cache_key);\n\n if cache_path.exists() {\n debug!(\"Using cached download: {}\", cache_path.display());\n return Ok(cache_path);\n }\n\n use futures::StreamExt;\n use tokio::fs::File as TokioFile;\n use tokio::io::AsyncWriteExt;\n\n let client = reqwest::Client::new();\n let response = client\n .get(parsed.clone())\n .send()\n .await\n .map_err(|e| SpsError::Http(std::sync::Arc::new(e)))?;\n if !response.status().is_success() {\n return Err(SpsError::DownloadError(\n cask.token.clone(),\n url_str.to_string(),\n format!(\"HTTP status {}\", response.status()),\n ));\n }\n\n // Get total size from Content-Length header if available\n let total_size = response.content_length();\n\n if let Some(parent) = cache_path.parent() {\n fs::create_dir_all(parent)?;\n }\n\n let mut file = TokioFile::create(&cache_path)\n .await\n .map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n\n // Use bytes_stream() for chunked download with progress reporting\n let mut stream = response.bytes_stream();\n let mut bytes_downloaded = 0u64;\n\n while let Some(chunk) = stream.next().await {\n let chunk = chunk.map_err(|e| SpsError::Http(std::sync::Arc::new(e)))?;\n\n file.write_all(&chunk)\n .await\n .map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n\n bytes_downloaded += chunk.len() as u64;\n\n // Call progress callback if provided\n if let Some(ref callback) = progress_callback {\n callback(bytes_downloaded, total_size);\n }\n }\n\n drop(file);\n match cask.sha256.as_ref() {\n Some(Sha256Field::Hex(s)) => {\n if s.eq_ignore_ascii_case(\"no_check\") {\n tracing::debug!(\n \"Skipping checksum verification for cask {} due to 'no_check' string.\",\n cache_path.display()\n );\n } else if !s.is_empty() {\n match sps_net::validation::verify_checksum(&cache_path, s) {\n Ok(_) => {\n tracing::debug!(\n \"Cask download checksum verified: {}\",\n cache_path.display()\n );\n }\n Err(e) => {\n tracing::error!(\n \"Cask download checksum mismatch ({}). Deleting cached file.\",\n e\n );\n let _ = fs::remove_file(&cache_path);\n return Err(e);\n }\n }\n } else {\n tracing::warn!(\n \"Skipping checksum verification for cask {} - empty sha256 provided.\",\n cache_path.display()\n );\n }\n }\n Some(Sha256Field::NoCheck { no_check: true }) => {\n tracing::debug!(\n \"Skipping checksum verification for cask {} due to 'no_check'.\",\n cache_path.display()\n );\n }\n _ => {\n tracing::warn!(\n \"Skipping checksum verification for cask {} - none provided.\",\n cache_path.display()\n );\n }\n }\n debug!(\"Download completed: {}\", cache_path.display());\n\n // --- Set quarantine xattr on the downloaded archive (macOS only) ---\n #[cfg(target_os = \"macos\")]\n {\n if let Err(e) = crate::utils::xattr::set_quarantine_attribute(&cache_path, \"sps-downloader\")\n {\n tracing::warn!(\n \"Failed to set quarantine attribute on downloaded archive {}: {}. Extraction and installation will proceed, but Gatekeeper behavior might be affected.\",\n cache_path.display(),\n e\n );\n }\n }\n\n Ok(cache_path)\n}\n\nuse sps_common::pipeline::JobAction;\n\npub fn install_cask(\n cask: &Cask,\n download_path: &Path,\n config: &Config,\n job_action: &JobAction,\n) -> Result<()> {\n debug!(\"Installing cask: {}\", cask.token);\n // This is the path in the *actual* Caskroom (e.g., /opt/homebrew/Caskroom/token/version)\n // where metadata and symlinks to /Applications will go.\n let actual_cask_room_version_path = config.cask_room_version_path(\n &cask.token,\n &cask.version.clone().unwrap_or_else(|| \"latest\".to_string()),\n );\n\n if !actual_cask_room_version_path.exists() {\n fs::create_dir_all(&actual_cask_room_version_path).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\n \"Failed create cask_room dir {}: {}\",\n actual_cask_room_version_path.display(),\n e\n ),\n )))\n })?;\n debug!(\n \"Created actual cask_room version directory: {}\",\n actual_cask_room_version_path.display()\n );\n }\n let mut detected_extension = download_path\n .extension()\n .and_then(|e| e.to_str())\n .unwrap_or(\"\")\n .to_lowercase();\n let non_extensions = [\"stable\", \"latest\", \"download\", \"bin\", \"\"];\n if non_extensions.contains(&detected_extension.as_str()) {\n debug!(\n \"Download path '{}' has no definite extension ('{}'), attempting content detection.\",\n download_path.display(),\n detected_extension\n );\n match infer::get_from_path(download_path) {\n Ok(Some(kind)) => {\n detected_extension = kind.extension().to_string();\n debug!(\"Detected file type via content: {}\", detected_extension);\n }\n Ok(None) => {\n error!(\n \"Could not determine file type from content for: {}\",\n download_path.display()\n );\n return Err(SpsError::Generic(format!(\n \"Could not determine file type for download: {}\",\n download_path.display()\n )));\n }\n Err(e) => {\n error!(\n \"Error reading file for type detection {}: {}\",\n download_path.display(),\n e\n );\n return Err(SpsError::Io(std::sync::Arc::new(e)));\n }\n }\n } else {\n debug!(\n \"Using file extension for type detection: {}\",\n detected_extension\n );\n }\n if detected_extension == \"pkg\" || detected_extension == \"mpkg\" {\n debug!(\"Detected PKG installer, running directly\");\n match artifacts::pkg::install_pkg_from_path(\n cask,\n download_path,\n &actual_cask_room_version_path, // PKG manifest items go into the actual cask_room\n config,\n ) {\n Ok(installed_artifacts) => {\n debug!(\"Writing PKG install manifest\");\n write_cask_manifest(cask, &actual_cask_room_version_path, installed_artifacts)?;\n debug!(\"Successfully installed PKG cask: {}\", cask.token);\n return Ok(());\n }\n Err(e) => {\n debug!(\"Failed to install PKG: {}\", e);\n // Clean up cask_room on error\n let _ = fs::remove_dir_all(&actual_cask_room_version_path);\n return Err(e);\n }\n }\n }\n let stage_dir = TempDir::new().map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed to create staging directory: {e}\"),\n )))\n })?;\n let stage_path = stage_dir.path();\n debug!(\"Created staging directory: {}\", stage_path.display());\n // Determine expected extension (this might need refinement)\n // Option 1: Parse from URL\n let expected_ext_from_url = download_path\n .extension()\n .and_then(|e| e.to_str())\n .unwrap_or(\"\");\n // Option 2: A new field in Cask JSON definition (preferred)\n // let expected_ext = cask.expected_extension.as_deref().unwrap_or(expected_ext_from_url);\n let expected_ext = expected_ext_from_url; // Use URL for now\n\n if !expected_ext.is_empty()\n && crate::build::compile::RECOGNISED_SINGLE_FILE_EXTENSIONS.contains(&expected_ext)\n {\n // Check if it's an archive/installer type we handle\n tracing::debug!(\n \"Verifying content type for {} against expected extension '{}'\",\n download_path.display(),\n expected_ext\n );\n if let Err(e) = sps_net::validation::verify_content_type(download_path, expected_ext) {\n tracing::error!(\"Content type verification failed: {}\", e);\n // Attempt cleanup?\n let _ = fs::remove_dir_all(&actual_cask_room_version_path);\n return Err(e);\n }\n } else {\n tracing::debug!(\n \"Skipping content type verification for {} (unknown/no expected extension: '{}')\",\n download_path.display(),\n expected_ext\n );\n }\n match detected_extension.as_str() {\n \"dmg\" => {\n debug!(\n \"Extracting DMG {} to stage {}...\",\n download_path.display(),\n stage_path.display()\n );\n dmg::extract_dmg_to_stage(download_path, stage_path)?;\n debug!(\"Successfully extracted DMG to staging area.\");\n }\n \"zip\" => {\n debug!(\n \"Extracting ZIP {} to stage {}...\",\n download_path.display(),\n stage_path.display()\n );\n extract::extract_archive(download_path, stage_path, 0, \"zip\")?;\n debug!(\"Successfully extracted ZIP to staging area.\");\n }\n \"gz\" | \"bz2\" | \"xz\" | \"tar\" => {\n let archive_type_for_extraction = detected_extension.as_str();\n debug!(\n \"Extracting TAR archive ({}) {} to stage {}...\",\n archive_type_for_extraction,\n download_path.display(),\n stage_path.display()\n );\n extract::extract_archive(download_path, stage_path, 0, archive_type_for_extraction)?;\n debug!(\"Successfully extracted TAR archive to staging area.\");\n }\n _ => {\n error!(\n \"Unsupported container/installer type '{}' for staged installation derived from {}\",\n detected_extension,\n download_path.display()\n );\n return Err(SpsError::Generic(format!(\n \"Unsupported file type for staged installation: {detected_extension}\"\n )));\n }\n }\n let mut all_installed_artifacts: Vec = Vec::new();\n let mut artifact_install_errors = Vec::new();\n if let Some(artifacts_def) = &cask.artifacts {\n debug!(\n \"Processing {} declared artifacts from staging area...\",\n artifacts_def.len()\n );\n for artifact_value in artifacts_def.iter() {\n if let Some(artifact_obj) = artifact_value.as_object() {\n if let Some((key, value)) = artifact_obj.iter().next() {\n debug!(\"Processing artifact type: {}\", key);\n let result: Result> = match key.as_str() {\n \"app\" => {\n let mut app_artifacts = vec![];\n if let Some(app_names) = value.as_array() {\n for app_name_val in app_names {\n if let Some(app_name) = app_name_val.as_str() {\n let staged_app_path = stage_path.join(app_name);\n debug!(\n \"Attempting to install app artifact: {}\",\n staged_app_path.display()\n );\n match artifacts::app::install_app_from_staged(\n cask,\n &staged_app_path,\n &actual_cask_room_version_path,\n config,\n job_action, // Pass job_action for upgrade logic\n ) {\n Ok(mut artifacts) => {\n app_artifacts.append(&mut artifacts)\n }\n Err(e) => {\n return Err(e);\n }\n }\n } else {\n debug!(\n \"Non-string value found in 'app' artifact array: {:?}\",\n app_name_val\n );\n }\n }\n } else {\n debug!(\"'app' artifact value is not an array: {:?}\", value);\n }\n Ok(app_artifacts)\n }\n \"pkg\" => {\n let mut installed_pkgs = vec![];\n if let Some(pkg_names) = value.as_array() {\n for pkg_val in pkg_names {\n if let Some(pkg_name) = pkg_val.as_str() {\n let staged_pkg_path = stage_path.join(pkg_name);\n debug!(\n \"Attempting to install staged pkg artifact: {}\",\n staged_pkg_path.display()\n );\n match artifacts::pkg::install_pkg_from_path(\n cask,\n &staged_pkg_path,\n &actual_cask_room_version_path, /* Pass actual\n * cask_room path */\n config,\n ) {\n Ok(mut artifacts) => {\n installed_pkgs.append(&mut artifacts)\n }\n Err(e) => {\n return Err(e);\n }\n }\n } else {\n debug!(\n \"Non-string value found in 'pkg' artifact array: {:?}\",\n pkg_val\n );\n }\n }\n } else {\n debug!(\"'pkg' artifact value is not an array: {:?}\", value);\n }\n Ok(installed_pkgs)\n }\n _ => {\n debug!(\"Artifact type '{}' not supported yet — skipping.\", key);\n Ok(vec![])\n }\n };\n match result {\n Ok(installed) => {\n if !installed.is_empty() {\n debug!(\n \"Successfully processed artifact '{}', added {} items.\",\n key,\n installed.len()\n );\n all_installed_artifacts.extend(installed);\n } else {\n debug!(\n \"Artifact handler for '{}' completed successfully but returned no artifacts.\",\n key\n );\n }\n }\n Err(e) => {\n error!(\"Error processing artifact '{}': {}\", key, e);\n artifact_install_errors.push(e);\n }\n }\n } else {\n debug!(\"Empty artifact object found: {:?}\", artifact_obj);\n }\n } else {\n debug!(\n \"Unexpected non-object artifact found in list: {:?}\",\n artifact_value\n );\n }\n }\n } else {\n error!(\n \"Cask {} definition is missing the required 'artifacts' array. Cannot determine what to install.\",\n cask.token\n );\n // Clean up the created actual_caskroom_version_path if no artifacts are defined\n let _ = fs::remove_dir_all(&actual_cask_room_version_path);\n return Err(SpsError::InstallError(format!(\n \"Cask '{}' has no artifacts defined.\",\n cask.token\n )));\n }\n if !artifact_install_errors.is_empty() {\n error!(\n \"Encountered {} errors installing artifacts for cask '{}'. Installation incomplete.\",\n artifact_install_errors.len(),\n cask.token\n );\n let _ = fs::remove_dir_all(&actual_cask_room_version_path); // Clean up actual cask_room on error\n return Err(artifact_install_errors.remove(0));\n }\n let actual_install_count = all_installed_artifacts\n .iter()\n .filter(|a| {\n !matches!(\n a,\n InstalledArtifact::PkgUtilReceipt { .. } | InstalledArtifact::Launchd { .. }\n )\n })\n .count();\n if actual_install_count == 0 {\n debug!(\n \"No installable artifacts (like app, pkg, binary, etc.) were processed for cask '{}' from the staged content. Check cask definition.\",\n cask.token\n );\n write_cask_manifest(\n cask,\n &actual_cask_room_version_path,\n all_installed_artifacts,\n )?;\n } else {\n debug!(\"Writing cask installation manifest\");\n write_cask_manifest(\n cask,\n &actual_cask_room_version_path,\n all_installed_artifacts,\n )?;\n }\n debug!(\"Successfully installed cask: {}\", cask.token);\n Ok(())\n}\n\n#[deprecated(note = \"Use write_cask_manifest with detailed InstalledArtifact enum instead\")]\npub fn write_receipt(\n cask: &Cask,\n cask_version_install_path: &Path,\n artifacts: Vec,\n) -> Result<()> {\n let receipt_path = cask_version_install_path.join(\"INSTALL_RECEIPT.json\");\n debug!(\"Writing legacy cask receipt: {}\", receipt_path.display());\n let timestamp = SystemTime::now()\n .duration_since(UNIX_EPOCH)\n .map_err(|e: SystemTimeError| SpsError::Generic(format!(\"System time error: {e}\")))?\n .as_secs();\n let receipt_data = json!({\n \"token\": cask.token,\n \"name\": cask.name.as_ref().and_then(|n| n.first()).cloned(),\n \"version\": cask.version.as_ref().unwrap_or(&\"latest\".to_string()),\n \"installed_at\": timestamp,\n \"artifacts_installed\": artifacts\n });\n if let Some(parent) = receipt_path.parent() {\n fs::create_dir_all(parent).map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n }\n let mut file =\n fs::File::create(&receipt_path).map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n serde_json::to_writer_pretty(&mut file, &receipt_data)\n .map_err(|e| SpsError::Json(std::sync::Arc::new(e)))?;\n debug!(\n \"Successfully wrote legacy receipt with {} artifact entries.\",\n artifacts.len()\n );\n Ok(())\n}\n\npub fn write_cask_manifest(\n cask: &Cask,\n cask_version_install_path: &Path,\n artifacts: Vec,\n) -> Result<()> {\n let manifest_path = cask_version_install_path.join(\"CASK_INSTALL_MANIFEST.json\");\n debug!(\"Writing cask manifest: {}\", manifest_path.display());\n let timestamp = SystemTime::now()\n .duration_since(UNIX_EPOCH)\n .map_err(|e: SystemTimeError| SpsError::Generic(format!(\"System time error: {e}\")))?\n .as_secs();\n\n // Determine primary app file name from artifacts\n let primary_app_file_name = artifacts.iter().find_map(|artifact| {\n if let InstalledArtifact::AppBundle { path } = artifact {\n path.file_name()\n .map(|name| name.to_string_lossy().to_string())\n } else {\n None\n }\n });\n\n // Always set is_installed=true when writing manifest (install or reinstall)\n // Try to determine cask_store_path from artifacts (AppBundle or CaskroomLink)\n let cask_store_path = artifacts.iter().find_map(|artifact| match artifact {\n InstalledArtifact::AppBundle { path } => Some(path.to_string_lossy().to_string()),\n InstalledArtifact::CaskroomLink { target_path, .. } => {\n Some(target_path.to_string_lossy().to_string())\n }\n _ => None,\n });\n\n let manifest_data = CaskInstallManifest {\n manifest_format_version: \"1.0\".to_string(),\n token: cask.token.clone(),\n version: cask.version.clone().unwrap_or_else(|| \"latest\".to_string()),\n installed_at: timestamp,\n artifacts,\n primary_app_file_name,\n is_installed: true,\n cask_store_path,\n };\n if let Some(parent) = manifest_path.parent() {\n fs::create_dir_all(parent).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed create parent dir {}: {}\", parent.display(), e),\n )))\n })?;\n }\n let file = fs::File::create(&manifest_path).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed create manifest {}: {}\", manifest_path.display(), e),\n )))\n })?;\n let writer = std::io::BufWriter::new(file);\n serde_json::to_writer_pretty(writer, &manifest_data).map_err(|e| {\n error!(\n \"Failed to serialize cask manifest JSON for {}: {}\",\n cask.token, e\n );\n SpsError::Json(std::sync::Arc::new(e))\n })?;\n debug!(\n \"Successfully wrote cask manifest with {} artifact entries.\",\n manifest_data.artifacts.len()\n );\n Ok(())\n}\n\n/// Recursively cleans up empty parent directories in the private cask store.\n/// Starts from the given path and walks up, removing empty directories until a non-empty or root is\n/// found.\npub fn cleanup_empty_parent_dirs_in_private_store(start_path: &Path, stop_at: &Path) {\n let mut current = start_path.parent().unwrap_or(start_path).to_path_buf(); // Start from parent\n while current != *stop_at {\n if let Ok(read_dir) = fs::read_dir(¤t) {\n if read_dir.count() == 0 {\n match fs::remove_dir(¤t) {\n Ok(_) => {\n debug!(\"Removed empty directory: {}\", current.display());\n }\n Err(e) => {\n debug!(\"Failed to remove directory {}: {}\", current.display(), e);\n break;\n }\n }\n } else {\n break;\n }\n } else {\n break;\n }\n if let Some(parent) = current.parent() {\n current = parent.to_path_buf();\n } else {\n break;\n }\n }\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/zap.rs", "// ===== sps-core/src/build/cask/artifacts/zap.rs =====\n\nuse std::fs;\nuse std::path::{Path, PathBuf}; // Import Path\nuse std::process::{Command, Stdio};\n\nuse regex::Regex;\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::InstalledArtifact;\n\n/// Implements the `zap` stanza by performing deep-clean actions\n/// such as trash, delete, rmdir, pkgutil forget, launchctl unload,\n/// and arbitrary scripts, matching Homebrew's Cask behavior.\npub fn install_zap(cask: &Cask, config: &Config) -> Result> {\n let mut artifacts: Vec = Vec::new();\n let home = config.home_dir();\n\n if let Some(entries) = &cask.artifacts {\n for entry in entries {\n if let Some(obj) = entry.as_object() {\n if let Some(zaps) = obj.get(\"zap\").and_then(|v| v.as_array()) {\n for zap_map in zaps {\n if let Some(zap_obj) = zap_map.as_object() {\n for (key, val) in zap_obj {\n match key.as_str() {\n \"trash\" => {\n if let Some(arr) = val.as_array() {\n for item in arr.iter().filter_map(|v| v.as_str()) {\n let target = expand_tilde(item, &home); // Pass &Path\n if !is_safe_path(&target, &home) {\n debug!(\n \"Unsafe trash path {}, skipping\",\n target.display()\n );\n continue;\n }\n debug!(\"Trashing {}...\", target.display());\n let _ = Command::new(\"trash\")\n .arg(&target)\n .stdout(Stdio::null())\n .stderr(Stdio::null())\n .status();\n }\n }\n }\n \"delete\" => {\n if let Some(arr) = val.as_array() {\n for item in arr.iter().filter_map(|v| v.as_str()) {\n let target = expand_tilde(item, &home); // Pass &Path\n if !is_safe_path(&target, &home) {\n debug!(\n \"Unsafe delete path {}, skipping\",\n target.display()\n );\n continue;\n }\n debug!(\"Deleting file {}...\", target.display());\n if let Err(e) = fs::remove_file(&target) {\n if e.kind() != std::io::ErrorKind::NotFound {\n debug!(\n \"Failed to delete {}: {}\",\n target.display(),\n e\n );\n }\n }\n }\n }\n }\n \"rmdir\" => {\n if let Some(arr) = val.as_array() {\n for item in arr.iter().filter_map(|v| v.as_str()) {\n let target = expand_tilde(item, &home); // Pass &Path\n if !is_safe_path(&target, &home) {\n debug!(\n \"Unsafe rmdir path {}, skipping\",\n target.display()\n );\n continue;\n }\n debug!(\n \"Removing directory {}...\",\n target.display()\n );\n if let Err(e) = fs::remove_dir_all(&target) {\n if e.kind() != std::io::ErrorKind::NotFound {\n debug!(\n \"Failed to rmdir {}: {}\",\n target.display(),\n e\n );\n }\n }\n }\n }\n }\n \"pkgutil\" => {\n if let Some(arr) = val.as_array() {\n for item in arr.iter().filter_map(|v| v.as_str()) {\n if !is_valid_pkgid(item) {\n debug!(\n \"Invalid pkgutil id '{}', skipping\",\n item\n );\n continue;\n }\n debug!(\"Forgetting pkgutil receipt {}...\", item);\n let _ = Command::new(\"pkgutil\")\n .arg(\"--forget\")\n .arg(item)\n .stdout(Stdio::null())\n .stderr(Stdio::null())\n .status();\n artifacts.push(InstalledArtifact::PkgUtilReceipt {\n id: item.to_string(),\n });\n }\n }\n }\n \"launchctl\" => {\n if let Some(arr) = val.as_array() {\n for label in arr.iter().filter_map(|v| v.as_str()) {\n if !is_valid_label(label) {\n debug!(\n \"Invalid launchctl label '{}', skipping\",\n label\n );\n continue;\n }\n let plist = home // Use expanded home\n .join(\"Library/LaunchAgents\")\n .join(format!(\"{label}.plist\"));\n if !is_safe_path(&plist, &home) {\n debug!(\n \"Unsafe plist path {} for label {}, skipping\",\n plist.display(),\n label\n );\n continue;\n }\n debug!(\n \"Unloading launchctl {}...\",\n plist.display()\n );\n let _ = Command::new(\"launchctl\")\n .arg(\"unload\")\n .arg(&plist)\n .stdout(Stdio::null())\n .stderr(Stdio::null())\n .status();\n artifacts.push(InstalledArtifact::Launchd {\n label: label.to_string(),\n path: Some(plist),\n });\n }\n }\n }\n \"script\" => {\n if let Some(cmd) = val.as_str() {\n if !is_valid_command(cmd) {\n debug!(\n \"Invalid zap script command '{}', skipping\",\n cmd\n );\n continue;\n }\n debug!(\"Running zap script: {}...\", cmd);\n let _ = Command::new(\"sh\")\n .arg(\"-c\")\n .arg(cmd)\n .stdout(Stdio::null())\n .stderr(Stdio::null())\n .status();\n }\n }\n \"signal\" => {\n if let Some(arr) = val.as_array() {\n for cmd in arr.iter().filter_map(|v| v.as_str()) {\n if !is_valid_command(cmd) {\n debug!(\n \"Invalid signal command '{}', skipping\",\n cmd\n );\n continue;\n }\n debug!(\"Running signal command: {}...\", cmd);\n let _ = Command::new(\"sh\")\n .arg(\"-c\")\n .arg(cmd)\n .stdout(Stdio::null())\n .stderr(Stdio::null())\n .status();\n }\n }\n }\n _ => debug!(\"Unsupported zap key '{}', skipping\", key),\n }\n }\n }\n }\n // Only process the first \"zap\" stanza found\n break;\n }\n }\n }\n }\n\n Ok(artifacts)\n}\n\n// New helper functions to validate paths and strings.\nfn is_safe_path(path: &Path, home: &Path) -> bool {\n if path\n .components()\n .any(|c| matches!(c, std::path::Component::ParentDir))\n {\n return false;\n }\n let path_str = path.to_string_lossy();\n if path.is_absolute()\n && (path_str.starts_with(\"/Applications\") || path_str.starts_with(\"/Library\"))\n {\n return true;\n }\n if path.starts_with(home) {\n return true;\n }\n if path_str.contains(\"Caskroom/Cellar\") {\n return true;\n }\n false\n}\n\nfn is_valid_pkgid(pkgid: &str) -> bool {\n let re = Regex::new(r\"^[a-zA-Z0-9.-]+$\").unwrap();\n re.is_match(pkgid)\n}\n\nfn is_valid_label(label: &str) -> bool {\n let re = Regex::new(r\"^[a-zA-Z0-9.-]+$\").unwrap();\n re.is_match(label)\n}\n\nfn is_valid_command(cmd: &str) -> bool {\n let re = Regex::new(r\"^[a-zA-Z0-9\\s\\-_./]+$\").unwrap();\n re.is_match(cmd)\n}\n\n/// Expand a path that may start with '~' to the user's home directory\nfn expand_tilde(path: &str, home: &Path) -> PathBuf {\n if let Some(stripped) = path.strip_prefix(\"~/\") {\n home.join(stripped)\n } else {\n PathBuf::from(path)\n }\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/pkg.rs", "use std::fs;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::cask::Cask;\nuse tracing::{debug, error};\n\nuse crate::install::cask::InstalledArtifact; // Artifact type alias is just Value\n\n/// Installs a PKG file and returns details of artifacts created/managed.\npub fn install_pkg_from_path(\n cask: &Cask,\n pkg_path: &Path,\n cask_version_install_path: &Path, // e.g., /opt/homebrew/Caskroom/foo/1.2.3\n _config: &Config, // Keep for potential future use\n) -> Result> {\n // <-- Return type changed\n debug!(\"Installing pkg file: {}\", pkg_path.display());\n\n if !pkg_path.exists() || !pkg_path.is_file() {\n return Err(SpsError::NotFound(format!(\n \"Package file not found or is not a file: {}\",\n pkg_path.display()\n )));\n }\n\n let pkg_name = pkg_path\n .file_name()\n .ok_or_else(|| SpsError::Generic(format!(\"Invalid pkg path: {}\", pkg_path.display())))?;\n\n // --- Prepare list for artifacts ---\n let mut installed_artifacts: Vec = Vec::new();\n\n // --- Copy PKG to Caskroom for Reference ---\n let caskroom_pkg_path = cask_version_install_path.join(pkg_name);\n debug!(\n \"Copying pkg to caskroom for reference: {}\",\n caskroom_pkg_path.display()\n );\n if let Some(parent) = caskroom_pkg_path.parent() {\n fs::create_dir_all(parent).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed create parent dir {}: {}\", parent.display(), e),\n )))\n })?;\n }\n if let Err(e) = fs::copy(pkg_path, &caskroom_pkg_path) {\n error!(\n \"Failed to copy PKG {} to {}: {}\",\n pkg_path.display(),\n caskroom_pkg_path.display(),\n e\n );\n return Err(SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed copy PKG to caskroom: {e}\"),\n ))));\n } else {\n // Record the reference copy artifact\n installed_artifacts.push(InstalledArtifact::CaskroomReference {\n path: caskroom_pkg_path.clone(),\n });\n }\n\n // --- Run Installer ---\n debug!(\"Running installer (this may require sudo)\");\n debug!(\n \"Executing: sudo installer -pkg {} -target /\",\n pkg_path.display()\n );\n let output = Command::new(\"sudo\")\n .arg(\"installer\")\n .arg(\"-pkg\")\n .arg(pkg_path)\n .arg(\"-target\")\n .arg(\"/\")\n .output()\n .map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed to execute sudo installer: {e}\"),\n )))\n })?;\n\n if !output.status.success() {\n let stderr = String::from_utf8_lossy(&output.stderr);\n error!(\"sudo installer failed ({}): {}\", output.status, stderr);\n // Don't clean up the reference copy here, let the main process handle directory removal on\n // failure\n return Err(SpsError::InstallError(format!(\n \"Package installation failed for {}: {}\",\n pkg_path.display(),\n stderr\n )));\n }\n debug!(\"Successfully ran installer command.\");\n let stdout = String::from_utf8_lossy(&output.stdout);\n if !stdout.trim().is_empty() {\n debug!(\"Installer stdout:\\n{}\", stdout);\n }\n\n // --- Record PkgUtil Receipts (based on cask definition) ---\n if let Some(artifacts) = &cask.artifacts {\n // artifacts is Option>\n for artifact_value in artifacts.iter() {\n if let Some(uninstall_array) =\n artifact_value.get(\"uninstall\").and_then(|v| v.as_array())\n {\n for stanza_value in uninstall_array {\n if let Some(stanza_obj) = stanza_value.as_object() {\n if let Some(pkgutil_id) = stanza_obj.get(\"pkgutil\").and_then(|v| v.as_str())\n {\n debug!(\"Found pkgutil ID to record: {}\", pkgutil_id);\n // Check for duplicates before adding\n let new_artifact = InstalledArtifact::PkgUtilReceipt {\n id: pkgutil_id.to_string(),\n };\n if !installed_artifacts.contains(&new_artifact) {\n // Need PartialEq for InstalledArtifact\n installed_artifacts.push(new_artifact);\n }\n }\n // Consider other uninstall keys like launchctl, delete?\n }\n }\n }\n // Optionally check \"zap\" stanzas too\n }\n }\n debug!(\"Successfully installed pkg: {}\", pkg_path.display());\n Ok(installed_artifacts) // <-- Return collected artifacts\n}\n"], ["/sps/sps-core/src/pipeline/worker.rs", "// sps-core/src/pipeline/worker.rs\nuse std::fs;\nuse std::path::PathBuf;\nuse std::sync::Arc;\n\nuse futures::executor::block_on;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::dependency::DependencyExt;\nuse sps_common::error::{Result as SpsResult, SpsError};\nuse sps_common::keg::KegRegistry;\nuse sps_common::model::formula::FormulaDependencies;\nuse sps_common::model::InstallTargetIdentifier;\nuse sps_common::pipeline::{JobAction, PipelineEvent, PipelinePackageType, WorkerJob};\nuse tokio::sync::broadcast;\nuse tracing::{debug, error, instrument, warn};\n\nuse crate::check::installed::{InstalledPackageInfo, PackageType as CorePackageType};\nuse crate::{build, install, uninstall, upgrade};\n\npub(super) fn execute_sync_job(\n worker_job: WorkerJob,\n config: &Config,\n cache: Arc,\n event_tx: broadcast::Sender,\n) -> std::result::Result<(JobAction, PipelinePackageType), Box<(JobAction, SpsError)>> {\n let action = worker_job.request.action.clone();\n\n let result = do_execute_sync_steps(worker_job, config, cache, event_tx);\n\n result\n .map_err(|e| Box::new((action.clone(), e)))\n .map(|pkg_type| (action, pkg_type))\n}\n\n#[instrument(skip_all, fields(job_id = %worker_job.request.target_id, action = ?worker_job.request.action))]\nfn do_execute_sync_steps(\n worker_job: WorkerJob,\n config: &Config,\n _cache: Arc, // Marked as unused if cache is not directly used in this function body\n event_tx: broadcast::Sender,\n) -> SpsResult {\n let job_request = worker_job.request;\n let download_path = worker_job.download_path;\n let is_source_from_private_store = worker_job.is_source_from_private_store;\n\n let (core_pkg_type, pipeline_pkg_type) = match &job_request.target_definition {\n InstallTargetIdentifier::Formula(_) => {\n (CorePackageType::Formula, PipelinePackageType::Formula)\n }\n InstallTargetIdentifier::Cask(_) => (CorePackageType::Cask, PipelinePackageType::Cask),\n };\n\n // Check dependencies before proceeding with formula install/upgrade\n if let InstallTargetIdentifier::Formula(formula_arc) = &job_request.target_definition {\n if matches!(job_request.action, JobAction::Install)\n || matches!(job_request.action, JobAction::Upgrade { .. })\n {\n debug!(\n \"[WORKER:{}] Pre-install check for dependencies. Formula: {}, Action: {:?}\",\n job_request.target_id,\n formula_arc.name(),\n job_request.action\n );\n\n let keg_registry = KegRegistry::new(config.clone());\n match formula_arc.dependencies() {\n Ok(dependencies) => {\n for dep in dependencies.runtime() {\n debug!(\"[WORKER:{}] Checking runtime dependency: '{}'. Required by: '{}'. Configured cellar: {}\", job_request.target_id, dep.name, formula_arc.name(), config.cellar_dir().display());\n\n match keg_registry.get_installed_keg(&dep.name) {\n Ok(Some(keg_info)) => {\n debug!(\"[WORKER:{}] Dependency '{}' FOUND by KegRegistry. Path: {}, Version: {}\", job_request.target_id, dep.name, keg_info.path.display(), keg_info.version_str);\n }\n Ok(None) => {\n debug!(\"[WORKER:{}] Dependency '{}' was NOT FOUND by KegRegistry for formula '{}'. THIS IS THE ERROR POINT.\", dep.name, job_request.target_id, formula_arc.name());\n let error_msg = format!(\n \"Runtime dependency '{}' for formula '{}' is not installed. Aborting operation for '{}'.\",\n dep.name, formula_arc.name(), job_request.target_id\n );\n error!(\"{}\", error_msg);\n return Err(SpsError::DependencyError(error_msg));\n }\n Err(e) => {\n debug!(\"[WORKER:{}] Error during KegRegistry check for dependency '{}': {}. Aborting for formula '{}'.\", job_request.target_id, dep.name, e, job_request.target_id);\n return Err(SpsError::Generic(format!(\n \"Failed to check KegRegistry for {}: {}\",\n dep.name, e\n )));\n }\n }\n }\n }\n Err(e) => {\n let error_msg = format!(\n \"Could not retrieve dependency list for formula '{}': {}. Aborting operation.\",\n job_request.target_id, e\n );\n error!(\"{}\", error_msg);\n return Err(SpsError::DependencyError(error_msg));\n }\n }\n debug!(\n \"[WORKER:{}] All required formula dependencies appear to be installed for '{}'.\",\n job_request.target_id,\n formula_arc.name()\n );\n }\n }\n\n let mut formula_installed_path: Option = None;\n\n match &job_request.action {\n JobAction::Upgrade {\n from_version,\n old_install_path,\n } => {\n debug!(\n \"[{}] Upgrading from version {}\",\n job_request.target_id, from_version\n );\n let old_info = InstalledPackageInfo {\n name: job_request.target_id.clone(),\n version: from_version.clone(),\n pkg_type: core_pkg_type.clone(),\n path: old_install_path.clone(),\n };\n\n match &job_request.target_definition {\n InstallTargetIdentifier::Formula(formula) => {\n let http_client_for_bottle_upgrade = Arc::new(reqwest::Client::new());\n let installed_path = if job_request.is_source_build {\n let _ = event_tx.send(PipelineEvent::BuildStarted {\n target_id: job_request.target_id.clone(),\n });\n let all_dep_paths = Vec::new(); // TODO: Populate this correctly if needed by upgrade_source_formula\n block_on(upgrade::source::upgrade_source_formula(\n formula,\n &download_path,\n &old_info,\n config,\n &all_dep_paths,\n ))?\n } else {\n block_on(upgrade::bottle::upgrade_bottle_formula(\n formula,\n &download_path,\n &old_info,\n config,\n http_client_for_bottle_upgrade,\n ))?\n };\n formula_installed_path = Some(installed_path);\n }\n InstallTargetIdentifier::Cask(cask) => {\n block_on(upgrade::cask::upgrade_cask_package(\n cask,\n &download_path,\n &old_info,\n config,\n ))?;\n }\n }\n }\n JobAction::Install | JobAction::Reinstall { .. } => {\n if let JobAction::Reinstall {\n version: from_version,\n current_install_path: old_install_path,\n } = &job_request.action\n {\n debug!(\n \"[{}] Reinstall: Removing existing version {}...\",\n job_request.target_id, from_version\n );\n let _ = event_tx.send(PipelineEvent::UninstallStarted {\n target_id: job_request.target_id.clone(),\n version: from_version.clone(),\n });\n\n let old_info_for_reinstall = InstalledPackageInfo {\n name: job_request.target_id.clone(),\n version: from_version.clone(),\n pkg_type: core_pkg_type.clone(),\n path: old_install_path.clone(),\n };\n let uninstall_opts = uninstall::UninstallOptions { skip_zap: true };\n\n match core_pkg_type {\n CorePackageType::Formula => uninstall::uninstall_formula_artifacts(\n &old_info_for_reinstall,\n config,\n &uninstall_opts,\n )?,\n CorePackageType::Cask => {\n uninstall::uninstall_cask_artifacts(&old_info_for_reinstall, config)?\n }\n }\n debug!(\n \"[{}] Reinstall: Removed existing version {}.\",\n job_request.target_id, from_version\n );\n let _ = event_tx.send(PipelineEvent::UninstallFinished {\n target_id: job_request.target_id.clone(),\n version: from_version.clone(),\n });\n }\n\n let _ = event_tx.send(PipelineEvent::InstallStarted {\n target_id: job_request.target_id.clone(),\n pkg_type: pipeline_pkg_type,\n });\n\n match &job_request.target_definition {\n InstallTargetIdentifier::Formula(formula) => {\n let install_dir_base =\n (**formula).install_prefix(config.cellar_dir().as_path())?;\n if let Some(parent_dir) = install_dir_base.parent() {\n fs::create_dir_all(parent_dir).map_err(|e| SpsError::Io(Arc::new(e)))?;\n }\n\n if job_request.is_source_build {\n debug!(\"[{}] Building from source...\", job_request.target_id);\n let _ = event_tx.send(PipelineEvent::BuildStarted {\n target_id: job_request.target_id.clone(),\n });\n let build_dep_paths: Vec = vec![]; // TODO: Populate this from ResolvedGraph\n\n let build_future = build::compile::build_from_source(\n &download_path,\n formula,\n config,\n &build_dep_paths,\n );\n let installed_dir = block_on(build_future)?;\n formula_installed_path = Some(installed_dir);\n } else {\n debug!(\"[{}] Installing bottle...\", job_request.target_id);\n let installed_dir =\n install::bottle::exec::install_bottle(&download_path, formula, config)?;\n formula_installed_path = Some(installed_dir);\n }\n }\n InstallTargetIdentifier::Cask(cask) => {\n if is_source_from_private_store {\n debug!(\n \"[{}] Reinstalling cask from private store...\",\n job_request.target_id\n );\n\n if let Some(file_name) = download_path.file_name() {\n let app_name = file_name.to_string_lossy().to_string();\n let applications_app_path = config.applications_dir().join(&app_name);\n\n if applications_app_path.exists()\n || applications_app_path.symlink_metadata().is_ok()\n {\n debug!(\n \"Removing existing app at {}\",\n applications_app_path.display()\n );\n let _ = install::cask::helpers::remove_path_robustly(\n &applications_app_path,\n config,\n true,\n );\n }\n\n debug!(\n \"Symlinking app from private store {} to {}\",\n download_path.display(),\n applications_app_path.display()\n );\n if let Err(e) =\n std::os::unix::fs::symlink(&download_path, &applications_app_path)\n {\n return Err(SpsError::InstallError(format!(\n \"Failed to symlink app from private store to {}: {}\",\n applications_app_path.display(),\n e\n )));\n }\n\n let cask_version =\n cask.version.clone().unwrap_or_else(|| \"latest\".to_string());\n let cask_version_path =\n config.cask_room_version_path(&cask.token, &cask_version);\n\n if !cask_version_path.exists() {\n fs::create_dir_all(&cask_version_path)?;\n }\n\n let caskroom_symlink_path = cask_version_path.join(&app_name);\n if caskroom_symlink_path.exists()\n || caskroom_symlink_path.symlink_metadata().is_ok()\n {\n let _ = fs::remove_file(&caskroom_symlink_path);\n }\n\n #[cfg(unix)]\n {\n if let Err(e) = std::os::unix::fs::symlink(\n &applications_app_path,\n &caskroom_symlink_path,\n ) {\n warn!(\"Failed to create Caskroom symlink: {}\", e);\n }\n }\n\n let created_artifacts = vec![\n sps_common::model::artifact::InstalledArtifact::AppBundle {\n path: applications_app_path.clone(),\n },\n sps_common::model::artifact::InstalledArtifact::CaskroomLink {\n link_path: caskroom_symlink_path.clone(),\n target_path: applications_app_path.clone(),\n },\n ];\n\n debug!(\n \"[{}] Writing manifest for private store reinstall...\",\n job_request.target_id\n );\n if let Err(e) = install::cask::write_cask_manifest(\n cask,\n &cask_version_path,\n created_artifacts,\n ) {\n error!(\n \"[{}] Failed to write CASK_INSTALL_MANIFEST.json during private store reinstall: {}\",\n job_request.target_id, e\n );\n return Err(SpsError::InstallError(format!(\n \"Failed to write manifest during private store reinstall for {}: {}\",\n job_request.target_id, e\n )));\n }\n } else {\n return Err(SpsError::InstallError(format!(\n \"Failed to get app name from private store path: {}\",\n download_path.display()\n )));\n }\n } else {\n debug!(\"[{}] Installing cask...\", job_request.target_id);\n install::cask::install_cask(\n cask,\n &download_path,\n config,\n &job_request.action,\n )?;\n }\n }\n }\n }\n };\n\n if let Some(ref installed_path) = formula_installed_path {\n debug!(\n \"[{}] Formula operation resulted in keg path: {}\",\n job_request.target_id,\n installed_path.display()\n );\n } else if core_pkg_type == CorePackageType::Cask {\n debug!(\"[{}] Cask operation completed.\", job_request.target_id);\n }\n\n if let (InstallTargetIdentifier::Formula(formula), Some(keg_path_for_linking)) =\n (&job_request.target_definition, &formula_installed_path)\n {\n debug!(\n \"[{}] Linking artifacts for formula {}...\",\n job_request.target_id,\n (**formula).name()\n );\n let _ = event_tx.send(PipelineEvent::LinkStarted {\n target_id: job_request.target_id.clone(),\n pkg_type: pipeline_pkg_type,\n });\n install::bottle::link::link_formula_artifacts(formula, keg_path_for_linking, config)?;\n debug!(\n \"[{}] Linking complete for formula {}.\",\n job_request.target_id,\n (**formula).name()\n );\n }\n\n Ok(pipeline_pkg_type)\n}\n"], ["/sps/sps-core/src/install/bottle/link.rs", "// ===== sps-core/src/build/formula/link.rs =====\nuse std::fs;\nuse std::io::Write;\nuse std::os::unix::fs as unix_fs;\n#[cfg(unix)]\nuse std::os::unix::fs::PermissionsExt;\nuse std::path::{Path, PathBuf};\n\nuse serde_json;\nuse sps_common::config::Config; // Import Config\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::formula::Formula;\nuse tracing::{debug, error};\n\nconst STANDARD_KEG_DIRS: [&str; 6] = [\"bin\", \"lib\", \"share\", \"include\", \"etc\", \"Frameworks\"];\n\n/// Link all artifacts from a formula's installation directory.\n// Added Config parameter\npub fn link_formula_artifacts(\n formula: &Formula,\n installed_keg_path: &Path,\n config: &Config, // Added config\n) -> Result<()> {\n debug!(\n \"Linking artifacts for {} from {}\",\n formula.name(),\n installed_keg_path.display()\n );\n\n let formula_content_root = determine_content_root(installed_keg_path)?;\n let mut symlinks_created = Vec::::new();\n\n // Use config methods for paths\n let opt_link_path = config.formula_opt_path(formula.name());\n let target_keg_dir = &formula_content_root;\n\n remove_existing_link_target(&opt_link_path)?;\n unix_fs::symlink(target_keg_dir, &opt_link_path).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed to create opt symlink for {}: {}\", formula.name(), e),\n )))\n })?;\n symlinks_created.push(opt_link_path.to_string_lossy().to_string());\n debug!(\n \" Linked opt path: {} -> {}\",\n opt_link_path.display(),\n target_keg_dir.display()\n );\n\n if let Some((base, _version)) = formula.name().split_once('@') {\n let alias_path = config.opt_dir().join(base); // Use config.opt_dir()\n if !alias_path.exists() {\n match unix_fs::symlink(target_keg_dir, &alias_path) {\n Ok(_) => {\n debug!(\n \" Added un‑versioned opt alias: {} -> {}\",\n alias_path.display(),\n target_keg_dir.display()\n );\n symlinks_created.push(alias_path.to_string_lossy().to_string());\n }\n Err(e) => {\n debug!(\n \" Could not create opt alias {}: {}\",\n alias_path.display(),\n e\n );\n }\n }\n }\n }\n\n let standard_artifact_dirs = [\"lib\", \"include\", \"share\"];\n for dir_name in &standard_artifact_dirs {\n let source_subdir = formula_content_root.join(dir_name);\n // Use config.prefix() for target base\n let target_prefix_subdir = config.sps_root().join(dir_name);\n\n if source_subdir.is_dir() {\n fs::create_dir_all(&target_prefix_subdir)?;\n for entry in fs::read_dir(&source_subdir)? {\n let entry = entry?;\n let source_item_path = entry.path();\n let file_name = entry.file_name();\n if file_name.to_string_lossy().starts_with('.') {\n continue;\n }\n\n let target_link = target_prefix_subdir.join(&file_name);\n remove_existing_link_target(&target_link)?;\n unix_fs::symlink(&source_item_path, &target_link).ok(); // ignore errors for individual links?\n symlinks_created.push(target_link.to_string_lossy().to_string());\n debug!(\n \" Linked {} -> {}\",\n target_link.display(),\n source_item_path.display()\n );\n }\n }\n }\n\n // Use config.bin_dir() for target bin\n let target_bin_dir = config.bin_dir();\n fs::create_dir_all(&target_bin_dir).ok();\n\n let source_bin_dir = formula_content_root.join(\"bin\");\n if source_bin_dir.is_dir() {\n create_wrappers_in_dir(\n &source_bin_dir,\n &target_bin_dir,\n &formula_content_root,\n &mut symlinks_created,\n )?;\n }\n let source_libexec_dir = formula_content_root.join(\"libexec\");\n if source_libexec_dir.is_dir() {\n create_wrappers_in_dir(\n &source_libexec_dir,\n &target_bin_dir,\n &formula_content_root,\n &mut symlinks_created,\n )?;\n }\n\n write_install_manifest(installed_keg_path, &symlinks_created)?;\n\n debug!(\n \"Successfully completed linking artifacts for {}\",\n formula.name()\n );\n Ok(())\n}\n\n// remove_existing_link_target, write_install_manifest remain mostly unchanged internally) ...\nfn create_wrappers_in_dir(\n source_dir: &Path,\n target_bin_dir: &Path,\n formula_content_root: &Path,\n wrappers_created: &mut Vec,\n) -> Result<()> {\n debug!(\n \"Scanning for executables in {} to create wrappers in {}\",\n source_dir.display(),\n target_bin_dir.display()\n );\n match fs::read_dir(source_dir) {\n Ok(entries) => {\n for entry_result in entries {\n match entry_result {\n Ok(entry) => {\n let source_item_path = entry.path();\n let file_name = entry.file_name();\n\n if file_name.to_string_lossy().starts_with('.') {\n continue;\n }\n\n if source_item_path.is_dir() {\n create_wrappers_in_dir(\n &source_item_path,\n target_bin_dir,\n formula_content_root,\n wrappers_created,\n )?;\n } else if source_item_path.is_file() {\n match is_executable(&source_item_path) {\n Ok(true) => {\n let wrapper_path = target_bin_dir.join(&file_name);\n debug!(\"Found executable: {}\", source_item_path.display());\n if remove_existing_link_target(&wrapper_path).is_ok() {\n debug!(\n \" Creating wrapper script: {} -> {}\",\n wrapper_path.display(),\n source_item_path.display()\n );\n match create_wrapper_script(\n &source_item_path,\n &wrapper_path,\n formula_content_root,\n ) {\n Ok(_) => {\n debug!(\n \" Created wrapper {} -> {}\",\n wrapper_path.display(),\n source_item_path.display()\n );\n wrappers_created.push(\n wrapper_path.to_string_lossy().to_string(),\n );\n }\n Err(e) => {\n error!(\n \"Failed to create wrapper script {} -> {}: {}\",\n wrapper_path.display(),\n source_item_path.display(),\n e\n );\n }\n }\n }\n }\n Ok(false) => { /* Not executable, ignore */ }\n Err(e) => {\n debug!(\n \" Could not check executable status for {}: {}\",\n source_item_path.display(),\n e\n );\n }\n }\n }\n }\n Err(e) => {\n debug!(\n \" Failed to process directory entry in {}: {}\",\n source_dir.display(),\n e\n );\n }\n }\n }\n }\n Err(e) => {\n debug!(\n \"Failed to read source directory {}: {}\",\n source_dir.display(),\n e\n );\n }\n }\n Ok(())\n}\nfn create_wrapper_script(\n target_executable: &Path,\n wrapper_path: &Path,\n formula_content_root: &Path,\n) -> Result<()> {\n let libexec_path = formula_content_root.join(\"libexec\");\n let perl_lib_path = libexec_path.join(\"lib\").join(\"perl5\");\n let python_lib_path = libexec_path.join(\"vendor\"); // Assuming simple vendor dir\n\n let mut script_content = String::new();\n script_content.push_str(\"#!/bin/bash\\n\");\n script_content.push_str(\"# Wrapper script generated by sp\\n\");\n script_content.push_str(\"set -e\\n\\n\");\n\n if perl_lib_path.exists() && perl_lib_path.is_dir() {\n script_content.push_str(&format!(\n \"export PERL5LIB=\\\"{}:$PERL5LIB\\\"\\n\",\n perl_lib_path.display()\n ));\n debug!(\n \" (Wrapper will set PERL5LIB to {})\",\n perl_lib_path.display()\n );\n }\n if python_lib_path.exists() && python_lib_path.is_dir() {\n script_content.push_str(&format!(\n \"export PYTHONPATH=\\\"{}:$PYTHONPATH\\\"\\n\",\n python_lib_path.display()\n ));\n debug!(\n \" (Wrapper will set PYTHONPATH to {})\",\n python_lib_path.display()\n );\n }\n\n script_content.push_str(&format!(\n \"\\nexec \\\"{}\\\" \\\"$@\\\"\\n\",\n target_executable.display()\n ));\n\n let mut file = fs::File::create(wrapper_path).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed create wrapper {}: {}\", wrapper_path.display(), e),\n )))\n })?;\n file.write_all(script_content.as_bytes()).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed write wrapper {}: {}\", wrapper_path.display(), e),\n )))\n })?;\n\n #[cfg(unix)]\n {\n let metadata = file.metadata()?;\n let mut permissions = metadata.permissions();\n permissions.set_mode(0o755);\n fs::set_permissions(wrapper_path, permissions).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\n \"Failed set wrapper executable {}: {}\",\n wrapper_path.display(),\n e\n ),\n )))\n })?;\n }\n\n Ok(())\n}\n\nfn determine_content_root(installed_keg_path: &Path) -> Result {\n let mut potential_subdirs = Vec::new();\n let mut top_level_files_found = false;\n if !installed_keg_path.is_dir() {\n error!(\n \"Keg path {} does not exist or is not a directory!\",\n installed_keg_path.display()\n );\n return Err(SpsError::NotFound(format!(\n \"Keg path not found: {}\",\n installed_keg_path.display()\n )));\n }\n match fs::read_dir(installed_keg_path) {\n Ok(entries) => {\n for entry_res in entries {\n if let Ok(entry) = entry_res {\n let path = entry.path();\n let file_name = entry.file_name();\n // --- Use OsStr comparison ---\n let file_name_osstr = file_name.as_os_str();\n if file_name_osstr.to_string_lossy().starts_with('.')\n || file_name_osstr == \"INSTALL_MANIFEST.json\"\n || file_name_osstr == \"INSTALL_RECEIPT.json\"\n {\n continue;\n }\n if path.is_dir() {\n // Store both path and name for check later\n potential_subdirs.push((path, file_name.to_string_lossy().to_string()));\n } else if path.is_file() {\n top_level_files_found = true;\n debug!(\n \"Found file '{}' at top level of keg {}, assuming no intermediate dir.\",\n file_name.to_string_lossy(), // Use lossy for display\n installed_keg_path.display()\n );\n break; // Stop scanning if top-level files found\n }\n } else {\n debug!(\n \"Failed to read directory entry in {}: {}\",\n installed_keg_path.display(),\n entry_res.err().unwrap() // Safe unwrap as we are in Err path\n );\n }\n }\n }\n Err(e) => {\n debug!(\n \"Could not read keg directory {} to check for intermediate dir: {}. Assuming keg path is content root.\",\n installed_keg_path.display(),\n e\n );\n return Ok(installed_keg_path.to_path_buf());\n }\n }\n\n // --- MODIFIED LOGIC ---\n if potential_subdirs.len() == 1 && !top_level_files_found {\n // Get the single subdirectory path and name\n let (intermediate_dir_path, intermediate_dir_name) = potential_subdirs.remove(0); // Use remove\n\n // Check if the single directory name is one of the standard install dirs\n if STANDARD_KEG_DIRS.contains(&intermediate_dir_name.as_str()) {\n debug!(\n \"Single directory found ('{}') is a standard directory. Using main keg directory {} as content root.\",\n intermediate_dir_name,\n installed_keg_path.display()\n );\n Ok(installed_keg_path.to_path_buf()) // Use main keg path\n } else {\n // Single dir is NOT a standard name, assume it's an intermediate content root\n debug!(\n \"Detected single non-standard intermediate content directory: {}\",\n intermediate_dir_path.display()\n );\n Ok(intermediate_dir_path) // Use the intermediate dir\n }\n // --- END MODIFIED LOGIC ---\n } else {\n // Handle multiple subdirs or top-level files found case (no change needed here)\n if potential_subdirs.len() > 1 {\n debug!(\n \"Multiple potential content directories found under keg {}. Using main keg directory as content root.\",\n installed_keg_path.display()\n );\n } else if top_level_files_found {\n debug!(\n \"Top-level files found in keg {}. Using main keg directory as content root.\",\n installed_keg_path.display()\n );\n } else if potential_subdirs.is_empty() {\n // Changed from else if to else\n debug!(\n \"No subdirectories or files found (excluding ignored ones) in keg {}. Using main keg directory as content root.\",\n installed_keg_path.display()\n );\n }\n Ok(installed_keg_path.to_path_buf()) // Use main keg path in these cases too\n }\n}\n\nfn remove_existing_link_target(path: &Path) -> Result<()> {\n match path.symlink_metadata() {\n Ok(metadata) => {\n debug!(\n \" Removing existing item at link target: {}\",\n path.display()\n );\n let is_dir = metadata.file_type().is_dir();\n let is_symlink = metadata.file_type().is_symlink();\n let is_real_dir = is_dir && !is_symlink;\n let remove_result = if is_real_dir {\n fs::remove_dir_all(path)\n } else {\n fs::remove_file(path)\n };\n if let Err(e) = remove_result {\n debug!(\n \" Failed to remove existing item at link target {}: {}\",\n path.display(),\n e\n );\n return Err(SpsError::Io(std::sync::Arc::new(e)));\n }\n Ok(())\n }\n Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),\n Err(e) => {\n debug!(\n \" Failed to get metadata for existing item {}: {}\",\n path.display(),\n e\n );\n Err(SpsError::Io(std::sync::Arc::new(e)))\n }\n }\n}\n\nfn write_install_manifest(installed_keg_path: &Path, symlinks_created: &[String]) -> Result<()> {\n let manifest_path = installed_keg_path.join(\"INSTALL_MANIFEST.json\");\n debug!(\"Writing install manifest to: {}\", manifest_path.display());\n match serde_json::to_string_pretty(&symlinks_created) {\n Ok(manifest_json) => match fs::write(&manifest_path, manifest_json) {\n Ok(_) => {\n debug!(\n \"Wrote install manifest with {} links: {}\",\n symlinks_created.len(),\n manifest_path.display()\n );\n }\n Err(e) => {\n error!(\n \"Failed to write install manifest {}: {}\",\n manifest_path.display(),\n e\n );\n return Err(SpsError::Io(std::sync::Arc::new(e)));\n }\n },\n Err(e) => {\n error!(\"Failed to serialize install manifest data: {}\", e);\n return Err(SpsError::Json(std::sync::Arc::new(e)));\n }\n }\n Ok(())\n}\n\npub fn unlink_formula_artifacts(\n formula_name: &str,\n version_str_full: &str, // e.g., \"1.2.3_1\"\n config: &Config,\n) -> Result<()> {\n debug!(\n \"Unlinking artifacts for {} version {}\",\n formula_name, version_str_full\n );\n // Use config method to get expected keg path based on name and version string\n let expected_keg_path = config.formula_keg_path(formula_name, version_str_full);\n let manifest_path = expected_keg_path.join(\"INSTALL_MANIFEST.json\"); // Manifest *inside* the keg\n\n if manifest_path.is_file() {\n debug!(\"Reading install manifest: {}\", manifest_path.display());\n match fs::read_to_string(&manifest_path) {\n Ok(manifest_str) => {\n match serde_json::from_str::>(&manifest_str) {\n Ok(links_to_remove) => {\n let mut unlinked_count = 0;\n let mut removal_errors = 0;\n if links_to_remove.is_empty() {\n debug!(\n \"Install manifest {} is empty. Cannot perform manifest-based unlink.\",\n manifest_path.display()\n );\n } else {\n // Use Config to get base paths for checking ownership/safety\n let opt_base = config.opt_dir();\n let bin_base = config.bin_dir();\n let lib_base = config.sps_root().join(\"lib\");\n let include_base = config.sps_root().join(\"include\");\n let share_base = config.sps_root().join(\"share\");\n // Add etc, sbin etc. if needed\n\n for link_str in links_to_remove {\n let link_path = PathBuf::from(link_str);\n // Check if it's under a managed directory (safety check)\n if link_path.starts_with(&opt_base)\n || link_path.starts_with(&bin_base)\n || link_path.starts_with(&lib_base)\n || link_path.starts_with(&include_base)\n || link_path.starts_with(&share_base)\n {\n match remove_existing_link_target(&link_path) {\n // Use helper\n Ok(_) => {\n debug!(\"Removed link/wrapper: {}\", link_path.display());\n unlinked_count += 1;\n }\n Err(e) => {\n // Log error but continue trying to remove others\n debug!(\n \"Failed to remove link/wrapper {}: {}\",\n link_path.display(),\n e\n );\n removal_errors += 1;\n }\n }\n } else {\n // This indicates a potentially corrupted manifest or a link\n // outside expected areas\n error!(\n \"Manifest contains unexpected link path, skipping removal: {}\",\n link_path.display()\n );\n removal_errors += 1; // Count as an error/problem\n }\n }\n }\n debug!(\n \"Attempted to unlink {} artifacts based on manifest.\",\n unlinked_count\n );\n if removal_errors > 0 {\n error!(\n \"Encountered {} errors while removing links listed in manifest.\",\n removal_errors\n );\n // Decide if this should be a hard error - perhaps not if keg is being\n // removed anyway? For now, just log\n // warnings.\n }\n Ok(()) // Return Ok even if some links failed, keg removal will happen next\n }\n Err(e) => {\n error!(\n \"Failed to parse formula install manifest {}: {}. Proceeding without detailed unlink.\",\n manifest_path.display(),\n e\n );\n // Don't error out, allow keg removal to proceed.\n Ok(())\n }\n }\n }\n Err(e) => {\n error!(\n \"Failed to read formula install manifest {}: {}. Proceeding without detailed unlink.\",\n manifest_path.display(),\n e\n );\n // Don't error out, allow keg removal to proceed.\n Ok(())\n }\n }\n } else {\n debug!(\n \"Warning: No install manifest found at {}. Cannot perform detailed unlink.\",\n manifest_path.display()\n );\n // Don't error out, allow keg removal to proceed.\n Ok(())\n }\n}\n\nfn is_executable(path: &Path) -> Result {\n if !path.try_exists().unwrap_or(false) || !path.is_file() {\n return Ok(false);\n }\n if cfg!(unix) {\n use std::os::unix::fs::PermissionsExt;\n match fs::metadata(path) {\n Ok(metadata) => Ok(metadata.permissions().mode() & 0o111 != 0),\n Err(e) => Err(SpsError::Io(std::sync::Arc::new(e))),\n }\n } else {\n Ok(true)\n }\n}\n"], ["/sps/sps-core/src/install/bottle/exec.rs", "use std::collections::{HashMap, HashSet};\nuse std::fs::{self, File};\nuse std::io::{Read, Write};\nuse std::os::unix::fs::{symlink, PermissionsExt};\nuse std::path::{Path, PathBuf};\nuse std::process::{Command as StdCommand, Stdio};\nuse std::sync::Arc;\n\nuse reqwest::Client;\nuse semver;\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::formula::{BottleFileSpec, Formula, FormulaDependencies};\nuse sps_net::http::ProgressCallback;\nuse sps_net::oci;\nuse sps_net::validation::verify_checksum;\nuse tempfile::NamedTempFile;\nuse tracing::{debug, error, warn};\nuse walkdir::WalkDir;\n\nuse super::macho;\nuse crate::install::bottle::get_current_platform;\nuse crate::install::extract::extract_archive;\n\npub async fn download_bottle(\n formula: &Formula,\n config: &Config,\n client: &Client,\n) -> Result {\n download_bottle_with_progress(formula, config, client, None).await\n}\n\npub async fn download_bottle_with_progress(\n formula: &Formula,\n config: &Config,\n client: &Client,\n progress_callback: Option,\n) -> Result {\n download_bottle_with_progress_and_cache_info(formula, config, client, progress_callback)\n .await\n .map(|(path, _)| path)\n}\n\npub async fn download_bottle_with_progress_and_cache_info(\n formula: &Formula,\n config: &Config,\n client: &Client,\n progress_callback: Option,\n) -> Result<(PathBuf, bool)> {\n debug!(\"Attempting to download bottle for {}\", formula.name);\n let (platform_tag, bottle_file_spec) = get_bottle_for_platform(formula)?;\n debug!(\n \"Selected bottle spec for platform '{}': URL={}, SHA256={}\",\n platform_tag, bottle_file_spec.url, bottle_file_spec.sha256\n );\n if bottle_file_spec.url.is_empty() {\n return Err(SpsError::DownloadError(\n formula.name.clone(),\n \"\".to_string(),\n \"Bottle spec has an empty URL.\".to_string(),\n ));\n }\n let standard_version_str = formula.version_str_full();\n let filename = format!(\n \"{}-{}.{}.bottle.tar.gz\",\n formula.name, standard_version_str, platform_tag\n );\n let cache_dir = config.cache_dir().join(\"bottles\");\n fs::create_dir_all(&cache_dir).map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n let bottle_cache_path = cache_dir.join(&filename);\n if bottle_cache_path.is_file() {\n debug!(\"Bottle found in cache: {}\", bottle_cache_path.display());\n if !bottle_file_spec.sha256.is_empty() {\n match verify_checksum(&bottle_cache_path, &bottle_file_spec.sha256) {\n Ok(_) => {\n debug!(\"Using valid cached bottle: {}\", bottle_cache_path.display());\n return Ok((bottle_cache_path, true));\n }\n Err(e) => {\n debug!(\n \"Cached bottle checksum mismatch ({}): {}. Redownloading.\",\n bottle_cache_path.display(),\n e\n );\n let _ = fs::remove_file(&bottle_cache_path);\n }\n }\n } else {\n warn!(\n \"Using cached bottle without checksum verification (checksum not specified): {}\",\n bottle_cache_path.display()\n );\n return Ok((bottle_cache_path, true));\n }\n } else {\n debug!(\"Bottle not found in cache.\");\n }\n let bottle_url_str = &bottle_file_spec.url;\n let registry_domain = config\n .artifact_domain\n .as_deref()\n .unwrap_or(oci::DEFAULT_GHCR_DOMAIN);\n let is_oci_blob_url = (bottle_url_str.contains(\"://ghcr.io/\")\n || bottle_url_str.contains(registry_domain))\n && bottle_url_str.contains(\"/blobs/sha256:\");\n debug!(\n \"Checking URL type: '{}'. Is OCI Blob URL? {}\",\n bottle_url_str, is_oci_blob_url\n );\n if is_oci_blob_url {\n let expected_digest = bottle_url_str.split(\"/blobs/sha256:\").nth(1).unwrap_or(\"\");\n if expected_digest.is_empty() {\n warn!(\n \"Could not extract expected SHA256 digest from OCI URL: {}\",\n bottle_url_str\n );\n }\n debug!(\n \"Detected OCI blob URL, initiating direct blob download: {} (Digest: {})\",\n bottle_url_str, expected_digest\n );\n match oci::download_oci_blob_with_progress(\n bottle_url_str,\n &bottle_cache_path,\n config,\n client,\n expected_digest,\n progress_callback.clone(),\n )\n .await\n {\n Ok(_) => {\n debug!(\n \"Successfully downloaded OCI blob to {}\",\n bottle_cache_path.display()\n );\n }\n Err(e) => {\n error!(\"Failed to download OCI blob from {}: {}\", bottle_url_str, e);\n let _ = fs::remove_file(&bottle_cache_path);\n return Err(SpsError::DownloadError(\n formula.name.clone(),\n bottle_url_str.to_string(),\n format!(\"Failed to download OCI blob: {e}\"),\n ));\n }\n }\n } else {\n debug!(\n \"Detected standard HTTPS URL, using direct download for: {}\",\n bottle_url_str\n );\n match sps_net::http::fetch_formula_source_or_bottle_with_progress(\n formula.name(),\n bottle_url_str,\n &bottle_file_spec.sha256,\n &[],\n config,\n progress_callback,\n )\n .await\n {\n Ok(downloaded_path) => {\n if downloaded_path != bottle_cache_path {\n debug!(\n \"fetch_formula_source_or_bottle returned path {}. Expected: {}. Assuming correct.\",\n downloaded_path.display(),\n bottle_cache_path.display()\n );\n if !bottle_cache_path.exists() {\n error!(\n \"Downloaded path {} exists, but expected final cache path {} does not!\",\n downloaded_path.display(),\n bottle_cache_path.display()\n );\n return Err(SpsError::Generic(format!(\n \"Download path mismatch and final file missing: {}\",\n bottle_cache_path.display()\n )));\n }\n }\n debug!(\n \"Successfully downloaded directly to {}\",\n bottle_cache_path.display()\n );\n }\n Err(e) => {\n error!(\"Failed to download directly from {}: {}\", bottle_url_str, e);\n return Err(e);\n }\n }\n }\n if !bottle_cache_path.exists() {\n error!(\n \"Bottle download process completed, but the final file {} does not exist.\",\n bottle_cache_path.display()\n );\n return Err(SpsError::Generic(format!(\n \"Bottle file missing after download attempt: {}\",\n bottle_cache_path.display()\n )));\n }\n debug!(\n \"Bottle download successful: {}\",\n bottle_cache_path.display()\n );\n Ok((bottle_cache_path, false))\n}\n\npub fn get_bottle_for_platform(formula: &Formula) -> Result<(String, &BottleFileSpec)> {\n let stable_spec = formula.bottle.stable.as_ref().ok_or_else(|| {\n SpsError::Generic(format!(\n \"Formula '{}' has no stable bottle specification.\",\n formula.name\n ))\n })?;\n if stable_spec.files.is_empty() {\n return Err(SpsError::Generic(format!(\n \"Formula '{}' has no bottle files listed in stable spec.\",\n formula.name\n )));\n }\n let current_platform = get_current_platform();\n if current_platform == \"unknown\" || current_platform.contains(\"unknown\") {\n debug!(\n \"Could not reliably determine current platform ('{}'). Bottle selection might be incorrect.\",\n current_platform\n );\n }\n debug!(\n \"Determining bottle for current platform: {}\",\n current_platform\n );\n debug!(\n \"Available bottle platforms in formula spec: {:?}\",\n stable_spec.files.keys().cloned().collect::>()\n );\n if let Some(spec) = stable_spec.files.get(¤t_platform) {\n debug!(\n \"Found exact bottle match for platform: {}\",\n current_platform\n );\n return Ok((current_platform.clone(), spec));\n }\n debug!(\"No exact match found for {}\", current_platform);\n const ARM_MACOS_VERSIONS: &[&str] = &[\"sequoia\", \"sonoma\", \"ventura\", \"monterey\", \"big_sur\"];\n const INTEL_MACOS_VERSIONS: &[&str] = &[\n \"sequoia\", \"sonoma\", \"ventura\", \"monterey\", \"big_sur\", \"catalina\", \"mojave\",\n ];\n if cfg!(target_os = \"macos\") {\n if let Some(current_os_name) = current_platform\n .strip_prefix(\"arm64_\")\n .or(Some(current_platform.as_str()))\n {\n let version_list = if current_platform.starts_with(\"arm64_\") {\n ARM_MACOS_VERSIONS\n } else {\n INTEL_MACOS_VERSIONS\n };\n if let Some(current_os_index) = version_list.iter().position(|&v| v == current_os_name)\n {\n for target_os_name in version_list.iter().skip(current_os_index) {\n let target_tag = if current_platform.starts_with(\"arm64_\") {\n format!(\"arm64_{target_os_name}\")\n } else {\n target_os_name.to_string()\n };\n if let Some(spec) = stable_spec.files.get(&target_tag) {\n debug!(\n \"No bottle found for exact platform '{}'. Using compatible older bottle '{}'.\",\n current_platform, target_tag\n );\n return Ok((target_tag, spec));\n }\n }\n debug!(\n \"Checked compatible older macOS versions ({:?}), no suitable bottle found.\",\n &version_list[current_os_index..]\n );\n } else {\n debug!(\n \"Current OS '{}' not found in known macOS version list.\",\n current_os_name\n );\n }\n } else {\n debug!(\n \"Could not extract OS name from platform tag '{}'\",\n current_platform\n );\n }\n }\n if current_platform.starts_with(\"arm64_\") {\n if let Some(spec) = stable_spec.files.get(\"arm64_big_sur\") {\n debug!(\n \"No specific OS bottle found for {}. Falling back to 'arm64_big_sur' bottle.\",\n current_platform\n );\n return Ok((\"arm64_big_sur\".to_string(), spec));\n }\n debug!(\"No 'arm64_big_sur' fallback bottle tag found.\");\n } else if cfg!(target_os = \"macos\") {\n if let Some(spec) = stable_spec.files.get(\"big_sur\") {\n debug!(\n \"No specific OS bottle found for {}. Falling back to 'big_sur' bottle.\",\n current_platform\n );\n return Ok((\"big_sur\".to_string(), spec));\n }\n debug!(\"No 'big_sur' fallback bottle tag found.\");\n }\n if let Some(spec) = stable_spec.files.get(\"all\") {\n debug!(\n \"No platform-specific or OS-specific bottle found for {}. Using 'all' platform bottle.\",\n current_platform\n );\n return Ok((\"all\".to_string(), spec));\n }\n debug!(\"No 'all' platform bottle found.\");\n Err(SpsError::DownloadError(\n formula.name.clone(),\n \"\".to_string(),\n format!(\n \"No compatible bottle found for platform '{}'. Available: {:?}\",\n current_platform,\n stable_spec.files.keys().collect::>()\n ),\n ))\n}\n\npub fn install_bottle(bottle_path: &Path, formula: &Formula, config: &Config) -> Result {\n let install_dir = formula.install_prefix(config.cellar_dir().as_path())?;\n if install_dir.exists() {\n debug!(\n \"Removing existing keg directory before installing: {}\",\n install_dir.display()\n );\n fs::remove_dir_all(&install_dir).map_err(|e| {\n SpsError::InstallError(format!(\n \"Failed to remove existing keg {}: {}\",\n install_dir.display(),\n e\n ))\n })?;\n }\n if let Some(parent_dir) = install_dir.parent() {\n fs::create_dir_all(parent_dir).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\n \"Failed to create parent dir {}: {}\",\n parent_dir.display(),\n e\n ),\n )))\n })?;\n } else {\n return Err(SpsError::InstallError(format!(\n \"Could not determine parent directory for install path: {}\",\n install_dir.display()\n )));\n }\n fs::create_dir_all(&install_dir).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed to create keg dir {}: {}\", install_dir.display(), e),\n )))\n })?;\n let strip_components = 2;\n debug!(\n \"Extracting bottle archive {} to {} with strip_components={}\",\n bottle_path.display(),\n install_dir.display(),\n strip_components\n );\n extract_archive(bottle_path, &install_dir, strip_components, \"gz\")?;\n debug!(\n \"Ensuring write permissions for extracted files in {}\",\n install_dir.display()\n );\n ensure_write_permissions(&install_dir)?;\n debug!(\"Performing bottle relocation in {}\", install_dir.display());\n perform_bottle_relocation(formula, &install_dir, config)?;\n ensure_llvm_symlinks(&install_dir, formula, config)?;\n crate::install::bottle::write_receipt(formula, &install_dir, \"bottle\")?;\n debug!(\n \"Bottle installation complete for {} at {}\",\n formula.name(),\n install_dir.display()\n );\n Ok(install_dir)\n}\n\nfn ensure_write_permissions(path: &Path) -> Result<()> {\n if !path.exists() {\n debug!(\n \"Path {} does not exist, cannot ensure write permissions.\",\n path.display()\n );\n return Ok(());\n }\n for entry_result in WalkDir::new(path).into_iter().filter_map(|e| e.ok()) {\n let entry_path = entry_result.path();\n if entry_path == path && entry_result.depth() == 0 {\n continue;\n }\n match fs::metadata(entry_path) {\n Ok(metadata) => {\n let mut perms = metadata.permissions();\n let _is_readonly = perms.readonly();\n #[cfg(unix)]\n {\n let current_mode = perms.mode();\n let new_mode = current_mode | 0o200;\n if new_mode != current_mode {\n perms.set_mode(new_mode);\n let _ = fs::set_permissions(entry_path, perms);\n }\n }\n #[cfg(not(unix))]\n {\n if _is_readonly {\n perms.set_readonly(false);\n let _ = fs::set_permissions(entry_path, perms);\n }\n }\n }\n Err(_e) => {}\n }\n }\n Ok(())\n}\n\nfn perform_bottle_relocation(formula: &Formula, install_dir: &Path, config: &Config) -> Result<()> {\n let mut repl: HashMap = HashMap::new();\n repl.insert(\n \"@@HOMEBREW_CELLAR@@\".into(),\n config.cellar_dir().to_string_lossy().into(),\n );\n repl.insert(\n \"@@HOMEBREW_PREFIX@@\".into(),\n config.sps_root().to_string_lossy().into(),\n );\n let _prefix_path_str = config.sps_root().to_string_lossy();\n let library_path_str = config\n .sps_root()\n .join(\"Library\")\n .to_string_lossy()\n .to_string(); // Assuming Library is under sps_root for this placeholder\n // HOMEBREW_REPOSITORY usually points to the Homebrew/brew git repo, not relevant for sps in\n // this context. If needed for a specific formula, it should point to\n // /opt/sps or similar.\n repl.insert(\n \"@@HOMEBREW_REPOSITORY@@\".into(),\n config.sps_root().to_string_lossy().into(),\n );\n repl.insert(\"@@HOMEBREW_LIBRARY@@\".into(), library_path_str.to_string());\n\n let formula_opt_path = config.formula_opt_path(formula.name());\n let formula_opt_str = formula_opt_path.to_string_lossy();\n let install_dir_str = install_dir.to_string_lossy();\n if formula_opt_str != install_dir_str {\n repl.insert(formula_opt_str.to_string(), install_dir_str.to_string());\n debug!(\n \"Adding self-opt relocation: {} -> {}\",\n formula_opt_str, install_dir_str\n );\n }\n\n if formula.name().starts_with(\"python@\") {\n let version_full = formula.version_str_full();\n let mut parts = version_full.split('.');\n if let (Some(major), Some(minor)) = (parts.next(), parts.next()) {\n let framework_version = format!(\"{major}.{minor}\");\n let framework_dir = install_dir\n .join(\"Frameworks\")\n .join(\"Python.framework\")\n .join(\"Versions\")\n .join(&framework_version);\n let python_lib = framework_dir.join(\"Python\");\n let python_bin = framework_dir\n .join(\"bin\")\n .join(format!(\"python{major}.{minor}\"));\n\n let absolute_python_lib_path_obj = install_dir\n .join(\"Frameworks\")\n .join(\"Python.framework\")\n .join(\"Versions\")\n .join(&framework_version)\n .join(\"Python\");\n let new_id_abs = absolute_python_lib_path_obj.to_str().ok_or_else(|| {\n SpsError::InstallError(format!(\n \"Failed to convert absolute Python library path to string: {}\",\n absolute_python_lib_path_obj.display()\n ))\n })?;\n\n debug!(\n \"Setting absolute ID for {}: {}\",\n python_lib.display(),\n new_id_abs\n );\n let status_id = StdCommand::new(\"install_name_tool\")\n .args([\"-id\", new_id_abs, python_lib.to_str().unwrap()])\n .stdout(Stdio::null())\n .stderr(Stdio::null())\n .status()\n .map_err(|e| SpsError::Io(Arc::new(e)))?;\n if !status_id.success() {\n error!(\"install_name_tool -id failed for {}\", python_lib.display());\n return Err(SpsError::InstallError(format!(\n \"Failed to set absolute id on Python dynamic library: {}\",\n python_lib.display()\n )));\n }\n\n debug!(\"Skipping -add_rpath as absolute paths are used for Python linkage.\");\n\n let old_load_placeholder = format!(\n \"@@HOMEBREW_CELLAR@@/{}/{}/Frameworks/Python.framework/Versions/{}/Python\",\n formula.name(),\n version_full,\n framework_version\n );\n let old_load_resource_placeholder = format!(\n \"@@HOMEBREW_CELLAR@@/{}/{}/Frameworks/Python.framework/Versions/{}/Resources/Python.app/Contents/MacOS/Python\",\n formula.name(),\n version_full,\n framework_version\n );\n let install_dir_str_ref = install_dir.to_string_lossy();\n let abs_old_load = format!(\n \"{install_dir_str_ref}/Frameworks/Python.framework/Versions/{framework_version}/Python\"\n );\n let abs_old_load_resource = format!(\n \"{install_dir_str_ref}/Frameworks/Python.framework/Versions/{framework_version}/Resources/Python.app/Contents/MacOS/Python\"\n );\n\n let run_change = |old: &str, new: &str, target: &Path| -> Result<()> {\n if !target.exists() {\n debug!(\n \"Target {} does not exist, skipping install_name_tool -change.\",\n target.display()\n );\n return Ok(());\n }\n debug!(\n \"Running install_name_tool -change {} {} {}\",\n old,\n new,\n target.display()\n );\n let output = StdCommand::new(\"install_name_tool\")\n .args([\"-change\", old, new, target.to_str().unwrap()])\n .output()\n .map_err(|e| SpsError::Io(Arc::new(e)))?;\n\n if !output.status.success() {\n let stderr = String::from_utf8_lossy(&output.stderr);\n if !stderr.contains(\"file not found\")\n && !stderr.contains(\"no LC_LOAD_DYLIB command specifying file\")\n && !stderr.contains(\"is not a Mach-O file\")\n && !stderr.contains(\"object file format invalid\")\n && !stderr.trim().is_empty()\n {\n error!(\n \"install_name_tool -change failed unexpectedly for target {}: {}\",\n target.display(),\n stderr.trim()\n );\n } else {\n debug!(\n \"install_name_tool -change: old path '{}' likely not found or target '{}' not relevant (stderr: {}).\",\n old,\n target.display(),\n stderr.trim()\n );\n }\n }\n Ok(())\n };\n\n debug!(\"Patching main executable: {}\", python_bin.display());\n run_change(&old_load_placeholder, new_id_abs, &python_bin)?;\n run_change(&old_load_resource_placeholder, new_id_abs, &python_bin)?;\n run_change(&abs_old_load, new_id_abs, &python_bin)?;\n run_change(&abs_old_load_resource, new_id_abs, &python_bin)?;\n\n let python_app = framework_dir\n .join(\"Resources\")\n .join(\"Python.app\")\n .join(\"Contents\")\n .join(\"MacOS\")\n .join(\"Python\");\n\n if python_app.exists() {\n debug!(\n \"Explicitly patching Python.app executable: {}\",\n python_app.display()\n );\n run_change(&old_load_placeholder, new_id_abs, &python_app)?;\n run_change(&abs_old_load, new_id_abs, &python_app)?;\n run_change(&old_load_resource_placeholder, new_id_abs, &python_app)?;\n run_change(&abs_old_load_resource, new_id_abs, &python_app)?;\n } else {\n warn!(\n \"Python.app executable not found at {}, skipping explicit patch.\",\n python_app.display()\n );\n }\n\n codesign_path(&python_lib)?;\n codesign_path(&python_bin)?;\n if python_app.exists() {\n codesign_path(&python_app)?;\n } else {\n debug!(\n \"Python.app binary not found at {}, skipping codesign.\",\n python_app.display()\n );\n }\n }\n }\n\n if let Some(perl_path) = find_brewed_perl(config.sps_root()).or_else(|| {\n if cfg!(target_os = \"macos\") {\n Some(PathBuf::from(\"/usr/bin/perl\"))\n } else {\n None\n }\n }) {\n repl.insert(\n \"@@HOMEBREW_PERL@@\".into(),\n perl_path.to_string_lossy().into(),\n );\n }\n\n match formula.dependencies() {\n Ok(deps) => {\n if let Some(openjdk) = deps\n .iter()\n .find(|d| d.name.starts_with(\"openjdk\"))\n .map(|d| d.name.clone())\n {\n let openjdk_opt = config.formula_opt_path(&openjdk);\n repl.insert(\n \"@@HOMEBREW_JAVA@@\".into(),\n openjdk_opt\n .join(\"libexec/openjdk.jdk/Contents/Home\")\n .to_string_lossy()\n .into(),\n );\n }\n }\n Err(e) => {\n warn!(\n \"Could not check formula dependencies during relocation for {}: {}\",\n formula.name(),\n e\n );\n }\n }\n\n repl.insert(\"HOMEBREW_RELOCATE_RPATHS\".into(), \"1\".into());\n\n let opt_placeholder = format!(\n \"@@HOMEBREW_OPT_{}@@\",\n formula.name().to_uppercase().replace(['-', '+', '.'], \"_\")\n );\n repl.insert(\n opt_placeholder,\n config\n .formula_opt_path(formula.name())\n .to_string_lossy()\n .into(),\n );\n\n match formula.dependencies() {\n Ok(deps) => {\n let llvm_dep_name = deps\n .iter()\n .find(|d| d.name.starts_with(\"llvm\"))\n .map(|d| d.name.clone());\n if let Some(name) = llvm_dep_name {\n let llvm_opt_path = config.formula_opt_path(&name);\n let llvm_lib = llvm_opt_path.join(\"lib\");\n if llvm_lib.is_dir() {\n repl.insert(\n \"@loader_path/../lib\".into(),\n llvm_lib.to_string_lossy().into(),\n );\n repl.insert(\n format!(\n \"@@HOMEBREW_OPT_{}@@/lib\",\n name.to_uppercase().replace(['-', '+', '.'], \"_\")\n ),\n llvm_lib.to_string_lossy().into(),\n );\n }\n }\n }\n Err(e) => {\n warn!(\n \"Could not check formula dependencies during LLVM relocation for {}: {}\",\n formula.name(),\n e\n );\n }\n }\n\n tracing::debug!(\"Relocation table:\");\n for (k, v) in &repl {\n tracing::debug!(\"{} → {}\", k, v);\n }\n original_relocation_scan_and_patch(formula, install_dir, config, repl)\n}\n\nfn original_relocation_scan_and_patch(\n _formula: &Formula,\n install_dir: &Path,\n _config: &Config,\n replacements: HashMap,\n) -> Result<()> {\n let mut text_replaced_count = 0;\n let mut macho_patched_count = 0;\n let mut permission_errors = 0;\n let mut macho_errors = 0;\n let mut io_errors = 0;\n let mut files_to_chmod: Vec = Vec::new();\n for entry in WalkDir::new(install_dir).into_iter().filter_map(|e| e.ok()) {\n let path = entry.path();\n let file_type = entry.file_type();\n if path\n .components()\n .any(|c| c.as_os_str().to_string_lossy().ends_with(\".app\"))\n {\n if file_type.is_file() {\n debug!(\"Skipping relocation inside .app bundle: {}\", path.display());\n }\n continue;\n }\n if file_type.is_symlink() {\n debug!(\"Checking symlink for potential chmod: {}\", path.display());\n if path\n .parent()\n .is_some_and(|p| p.ends_with(\"bin\") || p.ends_with(\"sbin\"))\n {\n files_to_chmod.push(path.to_path_buf());\n }\n continue;\n }\n if !file_type.is_file() {\n continue;\n }\n let (meta, initially_executable) = match fs::metadata(path) {\n Ok(m) => {\n #[cfg(unix)]\n let ie = m.permissions().mode() & 0o111 != 0;\n #[cfg(not(unix))]\n let ie = true;\n (m, ie)\n }\n Err(_e) => {\n debug!(\"Failed to get metadata for {}: {}\", path.display(), _e);\n io_errors += 1;\n continue;\n }\n };\n let is_in_exec_dir = path\n .parent()\n .is_some_and(|p| p.ends_with(\"bin\") || p.ends_with(\"sbin\"));\n if meta.permissions().readonly() {\n #[cfg(unix)]\n {\n let mut perms = meta.permissions();\n let current_mode = perms.mode();\n let new_mode = current_mode | 0o200;\n if new_mode != current_mode {\n perms.set_mode(new_mode);\n if fs::set_permissions(path, perms).is_err() {\n debug!(\n \"Skipping readonly file (and couldn't make writable): {}\",\n path.display()\n );\n continue;\n } else {\n debug!(\"Made readonly file writable: {}\", path.display());\n }\n }\n }\n #[cfg(not(unix))]\n {\n debug!(\n \"Skipping potentially readonly file on non-unix: {}\",\n path.display()\n );\n continue;\n }\n }\n let mut was_modified = false;\n let mut skipped_paths_for_file = Vec::new();\n if cfg!(target_os = \"macos\")\n && (initially_executable\n || is_in_exec_dir\n || path\n .extension()\n .is_some_and(|e| e == \"dylib\" || e == \"so\" || e == \"bundle\"))\n {\n match macho::patch_macho_file(path, &replacements) {\n Ok((true, skipped_paths)) => {\n macho_patched_count += 1;\n was_modified = true;\n skipped_paths_for_file = skipped_paths;\n }\n Ok((false, skipped_paths)) => {\n // Not Mach-O or no patches needed, but might have skipped paths\n skipped_paths_for_file = skipped_paths;\n }\n Err(SpsError::PathTooLongError(e)) => { // Specifically catch path too long\n error!(\n \"Mach-O patch failed (path too long) for {}: {}\",\n path.display(),\n e\n );\n macho_errors += 1;\n // Continue scanning other files even if one fails this way\n continue;\n }\n Err(SpsError::CodesignError(e)) => { // Specifically catch codesign errors\n error!(\n \"Mach-O patch failed (codesign error) for {}: {}\",\n path.display(),\n e\n );\n macho_errors += 1;\n // Continue scanning other files\n continue;\n }\n // Catch generic MachOError or Object error, treat as non-fatal for text replace\n Err(e @ SpsError::MachOError(_))\n | Err(e @ SpsError::Object(_))\n | Err(e @ SpsError::Generic(_)) // Catch Generic errors from patch_macho too\n | Err(e @ SpsError::Io(_)) => { // Catch IO errors from patch_macho\n debug!(\n \"Mach-O processing/patching failed for {}: {}. Skipping Mach-O patch for this file.\",\n path.display(),\n e\n );\n // Don't increment macho_errors here, as we fallback to text replace\n io_errors += 1; // Count as IO or generic error instead\n }\n // Catch other specific errors if needed\n Err(e) => {\n debug!(\n \"Unexpected error during Mach-O check/patch for {}: {}. Falling back to text replacer.\",\n path.display(),\n e\n );\n io_errors += 1;\n }\n }\n\n // Handle paths that were too long for Mach-O patching with install_name_tool fallback\n if !skipped_paths_for_file.is_empty() {\n debug!(\n \"Applying install_name_tool fallback for {} skipped paths in {}\",\n skipped_paths_for_file.len(),\n path.display()\n );\n debug!(\n \"Applying install_name_tool fallback for {} skipped paths in {}\",\n skipped_paths_for_file.len(),\n path.display()\n );\n for skipped in &skipped_paths_for_file {\n match apply_install_name_tool_change(&skipped.old_path, &skipped.new_path, path)\n {\n Ok(()) => {\n debug!(\n \"Successfully applied install_name_tool fallback: '{}' -> '{}' in {}\",\n skipped.old_path, skipped.new_path, path.display()\n );\n was_modified = true;\n }\n Err(e) => {\n warn!(\n \"install_name_tool fallback failed for '{}' -> '{}' in {}: {}\",\n skipped.old_path,\n skipped.new_path,\n path.display(),\n e\n );\n macho_errors += 1;\n }\n }\n }\n }\n }\n // Fallback to text replacement if not modified by Mach-O patching\n if !was_modified {\n // Heuristic check for text file (avoid reading huge binaries)\n let mut is_likely_text = false;\n if meta.len() < 5 * 1024 * 1024 {\n if let Ok(mut f) = File::open(path) {\n let mut buf = [0; 1024];\n match f.read(&mut buf) {\n Ok(n) if n > 0 => {\n if !buf[..n].contains(&0) {\n is_likely_text = true;\n }\n }\n Ok(_) => {\n is_likely_text = true;\n }\n Err(_) => {}\n }\n }\n }\n\n if is_likely_text {\n // Read the file content as string\n if let Ok(content) = fs::read_to_string(path) {\n let mut new_content = content.clone();\n let mut replacements_made = false;\n for (placeholder, replacement) in &replacements {\n if new_content.contains(placeholder) {\n new_content = new_content.replace(placeholder, replacement);\n replacements_made = true;\n }\n }\n // Write back only if changes were made\n if replacements_made {\n match write_text_file_atomic(path, &new_content) {\n Ok(_) => {\n text_replaced_count += 1;\n was_modified = true; // Mark as modified for chmod check\n }\n Err(e) => {\n error!(\n \"Failed to write replaced text to {}: {}\",\n path.display(),\n e\n );\n io_errors += 1;\n }\n }\n }\n } else if meta.len() > 0 {\n debug!(\n \"Could not read {} as string for text replacement.\",\n path.display()\n );\n io_errors += 1;\n }\n } else if meta.len() >= 5 * 1024 * 1024 {\n debug!(\n \"Skipping text replacement for large file: {}\",\n path.display()\n );\n } else {\n debug!(\n \"Skipping text replacement for likely binary file: {}\",\n path.display()\n );\n }\n }\n if was_modified || initially_executable || is_in_exec_dir {\n files_to_chmod.push(path.to_path_buf());\n }\n }\n\n #[cfg(unix)]\n {\n debug!(\n \"Ensuring execute permissions for {} potentially executable files/links\",\n files_to_chmod.len()\n );\n let unique_files_to_chmod: HashSet<_> = files_to_chmod.into_iter().collect();\n for p in &unique_files_to_chmod {\n if !p.exists() && p.symlink_metadata().is_err() {\n debug!(\"Skipping chmod for non-existent path: {}\", p.display());\n continue;\n }\n match fs::symlink_metadata(p) {\n Ok(m) => {\n if m.is_file() {\n let mut perms = m.permissions();\n let current_mode = perms.mode();\n let new_mode = current_mode | 0o111;\n if new_mode != current_mode {\n perms.set_mode(new_mode);\n if let Err(e) = fs::set_permissions(p, perms) {\n debug!(\"Failed to set +x on {}: {}\", p.display(), e);\n permission_errors += 1;\n }\n }\n }\n }\n Err(e) => {\n debug!(\n \"Could not stat {} during final chmod pass: {}\",\n p.display(),\n e\n );\n permission_errors += 1;\n }\n }\n }\n }\n\n debug!(\n \"Relocation scan complete. Text files replaced: {}, Mach-O files patched: {}\",\n text_replaced_count, macho_patched_count\n );\n if permission_errors > 0 || macho_errors > 0 || io_errors > 0 {\n debug!(\n \"Bottle relocation finished with issues: {} chmod errors, {} Mach-O errors, {} IO errors in {}.\",\n permission_errors,\n macho_errors,\n io_errors,\n install_dir.display()\n );\n if macho_errors > 0 {\n return Err(SpsError::InstallError(format!(\n \"Bottle relocation failed due to {} Mach-O errors in {}\",\n macho_errors,\n install_dir.display()\n )));\n }\n }\n Ok(())\n}\n\nfn codesign_path(target: &Path) -> Result<()> {\n debug!(\"Re‑signing: {}\", target.display());\n let status = StdCommand::new(\"codesign\")\n .args([\n \"-s\",\n \"-\",\n \"--force\",\n \"--preserve-metadata=identifier,entitlements\",\n target\n .to_str()\n .ok_or_else(|| SpsError::Generic(\"Non‑UTF8 path for codesign\".into()))?,\n ])\n .stdout(Stdio::null())\n .stderr(Stdio::null())\n .status()\n .map_err(|e| SpsError::Io(Arc::new(e)))?;\n if !status.success() {\n return Err(SpsError::CodesignError(format!(\n \"codesign failed for {}\",\n target.display()\n )));\n }\n Ok(())\n}\nfn write_text_file_atomic(original_path: &Path, content: &str) -> Result<()> {\n let dir = original_path.parent().ok_or_else(|| {\n SpsError::Generic(format!(\n \"Cannot get parent directory for {}\",\n original_path.display()\n ))\n })?;\n // Ensure the directory exists\n fs::create_dir_all(dir).map_err(|e| SpsError::Io(Arc::new(e)))?; // Use Arc::new\n\n let mut temp_file = NamedTempFile::new_in(dir)?;\n let temp_path = temp_file.path().to_path_buf(); // Store path before consuming temp_file\n\n // Write content\n temp_file.write_all(content.as_bytes())?;\n // Ensure data is flushed from application buffer to OS buffer\n temp_file.flush()?;\n // Attempt to sync data from OS buffer to disk (best effort)\n let _ = temp_file.as_file().sync_all();\n\n // Try to preserve original permissions\n let original_perms = fs::metadata(original_path).map(|m| m.permissions()).ok();\n\n // Atomically replace the original file with the temporary file\n temp_file.persist(original_path).map_err(|e| {\n error!(\n \"Failed to persist/rename temporary text file {} over {}: {}\",\n temp_path.display(), // Use stored path for logging\n original_path.display(),\n e.error // Log the underlying IO error\n );\n // Return the IO error wrapped in our error type\n SpsError::Io(Arc::new(e.error)) // Use Arc::new\n })?;\n\n // Restore original permissions if we captured them\n if let Some(perms) = original_perms {\n // Ignore errors setting permissions, best effort\n let _ = fs::set_permissions(original_path, perms);\n }\n Ok(())\n}\n\n#[cfg(unix)]\nfn find_brewed_perl(prefix: &Path) -> Option {\n let opt_dir = prefix.join(\"opt\");\n if !opt_dir.is_dir() {\n return None;\n }\n let mut best: Option<(semver::Version, PathBuf)> = None;\n match fs::read_dir(opt_dir) {\n Ok(entries) => {\n for entry_res in entries.flatten() {\n let name = entry_res.file_name();\n let s = name.to_string_lossy();\n let entry_path = entry_res.path();\n if !entry_path.is_dir() {\n continue;\n }\n if let Some(version_part) = s.strip_prefix(\"perl@\") {\n let version_str_padded = if version_part.contains('.') {\n let parts: Vec<&str> = version_part.split('.').collect();\n match parts.len() {\n 1 => format!(\"{}.0.0\", parts[0]), // e.g., perl@5 -> 5.0.0\n 2 => format!(\"{}.{}.0\", parts[0], parts[1]), /* e.g., perl@5.30 -> */\n // 5.30.0\n _ => version_part.to_string(), // Already 3+ parts\n }\n } else {\n format!(\"{version_part}.0.0\") // e.g., perl@5 -> 5.0.0 (handles case with no\n // dot)\n };\n\n if let Ok(v) = semver::Version::parse(&version_str_padded) {\n let candidate_bin = entry_path.join(\"bin/perl\");\n if candidate_bin.is_file()\n && (best.is_none() || v > best.as_ref().unwrap().0)\n {\n best = Some((v, candidate_bin));\n }\n }\n } else if s == \"perl\" {\n let candidate_bin = entry_path.join(\"bin/perl\");\n if candidate_bin.is_file() && best.is_none() {\n if let Ok(v_base) = semver::Version::parse(\"5.0.0\") {\n best = Some((v_base, candidate_bin));\n }\n }\n }\n }\n }\n Err(_e) => {\n debug!(\"Failed to read opt directory during perl search: {}\", _e);\n }\n }\n best.map(|(_, path)| path)\n}\n\n#[cfg(not(unix))]\nfn find_brewed_perl(_prefix: &Path) -> Option {\n None\n}\nfn ensure_llvm_symlinks(install_dir: &Path, formula: &Formula, config: &Config) -> Result<()> {\n let lib_dir = install_dir.join(\"lib\");\n if !lib_dir.exists() {\n debug!(\n \"Skipping LLVM symlink creation as lib dir is missing in {}\",\n install_dir.display()\n );\n return Ok(());\n }\n\n let llvm_dep_name = match formula.dependencies() {\n Ok(deps) => deps\n .iter()\n .find(|d| d.name.starts_with(\"llvm\"))\n .map(|dep| dep.name.clone()),\n Err(e) => {\n warn!(\n \"Could not check formula dependencies for LLVM symlink creation in {}: {}\",\n formula.name(),\n e\n );\n return Ok(()); // Don't error, just skip\n }\n };\n\n // Proceed only if llvm_dep_name is Some\n let llvm_dep_name = match llvm_dep_name {\n Some(name) => name,\n None => {\n debug!(\n \"Formula {} does not list an LLVM dependency.\",\n formula.name()\n );\n return Ok(());\n }\n };\n\n let llvm_opt_path = config.formula_opt_path(&llvm_dep_name);\n let llvm_lib_filename = if cfg!(target_os = \"macos\") {\n \"libLLVM.dylib\"\n } else if cfg!(target_os = \"linux\") {\n \"libLLVM.so\"\n } else {\n warn!(\"LLVM library filename unknown for target OS, skipping symlink.\");\n return Ok(());\n };\n let llvm_lib_path_in_opt = llvm_opt_path.join(\"lib\").join(llvm_lib_filename);\n if !llvm_lib_path_in_opt.exists() {\n debug!(\n \"Required LLVM library not found at {}. Cannot create symlink in {}.\",\n llvm_lib_path_in_opt.display(),\n formula.name()\n );\n return Ok(());\n }\n let symlink_target_path = lib_dir.join(llvm_lib_filename);\n if symlink_target_path.exists() || symlink_target_path.symlink_metadata().is_ok() {\n debug!(\n \"Symlink or file already exists at {}. Skipping creation.\",\n symlink_target_path.display()\n );\n return Ok(());\n }\n #[cfg(unix)]\n {\n if let Some(parent) = symlink_target_path.parent() {\n if !parent.exists() {\n fs::create_dir_all(parent)?;\n }\n }\n match symlink(&llvm_lib_path_in_opt, &symlink_target_path) {\n Ok(_) => debug!(\n \"Created symlink {} -> {}\",\n symlink_target_path.display(),\n llvm_lib_path_in_opt.display()\n ),\n Err(e) => {\n // Log as warning, don't fail install\n warn!(\n \"Failed to create LLVM symlink {} -> {}: {}\",\n symlink_target_path.display(),\n llvm_lib_path_in_opt.display(),\n e\n );\n }\n }\n\n let rustlib_dir = install_dir.join(\"lib\").join(\"rustlib\");\n if rustlib_dir.is_dir() {\n if let Ok(entries) = fs::read_dir(&rustlib_dir) {\n for entry in entries.flatten() {\n let triple_path = entry.path();\n if triple_path.is_dir() {\n let triple_lib_dir = triple_path.join(\"lib\");\n if triple_lib_dir.is_dir() {\n let nested_symlink = triple_lib_dir.join(llvm_lib_filename);\n\n if nested_symlink.exists() || nested_symlink.symlink_metadata().is_ok()\n {\n debug!(\n \"Symlink or file already exists at {}, skipping.\",\n nested_symlink.display()\n );\n continue;\n }\n\n if let Some(parent) = nested_symlink.parent() {\n let _ = fs::create_dir_all(parent);\n }\n match symlink(&llvm_lib_path_in_opt, &nested_symlink) {\n Ok(_) => debug!(\n \"Created symlink {} -> {}\",\n nested_symlink.display(),\n llvm_lib_path_in_opt.display()\n ),\n Err(e) => warn!(\n \"Failed to create LLVM symlink {} -> {}: {}\",\n nested_symlink.display(),\n llvm_lib_path_in_opt.display(),\n e\n ),\n }\n }\n }\n }\n }\n }\n }\n Ok(())\n}\n\n/// Applies a path change using install_name_tool as a fallback for Mach-O files\n/// where the path replacement is too long for direct binary patching.\nfn apply_install_name_tool_change(old_path: &str, new_path: &str, target: &Path) -> Result<()> {\n if !target.exists() {\n debug!(\n \"Target {} does not exist, skipping install_name_tool fallback.\",\n target.display()\n );\n return Ok(());\n }\n\n debug!(\n \"Running install_name_tool -change {} {} {}\",\n old_path,\n new_path,\n target.display()\n );\n\n let output = StdCommand::new(\"install_name_tool\")\n .args([\"-change\", old_path, new_path, target.to_str().unwrap()])\n .output()\n .map_err(|e| SpsError::Io(Arc::new(e)))?;\n\n if !output.status.success() {\n let stderr = String::from_utf8_lossy(&output.stderr);\n if !stderr.contains(\"file not found\")\n && !stderr.contains(\"no LC_LOAD_DYLIB command specifying file\")\n && !stderr.contains(\"is not a Mach-O file\")\n && !stderr.contains(\"object file format invalid\")\n && !stderr.trim().is_empty()\n {\n error!(\n \"install_name_tool -change failed unexpectedly for target {}: {}\",\n target.display(),\n stderr.trim()\n );\n return Err(SpsError::InstallError(format!(\n \"install_name_tool failed for {}: {}\",\n target.display(),\n stderr.trim()\n )));\n } else {\n debug!(\n \"install_name_tool -change: old path '{}' likely not found or target '{}' not relevant (stderr: {}).\",\n old_path,\n target.display(),\n stderr.trim()\n );\n return Ok(()); // No changes made, skip re-signing\n }\n }\n\n // Re-sign the binary after making changes (required on Apple Silicon)\n #[cfg(all(target_os = \"macos\", target_arch = \"aarch64\"))]\n {\n debug!(\n \"Re-signing binary after install_name_tool change: {}\",\n target.display()\n );\n codesign_path(target)?;\n }\n\n debug!(\n \"Successfully applied install_name_tool fallback for {} -> {} in {}\",\n old_path,\n new_path,\n target.display()\n );\n\n Ok(())\n}\n"], ["/sps/sps/src/pipeline/planner.rs", "// sps/src/pipeline/planner.rs\nuse std::collections::{HashMap, HashSet, VecDeque};\nuse std::path::{Path, PathBuf};\nuse std::sync::Arc;\n\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::dependency::resolver::{\n DependencyResolver, NodeInstallStrategy, PerTargetInstallPreferences, ResolutionContext,\n ResolutionStatus, ResolvedGraph,\n};\nuse sps_common::error::{Result as SpsResult, SpsError};\nuse sps_common::formulary::Formulary;\nuse sps_common::keg::KegRegistry;\nuse sps_common::model::{Cask, Formula, InstallTargetIdentifier};\nuse sps_common::pipeline::{JobAction, PipelineEvent, PlannedJob, PlannedOperations};\nuse sps_core::check::installed::{self, InstalledPackageInfo, PackageType as CorePackageType};\nuse sps_core::check::update::{self, UpdateInfo};\nuse tokio::sync::broadcast;\nuse tokio::task::JoinSet;\nuse tracing::{debug, error as trace_error, instrument, warn};\n\nuse super::runner::{get_panic_message, CommandType, PipelineFlags};\n\npub(crate) type PlanResult = SpsResult;\n\n#[derive(Debug, Default)]\nstruct IntermediatePlan {\n initial_ops: HashMap)>,\n errors: Vec<(String, SpsError)>,\n already_satisfied: HashSet,\n processed_globally: HashSet,\n private_store_sources: HashMap,\n}\n\n#[instrument(skip(cache))]\npub(crate) async fn fetch_target_definitions(\n names: &[String],\n cache: Arc,\n) -> HashMap> {\n let mut results = HashMap::new();\n if names.is_empty() {\n return results;\n }\n let mut futures = JoinSet::new();\n\n let formulae_map_handle = tokio::spawn(load_or_fetch_formulae_map(cache.clone()));\n let casks_map_handle = tokio::spawn(load_or_fetch_casks_map(cache.clone()));\n\n let formulae_map = match formulae_map_handle.await {\n Ok(Ok(map)) => Some(map),\n Ok(Err(e)) => {\n debug!(\"[FetchDefs] Failed to load/fetch full formulae list: {}\", e);\n None\n }\n Err(e) => {\n warn!(\n \"[FetchDefs] Formulae map loading task panicked: {}\",\n get_panic_message(e.into_panic()) // Ensure get_panic_message is accessible\n );\n None\n }\n };\n let casks_map = match casks_map_handle.await {\n Ok(Ok(map)) => Some(map),\n Ok(Err(e)) => {\n debug!(\"[FetchDefs] Failed to load/fetch full casks list: {}\", e);\n None\n }\n Err(e) => {\n warn!(\n \"[FetchDefs] Casks map loading task panicked: {}\",\n get_panic_message(e.into_panic()) // Ensure get_panic_message is accessible\n );\n None\n }\n };\n\n for name_str in names {\n let name_owned = name_str.to_string();\n let local_formulae_map = formulae_map.clone();\n let local_casks_map = casks_map.clone();\n\n futures.spawn(async move {\n if let Some(ref map) = local_formulae_map {\n if let Some(f_arc) = map.get(&name_owned) {\n return (name_owned, Ok(InstallTargetIdentifier::Formula(f_arc.clone())));\n }\n }\n if let Some(ref map) = local_casks_map {\n if let Some(c_arc) = map.get(&name_owned) {\n return (name_owned, Ok(InstallTargetIdentifier::Cask(c_arc.clone())));\n }\n }\n debug!(\"[FetchDefs] Definition for '{}' not found in cached lists, fetching directly from API...\", name_owned);\n match sps_net::api::get_formula(&name_owned).await {\n Ok(formula_obj) => return (name_owned, Ok(InstallTargetIdentifier::Formula(Arc::new(formula_obj)))),\n Err(SpsError::NotFound(_)) => {}\n Err(e) => return (name_owned, Err(e)),\n }\n match sps_net::api::get_cask(&name_owned).await {\n Ok(cask_obj) => (name_owned, Ok(InstallTargetIdentifier::Cask(Arc::new(cask_obj)))),\n Err(SpsError::NotFound(_)) => (name_owned.clone(), Err(SpsError::NotFound(format!(\"Formula or Cask '{name_owned}' not found\")))),\n Err(e) => (name_owned, Err(e)),\n }\n });\n }\n\n while let Some(res) = futures.join_next().await {\n match res {\n Ok((name, result)) => {\n results.insert(name, result);\n }\n Err(e) => {\n let panic_message = get_panic_message(e.into_panic());\n trace_error!(\n \"[FetchDefs] Task panicked during definition fetch: {}\",\n panic_message\n );\n results.insert(\n format!(\"[unknown_target_due_to_panic_{}]\", results.len()),\n Err(SpsError::Generic(format!(\n \"Definition fetching task panicked: {panic_message}\"\n ))),\n );\n }\n }\n }\n results\n}\n\nasync fn load_or_fetch_formulae_map(cache: Arc) -> SpsResult>> {\n match cache.load_raw(\"formula.json\") {\n Ok(data) => {\n let formulas: Vec = serde_json::from_str(&data)\n .map_err(|e| SpsError::Cache(format!(\"Parse cached formula.json failed: {e}\")))?;\n Ok(formulas\n .into_iter()\n .map(|f| (f.name.clone(), Arc::new(f)))\n .collect())\n }\n Err(_) => {\n debug!(\"[FetchDefs] Cache miss for formula.json, fetching from API...\");\n let raw_data = sps_net::api::fetch_all_formulas().await?;\n if let Err(e) = cache.store_raw(\"formula.json\", &raw_data) {\n warn!(\"Failed to store formula.json in cache: {}\", e);\n }\n let formulas: Vec =\n serde_json::from_str(&raw_data).map_err(|e| SpsError::Json(Arc::new(e)))?;\n Ok(formulas\n .into_iter()\n .map(|f| (f.name.clone(), Arc::new(f)))\n .collect())\n }\n }\n}\n\nasync fn load_or_fetch_casks_map(cache: Arc) -> SpsResult>> {\n match cache.load_raw(\"cask.json\") {\n Ok(data) => {\n let casks: Vec = serde_json::from_str(&data)\n .map_err(|e| SpsError::Cache(format!(\"Parse cached cask.json failed: {e}\")))?;\n Ok(casks\n .into_iter()\n .map(|c| (c.token.clone(), Arc::new(c)))\n .collect())\n }\n Err(_) => {\n debug!(\"[FetchDefs] Cache miss for cask.json, fetching from API...\");\n let raw_data = sps_net::api::fetch_all_casks().await?;\n if let Err(e) = cache.store_raw(\"cask.json\", &raw_data) {\n warn!(\"Failed to store cask.json in cache: {}\", e);\n }\n let casks: Vec =\n serde_json::from_str(&raw_data).map_err(|e| SpsError::Json(Arc::new(e)))?;\n Ok(casks\n .into_iter()\n .map(|c| (c.token.clone(), Arc::new(c)))\n .collect())\n }\n }\n}\n\npub(crate) struct OperationPlanner<'a> {\n config: &'a Config,\n cache: Arc,\n flags: &'a PipelineFlags,\n event_tx: broadcast::Sender,\n}\n\nimpl<'a> OperationPlanner<'a> {\n pub fn new(\n config: &'a Config,\n cache: Arc,\n flags: &'a PipelineFlags,\n event_tx: broadcast::Sender,\n ) -> Self {\n Self {\n config,\n cache,\n flags,\n event_tx,\n }\n }\n\n fn get_previous_installation_type(&self, old_keg_path: &Path) -> Option {\n let receipt_path = old_keg_path.join(\"INSTALL_RECEIPT.json\");\n if !receipt_path.is_file() {\n tracing::debug!(\n \"No INSTALL_RECEIPT.json found at {} for previous version.\",\n receipt_path.display()\n );\n return None;\n }\n\n match std::fs::read_to_string(&receipt_path) {\n Ok(content) => match serde_json::from_str::(&content) {\n Ok(json_value) => {\n let inst_type = json_value\n .get(\"installation_type\")\n .and_then(|it| it.as_str())\n .map(String::from);\n tracing::debug!(\n \"Previous installation type for {}: {:?}\",\n old_keg_path.display(),\n inst_type\n );\n inst_type\n }\n Err(e) => {\n tracing::warn!(\"Failed to parse INSTALL_RECEIPT.json at {}: {}. Cannot determine previous installation type.\", receipt_path.display(), e);\n None\n }\n },\n Err(e) => {\n tracing::warn!(\"Failed to read INSTALL_RECEIPT.json at {}: {}. Cannot determine previous installation type.\", receipt_path.display(), e);\n None\n }\n }\n }\n\n async fn check_installed_status(&self, name: &str) -> PlanResult> {\n installed::get_installed_package(name, self.config).await\n }\n\n async fn determine_cask_private_store_source(\n &self,\n name: &str,\n version_for_path: &str,\n ) -> Option {\n let cask_def_res = fetch_target_definitions(&[name.to_string()], self.cache.clone())\n .await\n .remove(name);\n\n if let Some(Ok(InstallTargetIdentifier::Cask(cask_arc))) = cask_def_res {\n if let Some(artifacts) = &cask_arc.artifacts {\n for artifact_entry in artifacts {\n if let Some(app_array) = artifact_entry.get(\"app\").and_then(|v| v.as_array()) {\n if let Some(app_name_val) = app_array.first() {\n if let Some(app_name_str) = app_name_val.as_str() {\n let private_path = self.config.cask_store_app_path(\n name,\n version_for_path,\n app_name_str,\n );\n if private_path.exists() && private_path.is_dir() {\n debug!(\"[Planner] Found reusable Cask private store bundle for {} version {}: {}\", name, version_for_path, private_path.display());\n return Some(private_path);\n }\n }\n }\n break;\n }\n }\n }\n }\n None\n }\n\n async fn plan_for_install(&self, targets: &[String]) -> PlanResult {\n let mut plan = IntermediatePlan::default();\n for name in targets {\n if plan.processed_globally.contains(name) {\n continue;\n }\n match self.check_installed_status(name).await {\n Ok(Some(installed_info)) => {\n let mut proceed_with_install = false;\n if installed_info.pkg_type == CorePackageType::Cask {\n let manifest_path = installed_info.path.join(\"CASK_INSTALL_MANIFEST.json\");\n if manifest_path.is_file() {\n if let Ok(manifest_str) = std::fs::read_to_string(&manifest_path) {\n if let Ok(manifest_json) =\n serde_json::from_str::(&manifest_str)\n {\n if let Some(is_installed_flag) =\n manifest_json.get(\"is_installed\").and_then(|v| v.as_bool())\n {\n if !is_installed_flag {\n debug!(\"Cask '{}' found but marked as not installed in manifest. Proceeding with install.\", name);\n proceed_with_install = true;\n }\n }\n }\n }\n } else {\n debug!(\n \"Cask '{}' found but manifest missing. Assuming needs install.\",\n name\n );\n proceed_with_install = true;\n }\n }\n if proceed_with_install {\n if let Some(private_path) = self\n .determine_cask_private_store_source(name, &installed_info.version)\n .await\n {\n plan.private_store_sources\n .insert(name.clone(), private_path);\n }\n plan.initial_ops\n .insert(name.clone(), (JobAction::Install, None));\n } else {\n debug!(\"Target '{}' already installed and manifest indicates it. Marking as satisfied.\", name);\n plan.already_satisfied.insert(name.clone());\n plan.processed_globally.insert(name.clone());\n }\n }\n Ok(None) => {\n if let Some(private_path) = self\n .determine_cask_private_store_source(name, \"latest\")\n .await\n {\n plan.private_store_sources\n .insert(name.clone(), private_path);\n }\n plan.initial_ops\n .insert(name.clone(), (JobAction::Install, None));\n }\n Err(e) => {\n plan.errors.push((\n name.clone(),\n SpsError::Generic(format!(\n \"Failed to check installed status for {name}: {e}\"\n )),\n ));\n plan.processed_globally.insert(name.clone());\n }\n }\n }\n Ok(plan)\n }\n\n async fn plan_for_reinstall(&self, targets: &[String]) -> PlanResult {\n let mut plan = IntermediatePlan::default();\n for name in targets {\n if plan.processed_globally.contains(name) {\n continue;\n }\n match self.check_installed_status(name).await {\n Ok(Some(installed_info)) => {\n if installed_info.pkg_type == CorePackageType::Cask {\n if let Some(private_path) = self\n .determine_cask_private_store_source(name, &installed_info.version)\n .await\n {\n plan.private_store_sources\n .insert(name.clone(), private_path);\n }\n }\n plan.initial_ops.insert(\n name.clone(),\n (\n JobAction::Reinstall {\n version: installed_info.version.clone(),\n current_install_path: installed_info.path.clone(),\n },\n None,\n ),\n );\n }\n Ok(None) => {\n plan.errors.push((\n name.clone(),\n SpsError::NotFound(format!(\"Cannot reinstall '{name}': not installed.\")),\n ));\n plan.processed_globally.insert(name.clone());\n }\n Err(e) => {\n plan.errors.push((\n name.clone(),\n SpsError::Generic(format!(\"Failed to check status for '{name}': {e}\")),\n ));\n plan.processed_globally.insert(name.clone());\n }\n }\n }\n Ok(plan)\n }\n\n async fn plan_for_upgrade(\n &self,\n targets: &[String],\n all: bool,\n ) -> PlanResult {\n let mut plan = IntermediatePlan::default();\n let packages_to_check = if all {\n installed::get_installed_packages(self.config)\n .await\n .map_err(|e| {\n plan.errors.push((\n \"\".to_string(),\n SpsError::Generic(format!(\"Failed to get installed packages: {e}\")),\n ));\n e\n })?\n } else {\n let mut specific = Vec::new();\n for name in targets {\n match self.check_installed_status(name).await {\n Ok(Some(info)) => {\n if info.pkg_type == CorePackageType::Cask {\n let manifest_path = info.path.join(\"CASK_INSTALL_MANIFEST.json\");\n if manifest_path.is_file() {\n if let Ok(manifest_str) = std::fs::read_to_string(&manifest_path) {\n if let Ok(manifest_json) =\n serde_json::from_str::(&manifest_str)\n {\n if !manifest_json\n .get(\"is_installed\")\n .and_then(|v| v.as_bool())\n .unwrap_or(true)\n {\n debug!(\"Skipping upgrade for Cask '{}' as its manifest indicates it's not fully installed.\", name);\n plan.processed_globally.insert(name.clone());\n continue;\n }\n }\n }\n }\n }\n specific.push(info);\n }\n Ok(None) => {\n plan.errors.push((\n name.to_string(),\n SpsError::NotFound(format!(\"Cannot upgrade '{name}': not installed.\")),\n ));\n plan.processed_globally.insert(name.clone());\n }\n Err(e) => {\n plan.errors.push((\n name.to_string(),\n SpsError::Generic(format!(\"Failed to check status for '{name}': {e}\")),\n ));\n plan.processed_globally.insert(name.clone());\n }\n }\n }\n specific\n };\n\n if packages_to_check.is_empty() {\n return Ok(plan);\n }\n\n match update::check_for_updates(&packages_to_check, &self.cache, self.config).await {\n Ok(updates) => {\n let update_map: HashMap =\n updates.into_iter().map(|u| (u.name.clone(), u)).collect();\n\n debug!(\n \"[Planner] Found {} available updates out of {} packages checked\",\n update_map.len(),\n packages_to_check.len()\n );\n debug!(\n \"[Planner] Available updates: {:?}\",\n update_map.keys().collect::>()\n );\n\n for p_info in packages_to_check {\n if plan.processed_globally.contains(&p_info.name) {\n continue;\n }\n if let Some(ui) = update_map.get(&p_info.name) {\n debug!(\n \"[Planner] Adding upgrade job for '{}': {} -> {}\",\n p_info.name, p_info.version, ui.available_version\n );\n plan.initial_ops.insert(\n p_info.name.clone(),\n (\n JobAction::Upgrade {\n from_version: p_info.version.clone(),\n old_install_path: p_info.path.clone(),\n },\n Some(ui.target_definition.clone()),\n ),\n );\n // Don't mark packages with updates as processed_globally\n // so they can be included in the final job list\n } else {\n debug!(\n \"[Planner] No update available for '{}', marking as already satisfied\",\n p_info.name\n );\n plan.already_satisfied.insert(p_info.name.clone());\n // Only mark packages without updates as processed_globally\n plan.processed_globally.insert(p_info.name.clone());\n }\n }\n }\n Err(e) => {\n plan.errors.push((\n \"[Update Check]\".to_string(),\n SpsError::Generic(format!(\"Failed to check for updates: {e}\")),\n ));\n }\n }\n Ok(plan)\n }\n\n // This now returns sps_common::pipeline::PlannedOperations\n pub async fn plan_operations(\n &self,\n initial_targets: &[String],\n command_type: CommandType,\n ) -> PlanResult {\n debug!(\n \"[Planner] Starting plan_operations with command_type: {:?}, targets: {:?}\",\n command_type, initial_targets\n );\n\n let mut intermediate_plan = match command_type {\n CommandType::Install => self.plan_for_install(initial_targets).await?,\n CommandType::Reinstall => self.plan_for_reinstall(initial_targets).await?,\n CommandType::Upgrade { all } => {\n debug!(\"[Planner] Calling plan_for_upgrade with all={}\", all);\n let plan = self.plan_for_upgrade(initial_targets, all).await?;\n debug!(\"[Planner] plan_for_upgrade returned with {} initial_ops, {} errors, {} already_satisfied\",\n plan.initial_ops.len(), plan.errors.len(), plan.already_satisfied.len());\n debug!(\n \"[Planner] Initial ops: {:?}\",\n plan.initial_ops.keys().collect::>()\n );\n debug!(\"[Planner] Already satisfied: {:?}\", plan.already_satisfied);\n plan\n }\n };\n\n let definitions_to_fetch: Vec = intermediate_plan\n .initial_ops\n .iter()\n .filter(|(name, (_, opt_def))| {\n opt_def.is_none() && !intermediate_plan.processed_globally.contains(*name)\n })\n .map(|(name, _)| name.clone())\n .collect();\n\n if !definitions_to_fetch.is_empty() {\n let fetched_defs =\n fetch_target_definitions(&definitions_to_fetch, self.cache.clone()).await;\n for (name, result) in fetched_defs {\n match result {\n Ok(target_def) => {\n if let Some((_action, opt_install_target)) =\n intermediate_plan.initial_ops.get_mut(&name)\n {\n *opt_install_target = Some(target_def);\n }\n }\n Err(e) => {\n intermediate_plan.errors.push((\n name.clone(),\n SpsError::Generic(format!(\"Failed to get definition for target: {e}\")),\n ));\n intermediate_plan.processed_globally.insert(name);\n }\n }\n }\n }\n self.event_tx\n .send(PipelineEvent::DependencyResolutionStarted)\n .ok();\n\n let mut formulae_for_resolution: HashMap = HashMap::new();\n let mut cask_deps_map: HashMap> = HashMap::new();\n let mut cask_processing_queue: VecDeque = VecDeque::new();\n\n for (name, (action, opt_def)) in &intermediate_plan.initial_ops {\n if intermediate_plan.processed_globally.contains(name) {\n continue;\n }\n\n // Handle both normal formula targets and upgrade targets\n match opt_def {\n Some(target @ InstallTargetIdentifier::Formula(_)) => {\n debug!(\n \"[Planner] Adding formula '{}' to resolution list with action {:?}\",\n name, action\n );\n formulae_for_resolution.insert(name.clone(), target.clone());\n }\n Some(InstallTargetIdentifier::Cask(c_arc)) => {\n debug!(\"[Planner] Adding cask '{}' to processing queue\", name);\n cask_processing_queue.push_back(name.clone());\n cask_deps_map.insert(name.clone(), c_arc.clone());\n }\n None => {\n if !intermediate_plan\n .errors\n .iter()\n .any(|(err_name, _)| err_name == name)\n {\n intermediate_plan.errors.push((\n name.clone(),\n SpsError::Generic(format!(\n \"Definition for '{name}' still missing after fetch attempt.\"\n )),\n ));\n intermediate_plan.processed_globally.insert(name.clone());\n }\n }\n }\n }\n\n let mut processed_casks_for_deps_pass: HashSet =\n intermediate_plan.processed_globally.clone();\n\n while let Some(cask_token) = cask_processing_queue.pop_front() {\n if processed_casks_for_deps_pass.contains(&cask_token) {\n continue;\n }\n processed_casks_for_deps_pass.insert(cask_token.clone());\n\n let cask_arc = match cask_deps_map.get(&cask_token) {\n Some(c) => c.clone(),\n None => {\n match fetch_target_definitions(\n std::slice::from_ref(&cask_token),\n self.cache.clone(),\n )\n .await\n .remove(&cask_token)\n {\n Some(Ok(InstallTargetIdentifier::Cask(c))) => {\n cask_deps_map.insert(cask_token.clone(), c.clone());\n c\n }\n Some(Err(e)) => {\n intermediate_plan.errors.push((cask_token.clone(), e));\n intermediate_plan\n .processed_globally\n .insert(cask_token.clone());\n continue;\n }\n _ => {\n intermediate_plan.errors.push((\n cask_token.clone(),\n SpsError::NotFound(format!(\n \"Cask definition for dependency '{cask_token}' not found.\"\n )),\n ));\n intermediate_plan\n .processed_globally\n .insert(cask_token.clone());\n continue;\n }\n }\n }\n };\n\n if let Some(deps) = &cask_arc.depends_on {\n for formula_dep_name in &deps.formula {\n if formulae_for_resolution.contains_key(formula_dep_name)\n || intermediate_plan\n .errors\n .iter()\n .any(|(n, _)| n == formula_dep_name)\n || intermediate_plan\n .already_satisfied\n .contains(formula_dep_name)\n {\n continue;\n }\n match fetch_target_definitions(\n std::slice::from_ref(formula_dep_name),\n self.cache.clone(),\n )\n .await\n .remove(formula_dep_name)\n {\n Some(Ok(target_def @ InstallTargetIdentifier::Formula(_))) => {\n formulae_for_resolution.insert(formula_dep_name.clone(), target_def);\n }\n Some(Ok(InstallTargetIdentifier::Cask(_))) => {\n intermediate_plan.errors.push((\n formula_dep_name.clone(),\n SpsError::Generic(format!(\n \"Dependency '{formula_dep_name}' of Cask '{cask_token}' is unexpectedly a Cask itself.\"\n )),\n ));\n intermediate_plan\n .processed_globally\n .insert(formula_dep_name.clone());\n }\n Some(Err(e)) => {\n intermediate_plan.errors.push((\n formula_dep_name.clone(),\n SpsError::Generic(format!(\n \"Failed def fetch for formula dep '{formula_dep_name}' of cask '{cask_token}': {e}\"\n )),\n ));\n intermediate_plan\n .processed_globally\n .insert(formula_dep_name.clone());\n }\n None => {\n intermediate_plan.errors.push((\n formula_dep_name.clone(),\n SpsError::NotFound(format!(\n \"Formula dep '{formula_dep_name}' for cask '{cask_token}' not found.\"\n )),\n ));\n intermediate_plan\n .processed_globally\n .insert(formula_dep_name.clone());\n }\n }\n }\n for dep_cask_token in &deps.cask {\n if !processed_casks_for_deps_pass.contains(dep_cask_token)\n && !cask_processing_queue.contains(dep_cask_token)\n {\n cask_processing_queue.push_back(dep_cask_token.clone());\n }\n }\n }\n }\n\n let mut resolved_formula_graph_opt: Option> = None;\n if !formulae_for_resolution.is_empty() {\n let targets_for_resolver: Vec<_> = formulae_for_resolution.keys().cloned().collect();\n let formulary = Formulary::new(self.config.clone());\n let keg_registry = KegRegistry::new(self.config.clone());\n\n let per_target_prefs = PerTargetInstallPreferences {\n force_source_build_targets: if self.flags.build_from_source {\n targets_for_resolver.iter().cloned().collect()\n } else {\n HashSet::new()\n },\n force_bottle_only_targets: HashSet::new(),\n };\n\n // Create map of initial target actions for the resolver\n let initial_target_actions: HashMap = intermediate_plan\n .initial_ops\n .iter()\n .filter_map(|(name, (action, _))| {\n if targets_for_resolver.contains(name) {\n Some((name.clone(), action.clone()))\n } else {\n debug!(\"[Planner] WARNING: Target '{}' with action {:?} is not in targets_for_resolver!\", name, action);\n None\n }\n })\n .collect();\n\n debug!(\n \"[Planner] Created initial_target_actions map with {} entries: {:?}\",\n initial_target_actions.len(),\n initial_target_actions\n );\n debug!(\"[Planner] Targets for resolver: {:?}\", targets_for_resolver);\n\n let ctx = ResolutionContext {\n formulary: &formulary,\n keg_registry: &keg_registry,\n sps_prefix: self.config.sps_root(),\n include_optional: self.flags.include_optional,\n include_test: false,\n skip_recommended: self.flags.skip_recommended,\n initial_target_preferences: &per_target_prefs,\n build_all_from_source: self.flags.build_from_source,\n cascade_source_preference_to_dependencies: true,\n has_bottle_for_current_platform:\n sps_core::install::bottle::has_bottle_for_current_platform,\n initial_target_actions: &initial_target_actions,\n };\n\n let mut resolver = DependencyResolver::new(ctx);\n debug!(\"[Planner] Created DependencyResolver, calling resolve_targets...\");\n match resolver.resolve_targets(&targets_for_resolver) {\n Ok(g) => {\n debug!(\n \"[Planner] Dependency resolution succeeded! Install plan has {} items\",\n g.install_plan.len()\n );\n resolved_formula_graph_opt = Some(Arc::new(g));\n }\n Err(e) => {\n debug!(\"[Planner] Dependency resolution failed: {}\", e);\n let resolver_error_msg = e.to_string(); // Capture full error\n for n in targets_for_resolver {\n if !intermediate_plan\n .errors\n .iter()\n .any(|(err_n, _)| err_n == &n)\n {\n intermediate_plan.errors.push((\n n.clone(),\n SpsError::DependencyError(resolver_error_msg.clone()),\n ));\n }\n intermediate_plan.processed_globally.insert(n);\n }\n }\n }\n }\n self.event_tx\n .send(PipelineEvent::DependencyResolutionFinished)\n .ok();\n\n let mut final_planned_jobs: Vec = Vec::new();\n let mut names_processed_from_initial_ops = HashSet::new();\n\n debug!(\n \"[Planner] Processing {} initial_ops into final jobs\",\n intermediate_plan.initial_ops.len()\n );\n for (name, (action, opt_def)) in &intermediate_plan.initial_ops {\n debug!(\n \"[Planner] Processing initial op '{}': action={:?}, has_def={}\",\n name,\n action,\n opt_def.is_some()\n );\n\n if intermediate_plan.processed_globally.contains(name) {\n debug!(\"[Planner] Skipping '{}' - already processed globally\", name);\n continue;\n }\n // If an error was recorded for this specific initial target (e.g. resolver failed for\n // it, or def missing) ensure it's marked as globally processed and not\n // added to final_planned_jobs.\n if intermediate_plan\n .errors\n .iter()\n .any(|(err_name, _)| err_name == name)\n {\n debug!(\"[Planner] Skipping job for initial op '{}' as an error was recorded for it during planning.\", name);\n intermediate_plan.processed_globally.insert(name.clone());\n continue;\n }\n if intermediate_plan.already_satisfied.contains(name) {\n debug!(\n \"[Planner] Skipping job for initial op '{}' as it's already satisfied.\",\n name\n );\n intermediate_plan.processed_globally.insert(name.clone());\n continue;\n }\n\n match opt_def {\n Some(target_def) => {\n let is_source_build = determine_build_strategy_for_job(\n target_def,\n action,\n self.flags,\n resolved_formula_graph_opt.as_deref(),\n self,\n );\n\n final_planned_jobs.push(PlannedJob {\n target_id: name.clone(),\n target_definition: target_def.clone(),\n action: action.clone(),\n is_source_build,\n use_private_store_source: intermediate_plan\n .private_store_sources\n .get(name)\n .cloned(),\n });\n names_processed_from_initial_ops.insert(name.clone());\n }\n None => {\n tracing::error!(\"[Planner] CRITICAL: Definition missing for planned operation on '{}' but no error was recorded in intermediate_plan.errors. This should not happen.\", name);\n if !intermediate_plan\n .errors\n .iter()\n .any(|(err_n, _)| err_n == name)\n {\n intermediate_plan.errors.push((\n name.clone(),\n SpsError::Generic(\"Definition missing unexpectedly.\".into()),\n ));\n }\n intermediate_plan.processed_globally.insert(name.clone());\n }\n }\n }\n\n if let Some(graph) = resolved_formula_graph_opt.as_ref() {\n for dep_detail in &graph.install_plan {\n let dep_name = dep_detail.formula.name();\n\n if names_processed_from_initial_ops.contains(dep_name)\n || intermediate_plan.processed_globally.contains(dep_name)\n || final_planned_jobs.iter().any(|j| j.target_id == dep_name)\n {\n continue;\n }\n\n if intermediate_plan\n .errors\n .iter()\n .any(|(err_name, _)| err_name == dep_name)\n {\n tracing::debug!(\"[Planner] Skipping job for dependency '{}' due to a pre-existing error recorded for it.\", dep_name);\n intermediate_plan\n .processed_globally\n .insert(dep_name.to_string());\n continue;\n }\n if dep_detail.status == ResolutionStatus::Failed {\n tracing::debug!(\"[Planner] Skipping job for dependency '{}' as its resolution status is Failed. Adding to planner errors.\", dep_name);\n // Ensure this error is also captured if not already.\n if !intermediate_plan\n .errors\n .iter()\n .any(|(err_name, _)| err_name == dep_name)\n {\n intermediate_plan.errors.push((\n dep_name.to_string(),\n SpsError::DependencyError(format!(\n \"Resolution failed for dependency {dep_name}\"\n )),\n ));\n }\n intermediate_plan\n .processed_globally\n .insert(dep_name.to_string());\n continue;\n }\n\n if matches!(\n dep_detail.status,\n ResolutionStatus::Missing | ResolutionStatus::Requested\n ) {\n let is_source_build_for_dep = determine_build_strategy_for_job(\n &InstallTargetIdentifier::Formula(dep_detail.formula.clone()),\n &JobAction::Install,\n self.flags,\n Some(graph),\n self,\n );\n debug!(\n \"Planning install for new formula dependency '{}'. Source build: {}\",\n dep_name, is_source_build_for_dep\n );\n\n final_planned_jobs.push(PlannedJob {\n target_id: dep_name.to_string(),\n target_definition: InstallTargetIdentifier::Formula(\n dep_detail.formula.clone(),\n ),\n action: JobAction::Install,\n is_source_build: is_source_build_for_dep,\n use_private_store_source: None,\n });\n } else if dep_detail.status == ResolutionStatus::Installed {\n intermediate_plan\n .already_satisfied\n .insert(dep_name.to_string());\n }\n }\n }\n\n for (cask_token, cask_arc) in cask_deps_map {\n if names_processed_from_initial_ops.contains(&cask_token)\n || intermediate_plan.processed_globally.contains(&cask_token)\n || final_planned_jobs.iter().any(|j| j.target_id == cask_token)\n {\n continue;\n }\n\n match self.check_installed_status(&cask_token).await {\n Ok(None) => {\n final_planned_jobs.push(PlannedJob {\n target_id: cask_token.clone(),\n target_definition: InstallTargetIdentifier::Cask(cask_arc.clone()),\n action: JobAction::Install,\n is_source_build: false,\n use_private_store_source: intermediate_plan\n .private_store_sources\n .get(&cask_token)\n .cloned(),\n });\n }\n Ok(Some(_installed_info)) => {\n intermediate_plan\n .already_satisfied\n .insert(cask_token.clone());\n }\n Err(e) => {\n intermediate_plan.errors.push((\n cask_token.clone(),\n SpsError::Generic(format!(\n \"Failed check install status for cask dependency {cask_token}: {e}\"\n )),\n ));\n intermediate_plan\n .processed_globally\n .insert(cask_token.clone());\n }\n }\n }\n if let Some(graph) = resolved_formula_graph_opt.as_ref() {\n if !final_planned_jobs.is_empty() {\n sort_planned_jobs(&mut final_planned_jobs, graph);\n }\n }\n\n debug!(\n \"[Planner] Finishing plan_operations with {} jobs, {} errors, {} already_satisfied\",\n final_planned_jobs.len(),\n intermediate_plan.errors.len(),\n intermediate_plan.already_satisfied.len()\n );\n debug!(\n \"[Planner] Final jobs: {:?}\",\n final_planned_jobs\n .iter()\n .map(|j| &j.target_id)\n .collect::>()\n );\n\n Ok(PlannedOperations {\n jobs: final_planned_jobs,\n errors: intermediate_plan.errors,\n already_installed_or_up_to_date: intermediate_plan.already_satisfied,\n resolved_graph: resolved_formula_graph_opt,\n })\n }\n}\n\nfn determine_build_strategy_for_job(\n target_def: &InstallTargetIdentifier,\n action: &JobAction,\n flags: &PipelineFlags,\n resolved_graph: Option<&ResolvedGraph>,\n planner: &OperationPlanner,\n) -> bool {\n match target_def {\n InstallTargetIdentifier::Formula(formula_arc) => {\n if flags.build_from_source {\n return true;\n }\n if let Some(graph) = resolved_graph {\n if let Some(resolved_detail) = graph.resolution_details.get(formula_arc.name()) {\n match resolved_detail.determined_install_strategy {\n NodeInstallStrategy::SourceOnly => return true,\n NodeInstallStrategy::BottleOrFail => return false,\n NodeInstallStrategy::BottlePreferred => {}\n }\n }\n }\n if let JobAction::Upgrade {\n old_install_path, ..\n } = action\n {\n if planner\n .get_previous_installation_type(old_install_path)\n .as_deref()\n == Some(\"source\")\n {\n return true;\n }\n }\n !sps_core::install::bottle::has_bottle_for_current_platform(formula_arc)\n }\n InstallTargetIdentifier::Cask(_) => false,\n }\n}\n\nfn sort_planned_jobs(jobs: &mut [PlannedJob], formula_graph: &ResolvedGraph) {\n let formula_order: HashMap = formula_graph\n .install_plan\n .iter()\n .enumerate()\n .map(|(idx, dep_detail)| (dep_detail.formula.name().to_string(), idx))\n .collect();\n\n jobs.sort_by_key(|job| match &job.target_definition {\n InstallTargetIdentifier::Formula(f_arc) => formula_order\n .get(f_arc.name())\n .copied()\n .unwrap_or(usize::MAX),\n InstallTargetIdentifier::Cask(_) => usize::MAX - 1,\n });\n}\n"], ["/sps/sps-core/src/check/installed.rs", "// sps-core/src/check/installed.rs\nuse std::fs::{self}; // Removed DirEntry as it's not directly used here\nuse std::io;\nuse std::path::PathBuf;\nuse std::sync::Arc;\n\nuse serde::{Deserialize, Serialize};\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::keg::KegRegistry; // KegRegistry is used\nuse tracing::{debug, warn};\n\n#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]\npub enum PackageType {\n Formula,\n Cask,\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub struct InstalledPackageInfo {\n pub name: String,\n pub version: String, // This will now store keg.version_str\n pub pkg_type: PackageType,\n pub path: PathBuf,\n}\n\n// Helper closure to handle io::Result -> Option logging errors\n// Defined outside the functions to avoid repetition\nfn handle_dir_entry(res: io::Result, dir_path_str: &str) -> Option {\n match res {\n Ok(entry) => Some(entry),\n Err(e) => {\n warn!(\"Error reading entry in {}: {}\", dir_path_str, e);\n None\n }\n }\n}\n\npub async fn get_installed_packages(config: &Config) -> Result> {\n let mut installed = Vec::new();\n let keg_registry = KegRegistry::new(config.clone());\n\n match keg_registry.list_installed_kegs() {\n Ok(kegs) => {\n for keg in kegs {\n installed.push(InstalledPackageInfo {\n name: keg.name,\n version: keg.version_str, // Use keg.version_str\n pkg_type: PackageType::Formula,\n path: keg.path,\n });\n }\n }\n Err(e) => warn!(\"Failed to list installed formulae: {}\", e),\n }\n\n let caskroom_dir = config.cask_room_dir();\n if caskroom_dir.is_dir() {\n let caskroom_dir_str = caskroom_dir.to_str().unwrap_or(\"caskroom\").to_string();\n let cask_token_entries_iter =\n fs::read_dir(&caskroom_dir).map_err(|e| SpsError::Io(Arc::new(e)))?;\n\n for entry_res in cask_token_entries_iter {\n if let Some(entry) = handle_dir_entry(entry_res, &caskroom_dir_str) {\n let cask_token_path = entry.path();\n if !cask_token_path.is_dir() {\n continue;\n }\n let cask_token = entry.file_name().to_string_lossy().to_string();\n\n match fs::read_dir(&cask_token_path) {\n Ok(version_entries_iter) => {\n for version_entry_res in version_entries_iter {\n if let Some(version_entry) = handle_dir_entry(\n version_entry_res,\n cask_token_path.to_str().unwrap_or(\"token_path\"),\n ) {\n let version_path = version_entry.path();\n if version_path.is_dir()\n && version_path.join(\"CASK_INSTALL_MANIFEST.json\").is_file()\n {\n let version_str =\n version_entry.file_name().to_string_lossy().to_string();\n let manifest_path =\n version_path.join(\"CASK_INSTALL_MANIFEST.json\");\n let mut include = true;\n if manifest_path.is_file() {\n if let Ok(manifest_str) =\n std::fs::read_to_string(&manifest_path)\n {\n if let Ok(manifest_json) =\n serde_json::from_str::(\n &manifest_str,\n )\n {\n if let Some(is_installed) = manifest_json\n .get(\"is_installed\")\n .and_then(|v| v.as_bool())\n {\n include = is_installed;\n }\n }\n }\n }\n if include {\n installed.push(InstalledPackageInfo {\n name: cask_token.clone(),\n version: version_str,\n pkg_type: PackageType::Cask,\n path: version_path,\n });\n }\n // Assuming one actively installed version per cask token based\n // on manifest logic\n // If multiple version folders exist but only one manifest says\n // is_installed=true, this is fine.\n // If the intent is to list *all* version folders, the break\n // might be removed,\n // but then \"is_installed\" logic per version becomes more\n // important.\n // For now, finding the first \"active\" one is usually sufficient\n // for list/upgrade checks.\n }\n }\n }\n }\n Err(e) => warn!(\"Failed to read cask versions for {}: {}\", cask_token, e),\n }\n }\n }\n } else {\n debug!(\n \"Caskroom directory {} does not exist.\",\n caskroom_dir.display()\n );\n }\n Ok(installed)\n}\n\npub async fn get_installed_package(\n name: &str,\n config: &Config,\n) -> Result> {\n let keg_registry = KegRegistry::new(config.clone());\n if let Some(keg) = keg_registry.get_installed_keg(name)? {\n return Ok(Some(InstalledPackageInfo {\n name: keg.name,\n version: keg.version_str, // Use keg.version_str\n pkg_type: PackageType::Formula,\n path: keg.path,\n }));\n }\n\n let cask_token_path = config.cask_room_token_path(name);\n if cask_token_path.is_dir() {\n let version_entries_iter =\n fs::read_dir(&cask_token_path).map_err(|e| SpsError::Io(Arc::new(e)))?;\n for version_entry_res in version_entries_iter {\n if let Some(version_entry) = handle_dir_entry(\n version_entry_res,\n cask_token_path.to_str().unwrap_or(\"token_path\"),\n ) {\n let version_path = version_entry.path();\n if version_path.is_dir()\n && version_path.join(\"CASK_INSTALL_MANIFEST.json\").is_file()\n {\n let version_str = version_entry.file_name().to_string_lossy().to_string();\n let manifest_path = version_path.join(\"CASK_INSTALL_MANIFEST.json\");\n let mut include = true;\n if manifest_path.is_file() {\n if let Ok(manifest_str) = std::fs::read_to_string(&manifest_path) {\n if let Ok(manifest_json) =\n serde_json::from_str::(&manifest_str)\n {\n if let Some(is_installed) =\n manifest_json.get(\"is_installed\").and_then(|v| v.as_bool())\n {\n include = is_installed;\n }\n }\n }\n }\n if include {\n return Ok(Some(InstalledPackageInfo {\n name: name.to_string(),\n version: version_str,\n pkg_type: PackageType::Cask,\n path: version_path,\n }));\n }\n }\n }\n }\n }\n Ok(None)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/preflight.rs", "use std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::InstalledArtifact;\n\n/// Execute any `preflight` commands listed in the Cask’s JSON artifact stanza.\n/// Returns an empty Vec since preflight does not produce install artifacts.\npub fn run_preflight(\n cask: &Cask,\n stage_path: &Path,\n _config: &Config,\n) -> Result> {\n // Iterate over artifacts, look for \"preflight\" keys\n if let Some(entries) = &cask.artifacts {\n for entry in entries.iter().filter_map(|v| v.as_object()) {\n if let Some(cmds) = entry.get(\"preflight\").and_then(|v| v.as_array()) {\n for cmd_val in cmds.iter().filter_map(|v| v.as_str()) {\n // Substitute $STAGEDIR placeholder\n let cmd_str = cmd_val.replace(\"$STAGEDIR\", stage_path.to_str().unwrap());\n debug!(\"Running preflight: {}\", cmd_str);\n let status = Command::new(\"sh\").arg(\"-c\").arg(&cmd_str).status()?;\n if !status.success() {\n return Err(SpsError::InstallError(format!(\n \"preflight failed: {cmd_str}\"\n )));\n }\n }\n }\n }\n }\n\n // No install artifacts to return\n Ok(Vec::new())\n}\n"], ["/sps/sps-common/src/model/cask.rs", "// ===== sps-common/src/model/cask.rs ===== // Corrected path\nuse std::collections::HashMap;\nuse std::fs;\n\nuse serde::{Deserialize, Serialize};\n\nuse crate::config::Config;\n\npub type Artifact = serde_json::Value;\n\n/// Represents the `url` field, which can be a simple string or a map with specs\n#[derive(Debug, Clone, Serialize, Deserialize)]\n#[serde(untagged)]\npub enum UrlField {\n Simple(String),\n WithSpec {\n url: String,\n #[serde(default)]\n verified: Option,\n #[serde(flatten)]\n other: HashMap,\n },\n}\n\n/// Represents the `sha256` field: hex, no_check, or per-architecture\n#[derive(Debug, Clone, Serialize, Deserialize)]\n#[serde(untagged)]\npub enum Sha256Field {\n Hex(String),\n #[serde(rename_all = \"snake_case\")]\n NoCheck {\n no_check: bool,\n },\n PerArch(HashMap),\n}\n\n/// Appcast metadata\n#[derive(Debug, Clone, Serialize, Deserialize)] // Ensure Serialize/Deserialize are here\npub struct Appcast {\n pub url: String,\n pub checkpoint: Option,\n}\n\n/// Represents conflicts with other casks or formulae\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub struct ConflictsWith {\n #[serde(default)]\n pub cask: Vec,\n #[serde(default)]\n pub formula: Vec,\n #[serde(flatten)]\n pub extra: HashMap,\n}\n\n/// Represents the specific architecture details found in some cask definitions\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub struct ArchSpec {\n #[serde(rename = \"type\")] // Map the JSON \"type\" field\n pub type_name: String, // e.g., \"arm\"\n pub bits: u32, // e.g., 64\n}\n\n/// Helper for architecture requirements: single string, list of strings, or list of spec objects\n#[derive(Debug, Clone, Serialize, Deserialize)]\n#[serde(untagged)]\npub enum ArchReq {\n One(String), // e.g., \"arm64\"\n Many(Vec), // e.g., [\"arm64\", \"x86_64\"]\n Specs(Vec),\n}\n\n/// Helper for macOS requirements: symbol, list, comparison, or map\n#[derive(Debug, Clone, Serialize, Deserialize)]\n#[serde(untagged)]\npub enum MacOSReq {\n Symbol(String), // \":big_sur\"\n Symbols(Vec), // [\":catalina\", \":big_sur\"]\n Comparison(String), // \">= :big_sur\"\n Map(HashMap>),\n}\n\n/// Helper to coerce string-or-list into Vec\n#[derive(Debug, Clone, Serialize, Deserialize)]\n#[serde(untagged)]\npub enum StringList {\n One(String),\n Many(Vec),\n}\n\nimpl From for Vec {\n fn from(item: StringList) -> Self {\n match item {\n StringList::One(s) => vec![s],\n StringList::Many(v) => v,\n }\n }\n}\n\n/// Represents `depends_on` block with multiple possible keys\n#[derive(Debug, Clone, Serialize, Deserialize, Default)]\npub struct DependsOn {\n #[serde(default)]\n pub cask: Vec,\n #[serde(default)]\n pub formula: Vec,\n #[serde(default)]\n pub arch: Option,\n #[serde(default)]\n pub macos: Option,\n #[serde(flatten)]\n pub extra: HashMap,\n}\n\n/// The main Cask model matching Homebrew JSON v2\n#[derive(Debug, Clone, Serialize, Deserialize, Default)]\npub struct Cask {\n pub token: String,\n\n #[serde(default)]\n pub name: Option>,\n pub version: Option,\n pub desc: Option,\n pub homepage: Option,\n\n #[serde(default)]\n pub artifacts: Option>,\n\n #[serde(default)]\n pub url: Option,\n #[serde(default)]\n pub url_specs: Option>,\n\n #[serde(default)]\n pub sha256: Option,\n\n pub appcast: Option,\n pub auto_updates: Option,\n\n #[serde(default)]\n pub depends_on: Option,\n\n #[serde(default)]\n pub conflicts_with: Option,\n\n pub caveats: Option,\n pub stage_only: Option,\n\n #[serde(default)]\n pub uninstall: Option>,\n\n #[serde(default)] // Only one default here\n pub zap: Option>,\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub struct CaskList {\n pub casks: Vec,\n}\n\n// --- ZAP STANZA SUPPORT ---\n\n/// Helper for zap: string or array of strings\n#[derive(Debug, Clone, Serialize, Deserialize)]\n#[serde(untagged)]\npub enum StringOrVec {\n String(String),\n Vec(Vec),\n}\nimpl StringOrVec {\n pub fn into_vec(self) -> Vec {\n match self {\n StringOrVec::String(s) => vec![s],\n StringOrVec::Vec(v) => v,\n }\n }\n}\n\n/// Zap action details (trash, delete, rmdir, pkgutil, launchctl, script, signal, etc)\n#[derive(Debug, Clone, Serialize, Deserialize)]\n#[serde(tag = \"action\", rename_all = \"snake_case\")]\npub enum ZapActionDetail {\n Trash(Vec),\n Delete(Vec),\n Rmdir(Vec),\n Pkgutil(StringOrVec),\n Launchctl(StringOrVec),\n Script {\n executable: String,\n args: Option>,\n },\n Signal(Vec),\n // Add more as needed\n}\n\n/// A zap stanza is a map of action -> detail\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub struct ZapStanza(pub std::collections::HashMap);\n\n// --- Cask Impl ---\n\nimpl Cask {\n /// Check if this cask is installed by looking for a manifest file\n /// in any versioned directory within the Caskroom.\n pub fn is_installed(&self, config: &Config) -> bool {\n let cask_dir = config.cask_room_token_path(&self.token); // e.g., /opt/sps/cask_room/firefox\n if !cask_dir.exists() || !cask_dir.is_dir() {\n return false;\n }\n\n // Iterate through entries (version dirs) inside the cask_dir\n match fs::read_dir(&cask_dir) {\n Ok(entries) => {\n // Clippy fix: Use flatten() to handle Result entries directly\n for entry in entries.flatten() {\n // <-- Use flatten() here\n let version_path = entry.path();\n // Check if it's a directory (representing a version)\n if version_path.is_dir() {\n // Check for the existence of the manifest file\n let manifest_path = version_path.join(\"CASK_INSTALL_MANIFEST.json\"); // <-- Correct filename\n if manifest_path.is_file() {\n // Check is_installed flag in manifest\n let mut include = true;\n if let Ok(manifest_str) = std::fs::read_to_string(&manifest_path) {\n if let Ok(manifest_json) =\n serde_json::from_str::(&manifest_str)\n {\n if let Some(is_installed) =\n manifest_json.get(\"is_installed\").and_then(|v| v.as_bool())\n {\n include = is_installed;\n }\n }\n }\n if include {\n // Found a manifest in at least one version directory, consider it\n // installed\n return true;\n }\n }\n }\n }\n // If loop completes without finding a manifest in any version dir\n false\n }\n Err(e) => {\n // Log error if reading the directory fails, but assume not installed\n tracing::warn!(\n \"Failed to read cask directory {} to check for installed versions: {}\",\n cask_dir.display(),\n e\n );\n false\n }\n }\n }\n\n /// Get the installed version of this cask by reading the directory names\n /// in the Caskroom. Returns the first version found (use cautiously if multiple\n /// versions could exist, though current install logic prevents this).\n pub fn installed_version(&self, config: &Config) -> Option {\n let cask_dir = config.cask_room_token_path(&self.token); //\n if !cask_dir.exists() {\n return None;\n }\n // Iterate through entries and return the first directory name found\n match fs::read_dir(&cask_dir) {\n Ok(entries) => {\n // Clippy fix: Use flatten()\n for entry in entries.flatten() {\n // <-- Use flatten() here\n let path = entry.path();\n // Check if it's a directory (representing a version)\n if path.is_dir() {\n if let Some(version_str) = path.file_name().and_then(|name| name.to_str()) {\n // Return the first version directory name found\n return Some(version_str.to_string());\n }\n }\n }\n // No version directories found\n None\n }\n Err(_) => None, // Error reading directory\n }\n }\n\n /// Get a friendly name for display purposes\n pub fn display_name(&self) -> String {\n self.name\n .as_ref()\n .and_then(|names| names.first().cloned())\n .unwrap_or_else(|| self.token.clone())\n }\n}\n"], ["/sps/sps-core/src/check/update.rs", "// sps-core/src/check/update.rs\n\nuse std::collections::HashMap;\nuse std::sync::Arc;\n\n// Imports from sps-common\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::formulary::Formulary; // Using the shared Formulary\nuse sps_common::model::version::Version as PkgVersion;\nuse sps_common::model::Cask; // Using the Cask and Formula from sps-common\n// Use the Cask and Formula structs from sps_common::model\n// Ensure InstallTargetIdentifier is correctly pathed if it's also in sps_common::model\nuse sps_common::model::InstallTargetIdentifier;\n// Imports from sps-net\nuse sps_net::api;\n\n// Imports from sps-core\nuse crate::check::installed::{InstalledPackageInfo, PackageType};\n\n#[derive(Debug, Clone)]\npub struct UpdateInfo {\n pub name: String,\n pub installed_version: String,\n pub available_version: String,\n pub pkg_type: PackageType,\n pub target_definition: InstallTargetIdentifier,\n}\n\n/// Ensures that the raw JSON data for formulas and casks exists in the main disk cache,\n/// fetching from the API if necessary.\nasync fn ensure_api_data_cached(cache: &Cache) -> Result<()> {\n let formula_check = cache.load_raw(\"formula.json\");\n let cask_check = cache.load_raw(\"cask.json\");\n\n // Determine if fetches are needed\n let mut fetch_formulas = false;\n if formula_check.is_err() {\n tracing::debug!(\"Local formula.json cache missing or unreadable. Scheduling fetch.\");\n fetch_formulas = true;\n }\n\n let mut fetch_casks = false;\n if cask_check.is_err() {\n tracing::debug!(\"Local cask.json cache missing or unreadable. Scheduling fetch.\");\n fetch_casks = true;\n }\n\n // Perform fetches concurrently if needed\n match (fetch_formulas, fetch_casks) {\n (true, true) => {\n tracing::debug!(\"Populating missing formula.json and cask.json from API...\");\n let (formula_res, cask_res) = tokio::join!(\n async {\n let data = api::fetch_all_formulas().await?;\n cache.store_raw(\"formula.json\", &data)?;\n Ok::<(), SpsError>(())\n },\n async {\n let data = api::fetch_all_casks().await?;\n cache.store_raw(\"cask.json\", &data)?;\n Ok::<(), SpsError>(())\n }\n );\n formula_res?;\n cask_res?;\n tracing::debug!(\"Formula.json and cask.json populated from API.\");\n }\n (true, false) => {\n tracing::debug!(\"Populating missing formula.json from API...\");\n let data = api::fetch_all_formulas().await?;\n cache.store_raw(\"formula.json\", &data)?;\n tracing::debug!(\"Formula.json populated from API.\");\n }\n (false, true) => {\n tracing::debug!(\"Populating missing cask.json from API...\");\n let data = api::fetch_all_casks().await?;\n cache.store_raw(\"cask.json\", &data)?;\n tracing::debug!(\"Cask.json populated from API.\");\n }\n (false, false) => {\n tracing::debug!(\"Local formula.json and cask.json caches are present.\");\n }\n }\n Ok(())\n}\n\npub async fn check_for_updates(\n installed_packages: &[InstalledPackageInfo],\n cache: &Cache,\n config: &Config,\n) -> Result> {\n // 1. Ensure the underlying JSON files in the main cache are populated.\n ensure_api_data_cached(cache)\n .await\n .map_err(|e| {\n tracing::error!(\n \"Failed to ensure API data is cached for update check: {}\",\n e\n );\n // Decide if this is a fatal error for update checking or if we can proceed with\n // potentially stale/missing data. For now, let's make it non-fatal but log\n // an error, as Formulary/cask parsing might still work with older cache.\n SpsError::Generic(format!(\n \"Failed to ensure API data in cache, update check might be unreliable: {e}\"\n ))\n })\n .ok(); // Continue even if this pre-fetch step fails, rely on Formulary/cask loading to handle actual\n // errors.\n\n // 2. Instantiate Formulary. It uses the `cache` (from sps-common) to load `formula.json`.\n let formulary = Formulary::new(config.clone());\n\n // 3. For Casks: Load the entire `cask.json` from cache and parse it robustly into Vec.\n // This uses the Cask definition from sps_common::model::cask.\n let casks_map: HashMap> = match cache.load_raw(\"cask.json\") {\n Ok(json_str) => {\n // Parse directly into Vec using the definition from sps-common::model::cask\n match serde_json::from_str::>(&json_str) {\n Ok(casks) => casks\n .into_iter()\n .map(|c| (c.token.clone(), Arc::new(c)))\n .collect(),\n Err(e) => {\n tracing::warn!(\n \"Failed to parse full cask.json string into Vec (from sps-common): {}. Cask update checks may be incomplete.\",\n e\n );\n HashMap::new()\n }\n }\n }\n Err(e) => {\n tracing::warn!(\n \"Failed to load cask.json string from cache: {}. Cask update checks will be based on no remote data.\", e\n );\n HashMap::new()\n }\n };\n\n tracing::debug!(\n \"[UpdateCheck] Starting update check for {} packages\",\n installed_packages.len()\n );\n let mut updates_available = Vec::new();\n\n for installed in installed_packages {\n tracing::debug!(\n \"[UpdateCheck] Checking package '{}' version '{}'\",\n installed.name,\n installed.version\n );\n match installed.pkg_type {\n PackageType::Formula => {\n match formulary.load_formula(&installed.name) {\n // Uses sps-common::formulary::Formulary\n Ok(latest_formula_obj) => {\n // Returns sps_common::model::formula::Formula\n let latest_formula_arc = Arc::new(latest_formula_obj);\n\n let latest_version_str = latest_formula_arc.version_str_full();\n tracing::debug!(\n \"[UpdateCheck] Formula '{}': installed='{}', latest='{}'\",\n installed.name,\n installed.version,\n latest_version_str\n );\n\n let installed_v_res = PkgVersion::parse(&installed.version);\n let latest_v_res = PkgVersion::parse(&latest_version_str);\n let installed_revision = installed\n .version\n .split('_')\n .nth(1)\n .and_then(|s| s.parse::().ok())\n .unwrap_or(0);\n\n let needs_update = match (installed_v_res, latest_v_res) {\n (Ok(iv), Ok(lv)) => {\n let version_newer = lv > iv;\n let revision_newer =\n lv == iv && latest_formula_arc.revision > installed_revision;\n tracing::debug!(\"[UpdateCheck] Formula '{}': version_newer={}, revision_newer={} (installed_rev={}, latest_rev={})\", \n installed.name, version_newer, revision_newer, installed_revision, latest_formula_arc.revision);\n version_newer || revision_newer\n }\n _ => {\n let different = installed.version != latest_version_str;\n tracing::debug!(\"[UpdateCheck] Formula '{}': fallback string comparison, different={}\", \n installed.name, different);\n different\n }\n };\n\n tracing::debug!(\n \"[UpdateCheck] Formula '{}': needs_update={}\",\n installed.name,\n needs_update\n );\n if needs_update {\n updates_available.push(UpdateInfo {\n name: installed.name.clone(),\n installed_version: installed.version.clone(),\n available_version: latest_version_str,\n pkg_type: PackageType::Formula,\n target_definition: InstallTargetIdentifier::Formula(\n // From sps-common\n latest_formula_arc.clone(),\n ),\n });\n }\n }\n Err(_e) => {\n tracing::debug!(\n \"Installed formula '{}' not found via Formulary. It might have been removed from the remote. Source error: {}\",\n installed.name, _e\n );\n }\n }\n }\n PackageType::Cask => {\n if let Some(latest_cask_arc) = casks_map.get(&installed.name) {\n // latest_cask_arc is Arc\n if let Some(available_version) = latest_cask_arc.version.as_ref() {\n if &installed.version != available_version {\n updates_available.push(UpdateInfo {\n name: installed.name.clone(),\n installed_version: installed.version.clone(),\n available_version: available_version.clone(),\n pkg_type: PackageType::Cask,\n target_definition: InstallTargetIdentifier::Cask(\n // From sps-common\n latest_cask_arc.clone(),\n ),\n });\n }\n } else {\n tracing::warn!(\n \"Latest cask definition for '{}' from casks_map has no version string.\",\n installed.name\n );\n }\n } else {\n tracing::warn!(\n \"Installed cask '{}' not found in the fully parsed casks_map.\",\n installed.name\n );\n }\n }\n }\n }\n\n tracing::debug!(\n \"[UpdateCheck] Update check complete: {} updates available out of {} packages checked\",\n updates_available.len(),\n installed_packages.len()\n );\n tracing::debug!(\n \"[UpdateCheck] Updates available for: {:?}\",\n updates_available\n .iter()\n .map(|u| &u.name)\n .collect::>()\n );\n\n Ok(updates_available)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/uninstall.rs", "use std::path::PathBuf;\n\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\n\n/// At install time, scan the `uninstall` stanza and turn each directive\n/// into an InstalledArtifact variant, so it can later be torn down.\npub fn record_uninstall(cask: &Cask) -> Result> {\n let mut artifacts = Vec::new();\n\n if let Some(entries) = &cask.artifacts {\n for entry in entries.iter().filter_map(|v| v.as_object()) {\n if let Some(steps) = entry.get(\"uninstall\").and_then(|v| v.as_array()) {\n for step in steps.iter().filter_map(|v| v.as_object()) {\n for (key, val) in step {\n match key.as_str() {\n \"pkgutil\" => {\n if let Some(id) = val.as_str() {\n artifacts.push(InstalledArtifact::PkgUtilReceipt {\n id: id.to_string(),\n });\n }\n }\n \"delete\" => {\n if let Some(arr) = val.as_array() {\n for p in arr.iter().filter_map(|v| v.as_str()) {\n artifacts.push(InstalledArtifact::MovedResource {\n path: PathBuf::from(p),\n });\n }\n }\n }\n \"rmdir\" => {\n if let Some(arr) = val.as_array() {\n for p in arr.iter().filter_map(|v| v.as_str()) {\n artifacts.push(InstalledArtifact::MovedResource {\n path: PathBuf::from(p),\n });\n }\n }\n }\n \"launchctl\" => {\n if let Some(arr) = val.as_array() {\n for lbl in arr.iter().filter_map(|v| v.as_str()) {\n artifacts.push(InstalledArtifact::Launchd {\n label: lbl.to_string(),\n path: None,\n });\n }\n }\n }\n // Add other uninstall keys similarly...\n _ => {}\n }\n }\n }\n }\n }\n }\n\n Ok(artifacts)\n}\n"], ["/sps/sps/src/cli/uninstall.rs", "use std::collections::{HashMap, HashSet};\nuse std::sync::Arc;\n\nuse clap::Args;\nuse colored::Colorize;\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::cask::Cask;\nuse sps_common::Cache;\nuse sps_core::check::{installed, PackageType};\nuse sps_core::{uninstall as core_uninstall, UninstallOptions};\nuse sps_net::api;\nuse tracing::{debug, error, warn};\nuse {serde_json, walkdir};\n\n#[derive(Args, Debug)]\npub struct Uninstall {\n /// The names of the formulas or casks to uninstall\n #[arg(required = true)] // Ensure at least one name is given\n pub names: Vec,\n /// Perform a deep clean for casks, removing associated user data, caches,\n /// and configuration files. Use with caution, data will be lost! Ignored for formulas.\n #[arg(\n long,\n help = \"Perform a deep clean for casks, removing associated user data, caches, and configuration files. Use with caution!\"\n )]\n pub zap: bool,\n}\n\nimpl Uninstall {\n pub async fn run(&self, config: &Config, cache: Arc) -> Result<()> {\n let names = &self.names;\n let mut errors: Vec<(String, SpsError)> = Vec::new();\n\n for name in names {\n // Basic name validation to prevent path traversal\n if name.contains('/') || name.contains(\"..\") {\n let msg = format!(\"Invalid package name '{name}' contains disallowed characters\");\n error!(\"✖ {msg}\");\n errors.push((name.to_string(), SpsError::Generic(msg)));\n continue;\n }\n\n println!(\"Uninstalling {name}...\");\n\n match installed::get_installed_package(name, config).await {\n Ok(Some(installed_info)) => {\n let (file_count, size_bytes) =\n count_files_and_size(&installed_info.path).unwrap_or((0, 0));\n let uninstall_opts = UninstallOptions { skip_zap: false };\n debug!(\n \"Attempting uninstall for {} ({:?})\",\n name, installed_info.pkg_type\n );\n let uninstall_result = match installed_info.pkg_type {\n PackageType::Formula => {\n if self.zap {\n warn!(\"--zap flag is ignored for formulas like '{}'.\", name);\n }\n core_uninstall::uninstall_formula_artifacts(\n &installed_info,\n config,\n &uninstall_opts,\n )\n }\n PackageType::Cask => {\n core_uninstall::uninstall_cask_artifacts(&installed_info, config)\n }\n };\n\n if let Err(e) = uninstall_result {\n error!(\"✖ Failed to uninstall '{}': {}\", name.cyan(), e);\n errors.push((name.to_string(), e));\n // Continue to zap anyway for casks, as per plan\n } else {\n println!(\n \"✓ Uninstalled {:?} {} ({} files, {})\",\n installed_info.pkg_type,\n name.green(),\n file_count,\n format_size(size_bytes)\n );\n }\n\n // --- Zap Uninstall (Conditional) ---\n if self.zap && installed_info.pkg_type == PackageType::Cask {\n println!(\"Zapping {name}...\");\n debug!(\n \"--zap specified for cask '{}', attempting deep clean.\",\n name\n );\n\n // Fetch the Cask definition (needed for the zap stanza)\n let cask_def_result: Result = async {\n match api::get_cask(name).await {\n Ok(cask) => Ok(cask),\n Err(e) => {\n warn!(\"Failed API fetch for zap definition for '{}' ({}), trying cache...\", name, e);\n match cache.load_raw(\"cask.json\") {\n Ok(raw_json) => {\n let casks: Vec = serde_json::from_str(&raw_json)\n .map_err(|cache_e| SpsError::Cache(format!(\"Failed parse cached cask.json: {cache_e}\")))?;\n casks.into_iter()\n .find(|c| c.token == *name)\n .ok_or_else(|| SpsError::NotFound(format!(\"Cask '{name}' def not in cache either\")))\n }\n Err(cache_e) => Err(SpsError::Cache(format!(\"Failed load cask cache for zap: {cache_e}\"))),\n }\n }\n }\n }.await;\n\n match cask_def_result {\n Ok(cask_def) => {\n match core_uninstall::zap_cask_artifacts(\n &installed_info,\n &cask_def,\n config,\n )\n .await\n {\n Ok(_) => {\n println!(\"✓ Zap complete for {}\", name.green());\n }\n Err(zap_err) => {\n error!(\"✖ Zap failed for '{}': {}\", name.cyan(), zap_err);\n errors.push((format!(\"{name} (zap)\"), zap_err));\n }\n }\n }\n Err(e) => {\n error!(\n \"✖ Could not get Cask definition for zap '{}': {}\",\n name.cyan(),\n e\n );\n errors.push((format!(\"{name} (zap definition)\"), e));\n }\n }\n }\n }\n Ok(None) => {\n let msg = format!(\"Package '{name}' is not installed.\");\n error!(\"✖ {msg}\");\n errors.push((name.to_string(), SpsError::NotFound(msg)));\n }\n Err(e) => {\n let msg = format!(\"Failed check install status for '{name}': {e}\");\n error!(\"✖ {msg}\");\n errors.push((name.clone(), SpsError::Generic(msg)));\n }\n }\n }\n\n if errors.is_empty() {\n Ok(())\n } else {\n eprintln!(\"\\n{}:\", \"Finished uninstalling with errors\".yellow());\n let mut errors_by_pkg: HashMap> = HashMap::new();\n for (pkg_name, error) in errors {\n errors_by_pkg\n .entry(pkg_name)\n .or_default()\n .push(error.to_string());\n }\n for (pkg_name, error_list) in errors_by_pkg {\n eprintln!(\"Package '{}':\", pkg_name.cyan());\n let unique_errors: HashSet<_> = error_list.into_iter().collect();\n for error_str in unique_errors {\n eprintln!(\"- {}\", error_str.red());\n }\n }\n Err(SpsError::Generic(\n \"Uninstall failed for one or more packages.\".to_string(),\n ))\n }\n }\n}\n\n// --- Unchanged Helper Functions ---\nfn count_files_and_size(path: &std::path::Path) -> Result<(usize, u64)> {\n let mut file_count = 0;\n let mut total_size = 0;\n for entry in walkdir::WalkDir::new(path) {\n match entry {\n Ok(entry_data) => {\n if entry_data.file_type().is_file() || entry_data.file_type().is_symlink() {\n match entry_data.metadata() {\n Ok(metadata) => {\n file_count += 1;\n if entry_data.file_type().is_file() {\n total_size += metadata.len();\n }\n }\n Err(e) => {\n tracing::warn!(\n \"Could not get metadata for {}: {}\",\n entry_data.path().display(),\n e\n );\n }\n }\n }\n }\n Err(e) => {\n tracing::warn!(\"Error traversing directory {}: {}\", path.display(), e);\n }\n }\n }\n Ok((file_count, total_size))\n}\n\nfn format_size(size: u64) -> String {\n const KB: u64 = 1024;\n const MB: u64 = KB * 1024;\n const GB: u64 = MB * 1024;\n if size >= GB {\n format!(\"{:.1}GB\", size as f64 / GB as f64)\n } else if size >= MB {\n format!(\"{:.1}MB\", size as f64 / MB as f64)\n } else if size >= KB {\n format!(\"{:.1}KB\", size as f64 / KB as f64)\n } else {\n format!(\"{size}B\")\n }\n}\n"], ["/sps/sps-core/src/uninstall/common.rs", "// sps-core/src/uninstall/common.rs\n\nuse std::path::{Component, Path, PathBuf};\nuse std::process::Command;\nuse std::{fs, io};\n\nuse sps_common::config::Config;\nuse tracing::{debug, error, warn};\n\n#[derive(Debug, Clone, Default)]\npub struct UninstallOptions {\n pub skip_zap: bool,\n}\n\n/// Removes a filesystem artifact (file or directory).\n///\n/// Attempts direct removal. If `use_sudo` is true and direct removal\n/// fails due to permission errors, it will attempt `sudo rm -rf`.\n///\n/// Returns `true` if the artifact is successfully removed or was already gone,\n/// `false` otherwise.\npub(crate) fn remove_filesystem_artifact(path: &Path, use_sudo: bool) -> bool {\n match path.symlink_metadata() {\n Ok(metadata) => {\n let file_type = metadata.file_type();\n // A directory is only a \"real\" directory if it's not a symlink.\n // Symlinks to directories should be removed with remove_file.\n let is_real_dir = file_type.is_dir();\n\n debug!(\n \"Removing filesystem artifact ({}) at: {}\",\n if is_real_dir {\n \"directory\"\n } else if file_type.is_symlink() {\n \"symlink\"\n } else {\n \"file\"\n },\n path.display()\n );\n\n let remove_op = || -> io::Result<()> {\n if is_real_dir {\n fs::remove_dir_all(path)\n } else {\n // This handles both files and symlinks\n fs::remove_file(path)\n }\n };\n\n if let Err(e) = remove_op() {\n if use_sudo && e.kind() == io::ErrorKind::PermissionDenied {\n warn!(\n \"Direct removal failed (Permission Denied). Trying with sudo rm -rf: {}\",\n path.display()\n );\n let output = Command::new(\"sudo\").arg(\"rm\").arg(\"-rf\").arg(path).output();\n match output {\n Ok(out) if out.status.success() => {\n debug!(\"Successfully removed {} with sudo.\", path.display());\n true\n }\n Ok(out) => {\n error!(\n \"Failed to remove {} with sudo: {}\",\n path.display(),\n String::from_utf8_lossy(&out.stderr).trim()\n );\n false\n }\n Err(sudo_err) => {\n error!(\n \"Error executing sudo rm for {}: {}\",\n path.display(),\n sudo_err\n );\n false\n }\n }\n } else if e.kind() != io::ErrorKind::NotFound {\n error!(\"Failed to remove artifact {}: {}\", path.display(), e);\n false\n } else {\n debug!(\"Artifact {} already removed.\", path.display());\n true\n }\n } else {\n debug!(\"Successfully removed artifact: {}\", path.display());\n true\n }\n }\n Err(e) if e.kind() == io::ErrorKind::NotFound => {\n debug!(\"Artifact not found (already removed?): {}\", path.display());\n true\n }\n Err(e) => {\n warn!(\n \"Failed to get metadata for artifact {}: {}\",\n path.display(),\n e\n );\n false\n }\n }\n}\n\n/// Expands a path string that may start with `~` to the user's home directory.\npub(crate) fn expand_tilde(path_str: &str, home: &Path) -> PathBuf {\n if let Some(stripped) = path_str.strip_prefix(\"~/\") {\n home.join(stripped)\n } else {\n PathBuf::from(path_str)\n }\n}\n\n/// Checks if a path is safe for zap operations.\n/// Safe paths are typically within user Library, .config, /Applications, /Library,\n/// or the sps cache directory. Root, home, /Applications, /Library themselves are not safe.\npub(crate) fn is_safe_path(path: &Path, home: &Path, config: &Config) -> bool {\n if path.components().any(|c| matches!(c, Component::ParentDir)) {\n warn!(\"Zap path rejected (contains '..'): {}\", path.display());\n return false;\n }\n let allowed_roots = [\n home.join(\"Library\"),\n home.join(\".config\"),\n PathBuf::from(\"/Applications\"),\n PathBuf::from(\"/Library\"),\n config.cache_dir().clone(),\n // Consider adding more specific allowed user dirs if necessary\n ];\n\n // Check if the path is exactly one of the top-level restricted paths\n if path == Path::new(\"/\")\n || path == home\n || path == Path::new(\"/Applications\")\n || path == Path::new(\"/Library\")\n {\n warn!(\"Zap path rejected (too broad): {}\", path.display());\n return false;\n }\n\n if allowed_roots.iter().any(|root| path.starts_with(root)) {\n return true;\n }\n\n warn!(\n \"Zap path rejected (outside allowed areas): {}\",\n path.display()\n );\n false\n}\n"], ["/sps/sps-core/src/install/bottle/macho.rs", "// sps-core/src/build/formula/macho.rs\n// Contains Mach-O specific patching logic for bottle relocation.\n// Updated to use MachOFatFile32 and MachOFatFile64 for FAT binary parsing.\n// Refactored to separate immutable analysis from mutable patching to fix borrow checker errors.\n\nuse std::collections::HashMap;\nuse std::fs;\nuse std::io::Write; // Keep for write_patched_buffer\nuse std::path::Path;\nuse std::process::{Command as StdCommand, Stdio}; // Keep for codesign\n\n// --- Imports needed for Mach-O patching (macOS only) ---\n#[cfg(target_os = \"macos\")]\nuse object::{\n self,\n macho::{MachHeader32, MachHeader64}, // Keep for Mach-O parsing\n read::macho::{\n FatArch,\n LoadCommandVariant, // Correct import path\n MachHeader,\n MachOFatFile32,\n MachOFatFile64, // Core Mach-O types + FAT types\n MachOFile,\n },\n Endianness,\n FileKind,\n ReadRef,\n};\nuse sps_common::error::{Result, SpsError};\nuse tempfile::NamedTempFile;\nuse tracing::{debug, error};\n\n// --- Platform‑specific constants for Mach‑O magic detection ---\n#[cfg(target_os = \"macos\")]\nconst MH_MAGIC: u32 = 0xfeedface;\n#[cfg(target_os = \"macos\")]\nconst MH_MAGIC_64: u32 = 0xfeedfacf;\n#[cfg(target_os = \"macos\")]\nconst MACHO_HEADER32_SIZE: usize = 28;\n#[cfg(target_os = \"macos\")]\nconst MACHO_HEADER64_SIZE: usize = 32;\n\n/// Core patch data for **one** string replacement location inside a Mach‑O file.\n#[cfg(target_os = \"macos\")]\n#[derive(Debug, Clone)]\nstruct PatchInfo {\n absolute_offset: usize, // Offset in the entire file buffer\n allocated_len: usize, // How much space was allocated for this string\n new_path: String, // The new string to write\n}\n\n/// Container for paths that couldn't be patched due to length constraints\n#[cfg(target_os = \"macos\")]\n#[derive(Debug, Clone)]\npub struct SkippedPath {\n pub old_path: String,\n pub new_path: String,\n}\n\n/// Main entry point for Mach‑O path patching (macOS only).\n/// Returns `Ok(true)` if patches were applied, `Ok(false)` if no patches needed.\n/// Returns a tuple: (patched: bool, skipped_paths: Vec)\n#[cfg(target_os = \"macos\")]\npub fn patch_macho_file(\n path: &Path,\n replacements: &HashMap,\n) -> Result<(bool, Vec)> {\n patch_macho_file_macos(path, replacements)\n}\n\n/// Container for paths that couldn't be patched due to length constraints\n#[cfg(not(target_os = \"macos\"))]\n#[derive(Debug, Clone)]\npub struct SkippedPath {\n pub old_path: String,\n pub new_path: String,\n}\n\n/// No‑op stub for non‑macOS platforms.\n#[cfg(not(target_os = \"macos\"))]\npub fn patch_macho_file(\n _path: &Path,\n _replacements: &HashMap,\n) -> Result<(bool, Vec)> {\n Ok((false, Vec::new()))\n}\n\n/// **macOS implementation**: Tries to patch Mach‑O files by replacing placeholders.\n#[cfg(target_os = \"macos\")]\nfn patch_macho_file_macos(\n path: &Path,\n replacements: &HashMap,\n) -> Result<(bool, Vec)> {\n debug!(\"Processing potential Mach-O file: {}\", path.display());\n\n // 1) Load the entire file into memory\n let buffer = match fs::read(path) {\n Ok(data) => data,\n Err(e) => {\n debug!(\"Failed to read {}: {}\", path.display(), e);\n return Ok((false, Vec::new()));\n }\n };\n if buffer.is_empty() {\n debug!(\"Empty file: {}\", path.display());\n return Ok((false, Vec::new()));\n }\n\n // 2) Identify the file type\n let kind = match object::FileKind::parse(&*buffer) {\n Ok(k) => k,\n Err(_e) => {\n debug!(\"Not an object file: {}\", path.display());\n return Ok((false, Vec::new()));\n }\n };\n\n // 3) **Analysis phase**: collect patches + skipped paths\n let (patches, skipped_paths) = collect_macho_patches(&buffer, kind, replacements, path)?;\n\n if patches.is_empty() {\n if skipped_paths.is_empty() {\n debug!(\"No patches needed for {}\", path.display());\n } else {\n debug!(\n \"No patches applied for {} ({} paths skipped due to length)\",\n path.display(),\n skipped_paths.len()\n );\n }\n return Ok((false, skipped_paths));\n }\n\n // 4) Clone buffer and apply all patches atomically\n let mut patched_buffer = buffer;\n for patch in &patches {\n patch_path_in_buffer(\n &mut patched_buffer,\n patch.absolute_offset,\n patch.allocated_len,\n &patch.new_path,\n path,\n )?;\n }\n\n // 5) Write atomically\n write_patched_buffer(path, &patched_buffer)?;\n debug!(\"Wrote patched Mach-O: {}\", path.display());\n\n // 6) Re‑sign on Apple Silicon\n #[cfg(target_arch = \"aarch64\")]\n {\n resign_binary(path)?;\n debug!(\"Re‑signed patched binary: {}\", path.display());\n }\n\n Ok((true, skipped_paths))\n}\n\n/// ASCII magic for the start of a static `ar` archive (`!\\n`)\n#[cfg(target_os = \"macos\")]\nconst AR_MAGIC: &[u8; 8] = b\"!\\n\";\n\n/// Examine a buffer (Mach‑O or FAT) and return every patch we must apply + skipped paths.\n#[cfg(target_os = \"macos\")]\nfn collect_macho_patches(\n buffer: &[u8],\n kind: FileKind,\n replacements: &HashMap,\n path_for_log: &Path,\n) -> Result<(Vec, Vec)> {\n let mut patches = Vec::::new();\n let mut skipped_paths = Vec::::new();\n\n match kind {\n /* ---------------------------------------------------------- */\n FileKind::MachO32 => {\n let m = MachOFile::, _>::parse(buffer)?;\n let (mut p, mut s) =\n find_patches_in_commands(&m, 0, MACHO_HEADER32_SIZE, replacements, path_for_log)?;\n patches.append(&mut p);\n skipped_paths.append(&mut s);\n }\n /* ---------------------------------------------------------- */\n FileKind::MachO64 => {\n let m = MachOFile::, _>::parse(buffer)?;\n let (mut p, mut s) =\n find_patches_in_commands(&m, 0, MACHO_HEADER64_SIZE, replacements, path_for_log)?;\n patches.append(&mut p);\n skipped_paths.append(&mut s);\n }\n /* ---------------------------------------------------------- */\n FileKind::MachOFat32 => {\n let fat = MachOFatFile32::parse(buffer)?;\n for (idx, arch) in fat.arches().iter().enumerate() {\n let (off, sz) = arch.file_range();\n let slice = &buffer[off as usize..(off + sz) as usize];\n\n /* short‑circuit: static .a archive inside FAT ---------- */\n if slice.starts_with(AR_MAGIC) {\n debug!(\"[slice {}] static archive – skipped\", idx);\n continue;\n }\n\n /* decide 32 / 64 by magic ------------------------------ */\n if slice.len() >= 4 {\n let magic = u32::from_le_bytes(slice[0..4].try_into().unwrap());\n if magic == MH_MAGIC_64 {\n if let Ok(m) = MachOFile::, _>::parse(slice) {\n let (mut p, mut s) = find_patches_in_commands(\n &m,\n off as usize,\n MACHO_HEADER64_SIZE,\n replacements,\n path_for_log,\n )?;\n patches.append(&mut p);\n skipped_paths.append(&mut s);\n }\n } else if magic == MH_MAGIC {\n if let Ok(m) = MachOFile::, _>::parse(slice) {\n let (mut p, mut s) = find_patches_in_commands(\n &m,\n off as usize,\n MACHO_HEADER32_SIZE,\n replacements,\n path_for_log,\n )?;\n patches.append(&mut p);\n skipped_paths.append(&mut s);\n }\n }\n }\n }\n }\n /* ---------------------------------------------------------- */\n FileKind::MachOFat64 => {\n let fat = MachOFatFile64::parse(buffer)?;\n for (idx, arch) in fat.arches().iter().enumerate() {\n let (off, sz) = arch.file_range();\n let slice = &buffer[off as usize..(off + sz) as usize];\n\n if slice.starts_with(AR_MAGIC) {\n debug!(\"[slice {}] static archive – skipped\", idx);\n continue;\n }\n\n if slice.len() >= 4 {\n let magic = u32::from_le_bytes(slice[0..4].try_into().unwrap());\n if magic == MH_MAGIC_64 {\n if let Ok(m) = MachOFile::, _>::parse(slice) {\n let (mut p, mut s) = find_patches_in_commands(\n &m,\n off as usize,\n MACHO_HEADER64_SIZE,\n replacements,\n path_for_log,\n )?;\n patches.append(&mut p);\n skipped_paths.append(&mut s);\n }\n } else if magic == MH_MAGIC {\n if let Ok(m) = MachOFile::, _>::parse(slice) {\n let (mut p, mut s) = find_patches_in_commands(\n &m,\n off as usize,\n MACHO_HEADER32_SIZE,\n replacements,\n path_for_log,\n )?;\n patches.append(&mut p);\n skipped_paths.append(&mut s);\n }\n }\n }\n }\n }\n /* ---------------------------------------------------------- */\n _ => { /* archives & unknown kinds are ignored */ }\n }\n\n Ok((patches, skipped_paths))\n}\n\n/// Iterates through load commands of a parsed MachOFile (slice) and returns\n/// patch details + skipped paths.\n#[cfg(target_os = \"macos\")]\nfn find_patches_in_commands<'data, Mach, R>(\n macho_file: &MachOFile<'data, Mach, R>,\n slice_base_offset: usize,\n header_size: usize,\n replacements: &HashMap,\n file_path_for_log: &Path,\n) -> Result<(Vec, Vec)>\nwhere\n Mach: MachHeader,\n R: ReadRef<'data>,\n{\n let endian = macho_file.endian();\n let mut patches = Vec::new();\n let mut skipped_paths = Vec::new();\n let mut cur_off = header_size;\n\n let mut it = macho_file.macho_load_commands()?;\n while let Some(cmd) = it.next()? {\n let cmd_size = cmd.cmdsize() as usize;\n let cmd_offset = cur_off; // offset *inside this slice*\n cur_off += cmd_size;\n\n let variant = match cmd.variant() {\n Ok(v) => v,\n Err(e) => {\n tracing::warn!(\n \"Malformed load‑command in {}: {}; skipping\",\n file_path_for_log.display(),\n e\n );\n continue;\n }\n };\n\n // — which commands carry path strings we might want? —\n let path_info: Option<(u32, &[u8])> = match variant {\n LoadCommandVariant::Dylib(d) | LoadCommandVariant::IdDylib(d) => cmd\n .string(endian, d.dylib.name)\n .ok()\n .map(|bytes| (d.dylib.name.offset.get(endian), bytes)),\n LoadCommandVariant::Rpath(r) => cmd\n .string(endian, r.path)\n .ok()\n .map(|bytes| (r.path.offset.get(endian), bytes)),\n _ => None,\n };\n\n if let Some((offset_in_cmd, bytes)) = path_info {\n if let Ok(old_path) = std::str::from_utf8(bytes) {\n if let Some(new_path) = find_and_replace_placeholders(old_path, replacements) {\n let allocated = cmd_size.saturating_sub(offset_in_cmd as usize);\n\n if new_path.len() + 1 > allocated {\n // would overflow – add to skipped paths instead of throwing\n tracing::debug!(\n \"Skip patch (too long): '{}' → '{}' (alloc {} B) in {}\",\n old_path,\n new_path,\n allocated,\n file_path_for_log.display()\n );\n skipped_paths.push(SkippedPath {\n old_path: old_path.to_string(),\n new_path: new_path.clone(),\n });\n continue;\n }\n\n patches.push(PatchInfo {\n absolute_offset: slice_base_offset + cmd_offset + offset_in_cmd as usize,\n allocated_len: allocated,\n new_path,\n });\n }\n }\n }\n }\n Ok((patches, skipped_paths))\n}\n\n/// Helper to replace placeholders in a string based on the replacements map.\n/// Returns `Some(String)` with replacements if any were made, `None` otherwise.\nfn find_and_replace_placeholders(\n current_path: &str,\n replacements: &HashMap,\n) -> Option {\n let mut new_path = current_path.to_string();\n let mut path_modified = false;\n // Iterate through all placeholder/replacement pairs\n for (placeholder, replacement) in replacements {\n // Check if the current path string contains the placeholder\n if new_path.contains(placeholder) {\n // Replace all occurrences of the placeholder\n new_path = new_path.replace(placeholder, replacement);\n path_modified = true; // Mark that a change was made\n debug!(\n \" Replaced '{}' with '{}' -> '{}'\",\n placeholder, replacement, new_path\n );\n }\n }\n // Return the modified string only if changes occurred\n if path_modified {\n Some(new_path)\n } else {\n None\n }\n}\n\n/// Write a new (null‑padded) path into the mutable buffer. \n/// Assumes the caller already verified the length.\n#[cfg(target_os = \"macos\")]\nfn patch_path_in_buffer(\n buf: &mut [u8],\n abs_off: usize,\n alloc_len: usize,\n new_path: &str,\n file: &Path,\n) -> Result<()> {\n if new_path.len() + 1 > alloc_len || abs_off + alloc_len > buf.len() {\n // should never happen – just log & skip\n tracing::debug!(\n \"Patch skipped (bounds) at {} in {}\",\n abs_off,\n file.display()\n );\n return Ok(());\n }\n\n // null‑padded copy\n buf[abs_off..abs_off + new_path.len()].copy_from_slice(new_path.as_bytes());\n buf[abs_off + new_path.len()..abs_off + alloc_len].fill(0);\n\n Ok(())\n}\n\n/// Writes the patched buffer to the original path atomically using a temporary file.\n#[cfg(target_os = \"macos\")]\nfn write_patched_buffer(original_path: &Path, buffer: &[u8]) -> Result<()> {\n // Get the directory containing the original file\n let dir = original_path.parent().ok_or_else(|| {\n SpsError::Generic(format!(\n \"Cannot get parent directory for {}\",\n original_path.display()\n ))\n })?;\n // Ensure the directory exists\n fs::create_dir_all(dir).map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n\n // Create a named temporary file in the same directory to facilitate atomic rename\n let mut temp_file = NamedTempFile::new_in(dir)?;\n debug!(\n \" Writing patched buffer ({} bytes) to temporary file: {:?}\",\n buffer.len(),\n temp_file.path()\n );\n // Write the entire modified buffer to the temporary file\n temp_file.write_all(buffer)?;\n // Ensure data is flushed to the OS buffer\n temp_file.flush()?;\n // Attempt to sync data to the disk\n temp_file.as_file().sync_all()?; // Ensure data is physically written\n\n // Atomically replace the original file with the temporary file\n // persist() renames the temp file over the original path.\n temp_file.persist(original_path).map_err(|e| {\n // If persist fails, the temporary file might still exist.\n // The error 'e' contains both the temp file and the underlying IO error.\n error!(\n \" Failed to persist/rename temporary file over {}: {}\",\n original_path.display(),\n e.error // Log the underlying IO error\n );\n // Return the IO error wrapped in our error type\n SpsError::Io(std::sync::Arc::new(e.error))\n })?;\n debug!(\n \" Atomically replaced {} with patched version\",\n original_path.display()\n );\n Ok(())\n}\n\n/// Re-signs the binary using the `codesign` command-line tool.\n/// This is typically necessary on Apple Silicon (aarch64) after modifying executables.\n#[cfg(all(target_os = \"macos\", target_arch = \"aarch64\"))]\nfn resign_binary(path: &Path) -> Result<()> {\n // Suppressed: debug!(\"Re-signing patched binary: {}\", path.display());\n let status = StdCommand::new(\"codesign\")\n .args([\n \"-s\",\n \"-\",\n \"--force\",\n \"--preserve-metadata=identifier,entitlements\",\n ])\n .arg(path)\n .stdout(Stdio::null())\n .stderr(Stdio::null())\n .status() // Execute the command and get its exit status\n .map_err(|e| {\n error!(\n \" Failed to execute codesign command for {}: {}\",\n path.display(),\n e\n );\n SpsError::Io(std::sync::Arc::new(e))\n })?;\n if status.success() {\n // Suppressed: debug!(\"Successfully re-signed {}\", path.display());\n Ok(())\n } else {\n error!(\n \" codesign command failed for {} with status: {}\",\n path.display(),\n status\n );\n Err(SpsError::CodesignError(format!(\n \"Failed to re-sign patched binary {}, it may not be executable. Exit status: {}\",\n path.display(),\n status\n )))\n }\n}\n\n// No-op stub for resigning on non-Apple Silicon macOS (e.g., x86_64)\n#[cfg(all(target_os = \"macos\", not(target_arch = \"aarch64\")))]\nfn resign_binary(_path: &Path) -> Result<()> {\n // No re-signing typically needed on Intel Macs after ad-hoc patching\n Ok(())\n}\n\n// No-op stub for resigning Innovations on non-macOS platforms\n#[cfg(not(target_os = \"macos\"))]\nfn resign_binary(_path: &Path) -> Result<()> {\n // Resigning is a macOS concept\n Ok(())\n}\n"], ["/sps/sps/src/cli/init.rs", "// sps/src/cli/init.rs\nuse std::fs::{self, File, OpenOptions};\nuse std::io::{BufRead, BufReader, Write};\nuse std::path::{Path, PathBuf};\nuse std::process::Command as StdCommand;\nuse std::sync::Arc;\n\nuse clap::Args;\nuse colored::Colorize;\nuse sps_common::config::Config; // Assuming Config is correctly in sps_common\nuse sps_common::error::{Result as SpsResult, SpsError};\nuse tempfile;\nuse tracing::{debug, error, warn};\n\n#[derive(Args, Debug)]\npub struct InitArgs {\n /// Force initialization even if /opt/sps appears to be an sps root already.\n #[arg(long)]\n pub force: bool,\n}\n\nimpl InitArgs {\n pub async fn run(&self, config: &Config) -> SpsResult<()> {\n debug!(\n \"Initializing sps environment at {}\",\n config.sps_root().display()\n );\n\n let sps_root = config.sps_root();\n let marker_path = config.sps_root_marker_path();\n\n // 1. Initial Checks (as current user) - (No change from your existing logic)\n if sps_root.exists() {\n let is_empty = match fs::read_dir(sps_root) {\n Ok(mut entries) => entries.next().is_none(),\n Err(_) => false, // If we can't read it, assume not empty or not accessible\n };\n\n if marker_path.exists() && !self.force {\n debug!(\n \"{} already exists. sps appears to be initialized. Use --force to re-initialize.\",\n marker_path.display()\n );\n return Ok(());\n }\n if !self.force && !is_empty && !marker_path.exists() {\n warn!(\n \"Directory {} exists but does not appear to be an sps root (missing marker {}).\",\n sps_root.display(),\n marker_path.file_name().unwrap_or_default().to_string_lossy()\n );\n warn!(\n \"Run with --force to initialize anyway (this might overwrite existing data or change permissions).\"\n );\n return Err(SpsError::Config(format!(\n \"{} exists but is not a recognized sps root. Aborting.\",\n sps_root.display()\n )));\n }\n if self.force {\n debug!(\n \"--force specified. Proceeding with initialization in {}.\",\n sps_root.display()\n );\n } else if is_empty {\n debug!(\n \"Directory {} exists but is empty. Proceeding with initialization.\",\n sps_root.display()\n );\n }\n }\n\n // 2. Privileged Operations\n let current_user_name = std::env::var(\"USER\")\n .or_else(|_| std::env::var(\"LOGNAME\"))\n .map_err(|_| {\n SpsError::Generic(\n \"Failed to get current username from USER or LOGNAME environment variables.\"\n .to_string(),\n )\n })?;\n\n let target_group_name = if cfg!(target_os = \"macos\") {\n \"admin\" // Standard admin group on macOS\n } else {\n // For Linux, 'staff' might not exist or be appropriate.\n // Often, the user's primary group is used, or a dedicated 'brew' group.\n // For simplicity, let's try to use the current user's name as the group too,\n // which works if the user has a group with the same name.\n // A more robust Linux solution might involve checking for 'staff' or other common\n // groups.\n ¤t_user_name\n };\n\n debug!(\n \"Will attempt to set ownership of sps-managed directories under {} to {}:{}\",\n sps_root.display(),\n current_user_name,\n target_group_name\n );\n\n println!(\n \"{}\",\n format!(\n \"sps may require sudo to create directories and set permissions in {}.\",\n sps_root.display()\n )\n .yellow()\n );\n\n // Define directories sps needs to ensure exist and can manage.\n // These are derived from your Config struct.\n let dirs_to_create_and_manage: Vec = vec![\n config.sps_root().to_path_buf(), // The root itself\n config.bin_dir(),\n config.cellar_dir(),\n config.cask_room_dir(),\n config.cask_store_dir(), // sps-specific\n config.opt_dir(),\n config.taps_dir(), // This is now sps_root/Library/Taps\n config.cache_dir(), // sps-specific (e.g., sps_root/sps_cache)\n config.logs_dir(), // sps-specific (e.g., sps_root/sps_logs)\n config.tmp_dir(),\n config.state_dir(),\n config\n .man_base_dir()\n .parent()\n .unwrap_or(sps_root)\n .to_path_buf(), // share\n config.man_base_dir(), // share/man\n config.sps_root().join(\"etc\"),\n config.sps_root().join(\"include\"),\n config.sps_root().join(\"lib\"),\n config.sps_root().join(\"share/doc\"),\n ];\n\n // Create directories with mkdir -p (non-destructive)\n for dir_path in &dirs_to_create_and_manage {\n // Only create if it doesn't exist to avoid unnecessary sudo calls if already present\n if !dir_path.exists() {\n debug!(\n \"Ensuring directory exists with sudo: {}\",\n dir_path.display()\n );\n run_sudo_command(\"mkdir\", &[\"-p\", &dir_path.to_string_lossy()])?;\n } else {\n debug!(\n \"Directory already exists, skipping mkdir: {}\",\n dir_path.display()\n );\n }\n }\n\n // Create the marker file (non-destructive to other content)\n debug!(\n \"Creating/updating marker file with sudo: {}\",\n marker_path.display()\n );\n let marker_content = \"sps root directory version 1\";\n // Using a temporary file for sudo tee to avoid permission issues with direct pipe\n let temp_marker_file =\n tempfile::NamedTempFile::new().map_err(|e| SpsError::Io(Arc::new(e)))?;\n fs::write(temp_marker_file.path(), marker_content)\n .map_err(|e| SpsError::Io(Arc::new(e)))?;\n run_sudo_command(\n \"cp\",\n &[\n temp_marker_file.path().to_str().unwrap(),\n marker_path.to_str().unwrap(),\n ],\n )?;\n\n #[cfg(unix)]\n {\n // More targeted chown and chmod\n debug!(\n \"Setting ownership and permissions for sps-managed directories under {}...\",\n sps_root.display()\n );\n\n // Chown/Chmod the top-level sps_root directory itself (non-recursively for chmod\n // initially) This is important if sps_root is /opt/sps and was just created\n // by root. If sps_root is /opt/homebrew, this ensures the current user can\n // at least manage it.\n run_sudo_command(\n \"chown\",\n &[\n &format!(\"{current_user_name}:{target_group_name}\"),\n &sps_root.to_string_lossy(),\n ],\n )?;\n run_sudo_command(\"chmod\", &[\"ug=rwx,o=rx\", &sps_root.to_string_lossy()])?; // 755 for the root\n\n // For specific subdirectories that sps actively manages and writes into frequently,\n // ensure they are owned by the user and have appropriate permissions.\n // We apply this recursively to sps-specific dirs and key shared dirs.\n let dirs_for_recursive_chown_chmod: Vec = vec![\n config.cellar_dir(),\n config.cask_room_dir(),\n config.cask_store_dir(), // sps-specific, definitely needs full user control\n config.opt_dir(),\n config.taps_dir(),\n config.cache_dir(), // sps-specific\n config.logs_dir(), // sps-specific\n config.tmp_dir(),\n config.state_dir(),\n // bin, lib, include, share, etc are often symlink farms.\n // The top-level of these should be writable by the user to create symlinks.\n // The actual kegs in Cellar will have their own permissions.\n config.bin_dir(),\n config.sps_root().join(\"lib\"),\n config.sps_root().join(\"include\"),\n config.sps_root().join(\"share\"),\n config.sps_root().join(\"etc\"),\n ];\n\n for dir_path in dirs_for_recursive_chown_chmod {\n if dir_path.exists() {\n // Only operate on existing directories\n debug!(\"Setting ownership (recursive) for: {}\", dir_path.display());\n run_sudo_command(\n \"chown\",\n &[\n \"-R\",\n &format!(\"{current_user_name}:{target_group_name}\"),\n &dir_path.to_string_lossy(),\n ],\n )?;\n\n debug!(\n \"Setting permissions (recursive ug=rwX,o=rX) for: {}\",\n dir_path.display()\n );\n run_sudo_command(\"chmod\", &[\"-R\", \"ug=rwX,o=rX\", &dir_path.to_string_lossy()])?;\n } else {\n warn!(\n \"Directory {} was expected but not found for chown/chmod. Marker: {}\",\n dir_path.display(),\n marker_path.display()\n );\n }\n }\n\n // Ensure bin is executable by all\n if config.bin_dir().exists() {\n debug!(\n \"Ensuring execute permissions for bin_dir: {}\",\n config.bin_dir().display()\n );\n run_sudo_command(\"chmod\", &[\"a+x\", &config.bin_dir().to_string_lossy()])?;\n // Also ensure contents of bin (wrappers, symlinks) are executable if they weren't\n // caught by -R ug=rwX This might be redundant if -R ug=rwX\n // correctly sets X for existing executables, but explicit `chmod\n // a+x` on individual files might be needed if they are newly created by sps.\n // For now, relying on the recursive chmod and the a+x on the bin_dir itself.\n }\n\n // Debug listing (optional, can be verbose)\n if tracing::enabled!(tracing::Level::DEBUG) {\n debug!(\"Listing {} after permission changes:\", sps_root.display());\n let ls_output_root = StdCommand::new(\"ls\").arg(\"-ld\").arg(sps_root).output();\n if let Ok(out) = ls_output_root {\n debug!(\n \"ls -ld {}: \\nSTDOUT: {}\\nSTDERR: {}\",\n sps_root.display(),\n String::from_utf8_lossy(&out.stdout),\n String::from_utf8_lossy(&out.stderr)\n );\n }\n for dir_path in &dirs_to_create_and_manage {\n if dir_path.exists() && dir_path != sps_root {\n let ls_output_sub = StdCommand::new(\"ls\").arg(\"-ld\").arg(dir_path).output();\n if let Ok(out) = ls_output_sub {\n debug!(\n \"ls -ld {}: \\nSTDOUT: {}\\nSTDERR: {}\",\n dir_path.display(),\n String::from_utf8_lossy(&out.stdout),\n String::from_utf8_lossy(&out.stderr)\n );\n }\n }\n }\n }\n }\n\n // 3. User-Specific PATH Configuration (runs as the original user) - (No change from your\n // existing logic)\n if let Err(e) = configure_shell_path(config, ¤t_user_name) {\n warn!(\n \"Could not fully configure shell PATH: {}. Manual configuration might be needed.\",\n e\n );\n print_manual_path_instructions(&config.bin_dir().to_string_lossy());\n }\n\n debug!(\n \"{} {}\",\n \"Successfully initialized sps environment at\".green(),\n config.sps_root().display().to_string().green()\n );\n Ok(())\n }\n}\n\n// run_sudo_command helper (no change from your existing logic)\nfn run_sudo_command(command: &str, args: &[&str]) -> SpsResult<()> {\n debug!(\"Running sudo {} {:?}\", command, args);\n let output = StdCommand::new(\"sudo\")\n .arg(command)\n .args(args)\n .output()\n .map_err(|e| SpsError::Io(Arc::new(e)))?;\n\n if !output.status.success() {\n let stderr = String::from_utf8_lossy(&output.stderr);\n let stdout = String::from_utf8_lossy(&output.stdout);\n error!(\n \"sudo {} {:?} failed ({}):\\nStdout: {}\\nStderr: {}\",\n command,\n args,\n output.status,\n stdout.trim(),\n stderr.trim()\n );\n Err(SpsError::Generic(format!(\n \"Failed to execute `sudo {} {:?}`: {}\",\n command,\n args,\n stderr.trim()\n )))\n } else {\n Ok(())\n }\n}\n\n// configure_shell_path helper (no change from your existing logic)\nfn configure_shell_path(config: &Config, current_user_name_for_log: &str) -> SpsResult<()> {\n debug!(\"Attempting to configure your shell for sps PATH...\");\n\n let sps_bin_path_str = config.bin_dir().to_string_lossy().into_owned();\n let home_dir = config.home_dir();\n if home_dir == PathBuf::from(\"/\") && current_user_name_for_log != \"root\" {\n warn!(\n \"Could not reliably determine your home directory (got '/'). Please add {} to your PATH manually for user {}.\",\n sps_bin_path_str, current_user_name_for_log\n );\n print_manual_path_instructions(&sps_bin_path_str);\n return Ok(());\n }\n\n let shell_path_env = std::env::var(\"SHELL\").unwrap_or_else(|_| \"unknown\".to_string());\n let mut config_files_updated: Vec = Vec::new();\n let mut path_seems_configured = false;\n\n let sps_path_line_zsh_bash = format!(\"export PATH=\\\"{sps_bin_path_str}:$PATH\\\"\");\n let sps_path_line_fish = format!(\"fish_add_path -P \\\"{sps_bin_path_str}\\\"\");\n\n if shell_path_env.contains(\"zsh\") {\n let zshrc_path = home_dir.join(\".zshrc\");\n if update_shell_config(\n &zshrc_path,\n &sps_path_line_zsh_bash,\n &sps_bin_path_str,\n \"Zsh\",\n false,\n )? {\n config_files_updated.push(zshrc_path.display().to_string());\n } else if line_exists_in_file(&zshrc_path, &sps_bin_path_str)? {\n path_seems_configured = true;\n }\n } else if shell_path_env.contains(\"bash\") {\n let bashrc_path = home_dir.join(\".bashrc\");\n let bash_profile_path = home_dir.join(\".bash_profile\");\n let profile_path = home_dir.join(\".profile\");\n\n let mut bash_updated_by_sps = false;\n if update_shell_config(\n &bashrc_path,\n &sps_path_line_zsh_bash,\n &sps_bin_path_str,\n \"Bash (.bashrc)\",\n false,\n )? {\n config_files_updated.push(bashrc_path.display().to_string());\n bash_updated_by_sps = true;\n if bash_profile_path.exists() {\n ensure_profile_sources_rc(&bash_profile_path, &bashrc_path, \"Bash (.bash_profile)\");\n } else if profile_path.exists() {\n ensure_profile_sources_rc(&profile_path, &bashrc_path, \"Bash (.profile)\");\n } else {\n debug!(\"Neither .bash_profile nor .profile found. Creating .bash_profile to source .bashrc.\");\n ensure_profile_sources_rc(&bash_profile_path, &bashrc_path, \"Bash (.bash_profile)\");\n }\n } else if update_shell_config(\n &bash_profile_path,\n &sps_path_line_zsh_bash,\n &sps_bin_path_str,\n \"Bash (.bash_profile)\",\n false,\n )? {\n config_files_updated.push(bash_profile_path.display().to_string());\n bash_updated_by_sps = true;\n } else if update_shell_config(\n &profile_path,\n &sps_path_line_zsh_bash,\n &sps_bin_path_str,\n \"Bash (.profile)\",\n false,\n )? {\n config_files_updated.push(profile_path.display().to_string());\n bash_updated_by_sps = true;\n }\n\n if !bash_updated_by_sps\n && (line_exists_in_file(&bashrc_path, &sps_bin_path_str)?\n || line_exists_in_file(&bash_profile_path, &sps_bin_path_str)?\n || line_exists_in_file(&profile_path, &sps_bin_path_str)?)\n {\n path_seems_configured = true;\n }\n } else if shell_path_env.contains(\"fish\") {\n let fish_config_dir = home_dir.join(\".config/fish\");\n if !fish_config_dir.exists() {\n if let Err(e) = fs::create_dir_all(&fish_config_dir) {\n warn!(\n \"Could not create Fish config directory {}: {}\",\n fish_config_dir.display(),\n e\n );\n }\n }\n if fish_config_dir.exists() {\n let fish_config_path = fish_config_dir.join(\"config.fish\");\n if update_shell_config(\n &fish_config_path,\n &sps_path_line_fish,\n &sps_bin_path_str,\n \"Fish\",\n true,\n )? {\n config_files_updated.push(fish_config_path.display().to_string());\n } else if line_exists_in_file(&fish_config_path, &sps_bin_path_str)? {\n path_seems_configured = true;\n }\n }\n } else {\n warn!(\n \"Unsupported shell for automatic PATH configuration: {}. Please add {} to your PATH manually.\",\n shell_path_env, sps_bin_path_str\n );\n print_manual_path_instructions(&sps_bin_path_str);\n return Ok(());\n }\n\n if !config_files_updated.is_empty() {\n println!(\n \"{} {} has been added to your PATH by modifying: {}\",\n \"sps\".cyan(),\n sps_bin_path_str.cyan(),\n config_files_updated.join(\", \").white()\n );\n println!(\n \"{}\",\n \"Please open a new terminal session or source your shell configuration file for the changes to take effect.\"\n .yellow()\n );\n if shell_path_env.contains(\"zsh\") {\n println!(\" Run: {}\", \"source ~/.zshrc\".green());\n }\n if shell_path_env.contains(\"bash\") {\n println!(\n \" Run: {} (or {} or {})\",\n \"source ~/.bashrc\".green(),\n \"source ~/.bash_profile\".green(),\n \"source ~/.profile\".green()\n );\n }\n if shell_path_env.contains(\"fish\") {\n println!(\n \" Run (usually not needed for fish_add_path, but won't hurt): {}\",\n \"source ~/.config/fish/config.fish\".green()\n );\n }\n } else if path_seems_configured {\n debug!(\"sps path ({}) is likely already configured for your shell ({}). No configuration files were modified.\", sps_bin_path_str.cyan(), shell_path_env.yellow());\n } else if !shell_path_env.is_empty() && shell_path_env != \"unknown\" {\n warn!(\"Could not automatically update PATH for your shell: {}. Please add {} to your PATH manually.\", shell_path_env.yellow(), sps_bin_path_str.cyan());\n print_manual_path_instructions(&sps_bin_path_str);\n }\n Ok(())\n}\n\n// print_manual_path_instructions helper (no change from your existing logic)\nfn print_manual_path_instructions(sps_bin_path_str: &str) {\n println!(\"\\n{} To use sps commands and installed packages directly, please add the following line to your shell configuration file:\", \"Action Required:\".yellow().bold());\n println!(\" (e.g., ~/.zshrc, ~/.bashrc, ~/.config/fish/config.fish)\");\n println!(\"\\n For Zsh or Bash:\");\n println!(\n \" {}\",\n format!(\"export PATH=\\\"{sps_bin_path_str}:$PATH\\\"\").green()\n );\n println!(\"\\n For Fish shell:\");\n println!(\n \" {}\",\n format!(\"fish_add_path -P \\\"{sps_bin_path_str}\\\"\").green()\n );\n println!(\n \"\\nThen, open a new terminal or run: {}\",\n \"source \".green()\n );\n}\n\n// line_exists_in_file helper (no change from your existing logic)\nfn line_exists_in_file(file_path: &Path, sps_bin_path_str: &str) -> SpsResult {\n if !file_path.exists() {\n return Ok(false);\n }\n let file = File::open(file_path).map_err(|e| SpsError::Io(Arc::new(e)))?;\n let reader = BufReader::new(file);\n let escaped_sps_bin_path = regex::escape(sps_bin_path_str);\n // Regex to find lines that configure PATH, trying to be robust for different shells\n // It looks for lines that set PATH or fish_user_paths and include the sps_bin_path_str\n // while trying to avoid commented out lines.\n let pattern = format!(\n r#\"(?m)^\\s*[^#]*\\b(?:PATH\\s*=|export\\s+PATH\\s*=|set\\s*(?:-gx\\s*|-U\\s*)?\\s*fish_user_paths\\b|fish_add_path\\s*(?:-P\\s*|-p\\s*)?)?[\"']?.*{escaped_sps_bin_path}.*[\"']?\"#\n );\n let search_pattern_regex = regex::Regex::new(&pattern)\n .map_err(|e| SpsError::Generic(format!(\"Failed to compile regex for PATH check: {e}\")))?;\n\n for line_result in reader.lines() {\n let line = line_result.map_err(|e| SpsError::Io(Arc::new(e)))?;\n if search_pattern_regex.is_match(&line) {\n debug!(\n \"Found sps PATH ({}) in {}: {}\",\n sps_bin_path_str,\n file_path.display(),\n line.trim()\n );\n return Ok(true);\n }\n }\n Ok(false)\n}\n\n// update_shell_config helper (no change from your existing logic)\nfn update_shell_config(\n config_path: &PathBuf,\n line_to_add: &str,\n sps_bin_path_str: &str,\n shell_name_for_log: &str,\n is_fish_shell: bool,\n) -> SpsResult {\n let sps_comment_tag_start = \"# SPS Path Management Start\";\n let sps_comment_tag_end = \"# SPS Path Management End\";\n\n if config_path.exists() {\n match line_exists_in_file(config_path, sps_bin_path_str) {\n Ok(true) => {\n debug!(\n \"sps path ({}) already configured or managed in {} ({}). Skipping modification.\",\n sps_bin_path_str,\n config_path.display(),\n shell_name_for_log\n );\n return Ok(false); // Path already seems configured\n }\n Ok(false) => { /* Proceed to add */ }\n Err(e) => {\n warn!(\n \"Could not reliably check existing configuration in {} ({}): {}. Attempting to add PATH.\",\n config_path.display(),\n shell_name_for_log,\n e\n );\n // Proceed with caution, might add duplicate if check failed but line exists\n }\n }\n }\n\n debug!(\n \"Adding sps PATH to {} ({})\",\n config_path.display(),\n shell_name_for_log\n );\n\n // Ensure parent directory exists\n if let Some(parent_dir) = config_path.parent() {\n if !parent_dir.exists() {\n fs::create_dir_all(parent_dir).map_err(|e| {\n SpsError::Io(Arc::new(std::io::Error::new(\n e.kind(),\n format!(\n \"Failed to create parent directory {}: {}\",\n parent_dir.display(),\n e\n ),\n )))\n })?;\n }\n }\n\n let mut file = OpenOptions::new()\n .append(true)\n .create(true)\n .open(config_path)\n .map_err(|e| {\n let msg = format!(\n \"Could not open/create shell config {} ({}): {}. Please add {} to your PATH manually.\",\n config_path.display(), shell_name_for_log, e, sps_bin_path_str\n );\n error!(\"{}\", msg);\n SpsError::Io(Arc::new(std::io::Error::new(e.kind(), msg)))\n })?;\n\n // Construct the block to add, ensuring it's idempotent for fish\n let block_to_add = if is_fish_shell {\n format!(\n \"\\n{sps_comment_tag_start}\\n# Add sps to PATH if not already present\\nif not contains \\\"{sps_bin_path_str}\\\" $fish_user_paths\\n {line_to_add}\\nend\\n{sps_comment_tag_end}\\n\"\n )\n } else {\n format!(\"\\n{sps_comment_tag_start}\\n{line_to_add}\\n{sps_comment_tag_end}\\n\")\n };\n\n if let Err(e) = writeln!(file, \"{block_to_add}\") {\n warn!(\n \"Failed to write to shell config {} ({}): {}\",\n config_path.display(),\n shell_name_for_log,\n e\n );\n Ok(false) // Indicate that update was not successful\n } else {\n debug!(\n \"Successfully updated {} ({}) with sps PATH.\",\n config_path.display(),\n shell_name_for_log\n );\n Ok(true) // Indicate successful update\n }\n}\n\n// ensure_profile_sources_rc helper (no change from your existing logic)\nfn ensure_profile_sources_rc(profile_path: &PathBuf, rc_path: &Path, shell_name_for_log: &str) {\n let rc_path_str = rc_path.to_string_lossy();\n // Regex to check if the profile file already sources the rc file.\n // Looks for lines like:\n // . /path/to/.bashrc\n // source /path/to/.bashrc\n // [ -f /path/to/.bashrc ] && . /path/to/.bashrc (and similar variants)\n let source_check_pattern = format!(\n r#\"(?m)^\\s*[^#]*(\\.|source|\\bsource\\b)\\s+[\"']?{}[\"']?\"#, /* More general source command\n * matching */\n regex::escape(&rc_path_str)\n );\n let source_check_regex = match regex::Regex::new(&source_check_pattern) {\n Ok(re) => re,\n Err(e) => {\n warn!(\"Failed to compile regex for sourcing check: {}. Skipping ensure_profile_sources_rc for {}\", e, profile_path.display());\n return;\n }\n };\n\n if profile_path.exists() {\n match fs::read_to_string(profile_path) {\n Ok(existing_content) => {\n if source_check_regex.is_match(&existing_content) {\n debug!(\n \"{} ({}) already sources {}.\",\n profile_path.display(),\n shell_name_for_log,\n rc_path.display()\n );\n return; // Already configured\n }\n }\n Err(e) => {\n warn!(\n \"Could not read {} to check if it sources {}: {}. Will attempt to append.\",\n profile_path.display(),\n rc_path.display(),\n e\n );\n }\n }\n }\n\n // Block to add to .bash_profile or .profile to source .bashrc\n let source_block_to_add = format!(\n \"\\n# Source {rc_filename} if it exists and is readable\\nif [ -f \\\"{rc_path_str}\\\" ] && [ -r \\\"{rc_path_str}\\\" ]; then\\n . \\\"{rc_path_str}\\\"\\nfi\\n\",\n rc_filename = rc_path.file_name().unwrap_or_default().to_string_lossy(),\n rc_path_str = rc_path_str\n );\n\n debug!(\n \"Attempting to ensure {} ({}) sources {}\",\n profile_path.display(),\n shell_name_for_log,\n rc_path.display()\n );\n\n if let Some(parent_dir) = profile_path.parent() {\n if !parent_dir.exists() {\n if let Err(e) = fs::create_dir_all(parent_dir) {\n warn!(\n \"Failed to create parent directory for {}: {}\",\n profile_path.display(),\n e\n );\n return; // Cannot proceed if parent dir creation fails\n }\n }\n }\n\n match OpenOptions::new()\n .append(true)\n .create(true)\n .open(profile_path)\n {\n Ok(mut file) => {\n if let Err(e) = writeln!(file, \"{source_block_to_add}\") {\n warn!(\n \"Failed to write to {} ({}): {}\",\n profile_path.display(),\n shell_name_for_log,\n e\n );\n } else {\n debug!(\n \"Updated {} ({}) to source {}.\",\n profile_path.display(),\n shell_name_for_log,\n rc_path.display()\n );\n }\n }\n Err(e) => {\n warn!(\n \"Could not open or create {} ({}) for updating: {}\",\n profile_path.display(),\n shell_name_for_log,\n e\n );\n }\n }\n}\n"], ["/sps/sps-common/src/keg.rs", "// sps-common/src/keg.rs\nuse std::fs;\nuse std::path::PathBuf;\n\n// Corrected tracing imports: added error, removed unused debug\nuse tracing::{debug, error, warn};\n\nuse super::config::Config;\nuse super::error::{Result, SpsError};\n\n/// Represents information about an installed package (Keg).\n#[derive(Debug, Clone, PartialEq, Eq)]\npub struct InstalledKeg {\n pub name: String,\n pub version_str: String,\n pub path: PathBuf,\n}\n\n/// Manages querying installed packages in the Cellar.\n#[derive(Debug)]\npub struct KegRegistry {\n config: Config,\n}\n\nimpl KegRegistry {\n pub fn new(config: Config) -> Self {\n Self { config }\n }\n\n fn formula_cellar_path(&self, name: &str) -> PathBuf {\n self.config.cellar_dir().join(name)\n }\n\n pub fn get_opt_path(&self, name: &str) -> PathBuf {\n self.config.opt_dir().join(name)\n }\n\n pub fn get_installed_keg(&self, name: &str) -> Result> {\n let formula_dir = self.formula_cellar_path(name);\n debug!(\n \"[KEG_REGISTRY:{}] get_installed_keg: Checking for formula '{}'. Path to check: {}\",\n name,\n name,\n formula_dir.display()\n );\n\n if !formula_dir.is_dir() {\n debug!(\"[KEG_REGISTRY:{}] get_installed_keg: Formula directory '{}' NOT FOUND or not a directory. Returning None.\", name, formula_dir.display());\n return Ok(None);\n }\n\n let mut latest_keg: Option = None;\n debug!(\n \"[KEG_REGISTRY:{}] get_installed_keg: Reading entries in formula directory '{}'\",\n name,\n formula_dir.display()\n );\n\n match fs::read_dir(&formula_dir) {\n Ok(entries) => {\n for entry_result in entries {\n match entry_result {\n Ok(entry) => {\n let path = entry.path();\n debug!(\n \"[KEG_REGISTRY:{}] get_installed_keg: Examining entry '{}'\",\n name,\n path.display()\n );\n\n if path.is_dir() {\n if let Some(version_str_full) =\n path.file_name().and_then(|n| n.to_str())\n {\n debug!(\"[KEG_REGISTRY:{}] get_installed_keg: Entry is a directory with name: {}\", name, version_str_full);\n\n let current_keg_candidate = InstalledKeg {\n name: name.to_string(),\n version_str: version_str_full.to_string(),\n path: path.clone(),\n };\n\n match latest_keg {\n Some(ref current_latest) => {\n // Compare &str with &str\n if version_str_full\n > current_latest.version_str.as_str()\n {\n debug!(\"[KEG_REGISTRY:{}] get_installed_keg: Updating latest keg (lexicographical) to: {}\", name, path.display());\n latest_keg = Some(current_keg_candidate);\n }\n }\n None => {\n debug!(\"[KEG_REGISTRY:{}] get_installed_keg: Setting first found keg as latest: {}\", name, path.display());\n latest_keg = Some(current_keg_candidate);\n }\n }\n } else {\n debug!(\"[KEG_REGISTRY:{}] get_installed_keg: Could not get filename as string for path '{}'\", name, path.display());\n }\n } else {\n debug!(\"[KEG_REGISTRY:{}] get_installed_keg: Entry '{}' is not a directory.\", name, path.display());\n }\n }\n Err(e) => {\n warn!(\"[KEG_REGISTRY:{}] get_installed_keg: Error reading a directory entry in '{}': {}. Skipping entry.\", name, formula_dir.display(), e);\n }\n }\n }\n }\n Err(e) => {\n // Corrected macro usage\n error!(\"[KEG_REGISTRY:{}] get_installed_keg: Failed to read_dir for formula directory '{}' (error: {}). Returning error.\", name, formula_dir.display(), e);\n return Err(SpsError::Io(std::sync::Arc::new(e)));\n }\n }\n\n if let Some(keg) = &latest_keg {\n // Corrected format string arguments\n debug!(\"[KEG_REGISTRY:{}] get_installed_keg: For formula '{}', latest keg found: path={}, version_str={}\", name, name, keg.path.display(), keg.version_str);\n } else {\n // Corrected format string arguments\n debug!(\"[KEG_REGISTRY:{}] get_installed_keg: For formula '{}', no installable keg version found in directory '{}'.\", name, name, formula_dir.display());\n }\n Ok(latest_keg)\n }\n\n pub fn list_installed_kegs(&self) -> Result> {\n let mut installed_kegs = Vec::new();\n let cellar_dir = self.cellar_path();\n debug!(\n \"[KEG_REGISTRY] list_installed_kegs: Scanning cellar: {}\",\n cellar_dir.display()\n );\n\n if !cellar_dir.is_dir() {\n debug!(\"[KEG_REGISTRY] list_installed_kegs: Cellar directory NOT FOUND. Returning empty list.\");\n return Ok(installed_kegs);\n }\n\n for formula_entry_res in fs::read_dir(cellar_dir)? {\n let formula_entry = match formula_entry_res {\n Ok(fe) => fe,\n Err(e) => {\n warn!(\"[KEG_REGISTRY] list_installed_kegs: Error reading entry in cellar: {}. Skipping.\", e);\n continue;\n }\n };\n let formula_path = formula_entry.path();\n debug!(\n \"[KEG_REGISTRY] list_installed_kegs: Examining formula path: {}\",\n formula_path.display()\n );\n\n if formula_path.is_dir() {\n if let Some(formula_name) = formula_path.file_name().and_then(|n| n.to_str()) {\n debug!(\n \"[KEG_REGISTRY] list_installed_kegs: Found formula directory: {}\",\n formula_name\n );\n match fs::read_dir(&formula_path) {\n Ok(version_entries) => {\n for version_entry_res in version_entries {\n let version_entry = match version_entry_res {\n Ok(ve) => ve,\n Err(e) => {\n warn!(\"[KEG_REGISTRY:{}] list_installed_kegs: Error reading version entry in '{}': {}. Skipping.\", formula_name, formula_path.display(), e);\n continue;\n }\n };\n let version_path = version_entry.path();\n debug!(\"[KEG_REGISTRY:{}] list_installed_kegs: Examining version path: {}\", formula_name, version_path.display());\n\n if version_path.is_dir() {\n if let Some(version_str_full) =\n version_path.file_name().and_then(|n| n.to_str())\n {\n debug!(\"[KEG_REGISTRY:{}] list_installed_kegs: Found version directory '{}' with name: {}\", formula_name, version_path.display(), version_str_full);\n installed_kegs.push(InstalledKeg {\n name: formula_name.to_string(),\n version_str: version_str_full.to_string(),\n path: version_path.clone(),\n });\n } else {\n debug!(\"[KEG_REGISTRY:{}] list_installed_kegs: Could not get filename for version path {}\", formula_name, version_path.display());\n }\n } else {\n debug!(\"[KEG_REGISTRY:{}] list_installed_kegs: Version path {} is not a directory.\", formula_name, version_path.display());\n }\n }\n }\n Err(e) => {\n warn!(\"[KEG_REGISTRY:{}] list_installed_kegs: Failed to read_dir for formula versions in '{}': {}.\", formula_name, formula_path.display(), e);\n }\n }\n } else {\n debug!(\"[KEG_REGISTRY] list_installed_kegs: Could not get filename for formula path {}\", formula_path.display());\n }\n } else {\n debug!(\n \"[KEG_REGISTRY] list_installed_kegs: Formula path {} is not a directory.\",\n formula_path.display()\n );\n }\n }\n debug!(\n \"[KEG_REGISTRY] list_installed_kegs: Found {} total installed keg versions.\",\n installed_kegs.len()\n );\n Ok(installed_kegs)\n }\n\n pub fn cellar_path(&self) -> PathBuf {\n self.config.cellar_dir()\n }\n\n pub fn get_keg_path(&self, name: &str, version_str_raw: &str) -> PathBuf {\n self.formula_cellar_path(name).join(version_str_raw)\n }\n}\n"], ["/sps/sps-core/src/install/bottle/mod.rs", "// ===== sps-core/src/build/formula/mod.rs =====\nuse std::fs::File;\nuse std::io::Write;\nuse std::path::{Path, PathBuf};\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::formula::Formula;\nuse tracing::{debug, error};\n\n// Declare submodules\npub mod exec;\npub mod link;\npub mod macho;\n\n/// Download formula resources from the internet asynchronously.\npub async fn download_formula(\n formula: &Formula,\n config: &Config,\n client: &reqwest::Client,\n) -> Result {\n if has_bottle_for_current_platform(formula) {\n exec::download_bottle(formula, config, client).await\n } else {\n Err(SpsError::Generic(format!(\n \"No bottle available for {} on this platform\",\n formula.name()\n )))\n }\n}\n\n/// Checks if a suitable bottle exists for the current platform, considering fallbacks.\npub fn has_bottle_for_current_platform(formula: &Formula) -> bool {\n let result = crate::install::bottle::exec::get_bottle_for_platform(formula);\n debug!(\n \"has_bottle_for_current_platform check for '{}': {:?}\",\n formula.name(),\n result.is_ok()\n );\n if let Err(e) = &result {\n debug!(\"Reason for no bottle: {}\", e);\n }\n result.is_ok()\n}\n\n// *** Updated get_current_platform function ***\nfn get_current_platform() -> String {\n if cfg!(target_os = \"macos\") {\n let arch = if std::env::consts::ARCH == \"aarch64\" {\n \"arm64\"\n } else if std::env::consts::ARCH == \"x86_64\" {\n \"x86_64\"\n } else {\n std::env::consts::ARCH\n };\n\n debug!(\"Attempting to determine macOS version using /usr/bin/sw_vers -productVersion\");\n match Command::new(\"/usr/bin/sw_vers\")\n .arg(\"-productVersion\")\n .output()\n {\n Ok(output) => {\n let stdout = String::from_utf8_lossy(&output.stdout);\n let stderr = String::from_utf8_lossy(&output.stderr);\n debug!(\"sw_vers status: {}\", output.status);\n if !output.status.success() || !stderr.trim().is_empty() {\n debug!(\"sw_vers stdout:\\n{}\", stdout);\n if !stderr.trim().is_empty() {\n debug!(\"sw_vers stderr:\\n{}\", stderr);\n }\n }\n\n if output.status.success() {\n let version_str = stdout.trim();\n if !version_str.is_empty() {\n debug!(\"Extracted version string: {}\", version_str);\n let os_name = match version_str.split('.').next() {\n Some(\"15\") => \"sequoia\",\n Some(\"14\") => \"sonoma\",\n Some(\"13\") => \"ventura\",\n Some(\"12\") => \"monterey\",\n Some(\"11\") => \"big_sur\",\n Some(\"10\") => match version_str.split('.').nth(1) {\n Some(\"15\") => \"catalina\",\n Some(\"14\") => \"mojave\",\n _ => {\n debug!(\n \"Unrecognized legacy macOS 10.x version: {}\",\n version_str\n );\n \"unknown_macos\"\n }\n },\n _ => {\n debug!(\"Unrecognized macOS major version: {}\", version_str);\n \"unknown_macos\"\n }\n };\n\n if os_name != \"unknown_macos\" {\n let platform_tag = if arch == \"arm64\" {\n format!(\"{arch}_{os_name}\")\n } else {\n os_name.to_string()\n };\n debug!(\"Determined platform tag: {}\", platform_tag);\n return platform_tag;\n }\n } else {\n error!(\"sw_vers -productVersion output was empty.\");\n }\n } else {\n error!(\n \"sw_vers -productVersion command failed with status: {}. Stderr: {}\",\n output.status,\n stderr.trim()\n );\n }\n }\n Err(e) => {\n error!(\"Failed to execute /usr/bin/sw_vers -productVersion: {}\", e);\n }\n }\n\n error!(\"!!! FAILED TO DETECT MACOS VERSION VIA SW_VERS !!!\");\n debug!(\"Using UNRELIABLE fallback platform detection. Bottle selection may be incorrect.\");\n if arch == \"arm64\" {\n debug!(\"Falling back to platform tag: arm64_monterey\");\n \"arm64_monterey\".to_string()\n } else {\n debug!(\"Falling back to platform tag: monterey\");\n \"monterey\".to_string()\n }\n } else if cfg!(target_os = \"linux\") {\n if std::env::consts::ARCH == \"aarch64\" {\n \"arm64_linux\".to_string()\n } else if std::env::consts::ARCH == \"x86_64\" {\n \"x86_64_linux\".to_string()\n } else {\n \"unknown\".to_string()\n }\n } else {\n debug!(\n \"Could not determine platform tag for OS: {}\",\n std::env::consts::OS\n );\n \"unknown\".to_string()\n }\n}\n\n// REMOVED: get_cellar_path (now in Config)\n\n// --- get_formula_cellar_path uses Config ---\n// Parameter changed from formula: &Formula to formula_name: &str\n// Parameter changed from config: &Config to cellar_path: &Path for consistency where Config isn't\n// fully available If Config *is* available, call config.formula_cellar_dir(formula.name()) instead.\n// **Keeping original signature for now where Config might not be easily passed**\npub fn get_formula_cellar_path(formula: &Formula, config: &Config) -> PathBuf {\n // Use Config method\n config.formula_cellar_dir(formula.name())\n}\n\n// --- write_receipt (unchanged) ---\npub fn write_receipt(\n formula: &Formula,\n install_dir: &Path,\n installation_type: &str, // \"bottle\" or \"source\"\n) -> Result<()> {\n let receipt_path = install_dir.join(\"INSTALL_RECEIPT.json\");\n let receipt_file = File::create(&receipt_path);\n let mut receipt_file = match receipt_file {\n Ok(file) => file,\n Err(e) => {\n error!(\n \"Failed to create receipt file at {}: {}\",\n receipt_path.display(),\n e\n );\n return Err(SpsError::Io(std::sync::Arc::new(e)));\n }\n };\n\n let resources_result = formula.resources();\n let resources_installed = match resources_result {\n Ok(res) => res.iter().map(|r| r.name.clone()).collect::>(),\n Err(_) => {\n debug!(\n \"Could not retrieve resources for formula {} when writing receipt.\",\n formula.name\n );\n vec![]\n }\n };\n\n let timestamp = chrono::Utc::now().to_rfc3339();\n\n let receipt = serde_json::json!({\n \"name\": formula.name, \"version\": formula.version_str_full(), \"time\": timestamp,\n \"source\": { \"type\": \"api\", \"url\": formula.url, },\n \"built_on\": {\n \"os\": std::env::consts::OS, \"arch\": std::env::consts::ARCH,\n \"platform_tag\": get_current_platform(),\n },\n \"installation_type\": installation_type,\n \"resources_installed\": resources_installed,\n });\n\n let receipt_json = match serde_json::to_string_pretty(&receipt) {\n Ok(json) => json,\n Err(e) => {\n error!(\n \"Failed to serialize receipt JSON for {}: {}\",\n formula.name, e\n );\n return Err(SpsError::Json(std::sync::Arc::new(e)));\n }\n };\n\n if let Err(e) = receipt_file.write_all(receipt_json.as_bytes()) {\n error!(\"Failed to write receipt file for {}: {}\", formula.name, e);\n return Err(SpsError::Io(std::sync::Arc::new(e)));\n }\n\n Ok(())\n}\n\n// --- Re-exports (unchanged) ---\npub use exec::install_bottle;\npub use link::link_formula_artifacts;\n"], ["/sps/sps-core/src/install/extract.rs", "// Path: sps-core/src/install/extract.rs\nuse std::collections::HashSet;\nuse std::fs::{self, File};\nuse std::io::{self, Read, Seek};\nuse std::path::{Component, Path, PathBuf};\nuse std::process::Command;\n\nuse bzip2::read::BzDecoder;\nuse flate2::read::GzDecoder;\nuse sps_common::error::{Result, SpsError};\nuse tar::{Archive, EntryType};\nuse tracing::{debug, error, warn};\nuse zip::ZipArchive;\n\n#[cfg(target_os = \"macos\")]\nuse crate::utils::xattr;\n\npub(crate) fn infer_archive_root_dir(\n archive_path: &Path,\n archive_type: &str,\n) -> Result> {\n tracing::debug!(\n \"Inferring root directory for archive: {}\",\n archive_path.display()\n );\n let file = File::open(archive_path).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed to open archive {}: {}\", archive_path.display(), e),\n )))\n })?;\n\n match archive_type {\n \"zip\" => infer_zip_root(file, archive_path),\n \"gz\" | \"tgz\" => {\n let decompressed = GzDecoder::new(file);\n infer_tar_root(decompressed, archive_path)\n }\n \"bz2\" | \"tbz\" | \"tbz2\" => {\n let decompressed = BzDecoder::new(file);\n infer_tar_root(decompressed, archive_path)\n }\n \"xz\" | \"txz\" => {\n // Use external xz command to decompress, then read as tar\n infer_xz_tar_root(archive_path)\n }\n \"tar\" => infer_tar_root(file, archive_path),\n _ => Err(SpsError::Generic(format!(\n \"Cannot infer root dir for unsupported archive type '{}' in {}\",\n archive_type,\n archive_path.display()\n ))),\n }\n}\n\nfn infer_tar_root(reader: R, archive_path_for_log: &Path) -> Result> {\n let mut archive = Archive::new(reader);\n let mut unique_roots = HashSet::new();\n let mut non_empty_entry_found = false;\n let mut first_component_name: Option = None;\n\n for entry_result in archive.entries()? {\n let entry = entry_result.map_err(|e| {\n SpsError::Generic(format!(\n \"Error reading TAR entry from {}: {}\",\n archive_path_for_log.display(),\n e\n ))\n })?;\n let path = entry\n .path()\n .map_err(|e| {\n SpsError::Generic(format!(\n \"Invalid path in TAR entry from {}: {}\",\n archive_path_for_log.display(),\n e\n ))\n })?\n .into_owned();\n\n if path.components().next().is_none() {\n continue;\n }\n\n if let Some(first_comp) = path.components().next() {\n if let Component::Normal(name) = first_comp {\n non_empty_entry_found = true;\n let current_root = PathBuf::from(name);\n if first_component_name.is_none() {\n first_component_name = Some(current_root.clone());\n }\n unique_roots.insert(current_root);\n\n if unique_roots.len() > 1 {\n tracing::debug!(\n \"Multiple top-level items found in TAR {}, cannot infer single root.\",\n archive_path_for_log.display()\n );\n return Ok(None);\n }\n } else {\n tracing::debug!(\n \"Non-standard top-level component ({:?}) found in TAR {}, cannot infer single root.\",\n first_comp,\n archive_path_for_log.display()\n );\n return Ok(None);\n }\n } else {\n tracing::debug!(\n \"Empty or unusual path found in TAR {}, cannot infer single root.\",\n archive_path_for_log.display()\n );\n return Ok(None);\n }\n }\n\n if unique_roots.len() == 1 && non_empty_entry_found {\n let inferred_root = first_component_name.unwrap();\n tracing::debug!(\n \"Inferred single root directory in TAR {}: {}\",\n archive_path_for_log.display(),\n inferred_root.display()\n );\n Ok(Some(inferred_root))\n } else if !non_empty_entry_found {\n tracing::warn!(\n \"TAR archive {} appears to be empty or contain only metadata.\",\n archive_path_for_log.display()\n );\n Ok(None)\n } else {\n tracing::debug!(\n \"No single common root directory found in TAR {}. unique_roots count: {}\",\n archive_path_for_log.display(),\n unique_roots.len()\n );\n Ok(None)\n }\n}\n\nfn infer_xz_tar_root(archive_path: &Path) -> Result> {\n // Create a temporary file for decompressed content\n let temp_file =\n tempfile::NamedTempFile::new().map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n\n // Use external xz command to decompress\n let output = Command::new(\"xz\")\n .args([\"-dc\", archive_path.to_str().unwrap()])\n .output()\n .map_err(|e| {\n SpsError::Generic(format!(\n \"Failed to run xz command for decompression: {e}. Make sure xz is installed.\"\n ))\n })?;\n\n if !output.status.success() {\n return Err(SpsError::Generic(format!(\n \"xz decompression failed: {}\",\n String::from_utf8_lossy(&output.stderr)\n )));\n }\n\n // Write decompressed data to temp file\n std::fs::write(temp_file.path(), &output.stdout)\n .map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n\n // Read as tar\n let file = File::open(temp_file.path()).map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n infer_tar_root(file, archive_path)\n}\n\nfn infer_zip_root(reader: R, archive_path: &Path) -> Result> {\n let mut archive = ZipArchive::new(reader).map_err(|e| {\n SpsError::Generic(format!(\n \"Failed to open ZIP archive {}: {}\",\n archive_path.display(),\n e\n ))\n })?;\n\n let mut root_candidates = HashSet::new();\n\n for i in 0..archive.len() {\n let file = archive\n .by_index(i)\n .map_err(|e| SpsError::Generic(format!(\"Failed to read ZIP entry {i}: {e}\")))?;\n\n if let Some(enclosed_name) = file.enclosed_name() {\n if let Some(Component::Normal(name)) = enclosed_name.components().next() {\n root_candidates.insert(name.to_string_lossy().to_string());\n }\n }\n }\n\n if root_candidates.len() == 1 {\n let root = root_candidates.into_iter().next().unwrap();\n Ok(Some(PathBuf::from(root)))\n } else {\n Ok(None)\n }\n}\n\n#[cfg(target_os = \"macos\")]\npub fn quarantine_extracted_apps_in_stage(stage_dir: &Path, agent_name: &str) -> Result<()> {\n use std::fs;\n\n use tracing::{debug, warn};\n debug!(\n \"Searching for .app bundles in {} to apply quarantine.\",\n stage_dir.display()\n );\n if stage_dir.is_dir() {\n for entry_result in fs::read_dir(stage_dir)? {\n let entry = entry_result?;\n let entry_path = entry.path();\n if entry_path.is_dir() && entry_path.extension().is_some_and(|ext| ext == \"app\") {\n debug!(\n \"Found app bundle in stage: {}. Applying quarantine.\",\n entry_path.display()\n );\n if let Err(e) = xattr::set_quarantine_attribute(&entry_path, agent_name) {\n warn!(\n \"Failed to set quarantine attribute on staged app {}: {}. Installation will continue.\",\n entry_path.display(),\n e\n );\n }\n }\n }\n }\n Ok(())\n}\n\npub fn extract_archive(\n archive_path: &Path,\n target_dir: &Path,\n strip_components: usize,\n archive_type: &str,\n) -> Result<()> {\n debug!(\n \"Extracting archive '{}' (type: {}) to '{}' (strip_components={}) using native Rust crates.\",\n archive_path.display(),\n archive_type,\n target_dir.display(),\n strip_components\n );\n\n fs::create_dir_all(target_dir).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\n \"Failed to create target directory {}: {}\",\n target_dir.display(),\n e\n ),\n )))\n })?;\n\n let file = File::open(archive_path).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed to open archive {}: {}\", archive_path.display(), e),\n )))\n })?;\n\n let result = match archive_type {\n \"zip\" => extract_zip_archive(file, target_dir, strip_components, archive_path),\n \"gz\" | \"tgz\" => {\n let tar = GzDecoder::new(file);\n extract_tar_archive(tar, target_dir, strip_components, archive_path)\n }\n \"bz2\" | \"tbz\" | \"tbz2\" => {\n let tar = BzDecoder::new(file);\n extract_tar_archive(tar, target_dir, strip_components, archive_path)\n }\n \"xz\" | \"txz\" => extract_xz_tar_archive(archive_path, target_dir, strip_components),\n \"tar\" => extract_tar_archive(file, target_dir, strip_components, archive_path),\n _ => Err(SpsError::Generic(format!(\n \"Unsupported archive type provided for extraction: '{}' for file {}\",\n archive_type,\n archive_path.display()\n ))),\n };\n #[cfg(target_os = \"macos\")]\n {\n if result.is_ok() {\n // Only quarantine if main extraction was successful\n if let Err(e) = quarantine_extracted_apps_in_stage(target_dir, \"sps-extractor\") {\n tracing::warn!(\n \"Error during post-extraction quarantine scan for {}: {}\",\n archive_path.display(),\n e\n );\n }\n }\n }\n result\n}\n\n/// Represents a hardlink operation that was deferred.\nfn extract_xz_tar_archive(\n archive_path: &Path,\n target_dir: &Path,\n strip_components: usize,\n) -> Result<()> {\n debug!(\n \"Extracting XZ+TAR archive using external xz command: {}\",\n archive_path.display()\n );\n\n // Create a temporary file for decompressed content\n let temp_file =\n tempfile::NamedTempFile::new().map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n\n // Use external xz command to decompress\n let output = Command::new(\"xz\")\n .args([\"-dc\", archive_path.to_str().unwrap()])\n .output()\n .map_err(|e| {\n SpsError::Generic(format!(\n \"Failed to run xz command for extraction: {e}. Make sure xz is installed.\"\n ))\n })?;\n\n if !output.status.success() {\n return Err(SpsError::Generic(format!(\n \"xz decompression failed during extraction: {}\",\n String::from_utf8_lossy(&output.stderr)\n )));\n }\n\n // Write decompressed data to temp file\n std::fs::write(temp_file.path(), &output.stdout)\n .map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n\n // Extract as tar\n let file = File::open(temp_file.path()).map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n extract_tar_archive(file, target_dir, strip_components, archive_path)\n}\n\n#[cfg(unix)]\nstruct DeferredHardLink {\n link_path_in_archive: PathBuf,\n target_name_in_archive: PathBuf,\n}\n\nfn extract_tar_archive(\n reader: R,\n target_dir: &Path,\n strip_components: usize,\n archive_path_for_log: &Path,\n) -> Result<()> {\n let mut archive = Archive::new(reader);\n archive.set_preserve_permissions(true);\n archive.set_unpack_xattrs(true);\n archive.set_overwrite(true);\n\n debug!(\n \"Starting TAR extraction for {}\",\n archive_path_for_log.display()\n );\n\n #[cfg(unix)]\n let mut deferred_hardlinks: Vec = Vec::new();\n let mut errors: Vec = Vec::new();\n\n for entry_result in archive.entries()? {\n let mut entry = entry_result.map_err(|e| {\n SpsError::Generic(format!(\n \"Error reading TAR entry from {}: {}\",\n archive_path_for_log.display(),\n e\n ))\n })?;\n\n let original_path_in_archive: PathBuf = entry\n .path()\n .map_err(|e| {\n SpsError::Generic(format!(\n \"Invalid path in TAR entry from {}: {}\",\n archive_path_for_log.display(),\n e\n ))\n })?\n .into_owned();\n\n let stripped_components_iter: Vec> = original_path_in_archive\n .components()\n .skip(strip_components)\n .collect();\n\n if stripped_components_iter.is_empty() {\n debug!(\n \"Skipping entry due to strip_components: {:?}\",\n original_path_in_archive\n );\n continue;\n }\n\n let mut final_target_path_on_disk = target_dir.to_path_buf();\n for comp in stripped_components_iter {\n match comp {\n Component::Normal(p) => final_target_path_on_disk.push(p),\n Component::CurDir => {}\n Component::ParentDir => {\n let msg = format!(\n \"Unsafe '..' in TAR path {} after stripping in {}\",\n original_path_in_archive.display(),\n archive_path_for_log.display()\n );\n error!(\"{}\", msg);\n errors.push(msg);\n continue;\n }\n Component::Prefix(_) | Component::RootDir => {\n let msg = format!(\n \"Disallowed component {:?} in TAR path {}\",\n comp,\n original_path_in_archive.display()\n );\n error!(\"{}\", msg);\n errors.push(msg);\n continue;\n }\n }\n }\n\n if !final_target_path_on_disk.starts_with(target_dir) {\n let msg = format!(\n \"Path traversal {} -> {} detected in {}\",\n original_path_in_archive.display(),\n final_target_path_on_disk.display(),\n archive_path_for_log.display()\n );\n error!(\"{}\", msg);\n errors.push(msg);\n continue;\n }\n\n if let Some(parent) = final_target_path_on_disk.parent() {\n if !parent.exists() {\n fs::create_dir_all(parent).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(io::Error::new(\n e.kind(),\n format!(\"Failed create parent dir {}: {}\", parent.display(), e),\n )))\n })?;\n }\n }\n\n #[cfg(unix)]\n if entry.header().entry_type() == EntryType::Link {\n if let Ok(Some(link_name_in_archive)) = entry.link_name() {\n let deferred_link = DeferredHardLink {\n link_path_in_archive: original_path_in_archive.clone(),\n target_name_in_archive: link_name_in_archive.into_owned(),\n };\n debug!(\n \"Deferring hardlink: archive path '{}' -> archive target '{}'\",\n original_path_in_archive.display(),\n deferred_link.target_name_in_archive.display()\n );\n deferred_hardlinks.push(deferred_link);\n continue;\n } else {\n let msg = format!(\n \"Hardlink entry '{}' in {} has no link target name.\",\n original_path_in_archive.display(),\n archive_path_for_log.display()\n );\n warn!(\"{}\", msg);\n errors.push(msg);\n continue;\n }\n }\n\n match entry.unpack(&final_target_path_on_disk) {\n Ok(_) => debug!(\n \"Unpacked TAR entry to: {}\",\n final_target_path_on_disk.display()\n ),\n Err(e) => {\n if e.kind() != io::ErrorKind::AlreadyExists {\n let msg = format!(\n \"Failed to unpack entry {:?} to {}: {}. Entry type: {:?}\",\n original_path_in_archive,\n final_target_path_on_disk.display(),\n e,\n entry.header().entry_type()\n );\n error!(\"{}\", msg);\n errors.push(msg);\n } else {\n debug!(\"Entry already exists at {}, skipping unpack (tar crate overwrite=true handles this).\", final_target_path_on_disk.display());\n }\n }\n }\n }\n\n #[cfg(unix)]\n for deferred in deferred_hardlinks {\n let mut disk_link_path = target_dir.to_path_buf();\n for comp in deferred\n .link_path_in_archive\n .components()\n .skip(strip_components)\n {\n if let Component::Normal(p) = comp {\n disk_link_path.push(p);\n }\n // Other components should have been caught by safety checks above\n }\n\n let mut disk_target_path = target_dir.to_path_buf();\n // The link_name_in_archive is relative to the archive root *before* stripping.\n // We need to apply stripping to it as well to find its final disk location.\n for comp in deferred\n .target_name_in_archive\n .components()\n .skip(strip_components)\n {\n if let Component::Normal(p) = comp {\n disk_target_path.push(p);\n }\n }\n\n if !disk_target_path.starts_with(target_dir) || !disk_link_path.starts_with(target_dir) {\n let msg = format!(\"Skipping deferred hardlink due to path traversal attempt: link '{}' -> target '{}'\", disk_link_path.display(), disk_target_path.display());\n error!(\"{}\", msg);\n errors.push(msg);\n continue;\n }\n\n debug!(\n \"Attempting deferred hardlink: disk link path '{}' -> disk target path '{}'\",\n disk_link_path.display(),\n disk_target_path.display()\n );\n\n if disk_target_path.exists() {\n if let Some(parent) = disk_link_path.parent() {\n if !parent.exists() {\n if let Err(e) = fs::create_dir_all(parent) {\n let msg = format!(\n \"Failed to create parent directory for deferred hardlink {}: {}\",\n disk_link_path.display(),\n e\n );\n error!(\"{}\", msg);\n errors.push(msg);\n continue;\n }\n }\n }\n\n if disk_link_path.symlink_metadata().is_ok() {\n // Check if something (file or symlink) exists at the link creation spot\n if let Err(e) = fs::remove_file(&disk_link_path) {\n // Attempt to remove it\n warn!(\"Could not remove existing file/symlink at hardlink destination {}: {}. Hardlink creation may fail.\", disk_link_path.display(), e);\n }\n }\n\n if let Err(e) = fs::hard_link(&disk_target_path, &disk_link_path) {\n let msg = format!(\n \"Failed to create deferred hardlink '{}' -> '{}': {}. Target exists: {}\",\n disk_link_path.display(),\n disk_target_path.display(),\n e,\n disk_target_path.exists()\n );\n error!(\"{}\", msg);\n errors.push(msg);\n } else {\n debug!(\n \"Successfully created deferred hardlink: '{}' -> '{}'\",\n disk_link_path.display(),\n disk_target_path.display()\n );\n }\n } else {\n let msg = format!(\n \"Target '{}' for deferred hardlink '{}' does not exist. Hardlink not created.\",\n disk_target_path.display(),\n disk_link_path.display()\n );\n error!(\"{}\", msg);\n errors.push(msg);\n }\n }\n\n if !errors.is_empty() {\n return Err(SpsError::InstallError(format!(\n \"Failed during TAR extraction for {} with {} error(s): {}\",\n archive_path_for_log.display(),\n errors.len(),\n errors.join(\"; \")\n )));\n }\n\n debug!(\n \"Finished TAR extraction for {}\",\n archive_path_for_log.display()\n );\n #[cfg(target_os = \"macos\")]\n {\n if let Err(e) = quarantine_extracted_apps_in_stage(target_dir, \"sps-tar-extractor\") {\n tracing::warn!(\n \"Error during post-tar extraction quarantine scan for {}: {}\",\n archive_path_for_log.display(),\n e\n );\n }\n }\n Ok(())\n}\n\nfn extract_zip_archive(\n reader: R,\n target_dir: &Path,\n strip_components: usize,\n archive_path_for_log: &Path,\n) -> Result<()> {\n let mut archive = ZipArchive::new(reader).map_err(|e| {\n SpsError::Generic(format!(\n \"Failed to open ZIP {}: {}\",\n archive_path_for_log.display(),\n e\n ))\n })?;\n\n debug!(\n \"Starting ZIP extraction for {}\",\n archive_path_for_log.display()\n );\n\n for i in 0..archive.len() {\n let mut file = archive\n .by_index(i)\n .map_err(|e| SpsError::Generic(format!(\"Failed to read ZIP entry {i}: {e}\")))?;\n\n let Some(original_path_in_archive) = file.enclosed_name() else {\n debug!(\"Skipping unsafe ZIP entry (no enclosed name)\");\n continue;\n };\n\n let stripped_components_iter: Vec> = original_path_in_archive\n .components()\n .skip(strip_components)\n .collect();\n\n if stripped_components_iter.is_empty() {\n debug!(\n \"Skipping ZIP entry {} due to strip_components\",\n original_path_in_archive.display()\n );\n continue;\n }\n\n let mut final_target_path_on_disk = target_dir.to_path_buf();\n for comp in stripped_components_iter {\n match comp {\n Component::Normal(p) => final_target_path_on_disk.push(p),\n Component::CurDir => {}\n Component::ParentDir => {\n error!(\n \"Unsafe '..' in ZIP path {} after strip_components\",\n original_path_in_archive.display()\n );\n return Err(SpsError::Generic(format!(\n \"Unsafe '..' component in ZIP path {}\",\n original_path_in_archive.display()\n )));\n }\n Component::Prefix(_) | Component::RootDir => {\n error!(\n \"Disallowed component {:?} in ZIP path {}\",\n comp,\n original_path_in_archive.display()\n );\n return Err(SpsError::Generic(format!(\n \"Disallowed component in ZIP path {}\",\n original_path_in_archive.display()\n )));\n }\n }\n }\n\n if !final_target_path_on_disk.starts_with(target_dir) {\n error!(\n \"ZIP path traversal detected: {} -> {}\",\n original_path_in_archive.display(),\n final_target_path_on_disk.display()\n );\n return Err(SpsError::Generic(format!(\n \"ZIP path traversal detected in {}\",\n archive_path_for_log.display()\n )));\n }\n\n if let Some(parent) = final_target_path_on_disk.parent() {\n if !parent.exists() {\n fs::create_dir_all(parent).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(io::Error::new(\n e.kind(),\n format!(\n \"Failed to create parent directory {}: {}\",\n parent.display(),\n e\n ),\n )))\n })?;\n }\n }\n\n if file.is_dir() {\n debug!(\n \"Creating directory: {}\",\n final_target_path_on_disk.display()\n );\n fs::create_dir_all(&final_target_path_on_disk).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(io::Error::new(\n e.kind(),\n format!(\n \"Failed to create directory {}: {}\",\n final_target_path_on_disk.display(),\n e\n ),\n )))\n })?;\n } else {\n // Regular file\n if final_target_path_on_disk.exists() {\n match fs::remove_file(&final_target_path_on_disk) {\n Ok(_) => {}\n Err(e) if e.kind() == io::ErrorKind::NotFound => {}\n Err(e) => return Err(SpsError::Io(std::sync::Arc::new(e))),\n }\n }\n\n debug!(\"Extracting file: {}\", final_target_path_on_disk.display());\n let mut outfile = File::create(&final_target_path_on_disk).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(io::Error::new(\n e.kind(),\n format!(\n \"Failed to create file {}: {}\",\n final_target_path_on_disk.display(),\n e\n ),\n )))\n })?;\n\n std::io::copy(&mut file, &mut outfile).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(io::Error::new(\n e.kind(),\n format!(\n \"Failed to write file {}: {}\",\n final_target_path_on_disk.display(),\n e\n ),\n )))\n })?;\n\n // Set permissions on Unix systems\n #[cfg(unix)]\n {\n use std::os::unix::fs::PermissionsExt;\n if let Some(mode) = file.unix_mode() {\n let perms = std::fs::Permissions::from_mode(mode);\n std::fs::set_permissions(&final_target_path_on_disk, perms)\n .map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n }\n }\n }\n }\n\n debug!(\n \"Finished ZIP extraction for {}\",\n archive_path_for_log.display()\n );\n\n // Apply quarantine to extracted apps on macOS\n #[cfg(target_os = \"macos\")]\n {\n if let Err(e) = quarantine_extracted_apps_in_stage(target_dir, \"sps-zip-extractor\") {\n tracing::warn!(\n \"Error during post-zip extraction quarantine scan for {}: {}\",\n archive_path_for_log.display(),\n e\n );\n }\n }\n\n Ok(())\n}\n"], ["/sps/sps-common/src/model/formula.rs", "// sps-core/src/model/formula.rs\n// *** Corrected: Removed derive Deserialize from ResourceSpec, removed unused SpsError import,\n// added ResourceSpec struct and parsing ***\n\nuse std::collections::HashMap;\nuse std::path::{Path, PathBuf};\n\nuse semver::Version;\nuse serde::{de, Deserialize, Deserializer, Serialize};\nuse serde_json::Value;\nuse tracing::{debug, error};\n\nuse crate::dependency::{Dependency, DependencyTag, Requirement};\nuse crate::error::Result; // <-- Import only Result // Use log crate imports\n\n// --- Resource Spec Struct ---\n// *** Added struct definition, REMOVED #[derive(Deserialize)] ***\n#[derive(Debug, Clone, Serialize, PartialEq, Eq)]\npub struct ResourceSpec {\n pub name: String,\n pub url: String,\n pub sha256: String,\n // Add other potential fields like version if needed later\n}\n\n// --- Bottle Related Structs (Original structure) ---\n#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]\npub struct BottleFileSpec {\n pub url: String,\n pub sha256: String,\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]\npub struct BottleSpec {\n pub stable: Option,\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]\npub struct BottleStableSpec {\n pub rebuild: u32,\n #[serde(default)]\n pub files: HashMap,\n}\n\n// --- Formula Version Struct (Original structure) ---\n#[derive(Deserialize, Serialize, Debug, Clone, Default, PartialEq, Eq)]\npub struct FormulaVersions {\n pub stable: Option,\n pub head: Option,\n #[serde(default)]\n pub bottle: bool,\n}\n\n// --- Main Formula Struct ---\n// *** Added 'resources' field ***\n#[derive(Debug, Clone, Serialize, PartialEq, Eq)]\npub struct Formula {\n pub name: String,\n pub stable_version_str: String,\n #[serde(rename = \"versions\")]\n pub version_semver: Version,\n #[serde(default)]\n pub revision: u32,\n #[serde(default)]\n pub desc: Option,\n #[serde(default)]\n pub homepage: Option,\n #[serde(default)]\n pub url: String,\n #[serde(default)]\n pub sha256: String,\n #[serde(default)]\n pub mirrors: Vec,\n #[serde(default)]\n pub bottle: BottleSpec,\n #[serde(skip_deserializing)]\n pub dependencies: Vec,\n #[serde(default, deserialize_with = \"deserialize_requirements\")]\n pub requirements: Vec,\n #[serde(skip_deserializing)] // Skip direct deserialization for this field\n pub resources: Vec, // Stores parsed resources\n #[serde(skip)]\n pub install_keg_path: Option,\n}\n\n// Custom deserialization logic for Formula\nimpl<'de> Deserialize<'de> for Formula {\n fn deserialize(deserializer: D) -> std::result::Result\n where\n D: Deserializer<'de>,\n {\n // Temporary struct reflecting the JSON structure more closely\n // *** Added 'resources' field to capture raw JSON Value ***\n #[derive(Deserialize, Debug)]\n struct RawFormulaData {\n name: String,\n #[serde(default)]\n revision: u32,\n desc: Option,\n homepage: Option,\n versions: FormulaVersions,\n #[serde(default)]\n url: String,\n #[serde(default)]\n sha256: String,\n #[serde(default)]\n mirrors: Vec,\n #[serde(default)]\n bottle: BottleSpec,\n #[serde(default)]\n dependencies: Vec,\n #[serde(default)]\n build_dependencies: Vec,\n #[serde(default)]\n test_dependencies: Vec,\n #[serde(default)]\n recommended_dependencies: Vec,\n #[serde(default)]\n optional_dependencies: Vec,\n #[serde(default, deserialize_with = \"deserialize_requirements\")]\n requirements: Vec,\n #[serde(default)]\n resources: Vec, // Capture resources as generic Value first\n #[serde(default)]\n urls: Option,\n }\n\n let raw: RawFormulaData = RawFormulaData::deserialize(deserializer)?;\n\n // --- Version Parsing (Original logic) ---\n let stable_version_str = raw\n .versions\n .stable\n .clone()\n .ok_or_else(|| de::Error::missing_field(\"versions.stable\"))?;\n let version_semver = match crate::model::version::Version::parse(&stable_version_str) {\n Ok(v) => v.into(),\n Err(_) => {\n let mut majors = 0u32;\n let mut minors = 0u32;\n let mut patches = 0u32;\n let mut part_count = 0;\n for (i, part) in stable_version_str.split('.').enumerate() {\n let numeric_part = part\n .chars()\n .take_while(|c| c.is_ascii_digit())\n .collect::();\n if numeric_part.is_empty() && i > 0 {\n break;\n }\n if numeric_part.len() < part.len() && i > 0 {\n if let Ok(num) = numeric_part.parse::() {\n match i {\n 0 => majors = num,\n 1 => minors = num,\n 2 => patches = num,\n _ => {}\n }\n part_count += 1;\n }\n break;\n }\n if let Ok(num) = numeric_part.parse::() {\n match i {\n 0 => majors = num,\n 1 => minors = num,\n 2 => patches = num,\n _ => {}\n }\n part_count += 1;\n }\n if i >= 2 {\n break;\n }\n }\n let version_str_padded = match part_count {\n 1 => format!(\"{majors}.0.0\"),\n 2 => format!(\"{majors}.{minors}.0\"),\n _ => format!(\"{majors}.{minors}.{patches}\"),\n };\n match Version::parse(&version_str_padded) {\n Ok(v) => v,\n Err(_) => {\n error!(\n \"Warning: Could not parse version '{}' (sanitized to '{}') for formula '{}'. Using 0.0.0.\",\n stable_version_str, version_str_padded, raw.name\n );\n Version::new(0, 0, 0)\n }\n }\n }\n };\n\n // --- URL/SHA256 Logic (Original logic) ---\n let mut final_url = raw.url;\n let mut final_sha256 = raw.sha256;\n if final_url.is_empty() {\n if let Some(Value::Object(urls_map)) = raw.urls {\n if let Some(Value::Object(stable_url_info)) = urls_map.get(\"stable\") {\n if let Some(Value::String(u)) = stable_url_info.get(\"url\") {\n final_url = u.clone();\n }\n if let Some(Value::String(s)) = stable_url_info\n .get(\"checksum\")\n .or_else(|| stable_url_info.get(\"sha256\"))\n {\n final_sha256 = s.clone();\n }\n }\n }\n }\n if final_url.is_empty() && raw.versions.head.is_none() {\n debug!(\"Warning: Formula '{}' has no stable URL defined.\", raw.name);\n }\n\n // --- Dependency Processing (Original logic) ---\n let mut combined_dependencies: Vec = Vec::new();\n let mut seen_deps: HashMap = HashMap::new();\n let mut process_list = |deps: &[String], tag: DependencyTag| {\n for name in deps {\n *seen_deps\n .entry(name.clone())\n .or_insert(DependencyTag::empty()) |= tag;\n }\n };\n process_list(&raw.dependencies, DependencyTag::RUNTIME);\n process_list(&raw.build_dependencies, DependencyTag::BUILD);\n process_list(&raw.test_dependencies, DependencyTag::TEST);\n process_list(\n &raw.recommended_dependencies,\n DependencyTag::RECOMMENDED | DependencyTag::RUNTIME,\n );\n process_list(\n &raw.optional_dependencies,\n DependencyTag::OPTIONAL | DependencyTag::RUNTIME,\n );\n for (name, tags) in seen_deps {\n combined_dependencies.push(Dependency::new_with_tags(name, tags));\n }\n\n // --- Resource Processing ---\n // *** Added parsing logic for the 'resources' field ***\n let mut combined_resources: Vec = Vec::new();\n for res_val in raw.resources {\n // Homebrew API JSON format puts resource spec inside a keyed object\n // e.g., { \"resource_name\": { \"url\": \"...\", \"sha256\": \"...\" } }\n if let Value::Object(map) = res_val {\n // Assume only one key-value pair per object in the array\n if let Some((res_name, res_spec_val)) = map.into_iter().next() {\n // Use the manual Deserialize impl for ResourceSpec\n match ResourceSpec::deserialize(res_spec_val.clone()) {\n // Use ::deserialize\n Ok(mut res_spec) => {\n // Inject the name from the key if missing\n if res_spec.name.is_empty() {\n res_spec.name = res_name;\n } else if res_spec.name != res_name {\n debug!(\n \"Resource name mismatch in formula '{}': key '{}' vs spec '{}'. Using key.\",\n raw.name, res_name, res_spec.name\n );\n res_spec.name = res_name; // Prefer key name\n }\n // Ensure required fields are present\n if res_spec.url.is_empty() || res_spec.sha256.is_empty() {\n debug!(\n \"Resource '{}' for formula '{}' is missing URL or SHA256. Skipping.\",\n res_spec.name, raw.name\n );\n continue;\n }\n debug!(\n \"Parsed resource '{}' for formula '{}'\",\n res_spec.name, raw.name\n );\n combined_resources.push(res_spec);\n }\n Err(e) => {\n // Use display for the error which comes from serde::de::Error::custom\n debug!(\n \"Failed to parse resource spec value for key '{}' in formula '{}': {}. Value: {:?}\",\n res_name, raw.name, e, res_spec_val\n );\n }\n }\n } else {\n debug!(\"Empty resource object found in formula '{}'.\", raw.name);\n }\n } else {\n debug!(\n \"Unexpected format for resource entry in formula '{}': expected object, got {:?}\",\n raw.name, res_val\n );\n }\n }\n\n Ok(Self {\n name: raw.name,\n stable_version_str,\n version_semver,\n revision: raw.revision,\n desc: raw.desc,\n homepage: raw.homepage,\n url: final_url,\n sha256: final_sha256,\n mirrors: raw.mirrors,\n bottle: raw.bottle,\n dependencies: combined_dependencies,\n requirements: raw.requirements,\n resources: combined_resources, // Assign parsed resources\n install_keg_path: None,\n })\n }\n}\n\n// --- Formula impl Methods ---\nimpl Formula {\n // dependencies() and requirements() are unchanged\n pub fn dependencies(&self) -> Result> {\n Ok(self.dependencies.clone())\n }\n pub fn requirements(&self) -> Result> {\n Ok(self.requirements.clone())\n }\n\n // *** Added: Returns a clone of the defined resources. ***\n pub fn resources(&self) -> Result> {\n Ok(self.resources.clone())\n }\n\n // Other methods (set_keg_path, version_str_full, accessors) are unchanged\n pub fn set_keg_path(&mut self, path: PathBuf) {\n self.install_keg_path = Some(path);\n }\n pub fn version_str_full(&self) -> String {\n if self.revision > 0 {\n format!(\"{}_{}\", self.stable_version_str, self.revision)\n } else {\n self.stable_version_str.clone()\n }\n }\n pub fn name(&self) -> &str {\n &self.name\n }\n pub fn version(&self) -> &Version {\n &self.version_semver\n }\n pub fn source_url(&self) -> &str {\n &self.url\n }\n pub fn source_sha256(&self) -> &str {\n &self.sha256\n }\n pub fn get_bottle_spec(&self, bottle_tag: &str) -> Option<&BottleFileSpec> {\n self.bottle.stable.as_ref()?.files.get(bottle_tag)\n }\n}\n\n// --- BuildEnvironment Dependency Interface (Unchanged) ---\npub trait FormulaDependencies {\n fn name(&self) -> &str;\n fn install_prefix(&self, cellar_path: &Path) -> Result;\n fn resolved_runtime_dependency_paths(&self) -> Result>;\n fn resolved_build_dependency_paths(&self) -> Result>;\n fn all_resolved_dependency_paths(&self) -> Result>;\n}\nimpl FormulaDependencies for Formula {\n fn name(&self) -> &str {\n &self.name\n }\n fn install_prefix(&self, cellar_path: &Path) -> Result {\n let version_string = self.version_str_full();\n Ok(cellar_path.join(self.name()).join(version_string))\n }\n fn resolved_runtime_dependency_paths(&self) -> Result> {\n Ok(Vec::new())\n }\n fn resolved_build_dependency_paths(&self) -> Result> {\n Ok(Vec::new())\n }\n fn all_resolved_dependency_paths(&self) -> Result> {\n Ok(Vec::new())\n }\n}\n\n// --- Deserialization Helpers ---\n// deserialize_requirements remains unchanged\nfn deserialize_requirements<'de, D>(\n deserializer: D,\n) -> std::result::Result, D::Error>\nwhere\n D: serde::Deserializer<'de>,\n{\n #[derive(Deserialize, Debug)]\n struct ReqWrapper {\n #[serde(default)]\n name: String,\n #[serde(default)]\n version: Option,\n #[serde(default)]\n cask: Option,\n #[serde(default)]\n download: Option,\n }\n let raw_reqs: Vec = Deserialize::deserialize(deserializer)?;\n let mut requirements = Vec::new();\n for req_val in raw_reqs {\n if let Ok(req_obj) = serde_json::from_value::(req_val.clone()) {\n match req_obj.name.as_str() {\n \"macos\" => {\n requirements.push(Requirement::MacOS(\n req_obj.version.unwrap_or_else(|| \"any\".to_string()),\n ));\n }\n \"xcode\" => {\n requirements.push(Requirement::Xcode(\n req_obj.version.unwrap_or_else(|| \"any\".to_string()),\n ));\n }\n \"cask\" => {\n requirements.push(Requirement::Other(format!(\n \"Cask Requirement: {}\",\n req_obj.cask.unwrap_or_else(|| \"?\".to_string())\n )));\n }\n \"download\" => {\n requirements.push(Requirement::Other(format!(\n \"Download Requirement: {}\",\n req_obj.download.unwrap_or_else(|| \"?\".to_string())\n )));\n }\n _ => requirements.push(Requirement::Other(format!(\n \"Unknown requirement type: {req_obj:?}\"\n ))),\n }\n } else if let Value::String(req_str) = req_val {\n match req_str.as_str() {\n \"macos\" => requirements.push(Requirement::MacOS(\"latest\".to_string())),\n \"xcode\" => requirements.push(Requirement::Xcode(\"latest\".to_string())),\n _ => {\n requirements.push(Requirement::Other(format!(\"Simple requirement: {req_str}\")))\n }\n }\n } else {\n debug!(\"Warning: Could not parse requirement: {:?}\", req_val);\n requirements.push(Requirement::Other(format!(\n \"Unparsed requirement: {req_val:?}\"\n )));\n }\n }\n Ok(requirements)\n}\n\n// Manual impl Deserialize for ResourceSpec (unchanged, this is needed)\nimpl<'de> Deserialize<'de> for ResourceSpec {\n fn deserialize(deserializer: D) -> std::result::Result\n where\n D: Deserializer<'de>,\n {\n #[derive(Deserialize)]\n struct Helper {\n #[serde(default)]\n name: String, // name is often the key, not in the value\n url: String,\n sha256: String,\n }\n let helper = Helper::deserialize(deserializer)?;\n // Note: The actual resource name comes from the key in the map during Formula\n // deserialization\n Ok(Self {\n name: helper.name,\n url: helper.url,\n sha256: helper.sha256,\n })\n }\n}\n"], ["/sps/sps-common/src/dependency/resolver.rs", "// sps-common/src/dependency/resolver.rs\nuse std::collections::{HashMap, HashSet, VecDeque};\nuse std::path::{Path, PathBuf};\nuse std::sync::Arc;\n\nuse tracing::{debug, error, warn};\n\nuse crate::dependency::{Dependency, DependencyTag};\nuse crate::error::{Result, SpsError};\nuse crate::formulary::Formulary;\nuse crate::keg::KegRegistry;\nuse crate::model::formula::Formula;\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq)]\npub enum NodeInstallStrategy {\n BottlePreferred,\n SourceOnly,\n BottleOrFail,\n}\n\n#[derive(Debug, Clone, Default)]\npub struct PerTargetInstallPreferences {\n pub force_source_build_targets: HashSet,\n pub force_bottle_only_targets: HashSet,\n}\n\npub struct ResolutionContext<'a> {\n pub formulary: &'a Formulary,\n pub keg_registry: &'a KegRegistry,\n pub sps_prefix: &'a Path,\n pub include_optional: bool,\n pub include_test: bool,\n pub skip_recommended: bool,\n pub initial_target_preferences: &'a PerTargetInstallPreferences,\n pub build_all_from_source: bool,\n pub cascade_source_preference_to_dependencies: bool,\n pub has_bottle_for_current_platform: fn(&Formula) -> bool,\n pub initial_target_actions: &'a HashMap,\n}\n\n#[derive(Debug, Clone)]\npub struct ResolvedDependency {\n pub formula: Arc,\n pub keg_path: Option,\n pub opt_path: Option,\n pub status: ResolutionStatus,\n pub accumulated_tags: DependencyTag,\n pub determined_install_strategy: NodeInstallStrategy,\n pub failure_reason: Option,\n}\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq)]\npub enum ResolutionStatus {\n Installed,\n Missing,\n Requested,\n SkippedOptional,\n NotFound,\n Failed,\n}\n\n#[derive(Debug, Clone, Default)]\npub struct ResolvedGraph {\n pub install_plan: Vec,\n pub build_dependency_opt_paths: Vec,\n pub runtime_dependency_opt_paths: Vec,\n pub resolution_details: HashMap,\n}\n\n// Added empty constructor\nimpl ResolvedGraph {\n pub fn empty() -> Self {\n Default::default()\n }\n}\n\npub struct DependencyResolver<'a> {\n context: ResolutionContext<'a>,\n formula_cache: HashMap>,\n visiting: HashSet,\n resolution_details: HashMap,\n errors: HashMap>,\n}\n\nimpl<'a> DependencyResolver<'a> {\n pub fn new(context: ResolutionContext<'a>) -> Self {\n Self {\n context,\n formula_cache: HashMap::new(),\n visiting: HashSet::new(),\n resolution_details: HashMap::new(),\n errors: HashMap::new(),\n }\n }\n\n fn determine_node_install_strategy(\n &self,\n formula_name: &str,\n formula_arc: &Arc,\n is_initial_target: bool,\n requesting_parent_strategy: Option,\n ) -> NodeInstallStrategy {\n if is_initial_target {\n if self\n .context\n .initial_target_preferences\n .force_source_build_targets\n .contains(formula_name)\n {\n return NodeInstallStrategy::SourceOnly;\n }\n if self\n .context\n .initial_target_preferences\n .force_bottle_only_targets\n .contains(formula_name)\n {\n return NodeInstallStrategy::BottleOrFail;\n }\n }\n\n if self.context.build_all_from_source {\n return NodeInstallStrategy::SourceOnly;\n }\n\n if self.context.cascade_source_preference_to_dependencies\n && matches!(\n requesting_parent_strategy,\n Some(NodeInstallStrategy::SourceOnly)\n )\n {\n return NodeInstallStrategy::SourceOnly;\n }\n if matches!(\n requesting_parent_strategy,\n Some(NodeInstallStrategy::BottleOrFail)\n ) {\n return NodeInstallStrategy::BottleOrFail;\n }\n\n let strategy = if (self.context.has_bottle_for_current_platform)(formula_arc) {\n NodeInstallStrategy::BottlePreferred\n } else {\n NodeInstallStrategy::SourceOnly\n };\n\n debug!(\n \"Install strategy for '{formula_name}': {:?} (initial_target={is_initial_target}, parent={:?}, bottle_available={})\",\n strategy,\n requesting_parent_strategy,\n (self.context.has_bottle_for_current_platform)(formula_arc)\n );\n strategy\n }\n\n pub fn resolve_targets(&mut self, targets: &[String]) -> Result {\n debug!(\"Starting dependency resolution for targets: {:?}\", targets);\n self.visiting.clear();\n self.resolution_details.clear();\n self.errors.clear();\n\n for target_name in targets {\n if let Err(e) = self.resolve_recursive(target_name, DependencyTag::RUNTIME, true, None)\n {\n self.errors.insert(target_name.clone(), Arc::new(e));\n warn!(\n \"Resolution failed for target '{}', but continuing for others.\",\n target_name\n );\n }\n }\n\n debug!(\n \"Raw resolved map after initial pass: {:?}\",\n self.resolution_details\n .iter()\n .map(|(k, v)| (k.clone(), v.status, v.accumulated_tags))\n .collect::>()\n );\n\n let sorted_list = match self.topological_sort() {\n Ok(list) => list,\n Err(e @ SpsError::DependencyError(_)) => {\n error!(\"Topological sort failed due to dependency cycle: {}\", e);\n return Err(e);\n }\n Err(e) => {\n error!(\"Topological sort failed: {}\", e);\n return Err(e);\n }\n };\n\n let install_plan: Vec = sorted_list\n .into_iter()\n .filter(|dep| {\n matches!(\n dep.status,\n ResolutionStatus::Missing | ResolutionStatus::Requested\n )\n })\n .collect();\n\n let mut build_paths = Vec::new();\n let mut runtime_paths = Vec::new();\n let mut seen_build_paths = HashSet::new();\n let mut seen_runtime_paths = HashSet::new();\n\n for dep in self.resolution_details.values() {\n if matches!(\n dep.status,\n ResolutionStatus::Installed\n | ResolutionStatus::Requested\n | ResolutionStatus::Missing\n ) {\n if let Some(opt_path) = &dep.opt_path {\n if dep.accumulated_tags.contains(DependencyTag::BUILD)\n && seen_build_paths.insert(opt_path.clone())\n {\n debug!(\"Adding build dep path: {}\", opt_path.display());\n build_paths.push(opt_path.clone());\n }\n if dep.accumulated_tags.intersects(\n DependencyTag::RUNTIME\n | DependencyTag::RECOMMENDED\n | DependencyTag::OPTIONAL,\n ) && seen_runtime_paths.insert(opt_path.clone())\n {\n debug!(\"Adding runtime dep path: {}\", opt_path.display());\n runtime_paths.push(opt_path.clone());\n }\n } else if dep.status != ResolutionStatus::NotFound\n && dep.status != ResolutionStatus::Failed\n {\n debug!(\n \"Warning: No opt_path found for resolved dependency {} ({:?})\",\n dep.formula.name(),\n dep.status\n );\n }\n }\n }\n\n if !self.errors.is_empty() {\n warn!(\n \"Resolution encountered errors for specific targets: {:?}\",\n self.errors\n .iter()\n .map(|(k, v)| (k, v.to_string()))\n .collect::>()\n );\n }\n\n debug!(\n \"Final installation plan (needs install/build): {:?}\",\n install_plan\n .iter()\n .map(|d| (d.formula.name(), d.status))\n .collect::>()\n );\n debug!(\n \"Collected build dependency paths: {:?}\",\n build_paths.iter().map(|p| p.display()).collect::>()\n );\n debug!(\n \"Collected runtime dependency paths: {:?}\",\n runtime_paths\n .iter()\n .map(|p| p.display())\n .collect::>()\n );\n\n Ok(ResolvedGraph {\n install_plan,\n build_dependency_opt_paths: build_paths,\n runtime_dependency_opt_paths: runtime_paths,\n resolution_details: self.resolution_details.clone(),\n })\n }\n\n fn update_existing_resolution(\n &mut self,\n name: &str,\n tags_from_parent_edge: DependencyTag,\n is_initial_target: bool,\n ) -> Result {\n let Some(existing) = self.resolution_details.get_mut(name) else {\n return Ok(false);\n };\n\n let original_status = existing.status;\n let original_tags = existing.accumulated_tags;\n let has_keg = existing.keg_path.is_some();\n\n let mut new_status = original_status;\n if is_initial_target && new_status == ResolutionStatus::Missing {\n new_status = ResolutionStatus::Requested;\n }\n\n let skip_recommended = self.context.skip_recommended;\n let include_optional = self.context.include_optional;\n\n if Self::should_upgrade_optional_status_static(\n new_status,\n tags_from_parent_edge,\n is_initial_target,\n has_keg,\n skip_recommended,\n include_optional,\n ) {\n new_status = if has_keg {\n ResolutionStatus::Installed\n } else if is_initial_target {\n ResolutionStatus::Requested\n } else {\n ResolutionStatus::Missing\n };\n }\n\n let mut needs_revisit = false;\n if new_status != original_status {\n debug!(\n \"Updating status for '{name}' from {:?} to {:?}\",\n original_status, new_status\n );\n existing.status = new_status;\n needs_revisit = true;\n }\n\n let combined_tags = original_tags | tags_from_parent_edge;\n if combined_tags != original_tags {\n debug!(\n \"Updating tags for '{name}' from {:?} to {:?}\",\n original_tags, combined_tags\n );\n existing.accumulated_tags = combined_tags;\n needs_revisit = true;\n }\n\n if !needs_revisit {\n debug!(\"'{}' already resolved with compatible status/tags.\", name);\n } else {\n debug!(\n \"Re-evaluating dependencies for '{}' due to status/tag update\",\n name\n );\n }\n\n Ok(needs_revisit)\n }\n\n fn should_upgrade_optional_status_static(\n current_status: ResolutionStatus,\n tags_from_parent_edge: DependencyTag,\n is_initial_target: bool,\n _has_keg: bool,\n skip_recommended: bool,\n include_optional: bool,\n ) -> bool {\n current_status == ResolutionStatus::SkippedOptional\n && (tags_from_parent_edge.contains(DependencyTag::RUNTIME)\n || tags_from_parent_edge.contains(DependencyTag::BUILD)\n || (tags_from_parent_edge.contains(DependencyTag::RECOMMENDED)\n && !skip_recommended)\n || (is_initial_target && include_optional))\n }\n\n fn load_or_cache_formula(\n &mut self,\n name: &str,\n tags_from_parent_edge: DependencyTag,\n ) -> Result>> {\n if let Some(f) = self.formula_cache.get(name) {\n return Ok(Some(f.clone()));\n }\n\n debug!(\"Loading formula definition for '{}'\", name);\n match self.context.formulary.load_formula(name) {\n Ok(f) => {\n let arc = Arc::new(f);\n self.formula_cache.insert(name.to_string(), arc.clone());\n Ok(Some(arc))\n }\n Err(e) => {\n error!(\"Failed to load formula definition for '{}': {}\", name, e);\n let msg = e.to_string();\n self.resolution_details.insert(\n name.to_string(),\n ResolvedDependency {\n formula: Arc::new(Formula::placeholder(name)),\n keg_path: None,\n opt_path: None,\n status: ResolutionStatus::NotFound,\n accumulated_tags: tags_from_parent_edge,\n determined_install_strategy: NodeInstallStrategy::BottlePreferred,\n failure_reason: Some(msg.clone()),\n },\n );\n self.errors\n .insert(name.to_string(), Arc::new(SpsError::NotFound(msg)));\n Ok(None)\n }\n }\n }\n\n fn create_initial_resolution(\n &mut self,\n name: &str,\n formula_arc: Arc,\n tags_from_parent_edge: DependencyTag,\n is_initial_target: bool,\n requesting_parent_strategy: Option,\n ) -> Result<()> {\n let current_node_strategy = self.determine_node_install_strategy(\n name,\n &formula_arc,\n is_initial_target,\n requesting_parent_strategy,\n );\n\n let (status, keg_path) =\n self.determine_resolution_status(name, is_initial_target, current_node_strategy)?;\n\n debug!(\n \"Initial status for '{}': {:?}, keg: {:?}, opt: {}\",\n name,\n status,\n keg_path,\n self.context.keg_registry.get_opt_path(name).display()\n );\n\n self.resolution_details.insert(\n name.to_string(),\n ResolvedDependency {\n formula: formula_arc.clone(),\n keg_path,\n opt_path: Some(self.context.keg_registry.get_opt_path(name)),\n status,\n accumulated_tags: tags_from_parent_edge,\n determined_install_strategy: current_node_strategy,\n failure_reason: None,\n },\n );\n\n Ok(())\n }\n\n fn determine_resolution_status(\n &self,\n name: &str,\n is_initial_target: bool,\n strategy: NodeInstallStrategy,\n ) -> Result<(ResolutionStatus, Option)> {\n match strategy {\n NodeInstallStrategy::SourceOnly => Ok((\n if is_initial_target {\n ResolutionStatus::Requested\n } else {\n ResolutionStatus::Missing\n },\n None,\n )),\n NodeInstallStrategy::BottlePreferred | NodeInstallStrategy::BottleOrFail => {\n if let Some(keg) = self.context.keg_registry.get_installed_keg(name)? {\n // Check if this is an upgrade target - if so, mark as Requested even if\n // installed\n let should_request_upgrade = is_initial_target\n && self\n .context\n .initial_target_actions\n .get(name)\n .map(|action| {\n matches!(action, crate::pipeline::JobAction::Upgrade { .. })\n })\n .unwrap_or(false);\n\n debug!(\"[Resolver] Package '{}': is_initial_target={}, should_request_upgrade={}, action={:?}\",\n name, is_initial_target, should_request_upgrade,\n self.context.initial_target_actions.get(name));\n\n if should_request_upgrade {\n debug!(\n \"[Resolver] Marking upgrade target '{}' as Requested (was installed)\",\n name\n );\n Ok((ResolutionStatus::Requested, Some(keg.path)))\n } else {\n debug!(\"[Resolver] Marking '{}' as Installed (normal case)\", name);\n Ok((ResolutionStatus::Installed, Some(keg.path)))\n }\n } else {\n debug!(\n \"[Resolver] Package '{}' not installed, marking as {}\",\n name,\n if is_initial_target {\n \"Requested\"\n } else {\n \"Missing\"\n }\n );\n Ok((\n if is_initial_target {\n ResolutionStatus::Requested\n } else {\n ResolutionStatus::Missing\n },\n None,\n ))\n }\n }\n }\n }\n\n fn process_dependencies(\n &mut self,\n dep_snapshot: &ResolvedDependency,\n parent_name: &str,\n ) -> Result<()> {\n for dep in dep_snapshot.formula.dependencies()? {\n let dep_name = &dep.name;\n let dep_tags = dep.tags;\n let parent_formula_name = dep_snapshot.formula.name();\n let parent_strategy = dep_snapshot.determined_install_strategy;\n\n debug!(\n \"RESOLVER: Evaluating edge: parent='{}' ({:?}), child='{}' ({:?})\",\n parent_formula_name, parent_strategy, dep_name, dep_tags\n );\n\n if !self.should_consider_dependency(&dep) {\n if !self.resolution_details.contains_key(dep_name.as_str()) {\n debug!(\"RESOLVER: Child '{}' of '{}' globally SKIPPED (e.g. optional/test not included). Tags: {:?}\", dep_name, parent_formula_name, dep_tags);\n }\n continue;\n }\n\n let should_process = self.context.should_process_dependency_edge(\n &dep_snapshot.formula,\n dep_tags,\n parent_strategy,\n );\n\n if !should_process {\n debug!(\n \"RESOLVER: Edge from '{}' (Strategy: {:?}) to child '{}' (Tags: {:?}) was SKIPPED by should_process_dependency_edge.\",\n parent_formula_name, parent_strategy, dep_name, dep_tags\n );\n continue;\n }\n\n debug!(\n \"RESOLVER: Edge from '{}' (Strategy: {:?}) to child '{}' (Tags: {:?}) WILL BE PROCESSED. Recursing.\",\n parent_formula_name, parent_strategy, dep_name, dep_tags\n );\n\n if let Err(e) = self.resolve_recursive(dep_name, dep_tags, false, Some(parent_strategy))\n {\n // Log the error but don't necessarily stop all resolution for this branch yet\n warn!(\n \"Error resolving child dependency '{}' for parent '{}': {}\",\n dep_name, parent_name, e\n );\n // Optionally, mark parent as failed if child error is critical\n // self.errors.insert(parent_name.to_string(), Arc::new(e)); // Storing error for\n // parent if needed\n }\n }\n Ok(())\n }\n\n fn resolve_recursive(\n &mut self,\n name: &str,\n tags_from_parent_edge: DependencyTag,\n is_initial_target: bool,\n requesting_parent_strategy: Option,\n ) -> Result<()> {\n debug!(\n \"Resolving: {} (requested as {:?}, is_target: {})\",\n name, tags_from_parent_edge, is_initial_target\n );\n\n if self.visiting.contains(name) {\n error!(\"Dependency cycle detected involving: {}\", name);\n return Err(SpsError::DependencyError(format!(\n \"Dependency cycle detected involving '{name}'\"\n )));\n }\n\n if self.update_existing_resolution(name, tags_from_parent_edge, is_initial_target)? {\n // Already exists and was updated, no need to reprocess\n return Ok(());\n }\n\n if self.resolution_details.contains_key(name) {\n // Already exists but didn't need update\n return Ok(());\n }\n\n // New resolution needed\n self.visiting.insert(name.to_string());\n\n let formula_arc = match self.load_or_cache_formula(name, tags_from_parent_edge) {\n Ok(Some(formula)) => formula,\n Ok(None) => {\n self.visiting.remove(name);\n return Ok(()); // Already handled error case\n }\n Err(e) => {\n self.visiting.remove(name);\n return Err(e);\n }\n };\n\n self.create_initial_resolution(\n name,\n formula_arc,\n tags_from_parent_edge,\n is_initial_target,\n requesting_parent_strategy,\n )?;\n\n let dep_snapshot = self\n .resolution_details\n .get(name)\n .expect(\"just inserted\")\n .clone();\n\n if matches!(\n dep_snapshot.status,\n ResolutionStatus::Failed | ResolutionStatus::NotFound\n ) {\n self.visiting.remove(name);\n return Ok(());\n }\n\n self.process_dependencies(&dep_snapshot, name)?;\n\n self.visiting.remove(name);\n debug!(\"Finished resolving '{}'\", name);\n Ok(())\n }\n\n fn topological_sort(&self) -> Result> {\n let mut in_degree: HashMap = HashMap::new();\n let mut adj: HashMap> = HashMap::new();\n let mut sorted_list = Vec::new();\n let mut queue = VecDeque::new();\n\n let relevant_nodes_map: HashMap = self\n .resolution_details\n .iter()\n .filter(|(_, dep)| {\n !matches!(\n dep.status,\n ResolutionStatus::NotFound | ResolutionStatus::Failed\n )\n })\n .map(|(k, v)| (k.clone(), v))\n .collect();\n\n for (parent_name, parent_rd) in &relevant_nodes_map {\n adj.entry(parent_name.clone()).or_default();\n in_degree.entry(parent_name.clone()).or_default();\n\n let parent_strategy = parent_rd.determined_install_strategy;\n if let Ok(dependencies) = parent_rd.formula.dependencies() {\n for child_edge in dependencies {\n let child_name = &child_edge.name;\n if relevant_nodes_map.contains_key(child_name)\n && self.context.should_process_dependency_edge(\n &parent_rd.formula,\n child_edge.tags,\n parent_strategy,\n )\n && adj\n .entry(parent_name.clone())\n .or_default()\n .insert(child_name.clone())\n {\n *in_degree.entry(child_name.clone()).or_default() += 1;\n }\n }\n }\n }\n\n for name in relevant_nodes_map.keys() {\n if *in_degree.get(name).unwrap_or(&1) == 0 {\n queue.push_back(name.clone());\n }\n }\n\n while let Some(u_name) = queue.pop_front() {\n if let Some(resolved_dep) = relevant_nodes_map.get(&u_name) {\n sorted_list.push((**resolved_dep).clone()); // Deref Arc then clone\n // ResolvedDependency\n }\n if let Some(neighbors) = adj.get(&u_name) {\n for v_name in neighbors {\n if relevant_nodes_map.contains_key(v_name) {\n // Check if neighbor is relevant\n if let Some(degree) = in_degree.get_mut(v_name) {\n *degree = degree.saturating_sub(1);\n if *degree == 0 {\n queue.push_back(v_name.clone());\n }\n }\n }\n }\n }\n }\n\n // Check for cycles: if sorted_list's length doesn't match relevant_nodes_map's length\n // (excluding already installed, skipped optional if not included, etc.)\n // A more direct check is if in_degree still contains non-zero values for relevant nodes.\n let mut cycle_detected = false;\n for (name, °ree) in &in_degree {\n if degree > 0 && relevant_nodes_map.contains_key(name) {\n // Further check if this node should have been processed (not skipped globally)\n if let Some(detail) = self.resolution_details.get(name) {\n if self\n .context\n .should_consider_edge_globally(detail.accumulated_tags)\n {\n error!(\"Cycle detected or unresolved dependency: Node '{}' still has in-degree {}. Tags: {:?}\", name, degree, detail.accumulated_tags);\n cycle_detected = true;\n } else {\n debug!(\"Node '{}' has in-degree {} but was globally skipped. Tags: {:?}. Not a cycle error.\", name, degree, detail.accumulated_tags);\n }\n }\n }\n }\n\n if cycle_detected {\n return Err(SpsError::DependencyError(\n \"Circular dependency detected or graph resolution incomplete\".to_string(),\n ));\n }\n\n Ok(sorted_list) // Return the full sorted list of relevant nodes\n }\n\n fn should_consider_dependency(&self, dep: &Dependency) -> bool {\n let tags = dep.tags;\n if tags.contains(DependencyTag::TEST) && !self.context.include_test {\n return false;\n }\n if tags.contains(DependencyTag::OPTIONAL) && !self.context.include_optional {\n return false;\n }\n if tags.contains(DependencyTag::RECOMMENDED) && self.context.skip_recommended {\n return false;\n }\n true\n }\n}\n\nimpl Formula {\n fn placeholder(name: &str) -> Self {\n Self {\n name: name.to_string(),\n stable_version_str: \"0.0.0\".to_string(),\n version_semver: semver::Version::new(0, 0, 0), // Direct use\n revision: 0,\n desc: Some(\"Placeholder for unresolved formula\".to_string()),\n homepage: None,\n url: String::new(),\n sha256: String::new(),\n mirrors: Vec::new(),\n bottle: Default::default(),\n dependencies: Vec::new(),\n requirements: Vec::new(),\n resources: Vec::new(),\n install_keg_path: None,\n }\n }\n}\n\nimpl<'a> ResolutionContext<'a> {\n pub fn should_process_dependency_edge(\n &self,\n parent_formula_for_logging: &Arc,\n edge_tags: DependencyTag,\n parent_node_determined_strategy: NodeInstallStrategy,\n ) -> bool {\n if !self.should_consider_edge_globally(edge_tags) {\n debug!(\n \"Edge with tags {:?} for child of '{}' globally SKIPPED (e.g. optional/test not included).\",\n edge_tags, parent_formula_for_logging.name()\n );\n return false;\n }\n\n match parent_node_determined_strategy {\n NodeInstallStrategy::BottlePreferred | NodeInstallStrategy::BottleOrFail => {\n let is_purely_build_dependency = edge_tags.contains(DependencyTag::BUILD)\n && !edge_tags.intersects(\n DependencyTag::RUNTIME\n | DependencyTag::RECOMMENDED\n | DependencyTag::OPTIONAL,\n );\n if is_purely_build_dependency {\n debug!(\"Edge with tags {:?} SKIPPED: Pure BUILD dependency of a bottle-installed parent '{}'.\", edge_tags, parent_formula_for_logging.name());\n return false;\n }\n }\n NodeInstallStrategy::SourceOnly => {\n // Process all relevant (non-globally-skipped) dependencies for source builds\n }\n }\n debug!(\n \"Edge with tags {:?} WILL BE PROCESSED for parent '{}' (strategy {:?}).\",\n edge_tags,\n parent_formula_for_logging.name(),\n parent_node_determined_strategy\n );\n true\n }\n\n pub fn should_consider_edge_globally(&self, edge_tags: DependencyTag) -> bool {\n if edge_tags.contains(DependencyTag::TEST) && !self.include_test {\n return false;\n }\n if edge_tags.contains(DependencyTag::OPTIONAL) && !self.include_optional {\n return false;\n }\n if edge_tags.contains(DependencyTag::RECOMMENDED) && self.skip_recommended {\n return false;\n }\n true\n }\n}\n"], ["/sps/sps-core/src/install/cask/helpers.rs", "use std::fs;\nuse std::path::Path;\n\nuse sps_common::config::Config;\nuse tracing::debug;\n\n/// Robustly removes a file or directory, handling symlinks and permissions.\n/// If `use_sudo_if_needed` is true, will attempt `sudo rm -rf` on permission errors.\npub fn remove_path_robustly(path: &Path, _config: &Config, use_sudo_if_needed: bool) -> bool {\n if !path.exists() && path.symlink_metadata().is_err() {\n debug!(\"Path {} not found for removal.\", path.display());\n return true;\n }\n let is_dir = path.is_dir()\n && !path\n .symlink_metadata()\n .is_ok_and(|m| m.file_type().is_symlink());\n let removal_op = || -> std::io::Result<()> {\n if is_dir {\n fs::remove_dir_all(path)\n } else {\n fs::remove_file(path)\n }\n };\n\n if let Err(e) = removal_op() {\n if e.kind() == std::io::ErrorKind::NotFound {\n return true;\n }\n if use_sudo_if_needed && e.kind() == std::io::ErrorKind::PermissionDenied {\n debug!(\n \"Direct removal of {} failed (Permission Denied). Trying with sudo rm -rf.\",\n path.display()\n );\n let output = std::process::Command::new(\"sudo\")\n .arg(\"rm\")\n .arg(\"-rf\")\n .arg(path)\n .output();\n match output {\n Ok(out) if out.status.success() => {\n debug!(\"Successfully removed {} with sudo.\", path.display());\n return true;\n }\n Ok(out) => {\n debug!(\n \"`sudo rm -rf {}` failed ({}): {}\",\n path.display(),\n out.status,\n String::from_utf8_lossy(&out.stderr).trim()\n );\n return false;\n }\n Err(sudo_e) => {\n debug!(\n \"Error executing `sudo rm -rf` for {}: {}\",\n path.display(),\n sudo_e\n );\n return false;\n }\n }\n } else {\n debug!(\"Failed to remove {}: {}\", path.display(), e);\n return false;\n }\n }\n debug!(\"Successfully removed {}.\", path.display());\n true\n}\n\n/// Recursively cleans up empty parent directories in the private cask store.\n/// Starts from the given path and walks up, removing empty directories until a non-empty or root is\n/// found.\npub fn cleanup_empty_parent_dirs_in_private_store(start_path: &Path, stop_at: &Path) {\n let mut current = start_path.to_path_buf();\n while current != *stop_at {\n if let Ok(read_dir) = fs::read_dir(¤t) {\n if read_dir.count() == 0 {\n match fs::remove_dir(¤t) {\n Ok(_) => {\n debug!(\"Removed empty directory: {}\", current.display());\n }\n Err(e) => {\n debug!(\"Failed to remove directory {}: {}\", current.display(), e);\n break;\n }\n }\n } else {\n break;\n }\n } else {\n break;\n }\n if let Some(parent) = current.parent() {\n current = parent.to_path_buf();\n } else {\n break;\n }\n }\n}\n"], ["/sps/sps/src/cli/info.rs", "//! Contains the logic for the `info` command.\n\nuse std::sync::Arc;\n\nuse clap::Args;\nuse colored::Colorize;\nuse serde_json::Value;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_net::api;\n\n#[derive(Args, Debug)]\npub struct Info {\n /// Name of the formula or cask\n pub name: String,\n\n /// Show information for a cask, not a formula\n #[arg(long)]\n pub cask: bool,\n}\n\nimpl Info {\n /// Displays detailed information about a formula or cask.\n pub async fn run(&self, _config: &Config, cache: Arc) -> Result<()> {\n let name = &self.name;\n let is_cask = self.cask;\n tracing::debug!(\"Getting info for package: {name}, is_cask: {is_cask}\",);\n\n // Print loading message instead of spinner\n println!(\"Loading info for {name}\");\n\n if self.cask {\n match get_cask_info(Arc::clone(&cache), name).await {\n Ok(info) => {\n print_cask_info(name, &info);\n Ok(())\n }\n Err(e) => Err(e),\n }\n } else {\n match get_formula_info_raw(Arc::clone(&cache), name).await {\n Ok(info) => {\n // Removed bottle check logic here as it was complex and potentially racy.\n // We'll try formula first, then cask if formula fails.\n print_formula_info(name, &info);\n return Ok(());\n }\n Err(SpsError::NotFound(_)) | Err(SpsError::Generic(_)) => {\n // If formula lookup failed (not found or generic error), try cask.\n tracing::debug!(\"Formula '{}' info failed, trying cask.\", name);\n }\n Err(e) => {\n return Err(e); // Propagate other errors (API, JSON, etc.)\n }\n }\n // --- Cask Fallback ---\n match get_cask_info(Arc::clone(&cache), name).await {\n Ok(info) => {\n print_cask_info(name, &info);\n Ok(())\n }\n Err(e) => {\n Err(e) // Return the cask error if both formula and cask fail\n }\n }\n }\n }\n}\n\n/// Retrieves formula information from the cache or API as raw JSON\nasync fn get_formula_info_raw(cache: Arc, name: &str) -> Result {\n match cache.load_raw(\"formula.json\") {\n Ok(formula_data) => {\n let formulas: Vec =\n serde_json::from_str(&formula_data).map_err(SpsError::from)?;\n for formula in formulas {\n if let Some(fname) = formula.get(\"name\").and_then(Value::as_str) {\n if fname == name {\n return Ok(formula);\n }\n }\n // Also check aliases if needed\n if let Some(aliases) = formula.get(\"aliases\").and_then(|a| a.as_array()) {\n if aliases.iter().any(|a| a.as_str() == Some(name)) {\n return Ok(formula);\n }\n }\n }\n tracing::debug!(\"Formula '{}' not found within cached 'formula.json'.\", name);\n // Explicitly return NotFound if not in cache\n return Err(SpsError::NotFound(format!(\n \"Formula '{name}' not found in cache\"\n )));\n }\n Err(e) => tracing::debug!(\n \"Cache file 'formula.json' not found or failed to load ({}). Fetching from API.\",\n e\n ),\n }\n tracing::debug!(\"Fetching formula '{}' directly from API\", name);\n // api::fetch_formula returns Value directly now\n let value = api::fetch_formula(name).await?;\n // Store in cache if fetched successfully\n // Note: This might overwrite the full list cache, consider storing individual files or a map\n // cache.store_raw(&format!(\"formula/{}.json\", name), &value.to_string())?; // Example of\n // storing individually\n Ok(value)\n}\n\n/// Retrieves cask information from the cache or API\nasync fn get_cask_info(cache: Arc, name: &str) -> Result {\n match cache.load_raw(\"cask.json\") {\n Ok(cask_data) => {\n let casks: Vec = serde_json::from_str(&cask_data).map_err(SpsError::from)?;\n for cask in casks {\n if let Some(token) = cask.get(\"token\").and_then(Value::as_str) {\n if token == name {\n return Ok(cask);\n }\n }\n // Check aliases if needed\n if let Some(aliases) = cask.get(\"aliases\").and_then(|a| a.as_array()) {\n if aliases.iter().any(|a| a.as_str() == Some(name)) {\n return Ok(cask);\n }\n }\n }\n tracing::debug!(\"Cask '{}' not found within cached 'cask.json'.\", name);\n // Explicitly return NotFound if not in cache\n return Err(SpsError::NotFound(format!(\n \"Cask '{name}' not found in cache\"\n )));\n }\n Err(e) => tracing::debug!(\n \"Cache file 'cask.json' not found or failed to load ({}). Fetching from API.\",\n e\n ),\n }\n tracing::debug!(\"Fetching cask '{}' directly from API\", name);\n // api::fetch_cask returns Value directly now\n let value = api::fetch_cask(name).await?;\n // Store in cache if fetched successfully\n // cache.store_raw(&format!(\"cask/{}.json\", name), &value.to_string())?; // Example of storing\n // individually\n Ok(value)\n}\n\n/// Prints formula information in a formatted table\nfn print_formula_info(_name: &str, formula: &Value) {\n // Basic info extraction\n let full_name = formula\n .get(\"full_name\")\n .and_then(|f| f.as_str())\n .unwrap_or(\"N/A\");\n let version = formula\n .get(\"versions\")\n .and_then(|v| v.get(\"stable\"))\n .and_then(|s| s.as_str())\n .unwrap_or(\"N/A\");\n let revision = formula\n .get(\"revision\")\n .and_then(|r| r.as_u64())\n .unwrap_or(0);\n let version_str = if revision > 0 {\n format!(\"{version}_{revision}\")\n } else {\n version.to_string()\n };\n let license = formula\n .get(\"license\")\n .and_then(|l| l.as_str())\n .unwrap_or(\"N/A\");\n let homepage = formula\n .get(\"homepage\")\n .and_then(|h| h.as_str())\n .unwrap_or(\"N/A\");\n\n // Header\n println!(\"{}\", format!(\"Formula: {full_name}\").green().bold());\n\n // Summary table\n let mut table = prettytable::Table::new();\n table.set_format(*prettytable::format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n table.add_row(prettytable::row![\"Version\", version_str]);\n table.add_row(prettytable::row![\"License\", license]);\n table.add_row(prettytable::row![\"Homepage\", homepage]);\n table.printstd();\n\n // Detailed sections\n if let Some(desc) = formula.get(\"desc\").and_then(|d| d.as_str()) {\n if !desc.is_empty() {\n println!(\"\\n{}\", \"Description\".blue().bold());\n println!(\"{desc}\");\n }\n }\n if let Some(caveats) = formula.get(\"caveats\").and_then(|c| c.as_str()) {\n if !caveats.is_empty() {\n println!(\"\\n{}\", \"Caveats\".blue().bold());\n println!(\"{caveats}\");\n }\n }\n\n // Combined Dependencies Section\n let mut dep_table = prettytable::Table::new();\n dep_table.set_format(*prettytable::format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n let mut has_deps = false;\n\n let mut add_deps = |title: &str, key: &str, tag: &str| {\n if let Some(deps) = formula.get(key).and_then(|d| d.as_array()) {\n let dep_list: Vec<&str> = deps.iter().filter_map(|d| d.as_str()).collect();\n if !dep_list.is_empty() {\n has_deps = true;\n for (i, d) in dep_list.iter().enumerate() {\n let display_title = if i == 0 { title } else { \"\" };\n let display_tag = if i == 0 {\n format!(\"({tag})\")\n } else {\n \"\".to_string()\n };\n dep_table.add_row(prettytable::row![display_title, d, display_tag]);\n }\n }\n }\n };\n\n add_deps(\"Required\", \"dependencies\", \"runtime\");\n add_deps(\n \"Recommended\",\n \"recommended_dependencies\",\n \"runtime, recommended\",\n );\n add_deps(\"Optional\", \"optional_dependencies\", \"runtime, optional\");\n add_deps(\"Build\", \"build_dependencies\", \"build\");\n add_deps(\"Test\", \"test_dependencies\", \"test\");\n\n if has_deps {\n println!(\"\\n{}\", \"Dependencies\".blue().bold());\n dep_table.printstd();\n }\n\n // Installation hint\n println!(\"\\n{}\", \"Installation\".blue().bold());\n println!(\n \" {} install {}\",\n \"sps\".cyan(),\n formula\n .get(\"name\")\n .and_then(|n| n.as_str())\n .unwrap_or(full_name) // Use short name if available\n );\n}\n\n/// Prints cask information in a formatted table\nfn print_cask_info(name: &str, cask: &Value) {\n // Header\n println!(\"{}\", format!(\"Cask: {name}\").green().bold());\n\n // Summary table\n let mut table = prettytable::Table::new();\n table.set_format(*prettytable::format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n if let Some(names) = cask.get(\"name\").and_then(|n| n.as_array()) {\n if let Some(first) = names.first().and_then(|s| s.as_str()) {\n table.add_row(prettytable::row![\"Name\", first]);\n }\n }\n if let Some(desc) = cask.get(\"desc\").and_then(|d| d.as_str()) {\n table.add_row(prettytable::row![\"Description\", desc]);\n }\n if let Some(homepage) = cask.get(\"homepage\").and_then(|h| h.as_str()) {\n table.add_row(prettytable::row![\"Homepage\", homepage]);\n }\n if let Some(version) = cask.get(\"version\").and_then(|v| v.as_str()) {\n table.add_row(prettytable::row![\"Version\", version]);\n }\n if let Some(url) = cask.get(\"url\").and_then(|u| u.as_str()) {\n table.add_row(prettytable::row![\"Download URL\", url]);\n }\n // Add SHA if present\n if let Some(sha) = cask.get(\"sha256\").and_then(|s| s.as_str()) {\n if !sha.is_empty() {\n table.add_row(prettytable::row![\"SHA256\", sha]);\n }\n }\n table.printstd();\n\n // Dependencies Section\n if let Some(deps) = cask.get(\"depends_on\").and_then(|d| d.as_object()) {\n let mut dep_table = prettytable::Table::new();\n dep_table.set_format(*prettytable::format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n let mut has_deps = false;\n\n if let Some(formulas) = deps.get(\"formula\").and_then(|f| f.as_array()) {\n if !formulas.is_empty() {\n has_deps = true;\n dep_table.add_row(prettytable::row![\n \"Formula\".yellow(),\n formulas\n .iter()\n .map(|v| v.as_str().unwrap_or(\"\"))\n .collect::>()\n .join(\", \")\n ]);\n }\n }\n if let Some(casks) = deps.get(\"cask\").and_then(|c| c.as_array()) {\n if !casks.is_empty() {\n has_deps = true;\n dep_table.add_row(prettytable::row![\n \"Cask\".yellow(),\n casks\n .iter()\n .map(|v| v.as_str().unwrap_or(\"\"))\n .collect::>()\n .join(\", \")\n ]);\n }\n }\n if let Some(macos) = deps.get(\"macos\") {\n has_deps = true;\n let macos_str = match macos {\n Value::String(s) => s.clone(),\n Value::Array(arr) => arr\n .iter()\n .map(|v| v.as_str().unwrap_or(\"\"))\n .collect::>()\n .join(\" or \"),\n _ => \"Unknown\".to_string(),\n };\n dep_table.add_row(prettytable::row![\"macOS\".yellow(), macos_str]);\n }\n\n if has_deps {\n println!(\"\\n{}\", \"Dependencies\".blue().bold());\n dep_table.printstd();\n }\n }\n\n // Installation hint\n println!(\"\\n{}\", \"Installation\".blue().bold());\n println!(\n \" {} install --cask {}\", // Always use --cask for clarity\n \"sps\".cyan(),\n name // Use the token 'name' passed to the function\n );\n}\n// Removed is_bottle_available check\n"], ["/sps/sps/src/pipeline/downloader.rs", "// sps/src/pipeline/downloader.rs\nuse std::fs;\nuse std::path::PathBuf;\nuse std::sync::Arc;\n\nuse reqwest::Client as HttpClient;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::model::InstallTargetIdentifier;\nuse sps_common::pipeline::{DownloadOutcome, PipelineEvent, PlannedJob};\nuse sps_common::SpsError;\nuse sps_core::{build, install};\nuse sps_net::http::ProgressCallback;\nuse sps_net::UrlField;\nuse tokio::sync::{broadcast, mpsc};\nuse tokio::task::JoinSet;\nuse tracing::{error, warn};\n\nuse super::runner::get_panic_message;\n\npub(crate) struct DownloadCoordinator {\n config: Config,\n cache: Arc,\n http_client: Arc,\n event_tx: Option>,\n}\n\nimpl DownloadCoordinator {\n pub fn new(\n config: Config,\n cache: Arc,\n http_client: Arc,\n event_tx: broadcast::Sender,\n ) -> Self {\n Self {\n config,\n cache,\n http_client,\n event_tx: Some(event_tx),\n }\n }\n\n pub async fn coordinate_downloads(\n &mut self,\n planned_jobs: Vec,\n download_outcome_tx: mpsc::Sender,\n ) -> Vec<(String, SpsError)> {\n let mut download_tasks = JoinSet::new();\n let mut critical_spawn_errors: Vec<(String, SpsError)> = Vec::new();\n\n for planned_job in planned_jobs {\n let _job_id_for_task = planned_job.target_id.clone();\n\n let task_config = self.config.clone();\n let task_cache = Arc::clone(&self.cache);\n let task_http_client = Arc::clone(&self.http_client);\n let task_event_tx = self.event_tx.as_ref().cloned();\n let outcome_tx_clone = download_outcome_tx.clone();\n let current_planned_job_for_task = planned_job.clone();\n\n download_tasks.spawn(async move {\n let job_id_in_task = current_planned_job_for_task.target_id.clone();\n let download_path_result: Result;\n\n if let Some(private_path) = current_planned_job_for_task.use_private_store_source.clone() {\n download_path_result = Ok(private_path);\n } else {\n let display_url_for_event = match ¤t_planned_job_for_task.target_definition {\n InstallTargetIdentifier::Formula(f) => {\n if !current_planned_job_for_task.is_source_build {\n sps_core::install::bottle::exec::get_bottle_for_platform(f)\n .map_or_else(|_| f.url.clone(), |(_, spec)| spec.url.clone())\n } else {\n f.url.clone()\n }\n }\n InstallTargetIdentifier::Cask(c) => match &c.url {\n Some(UrlField::Simple(s)) => s.clone(),\n Some(UrlField::WithSpec { url, .. }) => url.clone(),\n None => \"N/A (No Cask URL)\".to_string(),\n },\n };\n\n if display_url_for_event == \"N/A (No Cask URL)\"\n || (display_url_for_event.is_empty() && !current_planned_job_for_task.is_source_build)\n {\n let _err_msg = \"Download URL is missing or invalid\".to_string();\n let sps_err = SpsError::Generic(format!(\n \"Download URL is missing or invalid for job {job_id_in_task}\"\n ));\n if let Some(ref tx) = task_event_tx {\n tx.send(PipelineEvent::download_failed(\n job_id_in_task.clone(),\n display_url_for_event,\n &sps_err,\n )).ok();\n }\n download_path_result = Err(sps_err);\n } else {\n if let Some(ref tx) = task_event_tx {\n tx.send(PipelineEvent::DownloadStarted {\n target_id: job_id_in_task.clone(),\n url: display_url_for_event.clone(),\n }).ok();\n }\n\n // Create progress callback\n let progress_callback: Option = if let Some(ref tx) = task_event_tx {\n let tx_clone = tx.clone();\n let job_id_for_callback = job_id_in_task.clone();\n Some(Arc::new(move |bytes_so_far: u64, total_size: Option| {\n let _ = tx_clone.send(PipelineEvent::DownloadProgressUpdate {\n target_id: job_id_for_callback.clone(),\n bytes_so_far,\n total_size,\n });\n }))\n } else {\n None\n };\n\n let actual_download_result: Result<(PathBuf, bool), SpsError> =\n match ¤t_planned_job_for_task.target_definition {\n InstallTargetIdentifier::Formula(f) => {\n if current_planned_job_for_task.is_source_build {\n build::compile::download_source_with_progress(f, &task_config, progress_callback).await.map(|p| (p, false))\n } else {\n install::bottle::exec::download_bottle_with_progress_and_cache_info(\n f,\n &task_config,\n &task_http_client,\n progress_callback,\n )\n .await\n }\n }\n InstallTargetIdentifier::Cask(c) => {\n install::cask::download_cask_with_progress(c, task_cache.as_ref(), progress_callback).await.map(|p| (p, false))\n }\n };\n\n match actual_download_result {\n Ok((path, was_cached)) => {\n let size_bytes = fs::metadata(&path).map(|m| m.len()).unwrap_or(0);\n if let Some(ref tx) = task_event_tx {\n if was_cached {\n tx.send(PipelineEvent::DownloadCached {\n target_id: job_id_in_task.clone(),\n size_bytes,\n }).ok();\n } else {\n tx.send(PipelineEvent::DownloadFinished {\n target_id: job_id_in_task.clone(),\n path: path.clone(),\n size_bytes,\n }).ok();\n }\n }\n download_path_result = Ok(path);\n }\n Err(e) => {\n warn!(\n \"[DownloaderTask:{}] Download failed from {}: {}\",\n job_id_in_task, display_url_for_event, e\n );\n if let Some(ref tx) = task_event_tx {\n tx.send(PipelineEvent::download_failed(\n job_id_in_task.clone(),\n display_url_for_event,\n &e,\n )).ok();\n }\n download_path_result = Err(e);\n }\n }\n }\n }\n\n let outcome = DownloadOutcome {\n planned_job: current_planned_job_for_task,\n result: download_path_result,\n };\n\n if let Err(send_err) = outcome_tx_clone.send(outcome).await {\n error!(\n \"[DownloaderTask:{}] CRITICAL: Failed to send download outcome to runner: {}. Job processing will likely stall.\",\n job_id_in_task, send_err\n );\n }\n });\n }\n\n while let Some(join_result) = download_tasks.join_next().await {\n if let Err(e) = join_result {\n let panic_msg = get_panic_message(e.into_panic());\n error!(\n \"[Downloader] A download task panicked: {}. This job's outcome was not sent.\",\n panic_msg\n );\n critical_spawn_errors.push((\n \"[UnknownDownloadTaskPanic]\".to_string(),\n SpsError::Generic(format!(\"A download task panicked: {panic_msg}\")),\n ));\n }\n }\n self.event_tx = None;\n critical_spawn_errors\n }\n}\n"], ["/sps/sps/src/cli/list.rs", "use std::sync::Arc;\n\nuse clap::Args;\nuse colored::Colorize;\nuse prettytable::{format, Cell, Row, Table};\nuse serde_json::Value;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::formulary::Formulary;\nuse sps_core::check::installed::{get_installed_packages, PackageType};\nuse sps_core::check::update::check_for_updates;\nuse sps_core::check::InstalledPackageInfo;\n\n#[derive(Args, Debug)]\npub struct List {\n /// Show only formulas\n #[arg(long = \"formula\")]\n pub formula_only: bool,\n /// Show only casks\n #[arg(long = \"cask\")]\n pub cask_only: bool,\n /// Show only packages with updates available\n #[arg(long = \"outdated\")]\n pub outdated_only: bool,\n}\n\nimpl List {\n pub async fn run(&self, config: &Config, cache: Arc) -> Result<()> {\n let installed = get_installed_packages(config).await?;\n // Only show the latest version for each name\n use std::collections::HashMap;\n let mut formula_map: HashMap<&str, &sps_core::check::installed::InstalledPackageInfo> =\n HashMap::new();\n let mut cask_map: HashMap<&str, &sps_core::check::installed::InstalledPackageInfo> =\n HashMap::new();\n for pkg in &installed {\n match pkg.pkg_type {\n PackageType::Formula => {\n let entry = formula_map.entry(pkg.name.as_str()).or_insert(pkg);\n if pkg.version > entry.version {\n formula_map.insert(pkg.name.as_str(), pkg);\n }\n }\n PackageType::Cask => {\n let entry = cask_map.entry(pkg.name.as_str()).or_insert(pkg);\n if pkg.version > entry.version {\n cask_map.insert(pkg.name.as_str(), pkg);\n }\n }\n }\n }\n let mut formulas: Vec<&InstalledPackageInfo> = formula_map.values().copied().collect();\n let mut casks: Vec<&InstalledPackageInfo> = cask_map.values().copied().collect();\n // Sort formulas and casks alphabetically by name, then version\n formulas.sort_by(|a, b| a.name.cmp(&b.name).then(a.version.cmp(&b.version)));\n casks.sort_by(|a, b| a.name.cmp(&b.name).then(a.version.cmp(&b.version)));\n // If Nothing Installed.\n if formulas.is_empty() && casks.is_empty() {\n println!(\"{}\", \"0 formulas and casks installed\".yellow());\n return Ok(());\n }\n // If user wants to show installed formulas only.\n if self.formula_only {\n if self.outdated_only {\n self.print_outdated_formulas_table(&formulas, config)\n .await?;\n } else {\n self.print_formulas_table(formulas, config);\n }\n return Ok(());\n }\n // If user wants to show installed casks only.\n if self.cask_only {\n if self.outdated_only {\n self.print_outdated_casks_table(&casks, cache.clone())\n .await?;\n } else {\n self.print_casks_table(casks, cache);\n }\n return Ok(());\n }\n\n // If user wants to show only outdated packages\n if self.outdated_only {\n self.print_outdated_all_table(&formulas, &casks, config, cache)\n .await?;\n return Ok(());\n }\n\n // Default Implementation\n let formulary = Formulary::new(config.clone());\n let mut table = Table::new();\n table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n table.add_row(Row::new(vec![\n Cell::new(\"Type\").style_spec(\"b\"),\n Cell::new(\"Name\").style_spec(\"b\"),\n Cell::new(\"Installed\").style_spec(\"b\"),\n Cell::new(\"New Version?\").style_spec(\"b\"),\n ]));\n let mut formula_count = 0;\n let mut cask_count = 0;\n for pkg in formulas {\n let latest = formulary.load_formula(&pkg.name).ok();\n let (has_new, _) = match latest {\n Some(ref f) => {\n let latest_version = f.version_str_full();\n (latest_version != pkg.version, latest_version)\n }\n None => (false, \"-\".to_string()),\n };\n table.add_row(Row::new(vec![\n Cell::new(\"Formula\").style_spec(\"Fg\"),\n Cell::new(&pkg.name).style_spec(\"Fb\"),\n Cell::new(&pkg.version),\n // TODO: update to display the latest version string.\n // TODO: Not showing when the using --all flag.\n Cell::new(if has_new { \"✔\" } else { \"\" }),\n ]));\n formula_count += 1;\n }\n for pkg in casks {\n // Try to load cask info from cache\n let cask_val = cache.load_raw(\"cask.json\").ok().and_then(|raw| {\n serde_json::from_str::>(&raw)\n .ok()?\n .into_iter()\n .find(|v| v.get(\"token\").and_then(|t| t.as_str()) == Some(&pkg.name))\n });\n let (has_new, _) = match cask_val {\n Some(ref v) => {\n let latest_version = v.get(\"version\").and_then(|v| v.as_str()).unwrap_or(\"-\");\n (latest_version != pkg.version, latest_version.to_string())\n }\n None => (false, \"-\".to_string()),\n };\n table.add_row(Row::new(vec![\n Cell::new(\"Cask\").style_spec(\"Fy\"),\n Cell::new(&pkg.name).style_spec(\"Fb\"),\n Cell::new(&pkg.version),\n Cell::new(if has_new { \"✔\" } else { \"\" }),\n ]));\n cask_count += 1;\n }\n table.printstd();\n if formula_count > 0 && cask_count > 0 {\n println!(\n \"{}\",\n format!(\"{formula_count} formulas, {cask_count} casks installed\").bold()\n );\n } else if formula_count > 0 {\n println!(\"{}\", format!(\"{formula_count} formulas installed\").bold());\n } else if cask_count > 0 {\n println!(\"{}\", format!(\"{cask_count} casks installed\").bold());\n }\n Ok(())\n }\n\n fn print_formulas_table(\n &self,\n formulas: Vec<&sps_core::check::installed::InstalledPackageInfo>,\n config: &Config,\n ) {\n if formulas.is_empty() {\n println!(\"No formulas installed.\");\n return;\n }\n let formulary = Formulary::new(config.clone());\n let mut table = Table::new();\n table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n // Add header row with \"Formulas\" spanning all columns, font color green\n table.add_row(Row::new(vec![Cell::new_align(\n \"Formulas\",\n format::Alignment::CENTER,\n )\n .style_spec(\"bFg\")\n .with_hspan(3)]));\n table.add_row(Row::new(vec![\n Cell::new(\"Name\").style_spec(\"b\"),\n Cell::new(\"Installed\").style_spec(\"b\"),\n Cell::new(\"New Version?\").style_spec(\"b\"),\n ]));\n let mut formula_count = 0;\n for pkg in formulas {\n let latest = formulary.load_formula(&pkg.name).ok();\n let (has_new, _) = match latest {\n Some(ref f) => {\n let latest_version = f.version_str_full();\n (latest_version != pkg.version, latest_version)\n }\n None => (false, \"-\".to_string()),\n };\n table.add_row(Row::new(vec![\n Cell::new(&pkg.name).style_spec(\"Fb\"),\n Cell::new(&pkg.version),\n Cell::new(if has_new { \"✔\" } else { \"\" }),\n ]));\n formula_count += 1;\n }\n table.printstd();\n println!(\"{}\", format!(\"{formula_count} formulas installed\").bold());\n }\n\n fn print_casks_table(\n &self,\n casks: Vec<&sps_core::check::installed::InstalledPackageInfo>,\n cache: Arc,\n ) {\n if casks.is_empty() {\n println!(\"No casks installed.\");\n return;\n }\n let mut table = Table::new();\n table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n // Add header row with \"Casks\" spanning all columns, font color green\n table.add_row(Row::new(vec![Cell::new_align(\n \"Casks\",\n format::Alignment::CENTER,\n )\n .style_spec(\"bFg\")\n .with_hspan(3)]));\n table.add_row(Row::new(vec![\n Cell::new(\"Name\").style_spec(\"b\"),\n Cell::new(\"Installed\").style_spec(\"b\"),\n Cell::new(\"New Version?\").style_spec(\"b\"),\n ]));\n let mut cask_count = 0;\n for pkg in casks {\n // Try to load cask info from cache\n let cask_val = cache.load_raw(\"cask.json\").ok().and_then(|raw| {\n serde_json::from_str::>(&raw)\n .ok()?\n .into_iter()\n .find(|v| v.get(\"token\").and_then(|t| t.as_str()) == Some(&pkg.name))\n });\n let (has_new, _) = match cask_val {\n Some(ref v) => {\n let latest_version = v.get(\"version\").and_then(|v| v.as_str()).unwrap_or(\"-\");\n (latest_version != pkg.version, latest_version.to_string())\n }\n None => (false, \"-\".to_string()),\n };\n table.add_row(Row::new(vec![\n Cell::new(&pkg.name).style_spec(\"Fb\"),\n Cell::new(&pkg.version),\n Cell::new(if has_new { \"✔\" } else { \"\" }),\n ]));\n cask_count += 1;\n }\n table.printstd();\n println!(\"{}\", format!(\"{cask_count} casks installed\").bold());\n }\n\n async fn print_outdated_formulas_table(\n &self,\n formulas: &[&InstalledPackageInfo],\n config: &Config,\n ) -> Result<()> {\n if formulas.is_empty() {\n println!(\"No formulas installed.\");\n return Ok(());\n }\n\n // Convert to owned for update checking\n let formula_packages: Vec =\n formulas.iter().map(|&f| f.clone()).collect();\n let cache = sps_common::cache::Cache::new(config)?;\n let updates = check_for_updates(&formula_packages, &cache, config).await?;\n\n if updates.is_empty() {\n println!(\"No formula updates available.\");\n return Ok(());\n }\n\n let mut table = Table::new();\n table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n table.add_row(Row::new(vec![Cell::new_align(\n \"Outdated Formulas\",\n format::Alignment::CENTER,\n )\n .style_spec(\"bFg\")\n .with_hspan(3)]));\n table.add_row(Row::new(vec![\n Cell::new(\"Name\").style_spec(\"b\"),\n Cell::new(\"Installed\").style_spec(\"b\"),\n Cell::new(\"Available\").style_spec(\"b\"),\n ]));\n\n let mut count = 0;\n for update in updates {\n table.add_row(Row::new(vec![\n Cell::new(&update.name).style_spec(\"Fb\"),\n Cell::new(&update.installed_version),\n Cell::new(&update.available_version).style_spec(\"Fg\"),\n ]));\n count += 1;\n }\n\n table.printstd();\n println!(\"{}\", format!(\"{count} outdated formulas\").bold());\n Ok(())\n }\n\n async fn print_outdated_casks_table(\n &self,\n casks: &[&InstalledPackageInfo],\n cache: Arc,\n ) -> Result<()> {\n if casks.is_empty() {\n println!(\"No casks installed.\");\n return Ok(());\n }\n\n // Convert to owned for update checking\n let cask_packages: Vec = casks.iter().map(|&c| c.clone()).collect();\n let config = cache.config();\n let updates = check_for_updates(&cask_packages, &cache, config).await?;\n\n if updates.is_empty() {\n println!(\"No cask updates available.\");\n return Ok(());\n }\n\n let mut table = Table::new();\n table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n table.add_row(Row::new(vec![Cell::new_align(\n \"Outdated Casks\",\n format::Alignment::CENTER,\n )\n .style_spec(\"bFg\")\n .with_hspan(3)]));\n table.add_row(Row::new(vec![\n Cell::new(\"Name\").style_spec(\"b\"),\n Cell::new(\"Installed\").style_spec(\"b\"),\n Cell::new(\"Available\").style_spec(\"b\"),\n ]));\n\n let mut count = 0;\n for update in updates {\n table.add_row(Row::new(vec![\n Cell::new(&update.name).style_spec(\"Fb\"),\n Cell::new(&update.installed_version),\n Cell::new(&update.available_version).style_spec(\"Fy\"),\n ]));\n count += 1;\n }\n\n table.printstd();\n println!(\"{}\", format!(\"{count} outdated casks\").bold());\n Ok(())\n }\n\n async fn print_outdated_all_table(\n &self,\n formulas: &[&InstalledPackageInfo],\n casks: &[&InstalledPackageInfo],\n config: &Config,\n cache: Arc,\n ) -> Result<()> {\n // Convert to owned for update checking\n let mut all_packages: Vec = Vec::new();\n all_packages.extend(formulas.iter().map(|&f| f.clone()));\n all_packages.extend(casks.iter().map(|&c| c.clone()));\n\n if all_packages.is_empty() {\n println!(\"{}\", \"0 formulas and casks installed\".yellow());\n return Ok(());\n }\n\n let updates = check_for_updates(&all_packages, &cache, config).await?;\n\n if updates.is_empty() {\n println!(\"No outdated packages found.\");\n return Ok(());\n }\n\n let mut table = Table::new();\n table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n table.add_row(Row::new(vec![\n Cell::new(\"Type\").style_spec(\"b\"),\n Cell::new(\"Name\").style_spec(\"b\"),\n Cell::new(\"Installed\").style_spec(\"b\"),\n Cell::new(\"Available\").style_spec(\"b\"),\n ]));\n\n let mut formula_count = 0;\n let mut cask_count = 0;\n\n for update in updates {\n let (type_name, type_style) = match update.pkg_type {\n PackageType::Formula => {\n formula_count += 1;\n (\"Formula\", \"Fg\")\n }\n PackageType::Cask => {\n cask_count += 1;\n (\"Cask\", \"Fy\")\n }\n };\n\n table.add_row(Row::new(vec![\n Cell::new(type_name).style_spec(type_style),\n Cell::new(&update.name).style_spec(\"Fb\"),\n Cell::new(&update.installed_version),\n Cell::new(&update.available_version).style_spec(\"Fg\"),\n ]));\n }\n\n table.printstd();\n if formula_count > 0 && cask_count > 0 {\n println!(\n \"{}\",\n format!(\"{formula_count} outdated formulas, {cask_count} outdated casks\").bold()\n );\n } else if formula_count > 0 {\n println!(\"{}\", format!(\"{formula_count} outdated formulas\").bold());\n } else if cask_count > 0 {\n println!(\"{}\", format!(\"{cask_count} outdated casks\").bold());\n }\n Ok(())\n }\n}\n"], ["/sps/sps/src/pipeline/runner.rs", "// sps/src/pipeline/runner.rs\nuse std::collections::{HashMap, HashSet};\nuse std::sync::atomic::{AtomicUsize, Ordering};\nuse std::sync::{Arc, Mutex};\nuse std::time::Instant;\n\nuse colored::Colorize;\nuse crossbeam_channel::bounded as crossbeam_bounded;\nuse reqwest::Client as HttpClient;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::dependency::resolver::{ResolutionStatus, ResolvedGraph};\nuse sps_common::error::{Result as SpsResult, SpsError};\nuse sps_common::model::InstallTargetIdentifier;\nuse sps_common::pipeline::{\n DownloadOutcome, JobProcessingState, PipelineEvent, PlannedJob,\n PlannedOperations as PlannerOutputCommon, WorkerJob,\n};\nuse tokio::sync::{broadcast, mpsc};\nuse tokio::task::JoinHandle;\nuse tracing::{debug, error, instrument, warn};\n\nuse super::downloader::DownloadCoordinator;\nuse super::planner::OperationPlanner;\n\nconst WORKER_JOB_CHANNEL_SIZE: usize = 100;\nconst EVENT_CHANNEL_SIZE: usize = 100;\nconst DOWNLOAD_OUTCOME_CHANNEL_SIZE: usize = 100;\n\n#[derive(Debug, Clone, PartialEq, Eq)]\npub enum CommandType {\n Install,\n Reinstall,\n Upgrade { all: bool },\n}\n\n#[derive(Debug, Clone)]\npub struct PipelineFlags {\n pub build_from_source: bool,\n pub include_optional: bool,\n pub skip_recommended: bool,\n}\n\nstruct PropagationContext {\n all_planned_jobs: Arc>,\n job_states: Arc>>,\n resolved_graph: Arc,\n event_tx: Option>,\n final_fail_count: Arc,\n}\n\nfn err_to_string(e: &SpsError) -> String {\n e.to_string()\n}\n\npub(crate) fn get_panic_message(e: Box) -> String {\n match e.downcast_ref::<&'static str>() {\n Some(s) => (*s).to_string(),\n None => match e.downcast_ref::() {\n Some(s) => s.clone(),\n None => \"Unknown panic payload\".to_string(),\n },\n }\n}\n\n#[instrument(skip_all, fields(cmd = ?command_type, targets = ?initial_targets))]\npub async fn run_pipeline(\n initial_targets: &[String],\n command_type: CommandType,\n config: &Config,\n cache: Arc,\n flags: &PipelineFlags,\n) -> SpsResult<()> {\n debug!(\n \"Pipeline run initiated for targets: {:?}, command: {:?}\",\n initial_targets, command_type\n );\n let start_time = Instant::now();\n let final_success_count = Arc::new(AtomicUsize::new(0));\n let final_fail_count = Arc::new(AtomicUsize::new(0));\n\n debug!(\n \"Creating broadcast channel for pipeline events (EVENT_CHANNEL_SIZE={})\",\n EVENT_CHANNEL_SIZE\n );\n let (event_tx, mut event_rx_for_runner) =\n broadcast::channel::(EVENT_CHANNEL_SIZE);\n\n debug!(\"Cloning event_tx for runner_event_tx_clone\");\n let runner_event_tx_clone = event_tx.clone();\n\n debug!(\n \"Creating crossbeam worker job channel (WORKER_JOB_CHANNEL_SIZE={})\",\n WORKER_JOB_CHANNEL_SIZE\n );\n let (worker_job_tx, worker_job_rx_for_core) =\n crossbeam_bounded::(WORKER_JOB_CHANNEL_SIZE);\n\n debug!(\"Cloning event_tx for core_event_tx_for_worker_manager\");\n let core_config = config.clone();\n let core_cache_clone = cache.clone();\n let core_event_tx_for_worker_manager = event_tx.clone();\n let core_success_count_clone = Arc::clone(&final_success_count);\n let core_fail_count_clone = Arc::clone(&final_fail_count);\n debug!(\"Spawning core worker pool manager thread.\");\n let core_handle = std::thread::spawn(move || {\n debug!(\"CORE_THREAD: Core worker pool manager thread started.\");\n let result = sps_core::pipeline::engine::start_worker_pool_manager(\n core_config,\n core_cache_clone,\n worker_job_rx_for_core,\n core_event_tx_for_worker_manager,\n core_success_count_clone,\n core_fail_count_clone,\n );\n debug!(\n \"CORE_THREAD: Core worker pool manager thread finished. Result: {:?}\",\n result.is_ok()\n );\n result\n });\n\n debug!(\"Subscribing to event_tx for status_event_rx\");\n let status_config = config.clone();\n let status_event_rx = event_tx.subscribe();\n debug!(\"Spawning status handler task.\");\n let status_handle = tokio::spawn(crate::cli::status::handle_events(\n status_config,\n status_event_rx,\n ));\n\n debug!(\n \"Creating mpsc download_outcome channel (DOWNLOAD_OUTCOME_CHANNEL_SIZE={})\",\n DOWNLOAD_OUTCOME_CHANNEL_SIZE\n );\n let (download_outcome_tx, mut download_outcome_rx) =\n mpsc::channel::(DOWNLOAD_OUTCOME_CHANNEL_SIZE);\n\n debug!(\"Initializing pipeline planning phase...\");\n let planner_output: PlannerOutputCommon;\n {\n debug!(\"Cloning runner_event_tx_clone for planner_event_tx_clone\");\n let planner_event_tx_clone = runner_event_tx_clone.clone();\n debug!(\"Creating OperationPlanner.\");\n let operation_planner =\n OperationPlanner::new(config, cache.clone(), flags, planner_event_tx_clone);\n\n debug!(\"Calling plan_operations...\");\n match operation_planner\n .plan_operations(initial_targets, command_type.clone())\n .await\n {\n Ok(ops) => {\n debug!(\"plan_operations returned Ok.\");\n planner_output = ops;\n }\n Err(e) => {\n error!(\"Fatal planning error: {}\", e);\n runner_event_tx_clone\n .send(PipelineEvent::LogError {\n message: format!(\"Fatal planning error: {e}\"),\n })\n .ok();\n drop(worker_job_tx);\n if let Err(join_err) = core_handle.join() {\n error!(\n \"Core thread join error after planning failure: {:?}\",\n get_panic_message(join_err)\n );\n }\n let duration = start_time.elapsed();\n runner_event_tx_clone\n .send(PipelineEvent::PipelineFinished {\n duration_secs: duration.as_secs_f64(),\n success_count: 0,\n fail_count: initial_targets.len(),\n })\n .ok();\n\n debug!(\"Dropping runner_event_tx_clone due to planning error.\");\n drop(runner_event_tx_clone);\n debug!(\"Dropping main event_tx due to planning error.\");\n drop(event_tx);\n\n debug!(\"Awaiting status_handle after planning error.\");\n if let Err(join_err) = status_handle.await {\n error!(\n \"Status task join error after planning failure: {}\",\n join_err\n );\n }\n return Err(e);\n }\n }\n debug!(\"OperationPlanner scope ended, planner_event_tx_clone dropped.\");\n }\n\n let planned_jobs = Arc::new(planner_output.jobs);\n let resolved_graph = planner_output.resolved_graph.clone()\n .unwrap_or_else(|| {\n tracing::debug!(\"ResolvedGraph was None in planner output. Using a default empty graph. This is expected if no formulae required resolution or if planner reported errors for all formulae.\");\n Arc::new(sps_common::dependency::resolver::ResolvedGraph::default())\n });\n\n debug!(\n \"Planning finished. Total jobs in plan: {}.\",\n planned_jobs.len()\n );\n runner_event_tx_clone\n .send(PipelineEvent::PlanningFinished {\n job_count: planned_jobs.len(),\n })\n .ok();\n\n // Mark jobs with planner errors as failed and emit error events\n let job_processing_states = Arc::new(Mutex::new(HashMap::::new()));\n let mut jobs_pending_or_active = 0;\n let mut initial_fail_count_from_planner = 0;\n {\n let mut states_guard = job_processing_states.lock().unwrap();\n if !planner_output.errors.is_empty() {\n tracing::debug!(\n \"[Runner] Planner reported {} error(s). These targets will be marked as failed.\",\n planner_output.errors.len()\n );\n for (target_name, error) in &planner_output.errors {\n let msg = format!(\"✗ {}: {}\", target_name.cyan(), error);\n runner_event_tx_clone\n .send(PipelineEvent::LogError { message: msg })\n .ok();\n states_guard.insert(\n target_name.clone(),\n JobProcessingState::Failed(Arc::new(error.clone())),\n );\n initial_fail_count_from_planner += 1;\n }\n }\n for job in planned_jobs.iter() {\n if states_guard.contains_key(&job.target_id) {\n continue;\n }\n if planner_output\n .already_installed_or_up_to_date\n .contains(&job.target_id)\n {\n states_guard.insert(job.target_id.clone(), JobProcessingState::Succeeded);\n final_success_count.fetch_add(1, Ordering::Relaxed);\n debug!(\n \"[{}] Marked as Succeeded (pre-existing/up-to-date).\",\n job.target_id\n );\n } else if let Some((_, err)) = planner_output\n .errors\n .iter()\n .find(|(name, _)| name == &job.target_id)\n {\n states_guard.insert(\n job.target_id.clone(),\n JobProcessingState::Failed(Arc::new(err.clone())),\n );\n // Counted in initial_fail_count_from_planner\n debug!(\n \"[{}] Marked as Failed (planning error: {}).\",\n job.target_id, err\n );\n } else if job.use_private_store_source.is_some() {\n let path = job.use_private_store_source.clone().unwrap();\n states_guard.insert(\n job.target_id.clone(),\n JobProcessingState::Downloaded(path.clone()),\n );\n jobs_pending_or_active += 1;\n debug!(\n \"[{}] Initial state: Downloaded (private store: {}). Active jobs: {}\",\n job.target_id,\n path.display(),\n jobs_pending_or_active\n );\n } else {\n states_guard.insert(job.target_id.clone(), JobProcessingState::PendingDownload);\n jobs_pending_or_active += 1;\n debug!(\n \"[{}] Initial state: PendingDownload. Active jobs: {}\",\n job.target_id, jobs_pending_or_active\n );\n }\n }\n }\n debug!(\n \"Initial job states populated. Jobs pending/active: {}\",\n jobs_pending_or_active\n );\n\n let mut downloads_to_initiate = Vec::new();\n {\n let states_guard = job_processing_states.lock().unwrap();\n for job in planned_jobs.iter() {\n if matches!(\n states_guard.get(&job.target_id),\n Some(JobProcessingState::PendingDownload)\n ) {\n downloads_to_initiate.push(job.clone());\n }\n }\n }\n\n let mut download_coordinator_task_handle: Option>> = None;\n\n if !downloads_to_initiate.is_empty() {\n debug!(\"Cloning runner_event_tx_clone for download_coordinator_event_tx_clone\");\n let download_coordinator_event_tx_clone = runner_event_tx_clone.clone();\n let http_client = Arc::new(HttpClient::new());\n let config_for_downloader_owned = config.clone();\n\n let mut download_coordinator = DownloadCoordinator::new(\n config_for_downloader_owned,\n cache.clone(),\n http_client,\n download_coordinator_event_tx_clone,\n );\n debug!(\n \"Starting download coordination for {} jobs...\",\n downloads_to_initiate.len()\n );\n debug!(\"Cloning download_outcome_tx for tx_for_download_task\");\n let tx_for_download_task = download_outcome_tx.clone();\n\n debug!(\"Spawning DownloadCoordinator task.\");\n download_coordinator_task_handle = Some(tokio::spawn(async move {\n debug!(\"DOWNLOAD_COORD_TASK: DownloadCoordinator task started.\");\n let result = download_coordinator\n .coordinate_downloads(downloads_to_initiate, tx_for_download_task)\n .await;\n debug!(\"DOWNLOAD_COORD_TASK: DownloadCoordinator task finished. coordinate_downloads returned.\");\n result\n }));\n } else if jobs_pending_or_active > 0 {\n debug!(\n \"No downloads to initiate, but {} jobs are pending. Triggering check_and_dispatch.\",\n jobs_pending_or_active\n );\n check_and_dispatch(\n planned_jobs.clone(),\n job_processing_states.clone(),\n resolved_graph.clone(),\n &worker_job_tx,\n runner_event_tx_clone.clone(),\n config,\n flags,\n );\n } else {\n debug!(\"No downloads to initiate and no jobs pending/active. Pipeline might be empty or all pre-satisfied/failed.\");\n }\n\n drop(download_outcome_tx);\n debug!(\"Dropped main MPSC download_outcome_tx (runner's original clone).\");\n\n if !planned_jobs.is_empty() {\n runner_event_tx_clone\n .send(PipelineEvent::PipelineStarted {\n total_jobs: planned_jobs.len(),\n })\n .ok();\n }\n\n let mut propagation_ctx = PropagationContext {\n all_planned_jobs: planned_jobs.clone(),\n job_states: job_processing_states.clone(),\n resolved_graph: resolved_graph.clone(),\n event_tx: Some(runner_event_tx_clone.clone()),\n final_fail_count: final_fail_count.clone(),\n };\n\n debug!(\n \"Entering main event loop. Jobs pending/active: {}\",\n jobs_pending_or_active\n );\n\n // Robust main loop: continue while there are jobs pending/active, or downloads, or jobs in\n // states that could be dispatched\n fn has_pending_dispatchable_jobs(\n states_guard: &std::sync::MutexGuard>,\n ) -> bool {\n states_guard.values().any(|state| {\n matches!(\n state,\n JobProcessingState::Downloaded(_) | JobProcessingState::WaitingForDependencies(_)\n )\n })\n }\n\n while jobs_pending_or_active > 0\n || has_pending_dispatchable_jobs(&job_processing_states.lock().unwrap())\n {\n tokio::select! {\n biased;\n Some(download_outcome) = download_outcome_rx.recv() => {\n debug!(\"Received DownloadOutcome for '{}'.\", download_outcome.planned_job.target_id);\n process_download_outcome(\n download_outcome,\n &propagation_ctx,\n &mut jobs_pending_or_active,\n );\n debug!(\"After process_download_outcome, jobs_pending_or_active: {}. Triggering check_and_dispatch.\", jobs_pending_or_active);\n check_and_dispatch(\n planned_jobs.clone(),\n job_processing_states.clone(),\n resolved_graph.clone(),\n &worker_job_tx,\n runner_event_tx_clone.clone(),\n config,\n flags,\n );\n }\n Ok(event) = event_rx_for_runner.recv() => {\n match event {\n PipelineEvent::JobSuccess { ref target_id, .. } => {\n debug!(\"Received JobSuccess for '{}'.\", target_id);\n process_core_worker_feedback(\n target_id.clone(),\n true,\n None,\n job_processing_states.clone(),\n &mut jobs_pending_or_active,\n );\n debug!(\"After JobSuccess for '{}', jobs_pending_or_active: {}. Triggering check_and_dispatch.\", target_id, jobs_pending_or_active);\n check_and_dispatch(\n planned_jobs.clone(),\n job_processing_states.clone(),\n resolved_graph.clone(),\n &worker_job_tx,\n runner_event_tx_clone.clone(),\n config,\n flags,\n );\n }\n PipelineEvent::JobFailed { ref target_id, ref error, ref action } => {\n debug!(\"Received JobFailed for '{}' (Action: {:?}, Error: {}).\", target_id, action, error);\n process_core_worker_feedback(\n target_id.clone(),\n false,\n Some(SpsError::Generic(error.clone())),\n job_processing_states.clone(),\n &mut jobs_pending_or_active,\n );\n debug!(\"After JobFailed for '{}', jobs_pending_or_active: {}. Triggering failure propagation.\", target_id, jobs_pending_or_active);\n propagate_failure(\n target_id,\n Arc::new(SpsError::Generic(format!(\"Core worker failed for {target_id}: {error}\"))),\n &propagation_ctx,\n &mut jobs_pending_or_active,\n );\n check_and_dispatch(\n planned_jobs.clone(),\n job_processing_states.clone(),\n resolved_graph.clone(),\n &worker_job_tx,\n runner_event_tx_clone.clone(),\n config,\n flags,\n );\n }\n _ => {}\n }\n }\n else => {\n debug!(\"Main select loop 'else' branch. jobs_pending_or_active = {}. download_outcome_rx or event_rx_for_runner might be closed.\", jobs_pending_or_active);\n if jobs_pending_or_active > 0 || has_pending_dispatchable_jobs(&job_processing_states.lock().unwrap()) {\n warn!(\"Exiting main loop prematurely but still have {} jobs pending/active or dispatchable. This might indicate a stall or logic error.\", jobs_pending_or_active);\n }\n break;\n }\n }\n debug!(\n \"End of select! loop iteration. Jobs pending/active: {}\",\n jobs_pending_or_active\n );\n }\n debug!(\n \"Main event loop finished. Final jobs_pending_or_active: {}\",\n jobs_pending_or_active\n );\n\n drop(download_outcome_rx);\n debug!(\"Dropped MPSC download_outcome_rx (runner's receiver).\");\n\n if let Some(handle) = download_coordinator_task_handle {\n debug!(\"Waiting for DownloadCoordinator task to complete...\");\n match handle.await {\n Ok(critical_download_errors) => {\n if !critical_download_errors.is_empty() {\n warn!(\n \"DownloadCoordinator task reported critical errors: {:?}\",\n critical_download_errors\n );\n final_fail_count.fetch_add(critical_download_errors.len(), Ordering::Relaxed);\n }\n debug!(\"DownloadCoordinator task completed.\");\n }\n Err(e) => {\n let panic_msg = get_panic_message(Box::new(e));\n error!(\n \"DownloadCoordinator task panicked or failed to join: {}\",\n panic_msg\n );\n final_fail_count.fetch_add(1, Ordering::Relaxed);\n }\n }\n } else {\n debug!(\"No DownloadCoordinator task was spawned or it was already handled.\");\n }\n debug!(\"DownloadCoordinator task processing finished (awaited or none).\");\n\n debug!(\"Closing worker job channel (signal to core workers).\");\n drop(worker_job_tx);\n debug!(\"Waiting for core worker pool to join...\");\n match core_handle.join() {\n Ok(Ok(())) => debug!(\"Core worker pool manager thread completed successfully.\"),\n Ok(Err(e)) => {\n error!(\"Core worker pool manager thread failed: {}\", e);\n final_fail_count.fetch_add(1, Ordering::Relaxed);\n }\n Err(e) => {\n error!(\n \"Core worker pool manager thread panicked: {:?}\",\n get_panic_message(e)\n );\n final_fail_count.fetch_add(1, Ordering::Relaxed);\n }\n }\n debug!(\"Core worker pool joined. core_event_tx_for_worker_manager (broadcast sender) dropped.\");\n\n let duration = start_time.elapsed();\n let success_total = final_success_count.load(Ordering::Relaxed);\n let fail_total = final_fail_count.load(Ordering::Relaxed) + initial_fail_count_from_planner;\n\n debug!(\n \"Pipeline processing finished. Success: {}, Fail: {}. Duration: {:.2}s. Sending PipelineFinished event.\",\n success_total, fail_total, duration.as_secs_f64()\n );\n if let Err(e) = runner_event_tx_clone.send(PipelineEvent::PipelineFinished {\n duration_secs: duration.as_secs_f64(),\n success_count: success_total,\n fail_count: fail_total,\n }) {\n warn!(\n \"Failed to send PipelineFinished event: {:?}. Status handler might not receive it.\",\n e\n );\n }\n\n // Explicitly drop the event_tx inside propagation_ctx before dropping the last senders.\n propagation_ctx.event_tx = None;\n\n debug!(\"Dropping runner_event_tx_clone (broadcast sender).\");\n drop(runner_event_tx_clone);\n // event_rx_for_runner (broadcast receiver) goes out of scope here and is dropped.\n\n debug!(\"Dropping main event_tx (final broadcast sender).\");\n drop(event_tx);\n\n debug!(\"All known broadcast senders dropped. About to await status_handle.\");\n if let Err(e) = status_handle.await {\n warn!(\"Status handler task failed or panicked: {}\", e);\n } else {\n debug!(\"Status handler task completed successfully.\");\n }\n debug!(\"run_pipeline function is ending.\");\n\n if fail_total == 0 {\n Ok(())\n } else {\n let mut accumulated_errors = Vec::new();\n for (name, err_obj) in planner_output.errors {\n accumulated_errors.push(format!(\"Planning for '{name}': {err_obj}\"));\n }\n let states_guard = job_processing_states.lock().unwrap();\n for job in planned_jobs.iter() {\n if let Some(JobProcessingState::Failed(err_arc)) = states_guard.get(&job.target_id) {\n let err_str = err_to_string(err_arc);\n let job_err_msg = format!(\"Processing '{}': {}\", job.target_id, err_str);\n if !accumulated_errors.contains(&job_err_msg) {\n accumulated_errors.push(job_err_msg);\n }\n }\n }\n drop(states_guard);\n\n let specific_error_msg = if accumulated_errors.is_empty() {\n \"No specific errors logged, check core worker logs.\".to_string()\n } else {\n accumulated_errors.join(\"; \")\n };\n\n // Error details are already sent via PipelineEvent::JobFailed events\n // and will be displayed in status.rs\n Err(SpsError::InstallError(format!(\n \"Operation failed with {fail_total} total failure(s). Details: [{specific_error_msg}] (Worker errors are included in total)\"\n )))\n }\n}\n\nfn process_download_outcome(\n outcome: DownloadOutcome,\n propagation_ctx: &PropagationContext,\n jobs_pending_or_active: &mut usize,\n) {\n let job_id = outcome.planned_job.target_id.clone();\n let mut states_guard = propagation_ctx.job_states.lock().unwrap();\n\n match states_guard.get(&job_id) {\n Some(JobProcessingState::Succeeded) | Some(JobProcessingState::Failed(_)) => {\n debug!(\n \"[{}] DownloadOutcome: Job already in terminal state {:?}. Ignoring outcome.\",\n job_id,\n states_guard.get(&job_id)\n );\n return;\n }\n _ => {}\n }\n\n match outcome.result {\n Ok(path) => {\n debug!(\n \"[{}] DownloadOutcome: Success. Path: {}. Updating state to Downloaded.\",\n job_id,\n path.display()\n );\n states_guard.insert(job_id.clone(), JobProcessingState::Downloaded(path));\n }\n Err(e) => {\n warn!(\n \"[{}] DownloadOutcome: Failed. Error: {}. Updating state to Failed.\",\n job_id, e\n );\n let error_arc = Arc::new(e);\n states_guard.insert(\n job_id.clone(),\n JobProcessingState::Failed(error_arc.clone()),\n );\n\n if let Some(ref tx) = propagation_ctx.event_tx {\n tx.send(PipelineEvent::job_failed(\n job_id.clone(),\n outcome.planned_job.action.clone(),\n &error_arc,\n ))\n .ok();\n }\n propagation_ctx\n .final_fail_count\n .fetch_add(1, Ordering::Relaxed);\n\n if *jobs_pending_or_active > 0 {\n *jobs_pending_or_active -= 1;\n debug!(\"[{}] DownloadOutcome: Decremented jobs_pending_or_active to {} due to download failure.\", job_id, *jobs_pending_or_active);\n } else {\n warn!(\"[{}] DownloadOutcome: jobs_pending_or_active is already 0, cannot decrement for download failure.\", job_id);\n }\n\n drop(states_guard);\n debug!(\"[{}] DownloadOutcome: Propagating failure.\", job_id);\n propagate_failure(&job_id, error_arc, propagation_ctx, jobs_pending_or_active);\n }\n }\n}\n\nfn process_core_worker_feedback(\n target_id: String,\n success: bool,\n error: Option,\n job_states: Arc>>,\n jobs_pending_or_active: &mut usize,\n) {\n let mut states_guard = job_states.lock().unwrap();\n\n match states_guard.get(&target_id) {\n Some(JobProcessingState::Succeeded) | Some(JobProcessingState::Failed(_)) => {\n debug!(\"[{}] CoreFeedback: Job already in terminal state {:?}. Ignoring active job count update.\", target_id, states_guard.get(&target_id));\n return;\n }\n _ => {}\n }\n\n if success {\n debug!(\n \"[{}] CoreFeedback: Success. Updating state to Succeeded.\",\n target_id\n );\n states_guard.insert(target_id.clone(), JobProcessingState::Succeeded);\n } else {\n let err_msg = error.as_ref().map_or_else(\n || \"Unknown core worker error\".to_string(),\n |e| e.to_string(),\n );\n debug!(\n \"[{}] CoreFeedback: Failed. Error: {}. Updating state to Failed.\",\n target_id, err_msg\n );\n let err_arc = Arc::new(\n error.unwrap_or_else(|| SpsError::Generic(\"Unknown core worker error\".into())),\n );\n states_guard.insert(target_id.clone(), JobProcessingState::Failed(err_arc));\n }\n\n if *jobs_pending_or_active > 0 {\n *jobs_pending_or_active -= 1;\n debug!(\n \"[{}] CoreFeedback: Decremented jobs_pending_or_active to {}.\",\n target_id, *jobs_pending_or_active\n );\n } else {\n warn!(\n \"[{}] CoreFeedback: jobs_pending_or_active is already 0, cannot decrement.\",\n target_id\n );\n }\n}\n\nfn check_and_dispatch(\n planned_jobs_arc: Arc>,\n job_states: Arc>>,\n resolved_graph: Arc,\n worker_job_tx: &crossbeam_channel::Sender,\n event_tx: broadcast::Sender,\n config: &Config,\n flags: &PipelineFlags,\n) {\n debug!(\"--- Enter check_and_dispatch ---\");\n let mut states_guard = job_states.lock().unwrap();\n let mut dispatched_this_round = 0;\n\n for planned_job in planned_jobs_arc.iter() {\n let job_id = &planned_job.target_id;\n debug!(\"[{}] CheckDispatch: Evaluating job.\", job_id);\n\n let (current_state_is_dispatchable, path_for_dispatch) = {\n match states_guard.get(job_id) {\n Some(JobProcessingState::Downloaded(ref path)) => {\n debug!(\"[{}] CheckDispatch: Current state is Downloaded.\", job_id);\n (true, Some(path.clone()))\n }\n Some(JobProcessingState::WaitingForDependencies(ref path)) => {\n debug!(\n \"[{}] CheckDispatch: Current state is WaitingForDependencies.\",\n job_id\n );\n (true, Some(path.clone()))\n }\n other_state => {\n debug!(\n \"[{}] CheckDispatch: Not in a dispatchable state. Current state: {:?}.\",\n job_id,\n other_state.map(|s| format!(\"{s:?}\"))\n );\n (false, None)\n }\n }\n };\n\n if current_state_is_dispatchable {\n let path = path_for_dispatch.unwrap();\n drop(states_guard);\n debug!(\n \"[{}] CheckDispatch: Calling are_dependencies_succeeded.\",\n job_id\n );\n let dependencies_succeeded = are_dependencies_succeeded(\n job_id,\n &planned_job.target_definition,\n job_states.clone(),\n &resolved_graph,\n config,\n flags,\n );\n states_guard = job_states.lock().unwrap();\n debug!(\n \"[{}] CheckDispatch: are_dependencies_succeeded returned: {}.\",\n job_id, dependencies_succeeded\n );\n\n let current_state_after_dep_check = states_guard.get(job_id).cloned();\n if !matches!(\n current_state_after_dep_check,\n Some(JobProcessingState::Downloaded(_))\n | Some(JobProcessingState::WaitingForDependencies(_))\n ) {\n debug!(\"[{}] CheckDispatch: State changed to {:?} while checking dependencies. Skipping dispatch.\", job_id, current_state_after_dep_check);\n continue;\n }\n\n if dependencies_succeeded {\n debug!(\n \"[{}] CheckDispatch: All dependencies satisfied. Dispatching to core worker.\",\n job_id\n );\n let worker_job = WorkerJob {\n request: planned_job.clone(),\n download_path: path.clone(),\n download_size_bytes: std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0),\n is_source_from_private_store: planned_job.use_private_store_source.is_some(),\n };\n if worker_job_tx.send(worker_job).is_ok() {\n states_guard.insert(\n job_id.clone(),\n JobProcessingState::DispatchedToCore(path.clone()),\n );\n event_tx\n .send(PipelineEvent::JobDispatchedToCore {\n target_id: job_id.clone(),\n })\n .ok();\n dispatched_this_round += 1;\n debug!(\"[{}] CheckDispatch: Successfully dispatched.\", job_id);\n } else {\n error!(\"[{}] CheckDispatch: Failed to send job to worker channel (channel closed?). Marking as failed.\", job_id);\n let err = Arc::new(SpsError::Generic(\"Worker channel closed\".to_string()));\n if !matches!(\n states_guard.get(job_id),\n Some(JobProcessingState::Failed(_))\n ) {\n states_guard\n .insert(job_id.clone(), JobProcessingState::Failed(err.clone()));\n event_tx\n .send(PipelineEvent::job_failed(\n job_id.clone(),\n planned_job.action.clone(),\n &err,\n ))\n .ok();\n }\n }\n } else if matches!(\n current_state_after_dep_check,\n Some(JobProcessingState::Downloaded(_))\n ) {\n debug!(\"[{}] CheckDispatch: Dependencies not met. Updating state to WaitingForDependencies.\", job_id);\n states_guard.insert(\n job_id.clone(),\n JobProcessingState::WaitingForDependencies(path.clone()),\n );\n } else {\n debug!(\n \"[{}] CheckDispatch: Dependencies not met. State remains {:?}.\",\n job_id, current_state_after_dep_check\n );\n }\n }\n }\n if dispatched_this_round > 0 {\n debug!(\n \"Dispatched {} jobs to core workers in this round.\",\n dispatched_this_round\n );\n }\n debug!(\"--- Exit check_and_dispatch ---\");\n}\n\nfn are_dependencies_succeeded(\n target_id: &str,\n target_def: &InstallTargetIdentifier,\n job_states_arc: Arc>>,\n resolved_graph: &ResolvedGraph,\n config: &Config,\n flags: &PipelineFlags,\n) -> bool {\n debug!(\"[{}] AreDepsSucceeded: Checking dependencies...\", target_id);\n let dependencies_to_check: Vec = match target_def {\n InstallTargetIdentifier::Formula(formula_arc) => {\n if let Some(resolved_dep_info) =\n resolved_graph.resolution_details.get(formula_arc.name())\n {\n let parent_strategy = resolved_dep_info.determined_install_strategy;\n let empty_actions = std::collections::HashMap::new();\n let context = sps_common::dependency::ResolutionContext {\n formulary: &sps_common::formulary::Formulary::new(config.clone()),\n keg_registry: &sps_common::keg::KegRegistry::new(config.clone()),\n sps_prefix: config.sps_root(),\n include_optional: flags.include_optional,\n include_test: false,\n skip_recommended: flags.skip_recommended,\n initial_target_preferences: &Default::default(),\n build_all_from_source: flags.build_from_source,\n cascade_source_preference_to_dependencies: true,\n has_bottle_for_current_platform:\n sps_core::install::bottle::has_bottle_for_current_platform,\n initial_target_actions: &empty_actions,\n };\n\n let deps: Vec = formula_arc\n .dependencies()\n .unwrap_or_default()\n .iter()\n .filter(|dep_edge| {\n context.should_process_dependency_edge(\n formula_arc,\n dep_edge.tags,\n parent_strategy,\n )\n })\n .map(|dep_edge| dep_edge.name.clone())\n .collect();\n debug!(\n \"[{}] AreDepsSucceeded: Formula dependencies to check: {:?}\",\n target_id, deps\n );\n deps\n } else {\n warn!(\"[{}] AreDepsSucceeded: Formula not found in ResolvedGraph. Assuming no dependencies.\", target_id);\n Vec::new()\n }\n }\n InstallTargetIdentifier::Cask(cask_arc) => {\n let deps = if let Some(deps_on) = &cask_arc.depends_on {\n deps_on.formula.clone()\n } else {\n Vec::new()\n };\n debug!(\n \"[{}] AreDepsSucceeded: Cask formula dependencies to check: {:?}\",\n target_id, deps\n );\n deps\n }\n };\n\n if dependencies_to_check.is_empty() {\n debug!(\n \"[{}] AreDepsSucceeded: No dependencies to check. Returning true.\",\n target_id\n );\n return true;\n }\n\n let states_guard = job_states_arc.lock().unwrap();\n for dep_name in &dependencies_to_check {\n match states_guard.get(dep_name) {\n Some(JobProcessingState::Succeeded) => {\n debug!(\n \"[{}] AreDepsSucceeded: Dependency '{}' is Succeeded.\",\n target_id, dep_name\n );\n }\n Some(JobProcessingState::Failed(err)) => {\n debug!(\n \"[{}] AreDepsSucceeded: Dependency '{}' is FAILED ({}). Returning false.\",\n target_id,\n dep_name,\n err_to_string(err)\n );\n return false;\n }\n None => {\n if let Some(resolved_dep_detail) = resolved_graph.resolution_details.get(dep_name) {\n if resolved_dep_detail.status == ResolutionStatus::Installed {\n debug!(\"[{}] AreDepsSucceeded: Dependency '{}' is already installed (from ResolvedGraph).\", target_id, dep_name);\n } else {\n debug!(\"[{}] AreDepsSucceeded: Dependency '{}' has no active state and not ResolvedGraph::Installed (is {:?}). Returning false.\", target_id, dep_name, resolved_dep_detail.status);\n return false;\n }\n } else {\n warn!(\"[{}] AreDepsSucceeded: Dependency '{}' not found in job_states OR ResolvedGraph. Assuming not met. Returning false.\", target_id, dep_name);\n return false;\n }\n }\n other_state => {\n debug!(\"[{}] AreDepsSucceeded: Dependency '{}' is not yet Succeeded. Current state: {:?}. Returning false.\", target_id, dep_name, other_state.map(|s| format!(\"{s:?}\")));\n return false;\n }\n }\n }\n debug!(\n \"[{}] AreDepsSucceeded: All dependencies Succeeded or were pre-installed. Returning true.\",\n target_id\n );\n true\n}\n\nfn propagate_failure(\n failed_job_id: &str,\n failure_reason: Arc,\n ctx: &PropagationContext,\n jobs_pending_or_active: &mut usize,\n) {\n debug!(\n \"[{}] PropagateFailure: Starting for reason: {}\",\n failed_job_id, failure_reason\n );\n let mut dependents_to_fail_queue = vec![failed_job_id.to_string()];\n let mut newly_failed_dependents = HashSet::new();\n\n {\n let mut states_guard = ctx.job_states.lock().unwrap();\n if !matches!(\n states_guard.get(failed_job_id),\n Some(JobProcessingState::Failed(_))\n ) {\n states_guard.insert(\n failed_job_id.to_string(),\n JobProcessingState::Failed(failure_reason.clone()),\n );\n }\n }\n\n let mut current_idx = 0;\n while current_idx < dependents_to_fail_queue.len() {\n let current_source_of_failure = dependents_to_fail_queue[current_idx].clone();\n current_idx += 1;\n\n for job_to_check in ctx.all_planned_jobs.iter() {\n if job_to_check.target_id == failed_job_id\n || newly_failed_dependents.contains(&job_to_check.target_id)\n {\n continue;\n }\n\n let is_dependent = match &job_to_check.target_definition {\n InstallTargetIdentifier::Formula(formula_arc) => ctx\n .resolved_graph\n .resolution_details\n .get(formula_arc.name())\n .is_some_and(|res_dep_info| {\n res_dep_info\n .formula\n .dependencies()\n .unwrap_or_default()\n .iter()\n .any(|d| d.name == current_source_of_failure)\n }),\n InstallTargetIdentifier::Cask(cask_arc) => {\n cask_arc.depends_on.as_ref().is_some_and(|deps| {\n deps.formula.contains(¤t_source_of_failure)\n || deps.cask.contains(¤t_source_of_failure)\n })\n }\n };\n\n if is_dependent {\n let mut states_guard = ctx.job_states.lock().unwrap();\n let current_state_of_dependent = states_guard.get(&job_to_check.target_id).cloned();\n\n if !matches!(\n current_state_of_dependent,\n Some(JobProcessingState::Succeeded) | Some(JobProcessingState::Failed(_))\n ) {\n let propagated_error = Arc::new(SpsError::DependencyError(format!(\n \"Dependency '{}' failed: {}\",\n current_source_of_failure,\n err_to_string(&failure_reason)\n )));\n states_guard.insert(\n job_to_check.target_id.clone(),\n JobProcessingState::Failed(propagated_error.clone()),\n );\n\n if newly_failed_dependents.insert(job_to_check.target_id.clone()) {\n dependents_to_fail_queue.push(job_to_check.target_id.clone());\n ctx.final_fail_count.fetch_add(1, Ordering::Relaxed);\n\n if *jobs_pending_or_active > 0 {\n *jobs_pending_or_active -= 1;\n debug!(\"[{}] PropagateFailure: Decremented jobs_pending_or_active to {} for propagated failure.\", job_to_check.target_id, *jobs_pending_or_active);\n } else {\n warn!(\"[{}] PropagateFailure: jobs_pending_or_active is already 0, cannot decrement for propagated failure.\", job_to_check.target_id);\n }\n\n if let Some(ref tx) = ctx.event_tx {\n tx.send(PipelineEvent::job_failed(\n job_to_check.target_id.clone(),\n job_to_check.action.clone(),\n &propagated_error,\n ))\n .ok();\n }\n debug!(\"[{}] PropagateFailure: Marked as FAILED due to propagated failure from '{}'.\", job_to_check.target_id, current_source_of_failure);\n }\n }\n drop(states_guard);\n }\n }\n }\n\n if !newly_failed_dependents.is_empty() {\n debug!(\n \"[{}] PropagateFailure: Finished. Newly failed dependents: {:?}\",\n failed_job_id, newly_failed_dependents\n );\n } else {\n debug!(\n \"[{}] PropagateFailure: Finished. No new dependents marked as failed.\",\n failed_job_id\n );\n }\n}\n"], ["/sps/sps-net/src/http.rs", "use std::fs;\nuse std::path::{Path, PathBuf};\nuse std::sync::Arc;\nuse std::time::Duration;\n\nuse futures::StreamExt;\nuse reqwest::header::{HeaderMap, ACCEPT, USER_AGENT};\nuse reqwest::{Client, StatusCode};\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::formula::ResourceSpec;\nuse tokio::fs::File as TokioFile;\nuse tokio::io::AsyncWriteExt;\nuse tracing::{debug, error};\n\nuse crate::validation::{validate_url, verify_checksum};\n\npub type ProgressCallback = Arc) + Send + Sync>;\n\nconst DOWNLOAD_TIMEOUT_SECS: u64 = 300;\nconst CONNECT_TIMEOUT_SECS: u64 = 30;\nconst USER_AGENT_STRING: &str = \"sps package manager (Rust; +https://github.com/alexykn/sp)\";\n\npub async fn fetch_formula_source_or_bottle(\n formula_name: &str,\n url: &str,\n sha256_expected: &str,\n mirrors: &[String],\n config: &Config,\n) -> Result {\n fetch_formula_source_or_bottle_with_progress(\n formula_name,\n url,\n sha256_expected,\n mirrors,\n config,\n None,\n )\n .await\n}\n\npub async fn fetch_formula_source_or_bottle_with_progress(\n formula_name: &str,\n url: &str,\n sha256_expected: &str,\n mirrors: &[String],\n config: &Config,\n progress_callback: Option,\n) -> Result {\n let filename = url\n .split('/')\n .next_back()\n .map(|s| s.to_string())\n .unwrap_or_else(|| format!(\"{formula_name}-download\"));\n let cache_path = config.cache_dir().join(&filename);\n\n tracing::debug!(\n \"Preparing to fetch main resource for '{}' from URL: {}\",\n formula_name,\n url\n );\n tracing::debug!(\"Target cache path: {}\", cache_path.display());\n tracing::debug!(\"Expected SHA256: {}\", sha256_expected);\n\n if cache_path.is_file() {\n tracing::debug!(\"File exists in cache: {}\", cache_path.display());\n if !sha256_expected.is_empty() {\n match verify_checksum(&cache_path, sha256_expected) {\n Ok(_) => {\n tracing::debug!(\"Using valid cached file: {}\", cache_path.display());\n return Ok(cache_path);\n }\n Err(e) => {\n debug!(\n \"Cached file checksum mismatch ({}): {}. Redownloading.\",\n cache_path.display(),\n e\n );\n if let Err(remove_err) = fs::remove_file(&cache_path) {\n debug!(\n \"Failed to remove corrupted cached file {}: {}\",\n cache_path.display(),\n remove_err\n );\n }\n }\n }\n } else {\n tracing::debug!(\n \"Using cached file (no checksum provided): {}\",\n cache_path.display()\n );\n return Ok(cache_path);\n }\n } else {\n tracing::debug!(\"File not found in cache.\");\n }\n\n fs::create_dir_all(config.cache_dir()).map_err(|e| {\n SpsError::IoError(format!(\n \"Failed to create cache directory {}: {}\",\n config.cache_dir().display(),\n e\n ))\n })?;\n // Validate primary URL\n validate_url(url)?;\n\n let client = build_http_client()?;\n\n let urls_to_try = std::iter::once(url).chain(mirrors.iter().map(|s| s.as_str()));\n let mut last_error: Option = None;\n\n for current_url in urls_to_try {\n // Validate mirror URL\n validate_url(current_url)?;\n tracing::debug!(\"Attempting download from: {}\", current_url);\n match download_and_verify(\n &client,\n current_url,\n &cache_path,\n sha256_expected,\n progress_callback.clone(),\n )\n .await\n {\n Ok(path) => {\n tracing::debug!(\"Successfully downloaded and verified: {}\", path.display());\n return Ok(path);\n }\n Err(e) => {\n error!(\"Download attempt failed from {}: {}\", current_url, e);\n last_error = Some(e);\n }\n }\n }\n\n Err(last_error.unwrap_or_else(|| {\n SpsError::DownloadError(\n formula_name.to_string(),\n url.to_string(),\n \"All download attempts failed.\".to_string(),\n )\n }))\n}\n\npub async fn fetch_resource(\n formula_name: &str,\n resource: &ResourceSpec,\n config: &Config,\n) -> Result {\n fetch_resource_with_progress(formula_name, resource, config, None).await\n}\n\npub async fn fetch_resource_with_progress(\n formula_name: &str,\n resource: &ResourceSpec,\n config: &Config,\n progress_callback: Option,\n) -> Result {\n let resource_cache_dir = config.cache_dir().join(\"resources\");\n fs::create_dir_all(&resource_cache_dir).map_err(|e| {\n SpsError::IoError(format!(\n \"Failed to create resource cache directory {}: {}\",\n resource_cache_dir.display(),\n e\n ))\n })?;\n // Validate resource URL\n validate_url(&resource.url)?;\n\n let url_filename = resource\n .url\n .split('/')\n .next_back()\n .map(|s| s.to_string())\n .unwrap_or_else(|| format!(\"{}-download\", resource.name));\n let cache_filename = format!(\"{}-{}\", resource.name, url_filename);\n let cache_path = resource_cache_dir.join(&cache_filename);\n\n tracing::debug!(\n \"Preparing to fetch resource '{}' for formula '{}' from URL: {}\",\n resource.name,\n formula_name,\n resource.url\n );\n tracing::debug!(\"Target resource cache path: {}\", cache_path.display());\n tracing::debug!(\"Expected SHA256: {}\", resource.sha256);\n\n if cache_path.is_file() {\n tracing::debug!(\"Resource exists in cache: {}\", cache_path.display());\n match verify_checksum(&cache_path, &resource.sha256) {\n Ok(_) => {\n tracing::debug!(\"Using cached resource: {}\", cache_path.display());\n return Ok(cache_path);\n }\n Err(e) => {\n debug!(\n \"Cached resource checksum mismatch ({}): {}. Redownloading.\",\n cache_path.display(),\n e\n );\n if let Err(remove_err) = fs::remove_file(&cache_path) {\n debug!(\n \"Failed to remove corrupted cached resource file {}: {}\",\n cache_path.display(),\n remove_err\n );\n }\n }\n }\n } else {\n tracing::debug!(\"Resource not found in cache.\");\n }\n\n let client = build_http_client()?;\n match download_and_verify(\n &client,\n &resource.url,\n &cache_path,\n &resource.sha256,\n progress_callback,\n )\n .await\n {\n Ok(path) => {\n tracing::debug!(\n \"Successfully downloaded and verified resource: {}\",\n path.display()\n );\n Ok(path)\n }\n Err(e) => {\n error!(\"Resource download failed from {}: {}\", resource.url, e);\n let _ = fs::remove_file(&cache_path);\n Err(SpsError::DownloadError(\n resource.name.clone(),\n resource.url.clone(),\n format!(\"Download failed: {e}\"),\n ))\n }\n }\n}\n\nfn build_http_client() -> Result {\n let mut headers = HeaderMap::new();\n headers.insert(USER_AGENT, USER_AGENT_STRING.parse().unwrap());\n headers.insert(ACCEPT, \"*/*\".parse().unwrap());\n Client::builder()\n .timeout(Duration::from_secs(DOWNLOAD_TIMEOUT_SECS))\n .connect_timeout(Duration::from_secs(CONNECT_TIMEOUT_SECS))\n .default_headers(headers)\n .redirect(reqwest::redirect::Policy::limited(10))\n .build()\n .map_err(|e| SpsError::HttpError(format!(\"Failed to build HTTP client: {e}\")))\n}\n\nasync fn download_and_verify(\n client: &Client,\n url: &str,\n final_path: &Path,\n sha256_expected: &str,\n progress_callback: Option,\n) -> Result {\n let temp_filename = format!(\n \".{}.download\",\n final_path.file_name().unwrap_or_default().to_string_lossy()\n );\n let temp_path = final_path.with_file_name(temp_filename);\n tracing::debug!(\"Downloading to temporary path: {}\", temp_path.display());\n if temp_path.exists() {\n if let Err(e) = fs::remove_file(&temp_path) {\n tracing::warn!(\n \"Could not remove existing temporary file {}: {}\",\n temp_path.display(),\n e\n );\n }\n }\n\n let response = client.get(url).send().await.map_err(|e| {\n debug!(\"HTTP request failed for {url}: {e}\");\n SpsError::HttpError(format!(\"HTTP request failed for {url}: {e}\"))\n })?;\n let status = response.status();\n tracing::debug!(\"Received HTTP status: {} for {}\", status, url);\n\n if !status.is_success() {\n let body_text = response\n .text()\n .await\n .unwrap_or_else(|_| \"Failed to read response body\".to_string());\n tracing::error!(\"HTTP error {} for URL {}: {}\", status, url, body_text);\n return match status {\n StatusCode::NOT_FOUND => Err(SpsError::DownloadError(\n final_path\n .file_name()\n .map(|s| s.to_string_lossy().to_string())\n .unwrap_or_default(),\n url.to_string(),\n \"Resource not found (404)\".to_string(),\n )),\n StatusCode::FORBIDDEN => Err(SpsError::DownloadError(\n final_path\n .file_name()\n .map(|s| s.to_string_lossy().to_string())\n .unwrap_or_default(),\n url.to_string(),\n \"Access forbidden (403)\".to_string(),\n )),\n _ => Err(SpsError::HttpError(format!(\n \"HTTP error {status} for URL {url}: {body_text}\"\n ))),\n };\n }\n\n // Get total size from Content-Length header if available\n let total_size = response.content_length();\n\n let mut temp_file = TokioFile::create(&temp_path).await.map_err(|e| {\n SpsError::IoError(format!(\n \"Failed to create temp file {}: {}\",\n temp_path.display(),\n e\n ))\n })?;\n\n // Use bytes_stream() for chunked download with progress reporting\n let mut stream = response.bytes_stream();\n let mut bytes_downloaded = 0u64;\n\n while let Some(chunk) = stream.next().await {\n let chunk = chunk.map_err(|e| SpsError::HttpError(format!(\"Failed to read chunk: {e}\")))?;\n\n temp_file.write_all(&chunk).await.map_err(|e| {\n SpsError::IoError(format!(\n \"Failed to write chunk to {}: {}\",\n temp_path.display(),\n e\n ))\n })?;\n\n bytes_downloaded += chunk.len() as u64;\n\n // Call progress callback if provided\n if let Some(ref callback) = progress_callback {\n callback(bytes_downloaded, total_size);\n }\n }\n\n drop(temp_file);\n tracing::debug!(\"Finished writing download stream to temp file.\");\n\n if !sha256_expected.is_empty() {\n verify_checksum(&temp_path, sha256_expected)?;\n tracing::debug!(\n \"Checksum verified for temporary file: {}\",\n temp_path.display()\n );\n } else {\n tracing::warn!(\n \"Skipping checksum verification for {} - none provided.\",\n temp_path.display()\n );\n }\n\n fs::rename(&temp_path, final_path).map_err(|e| {\n SpsError::IoError(format!(\n \"Failed to move temp file {} to {}: {}\",\n temp_path.display(),\n final_path.display(),\n e\n ))\n })?;\n tracing::debug!(\n \"Moved verified file to final location: {}\",\n final_path.display()\n );\n Ok(final_path.to_path_buf())\n}\n"], ["/sps/sps/src/cli/search.rs", "use std::sync::Arc;\n\nuse clap::Args;\nuse colored::Colorize;\nuse prettytable::{format, Cell, Row, Table};\nuse serde_json::Value;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_net::api;\nuse terminal_size::{terminal_size, Width};\nuse unicode_width::{UnicodeWidthChar, UnicodeWidthStr};\n\n#[derive(Args, Debug)]\npub struct Search {\n pub query: String,\n #[arg(long, conflicts_with = \"cask\")]\n pub formula: bool,\n #[arg(long, conflicts_with = \"formula\")]\n pub cask: bool,\n}\n\npub enum SearchType {\n All,\n Formula,\n Cask,\n}\n\nimpl Search {\n pub async fn run(&self, config: &Config, cache: Arc) -> Result<()> {\n let search_type = if self.formula {\n SearchType::Formula\n } else if self.cask {\n SearchType::Cask\n } else {\n SearchType::All\n };\n run_search(&self.query, search_type, config, cache).await\n }\n}\n\npub async fn run_search(\n query: &str,\n search_type: SearchType,\n _config: &Config,\n cache: Arc,\n) -> Result<()> {\n tracing::debug!(\"Searching for packages matching: {}\", query);\n\n println!(\"Searching for \\\"{query}\\\"\");\n\n let mut formula_matches = Vec::new();\n let mut cask_matches = Vec::new();\n let mut formula_err = None;\n let mut cask_err = None;\n\n if matches!(search_type, SearchType::All | SearchType::Formula) {\n match search_formulas(Arc::clone(&cache), query).await {\n Ok(matches) => formula_matches = matches,\n Err(e) => {\n tracing::error!(\"Error searching formulas: {}\", e);\n formula_err = Some(e);\n }\n }\n }\n\n if matches!(search_type, SearchType::All | SearchType::Cask) {\n match search_casks(Arc::clone(&cache), query).await {\n Ok(matches) => cask_matches = matches,\n Err(e) => {\n tracing::error!(\"Error searching casks: {}\", e);\n cask_err = Some(e);\n }\n }\n }\n\n if formula_matches.is_empty() && cask_matches.is_empty() {\n if let Some(e) = formula_err.or(cask_err) {\n return Err(e);\n }\n }\n\n print_search_results(query, &formula_matches, &cask_matches);\n\n Ok(())\n}\n\nasync fn search_formulas(cache: Arc, query: &str) -> Result> {\n let query_lower = query.to_lowercase();\n let mut matches = Vec::new();\n let mut data_source_name = \"cache\";\n\n let formula_data_result = cache.load_raw(\"formula.json\");\n\n let formulas: Vec = match formula_data_result {\n Ok(formula_data) => serde_json::from_str(&formula_data)?,\n Err(e) => {\n tracing::debug!(\"Formula cache load failed ({}), fetching from API\", e);\n data_source_name = \"API\";\n let all_formulas = api::fetch_all_formulas().await?;\n\n if let Err(cache_err) = cache.store_raw(\"formula.json\", &all_formulas) {\n tracing::warn!(\"Failed to cache formula data after fetching: {}\", cache_err);\n }\n serde_json::from_str(&all_formulas)?\n }\n };\n\n for formula in formulas {\n if is_formula_match(&formula, &query_lower) {\n matches.push(formula);\n }\n }\n\n tracing::debug!(\n \"Found {} potential formula matches from {}\",\n matches.len(),\n data_source_name\n );\n tracing::debug!(\n \"Filtered down to {} formula matches with available bottles\",\n matches.len()\n );\n\n Ok(matches)\n}\n\nasync fn search_casks(cache: Arc, query: &str) -> Result> {\n let query_lower = query.to_lowercase();\n let mut matches = Vec::new();\n let mut data_source_name = \"cache\";\n\n let cask_data_result = cache.load_raw(\"cask.json\");\n\n let casks: Vec = match cask_data_result {\n Ok(cask_data) => serde_json::from_str(&cask_data)?,\n Err(e) => {\n tracing::debug!(\"Cask cache load failed ({}), fetching from API\", e);\n data_source_name = \"API\";\n let all_casks = api::fetch_all_casks().await?;\n\n if let Err(cache_err) = cache.store_raw(\"cask.json\", &all_casks) {\n tracing::warn!(\"Failed to cache cask data after fetching: {}\", cache_err);\n }\n serde_json::from_str(&all_casks)?\n }\n };\n\n for cask in casks {\n if is_cask_match(&cask, &query_lower) {\n matches.push(cask);\n }\n }\n tracing::debug!(\n \"Found {} cask matches from {}\",\n matches.len(),\n data_source_name\n );\n Ok(matches)\n}\n\nfn is_formula_match(formula: &Value, query: &str) -> bool {\n if let Some(name) = formula.get(\"name\").and_then(|n| n.as_str()) {\n if name.to_lowercase().contains(query) {\n return true;\n }\n }\n\n if let Some(full_name) = formula.get(\"full_name\").and_then(|n| n.as_str()) {\n if full_name.to_lowercase().contains(query) {\n return true;\n }\n }\n\n if let Some(desc) = formula.get(\"desc\").and_then(|d| d.as_str()) {\n if desc.to_lowercase().contains(query) {\n return true;\n }\n }\n\n if let Some(aliases) = formula.get(\"aliases\").and_then(|a| a.as_array()) {\n for alias in aliases {\n if let Some(alias_str) = alias.as_str() {\n if alias_str.to_lowercase().contains(query) {\n return true;\n }\n }\n }\n }\n\n false\n}\n\nfn is_cask_match(cask: &Value, query: &str) -> bool {\n if let Some(token) = cask.get(\"token\").and_then(|t| t.as_str()) {\n if token.to_lowercase().contains(query) {\n return true;\n }\n }\n\n if let Some(names) = cask.get(\"name\").and_then(|n| n.as_array()) {\n for name in names {\n if let Some(name_str) = name.as_str() {\n if name_str.to_lowercase().contains(query) {\n return true;\n }\n }\n }\n }\n\n if let Some(desc) = cask.get(\"desc\").and_then(|d| d.as_str()) {\n if desc.to_lowercase().contains(query) {\n return true;\n }\n }\n\n false\n}\n\nfn truncate_vis(s: &str, max: usize) -> String {\n if UnicodeWidthStr::width(s) <= max {\n return s.to_string();\n }\n let mut w = 0;\n let mut out = String::new();\n let effective_max = if max > 0 { max } else { 1 };\n\n for ch in s.chars() {\n let cw = UnicodeWidthChar::width(ch).unwrap_or(0);\n if w + cw >= effective_max.saturating_sub(1) {\n break;\n }\n out.push(ch);\n w += cw;\n }\n out.push('…');\n out\n}\n\npub fn print_search_results(query: &str, formula_matches: &[Value], cask_matches: &[Value]) {\n let total = formula_matches.len() + cask_matches.len();\n if total == 0 {\n println!(\"{}\", format!(\"No matches found for '{query}'\").yellow());\n return;\n }\n println!(\n \"{}\",\n format!(\"Found {total} result(s) for '{query}'\").bold()\n );\n\n let term_cols = terminal_size()\n .map(|(Width(w), _)| w as usize)\n .unwrap_or(120);\n\n let type_col = 7;\n let version_col = 10;\n let sep_width = 3 * 3;\n let total_fixed = type_col + version_col + sep_width;\n\n let name_min_width = 10;\n let desc_min_width = 20;\n\n let leftover = term_cols.saturating_sub(total_fixed);\n\n let name_prop_width = leftover / 3;\n\n let name_max = std::cmp::max(name_min_width, name_prop_width);\n let desc_max = std::cmp::max(desc_min_width, leftover.saturating_sub(name_max));\n\n let name_max = std::cmp::min(name_max, leftover.saturating_sub(desc_min_width));\n let desc_max = std::cmp::min(desc_max, leftover.saturating_sub(name_max));\n\n let mut tbl = Table::new();\n tbl.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n\n for formula in formula_matches {\n let raw_name = formula\n .get(\"name\")\n .and_then(|n| n.as_str())\n .unwrap_or(\"Unknown\");\n let raw_desc = formula.get(\"desc\").and_then(|d| d.as_str()).unwrap_or(\"\");\n let _name = truncate_vis(raw_name, name_max);\n let desc = truncate_vis(raw_desc, desc_max);\n\n let version = get_version(formula);\n\n tbl.add_row(Row::new(vec![\n Cell::new(\"Formula\").style_spec(\"Fg\"),\n Cell::new(&_name).style_spec(\"Fb\"),\n Cell::new(version),\n Cell::new(&desc),\n ]));\n }\n\n if !formula_matches.is_empty() && !cask_matches.is_empty() {\n tbl.add_row(Row::new(vec![Cell::new(\" \").with_hspan(4)]));\n }\n\n for cask in cask_matches {\n let raw_name = cask\n .get(\"token\")\n .and_then(|t| t.as_str())\n .unwrap_or(\"Unknown\");\n let raw_desc = cask.get(\"desc\").and_then(|d| d.as_str()).unwrap_or(\"\");\n let desc = truncate_vis(raw_desc, desc_max);\n\n let version = get_cask_version(cask);\n\n tbl.add_row(Row::new(vec![\n Cell::new(\"Cask\").style_spec(\"Fy\"),\n Cell::new(raw_name).style_spec(\"Fb\"),\n Cell::new(version),\n Cell::new(&desc),\n ]));\n }\n\n tbl.printstd();\n}\n\nfn get_version(formula: &Value) -> &str {\n formula\n .get(\"versions\")\n .and_then(|v| v.get(\"stable\"))\n .and_then(|v| v.as_str())\n .unwrap_or(\"-\")\n}\n\nfn get_cask_version(cask: &Value) -> &str {\n cask.get(\"version\").and_then(|v| v.as_str()).unwrap_or(\"-\")\n}\n"], ["/sps/sps/src/main.rs", "// sps/src/main.rs\nuse std::process::{self}; // StdCommand is used\nuse std::sync::Arc;\nuse std::time::{Duration, SystemTime};\nuse std::{env, fs};\n\nuse clap::Parser;\nuse colored::Colorize;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::error::{Result as spResult, SpsError};\nuse tracing::level_filters::LevelFilter;\nuse tracing::{debug, error, warn}; // Import all necessary tracing macros\nuse tracing_subscriber::fmt::writer::MakeWriterExt;\nuse tracing_subscriber::EnvFilter;\n\nmod cli;\nmod pipeline;\n// Correctly import InitArgs via the re-export in cli.rs or directly from its module\nuse cli::{CliArgs, Command, InitArgs};\n\n// Standalone function to handle the init command logic\nasync fn run_init_command(init_args: &InitArgs, verbose_level: u8) -> spResult<()> {\n let init_level_filter = match verbose_level {\n 0 => LevelFilter::INFO,\n 1 => LevelFilter::DEBUG,\n _ => LevelFilter::TRACE,\n };\n let _ = tracing_subscriber::fmt()\n .with_max_level(init_level_filter)\n .with_writer(std::io::stderr)\n .with_ansi(true)\n .without_time()\n .try_init();\n\n let initial_config_for_path = Config::load().map_err(|e| {\n // Handle error if even basic config loading fails for path determination\n SpsError::Config(format!(\n \"Could not determine sps_root for init (config load failed): {e}\"\n ))\n })?;\n\n // Create a minimal Config struct, primarily for sps_root() and derived paths.\n let temp_config_for_init = Config {\n sps_root: initial_config_for_path.sps_root().to_path_buf(),\n api_base_url: \"https://formulae.brew.sh/api\".to_string(),\n artifact_domain: None,\n docker_registry_token: None,\n docker_registry_basic_auth: None,\n github_api_token: None,\n };\n\n init_args.run(&temp_config_for_init).await\n}\n\n#[tokio::main]\nasync fn main() -> spResult<()> {\n let cli_args = CliArgs::parse();\n\n if let Command::Init(ref init_args_ref) = cli_args.command {\n match run_init_command(init_args_ref, cli_args.verbose).await {\n Ok(_) => {\n return Ok(());\n }\n Err(e) => {\n eprintln!(\"{}: Init command failed: {:#}\", \"Error\".red().bold(), e);\n process::exit(1);\n }\n }\n }\n\n let config = Config::load().map_err(|e| {\n SpsError::Config(format!(\n \"Could not load config (have you run 'sps init'?): {e}\"\n ))\n })?;\n\n let level_filter = match cli_args.verbose {\n 0 => LevelFilter::INFO,\n 1 => LevelFilter::DEBUG,\n _ => LevelFilter::TRACE,\n };\n let max_log_level = level_filter.into_level().unwrap_or(tracing::Level::INFO);\n\n let env_filter = EnvFilter::builder()\n .with_default_directive(level_filter.into())\n .with_env_var(\"SPS_LOG\")\n .from_env_lossy();\n\n let log_dir = config.logs_dir();\n if let Err(e) = fs::create_dir_all(&log_dir) {\n eprintln!(\n \"{} Failed to create log directory {}: {} (ensure 'sps init' was successful or try with sudo for the current command if appropriate)\",\n \"Error:\".red().bold(),\n log_dir.display(),\n e\n );\n let _ = tracing_subscriber::fmt() // Use `let _ =`\n .with_env_filter(env_filter)\n .with_writer(std::io::stderr)\n .with_ansi(true)\n .without_time()\n .try_init(); // Use try_init\n } else if cli_args.verbose > 0 {\n let file_appender = tracing_appender::rolling::daily(&log_dir, \"sps.log\");\n let (non_blocking_appender, guard) = tracing_appender::non_blocking(file_appender);\n\n // For verbose mode, show debug/trace logs on stderr too\n let stderr_writer = std::io::stderr.with_max_level(max_log_level);\n let file_writer = non_blocking_appender.with_max_level(max_log_level);\n\n let _ = tracing_subscriber::fmt() // Use `let _ =`\n .with_env_filter(env_filter)\n .with_writer(stderr_writer.and(file_writer))\n .with_ansi(true)\n .without_time()\n .try_init(); // Use try_init\n\n Box::leak(Box::new(guard)); // Keep guard alive\n\n tracing::debug!(\n // This will only work if try_init above was successful for this setup\n \"Verbose logging enabled. Writing logs to: {}/sps.log\",\n log_dir.display()\n );\n } else {\n let _ = tracing_subscriber::fmt() // Use `let _ =`\n .with_env_filter(env_filter)\n .with_writer(std::io::stderr)\n .with_ansi(true)\n .without_time()\n .try_init(); // Use try_init\n }\n\n let cache = Arc::new(Cache::new(&config).map_err(|e| {\n SpsError::Cache(format!(\n \"Could not initialize cache (ensure 'sps init' was successful): {e}\"\n ))\n })?);\n\n let needs_update_check = matches!(\n cli_args.command,\n Command::Install(_) | Command::Search { .. } | Command::Info { .. } | Command::Upgrade(_)\n );\n\n if needs_update_check {\n if let Err(e) = check_and_run_auto_update(&config, Arc::clone(&cache)).await {\n error!(\"Error during auto-update check: {}\", e); // Use `error!` macro\n }\n } else {\n debug!(\n // Use `debug!` macro\n \"Skipping auto-update check for command: {:?}\",\n cli_args.command\n );\n }\n\n // Pass config and cache to the command's run method\n let command_execution_result = match &cli_args.command {\n Command::Init(_) => {\n /* This case is handled above and main exits */\n unreachable!()\n }\n _ => cli_args.command.run(&config, cache).await,\n };\n\n if let Err(e) = command_execution_result {\n // For pipeline commands (Install, Reinstall, Upgrade), errors are already\n // displayed via the status system, so only log in verbose mode\n let is_pipeline_command = matches!(\n cli_args.command,\n Command::Install(_) | Command::Reinstall(_) | Command::Upgrade(_)\n );\n\n if is_pipeline_command {\n // Only show error details in verbose mode\n if cli_args.verbose > 0 {\n error!(\"Command failed: {:#}\", e);\n eprintln!(\"{}: {:#}\", \"Error\".red().bold(), e);\n }\n } else {\n // For non-pipeline commands, show errors normally\n error!(\"Command failed: {:#}\", e);\n eprintln!(\"{}: {:#}\", \"Error\".red().bold(), e);\n }\n process::exit(1);\n }\n\n debug!(\"Command completed successfully.\"); // Use `debug!` macro\n Ok(())\n}\n\nasync fn check_and_run_auto_update(config: &Config, cache: Arc) -> spResult<()> {\n if env::var(\"SPS_NO_AUTO_UPDATE\").is_ok_and(|v| v == \"1\") {\n debug!(\"Auto-update disabled via SPS_NO_AUTO_UPDATE=1.\");\n return Ok(());\n }\n\n let default_interval_secs: u64 = 86400;\n let update_interval_secs = env::var(\"SPS_AUTO_UPDATE_SECS\")\n .ok()\n .and_then(|s| s.parse::().ok())\n .unwrap_or(default_interval_secs);\n let update_interval = Duration::from_secs(update_interval_secs);\n debug!(\"Auto-update interval: {:?}\", update_interval);\n\n let timestamp_file = config.state_dir().join(\".sps_last_update_check\");\n debug!(\"Checking timestamp file: {}\", timestamp_file.display());\n\n if let Some(parent_dir) = timestamp_file.parent() {\n if !parent_dir.exists() {\n if let Err(e) = fs::create_dir_all(parent_dir) {\n warn!(\"Could not create state directory {} as user: {}. Auto-update might rely on 'sps init' to create this with sudo.\", parent_dir.display(), e);\n }\n }\n }\n\n let mut needs_update = true;\n if timestamp_file.exists() {\n if let Ok(metadata) = fs::metadata(×tamp_file) {\n if let Ok(modified_time) = metadata.modified() {\n match SystemTime::now().duration_since(modified_time) {\n Ok(age) => {\n debug!(\"Time since last update check: {:?}\", age);\n if age < update_interval {\n needs_update = false;\n debug!(\"Auto-update interval not yet passed.\");\n } else {\n debug!(\"Auto-update interval passed.\");\n }\n }\n Err(e) => {\n warn!(\n \"Could not get duration since last update check (system time error?): {}\",\n e\n );\n }\n }\n } else {\n warn!(\n \"Could not read modification time for timestamp file: {}\",\n timestamp_file.display()\n );\n }\n } else {\n debug!(\n \"Timestamp file {} metadata could not be read. Update needed.\",\n timestamp_file.display()\n );\n }\n } else {\n debug!(\n \"Timestamp file not found at {}. Update needed.\",\n timestamp_file.display()\n );\n }\n\n if needs_update {\n println!(\n \"{}{}\",\n \"==> \".bold().blue(),\n \"Running auto-update...\".bold()\n );\n match cli::update::Update.run(config, cache).await {\n Ok(_) => {\n println!(\n \"{}{}\",\n \"==> \".bold().blue(),\n \"Auto-update successful.\".bold()\n );\n match fs::File::create(×tamp_file) {\n Ok(_) => {\n debug!(\"Updated timestamp file: {}\", timestamp_file.display());\n }\n Err(e) => {\n warn!(\n \"Failed to create or update timestamp file '{}': {}\",\n timestamp_file.display(),\n e\n );\n }\n }\n }\n Err(e) => {\n error!(\"Auto-update failed: {}\", e);\n eprintln!(\"{} Auto-update failed: {}\", \"Warning:\".yellow(), e);\n }\n }\n } else {\n debug!(\"Skipping auto-update.\");\n }\n\n Ok(())\n}\n"], ["/sps/sps-core/src/install/cask/dmg.rs", "// In sps-core/src/build/cask/dmg.rs\n\nuse std::fs;\nuse std::io::{BufRead, BufReader};\nuse std::path::{Path, PathBuf};\nuse std::process::Command;\n\nuse sps_common::error::{Result, SpsError};\nuse tracing::{debug, error}; // Added log imports\n\n// --- Keep Existing Helpers ---\npub fn mount_dmg(dmg_path: &Path) -> Result {\n debug!(\"Mounting DMG: {}\", dmg_path.display());\n let output = Command::new(\"hdiutil\")\n .arg(\"attach\")\n .arg(\"-plist\")\n .arg(\"-nobrowse\")\n .arg(\"-readonly\")\n .arg(\"-mountrandom\")\n .arg(\"/tmp\") // Consider making mount location configurable or more robust\n .arg(dmg_path)\n .output()?;\n\n if !output.status.success() {\n let stderr = String::from_utf8_lossy(&output.stderr);\n error!(\n \"hdiutil attach failed for {}: {}\",\n dmg_path.display(),\n stderr\n );\n return Err(SpsError::Generic(format!(\n \"Failed to mount DMG '{}': {}\",\n dmg_path.display(),\n stderr\n )));\n }\n\n let mount_point = parse_mount_point(&output.stdout)?;\n debug!(\"DMG mounted at: {}\", mount_point.display());\n Ok(mount_point)\n}\n\npub fn unmount_dmg(mount_point: &Path) -> Result<()> {\n debug!(\"Unmounting DMG from: {}\", mount_point.display());\n // Add logging for commands\n debug!(\"Executing: hdiutil detach -force {}\", mount_point.display());\n let output = Command::new(\"hdiutil\")\n .arg(\"detach\")\n .arg(\"-force\")\n .arg(mount_point)\n .output()?;\n\n if !output.status.success() {\n let stderr = String::from_utf8_lossy(&output.stderr);\n debug!(\n \"hdiutil detach failed ({}): {}. Trying diskutil\",\n output.status, stderr\n );\n // Add logging for fallback\n debug!(\n \"Executing: diskutil unmount force {}\",\n mount_point.display()\n );\n let diskutil_output = Command::new(\"diskutil\")\n .arg(\"unmount\")\n .arg(\"force\")\n .arg(mount_point)\n .output()?;\n\n if !diskutil_output.status.success() {\n let diskutil_stderr = String::from_utf8_lossy(&diskutil_output.stderr);\n error!(\n \"diskutil unmount force failed ({}): {}\",\n diskutil_output.status, diskutil_stderr\n );\n // Consider returning error only if both fail? Or always error on diskutil fail?\n return Err(SpsError::Generic(format!(\n \"Failed to unmount DMG '{}' using hdiutil and diskutil: {}\",\n mount_point.display(),\n diskutil_stderr\n )));\n }\n }\n debug!(\"DMG successfully unmounted\");\n Ok(())\n}\n\nfn parse_mount_point(output: &[u8]) -> Result {\n // ... (existing implementation) ...\n // Use plist crate for more robust parsing if possible in the future\n let cursor = std::io::Cursor::new(output);\n let reader = BufReader::new(cursor);\n let mut in_sys_entities = false;\n let mut in_mount_point = false;\n let mut mount_path_str: Option = None;\n\n for line_res in reader.lines() {\n let line = line_res?;\n let trimmed = line.trim();\n\n if trimmed == \"system-entities\" {\n in_sys_entities = true;\n continue;\n }\n if !in_sys_entities {\n continue;\n }\n\n if trimmed == \"mount-point\" {\n in_mount_point = true;\n continue;\n }\n\n if in_mount_point && trimmed.starts_with(\"\") && trimmed.ends_with(\"\") {\n mount_path_str = Some(\n trimmed\n .trim_start_matches(\"\")\n .trim_end_matches(\"\")\n .to_string(),\n );\n break; // Found the first mount point, assume it's the main one\n }\n\n // Reset flags if we encounter closing tags for structures containing mount-point\n if trimmed == \"\" {\n in_mount_point = false;\n }\n if trimmed == \"\" && in_sys_entities {\n // End of system-entities\n // break; // Stop searching if we leave the system-entities array\n in_sys_entities = false; // Reset this flag too\n }\n }\n\n match mount_path_str {\n Some(path_str) if !path_str.is_empty() => {\n debug!(\"Parsed mount point from plist: {}\", path_str);\n Ok(PathBuf::from(path_str))\n }\n _ => {\n error!(\"Failed to parse mount point from hdiutil plist output.\");\n // Optionally log the raw output for debugging\n // error!(\"Raw hdiutil output:\\n{}\", String::from_utf8_lossy(output));\n Err(SpsError::Generic(\n \"Failed to determine mount point from hdiutil output\".to_string(),\n ))\n }\n }\n}\n\n// --- NEW Function ---\n/// Extracts the contents of a mounted DMG to a staging directory using `ditto`.\npub fn extract_dmg_to_stage(dmg_path: &Path, stage_dir: &Path) -> Result<()> {\n let mount_point = mount_dmg(dmg_path)?;\n\n // Ensure the stage directory exists (though TempDir should handle it)\n if !stage_dir.exists() {\n fs::create_dir_all(stage_dir).map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n }\n\n debug!(\n \"Copying contents from DMG mount {} to stage {} using ditto\",\n mount_point.display(),\n stage_dir.display()\n );\n // Use ditto for robust copying, preserving metadata\n // ditto \n debug!(\n \"Executing: ditto {} {}\",\n mount_point.display(),\n stage_dir.display()\n );\n let ditto_output = Command::new(\"ditto\")\n .arg(&mount_point) // Source first\n .arg(stage_dir) // Then destination\n .output()?;\n\n let unmount_result = unmount_dmg(&mount_point); // Unmount regardless of ditto success\n\n if !ditto_output.status.success() {\n let stderr = String::from_utf8_lossy(&ditto_output.stderr);\n error!(\"ditto command failed ({}): {}\", ditto_output.status, stderr);\n // Also log stdout which might contain info on specific file errors\n let stdout = String::from_utf8_lossy(&ditto_output.stdout);\n if !stdout.trim().is_empty() {\n error!(\"ditto stdout: {}\", stdout);\n }\n unmount_result?; // Ensure we still return unmount error if it happened\n return Err(SpsError::Generic(format!(\n \"Failed to copy DMG contents using ditto: {stderr}\"\n )));\n }\n\n // After ditto, quarantine any .app bundles in the stage (macOS only)\n #[cfg(target_os = \"macos\")]\n {\n if let Err(e) = crate::install::extract::quarantine_extracted_apps_in_stage(\n stage_dir,\n \"sps-dmg-extractor\",\n ) {\n tracing::warn!(\n \"Error during post-DMG extraction quarantine scan for {}: {}\",\n dmg_path.display(),\n e\n );\n }\n }\n\n unmount_result // Return the result of unmounting\n}\n"], ["/sps/sps-core/src/install/devtools.rs", "use std::env;\nuse std::path::PathBuf;\nuse std::process::{Command, Stdio};\n\nuse sps_common::error::{Result, SpsError};\nuse tracing::debug;\nuse which;\n\npub fn find_compiler(name: &str) -> Result {\n let env_var_name = match name {\n \"cc\" => \"CC\",\n \"c++\" | \"cxx\" => \"CXX\",\n _ => \"\",\n };\n if !env_var_name.is_empty() {\n if let Ok(compiler_path) = env::var(env_var_name) {\n let path = PathBuf::from(compiler_path);\n if path.is_file() {\n debug!(\n \"Using compiler from env var {}: {}\",\n env_var_name,\n path.display()\n );\n return Ok(path);\n } else {\n debug!(\n \"Env var {} points to non-existent file: {}\",\n env_var_name,\n path.display()\n );\n }\n }\n }\n\n if cfg!(target_os = \"macos\") {\n debug!(\"Attempting to find '{name}' using xcrun\");\n let output = Command::new(\"xcrun\")\n .arg(\"--find\")\n .arg(name)\n .stderr(Stdio::piped())\n .output();\n\n match output {\n Ok(out) if out.status.success() => {\n let path_str = String::from_utf8_lossy(&out.stdout).trim().to_string();\n if !path_str.is_empty() {\n let path = PathBuf::from(path_str);\n if path.is_file() {\n debug!(\"Found compiler via xcrun: {}\", path.display());\n return Ok(path);\n } else {\n debug!(\n \"xcrun found '{}' but path doesn't exist or isn't a file: {}\",\n name,\n path.display()\n );\n }\n } else {\n debug!(\"xcrun found '{name}' but returned empty path.\");\n }\n }\n Ok(out) => {\n let stderr = String::from_utf8_lossy(&out.stderr);\n debug!(\"xcrun failed to find '{}': {}\", name, stderr.trim());\n }\n Err(e) => {\n debug!(\"Failed to execute xcrun: {e}. Falling back to PATH search.\");\n }\n }\n }\n\n debug!(\"Falling back to searching PATH for '{name}'\");\n which::which(name).map_err(|e| {\n SpsError::BuildEnvError(format!(\"Failed to find compiler '{name}' on PATH: {e}\"))\n })\n}\n\npub fn find_sdk_path() -> Result {\n if cfg!(target_os = \"macos\") {\n debug!(\"Attempting to find macOS SDK path using xcrun\");\n let output = Command::new(\"xcrun\")\n .arg(\"--show-sdk-path\")\n .stderr(Stdio::piped())\n .output();\n\n match output {\n Ok(out) if out.status.success() => {\n let path_str = String::from_utf8_lossy(&out.stdout).trim().to_string();\n if path_str.is_empty() || path_str == \"/\" {\n return Err(SpsError::BuildEnvError(\n \"xcrun returned empty or invalid SDK path. Is Xcode or Command Line Tools installed correctly?\".to_string()\n ));\n }\n let sdk_path = PathBuf::from(path_str);\n if !sdk_path.exists() {\n return Err(SpsError::BuildEnvError(format!(\n \"SDK path reported by xcrun does not exist: {}\",\n sdk_path.display()\n )));\n }\n debug!(\"Found SDK path: {}\", sdk_path.display());\n Ok(sdk_path)\n }\n Ok(out) => {\n let stderr = String::from_utf8_lossy(&out.stderr);\n Err(SpsError::BuildEnvError(format!(\n \"xcrun failed to find SDK path: {}\",\n stderr.trim()\n )))\n }\n Err(e) => {\n Err(SpsError::BuildEnvError(format!(\n \"Failed to execute 'xcrun --show-sdk-path': {e}. Is Xcode or Command Line Tools installed?\"\n )))\n }\n }\n } else {\n debug!(\"Not on macOS, returning '/' as SDK path placeholder\");\n Ok(PathBuf::from(\"/\"))\n }\n}\n\npub fn get_macos_version() -> Result {\n if cfg!(target_os = \"macos\") {\n debug!(\"Attempting to get macOS version using sw_vers\");\n let output = Command::new(\"sw_vers\")\n .arg(\"-productVersion\")\n .stderr(Stdio::piped())\n .output();\n\n match output {\n Ok(out) if out.status.success() => {\n let version_full = String::from_utf8_lossy(&out.stdout).trim().to_string();\n let version_parts: Vec<&str> = version_full.split('.').collect();\n let version_short = if version_parts.len() >= 2 {\n format!(\"{}.{}\", version_parts[0], version_parts[1])\n } else {\n version_full.clone()\n };\n debug!(\"Found macOS version: {version_full} (short: {version_short})\");\n Ok(version_short)\n }\n Ok(out) => {\n let stderr = String::from_utf8_lossy(&out.stderr);\n Err(SpsError::BuildEnvError(format!(\n \"sw_vers failed to get product version: {}\",\n stderr.trim()\n )))\n }\n Err(e) => Err(SpsError::BuildEnvError(format!(\n \"Failed to execute 'sw_vers -productVersion': {e}\"\n ))),\n }\n } else {\n debug!(\"Not on macOS, returning '0.0' as version placeholder\");\n Ok(String::from(\"0.0\"))\n }\n}\n\npub fn get_arch_flag() -> String {\n if cfg!(target_os = \"macos\") {\n if cfg!(target_arch = \"x86_64\") {\n debug!(\"Detected target arch: x86_64\");\n \"-arch x86_64\".to_string()\n } else if cfg!(target_arch = \"aarch64\") {\n debug!(\"Detected target arch: aarch64 (arm64)\");\n \"-arch arm64\".to_string()\n } else {\n let arch = env::consts::ARCH;\n debug!(\n \"Unknown target architecture on macOS: {arch}, cannot determine -arch flag. Build might fail.\"\n );\n // Provide no flag in this unknown case? Or default to native?\n String::new()\n }\n } else {\n debug!(\"Not on macOS, returning empty arch flag.\");\n String::new()\n }\n}\n"], ["/sps/sps-common/src/config.rs", "// sps-common/src/config.rs\nuse std::env;\nuse std::path::{Path, PathBuf};\n\nuse directories::UserDirs; // Ensure this crate is in sps-common/Cargo.toml\nuse tracing::debug;\n\nuse super::error::Result; // Assuming SpsResult is Result from super::error\n\n// This constant will serve as a fallback if HOMEBREW_PREFIX is not set or is empty.\nconst DEFAULT_FALLBACK_SPS_ROOT: &str = \"/opt/homebrew\";\nconst SPS_ROOT_MARKER_FILENAME: &str = \".sps_root_v1\";\n\n#[derive(Debug, Clone)]\npub struct Config {\n pub sps_root: PathBuf, // Public for direct construction in main for init if needed\n pub api_base_url: String,\n pub artifact_domain: Option,\n pub docker_registry_token: Option,\n pub docker_registry_basic_auth: Option,\n pub github_api_token: Option,\n}\n\nimpl Config {\n pub fn load() -> Result {\n debug!(\"Loading sps configuration\");\n\n // Try to get SPS_ROOT from HOMEBREW_PREFIX environment variable.\n // Fallback to DEFAULT_FALLBACK_SPS_ROOT if not set or empty.\n let sps_root_str = env::var(\"HOMEBREW_PREFIX\").ok().filter(|s| !s.is_empty())\n .unwrap_or_else(|| {\n debug!(\n \"HOMEBREW_PREFIX environment variable not set or empty, falling back to default: {}\",\n DEFAULT_FALLBACK_SPS_ROOT\n );\n DEFAULT_FALLBACK_SPS_ROOT.to_string()\n });\n\n let sps_root_path = PathBuf::from(&sps_root_str);\n debug!(\"Effective SPS_ROOT set to: {}\", sps_root_path.display());\n\n let api_base_url = \"https://formulae.brew.sh/api\".to_string();\n\n let artifact_domain = env::var(\"HOMEBREW_ARTIFACT_DOMAIN\").ok();\n let docker_registry_token = env::var(\"HOMEBREW_DOCKER_REGISTRY_TOKEN\").ok();\n let docker_registry_basic_auth = env::var(\"HOMEBREW_DOCKER_REGISTRY_BASIC_AUTH_TOKEN\").ok();\n let github_api_token = env::var(\"HOMEBREW_GITHUB_API_TOKEN\").ok();\n\n debug!(\"Configuration loaded successfully.\");\n Ok(Self {\n sps_root: sps_root_path,\n api_base_url,\n artifact_domain,\n docker_registry_token,\n docker_registry_basic_auth,\n github_api_token,\n })\n }\n\n pub fn sps_root(&self) -> &Path {\n &self.sps_root\n }\n\n pub fn bin_dir(&self) -> PathBuf {\n self.sps_root.join(\"bin\")\n }\n\n pub fn cellar_dir(&self) -> PathBuf {\n self.sps_root.join(\"Cellar\") // Changed from \"cellar\" to \"Cellar\" to match Homebrew\n }\n\n pub fn cask_room_dir(&self) -> PathBuf {\n self.sps_root.join(\"Caskroom\") // Changed from \"cask_room\" to \"Caskroom\"\n }\n\n pub fn cask_store_dir(&self) -> PathBuf {\n self.sps_root.join(\"sps_cask_store\")\n }\n\n pub fn opt_dir(&self) -> PathBuf {\n self.sps_root.join(\"opt\")\n }\n\n pub fn taps_dir(&self) -> PathBuf {\n self.sps_root.join(\"Library/Taps\") // Adjusted to match Homebrew structure\n }\n\n pub fn cache_dir(&self) -> PathBuf {\n self.sps_root.join(\"sps_cache\")\n }\n\n pub fn logs_dir(&self) -> PathBuf {\n self.sps_root.join(\"sps_logs\")\n }\n\n pub fn tmp_dir(&self) -> PathBuf {\n self.sps_root.join(\"tmp\")\n }\n\n pub fn state_dir(&self) -> PathBuf {\n self.sps_root.join(\"sps_state\")\n }\n\n pub fn man_base_dir(&self) -> PathBuf {\n self.sps_root.join(\"share\").join(\"man\")\n }\n\n pub fn sps_root_marker_path(&self) -> PathBuf {\n self.sps_root.join(SPS_ROOT_MARKER_FILENAME)\n }\n\n pub fn applications_dir(&self) -> PathBuf {\n if cfg!(target_os = \"macos\") {\n PathBuf::from(\"/Applications\")\n } else {\n self.home_dir().join(\"Applications\")\n }\n }\n\n pub fn formula_cellar_dir(&self, formula_name: &str) -> PathBuf {\n self.cellar_dir().join(formula_name)\n }\n\n pub fn formula_keg_path(&self, formula_name: &str, version_str: &str) -> PathBuf {\n self.formula_cellar_dir(formula_name).join(version_str)\n }\n\n pub fn formula_opt_path(&self, formula_name: &str) -> PathBuf {\n self.opt_dir().join(formula_name)\n }\n\n pub fn cask_room_token_path(&self, cask_token: &str) -> PathBuf {\n self.cask_room_dir().join(cask_token)\n }\n\n pub fn cask_store_token_path(&self, cask_token: &str) -> PathBuf {\n self.cask_store_dir().join(cask_token)\n }\n\n pub fn cask_store_version_path(&self, cask_token: &str, version_str: &str) -> PathBuf {\n self.cask_store_token_path(cask_token).join(version_str)\n }\n\n pub fn cask_store_app_path(\n &self,\n cask_token: &str,\n version_str: &str,\n app_name: &str,\n ) -> PathBuf {\n self.cask_store_version_path(cask_token, version_str)\n .join(app_name)\n }\n\n pub fn cask_room_version_path(&self, cask_token: &str, version_str: &str) -> PathBuf {\n self.cask_room_token_path(cask_token).join(version_str)\n }\n\n pub fn home_dir(&self) -> PathBuf {\n UserDirs::new().map_or_else(|| PathBuf::from(\"/\"), |ud| ud.home_dir().to_path_buf())\n }\n\n pub fn get_tap_path(&self, name: &str) -> Option {\n let parts: Vec<&str> = name.split('/').collect();\n if parts.len() == 2 {\n Some(\n self.taps_dir()\n .join(parts[0]) // user, e.g., homebrew\n .join(format!(\"homebrew-{}\", parts[1])), // repo, e.g., homebrew-core\n )\n } else {\n None\n }\n }\n\n pub fn get_formula_path_from_tap(&self, tap_name: &str, formula_name: &str) -> Option {\n self.get_tap_path(tap_name).and_then(|tap_path| {\n let json_path = tap_path\n .join(\"Formula\") // Standard Homebrew tap structure\n .join(format!(\"{formula_name}.json\"));\n if json_path.exists() {\n return Some(json_path);\n }\n // Fallback to .rb for completeness, though API primarily gives JSON\n let rb_path = tap_path.join(\"Formula\").join(format!(\"{formula_name}.rb\"));\n if rb_path.exists() {\n return Some(rb_path);\n }\n None\n })\n }\n}\n\nimpl Default for Config {\n fn default() -> Self {\n Self::load().expect(\"Failed to load default configuration\")\n }\n}\n\npub fn load_config() -> Result {\n Config::load()\n}\n"], ["/sps/sps-core/src/utils/applescript.rs", "use std::path::Path;\nuse std::process::Command;\nuse std::thread;\nuse std::time::Duration;\n\nuse plist::Value as PlistValue;\nuse sps_common::error::Result;\nuse tracing::{debug, warn};\n\nfn get_bundle_identifier_from_app_path(app_path: &Path) -> Option {\n let info_plist_path = app_path.join(\"Contents/Info.plist\");\n if !info_plist_path.is_file() {\n debug!(\"Info.plist not found at {}\", info_plist_path.display());\n return None;\n }\n match PlistValue::from_file(&info_plist_path) {\n Ok(PlistValue::Dictionary(dict)) => dict\n .get(\"CFBundleIdentifier\")\n .and_then(PlistValue::as_string)\n .map(String::from),\n Ok(val) => {\n warn!(\n \"Info.plist at {} is not a dictionary. Value: {:?}\",\n info_plist_path.display(),\n val\n );\n None\n }\n Err(e) => {\n warn!(\n \"Failed to parse Info.plist at {}: {}\",\n info_plist_path.display(),\n e\n );\n None\n }\n }\n}\n\nfn is_app_running_by_bundle_id(bundle_id: &str) -> Result {\n let script = format!(\n \"tell application \\\"System Events\\\" to (exists (process 1 where bundle identifier is \\\"{bundle_id}\\\"))\"\n );\n debug!(\n \"Checking if app with bundle ID '{}' is running using script: {}\",\n bundle_id, script\n );\n\n let output = Command::new(\"osascript\").arg(\"-e\").arg(&script).output()?;\n\n if output.status.success() {\n let stdout = String::from_utf8_lossy(&output.stdout)\n .trim()\n .to_lowercase();\n debug!(\n \"is_app_running_by_bundle_id ('{}') stdout: '{}'\",\n bundle_id, stdout\n );\n Ok(stdout == \"true\")\n } else {\n let stderr = String::from_utf8_lossy(&output.stderr);\n warn!(\n \"osascript check running status for bundle ID '{}' failed. Status: {}, Stderr: {}\",\n bundle_id,\n output.status,\n stderr.trim()\n );\n Ok(false)\n }\n}\n\n/// Attempts to gracefully quit an application using its bundle identifier (preferred) or name via\n/// AppleScript. Retries several times, checking if the app is still running between attempts.\n/// Returns Ok even if the app could not be quit, as uninstall should proceed.\npub fn quit_app_gracefully(app_path: &Path) -> Result<()> {\n if !cfg!(target_os = \"macos\") {\n debug!(\"Not on macOS, skipping app quit for {}\", app_path.display());\n return Ok(());\n }\n if !app_path.exists() {\n debug!(\n \"App path {} does not exist, skipping quit attempt.\",\n app_path.display()\n );\n return Ok(());\n }\n\n let app_name_for_log = app_path\n .file_name()\n .map_or_else(|| app_path.to_string_lossy(), |name| name.to_string_lossy())\n .trim_end_matches(\".app\")\n .to_string();\n\n let bundle_identifier = get_bundle_identifier_from_app_path(app_path);\n\n let (script_target, using_bundle_id) = match &bundle_identifier {\n Some(id) => (id.clone(), true),\n None => {\n warn!(\n \"Could not get bundle identifier for {}. Will attempt to quit by name '{}'. This is less reliable.\",\n app_path.display(),\n app_name_for_log\n );\n (app_name_for_log.clone(), false)\n }\n };\n\n debug!(\n \"Attempting to quit app '{}' (script target: '{}', using bundle_id: {})\",\n app_name_for_log, script_target, using_bundle_id\n );\n\n // Initial check if app is running (only reliable if we have bundle ID)\n if using_bundle_id {\n match is_app_running_by_bundle_id(&script_target) {\n Ok(true) => debug!(\n \"App '{}' is running. Proceeding with quit attempts.\",\n script_target\n ),\n Ok(false) => {\n debug!(\"App '{}' is not running. Quit unnecessary.\", script_target);\n return Ok(());\n }\n Err(e) => {\n warn!(\n \"Could not determine if app '{}' is running (check failed: {}). Proceeding with quit attempt.\",\n script_target, e\n );\n }\n }\n }\n\n let quit_command = if using_bundle_id {\n format!(\"tell application id \\\"{script_target}\\\" to quit\")\n } else {\n format!(\"tell application \\\"{script_target}\\\" to quit\")\n };\n\n const MAX_QUIT_ATTEMPTS: usize = 4;\n const QUIT_DELAYS_SECS: [u64; MAX_QUIT_ATTEMPTS - 1] = [2, 3, 5];\n\n // Use enumerate over QUIT_DELAYS_SECS for Clippy compliance\n for (attempt, delay) in QUIT_DELAYS_SECS.iter().enumerate() {\n debug!(\n \"Quit attempt #{} for '{}' using command: {}\",\n attempt + 1,\n script_target,\n quit_command\n );\n\n let output = Command::new(\"osascript\")\n .arg(\"-e\")\n .arg(&quit_command)\n .output()?; // Propagate IO errors from osascript execution\n\n if output.status.success() {\n debug!(\n \"osascript quit command sent successfully for '{}' (attempt #{}).\",\n script_target,\n attempt + 1\n );\n } else {\n let stderr = String::from_utf8_lossy(&output.stderr);\n if stderr.contains(\"-1712\")\n || stderr.contains(\"-1728\")\n || stderr.contains(\"-600\")\n || stderr.to_lowercase().contains(\"application isn’t running\")\n || stderr.to_lowercase().contains(\"application not running\")\n {\n debug!(\n \"osascript: App '{}' reported as not running or not found (stderr: {}). Quit successful or unnecessary.\",\n script_target,\n stderr.trim()\n );\n return Ok(());\n } else {\n warn!(\n \"osascript quit command for '{}' failed (attempt #{}). Status: {}. Stderr: {}\",\n script_target,\n attempt + 1,\n output.status,\n stderr.trim()\n );\n }\n }\n\n // Wait briefly to allow the app to process the quit command\n thread::sleep(Duration::from_secs(*delay));\n\n // Check if the app is still running (if using bundle ID)\n if using_bundle_id {\n match is_app_running_by_bundle_id(&script_target) {\n Ok(true) => {\n debug!(\n \"App '{}' still running after attempt #{}. Retrying.\",\n script_target,\n attempt + 1\n );\n }\n Ok(false) => {\n debug!(\n \"App '{}' successfully quit after attempt #{}.\",\n script_target,\n attempt + 1\n );\n return Ok(());\n }\n Err(e) => {\n warn!(\n \"Could not verify if app '{}' quit after attempt #{}: {}. Assuming it might still be running.\",\n script_target,\n attempt + 1,\n e\n );\n }\n }\n }\n }\n\n // Final attempt (the fourth, not covered by QUIT_DELAYS_SECS)\n let attempt = QUIT_DELAYS_SECS.len();\n debug!(\n \"Quit attempt #{} for '{}' using command: {}\",\n attempt + 1,\n script_target,\n quit_command\n );\n\n let output = Command::new(\"osascript\")\n .arg(\"-e\")\n .arg(&quit_command)\n .output()?; // Propagate IO errors from osascript execution\n\n if output.status.success() {\n debug!(\n \"osascript quit command sent successfully for '{}' (attempt #{}).\",\n script_target,\n attempt + 1\n );\n } else {\n let stderr = String::from_utf8_lossy(&output.stderr);\n if stderr.contains(\"-1712\")\n || stderr.contains(\"-1728\")\n || stderr.contains(\"-600\")\n || stderr.to_lowercase().contains(\"application isn’t running\")\n || stderr.to_lowercase().contains(\"application not running\")\n {\n debug!(\n \"osascript: App '{}' reported as not running or not found (stderr: {}). Quit successful or unnecessary.\",\n script_target,\n stderr.trim()\n );\n return Ok(());\n } else {\n warn!(\n \"osascript quit command for '{}' failed (attempt #{}). Status: {}. Stderr: {}\",\n script_target,\n attempt + 1,\n output.status,\n stderr.trim()\n );\n }\n }\n\n // Final check if the app is still running (if using bundle ID)\n if using_bundle_id {\n match is_app_running_by_bundle_id(&script_target) {\n Ok(true) => {\n warn!(\n \"App '{}' still running after {} quit attempts.\",\n script_target, MAX_QUIT_ATTEMPTS\n );\n }\n Ok(false) => {\n debug!(\n \"App '{}' successfully quit after attempt #{}.\",\n script_target,\n attempt + 1\n );\n return Ok(());\n }\n Err(e) => {\n warn!(\n \"Could not verify if app '{}' quit after attempt #{}: {}. Assuming it might still be running.\",\n script_target,\n attempt + 1,\n e\n );\n }\n }\n } else {\n warn!(\n \"App '{}' (targeted by name) might still be running after {} quit attempts. Manual check may be needed.\",\n script_target,\n MAX_QUIT_ATTEMPTS\n );\n }\n Ok(())\n}\n"], ["/sps/sps-net/src/api.rs", "use std::sync::Arc;\n\nuse reqwest::header::{ACCEPT, AUTHORIZATION, USER_AGENT};\nuse reqwest::Client;\nuse serde_json::Value;\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::cask::{Cask, CaskList};\nuse sps_common::model::formula::Formula;\nuse tracing::{debug, error};\n\nconst FORMULAE_API_BASE_URL: &str = \"https://formulae.brew.sh/api\";\nconst GITHUB_API_BASE_URL: &str = \"https://api.github.com\";\nconst USER_AGENT_STRING: &str = \"sps Package Manager (Rust; +https://github.com/your/sp)\";\n\nfn build_api_client(config: &Config) -> Result {\n let mut headers = reqwest::header::HeaderMap::new();\n headers.insert(USER_AGENT, USER_AGENT_STRING.parse().unwrap());\n headers.insert(ACCEPT, \"application/vnd.github+json\".parse().unwrap());\n if let Some(token) = &config.github_api_token {\n debug!(\"Adding GitHub API token to request headers.\");\n match format!(\"Bearer {token}\").parse() {\n Ok(val) => {\n headers.insert(AUTHORIZATION, val);\n }\n Err(e) => {\n error!(\"Failed to parse GitHub API token into header value: {}\", e);\n }\n }\n } else {\n debug!(\"No GitHub API token found in config.\");\n }\n Ok(Client::builder().default_headers(headers).build()?)\n}\n\npub async fn fetch_raw_formulae_json(endpoint: &str) -> Result {\n let url = format!(\"{FORMULAE_API_BASE_URL}/{endpoint}\");\n debug!(\"Fetching data from Homebrew Formulae API: {}\", url);\n let client = reqwest::Client::builder()\n .user_agent(USER_AGENT_STRING)\n .build()?;\n let response = client.get(&url).send().await.map_err(|e| {\n debug!(\"HTTP request failed for {}: {}\", url, e);\n SpsError::Http(Arc::new(e))\n })?;\n if !response.status().is_success() {\n let status = response.status();\n let body = response\n .text()\n .await\n .unwrap_or_else(|e| format!(\"(Failed to read response body: {e})\"));\n debug!(\n \"HTTP request to {} returned non-success status: {}\",\n url, status\n );\n debug!(\"Response body for failed request to {}: {}\", url, body);\n return Err(SpsError::Api(format!(\"HTTP status {status} from {url}\")));\n }\n let body = response.text().await?;\n if body.trim().is_empty() {\n error!(\"Response body for {} was empty.\", url);\n return Err(SpsError::Api(format!(\n \"Empty response body received from {url}\"\n )));\n }\n Ok(body)\n}\n\npub async fn fetch_all_formulas() -> Result {\n fetch_raw_formulae_json(\"formula.json\").await\n}\n\npub async fn fetch_all_casks() -> Result {\n fetch_raw_formulae_json(\"cask.json\").await\n}\n\npub async fn fetch_formula(name: &str) -> Result {\n let direct_fetch_result = fetch_raw_formulae_json(&format!(\"formula/{name}.json\")).await;\n if let Ok(body) = direct_fetch_result {\n let formula: serde_json::Value = serde_json::from_str(&body)?;\n Ok(formula)\n } else {\n debug!(\n \"Direct fetch for formula '{}' failed ({:?}). Fetching full list as fallback.\",\n name,\n direct_fetch_result.err()\n );\n let all_formulas_body = fetch_all_formulas().await?;\n let formulas: Vec = serde_json::from_str(&all_formulas_body)?;\n for formula in formulas {\n if formula.get(\"name\").and_then(Value::as_str) == Some(name) {\n return Ok(formula);\n }\n if formula.get(\"full_name\").and_then(Value::as_str) == Some(name) {\n return Ok(formula);\n }\n }\n Err(SpsError::NotFound(format!(\n \"Formula '{name}' not found in API list\"\n )))\n }\n}\n\npub async fn fetch_cask(token: &str) -> Result {\n let direct_fetch_result = fetch_raw_formulae_json(&format!(\"cask/{token}.json\")).await;\n if let Ok(body) = direct_fetch_result {\n let cask: serde_json::Value = serde_json::from_str(&body)?;\n Ok(cask)\n } else {\n debug!(\n \"Direct fetch for cask '{}' failed ({:?}). Fetching full list as fallback.\",\n token,\n direct_fetch_result.err()\n );\n let all_casks_body = fetch_all_casks().await?;\n let casks: Vec = serde_json::from_str(&all_casks_body)?;\n for cask in casks {\n if cask.get(\"token\").and_then(Value::as_str) == Some(token) {\n return Ok(cask);\n }\n }\n Err(SpsError::NotFound(format!(\n \"Cask '{token}' not found in API list\"\n )))\n }\n}\n\nasync fn fetch_github_api_json(endpoint: &str, config: &Config) -> Result {\n let url = format!(\"{GITHUB_API_BASE_URL}{endpoint}\");\n debug!(\"Fetching data from GitHub API: {}\", url);\n let client = build_api_client(config)?;\n let response = client.get(&url).send().await.map_err(|e| {\n error!(\"GitHub API request failed for {}: {}\", url, e);\n SpsError::Http(Arc::new(e))\n })?;\n if !response.status().is_success() {\n let status = response.status();\n let body = response\n .text()\n .await\n .unwrap_or_else(|e| format!(\"(Failed to read response body: {e})\"));\n error!(\n \"GitHub API request to {} returned non-success status: {}\",\n url, status\n );\n debug!(\n \"Response body for failed GitHub API request to {}: {}\",\n url, body\n );\n return Err(SpsError::Api(format!(\"HTTP status {status} from {url}\")));\n }\n let value: Value = response.json::().await.map_err(|e| {\n error!(\"Failed to parse JSON response from {}: {}\", url, e);\n SpsError::ApiRequestError(e.to_string())\n })?;\n Ok(value)\n}\n\n#[allow(dead_code)]\nasync fn fetch_github_repo_info(owner: &str, repo: &str, config: &Config) -> Result {\n let endpoint = format!(\"/repos/{owner}/{repo}\");\n fetch_github_api_json(&endpoint, config).await\n}\n\npub async fn get_formula(name: &str) -> Result {\n let url = format!(\"{FORMULAE_API_BASE_URL}/formula/{name}.json\");\n debug!(\n \"Fetching and parsing formula data for '{}' from {}\",\n name, url\n );\n let client = reqwest::Client::new();\n let response = client.get(&url).send().await.map_err(|e| {\n debug!(\"HTTP request failed when fetching formula {}: {}\", name, e);\n SpsError::Http(Arc::new(e))\n })?;\n let status = response.status();\n let text = response.text().await?;\n if !status.is_success() {\n debug!(\"Failed to fetch formula {} (Status {})\", name, status);\n debug!(\"Response body for failed formula fetch {}: {}\", name, text);\n return Err(SpsError::Api(format!(\n \"Failed to fetch formula {name}: Status {status}\"\n )));\n }\n if text.trim().is_empty() {\n error!(\"Received empty body when fetching formula {}\", name);\n return Err(SpsError::Api(format!(\n \"Empty response body for formula {name}\"\n )));\n }\n match serde_json::from_str::(&text) {\n Ok(formula) => Ok(formula),\n Err(_) => match serde_json::from_str::>(&text) {\n Ok(mut formulas) if !formulas.is_empty() => {\n debug!(\n \"Parsed formula {} from a single-element array response.\",\n name\n );\n Ok(formulas.remove(0))\n }\n Ok(_) => {\n error!(\"Received empty array when fetching formula {}\", name);\n Err(SpsError::NotFound(format!(\n \"Formula '{name}' not found (empty array returned)\"\n )))\n }\n Err(e_vec) => {\n error!(\n \"Failed to parse formula {} as object or array. Error: {}. Body (sample): {}\",\n name,\n e_vec,\n text.chars().take(500).collect::()\n );\n Err(SpsError::Json(Arc::new(e_vec)))\n }\n },\n }\n}\n\npub async fn get_all_formulas() -> Result> {\n let raw_data = fetch_all_formulas().await?;\n serde_json::from_str(&raw_data).map_err(|e| {\n error!(\"Failed to parse all_formulas response: {}\", e);\n SpsError::Json(Arc::new(e))\n })\n}\n\npub async fn get_cask(name: &str) -> Result {\n let raw_json_result = fetch_cask(name).await;\n let raw_json = match raw_json_result {\n Ok(json_val) => json_val,\n Err(e) => {\n error!(\"Failed to fetch raw JSON for cask {}: {}\", name, e);\n return Err(e);\n }\n };\n match serde_json::from_value::(raw_json.clone()) {\n Ok(cask) => Ok(cask),\n Err(e) => {\n error!(\"Failed to parse cask {} JSON: {}\", name, e);\n match serde_json::to_string_pretty(&raw_json) {\n Ok(json_str) => {\n tracing::debug!(\"Problematic JSON for cask '{}':\\n{}\", name, json_str);\n }\n Err(fmt_err) => {\n tracing::debug!(\n \"Could not pretty-print problematic JSON for cask {}: {}\",\n name,\n fmt_err\n );\n tracing::debug!(\"Raw problematic value: {:?}\", raw_json);\n }\n }\n Err(SpsError::Json(Arc::new(e)))\n }\n }\n}\n\npub async fn get_all_casks() -> Result {\n let raw_data = fetch_all_casks().await?;\n let casks: Vec = serde_json::from_str(&raw_data).map_err(|e| {\n error!(\"Failed to parse all_casks response: {}\", e);\n SpsError::Json(Arc::new(e))\n })?;\n Ok(CaskList { casks })\n}\n"], ["/sps/sps-net/src/oci.rs", "use std::collections::HashMap;\nuse std::fs::{remove_file, File};\nuse std::path::Path;\nuse std::sync::Arc;\nuse std::time::Duration;\n\nuse futures::StreamExt;\nuse rand::rngs::SmallRng;\nuse rand::{Rng, SeedableRng};\nuse reqwest::header::{ACCEPT, AUTHORIZATION};\nuse reqwest::{Client, Response, StatusCode};\nuse serde::{Deserialize, Serialize};\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse tracing::{debug, error};\nuse url::Url;\n\nuse crate::http::ProgressCallback;\nuse crate::validation::{validate_url, verify_checksum};\n\nconst OCI_MANIFEST_V1_TYPE: &str = \"application/vnd.oci.image.index.v1+json\";\nconst OCI_LAYER_V1_TYPE: &str = \"application/vnd.oci.image.layer.v1.tar+gzip\";\nconst DEFAULT_GHCR_TOKEN_ENDPOINT: &str = \"https://ghcr.io/token\";\npub const DEFAULT_GHCR_DOMAIN: &str = \"ghcr.io\";\n\nconst CONNECT_TIMEOUT_SECS: u64 = 30;\nconst REQUEST_TIMEOUT_SECS: u64 = 300;\nconst USER_AGENT_STRING: &str = \"sps package manager (Rust; +https://github.com/alexykn/sps)\";\n\n#[derive(Deserialize, Debug)]\nstruct OciTokenResponse {\n token: String,\n}\n\n#[derive(Serialize, Deserialize, Debug, Clone)]\n#[serde(rename_all = \"camelCase\")]\npub struct OciManifestIndex {\n pub schema_version: u32,\n pub media_type: Option,\n pub manifests: Vec,\n}\n\n#[derive(Serialize, Deserialize, Debug, Clone)]\n#[serde(rename_all = \"camelCase\")]\npub struct OciManifestDescriptor {\n pub media_type: String,\n pub digest: String,\n pub size: u64,\n pub platform: Option,\n pub annotations: Option>,\n}\n\n#[derive(Serialize, Deserialize, Debug, Clone)]\n#[serde(rename_all = \"camelCase\")]\npub struct OciPlatform {\n pub architecture: String,\n pub os: String,\n #[serde(rename = \"os.version\")]\n pub os_version: Option,\n #[serde(default)]\n pub features: Vec,\n pub variant: Option,\n}\n\n#[derive(Debug, Clone)]\nenum OciAuth {\n None,\n AnonymousBearer { token: String },\n ExplicitBearer { token: String },\n Basic { encoded: String },\n}\n\nasync fn fetch_oci_resource(\n resource_url: &str,\n accept_header: &str,\n config: &Config,\n client: &Client,\n) -> Result {\n let url = Url::parse(resource_url)\n .map_err(|e| SpsError::Generic(format!(\"Invalid URL '{resource_url}': {e}\")))?;\n validate_url(url.as_str())?;\n let registry_domain = url.host_str().unwrap_or(DEFAULT_GHCR_DOMAIN);\n let repo_path = extract_repo_path_from_url(&url).unwrap_or(\"\");\n\n let auth = determine_auth(config, client, registry_domain, repo_path).await?;\n let resp = execute_oci_request(client, resource_url, accept_header, &auth).await?;\n let txt = resp.text().await.map_err(|e| SpsError::Http(Arc::new(e)))?;\n\n debug!(\"OCI response ({} bytes) from {}\", txt.len(), resource_url);\n serde_json::from_str(&txt).map_err(|e| {\n error!(\"JSON parse error from {}: {}\", resource_url, e);\n SpsError::Json(Arc::new(e))\n })\n}\n\npub async fn download_oci_blob(\n blob_url: &str,\n destination_path: &Path,\n config: &Config,\n client: &Client,\n expected_digest: &str,\n) -> Result<()> {\n download_oci_blob_with_progress(\n blob_url,\n destination_path,\n config,\n client,\n expected_digest,\n None,\n )\n .await\n}\n\npub async fn download_oci_blob_with_progress(\n blob_url: &str,\n destination_path: &Path,\n config: &Config,\n client: &Client,\n expected_digest: &str,\n progress_callback: Option,\n) -> Result<()> {\n debug!(\"Downloading OCI blob: {}\", blob_url);\n let url = Url::parse(blob_url)\n .map_err(|e| SpsError::Generic(format!(\"Invalid URL '{blob_url}': {e}\")))?;\n validate_url(url.as_str())?;\n let registry_domain = url.host_str().unwrap_or(DEFAULT_GHCR_DOMAIN);\n let repo_path = extract_repo_path_from_url(&url).unwrap_or(\"\");\n\n let auth = determine_auth(config, client, registry_domain, repo_path).await?;\n let resp = execute_oci_request(client, blob_url, OCI_LAYER_V1_TYPE, &auth).await?;\n\n // Get total size from Content-Length header if available\n let total_size = resp.content_length();\n\n let tmp = destination_path.with_file_name(format!(\n \".{}.download\",\n destination_path.file_name().unwrap().to_string_lossy()\n ));\n let mut out = File::create(&tmp).map_err(|e| SpsError::Io(Arc::new(e)))?;\n\n let mut stream = resp.bytes_stream();\n let mut bytes_downloaded = 0u64;\n\n while let Some(chunk) = stream.next().await {\n let b = chunk.map_err(|e| SpsError::Http(Arc::new(e)))?;\n std::io::Write::write_all(&mut out, &b).map_err(|e| SpsError::Io(Arc::new(e)))?;\n\n bytes_downloaded += b.len() as u64;\n\n // Call progress callback if provided\n if let Some(ref callback) = progress_callback {\n callback(bytes_downloaded, total_size);\n }\n }\n std::fs::rename(&tmp, destination_path).map_err(|e| SpsError::Io(Arc::new(e)))?;\n\n if !expected_digest.is_empty() {\n match verify_checksum(destination_path, expected_digest) {\n Ok(_) => {\n tracing::debug!(\"OCI Blob checksum verified: {}\", destination_path.display());\n }\n Err(e) => {\n tracing::error!(\n \"OCI Blob checksum mismatch ({}). Deleting downloaded file.\",\n e\n );\n let _ = remove_file(destination_path);\n return Err(e);\n }\n }\n } else {\n tracing::warn!(\n \"Skipping checksum verification for OCI blob {} - no checksum provided.\",\n destination_path.display()\n );\n }\n\n debug!(\"Blob saved to {}\", destination_path.display());\n Ok(())\n}\n\npub async fn fetch_oci_manifest_index(\n manifest_url: &str,\n config: &Config,\n client: &Client,\n) -> Result {\n fetch_oci_resource(manifest_url, OCI_MANIFEST_V1_TYPE, config, client).await\n}\n\npub fn build_oci_client() -> Result {\n Client::builder()\n .user_agent(USER_AGENT_STRING)\n .connect_timeout(Duration::from_secs(CONNECT_TIMEOUT_SECS))\n .timeout(Duration::from_secs(REQUEST_TIMEOUT_SECS))\n .redirect(reqwest::redirect::Policy::default())\n .build()\n .map_err(|e| SpsError::Http(Arc::new(e)))\n}\n\nfn extract_repo_path_from_url(url: &Url) -> Option<&str> {\n url.path()\n .trim_start_matches('/')\n .trim_start_matches(\"v2/\")\n .split(\"/manifests/\")\n .next()\n .and_then(|s| s.split(\"/blobs/\").next())\n .filter(|s| !s.is_empty())\n}\n\nasync fn determine_auth(\n config: &Config,\n client: &Client,\n registry_domain: &str,\n repo_path: &str,\n) -> Result {\n if let Some(token) = &config.docker_registry_token {\n debug!(\"Using explicit bearer for {}\", registry_domain);\n return Ok(OciAuth::ExplicitBearer {\n token: token.clone(),\n });\n }\n if let Some(basic) = &config.docker_registry_basic_auth {\n debug!(\"Using explicit basic auth for {}\", registry_domain);\n return Ok(OciAuth::Basic {\n encoded: basic.clone(),\n });\n }\n\n if registry_domain.eq_ignore_ascii_case(DEFAULT_GHCR_DOMAIN) && !repo_path.is_empty() {\n debug!(\n \"Anonymous token fetch for {} scope={}\",\n registry_domain, repo_path\n );\n match fetch_anonymous_token(client, registry_domain, repo_path).await {\n Ok(t) => return Ok(OciAuth::AnonymousBearer { token: t }),\n Err(e) => debug!(\"Anon token failed, proceeding unauthenticated: {}\", e),\n }\n }\n Ok(OciAuth::None)\n}\n\nasync fn fetch_anonymous_token(\n client: &Client,\n registry_domain: &str,\n repo_path: &str,\n) -> Result {\n let endpoint = if registry_domain.eq_ignore_ascii_case(DEFAULT_GHCR_DOMAIN) {\n DEFAULT_GHCR_TOKEN_ENDPOINT.to_string()\n } else {\n format!(\"https://{registry_domain}/token\")\n };\n let scope = format!(\"repository:{repo_path}:pull\");\n let token_url = format!(\"{endpoint}?service={registry_domain}&scope={scope}\");\n\n const MAX_RETRIES: u8 = 3;\n let base_delay = Duration::from_millis(200);\n let mut delay = base_delay;\n // Use a Sendable RNG\n let mut rng = SmallRng::from_os_rng();\n\n for attempt in 0..=MAX_RETRIES {\n debug!(\n \"Token attempt {}/{} from {}\",\n attempt + 1,\n MAX_RETRIES + 1,\n token_url\n );\n\n match client.get(&token_url).send().await {\n Ok(resp) if resp.status().is_success() => {\n let tok: OciTokenResponse = resp\n .json()\n .await\n .map_err(|e| SpsError::ApiRequestError(format!(\"Parse token response: {e}\")))?;\n return Ok(tok.token);\n }\n Ok(resp) => {\n let code = resp.status();\n let body = resp.text().await.unwrap_or_default();\n error!(\"Token fetch {}: {} – {}\", attempt + 1, code, body);\n if !code.is_server_error() || attempt == MAX_RETRIES {\n return Err(SpsError::Api(format!(\"Token endpoint {code}: {body}\")));\n }\n }\n Err(e) => {\n error!(\"Network error on token fetch {}: {}\", attempt + 1, e);\n if attempt == MAX_RETRIES {\n return Err(SpsError::Http(Arc::new(e)));\n }\n }\n }\n\n let jitter = rng.random_range(0..(base_delay.as_millis() as u64 / 2));\n tokio::time::sleep(delay + Duration::from_millis(jitter)).await;\n delay *= 2;\n }\n\n Err(SpsError::Api(format!(\n \"Failed to fetch OCI token after {} attempts\",\n MAX_RETRIES + 1\n )))\n}\n\nasync fn execute_oci_request(\n client: &Client,\n url: &str,\n accept: &str,\n auth: &OciAuth,\n) -> Result {\n debug!(\"OCI request → {} (Accept: {})\", url, accept);\n let mut req = client.get(url).header(ACCEPT, accept);\n match auth {\n OciAuth::AnonymousBearer { token } | OciAuth::ExplicitBearer { token }\n if !token.is_empty() =>\n {\n req = req.header(AUTHORIZATION, format!(\"Bearer {token}\"))\n }\n OciAuth::Basic { encoded } if !encoded.is_empty() => {\n req = req.header(AUTHORIZATION, format!(\"Basic {encoded}\"))\n }\n _ => {}\n }\n\n let resp = req.send().await.map_err(|e| SpsError::Http(Arc::new(e)))?;\n let status = resp.status();\n if status.is_success() {\n Ok(resp)\n } else {\n let body = resp.text().await.unwrap_or_default();\n error!(\"OCI {} ⇒ {} – {}\", url, status, body);\n let err = match status {\n StatusCode::UNAUTHORIZED => SpsError::Api(format!(\"Auth required: {status}\")),\n StatusCode::FORBIDDEN => SpsError::Api(format!(\"Permission denied: {status}\")),\n StatusCode::NOT_FOUND => SpsError::NotFound(format!(\"Not found: {status}\")),\n _ => SpsError::Api(format!(\"HTTP {status} – {body}\")),\n };\n Err(err)\n }\n}\n"], ["/sps/sps-core/src/utils/xattr.rs", "use std::path::Path;\nuse std::process::Command;\n\nuse anyhow::Context;\nuse sps_common::error::{Result, SpsError};\nuse tracing::{debug, error};\nuse uuid::Uuid;\nuse xattr;\n\n// Helper to get current timestamp as hex\nfn get_timestamp_hex() -> String {\n let secs = std::time::SystemTime::now()\n .duration_since(std::time::UNIX_EPOCH)\n .unwrap_or_default() // Defaults to 0 if time is before UNIX_EPOCH\n .as_secs();\n format!(\"{secs:x}\")\n}\n\n// Helper to generate a UUID as hex string\nfn get_uuid_hex() -> String {\n Uuid::new_v4().as_hyphenated().to_string().to_uppercase()\n}\n\n/// true → file **has** a com.apple.quarantine attribute \n/// false → attribute missing\npub fn has_quarantine_attribute(path: &Path) -> anyhow::Result {\n // The `xattr` crate has both path-level and FileExt APIs.\n // Path-level is simpler here.\n match xattr::get(path, \"com.apple.quarantine\") {\n Ok(Some(_)) => Ok(true),\n Ok(None) => Ok(false),\n Err(e) => Err(anyhow::Error::new(e))\n .with_context(|| format!(\"checking xattr on {}\", path.display())),\n }\n}\n\n/// Apply our standard quarantine only *if* none exists already.\n///\n/// `agent` should be the same string you currently pass to\n/// `set_quarantine_attribute()` – usually the cask token.\npub fn ensure_quarantine_attribute(path: &Path, agent: &str) -> anyhow::Result<()> {\n if has_quarantine_attribute(path)? {\n // Already quarantined (or the user cleared it and we respect that) → done\n return Ok(());\n }\n set_quarantine_attribute(path, agent)\n .with_context(|| format!(\"adding quarantine to {}\", path.display()))\n}\n\n/// Sets the 'com.apple.quarantine' extended attribute on a file or directory.\n/// Uses flags commonly seen for user-initiated downloads (0081).\n/// Logs errors assertively, as failure is critical for correct behavior.\npub fn set_quarantine_attribute(path: &Path, agent_name: &str) -> Result<()> {\n if !cfg!(target_os = \"macos\") {\n debug!(\n \"Not on macOS, skipping quarantine attribute for {}\",\n path.display()\n );\n return Ok(());\n }\n\n if !path.exists() {\n error!(\n \"Cannot set quarantine attribute, path does not exist: {}\",\n path.display()\n );\n return Err(SpsError::NotFound(format!(\n \"Path not found for setting quarantine attribute: {}\",\n path.display()\n )));\n }\n\n let timestamp_hex = get_timestamp_hex();\n let uuid_hex = get_uuid_hex();\n // Use \"0181\" to disable translocation and quarantine mirroring (Homebrew-style).\n // Format: \"flags;timestamp_hex;agent_name;uuid_hex\"\n let quarantine_value = format!(\"0181;{timestamp_hex};{agent_name};{uuid_hex}\");\n\n debug!(\n \"Setting quarantine attribute on {}: value='{}'\",\n path.display(),\n quarantine_value\n );\n\n let output = Command::new(\"xattr\")\n .arg(\"-w\")\n .arg(\"com.apple.quarantine\")\n .arg(&quarantine_value)\n .arg(path.as_os_str())\n .output();\n\n match output {\n Ok(out) => {\n if out.status.success() {\n debug!(\n \"Successfully set quarantine attribute for {}\",\n path.display()\n );\n Ok(())\n } else {\n let stderr = String::from_utf8_lossy(&out.stderr);\n error!( // Changed from warn to error as this is critical for the bug\n \"Failed to set quarantine attribute for {} (status: {}): {}. This may lead to data loss on reinstall or Gatekeeper issues.\",\n path.display(),\n out.status,\n stderr.trim()\n );\n // Return an error because failure to set this is likely to cause the reported bug\n Err(SpsError::Generic(format!(\n \"Failed to set com.apple.quarantine on {}: {}\",\n path.display(),\n stderr.trim()\n )))\n }\n }\n Err(e) => {\n error!(\n \"Failed to execute xattr command for {}: {}. Quarantine attribute not set.\",\n path.display(),\n e\n );\n Err(SpsError::Io(std::sync::Arc::new(e)))\n }\n }\n}\n"], ["/sps/sps-core/src/upgrade/cask.rs", "// sps-core/src/upgrade/cask.rs\n\nuse std::path::Path;\n\nuse sps_common::config::Config;\nuse sps_common::error::{Result as SpsResult, SpsError};\nuse sps_common::model::cask::Cask;\nuse sps_common::pipeline::JobAction; // Required for install_cask\nuse tracing::{debug, error};\n\nuse crate::check::installed::InstalledPackageInfo;\nuse crate::{install, uninstall};\n\n/// Upgrades a cask package using Homebrew's proven strategy.\npub async fn upgrade_cask_package(\n cask: &Cask,\n new_cask_download_path: &Path,\n old_install_info: &InstalledPackageInfo,\n config: &Config,\n) -> SpsResult<()> {\n debug!(\n \"Upgrading cask {} from {} to {}\",\n cask.token,\n old_install_info.version,\n cask.version.as_deref().unwrap_or(\"latest\")\n );\n\n // 1. Soft-uninstall the old version\n // This removes linked artifacts and updates the old manifest's is_installed flag.\n // It does not remove the old Caskroom version directory itself yet.\n debug!(\n \"Soft-uninstalling old cask version: {} at {}\",\n old_install_info.version,\n old_install_info.path.display()\n );\n uninstall::cask::uninstall_cask_artifacts(old_install_info, config).map_err(|e| {\n error!(\n \"Failed to soft-uninstall old version {} of cask {}: {}\",\n old_install_info.version, cask.token, e\n );\n SpsError::InstallError(format!(\n \"Failed to soft-uninstall old version during upgrade of {}: {e}\",\n cask.token\n ))\n })?;\n debug!(\n \"Successfully soft-uninstalled old version of {}\",\n cask.token\n );\n\n // 2. Install the new version\n // The install_cask function, particularly install_app_from_staged,\n // should handle the upgrade logic (like syncing app data) when\n // passed the JobAction::Upgrade.\n debug!(\n \"Installing new version for cask {} from {}\",\n cask.token,\n new_cask_download_path.display()\n );\n\n let job_action_for_install = JobAction::Upgrade {\n from_version: old_install_info.version.clone(),\n old_install_path: old_install_info.path.clone(),\n };\n\n install::cask::install_cask(\n cask,\n new_cask_download_path,\n config,\n &job_action_for_install,\n )\n .map_err(|e| {\n error!(\n \"Failed to install new version of cask {}: {}\",\n cask.token, e\n );\n SpsError::InstallError(format!(\n \"Failed to install new version during upgrade of {}: {e}\",\n cask.token\n ))\n })?;\n debug!(\"Successfully installed new version of cask {}\", cask.token);\n\n Ok(())\n}\n"], ["/sps/sps/src/cli/status.rs", "// sps/src/cli/status.rs\nuse std::collections::{HashMap, HashSet};\nuse std::io::{self, Write};\nuse std::time::Instant;\n\nuse colored::*;\nuse sps_common::config::Config;\nuse sps_common::pipeline::{PipelineEvent, PipelinePackageType};\nuse tokio::sync::broadcast;\nuse tracing::debug;\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq)]\nenum JobStatus {\n Waiting,\n Downloading,\n Downloaded,\n Cached,\n Processing,\n Installing,\n Linking,\n Success,\n Failed,\n}\n\nimpl JobStatus {\n fn display_state(&self) -> &'static str {\n match self {\n JobStatus::Waiting => \"waiting\",\n JobStatus::Downloading => \"downloading\",\n JobStatus::Downloaded => \"downloaded\",\n JobStatus::Cached => \"cached\",\n JobStatus::Processing => \"processing\",\n JobStatus::Installing => \"installing\",\n JobStatus::Linking => \"linking\",\n JobStatus::Success => \"success\",\n JobStatus::Failed => \"failed\",\n }\n }\n\n fn slot_indicator(&self) -> String {\n match self {\n JobStatus::Waiting => \" ⧗\".yellow().to_string(),\n JobStatus::Downloading => \" ⬇\".blue().to_string(),\n JobStatus::Downloaded => \" ✓\".green().to_string(),\n JobStatus::Cached => \" ⌂\".cyan().to_string(),\n JobStatus::Processing => \" ⚙\".yellow().to_string(),\n JobStatus::Installing => \" ⚙\".cyan().to_string(),\n JobStatus::Linking => \" →\".magenta().to_string(),\n JobStatus::Success => \" ✓\".green().bold().to_string(),\n JobStatus::Failed => \" ✗\".red().bold().to_string(),\n }\n }\n\n fn colored_state(&self) -> ColoredString {\n match self {\n JobStatus::Waiting => self.display_state().dimmed(),\n JobStatus::Downloading => self.display_state().blue(),\n JobStatus::Downloaded => self.display_state().green(),\n JobStatus::Cached => self.display_state().cyan(),\n JobStatus::Processing => self.display_state().yellow(),\n JobStatus::Installing => self.display_state().yellow(),\n JobStatus::Linking => self.display_state().yellow(),\n JobStatus::Success => self.display_state().green(),\n JobStatus::Failed => self.display_state().red(),\n }\n }\n}\n\nstruct JobInfo {\n name: String,\n status: JobStatus,\n size_bytes: Option,\n current_bytes_downloaded: Option,\n start_time: Option,\n pool_id: usize,\n}\n\nimpl JobInfo {\n fn _elapsed_str(&self) -> String {\n match self.start_time {\n Some(start) => format!(\"{:.1}s\", start.elapsed().as_secs_f64()),\n None => \"–\".to_string(),\n }\n }\n\n fn size_str(&self) -> String {\n match self.size_bytes {\n Some(bytes) => format_bytes(bytes),\n None => \"–\".to_string(),\n }\n }\n}\n\nstruct StatusDisplay {\n jobs: HashMap,\n job_order: Vec,\n total_jobs: usize,\n next_pool_id: usize,\n _start_time: Instant,\n active_downloads: HashSet,\n total_bytes: u64,\n downloaded_bytes: u64,\n last_speed_update: Instant,\n last_aggregate_bytes_snapshot: u64,\n current_speed_bps: f64,\n _speed_history: Vec,\n header_printed: bool,\n last_line_count: usize,\n}\n\nimpl StatusDisplay {\n fn new() -> Self {\n Self {\n jobs: HashMap::new(),\n job_order: Vec::new(),\n total_jobs: 0,\n next_pool_id: 1,\n _start_time: Instant::now(),\n active_downloads: HashSet::new(),\n total_bytes: 0,\n downloaded_bytes: 0,\n last_speed_update: Instant::now(),\n last_aggregate_bytes_snapshot: 0,\n current_speed_bps: 0.0,\n _speed_history: Vec::new(),\n header_printed: false,\n last_line_count: 0,\n }\n }\n\n fn add_job(&mut self, target_id: String, status: JobStatus, size_bytes: Option) {\n if !self.jobs.contains_key(&target_id) {\n let job_info = JobInfo {\n name: target_id.clone(),\n status,\n size_bytes,\n current_bytes_downloaded: if status == JobStatus::Downloading {\n Some(0)\n } else {\n None\n },\n start_time: if status != JobStatus::Waiting {\n Some(Instant::now())\n } else {\n None\n },\n pool_id: self.next_pool_id,\n };\n\n if let Some(bytes) = size_bytes {\n self.total_bytes += bytes;\n }\n\n if status == JobStatus::Downloading {\n self.active_downloads.insert(target_id.to_string());\n }\n\n self.jobs.insert(target_id.clone(), job_info);\n self.job_order.push(target_id);\n self.next_pool_id += 1;\n }\n }\n\n fn update_job_status(&mut self, target_id: &str, status: JobStatus, size_bytes: Option) {\n if let Some(job) = self.jobs.get_mut(target_id) {\n let was_downloading = job.status == JobStatus::Downloading;\n let is_downloading = status == JobStatus::Downloading;\n\n job.status = status;\n\n if job.start_time.is_none() && status != JobStatus::Waiting {\n job.start_time = Some(Instant::now());\n }\n\n if let Some(bytes) = size_bytes {\n if job.size_bytes.is_none() {\n self.total_bytes += bytes;\n }\n job.size_bytes = Some(bytes);\n }\n\n // Update download counts\n if was_downloading && !is_downloading {\n self.active_downloads.remove(target_id);\n if let Some(bytes) = job.size_bytes {\n job.current_bytes_downloaded = Some(bytes);\n self.downloaded_bytes += bytes;\n }\n } else if !was_downloading && is_downloading {\n self.active_downloads.insert(target_id.to_string());\n job.current_bytes_downloaded = Some(0);\n }\n }\n }\n\n fn update_download_progress(\n &mut self,\n target_id: &str,\n bytes_so_far: u64,\n total_size: Option,\n ) {\n if let Some(job) = self.jobs.get_mut(target_id) {\n job.current_bytes_downloaded = Some(bytes_so_far);\n\n if let Some(total) = total_size {\n if job.size_bytes.is_none() {\n // Update total bytes estimate\n self.total_bytes += total;\n job.size_bytes = Some(total);\n } else if job.size_bytes != Some(total) {\n // Adjust total bytes if estimate changed\n if let Some(old_size) = job.size_bytes {\n self.total_bytes = self.total_bytes.saturating_sub(old_size) + total;\n }\n job.size_bytes = Some(total);\n }\n }\n }\n }\n\n fn update_speed(&mut self) {\n let now = Instant::now();\n let time_diff = now.duration_since(self.last_speed_update).as_secs_f64();\n\n if time_diff >= 0.0625 {\n // Calculate current total bytes for all jobs with current download progress\n let current_active_bytes: u64 = self\n .jobs\n .values()\n .filter(|job| matches!(job.status, JobStatus::Downloading))\n .map(|job| job.current_bytes_downloaded.unwrap_or(0))\n .sum();\n\n // Calculate bytes difference since last update\n let bytes_diff =\n current_active_bytes.saturating_sub(self.last_aggregate_bytes_snapshot);\n\n // Calculate speed\n if time_diff > 0.0 && bytes_diff > 0 {\n self.current_speed_bps = bytes_diff as f64 / time_diff;\n } else if !self\n .jobs\n .values()\n .any(|job| job.status == JobStatus::Downloading)\n {\n // No active downloads, reset speed to 0\n self.current_speed_bps = 0.0;\n }\n // If no bytes diff but still have active downloads, keep previous speed\n\n self.last_speed_update = now;\n self.last_aggregate_bytes_snapshot = current_active_bytes;\n }\n }\n\n fn render(&mut self) {\n self.update_speed();\n\n if !self.header_printed {\n // First render - print header and jobs\n self.print_header();\n let job_output = self.build_job_rows();\n print!(\"{job_output}\");\n self.header_printed = true;\n // Count lines: header + jobs + separator + summary\n let job_lines = job_output.lines().count();\n self.last_line_count = 1 + job_lines + 1 + 1;\n } else {\n // Subsequent renders - clear and reprint header, job rows and summary\n self.clear_previous_output();\n self.print_header();\n let job_output = self.build_job_rows();\n print!(\"{job_output}\");\n // Update line count (header + jobs + separator)\n let job_lines = job_output.lines().count();\n self.last_line_count = 1 + job_lines + 1;\n }\n\n // Print separator\n println!(\"{}\", \"─\".repeat(49).dimmed());\n\n // Print status summary\n let completed = self\n .jobs\n .values()\n .filter(|j| matches!(j.status, JobStatus::Success))\n .count();\n let failed = self\n .jobs\n .values()\n .filter(|j| matches!(j.status, JobStatus::Failed))\n .count();\n let _progress_chars = self.generate_progress_bar(completed, failed);\n let _speed_str = format_speed(self.current_speed_bps);\n\n io::stdout().flush().unwrap();\n }\n\n fn print_header(&self) {\n println!(\n \"{:<6} {:<12} {:<15} {:>8} {}\",\n \"IID\".bold().dimmed(),\n \"STATE\".bold().dimmed(),\n \"PKG\".bold().dimmed(),\n \"SIZE\".bold().dimmed(),\n \"SLOT\".bold().dimmed()\n );\n }\n\n fn build_job_rows(&self) -> String {\n let mut output = String::new();\n\n // Job rows\n for target_id in &self.job_order {\n if let Some(job) = self.jobs.get(target_id) {\n let progress_str = if job.status == JobStatus::Downloading {\n match (job.current_bytes_downloaded, job.size_bytes) {\n (Some(downloaded), Some(_total)) => format_bytes(downloaded).to_string(),\n (Some(downloaded), None) => format_bytes(downloaded),\n _ => job.size_str(),\n }\n } else {\n job.size_str()\n };\n\n output.push_str(&format!(\n \"{:<6} {:<12} {:<15} {:>8} {}\\n\",\n format!(\"#{:02}\", job.pool_id).cyan(),\n job.status.colored_state(),\n job.name.cyan(),\n progress_str,\n job.status.slot_indicator()\n ));\n }\n }\n\n output\n }\n\n fn clear_previous_output(&self) {\n // Move cursor up and clear lines\n for _ in 0..self.last_line_count {\n print!(\"\\x1b[1A\\x1b[2K\"); // Move up one line and clear it\n }\n io::stdout().flush().unwrap();\n }\n\n fn generate_progress_bar(&self, completed: usize, failed: usize) -> String {\n if self.total_jobs == 0 {\n return \"\".to_string();\n }\n\n let total_done = completed + failed;\n let progress_width = 8;\n let filled = (total_done * progress_width) / self.total_jobs;\n let remaining = progress_width - filled;\n\n let filled_str = \"▍\".repeat(filled).green();\n let remaining_str = \"·\".repeat(remaining).dimmed();\n\n format!(\"{filled_str}{remaining_str}\")\n }\n}\n\nfn format_bytes(bytes: u64) -> String {\n const UNITS: &[&str] = &[\"B\", \"kB\", \"MB\", \"GB\"];\n let mut value = bytes as f64;\n let mut unit_idx = 0;\n\n while value >= 1000.0 && unit_idx < UNITS.len() - 1 {\n value /= 1000.0;\n unit_idx += 1;\n }\n\n if unit_idx == 0 {\n format!(\"{bytes}B\")\n } else {\n format!(\"{:.1}{}\", value, UNITS[unit_idx])\n }\n}\n\nfn format_speed(bytes_per_sec: f64) -> String {\n if bytes_per_sec < 1.0 {\n return \"0 B/s\".to_string();\n }\n\n const UNITS: &[&str] = &[\"B/s\", \"kB/s\", \"MB/s\", \"GB/s\"];\n let mut value = bytes_per_sec;\n let mut unit_idx = 0;\n\n while value >= 1000.0 && unit_idx < UNITS.len() - 1 {\n value /= 1000.0;\n unit_idx += 1;\n }\n\n format!(\"{:.1} {}\", value, UNITS[unit_idx])\n}\n\npub async fn handle_events(_config: Config, mut event_rx: broadcast::Receiver) {\n let mut display = StatusDisplay::new();\n let mut logs_buffer = Vec::new();\n let mut pipeline_active = false;\n let mut refresh_interval = tokio::time::interval(tokio::time::Duration::from_millis(62));\n refresh_interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);\n\n loop {\n tokio::select! {\n _ = refresh_interval.tick() => {\n if pipeline_active && display.header_printed {\n display.render();\n }\n }\n event_result = event_rx.recv() => {\n match event_result {\n Ok(event) => match event {\n PipelineEvent::PipelineStarted { total_jobs } => {\n pipeline_active = true;\n display.total_jobs = total_jobs;\n println!(\"{}\", \"Starting pipeline.\".cyan().bold());\n }\n PipelineEvent::PlanningStarted => {\n debug!(\"{}\", \"Planning operations.\".cyan());\n }\n PipelineEvent::DependencyResolutionStarted => {\n println!(\"{}\", \"Resolving dependencies\".cyan());\n }\n PipelineEvent::DependencyResolutionFinished => {\n debug!(\"{}\", \"Dependency resolution complete.\".cyan());\n }\n PipelineEvent::PlanningFinished { job_count } => {\n println!(\"{} {}\", \"Planning finished. Jobs:\".bold(), job_count);\n println!();\n }\n PipelineEvent::DownloadStarted { target_id, url: _ } => {\n display.add_job(target_id.clone(), JobStatus::Downloading, None);\n if pipeline_active {\n display.render();\n }\n }\n PipelineEvent::DownloadFinished {\n target_id,\n size_bytes,\n ..\n } => {\n display.update_job_status(&target_id, JobStatus::Downloaded, Some(size_bytes));\n if pipeline_active {\n display.render();\n }\n }\n PipelineEvent::DownloadProgressUpdate {\n target_id,\n bytes_so_far,\n total_size,\n } => {\n display.update_download_progress(&target_id, bytes_so_far, total_size);\n if pipeline_active {\n display.render();\n }\n }\n PipelineEvent::DownloadCached {\n target_id,\n size_bytes,\n } => {\n display.update_job_status(&target_id, JobStatus::Cached, Some(size_bytes));\n if pipeline_active {\n display.render();\n }\n }\n PipelineEvent::DownloadFailed {\n target_id, error, ..\n } => {\n display.update_job_status(&target_id, JobStatus::Failed, None);\n logs_buffer.push(format!(\n \"{} {}: {}\",\n \"Download failed:\".red(),\n target_id.cyan(),\n error.red()\n ));\n if pipeline_active {\n display.render();\n }\n }\n PipelineEvent::JobProcessingStarted { target_id } => {\n display.update_job_status(&target_id, JobStatus::Processing, None);\n if pipeline_active {\n display.render();\n }\n }\n PipelineEvent::BuildStarted { target_id } => {\n display.update_job_status(&target_id, JobStatus::Processing, None);\n if pipeline_active {\n display.render();\n }\n }\n PipelineEvent::InstallStarted { target_id, .. } => {\n display.update_job_status(&target_id, JobStatus::Installing, None);\n if pipeline_active {\n display.render();\n }\n }\n PipelineEvent::LinkStarted { target_id, .. } => {\n display.update_job_status(&target_id, JobStatus::Linking, None);\n if pipeline_active {\n display.render();\n }\n }\n PipelineEvent::JobSuccess {\n target_id,\n action,\n pkg_type,\n } => {\n display.update_job_status(&target_id, JobStatus::Success, None);\n let type_str = match pkg_type {\n PipelinePackageType::Formula => \"Formula\",\n PipelinePackageType::Cask => \"Cask\",\n };\n let action_str = match action {\n sps_common::pipeline::JobAction::Install => \"Installed\",\n sps_common::pipeline::JobAction::Upgrade { .. } => \"Upgraded\",\n sps_common::pipeline::JobAction::Reinstall { .. } => \"Reinstalled\",\n };\n logs_buffer.push(format!(\n \"{}: {} ({})\",\n action_str.green(),\n target_id.cyan(),\n type_str,\n ));\n if pipeline_active {\n display.render();\n }\n }\n PipelineEvent::JobFailed {\n target_id, error, ..\n } => {\n display.update_job_status(&target_id, JobStatus::Failed, None);\n logs_buffer.push(format!(\n \"{} {}: {}\",\n \"✗\".red().bold(),\n target_id.cyan(),\n error.red()\n ));\n if pipeline_active {\n display.render();\n }\n }\n PipelineEvent::LogInfo { message } => {\n logs_buffer.push(message);\n }\n PipelineEvent::LogWarn { message } => {\n logs_buffer.push(message.yellow().to_string());\n }\n PipelineEvent::LogError { message } => {\n logs_buffer.push(message.red().to_string());\n }\n PipelineEvent::PipelineFinished {\n duration_secs,\n success_count,\n fail_count,\n } => {\n if display.header_printed {\n display.render();\n }\n\n println!();\n\n println!(\n \"{} in {:.2}s ({} succeeded, {} failed)\",\n \"Pipeline finished\".bold(),\n duration_secs,\n success_count,\n fail_count\n );\n\n if !logs_buffer.is_empty() {\n println!();\n for log in &logs_buffer {\n println!(\"{log}\");\n }\n }\n\n break;\n }\n _ => {}\n },\n Err(broadcast::error::RecvError::Closed) => {\n break;\n }\n Err(broadcast::error::RecvError::Lagged(_)) => {\n // Ignore lag for now\n }\n }\n }\n }\n }\n}\n"], ["/sps/sps-core/src/uninstall/formula.rs", "// sps-core/src/uninstall/formula.rs\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse tracing::{debug, error, warn};\n\nuse crate::check::installed::InstalledPackageInfo;\nuse crate::install; // For install::bottle::link\nuse crate::uninstall::common::{remove_filesystem_artifact, UninstallOptions};\n\npub fn uninstall_formula_artifacts(\n info: &InstalledPackageInfo,\n config: &Config,\n _options: &UninstallOptions, /* options currently unused for formula but kept for signature\n * consistency */\n) -> Result<()> {\n debug!(\n \"Uninstalling Formula artifacts for {} version {}\",\n info.name, info.version\n );\n\n // 1. Unlink artifacts\n // This function should handle removal of symlinks from /opt/sps/bin, /opt/sps/lib etc.\n // and the /opt/sps/opt/formula_name link.\n install::bottle::link::unlink_formula_artifacts(&info.name, &info.version, config)?;\n\n // 2. Remove the keg directory\n if info.path.exists() {\n debug!(\"Removing formula keg directory: {}\", info.path.display());\n // For formula kegs, we generally expect them to be owned by the user or sps,\n // but sudo might be involved if permissions were changed manually or during a problematic\n // install. Setting use_sudo to true provides a fallback, though ideally it's not\n // needed for user-owned kegs.\n let use_sudo = true;\n if !remove_filesystem_artifact(&info.path, use_sudo) {\n // Check if it still exists after the removal attempt\n if info.path.exists() {\n error!(\n \"Failed remove keg {}: Check logs for sudo errors or other filesystem issues.\",\n info.path.display()\n );\n return Err(SpsError::InstallError(format!(\n \"Failed to remove keg directory: {}\",\n info.path.display()\n )));\n } else {\n // It means remove_filesystem_artifact returned false but the dir is gone\n // (possibly removed by sudo, or a race condition if another process removed it)\n debug!(\"Keg directory successfully removed (possibly with sudo).\");\n }\n }\n } else {\n warn!(\n \"Keg directory {} not found during uninstall. It might have been already removed.\",\n info.path.display()\n );\n }\n Ok(())\n}\n"], ["/sps/sps-core/src/upgrade/bottle.rs", "// sps-core/src/upgrade/bottle.rs\n\nuse std::path::{Path, PathBuf};\nuse std::sync::Arc;\n\nuse sps_common::config::Config;\nuse sps_common::error::{Result as SpsResult, SpsError};\nuse sps_common::model::formula::Formula;\nuse tracing::{debug, error};\n\nuse crate::check::installed::InstalledPackageInfo;\nuse crate::{install, uninstall};\n\n/// Upgrades a formula that is installed from a bottle.\n///\n/// This involves:\n/// 1. Uninstalling the old version of the formula.\n/// 2. Installing the new bottle.\n/// 3. Linking the new version.\npub async fn upgrade_bottle_formula(\n formula: &Formula,\n new_bottle_download_path: &Path,\n old_install_info: &InstalledPackageInfo,\n config: &Config,\n http_client: Arc, /* Added for download_bottle if needed, though path is\n * pre-downloaded */\n) -> SpsResult {\n debug!(\n \"Upgrading bottle formula {} from {} to {}\",\n formula.name(),\n old_install_info.version,\n formula.version_str_full()\n );\n\n // 1. Uninstall the old version\n debug!(\n \"Uninstalling old bottle version: {} at {}\",\n old_install_info.version,\n old_install_info.path.display()\n );\n let uninstall_opts = uninstall::UninstallOptions { skip_zap: true }; // Zap is not relevant for formula upgrades\n uninstall::formula::uninstall_formula_artifacts(old_install_info, config, &uninstall_opts)\n .map_err(|e| {\n error!(\n \"Failed to uninstall old version {} of formula {}: {}\",\n old_install_info.version,\n formula.name(),\n e\n );\n SpsError::InstallError(format!(\n \"Failed to uninstall old version during upgrade of {}: {e}\",\n formula.name()\n ))\n })?;\n debug!(\"Successfully uninstalled old version of {}\", formula.name());\n\n // 2. Install the new bottle\n // The new_bottle_download_path is already provided, so we call install_bottle directly.\n // If download was part of this function, http_client would be used.\n let _ = http_client; // Mark as used if not directly needed by install_bottle\n\n debug!(\n \"Installing new bottle for {} from {}\",\n formula.name(),\n new_bottle_download_path.display()\n );\n let installed_keg_path =\n install::bottle::exec::install_bottle(new_bottle_download_path, formula, config).map_err(\n |e| {\n error!(\n \"Failed to install new bottle for formula {}: {}\",\n formula.name(),\n e\n );\n SpsError::InstallError(format!(\n \"Failed to install new bottle during upgrade of {}: {e}\",\n formula.name()\n ))\n },\n )?;\n debug!(\n \"Successfully installed new bottle for {} to {}\",\n formula.name(),\n installed_keg_path.display()\n );\n\n // 3. Link the new version (linking is handled by the worker after this function returns the\n // path)\n // The install::bottle::exec::install_bottle writes the receipt, but linking is separate.\n // The worker will call link_formula_artifacts after this.\n\n Ok(installed_keg_path)\n}\n"], ["/sps/sps-common/src/cache.rs", "// src/utils/cache.rs\n// Handles caching of formula data and downloads\n\nuse std::fs;\nuse std::path::{Path, PathBuf};\nuse std::time::{Duration, SystemTime};\n\nuse super::error::{Result, SpsError};\nuse crate::Config;\n\n/// Define how long cache entries are considered valid\nconst CACHE_TTL: Duration = Duration::from_secs(24 * 60 * 60); // 24 hours\n\n/// Cache struct to manage cache operations\npub struct Cache {\n cache_dir: PathBuf,\n _config: Config, // Keep a reference to config if needed for other paths or future use\n}\n\nimpl Cache {\n /// Create a new Cache using the config's cache_dir\n pub fn new(config: &Config) -> Result {\n let cache_dir = config.cache_dir();\n if !cache_dir.exists() {\n fs::create_dir_all(&cache_dir)?;\n }\n\n Ok(Self {\n cache_dir,\n _config: config.clone(),\n })\n }\n\n /// Gets the cache directory path\n pub fn get_dir(&self) -> &Path {\n &self.cache_dir\n }\n\n /// Stores raw string data in the cache\n pub fn store_raw(&self, filename: &str, data: &str) -> Result<()> {\n let path = self.cache_dir.join(filename);\n tracing::debug!(\"Saving raw data to cache file: {:?}\", path);\n fs::write(&path, data)?;\n Ok(())\n }\n\n /// Loads raw string data from the cache\n pub fn load_raw(&self, filename: &str) -> Result {\n let path = self.cache_dir.join(filename);\n tracing::debug!(\"Loading raw data from cache file: {:?}\", path);\n\n if !path.exists() {\n return Err(SpsError::Cache(format!(\n \"Cache file {filename} does not exist\"\n )));\n }\n\n fs::read_to_string(&path).map_err(|e| SpsError::Cache(format!(\"IO error: {e}\")))\n }\n\n /// Checks if a cache file exists and is valid (within TTL)\n pub fn is_cache_valid(&self, filename: &str) -> Result {\n let path = self.cache_dir.join(filename);\n if !path.exists() {\n return Ok(false);\n }\n\n let metadata = fs::metadata(&path)?;\n let modified_time = metadata.modified()?;\n let age = SystemTime::now()\n .duration_since(modified_time)\n .map_err(|e| SpsError::Cache(format!(\"System time error: {e}\")))?;\n\n Ok(age <= CACHE_TTL)\n }\n\n /// Clears a specific cache file\n pub fn clear_file(&self, filename: &str) -> Result<()> {\n let path = self.cache_dir.join(filename);\n if path.exists() {\n fs::remove_file(&path)?;\n }\n Ok(())\n }\n\n /// Clears all cache files\n pub fn clear_all(&self) -> Result<()> {\n if self.cache_dir.exists() {\n fs::remove_dir_all(&self.cache_dir)?;\n fs::create_dir_all(&self.cache_dir)?;\n }\n Ok(())\n }\n\n /// Gets a reference to the config\n pub fn config(&self) -> &Config {\n &self._config\n }\n}\n"], ["/sps/sps-common/src/model/tap.rs", "// tap/tap.rs - Basic tap functionality // Should probably be in model module\n\nuse std::path::PathBuf;\n\nuse tracing::debug;\n\nuse crate::error::{Result, SpsError};\n\n/// Represents a source of packages (formulas and casks)\npub struct Tap {\n /// The user part of the tap name (e.g., \"homebrew\" in \"homebrew/core\")\n pub user: String,\n\n /// The repository part of the tap name (e.g., \"core\" in \"homebrew/core\")\n pub repo: String,\n\n /// The full path to the tap directory\n pub path: PathBuf,\n}\n\nimpl Tap {\n /// Create a new tap from user/repo format\n pub fn new(name: &str) -> Result {\n let parts: Vec<&str> = name.split('/').collect();\n if parts.len() != 2 {\n return Err(SpsError::Generic(format!(\"Invalid tap name: {name}\")));\n }\n let user = parts[0].to_string();\n let repo = parts[1].to_string();\n let prefix = if cfg!(target_arch = \"aarch64\") {\n PathBuf::from(\"/opt/homebrew\")\n } else {\n PathBuf::from(\"/usr/local\")\n };\n let path = prefix\n .join(\"Library/Taps\")\n .join(&user)\n .join(format!(\"homebrew-{repo}\"));\n Ok(Self { user, repo, path })\n }\n\n /// Update this tap by pulling latest changes\n pub fn update(&self) -> Result<()> {\n use git2::{FetchOptions, Repository};\n\n let repo = Repository::open(&self.path)\n .map_err(|e| SpsError::Generic(format!(\"Failed to open tap repository: {e}\")))?;\n\n // Fetch updates from origin\n let mut remote = repo\n .find_remote(\"origin\")\n .map_err(|e| SpsError::Generic(format!(\"Failed to find remote 'origin': {e}\")))?;\n\n let mut fetch_options = FetchOptions::new();\n remote\n .fetch(\n &[\"refs/heads/*:refs/heads/*\"],\n Some(&mut fetch_options),\n None,\n )\n .map_err(|e| SpsError::Generic(format!(\"Failed to fetch updates: {e}\")))?;\n\n // Merge changes\n let fetch_head = repo\n .find_reference(\"FETCH_HEAD\")\n .map_err(|e| SpsError::Generic(format!(\"Failed to find FETCH_HEAD: {e}\")))?;\n\n let fetch_commit = repo\n .reference_to_annotated_commit(&fetch_head)\n .map_err(|e| SpsError::Generic(format!(\"Failed to get commit from FETCH_HEAD: {e}\")))?;\n\n let analysis = repo\n .merge_analysis(&[&fetch_commit])\n .map_err(|e| SpsError::Generic(format!(\"Failed to analyze merge: {e}\")))?;\n\n if analysis.0.is_up_to_date() {\n debug!(\"Already up-to-date\");\n return Ok(());\n }\n\n if analysis.0.is_fast_forward() {\n let mut reference = repo\n .find_reference(\"refs/heads/master\")\n .map_err(|e| SpsError::Generic(format!(\"Failed to find master branch: {e}\")))?;\n reference\n .set_target(fetch_commit.id(), \"Fast-forward\")\n .map_err(|e| SpsError::Generic(format!(\"Failed to fast-forward: {e}\")))?;\n repo.set_head(\"refs/heads/master\")\n .map_err(|e| SpsError::Generic(format!(\"Failed to set HEAD: {e}\")))?;\n repo.checkout_head(Some(git2::build::CheckoutBuilder::default().force()))\n .map_err(|e| SpsError::Generic(format!(\"Failed to checkout: {e}\")))?;\n } else {\n return Err(SpsError::Generic(\n \"Tap requires merge but automatic merging is not implemented\".to_string(),\n ));\n }\n\n Ok(())\n }\n\n /// Remove this tap by deleting its local repository\n pub fn remove(&self) -> Result<()> {\n if !self.path.exists() {\n return Err(SpsError::NotFound(format!(\n \"Tap {} is not installed\",\n self.full_name()\n )));\n }\n debug!(\"Removing tap {}\", self.full_name());\n std::fs::remove_dir_all(&self.path).map_err(|e| {\n SpsError::Generic(format!(\"Failed to remove tap {}: {}\", self.full_name(), e))\n })\n }\n\n /// Get the full name of the tap (user/repo)\n pub fn full_name(&self) -> String {\n format!(\"{}/{}\", self.user, self.repo)\n }\n\n /// Check if this tap is installed locally\n pub fn is_installed(&self) -> bool {\n self.path.exists()\n }\n}\n"], ["/sps/sps-common/src/model/artifact.rs", "// sps-common/src/model/artifact.rs\nuse std::path::PathBuf;\n\nuse serde::{Deserialize, Serialize};\n\n/// Represents an item installed or managed by sps, recorded in the manifest.\n#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)] // Added Hash\n#[serde(tag = \"type\", rename_all = \"snake_case\")]\npub enum InstalledArtifact {\n /// The main application bundle (e.g., in /Applications).\n AppBundle { path: PathBuf },\n /// A command-line binary symlinked into the prefix's bin dir.\n BinaryLink {\n link_path: PathBuf,\n target_path: PathBuf,\n },\n /// A man page symlinked into the prefix's man dir.\n ManpageLink {\n link_path: PathBuf,\n target_path: PathBuf,\n },\n /// A resource moved to a standard system/user location (e.g., Font, PrefPane).\n MovedResource { path: PathBuf },\n /// A macOS package receipt ID managed by pkgutil.\n PkgUtilReceipt { id: String },\n /// A launchd service (Agent/Daemon).\n Launchd {\n label: String,\n path: Option,\n }, // Path is the plist file\n /// A symlink created within the Caskroom pointing to the actual installed artifact.\n /// Primarily for internal reference and potentially easier cleanup if needed.\n CaskroomLink {\n link_path: PathBuf,\n target_path: PathBuf,\n },\n /// A file copied *into* the Caskroom (e.g., a .pkg installer).\n CaskroomReference { path: PathBuf },\n}\n\n// Optional: Helper methods if needed\n// impl InstalledArtifact { ... }\n"], ["/sps/sps-core/src/upgrade/source.rs", "// sps-core/src/upgrade/source.rs\n\nuse std::path::{Path, PathBuf};\n\nuse sps_common::config::Config;\nuse sps_common::error::{Result as SpsResult, SpsError};\nuse sps_common::model::formula::Formula;\nuse tracing::{debug, error};\n\nuse crate::check::installed::InstalledPackageInfo;\nuse crate::{build, uninstall};\n\n/// Upgrades a formula that was/will be installed from source.\n///\n/// This involves:\n/// 1. Uninstalling the old version of the formula.\n/// 2. Building and installing the new version from source.\n/// 3. Linking the new version.\npub async fn upgrade_source_formula(\n formula: &Formula,\n new_source_download_path: &Path,\n old_install_info: &InstalledPackageInfo,\n config: &Config,\n all_installed_dependency_paths: &[PathBuf], // For build environment\n) -> SpsResult {\n debug!(\n \"Upgrading source-built formula {} from {} to {}\",\n formula.name(),\n old_install_info.version,\n formula.version_str_full()\n );\n\n // 1. Uninstall the old version\n debug!(\n \"Uninstalling old source-built version: {} at {}\",\n old_install_info.version,\n old_install_info.path.display()\n );\n let uninstall_opts = uninstall::UninstallOptions { skip_zap: true };\n uninstall::formula::uninstall_formula_artifacts(old_install_info, config, &uninstall_opts)\n .map_err(|e| {\n error!(\n \"Failed to uninstall old version {} of formula {}: {}\",\n old_install_info.version,\n formula.name(),\n e\n );\n SpsError::InstallError(format!(\n \"Failed to uninstall old version during source upgrade of {}: {e}\",\n formula.name()\n ))\n })?;\n debug!(\n \"Successfully uninstalled old source-built version of {}\",\n formula.name()\n );\n\n // 2. Build and install the new version from source\n debug!(\n \"Building new version of {} from source path {}\",\n formula.name(),\n new_source_download_path.display()\n );\n let installed_keg_path = build::compile::build_from_source(\n new_source_download_path,\n formula,\n config,\n all_installed_dependency_paths,\n )\n .await\n .map_err(|e| {\n error!(\n \"Failed to build new version of formula {} from source: {}\",\n formula.name(),\n e\n );\n SpsError::InstallError(format!(\n \"Failed to build new version from source during upgrade of {}: {e}\",\n formula.name()\n ))\n })?;\n debug!(\n \"Successfully built and installed new version of {} to {}\",\n formula.name(),\n installed_keg_path.display()\n );\n\n // 3. Linking is handled by the worker after this function returns the path.\n\n Ok(installed_keg_path)\n}\n"], ["/sps/sps-net/src/validation.rs", "// sps-io/src/checksum.rs\n//use std::sync::Arc;\nuse std::fs::File;\nuse std::io;\nuse std::path::Path;\n\nuse infer;\nuse sha2::{Digest, Sha256};\nuse sps_common::error::{Result, SpsError};\nuse url::Url;\n//use tokio::fs::File;\n//use tokio::io::AsyncReadExt;\n//use tracing::debug; // Use tracing\n\n///// Asynchronously verifies the SHA256 checksum of a file.\n///// Reads the file asynchronously but performs hashing synchronously.\n//pub async fn verify_checksum_async(path: &Path, expected: &str) -> Result<()> {\n//debug!(\"Async Verifying checksum for: {}\", path.display());\n// let file = File::open(path).await;\n// let mut file = match file {\n// Ok(f) => f,\n// Err(e) => {\n// return Err(SpsError::Io(Arc::new(e))); // Wrap IO error\n// }\n// };\n//\n// let mut hasher = Sha256::new();\n// let mut buffer = Vec::with_capacity(8192); // Use a Vec as buffer for read_buf\n// let mut total_bytes_read = 0;\n//\n// loop {\n// buffer.clear();\n// match file.read_buf(&mut buffer).await {\n// Ok(0) => break, // End of file\n// Ok(n) => {\n// hasher.update(&buffer[..n]);\n// total_bytes_read += n as u64;\n// }\n// Err(e) => {\n// return Err(SpsError::Io(Arc::new(e))); // Wrap IO error\n// }\n// }\n// }\n//\n// let hash_bytes = hasher.finalize();\n// let actual = hex::encode(hash_bytes);\n//\n// debug!(\n// \"Async Calculated SHA256: {} ({} bytes read)\",\n// actual, total_bytes_read\n// );\n// debug!(\"Expected SHA256: {}\", expected);\n//\n// if actual.eq_ignore_ascii_case(expected) {\n// Ok(())\n// } else {\n// Err(SpsError::ChecksumError(format!(\n// \"Checksum mismatch for {}: expected {}, got {}\",\n// path.display(),\n// expected,\n// actual\n// )))\n// }\n//}\n\n// Keep the synchronous version for now if needed elsewhere or for comparison\npub fn verify_checksum(path: &Path, expected: &str) -> Result<()> {\n tracing::debug!(\"Verifying checksum for: {}\", path.display());\n let mut file = File::open(path)?;\n let mut hasher = Sha256::new();\n let bytes_copied = io::copy(&mut file, &mut hasher)?;\n let hash_bytes = hasher.finalize();\n let actual = hex::encode(hash_bytes);\n tracing::debug!(\n \"Calculated SHA256: {} ({} bytes read)\",\n actual,\n bytes_copied\n );\n tracing::debug!(\"Expected SHA256: {}\", expected);\n if actual.eq_ignore_ascii_case(expected) {\n Ok(())\n } else {\n Err(SpsError::ChecksumError(format!(\n \"Checksum mismatch for {}: expected {}, got {}\",\n path.display(),\n expected,\n actual\n )))\n }\n}\n\n/// Verifies that the detected content type of the file matches the expected extension.\npub fn verify_content_type(path: &Path, expected_ext: &str) -> Result<()> {\n let kind_opt = infer::get_from_path(path)?;\n if let Some(kind) = kind_opt {\n let actual_ext = kind.extension();\n if actual_ext.eq_ignore_ascii_case(expected_ext) {\n tracing::debug!(\n \"Content type verified: {} matches expected {}\",\n actual_ext,\n expected_ext\n );\n Ok(())\n } else {\n Err(SpsError::Generic(format!(\n \"Content type mismatch for {}: expected extension '{}', but detected '{}'\",\n path.display(),\n expected_ext,\n actual_ext\n )))\n }\n } else {\n Err(SpsError::Generic(format!(\n \"Could not determine content type for {}\",\n path.display()\n )))\n }\n}\n\n/// Validates a URL, ensuring it uses the HTTPS scheme.\npub fn validate_url(url_str: &str) -> Result<()> {\n let url = Url::parse(url_str)\n .map_err(|e| SpsError::Generic(format!(\"Failed to parse URL '{url_str}': {e}\")))?;\n if url.scheme() == \"https\" {\n Ok(())\n } else {\n Err(SpsError::ValidationError(format!(\n \"Invalid URL scheme for '{}': Must be https, but got '{}'\",\n url_str,\n url.scheme()\n )))\n }\n}\n"], ["/sps/sps/src/cli/install.rs", "// sps-cli/src/cli/install.rs\n\nuse std::sync::Arc;\n\nuse clap::Args;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse tracing::instrument;\n\n// Import pipeline components from the new module\nuse crate::pipeline::runner::{self, CommandType, PipelineFlags};\n\n// Keep the Args struct specific to 'install' if needed, or reuse a common one\n#[derive(Debug, Args)]\npub struct InstallArgs {\n #[arg(required = true)]\n names: Vec,\n\n // Keep flags relevant to install/pipeline\n #[arg(long)]\n skip_deps: bool, // Note: May not be fully supported by core resolution yet\n #[arg(long, help = \"Force install specified targets as casks\")]\n cask: bool,\n #[arg(long, help = \"Force install specified targets as formulas\")]\n formula: bool,\n #[arg(long)]\n include_optional: bool,\n #[arg(long)]\n skip_recommended: bool,\n #[arg(\n long,\n help = \"Force building the formula from source, even if a bottle is available\"\n )]\n build_from_source: bool,\n // Worker/Queue size flags might belong here or be global CLI flags\n // #[arg(long, value_name = \"sps_WORKERS\")]\n // max_workers: Option,\n // #[arg(long, value_name = \"sps_QUEUE\")]\n // queue_size: Option,\n}\n\nimpl InstallArgs {\n #[instrument(skip(self, config, cache), fields(targets = ?self.names))]\n pub async fn run(&self, config: &Config, cache: Arc) -> Result<()> {\n // --- Argument Validation (moved from old run) ---\n if self.formula && self.cask {\n return Err(sps_common::error::SpsError::Generic(\n \"Cannot use --formula and --cask together.\".to_string(),\n ));\n }\n // Add validation for skip_deps if needed\n\n // --- Prepare Pipeline Flags ---\n let flags = PipelineFlags {\n build_from_source: self.build_from_source,\n include_optional: self.include_optional,\n skip_recommended: self.skip_recommended,\n // Add other flags...\n };\n\n // --- Determine Initial Targets based on --formula/--cask flags ---\n // (This logic might be better inside plan_package_operations based on CommandType)\n let initial_targets = self.names.clone(); // For install, all names are initial targets\n\n // --- Execute the Pipeline ---\n runner::run_pipeline(\n &initial_targets,\n CommandType::Install, // Specify the command type\n config,\n cache,\n &flags, // Pass the flags struct\n )\n .await\n }\n}\n"], ["/sps/sps-common/src/formulary.rs", "use std::collections::HashMap;\nuse std::sync::Arc;\n\nuse tracing::debug;\n\nuse super::cache::Cache;\nuse super::config::Config;\nuse super::error::{Result, SpsError};\nuse super::model::formula::Formula;\n\n#[derive()]\npub struct Formulary {\n cache: Cache,\n parsed_cache: std::sync::Mutex>>,\n}\n\nimpl Formulary {\n pub fn new(config: Config) -> Self {\n let cache = Cache::new(&config).unwrap_or_else(|e| {\n panic!(\"Failed to initialize cache in Formulary: {e}\");\n });\n Self {\n cache,\n parsed_cache: std::sync::Mutex::new(HashMap::new()),\n }\n }\n\n pub fn load_formula(&self, name: &str) -> Result {\n let mut parsed_cache_guard = self.parsed_cache.lock().unwrap();\n if let Some(formula_arc) = parsed_cache_guard.get(name) {\n debug!(\"Loaded formula '{}' from parsed cache.\", name);\n return Ok(Arc::clone(formula_arc).as_ref().clone());\n }\n drop(parsed_cache_guard);\n\n let raw_data = self.cache.load_raw(\"formula.json\")?;\n let all_formulas: Vec = serde_json::from_str(&raw_data)\n .map_err(|e| SpsError::Cache(format!(\"Failed to parse cached formula data: {e}\")))?;\n debug!(\"Parsed {} formulas.\", all_formulas.len());\n\n let mut found_formula: Option = None;\n parsed_cache_guard = self.parsed_cache.lock().unwrap();\n for formula in all_formulas {\n let formula_name = formula.name.clone();\n let formula_arc = std::sync::Arc::new(formula);\n\n if formula_name == name {\n found_formula = Some(Arc::clone(&formula_arc).as_ref().clone());\n }\n\n parsed_cache_guard\n .entry(formula_name)\n .or_insert(formula_arc);\n }\n\n match found_formula {\n Some(f) => {\n debug!(\n \"Successfully loaded formula '{}' version {}\",\n f.name,\n f.version_str_full()\n );\n Ok(f)\n }\n None => {\n debug!(\n \"Formula '{}' not found within the cached formula data.\",\n name\n );\n Err(SpsError::Generic(format!(\n \"Formula '{name}' not found in cache.\"\n )))\n }\n }\n }\n}\n"], ["/sps/sps/src/cli/update.rs", "//! Contains the logic for the `update` command.\nuse std::fs;\nuse std::sync::Arc;\n\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_net::api;\n\n#[derive(clap::Args, Debug)]\npub struct Update;\n\nimpl Update {\n pub async fn run(&self, config: &Config, cache: Arc) -> Result<()> {\n tracing::debug!(\"Running manual update...\"); // Log clearly it's the manual one\n\n // Use the ui utility function to create the spinner\n println!(\"Updating package lists\"); // <-- CHANGED\n\n tracing::debug!(\"Using cache directory: {:?}\", config.cache_dir());\n\n // Fetch and store raw formula data\n match api::fetch_all_formulas().await {\n Ok(raw_data) => {\n cache.store_raw(\"formula.json\", &raw_data)?;\n tracing::debug!(\"✓ Successfully cached formulas data\");\n println!(\"Cached formulas data\");\n }\n Err(e) => {\n let err_msg = format!(\"Failed to fetch/store formulas from API: {e}\");\n tracing::error!(\"{}\", err_msg);\n println!(); // Clear spinner on error\n return Err(e);\n }\n }\n\n // Fetch and store raw cask data\n match api::fetch_all_casks().await {\n Ok(raw_data) => {\n cache.store_raw(\"cask.json\", &raw_data)?;\n tracing::debug!(\"✓ Successfully cached casks data\");\n println!(\"Cached casks data\");\n }\n Err(e) => {\n let err_msg = format!(\"Failed to fetch/store casks from API: {e}\");\n tracing::error!(\"{}\", err_msg);\n return Err(e);\n }\n }\n\n // Update timestamp file\n let timestamp_file = config.state_dir().join(\".sps_last_update_check\");\n tracing::debug!(\n \"Manual update successful. Updating timestamp file: {}\",\n timestamp_file.display()\n );\n match fs::File::create(×tamp_file) {\n Ok(_) => {\n tracing::debug!(\"Updated timestamp file successfully.\");\n }\n Err(e) => {\n tracing::warn!(\n \"Failed to create or update timestamp file '{}': {}\",\n timestamp_file.display(),\n e\n );\n }\n }\n\n println!(\"Update completed successfully!\");\n Ok(())\n }\n}\n"], ["/sps/sps-common/src/model/version.rs", "// **File:** sps-core/src/model/version.rs (New file)\nuse std::fmt;\nuse std::str::FromStr;\n\nuse serde::{Deserialize, Deserializer, Serialize, Serializer};\n\nuse crate::error::{Result, SpsError};\n\n/// Wrapper around semver::Version for formula versions.\n#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]\npub struct Version(semver::Version);\n\nimpl Version {\n pub fn parse(s: &str) -> Result {\n // Attempt standard semver parse first\n semver::Version::parse(s).map(Version).or_else(|_| {\n // Homebrew often uses versions like \"1.2.3_1\" (revision) or just \"123\"\n // Try to handle these by stripping suffixes or padding\n // This is a simplified handling, Homebrew's PkgVersion is complex\n let cleaned = s.split('_').next().unwrap_or(s); // Take part before _\n let parts: Vec<&str> = cleaned.split('.').collect();\n let padded = match parts.len() {\n 1 => format!(\"{}.0.0\", parts[0]),\n 2 => format!(\"{}.{}.0\", parts[0], parts[1]),\n _ => cleaned.to_string(), // Use original if 3+ parts\n };\n semver::Version::parse(&padded).map(Version).map_err(|e| {\n SpsError::VersionError(format!(\n \"Failed to parse version '{s}' (tried '{padded}'): {e}\"\n ))\n })\n })\n }\n}\n\nimpl FromStr for Version {\n type Err = SpsError;\n fn from_str(s: &str) -> std::result::Result {\n Self::parse(s)\n }\n}\n\nimpl fmt::Display for Version {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n // TODO: Preserve original format if possible? PkgVersion complexity.\n // For now, display the parsed semver representation.\n write!(f, \"{}\", self.0)\n }\n}\n\n// Manual Serialize/Deserialize to handle the Version<->String conversion\nimpl Serialize for Version {\n fn serialize(&self, serializer: S) -> std::result::Result\n where\n S: Serializer,\n {\n serializer.serialize_str(&self.to_string())\n }\n}\n\nimpl AsRef for Version {\n fn as_ref(&self) -> &Self {\n self\n }\n}\n\n// Removed redundant ToString implementation as it conflicts with the blanket implementation in std.\n\nimpl From for semver::Version {\n fn from(version: Version) -> Self {\n version.0\n }\n}\n\nimpl<'de> Deserialize<'de> for Version {\n fn deserialize(deserializer: D) -> std::result::Result\n where\n D: Deserializer<'de>,\n {\n let s = String::deserialize(deserializer)?;\n Self::from_str(&s).map_err(serde::de::Error::custom)\n }\n}\n\n// Add to sps-core/src/utils/error.rs:\n// #[error(\"Version error: {0}\")]\n// VersionError(String),\n\n// Add to sps-core/Cargo.toml:\n// [dependencies]\n// semver = \"1.0\"\n"], ["/sps/sps-core/src/pipeline/engine.rs", "use std::sync::atomic::{AtomicUsize, Ordering};\nuse std::sync::Arc;\n\nuse crossbeam_channel::Receiver as CrossbeamReceiver;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::error::Result as SpsResult;\nuse sps_common::pipeline::{PipelineEvent, WorkerJob};\nuse threadpool::ThreadPool;\nuse tokio::sync::broadcast;\nuse tracing::{debug, instrument};\n\nuse super::worker;\n\n#[instrument(skip_all, name = \"core_worker_manager\")]\npub fn start_worker_pool_manager(\n config: Config,\n cache: Arc,\n worker_job_rx: CrossbeamReceiver,\n event_tx: broadcast::Sender,\n success_count: Arc,\n fail_count: Arc,\n) -> SpsResult<()> {\n let num_workers = std::cmp::max(1, num_cpus::get_physical().saturating_sub(1)).min(6);\n let pool = ThreadPool::new(num_workers);\n debug!(\n \"Core worker pool manager started with {} workers.\",\n num_workers\n );\n debug!(\"Worker pool created.\");\n\n for worker_job in worker_job_rx {\n let job_id = worker_job.request.target_id.clone();\n debug!(\n \"[{}] Received job from channel, preparing to submit to pool.\",\n job_id\n );\n\n let config_clone = config.clone();\n let cache_clone = Arc::clone(&cache);\n let event_tx_clone = event_tx.clone();\n let success_count_clone = Arc::clone(&success_count);\n let fail_count_clone = Arc::clone(&fail_count);\n\n let _ = event_tx_clone.send(PipelineEvent::JobProcessingStarted {\n target_id: job_id.clone(),\n });\n\n debug!(\"[{}] Submitting job to worker pool.\", job_id);\n\n pool.execute(move || {\n let job_result = worker::execute_sync_job(\n worker_job,\n &config_clone,\n cache_clone,\n event_tx_clone.clone(),\n );\n let job_id_for_log = job_id.clone();\n debug!(\n \"[{}] Worker job execution finished (execute_sync_job returned), result ok: {}\",\n job_id_for_log,\n job_result.is_ok()\n );\n\n let job_id_for_log = job_id.clone();\n match job_result {\n Ok((final_action, pkg_type)) => {\n success_count_clone.fetch_add(1, Ordering::Relaxed);\n debug!(\"[{}] Worker finished successfully.\", job_id);\n let _ = event_tx_clone.send(PipelineEvent::JobSuccess {\n target_id: job_id,\n action: final_action,\n pkg_type,\n });\n debug!(\"[{}] Worker result event sent.\", job_id_for_log);\n }\n Err(boxed) => {\n let (final_action, err) = *boxed;\n fail_count_clone.fetch_add(1, Ordering::Relaxed);\n // Error is sent via JobFailed event and displayed in status.rs\n let _ = event_tx_clone.send(PipelineEvent::JobFailed {\n target_id: job_id,\n action: final_action,\n error: err.to_string(),\n });\n debug!(\"[{}] Worker result event sent.\", job_id_for_log);\n }\n }\n debug!(\"[{}] Worker closure scope ending.\", job_id_for_log);\n });\n }\n pool.join();\n Ok(())\n}\n"], ["/sps/sps/src/cli/upgrade.rs", "use std::sync::Arc;\n\nuse clap::Args;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_core::check::installed;\n\nuse crate::pipeline::runner::{self, CommandType, PipelineFlags};\n\n#[derive(Args, Debug)]\npub struct UpgradeArgs {\n #[arg()]\n pub names: Vec,\n\n #[arg(long, conflicts_with = \"names\")]\n pub all: bool,\n\n #[arg(long)]\n pub build_from_source: bool,\n}\n\nimpl UpgradeArgs {\n pub async fn run(&self, config: &Config, cache: Arc) -> Result<()> {\n let targets = if self.all {\n // Get all installed package names\n let installed = installed::get_installed_packages(config).await?;\n installed.into_iter().map(|p| p.name).collect()\n } else {\n self.names.clone()\n };\n\n if targets.is_empty() {\n return Ok(());\n }\n\n let flags = PipelineFlags {\n // Populate flags from args\n build_from_source: self.build_from_source,\n // Upgrade should respect original install options ideally,\n // but for now let's default them. This could be enhanced later\n // by reading install receipts.\n include_optional: false,\n skip_recommended: false,\n // ... add other common flags if needed ...\n };\n\n runner::run_pipeline(\n &targets,\n CommandType::Upgrade { all: self.all },\n config,\n cache,\n &flags,\n )\n .await\n }\n}\n"], ["/sps/sps/src/cli.rs", "// sps/src/cli.rs\n//! Defines the command-line argument structure using clap.\nuse std::sync::Arc;\n\nuse clap::{ArgAction, Parser, Subcommand};\nuse sps_common::error::Result;\nuse sps_common::{Cache, Config};\n\n// Module declarations\npub mod info;\npub mod init;\npub mod install;\npub mod list;\npub mod reinstall;\npub mod search;\npub mod status;\npub mod uninstall;\npub mod update;\npub mod upgrade;\n// Re-export InitArgs to make it accessible as cli::InitArgs\n// Import other command Args structs\nuse crate::cli::info::Info;\npub use crate::cli::init::InitArgs;\nuse crate::cli::install::InstallArgs;\nuse crate::cli::list::List;\nuse crate::cli::reinstall::ReinstallArgs;\nuse crate::cli::search::Search;\nuse crate::cli::uninstall::Uninstall;\nuse crate::cli::update::Update;\nuse crate::cli::upgrade::UpgradeArgs;\n\n#[derive(Parser, Debug)]\n#[command(author, version, about, long_about = None, name = \"sps\", bin_name = \"sps\")]\n#[command(propagate_version = true)]\npub struct CliArgs {\n #[arg(short, long, action = ArgAction::Count, global = true)]\n pub verbose: u8,\n\n #[command(subcommand)]\n pub command: Command,\n}\n\n#[derive(Subcommand, Debug)]\npub enum Command {\n Init(InitArgs),\n Search(Search),\n List(List),\n Info(Info),\n Update(Update),\n Install(InstallArgs),\n Uninstall(Uninstall),\n Reinstall(ReinstallArgs),\n Upgrade(UpgradeArgs),\n}\n\nimpl Command {\n pub async fn run(&self, config: &Config, cache: Arc) -> Result<()> {\n match self {\n Self::Init(command) => command.run(config).await,\n Self::Search(command) => command.run(config, cache).await,\n Self::List(command) => command.run(config, cache).await,\n Self::Info(command) => command.run(config, cache).await,\n Self::Update(command) => command.run(config, cache).await,\n // Commands that use the pipeline\n Self::Install(command) => command.run(config, cache).await,\n Self::Reinstall(command) => command.run(config, cache).await,\n Self::Upgrade(command) => command.run(config, cache).await,\n Self::Uninstall(command) => command.run(config, cache).await,\n }\n }\n}\n\n// In install.rs, reinstall.rs, upgrade.rs, their run methods will now call\n// sps::cli::pipeline_runner::run_pipeline(...)\n// e.g., in sps/src/cli/install.rs:\n// use crate::cli::pipeline_runner::{self, CommandType, PipelineFlags};\n// ...\n// pipeline_runner::run_pipeline(&initial_targets, CommandType::Install, config, cache,\n// &flags).await\n"], ["/sps/sps-common/src/pipeline.rs", "// sps-common/src/pipeline.rs\nuse std::path::PathBuf;\nuse std::sync::Arc; // Required for Arc in JobProcessingState\n\nuse serde::{Deserialize, Serialize};\n\nuse crate::dependency::ResolvedGraph; // Needed for planner output\nuse crate::error::SpsError;\nuse crate::model::InstallTargetIdentifier;\n\n// --- Shared Enums / Structs ---\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]\npub enum PipelinePackageType {\n Formula,\n Cask,\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] // Added PartialEq, Eq\npub enum JobAction {\n Install,\n Upgrade {\n from_version: String,\n old_install_path: PathBuf,\n },\n Reinstall {\n version: String,\n current_install_path: PathBuf,\n },\n}\n\n#[derive(Debug, Clone)]\npub struct PlannedJob {\n pub target_id: String,\n pub target_definition: InstallTargetIdentifier,\n pub action: JobAction,\n pub is_source_build: bool,\n pub use_private_store_source: Option,\n}\n\n#[derive(Debug, Clone)]\npub struct WorkerJob {\n pub request: PlannedJob,\n pub download_path: PathBuf,\n pub download_size_bytes: u64,\n pub is_source_from_private_store: bool,\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub enum PipelineEvent {\n PipelineStarted {\n total_jobs: usize,\n },\n PipelineFinished {\n duration_secs: f64,\n success_count: usize,\n fail_count: usize,\n },\n PlanningStarted,\n DependencyResolutionStarted,\n DependencyResolutionFinished,\n PlanningFinished {\n job_count: usize,\n // Optionally, we can pass the ResolvedGraph here if the status handler needs it,\n // but it might be too large for a broadcast event.\n // resolved_graph: Option>, // Example\n },\n DownloadStarted {\n target_id: String,\n url: String,\n },\n DownloadFinished {\n target_id: String,\n path: PathBuf,\n size_bytes: u64,\n },\n DownloadProgressUpdate {\n target_id: String,\n bytes_so_far: u64,\n total_size: Option,\n },\n DownloadCached {\n target_id: String,\n size_bytes: u64,\n },\n DownloadFailed {\n target_id: String,\n url: String,\n error: String, // Keep as String for simplicity in events\n },\n JobProcessingStarted {\n // From core worker\n target_id: String,\n },\n JobDispatchedToCore {\n // New: From runner to UI when job sent to worker pool\n target_id: String,\n },\n UninstallStarted {\n target_id: String,\n version: String,\n },\n UninstallFinished {\n target_id: String,\n version: String,\n },\n BuildStarted {\n target_id: String,\n },\n InstallStarted {\n target_id: String,\n pkg_type: PipelinePackageType,\n },\n LinkStarted {\n target_id: String,\n pkg_type: PipelinePackageType,\n },\n JobSuccess {\n // From core worker\n target_id: String,\n action: JobAction,\n pkg_type: PipelinePackageType,\n },\n JobFailed {\n // From core worker or runner (propagated)\n target_id: String,\n action: JobAction, // Action that was attempted\n error: String, // Keep as String\n },\n LogInfo {\n message: String,\n },\n LogWarn {\n message: String,\n },\n LogError {\n message: String,\n },\n}\n\nimpl PipelineEvent {\n // SpsError kept for internal use, but events use String for error messages\n pub fn job_failed(target_id: String, action: JobAction, error: &SpsError) -> Self {\n PipelineEvent::JobFailed {\n target_id,\n action,\n error: error.to_string(),\n }\n }\n pub fn download_failed(target_id: String, url: String, error: &SpsError) -> Self {\n PipelineEvent::DownloadFailed {\n target_id,\n url,\n error: error.to_string(),\n }\n }\n}\n\n// --- New Structs and Enums for Refactored Runner ---\n\n/// Represents the current processing state of a job in the pipeline.\n#[derive(Debug, Clone)]\npub enum JobProcessingState {\n /// Waiting for download to be initiated.\n PendingDownload,\n /// Download is in progress (managed by DownloadCoordinator).\n Downloading,\n /// Download completed successfully, artifact at PathBuf.\n Downloaded(PathBuf),\n /// Downloaded, but waiting for dependencies to be in Succeeded state.\n WaitingForDependencies(PathBuf),\n /// Dispatched to the core worker pool for installation/processing.\n DispatchedToCore(PathBuf),\n /// Installation/processing is in progress by a core worker.\n Installing(PathBuf), // Path is still relevant\n /// Job completed successfully.\n Succeeded,\n /// Job failed. The String contains the error message. Arc for cheap cloning.\n Failed(Arc),\n}\n\n/// Outcome of a download attempt, sent from DownloadCoordinator to the main runner loop.\n#[derive(Debug)] // Clone not strictly needed if moved\npub struct DownloadOutcome {\n pub planned_job: PlannedJob, // The job this download was for\n pub result: Result, // Path to downloaded file or error\n}\n\n/// Structure returned by the planner, now including the ResolvedGraph.\n#[derive(Debug, Default)]\npub struct PlannedOperations {\n pub jobs: Vec, // Topologically sorted for formulae\n pub errors: Vec<(String, SpsError)>, // Errors from planning phase\n pub already_installed_or_up_to_date: std::collections::HashSet,\n pub resolved_graph: Option>, // Graph for dependency checking in runner\n}\n"], ["/sps/sps/src/cli/reinstall.rs", "// sps-cli/src/cli/reinstall.rs\nuse std::sync::Arc;\n\nuse clap::Args;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::error::Result;\n\nuse crate::pipeline::runner::{self, CommandType, PipelineFlags};\n\n#[derive(Args, Debug)]\npub struct ReinstallArgs {\n #[arg(required = true)]\n pub names: Vec,\n\n #[arg(\n long,\n help = \"Force building the formula from source, even if a bottle is available\"\n )]\n pub build_from_source: bool,\n}\n\nimpl ReinstallArgs {\n pub async fn run(&self, config: &Config, cache: Arc) -> Result<()> {\n let flags = PipelineFlags {\n // Populate flags from args\n build_from_source: self.build_from_source,\n include_optional: false, // Reinstall usually doesn't change optional deps\n skip_recommended: true, /* Reinstall usually doesn't change recommended deps\n * ... add other common flags if needed ... */\n };\n runner::run_pipeline(&self.names, CommandType::Reinstall, config, cache, &flags).await\n }\n}\n"], ["/sps/sps-common/src/dependency/definition.rs", "// **File:** sps-core/src/dependency/dependency.rs // Should be in the model module\nuse std::fmt;\n\nuse bitflags::bitflags;\nuse serde::{Deserialize, Serialize};\n\nbitflags! {\n #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]\n pub struct DependencyTag: u8 {\n const RUNTIME = 0b00000001;\n const BUILD = 0b00000010;\n const TEST = 0b00000100;\n const OPTIONAL = 0b00001000;\n const RECOMMENDED = 0b00010000;\n }\n}\n\nimpl Default for DependencyTag {\n fn default() -> Self {\n Self::RUNTIME\n }\n}\n\nimpl fmt::Display for DependencyTag {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"{self:?}\")\n }\n}\n\n#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]\npub struct Dependency {\n pub name: String,\n #[serde(default)]\n pub tags: DependencyTag,\n}\n\nimpl Dependency {\n pub fn new_runtime(name: impl Into) -> Self {\n Self {\n name: name.into(),\n tags: DependencyTag::RUNTIME,\n }\n }\n\n pub fn new_with_tags(name: impl Into, tags: DependencyTag) -> Self {\n Self {\n name: name.into(),\n tags,\n }\n }\n}\n\npub trait DependencyExt {\n fn filter_by_tags(&self, include: DependencyTag, exclude: DependencyTag) -> Vec<&Dependency>;\n fn runtime(&self) -> Vec<&Dependency>;\n fn build_time(&self) -> Vec<&Dependency>;\n}\n\nimpl DependencyExt for Vec {\n fn filter_by_tags(&self, include: DependencyTag, exclude: DependencyTag) -> Vec<&Dependency> {\n self.iter()\n .filter(|dep| dep.tags.contains(include) && !dep.tags.intersects(exclude))\n .collect()\n }\n\n fn runtime(&self) -> Vec<&Dependency> {\n // A dependency is runtime if its tags indicate it's needed at runtime.\n // This includes standard runtime, recommended, or optional dependencies.\n // Build-only or Test-only dependencies (without other runtime flags) are excluded.\n self.iter()\n .filter(|dep| {\n dep.tags.intersects(\n DependencyTag::RUNTIME | DependencyTag::RECOMMENDED | DependencyTag::OPTIONAL,\n )\n })\n .collect()\n }\n\n fn build_time(&self) -> Vec<&Dependency> {\n self.filter_by_tags(DependencyTag::BUILD, DependencyTag::empty())\n }\n}\n"], ["/sps/sps-common/src/model/mod.rs", "// src/model/mod.rs\n// Declares the modules within the model directory.\nuse std::sync::Arc;\n\npub mod artifact;\npub mod cask;\npub mod formula;\npub mod tap;\npub mod version;\n\n// Re-export\npub use artifact::InstalledArtifact;\npub use cask::Cask;\npub use formula::Formula;\n\n#[derive(Debug, Clone)]\npub enum InstallTargetIdentifier {\n Formula(Arc),\n Cask(Arc),\n}\n"], ["/sps/sps-core/src/install/mod.rs", "// ===== sps-core/src/build/mod.rs =====\n// Main module for build functionality\n// Removed deprecated functions and re-exports.\n\nuse std::path::PathBuf;\n\nuse sps_common::config::Config;\nuse sps_common::model::formula::Formula;\n\n// --- Submodules ---\npub mod bottle;\npub mod cask;\npub mod devtools;\npub mod extract;\n\n// --- Path helpers using Config ---\npub fn get_formula_opt_path(formula: &Formula, config: &Config) -> PathBuf {\n // Use new Config method\n config.formula_opt_path(formula.name())\n}\n\n// --- DEPRECATED EXTRACTION FUNCTIONS REMOVED ---\n"], ["/sps/sps-core/src/install/cask/artifacts/mod.rs", "pub mod app;\npub mod audio_unit_plugin;\npub mod binary;\npub mod colorpicker;\npub mod dictionary;\npub mod font;\npub mod input_method;\npub mod installer;\npub mod internet_plugin;\npub mod keyboard_layout;\npub mod manpage;\npub mod mdimporter;\npub mod pkg;\npub mod preflight;\npub mod prefpane;\npub mod qlplugin;\npub mod screen_saver;\npub mod service;\npub mod suite;\npub mod uninstall;\npub mod vst3_plugin;\npub mod vst_plugin;\npub mod zap;\n\n// Re‑export a single enum if you like:\npub use self::app::install_app_from_staged;\npub use self::audio_unit_plugin::install_audio_unit_plugin;\npub use self::binary::install_binary;\npub use self::colorpicker::install_colorpicker;\npub use self::dictionary::install_dictionary;\npub use self::font::install_font;\npub use self::input_method::install_input_method;\npub use self::installer::run_installer;\npub use self::internet_plugin::install_internet_plugin;\npub use self::keyboard_layout::install_keyboard_layout;\npub use self::manpage::install_manpage;\npub use self::mdimporter::install_mdimporter;\npub use self::pkg::install_pkg_from_path;\npub use self::preflight::run_preflight;\npub use self::prefpane::install_prefpane;\npub use self::qlplugin::install_qlplugin;\npub use self::screen_saver::install_screen_saver;\npub use self::service::install_service;\npub use self::suite::install_suite;\npub use self::uninstall::record_uninstall;\npub use self::vst3_plugin::install_vst3_plugin;\npub use self::vst_plugin::install_vst_plugin;\n"], ["/sps/sps-net/src/lib.rs", "// spm-fetch/src/lib.rs\npub mod api;\npub mod http;\npub mod oci;\npub mod validation;\n\n// Re-export necessary types from sps-core IF using Option A from Step 3\n// If using Option B (DTOs), you wouldn't depend on sps-core here for models.\n// Re-export the public fetching functions - ensure they are `pub`\npub use api::{\n fetch_all_casks, fetch_all_formulas, fetch_cask, fetch_formula, get_cask, /* ... */\n get_formula,\n};\npub use http::{fetch_formula_source_or_bottle, fetch_resource /* ... */};\npub use oci::{build_oci_client /* ... */, download_oci_blob, fetch_oci_manifest_index};\npub use sps_common::{\n model::{\n cask::{Sha256Field, UrlField},\n formula::ResourceSpec,\n Cask, Formula,\n }, // Example types needed\n {\n cache::Cache,\n error::{Result, SpsError},\n Config,\n }, // Need Config, Result, SpsError, Cache\n};\n\npub use crate::validation::{validate_url, verify_checksum, verify_content_type /* ... */};\n"], ["/sps/sps-common/src/error.rs", "use std::sync::Arc;\n\nuse thiserror::Error;\n\n#[derive(Error, Debug, Clone)]\npub enum SpsError {\n #[error(\"I/O Error: {0}\")]\n Io(#[from] Arc),\n\n #[error(\"HTTP Request Error: {0}\")]\n Http(#[from] Arc),\n\n #[error(\"JSON Parsing Error: {0}\")]\n Json(#[from] Arc),\n\n #[error(\"Semantic Versioning Error: {0}\")]\n SemVer(#[from] Arc),\n\n #[error(\"Object File Error: {0}\")]\n Object(#[from] Arc),\n\n #[error(\"Configuration Error: {0}\")]\n Config(String),\n\n #[error(\"API Error: {0}\")]\n Api(String),\n\n #[error(\"API Request Error: {0}\")]\n ApiRequestError(String),\n\n #[error(\"DownloadError: Failed to download '{0}' from '{1}': {2}\")]\n DownloadError(String, String, String),\n\n #[error(\"Cache Error: {0}\")]\n Cache(String),\n\n #[error(\"Resource Not Found: {0}\")]\n NotFound(String),\n\n #[error(\"Installation Error: {0}\")]\n InstallError(String),\n\n #[error(\"Generic Error: {0}\")]\n Generic(String),\n\n #[error(\"HttpError: {0}\")]\n HttpError(String),\n\n #[error(\"Checksum Mismatch: {0}\")]\n ChecksumMismatch(String),\n\n #[error(\"Validation Error: {0}\")]\n ValidationError(String),\n\n #[error(\"Checksum Error: {0}\")]\n ChecksumError(String),\n\n #[error(\"Parsing Error in {0}: {1}\")]\n ParseError(&'static str, String),\n\n #[error(\"Version error: {0}\")]\n VersionError(String),\n\n #[error(\"Dependency Error: {0}\")]\n DependencyError(String),\n\n #[error(\"Build environment setup failed: {0}\")]\n BuildEnvError(String),\n\n #[error(\"IoError: {0}\")]\n IoError(String),\n\n #[error(\"Failed to execute command: {0}\")]\n CommandExecError(String),\n\n #[error(\"Mach-O Error: {0}\")]\n MachOError(String),\n\n #[error(\"Mach-O Modification Error: {0}\")]\n MachOModificationError(String),\n\n #[error(\"Mach-O Relocation Error: Path too long - {0}\")]\n PathTooLongError(String),\n\n #[error(\"Codesign Error: {0}\")]\n CodesignError(String),\n}\n\nimpl From for SpsError {\n fn from(err: std::io::Error) -> Self {\n SpsError::Io(Arc::new(err))\n }\n}\n\nimpl From for SpsError {\n fn from(err: reqwest::Error) -> Self {\n SpsError::Http(Arc::new(err))\n }\n}\n\nimpl From for SpsError {\n fn from(err: serde_json::Error) -> Self {\n SpsError::Json(Arc::new(err))\n }\n}\n\nimpl From for SpsError {\n fn from(err: semver::Error) -> Self {\n SpsError::SemVer(Arc::new(err))\n }\n}\n\nimpl From for SpsError {\n fn from(err: object::read::Error) -> Self {\n SpsError::Object(Arc::new(err))\n }\n}\n\npub type Result = std::result::Result;\n"], ["/sps/sps-common/src/lib.rs", "// sps-common/src/lib.rs\npub mod cache;\npub mod config;\npub mod dependency;\npub mod error;\npub mod formulary;\npub mod keg;\npub mod model;\npub mod pipeline;\n// Optional: pub mod dependency_def;\n\n// Re-export key types\npub use cache::Cache;\npub use config::Config;\npub use error::{Result, SpsError};\npub use model::{Cask, Formula, InstalledArtifact}; // etc.\n // Optional: pub use dependency_def::{Dependency, DependencyTag};\n"], ["/sps/sps-common/src/dependency/requirement.rs", "// **File:** sps-core/src/dependency/requirement.rs (New file)\nuse std::fmt;\n\nuse serde::{Deserialize, Serialize};\n\n#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]\npub enum Requirement {\n MacOS(String),\n Xcode(String),\n Other(String),\n}\n\nimpl fmt::Display for Requirement {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n match self {\n Self::MacOS(v) => write!(f, \"macOS >= {v}\"),\n Self::Xcode(v) => write!(f, \"Xcode >= {v}\"),\n Self::Other(s) => write!(f, \"Requirement: {s}\"),\n }\n }\n}\n"], ["/sps/sps-core/src/uninstall/mod.rs", "// sps-core/src/uninstall/mod.rs\n\npub mod cask;\npub mod common;\npub mod formula;\n\n// Re-export key functions and types\npub use cask::{uninstall_cask_artifacts, zap_cask_artifacts};\npub use common::UninstallOptions;\npub use formula::uninstall_formula_artifacts;\n"], ["/sps/sps-core/src/lib.rs", "// sps-core/src/lib.rs\n\n// Declare the top-level modules within the library crate\npub mod build;\npub mod check;\npub mod install;\npub mod pipeline;\npub mod uninstall;\npub mod upgrade; // New\n#[cfg(target_os = \"macos\")]\npub mod utils; // New\n //pub mod utils;\n\n// Re-export key types for easier use by the CLI crate\n// Define InstallTargetIdentifier here or ensure it's public from cli/pipeline\n// For simplicity, let's define it here for now:\n\n// New\npub use uninstall::UninstallOptions; // New\n // New\n"], ["/sps/sps-core/src/upgrade/mod.rs", "// sps-core/src/upgrade/mod.rs\n\npub mod bottle;\npub mod cask;\npub mod source;\n\n// Re-export key upgrade functions\npub use self::bottle::upgrade_bottle_formula;\npub use self::cask::upgrade_cask_package;\npub use self::source::upgrade_source_formula;\n"], ["/sps/sps-core/src/check/mod.rs", "pub mod installed;\npub mod update;\n\npub use installed::{InstalledPackageInfo, PackageType};\npub use update::UpdateInfo;\n"], ["/sps/sps-common/src/dependency/mod.rs", "pub mod definition; // Renamed from 'dependency'\npub mod requirement;\npub mod resolver;\n\n// Re-export key types for easier access\npub use definition::{Dependency, DependencyExt, DependencyTag}; // Updated source module\npub use requirement::Requirement;\npub use resolver::{\n DependencyResolver, ResolutionContext, ResolutionStatus, ResolvedDependency, ResolvedGraph,\n};\n"], ["/sps/sps-core/src/utils/mod.rs", "#[cfg(target_os = \"macos\")]\npub mod applescript;\n#[cfg(target_os = \"macos\")]\npub mod xattr;\n"], ["/sps/sps/src/pipeline.rs", "pub mod downloader;\npub mod planner;\npub mod runner;\n"], ["/sps/sps-core/src/pipeline/mod.rs", "pub mod engine;\npub mod worker;\n"]], "task_instance_info": {"created_time": "2025-08-21 01:45:07", "created_task_model": "DeepSeek-R1", "function_skeleton": "pub fn install_suite (\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {}", "code_description": "This code segment functions to: Transfer application bundle directories from a temporary staging area to a system-wide applications location while maintaining version-specific references through symbolic links. It handles existing installations by performing cleanup operations, ensures successful file movement with fallback copying, and tracks installed components for management purposes."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```rust\n[TASK_BEGIN]\npub fn install_suite(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut artifacts = Vec::new();\n\n for suite_name in &cask.artifacts.suite {\n debug!(\"Installing suite artifact: {}\", suite_name);\n \n let source_path = stage_path.join(suite_name);\n let dest_path = config.applications_dir.join(suite_name);\n\n // Remove existing application directory if present\n remove_path_robustly(&dest_path)?;\n\n // Move from staging to final Applications location\n std::fs::rename(&source_path, &dest_path)?;\n\n // Create symlink in Caskroom directory\n let symlink_path = cask_version_install_path.join(suite_name);\n symlink(&dest_path, &symlink_path)?;\n\n artifacts.push(InstalledArtifact {\n path: symlink_path,\n // Additional fields would be populated here based on artifact metadata\n });\n }\n\n Ok(artifacts)\n}\n[TASK_END]\n```", "inference_time": "2025-08-21 01-46-13"}, "editdistance_info": {"edit_distance": 28.9003, "calculate_time": "2025-08-21 01:46:13", "true_code_clean": "pub fn install_suite(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def.iter() {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"suite\").and_then(|v| v.as_array()) {\n for entry in entries {\n if let Some(dir_name) = entry.as_str() {\n let src = stage_path.join(dir_name);\n if !src.exists() {\n debug!(\n \"Suite directory '{}' not found in staging, skipping\",\n dir_name\n );\n continue;\n }\n let dest_dir = config.applications_dir(); \n let dest = dest_dir.join(dir_name); \n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n debug!(\"Moving suite '{}' → '{}'\", src.display(), dest.display());\n let mv_status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !mv_status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n installed.push(InstalledArtifact::AppBundle { path: dest.clone() });\n let link = cask_version_install_path.join(dir_name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; \n }\n }\n }\n }\n Ok(installed)\n}", "predict_code_clean": "pub fn install_suite(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut artifacts = Vec::new();\n for suite_name in &cask.artifacts.suite {\n debug!(\"Installing suite artifact: {}\", suite_name);\n let source_path = stage_path.join(suite_name);\n let dest_path = config.applications_dir.join(suite_name);\n remove_path_robustly(&dest_path)?;\n std::fs::rename(&source_path, &dest_path)?;\n let symlink_path = cask_version_install_path.join(suite_name);\n symlink(&dest_path, &symlink_path)?;\n artifacts.push(InstalledArtifact {\n path: symlink_path,\n });\n }\n Ok(artifacts)\n}"}} {"repo_name": "sps", "file_name": "/sps/sps-common/src/keg.rs", "inference_info": {"prefix_code": "// sps-common/src/keg.rs\nuse std::fs;\nuse std::path::PathBuf;\n\n// Corrected tracing imports: added error, removed unused debug\nuse tracing::{debug, error, warn};\n\nuse super::config::Config;\nuse super::error::{Result, SpsError};\n\n/// Represents information about an installed package (Keg).\n#[derive(Debug, Clone, PartialEq, Eq)]\npub struct InstalledKeg {\n pub name: String,\n pub version_str: String,\n pub path: PathBuf,\n}\n\n/// Manages querying installed packages in the Cellar.\n#[derive(Debug)]\npub struct KegRegistry {\n config: Config,\n}\n\nimpl KegRegistry {\n pub fn new(config: Config) -> Self {\n Self { config }\n }\n\n fn formula_cellar_path(&self, name: &str) -> PathBuf {\n self.config.cellar_dir().join(name)\n }\n\n pub fn get_opt_path(&self, name: &str) -> PathBuf {\n self.config.opt_dir().join(name)\n }\n\n ", "suffix_code": "\n\n pub fn list_installed_kegs(&self) -> Result> {\n let mut installed_kegs = Vec::new();\n let cellar_dir = self.cellar_path();\n debug!(\n \"[KEG_REGISTRY] list_installed_kegs: Scanning cellar: {}\",\n cellar_dir.display()\n );\n\n if !cellar_dir.is_dir() {\n debug!(\"[KEG_REGISTRY] list_installed_kegs: Cellar directory NOT FOUND. Returning empty list.\");\n return Ok(installed_kegs);\n }\n\n for formula_entry_res in fs::read_dir(cellar_dir)? {\n let formula_entry = match formula_entry_res {\n Ok(fe) => fe,\n Err(e) => {\n warn!(\"[KEG_REGISTRY] list_installed_kegs: Error reading entry in cellar: {}. Skipping.\", e);\n continue;\n }\n };\n let formula_path = formula_entry.path();\n debug!(\n \"[KEG_REGISTRY] list_installed_kegs: Examining formula path: {}\",\n formula_path.display()\n );\n\n if formula_path.is_dir() {\n if let Some(formula_name) = formula_path.file_name().and_then(|n| n.to_str()) {\n debug!(\n \"[KEG_REGISTRY] list_installed_kegs: Found formula directory: {}\",\n formula_name\n );\n match fs::read_dir(&formula_path) {\n Ok(version_entries) => {\n for version_entry_res in version_entries {\n let version_entry = match version_entry_res {\n Ok(ve) => ve,\n Err(e) => {\n warn!(\"[KEG_REGISTRY:{}] list_installed_kegs: Error reading version entry in '{}': {}. Skipping.\", formula_name, formula_path.display(), e);\n continue;\n }\n };\n let version_path = version_entry.path();\n debug!(\"[KEG_REGISTRY:{}] list_installed_kegs: Examining version path: {}\", formula_name, version_path.display());\n\n if version_path.is_dir() {\n if let Some(version_str_full) =\n version_path.file_name().and_then(|n| n.to_str())\n {\n debug!(\"[KEG_REGISTRY:{}] list_installed_kegs: Found version directory '{}' with name: {}\", formula_name, version_path.display(), version_str_full);\n installed_kegs.push(InstalledKeg {\n name: formula_name.to_string(),\n version_str: version_str_full.to_string(),\n path: version_path.clone(),\n });\n } else {\n debug!(\"[KEG_REGISTRY:{}] list_installed_kegs: Could not get filename for version path {}\", formula_name, version_path.display());\n }\n } else {\n debug!(\"[KEG_REGISTRY:{}] list_installed_kegs: Version path {} is not a directory.\", formula_name, version_path.display());\n }\n }\n }\n Err(e) => {\n warn!(\"[KEG_REGISTRY:{}] list_installed_kegs: Failed to read_dir for formula versions in '{}': {}.\", formula_name, formula_path.display(), e);\n }\n }\n } else {\n debug!(\"[KEG_REGISTRY] list_installed_kegs: Could not get filename for formula path {}\", formula_path.display());\n }\n } else {\n debug!(\n \"[KEG_REGISTRY] list_installed_kegs: Formula path {} is not a directory.\",\n formula_path.display()\n );\n }\n }\n debug!(\n \"[KEG_REGISTRY] list_installed_kegs: Found {} total installed keg versions.\",\n installed_kegs.len()\n );\n Ok(installed_kegs)\n }\n\n pub fn cellar_path(&self) -> PathBuf {\n self.config.cellar_dir()\n }\n\n pub fn get_keg_path(&self, name: &str, version_str_raw: &str) -> PathBuf {\n self.formula_cellar_path(name).join(version_str_raw)\n }\n}\n", "middle_code": "pub fn get_installed_keg(&self, name: &str) -> Result> {\n let formula_dir = self.formula_cellar_path(name);\n debug!(\n \"[KEG_REGISTRY:{}] get_installed_keg: Checking for formula '{}'. Path to check: {}\",\n name,\n name,\n formula_dir.display()\n );\n if !formula_dir.is_dir() {\n debug!(\"[KEG_REGISTRY:{}] get_installed_keg: Formula directory '{}' NOT FOUND or not a directory. Returning None.\", name, formula_dir.display());\n return Ok(None);\n }\n let mut latest_keg: Option = None;\n debug!(\n \"[KEG_REGISTRY:{}] get_installed_keg: Reading entries in formula directory '{}'\",\n name,\n formula_dir.display()\n );\n match fs::read_dir(&formula_dir) {\n Ok(entries) => {\n for entry_result in entries {\n match entry_result {\n Ok(entry) => {\n let path = entry.path();\n debug!(\n \"[KEG_REGISTRY:{}] get_installed_keg: Examining entry '{}'\",\n name,\n path.display()\n );\n if path.is_dir() {\n if let Some(version_str_full) =\n path.file_name().and_then(|n| n.to_str())\n {\n debug!(\"[KEG_REGISTRY:{}] get_installed_keg: Entry is a directory with name: {}\", name, version_str_full);\n let current_keg_candidate = InstalledKeg {\n name: name.to_string(),\n version_str: version_str_full.to_string(),\n path: path.clone(),\n };\n match latest_keg {\n Some(ref current_latest) => {\n if version_str_full\n > current_latest.version_str.as_str()\n {\n debug!(\"[KEG_REGISTRY:{}] get_installed_keg: Updating latest keg (lexicographical) to: {}\", name, path.display());\n latest_keg = Some(current_keg_candidate);\n }\n }\n None => {\n debug!(\"[KEG_REGISTRY:{}] get_installed_keg: Setting first found keg as latest: {}\", name, path.display());\n latest_keg = Some(current_keg_candidate);\n }\n }\n } else {\n debug!(\"[KEG_REGISTRY:{}] get_installed_keg: Could not get filename as string for path '{}'\", name, path.display());\n }\n } else {\n debug!(\"[KEG_REGISTRY:{}] get_installed_keg: Entry '{}' is not a directory.\", name, path.display());\n }\n }\n Err(e) => {\n warn!(\"[KEG_REGISTRY:{}] get_installed_keg: Error reading a directory entry in '{}': {}. Skipping entry.\", name, formula_dir.display(), e);\n }\n }\n }\n }\n Err(e) => {\n error!(\"[KEG_REGISTRY:{}] get_installed_keg: Failed to read_dir for formula directory '{}' (error: {}). Returning error.\", name, formula_dir.display(), e);\n return Err(SpsError::Io(std::sync::Arc::new(e)));\n }\n }\n if let Some(keg) = &latest_keg {\n debug!(\"[KEG_REGISTRY:{}] get_installed_keg: For formula '{}', latest keg found: path={}, version_str={}\", name, name, keg.path.display(), keg.version_str);\n } else {\n debug!(\"[KEG_REGISTRY:{}] get_installed_keg: For formula '{}', no installable keg version found in directory '{}'.\", name, name, formula_dir.display());\n }\n Ok(latest_keg)\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "rust", "sub_task_type": null}, "context_code": [["/sps/sps-core/src/check/installed.rs", "// sps-core/src/check/installed.rs\nuse std::fs::{self}; // Removed DirEntry as it's not directly used here\nuse std::io;\nuse std::path::PathBuf;\nuse std::sync::Arc;\n\nuse serde::{Deserialize, Serialize};\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::keg::KegRegistry; // KegRegistry is used\nuse tracing::{debug, warn};\n\n#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]\npub enum PackageType {\n Formula,\n Cask,\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub struct InstalledPackageInfo {\n pub name: String,\n pub version: String, // This will now store keg.version_str\n pub pkg_type: PackageType,\n pub path: PathBuf,\n}\n\n// Helper closure to handle io::Result -> Option logging errors\n// Defined outside the functions to avoid repetition\nfn handle_dir_entry(res: io::Result, dir_path_str: &str) -> Option {\n match res {\n Ok(entry) => Some(entry),\n Err(e) => {\n warn!(\"Error reading entry in {}: {}\", dir_path_str, e);\n None\n }\n }\n}\n\npub async fn get_installed_packages(config: &Config) -> Result> {\n let mut installed = Vec::new();\n let keg_registry = KegRegistry::new(config.clone());\n\n match keg_registry.list_installed_kegs() {\n Ok(kegs) => {\n for keg in kegs {\n installed.push(InstalledPackageInfo {\n name: keg.name,\n version: keg.version_str, // Use keg.version_str\n pkg_type: PackageType::Formula,\n path: keg.path,\n });\n }\n }\n Err(e) => warn!(\"Failed to list installed formulae: {}\", e),\n }\n\n let caskroom_dir = config.cask_room_dir();\n if caskroom_dir.is_dir() {\n let caskroom_dir_str = caskroom_dir.to_str().unwrap_or(\"caskroom\").to_string();\n let cask_token_entries_iter =\n fs::read_dir(&caskroom_dir).map_err(|e| SpsError::Io(Arc::new(e)))?;\n\n for entry_res in cask_token_entries_iter {\n if let Some(entry) = handle_dir_entry(entry_res, &caskroom_dir_str) {\n let cask_token_path = entry.path();\n if !cask_token_path.is_dir() {\n continue;\n }\n let cask_token = entry.file_name().to_string_lossy().to_string();\n\n match fs::read_dir(&cask_token_path) {\n Ok(version_entries_iter) => {\n for version_entry_res in version_entries_iter {\n if let Some(version_entry) = handle_dir_entry(\n version_entry_res,\n cask_token_path.to_str().unwrap_or(\"token_path\"),\n ) {\n let version_path = version_entry.path();\n if version_path.is_dir()\n && version_path.join(\"CASK_INSTALL_MANIFEST.json\").is_file()\n {\n let version_str =\n version_entry.file_name().to_string_lossy().to_string();\n let manifest_path =\n version_path.join(\"CASK_INSTALL_MANIFEST.json\");\n let mut include = true;\n if manifest_path.is_file() {\n if let Ok(manifest_str) =\n std::fs::read_to_string(&manifest_path)\n {\n if let Ok(manifest_json) =\n serde_json::from_str::(\n &manifest_str,\n )\n {\n if let Some(is_installed) = manifest_json\n .get(\"is_installed\")\n .and_then(|v| v.as_bool())\n {\n include = is_installed;\n }\n }\n }\n }\n if include {\n installed.push(InstalledPackageInfo {\n name: cask_token.clone(),\n version: version_str,\n pkg_type: PackageType::Cask,\n path: version_path,\n });\n }\n // Assuming one actively installed version per cask token based\n // on manifest logic\n // If multiple version folders exist but only one manifest says\n // is_installed=true, this is fine.\n // If the intent is to list *all* version folders, the break\n // might be removed,\n // but then \"is_installed\" logic per version becomes more\n // important.\n // For now, finding the first \"active\" one is usually sufficient\n // for list/upgrade checks.\n }\n }\n }\n }\n Err(e) => warn!(\"Failed to read cask versions for {}: {}\", cask_token, e),\n }\n }\n }\n } else {\n debug!(\n \"Caskroom directory {} does not exist.\",\n caskroom_dir.display()\n );\n }\n Ok(installed)\n}\n\npub async fn get_installed_package(\n name: &str,\n config: &Config,\n) -> Result> {\n let keg_registry = KegRegistry::new(config.clone());\n if let Some(keg) = keg_registry.get_installed_keg(name)? {\n return Ok(Some(InstalledPackageInfo {\n name: keg.name,\n version: keg.version_str, // Use keg.version_str\n pkg_type: PackageType::Formula,\n path: keg.path,\n }));\n }\n\n let cask_token_path = config.cask_room_token_path(name);\n if cask_token_path.is_dir() {\n let version_entries_iter =\n fs::read_dir(&cask_token_path).map_err(|e| SpsError::Io(Arc::new(e)))?;\n for version_entry_res in version_entries_iter {\n if let Some(version_entry) = handle_dir_entry(\n version_entry_res,\n cask_token_path.to_str().unwrap_or(\"token_path\"),\n ) {\n let version_path = version_entry.path();\n if version_path.is_dir()\n && version_path.join(\"CASK_INSTALL_MANIFEST.json\").is_file()\n {\n let version_str = version_entry.file_name().to_string_lossy().to_string();\n let manifest_path = version_path.join(\"CASK_INSTALL_MANIFEST.json\");\n let mut include = true;\n if manifest_path.is_file() {\n if let Ok(manifest_str) = std::fs::read_to_string(&manifest_path) {\n if let Ok(manifest_json) =\n serde_json::from_str::(&manifest_str)\n {\n if let Some(is_installed) =\n manifest_json.get(\"is_installed\").and_then(|v| v.as_bool())\n {\n include = is_installed;\n }\n }\n }\n }\n if include {\n return Ok(Some(InstalledPackageInfo {\n name: name.to_string(),\n version: version_str,\n pkg_type: PackageType::Cask,\n path: version_path,\n }));\n }\n }\n }\n }\n }\n Ok(None)\n}\n"], ["/sps/sps-core/src/install/bottle/link.rs", "// ===== sps-core/src/build/formula/link.rs =====\nuse std::fs;\nuse std::io::Write;\nuse std::os::unix::fs as unix_fs;\n#[cfg(unix)]\nuse std::os::unix::fs::PermissionsExt;\nuse std::path::{Path, PathBuf};\n\nuse serde_json;\nuse sps_common::config::Config; // Import Config\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::formula::Formula;\nuse tracing::{debug, error};\n\nconst STANDARD_KEG_DIRS: [&str; 6] = [\"bin\", \"lib\", \"share\", \"include\", \"etc\", \"Frameworks\"];\n\n/// Link all artifacts from a formula's installation directory.\n// Added Config parameter\npub fn link_formula_artifacts(\n formula: &Formula,\n installed_keg_path: &Path,\n config: &Config, // Added config\n) -> Result<()> {\n debug!(\n \"Linking artifacts for {} from {}\",\n formula.name(),\n installed_keg_path.display()\n );\n\n let formula_content_root = determine_content_root(installed_keg_path)?;\n let mut symlinks_created = Vec::::new();\n\n // Use config methods for paths\n let opt_link_path = config.formula_opt_path(formula.name());\n let target_keg_dir = &formula_content_root;\n\n remove_existing_link_target(&opt_link_path)?;\n unix_fs::symlink(target_keg_dir, &opt_link_path).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed to create opt symlink for {}: {}\", formula.name(), e),\n )))\n })?;\n symlinks_created.push(opt_link_path.to_string_lossy().to_string());\n debug!(\n \" Linked opt path: {} -> {}\",\n opt_link_path.display(),\n target_keg_dir.display()\n );\n\n if let Some((base, _version)) = formula.name().split_once('@') {\n let alias_path = config.opt_dir().join(base); // Use config.opt_dir()\n if !alias_path.exists() {\n match unix_fs::symlink(target_keg_dir, &alias_path) {\n Ok(_) => {\n debug!(\n \" Added un‑versioned opt alias: {} -> {}\",\n alias_path.display(),\n target_keg_dir.display()\n );\n symlinks_created.push(alias_path.to_string_lossy().to_string());\n }\n Err(e) => {\n debug!(\n \" Could not create opt alias {}: {}\",\n alias_path.display(),\n e\n );\n }\n }\n }\n }\n\n let standard_artifact_dirs = [\"lib\", \"include\", \"share\"];\n for dir_name in &standard_artifact_dirs {\n let source_subdir = formula_content_root.join(dir_name);\n // Use config.prefix() for target base\n let target_prefix_subdir = config.sps_root().join(dir_name);\n\n if source_subdir.is_dir() {\n fs::create_dir_all(&target_prefix_subdir)?;\n for entry in fs::read_dir(&source_subdir)? {\n let entry = entry?;\n let source_item_path = entry.path();\n let file_name = entry.file_name();\n if file_name.to_string_lossy().starts_with('.') {\n continue;\n }\n\n let target_link = target_prefix_subdir.join(&file_name);\n remove_existing_link_target(&target_link)?;\n unix_fs::symlink(&source_item_path, &target_link).ok(); // ignore errors for individual links?\n symlinks_created.push(target_link.to_string_lossy().to_string());\n debug!(\n \" Linked {} -> {}\",\n target_link.display(),\n source_item_path.display()\n );\n }\n }\n }\n\n // Use config.bin_dir() for target bin\n let target_bin_dir = config.bin_dir();\n fs::create_dir_all(&target_bin_dir).ok();\n\n let source_bin_dir = formula_content_root.join(\"bin\");\n if source_bin_dir.is_dir() {\n create_wrappers_in_dir(\n &source_bin_dir,\n &target_bin_dir,\n &formula_content_root,\n &mut symlinks_created,\n )?;\n }\n let source_libexec_dir = formula_content_root.join(\"libexec\");\n if source_libexec_dir.is_dir() {\n create_wrappers_in_dir(\n &source_libexec_dir,\n &target_bin_dir,\n &formula_content_root,\n &mut symlinks_created,\n )?;\n }\n\n write_install_manifest(installed_keg_path, &symlinks_created)?;\n\n debug!(\n \"Successfully completed linking artifacts for {}\",\n formula.name()\n );\n Ok(())\n}\n\n// remove_existing_link_target, write_install_manifest remain mostly unchanged internally) ...\nfn create_wrappers_in_dir(\n source_dir: &Path,\n target_bin_dir: &Path,\n formula_content_root: &Path,\n wrappers_created: &mut Vec,\n) -> Result<()> {\n debug!(\n \"Scanning for executables in {} to create wrappers in {}\",\n source_dir.display(),\n target_bin_dir.display()\n );\n match fs::read_dir(source_dir) {\n Ok(entries) => {\n for entry_result in entries {\n match entry_result {\n Ok(entry) => {\n let source_item_path = entry.path();\n let file_name = entry.file_name();\n\n if file_name.to_string_lossy().starts_with('.') {\n continue;\n }\n\n if source_item_path.is_dir() {\n create_wrappers_in_dir(\n &source_item_path,\n target_bin_dir,\n formula_content_root,\n wrappers_created,\n )?;\n } else if source_item_path.is_file() {\n match is_executable(&source_item_path) {\n Ok(true) => {\n let wrapper_path = target_bin_dir.join(&file_name);\n debug!(\"Found executable: {}\", source_item_path.display());\n if remove_existing_link_target(&wrapper_path).is_ok() {\n debug!(\n \" Creating wrapper script: {} -> {}\",\n wrapper_path.display(),\n source_item_path.display()\n );\n match create_wrapper_script(\n &source_item_path,\n &wrapper_path,\n formula_content_root,\n ) {\n Ok(_) => {\n debug!(\n \" Created wrapper {} -> {}\",\n wrapper_path.display(),\n source_item_path.display()\n );\n wrappers_created.push(\n wrapper_path.to_string_lossy().to_string(),\n );\n }\n Err(e) => {\n error!(\n \"Failed to create wrapper script {} -> {}: {}\",\n wrapper_path.display(),\n source_item_path.display(),\n e\n );\n }\n }\n }\n }\n Ok(false) => { /* Not executable, ignore */ }\n Err(e) => {\n debug!(\n \" Could not check executable status for {}: {}\",\n source_item_path.display(),\n e\n );\n }\n }\n }\n }\n Err(e) => {\n debug!(\n \" Failed to process directory entry in {}: {}\",\n source_dir.display(),\n e\n );\n }\n }\n }\n }\n Err(e) => {\n debug!(\n \"Failed to read source directory {}: {}\",\n source_dir.display(),\n e\n );\n }\n }\n Ok(())\n}\nfn create_wrapper_script(\n target_executable: &Path,\n wrapper_path: &Path,\n formula_content_root: &Path,\n) -> Result<()> {\n let libexec_path = formula_content_root.join(\"libexec\");\n let perl_lib_path = libexec_path.join(\"lib\").join(\"perl5\");\n let python_lib_path = libexec_path.join(\"vendor\"); // Assuming simple vendor dir\n\n let mut script_content = String::new();\n script_content.push_str(\"#!/bin/bash\\n\");\n script_content.push_str(\"# Wrapper script generated by sp\\n\");\n script_content.push_str(\"set -e\\n\\n\");\n\n if perl_lib_path.exists() && perl_lib_path.is_dir() {\n script_content.push_str(&format!(\n \"export PERL5LIB=\\\"{}:$PERL5LIB\\\"\\n\",\n perl_lib_path.display()\n ));\n debug!(\n \" (Wrapper will set PERL5LIB to {})\",\n perl_lib_path.display()\n );\n }\n if python_lib_path.exists() && python_lib_path.is_dir() {\n script_content.push_str(&format!(\n \"export PYTHONPATH=\\\"{}:$PYTHONPATH\\\"\\n\",\n python_lib_path.display()\n ));\n debug!(\n \" (Wrapper will set PYTHONPATH to {})\",\n python_lib_path.display()\n );\n }\n\n script_content.push_str(&format!(\n \"\\nexec \\\"{}\\\" \\\"$@\\\"\\n\",\n target_executable.display()\n ));\n\n let mut file = fs::File::create(wrapper_path).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed create wrapper {}: {}\", wrapper_path.display(), e),\n )))\n })?;\n file.write_all(script_content.as_bytes()).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed write wrapper {}: {}\", wrapper_path.display(), e),\n )))\n })?;\n\n #[cfg(unix)]\n {\n let metadata = file.metadata()?;\n let mut permissions = metadata.permissions();\n permissions.set_mode(0o755);\n fs::set_permissions(wrapper_path, permissions).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\n \"Failed set wrapper executable {}: {}\",\n wrapper_path.display(),\n e\n ),\n )))\n })?;\n }\n\n Ok(())\n}\n\nfn determine_content_root(installed_keg_path: &Path) -> Result {\n let mut potential_subdirs = Vec::new();\n let mut top_level_files_found = false;\n if !installed_keg_path.is_dir() {\n error!(\n \"Keg path {} does not exist or is not a directory!\",\n installed_keg_path.display()\n );\n return Err(SpsError::NotFound(format!(\n \"Keg path not found: {}\",\n installed_keg_path.display()\n )));\n }\n match fs::read_dir(installed_keg_path) {\n Ok(entries) => {\n for entry_res in entries {\n if let Ok(entry) = entry_res {\n let path = entry.path();\n let file_name = entry.file_name();\n // --- Use OsStr comparison ---\n let file_name_osstr = file_name.as_os_str();\n if file_name_osstr.to_string_lossy().starts_with('.')\n || file_name_osstr == \"INSTALL_MANIFEST.json\"\n || file_name_osstr == \"INSTALL_RECEIPT.json\"\n {\n continue;\n }\n if path.is_dir() {\n // Store both path and name for check later\n potential_subdirs.push((path, file_name.to_string_lossy().to_string()));\n } else if path.is_file() {\n top_level_files_found = true;\n debug!(\n \"Found file '{}' at top level of keg {}, assuming no intermediate dir.\",\n file_name.to_string_lossy(), // Use lossy for display\n installed_keg_path.display()\n );\n break; // Stop scanning if top-level files found\n }\n } else {\n debug!(\n \"Failed to read directory entry in {}: {}\",\n installed_keg_path.display(),\n entry_res.err().unwrap() // Safe unwrap as we are in Err path\n );\n }\n }\n }\n Err(e) => {\n debug!(\n \"Could not read keg directory {} to check for intermediate dir: {}. Assuming keg path is content root.\",\n installed_keg_path.display(),\n e\n );\n return Ok(installed_keg_path.to_path_buf());\n }\n }\n\n // --- MODIFIED LOGIC ---\n if potential_subdirs.len() == 1 && !top_level_files_found {\n // Get the single subdirectory path and name\n let (intermediate_dir_path, intermediate_dir_name) = potential_subdirs.remove(0); // Use remove\n\n // Check if the single directory name is one of the standard install dirs\n if STANDARD_KEG_DIRS.contains(&intermediate_dir_name.as_str()) {\n debug!(\n \"Single directory found ('{}') is a standard directory. Using main keg directory {} as content root.\",\n intermediate_dir_name,\n installed_keg_path.display()\n );\n Ok(installed_keg_path.to_path_buf()) // Use main keg path\n } else {\n // Single dir is NOT a standard name, assume it's an intermediate content root\n debug!(\n \"Detected single non-standard intermediate content directory: {}\",\n intermediate_dir_path.display()\n );\n Ok(intermediate_dir_path) // Use the intermediate dir\n }\n // --- END MODIFIED LOGIC ---\n } else {\n // Handle multiple subdirs or top-level files found case (no change needed here)\n if potential_subdirs.len() > 1 {\n debug!(\n \"Multiple potential content directories found under keg {}. Using main keg directory as content root.\",\n installed_keg_path.display()\n );\n } else if top_level_files_found {\n debug!(\n \"Top-level files found in keg {}. Using main keg directory as content root.\",\n installed_keg_path.display()\n );\n } else if potential_subdirs.is_empty() {\n // Changed from else if to else\n debug!(\n \"No subdirectories or files found (excluding ignored ones) in keg {}. Using main keg directory as content root.\",\n installed_keg_path.display()\n );\n }\n Ok(installed_keg_path.to_path_buf()) // Use main keg path in these cases too\n }\n}\n\nfn remove_existing_link_target(path: &Path) -> Result<()> {\n match path.symlink_metadata() {\n Ok(metadata) => {\n debug!(\n \" Removing existing item at link target: {}\",\n path.display()\n );\n let is_dir = metadata.file_type().is_dir();\n let is_symlink = metadata.file_type().is_symlink();\n let is_real_dir = is_dir && !is_symlink;\n let remove_result = if is_real_dir {\n fs::remove_dir_all(path)\n } else {\n fs::remove_file(path)\n };\n if let Err(e) = remove_result {\n debug!(\n \" Failed to remove existing item at link target {}: {}\",\n path.display(),\n e\n );\n return Err(SpsError::Io(std::sync::Arc::new(e)));\n }\n Ok(())\n }\n Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),\n Err(e) => {\n debug!(\n \" Failed to get metadata for existing item {}: {}\",\n path.display(),\n e\n );\n Err(SpsError::Io(std::sync::Arc::new(e)))\n }\n }\n}\n\nfn write_install_manifest(installed_keg_path: &Path, symlinks_created: &[String]) -> Result<()> {\n let manifest_path = installed_keg_path.join(\"INSTALL_MANIFEST.json\");\n debug!(\"Writing install manifest to: {}\", manifest_path.display());\n match serde_json::to_string_pretty(&symlinks_created) {\n Ok(manifest_json) => match fs::write(&manifest_path, manifest_json) {\n Ok(_) => {\n debug!(\n \"Wrote install manifest with {} links: {}\",\n symlinks_created.len(),\n manifest_path.display()\n );\n }\n Err(e) => {\n error!(\n \"Failed to write install manifest {}: {}\",\n manifest_path.display(),\n e\n );\n return Err(SpsError::Io(std::sync::Arc::new(e)));\n }\n },\n Err(e) => {\n error!(\"Failed to serialize install manifest data: {}\", e);\n return Err(SpsError::Json(std::sync::Arc::new(e)));\n }\n }\n Ok(())\n}\n\npub fn unlink_formula_artifacts(\n formula_name: &str,\n version_str_full: &str, // e.g., \"1.2.3_1\"\n config: &Config,\n) -> Result<()> {\n debug!(\n \"Unlinking artifacts for {} version {}\",\n formula_name, version_str_full\n );\n // Use config method to get expected keg path based on name and version string\n let expected_keg_path = config.formula_keg_path(formula_name, version_str_full);\n let manifest_path = expected_keg_path.join(\"INSTALL_MANIFEST.json\"); // Manifest *inside* the keg\n\n if manifest_path.is_file() {\n debug!(\"Reading install manifest: {}\", manifest_path.display());\n match fs::read_to_string(&manifest_path) {\n Ok(manifest_str) => {\n match serde_json::from_str::>(&manifest_str) {\n Ok(links_to_remove) => {\n let mut unlinked_count = 0;\n let mut removal_errors = 0;\n if links_to_remove.is_empty() {\n debug!(\n \"Install manifest {} is empty. Cannot perform manifest-based unlink.\",\n manifest_path.display()\n );\n } else {\n // Use Config to get base paths for checking ownership/safety\n let opt_base = config.opt_dir();\n let bin_base = config.bin_dir();\n let lib_base = config.sps_root().join(\"lib\");\n let include_base = config.sps_root().join(\"include\");\n let share_base = config.sps_root().join(\"share\");\n // Add etc, sbin etc. if needed\n\n for link_str in links_to_remove {\n let link_path = PathBuf::from(link_str);\n // Check if it's under a managed directory (safety check)\n if link_path.starts_with(&opt_base)\n || link_path.starts_with(&bin_base)\n || link_path.starts_with(&lib_base)\n || link_path.starts_with(&include_base)\n || link_path.starts_with(&share_base)\n {\n match remove_existing_link_target(&link_path) {\n // Use helper\n Ok(_) => {\n debug!(\"Removed link/wrapper: {}\", link_path.display());\n unlinked_count += 1;\n }\n Err(e) => {\n // Log error but continue trying to remove others\n debug!(\n \"Failed to remove link/wrapper {}: {}\",\n link_path.display(),\n e\n );\n removal_errors += 1;\n }\n }\n } else {\n // This indicates a potentially corrupted manifest or a link\n // outside expected areas\n error!(\n \"Manifest contains unexpected link path, skipping removal: {}\",\n link_path.display()\n );\n removal_errors += 1; // Count as an error/problem\n }\n }\n }\n debug!(\n \"Attempted to unlink {} artifacts based on manifest.\",\n unlinked_count\n );\n if removal_errors > 0 {\n error!(\n \"Encountered {} errors while removing links listed in manifest.\",\n removal_errors\n );\n // Decide if this should be a hard error - perhaps not if keg is being\n // removed anyway? For now, just log\n // warnings.\n }\n Ok(()) // Return Ok even if some links failed, keg removal will happen next\n }\n Err(e) => {\n error!(\n \"Failed to parse formula install manifest {}: {}. Proceeding without detailed unlink.\",\n manifest_path.display(),\n e\n );\n // Don't error out, allow keg removal to proceed.\n Ok(())\n }\n }\n }\n Err(e) => {\n error!(\n \"Failed to read formula install manifest {}: {}. Proceeding without detailed unlink.\",\n manifest_path.display(),\n e\n );\n // Don't error out, allow keg removal to proceed.\n Ok(())\n }\n }\n } else {\n debug!(\n \"Warning: No install manifest found at {}. Cannot perform detailed unlink.\",\n manifest_path.display()\n );\n // Don't error out, allow keg removal to proceed.\n Ok(())\n }\n}\n\nfn is_executable(path: &Path) -> Result {\n if !path.try_exists().unwrap_or(false) || !path.is_file() {\n return Ok(false);\n }\n if cfg!(unix) {\n use std::os::unix::fs::PermissionsExt;\n match fs::metadata(path) {\n Ok(metadata) => Ok(metadata.permissions().mode() & 0o111 != 0),\n Err(e) => Err(SpsError::Io(std::sync::Arc::new(e))),\n }\n } else {\n Ok(true)\n }\n}\n"], ["/sps/sps-core/src/pipeline/worker.rs", "// sps-core/src/pipeline/worker.rs\nuse std::fs;\nuse std::path::PathBuf;\nuse std::sync::Arc;\n\nuse futures::executor::block_on;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::dependency::DependencyExt;\nuse sps_common::error::{Result as SpsResult, SpsError};\nuse sps_common::keg::KegRegistry;\nuse sps_common::model::formula::FormulaDependencies;\nuse sps_common::model::InstallTargetIdentifier;\nuse sps_common::pipeline::{JobAction, PipelineEvent, PipelinePackageType, WorkerJob};\nuse tokio::sync::broadcast;\nuse tracing::{debug, error, instrument, warn};\n\nuse crate::check::installed::{InstalledPackageInfo, PackageType as CorePackageType};\nuse crate::{build, install, uninstall, upgrade};\n\npub(super) fn execute_sync_job(\n worker_job: WorkerJob,\n config: &Config,\n cache: Arc,\n event_tx: broadcast::Sender,\n) -> std::result::Result<(JobAction, PipelinePackageType), Box<(JobAction, SpsError)>> {\n let action = worker_job.request.action.clone();\n\n let result = do_execute_sync_steps(worker_job, config, cache, event_tx);\n\n result\n .map_err(|e| Box::new((action.clone(), e)))\n .map(|pkg_type| (action, pkg_type))\n}\n\n#[instrument(skip_all, fields(job_id = %worker_job.request.target_id, action = ?worker_job.request.action))]\nfn do_execute_sync_steps(\n worker_job: WorkerJob,\n config: &Config,\n _cache: Arc, // Marked as unused if cache is not directly used in this function body\n event_tx: broadcast::Sender,\n) -> SpsResult {\n let job_request = worker_job.request;\n let download_path = worker_job.download_path;\n let is_source_from_private_store = worker_job.is_source_from_private_store;\n\n let (core_pkg_type, pipeline_pkg_type) = match &job_request.target_definition {\n InstallTargetIdentifier::Formula(_) => {\n (CorePackageType::Formula, PipelinePackageType::Formula)\n }\n InstallTargetIdentifier::Cask(_) => (CorePackageType::Cask, PipelinePackageType::Cask),\n };\n\n // Check dependencies before proceeding with formula install/upgrade\n if let InstallTargetIdentifier::Formula(formula_arc) = &job_request.target_definition {\n if matches!(job_request.action, JobAction::Install)\n || matches!(job_request.action, JobAction::Upgrade { .. })\n {\n debug!(\n \"[WORKER:{}] Pre-install check for dependencies. Formula: {}, Action: {:?}\",\n job_request.target_id,\n formula_arc.name(),\n job_request.action\n );\n\n let keg_registry = KegRegistry::new(config.clone());\n match formula_arc.dependencies() {\n Ok(dependencies) => {\n for dep in dependencies.runtime() {\n debug!(\"[WORKER:{}] Checking runtime dependency: '{}'. Required by: '{}'. Configured cellar: {}\", job_request.target_id, dep.name, formula_arc.name(), config.cellar_dir().display());\n\n match keg_registry.get_installed_keg(&dep.name) {\n Ok(Some(keg_info)) => {\n debug!(\"[WORKER:{}] Dependency '{}' FOUND by KegRegistry. Path: {}, Version: {}\", job_request.target_id, dep.name, keg_info.path.display(), keg_info.version_str);\n }\n Ok(None) => {\n debug!(\"[WORKER:{}] Dependency '{}' was NOT FOUND by KegRegistry for formula '{}'. THIS IS THE ERROR POINT.\", dep.name, job_request.target_id, formula_arc.name());\n let error_msg = format!(\n \"Runtime dependency '{}' for formula '{}' is not installed. Aborting operation for '{}'.\",\n dep.name, formula_arc.name(), job_request.target_id\n );\n error!(\"{}\", error_msg);\n return Err(SpsError::DependencyError(error_msg));\n }\n Err(e) => {\n debug!(\"[WORKER:{}] Error during KegRegistry check for dependency '{}': {}. Aborting for formula '{}'.\", job_request.target_id, dep.name, e, job_request.target_id);\n return Err(SpsError::Generic(format!(\n \"Failed to check KegRegistry for {}: {}\",\n dep.name, e\n )));\n }\n }\n }\n }\n Err(e) => {\n let error_msg = format!(\n \"Could not retrieve dependency list for formula '{}': {}. Aborting operation.\",\n job_request.target_id, e\n );\n error!(\"{}\", error_msg);\n return Err(SpsError::DependencyError(error_msg));\n }\n }\n debug!(\n \"[WORKER:{}] All required formula dependencies appear to be installed for '{}'.\",\n job_request.target_id,\n formula_arc.name()\n );\n }\n }\n\n let mut formula_installed_path: Option = None;\n\n match &job_request.action {\n JobAction::Upgrade {\n from_version,\n old_install_path,\n } => {\n debug!(\n \"[{}] Upgrading from version {}\",\n job_request.target_id, from_version\n );\n let old_info = InstalledPackageInfo {\n name: job_request.target_id.clone(),\n version: from_version.clone(),\n pkg_type: core_pkg_type.clone(),\n path: old_install_path.clone(),\n };\n\n match &job_request.target_definition {\n InstallTargetIdentifier::Formula(formula) => {\n let http_client_for_bottle_upgrade = Arc::new(reqwest::Client::new());\n let installed_path = if job_request.is_source_build {\n let _ = event_tx.send(PipelineEvent::BuildStarted {\n target_id: job_request.target_id.clone(),\n });\n let all_dep_paths = Vec::new(); // TODO: Populate this correctly if needed by upgrade_source_formula\n block_on(upgrade::source::upgrade_source_formula(\n formula,\n &download_path,\n &old_info,\n config,\n &all_dep_paths,\n ))?\n } else {\n block_on(upgrade::bottle::upgrade_bottle_formula(\n formula,\n &download_path,\n &old_info,\n config,\n http_client_for_bottle_upgrade,\n ))?\n };\n formula_installed_path = Some(installed_path);\n }\n InstallTargetIdentifier::Cask(cask) => {\n block_on(upgrade::cask::upgrade_cask_package(\n cask,\n &download_path,\n &old_info,\n config,\n ))?;\n }\n }\n }\n JobAction::Install | JobAction::Reinstall { .. } => {\n if let JobAction::Reinstall {\n version: from_version,\n current_install_path: old_install_path,\n } = &job_request.action\n {\n debug!(\n \"[{}] Reinstall: Removing existing version {}...\",\n job_request.target_id, from_version\n );\n let _ = event_tx.send(PipelineEvent::UninstallStarted {\n target_id: job_request.target_id.clone(),\n version: from_version.clone(),\n });\n\n let old_info_for_reinstall = InstalledPackageInfo {\n name: job_request.target_id.clone(),\n version: from_version.clone(),\n pkg_type: core_pkg_type.clone(),\n path: old_install_path.clone(),\n };\n let uninstall_opts = uninstall::UninstallOptions { skip_zap: true };\n\n match core_pkg_type {\n CorePackageType::Formula => uninstall::uninstall_formula_artifacts(\n &old_info_for_reinstall,\n config,\n &uninstall_opts,\n )?,\n CorePackageType::Cask => {\n uninstall::uninstall_cask_artifacts(&old_info_for_reinstall, config)?\n }\n }\n debug!(\n \"[{}] Reinstall: Removed existing version {}.\",\n job_request.target_id, from_version\n );\n let _ = event_tx.send(PipelineEvent::UninstallFinished {\n target_id: job_request.target_id.clone(),\n version: from_version.clone(),\n });\n }\n\n let _ = event_tx.send(PipelineEvent::InstallStarted {\n target_id: job_request.target_id.clone(),\n pkg_type: pipeline_pkg_type,\n });\n\n match &job_request.target_definition {\n InstallTargetIdentifier::Formula(formula) => {\n let install_dir_base =\n (**formula).install_prefix(config.cellar_dir().as_path())?;\n if let Some(parent_dir) = install_dir_base.parent() {\n fs::create_dir_all(parent_dir).map_err(|e| SpsError::Io(Arc::new(e)))?;\n }\n\n if job_request.is_source_build {\n debug!(\"[{}] Building from source...\", job_request.target_id);\n let _ = event_tx.send(PipelineEvent::BuildStarted {\n target_id: job_request.target_id.clone(),\n });\n let build_dep_paths: Vec = vec![]; // TODO: Populate this from ResolvedGraph\n\n let build_future = build::compile::build_from_source(\n &download_path,\n formula,\n config,\n &build_dep_paths,\n );\n let installed_dir = block_on(build_future)?;\n formula_installed_path = Some(installed_dir);\n } else {\n debug!(\"[{}] Installing bottle...\", job_request.target_id);\n let installed_dir =\n install::bottle::exec::install_bottle(&download_path, formula, config)?;\n formula_installed_path = Some(installed_dir);\n }\n }\n InstallTargetIdentifier::Cask(cask) => {\n if is_source_from_private_store {\n debug!(\n \"[{}] Reinstalling cask from private store...\",\n job_request.target_id\n );\n\n if let Some(file_name) = download_path.file_name() {\n let app_name = file_name.to_string_lossy().to_string();\n let applications_app_path = config.applications_dir().join(&app_name);\n\n if applications_app_path.exists()\n || applications_app_path.symlink_metadata().is_ok()\n {\n debug!(\n \"Removing existing app at {}\",\n applications_app_path.display()\n );\n let _ = install::cask::helpers::remove_path_robustly(\n &applications_app_path,\n config,\n true,\n );\n }\n\n debug!(\n \"Symlinking app from private store {} to {}\",\n download_path.display(),\n applications_app_path.display()\n );\n if let Err(e) =\n std::os::unix::fs::symlink(&download_path, &applications_app_path)\n {\n return Err(SpsError::InstallError(format!(\n \"Failed to symlink app from private store to {}: {}\",\n applications_app_path.display(),\n e\n )));\n }\n\n let cask_version =\n cask.version.clone().unwrap_or_else(|| \"latest\".to_string());\n let cask_version_path =\n config.cask_room_version_path(&cask.token, &cask_version);\n\n if !cask_version_path.exists() {\n fs::create_dir_all(&cask_version_path)?;\n }\n\n let caskroom_symlink_path = cask_version_path.join(&app_name);\n if caskroom_symlink_path.exists()\n || caskroom_symlink_path.symlink_metadata().is_ok()\n {\n let _ = fs::remove_file(&caskroom_symlink_path);\n }\n\n #[cfg(unix)]\n {\n if let Err(e) = std::os::unix::fs::symlink(\n &applications_app_path,\n &caskroom_symlink_path,\n ) {\n warn!(\"Failed to create Caskroom symlink: {}\", e);\n }\n }\n\n let created_artifacts = vec![\n sps_common::model::artifact::InstalledArtifact::AppBundle {\n path: applications_app_path.clone(),\n },\n sps_common::model::artifact::InstalledArtifact::CaskroomLink {\n link_path: caskroom_symlink_path.clone(),\n target_path: applications_app_path.clone(),\n },\n ];\n\n debug!(\n \"[{}] Writing manifest for private store reinstall...\",\n job_request.target_id\n );\n if let Err(e) = install::cask::write_cask_manifest(\n cask,\n &cask_version_path,\n created_artifacts,\n ) {\n error!(\n \"[{}] Failed to write CASK_INSTALL_MANIFEST.json during private store reinstall: {}\",\n job_request.target_id, e\n );\n return Err(SpsError::InstallError(format!(\n \"Failed to write manifest during private store reinstall for {}: {}\",\n job_request.target_id, e\n )));\n }\n } else {\n return Err(SpsError::InstallError(format!(\n \"Failed to get app name from private store path: {}\",\n download_path.display()\n )));\n }\n } else {\n debug!(\"[{}] Installing cask...\", job_request.target_id);\n install::cask::install_cask(\n cask,\n &download_path,\n config,\n &job_request.action,\n )?;\n }\n }\n }\n }\n };\n\n if let Some(ref installed_path) = formula_installed_path {\n debug!(\n \"[{}] Formula operation resulted in keg path: {}\",\n job_request.target_id,\n installed_path.display()\n );\n } else if core_pkg_type == CorePackageType::Cask {\n debug!(\"[{}] Cask operation completed.\", job_request.target_id);\n }\n\n if let (InstallTargetIdentifier::Formula(formula), Some(keg_path_for_linking)) =\n (&job_request.target_definition, &formula_installed_path)\n {\n debug!(\n \"[{}] Linking artifacts for formula {}...\",\n job_request.target_id,\n (**formula).name()\n );\n let _ = event_tx.send(PipelineEvent::LinkStarted {\n target_id: job_request.target_id.clone(),\n pkg_type: pipeline_pkg_type,\n });\n install::bottle::link::link_formula_artifacts(formula, keg_path_for_linking, config)?;\n debug!(\n \"[{}] Linking complete for formula {}.\",\n job_request.target_id,\n (**formula).name()\n );\n }\n\n Ok(pipeline_pkg_type)\n}\n"], ["/sps/sps/src/pipeline/planner.rs", "// sps/src/pipeline/planner.rs\nuse std::collections::{HashMap, HashSet, VecDeque};\nuse std::path::{Path, PathBuf};\nuse std::sync::Arc;\n\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::dependency::resolver::{\n DependencyResolver, NodeInstallStrategy, PerTargetInstallPreferences, ResolutionContext,\n ResolutionStatus, ResolvedGraph,\n};\nuse sps_common::error::{Result as SpsResult, SpsError};\nuse sps_common::formulary::Formulary;\nuse sps_common::keg::KegRegistry;\nuse sps_common::model::{Cask, Formula, InstallTargetIdentifier};\nuse sps_common::pipeline::{JobAction, PipelineEvent, PlannedJob, PlannedOperations};\nuse sps_core::check::installed::{self, InstalledPackageInfo, PackageType as CorePackageType};\nuse sps_core::check::update::{self, UpdateInfo};\nuse tokio::sync::broadcast;\nuse tokio::task::JoinSet;\nuse tracing::{debug, error as trace_error, instrument, warn};\n\nuse super::runner::{get_panic_message, CommandType, PipelineFlags};\n\npub(crate) type PlanResult = SpsResult;\n\n#[derive(Debug, Default)]\nstruct IntermediatePlan {\n initial_ops: HashMap)>,\n errors: Vec<(String, SpsError)>,\n already_satisfied: HashSet,\n processed_globally: HashSet,\n private_store_sources: HashMap,\n}\n\n#[instrument(skip(cache))]\npub(crate) async fn fetch_target_definitions(\n names: &[String],\n cache: Arc,\n) -> HashMap> {\n let mut results = HashMap::new();\n if names.is_empty() {\n return results;\n }\n let mut futures = JoinSet::new();\n\n let formulae_map_handle = tokio::spawn(load_or_fetch_formulae_map(cache.clone()));\n let casks_map_handle = tokio::spawn(load_or_fetch_casks_map(cache.clone()));\n\n let formulae_map = match formulae_map_handle.await {\n Ok(Ok(map)) => Some(map),\n Ok(Err(e)) => {\n debug!(\"[FetchDefs] Failed to load/fetch full formulae list: {}\", e);\n None\n }\n Err(e) => {\n warn!(\n \"[FetchDefs] Formulae map loading task panicked: {}\",\n get_panic_message(e.into_panic()) // Ensure get_panic_message is accessible\n );\n None\n }\n };\n let casks_map = match casks_map_handle.await {\n Ok(Ok(map)) => Some(map),\n Ok(Err(e)) => {\n debug!(\"[FetchDefs] Failed to load/fetch full casks list: {}\", e);\n None\n }\n Err(e) => {\n warn!(\n \"[FetchDefs] Casks map loading task panicked: {}\",\n get_panic_message(e.into_panic()) // Ensure get_panic_message is accessible\n );\n None\n }\n };\n\n for name_str in names {\n let name_owned = name_str.to_string();\n let local_formulae_map = formulae_map.clone();\n let local_casks_map = casks_map.clone();\n\n futures.spawn(async move {\n if let Some(ref map) = local_formulae_map {\n if let Some(f_arc) = map.get(&name_owned) {\n return (name_owned, Ok(InstallTargetIdentifier::Formula(f_arc.clone())));\n }\n }\n if let Some(ref map) = local_casks_map {\n if let Some(c_arc) = map.get(&name_owned) {\n return (name_owned, Ok(InstallTargetIdentifier::Cask(c_arc.clone())));\n }\n }\n debug!(\"[FetchDefs] Definition for '{}' not found in cached lists, fetching directly from API...\", name_owned);\n match sps_net::api::get_formula(&name_owned).await {\n Ok(formula_obj) => return (name_owned, Ok(InstallTargetIdentifier::Formula(Arc::new(formula_obj)))),\n Err(SpsError::NotFound(_)) => {}\n Err(e) => return (name_owned, Err(e)),\n }\n match sps_net::api::get_cask(&name_owned).await {\n Ok(cask_obj) => (name_owned, Ok(InstallTargetIdentifier::Cask(Arc::new(cask_obj)))),\n Err(SpsError::NotFound(_)) => (name_owned.clone(), Err(SpsError::NotFound(format!(\"Formula or Cask '{name_owned}' not found\")))),\n Err(e) => (name_owned, Err(e)),\n }\n });\n }\n\n while let Some(res) = futures.join_next().await {\n match res {\n Ok((name, result)) => {\n results.insert(name, result);\n }\n Err(e) => {\n let panic_message = get_panic_message(e.into_panic());\n trace_error!(\n \"[FetchDefs] Task panicked during definition fetch: {}\",\n panic_message\n );\n results.insert(\n format!(\"[unknown_target_due_to_panic_{}]\", results.len()),\n Err(SpsError::Generic(format!(\n \"Definition fetching task panicked: {panic_message}\"\n ))),\n );\n }\n }\n }\n results\n}\n\nasync fn load_or_fetch_formulae_map(cache: Arc) -> SpsResult>> {\n match cache.load_raw(\"formula.json\") {\n Ok(data) => {\n let formulas: Vec = serde_json::from_str(&data)\n .map_err(|e| SpsError::Cache(format!(\"Parse cached formula.json failed: {e}\")))?;\n Ok(formulas\n .into_iter()\n .map(|f| (f.name.clone(), Arc::new(f)))\n .collect())\n }\n Err(_) => {\n debug!(\"[FetchDefs] Cache miss for formula.json, fetching from API...\");\n let raw_data = sps_net::api::fetch_all_formulas().await?;\n if let Err(e) = cache.store_raw(\"formula.json\", &raw_data) {\n warn!(\"Failed to store formula.json in cache: {}\", e);\n }\n let formulas: Vec =\n serde_json::from_str(&raw_data).map_err(|e| SpsError::Json(Arc::new(e)))?;\n Ok(formulas\n .into_iter()\n .map(|f| (f.name.clone(), Arc::new(f)))\n .collect())\n }\n }\n}\n\nasync fn load_or_fetch_casks_map(cache: Arc) -> SpsResult>> {\n match cache.load_raw(\"cask.json\") {\n Ok(data) => {\n let casks: Vec = serde_json::from_str(&data)\n .map_err(|e| SpsError::Cache(format!(\"Parse cached cask.json failed: {e}\")))?;\n Ok(casks\n .into_iter()\n .map(|c| (c.token.clone(), Arc::new(c)))\n .collect())\n }\n Err(_) => {\n debug!(\"[FetchDefs] Cache miss for cask.json, fetching from API...\");\n let raw_data = sps_net::api::fetch_all_casks().await?;\n if let Err(e) = cache.store_raw(\"cask.json\", &raw_data) {\n warn!(\"Failed to store cask.json in cache: {}\", e);\n }\n let casks: Vec =\n serde_json::from_str(&raw_data).map_err(|e| SpsError::Json(Arc::new(e)))?;\n Ok(casks\n .into_iter()\n .map(|c| (c.token.clone(), Arc::new(c)))\n .collect())\n }\n }\n}\n\npub(crate) struct OperationPlanner<'a> {\n config: &'a Config,\n cache: Arc,\n flags: &'a PipelineFlags,\n event_tx: broadcast::Sender,\n}\n\nimpl<'a> OperationPlanner<'a> {\n pub fn new(\n config: &'a Config,\n cache: Arc,\n flags: &'a PipelineFlags,\n event_tx: broadcast::Sender,\n ) -> Self {\n Self {\n config,\n cache,\n flags,\n event_tx,\n }\n }\n\n fn get_previous_installation_type(&self, old_keg_path: &Path) -> Option {\n let receipt_path = old_keg_path.join(\"INSTALL_RECEIPT.json\");\n if !receipt_path.is_file() {\n tracing::debug!(\n \"No INSTALL_RECEIPT.json found at {} for previous version.\",\n receipt_path.display()\n );\n return None;\n }\n\n match std::fs::read_to_string(&receipt_path) {\n Ok(content) => match serde_json::from_str::(&content) {\n Ok(json_value) => {\n let inst_type = json_value\n .get(\"installation_type\")\n .and_then(|it| it.as_str())\n .map(String::from);\n tracing::debug!(\n \"Previous installation type for {}: {:?}\",\n old_keg_path.display(),\n inst_type\n );\n inst_type\n }\n Err(e) => {\n tracing::warn!(\"Failed to parse INSTALL_RECEIPT.json at {}: {}. Cannot determine previous installation type.\", receipt_path.display(), e);\n None\n }\n },\n Err(e) => {\n tracing::warn!(\"Failed to read INSTALL_RECEIPT.json at {}: {}. Cannot determine previous installation type.\", receipt_path.display(), e);\n None\n }\n }\n }\n\n async fn check_installed_status(&self, name: &str) -> PlanResult> {\n installed::get_installed_package(name, self.config).await\n }\n\n async fn determine_cask_private_store_source(\n &self,\n name: &str,\n version_for_path: &str,\n ) -> Option {\n let cask_def_res = fetch_target_definitions(&[name.to_string()], self.cache.clone())\n .await\n .remove(name);\n\n if let Some(Ok(InstallTargetIdentifier::Cask(cask_arc))) = cask_def_res {\n if let Some(artifacts) = &cask_arc.artifacts {\n for artifact_entry in artifacts {\n if let Some(app_array) = artifact_entry.get(\"app\").and_then(|v| v.as_array()) {\n if let Some(app_name_val) = app_array.first() {\n if let Some(app_name_str) = app_name_val.as_str() {\n let private_path = self.config.cask_store_app_path(\n name,\n version_for_path,\n app_name_str,\n );\n if private_path.exists() && private_path.is_dir() {\n debug!(\"[Planner] Found reusable Cask private store bundle for {} version {}: {}\", name, version_for_path, private_path.display());\n return Some(private_path);\n }\n }\n }\n break;\n }\n }\n }\n }\n None\n }\n\n async fn plan_for_install(&self, targets: &[String]) -> PlanResult {\n let mut plan = IntermediatePlan::default();\n for name in targets {\n if plan.processed_globally.contains(name) {\n continue;\n }\n match self.check_installed_status(name).await {\n Ok(Some(installed_info)) => {\n let mut proceed_with_install = false;\n if installed_info.pkg_type == CorePackageType::Cask {\n let manifest_path = installed_info.path.join(\"CASK_INSTALL_MANIFEST.json\");\n if manifest_path.is_file() {\n if let Ok(manifest_str) = std::fs::read_to_string(&manifest_path) {\n if let Ok(manifest_json) =\n serde_json::from_str::(&manifest_str)\n {\n if let Some(is_installed_flag) =\n manifest_json.get(\"is_installed\").and_then(|v| v.as_bool())\n {\n if !is_installed_flag {\n debug!(\"Cask '{}' found but marked as not installed in manifest. Proceeding with install.\", name);\n proceed_with_install = true;\n }\n }\n }\n }\n } else {\n debug!(\n \"Cask '{}' found but manifest missing. Assuming needs install.\",\n name\n );\n proceed_with_install = true;\n }\n }\n if proceed_with_install {\n if let Some(private_path) = self\n .determine_cask_private_store_source(name, &installed_info.version)\n .await\n {\n plan.private_store_sources\n .insert(name.clone(), private_path);\n }\n plan.initial_ops\n .insert(name.clone(), (JobAction::Install, None));\n } else {\n debug!(\"Target '{}' already installed and manifest indicates it. Marking as satisfied.\", name);\n plan.already_satisfied.insert(name.clone());\n plan.processed_globally.insert(name.clone());\n }\n }\n Ok(None) => {\n if let Some(private_path) = self\n .determine_cask_private_store_source(name, \"latest\")\n .await\n {\n plan.private_store_sources\n .insert(name.clone(), private_path);\n }\n plan.initial_ops\n .insert(name.clone(), (JobAction::Install, None));\n }\n Err(e) => {\n plan.errors.push((\n name.clone(),\n SpsError::Generic(format!(\n \"Failed to check installed status for {name}: {e}\"\n )),\n ));\n plan.processed_globally.insert(name.clone());\n }\n }\n }\n Ok(plan)\n }\n\n async fn plan_for_reinstall(&self, targets: &[String]) -> PlanResult {\n let mut plan = IntermediatePlan::default();\n for name in targets {\n if plan.processed_globally.contains(name) {\n continue;\n }\n match self.check_installed_status(name).await {\n Ok(Some(installed_info)) => {\n if installed_info.pkg_type == CorePackageType::Cask {\n if let Some(private_path) = self\n .determine_cask_private_store_source(name, &installed_info.version)\n .await\n {\n plan.private_store_sources\n .insert(name.clone(), private_path);\n }\n }\n plan.initial_ops.insert(\n name.clone(),\n (\n JobAction::Reinstall {\n version: installed_info.version.clone(),\n current_install_path: installed_info.path.clone(),\n },\n None,\n ),\n );\n }\n Ok(None) => {\n plan.errors.push((\n name.clone(),\n SpsError::NotFound(format!(\"Cannot reinstall '{name}': not installed.\")),\n ));\n plan.processed_globally.insert(name.clone());\n }\n Err(e) => {\n plan.errors.push((\n name.clone(),\n SpsError::Generic(format!(\"Failed to check status for '{name}': {e}\")),\n ));\n plan.processed_globally.insert(name.clone());\n }\n }\n }\n Ok(plan)\n }\n\n async fn plan_for_upgrade(\n &self,\n targets: &[String],\n all: bool,\n ) -> PlanResult {\n let mut plan = IntermediatePlan::default();\n let packages_to_check = if all {\n installed::get_installed_packages(self.config)\n .await\n .map_err(|e| {\n plan.errors.push((\n \"\".to_string(),\n SpsError::Generic(format!(\"Failed to get installed packages: {e}\")),\n ));\n e\n })?\n } else {\n let mut specific = Vec::new();\n for name in targets {\n match self.check_installed_status(name).await {\n Ok(Some(info)) => {\n if info.pkg_type == CorePackageType::Cask {\n let manifest_path = info.path.join(\"CASK_INSTALL_MANIFEST.json\");\n if manifest_path.is_file() {\n if let Ok(manifest_str) = std::fs::read_to_string(&manifest_path) {\n if let Ok(manifest_json) =\n serde_json::from_str::(&manifest_str)\n {\n if !manifest_json\n .get(\"is_installed\")\n .and_then(|v| v.as_bool())\n .unwrap_or(true)\n {\n debug!(\"Skipping upgrade for Cask '{}' as its manifest indicates it's not fully installed.\", name);\n plan.processed_globally.insert(name.clone());\n continue;\n }\n }\n }\n }\n }\n specific.push(info);\n }\n Ok(None) => {\n plan.errors.push((\n name.to_string(),\n SpsError::NotFound(format!(\"Cannot upgrade '{name}': not installed.\")),\n ));\n plan.processed_globally.insert(name.clone());\n }\n Err(e) => {\n plan.errors.push((\n name.to_string(),\n SpsError::Generic(format!(\"Failed to check status for '{name}': {e}\")),\n ));\n plan.processed_globally.insert(name.clone());\n }\n }\n }\n specific\n };\n\n if packages_to_check.is_empty() {\n return Ok(plan);\n }\n\n match update::check_for_updates(&packages_to_check, &self.cache, self.config).await {\n Ok(updates) => {\n let update_map: HashMap =\n updates.into_iter().map(|u| (u.name.clone(), u)).collect();\n\n debug!(\n \"[Planner] Found {} available updates out of {} packages checked\",\n update_map.len(),\n packages_to_check.len()\n );\n debug!(\n \"[Planner] Available updates: {:?}\",\n update_map.keys().collect::>()\n );\n\n for p_info in packages_to_check {\n if plan.processed_globally.contains(&p_info.name) {\n continue;\n }\n if let Some(ui) = update_map.get(&p_info.name) {\n debug!(\n \"[Planner] Adding upgrade job for '{}': {} -> {}\",\n p_info.name, p_info.version, ui.available_version\n );\n plan.initial_ops.insert(\n p_info.name.clone(),\n (\n JobAction::Upgrade {\n from_version: p_info.version.clone(),\n old_install_path: p_info.path.clone(),\n },\n Some(ui.target_definition.clone()),\n ),\n );\n // Don't mark packages with updates as processed_globally\n // so they can be included in the final job list\n } else {\n debug!(\n \"[Planner] No update available for '{}', marking as already satisfied\",\n p_info.name\n );\n plan.already_satisfied.insert(p_info.name.clone());\n // Only mark packages without updates as processed_globally\n plan.processed_globally.insert(p_info.name.clone());\n }\n }\n }\n Err(e) => {\n plan.errors.push((\n \"[Update Check]\".to_string(),\n SpsError::Generic(format!(\"Failed to check for updates: {e}\")),\n ));\n }\n }\n Ok(plan)\n }\n\n // This now returns sps_common::pipeline::PlannedOperations\n pub async fn plan_operations(\n &self,\n initial_targets: &[String],\n command_type: CommandType,\n ) -> PlanResult {\n debug!(\n \"[Planner] Starting plan_operations with command_type: {:?}, targets: {:?}\",\n command_type, initial_targets\n );\n\n let mut intermediate_plan = match command_type {\n CommandType::Install => self.plan_for_install(initial_targets).await?,\n CommandType::Reinstall => self.plan_for_reinstall(initial_targets).await?,\n CommandType::Upgrade { all } => {\n debug!(\"[Planner] Calling plan_for_upgrade with all={}\", all);\n let plan = self.plan_for_upgrade(initial_targets, all).await?;\n debug!(\"[Planner] plan_for_upgrade returned with {} initial_ops, {} errors, {} already_satisfied\",\n plan.initial_ops.len(), plan.errors.len(), plan.already_satisfied.len());\n debug!(\n \"[Planner] Initial ops: {:?}\",\n plan.initial_ops.keys().collect::>()\n );\n debug!(\"[Planner] Already satisfied: {:?}\", plan.already_satisfied);\n plan\n }\n };\n\n let definitions_to_fetch: Vec = intermediate_plan\n .initial_ops\n .iter()\n .filter(|(name, (_, opt_def))| {\n opt_def.is_none() && !intermediate_plan.processed_globally.contains(*name)\n })\n .map(|(name, _)| name.clone())\n .collect();\n\n if !definitions_to_fetch.is_empty() {\n let fetched_defs =\n fetch_target_definitions(&definitions_to_fetch, self.cache.clone()).await;\n for (name, result) in fetched_defs {\n match result {\n Ok(target_def) => {\n if let Some((_action, opt_install_target)) =\n intermediate_plan.initial_ops.get_mut(&name)\n {\n *opt_install_target = Some(target_def);\n }\n }\n Err(e) => {\n intermediate_plan.errors.push((\n name.clone(),\n SpsError::Generic(format!(\"Failed to get definition for target: {e}\")),\n ));\n intermediate_plan.processed_globally.insert(name);\n }\n }\n }\n }\n self.event_tx\n .send(PipelineEvent::DependencyResolutionStarted)\n .ok();\n\n let mut formulae_for_resolution: HashMap = HashMap::new();\n let mut cask_deps_map: HashMap> = HashMap::new();\n let mut cask_processing_queue: VecDeque = VecDeque::new();\n\n for (name, (action, opt_def)) in &intermediate_plan.initial_ops {\n if intermediate_plan.processed_globally.contains(name) {\n continue;\n }\n\n // Handle both normal formula targets and upgrade targets\n match opt_def {\n Some(target @ InstallTargetIdentifier::Formula(_)) => {\n debug!(\n \"[Planner] Adding formula '{}' to resolution list with action {:?}\",\n name, action\n );\n formulae_for_resolution.insert(name.clone(), target.clone());\n }\n Some(InstallTargetIdentifier::Cask(c_arc)) => {\n debug!(\"[Planner] Adding cask '{}' to processing queue\", name);\n cask_processing_queue.push_back(name.clone());\n cask_deps_map.insert(name.clone(), c_arc.clone());\n }\n None => {\n if !intermediate_plan\n .errors\n .iter()\n .any(|(err_name, _)| err_name == name)\n {\n intermediate_plan.errors.push((\n name.clone(),\n SpsError::Generic(format!(\n \"Definition for '{name}' still missing after fetch attempt.\"\n )),\n ));\n intermediate_plan.processed_globally.insert(name.clone());\n }\n }\n }\n }\n\n let mut processed_casks_for_deps_pass: HashSet =\n intermediate_plan.processed_globally.clone();\n\n while let Some(cask_token) = cask_processing_queue.pop_front() {\n if processed_casks_for_deps_pass.contains(&cask_token) {\n continue;\n }\n processed_casks_for_deps_pass.insert(cask_token.clone());\n\n let cask_arc = match cask_deps_map.get(&cask_token) {\n Some(c) => c.clone(),\n None => {\n match fetch_target_definitions(\n std::slice::from_ref(&cask_token),\n self.cache.clone(),\n )\n .await\n .remove(&cask_token)\n {\n Some(Ok(InstallTargetIdentifier::Cask(c))) => {\n cask_deps_map.insert(cask_token.clone(), c.clone());\n c\n }\n Some(Err(e)) => {\n intermediate_plan.errors.push((cask_token.clone(), e));\n intermediate_plan\n .processed_globally\n .insert(cask_token.clone());\n continue;\n }\n _ => {\n intermediate_plan.errors.push((\n cask_token.clone(),\n SpsError::NotFound(format!(\n \"Cask definition for dependency '{cask_token}' not found.\"\n )),\n ));\n intermediate_plan\n .processed_globally\n .insert(cask_token.clone());\n continue;\n }\n }\n }\n };\n\n if let Some(deps) = &cask_arc.depends_on {\n for formula_dep_name in &deps.formula {\n if formulae_for_resolution.contains_key(formula_dep_name)\n || intermediate_plan\n .errors\n .iter()\n .any(|(n, _)| n == formula_dep_name)\n || intermediate_plan\n .already_satisfied\n .contains(formula_dep_name)\n {\n continue;\n }\n match fetch_target_definitions(\n std::slice::from_ref(formula_dep_name),\n self.cache.clone(),\n )\n .await\n .remove(formula_dep_name)\n {\n Some(Ok(target_def @ InstallTargetIdentifier::Formula(_))) => {\n formulae_for_resolution.insert(formula_dep_name.clone(), target_def);\n }\n Some(Ok(InstallTargetIdentifier::Cask(_))) => {\n intermediate_plan.errors.push((\n formula_dep_name.clone(),\n SpsError::Generic(format!(\n \"Dependency '{formula_dep_name}' of Cask '{cask_token}' is unexpectedly a Cask itself.\"\n )),\n ));\n intermediate_plan\n .processed_globally\n .insert(formula_dep_name.clone());\n }\n Some(Err(e)) => {\n intermediate_plan.errors.push((\n formula_dep_name.clone(),\n SpsError::Generic(format!(\n \"Failed def fetch for formula dep '{formula_dep_name}' of cask '{cask_token}': {e}\"\n )),\n ));\n intermediate_plan\n .processed_globally\n .insert(formula_dep_name.clone());\n }\n None => {\n intermediate_plan.errors.push((\n formula_dep_name.clone(),\n SpsError::NotFound(format!(\n \"Formula dep '{formula_dep_name}' for cask '{cask_token}' not found.\"\n )),\n ));\n intermediate_plan\n .processed_globally\n .insert(formula_dep_name.clone());\n }\n }\n }\n for dep_cask_token in &deps.cask {\n if !processed_casks_for_deps_pass.contains(dep_cask_token)\n && !cask_processing_queue.contains(dep_cask_token)\n {\n cask_processing_queue.push_back(dep_cask_token.clone());\n }\n }\n }\n }\n\n let mut resolved_formula_graph_opt: Option> = None;\n if !formulae_for_resolution.is_empty() {\n let targets_for_resolver: Vec<_> = formulae_for_resolution.keys().cloned().collect();\n let formulary = Formulary::new(self.config.clone());\n let keg_registry = KegRegistry::new(self.config.clone());\n\n let per_target_prefs = PerTargetInstallPreferences {\n force_source_build_targets: if self.flags.build_from_source {\n targets_for_resolver.iter().cloned().collect()\n } else {\n HashSet::new()\n },\n force_bottle_only_targets: HashSet::new(),\n };\n\n // Create map of initial target actions for the resolver\n let initial_target_actions: HashMap = intermediate_plan\n .initial_ops\n .iter()\n .filter_map(|(name, (action, _))| {\n if targets_for_resolver.contains(name) {\n Some((name.clone(), action.clone()))\n } else {\n debug!(\"[Planner] WARNING: Target '{}' with action {:?} is not in targets_for_resolver!\", name, action);\n None\n }\n })\n .collect();\n\n debug!(\n \"[Planner] Created initial_target_actions map with {} entries: {:?}\",\n initial_target_actions.len(),\n initial_target_actions\n );\n debug!(\"[Planner] Targets for resolver: {:?}\", targets_for_resolver);\n\n let ctx = ResolutionContext {\n formulary: &formulary,\n keg_registry: &keg_registry,\n sps_prefix: self.config.sps_root(),\n include_optional: self.flags.include_optional,\n include_test: false,\n skip_recommended: self.flags.skip_recommended,\n initial_target_preferences: &per_target_prefs,\n build_all_from_source: self.flags.build_from_source,\n cascade_source_preference_to_dependencies: true,\n has_bottle_for_current_platform:\n sps_core::install::bottle::has_bottle_for_current_platform,\n initial_target_actions: &initial_target_actions,\n };\n\n let mut resolver = DependencyResolver::new(ctx);\n debug!(\"[Planner] Created DependencyResolver, calling resolve_targets...\");\n match resolver.resolve_targets(&targets_for_resolver) {\n Ok(g) => {\n debug!(\n \"[Planner] Dependency resolution succeeded! Install plan has {} items\",\n g.install_plan.len()\n );\n resolved_formula_graph_opt = Some(Arc::new(g));\n }\n Err(e) => {\n debug!(\"[Planner] Dependency resolution failed: {}\", e);\n let resolver_error_msg = e.to_string(); // Capture full error\n for n in targets_for_resolver {\n if !intermediate_plan\n .errors\n .iter()\n .any(|(err_n, _)| err_n == &n)\n {\n intermediate_plan.errors.push((\n n.clone(),\n SpsError::DependencyError(resolver_error_msg.clone()),\n ));\n }\n intermediate_plan.processed_globally.insert(n);\n }\n }\n }\n }\n self.event_tx\n .send(PipelineEvent::DependencyResolutionFinished)\n .ok();\n\n let mut final_planned_jobs: Vec = Vec::new();\n let mut names_processed_from_initial_ops = HashSet::new();\n\n debug!(\n \"[Planner] Processing {} initial_ops into final jobs\",\n intermediate_plan.initial_ops.len()\n );\n for (name, (action, opt_def)) in &intermediate_plan.initial_ops {\n debug!(\n \"[Planner] Processing initial op '{}': action={:?}, has_def={}\",\n name,\n action,\n opt_def.is_some()\n );\n\n if intermediate_plan.processed_globally.contains(name) {\n debug!(\"[Planner] Skipping '{}' - already processed globally\", name);\n continue;\n }\n // If an error was recorded for this specific initial target (e.g. resolver failed for\n // it, or def missing) ensure it's marked as globally processed and not\n // added to final_planned_jobs.\n if intermediate_plan\n .errors\n .iter()\n .any(|(err_name, _)| err_name == name)\n {\n debug!(\"[Planner] Skipping job for initial op '{}' as an error was recorded for it during planning.\", name);\n intermediate_plan.processed_globally.insert(name.clone());\n continue;\n }\n if intermediate_plan.already_satisfied.contains(name) {\n debug!(\n \"[Planner] Skipping job for initial op '{}' as it's already satisfied.\",\n name\n );\n intermediate_plan.processed_globally.insert(name.clone());\n continue;\n }\n\n match opt_def {\n Some(target_def) => {\n let is_source_build = determine_build_strategy_for_job(\n target_def,\n action,\n self.flags,\n resolved_formula_graph_opt.as_deref(),\n self,\n );\n\n final_planned_jobs.push(PlannedJob {\n target_id: name.clone(),\n target_definition: target_def.clone(),\n action: action.clone(),\n is_source_build,\n use_private_store_source: intermediate_plan\n .private_store_sources\n .get(name)\n .cloned(),\n });\n names_processed_from_initial_ops.insert(name.clone());\n }\n None => {\n tracing::error!(\"[Planner] CRITICAL: Definition missing for planned operation on '{}' but no error was recorded in intermediate_plan.errors. This should not happen.\", name);\n if !intermediate_plan\n .errors\n .iter()\n .any(|(err_n, _)| err_n == name)\n {\n intermediate_plan.errors.push((\n name.clone(),\n SpsError::Generic(\"Definition missing unexpectedly.\".into()),\n ));\n }\n intermediate_plan.processed_globally.insert(name.clone());\n }\n }\n }\n\n if let Some(graph) = resolved_formula_graph_opt.as_ref() {\n for dep_detail in &graph.install_plan {\n let dep_name = dep_detail.formula.name();\n\n if names_processed_from_initial_ops.contains(dep_name)\n || intermediate_plan.processed_globally.contains(dep_name)\n || final_planned_jobs.iter().any(|j| j.target_id == dep_name)\n {\n continue;\n }\n\n if intermediate_plan\n .errors\n .iter()\n .any(|(err_name, _)| err_name == dep_name)\n {\n tracing::debug!(\"[Planner] Skipping job for dependency '{}' due to a pre-existing error recorded for it.\", dep_name);\n intermediate_plan\n .processed_globally\n .insert(dep_name.to_string());\n continue;\n }\n if dep_detail.status == ResolutionStatus::Failed {\n tracing::debug!(\"[Planner] Skipping job for dependency '{}' as its resolution status is Failed. Adding to planner errors.\", dep_name);\n // Ensure this error is also captured if not already.\n if !intermediate_plan\n .errors\n .iter()\n .any(|(err_name, _)| err_name == dep_name)\n {\n intermediate_plan.errors.push((\n dep_name.to_string(),\n SpsError::DependencyError(format!(\n \"Resolution failed for dependency {dep_name}\"\n )),\n ));\n }\n intermediate_plan\n .processed_globally\n .insert(dep_name.to_string());\n continue;\n }\n\n if matches!(\n dep_detail.status,\n ResolutionStatus::Missing | ResolutionStatus::Requested\n ) {\n let is_source_build_for_dep = determine_build_strategy_for_job(\n &InstallTargetIdentifier::Formula(dep_detail.formula.clone()),\n &JobAction::Install,\n self.flags,\n Some(graph),\n self,\n );\n debug!(\n \"Planning install for new formula dependency '{}'. Source build: {}\",\n dep_name, is_source_build_for_dep\n );\n\n final_planned_jobs.push(PlannedJob {\n target_id: dep_name.to_string(),\n target_definition: InstallTargetIdentifier::Formula(\n dep_detail.formula.clone(),\n ),\n action: JobAction::Install,\n is_source_build: is_source_build_for_dep,\n use_private_store_source: None,\n });\n } else if dep_detail.status == ResolutionStatus::Installed {\n intermediate_plan\n .already_satisfied\n .insert(dep_name.to_string());\n }\n }\n }\n\n for (cask_token, cask_arc) in cask_deps_map {\n if names_processed_from_initial_ops.contains(&cask_token)\n || intermediate_plan.processed_globally.contains(&cask_token)\n || final_planned_jobs.iter().any(|j| j.target_id == cask_token)\n {\n continue;\n }\n\n match self.check_installed_status(&cask_token).await {\n Ok(None) => {\n final_planned_jobs.push(PlannedJob {\n target_id: cask_token.clone(),\n target_definition: InstallTargetIdentifier::Cask(cask_arc.clone()),\n action: JobAction::Install,\n is_source_build: false,\n use_private_store_source: intermediate_plan\n .private_store_sources\n .get(&cask_token)\n .cloned(),\n });\n }\n Ok(Some(_installed_info)) => {\n intermediate_plan\n .already_satisfied\n .insert(cask_token.clone());\n }\n Err(e) => {\n intermediate_plan.errors.push((\n cask_token.clone(),\n SpsError::Generic(format!(\n \"Failed check install status for cask dependency {cask_token}: {e}\"\n )),\n ));\n intermediate_plan\n .processed_globally\n .insert(cask_token.clone());\n }\n }\n }\n if let Some(graph) = resolved_formula_graph_opt.as_ref() {\n if !final_planned_jobs.is_empty() {\n sort_planned_jobs(&mut final_planned_jobs, graph);\n }\n }\n\n debug!(\n \"[Planner] Finishing plan_operations with {} jobs, {} errors, {} already_satisfied\",\n final_planned_jobs.len(),\n intermediate_plan.errors.len(),\n intermediate_plan.already_satisfied.len()\n );\n debug!(\n \"[Planner] Final jobs: {:?}\",\n final_planned_jobs\n .iter()\n .map(|j| &j.target_id)\n .collect::>()\n );\n\n Ok(PlannedOperations {\n jobs: final_planned_jobs,\n errors: intermediate_plan.errors,\n already_installed_or_up_to_date: intermediate_plan.already_satisfied,\n resolved_graph: resolved_formula_graph_opt,\n })\n }\n}\n\nfn determine_build_strategy_for_job(\n target_def: &InstallTargetIdentifier,\n action: &JobAction,\n flags: &PipelineFlags,\n resolved_graph: Option<&ResolvedGraph>,\n planner: &OperationPlanner,\n) -> bool {\n match target_def {\n InstallTargetIdentifier::Formula(formula_arc) => {\n if flags.build_from_source {\n return true;\n }\n if let Some(graph) = resolved_graph {\n if let Some(resolved_detail) = graph.resolution_details.get(formula_arc.name()) {\n match resolved_detail.determined_install_strategy {\n NodeInstallStrategy::SourceOnly => return true,\n NodeInstallStrategy::BottleOrFail => return false,\n NodeInstallStrategy::BottlePreferred => {}\n }\n }\n }\n if let JobAction::Upgrade {\n old_install_path, ..\n } = action\n {\n if planner\n .get_previous_installation_type(old_install_path)\n .as_deref()\n == Some(\"source\")\n {\n return true;\n }\n }\n !sps_core::install::bottle::has_bottle_for_current_platform(formula_arc)\n }\n InstallTargetIdentifier::Cask(_) => false,\n }\n}\n\nfn sort_planned_jobs(jobs: &mut [PlannedJob], formula_graph: &ResolvedGraph) {\n let formula_order: HashMap = formula_graph\n .install_plan\n .iter()\n .enumerate()\n .map(|(idx, dep_detail)| (dep_detail.formula.name().to_string(), idx))\n .collect();\n\n jobs.sort_by_key(|job| match &job.target_definition {\n InstallTargetIdentifier::Formula(f_arc) => formula_order\n .get(f_arc.name())\n .copied()\n .unwrap_or(usize::MAX),\n InstallTargetIdentifier::Cask(_) => usize::MAX - 1,\n });\n}\n"], ["/sps/sps-common/src/dependency/resolver.rs", "// sps-common/src/dependency/resolver.rs\nuse std::collections::{HashMap, HashSet, VecDeque};\nuse std::path::{Path, PathBuf};\nuse std::sync::Arc;\n\nuse tracing::{debug, error, warn};\n\nuse crate::dependency::{Dependency, DependencyTag};\nuse crate::error::{Result, SpsError};\nuse crate::formulary::Formulary;\nuse crate::keg::KegRegistry;\nuse crate::model::formula::Formula;\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq)]\npub enum NodeInstallStrategy {\n BottlePreferred,\n SourceOnly,\n BottleOrFail,\n}\n\n#[derive(Debug, Clone, Default)]\npub struct PerTargetInstallPreferences {\n pub force_source_build_targets: HashSet,\n pub force_bottle_only_targets: HashSet,\n}\n\npub struct ResolutionContext<'a> {\n pub formulary: &'a Formulary,\n pub keg_registry: &'a KegRegistry,\n pub sps_prefix: &'a Path,\n pub include_optional: bool,\n pub include_test: bool,\n pub skip_recommended: bool,\n pub initial_target_preferences: &'a PerTargetInstallPreferences,\n pub build_all_from_source: bool,\n pub cascade_source_preference_to_dependencies: bool,\n pub has_bottle_for_current_platform: fn(&Formula) -> bool,\n pub initial_target_actions: &'a HashMap,\n}\n\n#[derive(Debug, Clone)]\npub struct ResolvedDependency {\n pub formula: Arc,\n pub keg_path: Option,\n pub opt_path: Option,\n pub status: ResolutionStatus,\n pub accumulated_tags: DependencyTag,\n pub determined_install_strategy: NodeInstallStrategy,\n pub failure_reason: Option,\n}\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq)]\npub enum ResolutionStatus {\n Installed,\n Missing,\n Requested,\n SkippedOptional,\n NotFound,\n Failed,\n}\n\n#[derive(Debug, Clone, Default)]\npub struct ResolvedGraph {\n pub install_plan: Vec,\n pub build_dependency_opt_paths: Vec,\n pub runtime_dependency_opt_paths: Vec,\n pub resolution_details: HashMap,\n}\n\n// Added empty constructor\nimpl ResolvedGraph {\n pub fn empty() -> Self {\n Default::default()\n }\n}\n\npub struct DependencyResolver<'a> {\n context: ResolutionContext<'a>,\n formula_cache: HashMap>,\n visiting: HashSet,\n resolution_details: HashMap,\n errors: HashMap>,\n}\n\nimpl<'a> DependencyResolver<'a> {\n pub fn new(context: ResolutionContext<'a>) -> Self {\n Self {\n context,\n formula_cache: HashMap::new(),\n visiting: HashSet::new(),\n resolution_details: HashMap::new(),\n errors: HashMap::new(),\n }\n }\n\n fn determine_node_install_strategy(\n &self,\n formula_name: &str,\n formula_arc: &Arc,\n is_initial_target: bool,\n requesting_parent_strategy: Option,\n ) -> NodeInstallStrategy {\n if is_initial_target {\n if self\n .context\n .initial_target_preferences\n .force_source_build_targets\n .contains(formula_name)\n {\n return NodeInstallStrategy::SourceOnly;\n }\n if self\n .context\n .initial_target_preferences\n .force_bottle_only_targets\n .contains(formula_name)\n {\n return NodeInstallStrategy::BottleOrFail;\n }\n }\n\n if self.context.build_all_from_source {\n return NodeInstallStrategy::SourceOnly;\n }\n\n if self.context.cascade_source_preference_to_dependencies\n && matches!(\n requesting_parent_strategy,\n Some(NodeInstallStrategy::SourceOnly)\n )\n {\n return NodeInstallStrategy::SourceOnly;\n }\n if matches!(\n requesting_parent_strategy,\n Some(NodeInstallStrategy::BottleOrFail)\n ) {\n return NodeInstallStrategy::BottleOrFail;\n }\n\n let strategy = if (self.context.has_bottle_for_current_platform)(formula_arc) {\n NodeInstallStrategy::BottlePreferred\n } else {\n NodeInstallStrategy::SourceOnly\n };\n\n debug!(\n \"Install strategy for '{formula_name}': {:?} (initial_target={is_initial_target}, parent={:?}, bottle_available={})\",\n strategy,\n requesting_parent_strategy,\n (self.context.has_bottle_for_current_platform)(formula_arc)\n );\n strategy\n }\n\n pub fn resolve_targets(&mut self, targets: &[String]) -> Result {\n debug!(\"Starting dependency resolution for targets: {:?}\", targets);\n self.visiting.clear();\n self.resolution_details.clear();\n self.errors.clear();\n\n for target_name in targets {\n if let Err(e) = self.resolve_recursive(target_name, DependencyTag::RUNTIME, true, None)\n {\n self.errors.insert(target_name.clone(), Arc::new(e));\n warn!(\n \"Resolution failed for target '{}', but continuing for others.\",\n target_name\n );\n }\n }\n\n debug!(\n \"Raw resolved map after initial pass: {:?}\",\n self.resolution_details\n .iter()\n .map(|(k, v)| (k.clone(), v.status, v.accumulated_tags))\n .collect::>()\n );\n\n let sorted_list = match self.topological_sort() {\n Ok(list) => list,\n Err(e @ SpsError::DependencyError(_)) => {\n error!(\"Topological sort failed due to dependency cycle: {}\", e);\n return Err(e);\n }\n Err(e) => {\n error!(\"Topological sort failed: {}\", e);\n return Err(e);\n }\n };\n\n let install_plan: Vec = sorted_list\n .into_iter()\n .filter(|dep| {\n matches!(\n dep.status,\n ResolutionStatus::Missing | ResolutionStatus::Requested\n )\n })\n .collect();\n\n let mut build_paths = Vec::new();\n let mut runtime_paths = Vec::new();\n let mut seen_build_paths = HashSet::new();\n let mut seen_runtime_paths = HashSet::new();\n\n for dep in self.resolution_details.values() {\n if matches!(\n dep.status,\n ResolutionStatus::Installed\n | ResolutionStatus::Requested\n | ResolutionStatus::Missing\n ) {\n if let Some(opt_path) = &dep.opt_path {\n if dep.accumulated_tags.contains(DependencyTag::BUILD)\n && seen_build_paths.insert(opt_path.clone())\n {\n debug!(\"Adding build dep path: {}\", opt_path.display());\n build_paths.push(opt_path.clone());\n }\n if dep.accumulated_tags.intersects(\n DependencyTag::RUNTIME\n | DependencyTag::RECOMMENDED\n | DependencyTag::OPTIONAL,\n ) && seen_runtime_paths.insert(opt_path.clone())\n {\n debug!(\"Adding runtime dep path: {}\", opt_path.display());\n runtime_paths.push(opt_path.clone());\n }\n } else if dep.status != ResolutionStatus::NotFound\n && dep.status != ResolutionStatus::Failed\n {\n debug!(\n \"Warning: No opt_path found for resolved dependency {} ({:?})\",\n dep.formula.name(),\n dep.status\n );\n }\n }\n }\n\n if !self.errors.is_empty() {\n warn!(\n \"Resolution encountered errors for specific targets: {:?}\",\n self.errors\n .iter()\n .map(|(k, v)| (k, v.to_string()))\n .collect::>()\n );\n }\n\n debug!(\n \"Final installation plan (needs install/build): {:?}\",\n install_plan\n .iter()\n .map(|d| (d.formula.name(), d.status))\n .collect::>()\n );\n debug!(\n \"Collected build dependency paths: {:?}\",\n build_paths.iter().map(|p| p.display()).collect::>()\n );\n debug!(\n \"Collected runtime dependency paths: {:?}\",\n runtime_paths\n .iter()\n .map(|p| p.display())\n .collect::>()\n );\n\n Ok(ResolvedGraph {\n install_plan,\n build_dependency_opt_paths: build_paths,\n runtime_dependency_opt_paths: runtime_paths,\n resolution_details: self.resolution_details.clone(),\n })\n }\n\n fn update_existing_resolution(\n &mut self,\n name: &str,\n tags_from_parent_edge: DependencyTag,\n is_initial_target: bool,\n ) -> Result {\n let Some(existing) = self.resolution_details.get_mut(name) else {\n return Ok(false);\n };\n\n let original_status = existing.status;\n let original_tags = existing.accumulated_tags;\n let has_keg = existing.keg_path.is_some();\n\n let mut new_status = original_status;\n if is_initial_target && new_status == ResolutionStatus::Missing {\n new_status = ResolutionStatus::Requested;\n }\n\n let skip_recommended = self.context.skip_recommended;\n let include_optional = self.context.include_optional;\n\n if Self::should_upgrade_optional_status_static(\n new_status,\n tags_from_parent_edge,\n is_initial_target,\n has_keg,\n skip_recommended,\n include_optional,\n ) {\n new_status = if has_keg {\n ResolutionStatus::Installed\n } else if is_initial_target {\n ResolutionStatus::Requested\n } else {\n ResolutionStatus::Missing\n };\n }\n\n let mut needs_revisit = false;\n if new_status != original_status {\n debug!(\n \"Updating status for '{name}' from {:?} to {:?}\",\n original_status, new_status\n );\n existing.status = new_status;\n needs_revisit = true;\n }\n\n let combined_tags = original_tags | tags_from_parent_edge;\n if combined_tags != original_tags {\n debug!(\n \"Updating tags for '{name}' from {:?} to {:?}\",\n original_tags, combined_tags\n );\n existing.accumulated_tags = combined_tags;\n needs_revisit = true;\n }\n\n if !needs_revisit {\n debug!(\"'{}' already resolved with compatible status/tags.\", name);\n } else {\n debug!(\n \"Re-evaluating dependencies for '{}' due to status/tag update\",\n name\n );\n }\n\n Ok(needs_revisit)\n }\n\n fn should_upgrade_optional_status_static(\n current_status: ResolutionStatus,\n tags_from_parent_edge: DependencyTag,\n is_initial_target: bool,\n _has_keg: bool,\n skip_recommended: bool,\n include_optional: bool,\n ) -> bool {\n current_status == ResolutionStatus::SkippedOptional\n && (tags_from_parent_edge.contains(DependencyTag::RUNTIME)\n || tags_from_parent_edge.contains(DependencyTag::BUILD)\n || (tags_from_parent_edge.contains(DependencyTag::RECOMMENDED)\n && !skip_recommended)\n || (is_initial_target && include_optional))\n }\n\n fn load_or_cache_formula(\n &mut self,\n name: &str,\n tags_from_parent_edge: DependencyTag,\n ) -> Result>> {\n if let Some(f) = self.formula_cache.get(name) {\n return Ok(Some(f.clone()));\n }\n\n debug!(\"Loading formula definition for '{}'\", name);\n match self.context.formulary.load_formula(name) {\n Ok(f) => {\n let arc = Arc::new(f);\n self.formula_cache.insert(name.to_string(), arc.clone());\n Ok(Some(arc))\n }\n Err(e) => {\n error!(\"Failed to load formula definition for '{}': {}\", name, e);\n let msg = e.to_string();\n self.resolution_details.insert(\n name.to_string(),\n ResolvedDependency {\n formula: Arc::new(Formula::placeholder(name)),\n keg_path: None,\n opt_path: None,\n status: ResolutionStatus::NotFound,\n accumulated_tags: tags_from_parent_edge,\n determined_install_strategy: NodeInstallStrategy::BottlePreferred,\n failure_reason: Some(msg.clone()),\n },\n );\n self.errors\n .insert(name.to_string(), Arc::new(SpsError::NotFound(msg)));\n Ok(None)\n }\n }\n }\n\n fn create_initial_resolution(\n &mut self,\n name: &str,\n formula_arc: Arc,\n tags_from_parent_edge: DependencyTag,\n is_initial_target: bool,\n requesting_parent_strategy: Option,\n ) -> Result<()> {\n let current_node_strategy = self.determine_node_install_strategy(\n name,\n &formula_arc,\n is_initial_target,\n requesting_parent_strategy,\n );\n\n let (status, keg_path) =\n self.determine_resolution_status(name, is_initial_target, current_node_strategy)?;\n\n debug!(\n \"Initial status for '{}': {:?}, keg: {:?}, opt: {}\",\n name,\n status,\n keg_path,\n self.context.keg_registry.get_opt_path(name).display()\n );\n\n self.resolution_details.insert(\n name.to_string(),\n ResolvedDependency {\n formula: formula_arc.clone(),\n keg_path,\n opt_path: Some(self.context.keg_registry.get_opt_path(name)),\n status,\n accumulated_tags: tags_from_parent_edge,\n determined_install_strategy: current_node_strategy,\n failure_reason: None,\n },\n );\n\n Ok(())\n }\n\n fn determine_resolution_status(\n &self,\n name: &str,\n is_initial_target: bool,\n strategy: NodeInstallStrategy,\n ) -> Result<(ResolutionStatus, Option)> {\n match strategy {\n NodeInstallStrategy::SourceOnly => Ok((\n if is_initial_target {\n ResolutionStatus::Requested\n } else {\n ResolutionStatus::Missing\n },\n None,\n )),\n NodeInstallStrategy::BottlePreferred | NodeInstallStrategy::BottleOrFail => {\n if let Some(keg) = self.context.keg_registry.get_installed_keg(name)? {\n // Check if this is an upgrade target - if so, mark as Requested even if\n // installed\n let should_request_upgrade = is_initial_target\n && self\n .context\n .initial_target_actions\n .get(name)\n .map(|action| {\n matches!(action, crate::pipeline::JobAction::Upgrade { .. })\n })\n .unwrap_or(false);\n\n debug!(\"[Resolver] Package '{}': is_initial_target={}, should_request_upgrade={}, action={:?}\",\n name, is_initial_target, should_request_upgrade,\n self.context.initial_target_actions.get(name));\n\n if should_request_upgrade {\n debug!(\n \"[Resolver] Marking upgrade target '{}' as Requested (was installed)\",\n name\n );\n Ok((ResolutionStatus::Requested, Some(keg.path)))\n } else {\n debug!(\"[Resolver] Marking '{}' as Installed (normal case)\", name);\n Ok((ResolutionStatus::Installed, Some(keg.path)))\n }\n } else {\n debug!(\n \"[Resolver] Package '{}' not installed, marking as {}\",\n name,\n if is_initial_target {\n \"Requested\"\n } else {\n \"Missing\"\n }\n );\n Ok((\n if is_initial_target {\n ResolutionStatus::Requested\n } else {\n ResolutionStatus::Missing\n },\n None,\n ))\n }\n }\n }\n }\n\n fn process_dependencies(\n &mut self,\n dep_snapshot: &ResolvedDependency,\n parent_name: &str,\n ) -> Result<()> {\n for dep in dep_snapshot.formula.dependencies()? {\n let dep_name = &dep.name;\n let dep_tags = dep.tags;\n let parent_formula_name = dep_snapshot.formula.name();\n let parent_strategy = dep_snapshot.determined_install_strategy;\n\n debug!(\n \"RESOLVER: Evaluating edge: parent='{}' ({:?}), child='{}' ({:?})\",\n parent_formula_name, parent_strategy, dep_name, dep_tags\n );\n\n if !self.should_consider_dependency(&dep) {\n if !self.resolution_details.contains_key(dep_name.as_str()) {\n debug!(\"RESOLVER: Child '{}' of '{}' globally SKIPPED (e.g. optional/test not included). Tags: {:?}\", dep_name, parent_formula_name, dep_tags);\n }\n continue;\n }\n\n let should_process = self.context.should_process_dependency_edge(\n &dep_snapshot.formula,\n dep_tags,\n parent_strategy,\n );\n\n if !should_process {\n debug!(\n \"RESOLVER: Edge from '{}' (Strategy: {:?}) to child '{}' (Tags: {:?}) was SKIPPED by should_process_dependency_edge.\",\n parent_formula_name, parent_strategy, dep_name, dep_tags\n );\n continue;\n }\n\n debug!(\n \"RESOLVER: Edge from '{}' (Strategy: {:?}) to child '{}' (Tags: {:?}) WILL BE PROCESSED. Recursing.\",\n parent_formula_name, parent_strategy, dep_name, dep_tags\n );\n\n if let Err(e) = self.resolve_recursive(dep_name, dep_tags, false, Some(parent_strategy))\n {\n // Log the error but don't necessarily stop all resolution for this branch yet\n warn!(\n \"Error resolving child dependency '{}' for parent '{}': {}\",\n dep_name, parent_name, e\n );\n // Optionally, mark parent as failed if child error is critical\n // self.errors.insert(parent_name.to_string(), Arc::new(e)); // Storing error for\n // parent if needed\n }\n }\n Ok(())\n }\n\n fn resolve_recursive(\n &mut self,\n name: &str,\n tags_from_parent_edge: DependencyTag,\n is_initial_target: bool,\n requesting_parent_strategy: Option,\n ) -> Result<()> {\n debug!(\n \"Resolving: {} (requested as {:?}, is_target: {})\",\n name, tags_from_parent_edge, is_initial_target\n );\n\n if self.visiting.contains(name) {\n error!(\"Dependency cycle detected involving: {}\", name);\n return Err(SpsError::DependencyError(format!(\n \"Dependency cycle detected involving '{name}'\"\n )));\n }\n\n if self.update_existing_resolution(name, tags_from_parent_edge, is_initial_target)? {\n // Already exists and was updated, no need to reprocess\n return Ok(());\n }\n\n if self.resolution_details.contains_key(name) {\n // Already exists but didn't need update\n return Ok(());\n }\n\n // New resolution needed\n self.visiting.insert(name.to_string());\n\n let formula_arc = match self.load_or_cache_formula(name, tags_from_parent_edge) {\n Ok(Some(formula)) => formula,\n Ok(None) => {\n self.visiting.remove(name);\n return Ok(()); // Already handled error case\n }\n Err(e) => {\n self.visiting.remove(name);\n return Err(e);\n }\n };\n\n self.create_initial_resolution(\n name,\n formula_arc,\n tags_from_parent_edge,\n is_initial_target,\n requesting_parent_strategy,\n )?;\n\n let dep_snapshot = self\n .resolution_details\n .get(name)\n .expect(\"just inserted\")\n .clone();\n\n if matches!(\n dep_snapshot.status,\n ResolutionStatus::Failed | ResolutionStatus::NotFound\n ) {\n self.visiting.remove(name);\n return Ok(());\n }\n\n self.process_dependencies(&dep_snapshot, name)?;\n\n self.visiting.remove(name);\n debug!(\"Finished resolving '{}'\", name);\n Ok(())\n }\n\n fn topological_sort(&self) -> Result> {\n let mut in_degree: HashMap = HashMap::new();\n let mut adj: HashMap> = HashMap::new();\n let mut sorted_list = Vec::new();\n let mut queue = VecDeque::new();\n\n let relevant_nodes_map: HashMap = self\n .resolution_details\n .iter()\n .filter(|(_, dep)| {\n !matches!(\n dep.status,\n ResolutionStatus::NotFound | ResolutionStatus::Failed\n )\n })\n .map(|(k, v)| (k.clone(), v))\n .collect();\n\n for (parent_name, parent_rd) in &relevant_nodes_map {\n adj.entry(parent_name.clone()).or_default();\n in_degree.entry(parent_name.clone()).or_default();\n\n let parent_strategy = parent_rd.determined_install_strategy;\n if let Ok(dependencies) = parent_rd.formula.dependencies() {\n for child_edge in dependencies {\n let child_name = &child_edge.name;\n if relevant_nodes_map.contains_key(child_name)\n && self.context.should_process_dependency_edge(\n &parent_rd.formula,\n child_edge.tags,\n parent_strategy,\n )\n && adj\n .entry(parent_name.clone())\n .or_default()\n .insert(child_name.clone())\n {\n *in_degree.entry(child_name.clone()).or_default() += 1;\n }\n }\n }\n }\n\n for name in relevant_nodes_map.keys() {\n if *in_degree.get(name).unwrap_or(&1) == 0 {\n queue.push_back(name.clone());\n }\n }\n\n while let Some(u_name) = queue.pop_front() {\n if let Some(resolved_dep) = relevant_nodes_map.get(&u_name) {\n sorted_list.push((**resolved_dep).clone()); // Deref Arc then clone\n // ResolvedDependency\n }\n if let Some(neighbors) = adj.get(&u_name) {\n for v_name in neighbors {\n if relevant_nodes_map.contains_key(v_name) {\n // Check if neighbor is relevant\n if let Some(degree) = in_degree.get_mut(v_name) {\n *degree = degree.saturating_sub(1);\n if *degree == 0 {\n queue.push_back(v_name.clone());\n }\n }\n }\n }\n }\n }\n\n // Check for cycles: if sorted_list's length doesn't match relevant_nodes_map's length\n // (excluding already installed, skipped optional if not included, etc.)\n // A more direct check is if in_degree still contains non-zero values for relevant nodes.\n let mut cycle_detected = false;\n for (name, °ree) in &in_degree {\n if degree > 0 && relevant_nodes_map.contains_key(name) {\n // Further check if this node should have been processed (not skipped globally)\n if let Some(detail) = self.resolution_details.get(name) {\n if self\n .context\n .should_consider_edge_globally(detail.accumulated_tags)\n {\n error!(\"Cycle detected or unresolved dependency: Node '{}' still has in-degree {}. Tags: {:?}\", name, degree, detail.accumulated_tags);\n cycle_detected = true;\n } else {\n debug!(\"Node '{}' has in-degree {} but was globally skipped. Tags: {:?}. Not a cycle error.\", name, degree, detail.accumulated_tags);\n }\n }\n }\n }\n\n if cycle_detected {\n return Err(SpsError::DependencyError(\n \"Circular dependency detected or graph resolution incomplete\".to_string(),\n ));\n }\n\n Ok(sorted_list) // Return the full sorted list of relevant nodes\n }\n\n fn should_consider_dependency(&self, dep: &Dependency) -> bool {\n let tags = dep.tags;\n if tags.contains(DependencyTag::TEST) && !self.context.include_test {\n return false;\n }\n if tags.contains(DependencyTag::OPTIONAL) && !self.context.include_optional {\n return false;\n }\n if tags.contains(DependencyTag::RECOMMENDED) && self.context.skip_recommended {\n return false;\n }\n true\n }\n}\n\nimpl Formula {\n fn placeholder(name: &str) -> Self {\n Self {\n name: name.to_string(),\n stable_version_str: \"0.0.0\".to_string(),\n version_semver: semver::Version::new(0, 0, 0), // Direct use\n revision: 0,\n desc: Some(\"Placeholder for unresolved formula\".to_string()),\n homepage: None,\n url: String::new(),\n sha256: String::new(),\n mirrors: Vec::new(),\n bottle: Default::default(),\n dependencies: Vec::new(),\n requirements: Vec::new(),\n resources: Vec::new(),\n install_keg_path: None,\n }\n }\n}\n\nimpl<'a> ResolutionContext<'a> {\n pub fn should_process_dependency_edge(\n &self,\n parent_formula_for_logging: &Arc,\n edge_tags: DependencyTag,\n parent_node_determined_strategy: NodeInstallStrategy,\n ) -> bool {\n if !self.should_consider_edge_globally(edge_tags) {\n debug!(\n \"Edge with tags {:?} for child of '{}' globally SKIPPED (e.g. optional/test not included).\",\n edge_tags, parent_formula_for_logging.name()\n );\n return false;\n }\n\n match parent_node_determined_strategy {\n NodeInstallStrategy::BottlePreferred | NodeInstallStrategy::BottleOrFail => {\n let is_purely_build_dependency = edge_tags.contains(DependencyTag::BUILD)\n && !edge_tags.intersects(\n DependencyTag::RUNTIME\n | DependencyTag::RECOMMENDED\n | DependencyTag::OPTIONAL,\n );\n if is_purely_build_dependency {\n debug!(\"Edge with tags {:?} SKIPPED: Pure BUILD dependency of a bottle-installed parent '{}'.\", edge_tags, parent_formula_for_logging.name());\n return false;\n }\n }\n NodeInstallStrategy::SourceOnly => {\n // Process all relevant (non-globally-skipped) dependencies for source builds\n }\n }\n debug!(\n \"Edge with tags {:?} WILL BE PROCESSED for parent '{}' (strategy {:?}).\",\n edge_tags,\n parent_formula_for_logging.name(),\n parent_node_determined_strategy\n );\n true\n }\n\n pub fn should_consider_edge_globally(&self, edge_tags: DependencyTag) -> bool {\n if edge_tags.contains(DependencyTag::TEST) && !self.include_test {\n return false;\n }\n if edge_tags.contains(DependencyTag::OPTIONAL) && !self.include_optional {\n return false;\n }\n if edge_tags.contains(DependencyTag::RECOMMENDED) && self.skip_recommended {\n return false;\n }\n true\n }\n}\n"], ["/sps/sps-core/src/install/cask/mod.rs", "pub mod artifacts;\npub mod dmg;\npub mod helpers;\n\nuse std::fs;\nuse std::path::{Path, PathBuf};\nuse std::time::{SystemTime, SystemTimeError, UNIX_EPOCH};\n\nuse infer;\nuse reqwest::Url;\nuse serde::{Deserialize, Serialize};\nuse serde_json::json;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::{Cask, Sha256Field, UrlField};\nuse sps_net::http::ProgressCallback;\nuse tempfile::TempDir;\nuse tracing::{debug, error};\n\nuse crate::install::extract;\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub struct CaskInstallManifest {\n pub manifest_format_version: String,\n pub token: String,\n pub version: String,\n pub installed_at: u64,\n pub artifacts: Vec,\n pub primary_app_file_name: Option,\n pub is_installed: bool, // New flag for soft uninstall\n pub cask_store_path: Option, // Path to private store app, if available\n}\n\n/// Returns the path to the cask's version directory in the private store.\npub fn sps_private_cask_version_dir(cask: &Cask, config: &Config) -> PathBuf {\n let version = cask.version.clone().unwrap_or_else(|| \"latest\".to_string());\n config.cask_store_version_path(&cask.token, &version)\n}\n\n/// Returns the path to the cask's token directory in the private store.\npub fn sps_private_cask_token_dir(cask: &Cask, config: &Config) -> PathBuf {\n config.cask_store_token_path(&cask.token)\n}\n\n/// Returns the path to the main app bundle for a cask in the private store.\n/// This assumes the primary app bundle is named as specified in the cask's artifacts.\npub fn sps_private_cask_app_path(cask: &Cask, config: &Config) -> Option {\n let version = cask.version.clone().unwrap_or_else(|| \"latest\".to_string());\n if let Some(cask_artifacts) = &cask.artifacts {\n for artifact in cask_artifacts {\n if let Some(obj) = artifact.as_object() {\n if let Some(apps) = obj.get(\"app\") {\n if let Some(app_names) = apps.as_array() {\n if let Some(app_name_val) = app_names.first() {\n if let Some(app_name) = app_name_val.as_str() {\n return Some(config.cask_store_app_path(\n &cask.token,\n &version,\n app_name,\n ));\n }\n }\n }\n }\n }\n }\n }\n None\n}\n\npub async fn download_cask(cask: &Cask, cache: &Cache) -> Result {\n download_cask_with_progress(cask, cache, None).await\n}\n\npub async fn download_cask_with_progress(\n cask: &Cask,\n cache: &Cache,\n progress_callback: Option,\n) -> Result {\n let url_field = cask\n .url\n .as_ref()\n .ok_or_else(|| SpsError::Generic(format!(\"Cask {} has no URL\", cask.token)))?;\n let url_str = match url_field {\n UrlField::Simple(u) => u.as_str(),\n UrlField::WithSpec { url, .. } => url.as_str(),\n };\n\n if url_str.is_empty() {\n return Err(SpsError::Generic(format!(\n \"Cask {} has an empty URL\",\n cask.token\n )));\n }\n\n debug!(\"Downloading cask from {}\", url_str);\n let parsed = Url::parse(url_str)\n .map_err(|e| SpsError::Generic(format!(\"Invalid URL '{url_str}': {e}\")))?;\n sps_net::validation::validate_url(parsed.as_str())?;\n let file_name = parsed\n .path_segments()\n .and_then(|mut segments| segments.next_back())\n .filter(|s| !s.is_empty())\n .map(|s| s.to_string())\n .unwrap_or_else(|| {\n debug!(\"URL has no filename component, using fallback name for cache based on token.\");\n format!(\"cask-{}-download.tmp\", cask.token.replace('/', \"_\"))\n });\n let cache_key = format!(\"cask-{}-{}\", cask.token, file_name);\n let cache_path = cache.get_dir().join(\"cask_downloads\").join(&cache_key);\n\n if cache_path.exists() {\n debug!(\"Using cached download: {}\", cache_path.display());\n return Ok(cache_path);\n }\n\n use futures::StreamExt;\n use tokio::fs::File as TokioFile;\n use tokio::io::AsyncWriteExt;\n\n let client = reqwest::Client::new();\n let response = client\n .get(parsed.clone())\n .send()\n .await\n .map_err(|e| SpsError::Http(std::sync::Arc::new(e)))?;\n if !response.status().is_success() {\n return Err(SpsError::DownloadError(\n cask.token.clone(),\n url_str.to_string(),\n format!(\"HTTP status {}\", response.status()),\n ));\n }\n\n // Get total size from Content-Length header if available\n let total_size = response.content_length();\n\n if let Some(parent) = cache_path.parent() {\n fs::create_dir_all(parent)?;\n }\n\n let mut file = TokioFile::create(&cache_path)\n .await\n .map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n\n // Use bytes_stream() for chunked download with progress reporting\n let mut stream = response.bytes_stream();\n let mut bytes_downloaded = 0u64;\n\n while let Some(chunk) = stream.next().await {\n let chunk = chunk.map_err(|e| SpsError::Http(std::sync::Arc::new(e)))?;\n\n file.write_all(&chunk)\n .await\n .map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n\n bytes_downloaded += chunk.len() as u64;\n\n // Call progress callback if provided\n if let Some(ref callback) = progress_callback {\n callback(bytes_downloaded, total_size);\n }\n }\n\n drop(file);\n match cask.sha256.as_ref() {\n Some(Sha256Field::Hex(s)) => {\n if s.eq_ignore_ascii_case(\"no_check\") {\n tracing::debug!(\n \"Skipping checksum verification for cask {} due to 'no_check' string.\",\n cache_path.display()\n );\n } else if !s.is_empty() {\n match sps_net::validation::verify_checksum(&cache_path, s) {\n Ok(_) => {\n tracing::debug!(\n \"Cask download checksum verified: {}\",\n cache_path.display()\n );\n }\n Err(e) => {\n tracing::error!(\n \"Cask download checksum mismatch ({}). Deleting cached file.\",\n e\n );\n let _ = fs::remove_file(&cache_path);\n return Err(e);\n }\n }\n } else {\n tracing::warn!(\n \"Skipping checksum verification for cask {} - empty sha256 provided.\",\n cache_path.display()\n );\n }\n }\n Some(Sha256Field::NoCheck { no_check: true }) => {\n tracing::debug!(\n \"Skipping checksum verification for cask {} due to 'no_check'.\",\n cache_path.display()\n );\n }\n _ => {\n tracing::warn!(\n \"Skipping checksum verification for cask {} - none provided.\",\n cache_path.display()\n );\n }\n }\n debug!(\"Download completed: {}\", cache_path.display());\n\n // --- Set quarantine xattr on the downloaded archive (macOS only) ---\n #[cfg(target_os = \"macos\")]\n {\n if let Err(e) = crate::utils::xattr::set_quarantine_attribute(&cache_path, \"sps-downloader\")\n {\n tracing::warn!(\n \"Failed to set quarantine attribute on downloaded archive {}: {}. Extraction and installation will proceed, but Gatekeeper behavior might be affected.\",\n cache_path.display(),\n e\n );\n }\n }\n\n Ok(cache_path)\n}\n\nuse sps_common::pipeline::JobAction;\n\npub fn install_cask(\n cask: &Cask,\n download_path: &Path,\n config: &Config,\n job_action: &JobAction,\n) -> Result<()> {\n debug!(\"Installing cask: {}\", cask.token);\n // This is the path in the *actual* Caskroom (e.g., /opt/homebrew/Caskroom/token/version)\n // where metadata and symlinks to /Applications will go.\n let actual_cask_room_version_path = config.cask_room_version_path(\n &cask.token,\n &cask.version.clone().unwrap_or_else(|| \"latest\".to_string()),\n );\n\n if !actual_cask_room_version_path.exists() {\n fs::create_dir_all(&actual_cask_room_version_path).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\n \"Failed create cask_room dir {}: {}\",\n actual_cask_room_version_path.display(),\n e\n ),\n )))\n })?;\n debug!(\n \"Created actual cask_room version directory: {}\",\n actual_cask_room_version_path.display()\n );\n }\n let mut detected_extension = download_path\n .extension()\n .and_then(|e| e.to_str())\n .unwrap_or(\"\")\n .to_lowercase();\n let non_extensions = [\"stable\", \"latest\", \"download\", \"bin\", \"\"];\n if non_extensions.contains(&detected_extension.as_str()) {\n debug!(\n \"Download path '{}' has no definite extension ('{}'), attempting content detection.\",\n download_path.display(),\n detected_extension\n );\n match infer::get_from_path(download_path) {\n Ok(Some(kind)) => {\n detected_extension = kind.extension().to_string();\n debug!(\"Detected file type via content: {}\", detected_extension);\n }\n Ok(None) => {\n error!(\n \"Could not determine file type from content for: {}\",\n download_path.display()\n );\n return Err(SpsError::Generic(format!(\n \"Could not determine file type for download: {}\",\n download_path.display()\n )));\n }\n Err(e) => {\n error!(\n \"Error reading file for type detection {}: {}\",\n download_path.display(),\n e\n );\n return Err(SpsError::Io(std::sync::Arc::new(e)));\n }\n }\n } else {\n debug!(\n \"Using file extension for type detection: {}\",\n detected_extension\n );\n }\n if detected_extension == \"pkg\" || detected_extension == \"mpkg\" {\n debug!(\"Detected PKG installer, running directly\");\n match artifacts::pkg::install_pkg_from_path(\n cask,\n download_path,\n &actual_cask_room_version_path, // PKG manifest items go into the actual cask_room\n config,\n ) {\n Ok(installed_artifacts) => {\n debug!(\"Writing PKG install manifest\");\n write_cask_manifest(cask, &actual_cask_room_version_path, installed_artifacts)?;\n debug!(\"Successfully installed PKG cask: {}\", cask.token);\n return Ok(());\n }\n Err(e) => {\n debug!(\"Failed to install PKG: {}\", e);\n // Clean up cask_room on error\n let _ = fs::remove_dir_all(&actual_cask_room_version_path);\n return Err(e);\n }\n }\n }\n let stage_dir = TempDir::new().map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed to create staging directory: {e}\"),\n )))\n })?;\n let stage_path = stage_dir.path();\n debug!(\"Created staging directory: {}\", stage_path.display());\n // Determine expected extension (this might need refinement)\n // Option 1: Parse from URL\n let expected_ext_from_url = download_path\n .extension()\n .and_then(|e| e.to_str())\n .unwrap_or(\"\");\n // Option 2: A new field in Cask JSON definition (preferred)\n // let expected_ext = cask.expected_extension.as_deref().unwrap_or(expected_ext_from_url);\n let expected_ext = expected_ext_from_url; // Use URL for now\n\n if !expected_ext.is_empty()\n && crate::build::compile::RECOGNISED_SINGLE_FILE_EXTENSIONS.contains(&expected_ext)\n {\n // Check if it's an archive/installer type we handle\n tracing::debug!(\n \"Verifying content type for {} against expected extension '{}'\",\n download_path.display(),\n expected_ext\n );\n if let Err(e) = sps_net::validation::verify_content_type(download_path, expected_ext) {\n tracing::error!(\"Content type verification failed: {}\", e);\n // Attempt cleanup?\n let _ = fs::remove_dir_all(&actual_cask_room_version_path);\n return Err(e);\n }\n } else {\n tracing::debug!(\n \"Skipping content type verification for {} (unknown/no expected extension: '{}')\",\n download_path.display(),\n expected_ext\n );\n }\n match detected_extension.as_str() {\n \"dmg\" => {\n debug!(\n \"Extracting DMG {} to stage {}...\",\n download_path.display(),\n stage_path.display()\n );\n dmg::extract_dmg_to_stage(download_path, stage_path)?;\n debug!(\"Successfully extracted DMG to staging area.\");\n }\n \"zip\" => {\n debug!(\n \"Extracting ZIP {} to stage {}...\",\n download_path.display(),\n stage_path.display()\n );\n extract::extract_archive(download_path, stage_path, 0, \"zip\")?;\n debug!(\"Successfully extracted ZIP to staging area.\");\n }\n \"gz\" | \"bz2\" | \"xz\" | \"tar\" => {\n let archive_type_for_extraction = detected_extension.as_str();\n debug!(\n \"Extracting TAR archive ({}) {} to stage {}...\",\n archive_type_for_extraction,\n download_path.display(),\n stage_path.display()\n );\n extract::extract_archive(download_path, stage_path, 0, archive_type_for_extraction)?;\n debug!(\"Successfully extracted TAR archive to staging area.\");\n }\n _ => {\n error!(\n \"Unsupported container/installer type '{}' for staged installation derived from {}\",\n detected_extension,\n download_path.display()\n );\n return Err(SpsError::Generic(format!(\n \"Unsupported file type for staged installation: {detected_extension}\"\n )));\n }\n }\n let mut all_installed_artifacts: Vec = Vec::new();\n let mut artifact_install_errors = Vec::new();\n if let Some(artifacts_def) = &cask.artifacts {\n debug!(\n \"Processing {} declared artifacts from staging area...\",\n artifacts_def.len()\n );\n for artifact_value in artifacts_def.iter() {\n if let Some(artifact_obj) = artifact_value.as_object() {\n if let Some((key, value)) = artifact_obj.iter().next() {\n debug!(\"Processing artifact type: {}\", key);\n let result: Result> = match key.as_str() {\n \"app\" => {\n let mut app_artifacts = vec![];\n if let Some(app_names) = value.as_array() {\n for app_name_val in app_names {\n if let Some(app_name) = app_name_val.as_str() {\n let staged_app_path = stage_path.join(app_name);\n debug!(\n \"Attempting to install app artifact: {}\",\n staged_app_path.display()\n );\n match artifacts::app::install_app_from_staged(\n cask,\n &staged_app_path,\n &actual_cask_room_version_path,\n config,\n job_action, // Pass job_action for upgrade logic\n ) {\n Ok(mut artifacts) => {\n app_artifacts.append(&mut artifacts)\n }\n Err(e) => {\n return Err(e);\n }\n }\n } else {\n debug!(\n \"Non-string value found in 'app' artifact array: {:?}\",\n app_name_val\n );\n }\n }\n } else {\n debug!(\"'app' artifact value is not an array: {:?}\", value);\n }\n Ok(app_artifacts)\n }\n \"pkg\" => {\n let mut installed_pkgs = vec![];\n if let Some(pkg_names) = value.as_array() {\n for pkg_val in pkg_names {\n if let Some(pkg_name) = pkg_val.as_str() {\n let staged_pkg_path = stage_path.join(pkg_name);\n debug!(\n \"Attempting to install staged pkg artifact: {}\",\n staged_pkg_path.display()\n );\n match artifacts::pkg::install_pkg_from_path(\n cask,\n &staged_pkg_path,\n &actual_cask_room_version_path, /* Pass actual\n * cask_room path */\n config,\n ) {\n Ok(mut artifacts) => {\n installed_pkgs.append(&mut artifacts)\n }\n Err(e) => {\n return Err(e);\n }\n }\n } else {\n debug!(\n \"Non-string value found in 'pkg' artifact array: {:?}\",\n pkg_val\n );\n }\n }\n } else {\n debug!(\"'pkg' artifact value is not an array: {:?}\", value);\n }\n Ok(installed_pkgs)\n }\n _ => {\n debug!(\"Artifact type '{}' not supported yet — skipping.\", key);\n Ok(vec![])\n }\n };\n match result {\n Ok(installed) => {\n if !installed.is_empty() {\n debug!(\n \"Successfully processed artifact '{}', added {} items.\",\n key,\n installed.len()\n );\n all_installed_artifacts.extend(installed);\n } else {\n debug!(\n \"Artifact handler for '{}' completed successfully but returned no artifacts.\",\n key\n );\n }\n }\n Err(e) => {\n error!(\"Error processing artifact '{}': {}\", key, e);\n artifact_install_errors.push(e);\n }\n }\n } else {\n debug!(\"Empty artifact object found: {:?}\", artifact_obj);\n }\n } else {\n debug!(\n \"Unexpected non-object artifact found in list: {:?}\",\n artifact_value\n );\n }\n }\n } else {\n error!(\n \"Cask {} definition is missing the required 'artifacts' array. Cannot determine what to install.\",\n cask.token\n );\n // Clean up the created actual_caskroom_version_path if no artifacts are defined\n let _ = fs::remove_dir_all(&actual_cask_room_version_path);\n return Err(SpsError::InstallError(format!(\n \"Cask '{}' has no artifacts defined.\",\n cask.token\n )));\n }\n if !artifact_install_errors.is_empty() {\n error!(\n \"Encountered {} errors installing artifacts for cask '{}'. Installation incomplete.\",\n artifact_install_errors.len(),\n cask.token\n );\n let _ = fs::remove_dir_all(&actual_cask_room_version_path); // Clean up actual cask_room on error\n return Err(artifact_install_errors.remove(0));\n }\n let actual_install_count = all_installed_artifacts\n .iter()\n .filter(|a| {\n !matches!(\n a,\n InstalledArtifact::PkgUtilReceipt { .. } | InstalledArtifact::Launchd { .. }\n )\n })\n .count();\n if actual_install_count == 0 {\n debug!(\n \"No installable artifacts (like app, pkg, binary, etc.) were processed for cask '{}' from the staged content. Check cask definition.\",\n cask.token\n );\n write_cask_manifest(\n cask,\n &actual_cask_room_version_path,\n all_installed_artifacts,\n )?;\n } else {\n debug!(\"Writing cask installation manifest\");\n write_cask_manifest(\n cask,\n &actual_cask_room_version_path,\n all_installed_artifacts,\n )?;\n }\n debug!(\"Successfully installed cask: {}\", cask.token);\n Ok(())\n}\n\n#[deprecated(note = \"Use write_cask_manifest with detailed InstalledArtifact enum instead\")]\npub fn write_receipt(\n cask: &Cask,\n cask_version_install_path: &Path,\n artifacts: Vec,\n) -> Result<()> {\n let receipt_path = cask_version_install_path.join(\"INSTALL_RECEIPT.json\");\n debug!(\"Writing legacy cask receipt: {}\", receipt_path.display());\n let timestamp = SystemTime::now()\n .duration_since(UNIX_EPOCH)\n .map_err(|e: SystemTimeError| SpsError::Generic(format!(\"System time error: {e}\")))?\n .as_secs();\n let receipt_data = json!({\n \"token\": cask.token,\n \"name\": cask.name.as_ref().and_then(|n| n.first()).cloned(),\n \"version\": cask.version.as_ref().unwrap_or(&\"latest\".to_string()),\n \"installed_at\": timestamp,\n \"artifacts_installed\": artifacts\n });\n if let Some(parent) = receipt_path.parent() {\n fs::create_dir_all(parent).map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n }\n let mut file =\n fs::File::create(&receipt_path).map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n serde_json::to_writer_pretty(&mut file, &receipt_data)\n .map_err(|e| SpsError::Json(std::sync::Arc::new(e)))?;\n debug!(\n \"Successfully wrote legacy receipt with {} artifact entries.\",\n artifacts.len()\n );\n Ok(())\n}\n\npub fn write_cask_manifest(\n cask: &Cask,\n cask_version_install_path: &Path,\n artifacts: Vec,\n) -> Result<()> {\n let manifest_path = cask_version_install_path.join(\"CASK_INSTALL_MANIFEST.json\");\n debug!(\"Writing cask manifest: {}\", manifest_path.display());\n let timestamp = SystemTime::now()\n .duration_since(UNIX_EPOCH)\n .map_err(|e: SystemTimeError| SpsError::Generic(format!(\"System time error: {e}\")))?\n .as_secs();\n\n // Determine primary app file name from artifacts\n let primary_app_file_name = artifacts.iter().find_map(|artifact| {\n if let InstalledArtifact::AppBundle { path } = artifact {\n path.file_name()\n .map(|name| name.to_string_lossy().to_string())\n } else {\n None\n }\n });\n\n // Always set is_installed=true when writing manifest (install or reinstall)\n // Try to determine cask_store_path from artifacts (AppBundle or CaskroomLink)\n let cask_store_path = artifacts.iter().find_map(|artifact| match artifact {\n InstalledArtifact::AppBundle { path } => Some(path.to_string_lossy().to_string()),\n InstalledArtifact::CaskroomLink { target_path, .. } => {\n Some(target_path.to_string_lossy().to_string())\n }\n _ => None,\n });\n\n let manifest_data = CaskInstallManifest {\n manifest_format_version: \"1.0\".to_string(),\n token: cask.token.clone(),\n version: cask.version.clone().unwrap_or_else(|| \"latest\".to_string()),\n installed_at: timestamp,\n artifacts,\n primary_app_file_name,\n is_installed: true,\n cask_store_path,\n };\n if let Some(parent) = manifest_path.parent() {\n fs::create_dir_all(parent).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed create parent dir {}: {}\", parent.display(), e),\n )))\n })?;\n }\n let file = fs::File::create(&manifest_path).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed create manifest {}: {}\", manifest_path.display(), e),\n )))\n })?;\n let writer = std::io::BufWriter::new(file);\n serde_json::to_writer_pretty(writer, &manifest_data).map_err(|e| {\n error!(\n \"Failed to serialize cask manifest JSON for {}: {}\",\n cask.token, e\n );\n SpsError::Json(std::sync::Arc::new(e))\n })?;\n debug!(\n \"Successfully wrote cask manifest with {} artifact entries.\",\n manifest_data.artifacts.len()\n );\n Ok(())\n}\n\n/// Recursively cleans up empty parent directories in the private cask store.\n/// Starts from the given path and walks up, removing empty directories until a non-empty or root is\n/// found.\npub fn cleanup_empty_parent_dirs_in_private_store(start_path: &Path, stop_at: &Path) {\n let mut current = start_path.parent().unwrap_or(start_path).to_path_buf(); // Start from parent\n while current != *stop_at {\n if let Ok(read_dir) = fs::read_dir(¤t) {\n if read_dir.count() == 0 {\n match fs::remove_dir(¤t) {\n Ok(_) => {\n debug!(\"Removed empty directory: {}\", current.display());\n }\n Err(e) => {\n debug!(\"Failed to remove directory {}: {}\", current.display(), e);\n break;\n }\n }\n } else {\n break;\n }\n } else {\n break;\n }\n if let Some(parent) = current.parent() {\n current = parent.to_path_buf();\n } else {\n break;\n }\n }\n}\n"], ["/sps/sps-common/src/model/formula.rs", "// sps-core/src/model/formula.rs\n// *** Corrected: Removed derive Deserialize from ResourceSpec, removed unused SpsError import,\n// added ResourceSpec struct and parsing ***\n\nuse std::collections::HashMap;\nuse std::path::{Path, PathBuf};\n\nuse semver::Version;\nuse serde::{de, Deserialize, Deserializer, Serialize};\nuse serde_json::Value;\nuse tracing::{debug, error};\n\nuse crate::dependency::{Dependency, DependencyTag, Requirement};\nuse crate::error::Result; // <-- Import only Result // Use log crate imports\n\n// --- Resource Spec Struct ---\n// *** Added struct definition, REMOVED #[derive(Deserialize)] ***\n#[derive(Debug, Clone, Serialize, PartialEq, Eq)]\npub struct ResourceSpec {\n pub name: String,\n pub url: String,\n pub sha256: String,\n // Add other potential fields like version if needed later\n}\n\n// --- Bottle Related Structs (Original structure) ---\n#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]\npub struct BottleFileSpec {\n pub url: String,\n pub sha256: String,\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]\npub struct BottleSpec {\n pub stable: Option,\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]\npub struct BottleStableSpec {\n pub rebuild: u32,\n #[serde(default)]\n pub files: HashMap,\n}\n\n// --- Formula Version Struct (Original structure) ---\n#[derive(Deserialize, Serialize, Debug, Clone, Default, PartialEq, Eq)]\npub struct FormulaVersions {\n pub stable: Option,\n pub head: Option,\n #[serde(default)]\n pub bottle: bool,\n}\n\n// --- Main Formula Struct ---\n// *** Added 'resources' field ***\n#[derive(Debug, Clone, Serialize, PartialEq, Eq)]\npub struct Formula {\n pub name: String,\n pub stable_version_str: String,\n #[serde(rename = \"versions\")]\n pub version_semver: Version,\n #[serde(default)]\n pub revision: u32,\n #[serde(default)]\n pub desc: Option,\n #[serde(default)]\n pub homepage: Option,\n #[serde(default)]\n pub url: String,\n #[serde(default)]\n pub sha256: String,\n #[serde(default)]\n pub mirrors: Vec,\n #[serde(default)]\n pub bottle: BottleSpec,\n #[serde(skip_deserializing)]\n pub dependencies: Vec,\n #[serde(default, deserialize_with = \"deserialize_requirements\")]\n pub requirements: Vec,\n #[serde(skip_deserializing)] // Skip direct deserialization for this field\n pub resources: Vec, // Stores parsed resources\n #[serde(skip)]\n pub install_keg_path: Option,\n}\n\n// Custom deserialization logic for Formula\nimpl<'de> Deserialize<'de> for Formula {\n fn deserialize(deserializer: D) -> std::result::Result\n where\n D: Deserializer<'de>,\n {\n // Temporary struct reflecting the JSON structure more closely\n // *** Added 'resources' field to capture raw JSON Value ***\n #[derive(Deserialize, Debug)]\n struct RawFormulaData {\n name: String,\n #[serde(default)]\n revision: u32,\n desc: Option,\n homepage: Option,\n versions: FormulaVersions,\n #[serde(default)]\n url: String,\n #[serde(default)]\n sha256: String,\n #[serde(default)]\n mirrors: Vec,\n #[serde(default)]\n bottle: BottleSpec,\n #[serde(default)]\n dependencies: Vec,\n #[serde(default)]\n build_dependencies: Vec,\n #[serde(default)]\n test_dependencies: Vec,\n #[serde(default)]\n recommended_dependencies: Vec,\n #[serde(default)]\n optional_dependencies: Vec,\n #[serde(default, deserialize_with = \"deserialize_requirements\")]\n requirements: Vec,\n #[serde(default)]\n resources: Vec, // Capture resources as generic Value first\n #[serde(default)]\n urls: Option,\n }\n\n let raw: RawFormulaData = RawFormulaData::deserialize(deserializer)?;\n\n // --- Version Parsing (Original logic) ---\n let stable_version_str = raw\n .versions\n .stable\n .clone()\n .ok_or_else(|| de::Error::missing_field(\"versions.stable\"))?;\n let version_semver = match crate::model::version::Version::parse(&stable_version_str) {\n Ok(v) => v.into(),\n Err(_) => {\n let mut majors = 0u32;\n let mut minors = 0u32;\n let mut patches = 0u32;\n let mut part_count = 0;\n for (i, part) in stable_version_str.split('.').enumerate() {\n let numeric_part = part\n .chars()\n .take_while(|c| c.is_ascii_digit())\n .collect::();\n if numeric_part.is_empty() && i > 0 {\n break;\n }\n if numeric_part.len() < part.len() && i > 0 {\n if let Ok(num) = numeric_part.parse::() {\n match i {\n 0 => majors = num,\n 1 => minors = num,\n 2 => patches = num,\n _ => {}\n }\n part_count += 1;\n }\n break;\n }\n if let Ok(num) = numeric_part.parse::() {\n match i {\n 0 => majors = num,\n 1 => minors = num,\n 2 => patches = num,\n _ => {}\n }\n part_count += 1;\n }\n if i >= 2 {\n break;\n }\n }\n let version_str_padded = match part_count {\n 1 => format!(\"{majors}.0.0\"),\n 2 => format!(\"{majors}.{minors}.0\"),\n _ => format!(\"{majors}.{minors}.{patches}\"),\n };\n match Version::parse(&version_str_padded) {\n Ok(v) => v,\n Err(_) => {\n error!(\n \"Warning: Could not parse version '{}' (sanitized to '{}') for formula '{}'. Using 0.0.0.\",\n stable_version_str, version_str_padded, raw.name\n );\n Version::new(0, 0, 0)\n }\n }\n }\n };\n\n // --- URL/SHA256 Logic (Original logic) ---\n let mut final_url = raw.url;\n let mut final_sha256 = raw.sha256;\n if final_url.is_empty() {\n if let Some(Value::Object(urls_map)) = raw.urls {\n if let Some(Value::Object(stable_url_info)) = urls_map.get(\"stable\") {\n if let Some(Value::String(u)) = stable_url_info.get(\"url\") {\n final_url = u.clone();\n }\n if let Some(Value::String(s)) = stable_url_info\n .get(\"checksum\")\n .or_else(|| stable_url_info.get(\"sha256\"))\n {\n final_sha256 = s.clone();\n }\n }\n }\n }\n if final_url.is_empty() && raw.versions.head.is_none() {\n debug!(\"Warning: Formula '{}' has no stable URL defined.\", raw.name);\n }\n\n // --- Dependency Processing (Original logic) ---\n let mut combined_dependencies: Vec = Vec::new();\n let mut seen_deps: HashMap = HashMap::new();\n let mut process_list = |deps: &[String], tag: DependencyTag| {\n for name in deps {\n *seen_deps\n .entry(name.clone())\n .or_insert(DependencyTag::empty()) |= tag;\n }\n };\n process_list(&raw.dependencies, DependencyTag::RUNTIME);\n process_list(&raw.build_dependencies, DependencyTag::BUILD);\n process_list(&raw.test_dependencies, DependencyTag::TEST);\n process_list(\n &raw.recommended_dependencies,\n DependencyTag::RECOMMENDED | DependencyTag::RUNTIME,\n );\n process_list(\n &raw.optional_dependencies,\n DependencyTag::OPTIONAL | DependencyTag::RUNTIME,\n );\n for (name, tags) in seen_deps {\n combined_dependencies.push(Dependency::new_with_tags(name, tags));\n }\n\n // --- Resource Processing ---\n // *** Added parsing logic for the 'resources' field ***\n let mut combined_resources: Vec = Vec::new();\n for res_val in raw.resources {\n // Homebrew API JSON format puts resource spec inside a keyed object\n // e.g., { \"resource_name\": { \"url\": \"...\", \"sha256\": \"...\" } }\n if let Value::Object(map) = res_val {\n // Assume only one key-value pair per object in the array\n if let Some((res_name, res_spec_val)) = map.into_iter().next() {\n // Use the manual Deserialize impl for ResourceSpec\n match ResourceSpec::deserialize(res_spec_val.clone()) {\n // Use ::deserialize\n Ok(mut res_spec) => {\n // Inject the name from the key if missing\n if res_spec.name.is_empty() {\n res_spec.name = res_name;\n } else if res_spec.name != res_name {\n debug!(\n \"Resource name mismatch in formula '{}': key '{}' vs spec '{}'. Using key.\",\n raw.name, res_name, res_spec.name\n );\n res_spec.name = res_name; // Prefer key name\n }\n // Ensure required fields are present\n if res_spec.url.is_empty() || res_spec.sha256.is_empty() {\n debug!(\n \"Resource '{}' for formula '{}' is missing URL or SHA256. Skipping.\",\n res_spec.name, raw.name\n );\n continue;\n }\n debug!(\n \"Parsed resource '{}' for formula '{}'\",\n res_spec.name, raw.name\n );\n combined_resources.push(res_spec);\n }\n Err(e) => {\n // Use display for the error which comes from serde::de::Error::custom\n debug!(\n \"Failed to parse resource spec value for key '{}' in formula '{}': {}. Value: {:?}\",\n res_name, raw.name, e, res_spec_val\n );\n }\n }\n } else {\n debug!(\"Empty resource object found in formula '{}'.\", raw.name);\n }\n } else {\n debug!(\n \"Unexpected format for resource entry in formula '{}': expected object, got {:?}\",\n raw.name, res_val\n );\n }\n }\n\n Ok(Self {\n name: raw.name,\n stable_version_str,\n version_semver,\n revision: raw.revision,\n desc: raw.desc,\n homepage: raw.homepage,\n url: final_url,\n sha256: final_sha256,\n mirrors: raw.mirrors,\n bottle: raw.bottle,\n dependencies: combined_dependencies,\n requirements: raw.requirements,\n resources: combined_resources, // Assign parsed resources\n install_keg_path: None,\n })\n }\n}\n\n// --- Formula impl Methods ---\nimpl Formula {\n // dependencies() and requirements() are unchanged\n pub fn dependencies(&self) -> Result> {\n Ok(self.dependencies.clone())\n }\n pub fn requirements(&self) -> Result> {\n Ok(self.requirements.clone())\n }\n\n // *** Added: Returns a clone of the defined resources. ***\n pub fn resources(&self) -> Result> {\n Ok(self.resources.clone())\n }\n\n // Other methods (set_keg_path, version_str_full, accessors) are unchanged\n pub fn set_keg_path(&mut self, path: PathBuf) {\n self.install_keg_path = Some(path);\n }\n pub fn version_str_full(&self) -> String {\n if self.revision > 0 {\n format!(\"{}_{}\", self.stable_version_str, self.revision)\n } else {\n self.stable_version_str.clone()\n }\n }\n pub fn name(&self) -> &str {\n &self.name\n }\n pub fn version(&self) -> &Version {\n &self.version_semver\n }\n pub fn source_url(&self) -> &str {\n &self.url\n }\n pub fn source_sha256(&self) -> &str {\n &self.sha256\n }\n pub fn get_bottle_spec(&self, bottle_tag: &str) -> Option<&BottleFileSpec> {\n self.bottle.stable.as_ref()?.files.get(bottle_tag)\n }\n}\n\n// --- BuildEnvironment Dependency Interface (Unchanged) ---\npub trait FormulaDependencies {\n fn name(&self) -> &str;\n fn install_prefix(&self, cellar_path: &Path) -> Result;\n fn resolved_runtime_dependency_paths(&self) -> Result>;\n fn resolved_build_dependency_paths(&self) -> Result>;\n fn all_resolved_dependency_paths(&self) -> Result>;\n}\nimpl FormulaDependencies for Formula {\n fn name(&self) -> &str {\n &self.name\n }\n fn install_prefix(&self, cellar_path: &Path) -> Result {\n let version_string = self.version_str_full();\n Ok(cellar_path.join(self.name()).join(version_string))\n }\n fn resolved_runtime_dependency_paths(&self) -> Result> {\n Ok(Vec::new())\n }\n fn resolved_build_dependency_paths(&self) -> Result> {\n Ok(Vec::new())\n }\n fn all_resolved_dependency_paths(&self) -> Result> {\n Ok(Vec::new())\n }\n}\n\n// --- Deserialization Helpers ---\n// deserialize_requirements remains unchanged\nfn deserialize_requirements<'de, D>(\n deserializer: D,\n) -> std::result::Result, D::Error>\nwhere\n D: serde::Deserializer<'de>,\n{\n #[derive(Deserialize, Debug)]\n struct ReqWrapper {\n #[serde(default)]\n name: String,\n #[serde(default)]\n version: Option,\n #[serde(default)]\n cask: Option,\n #[serde(default)]\n download: Option,\n }\n let raw_reqs: Vec = Deserialize::deserialize(deserializer)?;\n let mut requirements = Vec::new();\n for req_val in raw_reqs {\n if let Ok(req_obj) = serde_json::from_value::(req_val.clone()) {\n match req_obj.name.as_str() {\n \"macos\" => {\n requirements.push(Requirement::MacOS(\n req_obj.version.unwrap_or_else(|| \"any\".to_string()),\n ));\n }\n \"xcode\" => {\n requirements.push(Requirement::Xcode(\n req_obj.version.unwrap_or_else(|| \"any\".to_string()),\n ));\n }\n \"cask\" => {\n requirements.push(Requirement::Other(format!(\n \"Cask Requirement: {}\",\n req_obj.cask.unwrap_or_else(|| \"?\".to_string())\n )));\n }\n \"download\" => {\n requirements.push(Requirement::Other(format!(\n \"Download Requirement: {}\",\n req_obj.download.unwrap_or_else(|| \"?\".to_string())\n )));\n }\n _ => requirements.push(Requirement::Other(format!(\n \"Unknown requirement type: {req_obj:?}\"\n ))),\n }\n } else if let Value::String(req_str) = req_val {\n match req_str.as_str() {\n \"macos\" => requirements.push(Requirement::MacOS(\"latest\".to_string())),\n \"xcode\" => requirements.push(Requirement::Xcode(\"latest\".to_string())),\n _ => {\n requirements.push(Requirement::Other(format!(\"Simple requirement: {req_str}\")))\n }\n }\n } else {\n debug!(\"Warning: Could not parse requirement: {:?}\", req_val);\n requirements.push(Requirement::Other(format!(\n \"Unparsed requirement: {req_val:?}\"\n )));\n }\n }\n Ok(requirements)\n}\n\n// Manual impl Deserialize for ResourceSpec (unchanged, this is needed)\nimpl<'de> Deserialize<'de> for ResourceSpec {\n fn deserialize(deserializer: D) -> std::result::Result\n where\n D: Deserializer<'de>,\n {\n #[derive(Deserialize)]\n struct Helper {\n #[serde(default)]\n name: String, // name is often the key, not in the value\n url: String,\n sha256: String,\n }\n let helper = Helper::deserialize(deserializer)?;\n // Note: The actual resource name comes from the key in the map during Formula\n // deserialization\n Ok(Self {\n name: helper.name,\n url: helper.url,\n sha256: helper.sha256,\n })\n }\n}\n"], ["/sps/sps-core/src/install/bottle/exec.rs", "use std::collections::{HashMap, HashSet};\nuse std::fs::{self, File};\nuse std::io::{Read, Write};\nuse std::os::unix::fs::{symlink, PermissionsExt};\nuse std::path::{Path, PathBuf};\nuse std::process::{Command as StdCommand, Stdio};\nuse std::sync::Arc;\n\nuse reqwest::Client;\nuse semver;\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::formula::{BottleFileSpec, Formula, FormulaDependencies};\nuse sps_net::http::ProgressCallback;\nuse sps_net::oci;\nuse sps_net::validation::verify_checksum;\nuse tempfile::NamedTempFile;\nuse tracing::{debug, error, warn};\nuse walkdir::WalkDir;\n\nuse super::macho;\nuse crate::install::bottle::get_current_platform;\nuse crate::install::extract::extract_archive;\n\npub async fn download_bottle(\n formula: &Formula,\n config: &Config,\n client: &Client,\n) -> Result {\n download_bottle_with_progress(formula, config, client, None).await\n}\n\npub async fn download_bottle_with_progress(\n formula: &Formula,\n config: &Config,\n client: &Client,\n progress_callback: Option,\n) -> Result {\n download_bottle_with_progress_and_cache_info(formula, config, client, progress_callback)\n .await\n .map(|(path, _)| path)\n}\n\npub async fn download_bottle_with_progress_and_cache_info(\n formula: &Formula,\n config: &Config,\n client: &Client,\n progress_callback: Option,\n) -> Result<(PathBuf, bool)> {\n debug!(\"Attempting to download bottle for {}\", formula.name);\n let (platform_tag, bottle_file_spec) = get_bottle_for_platform(formula)?;\n debug!(\n \"Selected bottle spec for platform '{}': URL={}, SHA256={}\",\n platform_tag, bottle_file_spec.url, bottle_file_spec.sha256\n );\n if bottle_file_spec.url.is_empty() {\n return Err(SpsError::DownloadError(\n formula.name.clone(),\n \"\".to_string(),\n \"Bottle spec has an empty URL.\".to_string(),\n ));\n }\n let standard_version_str = formula.version_str_full();\n let filename = format!(\n \"{}-{}.{}.bottle.tar.gz\",\n formula.name, standard_version_str, platform_tag\n );\n let cache_dir = config.cache_dir().join(\"bottles\");\n fs::create_dir_all(&cache_dir).map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n let bottle_cache_path = cache_dir.join(&filename);\n if bottle_cache_path.is_file() {\n debug!(\"Bottle found in cache: {}\", bottle_cache_path.display());\n if !bottle_file_spec.sha256.is_empty() {\n match verify_checksum(&bottle_cache_path, &bottle_file_spec.sha256) {\n Ok(_) => {\n debug!(\"Using valid cached bottle: {}\", bottle_cache_path.display());\n return Ok((bottle_cache_path, true));\n }\n Err(e) => {\n debug!(\n \"Cached bottle checksum mismatch ({}): {}. Redownloading.\",\n bottle_cache_path.display(),\n e\n );\n let _ = fs::remove_file(&bottle_cache_path);\n }\n }\n } else {\n warn!(\n \"Using cached bottle without checksum verification (checksum not specified): {}\",\n bottle_cache_path.display()\n );\n return Ok((bottle_cache_path, true));\n }\n } else {\n debug!(\"Bottle not found in cache.\");\n }\n let bottle_url_str = &bottle_file_spec.url;\n let registry_domain = config\n .artifact_domain\n .as_deref()\n .unwrap_or(oci::DEFAULT_GHCR_DOMAIN);\n let is_oci_blob_url = (bottle_url_str.contains(\"://ghcr.io/\")\n || bottle_url_str.contains(registry_domain))\n && bottle_url_str.contains(\"/blobs/sha256:\");\n debug!(\n \"Checking URL type: '{}'. Is OCI Blob URL? {}\",\n bottle_url_str, is_oci_blob_url\n );\n if is_oci_blob_url {\n let expected_digest = bottle_url_str.split(\"/blobs/sha256:\").nth(1).unwrap_or(\"\");\n if expected_digest.is_empty() {\n warn!(\n \"Could not extract expected SHA256 digest from OCI URL: {}\",\n bottle_url_str\n );\n }\n debug!(\n \"Detected OCI blob URL, initiating direct blob download: {} (Digest: {})\",\n bottle_url_str, expected_digest\n );\n match oci::download_oci_blob_with_progress(\n bottle_url_str,\n &bottle_cache_path,\n config,\n client,\n expected_digest,\n progress_callback.clone(),\n )\n .await\n {\n Ok(_) => {\n debug!(\n \"Successfully downloaded OCI blob to {}\",\n bottle_cache_path.display()\n );\n }\n Err(e) => {\n error!(\"Failed to download OCI blob from {}: {}\", bottle_url_str, e);\n let _ = fs::remove_file(&bottle_cache_path);\n return Err(SpsError::DownloadError(\n formula.name.clone(),\n bottle_url_str.to_string(),\n format!(\"Failed to download OCI blob: {e}\"),\n ));\n }\n }\n } else {\n debug!(\n \"Detected standard HTTPS URL, using direct download for: {}\",\n bottle_url_str\n );\n match sps_net::http::fetch_formula_source_or_bottle_with_progress(\n formula.name(),\n bottle_url_str,\n &bottle_file_spec.sha256,\n &[],\n config,\n progress_callback,\n )\n .await\n {\n Ok(downloaded_path) => {\n if downloaded_path != bottle_cache_path {\n debug!(\n \"fetch_formula_source_or_bottle returned path {}. Expected: {}. Assuming correct.\",\n downloaded_path.display(),\n bottle_cache_path.display()\n );\n if !bottle_cache_path.exists() {\n error!(\n \"Downloaded path {} exists, but expected final cache path {} does not!\",\n downloaded_path.display(),\n bottle_cache_path.display()\n );\n return Err(SpsError::Generic(format!(\n \"Download path mismatch and final file missing: {}\",\n bottle_cache_path.display()\n )));\n }\n }\n debug!(\n \"Successfully downloaded directly to {}\",\n bottle_cache_path.display()\n );\n }\n Err(e) => {\n error!(\"Failed to download directly from {}: {}\", bottle_url_str, e);\n return Err(e);\n }\n }\n }\n if !bottle_cache_path.exists() {\n error!(\n \"Bottle download process completed, but the final file {} does not exist.\",\n bottle_cache_path.display()\n );\n return Err(SpsError::Generic(format!(\n \"Bottle file missing after download attempt: {}\",\n bottle_cache_path.display()\n )));\n }\n debug!(\n \"Bottle download successful: {}\",\n bottle_cache_path.display()\n );\n Ok((bottle_cache_path, false))\n}\n\npub fn get_bottle_for_platform(formula: &Formula) -> Result<(String, &BottleFileSpec)> {\n let stable_spec = formula.bottle.stable.as_ref().ok_or_else(|| {\n SpsError::Generic(format!(\n \"Formula '{}' has no stable bottle specification.\",\n formula.name\n ))\n })?;\n if stable_spec.files.is_empty() {\n return Err(SpsError::Generic(format!(\n \"Formula '{}' has no bottle files listed in stable spec.\",\n formula.name\n )));\n }\n let current_platform = get_current_platform();\n if current_platform == \"unknown\" || current_platform.contains(\"unknown\") {\n debug!(\n \"Could not reliably determine current platform ('{}'). Bottle selection might be incorrect.\",\n current_platform\n );\n }\n debug!(\n \"Determining bottle for current platform: {}\",\n current_platform\n );\n debug!(\n \"Available bottle platforms in formula spec: {:?}\",\n stable_spec.files.keys().cloned().collect::>()\n );\n if let Some(spec) = stable_spec.files.get(¤t_platform) {\n debug!(\n \"Found exact bottle match for platform: {}\",\n current_platform\n );\n return Ok((current_platform.clone(), spec));\n }\n debug!(\"No exact match found for {}\", current_platform);\n const ARM_MACOS_VERSIONS: &[&str] = &[\"sequoia\", \"sonoma\", \"ventura\", \"monterey\", \"big_sur\"];\n const INTEL_MACOS_VERSIONS: &[&str] = &[\n \"sequoia\", \"sonoma\", \"ventura\", \"monterey\", \"big_sur\", \"catalina\", \"mojave\",\n ];\n if cfg!(target_os = \"macos\") {\n if let Some(current_os_name) = current_platform\n .strip_prefix(\"arm64_\")\n .or(Some(current_platform.as_str()))\n {\n let version_list = if current_platform.starts_with(\"arm64_\") {\n ARM_MACOS_VERSIONS\n } else {\n INTEL_MACOS_VERSIONS\n };\n if let Some(current_os_index) = version_list.iter().position(|&v| v == current_os_name)\n {\n for target_os_name in version_list.iter().skip(current_os_index) {\n let target_tag = if current_platform.starts_with(\"arm64_\") {\n format!(\"arm64_{target_os_name}\")\n } else {\n target_os_name.to_string()\n };\n if let Some(spec) = stable_spec.files.get(&target_tag) {\n debug!(\n \"No bottle found for exact platform '{}'. Using compatible older bottle '{}'.\",\n current_platform, target_tag\n );\n return Ok((target_tag, spec));\n }\n }\n debug!(\n \"Checked compatible older macOS versions ({:?}), no suitable bottle found.\",\n &version_list[current_os_index..]\n );\n } else {\n debug!(\n \"Current OS '{}' not found in known macOS version list.\",\n current_os_name\n );\n }\n } else {\n debug!(\n \"Could not extract OS name from platform tag '{}'\",\n current_platform\n );\n }\n }\n if current_platform.starts_with(\"arm64_\") {\n if let Some(spec) = stable_spec.files.get(\"arm64_big_sur\") {\n debug!(\n \"No specific OS bottle found for {}. Falling back to 'arm64_big_sur' bottle.\",\n current_platform\n );\n return Ok((\"arm64_big_sur\".to_string(), spec));\n }\n debug!(\"No 'arm64_big_sur' fallback bottle tag found.\");\n } else if cfg!(target_os = \"macos\") {\n if let Some(spec) = stable_spec.files.get(\"big_sur\") {\n debug!(\n \"No specific OS bottle found for {}. Falling back to 'big_sur' bottle.\",\n current_platform\n );\n return Ok((\"big_sur\".to_string(), spec));\n }\n debug!(\"No 'big_sur' fallback bottle tag found.\");\n }\n if let Some(spec) = stable_spec.files.get(\"all\") {\n debug!(\n \"No platform-specific or OS-specific bottle found for {}. Using 'all' platform bottle.\",\n current_platform\n );\n return Ok((\"all\".to_string(), spec));\n }\n debug!(\"No 'all' platform bottle found.\");\n Err(SpsError::DownloadError(\n formula.name.clone(),\n \"\".to_string(),\n format!(\n \"No compatible bottle found for platform '{}'. Available: {:?}\",\n current_platform,\n stable_spec.files.keys().collect::>()\n ),\n ))\n}\n\npub fn install_bottle(bottle_path: &Path, formula: &Formula, config: &Config) -> Result {\n let install_dir = formula.install_prefix(config.cellar_dir().as_path())?;\n if install_dir.exists() {\n debug!(\n \"Removing existing keg directory before installing: {}\",\n install_dir.display()\n );\n fs::remove_dir_all(&install_dir).map_err(|e| {\n SpsError::InstallError(format!(\n \"Failed to remove existing keg {}: {}\",\n install_dir.display(),\n e\n ))\n })?;\n }\n if let Some(parent_dir) = install_dir.parent() {\n fs::create_dir_all(parent_dir).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\n \"Failed to create parent dir {}: {}\",\n parent_dir.display(),\n e\n ),\n )))\n })?;\n } else {\n return Err(SpsError::InstallError(format!(\n \"Could not determine parent directory for install path: {}\",\n install_dir.display()\n )));\n }\n fs::create_dir_all(&install_dir).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed to create keg dir {}: {}\", install_dir.display(), e),\n )))\n })?;\n let strip_components = 2;\n debug!(\n \"Extracting bottle archive {} to {} with strip_components={}\",\n bottle_path.display(),\n install_dir.display(),\n strip_components\n );\n extract_archive(bottle_path, &install_dir, strip_components, \"gz\")?;\n debug!(\n \"Ensuring write permissions for extracted files in {}\",\n install_dir.display()\n );\n ensure_write_permissions(&install_dir)?;\n debug!(\"Performing bottle relocation in {}\", install_dir.display());\n perform_bottle_relocation(formula, &install_dir, config)?;\n ensure_llvm_symlinks(&install_dir, formula, config)?;\n crate::install::bottle::write_receipt(formula, &install_dir, \"bottle\")?;\n debug!(\n \"Bottle installation complete for {} at {}\",\n formula.name(),\n install_dir.display()\n );\n Ok(install_dir)\n}\n\nfn ensure_write_permissions(path: &Path) -> Result<()> {\n if !path.exists() {\n debug!(\n \"Path {} does not exist, cannot ensure write permissions.\",\n path.display()\n );\n return Ok(());\n }\n for entry_result in WalkDir::new(path).into_iter().filter_map(|e| e.ok()) {\n let entry_path = entry_result.path();\n if entry_path == path && entry_result.depth() == 0 {\n continue;\n }\n match fs::metadata(entry_path) {\n Ok(metadata) => {\n let mut perms = metadata.permissions();\n let _is_readonly = perms.readonly();\n #[cfg(unix)]\n {\n let current_mode = perms.mode();\n let new_mode = current_mode | 0o200;\n if new_mode != current_mode {\n perms.set_mode(new_mode);\n let _ = fs::set_permissions(entry_path, perms);\n }\n }\n #[cfg(not(unix))]\n {\n if _is_readonly {\n perms.set_readonly(false);\n let _ = fs::set_permissions(entry_path, perms);\n }\n }\n }\n Err(_e) => {}\n }\n }\n Ok(())\n}\n\nfn perform_bottle_relocation(formula: &Formula, install_dir: &Path, config: &Config) -> Result<()> {\n let mut repl: HashMap = HashMap::new();\n repl.insert(\n \"@@HOMEBREW_CELLAR@@\".into(),\n config.cellar_dir().to_string_lossy().into(),\n );\n repl.insert(\n \"@@HOMEBREW_PREFIX@@\".into(),\n config.sps_root().to_string_lossy().into(),\n );\n let _prefix_path_str = config.sps_root().to_string_lossy();\n let library_path_str = config\n .sps_root()\n .join(\"Library\")\n .to_string_lossy()\n .to_string(); // Assuming Library is under sps_root for this placeholder\n // HOMEBREW_REPOSITORY usually points to the Homebrew/brew git repo, not relevant for sps in\n // this context. If needed for a specific formula, it should point to\n // /opt/sps or similar.\n repl.insert(\n \"@@HOMEBREW_REPOSITORY@@\".into(),\n config.sps_root().to_string_lossy().into(),\n );\n repl.insert(\"@@HOMEBREW_LIBRARY@@\".into(), library_path_str.to_string());\n\n let formula_opt_path = config.formula_opt_path(formula.name());\n let formula_opt_str = formula_opt_path.to_string_lossy();\n let install_dir_str = install_dir.to_string_lossy();\n if formula_opt_str != install_dir_str {\n repl.insert(formula_opt_str.to_string(), install_dir_str.to_string());\n debug!(\n \"Adding self-opt relocation: {} -> {}\",\n formula_opt_str, install_dir_str\n );\n }\n\n if formula.name().starts_with(\"python@\") {\n let version_full = formula.version_str_full();\n let mut parts = version_full.split('.');\n if let (Some(major), Some(minor)) = (parts.next(), parts.next()) {\n let framework_version = format!(\"{major}.{minor}\");\n let framework_dir = install_dir\n .join(\"Frameworks\")\n .join(\"Python.framework\")\n .join(\"Versions\")\n .join(&framework_version);\n let python_lib = framework_dir.join(\"Python\");\n let python_bin = framework_dir\n .join(\"bin\")\n .join(format!(\"python{major}.{minor}\"));\n\n let absolute_python_lib_path_obj = install_dir\n .join(\"Frameworks\")\n .join(\"Python.framework\")\n .join(\"Versions\")\n .join(&framework_version)\n .join(\"Python\");\n let new_id_abs = absolute_python_lib_path_obj.to_str().ok_or_else(|| {\n SpsError::InstallError(format!(\n \"Failed to convert absolute Python library path to string: {}\",\n absolute_python_lib_path_obj.display()\n ))\n })?;\n\n debug!(\n \"Setting absolute ID for {}: {}\",\n python_lib.display(),\n new_id_abs\n );\n let status_id = StdCommand::new(\"install_name_tool\")\n .args([\"-id\", new_id_abs, python_lib.to_str().unwrap()])\n .stdout(Stdio::null())\n .stderr(Stdio::null())\n .status()\n .map_err(|e| SpsError::Io(Arc::new(e)))?;\n if !status_id.success() {\n error!(\"install_name_tool -id failed for {}\", python_lib.display());\n return Err(SpsError::InstallError(format!(\n \"Failed to set absolute id on Python dynamic library: {}\",\n python_lib.display()\n )));\n }\n\n debug!(\"Skipping -add_rpath as absolute paths are used for Python linkage.\");\n\n let old_load_placeholder = format!(\n \"@@HOMEBREW_CELLAR@@/{}/{}/Frameworks/Python.framework/Versions/{}/Python\",\n formula.name(),\n version_full,\n framework_version\n );\n let old_load_resource_placeholder = format!(\n \"@@HOMEBREW_CELLAR@@/{}/{}/Frameworks/Python.framework/Versions/{}/Resources/Python.app/Contents/MacOS/Python\",\n formula.name(),\n version_full,\n framework_version\n );\n let install_dir_str_ref = install_dir.to_string_lossy();\n let abs_old_load = format!(\n \"{install_dir_str_ref}/Frameworks/Python.framework/Versions/{framework_version}/Python\"\n );\n let abs_old_load_resource = format!(\n \"{install_dir_str_ref}/Frameworks/Python.framework/Versions/{framework_version}/Resources/Python.app/Contents/MacOS/Python\"\n );\n\n let run_change = |old: &str, new: &str, target: &Path| -> Result<()> {\n if !target.exists() {\n debug!(\n \"Target {} does not exist, skipping install_name_tool -change.\",\n target.display()\n );\n return Ok(());\n }\n debug!(\n \"Running install_name_tool -change {} {} {}\",\n old,\n new,\n target.display()\n );\n let output = StdCommand::new(\"install_name_tool\")\n .args([\"-change\", old, new, target.to_str().unwrap()])\n .output()\n .map_err(|e| SpsError::Io(Arc::new(e)))?;\n\n if !output.status.success() {\n let stderr = String::from_utf8_lossy(&output.stderr);\n if !stderr.contains(\"file not found\")\n && !stderr.contains(\"no LC_LOAD_DYLIB command specifying file\")\n && !stderr.contains(\"is not a Mach-O file\")\n && !stderr.contains(\"object file format invalid\")\n && !stderr.trim().is_empty()\n {\n error!(\n \"install_name_tool -change failed unexpectedly for target {}: {}\",\n target.display(),\n stderr.trim()\n );\n } else {\n debug!(\n \"install_name_tool -change: old path '{}' likely not found or target '{}' not relevant (stderr: {}).\",\n old,\n target.display(),\n stderr.trim()\n );\n }\n }\n Ok(())\n };\n\n debug!(\"Patching main executable: {}\", python_bin.display());\n run_change(&old_load_placeholder, new_id_abs, &python_bin)?;\n run_change(&old_load_resource_placeholder, new_id_abs, &python_bin)?;\n run_change(&abs_old_load, new_id_abs, &python_bin)?;\n run_change(&abs_old_load_resource, new_id_abs, &python_bin)?;\n\n let python_app = framework_dir\n .join(\"Resources\")\n .join(\"Python.app\")\n .join(\"Contents\")\n .join(\"MacOS\")\n .join(\"Python\");\n\n if python_app.exists() {\n debug!(\n \"Explicitly patching Python.app executable: {}\",\n python_app.display()\n );\n run_change(&old_load_placeholder, new_id_abs, &python_app)?;\n run_change(&abs_old_load, new_id_abs, &python_app)?;\n run_change(&old_load_resource_placeholder, new_id_abs, &python_app)?;\n run_change(&abs_old_load_resource, new_id_abs, &python_app)?;\n } else {\n warn!(\n \"Python.app executable not found at {}, skipping explicit patch.\",\n python_app.display()\n );\n }\n\n codesign_path(&python_lib)?;\n codesign_path(&python_bin)?;\n if python_app.exists() {\n codesign_path(&python_app)?;\n } else {\n debug!(\n \"Python.app binary not found at {}, skipping codesign.\",\n python_app.display()\n );\n }\n }\n }\n\n if let Some(perl_path) = find_brewed_perl(config.sps_root()).or_else(|| {\n if cfg!(target_os = \"macos\") {\n Some(PathBuf::from(\"/usr/bin/perl\"))\n } else {\n None\n }\n }) {\n repl.insert(\n \"@@HOMEBREW_PERL@@\".into(),\n perl_path.to_string_lossy().into(),\n );\n }\n\n match formula.dependencies() {\n Ok(deps) => {\n if let Some(openjdk) = deps\n .iter()\n .find(|d| d.name.starts_with(\"openjdk\"))\n .map(|d| d.name.clone())\n {\n let openjdk_opt = config.formula_opt_path(&openjdk);\n repl.insert(\n \"@@HOMEBREW_JAVA@@\".into(),\n openjdk_opt\n .join(\"libexec/openjdk.jdk/Contents/Home\")\n .to_string_lossy()\n .into(),\n );\n }\n }\n Err(e) => {\n warn!(\n \"Could not check formula dependencies during relocation for {}: {}\",\n formula.name(),\n e\n );\n }\n }\n\n repl.insert(\"HOMEBREW_RELOCATE_RPATHS\".into(), \"1\".into());\n\n let opt_placeholder = format!(\n \"@@HOMEBREW_OPT_{}@@\",\n formula.name().to_uppercase().replace(['-', '+', '.'], \"_\")\n );\n repl.insert(\n opt_placeholder,\n config\n .formula_opt_path(formula.name())\n .to_string_lossy()\n .into(),\n );\n\n match formula.dependencies() {\n Ok(deps) => {\n let llvm_dep_name = deps\n .iter()\n .find(|d| d.name.starts_with(\"llvm\"))\n .map(|d| d.name.clone());\n if let Some(name) = llvm_dep_name {\n let llvm_opt_path = config.formula_opt_path(&name);\n let llvm_lib = llvm_opt_path.join(\"lib\");\n if llvm_lib.is_dir() {\n repl.insert(\n \"@loader_path/../lib\".into(),\n llvm_lib.to_string_lossy().into(),\n );\n repl.insert(\n format!(\n \"@@HOMEBREW_OPT_{}@@/lib\",\n name.to_uppercase().replace(['-', '+', '.'], \"_\")\n ),\n llvm_lib.to_string_lossy().into(),\n );\n }\n }\n }\n Err(e) => {\n warn!(\n \"Could not check formula dependencies during LLVM relocation for {}: {}\",\n formula.name(),\n e\n );\n }\n }\n\n tracing::debug!(\"Relocation table:\");\n for (k, v) in &repl {\n tracing::debug!(\"{} → {}\", k, v);\n }\n original_relocation_scan_and_patch(formula, install_dir, config, repl)\n}\n\nfn original_relocation_scan_and_patch(\n _formula: &Formula,\n install_dir: &Path,\n _config: &Config,\n replacements: HashMap,\n) -> Result<()> {\n let mut text_replaced_count = 0;\n let mut macho_patched_count = 0;\n let mut permission_errors = 0;\n let mut macho_errors = 0;\n let mut io_errors = 0;\n let mut files_to_chmod: Vec = Vec::new();\n for entry in WalkDir::new(install_dir).into_iter().filter_map(|e| e.ok()) {\n let path = entry.path();\n let file_type = entry.file_type();\n if path\n .components()\n .any(|c| c.as_os_str().to_string_lossy().ends_with(\".app\"))\n {\n if file_type.is_file() {\n debug!(\"Skipping relocation inside .app bundle: {}\", path.display());\n }\n continue;\n }\n if file_type.is_symlink() {\n debug!(\"Checking symlink for potential chmod: {}\", path.display());\n if path\n .parent()\n .is_some_and(|p| p.ends_with(\"bin\") || p.ends_with(\"sbin\"))\n {\n files_to_chmod.push(path.to_path_buf());\n }\n continue;\n }\n if !file_type.is_file() {\n continue;\n }\n let (meta, initially_executable) = match fs::metadata(path) {\n Ok(m) => {\n #[cfg(unix)]\n let ie = m.permissions().mode() & 0o111 != 0;\n #[cfg(not(unix))]\n let ie = true;\n (m, ie)\n }\n Err(_e) => {\n debug!(\"Failed to get metadata for {}: {}\", path.display(), _e);\n io_errors += 1;\n continue;\n }\n };\n let is_in_exec_dir = path\n .parent()\n .is_some_and(|p| p.ends_with(\"bin\") || p.ends_with(\"sbin\"));\n if meta.permissions().readonly() {\n #[cfg(unix)]\n {\n let mut perms = meta.permissions();\n let current_mode = perms.mode();\n let new_mode = current_mode | 0o200;\n if new_mode != current_mode {\n perms.set_mode(new_mode);\n if fs::set_permissions(path, perms).is_err() {\n debug!(\n \"Skipping readonly file (and couldn't make writable): {}\",\n path.display()\n );\n continue;\n } else {\n debug!(\"Made readonly file writable: {}\", path.display());\n }\n }\n }\n #[cfg(not(unix))]\n {\n debug!(\n \"Skipping potentially readonly file on non-unix: {}\",\n path.display()\n );\n continue;\n }\n }\n let mut was_modified = false;\n let mut skipped_paths_for_file = Vec::new();\n if cfg!(target_os = \"macos\")\n && (initially_executable\n || is_in_exec_dir\n || path\n .extension()\n .is_some_and(|e| e == \"dylib\" || e == \"so\" || e == \"bundle\"))\n {\n match macho::patch_macho_file(path, &replacements) {\n Ok((true, skipped_paths)) => {\n macho_patched_count += 1;\n was_modified = true;\n skipped_paths_for_file = skipped_paths;\n }\n Ok((false, skipped_paths)) => {\n // Not Mach-O or no patches needed, but might have skipped paths\n skipped_paths_for_file = skipped_paths;\n }\n Err(SpsError::PathTooLongError(e)) => { // Specifically catch path too long\n error!(\n \"Mach-O patch failed (path too long) for {}: {}\",\n path.display(),\n e\n );\n macho_errors += 1;\n // Continue scanning other files even if one fails this way\n continue;\n }\n Err(SpsError::CodesignError(e)) => { // Specifically catch codesign errors\n error!(\n \"Mach-O patch failed (codesign error) for {}: {}\",\n path.display(),\n e\n );\n macho_errors += 1;\n // Continue scanning other files\n continue;\n }\n // Catch generic MachOError or Object error, treat as non-fatal for text replace\n Err(e @ SpsError::MachOError(_))\n | Err(e @ SpsError::Object(_))\n | Err(e @ SpsError::Generic(_)) // Catch Generic errors from patch_macho too\n | Err(e @ SpsError::Io(_)) => { // Catch IO errors from patch_macho\n debug!(\n \"Mach-O processing/patching failed for {}: {}. Skipping Mach-O patch for this file.\",\n path.display(),\n e\n );\n // Don't increment macho_errors here, as we fallback to text replace\n io_errors += 1; // Count as IO or generic error instead\n }\n // Catch other specific errors if needed\n Err(e) => {\n debug!(\n \"Unexpected error during Mach-O check/patch for {}: {}. Falling back to text replacer.\",\n path.display(),\n e\n );\n io_errors += 1;\n }\n }\n\n // Handle paths that were too long for Mach-O patching with install_name_tool fallback\n if !skipped_paths_for_file.is_empty() {\n debug!(\n \"Applying install_name_tool fallback for {} skipped paths in {}\",\n skipped_paths_for_file.len(),\n path.display()\n );\n debug!(\n \"Applying install_name_tool fallback for {} skipped paths in {}\",\n skipped_paths_for_file.len(),\n path.display()\n );\n for skipped in &skipped_paths_for_file {\n match apply_install_name_tool_change(&skipped.old_path, &skipped.new_path, path)\n {\n Ok(()) => {\n debug!(\n \"Successfully applied install_name_tool fallback: '{}' -> '{}' in {}\",\n skipped.old_path, skipped.new_path, path.display()\n );\n was_modified = true;\n }\n Err(e) => {\n warn!(\n \"install_name_tool fallback failed for '{}' -> '{}' in {}: {}\",\n skipped.old_path,\n skipped.new_path,\n path.display(),\n e\n );\n macho_errors += 1;\n }\n }\n }\n }\n }\n // Fallback to text replacement if not modified by Mach-O patching\n if !was_modified {\n // Heuristic check for text file (avoid reading huge binaries)\n let mut is_likely_text = false;\n if meta.len() < 5 * 1024 * 1024 {\n if let Ok(mut f) = File::open(path) {\n let mut buf = [0; 1024];\n match f.read(&mut buf) {\n Ok(n) if n > 0 => {\n if !buf[..n].contains(&0) {\n is_likely_text = true;\n }\n }\n Ok(_) => {\n is_likely_text = true;\n }\n Err(_) => {}\n }\n }\n }\n\n if is_likely_text {\n // Read the file content as string\n if let Ok(content) = fs::read_to_string(path) {\n let mut new_content = content.clone();\n let mut replacements_made = false;\n for (placeholder, replacement) in &replacements {\n if new_content.contains(placeholder) {\n new_content = new_content.replace(placeholder, replacement);\n replacements_made = true;\n }\n }\n // Write back only if changes were made\n if replacements_made {\n match write_text_file_atomic(path, &new_content) {\n Ok(_) => {\n text_replaced_count += 1;\n was_modified = true; // Mark as modified for chmod check\n }\n Err(e) => {\n error!(\n \"Failed to write replaced text to {}: {}\",\n path.display(),\n e\n );\n io_errors += 1;\n }\n }\n }\n } else if meta.len() > 0 {\n debug!(\n \"Could not read {} as string for text replacement.\",\n path.display()\n );\n io_errors += 1;\n }\n } else if meta.len() >= 5 * 1024 * 1024 {\n debug!(\n \"Skipping text replacement for large file: {}\",\n path.display()\n );\n } else {\n debug!(\n \"Skipping text replacement for likely binary file: {}\",\n path.display()\n );\n }\n }\n if was_modified || initially_executable || is_in_exec_dir {\n files_to_chmod.push(path.to_path_buf());\n }\n }\n\n #[cfg(unix)]\n {\n debug!(\n \"Ensuring execute permissions for {} potentially executable files/links\",\n files_to_chmod.len()\n );\n let unique_files_to_chmod: HashSet<_> = files_to_chmod.into_iter().collect();\n for p in &unique_files_to_chmod {\n if !p.exists() && p.symlink_metadata().is_err() {\n debug!(\"Skipping chmod for non-existent path: {}\", p.display());\n continue;\n }\n match fs::symlink_metadata(p) {\n Ok(m) => {\n if m.is_file() {\n let mut perms = m.permissions();\n let current_mode = perms.mode();\n let new_mode = current_mode | 0o111;\n if new_mode != current_mode {\n perms.set_mode(new_mode);\n if let Err(e) = fs::set_permissions(p, perms) {\n debug!(\"Failed to set +x on {}: {}\", p.display(), e);\n permission_errors += 1;\n }\n }\n }\n }\n Err(e) => {\n debug!(\n \"Could not stat {} during final chmod pass: {}\",\n p.display(),\n e\n );\n permission_errors += 1;\n }\n }\n }\n }\n\n debug!(\n \"Relocation scan complete. Text files replaced: {}, Mach-O files patched: {}\",\n text_replaced_count, macho_patched_count\n );\n if permission_errors > 0 || macho_errors > 0 || io_errors > 0 {\n debug!(\n \"Bottle relocation finished with issues: {} chmod errors, {} Mach-O errors, {} IO errors in {}.\",\n permission_errors,\n macho_errors,\n io_errors,\n install_dir.display()\n );\n if macho_errors > 0 {\n return Err(SpsError::InstallError(format!(\n \"Bottle relocation failed due to {} Mach-O errors in {}\",\n macho_errors,\n install_dir.display()\n )));\n }\n }\n Ok(())\n}\n\nfn codesign_path(target: &Path) -> Result<()> {\n debug!(\"Re‑signing: {}\", target.display());\n let status = StdCommand::new(\"codesign\")\n .args([\n \"-s\",\n \"-\",\n \"--force\",\n \"--preserve-metadata=identifier,entitlements\",\n target\n .to_str()\n .ok_or_else(|| SpsError::Generic(\"Non‑UTF8 path for codesign\".into()))?,\n ])\n .stdout(Stdio::null())\n .stderr(Stdio::null())\n .status()\n .map_err(|e| SpsError::Io(Arc::new(e)))?;\n if !status.success() {\n return Err(SpsError::CodesignError(format!(\n \"codesign failed for {}\",\n target.display()\n )));\n }\n Ok(())\n}\nfn write_text_file_atomic(original_path: &Path, content: &str) -> Result<()> {\n let dir = original_path.parent().ok_or_else(|| {\n SpsError::Generic(format!(\n \"Cannot get parent directory for {}\",\n original_path.display()\n ))\n })?;\n // Ensure the directory exists\n fs::create_dir_all(dir).map_err(|e| SpsError::Io(Arc::new(e)))?; // Use Arc::new\n\n let mut temp_file = NamedTempFile::new_in(dir)?;\n let temp_path = temp_file.path().to_path_buf(); // Store path before consuming temp_file\n\n // Write content\n temp_file.write_all(content.as_bytes())?;\n // Ensure data is flushed from application buffer to OS buffer\n temp_file.flush()?;\n // Attempt to sync data from OS buffer to disk (best effort)\n let _ = temp_file.as_file().sync_all();\n\n // Try to preserve original permissions\n let original_perms = fs::metadata(original_path).map(|m| m.permissions()).ok();\n\n // Atomically replace the original file with the temporary file\n temp_file.persist(original_path).map_err(|e| {\n error!(\n \"Failed to persist/rename temporary text file {} over {}: {}\",\n temp_path.display(), // Use stored path for logging\n original_path.display(),\n e.error // Log the underlying IO error\n );\n // Return the IO error wrapped in our error type\n SpsError::Io(Arc::new(e.error)) // Use Arc::new\n })?;\n\n // Restore original permissions if we captured them\n if let Some(perms) = original_perms {\n // Ignore errors setting permissions, best effort\n let _ = fs::set_permissions(original_path, perms);\n }\n Ok(())\n}\n\n#[cfg(unix)]\nfn find_brewed_perl(prefix: &Path) -> Option {\n let opt_dir = prefix.join(\"opt\");\n if !opt_dir.is_dir() {\n return None;\n }\n let mut best: Option<(semver::Version, PathBuf)> = None;\n match fs::read_dir(opt_dir) {\n Ok(entries) => {\n for entry_res in entries.flatten() {\n let name = entry_res.file_name();\n let s = name.to_string_lossy();\n let entry_path = entry_res.path();\n if !entry_path.is_dir() {\n continue;\n }\n if let Some(version_part) = s.strip_prefix(\"perl@\") {\n let version_str_padded = if version_part.contains('.') {\n let parts: Vec<&str> = version_part.split('.').collect();\n match parts.len() {\n 1 => format!(\"{}.0.0\", parts[0]), // e.g., perl@5 -> 5.0.0\n 2 => format!(\"{}.{}.0\", parts[0], parts[1]), /* e.g., perl@5.30 -> */\n // 5.30.0\n _ => version_part.to_string(), // Already 3+ parts\n }\n } else {\n format!(\"{version_part}.0.0\") // e.g., perl@5 -> 5.0.0 (handles case with no\n // dot)\n };\n\n if let Ok(v) = semver::Version::parse(&version_str_padded) {\n let candidate_bin = entry_path.join(\"bin/perl\");\n if candidate_bin.is_file()\n && (best.is_none() || v > best.as_ref().unwrap().0)\n {\n best = Some((v, candidate_bin));\n }\n }\n } else if s == \"perl\" {\n let candidate_bin = entry_path.join(\"bin/perl\");\n if candidate_bin.is_file() && best.is_none() {\n if let Ok(v_base) = semver::Version::parse(\"5.0.0\") {\n best = Some((v_base, candidate_bin));\n }\n }\n }\n }\n }\n Err(_e) => {\n debug!(\"Failed to read opt directory during perl search: {}\", _e);\n }\n }\n best.map(|(_, path)| path)\n}\n\n#[cfg(not(unix))]\nfn find_brewed_perl(_prefix: &Path) -> Option {\n None\n}\nfn ensure_llvm_symlinks(install_dir: &Path, formula: &Formula, config: &Config) -> Result<()> {\n let lib_dir = install_dir.join(\"lib\");\n if !lib_dir.exists() {\n debug!(\n \"Skipping LLVM symlink creation as lib dir is missing in {}\",\n install_dir.display()\n );\n return Ok(());\n }\n\n let llvm_dep_name = match formula.dependencies() {\n Ok(deps) => deps\n .iter()\n .find(|d| d.name.starts_with(\"llvm\"))\n .map(|dep| dep.name.clone()),\n Err(e) => {\n warn!(\n \"Could not check formula dependencies for LLVM symlink creation in {}: {}\",\n formula.name(),\n e\n );\n return Ok(()); // Don't error, just skip\n }\n };\n\n // Proceed only if llvm_dep_name is Some\n let llvm_dep_name = match llvm_dep_name {\n Some(name) => name,\n None => {\n debug!(\n \"Formula {} does not list an LLVM dependency.\",\n formula.name()\n );\n return Ok(());\n }\n };\n\n let llvm_opt_path = config.formula_opt_path(&llvm_dep_name);\n let llvm_lib_filename = if cfg!(target_os = \"macos\") {\n \"libLLVM.dylib\"\n } else if cfg!(target_os = \"linux\") {\n \"libLLVM.so\"\n } else {\n warn!(\"LLVM library filename unknown for target OS, skipping symlink.\");\n return Ok(());\n };\n let llvm_lib_path_in_opt = llvm_opt_path.join(\"lib\").join(llvm_lib_filename);\n if !llvm_lib_path_in_opt.exists() {\n debug!(\n \"Required LLVM library not found at {}. Cannot create symlink in {}.\",\n llvm_lib_path_in_opt.display(),\n formula.name()\n );\n return Ok(());\n }\n let symlink_target_path = lib_dir.join(llvm_lib_filename);\n if symlink_target_path.exists() || symlink_target_path.symlink_metadata().is_ok() {\n debug!(\n \"Symlink or file already exists at {}. Skipping creation.\",\n symlink_target_path.display()\n );\n return Ok(());\n }\n #[cfg(unix)]\n {\n if let Some(parent) = symlink_target_path.parent() {\n if !parent.exists() {\n fs::create_dir_all(parent)?;\n }\n }\n match symlink(&llvm_lib_path_in_opt, &symlink_target_path) {\n Ok(_) => debug!(\n \"Created symlink {} -> {}\",\n symlink_target_path.display(),\n llvm_lib_path_in_opt.display()\n ),\n Err(e) => {\n // Log as warning, don't fail install\n warn!(\n \"Failed to create LLVM symlink {} -> {}: {}\",\n symlink_target_path.display(),\n llvm_lib_path_in_opt.display(),\n e\n );\n }\n }\n\n let rustlib_dir = install_dir.join(\"lib\").join(\"rustlib\");\n if rustlib_dir.is_dir() {\n if let Ok(entries) = fs::read_dir(&rustlib_dir) {\n for entry in entries.flatten() {\n let triple_path = entry.path();\n if triple_path.is_dir() {\n let triple_lib_dir = triple_path.join(\"lib\");\n if triple_lib_dir.is_dir() {\n let nested_symlink = triple_lib_dir.join(llvm_lib_filename);\n\n if nested_symlink.exists() || nested_symlink.symlink_metadata().is_ok()\n {\n debug!(\n \"Symlink or file already exists at {}, skipping.\",\n nested_symlink.display()\n );\n continue;\n }\n\n if let Some(parent) = nested_symlink.parent() {\n let _ = fs::create_dir_all(parent);\n }\n match symlink(&llvm_lib_path_in_opt, &nested_symlink) {\n Ok(_) => debug!(\n \"Created symlink {} -> {}\",\n nested_symlink.display(),\n llvm_lib_path_in_opt.display()\n ),\n Err(e) => warn!(\n \"Failed to create LLVM symlink {} -> {}: {}\",\n nested_symlink.display(),\n llvm_lib_path_in_opt.display(),\n e\n ),\n }\n }\n }\n }\n }\n }\n }\n Ok(())\n}\n\n/// Applies a path change using install_name_tool as a fallback for Mach-O files\n/// where the path replacement is too long for direct binary patching.\nfn apply_install_name_tool_change(old_path: &str, new_path: &str, target: &Path) -> Result<()> {\n if !target.exists() {\n debug!(\n \"Target {} does not exist, skipping install_name_tool fallback.\",\n target.display()\n );\n return Ok(());\n }\n\n debug!(\n \"Running install_name_tool -change {} {} {}\",\n old_path,\n new_path,\n target.display()\n );\n\n let output = StdCommand::new(\"install_name_tool\")\n .args([\"-change\", old_path, new_path, target.to_str().unwrap()])\n .output()\n .map_err(|e| SpsError::Io(Arc::new(e)))?;\n\n if !output.status.success() {\n let stderr = String::from_utf8_lossy(&output.stderr);\n if !stderr.contains(\"file not found\")\n && !stderr.contains(\"no LC_LOAD_DYLIB command specifying file\")\n && !stderr.contains(\"is not a Mach-O file\")\n && !stderr.contains(\"object file format invalid\")\n && !stderr.trim().is_empty()\n {\n error!(\n \"install_name_tool -change failed unexpectedly for target {}: {}\",\n target.display(),\n stderr.trim()\n );\n return Err(SpsError::InstallError(format!(\n \"install_name_tool failed for {}: {}\",\n target.display(),\n stderr.trim()\n )));\n } else {\n debug!(\n \"install_name_tool -change: old path '{}' likely not found or target '{}' not relevant (stderr: {}).\",\n old_path,\n target.display(),\n stderr.trim()\n );\n return Ok(()); // No changes made, skip re-signing\n }\n }\n\n // Re-sign the binary after making changes (required on Apple Silicon)\n #[cfg(all(target_os = \"macos\", target_arch = \"aarch64\"))]\n {\n debug!(\n \"Re-signing binary after install_name_tool change: {}\",\n target.display()\n );\n codesign_path(target)?;\n }\n\n debug!(\n \"Successfully applied install_name_tool fallback for {} -> {} in {}\",\n old_path,\n new_path,\n target.display()\n );\n\n Ok(())\n}\n"], ["/sps/sps-common/src/config.rs", "// sps-common/src/config.rs\nuse std::env;\nuse std::path::{Path, PathBuf};\n\nuse directories::UserDirs; // Ensure this crate is in sps-common/Cargo.toml\nuse tracing::debug;\n\nuse super::error::Result; // Assuming SpsResult is Result from super::error\n\n// This constant will serve as a fallback if HOMEBREW_PREFIX is not set or is empty.\nconst DEFAULT_FALLBACK_SPS_ROOT: &str = \"/opt/homebrew\";\nconst SPS_ROOT_MARKER_FILENAME: &str = \".sps_root_v1\";\n\n#[derive(Debug, Clone)]\npub struct Config {\n pub sps_root: PathBuf, // Public for direct construction in main for init if needed\n pub api_base_url: String,\n pub artifact_domain: Option,\n pub docker_registry_token: Option,\n pub docker_registry_basic_auth: Option,\n pub github_api_token: Option,\n}\n\nimpl Config {\n pub fn load() -> Result {\n debug!(\"Loading sps configuration\");\n\n // Try to get SPS_ROOT from HOMEBREW_PREFIX environment variable.\n // Fallback to DEFAULT_FALLBACK_SPS_ROOT if not set or empty.\n let sps_root_str = env::var(\"HOMEBREW_PREFIX\").ok().filter(|s| !s.is_empty())\n .unwrap_or_else(|| {\n debug!(\n \"HOMEBREW_PREFIX environment variable not set or empty, falling back to default: {}\",\n DEFAULT_FALLBACK_SPS_ROOT\n );\n DEFAULT_FALLBACK_SPS_ROOT.to_string()\n });\n\n let sps_root_path = PathBuf::from(&sps_root_str);\n debug!(\"Effective SPS_ROOT set to: {}\", sps_root_path.display());\n\n let api_base_url = \"https://formulae.brew.sh/api\".to_string();\n\n let artifact_domain = env::var(\"HOMEBREW_ARTIFACT_DOMAIN\").ok();\n let docker_registry_token = env::var(\"HOMEBREW_DOCKER_REGISTRY_TOKEN\").ok();\n let docker_registry_basic_auth = env::var(\"HOMEBREW_DOCKER_REGISTRY_BASIC_AUTH_TOKEN\").ok();\n let github_api_token = env::var(\"HOMEBREW_GITHUB_API_TOKEN\").ok();\n\n debug!(\"Configuration loaded successfully.\");\n Ok(Self {\n sps_root: sps_root_path,\n api_base_url,\n artifact_domain,\n docker_registry_token,\n docker_registry_basic_auth,\n github_api_token,\n })\n }\n\n pub fn sps_root(&self) -> &Path {\n &self.sps_root\n }\n\n pub fn bin_dir(&self) -> PathBuf {\n self.sps_root.join(\"bin\")\n }\n\n pub fn cellar_dir(&self) -> PathBuf {\n self.sps_root.join(\"Cellar\") // Changed from \"cellar\" to \"Cellar\" to match Homebrew\n }\n\n pub fn cask_room_dir(&self) -> PathBuf {\n self.sps_root.join(\"Caskroom\") // Changed from \"cask_room\" to \"Caskroom\"\n }\n\n pub fn cask_store_dir(&self) -> PathBuf {\n self.sps_root.join(\"sps_cask_store\")\n }\n\n pub fn opt_dir(&self) -> PathBuf {\n self.sps_root.join(\"opt\")\n }\n\n pub fn taps_dir(&self) -> PathBuf {\n self.sps_root.join(\"Library/Taps\") // Adjusted to match Homebrew structure\n }\n\n pub fn cache_dir(&self) -> PathBuf {\n self.sps_root.join(\"sps_cache\")\n }\n\n pub fn logs_dir(&self) -> PathBuf {\n self.sps_root.join(\"sps_logs\")\n }\n\n pub fn tmp_dir(&self) -> PathBuf {\n self.sps_root.join(\"tmp\")\n }\n\n pub fn state_dir(&self) -> PathBuf {\n self.sps_root.join(\"sps_state\")\n }\n\n pub fn man_base_dir(&self) -> PathBuf {\n self.sps_root.join(\"share\").join(\"man\")\n }\n\n pub fn sps_root_marker_path(&self) -> PathBuf {\n self.sps_root.join(SPS_ROOT_MARKER_FILENAME)\n }\n\n pub fn applications_dir(&self) -> PathBuf {\n if cfg!(target_os = \"macos\") {\n PathBuf::from(\"/Applications\")\n } else {\n self.home_dir().join(\"Applications\")\n }\n }\n\n pub fn formula_cellar_dir(&self, formula_name: &str) -> PathBuf {\n self.cellar_dir().join(formula_name)\n }\n\n pub fn formula_keg_path(&self, formula_name: &str, version_str: &str) -> PathBuf {\n self.formula_cellar_dir(formula_name).join(version_str)\n }\n\n pub fn formula_opt_path(&self, formula_name: &str) -> PathBuf {\n self.opt_dir().join(formula_name)\n }\n\n pub fn cask_room_token_path(&self, cask_token: &str) -> PathBuf {\n self.cask_room_dir().join(cask_token)\n }\n\n pub fn cask_store_token_path(&self, cask_token: &str) -> PathBuf {\n self.cask_store_dir().join(cask_token)\n }\n\n pub fn cask_store_version_path(&self, cask_token: &str, version_str: &str) -> PathBuf {\n self.cask_store_token_path(cask_token).join(version_str)\n }\n\n pub fn cask_store_app_path(\n &self,\n cask_token: &str,\n version_str: &str,\n app_name: &str,\n ) -> PathBuf {\n self.cask_store_version_path(cask_token, version_str)\n .join(app_name)\n }\n\n pub fn cask_room_version_path(&self, cask_token: &str, version_str: &str) -> PathBuf {\n self.cask_room_token_path(cask_token).join(version_str)\n }\n\n pub fn home_dir(&self) -> PathBuf {\n UserDirs::new().map_or_else(|| PathBuf::from(\"/\"), |ud| ud.home_dir().to_path_buf())\n }\n\n pub fn get_tap_path(&self, name: &str) -> Option {\n let parts: Vec<&str> = name.split('/').collect();\n if parts.len() == 2 {\n Some(\n self.taps_dir()\n .join(parts[0]) // user, e.g., homebrew\n .join(format!(\"homebrew-{}\", parts[1])), // repo, e.g., homebrew-core\n )\n } else {\n None\n }\n }\n\n pub fn get_formula_path_from_tap(&self, tap_name: &str, formula_name: &str) -> Option {\n self.get_tap_path(tap_name).and_then(|tap_path| {\n let json_path = tap_path\n .join(\"Formula\") // Standard Homebrew tap structure\n .join(format!(\"{formula_name}.json\"));\n if json_path.exists() {\n return Some(json_path);\n }\n // Fallback to .rb for completeness, though API primarily gives JSON\n let rb_path = tap_path.join(\"Formula\").join(format!(\"{formula_name}.rb\"));\n if rb_path.exists() {\n return Some(rb_path);\n }\n None\n })\n }\n}\n\nimpl Default for Config {\n fn default() -> Self {\n Self::load().expect(\"Failed to load default configuration\")\n }\n}\n\npub fn load_config() -> Result {\n Config::load()\n}\n"], ["/sps/sps/src/pipeline/runner.rs", "// sps/src/pipeline/runner.rs\nuse std::collections::{HashMap, HashSet};\nuse std::sync::atomic::{AtomicUsize, Ordering};\nuse std::sync::{Arc, Mutex};\nuse std::time::Instant;\n\nuse colored::Colorize;\nuse crossbeam_channel::bounded as crossbeam_bounded;\nuse reqwest::Client as HttpClient;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::dependency::resolver::{ResolutionStatus, ResolvedGraph};\nuse sps_common::error::{Result as SpsResult, SpsError};\nuse sps_common::model::InstallTargetIdentifier;\nuse sps_common::pipeline::{\n DownloadOutcome, JobProcessingState, PipelineEvent, PlannedJob,\n PlannedOperations as PlannerOutputCommon, WorkerJob,\n};\nuse tokio::sync::{broadcast, mpsc};\nuse tokio::task::JoinHandle;\nuse tracing::{debug, error, instrument, warn};\n\nuse super::downloader::DownloadCoordinator;\nuse super::planner::OperationPlanner;\n\nconst WORKER_JOB_CHANNEL_SIZE: usize = 100;\nconst EVENT_CHANNEL_SIZE: usize = 100;\nconst DOWNLOAD_OUTCOME_CHANNEL_SIZE: usize = 100;\n\n#[derive(Debug, Clone, PartialEq, Eq)]\npub enum CommandType {\n Install,\n Reinstall,\n Upgrade { all: bool },\n}\n\n#[derive(Debug, Clone)]\npub struct PipelineFlags {\n pub build_from_source: bool,\n pub include_optional: bool,\n pub skip_recommended: bool,\n}\n\nstruct PropagationContext {\n all_planned_jobs: Arc>,\n job_states: Arc>>,\n resolved_graph: Arc,\n event_tx: Option>,\n final_fail_count: Arc,\n}\n\nfn err_to_string(e: &SpsError) -> String {\n e.to_string()\n}\n\npub(crate) fn get_panic_message(e: Box) -> String {\n match e.downcast_ref::<&'static str>() {\n Some(s) => (*s).to_string(),\n None => match e.downcast_ref::() {\n Some(s) => s.clone(),\n None => \"Unknown panic payload\".to_string(),\n },\n }\n}\n\n#[instrument(skip_all, fields(cmd = ?command_type, targets = ?initial_targets))]\npub async fn run_pipeline(\n initial_targets: &[String],\n command_type: CommandType,\n config: &Config,\n cache: Arc,\n flags: &PipelineFlags,\n) -> SpsResult<()> {\n debug!(\n \"Pipeline run initiated for targets: {:?}, command: {:?}\",\n initial_targets, command_type\n );\n let start_time = Instant::now();\n let final_success_count = Arc::new(AtomicUsize::new(0));\n let final_fail_count = Arc::new(AtomicUsize::new(0));\n\n debug!(\n \"Creating broadcast channel for pipeline events (EVENT_CHANNEL_SIZE={})\",\n EVENT_CHANNEL_SIZE\n );\n let (event_tx, mut event_rx_for_runner) =\n broadcast::channel::(EVENT_CHANNEL_SIZE);\n\n debug!(\"Cloning event_tx for runner_event_tx_clone\");\n let runner_event_tx_clone = event_tx.clone();\n\n debug!(\n \"Creating crossbeam worker job channel (WORKER_JOB_CHANNEL_SIZE={})\",\n WORKER_JOB_CHANNEL_SIZE\n );\n let (worker_job_tx, worker_job_rx_for_core) =\n crossbeam_bounded::(WORKER_JOB_CHANNEL_SIZE);\n\n debug!(\"Cloning event_tx for core_event_tx_for_worker_manager\");\n let core_config = config.clone();\n let core_cache_clone = cache.clone();\n let core_event_tx_for_worker_manager = event_tx.clone();\n let core_success_count_clone = Arc::clone(&final_success_count);\n let core_fail_count_clone = Arc::clone(&final_fail_count);\n debug!(\"Spawning core worker pool manager thread.\");\n let core_handle = std::thread::spawn(move || {\n debug!(\"CORE_THREAD: Core worker pool manager thread started.\");\n let result = sps_core::pipeline::engine::start_worker_pool_manager(\n core_config,\n core_cache_clone,\n worker_job_rx_for_core,\n core_event_tx_for_worker_manager,\n core_success_count_clone,\n core_fail_count_clone,\n );\n debug!(\n \"CORE_THREAD: Core worker pool manager thread finished. Result: {:?}\",\n result.is_ok()\n );\n result\n });\n\n debug!(\"Subscribing to event_tx for status_event_rx\");\n let status_config = config.clone();\n let status_event_rx = event_tx.subscribe();\n debug!(\"Spawning status handler task.\");\n let status_handle = tokio::spawn(crate::cli::status::handle_events(\n status_config,\n status_event_rx,\n ));\n\n debug!(\n \"Creating mpsc download_outcome channel (DOWNLOAD_OUTCOME_CHANNEL_SIZE={})\",\n DOWNLOAD_OUTCOME_CHANNEL_SIZE\n );\n let (download_outcome_tx, mut download_outcome_rx) =\n mpsc::channel::(DOWNLOAD_OUTCOME_CHANNEL_SIZE);\n\n debug!(\"Initializing pipeline planning phase...\");\n let planner_output: PlannerOutputCommon;\n {\n debug!(\"Cloning runner_event_tx_clone for planner_event_tx_clone\");\n let planner_event_tx_clone = runner_event_tx_clone.clone();\n debug!(\"Creating OperationPlanner.\");\n let operation_planner =\n OperationPlanner::new(config, cache.clone(), flags, planner_event_tx_clone);\n\n debug!(\"Calling plan_operations...\");\n match operation_planner\n .plan_operations(initial_targets, command_type.clone())\n .await\n {\n Ok(ops) => {\n debug!(\"plan_operations returned Ok.\");\n planner_output = ops;\n }\n Err(e) => {\n error!(\"Fatal planning error: {}\", e);\n runner_event_tx_clone\n .send(PipelineEvent::LogError {\n message: format!(\"Fatal planning error: {e}\"),\n })\n .ok();\n drop(worker_job_tx);\n if let Err(join_err) = core_handle.join() {\n error!(\n \"Core thread join error after planning failure: {:?}\",\n get_panic_message(join_err)\n );\n }\n let duration = start_time.elapsed();\n runner_event_tx_clone\n .send(PipelineEvent::PipelineFinished {\n duration_secs: duration.as_secs_f64(),\n success_count: 0,\n fail_count: initial_targets.len(),\n })\n .ok();\n\n debug!(\"Dropping runner_event_tx_clone due to planning error.\");\n drop(runner_event_tx_clone);\n debug!(\"Dropping main event_tx due to planning error.\");\n drop(event_tx);\n\n debug!(\"Awaiting status_handle after planning error.\");\n if let Err(join_err) = status_handle.await {\n error!(\n \"Status task join error after planning failure: {}\",\n join_err\n );\n }\n return Err(e);\n }\n }\n debug!(\"OperationPlanner scope ended, planner_event_tx_clone dropped.\");\n }\n\n let planned_jobs = Arc::new(planner_output.jobs);\n let resolved_graph = planner_output.resolved_graph.clone()\n .unwrap_or_else(|| {\n tracing::debug!(\"ResolvedGraph was None in planner output. Using a default empty graph. This is expected if no formulae required resolution or if planner reported errors for all formulae.\");\n Arc::new(sps_common::dependency::resolver::ResolvedGraph::default())\n });\n\n debug!(\n \"Planning finished. Total jobs in plan: {}.\",\n planned_jobs.len()\n );\n runner_event_tx_clone\n .send(PipelineEvent::PlanningFinished {\n job_count: planned_jobs.len(),\n })\n .ok();\n\n // Mark jobs with planner errors as failed and emit error events\n let job_processing_states = Arc::new(Mutex::new(HashMap::::new()));\n let mut jobs_pending_or_active = 0;\n let mut initial_fail_count_from_planner = 0;\n {\n let mut states_guard = job_processing_states.lock().unwrap();\n if !planner_output.errors.is_empty() {\n tracing::debug!(\n \"[Runner] Planner reported {} error(s). These targets will be marked as failed.\",\n planner_output.errors.len()\n );\n for (target_name, error) in &planner_output.errors {\n let msg = format!(\"✗ {}: {}\", target_name.cyan(), error);\n runner_event_tx_clone\n .send(PipelineEvent::LogError { message: msg })\n .ok();\n states_guard.insert(\n target_name.clone(),\n JobProcessingState::Failed(Arc::new(error.clone())),\n );\n initial_fail_count_from_planner += 1;\n }\n }\n for job in planned_jobs.iter() {\n if states_guard.contains_key(&job.target_id) {\n continue;\n }\n if planner_output\n .already_installed_or_up_to_date\n .contains(&job.target_id)\n {\n states_guard.insert(job.target_id.clone(), JobProcessingState::Succeeded);\n final_success_count.fetch_add(1, Ordering::Relaxed);\n debug!(\n \"[{}] Marked as Succeeded (pre-existing/up-to-date).\",\n job.target_id\n );\n } else if let Some((_, err)) = planner_output\n .errors\n .iter()\n .find(|(name, _)| name == &job.target_id)\n {\n states_guard.insert(\n job.target_id.clone(),\n JobProcessingState::Failed(Arc::new(err.clone())),\n );\n // Counted in initial_fail_count_from_planner\n debug!(\n \"[{}] Marked as Failed (planning error: {}).\",\n job.target_id, err\n );\n } else if job.use_private_store_source.is_some() {\n let path = job.use_private_store_source.clone().unwrap();\n states_guard.insert(\n job.target_id.clone(),\n JobProcessingState::Downloaded(path.clone()),\n );\n jobs_pending_or_active += 1;\n debug!(\n \"[{}] Initial state: Downloaded (private store: {}). Active jobs: {}\",\n job.target_id,\n path.display(),\n jobs_pending_or_active\n );\n } else {\n states_guard.insert(job.target_id.clone(), JobProcessingState::PendingDownload);\n jobs_pending_or_active += 1;\n debug!(\n \"[{}] Initial state: PendingDownload. Active jobs: {}\",\n job.target_id, jobs_pending_or_active\n );\n }\n }\n }\n debug!(\n \"Initial job states populated. Jobs pending/active: {}\",\n jobs_pending_or_active\n );\n\n let mut downloads_to_initiate = Vec::new();\n {\n let states_guard = job_processing_states.lock().unwrap();\n for job in planned_jobs.iter() {\n if matches!(\n states_guard.get(&job.target_id),\n Some(JobProcessingState::PendingDownload)\n ) {\n downloads_to_initiate.push(job.clone());\n }\n }\n }\n\n let mut download_coordinator_task_handle: Option>> = None;\n\n if !downloads_to_initiate.is_empty() {\n debug!(\"Cloning runner_event_tx_clone for download_coordinator_event_tx_clone\");\n let download_coordinator_event_tx_clone = runner_event_tx_clone.clone();\n let http_client = Arc::new(HttpClient::new());\n let config_for_downloader_owned = config.clone();\n\n let mut download_coordinator = DownloadCoordinator::new(\n config_for_downloader_owned,\n cache.clone(),\n http_client,\n download_coordinator_event_tx_clone,\n );\n debug!(\n \"Starting download coordination for {} jobs...\",\n downloads_to_initiate.len()\n );\n debug!(\"Cloning download_outcome_tx for tx_for_download_task\");\n let tx_for_download_task = download_outcome_tx.clone();\n\n debug!(\"Spawning DownloadCoordinator task.\");\n download_coordinator_task_handle = Some(tokio::spawn(async move {\n debug!(\"DOWNLOAD_COORD_TASK: DownloadCoordinator task started.\");\n let result = download_coordinator\n .coordinate_downloads(downloads_to_initiate, tx_for_download_task)\n .await;\n debug!(\"DOWNLOAD_COORD_TASK: DownloadCoordinator task finished. coordinate_downloads returned.\");\n result\n }));\n } else if jobs_pending_or_active > 0 {\n debug!(\n \"No downloads to initiate, but {} jobs are pending. Triggering check_and_dispatch.\",\n jobs_pending_or_active\n );\n check_and_dispatch(\n planned_jobs.clone(),\n job_processing_states.clone(),\n resolved_graph.clone(),\n &worker_job_tx,\n runner_event_tx_clone.clone(),\n config,\n flags,\n );\n } else {\n debug!(\"No downloads to initiate and no jobs pending/active. Pipeline might be empty or all pre-satisfied/failed.\");\n }\n\n drop(download_outcome_tx);\n debug!(\"Dropped main MPSC download_outcome_tx (runner's original clone).\");\n\n if !planned_jobs.is_empty() {\n runner_event_tx_clone\n .send(PipelineEvent::PipelineStarted {\n total_jobs: planned_jobs.len(),\n })\n .ok();\n }\n\n let mut propagation_ctx = PropagationContext {\n all_planned_jobs: planned_jobs.clone(),\n job_states: job_processing_states.clone(),\n resolved_graph: resolved_graph.clone(),\n event_tx: Some(runner_event_tx_clone.clone()),\n final_fail_count: final_fail_count.clone(),\n };\n\n debug!(\n \"Entering main event loop. Jobs pending/active: {}\",\n jobs_pending_or_active\n );\n\n // Robust main loop: continue while there are jobs pending/active, or downloads, or jobs in\n // states that could be dispatched\n fn has_pending_dispatchable_jobs(\n states_guard: &std::sync::MutexGuard>,\n ) -> bool {\n states_guard.values().any(|state| {\n matches!(\n state,\n JobProcessingState::Downloaded(_) | JobProcessingState::WaitingForDependencies(_)\n )\n })\n }\n\n while jobs_pending_or_active > 0\n || has_pending_dispatchable_jobs(&job_processing_states.lock().unwrap())\n {\n tokio::select! {\n biased;\n Some(download_outcome) = download_outcome_rx.recv() => {\n debug!(\"Received DownloadOutcome for '{}'.\", download_outcome.planned_job.target_id);\n process_download_outcome(\n download_outcome,\n &propagation_ctx,\n &mut jobs_pending_or_active,\n );\n debug!(\"After process_download_outcome, jobs_pending_or_active: {}. Triggering check_and_dispatch.\", jobs_pending_or_active);\n check_and_dispatch(\n planned_jobs.clone(),\n job_processing_states.clone(),\n resolved_graph.clone(),\n &worker_job_tx,\n runner_event_tx_clone.clone(),\n config,\n flags,\n );\n }\n Ok(event) = event_rx_for_runner.recv() => {\n match event {\n PipelineEvent::JobSuccess { ref target_id, .. } => {\n debug!(\"Received JobSuccess for '{}'.\", target_id);\n process_core_worker_feedback(\n target_id.clone(),\n true,\n None,\n job_processing_states.clone(),\n &mut jobs_pending_or_active,\n );\n debug!(\"After JobSuccess for '{}', jobs_pending_or_active: {}. Triggering check_and_dispatch.\", target_id, jobs_pending_or_active);\n check_and_dispatch(\n planned_jobs.clone(),\n job_processing_states.clone(),\n resolved_graph.clone(),\n &worker_job_tx,\n runner_event_tx_clone.clone(),\n config,\n flags,\n );\n }\n PipelineEvent::JobFailed { ref target_id, ref error, ref action } => {\n debug!(\"Received JobFailed for '{}' (Action: {:?}, Error: {}).\", target_id, action, error);\n process_core_worker_feedback(\n target_id.clone(),\n false,\n Some(SpsError::Generic(error.clone())),\n job_processing_states.clone(),\n &mut jobs_pending_or_active,\n );\n debug!(\"After JobFailed for '{}', jobs_pending_or_active: {}. Triggering failure propagation.\", target_id, jobs_pending_or_active);\n propagate_failure(\n target_id,\n Arc::new(SpsError::Generic(format!(\"Core worker failed for {target_id}: {error}\"))),\n &propagation_ctx,\n &mut jobs_pending_or_active,\n );\n check_and_dispatch(\n planned_jobs.clone(),\n job_processing_states.clone(),\n resolved_graph.clone(),\n &worker_job_tx,\n runner_event_tx_clone.clone(),\n config,\n flags,\n );\n }\n _ => {}\n }\n }\n else => {\n debug!(\"Main select loop 'else' branch. jobs_pending_or_active = {}. download_outcome_rx or event_rx_for_runner might be closed.\", jobs_pending_or_active);\n if jobs_pending_or_active > 0 || has_pending_dispatchable_jobs(&job_processing_states.lock().unwrap()) {\n warn!(\"Exiting main loop prematurely but still have {} jobs pending/active or dispatchable. This might indicate a stall or logic error.\", jobs_pending_or_active);\n }\n break;\n }\n }\n debug!(\n \"End of select! loop iteration. Jobs pending/active: {}\",\n jobs_pending_or_active\n );\n }\n debug!(\n \"Main event loop finished. Final jobs_pending_or_active: {}\",\n jobs_pending_or_active\n );\n\n drop(download_outcome_rx);\n debug!(\"Dropped MPSC download_outcome_rx (runner's receiver).\");\n\n if let Some(handle) = download_coordinator_task_handle {\n debug!(\"Waiting for DownloadCoordinator task to complete...\");\n match handle.await {\n Ok(critical_download_errors) => {\n if !critical_download_errors.is_empty() {\n warn!(\n \"DownloadCoordinator task reported critical errors: {:?}\",\n critical_download_errors\n );\n final_fail_count.fetch_add(critical_download_errors.len(), Ordering::Relaxed);\n }\n debug!(\"DownloadCoordinator task completed.\");\n }\n Err(e) => {\n let panic_msg = get_panic_message(Box::new(e));\n error!(\n \"DownloadCoordinator task panicked or failed to join: {}\",\n panic_msg\n );\n final_fail_count.fetch_add(1, Ordering::Relaxed);\n }\n }\n } else {\n debug!(\"No DownloadCoordinator task was spawned or it was already handled.\");\n }\n debug!(\"DownloadCoordinator task processing finished (awaited or none).\");\n\n debug!(\"Closing worker job channel (signal to core workers).\");\n drop(worker_job_tx);\n debug!(\"Waiting for core worker pool to join...\");\n match core_handle.join() {\n Ok(Ok(())) => debug!(\"Core worker pool manager thread completed successfully.\"),\n Ok(Err(e)) => {\n error!(\"Core worker pool manager thread failed: {}\", e);\n final_fail_count.fetch_add(1, Ordering::Relaxed);\n }\n Err(e) => {\n error!(\n \"Core worker pool manager thread panicked: {:?}\",\n get_panic_message(e)\n );\n final_fail_count.fetch_add(1, Ordering::Relaxed);\n }\n }\n debug!(\"Core worker pool joined. core_event_tx_for_worker_manager (broadcast sender) dropped.\");\n\n let duration = start_time.elapsed();\n let success_total = final_success_count.load(Ordering::Relaxed);\n let fail_total = final_fail_count.load(Ordering::Relaxed) + initial_fail_count_from_planner;\n\n debug!(\n \"Pipeline processing finished. Success: {}, Fail: {}. Duration: {:.2}s. Sending PipelineFinished event.\",\n success_total, fail_total, duration.as_secs_f64()\n );\n if let Err(e) = runner_event_tx_clone.send(PipelineEvent::PipelineFinished {\n duration_secs: duration.as_secs_f64(),\n success_count: success_total,\n fail_count: fail_total,\n }) {\n warn!(\n \"Failed to send PipelineFinished event: {:?}. Status handler might not receive it.\",\n e\n );\n }\n\n // Explicitly drop the event_tx inside propagation_ctx before dropping the last senders.\n propagation_ctx.event_tx = None;\n\n debug!(\"Dropping runner_event_tx_clone (broadcast sender).\");\n drop(runner_event_tx_clone);\n // event_rx_for_runner (broadcast receiver) goes out of scope here and is dropped.\n\n debug!(\"Dropping main event_tx (final broadcast sender).\");\n drop(event_tx);\n\n debug!(\"All known broadcast senders dropped. About to await status_handle.\");\n if let Err(e) = status_handle.await {\n warn!(\"Status handler task failed or panicked: {}\", e);\n } else {\n debug!(\"Status handler task completed successfully.\");\n }\n debug!(\"run_pipeline function is ending.\");\n\n if fail_total == 0 {\n Ok(())\n } else {\n let mut accumulated_errors = Vec::new();\n for (name, err_obj) in planner_output.errors {\n accumulated_errors.push(format!(\"Planning for '{name}': {err_obj}\"));\n }\n let states_guard = job_processing_states.lock().unwrap();\n for job in planned_jobs.iter() {\n if let Some(JobProcessingState::Failed(err_arc)) = states_guard.get(&job.target_id) {\n let err_str = err_to_string(err_arc);\n let job_err_msg = format!(\"Processing '{}': {}\", job.target_id, err_str);\n if !accumulated_errors.contains(&job_err_msg) {\n accumulated_errors.push(job_err_msg);\n }\n }\n }\n drop(states_guard);\n\n let specific_error_msg = if accumulated_errors.is_empty() {\n \"No specific errors logged, check core worker logs.\".to_string()\n } else {\n accumulated_errors.join(\"; \")\n };\n\n // Error details are already sent via PipelineEvent::JobFailed events\n // and will be displayed in status.rs\n Err(SpsError::InstallError(format!(\n \"Operation failed with {fail_total} total failure(s). Details: [{specific_error_msg}] (Worker errors are included in total)\"\n )))\n }\n}\n\nfn process_download_outcome(\n outcome: DownloadOutcome,\n propagation_ctx: &PropagationContext,\n jobs_pending_or_active: &mut usize,\n) {\n let job_id = outcome.planned_job.target_id.clone();\n let mut states_guard = propagation_ctx.job_states.lock().unwrap();\n\n match states_guard.get(&job_id) {\n Some(JobProcessingState::Succeeded) | Some(JobProcessingState::Failed(_)) => {\n debug!(\n \"[{}] DownloadOutcome: Job already in terminal state {:?}. Ignoring outcome.\",\n job_id,\n states_guard.get(&job_id)\n );\n return;\n }\n _ => {}\n }\n\n match outcome.result {\n Ok(path) => {\n debug!(\n \"[{}] DownloadOutcome: Success. Path: {}. Updating state to Downloaded.\",\n job_id,\n path.display()\n );\n states_guard.insert(job_id.clone(), JobProcessingState::Downloaded(path));\n }\n Err(e) => {\n warn!(\n \"[{}] DownloadOutcome: Failed. Error: {}. Updating state to Failed.\",\n job_id, e\n );\n let error_arc = Arc::new(e);\n states_guard.insert(\n job_id.clone(),\n JobProcessingState::Failed(error_arc.clone()),\n );\n\n if let Some(ref tx) = propagation_ctx.event_tx {\n tx.send(PipelineEvent::job_failed(\n job_id.clone(),\n outcome.planned_job.action.clone(),\n &error_arc,\n ))\n .ok();\n }\n propagation_ctx\n .final_fail_count\n .fetch_add(1, Ordering::Relaxed);\n\n if *jobs_pending_or_active > 0 {\n *jobs_pending_or_active -= 1;\n debug!(\"[{}] DownloadOutcome: Decremented jobs_pending_or_active to {} due to download failure.\", job_id, *jobs_pending_or_active);\n } else {\n warn!(\"[{}] DownloadOutcome: jobs_pending_or_active is already 0, cannot decrement for download failure.\", job_id);\n }\n\n drop(states_guard);\n debug!(\"[{}] DownloadOutcome: Propagating failure.\", job_id);\n propagate_failure(&job_id, error_arc, propagation_ctx, jobs_pending_or_active);\n }\n }\n}\n\nfn process_core_worker_feedback(\n target_id: String,\n success: bool,\n error: Option,\n job_states: Arc>>,\n jobs_pending_or_active: &mut usize,\n) {\n let mut states_guard = job_states.lock().unwrap();\n\n match states_guard.get(&target_id) {\n Some(JobProcessingState::Succeeded) | Some(JobProcessingState::Failed(_)) => {\n debug!(\"[{}] CoreFeedback: Job already in terminal state {:?}. Ignoring active job count update.\", target_id, states_guard.get(&target_id));\n return;\n }\n _ => {}\n }\n\n if success {\n debug!(\n \"[{}] CoreFeedback: Success. Updating state to Succeeded.\",\n target_id\n );\n states_guard.insert(target_id.clone(), JobProcessingState::Succeeded);\n } else {\n let err_msg = error.as_ref().map_or_else(\n || \"Unknown core worker error\".to_string(),\n |e| e.to_string(),\n );\n debug!(\n \"[{}] CoreFeedback: Failed. Error: {}. Updating state to Failed.\",\n target_id, err_msg\n );\n let err_arc = Arc::new(\n error.unwrap_or_else(|| SpsError::Generic(\"Unknown core worker error\".into())),\n );\n states_guard.insert(target_id.clone(), JobProcessingState::Failed(err_arc));\n }\n\n if *jobs_pending_or_active > 0 {\n *jobs_pending_or_active -= 1;\n debug!(\n \"[{}] CoreFeedback: Decremented jobs_pending_or_active to {}.\",\n target_id, *jobs_pending_or_active\n );\n } else {\n warn!(\n \"[{}] CoreFeedback: jobs_pending_or_active is already 0, cannot decrement.\",\n target_id\n );\n }\n}\n\nfn check_and_dispatch(\n planned_jobs_arc: Arc>,\n job_states: Arc>>,\n resolved_graph: Arc,\n worker_job_tx: &crossbeam_channel::Sender,\n event_tx: broadcast::Sender,\n config: &Config,\n flags: &PipelineFlags,\n) {\n debug!(\"--- Enter check_and_dispatch ---\");\n let mut states_guard = job_states.lock().unwrap();\n let mut dispatched_this_round = 0;\n\n for planned_job in planned_jobs_arc.iter() {\n let job_id = &planned_job.target_id;\n debug!(\"[{}] CheckDispatch: Evaluating job.\", job_id);\n\n let (current_state_is_dispatchable, path_for_dispatch) = {\n match states_guard.get(job_id) {\n Some(JobProcessingState::Downloaded(ref path)) => {\n debug!(\"[{}] CheckDispatch: Current state is Downloaded.\", job_id);\n (true, Some(path.clone()))\n }\n Some(JobProcessingState::WaitingForDependencies(ref path)) => {\n debug!(\n \"[{}] CheckDispatch: Current state is WaitingForDependencies.\",\n job_id\n );\n (true, Some(path.clone()))\n }\n other_state => {\n debug!(\n \"[{}] CheckDispatch: Not in a dispatchable state. Current state: {:?}.\",\n job_id,\n other_state.map(|s| format!(\"{s:?}\"))\n );\n (false, None)\n }\n }\n };\n\n if current_state_is_dispatchable {\n let path = path_for_dispatch.unwrap();\n drop(states_guard);\n debug!(\n \"[{}] CheckDispatch: Calling are_dependencies_succeeded.\",\n job_id\n );\n let dependencies_succeeded = are_dependencies_succeeded(\n job_id,\n &planned_job.target_definition,\n job_states.clone(),\n &resolved_graph,\n config,\n flags,\n );\n states_guard = job_states.lock().unwrap();\n debug!(\n \"[{}] CheckDispatch: are_dependencies_succeeded returned: {}.\",\n job_id, dependencies_succeeded\n );\n\n let current_state_after_dep_check = states_guard.get(job_id).cloned();\n if !matches!(\n current_state_after_dep_check,\n Some(JobProcessingState::Downloaded(_))\n | Some(JobProcessingState::WaitingForDependencies(_))\n ) {\n debug!(\"[{}] CheckDispatch: State changed to {:?} while checking dependencies. Skipping dispatch.\", job_id, current_state_after_dep_check);\n continue;\n }\n\n if dependencies_succeeded {\n debug!(\n \"[{}] CheckDispatch: All dependencies satisfied. Dispatching to core worker.\",\n job_id\n );\n let worker_job = WorkerJob {\n request: planned_job.clone(),\n download_path: path.clone(),\n download_size_bytes: std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0),\n is_source_from_private_store: planned_job.use_private_store_source.is_some(),\n };\n if worker_job_tx.send(worker_job).is_ok() {\n states_guard.insert(\n job_id.clone(),\n JobProcessingState::DispatchedToCore(path.clone()),\n );\n event_tx\n .send(PipelineEvent::JobDispatchedToCore {\n target_id: job_id.clone(),\n })\n .ok();\n dispatched_this_round += 1;\n debug!(\"[{}] CheckDispatch: Successfully dispatched.\", job_id);\n } else {\n error!(\"[{}] CheckDispatch: Failed to send job to worker channel (channel closed?). Marking as failed.\", job_id);\n let err = Arc::new(SpsError::Generic(\"Worker channel closed\".to_string()));\n if !matches!(\n states_guard.get(job_id),\n Some(JobProcessingState::Failed(_))\n ) {\n states_guard\n .insert(job_id.clone(), JobProcessingState::Failed(err.clone()));\n event_tx\n .send(PipelineEvent::job_failed(\n job_id.clone(),\n planned_job.action.clone(),\n &err,\n ))\n .ok();\n }\n }\n } else if matches!(\n current_state_after_dep_check,\n Some(JobProcessingState::Downloaded(_))\n ) {\n debug!(\"[{}] CheckDispatch: Dependencies not met. Updating state to WaitingForDependencies.\", job_id);\n states_guard.insert(\n job_id.clone(),\n JobProcessingState::WaitingForDependencies(path.clone()),\n );\n } else {\n debug!(\n \"[{}] CheckDispatch: Dependencies not met. State remains {:?}.\",\n job_id, current_state_after_dep_check\n );\n }\n }\n }\n if dispatched_this_round > 0 {\n debug!(\n \"Dispatched {} jobs to core workers in this round.\",\n dispatched_this_round\n );\n }\n debug!(\"--- Exit check_and_dispatch ---\");\n}\n\nfn are_dependencies_succeeded(\n target_id: &str,\n target_def: &InstallTargetIdentifier,\n job_states_arc: Arc>>,\n resolved_graph: &ResolvedGraph,\n config: &Config,\n flags: &PipelineFlags,\n) -> bool {\n debug!(\"[{}] AreDepsSucceeded: Checking dependencies...\", target_id);\n let dependencies_to_check: Vec = match target_def {\n InstallTargetIdentifier::Formula(formula_arc) => {\n if let Some(resolved_dep_info) =\n resolved_graph.resolution_details.get(formula_arc.name())\n {\n let parent_strategy = resolved_dep_info.determined_install_strategy;\n let empty_actions = std::collections::HashMap::new();\n let context = sps_common::dependency::ResolutionContext {\n formulary: &sps_common::formulary::Formulary::new(config.clone()),\n keg_registry: &sps_common::keg::KegRegistry::new(config.clone()),\n sps_prefix: config.sps_root(),\n include_optional: flags.include_optional,\n include_test: false,\n skip_recommended: flags.skip_recommended,\n initial_target_preferences: &Default::default(),\n build_all_from_source: flags.build_from_source,\n cascade_source_preference_to_dependencies: true,\n has_bottle_for_current_platform:\n sps_core::install::bottle::has_bottle_for_current_platform,\n initial_target_actions: &empty_actions,\n };\n\n let deps: Vec = formula_arc\n .dependencies()\n .unwrap_or_default()\n .iter()\n .filter(|dep_edge| {\n context.should_process_dependency_edge(\n formula_arc,\n dep_edge.tags,\n parent_strategy,\n )\n })\n .map(|dep_edge| dep_edge.name.clone())\n .collect();\n debug!(\n \"[{}] AreDepsSucceeded: Formula dependencies to check: {:?}\",\n target_id, deps\n );\n deps\n } else {\n warn!(\"[{}] AreDepsSucceeded: Formula not found in ResolvedGraph. Assuming no dependencies.\", target_id);\n Vec::new()\n }\n }\n InstallTargetIdentifier::Cask(cask_arc) => {\n let deps = if let Some(deps_on) = &cask_arc.depends_on {\n deps_on.formula.clone()\n } else {\n Vec::new()\n };\n debug!(\n \"[{}] AreDepsSucceeded: Cask formula dependencies to check: {:?}\",\n target_id, deps\n );\n deps\n }\n };\n\n if dependencies_to_check.is_empty() {\n debug!(\n \"[{}] AreDepsSucceeded: No dependencies to check. Returning true.\",\n target_id\n );\n return true;\n }\n\n let states_guard = job_states_arc.lock().unwrap();\n for dep_name in &dependencies_to_check {\n match states_guard.get(dep_name) {\n Some(JobProcessingState::Succeeded) => {\n debug!(\n \"[{}] AreDepsSucceeded: Dependency '{}' is Succeeded.\",\n target_id, dep_name\n );\n }\n Some(JobProcessingState::Failed(err)) => {\n debug!(\n \"[{}] AreDepsSucceeded: Dependency '{}' is FAILED ({}). Returning false.\",\n target_id,\n dep_name,\n err_to_string(err)\n );\n return false;\n }\n None => {\n if let Some(resolved_dep_detail) = resolved_graph.resolution_details.get(dep_name) {\n if resolved_dep_detail.status == ResolutionStatus::Installed {\n debug!(\"[{}] AreDepsSucceeded: Dependency '{}' is already installed (from ResolvedGraph).\", target_id, dep_name);\n } else {\n debug!(\"[{}] AreDepsSucceeded: Dependency '{}' has no active state and not ResolvedGraph::Installed (is {:?}). Returning false.\", target_id, dep_name, resolved_dep_detail.status);\n return false;\n }\n } else {\n warn!(\"[{}] AreDepsSucceeded: Dependency '{}' not found in job_states OR ResolvedGraph. Assuming not met. Returning false.\", target_id, dep_name);\n return false;\n }\n }\n other_state => {\n debug!(\"[{}] AreDepsSucceeded: Dependency '{}' is not yet Succeeded. Current state: {:?}. Returning false.\", target_id, dep_name, other_state.map(|s| format!(\"{s:?}\")));\n return false;\n }\n }\n }\n debug!(\n \"[{}] AreDepsSucceeded: All dependencies Succeeded or were pre-installed. Returning true.\",\n target_id\n );\n true\n}\n\nfn propagate_failure(\n failed_job_id: &str,\n failure_reason: Arc,\n ctx: &PropagationContext,\n jobs_pending_or_active: &mut usize,\n) {\n debug!(\n \"[{}] PropagateFailure: Starting for reason: {}\",\n failed_job_id, failure_reason\n );\n let mut dependents_to_fail_queue = vec![failed_job_id.to_string()];\n let mut newly_failed_dependents = HashSet::new();\n\n {\n let mut states_guard = ctx.job_states.lock().unwrap();\n if !matches!(\n states_guard.get(failed_job_id),\n Some(JobProcessingState::Failed(_))\n ) {\n states_guard.insert(\n failed_job_id.to_string(),\n JobProcessingState::Failed(failure_reason.clone()),\n );\n }\n }\n\n let mut current_idx = 0;\n while current_idx < dependents_to_fail_queue.len() {\n let current_source_of_failure = dependents_to_fail_queue[current_idx].clone();\n current_idx += 1;\n\n for job_to_check in ctx.all_planned_jobs.iter() {\n if job_to_check.target_id == failed_job_id\n || newly_failed_dependents.contains(&job_to_check.target_id)\n {\n continue;\n }\n\n let is_dependent = match &job_to_check.target_definition {\n InstallTargetIdentifier::Formula(formula_arc) => ctx\n .resolved_graph\n .resolution_details\n .get(formula_arc.name())\n .is_some_and(|res_dep_info| {\n res_dep_info\n .formula\n .dependencies()\n .unwrap_or_default()\n .iter()\n .any(|d| d.name == current_source_of_failure)\n }),\n InstallTargetIdentifier::Cask(cask_arc) => {\n cask_arc.depends_on.as_ref().is_some_and(|deps| {\n deps.formula.contains(¤t_source_of_failure)\n || deps.cask.contains(¤t_source_of_failure)\n })\n }\n };\n\n if is_dependent {\n let mut states_guard = ctx.job_states.lock().unwrap();\n let current_state_of_dependent = states_guard.get(&job_to_check.target_id).cloned();\n\n if !matches!(\n current_state_of_dependent,\n Some(JobProcessingState::Succeeded) | Some(JobProcessingState::Failed(_))\n ) {\n let propagated_error = Arc::new(SpsError::DependencyError(format!(\n \"Dependency '{}' failed: {}\",\n current_source_of_failure,\n err_to_string(&failure_reason)\n )));\n states_guard.insert(\n job_to_check.target_id.clone(),\n JobProcessingState::Failed(propagated_error.clone()),\n );\n\n if newly_failed_dependents.insert(job_to_check.target_id.clone()) {\n dependents_to_fail_queue.push(job_to_check.target_id.clone());\n ctx.final_fail_count.fetch_add(1, Ordering::Relaxed);\n\n if *jobs_pending_or_active > 0 {\n *jobs_pending_or_active -= 1;\n debug!(\"[{}] PropagateFailure: Decremented jobs_pending_or_active to {} for propagated failure.\", job_to_check.target_id, *jobs_pending_or_active);\n } else {\n warn!(\"[{}] PropagateFailure: jobs_pending_or_active is already 0, cannot decrement for propagated failure.\", job_to_check.target_id);\n }\n\n if let Some(ref tx) = ctx.event_tx {\n tx.send(PipelineEvent::job_failed(\n job_to_check.target_id.clone(),\n job_to_check.action.clone(),\n &propagated_error,\n ))\n .ok();\n }\n debug!(\"[{}] PropagateFailure: Marked as FAILED due to propagated failure from '{}'.\", job_to_check.target_id, current_source_of_failure);\n }\n }\n drop(states_guard);\n }\n }\n }\n\n if !newly_failed_dependents.is_empty() {\n debug!(\n \"[{}] PropagateFailure: Finished. Newly failed dependents: {:?}\",\n failed_job_id, newly_failed_dependents\n );\n } else {\n debug!(\n \"[{}] PropagateFailure: Finished. No new dependents marked as failed.\",\n failed_job_id\n );\n }\n}\n"], ["/sps/sps-core/src/install/bottle/mod.rs", "// ===== sps-core/src/build/formula/mod.rs =====\nuse std::fs::File;\nuse std::io::Write;\nuse std::path::{Path, PathBuf};\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::formula::Formula;\nuse tracing::{debug, error};\n\n// Declare submodules\npub mod exec;\npub mod link;\npub mod macho;\n\n/// Download formula resources from the internet asynchronously.\npub async fn download_formula(\n formula: &Formula,\n config: &Config,\n client: &reqwest::Client,\n) -> Result {\n if has_bottle_for_current_platform(formula) {\n exec::download_bottle(formula, config, client).await\n } else {\n Err(SpsError::Generic(format!(\n \"No bottle available for {} on this platform\",\n formula.name()\n )))\n }\n}\n\n/// Checks if a suitable bottle exists for the current platform, considering fallbacks.\npub fn has_bottle_for_current_platform(formula: &Formula) -> bool {\n let result = crate::install::bottle::exec::get_bottle_for_platform(formula);\n debug!(\n \"has_bottle_for_current_platform check for '{}': {:?}\",\n formula.name(),\n result.is_ok()\n );\n if let Err(e) = &result {\n debug!(\"Reason for no bottle: {}\", e);\n }\n result.is_ok()\n}\n\n// *** Updated get_current_platform function ***\nfn get_current_platform() -> String {\n if cfg!(target_os = \"macos\") {\n let arch = if std::env::consts::ARCH == \"aarch64\" {\n \"arm64\"\n } else if std::env::consts::ARCH == \"x86_64\" {\n \"x86_64\"\n } else {\n std::env::consts::ARCH\n };\n\n debug!(\"Attempting to determine macOS version using /usr/bin/sw_vers -productVersion\");\n match Command::new(\"/usr/bin/sw_vers\")\n .arg(\"-productVersion\")\n .output()\n {\n Ok(output) => {\n let stdout = String::from_utf8_lossy(&output.stdout);\n let stderr = String::from_utf8_lossy(&output.stderr);\n debug!(\"sw_vers status: {}\", output.status);\n if !output.status.success() || !stderr.trim().is_empty() {\n debug!(\"sw_vers stdout:\\n{}\", stdout);\n if !stderr.trim().is_empty() {\n debug!(\"sw_vers stderr:\\n{}\", stderr);\n }\n }\n\n if output.status.success() {\n let version_str = stdout.trim();\n if !version_str.is_empty() {\n debug!(\"Extracted version string: {}\", version_str);\n let os_name = match version_str.split('.').next() {\n Some(\"15\") => \"sequoia\",\n Some(\"14\") => \"sonoma\",\n Some(\"13\") => \"ventura\",\n Some(\"12\") => \"monterey\",\n Some(\"11\") => \"big_sur\",\n Some(\"10\") => match version_str.split('.').nth(1) {\n Some(\"15\") => \"catalina\",\n Some(\"14\") => \"mojave\",\n _ => {\n debug!(\n \"Unrecognized legacy macOS 10.x version: {}\",\n version_str\n );\n \"unknown_macos\"\n }\n },\n _ => {\n debug!(\"Unrecognized macOS major version: {}\", version_str);\n \"unknown_macos\"\n }\n };\n\n if os_name != \"unknown_macos\" {\n let platform_tag = if arch == \"arm64\" {\n format!(\"{arch}_{os_name}\")\n } else {\n os_name.to_string()\n };\n debug!(\"Determined platform tag: {}\", platform_tag);\n return platform_tag;\n }\n } else {\n error!(\"sw_vers -productVersion output was empty.\");\n }\n } else {\n error!(\n \"sw_vers -productVersion command failed with status: {}. Stderr: {}\",\n output.status,\n stderr.trim()\n );\n }\n }\n Err(e) => {\n error!(\"Failed to execute /usr/bin/sw_vers -productVersion: {}\", e);\n }\n }\n\n error!(\"!!! FAILED TO DETECT MACOS VERSION VIA SW_VERS !!!\");\n debug!(\"Using UNRELIABLE fallback platform detection. Bottle selection may be incorrect.\");\n if arch == \"arm64\" {\n debug!(\"Falling back to platform tag: arm64_monterey\");\n \"arm64_monterey\".to_string()\n } else {\n debug!(\"Falling back to platform tag: monterey\");\n \"monterey\".to_string()\n }\n } else if cfg!(target_os = \"linux\") {\n if std::env::consts::ARCH == \"aarch64\" {\n \"arm64_linux\".to_string()\n } else if std::env::consts::ARCH == \"x86_64\" {\n \"x86_64_linux\".to_string()\n } else {\n \"unknown\".to_string()\n }\n } else {\n debug!(\n \"Could not determine platform tag for OS: {}\",\n std::env::consts::OS\n );\n \"unknown\".to_string()\n }\n}\n\n// REMOVED: get_cellar_path (now in Config)\n\n// --- get_formula_cellar_path uses Config ---\n// Parameter changed from formula: &Formula to formula_name: &str\n// Parameter changed from config: &Config to cellar_path: &Path for consistency where Config isn't\n// fully available If Config *is* available, call config.formula_cellar_dir(formula.name()) instead.\n// **Keeping original signature for now where Config might not be easily passed**\npub fn get_formula_cellar_path(formula: &Formula, config: &Config) -> PathBuf {\n // Use Config method\n config.formula_cellar_dir(formula.name())\n}\n\n// --- write_receipt (unchanged) ---\npub fn write_receipt(\n formula: &Formula,\n install_dir: &Path,\n installation_type: &str, // \"bottle\" or \"source\"\n) -> Result<()> {\n let receipt_path = install_dir.join(\"INSTALL_RECEIPT.json\");\n let receipt_file = File::create(&receipt_path);\n let mut receipt_file = match receipt_file {\n Ok(file) => file,\n Err(e) => {\n error!(\n \"Failed to create receipt file at {}: {}\",\n receipt_path.display(),\n e\n );\n return Err(SpsError::Io(std::sync::Arc::new(e)));\n }\n };\n\n let resources_result = formula.resources();\n let resources_installed = match resources_result {\n Ok(res) => res.iter().map(|r| r.name.clone()).collect::>(),\n Err(_) => {\n debug!(\n \"Could not retrieve resources for formula {} when writing receipt.\",\n formula.name\n );\n vec![]\n }\n };\n\n let timestamp = chrono::Utc::now().to_rfc3339();\n\n let receipt = serde_json::json!({\n \"name\": formula.name, \"version\": formula.version_str_full(), \"time\": timestamp,\n \"source\": { \"type\": \"api\", \"url\": formula.url, },\n \"built_on\": {\n \"os\": std::env::consts::OS, \"arch\": std::env::consts::ARCH,\n \"platform_tag\": get_current_platform(),\n },\n \"installation_type\": installation_type,\n \"resources_installed\": resources_installed,\n });\n\n let receipt_json = match serde_json::to_string_pretty(&receipt) {\n Ok(json) => json,\n Err(e) => {\n error!(\n \"Failed to serialize receipt JSON for {}: {}\",\n formula.name, e\n );\n return Err(SpsError::Json(std::sync::Arc::new(e)));\n }\n };\n\n if let Err(e) = receipt_file.write_all(receipt_json.as_bytes()) {\n error!(\"Failed to write receipt file for {}: {}\", formula.name, e);\n return Err(SpsError::Io(std::sync::Arc::new(e)));\n }\n\n Ok(())\n}\n\n// --- Re-exports (unchanged) ---\npub use exec::install_bottle;\npub use link::link_formula_artifacts;\n"], ["/sps/sps-core/src/uninstall/cask.rs", "// sps-core/src/uninstall/cask.rs\nuse std::fs;\nuse std::path::{Path, PathBuf};\nuse std::process::{Command, Stdio};\n\nuse lazy_static::lazy_static;\nuse regex::Regex;\n// serde_json is used for CaskInstallManifest deserialization\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::{Cask, ZapActionDetail};\nuse tracing::{debug, error, warn};\nuse trash; // This will be used by trash_path\n\n// Import helpers from the common module within the uninstall scope\nuse super::common::{expand_tilde, is_safe_path, remove_filesystem_artifact};\nuse crate::check::installed::InstalledPackageInfo;\n// Corrected import path if install::cask::helpers is where it lives now\nuse crate::install::cask::helpers::{\n cleanup_empty_parent_dirs_in_private_store,\n remove_path_robustly as remove_path_robustly_from_install_helpers,\n};\nuse crate::install::cask::CaskInstallManifest;\n#[cfg(target_os = \"macos\")]\nuse crate::utils::applescript;\n\nlazy_static! {\n static ref VALID_PKGID_RE: Regex = Regex::new(r\"^[a-zA-Z0-9._-]+$\").unwrap();\n static ref VALID_LABEL_RE: Regex = Regex::new(r\"^[a-zA-Z0-9._-]+$\").unwrap();\n static ref VALID_SCRIPT_PATH_RE: Regex = Regex::new(r\"^[a-zA-Z0-9/._-]+$\").unwrap();\n static ref VALID_SIGNAL_RE: Regex = Regex::new(r\"^[A-Z0-9]+$\").unwrap();\n static ref VALID_BUNDLE_ID_RE: Regex =\n Regex::new(r\"^[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)+$\").unwrap();\n}\n\n/// Performs a \"soft\" uninstall for a Cask.\n/// It processes the `CASK_INSTALL_MANIFEST.json` to remove linked artifacts\n/// and then updates the manifest to mark the cask as not currently installed.\n/// The Cask's versioned directory in the Caskroom is NOT removed.\npub fn uninstall_cask_artifacts(info: &InstalledPackageInfo, config: &Config) -> Result<()> {\n debug!(\n \"Soft uninstalling Cask artifacts for {} version {}\",\n info.name, info.version\n );\n let manifest_path = info.path.join(\"CASK_INSTALL_MANIFEST.json\");\n let mut removal_errors: Vec = Vec::new();\n\n if manifest_path.is_file() {\n debug!(\n \"Processing manifest for soft uninstall: {}\",\n manifest_path.display()\n );\n match fs::read_to_string(&manifest_path) {\n Ok(manifest_str) => match serde_json::from_str::(&manifest_str) {\n Ok(mut manifest) => {\n if !manifest.is_installed {\n debug!(\"Cask {} version {} is already marked as uninstalled in manifest. Nothing to do for soft uninstall.\", info.name, info.version);\n return Ok(());\n }\n\n debug!(\n \"Soft uninstalling {} artifacts listed in manifest for {} {}...\",\n manifest.artifacts.len(),\n info.name,\n info.version\n );\n for artifact in manifest.artifacts.iter().rev() {\n if !process_artifact_uninstall_core(artifact, config, false) {\n removal_errors.push(format!(\"Failed to remove artifact: {artifact:?}\"));\n }\n }\n\n manifest.is_installed = false;\n match fs::File::create(&manifest_path) {\n Ok(file) => {\n let writer = std::io::BufWriter::new(file);\n if let Err(e) = serde_json::to_writer_pretty(writer, &manifest) {\n warn!(\n \"Failed to update manifest {}: {}\",\n manifest_path.display(),\n e\n );\n } else {\n debug!(\n \"Manifest updated successfully for soft uninstall: {}\",\n manifest_path.display()\n );\n }\n }\n Err(e) => {\n warn!(\n \"Failed to open manifest for writing (soft uninstall) at {}: {}\",\n manifest_path.display(),\n e\n );\n }\n }\n }\n Err(e) => warn!(\n \"Failed to parse cask manifest {}: {}. Cannot perform detailed soft uninstall.\",\n manifest_path.display(),\n e\n ),\n },\n Err(e) => warn!(\n \"Failed to read cask manifest {}: {}. Cannot perform detailed soft uninstall.\",\n manifest_path.display(),\n e\n ),\n }\n } else {\n warn!(\n \"No CASK_INSTALL_MANIFEST.json found in {}. Cannot perform detailed soft uninstall for {} {}.\",\n info.path.display(),\n info.name,\n info.version\n );\n }\n\n if removal_errors.is_empty() {\n Ok(())\n } else {\n Err(SpsError::InstallError(format!(\n \"Errors during cask artifact soft removal for {}: {}\",\n info.name,\n removal_errors.join(\"; \")\n )))\n }\n}\n\n/// Performs a \"zap\" uninstall for a Cask, removing files defined in `zap` stanzas\n/// and cleaning up the private store. Also marks the cask as uninstalled in its manifest.\npub async fn zap_cask_artifacts(\n info: &InstalledPackageInfo,\n cask_def: &Cask,\n config: &Config,\n) -> Result<()> {\n debug!(\"Starting ZAP process for cask: {}\", cask_def.token);\n let home = config.home_dir();\n let cask_version_path_in_caskroom = &info.path;\n let mut zap_errors: Vec = Vec::new();\n\n let mut primary_app_name_from_manifest: Option = None;\n let manifest_path = cask_version_path_in_caskroom.join(\"CASK_INSTALL_MANIFEST.json\");\n\n if manifest_path.is_file() {\n match fs::read_to_string(&manifest_path) {\n Ok(manifest_str) => match serde_json::from_str::(&manifest_str) {\n Ok(mut manifest) => {\n primary_app_name_from_manifest = manifest.primary_app_file_name.clone();\n if manifest.is_installed {\n manifest.is_installed = false;\n if let Ok(file) = fs::File::create(&manifest_path) {\n let writer = std::io::BufWriter::new(file);\n if let Err(e) = serde_json::to_writer_pretty(writer, &manifest) {\n warn!(\n \"Failed to update manifest during zap for {}: {}\",\n manifest_path.display(),\n e\n );\n }\n } else {\n warn!(\n \"Failed to open manifest for writing during zap at {}\",\n manifest_path.display()\n );\n }\n }\n }\n Err(e) => warn!(\n \"Failed to parse manifest during zap {}: {}\",\n manifest_path.display(),\n e\n ),\n },\n Err(e) => warn!(\n \"Failed to read manifest during zap {}: {}\",\n manifest_path.display(),\n e\n ),\n }\n } else {\n warn!(\"No manifest found at {} during zap. Private store cleanup might be incomplete if app name changed.\", manifest_path.display());\n }\n\n if !cleanup_private_store(\n &cask_def.token,\n &info.version,\n primary_app_name_from_manifest.as_deref(),\n config,\n ) {\n let msg = format!(\n \"Failed to clean up private store for cask {} version {}\",\n cask_def.token, info.version\n );\n warn!(\"{}\", msg);\n zap_errors.push(msg);\n }\n\n let zap_stanzas = match &cask_def.zap {\n Some(stanzas) => stanzas,\n None => {\n debug!(\"No zap stanza found for cask {}\", cask_def.token);\n // Proceed to Caskroom cleanup even if no specific zap actions\n if !remove_filesystem_artifact(cask_version_path_in_caskroom, true) {\n // use_sudo = true for Caskroom\n if cask_version_path_in_caskroom.exists() {\n zap_errors.push(format!(\n \"Failed to remove Caskroom version directory during zap: {}\",\n cask_version_path_in_caskroom.display()\n ));\n }\n }\n if let Some(parent_token_dir) = cask_version_path_in_caskroom.parent() {\n if parent_token_dir.exists() && parent_token_dir.is_dir() {\n match fs::read_dir(parent_token_dir) {\n Ok(mut entries) => {\n if entries.next().is_none()\n && !remove_filesystem_artifact(parent_token_dir, true)\n && parent_token_dir.exists()\n {\n warn!(\"Failed to remove empty Caskroom token directory during zap: {}\", parent_token_dir.display());\n }\n }\n Err(e) => warn!(\n \"Failed to read Caskroom token dir {} during zap: {}\",\n parent_token_dir.display(),\n e\n ),\n }\n }\n }\n return if zap_errors.is_empty() {\n Ok(())\n } else {\n Err(SpsError::Generic(zap_errors.join(\"; \")))\n };\n }\n };\n\n for stanza_map in zap_stanzas {\n for (action_key, action_detail) in &stanza_map.0 {\n debug!(\n \"Processing zap action: {} = {:?}\",\n action_key, action_detail\n );\n match action_detail {\n ZapActionDetail::Trash(paths) => {\n for path_str in paths {\n let target = expand_tilde(path_str, &home);\n if is_safe_path(&target, &home, config) {\n if !trash_path(&target) {\n // Logged within trash_path\n }\n } else {\n zap_errors\n .push(format!(\"Skipped unsafe trash path {}\", target.display()));\n }\n }\n }\n ZapActionDetail::Delete(paths) | ZapActionDetail::Rmdir(paths) => {\n for path_str in paths {\n let target = expand_tilde(path_str, &home);\n if is_safe_path(&target, &home, config) {\n let use_sudo = target.starts_with(\"/Library\")\n || target.starts_with(\"/Applications\");\n let exists_before =\n target.exists() || target.symlink_metadata().is_ok();\n if exists_before {\n if action_key == \"rmdir\" && !target.is_dir() {\n warn!(\"Zap rmdir target is not a directory: {}. Attempting as file delete.\", target.display());\n }\n if !remove_filesystem_artifact(&target, use_sudo)\n && (target.exists() || target.symlink_metadata().is_ok())\n {\n zap_errors.push(format!(\n \"Failed to {} {}\",\n action_key,\n target.display()\n ));\n }\n } else {\n debug!(\n \"Zap target {} not found, skipping removal.\",\n target.display()\n );\n }\n } else {\n zap_errors.push(format!(\n \"Skipped unsafe {} path {}\",\n action_key,\n target.display()\n ));\n }\n }\n }\n ZapActionDetail::Pkgutil(ids_sv) => {\n for id in ids_sv.clone().into_vec() {\n if !VALID_PKGID_RE.is_match(&id) {\n warn!(\"Invalid pkgutil ID format for zap: '{}'. Skipping.\", id);\n zap_errors.push(format!(\"Invalid pkgutil ID: {id}\"));\n continue;\n }\n if !forget_pkgutil_receipt(&id) {\n // Error logged in helper\n }\n }\n }\n ZapActionDetail::Launchctl(labels_sv) => {\n for label in labels_sv.clone().into_vec() {\n if !VALID_LABEL_RE.is_match(&label) {\n warn!(\n \"Invalid launchctl label format for zap: '{}'. Skipping.\",\n label\n );\n zap_errors.push(format!(\"Invalid launchctl label: {label}\"));\n continue;\n }\n let potential_paths = vec![\n home.join(\"Library/LaunchAgents\")\n .join(format!(\"{label}.plist\")),\n PathBuf::from(\"/Library/LaunchAgents\").join(format!(\"{label}.plist\")),\n PathBuf::from(\"/Library/LaunchDaemons\").join(format!(\"{label}.plist\")),\n ];\n let path_to_try = potential_paths.into_iter().find(|p| p.exists());\n if !unload_and_remove_launchd(&label, path_to_try.as_deref()) {\n // Error logged in helper\n }\n }\n }\n ZapActionDetail::Script { executable, args } => {\n let script_path_str = executable;\n if !VALID_SCRIPT_PATH_RE.is_match(script_path_str) {\n error!(\n \"Zap script path contains invalid characters: '{}'. Skipping.\",\n script_path_str\n );\n zap_errors.push(format!(\"Skipped invalid script path: {script_path_str}\"));\n continue;\n }\n let script_full_path = PathBuf::from(script_path_str);\n if !script_full_path.exists() {\n if !script_full_path.is_absolute() {\n if let Ok(found_path) = which::which(&script_full_path) {\n debug!(\n \"Found zap script {} in PATH: {}\",\n script_full_path.display(),\n found_path.display()\n );\n run_zap_script(\n &found_path,\n args.as_ref().map(|v| v.as_slice()),\n &mut zap_errors,\n );\n } else {\n error!(\n \"Zap script '{}' not found (absolute or in PATH). Skipping.\",\n script_full_path.display()\n );\n zap_errors.push(format!(\n \"Zap script not found: {}\",\n script_full_path.display()\n ));\n }\n } else {\n error!(\n \"Absolute zap script path '{}' not found. Skipping.\",\n script_full_path.display()\n );\n zap_errors.push(format!(\n \"Zap script not found: {}\",\n script_full_path.display()\n ));\n }\n continue;\n }\n run_zap_script(\n &script_full_path,\n args.as_ref().map(|v| v.as_slice()),\n &mut zap_errors,\n );\n }\n ZapActionDetail::Signal(signals) => {\n for signal_spec in signals {\n let parts: Vec<&str> = signal_spec.splitn(2, '/').collect();\n if parts.len() != 2 {\n warn!(\"Invalid signal spec format '{}', expected SIGNAL/bundle.id. Skipping.\", signal_spec);\n zap_errors.push(format!(\"Invalid signal spec: {signal_spec}\"));\n continue;\n }\n let signal = parts[0].trim().to_uppercase();\n let bundle_id_or_pattern = parts[1].trim();\n\n if !VALID_SIGNAL_RE.is_match(&signal) {\n warn!(\n \"Invalid signal name '{}' in spec '{}'. Skipping.\",\n signal, signal_spec\n );\n zap_errors.push(format!(\"Invalid signal name: {signal}\"));\n continue;\n }\n\n debug!(\"Sending signal {} to processes matching ID/pattern '{}' (using pkill -f)\", signal, bundle_id_or_pattern);\n let mut cmd = Command::new(\"pkill\");\n cmd.arg(format!(\"-{signal}\")); // Standard signal format for pkill\n cmd.arg(\"-f\");\n cmd.arg(bundle_id_or_pattern);\n cmd.stdout(Stdio::null()).stderr(Stdio::piped());\n match cmd.status() {\n Ok(status) => {\n if status.success() {\n debug!(\"Successfully sent signal {} via pkill to processes matching '{}'.\", signal, bundle_id_or_pattern);\n } else if status.code() == Some(1) {\n debug!(\"No running processes found matching ID/pattern '{}' for signal {} via pkill.\", bundle_id_or_pattern, signal);\n } else {\n warn!(\"pkill command failed for signal {} / ID/pattern '{}' with status: {}\", signal, bundle_id_or_pattern, status);\n }\n }\n Err(e) => {\n error!(\n \"Failed to execute pkill for signal {} / ID/pattern '{}': {}\",\n signal, bundle_id_or_pattern, e\n );\n zap_errors.push(format!(\"Failed to run pkill for signal {signal}\"));\n }\n }\n }\n }\n }\n }\n }\n\n debug!(\n \"Zap: Removing Caskroom version directory: {}\",\n cask_version_path_in_caskroom.display()\n );\n if !remove_filesystem_artifact(cask_version_path_in_caskroom, true)\n && cask_version_path_in_caskroom.exists()\n {\n let msg = format!(\n \"Failed to remove Caskroom version directory during zap: {}\",\n cask_version_path_in_caskroom.display()\n );\n error!(\"{}\", msg);\n zap_errors.push(msg);\n }\n\n if let Some(parent_token_dir) = cask_version_path_in_caskroom.parent() {\n if parent_token_dir.exists() && parent_token_dir.is_dir() {\n match fs::read_dir(parent_token_dir) {\n Ok(mut entries) => {\n if entries.next().is_none() {\n debug!(\n \"Zap: Removing empty Caskroom token directory: {}\",\n parent_token_dir.display()\n );\n if !remove_filesystem_artifact(parent_token_dir, true)\n && parent_token_dir.exists()\n {\n warn!(\n \"Failed to remove empty Caskroom token directory during zap: {}\",\n parent_token_dir.display()\n );\n }\n }\n }\n Err(e) => warn!(\n \"Failed to read Caskroom token directory {} during zap cleanup: {}\",\n parent_token_dir.display(),\n e\n ),\n }\n }\n }\n\n if zap_errors.is_empty() {\n debug!(\n \"Zap process completed successfully for cask: {}\",\n cask_def.token\n );\n Ok(())\n } else {\n error!(\n \"Zap process for {} completed with errors: {}\",\n cask_def.token,\n zap_errors.join(\"; \")\n );\n Err(SpsError::InstallError(format!(\n \"Zap for {} failed with errors: {}\",\n cask_def.token,\n zap_errors.join(\"; \")\n )))\n }\n}\n\nfn process_artifact_uninstall_core(\n artifact: &InstalledArtifact,\n config: &Config,\n use_sudo_for_zap: bool,\n) -> bool {\n debug!(\"Processing artifact removal: {:?}\", artifact);\n match artifact {\n InstalledArtifact::AppBundle { path } => {\n debug!(\"Uninstall: Removing AppBundle at {}\", path.display());\n match path.symlink_metadata() {\n Ok(metadata) if metadata.file_type().is_symlink() => {\n debug!(\"AppBundle at {} is a symlink; unlinking.\", path.display());\n match std::fs::remove_file(path) {\n Ok(_) => true,\n Err(e) => {\n warn!(\"Failed to unlink symlink at {}: {}\", path.display(), e);\n false\n }\n }\n }\n Ok(metadata) if metadata.file_type().is_dir() => {\n #[cfg(target_os = \"macos\")]\n {\n if path.exists() {\n if let Err(e) = applescript::quit_app_gracefully(path) {\n warn!(\n \"Attempt to gracefully quit app at {} failed: {} (proceeding)\",\n path.display(),\n e\n );\n }\n } else {\n debug!(\n \"App bundle at {} does not exist, skipping quit.\",\n path.display()\n );\n }\n }\n let use_sudo = path.starts_with(config.applications_dir())\n || path.starts_with(\"/Applications\")\n || use_sudo_for_zap;\n remove_filesystem_artifact(path, use_sudo)\n }\n Ok(_) | Err(_) => {\n let use_sudo = path.starts_with(config.applications_dir())\n || path.starts_with(\"/Applications\")\n || use_sudo_for_zap;\n remove_filesystem_artifact(path, use_sudo)\n }\n }\n }\n InstalledArtifact::BinaryLink { link_path, .. }\n | InstalledArtifact::ManpageLink { link_path, .. }\n | InstalledArtifact::CaskroomLink { link_path, .. } => {\n debug!(\"Uninstall: Removing link at {}\", link_path.display());\n remove_filesystem_artifact(link_path, use_sudo_for_zap)\n }\n InstalledArtifact::PkgUtilReceipt { id } => {\n debug!(\"Uninstall: Forgetting PkgUtilReceipt {}\", id);\n forget_pkgutil_receipt(id)\n }\n InstalledArtifact::Launchd { label, path } => {\n debug!(\"Uninstall: Unloading Launchd {} (path: {:?})\", label, path);\n unload_and_remove_launchd(label, path.as_deref())\n }\n InstalledArtifact::MovedResource { path } => {\n debug!(\"Uninstall: Removing MovedResource at {}\", path.display());\n remove_filesystem_artifact(path, use_sudo_for_zap)\n }\n InstalledArtifact::CaskroomReference { path } => {\n debug!(\n \"Uninstall: Removing CaskroomReference at {}\",\n path.display()\n );\n remove_filesystem_artifact(path, use_sudo_for_zap)\n }\n }\n}\n\nfn forget_pkgutil_receipt(id: &str) -> bool {\n if !VALID_PKGID_RE.is_match(id) {\n error!(\"Invalid pkgutil ID format: '{}'. Skipping forget.\", id);\n return false;\n }\n debug!(\"Forgetting package receipt (requires sudo): {}\", id);\n let output = Command::new(\"sudo\")\n .arg(\"pkgutil\")\n .arg(\"--forget\")\n .arg(id)\n .output();\n match output {\n Ok(out) if out.status.success() => {\n debug!(\"Successfully forgot package receipt {}\", id);\n true\n }\n Ok(out) => {\n let stderr = String::from_utf8_lossy(&out.stderr);\n if !stderr.contains(\"No receipt for\") && !stderr.trim().is_empty() {\n error!(\"Failed to forget package receipt {}: {}\", id, stderr.trim());\n // Return false if pkgutil fails for a reason other than \"No receipt\"\n return false;\n } else {\n debug!(\"Package receipt {} already forgotten or never existed.\", id);\n }\n true\n }\n Err(e) => {\n error!(\"Failed to execute sudo pkgutil --forget {}: {}\", id, e);\n false\n }\n }\n}\n\nfn unload_and_remove_launchd(label: &str, path: Option<&Path>) -> bool {\n if !VALID_LABEL_RE.is_match(label) {\n error!(\n \"Invalid launchd label format: '{}'. Skipping unload/remove.\",\n label\n );\n return false;\n }\n debug!(\"Unloading launchd service (if loaded): {}\", label);\n let unload_output = Command::new(\"launchctl\")\n .arg(\"unload\")\n .arg(\"-w\")\n .arg(label)\n .stderr(Stdio::piped())\n .output();\n\n let mut unload_successful_or_not_loaded = false;\n match unload_output {\n Ok(out) if out.status.success() => {\n debug!(\"Successfully unloaded launchd service {}\", label);\n unload_successful_or_not_loaded = true;\n }\n Ok(out) => {\n let stderr = String::from_utf8_lossy(&out.stderr);\n if stderr.contains(\"Could not find specified service\")\n || stderr.contains(\"service is not loaded\")\n || stderr.trim().is_empty()\n {\n debug!(\"Launchd service {} already unloaded or not found.\", label);\n unload_successful_or_not_loaded = true;\n } else {\n warn!(\n \"launchctl unload {} failed (but proceeding with plist removal attempt): {}\",\n label,\n stderr.trim()\n );\n // Proceed to try plist removal even if unload reports other errors\n }\n }\n Err(e) => {\n warn!(\"Failed to execute launchctl unload {} (but proceeding with plist removal attempt): {}\", label, e);\n }\n }\n\n if let Some(plist_path) = path {\n if plist_path.exists() {\n debug!(\"Removing launchd plist file: {}\", plist_path.display());\n let use_sudo = plist_path.starts_with(\"/Library/LaunchDaemons\")\n || plist_path.starts_with(\"/Library/LaunchAgents\");\n if !remove_filesystem_artifact(plist_path, use_sudo) {\n warn!(\"Failed to remove launchd plist: {}\", plist_path.display());\n return false; // If plist removal fails, consider the operation failed\n }\n } else {\n debug!(\n \"Launchd plist path {} does not exist, skip removal.\",\n plist_path.display()\n );\n }\n } else {\n debug!(\n \"No path provided for launchd plist removal for label {}\",\n label\n );\n }\n unload_successful_or_not_loaded // Success depends on unload and optional plist removal\n}\n\nfn trash_path(path: &Path) -> bool {\n if !path.exists() && path.symlink_metadata().is_err() {\n debug!(\"Path for trashing not found: {}\", path.display());\n return true;\n }\n match trash::delete(path) {\n Ok(_) => {\n debug!(\"Trashed: {}\", path.display());\n true\n }\n Err(e) => {\n warn!(\"Failed to trash {} (proceeding anyway): {}. This might require manual cleanup or installing a 'trash' utility.\", path.display(), e);\n true\n }\n }\n}\n\n/// Helper for zap scripts.\nfn run_zap_script(script_path: &Path, args: Option<&[String]>, errors: &mut Vec) {\n debug!(\n \"Running zap script: {} with args {:?}\",\n script_path.display(),\n args.unwrap_or_default()\n );\n let mut cmd = Command::new(script_path);\n if let Some(script_args) = args {\n cmd.args(script_args);\n }\n cmd.stdout(Stdio::piped()).stderr(Stdio::piped());\n\n match cmd.output() {\n Ok(output) => {\n log_command_output(\n \"Zap script\",\n &script_path.display().to_string(),\n &output,\n errors,\n );\n }\n Err(e) => {\n let msg = format!(\n \"Failed to execute zap script '{}': {}\",\n script_path.display(),\n e\n );\n error!(\"{}\", msg);\n errors.push(msg);\n }\n }\n}\n\n/// Logs the output of a command and adds to error list if it failed.\nfn log_command_output(\n context: &str,\n command_str: &str,\n output: &std::process::Output,\n errors: &mut Vec,\n) {\n let stdout = String::from_utf8_lossy(&output.stdout);\n let stderr = String::from_utf8_lossy(&output.stderr);\n if !output.status.success() {\n error!(\n \"{} '{}' failed with status {}: {}\",\n context,\n command_str,\n output.status,\n stderr.trim()\n );\n if !stdout.trim().is_empty() {\n error!(\"{} stdout: {}\", context, stdout.trim());\n }\n errors.push(format!(\"{context} '{command_str}' failed\"));\n } else {\n debug!(\"{} '{}' executed successfully.\", context, command_str);\n if !stdout.trim().is_empty() {\n debug!(\"{} stdout: {}\", context, stdout.trim());\n }\n if !stderr.trim().is_empty() {\n debug!(\"{} stderr: {}\", context, stderr.trim());\n }\n }\n}\n\n// Helper function specifically for cleaning up the private store.\n// This was originally inside zap_cask_artifacts.\nfn cleanup_private_store(\n cask_token: &str,\n version: &str,\n app_name: Option<&str>, // The actual .app name, not the token\n config: &Config,\n) -> bool {\n debug!(\n \"Cleaning up private store for cask {} version {}\",\n cask_token, version\n );\n\n let private_version_dir = config.cask_store_version_path(cask_token, version);\n\n if let Some(app) = app_name {\n let app_path_in_private_store = private_version_dir.join(app);\n if app_path_in_private_store.exists()\n || app_path_in_private_store.symlink_metadata().is_ok()\n {\n debug!(\n \"Removing app from private store: {}\",\n app_path_in_private_store.display()\n );\n // Use the helper from install::cask::helpers, assuming it's correctly located and\n // public\n if !remove_path_robustly_from_install_helpers(&app_path_in_private_store, config, false)\n {\n // use_sudo=false for private store\n warn!(\n \"Failed to remove app from private store: {}\",\n app_path_in_private_store.display()\n );\n // Potentially return false or collect errors, depending on desired strictness\n }\n }\n }\n\n // After attempting to remove specific app, remove the version directory if it exists\n // This also handles cases where app_name was None.\n if private_version_dir.exists() {\n debug!(\n \"Removing private store version directory: {}\",\n private_version_dir.display()\n );\n match fs::remove_dir_all(&private_version_dir) {\n Ok(_) => debug!(\n \"Successfully removed private store version directory {}\",\n private_version_dir.display()\n ),\n Err(e) => {\n warn!(\n \"Failed to remove private store version directory {}: {}\",\n private_version_dir.display(),\n e\n );\n return false; // If the version dir removal fails, consider it a failure\n }\n }\n }\n\n // Clean up empty parent token directory.\n cleanup_empty_parent_dirs_in_private_store(\n &private_version_dir, // Start from the version dir (or its parent if it was just removed)\n &config.cask_store_dir(),\n );\n\n true\n}\n"], ["/sps/sps-common/src/model/cask.rs", "// ===== sps-common/src/model/cask.rs ===== // Corrected path\nuse std::collections::HashMap;\nuse std::fs;\n\nuse serde::{Deserialize, Serialize};\n\nuse crate::config::Config;\n\npub type Artifact = serde_json::Value;\n\n/// Represents the `url` field, which can be a simple string or a map with specs\n#[derive(Debug, Clone, Serialize, Deserialize)]\n#[serde(untagged)]\npub enum UrlField {\n Simple(String),\n WithSpec {\n url: String,\n #[serde(default)]\n verified: Option,\n #[serde(flatten)]\n other: HashMap,\n },\n}\n\n/// Represents the `sha256` field: hex, no_check, or per-architecture\n#[derive(Debug, Clone, Serialize, Deserialize)]\n#[serde(untagged)]\npub enum Sha256Field {\n Hex(String),\n #[serde(rename_all = \"snake_case\")]\n NoCheck {\n no_check: bool,\n },\n PerArch(HashMap),\n}\n\n/// Appcast metadata\n#[derive(Debug, Clone, Serialize, Deserialize)] // Ensure Serialize/Deserialize are here\npub struct Appcast {\n pub url: String,\n pub checkpoint: Option,\n}\n\n/// Represents conflicts with other casks or formulae\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub struct ConflictsWith {\n #[serde(default)]\n pub cask: Vec,\n #[serde(default)]\n pub formula: Vec,\n #[serde(flatten)]\n pub extra: HashMap,\n}\n\n/// Represents the specific architecture details found in some cask definitions\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub struct ArchSpec {\n #[serde(rename = \"type\")] // Map the JSON \"type\" field\n pub type_name: String, // e.g., \"arm\"\n pub bits: u32, // e.g., 64\n}\n\n/// Helper for architecture requirements: single string, list of strings, or list of spec objects\n#[derive(Debug, Clone, Serialize, Deserialize)]\n#[serde(untagged)]\npub enum ArchReq {\n One(String), // e.g., \"arm64\"\n Many(Vec), // e.g., [\"arm64\", \"x86_64\"]\n Specs(Vec),\n}\n\n/// Helper for macOS requirements: symbol, list, comparison, or map\n#[derive(Debug, Clone, Serialize, Deserialize)]\n#[serde(untagged)]\npub enum MacOSReq {\n Symbol(String), // \":big_sur\"\n Symbols(Vec), // [\":catalina\", \":big_sur\"]\n Comparison(String), // \">= :big_sur\"\n Map(HashMap>),\n}\n\n/// Helper to coerce string-or-list into Vec\n#[derive(Debug, Clone, Serialize, Deserialize)]\n#[serde(untagged)]\npub enum StringList {\n One(String),\n Many(Vec),\n}\n\nimpl From for Vec {\n fn from(item: StringList) -> Self {\n match item {\n StringList::One(s) => vec![s],\n StringList::Many(v) => v,\n }\n }\n}\n\n/// Represents `depends_on` block with multiple possible keys\n#[derive(Debug, Clone, Serialize, Deserialize, Default)]\npub struct DependsOn {\n #[serde(default)]\n pub cask: Vec,\n #[serde(default)]\n pub formula: Vec,\n #[serde(default)]\n pub arch: Option,\n #[serde(default)]\n pub macos: Option,\n #[serde(flatten)]\n pub extra: HashMap,\n}\n\n/// The main Cask model matching Homebrew JSON v2\n#[derive(Debug, Clone, Serialize, Deserialize, Default)]\npub struct Cask {\n pub token: String,\n\n #[serde(default)]\n pub name: Option>,\n pub version: Option,\n pub desc: Option,\n pub homepage: Option,\n\n #[serde(default)]\n pub artifacts: Option>,\n\n #[serde(default)]\n pub url: Option,\n #[serde(default)]\n pub url_specs: Option>,\n\n #[serde(default)]\n pub sha256: Option,\n\n pub appcast: Option,\n pub auto_updates: Option,\n\n #[serde(default)]\n pub depends_on: Option,\n\n #[serde(default)]\n pub conflicts_with: Option,\n\n pub caveats: Option,\n pub stage_only: Option,\n\n #[serde(default)]\n pub uninstall: Option>,\n\n #[serde(default)] // Only one default here\n pub zap: Option>,\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub struct CaskList {\n pub casks: Vec,\n}\n\n// --- ZAP STANZA SUPPORT ---\n\n/// Helper for zap: string or array of strings\n#[derive(Debug, Clone, Serialize, Deserialize)]\n#[serde(untagged)]\npub enum StringOrVec {\n String(String),\n Vec(Vec),\n}\nimpl StringOrVec {\n pub fn into_vec(self) -> Vec {\n match self {\n StringOrVec::String(s) => vec![s],\n StringOrVec::Vec(v) => v,\n }\n }\n}\n\n/// Zap action details (trash, delete, rmdir, pkgutil, launchctl, script, signal, etc)\n#[derive(Debug, Clone, Serialize, Deserialize)]\n#[serde(tag = \"action\", rename_all = \"snake_case\")]\npub enum ZapActionDetail {\n Trash(Vec),\n Delete(Vec),\n Rmdir(Vec),\n Pkgutil(StringOrVec),\n Launchctl(StringOrVec),\n Script {\n executable: String,\n args: Option>,\n },\n Signal(Vec),\n // Add more as needed\n}\n\n/// A zap stanza is a map of action -> detail\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub struct ZapStanza(pub std::collections::HashMap);\n\n// --- Cask Impl ---\n\nimpl Cask {\n /// Check if this cask is installed by looking for a manifest file\n /// in any versioned directory within the Caskroom.\n pub fn is_installed(&self, config: &Config) -> bool {\n let cask_dir = config.cask_room_token_path(&self.token); // e.g., /opt/sps/cask_room/firefox\n if !cask_dir.exists() || !cask_dir.is_dir() {\n return false;\n }\n\n // Iterate through entries (version dirs) inside the cask_dir\n match fs::read_dir(&cask_dir) {\n Ok(entries) => {\n // Clippy fix: Use flatten() to handle Result entries directly\n for entry in entries.flatten() {\n // <-- Use flatten() here\n let version_path = entry.path();\n // Check if it's a directory (representing a version)\n if version_path.is_dir() {\n // Check for the existence of the manifest file\n let manifest_path = version_path.join(\"CASK_INSTALL_MANIFEST.json\"); // <-- Correct filename\n if manifest_path.is_file() {\n // Check is_installed flag in manifest\n let mut include = true;\n if let Ok(manifest_str) = std::fs::read_to_string(&manifest_path) {\n if let Ok(manifest_json) =\n serde_json::from_str::(&manifest_str)\n {\n if let Some(is_installed) =\n manifest_json.get(\"is_installed\").and_then(|v| v.as_bool())\n {\n include = is_installed;\n }\n }\n }\n if include {\n // Found a manifest in at least one version directory, consider it\n // installed\n return true;\n }\n }\n }\n }\n // If loop completes without finding a manifest in any version dir\n false\n }\n Err(e) => {\n // Log error if reading the directory fails, but assume not installed\n tracing::warn!(\n \"Failed to read cask directory {} to check for installed versions: {}\",\n cask_dir.display(),\n e\n );\n false\n }\n }\n }\n\n /// Get the installed version of this cask by reading the directory names\n /// in the Caskroom. Returns the first version found (use cautiously if multiple\n /// versions could exist, though current install logic prevents this).\n pub fn installed_version(&self, config: &Config) -> Option {\n let cask_dir = config.cask_room_token_path(&self.token); //\n if !cask_dir.exists() {\n return None;\n }\n // Iterate through entries and return the first directory name found\n match fs::read_dir(&cask_dir) {\n Ok(entries) => {\n // Clippy fix: Use flatten()\n for entry in entries.flatten() {\n // <-- Use flatten() here\n let path = entry.path();\n // Check if it's a directory (representing a version)\n if path.is_dir() {\n if let Some(version_str) = path.file_name().and_then(|name| name.to_str()) {\n // Return the first version directory name found\n return Some(version_str.to_string());\n }\n }\n }\n // No version directories found\n None\n }\n Err(_) => None, // Error reading directory\n }\n }\n\n /// Get a friendly name for display purposes\n pub fn display_name(&self) -> String {\n self.name\n .as_ref()\n .and_then(|names| names.first().cloned())\n .unwrap_or_else(|| self.token.clone())\n }\n}\n"], ["/sps/sps-core/src/check/update.rs", "// sps-core/src/check/update.rs\n\nuse std::collections::HashMap;\nuse std::sync::Arc;\n\n// Imports from sps-common\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::formulary::Formulary; // Using the shared Formulary\nuse sps_common::model::version::Version as PkgVersion;\nuse sps_common::model::Cask; // Using the Cask and Formula from sps-common\n// Use the Cask and Formula structs from sps_common::model\n// Ensure InstallTargetIdentifier is correctly pathed if it's also in sps_common::model\nuse sps_common::model::InstallTargetIdentifier;\n// Imports from sps-net\nuse sps_net::api;\n\n// Imports from sps-core\nuse crate::check::installed::{InstalledPackageInfo, PackageType};\n\n#[derive(Debug, Clone)]\npub struct UpdateInfo {\n pub name: String,\n pub installed_version: String,\n pub available_version: String,\n pub pkg_type: PackageType,\n pub target_definition: InstallTargetIdentifier,\n}\n\n/// Ensures that the raw JSON data for formulas and casks exists in the main disk cache,\n/// fetching from the API if necessary.\nasync fn ensure_api_data_cached(cache: &Cache) -> Result<()> {\n let formula_check = cache.load_raw(\"formula.json\");\n let cask_check = cache.load_raw(\"cask.json\");\n\n // Determine if fetches are needed\n let mut fetch_formulas = false;\n if formula_check.is_err() {\n tracing::debug!(\"Local formula.json cache missing or unreadable. Scheduling fetch.\");\n fetch_formulas = true;\n }\n\n let mut fetch_casks = false;\n if cask_check.is_err() {\n tracing::debug!(\"Local cask.json cache missing or unreadable. Scheduling fetch.\");\n fetch_casks = true;\n }\n\n // Perform fetches concurrently if needed\n match (fetch_formulas, fetch_casks) {\n (true, true) => {\n tracing::debug!(\"Populating missing formula.json and cask.json from API...\");\n let (formula_res, cask_res) = tokio::join!(\n async {\n let data = api::fetch_all_formulas().await?;\n cache.store_raw(\"formula.json\", &data)?;\n Ok::<(), SpsError>(())\n },\n async {\n let data = api::fetch_all_casks().await?;\n cache.store_raw(\"cask.json\", &data)?;\n Ok::<(), SpsError>(())\n }\n );\n formula_res?;\n cask_res?;\n tracing::debug!(\"Formula.json and cask.json populated from API.\");\n }\n (true, false) => {\n tracing::debug!(\"Populating missing formula.json from API...\");\n let data = api::fetch_all_formulas().await?;\n cache.store_raw(\"formula.json\", &data)?;\n tracing::debug!(\"Formula.json populated from API.\");\n }\n (false, true) => {\n tracing::debug!(\"Populating missing cask.json from API...\");\n let data = api::fetch_all_casks().await?;\n cache.store_raw(\"cask.json\", &data)?;\n tracing::debug!(\"Cask.json populated from API.\");\n }\n (false, false) => {\n tracing::debug!(\"Local formula.json and cask.json caches are present.\");\n }\n }\n Ok(())\n}\n\npub async fn check_for_updates(\n installed_packages: &[InstalledPackageInfo],\n cache: &Cache,\n config: &Config,\n) -> Result> {\n // 1. Ensure the underlying JSON files in the main cache are populated.\n ensure_api_data_cached(cache)\n .await\n .map_err(|e| {\n tracing::error!(\n \"Failed to ensure API data is cached for update check: {}\",\n e\n );\n // Decide if this is a fatal error for update checking or if we can proceed with\n // potentially stale/missing data. For now, let's make it non-fatal but log\n // an error, as Formulary/cask parsing might still work with older cache.\n SpsError::Generic(format!(\n \"Failed to ensure API data in cache, update check might be unreliable: {e}\"\n ))\n })\n .ok(); // Continue even if this pre-fetch step fails, rely on Formulary/cask loading to handle actual\n // errors.\n\n // 2. Instantiate Formulary. It uses the `cache` (from sps-common) to load `formula.json`.\n let formulary = Formulary::new(config.clone());\n\n // 3. For Casks: Load the entire `cask.json` from cache and parse it robustly into Vec.\n // This uses the Cask definition from sps_common::model::cask.\n let casks_map: HashMap> = match cache.load_raw(\"cask.json\") {\n Ok(json_str) => {\n // Parse directly into Vec using the definition from sps-common::model::cask\n match serde_json::from_str::>(&json_str) {\n Ok(casks) => casks\n .into_iter()\n .map(|c| (c.token.clone(), Arc::new(c)))\n .collect(),\n Err(e) => {\n tracing::warn!(\n \"Failed to parse full cask.json string into Vec (from sps-common): {}. Cask update checks may be incomplete.\",\n e\n );\n HashMap::new()\n }\n }\n }\n Err(e) => {\n tracing::warn!(\n \"Failed to load cask.json string from cache: {}. Cask update checks will be based on no remote data.\", e\n );\n HashMap::new()\n }\n };\n\n tracing::debug!(\n \"[UpdateCheck] Starting update check for {} packages\",\n installed_packages.len()\n );\n let mut updates_available = Vec::new();\n\n for installed in installed_packages {\n tracing::debug!(\n \"[UpdateCheck] Checking package '{}' version '{}'\",\n installed.name,\n installed.version\n );\n match installed.pkg_type {\n PackageType::Formula => {\n match formulary.load_formula(&installed.name) {\n // Uses sps-common::formulary::Formulary\n Ok(latest_formula_obj) => {\n // Returns sps_common::model::formula::Formula\n let latest_formula_arc = Arc::new(latest_formula_obj);\n\n let latest_version_str = latest_formula_arc.version_str_full();\n tracing::debug!(\n \"[UpdateCheck] Formula '{}': installed='{}', latest='{}'\",\n installed.name,\n installed.version,\n latest_version_str\n );\n\n let installed_v_res = PkgVersion::parse(&installed.version);\n let latest_v_res = PkgVersion::parse(&latest_version_str);\n let installed_revision = installed\n .version\n .split('_')\n .nth(1)\n .and_then(|s| s.parse::().ok())\n .unwrap_or(0);\n\n let needs_update = match (installed_v_res, latest_v_res) {\n (Ok(iv), Ok(lv)) => {\n let version_newer = lv > iv;\n let revision_newer =\n lv == iv && latest_formula_arc.revision > installed_revision;\n tracing::debug!(\"[UpdateCheck] Formula '{}': version_newer={}, revision_newer={} (installed_rev={}, latest_rev={})\", \n installed.name, version_newer, revision_newer, installed_revision, latest_formula_arc.revision);\n version_newer || revision_newer\n }\n _ => {\n let different = installed.version != latest_version_str;\n tracing::debug!(\"[UpdateCheck] Formula '{}': fallback string comparison, different={}\", \n installed.name, different);\n different\n }\n };\n\n tracing::debug!(\n \"[UpdateCheck] Formula '{}': needs_update={}\",\n installed.name,\n needs_update\n );\n if needs_update {\n updates_available.push(UpdateInfo {\n name: installed.name.clone(),\n installed_version: installed.version.clone(),\n available_version: latest_version_str,\n pkg_type: PackageType::Formula,\n target_definition: InstallTargetIdentifier::Formula(\n // From sps-common\n latest_formula_arc.clone(),\n ),\n });\n }\n }\n Err(_e) => {\n tracing::debug!(\n \"Installed formula '{}' not found via Formulary. It might have been removed from the remote. Source error: {}\",\n installed.name, _e\n );\n }\n }\n }\n PackageType::Cask => {\n if let Some(latest_cask_arc) = casks_map.get(&installed.name) {\n // latest_cask_arc is Arc\n if let Some(available_version) = latest_cask_arc.version.as_ref() {\n if &installed.version != available_version {\n updates_available.push(UpdateInfo {\n name: installed.name.clone(),\n installed_version: installed.version.clone(),\n available_version: available_version.clone(),\n pkg_type: PackageType::Cask,\n target_definition: InstallTargetIdentifier::Cask(\n // From sps-common\n latest_cask_arc.clone(),\n ),\n });\n }\n } else {\n tracing::warn!(\n \"Latest cask definition for '{}' from casks_map has no version string.\",\n installed.name\n );\n }\n } else {\n tracing::warn!(\n \"Installed cask '{}' not found in the fully parsed casks_map.\",\n installed.name\n );\n }\n }\n }\n }\n\n tracing::debug!(\n \"[UpdateCheck] Update check complete: {} updates available out of {} packages checked\",\n updates_available.len(),\n installed_packages.len()\n );\n tracing::debug!(\n \"[UpdateCheck] Updates available for: {:?}\",\n updates_available\n .iter()\n .map(|u| &u.name)\n .collect::>()\n );\n\n Ok(updates_available)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/app.rs", "// In sps-core/src/build/cask/app.rs\n\nuse std::fs;\nuse std::path::{Path, PathBuf};\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::{debug, error, warn};\n\n#[cfg(target_os = \"macos\")]\n/// Finds the primary .app bundle in a directory. Returns an error if none or ambiguous.\n/// If multiple .app bundles are found, returns the first and logs a warning.\npub fn find_primary_app_bundle_in_dir(dir: &Path) -> Result {\n if !dir.is_dir() {\n return Err(SpsError::NotFound(format!(\n \"Directory {} not found for app bundle scan.\",\n dir.display()\n )));\n }\n let mut app_bundles = Vec::new();\n for entry_res in fs::read_dir(dir)? {\n let entry = entry_res?;\n let path = entry.path();\n if path.is_dir() && path.extension().is_some_and(|ext| ext == \"app\") {\n app_bundles.push(path);\n }\n }\n if app_bundles.is_empty() {\n Err(SpsError::NotFound(format!(\n \"No .app bundle found in {}\",\n dir.display()\n )))\n } else if app_bundles.len() == 1 {\n Ok(app_bundles.remove(0))\n } else {\n // Heuristic: return the largest .app bundle if multiple are found, or one matching a common\n // pattern. For now, error if multiple are present to force explicit handling in\n // Cask definitions if needed.\n warn!(\"Multiple .app bundles found in {}: {:?}. Returning the first one, but this might be ambiguous.\", dir.display(), app_bundles);\n Ok(app_bundles.remove(0)) // Or error out\n }\n}\n\nuse sps_common::pipeline::JobAction;\n\npub fn install_app_from_staged(\n cask: &Cask,\n staged_app_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n job_action: &JobAction,\n) -> Result> {\n if !staged_app_path.exists() || !staged_app_path.is_dir() {\n return Err(SpsError::NotFound(format!(\n \"Staged app bundle for {} not found or is not a directory: {}\",\n cask.token,\n staged_app_path.display()\n )));\n }\n\n let app_name = staged_app_path\n .file_name()\n .ok_or_else(|| {\n SpsError::Generic(format!(\n \"Invalid staged app path (no filename): {}\",\n staged_app_path.display()\n ))\n })?\n .to_string_lossy();\n\n let new_version_str = cask.version.clone().unwrap_or_else(|| \"latest\".to_string());\n let final_private_store_app_path: PathBuf;\n\n // Determine if we are upgrading and if the old private store app path exists\n let mut did_upgrade = false;\n\n if let JobAction::Upgrade {\n from_version,\n old_install_path,\n ..\n } = job_action\n {\n debug!(\n \"[{}] Processing app install as UPGRADE from version {}\",\n cask.token, from_version\n );\n\n // Try to get primary_app_file_name from the old manifest to build the old private store\n // path\n let old_manifest_path = old_install_path.join(\"CASK_INSTALL_MANIFEST.json\");\n let old_primary_app_name = if old_manifest_path.is_file() {\n fs::read_to_string(&old_manifest_path)\n .ok()\n .and_then(|s| {\n serde_json::from_str::(&s).ok()\n })\n .and_then(|m| m.primary_app_file_name)\n } else {\n // Fallback if old manifest is missing, use current app_name (less reliable if app name\n // changed)\n warn!(\"[{}] Old manifest not found at {} during upgrade. Using current app name '{}' for private store path derivation.\", cask.token, old_manifest_path.display(), app_name);\n Some(app_name.to_string())\n };\n\n if let Some(name_for_old_path) = old_primary_app_name {\n let old_private_store_app_dir_path =\n config.cask_store_version_path(&cask.token, from_version);\n let old_private_store_app_bundle_path =\n old_private_store_app_dir_path.join(&name_for_old_path);\n if old_private_store_app_bundle_path.exists()\n && old_private_store_app_bundle_path.is_dir()\n {\n debug!(\"[{}] UPGRADE: Old private store app bundle found at {}. Using Homebrew-style overwrite strategy.\", cask.token, old_private_store_app_bundle_path.display());\n\n // ========================================================================\n // CRITICAL: Homebrew-Style App Bundle Replacement Strategy\n // ========================================================================\n // WHY THIS APPROACH:\n // 1. Preserves extended attributes (quarantine, code signing, etc.)\n // 2. Maintains app bundle identity → prevents Gatekeeper reset\n // 3. Avoids breaking symlinks and file system references\n // 4. Ensures user data in ~/Library remains accessible to the app\n //\n // DO NOT CHANGE TO fs::rename() or similar - it breaks Gatekeeper!\n // ========================================================================\n\n // Step 1: Remove the old app bundle from private store\n // (This is safe because we're about to replace it with the new version)\n let rm_status = Command::new(\"rm\")\n .arg(\"-rf\")\n .arg(&old_private_store_app_bundle_path)\n .status()\n .map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n\n if !rm_status.success() {\n return Err(SpsError::InstallError(format!(\n \"Failed to remove old app bundle during upgrade: {}\",\n old_private_store_app_bundle_path.display()\n )));\n }\n\n // Step 2: Copy the new app bundle with ALL attributes preserved\n // The -pR flags are critical:\n // -p: Preserve file attributes, ownership, timestamps\n // -R: Recursive copy for directories\n // This ensures Gatekeeper approval and code signing are maintained\n let cp_status = Command::new(\"cp\")\n .arg(\"-pR\") // CRITICAL: Preserve all attributes, links, and metadata\n .arg(staged_app_path)\n .arg(&old_private_store_app_bundle_path)\n .status()\n .map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n\n if !cp_status.success() {\n return Err(SpsError::InstallError(format!(\n \"Failed to copy new app bundle during upgrade: {} -> {}\",\n staged_app_path.display(),\n old_private_store_app_bundle_path.display()\n )));\n }\n\n debug!(\n \"[{}] UPGRADE: Successfully overwrote old app bundle with new version using cp -pR\",\n cask.token\n );\n\n // Now, rename the parent version directory (e.g., .../1.0 -> .../1.1)\n let new_private_store_version_dir =\n config.cask_store_version_path(&cask.token, &new_version_str);\n if old_private_store_app_dir_path != new_private_store_version_dir {\n debug!(\n \"[{}] Renaming private store version dir from {} to {}\",\n cask.token,\n old_private_store_app_dir_path.display(),\n new_private_store_version_dir.display()\n );\n fs::rename(\n &old_private_store_app_dir_path,\n &new_private_store_version_dir,\n )\n .map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n }\n final_private_store_app_path =\n new_private_store_version_dir.join(app_name.as_ref());\n did_upgrade = true;\n } else {\n warn!(\"[{}] UPGRADE: Old private store app path {} not found or not a dir. Proceeding with fresh private store placement for new version.\", cask.token, old_private_store_app_bundle_path.display());\n // Fallback to fresh placement\n final_private_store_app_path =\n config.cask_store_app_path(&cask.token, &new_version_str, app_name.as_ref());\n }\n } else {\n warn!(\"[{}] UPGRADE: Could not determine old app bundle name. Proceeding with fresh private store placement for new version.\", cask.token);\n final_private_store_app_path =\n config.cask_store_app_path(&cask.token, &new_version_str, app_name.as_ref());\n }\n } else {\n // Not an upgrade\n final_private_store_app_path =\n config.cask_store_app_path(&cask.token, &new_version_str, app_name.as_ref());\n }\n\n let final_app_destination_in_applications = config.applications_dir().join(app_name.as_ref());\n let caskroom_symlink_to_final_app = cask_version_install_path.join(app_name.as_ref());\n\n debug!(\n \"Installing app '{}': Staged -> Private Store -> /Applications -> Caskroom Symlink\",\n app_name\n );\n debug!(\" Staged app source: {}\", staged_app_path.display());\n debug!(\n \" Private store copy target: {}\",\n final_private_store_app_path.display()\n );\n debug!(\n \" Final /Applications target: {}\",\n final_app_destination_in_applications.display()\n );\n debug!(\n \" Caskroom symlink target: {}\",\n caskroom_symlink_to_final_app.display()\n );\n\n // 1. Ensure Caskroom version path exists\n if !cask_version_install_path.exists() {\n fs::create_dir_all(cask_version_install_path).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\n \"Failed to create cask version dir {}: {}\",\n cask_version_install_path.display(),\n e\n ),\n )))\n })?;\n }\n\n // 2. Create private store directory if it doesn't exist\n if let Some(parent) = final_private_store_app_path.parent() {\n if !parent.exists() {\n debug!(\"Creating private store directory: {}\", parent.display());\n fs::create_dir_all(parent).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\n \"Failed to create private store dir {}: {}\",\n parent.display(),\n e\n ),\n )))\n })?;\n }\n }\n\n if !did_upgrade {\n // 3. Clean existing app in private store (if any from a failed prior attempt)\n if final_private_store_app_path.exists()\n || final_private_store_app_path.symlink_metadata().is_ok()\n {\n debug!(\n \"Removing existing item at private store path: {}\",\n final_private_store_app_path.display()\n );\n let _ = remove_path_robustly(&final_private_store_app_path, config, false);\n }\n\n // 4. Move from temporary stage to private store\n debug!(\n \"Moving staged app {} to private store path {}\",\n staged_app_path.display(),\n final_private_store_app_path.display()\n );\n if let Err(e) = fs::rename(staged_app_path, &final_private_store_app_path) {\n error!(\n \"Failed to move staged app to private store: {}. Source: {}, Dest: {}\",\n e,\n staged_app_path.display(),\n final_private_store_app_path.display()\n );\n return Err(SpsError::Io(std::sync::Arc::new(e)));\n }\n }\n\n // 5. Set/Verify Quarantine on private store copy (only if not already present)\n #[cfg(target_os = \"macos\")]\n {\n debug!(\n \"Setting/verifying quarantine on private store copy: {}\",\n final_private_store_app_path.display()\n );\n if let Err(e) = crate::utils::xattr::ensure_quarantine_attribute(\n &final_private_store_app_path,\n &cask.token,\n ) {\n error!(\n \"Failed to set quarantine on private store copy {}: {}. This is critical.\",\n final_private_store_app_path.display(),\n e\n );\n return Err(SpsError::InstallError(format!(\n \"Failed to set quarantine on private store copy {}: {}\",\n final_private_store_app_path.display(),\n e\n )));\n }\n }\n\n // ============================================================================\n // STEP 6: Handle /Applications Destination - THE MOST CRITICAL PART\n // ============================================================================\n // This is where we apply Homebrew's breakthrough strategy that preserves\n // user data and prevents Gatekeeper resets during upgrades.\n //\n // UPGRADE vs FRESH INSTALL Strategy:\n // - UPGRADE: Overwrite app in /Applications directly (preserves identity)\n // - FRESH INSTALL: Use symlink approach (normal installation)\n //\n // WHY THIS SPLIT MATTERS:\n // During upgrades, the app in /Applications already has:\n // 1. Gatekeeper approval and quarantine exemptions\n // 2. Extended attributes that macOS recognizes\n // 3. User trust and security context\n // 4. Associated user data in ~/Library that the app can access\n //\n // By overwriting IN PLACE with cp -pR, we maintain all of this state.\n // ============================================================================\n\n if let JobAction::Upgrade { .. } = job_action {\n // =======================================================================\n // UPGRADE PATH: Direct Overwrite Strategy (Homebrew's Approach)\n // =======================================================================\n // This is the breakthrough that prevents Gatekeeper resets and data loss.\n // We overwrite the existing app directly rather than removing and\n // re-symlinking, which would break the app's established identity.\n // =======================================================================\n\n if final_app_destination_in_applications.exists() {\n debug!(\n \"UPGRADE: Overwriting existing app at /Applications using Homebrew strategy: {}\",\n final_app_destination_in_applications.display()\n );\n\n // Step 1: Remove the old app in /Applications\n // We need sudo because /Applications requires elevated permissions\n let rm_status = Command::new(\"sudo\")\n .arg(\"rm\")\n .arg(\"-rf\")\n .arg(&final_app_destination_in_applications)\n .status()\n .map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n\n if !rm_status.success() {\n return Err(SpsError::InstallError(format!(\n \"Failed to remove existing app during upgrade: {}\",\n final_app_destination_in_applications.display()\n )));\n }\n\n // Copy the new app directly to /Applications, preserving all attributes\n let cp_status = Command::new(\"sudo\")\n .arg(\"cp\")\n .arg(\"-pR\") // Preserve all attributes, links, and metadata\n .arg(&final_private_store_app_path)\n .arg(&final_app_destination_in_applications)\n .status()\n .map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n\n if !cp_status.success() {\n return Err(SpsError::InstallError(format!(\n \"Failed to copy new app to /Applications during upgrade: {}\",\n final_app_destination_in_applications.display()\n )));\n }\n\n debug!(\n \"UPGRADE: Successfully overwrote app in /Applications, preserving identity: {}\",\n final_app_destination_in_applications.display()\n );\n } else {\n // App doesn't exist in /Applications during upgrade - fall back to symlink approach\n debug!(\n \"UPGRADE: App not found in /Applications, creating fresh symlink: {}\",\n final_app_destination_in_applications.display()\n );\n if let Err(e) = std::os::unix::fs::symlink(\n &final_private_store_app_path,\n &final_app_destination_in_applications,\n ) {\n error!(\n \"Failed to symlink app from private store to /Applications: {} -> {}: {}\",\n final_private_store_app_path.display(),\n final_app_destination_in_applications.display(),\n e\n );\n return Err(SpsError::InstallError(format!(\n \"Failed to symlink app from private store to {}: {}\",\n final_app_destination_in_applications.display(),\n e\n )));\n }\n }\n } else {\n // Fresh install: Clean existing app destination and create symlink\n if final_app_destination_in_applications.exists()\n || final_app_destination_in_applications\n .symlink_metadata()\n .is_ok()\n {\n debug!(\n \"Removing existing app at /Applications: {}\",\n final_app_destination_in_applications.display()\n );\n if !remove_path_robustly(&final_app_destination_in_applications, config, true) {\n return Err(SpsError::InstallError(format!(\n \"Failed to remove existing app at {}\",\n final_app_destination_in_applications.display()\n )));\n }\n }\n\n // 7. Symlink from /Applications to private store app bundle\n debug!(\n \"INFO: About to symlink app from private store {} to /Applications {}\",\n final_private_store_app_path.display(),\n final_app_destination_in_applications.display()\n );\n if let Err(e) = std::os::unix::fs::symlink(\n &final_private_store_app_path,\n &final_app_destination_in_applications,\n ) {\n error!(\n \"Failed to symlink app from private store to /Applications: {} -> {}: {}\",\n final_private_store_app_path.display(),\n final_app_destination_in_applications.display(),\n e\n );\n return Err(SpsError::InstallError(format!(\n \"Failed to symlink app from private store to {}: {}\",\n final_app_destination_in_applications.display(),\n e\n )));\n }\n }\n\n // Remove quarantine attributes from the app in /Applications (whether copied or symlinked)\n #[cfg(target_os = \"macos\")]\n {\n use xattr;\n let _ = xattr::remove(\n &final_app_destination_in_applications,\n \"com.apple.quarantine\",\n );\n let _ = xattr::remove(\n &final_app_destination_in_applications,\n \"com.apple.provenance\",\n );\n let _ = xattr::remove(&final_app_destination_in_applications, \"com.apple.macl\");\n }\n\n match job_action {\n JobAction::Upgrade { .. } => {\n debug!(\n \"INFO: Successfully updated app in /Applications during upgrade: {}\",\n final_app_destination_in_applications.display()\n );\n }\n _ => {\n debug!(\n \"INFO: Successfully symlinked app from private store {} to /Applications {}\",\n final_private_store_app_path.display(),\n final_app_destination_in_applications.display()\n );\n }\n }\n\n // 7. No quarantine set on the symlink in /Applications; attribute remains on private store\n // copy.\n\n // 8. Create Caskroom Symlink TO the app in /Applications\n let actual_caskroom_symlink_path = cask_version_install_path.join(app_name.as_ref());\n debug!(\n \"Creating Caskroom symlink {} -> {}\",\n actual_caskroom_symlink_path.display(),\n final_app_destination_in_applications.display()\n );\n\n if actual_caskroom_symlink_path.symlink_metadata().is_ok() {\n if let Err(e) = fs::remove_file(&actual_caskroom_symlink_path) {\n warn!(\n \"Failed to remove existing item at Caskroom symlink path {}: {}. Proceeding.\",\n actual_caskroom_symlink_path.display(),\n e\n );\n }\n }\n\n #[cfg(unix)]\n {\n if let Err(e) = std::os::unix::fs::symlink(\n &final_app_destination_in_applications,\n &actual_caskroom_symlink_path,\n ) {\n error!(\n \"Failed to create Caskroom symlink {} -> {}: {}\",\n actual_caskroom_symlink_path.display(),\n final_app_destination_in_applications.display(),\n e\n );\n let _ = remove_path_robustly(&final_app_destination_in_applications, config, true);\n return Err(SpsError::Io(std::sync::Arc::new(e)));\n }\n }\n\n let mut created_artifacts = vec![InstalledArtifact::AppBundle {\n path: final_app_destination_in_applications.clone(),\n }];\n created_artifacts.push(InstalledArtifact::CaskroomLink {\n link_path: actual_caskroom_symlink_path,\n target_path: final_app_destination_in_applications.clone(),\n });\n\n debug!(\n \"Successfully installed app artifact: {} (Cask: {})\",\n app_name, cask.token\n );\n\n // Write CASK_INSTALL_MANIFEST.json to ensure package is always detected as installed\n if let Err(e) = crate::install::cask::write_cask_manifest(\n cask,\n cask_version_install_path,\n created_artifacts.clone(),\n ) {\n error!(\n \"Failed to write CASK_INSTALL_MANIFEST.json for {}: {}\",\n cask.token, e\n );\n return Err(SpsError::InstallError(format!(\n \"Failed to write CASK_INSTALL_MANIFEST.json for {}: {}\",\n cask.token, e\n )));\n }\n\n Ok(created_artifacts)\n}\n\n/// Helper function for robust path removal (internal to app.rs or moved to a common util)\nfn remove_path_robustly(path: &Path, _config: &Config, use_sudo_if_needed: bool) -> bool {\n if !path.exists() && path.symlink_metadata().is_err() {\n debug!(\"Path {} not found for removal.\", path.display());\n return true;\n }\n let is_dir = path.is_dir()\n && !path\n .symlink_metadata()\n .is_ok_and(|m| m.file_type().is_symlink());\n let removal_op = || -> std::io::Result<()> {\n if is_dir {\n fs::remove_dir_all(path)\n } else {\n fs::remove_file(path)\n }\n };\n\n if let Err(e) = removal_op() {\n if e.kind() == std::io::ErrorKind::NotFound {\n return true;\n }\n if use_sudo_if_needed && e.kind() == std::io::ErrorKind::PermissionDenied {\n warn!(\n \"Direct removal of {} failed (Permission Denied). Trying with sudo rm -rf.\",\n path.display()\n );\n let output = Command::new(\"sudo\").arg(\"rm\").arg(\"-rf\").arg(path).output();\n match output {\n Ok(out) if out.status.success() => {\n debug!(\"Successfully removed {} with sudo.\", path.display());\n return true;\n }\n Ok(out) => {\n error!(\n \"`sudo rm -rf {}` failed ({}): {}\",\n path.display(),\n out.status,\n String::from_utf8_lossy(&out.stderr).trim()\n );\n return false;\n }\n Err(sudo_e) => {\n error!(\n \"Error executing `sudo rm -rf` for {}: {}\",\n path.display(),\n sudo_e\n );\n return false;\n }\n }\n } else {\n error!(\"Failed to remove {}: {}\", path.display(), e);\n return false;\n }\n }\n debug!(\"Successfully removed {}.\", path.display());\n true\n}\n"], ["/sps/sps/src/cli/uninstall.rs", "use std::collections::{HashMap, HashSet};\nuse std::sync::Arc;\n\nuse clap::Args;\nuse colored::Colorize;\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::cask::Cask;\nuse sps_common::Cache;\nuse sps_core::check::{installed, PackageType};\nuse sps_core::{uninstall as core_uninstall, UninstallOptions};\nuse sps_net::api;\nuse tracing::{debug, error, warn};\nuse {serde_json, walkdir};\n\n#[derive(Args, Debug)]\npub struct Uninstall {\n /// The names of the formulas or casks to uninstall\n #[arg(required = true)] // Ensure at least one name is given\n pub names: Vec,\n /// Perform a deep clean for casks, removing associated user data, caches,\n /// and configuration files. Use with caution, data will be lost! Ignored for formulas.\n #[arg(\n long,\n help = \"Perform a deep clean for casks, removing associated user data, caches, and configuration files. Use with caution!\"\n )]\n pub zap: bool,\n}\n\nimpl Uninstall {\n pub async fn run(&self, config: &Config, cache: Arc) -> Result<()> {\n let names = &self.names;\n let mut errors: Vec<(String, SpsError)> = Vec::new();\n\n for name in names {\n // Basic name validation to prevent path traversal\n if name.contains('/') || name.contains(\"..\") {\n let msg = format!(\"Invalid package name '{name}' contains disallowed characters\");\n error!(\"✖ {msg}\");\n errors.push((name.to_string(), SpsError::Generic(msg)));\n continue;\n }\n\n println!(\"Uninstalling {name}...\");\n\n match installed::get_installed_package(name, config).await {\n Ok(Some(installed_info)) => {\n let (file_count, size_bytes) =\n count_files_and_size(&installed_info.path).unwrap_or((0, 0));\n let uninstall_opts = UninstallOptions { skip_zap: false };\n debug!(\n \"Attempting uninstall for {} ({:?})\",\n name, installed_info.pkg_type\n );\n let uninstall_result = match installed_info.pkg_type {\n PackageType::Formula => {\n if self.zap {\n warn!(\"--zap flag is ignored for formulas like '{}'.\", name);\n }\n core_uninstall::uninstall_formula_artifacts(\n &installed_info,\n config,\n &uninstall_opts,\n )\n }\n PackageType::Cask => {\n core_uninstall::uninstall_cask_artifacts(&installed_info, config)\n }\n };\n\n if let Err(e) = uninstall_result {\n error!(\"✖ Failed to uninstall '{}': {}\", name.cyan(), e);\n errors.push((name.to_string(), e));\n // Continue to zap anyway for casks, as per plan\n } else {\n println!(\n \"✓ Uninstalled {:?} {} ({} files, {})\",\n installed_info.pkg_type,\n name.green(),\n file_count,\n format_size(size_bytes)\n );\n }\n\n // --- Zap Uninstall (Conditional) ---\n if self.zap && installed_info.pkg_type == PackageType::Cask {\n println!(\"Zapping {name}...\");\n debug!(\n \"--zap specified for cask '{}', attempting deep clean.\",\n name\n );\n\n // Fetch the Cask definition (needed for the zap stanza)\n let cask_def_result: Result = async {\n match api::get_cask(name).await {\n Ok(cask) => Ok(cask),\n Err(e) => {\n warn!(\"Failed API fetch for zap definition for '{}' ({}), trying cache...\", name, e);\n match cache.load_raw(\"cask.json\") {\n Ok(raw_json) => {\n let casks: Vec = serde_json::from_str(&raw_json)\n .map_err(|cache_e| SpsError::Cache(format!(\"Failed parse cached cask.json: {cache_e}\")))?;\n casks.into_iter()\n .find(|c| c.token == *name)\n .ok_or_else(|| SpsError::NotFound(format!(\"Cask '{name}' def not in cache either\")))\n }\n Err(cache_e) => Err(SpsError::Cache(format!(\"Failed load cask cache for zap: {cache_e}\"))),\n }\n }\n }\n }.await;\n\n match cask_def_result {\n Ok(cask_def) => {\n match core_uninstall::zap_cask_artifacts(\n &installed_info,\n &cask_def,\n config,\n )\n .await\n {\n Ok(_) => {\n println!(\"✓ Zap complete for {}\", name.green());\n }\n Err(zap_err) => {\n error!(\"✖ Zap failed for '{}': {}\", name.cyan(), zap_err);\n errors.push((format!(\"{name} (zap)\"), zap_err));\n }\n }\n }\n Err(e) => {\n error!(\n \"✖ Could not get Cask definition for zap '{}': {}\",\n name.cyan(),\n e\n );\n errors.push((format!(\"{name} (zap definition)\"), e));\n }\n }\n }\n }\n Ok(None) => {\n let msg = format!(\"Package '{name}' is not installed.\");\n error!(\"✖ {msg}\");\n errors.push((name.to_string(), SpsError::NotFound(msg)));\n }\n Err(e) => {\n let msg = format!(\"Failed check install status for '{name}': {e}\");\n error!(\"✖ {msg}\");\n errors.push((name.clone(), SpsError::Generic(msg)));\n }\n }\n }\n\n if errors.is_empty() {\n Ok(())\n } else {\n eprintln!(\"\\n{}:\", \"Finished uninstalling with errors\".yellow());\n let mut errors_by_pkg: HashMap> = HashMap::new();\n for (pkg_name, error) in errors {\n errors_by_pkg\n .entry(pkg_name)\n .or_default()\n .push(error.to_string());\n }\n for (pkg_name, error_list) in errors_by_pkg {\n eprintln!(\"Package '{}':\", pkg_name.cyan());\n let unique_errors: HashSet<_> = error_list.into_iter().collect();\n for error_str in unique_errors {\n eprintln!(\"- {}\", error_str.red());\n }\n }\n Err(SpsError::Generic(\n \"Uninstall failed for one or more packages.\".to_string(),\n ))\n }\n }\n}\n\n// --- Unchanged Helper Functions ---\nfn count_files_and_size(path: &std::path::Path) -> Result<(usize, u64)> {\n let mut file_count = 0;\n let mut total_size = 0;\n for entry in walkdir::WalkDir::new(path) {\n match entry {\n Ok(entry_data) => {\n if entry_data.file_type().is_file() || entry_data.file_type().is_symlink() {\n match entry_data.metadata() {\n Ok(metadata) => {\n file_count += 1;\n if entry_data.file_type().is_file() {\n total_size += metadata.len();\n }\n }\n Err(e) => {\n tracing::warn!(\n \"Could not get metadata for {}: {}\",\n entry_data.path().display(),\n e\n );\n }\n }\n }\n }\n Err(e) => {\n tracing::warn!(\"Error traversing directory {}: {}\", path.display(), e);\n }\n }\n }\n Ok((file_count, total_size))\n}\n\nfn format_size(size: u64) -> String {\n const KB: u64 = 1024;\n const MB: u64 = KB * 1024;\n const GB: u64 = MB * 1024;\n if size >= GB {\n format!(\"{:.1}GB\", size as f64 / GB as f64)\n } else if size >= MB {\n format!(\"{:.1}MB\", size as f64 / MB as f64)\n } else if size >= KB {\n format!(\"{:.1}KB\", size as f64 / KB as f64)\n } else {\n format!(\"{size}B\")\n }\n}\n"], ["/sps/sps-core/src/upgrade/source.rs", "// sps-core/src/upgrade/source.rs\n\nuse std::path::{Path, PathBuf};\n\nuse sps_common::config::Config;\nuse sps_common::error::{Result as SpsResult, SpsError};\nuse sps_common::model::formula::Formula;\nuse tracing::{debug, error};\n\nuse crate::check::installed::InstalledPackageInfo;\nuse crate::{build, uninstall};\n\n/// Upgrades a formula that was/will be installed from source.\n///\n/// This involves:\n/// 1. Uninstalling the old version of the formula.\n/// 2. Building and installing the new version from source.\n/// 3. Linking the new version.\npub async fn upgrade_source_formula(\n formula: &Formula,\n new_source_download_path: &Path,\n old_install_info: &InstalledPackageInfo,\n config: &Config,\n all_installed_dependency_paths: &[PathBuf], // For build environment\n) -> SpsResult {\n debug!(\n \"Upgrading source-built formula {} from {} to {}\",\n formula.name(),\n old_install_info.version,\n formula.version_str_full()\n );\n\n // 1. Uninstall the old version\n debug!(\n \"Uninstalling old source-built version: {} at {}\",\n old_install_info.version,\n old_install_info.path.display()\n );\n let uninstall_opts = uninstall::UninstallOptions { skip_zap: true };\n uninstall::formula::uninstall_formula_artifacts(old_install_info, config, &uninstall_opts)\n .map_err(|e| {\n error!(\n \"Failed to uninstall old version {} of formula {}: {}\",\n old_install_info.version,\n formula.name(),\n e\n );\n SpsError::InstallError(format!(\n \"Failed to uninstall old version during source upgrade of {}: {e}\",\n formula.name()\n ))\n })?;\n debug!(\n \"Successfully uninstalled old source-built version of {}\",\n formula.name()\n );\n\n // 2. Build and install the new version from source\n debug!(\n \"Building new version of {} from source path {}\",\n formula.name(),\n new_source_download_path.display()\n );\n let installed_keg_path = build::compile::build_from_source(\n new_source_download_path,\n formula,\n config,\n all_installed_dependency_paths,\n )\n .await\n .map_err(|e| {\n error!(\n \"Failed to build new version of formula {} from source: {}\",\n formula.name(),\n e\n );\n SpsError::InstallError(format!(\n \"Failed to build new version from source during upgrade of {}: {e}\",\n formula.name()\n ))\n })?;\n debug!(\n \"Successfully built and installed new version of {} to {}\",\n formula.name(),\n installed_keg_path.display()\n );\n\n // 3. Linking is handled by the worker after this function returns the path.\n\n Ok(installed_keg_path)\n}\n"], ["/sps/sps/src/cli/init.rs", "// sps/src/cli/init.rs\nuse std::fs::{self, File, OpenOptions};\nuse std::io::{BufRead, BufReader, Write};\nuse std::path::{Path, PathBuf};\nuse std::process::Command as StdCommand;\nuse std::sync::Arc;\n\nuse clap::Args;\nuse colored::Colorize;\nuse sps_common::config::Config; // Assuming Config is correctly in sps_common\nuse sps_common::error::{Result as SpsResult, SpsError};\nuse tempfile;\nuse tracing::{debug, error, warn};\n\n#[derive(Args, Debug)]\npub struct InitArgs {\n /// Force initialization even if /opt/sps appears to be an sps root already.\n #[arg(long)]\n pub force: bool,\n}\n\nimpl InitArgs {\n pub async fn run(&self, config: &Config) -> SpsResult<()> {\n debug!(\n \"Initializing sps environment at {}\",\n config.sps_root().display()\n );\n\n let sps_root = config.sps_root();\n let marker_path = config.sps_root_marker_path();\n\n // 1. Initial Checks (as current user) - (No change from your existing logic)\n if sps_root.exists() {\n let is_empty = match fs::read_dir(sps_root) {\n Ok(mut entries) => entries.next().is_none(),\n Err(_) => false, // If we can't read it, assume not empty or not accessible\n };\n\n if marker_path.exists() && !self.force {\n debug!(\n \"{} already exists. sps appears to be initialized. Use --force to re-initialize.\",\n marker_path.display()\n );\n return Ok(());\n }\n if !self.force && !is_empty && !marker_path.exists() {\n warn!(\n \"Directory {} exists but does not appear to be an sps root (missing marker {}).\",\n sps_root.display(),\n marker_path.file_name().unwrap_or_default().to_string_lossy()\n );\n warn!(\n \"Run with --force to initialize anyway (this might overwrite existing data or change permissions).\"\n );\n return Err(SpsError::Config(format!(\n \"{} exists but is not a recognized sps root. Aborting.\",\n sps_root.display()\n )));\n }\n if self.force {\n debug!(\n \"--force specified. Proceeding with initialization in {}.\",\n sps_root.display()\n );\n } else if is_empty {\n debug!(\n \"Directory {} exists but is empty. Proceeding with initialization.\",\n sps_root.display()\n );\n }\n }\n\n // 2. Privileged Operations\n let current_user_name = std::env::var(\"USER\")\n .or_else(|_| std::env::var(\"LOGNAME\"))\n .map_err(|_| {\n SpsError::Generic(\n \"Failed to get current username from USER or LOGNAME environment variables.\"\n .to_string(),\n )\n })?;\n\n let target_group_name = if cfg!(target_os = \"macos\") {\n \"admin\" // Standard admin group on macOS\n } else {\n // For Linux, 'staff' might not exist or be appropriate.\n // Often, the user's primary group is used, or a dedicated 'brew' group.\n // For simplicity, let's try to use the current user's name as the group too,\n // which works if the user has a group with the same name.\n // A more robust Linux solution might involve checking for 'staff' or other common\n // groups.\n ¤t_user_name\n };\n\n debug!(\n \"Will attempt to set ownership of sps-managed directories under {} to {}:{}\",\n sps_root.display(),\n current_user_name,\n target_group_name\n );\n\n println!(\n \"{}\",\n format!(\n \"sps may require sudo to create directories and set permissions in {}.\",\n sps_root.display()\n )\n .yellow()\n );\n\n // Define directories sps needs to ensure exist and can manage.\n // These are derived from your Config struct.\n let dirs_to_create_and_manage: Vec = vec![\n config.sps_root().to_path_buf(), // The root itself\n config.bin_dir(),\n config.cellar_dir(),\n config.cask_room_dir(),\n config.cask_store_dir(), // sps-specific\n config.opt_dir(),\n config.taps_dir(), // This is now sps_root/Library/Taps\n config.cache_dir(), // sps-specific (e.g., sps_root/sps_cache)\n config.logs_dir(), // sps-specific (e.g., sps_root/sps_logs)\n config.tmp_dir(),\n config.state_dir(),\n config\n .man_base_dir()\n .parent()\n .unwrap_or(sps_root)\n .to_path_buf(), // share\n config.man_base_dir(), // share/man\n config.sps_root().join(\"etc\"),\n config.sps_root().join(\"include\"),\n config.sps_root().join(\"lib\"),\n config.sps_root().join(\"share/doc\"),\n ];\n\n // Create directories with mkdir -p (non-destructive)\n for dir_path in &dirs_to_create_and_manage {\n // Only create if it doesn't exist to avoid unnecessary sudo calls if already present\n if !dir_path.exists() {\n debug!(\n \"Ensuring directory exists with sudo: {}\",\n dir_path.display()\n );\n run_sudo_command(\"mkdir\", &[\"-p\", &dir_path.to_string_lossy()])?;\n } else {\n debug!(\n \"Directory already exists, skipping mkdir: {}\",\n dir_path.display()\n );\n }\n }\n\n // Create the marker file (non-destructive to other content)\n debug!(\n \"Creating/updating marker file with sudo: {}\",\n marker_path.display()\n );\n let marker_content = \"sps root directory version 1\";\n // Using a temporary file for sudo tee to avoid permission issues with direct pipe\n let temp_marker_file =\n tempfile::NamedTempFile::new().map_err(|e| SpsError::Io(Arc::new(e)))?;\n fs::write(temp_marker_file.path(), marker_content)\n .map_err(|e| SpsError::Io(Arc::new(e)))?;\n run_sudo_command(\n \"cp\",\n &[\n temp_marker_file.path().to_str().unwrap(),\n marker_path.to_str().unwrap(),\n ],\n )?;\n\n #[cfg(unix)]\n {\n // More targeted chown and chmod\n debug!(\n \"Setting ownership and permissions for sps-managed directories under {}...\",\n sps_root.display()\n );\n\n // Chown/Chmod the top-level sps_root directory itself (non-recursively for chmod\n // initially) This is important if sps_root is /opt/sps and was just created\n // by root. If sps_root is /opt/homebrew, this ensures the current user can\n // at least manage it.\n run_sudo_command(\n \"chown\",\n &[\n &format!(\"{current_user_name}:{target_group_name}\"),\n &sps_root.to_string_lossy(),\n ],\n )?;\n run_sudo_command(\"chmod\", &[\"ug=rwx,o=rx\", &sps_root.to_string_lossy()])?; // 755 for the root\n\n // For specific subdirectories that sps actively manages and writes into frequently,\n // ensure they are owned by the user and have appropriate permissions.\n // We apply this recursively to sps-specific dirs and key shared dirs.\n let dirs_for_recursive_chown_chmod: Vec = vec![\n config.cellar_dir(),\n config.cask_room_dir(),\n config.cask_store_dir(), // sps-specific, definitely needs full user control\n config.opt_dir(),\n config.taps_dir(),\n config.cache_dir(), // sps-specific\n config.logs_dir(), // sps-specific\n config.tmp_dir(),\n config.state_dir(),\n // bin, lib, include, share, etc are often symlink farms.\n // The top-level of these should be writable by the user to create symlinks.\n // The actual kegs in Cellar will have their own permissions.\n config.bin_dir(),\n config.sps_root().join(\"lib\"),\n config.sps_root().join(\"include\"),\n config.sps_root().join(\"share\"),\n config.sps_root().join(\"etc\"),\n ];\n\n for dir_path in dirs_for_recursive_chown_chmod {\n if dir_path.exists() {\n // Only operate on existing directories\n debug!(\"Setting ownership (recursive) for: {}\", dir_path.display());\n run_sudo_command(\n \"chown\",\n &[\n \"-R\",\n &format!(\"{current_user_name}:{target_group_name}\"),\n &dir_path.to_string_lossy(),\n ],\n )?;\n\n debug!(\n \"Setting permissions (recursive ug=rwX,o=rX) for: {}\",\n dir_path.display()\n );\n run_sudo_command(\"chmod\", &[\"-R\", \"ug=rwX,o=rX\", &dir_path.to_string_lossy()])?;\n } else {\n warn!(\n \"Directory {} was expected but not found for chown/chmod. Marker: {}\",\n dir_path.display(),\n marker_path.display()\n );\n }\n }\n\n // Ensure bin is executable by all\n if config.bin_dir().exists() {\n debug!(\n \"Ensuring execute permissions for bin_dir: {}\",\n config.bin_dir().display()\n );\n run_sudo_command(\"chmod\", &[\"a+x\", &config.bin_dir().to_string_lossy()])?;\n // Also ensure contents of bin (wrappers, symlinks) are executable if they weren't\n // caught by -R ug=rwX This might be redundant if -R ug=rwX\n // correctly sets X for existing executables, but explicit `chmod\n // a+x` on individual files might be needed if they are newly created by sps.\n // For now, relying on the recursive chmod and the a+x on the bin_dir itself.\n }\n\n // Debug listing (optional, can be verbose)\n if tracing::enabled!(tracing::Level::DEBUG) {\n debug!(\"Listing {} after permission changes:\", sps_root.display());\n let ls_output_root = StdCommand::new(\"ls\").arg(\"-ld\").arg(sps_root).output();\n if let Ok(out) = ls_output_root {\n debug!(\n \"ls -ld {}: \\nSTDOUT: {}\\nSTDERR: {}\",\n sps_root.display(),\n String::from_utf8_lossy(&out.stdout),\n String::from_utf8_lossy(&out.stderr)\n );\n }\n for dir_path in &dirs_to_create_and_manage {\n if dir_path.exists() && dir_path != sps_root {\n let ls_output_sub = StdCommand::new(\"ls\").arg(\"-ld\").arg(dir_path).output();\n if let Ok(out) = ls_output_sub {\n debug!(\n \"ls -ld {}: \\nSTDOUT: {}\\nSTDERR: {}\",\n dir_path.display(),\n String::from_utf8_lossy(&out.stdout),\n String::from_utf8_lossy(&out.stderr)\n );\n }\n }\n }\n }\n }\n\n // 3. User-Specific PATH Configuration (runs as the original user) - (No change from your\n // existing logic)\n if let Err(e) = configure_shell_path(config, ¤t_user_name) {\n warn!(\n \"Could not fully configure shell PATH: {}. Manual configuration might be needed.\",\n e\n );\n print_manual_path_instructions(&config.bin_dir().to_string_lossy());\n }\n\n debug!(\n \"{} {}\",\n \"Successfully initialized sps environment at\".green(),\n config.sps_root().display().to_string().green()\n );\n Ok(())\n }\n}\n\n// run_sudo_command helper (no change from your existing logic)\nfn run_sudo_command(command: &str, args: &[&str]) -> SpsResult<()> {\n debug!(\"Running sudo {} {:?}\", command, args);\n let output = StdCommand::new(\"sudo\")\n .arg(command)\n .args(args)\n .output()\n .map_err(|e| SpsError::Io(Arc::new(e)))?;\n\n if !output.status.success() {\n let stderr = String::from_utf8_lossy(&output.stderr);\n let stdout = String::from_utf8_lossy(&output.stdout);\n error!(\n \"sudo {} {:?} failed ({}):\\nStdout: {}\\nStderr: {}\",\n command,\n args,\n output.status,\n stdout.trim(),\n stderr.trim()\n );\n Err(SpsError::Generic(format!(\n \"Failed to execute `sudo {} {:?}`: {}\",\n command,\n args,\n stderr.trim()\n )))\n } else {\n Ok(())\n }\n}\n\n// configure_shell_path helper (no change from your existing logic)\nfn configure_shell_path(config: &Config, current_user_name_for_log: &str) -> SpsResult<()> {\n debug!(\"Attempting to configure your shell for sps PATH...\");\n\n let sps_bin_path_str = config.bin_dir().to_string_lossy().into_owned();\n let home_dir = config.home_dir();\n if home_dir == PathBuf::from(\"/\") && current_user_name_for_log != \"root\" {\n warn!(\n \"Could not reliably determine your home directory (got '/'). Please add {} to your PATH manually for user {}.\",\n sps_bin_path_str, current_user_name_for_log\n );\n print_manual_path_instructions(&sps_bin_path_str);\n return Ok(());\n }\n\n let shell_path_env = std::env::var(\"SHELL\").unwrap_or_else(|_| \"unknown\".to_string());\n let mut config_files_updated: Vec = Vec::new();\n let mut path_seems_configured = false;\n\n let sps_path_line_zsh_bash = format!(\"export PATH=\\\"{sps_bin_path_str}:$PATH\\\"\");\n let sps_path_line_fish = format!(\"fish_add_path -P \\\"{sps_bin_path_str}\\\"\");\n\n if shell_path_env.contains(\"zsh\") {\n let zshrc_path = home_dir.join(\".zshrc\");\n if update_shell_config(\n &zshrc_path,\n &sps_path_line_zsh_bash,\n &sps_bin_path_str,\n \"Zsh\",\n false,\n )? {\n config_files_updated.push(zshrc_path.display().to_string());\n } else if line_exists_in_file(&zshrc_path, &sps_bin_path_str)? {\n path_seems_configured = true;\n }\n } else if shell_path_env.contains(\"bash\") {\n let bashrc_path = home_dir.join(\".bashrc\");\n let bash_profile_path = home_dir.join(\".bash_profile\");\n let profile_path = home_dir.join(\".profile\");\n\n let mut bash_updated_by_sps = false;\n if update_shell_config(\n &bashrc_path,\n &sps_path_line_zsh_bash,\n &sps_bin_path_str,\n \"Bash (.bashrc)\",\n false,\n )? {\n config_files_updated.push(bashrc_path.display().to_string());\n bash_updated_by_sps = true;\n if bash_profile_path.exists() {\n ensure_profile_sources_rc(&bash_profile_path, &bashrc_path, \"Bash (.bash_profile)\");\n } else if profile_path.exists() {\n ensure_profile_sources_rc(&profile_path, &bashrc_path, \"Bash (.profile)\");\n } else {\n debug!(\"Neither .bash_profile nor .profile found. Creating .bash_profile to source .bashrc.\");\n ensure_profile_sources_rc(&bash_profile_path, &bashrc_path, \"Bash (.bash_profile)\");\n }\n } else if update_shell_config(\n &bash_profile_path,\n &sps_path_line_zsh_bash,\n &sps_bin_path_str,\n \"Bash (.bash_profile)\",\n false,\n )? {\n config_files_updated.push(bash_profile_path.display().to_string());\n bash_updated_by_sps = true;\n } else if update_shell_config(\n &profile_path,\n &sps_path_line_zsh_bash,\n &sps_bin_path_str,\n \"Bash (.profile)\",\n false,\n )? {\n config_files_updated.push(profile_path.display().to_string());\n bash_updated_by_sps = true;\n }\n\n if !bash_updated_by_sps\n && (line_exists_in_file(&bashrc_path, &sps_bin_path_str)?\n || line_exists_in_file(&bash_profile_path, &sps_bin_path_str)?\n || line_exists_in_file(&profile_path, &sps_bin_path_str)?)\n {\n path_seems_configured = true;\n }\n } else if shell_path_env.contains(\"fish\") {\n let fish_config_dir = home_dir.join(\".config/fish\");\n if !fish_config_dir.exists() {\n if let Err(e) = fs::create_dir_all(&fish_config_dir) {\n warn!(\n \"Could not create Fish config directory {}: {}\",\n fish_config_dir.display(),\n e\n );\n }\n }\n if fish_config_dir.exists() {\n let fish_config_path = fish_config_dir.join(\"config.fish\");\n if update_shell_config(\n &fish_config_path,\n &sps_path_line_fish,\n &sps_bin_path_str,\n \"Fish\",\n true,\n )? {\n config_files_updated.push(fish_config_path.display().to_string());\n } else if line_exists_in_file(&fish_config_path, &sps_bin_path_str)? {\n path_seems_configured = true;\n }\n }\n } else {\n warn!(\n \"Unsupported shell for automatic PATH configuration: {}. Please add {} to your PATH manually.\",\n shell_path_env, sps_bin_path_str\n );\n print_manual_path_instructions(&sps_bin_path_str);\n return Ok(());\n }\n\n if !config_files_updated.is_empty() {\n println!(\n \"{} {} has been added to your PATH by modifying: {}\",\n \"sps\".cyan(),\n sps_bin_path_str.cyan(),\n config_files_updated.join(\", \").white()\n );\n println!(\n \"{}\",\n \"Please open a new terminal session or source your shell configuration file for the changes to take effect.\"\n .yellow()\n );\n if shell_path_env.contains(\"zsh\") {\n println!(\" Run: {}\", \"source ~/.zshrc\".green());\n }\n if shell_path_env.contains(\"bash\") {\n println!(\n \" Run: {} (or {} or {})\",\n \"source ~/.bashrc\".green(),\n \"source ~/.bash_profile\".green(),\n \"source ~/.profile\".green()\n );\n }\n if shell_path_env.contains(\"fish\") {\n println!(\n \" Run (usually not needed for fish_add_path, but won't hurt): {}\",\n \"source ~/.config/fish/config.fish\".green()\n );\n }\n } else if path_seems_configured {\n debug!(\"sps path ({}) is likely already configured for your shell ({}). No configuration files were modified.\", sps_bin_path_str.cyan(), shell_path_env.yellow());\n } else if !shell_path_env.is_empty() && shell_path_env != \"unknown\" {\n warn!(\"Could not automatically update PATH for your shell: {}. Please add {} to your PATH manually.\", shell_path_env.yellow(), sps_bin_path_str.cyan());\n print_manual_path_instructions(&sps_bin_path_str);\n }\n Ok(())\n}\n\n// print_manual_path_instructions helper (no change from your existing logic)\nfn print_manual_path_instructions(sps_bin_path_str: &str) {\n println!(\"\\n{} To use sps commands and installed packages directly, please add the following line to your shell configuration file:\", \"Action Required:\".yellow().bold());\n println!(\" (e.g., ~/.zshrc, ~/.bashrc, ~/.config/fish/config.fish)\");\n println!(\"\\n For Zsh or Bash:\");\n println!(\n \" {}\",\n format!(\"export PATH=\\\"{sps_bin_path_str}:$PATH\\\"\").green()\n );\n println!(\"\\n For Fish shell:\");\n println!(\n \" {}\",\n format!(\"fish_add_path -P \\\"{sps_bin_path_str}\\\"\").green()\n );\n println!(\n \"\\nThen, open a new terminal or run: {}\",\n \"source \".green()\n );\n}\n\n// line_exists_in_file helper (no change from your existing logic)\nfn line_exists_in_file(file_path: &Path, sps_bin_path_str: &str) -> SpsResult {\n if !file_path.exists() {\n return Ok(false);\n }\n let file = File::open(file_path).map_err(|e| SpsError::Io(Arc::new(e)))?;\n let reader = BufReader::new(file);\n let escaped_sps_bin_path = regex::escape(sps_bin_path_str);\n // Regex to find lines that configure PATH, trying to be robust for different shells\n // It looks for lines that set PATH or fish_user_paths and include the sps_bin_path_str\n // while trying to avoid commented out lines.\n let pattern = format!(\n r#\"(?m)^\\s*[^#]*\\b(?:PATH\\s*=|export\\s+PATH\\s*=|set\\s*(?:-gx\\s*|-U\\s*)?\\s*fish_user_paths\\b|fish_add_path\\s*(?:-P\\s*|-p\\s*)?)?[\"']?.*{escaped_sps_bin_path}.*[\"']?\"#\n );\n let search_pattern_regex = regex::Regex::new(&pattern)\n .map_err(|e| SpsError::Generic(format!(\"Failed to compile regex for PATH check: {e}\")))?;\n\n for line_result in reader.lines() {\n let line = line_result.map_err(|e| SpsError::Io(Arc::new(e)))?;\n if search_pattern_regex.is_match(&line) {\n debug!(\n \"Found sps PATH ({}) in {}: {}\",\n sps_bin_path_str,\n file_path.display(),\n line.trim()\n );\n return Ok(true);\n }\n }\n Ok(false)\n}\n\n// update_shell_config helper (no change from your existing logic)\nfn update_shell_config(\n config_path: &PathBuf,\n line_to_add: &str,\n sps_bin_path_str: &str,\n shell_name_for_log: &str,\n is_fish_shell: bool,\n) -> SpsResult {\n let sps_comment_tag_start = \"# SPS Path Management Start\";\n let sps_comment_tag_end = \"# SPS Path Management End\";\n\n if config_path.exists() {\n match line_exists_in_file(config_path, sps_bin_path_str) {\n Ok(true) => {\n debug!(\n \"sps path ({}) already configured or managed in {} ({}). Skipping modification.\",\n sps_bin_path_str,\n config_path.display(),\n shell_name_for_log\n );\n return Ok(false); // Path already seems configured\n }\n Ok(false) => { /* Proceed to add */ }\n Err(e) => {\n warn!(\n \"Could not reliably check existing configuration in {} ({}): {}. Attempting to add PATH.\",\n config_path.display(),\n shell_name_for_log,\n e\n );\n // Proceed with caution, might add duplicate if check failed but line exists\n }\n }\n }\n\n debug!(\n \"Adding sps PATH to {} ({})\",\n config_path.display(),\n shell_name_for_log\n );\n\n // Ensure parent directory exists\n if let Some(parent_dir) = config_path.parent() {\n if !parent_dir.exists() {\n fs::create_dir_all(parent_dir).map_err(|e| {\n SpsError::Io(Arc::new(std::io::Error::new(\n e.kind(),\n format!(\n \"Failed to create parent directory {}: {}\",\n parent_dir.display(),\n e\n ),\n )))\n })?;\n }\n }\n\n let mut file = OpenOptions::new()\n .append(true)\n .create(true)\n .open(config_path)\n .map_err(|e| {\n let msg = format!(\n \"Could not open/create shell config {} ({}): {}. Please add {} to your PATH manually.\",\n config_path.display(), shell_name_for_log, e, sps_bin_path_str\n );\n error!(\"{}\", msg);\n SpsError::Io(Arc::new(std::io::Error::new(e.kind(), msg)))\n })?;\n\n // Construct the block to add, ensuring it's idempotent for fish\n let block_to_add = if is_fish_shell {\n format!(\n \"\\n{sps_comment_tag_start}\\n# Add sps to PATH if not already present\\nif not contains \\\"{sps_bin_path_str}\\\" $fish_user_paths\\n {line_to_add}\\nend\\n{sps_comment_tag_end}\\n\"\n )\n } else {\n format!(\"\\n{sps_comment_tag_start}\\n{line_to_add}\\n{sps_comment_tag_end}\\n\")\n };\n\n if let Err(e) = writeln!(file, \"{block_to_add}\") {\n warn!(\n \"Failed to write to shell config {} ({}): {}\",\n config_path.display(),\n shell_name_for_log,\n e\n );\n Ok(false) // Indicate that update was not successful\n } else {\n debug!(\n \"Successfully updated {} ({}) with sps PATH.\",\n config_path.display(),\n shell_name_for_log\n );\n Ok(true) // Indicate successful update\n }\n}\n\n// ensure_profile_sources_rc helper (no change from your existing logic)\nfn ensure_profile_sources_rc(profile_path: &PathBuf, rc_path: &Path, shell_name_for_log: &str) {\n let rc_path_str = rc_path.to_string_lossy();\n // Regex to check if the profile file already sources the rc file.\n // Looks for lines like:\n // . /path/to/.bashrc\n // source /path/to/.bashrc\n // [ -f /path/to/.bashrc ] && . /path/to/.bashrc (and similar variants)\n let source_check_pattern = format!(\n r#\"(?m)^\\s*[^#]*(\\.|source|\\bsource\\b)\\s+[\"']?{}[\"']?\"#, /* More general source command\n * matching */\n regex::escape(&rc_path_str)\n );\n let source_check_regex = match regex::Regex::new(&source_check_pattern) {\n Ok(re) => re,\n Err(e) => {\n warn!(\"Failed to compile regex for sourcing check: {}. Skipping ensure_profile_sources_rc for {}\", e, profile_path.display());\n return;\n }\n };\n\n if profile_path.exists() {\n match fs::read_to_string(profile_path) {\n Ok(existing_content) => {\n if source_check_regex.is_match(&existing_content) {\n debug!(\n \"{} ({}) already sources {}.\",\n profile_path.display(),\n shell_name_for_log,\n rc_path.display()\n );\n return; // Already configured\n }\n }\n Err(e) => {\n warn!(\n \"Could not read {} to check if it sources {}: {}. Will attempt to append.\",\n profile_path.display(),\n rc_path.display(),\n e\n );\n }\n }\n }\n\n // Block to add to .bash_profile or .profile to source .bashrc\n let source_block_to_add = format!(\n \"\\n# Source {rc_filename} if it exists and is readable\\nif [ -f \\\"{rc_path_str}\\\" ] && [ -r \\\"{rc_path_str}\\\" ]; then\\n . \\\"{rc_path_str}\\\"\\nfi\\n\",\n rc_filename = rc_path.file_name().unwrap_or_default().to_string_lossy(),\n rc_path_str = rc_path_str\n );\n\n debug!(\n \"Attempting to ensure {} ({}) sources {}\",\n profile_path.display(),\n shell_name_for_log,\n rc_path.display()\n );\n\n if let Some(parent_dir) = profile_path.parent() {\n if !parent_dir.exists() {\n if let Err(e) = fs::create_dir_all(parent_dir) {\n warn!(\n \"Failed to create parent directory for {}: {}\",\n profile_path.display(),\n e\n );\n return; // Cannot proceed if parent dir creation fails\n }\n }\n }\n\n match OpenOptions::new()\n .append(true)\n .create(true)\n .open(profile_path)\n {\n Ok(mut file) => {\n if let Err(e) = writeln!(file, \"{source_block_to_add}\") {\n warn!(\n \"Failed to write to {} ({}): {}\",\n profile_path.display(),\n shell_name_for_log,\n e\n );\n } else {\n debug!(\n \"Updated {} ({}) to source {}.\",\n profile_path.display(),\n shell_name_for_log,\n rc_path.display()\n );\n }\n }\n Err(e) => {\n warn!(\n \"Could not open or create {} ({}) for updating: {}\",\n profile_path.display(),\n shell_name_for_log,\n e\n );\n }\n }\n}\n"], ["/sps/sps-core/src/install/extract.rs", "// Path: sps-core/src/install/extract.rs\nuse std::collections::HashSet;\nuse std::fs::{self, File};\nuse std::io::{self, Read, Seek};\nuse std::path::{Component, Path, PathBuf};\nuse std::process::Command;\n\nuse bzip2::read::BzDecoder;\nuse flate2::read::GzDecoder;\nuse sps_common::error::{Result, SpsError};\nuse tar::{Archive, EntryType};\nuse tracing::{debug, error, warn};\nuse zip::ZipArchive;\n\n#[cfg(target_os = \"macos\")]\nuse crate::utils::xattr;\n\npub(crate) fn infer_archive_root_dir(\n archive_path: &Path,\n archive_type: &str,\n) -> Result> {\n tracing::debug!(\n \"Inferring root directory for archive: {}\",\n archive_path.display()\n );\n let file = File::open(archive_path).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed to open archive {}: {}\", archive_path.display(), e),\n )))\n })?;\n\n match archive_type {\n \"zip\" => infer_zip_root(file, archive_path),\n \"gz\" | \"tgz\" => {\n let decompressed = GzDecoder::new(file);\n infer_tar_root(decompressed, archive_path)\n }\n \"bz2\" | \"tbz\" | \"tbz2\" => {\n let decompressed = BzDecoder::new(file);\n infer_tar_root(decompressed, archive_path)\n }\n \"xz\" | \"txz\" => {\n // Use external xz command to decompress, then read as tar\n infer_xz_tar_root(archive_path)\n }\n \"tar\" => infer_tar_root(file, archive_path),\n _ => Err(SpsError::Generic(format!(\n \"Cannot infer root dir for unsupported archive type '{}' in {}\",\n archive_type,\n archive_path.display()\n ))),\n }\n}\n\nfn infer_tar_root(reader: R, archive_path_for_log: &Path) -> Result> {\n let mut archive = Archive::new(reader);\n let mut unique_roots = HashSet::new();\n let mut non_empty_entry_found = false;\n let mut first_component_name: Option = None;\n\n for entry_result in archive.entries()? {\n let entry = entry_result.map_err(|e| {\n SpsError::Generic(format!(\n \"Error reading TAR entry from {}: {}\",\n archive_path_for_log.display(),\n e\n ))\n })?;\n let path = entry\n .path()\n .map_err(|e| {\n SpsError::Generic(format!(\n \"Invalid path in TAR entry from {}: {}\",\n archive_path_for_log.display(),\n e\n ))\n })?\n .into_owned();\n\n if path.components().next().is_none() {\n continue;\n }\n\n if let Some(first_comp) = path.components().next() {\n if let Component::Normal(name) = first_comp {\n non_empty_entry_found = true;\n let current_root = PathBuf::from(name);\n if first_component_name.is_none() {\n first_component_name = Some(current_root.clone());\n }\n unique_roots.insert(current_root);\n\n if unique_roots.len() > 1 {\n tracing::debug!(\n \"Multiple top-level items found in TAR {}, cannot infer single root.\",\n archive_path_for_log.display()\n );\n return Ok(None);\n }\n } else {\n tracing::debug!(\n \"Non-standard top-level component ({:?}) found in TAR {}, cannot infer single root.\",\n first_comp,\n archive_path_for_log.display()\n );\n return Ok(None);\n }\n } else {\n tracing::debug!(\n \"Empty or unusual path found in TAR {}, cannot infer single root.\",\n archive_path_for_log.display()\n );\n return Ok(None);\n }\n }\n\n if unique_roots.len() == 1 && non_empty_entry_found {\n let inferred_root = first_component_name.unwrap();\n tracing::debug!(\n \"Inferred single root directory in TAR {}: {}\",\n archive_path_for_log.display(),\n inferred_root.display()\n );\n Ok(Some(inferred_root))\n } else if !non_empty_entry_found {\n tracing::warn!(\n \"TAR archive {} appears to be empty or contain only metadata.\",\n archive_path_for_log.display()\n );\n Ok(None)\n } else {\n tracing::debug!(\n \"No single common root directory found in TAR {}. unique_roots count: {}\",\n archive_path_for_log.display(),\n unique_roots.len()\n );\n Ok(None)\n }\n}\n\nfn infer_xz_tar_root(archive_path: &Path) -> Result> {\n // Create a temporary file for decompressed content\n let temp_file =\n tempfile::NamedTempFile::new().map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n\n // Use external xz command to decompress\n let output = Command::new(\"xz\")\n .args([\"-dc\", archive_path.to_str().unwrap()])\n .output()\n .map_err(|e| {\n SpsError::Generic(format!(\n \"Failed to run xz command for decompression: {e}. Make sure xz is installed.\"\n ))\n })?;\n\n if !output.status.success() {\n return Err(SpsError::Generic(format!(\n \"xz decompression failed: {}\",\n String::from_utf8_lossy(&output.stderr)\n )));\n }\n\n // Write decompressed data to temp file\n std::fs::write(temp_file.path(), &output.stdout)\n .map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n\n // Read as tar\n let file = File::open(temp_file.path()).map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n infer_tar_root(file, archive_path)\n}\n\nfn infer_zip_root(reader: R, archive_path: &Path) -> Result> {\n let mut archive = ZipArchive::new(reader).map_err(|e| {\n SpsError::Generic(format!(\n \"Failed to open ZIP archive {}: {}\",\n archive_path.display(),\n e\n ))\n })?;\n\n let mut root_candidates = HashSet::new();\n\n for i in 0..archive.len() {\n let file = archive\n .by_index(i)\n .map_err(|e| SpsError::Generic(format!(\"Failed to read ZIP entry {i}: {e}\")))?;\n\n if let Some(enclosed_name) = file.enclosed_name() {\n if let Some(Component::Normal(name)) = enclosed_name.components().next() {\n root_candidates.insert(name.to_string_lossy().to_string());\n }\n }\n }\n\n if root_candidates.len() == 1 {\n let root = root_candidates.into_iter().next().unwrap();\n Ok(Some(PathBuf::from(root)))\n } else {\n Ok(None)\n }\n}\n\n#[cfg(target_os = \"macos\")]\npub fn quarantine_extracted_apps_in_stage(stage_dir: &Path, agent_name: &str) -> Result<()> {\n use std::fs;\n\n use tracing::{debug, warn};\n debug!(\n \"Searching for .app bundles in {} to apply quarantine.\",\n stage_dir.display()\n );\n if stage_dir.is_dir() {\n for entry_result in fs::read_dir(stage_dir)? {\n let entry = entry_result?;\n let entry_path = entry.path();\n if entry_path.is_dir() && entry_path.extension().is_some_and(|ext| ext == \"app\") {\n debug!(\n \"Found app bundle in stage: {}. Applying quarantine.\",\n entry_path.display()\n );\n if let Err(e) = xattr::set_quarantine_attribute(&entry_path, agent_name) {\n warn!(\n \"Failed to set quarantine attribute on staged app {}: {}. Installation will continue.\",\n entry_path.display(),\n e\n );\n }\n }\n }\n }\n Ok(())\n}\n\npub fn extract_archive(\n archive_path: &Path,\n target_dir: &Path,\n strip_components: usize,\n archive_type: &str,\n) -> Result<()> {\n debug!(\n \"Extracting archive '{}' (type: {}) to '{}' (strip_components={}) using native Rust crates.\",\n archive_path.display(),\n archive_type,\n target_dir.display(),\n strip_components\n );\n\n fs::create_dir_all(target_dir).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\n \"Failed to create target directory {}: {}\",\n target_dir.display(),\n e\n ),\n )))\n })?;\n\n let file = File::open(archive_path).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed to open archive {}: {}\", archive_path.display(), e),\n )))\n })?;\n\n let result = match archive_type {\n \"zip\" => extract_zip_archive(file, target_dir, strip_components, archive_path),\n \"gz\" | \"tgz\" => {\n let tar = GzDecoder::new(file);\n extract_tar_archive(tar, target_dir, strip_components, archive_path)\n }\n \"bz2\" | \"tbz\" | \"tbz2\" => {\n let tar = BzDecoder::new(file);\n extract_tar_archive(tar, target_dir, strip_components, archive_path)\n }\n \"xz\" | \"txz\" => extract_xz_tar_archive(archive_path, target_dir, strip_components),\n \"tar\" => extract_tar_archive(file, target_dir, strip_components, archive_path),\n _ => Err(SpsError::Generic(format!(\n \"Unsupported archive type provided for extraction: '{}' for file {}\",\n archive_type,\n archive_path.display()\n ))),\n };\n #[cfg(target_os = \"macos\")]\n {\n if result.is_ok() {\n // Only quarantine if main extraction was successful\n if let Err(e) = quarantine_extracted_apps_in_stage(target_dir, \"sps-extractor\") {\n tracing::warn!(\n \"Error during post-extraction quarantine scan for {}: {}\",\n archive_path.display(),\n e\n );\n }\n }\n }\n result\n}\n\n/// Represents a hardlink operation that was deferred.\nfn extract_xz_tar_archive(\n archive_path: &Path,\n target_dir: &Path,\n strip_components: usize,\n) -> Result<()> {\n debug!(\n \"Extracting XZ+TAR archive using external xz command: {}\",\n archive_path.display()\n );\n\n // Create a temporary file for decompressed content\n let temp_file =\n tempfile::NamedTempFile::new().map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n\n // Use external xz command to decompress\n let output = Command::new(\"xz\")\n .args([\"-dc\", archive_path.to_str().unwrap()])\n .output()\n .map_err(|e| {\n SpsError::Generic(format!(\n \"Failed to run xz command for extraction: {e}. Make sure xz is installed.\"\n ))\n })?;\n\n if !output.status.success() {\n return Err(SpsError::Generic(format!(\n \"xz decompression failed during extraction: {}\",\n String::from_utf8_lossy(&output.stderr)\n )));\n }\n\n // Write decompressed data to temp file\n std::fs::write(temp_file.path(), &output.stdout)\n .map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n\n // Extract as tar\n let file = File::open(temp_file.path()).map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n extract_tar_archive(file, target_dir, strip_components, archive_path)\n}\n\n#[cfg(unix)]\nstruct DeferredHardLink {\n link_path_in_archive: PathBuf,\n target_name_in_archive: PathBuf,\n}\n\nfn extract_tar_archive(\n reader: R,\n target_dir: &Path,\n strip_components: usize,\n archive_path_for_log: &Path,\n) -> Result<()> {\n let mut archive = Archive::new(reader);\n archive.set_preserve_permissions(true);\n archive.set_unpack_xattrs(true);\n archive.set_overwrite(true);\n\n debug!(\n \"Starting TAR extraction for {}\",\n archive_path_for_log.display()\n );\n\n #[cfg(unix)]\n let mut deferred_hardlinks: Vec = Vec::new();\n let mut errors: Vec = Vec::new();\n\n for entry_result in archive.entries()? {\n let mut entry = entry_result.map_err(|e| {\n SpsError::Generic(format!(\n \"Error reading TAR entry from {}: {}\",\n archive_path_for_log.display(),\n e\n ))\n })?;\n\n let original_path_in_archive: PathBuf = entry\n .path()\n .map_err(|e| {\n SpsError::Generic(format!(\n \"Invalid path in TAR entry from {}: {}\",\n archive_path_for_log.display(),\n e\n ))\n })?\n .into_owned();\n\n let stripped_components_iter: Vec> = original_path_in_archive\n .components()\n .skip(strip_components)\n .collect();\n\n if stripped_components_iter.is_empty() {\n debug!(\n \"Skipping entry due to strip_components: {:?}\",\n original_path_in_archive\n );\n continue;\n }\n\n let mut final_target_path_on_disk = target_dir.to_path_buf();\n for comp in stripped_components_iter {\n match comp {\n Component::Normal(p) => final_target_path_on_disk.push(p),\n Component::CurDir => {}\n Component::ParentDir => {\n let msg = format!(\n \"Unsafe '..' in TAR path {} after stripping in {}\",\n original_path_in_archive.display(),\n archive_path_for_log.display()\n );\n error!(\"{}\", msg);\n errors.push(msg);\n continue;\n }\n Component::Prefix(_) | Component::RootDir => {\n let msg = format!(\n \"Disallowed component {:?} in TAR path {}\",\n comp,\n original_path_in_archive.display()\n );\n error!(\"{}\", msg);\n errors.push(msg);\n continue;\n }\n }\n }\n\n if !final_target_path_on_disk.starts_with(target_dir) {\n let msg = format!(\n \"Path traversal {} -> {} detected in {}\",\n original_path_in_archive.display(),\n final_target_path_on_disk.display(),\n archive_path_for_log.display()\n );\n error!(\"{}\", msg);\n errors.push(msg);\n continue;\n }\n\n if let Some(parent) = final_target_path_on_disk.parent() {\n if !parent.exists() {\n fs::create_dir_all(parent).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(io::Error::new(\n e.kind(),\n format!(\"Failed create parent dir {}: {}\", parent.display(), e),\n )))\n })?;\n }\n }\n\n #[cfg(unix)]\n if entry.header().entry_type() == EntryType::Link {\n if let Ok(Some(link_name_in_archive)) = entry.link_name() {\n let deferred_link = DeferredHardLink {\n link_path_in_archive: original_path_in_archive.clone(),\n target_name_in_archive: link_name_in_archive.into_owned(),\n };\n debug!(\n \"Deferring hardlink: archive path '{}' -> archive target '{}'\",\n original_path_in_archive.display(),\n deferred_link.target_name_in_archive.display()\n );\n deferred_hardlinks.push(deferred_link);\n continue;\n } else {\n let msg = format!(\n \"Hardlink entry '{}' in {} has no link target name.\",\n original_path_in_archive.display(),\n archive_path_for_log.display()\n );\n warn!(\"{}\", msg);\n errors.push(msg);\n continue;\n }\n }\n\n match entry.unpack(&final_target_path_on_disk) {\n Ok(_) => debug!(\n \"Unpacked TAR entry to: {}\",\n final_target_path_on_disk.display()\n ),\n Err(e) => {\n if e.kind() != io::ErrorKind::AlreadyExists {\n let msg = format!(\n \"Failed to unpack entry {:?} to {}: {}. Entry type: {:?}\",\n original_path_in_archive,\n final_target_path_on_disk.display(),\n e,\n entry.header().entry_type()\n );\n error!(\"{}\", msg);\n errors.push(msg);\n } else {\n debug!(\"Entry already exists at {}, skipping unpack (tar crate overwrite=true handles this).\", final_target_path_on_disk.display());\n }\n }\n }\n }\n\n #[cfg(unix)]\n for deferred in deferred_hardlinks {\n let mut disk_link_path = target_dir.to_path_buf();\n for comp in deferred\n .link_path_in_archive\n .components()\n .skip(strip_components)\n {\n if let Component::Normal(p) = comp {\n disk_link_path.push(p);\n }\n // Other components should have been caught by safety checks above\n }\n\n let mut disk_target_path = target_dir.to_path_buf();\n // The link_name_in_archive is relative to the archive root *before* stripping.\n // We need to apply stripping to it as well to find its final disk location.\n for comp in deferred\n .target_name_in_archive\n .components()\n .skip(strip_components)\n {\n if let Component::Normal(p) = comp {\n disk_target_path.push(p);\n }\n }\n\n if !disk_target_path.starts_with(target_dir) || !disk_link_path.starts_with(target_dir) {\n let msg = format!(\"Skipping deferred hardlink due to path traversal attempt: link '{}' -> target '{}'\", disk_link_path.display(), disk_target_path.display());\n error!(\"{}\", msg);\n errors.push(msg);\n continue;\n }\n\n debug!(\n \"Attempting deferred hardlink: disk link path '{}' -> disk target path '{}'\",\n disk_link_path.display(),\n disk_target_path.display()\n );\n\n if disk_target_path.exists() {\n if let Some(parent) = disk_link_path.parent() {\n if !parent.exists() {\n if let Err(e) = fs::create_dir_all(parent) {\n let msg = format!(\n \"Failed to create parent directory for deferred hardlink {}: {}\",\n disk_link_path.display(),\n e\n );\n error!(\"{}\", msg);\n errors.push(msg);\n continue;\n }\n }\n }\n\n if disk_link_path.symlink_metadata().is_ok() {\n // Check if something (file or symlink) exists at the link creation spot\n if let Err(e) = fs::remove_file(&disk_link_path) {\n // Attempt to remove it\n warn!(\"Could not remove existing file/symlink at hardlink destination {}: {}. Hardlink creation may fail.\", disk_link_path.display(), e);\n }\n }\n\n if let Err(e) = fs::hard_link(&disk_target_path, &disk_link_path) {\n let msg = format!(\n \"Failed to create deferred hardlink '{}' -> '{}': {}. Target exists: {}\",\n disk_link_path.display(),\n disk_target_path.display(),\n e,\n disk_target_path.exists()\n );\n error!(\"{}\", msg);\n errors.push(msg);\n } else {\n debug!(\n \"Successfully created deferred hardlink: '{}' -> '{}'\",\n disk_link_path.display(),\n disk_target_path.display()\n );\n }\n } else {\n let msg = format!(\n \"Target '{}' for deferred hardlink '{}' does not exist. Hardlink not created.\",\n disk_target_path.display(),\n disk_link_path.display()\n );\n error!(\"{}\", msg);\n errors.push(msg);\n }\n }\n\n if !errors.is_empty() {\n return Err(SpsError::InstallError(format!(\n \"Failed during TAR extraction for {} with {} error(s): {}\",\n archive_path_for_log.display(),\n errors.len(),\n errors.join(\"; \")\n )));\n }\n\n debug!(\n \"Finished TAR extraction for {}\",\n archive_path_for_log.display()\n );\n #[cfg(target_os = \"macos\")]\n {\n if let Err(e) = quarantine_extracted_apps_in_stage(target_dir, \"sps-tar-extractor\") {\n tracing::warn!(\n \"Error during post-tar extraction quarantine scan for {}: {}\",\n archive_path_for_log.display(),\n e\n );\n }\n }\n Ok(())\n}\n\nfn extract_zip_archive(\n reader: R,\n target_dir: &Path,\n strip_components: usize,\n archive_path_for_log: &Path,\n) -> Result<()> {\n let mut archive = ZipArchive::new(reader).map_err(|e| {\n SpsError::Generic(format!(\n \"Failed to open ZIP {}: {}\",\n archive_path_for_log.display(),\n e\n ))\n })?;\n\n debug!(\n \"Starting ZIP extraction for {}\",\n archive_path_for_log.display()\n );\n\n for i in 0..archive.len() {\n let mut file = archive\n .by_index(i)\n .map_err(|e| SpsError::Generic(format!(\"Failed to read ZIP entry {i}: {e}\")))?;\n\n let Some(original_path_in_archive) = file.enclosed_name() else {\n debug!(\"Skipping unsafe ZIP entry (no enclosed name)\");\n continue;\n };\n\n let stripped_components_iter: Vec> = original_path_in_archive\n .components()\n .skip(strip_components)\n .collect();\n\n if stripped_components_iter.is_empty() {\n debug!(\n \"Skipping ZIP entry {} due to strip_components\",\n original_path_in_archive.display()\n );\n continue;\n }\n\n let mut final_target_path_on_disk = target_dir.to_path_buf();\n for comp in stripped_components_iter {\n match comp {\n Component::Normal(p) => final_target_path_on_disk.push(p),\n Component::CurDir => {}\n Component::ParentDir => {\n error!(\n \"Unsafe '..' in ZIP path {} after strip_components\",\n original_path_in_archive.display()\n );\n return Err(SpsError::Generic(format!(\n \"Unsafe '..' component in ZIP path {}\",\n original_path_in_archive.display()\n )));\n }\n Component::Prefix(_) | Component::RootDir => {\n error!(\n \"Disallowed component {:?} in ZIP path {}\",\n comp,\n original_path_in_archive.display()\n );\n return Err(SpsError::Generic(format!(\n \"Disallowed component in ZIP path {}\",\n original_path_in_archive.display()\n )));\n }\n }\n }\n\n if !final_target_path_on_disk.starts_with(target_dir) {\n error!(\n \"ZIP path traversal detected: {} -> {}\",\n original_path_in_archive.display(),\n final_target_path_on_disk.display()\n );\n return Err(SpsError::Generic(format!(\n \"ZIP path traversal detected in {}\",\n archive_path_for_log.display()\n )));\n }\n\n if let Some(parent) = final_target_path_on_disk.parent() {\n if !parent.exists() {\n fs::create_dir_all(parent).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(io::Error::new(\n e.kind(),\n format!(\n \"Failed to create parent directory {}: {}\",\n parent.display(),\n e\n ),\n )))\n })?;\n }\n }\n\n if file.is_dir() {\n debug!(\n \"Creating directory: {}\",\n final_target_path_on_disk.display()\n );\n fs::create_dir_all(&final_target_path_on_disk).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(io::Error::new(\n e.kind(),\n format!(\n \"Failed to create directory {}: {}\",\n final_target_path_on_disk.display(),\n e\n ),\n )))\n })?;\n } else {\n // Regular file\n if final_target_path_on_disk.exists() {\n match fs::remove_file(&final_target_path_on_disk) {\n Ok(_) => {}\n Err(e) if e.kind() == io::ErrorKind::NotFound => {}\n Err(e) => return Err(SpsError::Io(std::sync::Arc::new(e))),\n }\n }\n\n debug!(\"Extracting file: {}\", final_target_path_on_disk.display());\n let mut outfile = File::create(&final_target_path_on_disk).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(io::Error::new(\n e.kind(),\n format!(\n \"Failed to create file {}: {}\",\n final_target_path_on_disk.display(),\n e\n ),\n )))\n })?;\n\n std::io::copy(&mut file, &mut outfile).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(io::Error::new(\n e.kind(),\n format!(\n \"Failed to write file {}: {}\",\n final_target_path_on_disk.display(),\n e\n ),\n )))\n })?;\n\n // Set permissions on Unix systems\n #[cfg(unix)]\n {\n use std::os::unix::fs::PermissionsExt;\n if let Some(mode) = file.unix_mode() {\n let perms = std::fs::Permissions::from_mode(mode);\n std::fs::set_permissions(&final_target_path_on_disk, perms)\n .map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n }\n }\n }\n }\n\n debug!(\n \"Finished ZIP extraction for {}\",\n archive_path_for_log.display()\n );\n\n // Apply quarantine to extracted apps on macOS\n #[cfg(target_os = \"macos\")]\n {\n if let Err(e) = quarantine_extracted_apps_in_stage(target_dir, \"sps-zip-extractor\") {\n tracing::warn!(\n \"Error during post-zip extraction quarantine scan for {}: {}\",\n archive_path_for_log.display(),\n e\n );\n }\n }\n\n Ok(())\n}\n"], ["/sps/sps/src/cli/info.rs", "//! Contains the logic for the `info` command.\n\nuse std::sync::Arc;\n\nuse clap::Args;\nuse colored::Colorize;\nuse serde_json::Value;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_net::api;\n\n#[derive(Args, Debug)]\npub struct Info {\n /// Name of the formula or cask\n pub name: String,\n\n /// Show information for a cask, not a formula\n #[arg(long)]\n pub cask: bool,\n}\n\nimpl Info {\n /// Displays detailed information about a formula or cask.\n pub async fn run(&self, _config: &Config, cache: Arc) -> Result<()> {\n let name = &self.name;\n let is_cask = self.cask;\n tracing::debug!(\"Getting info for package: {name}, is_cask: {is_cask}\",);\n\n // Print loading message instead of spinner\n println!(\"Loading info for {name}\");\n\n if self.cask {\n match get_cask_info(Arc::clone(&cache), name).await {\n Ok(info) => {\n print_cask_info(name, &info);\n Ok(())\n }\n Err(e) => Err(e),\n }\n } else {\n match get_formula_info_raw(Arc::clone(&cache), name).await {\n Ok(info) => {\n // Removed bottle check logic here as it was complex and potentially racy.\n // We'll try formula first, then cask if formula fails.\n print_formula_info(name, &info);\n return Ok(());\n }\n Err(SpsError::NotFound(_)) | Err(SpsError::Generic(_)) => {\n // If formula lookup failed (not found or generic error), try cask.\n tracing::debug!(\"Formula '{}' info failed, trying cask.\", name);\n }\n Err(e) => {\n return Err(e); // Propagate other errors (API, JSON, etc.)\n }\n }\n // --- Cask Fallback ---\n match get_cask_info(Arc::clone(&cache), name).await {\n Ok(info) => {\n print_cask_info(name, &info);\n Ok(())\n }\n Err(e) => {\n Err(e) // Return the cask error if both formula and cask fail\n }\n }\n }\n }\n}\n\n/// Retrieves formula information from the cache or API as raw JSON\nasync fn get_formula_info_raw(cache: Arc, name: &str) -> Result {\n match cache.load_raw(\"formula.json\") {\n Ok(formula_data) => {\n let formulas: Vec =\n serde_json::from_str(&formula_data).map_err(SpsError::from)?;\n for formula in formulas {\n if let Some(fname) = formula.get(\"name\").and_then(Value::as_str) {\n if fname == name {\n return Ok(formula);\n }\n }\n // Also check aliases if needed\n if let Some(aliases) = formula.get(\"aliases\").and_then(|a| a.as_array()) {\n if aliases.iter().any(|a| a.as_str() == Some(name)) {\n return Ok(formula);\n }\n }\n }\n tracing::debug!(\"Formula '{}' not found within cached 'formula.json'.\", name);\n // Explicitly return NotFound if not in cache\n return Err(SpsError::NotFound(format!(\n \"Formula '{name}' not found in cache\"\n )));\n }\n Err(e) => tracing::debug!(\n \"Cache file 'formula.json' not found or failed to load ({}). Fetching from API.\",\n e\n ),\n }\n tracing::debug!(\"Fetching formula '{}' directly from API\", name);\n // api::fetch_formula returns Value directly now\n let value = api::fetch_formula(name).await?;\n // Store in cache if fetched successfully\n // Note: This might overwrite the full list cache, consider storing individual files or a map\n // cache.store_raw(&format!(\"formula/{}.json\", name), &value.to_string())?; // Example of\n // storing individually\n Ok(value)\n}\n\n/// Retrieves cask information from the cache or API\nasync fn get_cask_info(cache: Arc, name: &str) -> Result {\n match cache.load_raw(\"cask.json\") {\n Ok(cask_data) => {\n let casks: Vec = serde_json::from_str(&cask_data).map_err(SpsError::from)?;\n for cask in casks {\n if let Some(token) = cask.get(\"token\").and_then(Value::as_str) {\n if token == name {\n return Ok(cask);\n }\n }\n // Check aliases if needed\n if let Some(aliases) = cask.get(\"aliases\").and_then(|a| a.as_array()) {\n if aliases.iter().any(|a| a.as_str() == Some(name)) {\n return Ok(cask);\n }\n }\n }\n tracing::debug!(\"Cask '{}' not found within cached 'cask.json'.\", name);\n // Explicitly return NotFound if not in cache\n return Err(SpsError::NotFound(format!(\n \"Cask '{name}' not found in cache\"\n )));\n }\n Err(e) => tracing::debug!(\n \"Cache file 'cask.json' not found or failed to load ({}). Fetching from API.\",\n e\n ),\n }\n tracing::debug!(\"Fetching cask '{}' directly from API\", name);\n // api::fetch_cask returns Value directly now\n let value = api::fetch_cask(name).await?;\n // Store in cache if fetched successfully\n // cache.store_raw(&format!(\"cask/{}.json\", name), &value.to_string())?; // Example of storing\n // individually\n Ok(value)\n}\n\n/// Prints formula information in a formatted table\nfn print_formula_info(_name: &str, formula: &Value) {\n // Basic info extraction\n let full_name = formula\n .get(\"full_name\")\n .and_then(|f| f.as_str())\n .unwrap_or(\"N/A\");\n let version = formula\n .get(\"versions\")\n .and_then(|v| v.get(\"stable\"))\n .and_then(|s| s.as_str())\n .unwrap_or(\"N/A\");\n let revision = formula\n .get(\"revision\")\n .and_then(|r| r.as_u64())\n .unwrap_or(0);\n let version_str = if revision > 0 {\n format!(\"{version}_{revision}\")\n } else {\n version.to_string()\n };\n let license = formula\n .get(\"license\")\n .and_then(|l| l.as_str())\n .unwrap_or(\"N/A\");\n let homepage = formula\n .get(\"homepage\")\n .and_then(|h| h.as_str())\n .unwrap_or(\"N/A\");\n\n // Header\n println!(\"{}\", format!(\"Formula: {full_name}\").green().bold());\n\n // Summary table\n let mut table = prettytable::Table::new();\n table.set_format(*prettytable::format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n table.add_row(prettytable::row![\"Version\", version_str]);\n table.add_row(prettytable::row![\"License\", license]);\n table.add_row(prettytable::row![\"Homepage\", homepage]);\n table.printstd();\n\n // Detailed sections\n if let Some(desc) = formula.get(\"desc\").and_then(|d| d.as_str()) {\n if !desc.is_empty() {\n println!(\"\\n{}\", \"Description\".blue().bold());\n println!(\"{desc}\");\n }\n }\n if let Some(caveats) = formula.get(\"caveats\").and_then(|c| c.as_str()) {\n if !caveats.is_empty() {\n println!(\"\\n{}\", \"Caveats\".blue().bold());\n println!(\"{caveats}\");\n }\n }\n\n // Combined Dependencies Section\n let mut dep_table = prettytable::Table::new();\n dep_table.set_format(*prettytable::format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n let mut has_deps = false;\n\n let mut add_deps = |title: &str, key: &str, tag: &str| {\n if let Some(deps) = formula.get(key).and_then(|d| d.as_array()) {\n let dep_list: Vec<&str> = deps.iter().filter_map(|d| d.as_str()).collect();\n if !dep_list.is_empty() {\n has_deps = true;\n for (i, d) in dep_list.iter().enumerate() {\n let display_title = if i == 0 { title } else { \"\" };\n let display_tag = if i == 0 {\n format!(\"({tag})\")\n } else {\n \"\".to_string()\n };\n dep_table.add_row(prettytable::row![display_title, d, display_tag]);\n }\n }\n }\n };\n\n add_deps(\"Required\", \"dependencies\", \"runtime\");\n add_deps(\n \"Recommended\",\n \"recommended_dependencies\",\n \"runtime, recommended\",\n );\n add_deps(\"Optional\", \"optional_dependencies\", \"runtime, optional\");\n add_deps(\"Build\", \"build_dependencies\", \"build\");\n add_deps(\"Test\", \"test_dependencies\", \"test\");\n\n if has_deps {\n println!(\"\\n{}\", \"Dependencies\".blue().bold());\n dep_table.printstd();\n }\n\n // Installation hint\n println!(\"\\n{}\", \"Installation\".blue().bold());\n println!(\n \" {} install {}\",\n \"sps\".cyan(),\n formula\n .get(\"name\")\n .and_then(|n| n.as_str())\n .unwrap_or(full_name) // Use short name if available\n );\n}\n\n/// Prints cask information in a formatted table\nfn print_cask_info(name: &str, cask: &Value) {\n // Header\n println!(\"{}\", format!(\"Cask: {name}\").green().bold());\n\n // Summary table\n let mut table = prettytable::Table::new();\n table.set_format(*prettytable::format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n if let Some(names) = cask.get(\"name\").and_then(|n| n.as_array()) {\n if let Some(first) = names.first().and_then(|s| s.as_str()) {\n table.add_row(prettytable::row![\"Name\", first]);\n }\n }\n if let Some(desc) = cask.get(\"desc\").and_then(|d| d.as_str()) {\n table.add_row(prettytable::row![\"Description\", desc]);\n }\n if let Some(homepage) = cask.get(\"homepage\").and_then(|h| h.as_str()) {\n table.add_row(prettytable::row![\"Homepage\", homepage]);\n }\n if let Some(version) = cask.get(\"version\").and_then(|v| v.as_str()) {\n table.add_row(prettytable::row![\"Version\", version]);\n }\n if let Some(url) = cask.get(\"url\").and_then(|u| u.as_str()) {\n table.add_row(prettytable::row![\"Download URL\", url]);\n }\n // Add SHA if present\n if let Some(sha) = cask.get(\"sha256\").and_then(|s| s.as_str()) {\n if !sha.is_empty() {\n table.add_row(prettytable::row![\"SHA256\", sha]);\n }\n }\n table.printstd();\n\n // Dependencies Section\n if let Some(deps) = cask.get(\"depends_on\").and_then(|d| d.as_object()) {\n let mut dep_table = prettytable::Table::new();\n dep_table.set_format(*prettytable::format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n let mut has_deps = false;\n\n if let Some(formulas) = deps.get(\"formula\").and_then(|f| f.as_array()) {\n if !formulas.is_empty() {\n has_deps = true;\n dep_table.add_row(prettytable::row![\n \"Formula\".yellow(),\n formulas\n .iter()\n .map(|v| v.as_str().unwrap_or(\"\"))\n .collect::>()\n .join(\", \")\n ]);\n }\n }\n if let Some(casks) = deps.get(\"cask\").and_then(|c| c.as_array()) {\n if !casks.is_empty() {\n has_deps = true;\n dep_table.add_row(prettytable::row![\n \"Cask\".yellow(),\n casks\n .iter()\n .map(|v| v.as_str().unwrap_or(\"\"))\n .collect::>()\n .join(\", \")\n ]);\n }\n }\n if let Some(macos) = deps.get(\"macos\") {\n has_deps = true;\n let macos_str = match macos {\n Value::String(s) => s.clone(),\n Value::Array(arr) => arr\n .iter()\n .map(|v| v.as_str().unwrap_or(\"\"))\n .collect::>()\n .join(\" or \"),\n _ => \"Unknown\".to_string(),\n };\n dep_table.add_row(prettytable::row![\"macOS\".yellow(), macos_str]);\n }\n\n if has_deps {\n println!(\"\\n{}\", \"Dependencies\".blue().bold());\n dep_table.printstd();\n }\n }\n\n // Installation hint\n println!(\"\\n{}\", \"Installation\".blue().bold());\n println!(\n \" {} install --cask {}\", // Always use --cask for clarity\n \"sps\".cyan(),\n name // Use the token 'name' passed to the function\n );\n}\n// Removed is_bottle_available check\n"], ["/sps/sps/src/cli/list.rs", "use std::sync::Arc;\n\nuse clap::Args;\nuse colored::Colorize;\nuse prettytable::{format, Cell, Row, Table};\nuse serde_json::Value;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::formulary::Formulary;\nuse sps_core::check::installed::{get_installed_packages, PackageType};\nuse sps_core::check::update::check_for_updates;\nuse sps_core::check::InstalledPackageInfo;\n\n#[derive(Args, Debug)]\npub struct List {\n /// Show only formulas\n #[arg(long = \"formula\")]\n pub formula_only: bool,\n /// Show only casks\n #[arg(long = \"cask\")]\n pub cask_only: bool,\n /// Show only packages with updates available\n #[arg(long = \"outdated\")]\n pub outdated_only: bool,\n}\n\nimpl List {\n pub async fn run(&self, config: &Config, cache: Arc) -> Result<()> {\n let installed = get_installed_packages(config).await?;\n // Only show the latest version for each name\n use std::collections::HashMap;\n let mut formula_map: HashMap<&str, &sps_core::check::installed::InstalledPackageInfo> =\n HashMap::new();\n let mut cask_map: HashMap<&str, &sps_core::check::installed::InstalledPackageInfo> =\n HashMap::new();\n for pkg in &installed {\n match pkg.pkg_type {\n PackageType::Formula => {\n let entry = formula_map.entry(pkg.name.as_str()).or_insert(pkg);\n if pkg.version > entry.version {\n formula_map.insert(pkg.name.as_str(), pkg);\n }\n }\n PackageType::Cask => {\n let entry = cask_map.entry(pkg.name.as_str()).or_insert(pkg);\n if pkg.version > entry.version {\n cask_map.insert(pkg.name.as_str(), pkg);\n }\n }\n }\n }\n let mut formulas: Vec<&InstalledPackageInfo> = formula_map.values().copied().collect();\n let mut casks: Vec<&InstalledPackageInfo> = cask_map.values().copied().collect();\n // Sort formulas and casks alphabetically by name, then version\n formulas.sort_by(|a, b| a.name.cmp(&b.name).then(a.version.cmp(&b.version)));\n casks.sort_by(|a, b| a.name.cmp(&b.name).then(a.version.cmp(&b.version)));\n // If Nothing Installed.\n if formulas.is_empty() && casks.is_empty() {\n println!(\"{}\", \"0 formulas and casks installed\".yellow());\n return Ok(());\n }\n // If user wants to show installed formulas only.\n if self.formula_only {\n if self.outdated_only {\n self.print_outdated_formulas_table(&formulas, config)\n .await?;\n } else {\n self.print_formulas_table(formulas, config);\n }\n return Ok(());\n }\n // If user wants to show installed casks only.\n if self.cask_only {\n if self.outdated_only {\n self.print_outdated_casks_table(&casks, cache.clone())\n .await?;\n } else {\n self.print_casks_table(casks, cache);\n }\n return Ok(());\n }\n\n // If user wants to show only outdated packages\n if self.outdated_only {\n self.print_outdated_all_table(&formulas, &casks, config, cache)\n .await?;\n return Ok(());\n }\n\n // Default Implementation\n let formulary = Formulary::new(config.clone());\n let mut table = Table::new();\n table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n table.add_row(Row::new(vec![\n Cell::new(\"Type\").style_spec(\"b\"),\n Cell::new(\"Name\").style_spec(\"b\"),\n Cell::new(\"Installed\").style_spec(\"b\"),\n Cell::new(\"New Version?\").style_spec(\"b\"),\n ]));\n let mut formula_count = 0;\n let mut cask_count = 0;\n for pkg in formulas {\n let latest = formulary.load_formula(&pkg.name).ok();\n let (has_new, _) = match latest {\n Some(ref f) => {\n let latest_version = f.version_str_full();\n (latest_version != pkg.version, latest_version)\n }\n None => (false, \"-\".to_string()),\n };\n table.add_row(Row::new(vec![\n Cell::new(\"Formula\").style_spec(\"Fg\"),\n Cell::new(&pkg.name).style_spec(\"Fb\"),\n Cell::new(&pkg.version),\n // TODO: update to display the latest version string.\n // TODO: Not showing when the using --all flag.\n Cell::new(if has_new { \"✔\" } else { \"\" }),\n ]));\n formula_count += 1;\n }\n for pkg in casks {\n // Try to load cask info from cache\n let cask_val = cache.load_raw(\"cask.json\").ok().and_then(|raw| {\n serde_json::from_str::>(&raw)\n .ok()?\n .into_iter()\n .find(|v| v.get(\"token\").and_then(|t| t.as_str()) == Some(&pkg.name))\n });\n let (has_new, _) = match cask_val {\n Some(ref v) => {\n let latest_version = v.get(\"version\").and_then(|v| v.as_str()).unwrap_or(\"-\");\n (latest_version != pkg.version, latest_version.to_string())\n }\n None => (false, \"-\".to_string()),\n };\n table.add_row(Row::new(vec![\n Cell::new(\"Cask\").style_spec(\"Fy\"),\n Cell::new(&pkg.name).style_spec(\"Fb\"),\n Cell::new(&pkg.version),\n Cell::new(if has_new { \"✔\" } else { \"\" }),\n ]));\n cask_count += 1;\n }\n table.printstd();\n if formula_count > 0 && cask_count > 0 {\n println!(\n \"{}\",\n format!(\"{formula_count} formulas, {cask_count} casks installed\").bold()\n );\n } else if formula_count > 0 {\n println!(\"{}\", format!(\"{formula_count} formulas installed\").bold());\n } else if cask_count > 0 {\n println!(\"{}\", format!(\"{cask_count} casks installed\").bold());\n }\n Ok(())\n }\n\n fn print_formulas_table(\n &self,\n formulas: Vec<&sps_core::check::installed::InstalledPackageInfo>,\n config: &Config,\n ) {\n if formulas.is_empty() {\n println!(\"No formulas installed.\");\n return;\n }\n let formulary = Formulary::new(config.clone());\n let mut table = Table::new();\n table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n // Add header row with \"Formulas\" spanning all columns, font color green\n table.add_row(Row::new(vec![Cell::new_align(\n \"Formulas\",\n format::Alignment::CENTER,\n )\n .style_spec(\"bFg\")\n .with_hspan(3)]));\n table.add_row(Row::new(vec![\n Cell::new(\"Name\").style_spec(\"b\"),\n Cell::new(\"Installed\").style_spec(\"b\"),\n Cell::new(\"New Version?\").style_spec(\"b\"),\n ]));\n let mut formula_count = 0;\n for pkg in formulas {\n let latest = formulary.load_formula(&pkg.name).ok();\n let (has_new, _) = match latest {\n Some(ref f) => {\n let latest_version = f.version_str_full();\n (latest_version != pkg.version, latest_version)\n }\n None => (false, \"-\".to_string()),\n };\n table.add_row(Row::new(vec![\n Cell::new(&pkg.name).style_spec(\"Fb\"),\n Cell::new(&pkg.version),\n Cell::new(if has_new { \"✔\" } else { \"\" }),\n ]));\n formula_count += 1;\n }\n table.printstd();\n println!(\"{}\", format!(\"{formula_count} formulas installed\").bold());\n }\n\n fn print_casks_table(\n &self,\n casks: Vec<&sps_core::check::installed::InstalledPackageInfo>,\n cache: Arc,\n ) {\n if casks.is_empty() {\n println!(\"No casks installed.\");\n return;\n }\n let mut table = Table::new();\n table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n // Add header row with \"Casks\" spanning all columns, font color green\n table.add_row(Row::new(vec![Cell::new_align(\n \"Casks\",\n format::Alignment::CENTER,\n )\n .style_spec(\"bFg\")\n .with_hspan(3)]));\n table.add_row(Row::new(vec![\n Cell::new(\"Name\").style_spec(\"b\"),\n Cell::new(\"Installed\").style_spec(\"b\"),\n Cell::new(\"New Version?\").style_spec(\"b\"),\n ]));\n let mut cask_count = 0;\n for pkg in casks {\n // Try to load cask info from cache\n let cask_val = cache.load_raw(\"cask.json\").ok().and_then(|raw| {\n serde_json::from_str::>(&raw)\n .ok()?\n .into_iter()\n .find(|v| v.get(\"token\").and_then(|t| t.as_str()) == Some(&pkg.name))\n });\n let (has_new, _) = match cask_val {\n Some(ref v) => {\n let latest_version = v.get(\"version\").and_then(|v| v.as_str()).unwrap_or(\"-\");\n (latest_version != pkg.version, latest_version.to_string())\n }\n None => (false, \"-\".to_string()),\n };\n table.add_row(Row::new(vec![\n Cell::new(&pkg.name).style_spec(\"Fb\"),\n Cell::new(&pkg.version),\n Cell::new(if has_new { \"✔\" } else { \"\" }),\n ]));\n cask_count += 1;\n }\n table.printstd();\n println!(\"{}\", format!(\"{cask_count} casks installed\").bold());\n }\n\n async fn print_outdated_formulas_table(\n &self,\n formulas: &[&InstalledPackageInfo],\n config: &Config,\n ) -> Result<()> {\n if formulas.is_empty() {\n println!(\"No formulas installed.\");\n return Ok(());\n }\n\n // Convert to owned for update checking\n let formula_packages: Vec =\n formulas.iter().map(|&f| f.clone()).collect();\n let cache = sps_common::cache::Cache::new(config)?;\n let updates = check_for_updates(&formula_packages, &cache, config).await?;\n\n if updates.is_empty() {\n println!(\"No formula updates available.\");\n return Ok(());\n }\n\n let mut table = Table::new();\n table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n table.add_row(Row::new(vec![Cell::new_align(\n \"Outdated Formulas\",\n format::Alignment::CENTER,\n )\n .style_spec(\"bFg\")\n .with_hspan(3)]));\n table.add_row(Row::new(vec![\n Cell::new(\"Name\").style_spec(\"b\"),\n Cell::new(\"Installed\").style_spec(\"b\"),\n Cell::new(\"Available\").style_spec(\"b\"),\n ]));\n\n let mut count = 0;\n for update in updates {\n table.add_row(Row::new(vec![\n Cell::new(&update.name).style_spec(\"Fb\"),\n Cell::new(&update.installed_version),\n Cell::new(&update.available_version).style_spec(\"Fg\"),\n ]));\n count += 1;\n }\n\n table.printstd();\n println!(\"{}\", format!(\"{count} outdated formulas\").bold());\n Ok(())\n }\n\n async fn print_outdated_casks_table(\n &self,\n casks: &[&InstalledPackageInfo],\n cache: Arc,\n ) -> Result<()> {\n if casks.is_empty() {\n println!(\"No casks installed.\");\n return Ok(());\n }\n\n // Convert to owned for update checking\n let cask_packages: Vec = casks.iter().map(|&c| c.clone()).collect();\n let config = cache.config();\n let updates = check_for_updates(&cask_packages, &cache, config).await?;\n\n if updates.is_empty() {\n println!(\"No cask updates available.\");\n return Ok(());\n }\n\n let mut table = Table::new();\n table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n table.add_row(Row::new(vec![Cell::new_align(\n \"Outdated Casks\",\n format::Alignment::CENTER,\n )\n .style_spec(\"bFg\")\n .with_hspan(3)]));\n table.add_row(Row::new(vec![\n Cell::new(\"Name\").style_spec(\"b\"),\n Cell::new(\"Installed\").style_spec(\"b\"),\n Cell::new(\"Available\").style_spec(\"b\"),\n ]));\n\n let mut count = 0;\n for update in updates {\n table.add_row(Row::new(vec![\n Cell::new(&update.name).style_spec(\"Fb\"),\n Cell::new(&update.installed_version),\n Cell::new(&update.available_version).style_spec(\"Fy\"),\n ]));\n count += 1;\n }\n\n table.printstd();\n println!(\"{}\", format!(\"{count} outdated casks\").bold());\n Ok(())\n }\n\n async fn print_outdated_all_table(\n &self,\n formulas: &[&InstalledPackageInfo],\n casks: &[&InstalledPackageInfo],\n config: &Config,\n cache: Arc,\n ) -> Result<()> {\n // Convert to owned for update checking\n let mut all_packages: Vec = Vec::new();\n all_packages.extend(formulas.iter().map(|&f| f.clone()));\n all_packages.extend(casks.iter().map(|&c| c.clone()));\n\n if all_packages.is_empty() {\n println!(\"{}\", \"0 formulas and casks installed\".yellow());\n return Ok(());\n }\n\n let updates = check_for_updates(&all_packages, &cache, config).await?;\n\n if updates.is_empty() {\n println!(\"No outdated packages found.\");\n return Ok(());\n }\n\n let mut table = Table::new();\n table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n table.add_row(Row::new(vec![\n Cell::new(\"Type\").style_spec(\"b\"),\n Cell::new(\"Name\").style_spec(\"b\"),\n Cell::new(\"Installed\").style_spec(\"b\"),\n Cell::new(\"Available\").style_spec(\"b\"),\n ]));\n\n let mut formula_count = 0;\n let mut cask_count = 0;\n\n for update in updates {\n let (type_name, type_style) = match update.pkg_type {\n PackageType::Formula => {\n formula_count += 1;\n (\"Formula\", \"Fg\")\n }\n PackageType::Cask => {\n cask_count += 1;\n (\"Cask\", \"Fy\")\n }\n };\n\n table.add_row(Row::new(vec![\n Cell::new(type_name).style_spec(type_style),\n Cell::new(&update.name).style_spec(\"Fb\"),\n Cell::new(&update.installed_version),\n Cell::new(&update.available_version).style_spec(\"Fg\"),\n ]));\n }\n\n table.printstd();\n if formula_count > 0 && cask_count > 0 {\n println!(\n \"{}\",\n format!(\"{formula_count} outdated formulas, {cask_count} outdated casks\").bold()\n );\n } else if formula_count > 0 {\n println!(\"{}\", format!(\"{formula_count} outdated formulas\").bold());\n } else if cask_count > 0 {\n println!(\"{}\", format!(\"{cask_count} outdated casks\").bold());\n }\n Ok(())\n }\n}\n"], ["/sps/sps-core/src/upgrade/bottle.rs", "// sps-core/src/upgrade/bottle.rs\n\nuse std::path::{Path, PathBuf};\nuse std::sync::Arc;\n\nuse sps_common::config::Config;\nuse sps_common::error::{Result as SpsResult, SpsError};\nuse sps_common::model::formula::Formula;\nuse tracing::{debug, error};\n\nuse crate::check::installed::InstalledPackageInfo;\nuse crate::{install, uninstall};\n\n/// Upgrades a formula that is installed from a bottle.\n///\n/// This involves:\n/// 1. Uninstalling the old version of the formula.\n/// 2. Installing the new bottle.\n/// 3. Linking the new version.\npub async fn upgrade_bottle_formula(\n formula: &Formula,\n new_bottle_download_path: &Path,\n old_install_info: &InstalledPackageInfo,\n config: &Config,\n http_client: Arc, /* Added for download_bottle if needed, though path is\n * pre-downloaded */\n) -> SpsResult {\n debug!(\n \"Upgrading bottle formula {} from {} to {}\",\n formula.name(),\n old_install_info.version,\n formula.version_str_full()\n );\n\n // 1. Uninstall the old version\n debug!(\n \"Uninstalling old bottle version: {} at {}\",\n old_install_info.version,\n old_install_info.path.display()\n );\n let uninstall_opts = uninstall::UninstallOptions { skip_zap: true }; // Zap is not relevant for formula upgrades\n uninstall::formula::uninstall_formula_artifacts(old_install_info, config, &uninstall_opts)\n .map_err(|e| {\n error!(\n \"Failed to uninstall old version {} of formula {}: {}\",\n old_install_info.version,\n formula.name(),\n e\n );\n SpsError::InstallError(format!(\n \"Failed to uninstall old version during upgrade of {}: {e}\",\n formula.name()\n ))\n })?;\n debug!(\"Successfully uninstalled old version of {}\", formula.name());\n\n // 2. Install the new bottle\n // The new_bottle_download_path is already provided, so we call install_bottle directly.\n // If download was part of this function, http_client would be used.\n let _ = http_client; // Mark as used if not directly needed by install_bottle\n\n debug!(\n \"Installing new bottle for {} from {}\",\n formula.name(),\n new_bottle_download_path.display()\n );\n let installed_keg_path =\n install::bottle::exec::install_bottle(new_bottle_download_path, formula, config).map_err(\n |e| {\n error!(\n \"Failed to install new bottle for formula {}: {}\",\n formula.name(),\n e\n );\n SpsError::InstallError(format!(\n \"Failed to install new bottle during upgrade of {}: {e}\",\n formula.name()\n ))\n },\n )?;\n debug!(\n \"Successfully installed new bottle for {} to {}\",\n formula.name(),\n installed_keg_path.display()\n );\n\n // 3. Link the new version (linking is handled by the worker after this function returns the\n // path)\n // The install::bottle::exec::install_bottle writes the receipt, but linking is separate.\n // The worker will call link_formula_artifacts after this.\n\n Ok(installed_keg_path)\n}\n"], ["/sps/sps-net/src/api.rs", "use std::sync::Arc;\n\nuse reqwest::header::{ACCEPT, AUTHORIZATION, USER_AGENT};\nuse reqwest::Client;\nuse serde_json::Value;\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::cask::{Cask, CaskList};\nuse sps_common::model::formula::Formula;\nuse tracing::{debug, error};\n\nconst FORMULAE_API_BASE_URL: &str = \"https://formulae.brew.sh/api\";\nconst GITHUB_API_BASE_URL: &str = \"https://api.github.com\";\nconst USER_AGENT_STRING: &str = \"sps Package Manager (Rust; +https://github.com/your/sp)\";\n\nfn build_api_client(config: &Config) -> Result {\n let mut headers = reqwest::header::HeaderMap::new();\n headers.insert(USER_AGENT, USER_AGENT_STRING.parse().unwrap());\n headers.insert(ACCEPT, \"application/vnd.github+json\".parse().unwrap());\n if let Some(token) = &config.github_api_token {\n debug!(\"Adding GitHub API token to request headers.\");\n match format!(\"Bearer {token}\").parse() {\n Ok(val) => {\n headers.insert(AUTHORIZATION, val);\n }\n Err(e) => {\n error!(\"Failed to parse GitHub API token into header value: {}\", e);\n }\n }\n } else {\n debug!(\"No GitHub API token found in config.\");\n }\n Ok(Client::builder().default_headers(headers).build()?)\n}\n\npub async fn fetch_raw_formulae_json(endpoint: &str) -> Result {\n let url = format!(\"{FORMULAE_API_BASE_URL}/{endpoint}\");\n debug!(\"Fetching data from Homebrew Formulae API: {}\", url);\n let client = reqwest::Client::builder()\n .user_agent(USER_AGENT_STRING)\n .build()?;\n let response = client.get(&url).send().await.map_err(|e| {\n debug!(\"HTTP request failed for {}: {}\", url, e);\n SpsError::Http(Arc::new(e))\n })?;\n if !response.status().is_success() {\n let status = response.status();\n let body = response\n .text()\n .await\n .unwrap_or_else(|e| format!(\"(Failed to read response body: {e})\"));\n debug!(\n \"HTTP request to {} returned non-success status: {}\",\n url, status\n );\n debug!(\"Response body for failed request to {}: {}\", url, body);\n return Err(SpsError::Api(format!(\"HTTP status {status} from {url}\")));\n }\n let body = response.text().await?;\n if body.trim().is_empty() {\n error!(\"Response body for {} was empty.\", url);\n return Err(SpsError::Api(format!(\n \"Empty response body received from {url}\"\n )));\n }\n Ok(body)\n}\n\npub async fn fetch_all_formulas() -> Result {\n fetch_raw_formulae_json(\"formula.json\").await\n}\n\npub async fn fetch_all_casks() -> Result {\n fetch_raw_formulae_json(\"cask.json\").await\n}\n\npub async fn fetch_formula(name: &str) -> Result {\n let direct_fetch_result = fetch_raw_formulae_json(&format!(\"formula/{name}.json\")).await;\n if let Ok(body) = direct_fetch_result {\n let formula: serde_json::Value = serde_json::from_str(&body)?;\n Ok(formula)\n } else {\n debug!(\n \"Direct fetch for formula '{}' failed ({:?}). Fetching full list as fallback.\",\n name,\n direct_fetch_result.err()\n );\n let all_formulas_body = fetch_all_formulas().await?;\n let formulas: Vec = serde_json::from_str(&all_formulas_body)?;\n for formula in formulas {\n if formula.get(\"name\").and_then(Value::as_str) == Some(name) {\n return Ok(formula);\n }\n if formula.get(\"full_name\").and_then(Value::as_str) == Some(name) {\n return Ok(formula);\n }\n }\n Err(SpsError::NotFound(format!(\n \"Formula '{name}' not found in API list\"\n )))\n }\n}\n\npub async fn fetch_cask(token: &str) -> Result {\n let direct_fetch_result = fetch_raw_formulae_json(&format!(\"cask/{token}.json\")).await;\n if let Ok(body) = direct_fetch_result {\n let cask: serde_json::Value = serde_json::from_str(&body)?;\n Ok(cask)\n } else {\n debug!(\n \"Direct fetch for cask '{}' failed ({:?}). Fetching full list as fallback.\",\n token,\n direct_fetch_result.err()\n );\n let all_casks_body = fetch_all_casks().await?;\n let casks: Vec = serde_json::from_str(&all_casks_body)?;\n for cask in casks {\n if cask.get(\"token\").and_then(Value::as_str) == Some(token) {\n return Ok(cask);\n }\n }\n Err(SpsError::NotFound(format!(\n \"Cask '{token}' not found in API list\"\n )))\n }\n}\n\nasync fn fetch_github_api_json(endpoint: &str, config: &Config) -> Result {\n let url = format!(\"{GITHUB_API_BASE_URL}{endpoint}\");\n debug!(\"Fetching data from GitHub API: {}\", url);\n let client = build_api_client(config)?;\n let response = client.get(&url).send().await.map_err(|e| {\n error!(\"GitHub API request failed for {}: {}\", url, e);\n SpsError::Http(Arc::new(e))\n })?;\n if !response.status().is_success() {\n let status = response.status();\n let body = response\n .text()\n .await\n .unwrap_or_else(|e| format!(\"(Failed to read response body: {e})\"));\n error!(\n \"GitHub API request to {} returned non-success status: {}\",\n url, status\n );\n debug!(\n \"Response body for failed GitHub API request to {}: {}\",\n url, body\n );\n return Err(SpsError::Api(format!(\"HTTP status {status} from {url}\")));\n }\n let value: Value = response.json::().await.map_err(|e| {\n error!(\"Failed to parse JSON response from {}: {}\", url, e);\n SpsError::ApiRequestError(e.to_string())\n })?;\n Ok(value)\n}\n\n#[allow(dead_code)]\nasync fn fetch_github_repo_info(owner: &str, repo: &str, config: &Config) -> Result {\n let endpoint = format!(\"/repos/{owner}/{repo}\");\n fetch_github_api_json(&endpoint, config).await\n}\n\npub async fn get_formula(name: &str) -> Result {\n let url = format!(\"{FORMULAE_API_BASE_URL}/formula/{name}.json\");\n debug!(\n \"Fetching and parsing formula data for '{}' from {}\",\n name, url\n );\n let client = reqwest::Client::new();\n let response = client.get(&url).send().await.map_err(|e| {\n debug!(\"HTTP request failed when fetching formula {}: {}\", name, e);\n SpsError::Http(Arc::new(e))\n })?;\n let status = response.status();\n let text = response.text().await?;\n if !status.is_success() {\n debug!(\"Failed to fetch formula {} (Status {})\", name, status);\n debug!(\"Response body for failed formula fetch {}: {}\", name, text);\n return Err(SpsError::Api(format!(\n \"Failed to fetch formula {name}: Status {status}\"\n )));\n }\n if text.trim().is_empty() {\n error!(\"Received empty body when fetching formula {}\", name);\n return Err(SpsError::Api(format!(\n \"Empty response body for formula {name}\"\n )));\n }\n match serde_json::from_str::(&text) {\n Ok(formula) => Ok(formula),\n Err(_) => match serde_json::from_str::>(&text) {\n Ok(mut formulas) if !formulas.is_empty() => {\n debug!(\n \"Parsed formula {} from a single-element array response.\",\n name\n );\n Ok(formulas.remove(0))\n }\n Ok(_) => {\n error!(\"Received empty array when fetching formula {}\", name);\n Err(SpsError::NotFound(format!(\n \"Formula '{name}' not found (empty array returned)\"\n )))\n }\n Err(e_vec) => {\n error!(\n \"Failed to parse formula {} as object or array. Error: {}. Body (sample): {}\",\n name,\n e_vec,\n text.chars().take(500).collect::()\n );\n Err(SpsError::Json(Arc::new(e_vec)))\n }\n },\n }\n}\n\npub async fn get_all_formulas() -> Result> {\n let raw_data = fetch_all_formulas().await?;\n serde_json::from_str(&raw_data).map_err(|e| {\n error!(\"Failed to parse all_formulas response: {}\", e);\n SpsError::Json(Arc::new(e))\n })\n}\n\npub async fn get_cask(name: &str) -> Result {\n let raw_json_result = fetch_cask(name).await;\n let raw_json = match raw_json_result {\n Ok(json_val) => json_val,\n Err(e) => {\n error!(\"Failed to fetch raw JSON for cask {}: {}\", name, e);\n return Err(e);\n }\n };\n match serde_json::from_value::(raw_json.clone()) {\n Ok(cask) => Ok(cask),\n Err(e) => {\n error!(\"Failed to parse cask {} JSON: {}\", name, e);\n match serde_json::to_string_pretty(&raw_json) {\n Ok(json_str) => {\n tracing::debug!(\"Problematic JSON for cask '{}':\\n{}\", name, json_str);\n }\n Err(fmt_err) => {\n tracing::debug!(\n \"Could not pretty-print problematic JSON for cask {}: {}\",\n name,\n fmt_err\n );\n tracing::debug!(\"Raw problematic value: {:?}\", raw_json);\n }\n }\n Err(SpsError::Json(Arc::new(e)))\n }\n }\n}\n\npub async fn get_all_casks() -> Result {\n let raw_data = fetch_all_casks().await?;\n let casks: Vec = serde_json::from_str(&raw_data).map_err(|e| {\n error!(\"Failed to parse all_casks response: {}\", e);\n SpsError::Json(Arc::new(e))\n })?;\n Ok(CaskList { casks })\n}\n"], ["/sps/sps/src/cli/search.rs", "use std::sync::Arc;\n\nuse clap::Args;\nuse colored::Colorize;\nuse prettytable::{format, Cell, Row, Table};\nuse serde_json::Value;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_net::api;\nuse terminal_size::{terminal_size, Width};\nuse unicode_width::{UnicodeWidthChar, UnicodeWidthStr};\n\n#[derive(Args, Debug)]\npub struct Search {\n pub query: String,\n #[arg(long, conflicts_with = \"cask\")]\n pub formula: bool,\n #[arg(long, conflicts_with = \"formula\")]\n pub cask: bool,\n}\n\npub enum SearchType {\n All,\n Formula,\n Cask,\n}\n\nimpl Search {\n pub async fn run(&self, config: &Config, cache: Arc) -> Result<()> {\n let search_type = if self.formula {\n SearchType::Formula\n } else if self.cask {\n SearchType::Cask\n } else {\n SearchType::All\n };\n run_search(&self.query, search_type, config, cache).await\n }\n}\n\npub async fn run_search(\n query: &str,\n search_type: SearchType,\n _config: &Config,\n cache: Arc,\n) -> Result<()> {\n tracing::debug!(\"Searching for packages matching: {}\", query);\n\n println!(\"Searching for \\\"{query}\\\"\");\n\n let mut formula_matches = Vec::new();\n let mut cask_matches = Vec::new();\n let mut formula_err = None;\n let mut cask_err = None;\n\n if matches!(search_type, SearchType::All | SearchType::Formula) {\n match search_formulas(Arc::clone(&cache), query).await {\n Ok(matches) => formula_matches = matches,\n Err(e) => {\n tracing::error!(\"Error searching formulas: {}\", e);\n formula_err = Some(e);\n }\n }\n }\n\n if matches!(search_type, SearchType::All | SearchType::Cask) {\n match search_casks(Arc::clone(&cache), query).await {\n Ok(matches) => cask_matches = matches,\n Err(e) => {\n tracing::error!(\"Error searching casks: {}\", e);\n cask_err = Some(e);\n }\n }\n }\n\n if formula_matches.is_empty() && cask_matches.is_empty() {\n if let Some(e) = formula_err.or(cask_err) {\n return Err(e);\n }\n }\n\n print_search_results(query, &formula_matches, &cask_matches);\n\n Ok(())\n}\n\nasync fn search_formulas(cache: Arc, query: &str) -> Result> {\n let query_lower = query.to_lowercase();\n let mut matches = Vec::new();\n let mut data_source_name = \"cache\";\n\n let formula_data_result = cache.load_raw(\"formula.json\");\n\n let formulas: Vec = match formula_data_result {\n Ok(formula_data) => serde_json::from_str(&formula_data)?,\n Err(e) => {\n tracing::debug!(\"Formula cache load failed ({}), fetching from API\", e);\n data_source_name = \"API\";\n let all_formulas = api::fetch_all_formulas().await?;\n\n if let Err(cache_err) = cache.store_raw(\"formula.json\", &all_formulas) {\n tracing::warn!(\"Failed to cache formula data after fetching: {}\", cache_err);\n }\n serde_json::from_str(&all_formulas)?\n }\n };\n\n for formula in formulas {\n if is_formula_match(&formula, &query_lower) {\n matches.push(formula);\n }\n }\n\n tracing::debug!(\n \"Found {} potential formula matches from {}\",\n matches.len(),\n data_source_name\n );\n tracing::debug!(\n \"Filtered down to {} formula matches with available bottles\",\n matches.len()\n );\n\n Ok(matches)\n}\n\nasync fn search_casks(cache: Arc, query: &str) -> Result> {\n let query_lower = query.to_lowercase();\n let mut matches = Vec::new();\n let mut data_source_name = \"cache\";\n\n let cask_data_result = cache.load_raw(\"cask.json\");\n\n let casks: Vec = match cask_data_result {\n Ok(cask_data) => serde_json::from_str(&cask_data)?,\n Err(e) => {\n tracing::debug!(\"Cask cache load failed ({}), fetching from API\", e);\n data_source_name = \"API\";\n let all_casks = api::fetch_all_casks().await?;\n\n if let Err(cache_err) = cache.store_raw(\"cask.json\", &all_casks) {\n tracing::warn!(\"Failed to cache cask data after fetching: {}\", cache_err);\n }\n serde_json::from_str(&all_casks)?\n }\n };\n\n for cask in casks {\n if is_cask_match(&cask, &query_lower) {\n matches.push(cask);\n }\n }\n tracing::debug!(\n \"Found {} cask matches from {}\",\n matches.len(),\n data_source_name\n );\n Ok(matches)\n}\n\nfn is_formula_match(formula: &Value, query: &str) -> bool {\n if let Some(name) = formula.get(\"name\").and_then(|n| n.as_str()) {\n if name.to_lowercase().contains(query) {\n return true;\n }\n }\n\n if let Some(full_name) = formula.get(\"full_name\").and_then(|n| n.as_str()) {\n if full_name.to_lowercase().contains(query) {\n return true;\n }\n }\n\n if let Some(desc) = formula.get(\"desc\").and_then(|d| d.as_str()) {\n if desc.to_lowercase().contains(query) {\n return true;\n }\n }\n\n if let Some(aliases) = formula.get(\"aliases\").and_then(|a| a.as_array()) {\n for alias in aliases {\n if let Some(alias_str) = alias.as_str() {\n if alias_str.to_lowercase().contains(query) {\n return true;\n }\n }\n }\n }\n\n false\n}\n\nfn is_cask_match(cask: &Value, query: &str) -> bool {\n if let Some(token) = cask.get(\"token\").and_then(|t| t.as_str()) {\n if token.to_lowercase().contains(query) {\n return true;\n }\n }\n\n if let Some(names) = cask.get(\"name\").and_then(|n| n.as_array()) {\n for name in names {\n if let Some(name_str) = name.as_str() {\n if name_str.to_lowercase().contains(query) {\n return true;\n }\n }\n }\n }\n\n if let Some(desc) = cask.get(\"desc\").and_then(|d| d.as_str()) {\n if desc.to_lowercase().contains(query) {\n return true;\n }\n }\n\n false\n}\n\nfn truncate_vis(s: &str, max: usize) -> String {\n if UnicodeWidthStr::width(s) <= max {\n return s.to_string();\n }\n let mut w = 0;\n let mut out = String::new();\n let effective_max = if max > 0 { max } else { 1 };\n\n for ch in s.chars() {\n let cw = UnicodeWidthChar::width(ch).unwrap_or(0);\n if w + cw >= effective_max.saturating_sub(1) {\n break;\n }\n out.push(ch);\n w += cw;\n }\n out.push('…');\n out\n}\n\npub fn print_search_results(query: &str, formula_matches: &[Value], cask_matches: &[Value]) {\n let total = formula_matches.len() + cask_matches.len();\n if total == 0 {\n println!(\"{}\", format!(\"No matches found for '{query}'\").yellow());\n return;\n }\n println!(\n \"{}\",\n format!(\"Found {total} result(s) for '{query}'\").bold()\n );\n\n let term_cols = terminal_size()\n .map(|(Width(w), _)| w as usize)\n .unwrap_or(120);\n\n let type_col = 7;\n let version_col = 10;\n let sep_width = 3 * 3;\n let total_fixed = type_col + version_col + sep_width;\n\n let name_min_width = 10;\n let desc_min_width = 20;\n\n let leftover = term_cols.saturating_sub(total_fixed);\n\n let name_prop_width = leftover / 3;\n\n let name_max = std::cmp::max(name_min_width, name_prop_width);\n let desc_max = std::cmp::max(desc_min_width, leftover.saturating_sub(name_max));\n\n let name_max = std::cmp::min(name_max, leftover.saturating_sub(desc_min_width));\n let desc_max = std::cmp::min(desc_max, leftover.saturating_sub(name_max));\n\n let mut tbl = Table::new();\n tbl.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);\n\n for formula in formula_matches {\n let raw_name = formula\n .get(\"name\")\n .and_then(|n| n.as_str())\n .unwrap_or(\"Unknown\");\n let raw_desc = formula.get(\"desc\").and_then(|d| d.as_str()).unwrap_or(\"\");\n let _name = truncate_vis(raw_name, name_max);\n let desc = truncate_vis(raw_desc, desc_max);\n\n let version = get_version(formula);\n\n tbl.add_row(Row::new(vec![\n Cell::new(\"Formula\").style_spec(\"Fg\"),\n Cell::new(&_name).style_spec(\"Fb\"),\n Cell::new(version),\n Cell::new(&desc),\n ]));\n }\n\n if !formula_matches.is_empty() && !cask_matches.is_empty() {\n tbl.add_row(Row::new(vec![Cell::new(\" \").with_hspan(4)]));\n }\n\n for cask in cask_matches {\n let raw_name = cask\n .get(\"token\")\n .and_then(|t| t.as_str())\n .unwrap_or(\"Unknown\");\n let raw_desc = cask.get(\"desc\").and_then(|d| d.as_str()).unwrap_or(\"\");\n let desc = truncate_vis(raw_desc, desc_max);\n\n let version = get_cask_version(cask);\n\n tbl.add_row(Row::new(vec![\n Cell::new(\"Cask\").style_spec(\"Fy\"),\n Cell::new(raw_name).style_spec(\"Fb\"),\n Cell::new(version),\n Cell::new(&desc),\n ]));\n }\n\n tbl.printstd();\n}\n\nfn get_version(formula: &Value) -> &str {\n formula\n .get(\"versions\")\n .and_then(|v| v.get(\"stable\"))\n .and_then(|v| v.as_str())\n .unwrap_or(\"-\")\n}\n\nfn get_cask_version(cask: &Value) -> &str {\n cask.get(\"version\").and_then(|v| v.as_str()).unwrap_or(\"-\")\n}\n"], ["/sps/sps/src/pipeline/downloader.rs", "// sps/src/pipeline/downloader.rs\nuse std::fs;\nuse std::path::PathBuf;\nuse std::sync::Arc;\n\nuse reqwest::Client as HttpClient;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::model::InstallTargetIdentifier;\nuse sps_common::pipeline::{DownloadOutcome, PipelineEvent, PlannedJob};\nuse sps_common::SpsError;\nuse sps_core::{build, install};\nuse sps_net::http::ProgressCallback;\nuse sps_net::UrlField;\nuse tokio::sync::{broadcast, mpsc};\nuse tokio::task::JoinSet;\nuse tracing::{error, warn};\n\nuse super::runner::get_panic_message;\n\npub(crate) struct DownloadCoordinator {\n config: Config,\n cache: Arc,\n http_client: Arc,\n event_tx: Option>,\n}\n\nimpl DownloadCoordinator {\n pub fn new(\n config: Config,\n cache: Arc,\n http_client: Arc,\n event_tx: broadcast::Sender,\n ) -> Self {\n Self {\n config,\n cache,\n http_client,\n event_tx: Some(event_tx),\n }\n }\n\n pub async fn coordinate_downloads(\n &mut self,\n planned_jobs: Vec,\n download_outcome_tx: mpsc::Sender,\n ) -> Vec<(String, SpsError)> {\n let mut download_tasks = JoinSet::new();\n let mut critical_spawn_errors: Vec<(String, SpsError)> = Vec::new();\n\n for planned_job in planned_jobs {\n let _job_id_for_task = planned_job.target_id.clone();\n\n let task_config = self.config.clone();\n let task_cache = Arc::clone(&self.cache);\n let task_http_client = Arc::clone(&self.http_client);\n let task_event_tx = self.event_tx.as_ref().cloned();\n let outcome_tx_clone = download_outcome_tx.clone();\n let current_planned_job_for_task = planned_job.clone();\n\n download_tasks.spawn(async move {\n let job_id_in_task = current_planned_job_for_task.target_id.clone();\n let download_path_result: Result;\n\n if let Some(private_path) = current_planned_job_for_task.use_private_store_source.clone() {\n download_path_result = Ok(private_path);\n } else {\n let display_url_for_event = match ¤t_planned_job_for_task.target_definition {\n InstallTargetIdentifier::Formula(f) => {\n if !current_planned_job_for_task.is_source_build {\n sps_core::install::bottle::exec::get_bottle_for_platform(f)\n .map_or_else(|_| f.url.clone(), |(_, spec)| spec.url.clone())\n } else {\n f.url.clone()\n }\n }\n InstallTargetIdentifier::Cask(c) => match &c.url {\n Some(UrlField::Simple(s)) => s.clone(),\n Some(UrlField::WithSpec { url, .. }) => url.clone(),\n None => \"N/A (No Cask URL)\".to_string(),\n },\n };\n\n if display_url_for_event == \"N/A (No Cask URL)\"\n || (display_url_for_event.is_empty() && !current_planned_job_for_task.is_source_build)\n {\n let _err_msg = \"Download URL is missing or invalid\".to_string();\n let sps_err = SpsError::Generic(format!(\n \"Download URL is missing or invalid for job {job_id_in_task}\"\n ));\n if let Some(ref tx) = task_event_tx {\n tx.send(PipelineEvent::download_failed(\n job_id_in_task.clone(),\n display_url_for_event,\n &sps_err,\n )).ok();\n }\n download_path_result = Err(sps_err);\n } else {\n if let Some(ref tx) = task_event_tx {\n tx.send(PipelineEvent::DownloadStarted {\n target_id: job_id_in_task.clone(),\n url: display_url_for_event.clone(),\n }).ok();\n }\n\n // Create progress callback\n let progress_callback: Option = if let Some(ref tx) = task_event_tx {\n let tx_clone = tx.clone();\n let job_id_for_callback = job_id_in_task.clone();\n Some(Arc::new(move |bytes_so_far: u64, total_size: Option| {\n let _ = tx_clone.send(PipelineEvent::DownloadProgressUpdate {\n target_id: job_id_for_callback.clone(),\n bytes_so_far,\n total_size,\n });\n }))\n } else {\n None\n };\n\n let actual_download_result: Result<(PathBuf, bool), SpsError> =\n match ¤t_planned_job_for_task.target_definition {\n InstallTargetIdentifier::Formula(f) => {\n if current_planned_job_for_task.is_source_build {\n build::compile::download_source_with_progress(f, &task_config, progress_callback).await.map(|p| (p, false))\n } else {\n install::bottle::exec::download_bottle_with_progress_and_cache_info(\n f,\n &task_config,\n &task_http_client,\n progress_callback,\n )\n .await\n }\n }\n InstallTargetIdentifier::Cask(c) => {\n install::cask::download_cask_with_progress(c, task_cache.as_ref(), progress_callback).await.map(|p| (p, false))\n }\n };\n\n match actual_download_result {\n Ok((path, was_cached)) => {\n let size_bytes = fs::metadata(&path).map(|m| m.len()).unwrap_or(0);\n if let Some(ref tx) = task_event_tx {\n if was_cached {\n tx.send(PipelineEvent::DownloadCached {\n target_id: job_id_in_task.clone(),\n size_bytes,\n }).ok();\n } else {\n tx.send(PipelineEvent::DownloadFinished {\n target_id: job_id_in_task.clone(),\n path: path.clone(),\n size_bytes,\n }).ok();\n }\n }\n download_path_result = Ok(path);\n }\n Err(e) => {\n warn!(\n \"[DownloaderTask:{}] Download failed from {}: {}\",\n job_id_in_task, display_url_for_event, e\n );\n if let Some(ref tx) = task_event_tx {\n tx.send(PipelineEvent::download_failed(\n job_id_in_task.clone(),\n display_url_for_event,\n &e,\n )).ok();\n }\n download_path_result = Err(e);\n }\n }\n }\n }\n\n let outcome = DownloadOutcome {\n planned_job: current_planned_job_for_task,\n result: download_path_result,\n };\n\n if let Err(send_err) = outcome_tx_clone.send(outcome).await {\n error!(\n \"[DownloaderTask:{}] CRITICAL: Failed to send download outcome to runner: {}. Job processing will likely stall.\",\n job_id_in_task, send_err\n );\n }\n });\n }\n\n while let Some(join_result) = download_tasks.join_next().await {\n if let Err(e) = join_result {\n let panic_msg = get_panic_message(e.into_panic());\n error!(\n \"[Downloader] A download task panicked: {}. This job's outcome was not sent.\",\n panic_msg\n );\n critical_spawn_errors.push((\n \"[UnknownDownloadTaskPanic]\".to_string(),\n SpsError::Generic(format!(\"A download task panicked: {panic_msg}\")),\n ));\n }\n }\n self.event_tx = None;\n critical_spawn_errors\n }\n}\n"], ["/sps/sps-core/src/uninstall/formula.rs", "// sps-core/src/uninstall/formula.rs\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse tracing::{debug, error, warn};\n\nuse crate::check::installed::InstalledPackageInfo;\nuse crate::install; // For install::bottle::link\nuse crate::uninstall::common::{remove_filesystem_artifact, UninstallOptions};\n\npub fn uninstall_formula_artifacts(\n info: &InstalledPackageInfo,\n config: &Config,\n _options: &UninstallOptions, /* options currently unused for formula but kept for signature\n * consistency */\n) -> Result<()> {\n debug!(\n \"Uninstalling Formula artifacts for {} version {}\",\n info.name, info.version\n );\n\n // 1. Unlink artifacts\n // This function should handle removal of symlinks from /opt/sps/bin, /opt/sps/lib etc.\n // and the /opt/sps/opt/formula_name link.\n install::bottle::link::unlink_formula_artifacts(&info.name, &info.version, config)?;\n\n // 2. Remove the keg directory\n if info.path.exists() {\n debug!(\"Removing formula keg directory: {}\", info.path.display());\n // For formula kegs, we generally expect them to be owned by the user or sps,\n // but sudo might be involved if permissions were changed manually or during a problematic\n // install. Setting use_sudo to true provides a fallback, though ideally it's not\n // needed for user-owned kegs.\n let use_sudo = true;\n if !remove_filesystem_artifact(&info.path, use_sudo) {\n // Check if it still exists after the removal attempt\n if info.path.exists() {\n error!(\n \"Failed remove keg {}: Check logs for sudo errors or other filesystem issues.\",\n info.path.display()\n );\n return Err(SpsError::InstallError(format!(\n \"Failed to remove keg directory: {}\",\n info.path.display()\n )));\n } else {\n // It means remove_filesystem_artifact returned false but the dir is gone\n // (possibly removed by sudo, or a race condition if another process removed it)\n debug!(\"Keg directory successfully removed (possibly with sudo).\");\n }\n }\n } else {\n warn!(\n \"Keg directory {} not found during uninstall. It might have been already removed.\",\n info.path.display()\n );\n }\n Ok(())\n}\n"], ["/sps/sps-core/src/install/bottle/macho.rs", "// sps-core/src/build/formula/macho.rs\n// Contains Mach-O specific patching logic for bottle relocation.\n// Updated to use MachOFatFile32 and MachOFatFile64 for FAT binary parsing.\n// Refactored to separate immutable analysis from mutable patching to fix borrow checker errors.\n\nuse std::collections::HashMap;\nuse std::fs;\nuse std::io::Write; // Keep for write_patched_buffer\nuse std::path::Path;\nuse std::process::{Command as StdCommand, Stdio}; // Keep for codesign\n\n// --- Imports needed for Mach-O patching (macOS only) ---\n#[cfg(target_os = \"macos\")]\nuse object::{\n self,\n macho::{MachHeader32, MachHeader64}, // Keep for Mach-O parsing\n read::macho::{\n FatArch,\n LoadCommandVariant, // Correct import path\n MachHeader,\n MachOFatFile32,\n MachOFatFile64, // Core Mach-O types + FAT types\n MachOFile,\n },\n Endianness,\n FileKind,\n ReadRef,\n};\nuse sps_common::error::{Result, SpsError};\nuse tempfile::NamedTempFile;\nuse tracing::{debug, error};\n\n// --- Platform‑specific constants for Mach‑O magic detection ---\n#[cfg(target_os = \"macos\")]\nconst MH_MAGIC: u32 = 0xfeedface;\n#[cfg(target_os = \"macos\")]\nconst MH_MAGIC_64: u32 = 0xfeedfacf;\n#[cfg(target_os = \"macos\")]\nconst MACHO_HEADER32_SIZE: usize = 28;\n#[cfg(target_os = \"macos\")]\nconst MACHO_HEADER64_SIZE: usize = 32;\n\n/// Core patch data for **one** string replacement location inside a Mach‑O file.\n#[cfg(target_os = \"macos\")]\n#[derive(Debug, Clone)]\nstruct PatchInfo {\n absolute_offset: usize, // Offset in the entire file buffer\n allocated_len: usize, // How much space was allocated for this string\n new_path: String, // The new string to write\n}\n\n/// Container for paths that couldn't be patched due to length constraints\n#[cfg(target_os = \"macos\")]\n#[derive(Debug, Clone)]\npub struct SkippedPath {\n pub old_path: String,\n pub new_path: String,\n}\n\n/// Main entry point for Mach‑O path patching (macOS only).\n/// Returns `Ok(true)` if patches were applied, `Ok(false)` if no patches needed.\n/// Returns a tuple: (patched: bool, skipped_paths: Vec)\n#[cfg(target_os = \"macos\")]\npub fn patch_macho_file(\n path: &Path,\n replacements: &HashMap,\n) -> Result<(bool, Vec)> {\n patch_macho_file_macos(path, replacements)\n}\n\n/// Container for paths that couldn't be patched due to length constraints\n#[cfg(not(target_os = \"macos\"))]\n#[derive(Debug, Clone)]\npub struct SkippedPath {\n pub old_path: String,\n pub new_path: String,\n}\n\n/// No‑op stub for non‑macOS platforms.\n#[cfg(not(target_os = \"macos\"))]\npub fn patch_macho_file(\n _path: &Path,\n _replacements: &HashMap,\n) -> Result<(bool, Vec)> {\n Ok((false, Vec::new()))\n}\n\n/// **macOS implementation**: Tries to patch Mach‑O files by replacing placeholders.\n#[cfg(target_os = \"macos\")]\nfn patch_macho_file_macos(\n path: &Path,\n replacements: &HashMap,\n) -> Result<(bool, Vec)> {\n debug!(\"Processing potential Mach-O file: {}\", path.display());\n\n // 1) Load the entire file into memory\n let buffer = match fs::read(path) {\n Ok(data) => data,\n Err(e) => {\n debug!(\"Failed to read {}: {}\", path.display(), e);\n return Ok((false, Vec::new()));\n }\n };\n if buffer.is_empty() {\n debug!(\"Empty file: {}\", path.display());\n return Ok((false, Vec::new()));\n }\n\n // 2) Identify the file type\n let kind = match object::FileKind::parse(&*buffer) {\n Ok(k) => k,\n Err(_e) => {\n debug!(\"Not an object file: {}\", path.display());\n return Ok((false, Vec::new()));\n }\n };\n\n // 3) **Analysis phase**: collect patches + skipped paths\n let (patches, skipped_paths) = collect_macho_patches(&buffer, kind, replacements, path)?;\n\n if patches.is_empty() {\n if skipped_paths.is_empty() {\n debug!(\"No patches needed for {}\", path.display());\n } else {\n debug!(\n \"No patches applied for {} ({} paths skipped due to length)\",\n path.display(),\n skipped_paths.len()\n );\n }\n return Ok((false, skipped_paths));\n }\n\n // 4) Clone buffer and apply all patches atomically\n let mut patched_buffer = buffer;\n for patch in &patches {\n patch_path_in_buffer(\n &mut patched_buffer,\n patch.absolute_offset,\n patch.allocated_len,\n &patch.new_path,\n path,\n )?;\n }\n\n // 5) Write atomically\n write_patched_buffer(path, &patched_buffer)?;\n debug!(\"Wrote patched Mach-O: {}\", path.display());\n\n // 6) Re‑sign on Apple Silicon\n #[cfg(target_arch = \"aarch64\")]\n {\n resign_binary(path)?;\n debug!(\"Re‑signed patched binary: {}\", path.display());\n }\n\n Ok((true, skipped_paths))\n}\n\n/// ASCII magic for the start of a static `ar` archive (`!\\n`)\n#[cfg(target_os = \"macos\")]\nconst AR_MAGIC: &[u8; 8] = b\"!\\n\";\n\n/// Examine a buffer (Mach‑O or FAT) and return every patch we must apply + skipped paths.\n#[cfg(target_os = \"macos\")]\nfn collect_macho_patches(\n buffer: &[u8],\n kind: FileKind,\n replacements: &HashMap,\n path_for_log: &Path,\n) -> Result<(Vec, Vec)> {\n let mut patches = Vec::::new();\n let mut skipped_paths = Vec::::new();\n\n match kind {\n /* ---------------------------------------------------------- */\n FileKind::MachO32 => {\n let m = MachOFile::, _>::parse(buffer)?;\n let (mut p, mut s) =\n find_patches_in_commands(&m, 0, MACHO_HEADER32_SIZE, replacements, path_for_log)?;\n patches.append(&mut p);\n skipped_paths.append(&mut s);\n }\n /* ---------------------------------------------------------- */\n FileKind::MachO64 => {\n let m = MachOFile::, _>::parse(buffer)?;\n let (mut p, mut s) =\n find_patches_in_commands(&m, 0, MACHO_HEADER64_SIZE, replacements, path_for_log)?;\n patches.append(&mut p);\n skipped_paths.append(&mut s);\n }\n /* ---------------------------------------------------------- */\n FileKind::MachOFat32 => {\n let fat = MachOFatFile32::parse(buffer)?;\n for (idx, arch) in fat.arches().iter().enumerate() {\n let (off, sz) = arch.file_range();\n let slice = &buffer[off as usize..(off + sz) as usize];\n\n /* short‑circuit: static .a archive inside FAT ---------- */\n if slice.starts_with(AR_MAGIC) {\n debug!(\"[slice {}] static archive – skipped\", idx);\n continue;\n }\n\n /* decide 32 / 64 by magic ------------------------------ */\n if slice.len() >= 4 {\n let magic = u32::from_le_bytes(slice[0..4].try_into().unwrap());\n if magic == MH_MAGIC_64 {\n if let Ok(m) = MachOFile::, _>::parse(slice) {\n let (mut p, mut s) = find_patches_in_commands(\n &m,\n off as usize,\n MACHO_HEADER64_SIZE,\n replacements,\n path_for_log,\n )?;\n patches.append(&mut p);\n skipped_paths.append(&mut s);\n }\n } else if magic == MH_MAGIC {\n if let Ok(m) = MachOFile::, _>::parse(slice) {\n let (mut p, mut s) = find_patches_in_commands(\n &m,\n off as usize,\n MACHO_HEADER32_SIZE,\n replacements,\n path_for_log,\n )?;\n patches.append(&mut p);\n skipped_paths.append(&mut s);\n }\n }\n }\n }\n }\n /* ---------------------------------------------------------- */\n FileKind::MachOFat64 => {\n let fat = MachOFatFile64::parse(buffer)?;\n for (idx, arch) in fat.arches().iter().enumerate() {\n let (off, sz) = arch.file_range();\n let slice = &buffer[off as usize..(off + sz) as usize];\n\n if slice.starts_with(AR_MAGIC) {\n debug!(\"[slice {}] static archive – skipped\", idx);\n continue;\n }\n\n if slice.len() >= 4 {\n let magic = u32::from_le_bytes(slice[0..4].try_into().unwrap());\n if magic == MH_MAGIC_64 {\n if let Ok(m) = MachOFile::, _>::parse(slice) {\n let (mut p, mut s) = find_patches_in_commands(\n &m,\n off as usize,\n MACHO_HEADER64_SIZE,\n replacements,\n path_for_log,\n )?;\n patches.append(&mut p);\n skipped_paths.append(&mut s);\n }\n } else if magic == MH_MAGIC {\n if let Ok(m) = MachOFile::, _>::parse(slice) {\n let (mut p, mut s) = find_patches_in_commands(\n &m,\n off as usize,\n MACHO_HEADER32_SIZE,\n replacements,\n path_for_log,\n )?;\n patches.append(&mut p);\n skipped_paths.append(&mut s);\n }\n }\n }\n }\n }\n /* ---------------------------------------------------------- */\n _ => { /* archives & unknown kinds are ignored */ }\n }\n\n Ok((patches, skipped_paths))\n}\n\n/// Iterates through load commands of a parsed MachOFile (slice) and returns\n/// patch details + skipped paths.\n#[cfg(target_os = \"macos\")]\nfn find_patches_in_commands<'data, Mach, R>(\n macho_file: &MachOFile<'data, Mach, R>,\n slice_base_offset: usize,\n header_size: usize,\n replacements: &HashMap,\n file_path_for_log: &Path,\n) -> Result<(Vec, Vec)>\nwhere\n Mach: MachHeader,\n R: ReadRef<'data>,\n{\n let endian = macho_file.endian();\n let mut patches = Vec::new();\n let mut skipped_paths = Vec::new();\n let mut cur_off = header_size;\n\n let mut it = macho_file.macho_load_commands()?;\n while let Some(cmd) = it.next()? {\n let cmd_size = cmd.cmdsize() as usize;\n let cmd_offset = cur_off; // offset *inside this slice*\n cur_off += cmd_size;\n\n let variant = match cmd.variant() {\n Ok(v) => v,\n Err(e) => {\n tracing::warn!(\n \"Malformed load‑command in {}: {}; skipping\",\n file_path_for_log.display(),\n e\n );\n continue;\n }\n };\n\n // — which commands carry path strings we might want? —\n let path_info: Option<(u32, &[u8])> = match variant {\n LoadCommandVariant::Dylib(d) | LoadCommandVariant::IdDylib(d) => cmd\n .string(endian, d.dylib.name)\n .ok()\n .map(|bytes| (d.dylib.name.offset.get(endian), bytes)),\n LoadCommandVariant::Rpath(r) => cmd\n .string(endian, r.path)\n .ok()\n .map(|bytes| (r.path.offset.get(endian), bytes)),\n _ => None,\n };\n\n if let Some((offset_in_cmd, bytes)) = path_info {\n if let Ok(old_path) = std::str::from_utf8(bytes) {\n if let Some(new_path) = find_and_replace_placeholders(old_path, replacements) {\n let allocated = cmd_size.saturating_sub(offset_in_cmd as usize);\n\n if new_path.len() + 1 > allocated {\n // would overflow – add to skipped paths instead of throwing\n tracing::debug!(\n \"Skip patch (too long): '{}' → '{}' (alloc {} B) in {}\",\n old_path,\n new_path,\n allocated,\n file_path_for_log.display()\n );\n skipped_paths.push(SkippedPath {\n old_path: old_path.to_string(),\n new_path: new_path.clone(),\n });\n continue;\n }\n\n patches.push(PatchInfo {\n absolute_offset: slice_base_offset + cmd_offset + offset_in_cmd as usize,\n allocated_len: allocated,\n new_path,\n });\n }\n }\n }\n }\n Ok((patches, skipped_paths))\n}\n\n/// Helper to replace placeholders in a string based on the replacements map.\n/// Returns `Some(String)` with replacements if any were made, `None` otherwise.\nfn find_and_replace_placeholders(\n current_path: &str,\n replacements: &HashMap,\n) -> Option {\n let mut new_path = current_path.to_string();\n let mut path_modified = false;\n // Iterate through all placeholder/replacement pairs\n for (placeholder, replacement) in replacements {\n // Check if the current path string contains the placeholder\n if new_path.contains(placeholder) {\n // Replace all occurrences of the placeholder\n new_path = new_path.replace(placeholder, replacement);\n path_modified = true; // Mark that a change was made\n debug!(\n \" Replaced '{}' with '{}' -> '{}'\",\n placeholder, replacement, new_path\n );\n }\n }\n // Return the modified string only if changes occurred\n if path_modified {\n Some(new_path)\n } else {\n None\n }\n}\n\n/// Write a new (null‑padded) path into the mutable buffer. \n/// Assumes the caller already verified the length.\n#[cfg(target_os = \"macos\")]\nfn patch_path_in_buffer(\n buf: &mut [u8],\n abs_off: usize,\n alloc_len: usize,\n new_path: &str,\n file: &Path,\n) -> Result<()> {\n if new_path.len() + 1 > alloc_len || abs_off + alloc_len > buf.len() {\n // should never happen – just log & skip\n tracing::debug!(\n \"Patch skipped (bounds) at {} in {}\",\n abs_off,\n file.display()\n );\n return Ok(());\n }\n\n // null‑padded copy\n buf[abs_off..abs_off + new_path.len()].copy_from_slice(new_path.as_bytes());\n buf[abs_off + new_path.len()..abs_off + alloc_len].fill(0);\n\n Ok(())\n}\n\n/// Writes the patched buffer to the original path atomically using a temporary file.\n#[cfg(target_os = \"macos\")]\nfn write_patched_buffer(original_path: &Path, buffer: &[u8]) -> Result<()> {\n // Get the directory containing the original file\n let dir = original_path.parent().ok_or_else(|| {\n SpsError::Generic(format!(\n \"Cannot get parent directory for {}\",\n original_path.display()\n ))\n })?;\n // Ensure the directory exists\n fs::create_dir_all(dir).map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n\n // Create a named temporary file in the same directory to facilitate atomic rename\n let mut temp_file = NamedTempFile::new_in(dir)?;\n debug!(\n \" Writing patched buffer ({} bytes) to temporary file: {:?}\",\n buffer.len(),\n temp_file.path()\n );\n // Write the entire modified buffer to the temporary file\n temp_file.write_all(buffer)?;\n // Ensure data is flushed to the OS buffer\n temp_file.flush()?;\n // Attempt to sync data to the disk\n temp_file.as_file().sync_all()?; // Ensure data is physically written\n\n // Atomically replace the original file with the temporary file\n // persist() renames the temp file over the original path.\n temp_file.persist(original_path).map_err(|e| {\n // If persist fails, the temporary file might still exist.\n // The error 'e' contains both the temp file and the underlying IO error.\n error!(\n \" Failed to persist/rename temporary file over {}: {}\",\n original_path.display(),\n e.error // Log the underlying IO error\n );\n // Return the IO error wrapped in our error type\n SpsError::Io(std::sync::Arc::new(e.error))\n })?;\n debug!(\n \" Atomically replaced {} with patched version\",\n original_path.display()\n );\n Ok(())\n}\n\n/// Re-signs the binary using the `codesign` command-line tool.\n/// This is typically necessary on Apple Silicon (aarch64) after modifying executables.\n#[cfg(all(target_os = \"macos\", target_arch = \"aarch64\"))]\nfn resign_binary(path: &Path) -> Result<()> {\n // Suppressed: debug!(\"Re-signing patched binary: {}\", path.display());\n let status = StdCommand::new(\"codesign\")\n .args([\n \"-s\",\n \"-\",\n \"--force\",\n \"--preserve-metadata=identifier,entitlements\",\n ])\n .arg(path)\n .stdout(Stdio::null())\n .stderr(Stdio::null())\n .status() // Execute the command and get its exit status\n .map_err(|e| {\n error!(\n \" Failed to execute codesign command for {}: {}\",\n path.display(),\n e\n );\n SpsError::Io(std::sync::Arc::new(e))\n })?;\n if status.success() {\n // Suppressed: debug!(\"Successfully re-signed {}\", path.display());\n Ok(())\n } else {\n error!(\n \" codesign command failed for {} with status: {}\",\n path.display(),\n status\n );\n Err(SpsError::CodesignError(format!(\n \"Failed to re-sign patched binary {}, it may not be executable. Exit status: {}\",\n path.display(),\n status\n )))\n }\n}\n\n// No-op stub for resigning on non-Apple Silicon macOS (e.g., x86_64)\n#[cfg(all(target_os = \"macos\", not(target_arch = \"aarch64\")))]\nfn resign_binary(_path: &Path) -> Result<()> {\n // No re-signing typically needed on Intel Macs after ad-hoc patching\n Ok(())\n}\n\n// No-op stub for resigning Innovations on non-macOS platforms\n#[cfg(not(target_os = \"macos\"))]\nfn resign_binary(_path: &Path) -> Result<()> {\n // Resigning is a macOS concept\n Ok(())\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/zap.rs", "// ===== sps-core/src/build/cask/artifacts/zap.rs =====\n\nuse std::fs;\nuse std::path::{Path, PathBuf}; // Import Path\nuse std::process::{Command, Stdio};\n\nuse regex::Regex;\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::InstalledArtifact;\n\n/// Implements the `zap` stanza by performing deep-clean actions\n/// such as trash, delete, rmdir, pkgutil forget, launchctl unload,\n/// and arbitrary scripts, matching Homebrew's Cask behavior.\npub fn install_zap(cask: &Cask, config: &Config) -> Result> {\n let mut artifacts: Vec = Vec::new();\n let home = config.home_dir();\n\n if let Some(entries) = &cask.artifacts {\n for entry in entries {\n if let Some(obj) = entry.as_object() {\n if let Some(zaps) = obj.get(\"zap\").and_then(|v| v.as_array()) {\n for zap_map in zaps {\n if let Some(zap_obj) = zap_map.as_object() {\n for (key, val) in zap_obj {\n match key.as_str() {\n \"trash\" => {\n if let Some(arr) = val.as_array() {\n for item in arr.iter().filter_map(|v| v.as_str()) {\n let target = expand_tilde(item, &home); // Pass &Path\n if !is_safe_path(&target, &home) {\n debug!(\n \"Unsafe trash path {}, skipping\",\n target.display()\n );\n continue;\n }\n debug!(\"Trashing {}...\", target.display());\n let _ = Command::new(\"trash\")\n .arg(&target)\n .stdout(Stdio::null())\n .stderr(Stdio::null())\n .status();\n }\n }\n }\n \"delete\" => {\n if let Some(arr) = val.as_array() {\n for item in arr.iter().filter_map(|v| v.as_str()) {\n let target = expand_tilde(item, &home); // Pass &Path\n if !is_safe_path(&target, &home) {\n debug!(\n \"Unsafe delete path {}, skipping\",\n target.display()\n );\n continue;\n }\n debug!(\"Deleting file {}...\", target.display());\n if let Err(e) = fs::remove_file(&target) {\n if e.kind() != std::io::ErrorKind::NotFound {\n debug!(\n \"Failed to delete {}: {}\",\n target.display(),\n e\n );\n }\n }\n }\n }\n }\n \"rmdir\" => {\n if let Some(arr) = val.as_array() {\n for item in arr.iter().filter_map(|v| v.as_str()) {\n let target = expand_tilde(item, &home); // Pass &Path\n if !is_safe_path(&target, &home) {\n debug!(\n \"Unsafe rmdir path {}, skipping\",\n target.display()\n );\n continue;\n }\n debug!(\n \"Removing directory {}...\",\n target.display()\n );\n if let Err(e) = fs::remove_dir_all(&target) {\n if e.kind() != std::io::ErrorKind::NotFound {\n debug!(\n \"Failed to rmdir {}: {}\",\n target.display(),\n e\n );\n }\n }\n }\n }\n }\n \"pkgutil\" => {\n if let Some(arr) = val.as_array() {\n for item in arr.iter().filter_map(|v| v.as_str()) {\n if !is_valid_pkgid(item) {\n debug!(\n \"Invalid pkgutil id '{}', skipping\",\n item\n );\n continue;\n }\n debug!(\"Forgetting pkgutil receipt {}...\", item);\n let _ = Command::new(\"pkgutil\")\n .arg(\"--forget\")\n .arg(item)\n .stdout(Stdio::null())\n .stderr(Stdio::null())\n .status();\n artifacts.push(InstalledArtifact::PkgUtilReceipt {\n id: item.to_string(),\n });\n }\n }\n }\n \"launchctl\" => {\n if let Some(arr) = val.as_array() {\n for label in arr.iter().filter_map(|v| v.as_str()) {\n if !is_valid_label(label) {\n debug!(\n \"Invalid launchctl label '{}', skipping\",\n label\n );\n continue;\n }\n let plist = home // Use expanded home\n .join(\"Library/LaunchAgents\")\n .join(format!(\"{label}.plist\"));\n if !is_safe_path(&plist, &home) {\n debug!(\n \"Unsafe plist path {} for label {}, skipping\",\n plist.display(),\n label\n );\n continue;\n }\n debug!(\n \"Unloading launchctl {}...\",\n plist.display()\n );\n let _ = Command::new(\"launchctl\")\n .arg(\"unload\")\n .arg(&plist)\n .stdout(Stdio::null())\n .stderr(Stdio::null())\n .status();\n artifacts.push(InstalledArtifact::Launchd {\n label: label.to_string(),\n path: Some(plist),\n });\n }\n }\n }\n \"script\" => {\n if let Some(cmd) = val.as_str() {\n if !is_valid_command(cmd) {\n debug!(\n \"Invalid zap script command '{}', skipping\",\n cmd\n );\n continue;\n }\n debug!(\"Running zap script: {}...\", cmd);\n let _ = Command::new(\"sh\")\n .arg(\"-c\")\n .arg(cmd)\n .stdout(Stdio::null())\n .stderr(Stdio::null())\n .status();\n }\n }\n \"signal\" => {\n if let Some(arr) = val.as_array() {\n for cmd in arr.iter().filter_map(|v| v.as_str()) {\n if !is_valid_command(cmd) {\n debug!(\n \"Invalid signal command '{}', skipping\",\n cmd\n );\n continue;\n }\n debug!(\"Running signal command: {}...\", cmd);\n let _ = Command::new(\"sh\")\n .arg(\"-c\")\n .arg(cmd)\n .stdout(Stdio::null())\n .stderr(Stdio::null())\n .status();\n }\n }\n }\n _ => debug!(\"Unsupported zap key '{}', skipping\", key),\n }\n }\n }\n }\n // Only process the first \"zap\" stanza found\n break;\n }\n }\n }\n }\n\n Ok(artifacts)\n}\n\n// New helper functions to validate paths and strings.\nfn is_safe_path(path: &Path, home: &Path) -> bool {\n if path\n .components()\n .any(|c| matches!(c, std::path::Component::ParentDir))\n {\n return false;\n }\n let path_str = path.to_string_lossy();\n if path.is_absolute()\n && (path_str.starts_with(\"/Applications\") || path_str.starts_with(\"/Library\"))\n {\n return true;\n }\n if path.starts_with(home) {\n return true;\n }\n if path_str.contains(\"Caskroom/Cellar\") {\n return true;\n }\n false\n}\n\nfn is_valid_pkgid(pkgid: &str) -> bool {\n let re = Regex::new(r\"^[a-zA-Z0-9.-]+$\").unwrap();\n re.is_match(pkgid)\n}\n\nfn is_valid_label(label: &str) -> bool {\n let re = Regex::new(r\"^[a-zA-Z0-9.-]+$\").unwrap();\n re.is_match(label)\n}\n\nfn is_valid_command(cmd: &str) -> bool {\n let re = Regex::new(r\"^[a-zA-Z0-9\\s\\-_./]+$\").unwrap();\n re.is_match(cmd)\n}\n\n/// Expand a path that may start with '~' to the user's home directory\nfn expand_tilde(path: &str, home: &Path) -> PathBuf {\n if let Some(stripped) = path.strip_prefix(\"~/\") {\n home.join(stripped)\n } else {\n PathBuf::from(path)\n }\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/pkg.rs", "use std::fs;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::cask::Cask;\nuse tracing::{debug, error};\n\nuse crate::install::cask::InstalledArtifact; // Artifact type alias is just Value\n\n/// Installs a PKG file and returns details of artifacts created/managed.\npub fn install_pkg_from_path(\n cask: &Cask,\n pkg_path: &Path,\n cask_version_install_path: &Path, // e.g., /opt/homebrew/Caskroom/foo/1.2.3\n _config: &Config, // Keep for potential future use\n) -> Result> {\n // <-- Return type changed\n debug!(\"Installing pkg file: {}\", pkg_path.display());\n\n if !pkg_path.exists() || !pkg_path.is_file() {\n return Err(SpsError::NotFound(format!(\n \"Package file not found or is not a file: {}\",\n pkg_path.display()\n )));\n }\n\n let pkg_name = pkg_path\n .file_name()\n .ok_or_else(|| SpsError::Generic(format!(\"Invalid pkg path: {}\", pkg_path.display())))?;\n\n // --- Prepare list for artifacts ---\n let mut installed_artifacts: Vec = Vec::new();\n\n // --- Copy PKG to Caskroom for Reference ---\n let caskroom_pkg_path = cask_version_install_path.join(pkg_name);\n debug!(\n \"Copying pkg to caskroom for reference: {}\",\n caskroom_pkg_path.display()\n );\n if let Some(parent) = caskroom_pkg_path.parent() {\n fs::create_dir_all(parent).map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed create parent dir {}: {}\", parent.display(), e),\n )))\n })?;\n }\n if let Err(e) = fs::copy(pkg_path, &caskroom_pkg_path) {\n error!(\n \"Failed to copy PKG {} to {}: {}\",\n pkg_path.display(),\n caskroom_pkg_path.display(),\n e\n );\n return Err(SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed copy PKG to caskroom: {e}\"),\n ))));\n } else {\n // Record the reference copy artifact\n installed_artifacts.push(InstalledArtifact::CaskroomReference {\n path: caskroom_pkg_path.clone(),\n });\n }\n\n // --- Run Installer ---\n debug!(\"Running installer (this may require sudo)\");\n debug!(\n \"Executing: sudo installer -pkg {} -target /\",\n pkg_path.display()\n );\n let output = Command::new(\"sudo\")\n .arg(\"installer\")\n .arg(\"-pkg\")\n .arg(pkg_path)\n .arg(\"-target\")\n .arg(\"/\")\n .output()\n .map_err(|e| {\n SpsError::Io(std::sync::Arc::new(std::io::Error::new(\n e.kind(),\n format!(\"Failed to execute sudo installer: {e}\"),\n )))\n })?;\n\n if !output.status.success() {\n let stderr = String::from_utf8_lossy(&output.stderr);\n error!(\"sudo installer failed ({}): {}\", output.status, stderr);\n // Don't clean up the reference copy here, let the main process handle directory removal on\n // failure\n return Err(SpsError::InstallError(format!(\n \"Package installation failed for {}: {}\",\n pkg_path.display(),\n stderr\n )));\n }\n debug!(\"Successfully ran installer command.\");\n let stdout = String::from_utf8_lossy(&output.stdout);\n if !stdout.trim().is_empty() {\n debug!(\"Installer stdout:\\n{}\", stdout);\n }\n\n // --- Record PkgUtil Receipts (based on cask definition) ---\n if let Some(artifacts) = &cask.artifacts {\n // artifacts is Option>\n for artifact_value in artifacts.iter() {\n if let Some(uninstall_array) =\n artifact_value.get(\"uninstall\").and_then(|v| v.as_array())\n {\n for stanza_value in uninstall_array {\n if let Some(stanza_obj) = stanza_value.as_object() {\n if let Some(pkgutil_id) = stanza_obj.get(\"pkgutil\").and_then(|v| v.as_str())\n {\n debug!(\"Found pkgutil ID to record: {}\", pkgutil_id);\n // Check for duplicates before adding\n let new_artifact = InstalledArtifact::PkgUtilReceipt {\n id: pkgutil_id.to_string(),\n };\n if !installed_artifacts.contains(&new_artifact) {\n // Need PartialEq for InstalledArtifact\n installed_artifacts.push(new_artifact);\n }\n }\n // Consider other uninstall keys like launchctl, delete?\n }\n }\n }\n // Optionally check \"zap\" stanzas too\n }\n }\n debug!(\"Successfully installed pkg: {}\", pkg_path.display());\n Ok(installed_artifacts) // <-- Return collected artifacts\n}\n"], ["/sps/sps-core/src/install/devtools.rs", "use std::env;\nuse std::path::PathBuf;\nuse std::process::{Command, Stdio};\n\nuse sps_common::error::{Result, SpsError};\nuse tracing::debug;\nuse which;\n\npub fn find_compiler(name: &str) -> Result {\n let env_var_name = match name {\n \"cc\" => \"CC\",\n \"c++\" | \"cxx\" => \"CXX\",\n _ => \"\",\n };\n if !env_var_name.is_empty() {\n if let Ok(compiler_path) = env::var(env_var_name) {\n let path = PathBuf::from(compiler_path);\n if path.is_file() {\n debug!(\n \"Using compiler from env var {}: {}\",\n env_var_name,\n path.display()\n );\n return Ok(path);\n } else {\n debug!(\n \"Env var {} points to non-existent file: {}\",\n env_var_name,\n path.display()\n );\n }\n }\n }\n\n if cfg!(target_os = \"macos\") {\n debug!(\"Attempting to find '{name}' using xcrun\");\n let output = Command::new(\"xcrun\")\n .arg(\"--find\")\n .arg(name)\n .stderr(Stdio::piped())\n .output();\n\n match output {\n Ok(out) if out.status.success() => {\n let path_str = String::from_utf8_lossy(&out.stdout).trim().to_string();\n if !path_str.is_empty() {\n let path = PathBuf::from(path_str);\n if path.is_file() {\n debug!(\"Found compiler via xcrun: {}\", path.display());\n return Ok(path);\n } else {\n debug!(\n \"xcrun found '{}' but path doesn't exist or isn't a file: {}\",\n name,\n path.display()\n );\n }\n } else {\n debug!(\"xcrun found '{name}' but returned empty path.\");\n }\n }\n Ok(out) => {\n let stderr = String::from_utf8_lossy(&out.stderr);\n debug!(\"xcrun failed to find '{}': {}\", name, stderr.trim());\n }\n Err(e) => {\n debug!(\"Failed to execute xcrun: {e}. Falling back to PATH search.\");\n }\n }\n }\n\n debug!(\"Falling back to searching PATH for '{name}'\");\n which::which(name).map_err(|e| {\n SpsError::BuildEnvError(format!(\"Failed to find compiler '{name}' on PATH: {e}\"))\n })\n}\n\npub fn find_sdk_path() -> Result {\n if cfg!(target_os = \"macos\") {\n debug!(\"Attempting to find macOS SDK path using xcrun\");\n let output = Command::new(\"xcrun\")\n .arg(\"--show-sdk-path\")\n .stderr(Stdio::piped())\n .output();\n\n match output {\n Ok(out) if out.status.success() => {\n let path_str = String::from_utf8_lossy(&out.stdout).trim().to_string();\n if path_str.is_empty() || path_str == \"/\" {\n return Err(SpsError::BuildEnvError(\n \"xcrun returned empty or invalid SDK path. Is Xcode or Command Line Tools installed correctly?\".to_string()\n ));\n }\n let sdk_path = PathBuf::from(path_str);\n if !sdk_path.exists() {\n return Err(SpsError::BuildEnvError(format!(\n \"SDK path reported by xcrun does not exist: {}\",\n sdk_path.display()\n )));\n }\n debug!(\"Found SDK path: {}\", sdk_path.display());\n Ok(sdk_path)\n }\n Ok(out) => {\n let stderr = String::from_utf8_lossy(&out.stderr);\n Err(SpsError::BuildEnvError(format!(\n \"xcrun failed to find SDK path: {}\",\n stderr.trim()\n )))\n }\n Err(e) => {\n Err(SpsError::BuildEnvError(format!(\n \"Failed to execute 'xcrun --show-sdk-path': {e}. Is Xcode or Command Line Tools installed?\"\n )))\n }\n }\n } else {\n debug!(\"Not on macOS, returning '/' as SDK path placeholder\");\n Ok(PathBuf::from(\"/\"))\n }\n}\n\npub fn get_macos_version() -> Result {\n if cfg!(target_os = \"macos\") {\n debug!(\"Attempting to get macOS version using sw_vers\");\n let output = Command::new(\"sw_vers\")\n .arg(\"-productVersion\")\n .stderr(Stdio::piped())\n .output();\n\n match output {\n Ok(out) if out.status.success() => {\n let version_full = String::from_utf8_lossy(&out.stdout).trim().to_string();\n let version_parts: Vec<&str> = version_full.split('.').collect();\n let version_short = if version_parts.len() >= 2 {\n format!(\"{}.{}\", version_parts[0], version_parts[1])\n } else {\n version_full.clone()\n };\n debug!(\"Found macOS version: {version_full} (short: {version_short})\");\n Ok(version_short)\n }\n Ok(out) => {\n let stderr = String::from_utf8_lossy(&out.stderr);\n Err(SpsError::BuildEnvError(format!(\n \"sw_vers failed to get product version: {}\",\n stderr.trim()\n )))\n }\n Err(e) => Err(SpsError::BuildEnvError(format!(\n \"Failed to execute 'sw_vers -productVersion': {e}\"\n ))),\n }\n } else {\n debug!(\"Not on macOS, returning '0.0' as version placeholder\");\n Ok(String::from(\"0.0\"))\n }\n}\n\npub fn get_arch_flag() -> String {\n if cfg!(target_os = \"macos\") {\n if cfg!(target_arch = \"x86_64\") {\n debug!(\"Detected target arch: x86_64\");\n \"-arch x86_64\".to_string()\n } else if cfg!(target_arch = \"aarch64\") {\n debug!(\"Detected target arch: aarch64 (arm64)\");\n \"-arch arm64\".to_string()\n } else {\n let arch = env::consts::ARCH;\n debug!(\n \"Unknown target architecture on macOS: {arch}, cannot determine -arch flag. Build might fail.\"\n );\n // Provide no flag in this unknown case? Or default to native?\n String::new()\n }\n } else {\n debug!(\"Not on macOS, returning empty arch flag.\");\n String::new()\n }\n}\n"], ["/sps/sps-net/src/http.rs", "use std::fs;\nuse std::path::{Path, PathBuf};\nuse std::sync::Arc;\nuse std::time::Duration;\n\nuse futures::StreamExt;\nuse reqwest::header::{HeaderMap, ACCEPT, USER_AGENT};\nuse reqwest::{Client, StatusCode};\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::formula::ResourceSpec;\nuse tokio::fs::File as TokioFile;\nuse tokio::io::AsyncWriteExt;\nuse tracing::{debug, error};\n\nuse crate::validation::{validate_url, verify_checksum};\n\npub type ProgressCallback = Arc) + Send + Sync>;\n\nconst DOWNLOAD_TIMEOUT_SECS: u64 = 300;\nconst CONNECT_TIMEOUT_SECS: u64 = 30;\nconst USER_AGENT_STRING: &str = \"sps package manager (Rust; +https://github.com/alexykn/sp)\";\n\npub async fn fetch_formula_source_or_bottle(\n formula_name: &str,\n url: &str,\n sha256_expected: &str,\n mirrors: &[String],\n config: &Config,\n) -> Result {\n fetch_formula_source_or_bottle_with_progress(\n formula_name,\n url,\n sha256_expected,\n mirrors,\n config,\n None,\n )\n .await\n}\n\npub async fn fetch_formula_source_or_bottle_with_progress(\n formula_name: &str,\n url: &str,\n sha256_expected: &str,\n mirrors: &[String],\n config: &Config,\n progress_callback: Option,\n) -> Result {\n let filename = url\n .split('/')\n .next_back()\n .map(|s| s.to_string())\n .unwrap_or_else(|| format!(\"{formula_name}-download\"));\n let cache_path = config.cache_dir().join(&filename);\n\n tracing::debug!(\n \"Preparing to fetch main resource for '{}' from URL: {}\",\n formula_name,\n url\n );\n tracing::debug!(\"Target cache path: {}\", cache_path.display());\n tracing::debug!(\"Expected SHA256: {}\", sha256_expected);\n\n if cache_path.is_file() {\n tracing::debug!(\"File exists in cache: {}\", cache_path.display());\n if !sha256_expected.is_empty() {\n match verify_checksum(&cache_path, sha256_expected) {\n Ok(_) => {\n tracing::debug!(\"Using valid cached file: {}\", cache_path.display());\n return Ok(cache_path);\n }\n Err(e) => {\n debug!(\n \"Cached file checksum mismatch ({}): {}. Redownloading.\",\n cache_path.display(),\n e\n );\n if let Err(remove_err) = fs::remove_file(&cache_path) {\n debug!(\n \"Failed to remove corrupted cached file {}: {}\",\n cache_path.display(),\n remove_err\n );\n }\n }\n }\n } else {\n tracing::debug!(\n \"Using cached file (no checksum provided): {}\",\n cache_path.display()\n );\n return Ok(cache_path);\n }\n } else {\n tracing::debug!(\"File not found in cache.\");\n }\n\n fs::create_dir_all(config.cache_dir()).map_err(|e| {\n SpsError::IoError(format!(\n \"Failed to create cache directory {}: {}\",\n config.cache_dir().display(),\n e\n ))\n })?;\n // Validate primary URL\n validate_url(url)?;\n\n let client = build_http_client()?;\n\n let urls_to_try = std::iter::once(url).chain(mirrors.iter().map(|s| s.as_str()));\n let mut last_error: Option = None;\n\n for current_url in urls_to_try {\n // Validate mirror URL\n validate_url(current_url)?;\n tracing::debug!(\"Attempting download from: {}\", current_url);\n match download_and_verify(\n &client,\n current_url,\n &cache_path,\n sha256_expected,\n progress_callback.clone(),\n )\n .await\n {\n Ok(path) => {\n tracing::debug!(\"Successfully downloaded and verified: {}\", path.display());\n return Ok(path);\n }\n Err(e) => {\n error!(\"Download attempt failed from {}: {}\", current_url, e);\n last_error = Some(e);\n }\n }\n }\n\n Err(last_error.unwrap_or_else(|| {\n SpsError::DownloadError(\n formula_name.to_string(),\n url.to_string(),\n \"All download attempts failed.\".to_string(),\n )\n }))\n}\n\npub async fn fetch_resource(\n formula_name: &str,\n resource: &ResourceSpec,\n config: &Config,\n) -> Result {\n fetch_resource_with_progress(formula_name, resource, config, None).await\n}\n\npub async fn fetch_resource_with_progress(\n formula_name: &str,\n resource: &ResourceSpec,\n config: &Config,\n progress_callback: Option,\n) -> Result {\n let resource_cache_dir = config.cache_dir().join(\"resources\");\n fs::create_dir_all(&resource_cache_dir).map_err(|e| {\n SpsError::IoError(format!(\n \"Failed to create resource cache directory {}: {}\",\n resource_cache_dir.display(),\n e\n ))\n })?;\n // Validate resource URL\n validate_url(&resource.url)?;\n\n let url_filename = resource\n .url\n .split('/')\n .next_back()\n .map(|s| s.to_string())\n .unwrap_or_else(|| format!(\"{}-download\", resource.name));\n let cache_filename = format!(\"{}-{}\", resource.name, url_filename);\n let cache_path = resource_cache_dir.join(&cache_filename);\n\n tracing::debug!(\n \"Preparing to fetch resource '{}' for formula '{}' from URL: {}\",\n resource.name,\n formula_name,\n resource.url\n );\n tracing::debug!(\"Target resource cache path: {}\", cache_path.display());\n tracing::debug!(\"Expected SHA256: {}\", resource.sha256);\n\n if cache_path.is_file() {\n tracing::debug!(\"Resource exists in cache: {}\", cache_path.display());\n match verify_checksum(&cache_path, &resource.sha256) {\n Ok(_) => {\n tracing::debug!(\"Using cached resource: {}\", cache_path.display());\n return Ok(cache_path);\n }\n Err(e) => {\n debug!(\n \"Cached resource checksum mismatch ({}): {}. Redownloading.\",\n cache_path.display(),\n e\n );\n if let Err(remove_err) = fs::remove_file(&cache_path) {\n debug!(\n \"Failed to remove corrupted cached resource file {}: {}\",\n cache_path.display(),\n remove_err\n );\n }\n }\n }\n } else {\n tracing::debug!(\"Resource not found in cache.\");\n }\n\n let client = build_http_client()?;\n match download_and_verify(\n &client,\n &resource.url,\n &cache_path,\n &resource.sha256,\n progress_callback,\n )\n .await\n {\n Ok(path) => {\n tracing::debug!(\n \"Successfully downloaded and verified resource: {}\",\n path.display()\n );\n Ok(path)\n }\n Err(e) => {\n error!(\"Resource download failed from {}: {}\", resource.url, e);\n let _ = fs::remove_file(&cache_path);\n Err(SpsError::DownloadError(\n resource.name.clone(),\n resource.url.clone(),\n format!(\"Download failed: {e}\"),\n ))\n }\n }\n}\n\nfn build_http_client() -> Result {\n let mut headers = HeaderMap::new();\n headers.insert(USER_AGENT, USER_AGENT_STRING.parse().unwrap());\n headers.insert(ACCEPT, \"*/*\".parse().unwrap());\n Client::builder()\n .timeout(Duration::from_secs(DOWNLOAD_TIMEOUT_SECS))\n .connect_timeout(Duration::from_secs(CONNECT_TIMEOUT_SECS))\n .default_headers(headers)\n .redirect(reqwest::redirect::Policy::limited(10))\n .build()\n .map_err(|e| SpsError::HttpError(format!(\"Failed to build HTTP client: {e}\")))\n}\n\nasync fn download_and_verify(\n client: &Client,\n url: &str,\n final_path: &Path,\n sha256_expected: &str,\n progress_callback: Option,\n) -> Result {\n let temp_filename = format!(\n \".{}.download\",\n final_path.file_name().unwrap_or_default().to_string_lossy()\n );\n let temp_path = final_path.with_file_name(temp_filename);\n tracing::debug!(\"Downloading to temporary path: {}\", temp_path.display());\n if temp_path.exists() {\n if let Err(e) = fs::remove_file(&temp_path) {\n tracing::warn!(\n \"Could not remove existing temporary file {}: {}\",\n temp_path.display(),\n e\n );\n }\n }\n\n let response = client.get(url).send().await.map_err(|e| {\n debug!(\"HTTP request failed for {url}: {e}\");\n SpsError::HttpError(format!(\"HTTP request failed for {url}: {e}\"))\n })?;\n let status = response.status();\n tracing::debug!(\"Received HTTP status: {} for {}\", status, url);\n\n if !status.is_success() {\n let body_text = response\n .text()\n .await\n .unwrap_or_else(|_| \"Failed to read response body\".to_string());\n tracing::error!(\"HTTP error {} for URL {}: {}\", status, url, body_text);\n return match status {\n StatusCode::NOT_FOUND => Err(SpsError::DownloadError(\n final_path\n .file_name()\n .map(|s| s.to_string_lossy().to_string())\n .unwrap_or_default(),\n url.to_string(),\n \"Resource not found (404)\".to_string(),\n )),\n StatusCode::FORBIDDEN => Err(SpsError::DownloadError(\n final_path\n .file_name()\n .map(|s| s.to_string_lossy().to_string())\n .unwrap_or_default(),\n url.to_string(),\n \"Access forbidden (403)\".to_string(),\n )),\n _ => Err(SpsError::HttpError(format!(\n \"HTTP error {status} for URL {url}: {body_text}\"\n ))),\n };\n }\n\n // Get total size from Content-Length header if available\n let total_size = response.content_length();\n\n let mut temp_file = TokioFile::create(&temp_path).await.map_err(|e| {\n SpsError::IoError(format!(\n \"Failed to create temp file {}: {}\",\n temp_path.display(),\n e\n ))\n })?;\n\n // Use bytes_stream() for chunked download with progress reporting\n let mut stream = response.bytes_stream();\n let mut bytes_downloaded = 0u64;\n\n while let Some(chunk) = stream.next().await {\n let chunk = chunk.map_err(|e| SpsError::HttpError(format!(\"Failed to read chunk: {e}\")))?;\n\n temp_file.write_all(&chunk).await.map_err(|e| {\n SpsError::IoError(format!(\n \"Failed to write chunk to {}: {}\",\n temp_path.display(),\n e\n ))\n })?;\n\n bytes_downloaded += chunk.len() as u64;\n\n // Call progress callback if provided\n if let Some(ref callback) = progress_callback {\n callback(bytes_downloaded, total_size);\n }\n }\n\n drop(temp_file);\n tracing::debug!(\"Finished writing download stream to temp file.\");\n\n if !sha256_expected.is_empty() {\n verify_checksum(&temp_path, sha256_expected)?;\n tracing::debug!(\n \"Checksum verified for temporary file: {}\",\n temp_path.display()\n );\n } else {\n tracing::warn!(\n \"Skipping checksum verification for {} - none provided.\",\n temp_path.display()\n );\n }\n\n fs::rename(&temp_path, final_path).map_err(|e| {\n SpsError::IoError(format!(\n \"Failed to move temp file {} to {}: {}\",\n temp_path.display(),\n final_path.display(),\n e\n ))\n })?;\n tracing::debug!(\n \"Moved verified file to final location: {}\",\n final_path.display()\n );\n Ok(final_path.to_path_buf())\n}\n"], ["/sps/sps-core/src/install/cask/dmg.rs", "// In sps-core/src/build/cask/dmg.rs\n\nuse std::fs;\nuse std::io::{BufRead, BufReader};\nuse std::path::{Path, PathBuf};\nuse std::process::Command;\n\nuse sps_common::error::{Result, SpsError};\nuse tracing::{debug, error}; // Added log imports\n\n// --- Keep Existing Helpers ---\npub fn mount_dmg(dmg_path: &Path) -> Result {\n debug!(\"Mounting DMG: {}\", dmg_path.display());\n let output = Command::new(\"hdiutil\")\n .arg(\"attach\")\n .arg(\"-plist\")\n .arg(\"-nobrowse\")\n .arg(\"-readonly\")\n .arg(\"-mountrandom\")\n .arg(\"/tmp\") // Consider making mount location configurable or more robust\n .arg(dmg_path)\n .output()?;\n\n if !output.status.success() {\n let stderr = String::from_utf8_lossy(&output.stderr);\n error!(\n \"hdiutil attach failed for {}: {}\",\n dmg_path.display(),\n stderr\n );\n return Err(SpsError::Generic(format!(\n \"Failed to mount DMG '{}': {}\",\n dmg_path.display(),\n stderr\n )));\n }\n\n let mount_point = parse_mount_point(&output.stdout)?;\n debug!(\"DMG mounted at: {}\", mount_point.display());\n Ok(mount_point)\n}\n\npub fn unmount_dmg(mount_point: &Path) -> Result<()> {\n debug!(\"Unmounting DMG from: {}\", mount_point.display());\n // Add logging for commands\n debug!(\"Executing: hdiutil detach -force {}\", mount_point.display());\n let output = Command::new(\"hdiutil\")\n .arg(\"detach\")\n .arg(\"-force\")\n .arg(mount_point)\n .output()?;\n\n if !output.status.success() {\n let stderr = String::from_utf8_lossy(&output.stderr);\n debug!(\n \"hdiutil detach failed ({}): {}. Trying diskutil\",\n output.status, stderr\n );\n // Add logging for fallback\n debug!(\n \"Executing: diskutil unmount force {}\",\n mount_point.display()\n );\n let diskutil_output = Command::new(\"diskutil\")\n .arg(\"unmount\")\n .arg(\"force\")\n .arg(mount_point)\n .output()?;\n\n if !diskutil_output.status.success() {\n let diskutil_stderr = String::from_utf8_lossy(&diskutil_output.stderr);\n error!(\n \"diskutil unmount force failed ({}): {}\",\n diskutil_output.status, diskutil_stderr\n );\n // Consider returning error only if both fail? Or always error on diskutil fail?\n return Err(SpsError::Generic(format!(\n \"Failed to unmount DMG '{}' using hdiutil and diskutil: {}\",\n mount_point.display(),\n diskutil_stderr\n )));\n }\n }\n debug!(\"DMG successfully unmounted\");\n Ok(())\n}\n\nfn parse_mount_point(output: &[u8]) -> Result {\n // ... (existing implementation) ...\n // Use plist crate for more robust parsing if possible in the future\n let cursor = std::io::Cursor::new(output);\n let reader = BufReader::new(cursor);\n let mut in_sys_entities = false;\n let mut in_mount_point = false;\n let mut mount_path_str: Option = None;\n\n for line_res in reader.lines() {\n let line = line_res?;\n let trimmed = line.trim();\n\n if trimmed == \"system-entities\" {\n in_sys_entities = true;\n continue;\n }\n if !in_sys_entities {\n continue;\n }\n\n if trimmed == \"mount-point\" {\n in_mount_point = true;\n continue;\n }\n\n if in_mount_point && trimmed.starts_with(\"\") && trimmed.ends_with(\"\") {\n mount_path_str = Some(\n trimmed\n .trim_start_matches(\"\")\n .trim_end_matches(\"\")\n .to_string(),\n );\n break; // Found the first mount point, assume it's the main one\n }\n\n // Reset flags if we encounter closing tags for structures containing mount-point\n if trimmed == \"\" {\n in_mount_point = false;\n }\n if trimmed == \"\" && in_sys_entities {\n // End of system-entities\n // break; // Stop searching if we leave the system-entities array\n in_sys_entities = false; // Reset this flag too\n }\n }\n\n match mount_path_str {\n Some(path_str) if !path_str.is_empty() => {\n debug!(\"Parsed mount point from plist: {}\", path_str);\n Ok(PathBuf::from(path_str))\n }\n _ => {\n error!(\"Failed to parse mount point from hdiutil plist output.\");\n // Optionally log the raw output for debugging\n // error!(\"Raw hdiutil output:\\n{}\", String::from_utf8_lossy(output));\n Err(SpsError::Generic(\n \"Failed to determine mount point from hdiutil output\".to_string(),\n ))\n }\n }\n}\n\n// --- NEW Function ---\n/// Extracts the contents of a mounted DMG to a staging directory using `ditto`.\npub fn extract_dmg_to_stage(dmg_path: &Path, stage_dir: &Path) -> Result<()> {\n let mount_point = mount_dmg(dmg_path)?;\n\n // Ensure the stage directory exists (though TempDir should handle it)\n if !stage_dir.exists() {\n fs::create_dir_all(stage_dir).map_err(|e| SpsError::Io(std::sync::Arc::new(e)))?;\n }\n\n debug!(\n \"Copying contents from DMG mount {} to stage {} using ditto\",\n mount_point.display(),\n stage_dir.display()\n );\n // Use ditto for robust copying, preserving metadata\n // ditto \n debug!(\n \"Executing: ditto {} {}\",\n mount_point.display(),\n stage_dir.display()\n );\n let ditto_output = Command::new(\"ditto\")\n .arg(&mount_point) // Source first\n .arg(stage_dir) // Then destination\n .output()?;\n\n let unmount_result = unmount_dmg(&mount_point); // Unmount regardless of ditto success\n\n if !ditto_output.status.success() {\n let stderr = String::from_utf8_lossy(&ditto_output.stderr);\n error!(\"ditto command failed ({}): {}\", ditto_output.status, stderr);\n // Also log stdout which might contain info on specific file errors\n let stdout = String::from_utf8_lossy(&ditto_output.stdout);\n if !stdout.trim().is_empty() {\n error!(\"ditto stdout: {}\", stdout);\n }\n unmount_result?; // Ensure we still return unmount error if it happened\n return Err(SpsError::Generic(format!(\n \"Failed to copy DMG contents using ditto: {stderr}\"\n )));\n }\n\n // After ditto, quarantine any .app bundles in the stage (macOS only)\n #[cfg(target_os = \"macos\")]\n {\n if let Err(e) = crate::install::extract::quarantine_extracted_apps_in_stage(\n stage_dir,\n \"sps-dmg-extractor\",\n ) {\n tracing::warn!(\n \"Error during post-DMG extraction quarantine scan for {}: {}\",\n dmg_path.display(),\n e\n );\n }\n }\n\n unmount_result // Return the result of unmounting\n}\n"], ["/sps/sps-core/src/uninstall/common.rs", "// sps-core/src/uninstall/common.rs\n\nuse std::path::{Component, Path, PathBuf};\nuse std::process::Command;\nuse std::{fs, io};\n\nuse sps_common::config::Config;\nuse tracing::{debug, error, warn};\n\n#[derive(Debug, Clone, Default)]\npub struct UninstallOptions {\n pub skip_zap: bool,\n}\n\n/// Removes a filesystem artifact (file or directory).\n///\n/// Attempts direct removal. If `use_sudo` is true and direct removal\n/// fails due to permission errors, it will attempt `sudo rm -rf`.\n///\n/// Returns `true` if the artifact is successfully removed or was already gone,\n/// `false` otherwise.\npub(crate) fn remove_filesystem_artifact(path: &Path, use_sudo: bool) -> bool {\n match path.symlink_metadata() {\n Ok(metadata) => {\n let file_type = metadata.file_type();\n // A directory is only a \"real\" directory if it's not a symlink.\n // Symlinks to directories should be removed with remove_file.\n let is_real_dir = file_type.is_dir();\n\n debug!(\n \"Removing filesystem artifact ({}) at: {}\",\n if is_real_dir {\n \"directory\"\n } else if file_type.is_symlink() {\n \"symlink\"\n } else {\n \"file\"\n },\n path.display()\n );\n\n let remove_op = || -> io::Result<()> {\n if is_real_dir {\n fs::remove_dir_all(path)\n } else {\n // This handles both files and symlinks\n fs::remove_file(path)\n }\n };\n\n if let Err(e) = remove_op() {\n if use_sudo && e.kind() == io::ErrorKind::PermissionDenied {\n warn!(\n \"Direct removal failed (Permission Denied). Trying with sudo rm -rf: {}\",\n path.display()\n );\n let output = Command::new(\"sudo\").arg(\"rm\").arg(\"-rf\").arg(path).output();\n match output {\n Ok(out) if out.status.success() => {\n debug!(\"Successfully removed {} with sudo.\", path.display());\n true\n }\n Ok(out) => {\n error!(\n \"Failed to remove {} with sudo: {}\",\n path.display(),\n String::from_utf8_lossy(&out.stderr).trim()\n );\n false\n }\n Err(sudo_err) => {\n error!(\n \"Error executing sudo rm for {}: {}\",\n path.display(),\n sudo_err\n );\n false\n }\n }\n } else if e.kind() != io::ErrorKind::NotFound {\n error!(\"Failed to remove artifact {}: {}\", path.display(), e);\n false\n } else {\n debug!(\"Artifact {} already removed.\", path.display());\n true\n }\n } else {\n debug!(\"Successfully removed artifact: {}\", path.display());\n true\n }\n }\n Err(e) if e.kind() == io::ErrorKind::NotFound => {\n debug!(\"Artifact not found (already removed?): {}\", path.display());\n true\n }\n Err(e) => {\n warn!(\n \"Failed to get metadata for artifact {}: {}\",\n path.display(),\n e\n );\n false\n }\n }\n}\n\n/// Expands a path string that may start with `~` to the user's home directory.\npub(crate) fn expand_tilde(path_str: &str, home: &Path) -> PathBuf {\n if let Some(stripped) = path_str.strip_prefix(\"~/\") {\n home.join(stripped)\n } else {\n PathBuf::from(path_str)\n }\n}\n\n/// Checks if a path is safe for zap operations.\n/// Safe paths are typically within user Library, .config, /Applications, /Library,\n/// or the sps cache directory. Root, home, /Applications, /Library themselves are not safe.\npub(crate) fn is_safe_path(path: &Path, home: &Path, config: &Config) -> bool {\n if path.components().any(|c| matches!(c, Component::ParentDir)) {\n warn!(\"Zap path rejected (contains '..'): {}\", path.display());\n return false;\n }\n let allowed_roots = [\n home.join(\"Library\"),\n home.join(\".config\"),\n PathBuf::from(\"/Applications\"),\n PathBuf::from(\"/Library\"),\n config.cache_dir().clone(),\n // Consider adding more specific allowed user dirs if necessary\n ];\n\n // Check if the path is exactly one of the top-level restricted paths\n if path == Path::new(\"/\")\n || path == home\n || path == Path::new(\"/Applications\")\n || path == Path::new(\"/Library\")\n {\n warn!(\"Zap path rejected (too broad): {}\", path.display());\n return false;\n }\n\n if allowed_roots.iter().any(|root| path.starts_with(root)) {\n return true;\n }\n\n warn!(\n \"Zap path rejected (outside allowed areas): {}\",\n path.display()\n );\n false\n}\n"], ["/sps/sps/src/main.rs", "// sps/src/main.rs\nuse std::process::{self}; // StdCommand is used\nuse std::sync::Arc;\nuse std::time::{Duration, SystemTime};\nuse std::{env, fs};\n\nuse clap::Parser;\nuse colored::Colorize;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::error::{Result as spResult, SpsError};\nuse tracing::level_filters::LevelFilter;\nuse tracing::{debug, error, warn}; // Import all necessary tracing macros\nuse tracing_subscriber::fmt::writer::MakeWriterExt;\nuse tracing_subscriber::EnvFilter;\n\nmod cli;\nmod pipeline;\n// Correctly import InitArgs via the re-export in cli.rs or directly from its module\nuse cli::{CliArgs, Command, InitArgs};\n\n// Standalone function to handle the init command logic\nasync fn run_init_command(init_args: &InitArgs, verbose_level: u8) -> spResult<()> {\n let init_level_filter = match verbose_level {\n 0 => LevelFilter::INFO,\n 1 => LevelFilter::DEBUG,\n _ => LevelFilter::TRACE,\n };\n let _ = tracing_subscriber::fmt()\n .with_max_level(init_level_filter)\n .with_writer(std::io::stderr)\n .with_ansi(true)\n .without_time()\n .try_init();\n\n let initial_config_for_path = Config::load().map_err(|e| {\n // Handle error if even basic config loading fails for path determination\n SpsError::Config(format!(\n \"Could not determine sps_root for init (config load failed): {e}\"\n ))\n })?;\n\n // Create a minimal Config struct, primarily for sps_root() and derived paths.\n let temp_config_for_init = Config {\n sps_root: initial_config_for_path.sps_root().to_path_buf(),\n api_base_url: \"https://formulae.brew.sh/api\".to_string(),\n artifact_domain: None,\n docker_registry_token: None,\n docker_registry_basic_auth: None,\n github_api_token: None,\n };\n\n init_args.run(&temp_config_for_init).await\n}\n\n#[tokio::main]\nasync fn main() -> spResult<()> {\n let cli_args = CliArgs::parse();\n\n if let Command::Init(ref init_args_ref) = cli_args.command {\n match run_init_command(init_args_ref, cli_args.verbose).await {\n Ok(_) => {\n return Ok(());\n }\n Err(e) => {\n eprintln!(\"{}: Init command failed: {:#}\", \"Error\".red().bold(), e);\n process::exit(1);\n }\n }\n }\n\n let config = Config::load().map_err(|e| {\n SpsError::Config(format!(\n \"Could not load config (have you run 'sps init'?): {e}\"\n ))\n })?;\n\n let level_filter = match cli_args.verbose {\n 0 => LevelFilter::INFO,\n 1 => LevelFilter::DEBUG,\n _ => LevelFilter::TRACE,\n };\n let max_log_level = level_filter.into_level().unwrap_or(tracing::Level::INFO);\n\n let env_filter = EnvFilter::builder()\n .with_default_directive(level_filter.into())\n .with_env_var(\"SPS_LOG\")\n .from_env_lossy();\n\n let log_dir = config.logs_dir();\n if let Err(e) = fs::create_dir_all(&log_dir) {\n eprintln!(\n \"{} Failed to create log directory {}: {} (ensure 'sps init' was successful or try with sudo for the current command if appropriate)\",\n \"Error:\".red().bold(),\n log_dir.display(),\n e\n );\n let _ = tracing_subscriber::fmt() // Use `let _ =`\n .with_env_filter(env_filter)\n .with_writer(std::io::stderr)\n .with_ansi(true)\n .without_time()\n .try_init(); // Use try_init\n } else if cli_args.verbose > 0 {\n let file_appender = tracing_appender::rolling::daily(&log_dir, \"sps.log\");\n let (non_blocking_appender, guard) = tracing_appender::non_blocking(file_appender);\n\n // For verbose mode, show debug/trace logs on stderr too\n let stderr_writer = std::io::stderr.with_max_level(max_log_level);\n let file_writer = non_blocking_appender.with_max_level(max_log_level);\n\n let _ = tracing_subscriber::fmt() // Use `let _ =`\n .with_env_filter(env_filter)\n .with_writer(stderr_writer.and(file_writer))\n .with_ansi(true)\n .without_time()\n .try_init(); // Use try_init\n\n Box::leak(Box::new(guard)); // Keep guard alive\n\n tracing::debug!(\n // This will only work if try_init above was successful for this setup\n \"Verbose logging enabled. Writing logs to: {}/sps.log\",\n log_dir.display()\n );\n } else {\n let _ = tracing_subscriber::fmt() // Use `let _ =`\n .with_env_filter(env_filter)\n .with_writer(std::io::stderr)\n .with_ansi(true)\n .without_time()\n .try_init(); // Use try_init\n }\n\n let cache = Arc::new(Cache::new(&config).map_err(|e| {\n SpsError::Cache(format!(\n \"Could not initialize cache (ensure 'sps init' was successful): {e}\"\n ))\n })?);\n\n let needs_update_check = matches!(\n cli_args.command,\n Command::Install(_) | Command::Search { .. } | Command::Info { .. } | Command::Upgrade(_)\n );\n\n if needs_update_check {\n if let Err(e) = check_and_run_auto_update(&config, Arc::clone(&cache)).await {\n error!(\"Error during auto-update check: {}\", e); // Use `error!` macro\n }\n } else {\n debug!(\n // Use `debug!` macro\n \"Skipping auto-update check for command: {:?}\",\n cli_args.command\n );\n }\n\n // Pass config and cache to the command's run method\n let command_execution_result = match &cli_args.command {\n Command::Init(_) => {\n /* This case is handled above and main exits */\n unreachable!()\n }\n _ => cli_args.command.run(&config, cache).await,\n };\n\n if let Err(e) = command_execution_result {\n // For pipeline commands (Install, Reinstall, Upgrade), errors are already\n // displayed via the status system, so only log in verbose mode\n let is_pipeline_command = matches!(\n cli_args.command,\n Command::Install(_) | Command::Reinstall(_) | Command::Upgrade(_)\n );\n\n if is_pipeline_command {\n // Only show error details in verbose mode\n if cli_args.verbose > 0 {\n error!(\"Command failed: {:#}\", e);\n eprintln!(\"{}: {:#}\", \"Error\".red().bold(), e);\n }\n } else {\n // For non-pipeline commands, show errors normally\n error!(\"Command failed: {:#}\", e);\n eprintln!(\"{}: {:#}\", \"Error\".red().bold(), e);\n }\n process::exit(1);\n }\n\n debug!(\"Command completed successfully.\"); // Use `debug!` macro\n Ok(())\n}\n\nasync fn check_and_run_auto_update(config: &Config, cache: Arc) -> spResult<()> {\n if env::var(\"SPS_NO_AUTO_UPDATE\").is_ok_and(|v| v == \"1\") {\n debug!(\"Auto-update disabled via SPS_NO_AUTO_UPDATE=1.\");\n return Ok(());\n }\n\n let default_interval_secs: u64 = 86400;\n let update_interval_secs = env::var(\"SPS_AUTO_UPDATE_SECS\")\n .ok()\n .and_then(|s| s.parse::().ok())\n .unwrap_or(default_interval_secs);\n let update_interval = Duration::from_secs(update_interval_secs);\n debug!(\"Auto-update interval: {:?}\", update_interval);\n\n let timestamp_file = config.state_dir().join(\".sps_last_update_check\");\n debug!(\"Checking timestamp file: {}\", timestamp_file.display());\n\n if let Some(parent_dir) = timestamp_file.parent() {\n if !parent_dir.exists() {\n if let Err(e) = fs::create_dir_all(parent_dir) {\n warn!(\"Could not create state directory {} as user: {}. Auto-update might rely on 'sps init' to create this with sudo.\", parent_dir.display(), e);\n }\n }\n }\n\n let mut needs_update = true;\n if timestamp_file.exists() {\n if let Ok(metadata) = fs::metadata(×tamp_file) {\n if let Ok(modified_time) = metadata.modified() {\n match SystemTime::now().duration_since(modified_time) {\n Ok(age) => {\n debug!(\"Time since last update check: {:?}\", age);\n if age < update_interval {\n needs_update = false;\n debug!(\"Auto-update interval not yet passed.\");\n } else {\n debug!(\"Auto-update interval passed.\");\n }\n }\n Err(e) => {\n warn!(\n \"Could not get duration since last update check (system time error?): {}\",\n e\n );\n }\n }\n } else {\n warn!(\n \"Could not read modification time for timestamp file: {}\",\n timestamp_file.display()\n );\n }\n } else {\n debug!(\n \"Timestamp file {} metadata could not be read. Update needed.\",\n timestamp_file.display()\n );\n }\n } else {\n debug!(\n \"Timestamp file not found at {}. Update needed.\",\n timestamp_file.display()\n );\n }\n\n if needs_update {\n println!(\n \"{}{}\",\n \"==> \".bold().blue(),\n \"Running auto-update...\".bold()\n );\n match cli::update::Update.run(config, cache).await {\n Ok(_) => {\n println!(\n \"{}{}\",\n \"==> \".bold().blue(),\n \"Auto-update successful.\".bold()\n );\n match fs::File::create(×tamp_file) {\n Ok(_) => {\n debug!(\"Updated timestamp file: {}\", timestamp_file.display());\n }\n Err(e) => {\n warn!(\n \"Failed to create or update timestamp file '{}': {}\",\n timestamp_file.display(),\n e\n );\n }\n }\n }\n Err(e) => {\n error!(\"Auto-update failed: {}\", e);\n eprintln!(\"{} Auto-update failed: {}\", \"Warning:\".yellow(), e);\n }\n }\n } else {\n debug!(\"Skipping auto-update.\");\n }\n\n Ok(())\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/binary.rs", "// ===== sps-core/src/build/cask/artifacts/binary.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Installs `binary` artifacts, which can be declared as:\n/// - a simple string: `\"foo\"` (source and target both `\"foo\"`)\n/// - a map: `{ \"source\": \"path/in/stage\", \"target\": \"name\", \"chmod\": \"0755\" }`\n/// - a map with just `\"target\"`: automatically generate a wrapper script\n///\n/// Copies or symlinks executables into the prefix bin directory,\n/// and records both the link and caskroom reference.\npub fn install_binary(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"binary\") {\n // Normalize into an array\n let arr = if let Some(arr) = entries.as_array() {\n arr.clone()\n } else {\n vec![entries.clone()]\n };\n\n let bin_dir = config.bin_dir();\n fs::create_dir_all(&bin_dir)?;\n\n for entry in arr {\n // Determine source, target, and optional chmod\n let (source_rel, target_name, chmod) = if let Some(tgt) = entry.as_str() {\n // simple form: \"foo\"\n (tgt.to_string(), tgt.to_string(), None)\n } else if let Some(m) = entry.as_object() {\n let target = m\n .get(\"target\")\n .and_then(|v| v.as_str())\n .map(String::from)\n .ok_or_else(|| {\n SpsError::InstallError(format!(\n \"Binary artifact missing 'target': {m:?}\"\n ))\n })?;\n\n let chmod = m.get(\"chmod\").and_then(|v| v.as_str()).map(String::from);\n\n // If `source` is provided, use it; otherwise generate wrapper\n let source = if let Some(src) = m.get(\"source\").and_then(|v| v.as_str())\n {\n src.to_string()\n } else {\n // generate wrapper script in caskroom\n let wrapper_name = format!(\"{target}.wrapper.sh\");\n let wrapper_path = cask_version_install_path.join(&wrapper_name);\n\n // assume the real executable lives inside the .app bundle\n let app_name = format!(\"{}.app\", cask.display_name());\n let exe_path =\n format!(\"/Applications/{app_name}/Contents/MacOS/{target}\");\n\n let script =\n format!(\"#!/usr/bin/env bash\\nexec \\\"{exe_path}\\\" \\\"$@\\\"\\n\");\n fs::write(&wrapper_path, script)?;\n Command::new(\"chmod\")\n .arg(\"+x\")\n .arg(&wrapper_path)\n .status()?;\n\n wrapper_name\n };\n\n (source, target, chmod)\n } else {\n debug!(\"Invalid binary artifact entry: {:?}\", entry);\n continue;\n };\n\n let src_path = stage_path.join(&source_rel);\n if !src_path.exists() {\n debug!(\"Binary source '{}' not found, skipping\", src_path.display());\n continue;\n }\n\n // Link into bin_dir\n let link_path = bin_dir.join(&target_name);\n let _ = fs::remove_file(&link_path);\n debug!(\n \"Linking binary '{}' → '{}'\",\n src_path.display(),\n link_path.display()\n );\n symlink(&src_path, &link_path)?;\n\n // Apply chmod if specified\n if let Some(mode) = chmod.as_deref() {\n let _ = Command::new(\"chmod\").arg(mode).arg(&link_path).status();\n }\n\n installed.push(InstalledArtifact::BinaryLink {\n link_path: link_path.clone(),\n target_path: src_path.clone(),\n });\n\n // Also create a Caskroom symlink for reference\n let caskroom_link = cask_version_install_path.join(&target_name);\n let _ = remove_path_robustly(&caskroom_link, config, true);\n symlink(&link_path, &caskroom_link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: caskroom_link,\n target_path: link_path.clone(),\n });\n }\n\n // Only one binary stanza per cask\n break;\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-common/src/formulary.rs", "use std::collections::HashMap;\nuse std::sync::Arc;\n\nuse tracing::debug;\n\nuse super::cache::Cache;\nuse super::config::Config;\nuse super::error::{Result, SpsError};\nuse super::model::formula::Formula;\n\n#[derive()]\npub struct Formulary {\n cache: Cache,\n parsed_cache: std::sync::Mutex>>,\n}\n\nimpl Formulary {\n pub fn new(config: Config) -> Self {\n let cache = Cache::new(&config).unwrap_or_else(|e| {\n panic!(\"Failed to initialize cache in Formulary: {e}\");\n });\n Self {\n cache,\n parsed_cache: std::sync::Mutex::new(HashMap::new()),\n }\n }\n\n pub fn load_formula(&self, name: &str) -> Result {\n let mut parsed_cache_guard = self.parsed_cache.lock().unwrap();\n if let Some(formula_arc) = parsed_cache_guard.get(name) {\n debug!(\"Loaded formula '{}' from parsed cache.\", name);\n return Ok(Arc::clone(formula_arc).as_ref().clone());\n }\n drop(parsed_cache_guard);\n\n let raw_data = self.cache.load_raw(\"formula.json\")?;\n let all_formulas: Vec = serde_json::from_str(&raw_data)\n .map_err(|e| SpsError::Cache(format!(\"Failed to parse cached formula data: {e}\")))?;\n debug!(\"Parsed {} formulas.\", all_formulas.len());\n\n let mut found_formula: Option = None;\n parsed_cache_guard = self.parsed_cache.lock().unwrap();\n for formula in all_formulas {\n let formula_name = formula.name.clone();\n let formula_arc = std::sync::Arc::new(formula);\n\n if formula_name == name {\n found_formula = Some(Arc::clone(&formula_arc).as_ref().clone());\n }\n\n parsed_cache_guard\n .entry(formula_name)\n .or_insert(formula_arc);\n }\n\n match found_formula {\n Some(f) => {\n debug!(\n \"Successfully loaded formula '{}' version {}\",\n f.name,\n f.version_str_full()\n );\n Ok(f)\n }\n None => {\n debug!(\n \"Formula '{}' not found within the cached formula data.\",\n name\n );\n Err(SpsError::Generic(format!(\n \"Formula '{name}' not found in cache.\"\n )))\n }\n }\n }\n}\n"], ["/sps/sps-common/src/model/tap.rs", "// tap/tap.rs - Basic tap functionality // Should probably be in model module\n\nuse std::path::PathBuf;\n\nuse tracing::debug;\n\nuse crate::error::{Result, SpsError};\n\n/// Represents a source of packages (formulas and casks)\npub struct Tap {\n /// The user part of the tap name (e.g., \"homebrew\" in \"homebrew/core\")\n pub user: String,\n\n /// The repository part of the tap name (e.g., \"core\" in \"homebrew/core\")\n pub repo: String,\n\n /// The full path to the tap directory\n pub path: PathBuf,\n}\n\nimpl Tap {\n /// Create a new tap from user/repo format\n pub fn new(name: &str) -> Result {\n let parts: Vec<&str> = name.split('/').collect();\n if parts.len() != 2 {\n return Err(SpsError::Generic(format!(\"Invalid tap name: {name}\")));\n }\n let user = parts[0].to_string();\n let repo = parts[1].to_string();\n let prefix = if cfg!(target_arch = \"aarch64\") {\n PathBuf::from(\"/opt/homebrew\")\n } else {\n PathBuf::from(\"/usr/local\")\n };\n let path = prefix\n .join(\"Library/Taps\")\n .join(&user)\n .join(format!(\"homebrew-{repo}\"));\n Ok(Self { user, repo, path })\n }\n\n /// Update this tap by pulling latest changes\n pub fn update(&self) -> Result<()> {\n use git2::{FetchOptions, Repository};\n\n let repo = Repository::open(&self.path)\n .map_err(|e| SpsError::Generic(format!(\"Failed to open tap repository: {e}\")))?;\n\n // Fetch updates from origin\n let mut remote = repo\n .find_remote(\"origin\")\n .map_err(|e| SpsError::Generic(format!(\"Failed to find remote 'origin': {e}\")))?;\n\n let mut fetch_options = FetchOptions::new();\n remote\n .fetch(\n &[\"refs/heads/*:refs/heads/*\"],\n Some(&mut fetch_options),\n None,\n )\n .map_err(|e| SpsError::Generic(format!(\"Failed to fetch updates: {e}\")))?;\n\n // Merge changes\n let fetch_head = repo\n .find_reference(\"FETCH_HEAD\")\n .map_err(|e| SpsError::Generic(format!(\"Failed to find FETCH_HEAD: {e}\")))?;\n\n let fetch_commit = repo\n .reference_to_annotated_commit(&fetch_head)\n .map_err(|e| SpsError::Generic(format!(\"Failed to get commit from FETCH_HEAD: {e}\")))?;\n\n let analysis = repo\n .merge_analysis(&[&fetch_commit])\n .map_err(|e| SpsError::Generic(format!(\"Failed to analyze merge: {e}\")))?;\n\n if analysis.0.is_up_to_date() {\n debug!(\"Already up-to-date\");\n return Ok(());\n }\n\n if analysis.0.is_fast_forward() {\n let mut reference = repo\n .find_reference(\"refs/heads/master\")\n .map_err(|e| SpsError::Generic(format!(\"Failed to find master branch: {e}\")))?;\n reference\n .set_target(fetch_commit.id(), \"Fast-forward\")\n .map_err(|e| SpsError::Generic(format!(\"Failed to fast-forward: {e}\")))?;\n repo.set_head(\"refs/heads/master\")\n .map_err(|e| SpsError::Generic(format!(\"Failed to set HEAD: {e}\")))?;\n repo.checkout_head(Some(git2::build::CheckoutBuilder::default().force()))\n .map_err(|e| SpsError::Generic(format!(\"Failed to checkout: {e}\")))?;\n } else {\n return Err(SpsError::Generic(\n \"Tap requires merge but automatic merging is not implemented\".to_string(),\n ));\n }\n\n Ok(())\n }\n\n /// Remove this tap by deleting its local repository\n pub fn remove(&self) -> Result<()> {\n if !self.path.exists() {\n return Err(SpsError::NotFound(format!(\n \"Tap {} is not installed\",\n self.full_name()\n )));\n }\n debug!(\"Removing tap {}\", self.full_name());\n std::fs::remove_dir_all(&self.path).map_err(|e| {\n SpsError::Generic(format!(\"Failed to remove tap {}: {}\", self.full_name(), e))\n })\n }\n\n /// Get the full name of the tap (user/repo)\n pub fn full_name(&self) -> String {\n format!(\"{}/{}\", self.user, self.repo)\n }\n\n /// Check if this tap is installed locally\n pub fn is_installed(&self) -> bool {\n self.path.exists()\n }\n}\n"], ["/sps/sps-core/src/utils/applescript.rs", "use std::path::Path;\nuse std::process::Command;\nuse std::thread;\nuse std::time::Duration;\n\nuse plist::Value as PlistValue;\nuse sps_common::error::Result;\nuse tracing::{debug, warn};\n\nfn get_bundle_identifier_from_app_path(app_path: &Path) -> Option {\n let info_plist_path = app_path.join(\"Contents/Info.plist\");\n if !info_plist_path.is_file() {\n debug!(\"Info.plist not found at {}\", info_plist_path.display());\n return None;\n }\n match PlistValue::from_file(&info_plist_path) {\n Ok(PlistValue::Dictionary(dict)) => dict\n .get(\"CFBundleIdentifier\")\n .and_then(PlistValue::as_string)\n .map(String::from),\n Ok(val) => {\n warn!(\n \"Info.plist at {} is not a dictionary. Value: {:?}\",\n info_plist_path.display(),\n val\n );\n None\n }\n Err(e) => {\n warn!(\n \"Failed to parse Info.plist at {}: {}\",\n info_plist_path.display(),\n e\n );\n None\n }\n }\n}\n\nfn is_app_running_by_bundle_id(bundle_id: &str) -> Result {\n let script = format!(\n \"tell application \\\"System Events\\\" to (exists (process 1 where bundle identifier is \\\"{bundle_id}\\\"))\"\n );\n debug!(\n \"Checking if app with bundle ID '{}' is running using script: {}\",\n bundle_id, script\n );\n\n let output = Command::new(\"osascript\").arg(\"-e\").arg(&script).output()?;\n\n if output.status.success() {\n let stdout = String::from_utf8_lossy(&output.stdout)\n .trim()\n .to_lowercase();\n debug!(\n \"is_app_running_by_bundle_id ('{}') stdout: '{}'\",\n bundle_id, stdout\n );\n Ok(stdout == \"true\")\n } else {\n let stderr = String::from_utf8_lossy(&output.stderr);\n warn!(\n \"osascript check running status for bundle ID '{}' failed. Status: {}, Stderr: {}\",\n bundle_id,\n output.status,\n stderr.trim()\n );\n Ok(false)\n }\n}\n\n/// Attempts to gracefully quit an application using its bundle identifier (preferred) or name via\n/// AppleScript. Retries several times, checking if the app is still running between attempts.\n/// Returns Ok even if the app could not be quit, as uninstall should proceed.\npub fn quit_app_gracefully(app_path: &Path) -> Result<()> {\n if !cfg!(target_os = \"macos\") {\n debug!(\"Not on macOS, skipping app quit for {}\", app_path.display());\n return Ok(());\n }\n if !app_path.exists() {\n debug!(\n \"App path {} does not exist, skipping quit attempt.\",\n app_path.display()\n );\n return Ok(());\n }\n\n let app_name_for_log = app_path\n .file_name()\n .map_or_else(|| app_path.to_string_lossy(), |name| name.to_string_lossy())\n .trim_end_matches(\".app\")\n .to_string();\n\n let bundle_identifier = get_bundle_identifier_from_app_path(app_path);\n\n let (script_target, using_bundle_id) = match &bundle_identifier {\n Some(id) => (id.clone(), true),\n None => {\n warn!(\n \"Could not get bundle identifier for {}. Will attempt to quit by name '{}'. This is less reliable.\",\n app_path.display(),\n app_name_for_log\n );\n (app_name_for_log.clone(), false)\n }\n };\n\n debug!(\n \"Attempting to quit app '{}' (script target: '{}', using bundle_id: {})\",\n app_name_for_log, script_target, using_bundle_id\n );\n\n // Initial check if app is running (only reliable if we have bundle ID)\n if using_bundle_id {\n match is_app_running_by_bundle_id(&script_target) {\n Ok(true) => debug!(\n \"App '{}' is running. Proceeding with quit attempts.\",\n script_target\n ),\n Ok(false) => {\n debug!(\"App '{}' is not running. Quit unnecessary.\", script_target);\n return Ok(());\n }\n Err(e) => {\n warn!(\n \"Could not determine if app '{}' is running (check failed: {}). Proceeding with quit attempt.\",\n script_target, e\n );\n }\n }\n }\n\n let quit_command = if using_bundle_id {\n format!(\"tell application id \\\"{script_target}\\\" to quit\")\n } else {\n format!(\"tell application \\\"{script_target}\\\" to quit\")\n };\n\n const MAX_QUIT_ATTEMPTS: usize = 4;\n const QUIT_DELAYS_SECS: [u64; MAX_QUIT_ATTEMPTS - 1] = [2, 3, 5];\n\n // Use enumerate over QUIT_DELAYS_SECS for Clippy compliance\n for (attempt, delay) in QUIT_DELAYS_SECS.iter().enumerate() {\n debug!(\n \"Quit attempt #{} for '{}' using command: {}\",\n attempt + 1,\n script_target,\n quit_command\n );\n\n let output = Command::new(\"osascript\")\n .arg(\"-e\")\n .arg(&quit_command)\n .output()?; // Propagate IO errors from osascript execution\n\n if output.status.success() {\n debug!(\n \"osascript quit command sent successfully for '{}' (attempt #{}).\",\n script_target,\n attempt + 1\n );\n } else {\n let stderr = String::from_utf8_lossy(&output.stderr);\n if stderr.contains(\"-1712\")\n || stderr.contains(\"-1728\")\n || stderr.contains(\"-600\")\n || stderr.to_lowercase().contains(\"application isn’t running\")\n || stderr.to_lowercase().contains(\"application not running\")\n {\n debug!(\n \"osascript: App '{}' reported as not running or not found (stderr: {}). Quit successful or unnecessary.\",\n script_target,\n stderr.trim()\n );\n return Ok(());\n } else {\n warn!(\n \"osascript quit command for '{}' failed (attempt #{}). Status: {}. Stderr: {}\",\n script_target,\n attempt + 1,\n output.status,\n stderr.trim()\n );\n }\n }\n\n // Wait briefly to allow the app to process the quit command\n thread::sleep(Duration::from_secs(*delay));\n\n // Check if the app is still running (if using bundle ID)\n if using_bundle_id {\n match is_app_running_by_bundle_id(&script_target) {\n Ok(true) => {\n debug!(\n \"App '{}' still running after attempt #{}. Retrying.\",\n script_target,\n attempt + 1\n );\n }\n Ok(false) => {\n debug!(\n \"App '{}' successfully quit after attempt #{}.\",\n script_target,\n attempt + 1\n );\n return Ok(());\n }\n Err(e) => {\n warn!(\n \"Could not verify if app '{}' quit after attempt #{}: {}. Assuming it might still be running.\",\n script_target,\n attempt + 1,\n e\n );\n }\n }\n }\n }\n\n // Final attempt (the fourth, not covered by QUIT_DELAYS_SECS)\n let attempt = QUIT_DELAYS_SECS.len();\n debug!(\n \"Quit attempt #{} for '{}' using command: {}\",\n attempt + 1,\n script_target,\n quit_command\n );\n\n let output = Command::new(\"osascript\")\n .arg(\"-e\")\n .arg(&quit_command)\n .output()?; // Propagate IO errors from osascript execution\n\n if output.status.success() {\n debug!(\n \"osascript quit command sent successfully for '{}' (attempt #{}).\",\n script_target,\n attempt + 1\n );\n } else {\n let stderr = String::from_utf8_lossy(&output.stderr);\n if stderr.contains(\"-1712\")\n || stderr.contains(\"-1728\")\n || stderr.contains(\"-600\")\n || stderr.to_lowercase().contains(\"application isn’t running\")\n || stderr.to_lowercase().contains(\"application not running\")\n {\n debug!(\n \"osascript: App '{}' reported as not running or not found (stderr: {}). Quit successful or unnecessary.\",\n script_target,\n stderr.trim()\n );\n return Ok(());\n } else {\n warn!(\n \"osascript quit command for '{}' failed (attempt #{}). Status: {}. Stderr: {}\",\n script_target,\n attempt + 1,\n output.status,\n stderr.trim()\n );\n }\n }\n\n // Final check if the app is still running (if using bundle ID)\n if using_bundle_id {\n match is_app_running_by_bundle_id(&script_target) {\n Ok(true) => {\n warn!(\n \"App '{}' still running after {} quit attempts.\",\n script_target, MAX_QUIT_ATTEMPTS\n );\n }\n Ok(false) => {\n debug!(\n \"App '{}' successfully quit after attempt #{}.\",\n script_target,\n attempt + 1\n );\n return Ok(());\n }\n Err(e) => {\n warn!(\n \"Could not verify if app '{}' quit after attempt #{}: {}. Assuming it might still be running.\",\n script_target,\n attempt + 1,\n e\n );\n }\n }\n } else {\n warn!(\n \"App '{}' (targeted by name) might still be running after {} quit attempts. Manual check may be needed.\",\n script_target,\n MAX_QUIT_ATTEMPTS\n );\n }\n Ok(())\n}\n"], ["/sps/sps-core/src/pipeline/engine.rs", "use std::sync::atomic::{AtomicUsize, Ordering};\nuse std::sync::Arc;\n\nuse crossbeam_channel::Receiver as CrossbeamReceiver;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::error::Result as SpsResult;\nuse sps_common::pipeline::{PipelineEvent, WorkerJob};\nuse threadpool::ThreadPool;\nuse tokio::sync::broadcast;\nuse tracing::{debug, instrument};\n\nuse super::worker;\n\n#[instrument(skip_all, name = \"core_worker_manager\")]\npub fn start_worker_pool_manager(\n config: Config,\n cache: Arc,\n worker_job_rx: CrossbeamReceiver,\n event_tx: broadcast::Sender,\n success_count: Arc,\n fail_count: Arc,\n) -> SpsResult<()> {\n let num_workers = std::cmp::max(1, num_cpus::get_physical().saturating_sub(1)).min(6);\n let pool = ThreadPool::new(num_workers);\n debug!(\n \"Core worker pool manager started with {} workers.\",\n num_workers\n );\n debug!(\"Worker pool created.\");\n\n for worker_job in worker_job_rx {\n let job_id = worker_job.request.target_id.clone();\n debug!(\n \"[{}] Received job from channel, preparing to submit to pool.\",\n job_id\n );\n\n let config_clone = config.clone();\n let cache_clone = Arc::clone(&cache);\n let event_tx_clone = event_tx.clone();\n let success_count_clone = Arc::clone(&success_count);\n let fail_count_clone = Arc::clone(&fail_count);\n\n let _ = event_tx_clone.send(PipelineEvent::JobProcessingStarted {\n target_id: job_id.clone(),\n });\n\n debug!(\"[{}] Submitting job to worker pool.\", job_id);\n\n pool.execute(move || {\n let job_result = worker::execute_sync_job(\n worker_job,\n &config_clone,\n cache_clone,\n event_tx_clone.clone(),\n );\n let job_id_for_log = job_id.clone();\n debug!(\n \"[{}] Worker job execution finished (execute_sync_job returned), result ok: {}\",\n job_id_for_log,\n job_result.is_ok()\n );\n\n let job_id_for_log = job_id.clone();\n match job_result {\n Ok((final_action, pkg_type)) => {\n success_count_clone.fetch_add(1, Ordering::Relaxed);\n debug!(\"[{}] Worker finished successfully.\", job_id);\n let _ = event_tx_clone.send(PipelineEvent::JobSuccess {\n target_id: job_id,\n action: final_action,\n pkg_type,\n });\n debug!(\"[{}] Worker result event sent.\", job_id_for_log);\n }\n Err(boxed) => {\n let (final_action, err) = *boxed;\n fail_count_clone.fetch_add(1, Ordering::Relaxed);\n // Error is sent via JobFailed event and displayed in status.rs\n let _ = event_tx_clone.send(PipelineEvent::JobFailed {\n target_id: job_id,\n action: final_action,\n error: err.to_string(),\n });\n debug!(\"[{}] Worker result event sent.\", job_id_for_log);\n }\n }\n debug!(\"[{}] Worker closure scope ending.\", job_id_for_log);\n });\n }\n pool.join();\n Ok(())\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/installer.rs", "// ===== sps-core/src/build/cask/artifacts/installer.rs =====\n\nuse std::path::Path;\nuse std::process::{Command, Stdio};\n\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::InstalledArtifact;\n\n// Helper to validate that the executable is a filename (relative, no '/' or \"..\")\nfn validate_filename_or_relative_path(file: &str) -> Result {\n if file.starts_with(\"/\") || file.contains(\"..\") || file.contains(\"/\") {\n return Err(SpsError::Generic(format!(\n \"Invalid executable filename: {file}\"\n )));\n }\n Ok(file.to_string())\n}\n\n// Helper to validate a command argument based on allowed characters or allowed option form\nfn validate_argument(arg: &str) -> Result {\n if arg.starts_with(\"-\") {\n return Ok(arg.to_string());\n }\n if arg.starts_with(\"/\") || arg.contains(\"..\") || arg.contains(\"/\") {\n return Err(SpsError::Generic(format!(\"Invalid argument: {arg}\")));\n }\n if !arg\n .chars()\n .all(|c| c.is_alphanumeric() || c == '-' || c == '_' || c == '.')\n {\n return Err(SpsError::Generic(format!(\n \"Invalid characters in argument: {arg}\"\n )));\n }\n Ok(arg.to_string())\n}\n\n/// Implements the `installer` stanza:\n/// - `manual`: prints instructions to open the staged path.\n/// - `script`: runs the given executable with args, under sudo if requested.\n///\n/// Mirrors Homebrew’s `Cask::Artifact::Installer` behavior :contentReference[oaicite:1]{index=1}.\npub fn run_installer(\n cask: &Cask,\n stage_path: &Path,\n _cask_version_install_path: &Path,\n _config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n // Find the `installer` definitions in the raw JSON artifacts\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(insts) = obj.get(\"installer\").and_then(|v| v.as_array()) {\n for inst in insts {\n if let Some(inst_obj) = inst.as_object() {\n if let Some(man) = inst_obj.get(\"manual\").and_then(|v| v.as_str()) {\n debug!(\n \"Cask {} requires manual install. To finish:\\n open {}\",\n cask.token,\n stage_path.join(man).display()\n );\n continue;\n }\n let exe_key = if inst_obj.contains_key(\"script\") {\n \"script\"\n } else {\n \"executable\"\n };\n let executable = inst_obj\n .get(exe_key)\n .and_then(|v| v.as_str())\n .ok_or_else(|| {\n SpsError::Generic(format!(\n \"installer stanza missing '{exe_key}' field\"\n ))\n })?;\n let args: Vec = inst_obj\n .get(\"args\")\n .and_then(|v| v.as_array())\n .map(|arr| {\n arr.iter()\n .filter_map(|a| a.as_str().map(String::from))\n .collect()\n })\n .unwrap_or_default();\n let use_sudo = inst_obj\n .get(\"sudo\")\n .and_then(|v| v.as_bool())\n .unwrap_or(false);\n\n let validated_executable =\n validate_filename_or_relative_path(executable)?;\n let mut validated_args = Vec::new();\n for arg in &args {\n validated_args.push(validate_argument(arg)?);\n }\n\n let script_path = stage_path.join(&validated_executable);\n if !script_path.exists() {\n return Err(SpsError::NotFound(format!(\n \"Installer script not found: {}\",\n script_path.display()\n )));\n }\n\n debug!(\n \"Running installer script '{}' for cask {}\",\n script_path.display(),\n cask.token\n );\n let mut cmd = if use_sudo {\n let mut c = Command::new(\"sudo\");\n c.arg(script_path.clone());\n c\n } else {\n Command::new(script_path.clone())\n };\n cmd.args(&validated_args);\n cmd.stdin(Stdio::null())\n .stdout(Stdio::inherit())\n .stderr(Stdio::inherit());\n\n let status = cmd.status().map_err(|e| {\n SpsError::Generic(format!(\"Failed to spawn installer script: {e}\"))\n })?;\n if !status.success() {\n return Err(SpsError::InstallError(format!(\n \"Installer script exited with {status}\"\n )));\n }\n\n installed\n .push(InstalledArtifact::CaskroomReference { path: script_path });\n }\n }\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/manpage.rs", "// ===== src/build/cask/artifacts/manpage.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::sync::LazyLock;\n\nuse regex::Regex;\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n// --- Moved Regex Creation Outside ---\nstatic MANPAGE_RE: LazyLock =\n LazyLock::new(|| Regex::new(r\"\\.([1-8nl])(?:\\.gz)?$\").unwrap());\n\n/// Install any `manpage` stanzas from the Cask definition.\n/// Mirrors Homebrew’s `Cask::Artifact::Manpage < Symlinked` behavior\n/// :contentReference[oaicite:3]{index=3}.\npub fn install_manpage(\n cask: &Cask,\n stage_path: &Path,\n _cask_version_install_path: &Path, // Not needed for symlinking manpages\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n // Look up the \"manpage\" array in the raw artifacts JSON :contentReference[oaicite:4]{index=4}\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"manpage\").and_then(|v| v.as_array()) {\n for entry in entries {\n if let Some(man_file) = entry.as_str() {\n let src = stage_path.join(man_file);\n if !src.exists() {\n debug!(\n \"Manpage '{}' not found in staging area, skipping\",\n man_file\n );\n continue;\n }\n\n // Use the static regex\n let section = if let Some(caps) = MANPAGE_RE.captures(man_file) {\n caps.get(1).unwrap().as_str()\n } else {\n debug!(\n \"Filename '{}' does not look like a manpage, skipping\",\n man_file\n );\n continue;\n };\n\n // Build the target directory: e.g. /opt/sps/share/man/man1\n let man_dir = config.man_base_dir().join(format!(\"man{section}\"));\n fs::create_dir_all(&man_dir)?;\n\n // Determine the target path\n let file_name = Path::new(man_file).file_name().ok_or_else(|| {\n sps_common::error::SpsError::Generic(format!(\n \"Invalid manpage filename: {man_file}\"\n ))\n })?; // Handle potential None\n let dest = man_dir.join(file_name);\n\n // Remove any existing file or symlink\n // :contentReference[oaicite:7]{index=7}\n if dest.exists() || dest.symlink_metadata().is_ok() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\"Linking manpage '{}' → '{}'\", src.display(), dest.display());\n // Create the symlink\n symlink(&src, &dest)?;\n\n // Record it in our manifest\n installed.push(InstalledArtifact::ManpageLink {\n link_path: dest.clone(),\n target_path: src.clone(),\n });\n }\n }\n // Assume only one \"manpage\" stanza per Cask based on Homebrew structure\n break;\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/helpers.rs", "use std::fs;\nuse std::path::Path;\n\nuse sps_common::config::Config;\nuse tracing::debug;\n\n/// Robustly removes a file or directory, handling symlinks and permissions.\n/// If `use_sudo_if_needed` is true, will attempt `sudo rm -rf` on permission errors.\npub fn remove_path_robustly(path: &Path, _config: &Config, use_sudo_if_needed: bool) -> bool {\n if !path.exists() && path.symlink_metadata().is_err() {\n debug!(\"Path {} not found for removal.\", path.display());\n return true;\n }\n let is_dir = path.is_dir()\n && !path\n .symlink_metadata()\n .is_ok_and(|m| m.file_type().is_symlink());\n let removal_op = || -> std::io::Result<()> {\n if is_dir {\n fs::remove_dir_all(path)\n } else {\n fs::remove_file(path)\n }\n };\n\n if let Err(e) = removal_op() {\n if e.kind() == std::io::ErrorKind::NotFound {\n return true;\n }\n if use_sudo_if_needed && e.kind() == std::io::ErrorKind::PermissionDenied {\n debug!(\n \"Direct removal of {} failed (Permission Denied). Trying with sudo rm -rf.\",\n path.display()\n );\n let output = std::process::Command::new(\"sudo\")\n .arg(\"rm\")\n .arg(\"-rf\")\n .arg(path)\n .output();\n match output {\n Ok(out) if out.status.success() => {\n debug!(\"Successfully removed {} with sudo.\", path.display());\n return true;\n }\n Ok(out) => {\n debug!(\n \"`sudo rm -rf {}` failed ({}): {}\",\n path.display(),\n out.status,\n String::from_utf8_lossy(&out.stderr).trim()\n );\n return false;\n }\n Err(sudo_e) => {\n debug!(\n \"Error executing `sudo rm -rf` for {}: {}\",\n path.display(),\n sudo_e\n );\n return false;\n }\n }\n } else {\n debug!(\"Failed to remove {}: {}\", path.display(), e);\n return false;\n }\n }\n debug!(\"Successfully removed {}.\", path.display());\n true\n}\n\n/// Recursively cleans up empty parent directories in the private cask store.\n/// Starts from the given path and walks up, removing empty directories until a non-empty or root is\n/// found.\npub fn cleanup_empty_parent_dirs_in_private_store(start_path: &Path, stop_at: &Path) {\n let mut current = start_path.to_path_buf();\n while current != *stop_at {\n if let Ok(read_dir) = fs::read_dir(¤t) {\n if read_dir.count() == 0 {\n match fs::remove_dir(¤t) {\n Ok(_) => {\n debug!(\"Removed empty directory: {}\", current.display());\n }\n Err(e) => {\n debug!(\"Failed to remove directory {}: {}\", current.display(), e);\n break;\n }\n }\n } else {\n break;\n }\n } else {\n break;\n }\n if let Some(parent) = current.parent() {\n current = parent.to_path_buf();\n } else {\n break;\n }\n }\n}\n"], ["/sps/sps-core/src/utils/xattr.rs", "use std::path::Path;\nuse std::process::Command;\n\nuse anyhow::Context;\nuse sps_common::error::{Result, SpsError};\nuse tracing::{debug, error};\nuse uuid::Uuid;\nuse xattr;\n\n// Helper to get current timestamp as hex\nfn get_timestamp_hex() -> String {\n let secs = std::time::SystemTime::now()\n .duration_since(std::time::UNIX_EPOCH)\n .unwrap_or_default() // Defaults to 0 if time is before UNIX_EPOCH\n .as_secs();\n format!(\"{secs:x}\")\n}\n\n// Helper to generate a UUID as hex string\nfn get_uuid_hex() -> String {\n Uuid::new_v4().as_hyphenated().to_string().to_uppercase()\n}\n\n/// true → file **has** a com.apple.quarantine attribute \n/// false → attribute missing\npub fn has_quarantine_attribute(path: &Path) -> anyhow::Result {\n // The `xattr` crate has both path-level and FileExt APIs.\n // Path-level is simpler here.\n match xattr::get(path, \"com.apple.quarantine\") {\n Ok(Some(_)) => Ok(true),\n Ok(None) => Ok(false),\n Err(e) => Err(anyhow::Error::new(e))\n .with_context(|| format!(\"checking xattr on {}\", path.display())),\n }\n}\n\n/// Apply our standard quarantine only *if* none exists already.\n///\n/// `agent` should be the same string you currently pass to\n/// `set_quarantine_attribute()` – usually the cask token.\npub fn ensure_quarantine_attribute(path: &Path, agent: &str) -> anyhow::Result<()> {\n if has_quarantine_attribute(path)? {\n // Already quarantined (or the user cleared it and we respect that) → done\n return Ok(());\n }\n set_quarantine_attribute(path, agent)\n .with_context(|| format!(\"adding quarantine to {}\", path.display()))\n}\n\n/// Sets the 'com.apple.quarantine' extended attribute on a file or directory.\n/// Uses flags commonly seen for user-initiated downloads (0081).\n/// Logs errors assertively, as failure is critical for correct behavior.\npub fn set_quarantine_attribute(path: &Path, agent_name: &str) -> Result<()> {\n if !cfg!(target_os = \"macos\") {\n debug!(\n \"Not on macOS, skipping quarantine attribute for {}\",\n path.display()\n );\n return Ok(());\n }\n\n if !path.exists() {\n error!(\n \"Cannot set quarantine attribute, path does not exist: {}\",\n path.display()\n );\n return Err(SpsError::NotFound(format!(\n \"Path not found for setting quarantine attribute: {}\",\n path.display()\n )));\n }\n\n let timestamp_hex = get_timestamp_hex();\n let uuid_hex = get_uuid_hex();\n // Use \"0181\" to disable translocation and quarantine mirroring (Homebrew-style).\n // Format: \"flags;timestamp_hex;agent_name;uuid_hex\"\n let quarantine_value = format!(\"0181;{timestamp_hex};{agent_name};{uuid_hex}\");\n\n debug!(\n \"Setting quarantine attribute on {}: value='{}'\",\n path.display(),\n quarantine_value\n );\n\n let output = Command::new(\"xattr\")\n .arg(\"-w\")\n .arg(\"com.apple.quarantine\")\n .arg(&quarantine_value)\n .arg(path.as_os_str())\n .output();\n\n match output {\n Ok(out) => {\n if out.status.success() {\n debug!(\n \"Successfully set quarantine attribute for {}\",\n path.display()\n );\n Ok(())\n } else {\n let stderr = String::from_utf8_lossy(&out.stderr);\n error!( // Changed from warn to error as this is critical for the bug\n \"Failed to set quarantine attribute for {} (status: {}): {}. This may lead to data loss on reinstall or Gatekeeper issues.\",\n path.display(),\n out.status,\n stderr.trim()\n );\n // Return an error because failure to set this is likely to cause the reported bug\n Err(SpsError::Generic(format!(\n \"Failed to set com.apple.quarantine on {}: {}\",\n path.display(),\n stderr.trim()\n )))\n }\n }\n Err(e) => {\n error!(\n \"Failed to execute xattr command for {}: {}. Quarantine attribute not set.\",\n path.display(),\n e\n );\n Err(SpsError::Io(std::sync::Arc::new(e)))\n }\n }\n}\n"], ["/sps/sps/src/cli/status.rs", "// sps/src/cli/status.rs\nuse std::collections::{HashMap, HashSet};\nuse std::io::{self, Write};\nuse std::time::Instant;\n\nuse colored::*;\nuse sps_common::config::Config;\nuse sps_common::pipeline::{PipelineEvent, PipelinePackageType};\nuse tokio::sync::broadcast;\nuse tracing::debug;\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq)]\nenum JobStatus {\n Waiting,\n Downloading,\n Downloaded,\n Cached,\n Processing,\n Installing,\n Linking,\n Success,\n Failed,\n}\n\nimpl JobStatus {\n fn display_state(&self) -> &'static str {\n match self {\n JobStatus::Waiting => \"waiting\",\n JobStatus::Downloading => \"downloading\",\n JobStatus::Downloaded => \"downloaded\",\n JobStatus::Cached => \"cached\",\n JobStatus::Processing => \"processing\",\n JobStatus::Installing => \"installing\",\n JobStatus::Linking => \"linking\",\n JobStatus::Success => \"success\",\n JobStatus::Failed => \"failed\",\n }\n }\n\n fn slot_indicator(&self) -> String {\n match self {\n JobStatus::Waiting => \" ⧗\".yellow().to_string(),\n JobStatus::Downloading => \" ⬇\".blue().to_string(),\n JobStatus::Downloaded => \" ✓\".green().to_string(),\n JobStatus::Cached => \" ⌂\".cyan().to_string(),\n JobStatus::Processing => \" ⚙\".yellow().to_string(),\n JobStatus::Installing => \" ⚙\".cyan().to_string(),\n JobStatus::Linking => \" →\".magenta().to_string(),\n JobStatus::Success => \" ✓\".green().bold().to_string(),\n JobStatus::Failed => \" ✗\".red().bold().to_string(),\n }\n }\n\n fn colored_state(&self) -> ColoredString {\n match self {\n JobStatus::Waiting => self.display_state().dimmed(),\n JobStatus::Downloading => self.display_state().blue(),\n JobStatus::Downloaded => self.display_state().green(),\n JobStatus::Cached => self.display_state().cyan(),\n JobStatus::Processing => self.display_state().yellow(),\n JobStatus::Installing => self.display_state().yellow(),\n JobStatus::Linking => self.display_state().yellow(),\n JobStatus::Success => self.display_state().green(),\n JobStatus::Failed => self.display_state().red(),\n }\n }\n}\n\nstruct JobInfo {\n name: String,\n status: JobStatus,\n size_bytes: Option,\n current_bytes_downloaded: Option,\n start_time: Option,\n pool_id: usize,\n}\n\nimpl JobInfo {\n fn _elapsed_str(&self) -> String {\n match self.start_time {\n Some(start) => format!(\"{:.1}s\", start.elapsed().as_secs_f64()),\n None => \"–\".to_string(),\n }\n }\n\n fn size_str(&self) -> String {\n match self.size_bytes {\n Some(bytes) => format_bytes(bytes),\n None => \"–\".to_string(),\n }\n }\n}\n\nstruct StatusDisplay {\n jobs: HashMap,\n job_order: Vec,\n total_jobs: usize,\n next_pool_id: usize,\n _start_time: Instant,\n active_downloads: HashSet,\n total_bytes: u64,\n downloaded_bytes: u64,\n last_speed_update: Instant,\n last_aggregate_bytes_snapshot: u64,\n current_speed_bps: f64,\n _speed_history: Vec,\n header_printed: bool,\n last_line_count: usize,\n}\n\nimpl StatusDisplay {\n fn new() -> Self {\n Self {\n jobs: HashMap::new(),\n job_order: Vec::new(),\n total_jobs: 0,\n next_pool_id: 1,\n _start_time: Instant::now(),\n active_downloads: HashSet::new(),\n total_bytes: 0,\n downloaded_bytes: 0,\n last_speed_update: Instant::now(),\n last_aggregate_bytes_snapshot: 0,\n current_speed_bps: 0.0,\n _speed_history: Vec::new(),\n header_printed: false,\n last_line_count: 0,\n }\n }\n\n fn add_job(&mut self, target_id: String, status: JobStatus, size_bytes: Option) {\n if !self.jobs.contains_key(&target_id) {\n let job_info = JobInfo {\n name: target_id.clone(),\n status,\n size_bytes,\n current_bytes_downloaded: if status == JobStatus::Downloading {\n Some(0)\n } else {\n None\n },\n start_time: if status != JobStatus::Waiting {\n Some(Instant::now())\n } else {\n None\n },\n pool_id: self.next_pool_id,\n };\n\n if let Some(bytes) = size_bytes {\n self.total_bytes += bytes;\n }\n\n if status == JobStatus::Downloading {\n self.active_downloads.insert(target_id.to_string());\n }\n\n self.jobs.insert(target_id.clone(), job_info);\n self.job_order.push(target_id);\n self.next_pool_id += 1;\n }\n }\n\n fn update_job_status(&mut self, target_id: &str, status: JobStatus, size_bytes: Option) {\n if let Some(job) = self.jobs.get_mut(target_id) {\n let was_downloading = job.status == JobStatus::Downloading;\n let is_downloading = status == JobStatus::Downloading;\n\n job.status = status;\n\n if job.start_time.is_none() && status != JobStatus::Waiting {\n job.start_time = Some(Instant::now());\n }\n\n if let Some(bytes) = size_bytes {\n if job.size_bytes.is_none() {\n self.total_bytes += bytes;\n }\n job.size_bytes = Some(bytes);\n }\n\n // Update download counts\n if was_downloading && !is_downloading {\n self.active_downloads.remove(target_id);\n if let Some(bytes) = job.size_bytes {\n job.current_bytes_downloaded = Some(bytes);\n self.downloaded_bytes += bytes;\n }\n } else if !was_downloading && is_downloading {\n self.active_downloads.insert(target_id.to_string());\n job.current_bytes_downloaded = Some(0);\n }\n }\n }\n\n fn update_download_progress(\n &mut self,\n target_id: &str,\n bytes_so_far: u64,\n total_size: Option,\n ) {\n if let Some(job) = self.jobs.get_mut(target_id) {\n job.current_bytes_downloaded = Some(bytes_so_far);\n\n if let Some(total) = total_size {\n if job.size_bytes.is_none() {\n // Update total bytes estimate\n self.total_bytes += total;\n job.size_bytes = Some(total);\n } else if job.size_bytes != Some(total) {\n // Adjust total bytes if estimate changed\n if let Some(old_size) = job.size_bytes {\n self.total_bytes = self.total_bytes.saturating_sub(old_size) + total;\n }\n job.size_bytes = Some(total);\n }\n }\n }\n }\n\n fn update_speed(&mut self) {\n let now = Instant::now();\n let time_diff = now.duration_since(self.last_speed_update).as_secs_f64();\n\n if time_diff >= 0.0625 {\n // Calculate current total bytes for all jobs with current download progress\n let current_active_bytes: u64 = self\n .jobs\n .values()\n .filter(|job| matches!(job.status, JobStatus::Downloading))\n .map(|job| job.current_bytes_downloaded.unwrap_or(0))\n .sum();\n\n // Calculate bytes difference since last update\n let bytes_diff =\n current_active_bytes.saturating_sub(self.last_aggregate_bytes_snapshot);\n\n // Calculate speed\n if time_diff > 0.0 && bytes_diff > 0 {\n self.current_speed_bps = bytes_diff as f64 / time_diff;\n } else if !self\n .jobs\n .values()\n .any(|job| job.status == JobStatus::Downloading)\n {\n // No active downloads, reset speed to 0\n self.current_speed_bps = 0.0;\n }\n // If no bytes diff but still have active downloads, keep previous speed\n\n self.last_speed_update = now;\n self.last_aggregate_bytes_snapshot = current_active_bytes;\n }\n }\n\n fn render(&mut self) {\n self.update_speed();\n\n if !self.header_printed {\n // First render - print header and jobs\n self.print_header();\n let job_output = self.build_job_rows();\n print!(\"{job_output}\");\n self.header_printed = true;\n // Count lines: header + jobs + separator + summary\n let job_lines = job_output.lines().count();\n self.last_line_count = 1 + job_lines + 1 + 1;\n } else {\n // Subsequent renders - clear and reprint header, job rows and summary\n self.clear_previous_output();\n self.print_header();\n let job_output = self.build_job_rows();\n print!(\"{job_output}\");\n // Update line count (header + jobs + separator)\n let job_lines = job_output.lines().count();\n self.last_line_count = 1 + job_lines + 1;\n }\n\n // Print separator\n println!(\"{}\", \"─\".repeat(49).dimmed());\n\n // Print status summary\n let completed = self\n .jobs\n .values()\n .filter(|j| matches!(j.status, JobStatus::Success))\n .count();\n let failed = self\n .jobs\n .values()\n .filter(|j| matches!(j.status, JobStatus::Failed))\n .count();\n let _progress_chars = self.generate_progress_bar(completed, failed);\n let _speed_str = format_speed(self.current_speed_bps);\n\n io::stdout().flush().unwrap();\n }\n\n fn print_header(&self) {\n println!(\n \"{:<6} {:<12} {:<15} {:>8} {}\",\n \"IID\".bold().dimmed(),\n \"STATE\".bold().dimmed(),\n \"PKG\".bold().dimmed(),\n \"SIZE\".bold().dimmed(),\n \"SLOT\".bold().dimmed()\n );\n }\n\n fn build_job_rows(&self) -> String {\n let mut output = String::new();\n\n // Job rows\n for target_id in &self.job_order {\n if let Some(job) = self.jobs.get(target_id) {\n let progress_str = if job.status == JobStatus::Downloading {\n match (job.current_bytes_downloaded, job.size_bytes) {\n (Some(downloaded), Some(_total)) => format_bytes(downloaded).to_string(),\n (Some(downloaded), None) => format_bytes(downloaded),\n _ => job.size_str(),\n }\n } else {\n job.size_str()\n };\n\n output.push_str(&format!(\n \"{:<6} {:<12} {:<15} {:>8} {}\\n\",\n format!(\"#{:02}\", job.pool_id).cyan(),\n job.status.colored_state(),\n job.name.cyan(),\n progress_str,\n job.status.slot_indicator()\n ));\n }\n }\n\n output\n }\n\n fn clear_previous_output(&self) {\n // Move cursor up and clear lines\n for _ in 0..self.last_line_count {\n print!(\"\\x1b[1A\\x1b[2K\"); // Move up one line and clear it\n }\n io::stdout().flush().unwrap();\n }\n\n fn generate_progress_bar(&self, completed: usize, failed: usize) -> String {\n if self.total_jobs == 0 {\n return \"\".to_string();\n }\n\n let total_done = completed + failed;\n let progress_width = 8;\n let filled = (total_done * progress_width) / self.total_jobs;\n let remaining = progress_width - filled;\n\n let filled_str = \"▍\".repeat(filled).green();\n let remaining_str = \"·\".repeat(remaining).dimmed();\n\n format!(\"{filled_str}{remaining_str}\")\n }\n}\n\nfn format_bytes(bytes: u64) -> String {\n const UNITS: &[&str] = &[\"B\", \"kB\", \"MB\", \"GB\"];\n let mut value = bytes as f64;\n let mut unit_idx = 0;\n\n while value >= 1000.0 && unit_idx < UNITS.len() - 1 {\n value /= 1000.0;\n unit_idx += 1;\n }\n\n if unit_idx == 0 {\n format!(\"{bytes}B\")\n } else {\n format!(\"{:.1}{}\", value, UNITS[unit_idx])\n }\n}\n\nfn format_speed(bytes_per_sec: f64) -> String {\n if bytes_per_sec < 1.0 {\n return \"0 B/s\".to_string();\n }\n\n const UNITS: &[&str] = &[\"B/s\", \"kB/s\", \"MB/s\", \"GB/s\"];\n let mut value = bytes_per_sec;\n let mut unit_idx = 0;\n\n while value >= 1000.0 && unit_idx < UNITS.len() - 1 {\n value /= 1000.0;\n unit_idx += 1;\n }\n\n format!(\"{:.1} {}\", value, UNITS[unit_idx])\n}\n\npub async fn handle_events(_config: Config, mut event_rx: broadcast::Receiver) {\n let mut display = StatusDisplay::new();\n let mut logs_buffer = Vec::new();\n let mut pipeline_active = false;\n let mut refresh_interval = tokio::time::interval(tokio::time::Duration::from_millis(62));\n refresh_interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);\n\n loop {\n tokio::select! {\n _ = refresh_interval.tick() => {\n if pipeline_active && display.header_printed {\n display.render();\n }\n }\n event_result = event_rx.recv() => {\n match event_result {\n Ok(event) => match event {\n PipelineEvent::PipelineStarted { total_jobs } => {\n pipeline_active = true;\n display.total_jobs = total_jobs;\n println!(\"{}\", \"Starting pipeline.\".cyan().bold());\n }\n PipelineEvent::PlanningStarted => {\n debug!(\"{}\", \"Planning operations.\".cyan());\n }\n PipelineEvent::DependencyResolutionStarted => {\n println!(\"{}\", \"Resolving dependencies\".cyan());\n }\n PipelineEvent::DependencyResolutionFinished => {\n debug!(\"{}\", \"Dependency resolution complete.\".cyan());\n }\n PipelineEvent::PlanningFinished { job_count } => {\n println!(\"{} {}\", \"Planning finished. Jobs:\".bold(), job_count);\n println!();\n }\n PipelineEvent::DownloadStarted { target_id, url: _ } => {\n display.add_job(target_id.clone(), JobStatus::Downloading, None);\n if pipeline_active {\n display.render();\n }\n }\n PipelineEvent::DownloadFinished {\n target_id,\n size_bytes,\n ..\n } => {\n display.update_job_status(&target_id, JobStatus::Downloaded, Some(size_bytes));\n if pipeline_active {\n display.render();\n }\n }\n PipelineEvent::DownloadProgressUpdate {\n target_id,\n bytes_so_far,\n total_size,\n } => {\n display.update_download_progress(&target_id, bytes_so_far, total_size);\n if pipeline_active {\n display.render();\n }\n }\n PipelineEvent::DownloadCached {\n target_id,\n size_bytes,\n } => {\n display.update_job_status(&target_id, JobStatus::Cached, Some(size_bytes));\n if pipeline_active {\n display.render();\n }\n }\n PipelineEvent::DownloadFailed {\n target_id, error, ..\n } => {\n display.update_job_status(&target_id, JobStatus::Failed, None);\n logs_buffer.push(format!(\n \"{} {}: {}\",\n \"Download failed:\".red(),\n target_id.cyan(),\n error.red()\n ));\n if pipeline_active {\n display.render();\n }\n }\n PipelineEvent::JobProcessingStarted { target_id } => {\n display.update_job_status(&target_id, JobStatus::Processing, None);\n if pipeline_active {\n display.render();\n }\n }\n PipelineEvent::BuildStarted { target_id } => {\n display.update_job_status(&target_id, JobStatus::Processing, None);\n if pipeline_active {\n display.render();\n }\n }\n PipelineEvent::InstallStarted { target_id, .. } => {\n display.update_job_status(&target_id, JobStatus::Installing, None);\n if pipeline_active {\n display.render();\n }\n }\n PipelineEvent::LinkStarted { target_id, .. } => {\n display.update_job_status(&target_id, JobStatus::Linking, None);\n if pipeline_active {\n display.render();\n }\n }\n PipelineEvent::JobSuccess {\n target_id,\n action,\n pkg_type,\n } => {\n display.update_job_status(&target_id, JobStatus::Success, None);\n let type_str = match pkg_type {\n PipelinePackageType::Formula => \"Formula\",\n PipelinePackageType::Cask => \"Cask\",\n };\n let action_str = match action {\n sps_common::pipeline::JobAction::Install => \"Installed\",\n sps_common::pipeline::JobAction::Upgrade { .. } => \"Upgraded\",\n sps_common::pipeline::JobAction::Reinstall { .. } => \"Reinstalled\",\n };\n logs_buffer.push(format!(\n \"{}: {} ({})\",\n action_str.green(),\n target_id.cyan(),\n type_str,\n ));\n if pipeline_active {\n display.render();\n }\n }\n PipelineEvent::JobFailed {\n target_id, error, ..\n } => {\n display.update_job_status(&target_id, JobStatus::Failed, None);\n logs_buffer.push(format!(\n \"{} {}: {}\",\n \"✗\".red().bold(),\n target_id.cyan(),\n error.red()\n ));\n if pipeline_active {\n display.render();\n }\n }\n PipelineEvent::LogInfo { message } => {\n logs_buffer.push(message);\n }\n PipelineEvent::LogWarn { message } => {\n logs_buffer.push(message.yellow().to_string());\n }\n PipelineEvent::LogError { message } => {\n logs_buffer.push(message.red().to_string());\n }\n PipelineEvent::PipelineFinished {\n duration_secs,\n success_count,\n fail_count,\n } => {\n if display.header_printed {\n display.render();\n }\n\n println!();\n\n println!(\n \"{} in {:.2}s ({} succeeded, {} failed)\",\n \"Pipeline finished\".bold(),\n duration_secs,\n success_count,\n fail_count\n );\n\n if !logs_buffer.is_empty() {\n println!();\n for log in &logs_buffer {\n println!(\"{log}\");\n }\n }\n\n break;\n }\n _ => {}\n },\n Err(broadcast::error::RecvError::Closed) => {\n break;\n }\n Err(broadcast::error::RecvError::Lagged(_)) => {\n // Ignore lag for now\n }\n }\n }\n }\n }\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/colorpicker.rs", "// ===== sps-core/src/build/cask/artifacts/colorpicker.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Installs any `colorpicker` stanzas from the Cask definition.\n///\n/// Homebrew’s `Colorpicker` artifact simply subclasses `Moved` with\n/// `dirmethod :colorpickerdir` → `~/Library/ColorPickers` :contentReference[oaicite:3]{index=3}.\npub fn install_colorpicker(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"colorpicker\").and_then(|v| v.as_array()) {\n // For each declared bundle name:\n for entry in entries {\n if let Some(bundle_name) = entry.as_str() {\n let src = stage_path.join(bundle_name);\n if !src.exists() {\n debug!(\n \"Colorpicker bundle '{}' not found in stage; skipping\",\n bundle_name\n );\n continue;\n }\n\n // Ensure ~/Library/ColorPickers exists\n // :contentReference[oaicite:4]{index=4}\n let dest_dir = config\n .home_dir() // e.g. /Users/alxknt\n .join(\"Library\")\n .join(\"ColorPickers\");\n fs::create_dir_all(&dest_dir)?;\n\n let dest = dest_dir.join(bundle_name);\n // Remove any previous copy\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Moving colorpicker '{}' → '{}'\",\n src.display(),\n dest.display()\n );\n // mv, fallback to cp -R if necessary (cross‑device)\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record as a moved artifact (bundle installed)\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink back into Caskroom for reference\n // :contentReference[oaicite:5]{index=5}\n let link = cask_version_install_path.join(bundle_name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // only one `colorpicker` stanza per cask\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/mdimporter.rs", "// ===== sps-core/src/build/cask/artifacts/mdimporter.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Installs `mdimporter` bundles from the staging area into\n/// `~/Library/Spotlight`, then symlinks them into the Caskroom,\n/// and reloads them via `mdimport -r` so Spotlight picks them up.\n///\n/// Mirrors Homebrew’s `Mdimporter < Moved` behavior.\npub fn install_mdimporter(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"mdimporter\").and_then(|v| v.as_array()) {\n // Target directory for user Spotlight importers\n let dest_dir = config.home_dir().join(\"Library\").join(\"Spotlight\");\n fs::create_dir_all(&dest_dir)?;\n\n for entry in entries {\n if let Some(bundle_name) = entry.as_str() {\n let src = stage_path.join(bundle_name);\n if !src.exists() {\n debug!(\n \"Mdimporter bundle '{}' not found in staging; skipping\",\n bundle_name\n );\n continue;\n }\n\n let dest = dest_dir.join(bundle_name);\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Installing mdimporter '{}' → '{}',\",\n src.display(),\n dest.display()\n );\n // Try move, fallback to copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record moved importer\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink for reference\n let link = cask_version_install_path.join(bundle_name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n\n // Reload Spotlight importer so it's picked up immediately\n debug!(\"Reloading Spotlight importer: {}\", dest.display());\n let _ = Command::new(\"/usr/bin/mdimport\")\n .arg(\"-r\")\n .arg(&dest)\n .status();\n }\n }\n break; // one stanza only\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/suite.rs", "// src/build/cask/artifacts/suite.rs\n\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Implements the `suite` stanza by moving each named directory from\n/// the staging area into `/Applications`, then symlinking it in the Caskroom.\n///\n/// Mirrors Homebrew’s Suite < Moved behavior (dirmethod :appdir)\n/// :contentReference[oaicite:3]{index=3}\npub fn install_suite(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n // Find the `suite` definition in the raw JSON artifacts\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def.iter() {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"suite\").and_then(|v| v.as_array()) {\n for entry in entries {\n if let Some(dir_name) = entry.as_str() {\n let src = stage_path.join(dir_name);\n if !src.exists() {\n debug!(\n \"Suite directory '{}' not found in staging, skipping\",\n dir_name\n );\n continue;\n }\n\n let dest_dir = config.applications_dir(); // e.g. /Applications\n let dest = dest_dir.join(dir_name); // e.g. /Applications/Foobar Suite\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n // remove old\n }\n\n debug!(\"Moving suite '{}' → '{}'\", src.display(), dest.display());\n // Try a rename (mv); fall back to recursive copy if cross‑filesystem\n let mv_status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !mv_status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record as an App artifact (a directory moved into /Applications)\n installed.push(InstalledArtifact::AppBundle { path: dest.clone() });\n\n // Then symlink it under Caskroom for reference\n let link = cask_version_install_path.join(dir_name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // only one \"suite\" stanza per cask\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-net/src/oci.rs", "use std::collections::HashMap;\nuse std::fs::{remove_file, File};\nuse std::path::Path;\nuse std::sync::Arc;\nuse std::time::Duration;\n\nuse futures::StreamExt;\nuse rand::rngs::SmallRng;\nuse rand::{Rng, SeedableRng};\nuse reqwest::header::{ACCEPT, AUTHORIZATION};\nuse reqwest::{Client, Response, StatusCode};\nuse serde::{Deserialize, Serialize};\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse tracing::{debug, error};\nuse url::Url;\n\nuse crate::http::ProgressCallback;\nuse crate::validation::{validate_url, verify_checksum};\n\nconst OCI_MANIFEST_V1_TYPE: &str = \"application/vnd.oci.image.index.v1+json\";\nconst OCI_LAYER_V1_TYPE: &str = \"application/vnd.oci.image.layer.v1.tar+gzip\";\nconst DEFAULT_GHCR_TOKEN_ENDPOINT: &str = \"https://ghcr.io/token\";\npub const DEFAULT_GHCR_DOMAIN: &str = \"ghcr.io\";\n\nconst CONNECT_TIMEOUT_SECS: u64 = 30;\nconst REQUEST_TIMEOUT_SECS: u64 = 300;\nconst USER_AGENT_STRING: &str = \"sps package manager (Rust; +https://github.com/alexykn/sps)\";\n\n#[derive(Deserialize, Debug)]\nstruct OciTokenResponse {\n token: String,\n}\n\n#[derive(Serialize, Deserialize, Debug, Clone)]\n#[serde(rename_all = \"camelCase\")]\npub struct OciManifestIndex {\n pub schema_version: u32,\n pub media_type: Option,\n pub manifests: Vec,\n}\n\n#[derive(Serialize, Deserialize, Debug, Clone)]\n#[serde(rename_all = \"camelCase\")]\npub struct OciManifestDescriptor {\n pub media_type: String,\n pub digest: String,\n pub size: u64,\n pub platform: Option,\n pub annotations: Option>,\n}\n\n#[derive(Serialize, Deserialize, Debug, Clone)]\n#[serde(rename_all = \"camelCase\")]\npub struct OciPlatform {\n pub architecture: String,\n pub os: String,\n #[serde(rename = \"os.version\")]\n pub os_version: Option,\n #[serde(default)]\n pub features: Vec,\n pub variant: Option,\n}\n\n#[derive(Debug, Clone)]\nenum OciAuth {\n None,\n AnonymousBearer { token: String },\n ExplicitBearer { token: String },\n Basic { encoded: String },\n}\n\nasync fn fetch_oci_resource(\n resource_url: &str,\n accept_header: &str,\n config: &Config,\n client: &Client,\n) -> Result {\n let url = Url::parse(resource_url)\n .map_err(|e| SpsError::Generic(format!(\"Invalid URL '{resource_url}': {e}\")))?;\n validate_url(url.as_str())?;\n let registry_domain = url.host_str().unwrap_or(DEFAULT_GHCR_DOMAIN);\n let repo_path = extract_repo_path_from_url(&url).unwrap_or(\"\");\n\n let auth = determine_auth(config, client, registry_domain, repo_path).await?;\n let resp = execute_oci_request(client, resource_url, accept_header, &auth).await?;\n let txt = resp.text().await.map_err(|e| SpsError::Http(Arc::new(e)))?;\n\n debug!(\"OCI response ({} bytes) from {}\", txt.len(), resource_url);\n serde_json::from_str(&txt).map_err(|e| {\n error!(\"JSON parse error from {}: {}\", resource_url, e);\n SpsError::Json(Arc::new(e))\n })\n}\n\npub async fn download_oci_blob(\n blob_url: &str,\n destination_path: &Path,\n config: &Config,\n client: &Client,\n expected_digest: &str,\n) -> Result<()> {\n download_oci_blob_with_progress(\n blob_url,\n destination_path,\n config,\n client,\n expected_digest,\n None,\n )\n .await\n}\n\npub async fn download_oci_blob_with_progress(\n blob_url: &str,\n destination_path: &Path,\n config: &Config,\n client: &Client,\n expected_digest: &str,\n progress_callback: Option,\n) -> Result<()> {\n debug!(\"Downloading OCI blob: {}\", blob_url);\n let url = Url::parse(blob_url)\n .map_err(|e| SpsError::Generic(format!(\"Invalid URL '{blob_url}': {e}\")))?;\n validate_url(url.as_str())?;\n let registry_domain = url.host_str().unwrap_or(DEFAULT_GHCR_DOMAIN);\n let repo_path = extract_repo_path_from_url(&url).unwrap_or(\"\");\n\n let auth = determine_auth(config, client, registry_domain, repo_path).await?;\n let resp = execute_oci_request(client, blob_url, OCI_LAYER_V1_TYPE, &auth).await?;\n\n // Get total size from Content-Length header if available\n let total_size = resp.content_length();\n\n let tmp = destination_path.with_file_name(format!(\n \".{}.download\",\n destination_path.file_name().unwrap().to_string_lossy()\n ));\n let mut out = File::create(&tmp).map_err(|e| SpsError::Io(Arc::new(e)))?;\n\n let mut stream = resp.bytes_stream();\n let mut bytes_downloaded = 0u64;\n\n while let Some(chunk) = stream.next().await {\n let b = chunk.map_err(|e| SpsError::Http(Arc::new(e)))?;\n std::io::Write::write_all(&mut out, &b).map_err(|e| SpsError::Io(Arc::new(e)))?;\n\n bytes_downloaded += b.len() as u64;\n\n // Call progress callback if provided\n if let Some(ref callback) = progress_callback {\n callback(bytes_downloaded, total_size);\n }\n }\n std::fs::rename(&tmp, destination_path).map_err(|e| SpsError::Io(Arc::new(e)))?;\n\n if !expected_digest.is_empty() {\n match verify_checksum(destination_path, expected_digest) {\n Ok(_) => {\n tracing::debug!(\"OCI Blob checksum verified: {}\", destination_path.display());\n }\n Err(e) => {\n tracing::error!(\n \"OCI Blob checksum mismatch ({}). Deleting downloaded file.\",\n e\n );\n let _ = remove_file(destination_path);\n return Err(e);\n }\n }\n } else {\n tracing::warn!(\n \"Skipping checksum verification for OCI blob {} - no checksum provided.\",\n destination_path.display()\n );\n }\n\n debug!(\"Blob saved to {}\", destination_path.display());\n Ok(())\n}\n\npub async fn fetch_oci_manifest_index(\n manifest_url: &str,\n config: &Config,\n client: &Client,\n) -> Result {\n fetch_oci_resource(manifest_url, OCI_MANIFEST_V1_TYPE, config, client).await\n}\n\npub fn build_oci_client() -> Result {\n Client::builder()\n .user_agent(USER_AGENT_STRING)\n .connect_timeout(Duration::from_secs(CONNECT_TIMEOUT_SECS))\n .timeout(Duration::from_secs(REQUEST_TIMEOUT_SECS))\n .redirect(reqwest::redirect::Policy::default())\n .build()\n .map_err(|e| SpsError::Http(Arc::new(e)))\n}\n\nfn extract_repo_path_from_url(url: &Url) -> Option<&str> {\n url.path()\n .trim_start_matches('/')\n .trim_start_matches(\"v2/\")\n .split(\"/manifests/\")\n .next()\n .and_then(|s| s.split(\"/blobs/\").next())\n .filter(|s| !s.is_empty())\n}\n\nasync fn determine_auth(\n config: &Config,\n client: &Client,\n registry_domain: &str,\n repo_path: &str,\n) -> Result {\n if let Some(token) = &config.docker_registry_token {\n debug!(\"Using explicit bearer for {}\", registry_domain);\n return Ok(OciAuth::ExplicitBearer {\n token: token.clone(),\n });\n }\n if let Some(basic) = &config.docker_registry_basic_auth {\n debug!(\"Using explicit basic auth for {}\", registry_domain);\n return Ok(OciAuth::Basic {\n encoded: basic.clone(),\n });\n }\n\n if registry_domain.eq_ignore_ascii_case(DEFAULT_GHCR_DOMAIN) && !repo_path.is_empty() {\n debug!(\n \"Anonymous token fetch for {} scope={}\",\n registry_domain, repo_path\n );\n match fetch_anonymous_token(client, registry_domain, repo_path).await {\n Ok(t) => return Ok(OciAuth::AnonymousBearer { token: t }),\n Err(e) => debug!(\"Anon token failed, proceeding unauthenticated: {}\", e),\n }\n }\n Ok(OciAuth::None)\n}\n\nasync fn fetch_anonymous_token(\n client: &Client,\n registry_domain: &str,\n repo_path: &str,\n) -> Result {\n let endpoint = if registry_domain.eq_ignore_ascii_case(DEFAULT_GHCR_DOMAIN) {\n DEFAULT_GHCR_TOKEN_ENDPOINT.to_string()\n } else {\n format!(\"https://{registry_domain}/token\")\n };\n let scope = format!(\"repository:{repo_path}:pull\");\n let token_url = format!(\"{endpoint}?service={registry_domain}&scope={scope}\");\n\n const MAX_RETRIES: u8 = 3;\n let base_delay = Duration::from_millis(200);\n let mut delay = base_delay;\n // Use a Sendable RNG\n let mut rng = SmallRng::from_os_rng();\n\n for attempt in 0..=MAX_RETRIES {\n debug!(\n \"Token attempt {}/{} from {}\",\n attempt + 1,\n MAX_RETRIES + 1,\n token_url\n );\n\n match client.get(&token_url).send().await {\n Ok(resp) if resp.status().is_success() => {\n let tok: OciTokenResponse = resp\n .json()\n .await\n .map_err(|e| SpsError::ApiRequestError(format!(\"Parse token response: {e}\")))?;\n return Ok(tok.token);\n }\n Ok(resp) => {\n let code = resp.status();\n let body = resp.text().await.unwrap_or_default();\n error!(\"Token fetch {}: {} – {}\", attempt + 1, code, body);\n if !code.is_server_error() || attempt == MAX_RETRIES {\n return Err(SpsError::Api(format!(\"Token endpoint {code}: {body}\")));\n }\n }\n Err(e) => {\n error!(\"Network error on token fetch {}: {}\", attempt + 1, e);\n if attempt == MAX_RETRIES {\n return Err(SpsError::Http(Arc::new(e)));\n }\n }\n }\n\n let jitter = rng.random_range(0..(base_delay.as_millis() as u64 / 2));\n tokio::time::sleep(delay + Duration::from_millis(jitter)).await;\n delay *= 2;\n }\n\n Err(SpsError::Api(format!(\n \"Failed to fetch OCI token after {} attempts\",\n MAX_RETRIES + 1\n )))\n}\n\nasync fn execute_oci_request(\n client: &Client,\n url: &str,\n accept: &str,\n auth: &OciAuth,\n) -> Result {\n debug!(\"OCI request → {} (Accept: {})\", url, accept);\n let mut req = client.get(url).header(ACCEPT, accept);\n match auth {\n OciAuth::AnonymousBearer { token } | OciAuth::ExplicitBearer { token }\n if !token.is_empty() =>\n {\n req = req.header(AUTHORIZATION, format!(\"Bearer {token}\"))\n }\n OciAuth::Basic { encoded } if !encoded.is_empty() => {\n req = req.header(AUTHORIZATION, format!(\"Basic {encoded}\"))\n }\n _ => {}\n }\n\n let resp = req.send().await.map_err(|e| SpsError::Http(Arc::new(e)))?;\n let status = resp.status();\n if status.is_success() {\n Ok(resp)\n } else {\n let body = resp.text().await.unwrap_or_default();\n error!(\"OCI {} ⇒ {} – {}\", url, status, body);\n let err = match status {\n StatusCode::UNAUTHORIZED => SpsError::Api(format!(\"Auth required: {status}\")),\n StatusCode::FORBIDDEN => SpsError::Api(format!(\"Permission denied: {status}\")),\n StatusCode::NOT_FOUND => SpsError::NotFound(format!(\"Not found: {status}\")),\n _ => SpsError::Api(format!(\"HTTP {status} – {body}\")),\n };\n Err(err)\n }\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/font.rs", "// ===== sps-core/src/build/cask/artifacts/font.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Implements the `font` stanza by moving each declared\n/// font file or directory from the staging area into\n/// `~/Library/Fonts`, then symlinking it in the Caskroom.\n///\n/// Mirrors Homebrew’s `Dictionary < Moved` and `Colorpicker < Moved` pattern.\npub fn install_font(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n // Look for \"font\" entries in the JSON artifacts\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"font\").and_then(|v| v.as_array()) {\n // Target directory for user fonts\n let dest_dir = config.home_dir().join(\"Library\").join(\"Fonts\");\n fs::create_dir_all(&dest_dir)?;\n\n for entry in entries {\n if let Some(name) = entry.as_str() {\n let src = stage_path.join(name);\n if !src.exists() {\n debug!(\"Font '{}' not found in staging; skipping\", name);\n continue;\n }\n\n let dest = dest_dir.join(name);\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\"Installing font '{}' → '{}'\", src.display(), dest.display());\n // Try move, fallback to copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record moved font\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink into Caskroom for reference\n let link = cask_version_install_path.join(name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // single font stanza per cask\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/dictionary.rs", "// ===== sps-core/src/build/cask/artifacts/dictionary.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Implements the `dictionary` stanza by moving each declared\n/// `.dictionary` bundle from the staging area into `~/Library/Dictionaries`,\n/// then symlinking it in the Caskroom.\n///\n/// Homebrew’s Ruby definition is simply:\n/// ```ruby\n/// class Dictionary < Moved; end\n/// ```\n/// :contentReference[oaicite:2]{index=2}\npub fn install_dictionary(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n // Find any `dictionary` arrays in the raw JSON artifacts\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"dictionary\").and_then(|v| v.as_array()) {\n for entry in entries {\n if let Some(bundle_name) = entry.as_str() {\n let src = stage_path.join(bundle_name);\n if !src.exists() {\n debug!(\n \"Dictionary bundle '{}' not found in staging; skipping\",\n bundle_name\n );\n continue;\n }\n\n // Standard user dictionary directory: ~/Library/Dictionaries\n // :contentReference[oaicite:3]{index=3}\n let dest_dir = config\n .home_dir() // e.g. /Users/alxknt\n .join(\"Library\")\n .join(\"Dictionaries\");\n fs::create_dir_all(&dest_dir)?;\n\n let dest = dest_dir.join(bundle_name);\n // Remove any previous install\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Moving dictionary '{}' → '{}'\",\n src.display(),\n dest.display()\n );\n // Try a direct move; fall back to recursive copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record the moved bundle\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink back into Caskroom for reference\n let link = cask_version_install_path.join(bundle_name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // Only one `dictionary` stanza per cask\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/keyboard_layout.rs", "// ===== sps-core/src/build/cask/artifacts/keyboard_layout.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Mirrors Homebrew’s `KeyboardLayout < Moved` behavior.\npub fn install_keyboard_layout(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"keyboard_layout\").and_then(|v| v.as_array()) {\n // Target directory for user keyboard layouts\n let dest_dir = config.home_dir().join(\"Library\").join(\"Keyboard Layouts\");\n fs::create_dir_all(&dest_dir)?;\n\n for entry in entries {\n if let Some(bundle_name) = entry.as_str() {\n let src = stage_path.join(bundle_name);\n if !src.exists() {\n debug!(\n \"Keyboard layout '{}' not found in staging; skipping\",\n bundle_name\n );\n continue;\n }\n\n let dest = dest_dir.join(bundle_name);\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Installing keyboard layout '{}' → '{}'\",\n src.display(),\n dest.display()\n );\n // Try move, fallback to copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record moved bundle\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink into Caskroom\n let link = cask_version_install_path.join(bundle_name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // one stanza only\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/service.rs", "// ===== sps-core/src/build/cask/artifacts/service.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers;\n\n/// Installs `service` artifacts by moving each declared\n/// Automator workflow or service bundle from the staging area into\n/// `~/Library/Services`, then symlinking it in the Caskroom.\n///\n/// Mirrors Homebrew’s `Service < Moved` behavior.\npub fn install_service(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"service\").and_then(|v| v.as_array()) {\n // Target directory for user Services\n let dest_dir = config.home_dir().join(\"Library\").join(\"Services\");\n fs::create_dir_all(&dest_dir)?;\n\n for entry in entries {\n if let Some(bundle_name) = entry.as_str() {\n let src = stage_path.join(bundle_name);\n if !src.exists() {\n debug!(\n \"Service bundle '{}' not found in staging; skipping\",\n bundle_name\n );\n continue;\n }\n\n let dest = dest_dir.join(bundle_name);\n if dest.exists() {\n let _ = helpers::remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Installing service '{}' → '{}'\",\n src.display(),\n dest.display()\n );\n // Try move, fallback to copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record moved service\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink into Caskroom for reference\n let link = cask_version_install_path.join(bundle_name);\n let _ = helpers::remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // one stanza only\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/qlplugin.rs", "// ===== sps-core/src/build/cask/artifacts/qlplugin.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Installs `qlplugin` bundles from the staging area into\n/// `~/Library/QuickLook`, then symlinks them into the Caskroom.\n///\n/// Mirrors Homebrew’s `QuickLook < Moved` pattern for QuickLook plugins.\npub fn install_qlplugin(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n // Look for \"qlplugin\" entries in the JSON artifacts\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"qlplugin\").and_then(|v| v.as_array()) {\n // Target directory for QuickLook plugins\n let dest_dir = config.home_dir().join(\"Library\").join(\"QuickLook\");\n fs::create_dir_all(&dest_dir)?;\n\n for entry in entries {\n if let Some(bundle_name) = entry.as_str() {\n let src = stage_path.join(bundle_name);\n if !src.exists() {\n debug!(\n \"QuickLook plugin '{}' not found in staging; skipping\",\n bundle_name\n );\n continue;\n }\n\n let dest = dest_dir.join(bundle_name);\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Installing QuickLook plugin '{}' → '{}',\",\n src.display(),\n dest.display()\n );\n // Try move, fallback to copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record moved plugin\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink into Caskroom for reference\n let link = cask_version_install_path.join(bundle_name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // single stanza\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/internet_plugin.rs", "// ===== sps-core/src/build/cask/artifacts/internet_plugin.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Implements the `internet_plugin` stanza by moving each declared\n/// internet plugin bundle from the staging area into\n/// `~/Library/Internet Plug-Ins`, then symlinking it in the Caskroom.\n///\n/// Mirrors Homebrew’s `InternetPlugin < Moved` pattern.\npub fn install_internet_plugin(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n // Look for \"internet_plugin\" entries in the JSON artifacts\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"internet_plugin\").and_then(|v| v.as_array()) {\n // Target directory for user internet plugins\n let dest_dir = config.home_dir().join(\"Library\").join(\"Internet Plug-Ins\");\n fs::create_dir_all(&dest_dir)?;\n\n for entry in entries {\n if let Some(name) = entry.as_str() {\n let src = stage_path.join(name);\n if !src.exists() {\n debug!(\"Internet plugin '{}' not found in staging; skipping\", name);\n continue;\n }\n\n let dest = dest_dir.join(name);\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Installing internet plugin '{}' → '{}'\",\n src.display(),\n dest.display()\n );\n // Try move, fallback to copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record moved plugin\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink into Caskroom for reference\n let link = cask_version_install_path.join(name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // single stanza\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/screen_saver.rs", "// ===== sps-core/src/build/cask/artifacts/screen_saver.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Installs `screen_saver` bundles from the staging area into\n/// `~/Library/Screen Savers`, then symlinks them into the Caskroom.\n///\n/// Mirrors Homebrew’s `ScreenSaver < Moved` pattern.\npub fn install_screen_saver(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"screen_saver\").and_then(|v| v.as_array()) {\n // Target directory for user screen savers\n let dest_dir = config.home_dir().join(\"Library\").join(\"Screen Savers\");\n fs::create_dir_all(&dest_dir)?;\n\n for entry in entries {\n if let Some(bundle_name) = entry.as_str() {\n let src = stage_path.join(bundle_name);\n if !src.exists() {\n debug!(\n \"Screen saver '{}' not found in staging; skipping\",\n bundle_name\n );\n continue;\n }\n\n let dest = dest_dir.join(bundle_name);\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Installing screen saver '{}' → '{}',\",\n src.display(),\n dest.display()\n );\n // Try move, fallback to copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record moved screen saver\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink into Caskroom for reference\n let link = cask_version_install_path.join(bundle_name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // single stanza\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/prefpane.rs", "// ===== sps-core/src/build/cask/artifacts/prefpane.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Implements the `prefpane` stanza by moving each declared\n/// preference pane bundle from the staging area into\n/// `~/Library/PreferencePanes`, then symlinking it in the Caskroom.\n///\n/// Mirrors Homebrew’s `Prefpane < Moved` pattern.\npub fn install_prefpane(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n // Look for \"prefpane\" entries in the JSON artifacts\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"prefpane\").and_then(|v| v.as_array()) {\n // Target directory for user preference panes\n let dest_dir = config.home_dir().join(\"Library\").join(\"PreferencePanes\");\n fs::create_dir_all(&dest_dir)?;\n\n for entry in entries {\n if let Some(bundle_name) = entry.as_str() {\n let src = stage_path.join(bundle_name);\n if !src.exists() {\n debug!(\n \"Preference pane '{}' not found in staging; skipping\",\n bundle_name\n );\n continue;\n }\n\n let dest = dest_dir.join(bundle_name);\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Installing prefpane '{}' → '{}'\",\n src.display(),\n dest.display()\n );\n // Try move, fallback to copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record moved bundle\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink into Caskroom for reference\n let link = cask_version_install_path.join(bundle_name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // single stanza\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/audio_unit_plugin.rs", "// ===== sps-core/src/build/cask/artifacts/audio_unit_plugin.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Installs `audio_unit_plugin` bundles from the staging area into\n/// `~/Library/Audio/Plug-Ins/Components`, then symlinks them into the Caskroom.\n///\n/// Mirrors Homebrew’s `AudioUnitPlugin < Moved` pattern.\npub fn install_audio_unit_plugin(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"audio_unit_plugin\").and_then(|v| v.as_array()) {\n // Target directory for Audio Unit components\n let dest_dir = config\n .home_dir()\n .join(\"Library\")\n .join(\"Audio\")\n .join(\"Plug-Ins\")\n .join(\"Components\");\n fs::create_dir_all(&dest_dir)?;\n\n for entry in entries {\n if let Some(bundle_name) = entry.as_str() {\n let src = stage_path.join(bundle_name);\n if !src.exists() {\n debug!(\n \"AudioUnit plugin '{}' not found in staging; skipping\",\n bundle_name\n );\n continue;\n }\n\n let dest = dest_dir.join(bundle_name);\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Installing AudioUnit plugin '{}' → '{}'\",\n src.display(),\n dest.display()\n );\n // Try move, fallback to copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record moved plugin\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink into Caskroom for reference\n let link = cask_version_install_path.join(bundle_name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // one stanza only\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/vst_plugin.rs", "// ===== sps-core/src/build/cask/artifacts/vst_plugin.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Installs `vst_plugin` bundles from the staging area into\n/// `~/Library/Audio/Plug-Ins/VST`, then symlinks them into the Caskroom.\n///\n/// Mirrors Homebrew’s `VstPlugin < Moved` pattern.\npub fn install_vst_plugin(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"vst_plugin\").and_then(|v| v.as_array()) {\n // Target directory for VST plugins\n let dest_dir = config\n .home_dir()\n .join(\"Library\")\n .join(\"Audio\")\n .join(\"Plug-Ins\")\n .join(\"VST\");\n fs::create_dir_all(&dest_dir)?;\n\n for entry in entries {\n if let Some(bundle_name) = entry.as_str() {\n let src = stage_path.join(bundle_name);\n if !src.exists() {\n debug!(\n \"VST plugin '{}' not found in staging; skipping\",\n bundle_name\n );\n continue;\n }\n\n let dest = dest_dir.join(bundle_name);\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Installing VST plugin '{}' → '{}'\",\n src.display(),\n dest.display()\n );\n // Try move, fallback to copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record moved plugin\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink into Caskroom for reference\n let link = cask_version_install_path.join(bundle_name);\n let _ = remove_path_robustly(&link, config, true);\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // single stanza\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-common/src/cache.rs", "// src/utils/cache.rs\n// Handles caching of formula data and downloads\n\nuse std::fs;\nuse std::path::{Path, PathBuf};\nuse std::time::{Duration, SystemTime};\n\nuse super::error::{Result, SpsError};\nuse crate::Config;\n\n/// Define how long cache entries are considered valid\nconst CACHE_TTL: Duration = Duration::from_secs(24 * 60 * 60); // 24 hours\n\n/// Cache struct to manage cache operations\npub struct Cache {\n cache_dir: PathBuf,\n _config: Config, // Keep a reference to config if needed for other paths or future use\n}\n\nimpl Cache {\n /// Create a new Cache using the config's cache_dir\n pub fn new(config: &Config) -> Result {\n let cache_dir = config.cache_dir();\n if !cache_dir.exists() {\n fs::create_dir_all(&cache_dir)?;\n }\n\n Ok(Self {\n cache_dir,\n _config: config.clone(),\n })\n }\n\n /// Gets the cache directory path\n pub fn get_dir(&self) -> &Path {\n &self.cache_dir\n }\n\n /// Stores raw string data in the cache\n pub fn store_raw(&self, filename: &str, data: &str) -> Result<()> {\n let path = self.cache_dir.join(filename);\n tracing::debug!(\"Saving raw data to cache file: {:?}\", path);\n fs::write(&path, data)?;\n Ok(())\n }\n\n /// Loads raw string data from the cache\n pub fn load_raw(&self, filename: &str) -> Result {\n let path = self.cache_dir.join(filename);\n tracing::debug!(\"Loading raw data from cache file: {:?}\", path);\n\n if !path.exists() {\n return Err(SpsError::Cache(format!(\n \"Cache file {filename} does not exist\"\n )));\n }\n\n fs::read_to_string(&path).map_err(|e| SpsError::Cache(format!(\"IO error: {e}\")))\n }\n\n /// Checks if a cache file exists and is valid (within TTL)\n pub fn is_cache_valid(&self, filename: &str) -> Result {\n let path = self.cache_dir.join(filename);\n if !path.exists() {\n return Ok(false);\n }\n\n let metadata = fs::metadata(&path)?;\n let modified_time = metadata.modified()?;\n let age = SystemTime::now()\n .duration_since(modified_time)\n .map_err(|e| SpsError::Cache(format!(\"System time error: {e}\")))?;\n\n Ok(age <= CACHE_TTL)\n }\n\n /// Clears a specific cache file\n pub fn clear_file(&self, filename: &str) -> Result<()> {\n let path = self.cache_dir.join(filename);\n if path.exists() {\n fs::remove_file(&path)?;\n }\n Ok(())\n }\n\n /// Clears all cache files\n pub fn clear_all(&self) -> Result<()> {\n if self.cache_dir.exists() {\n fs::remove_dir_all(&self.cache_dir)?;\n fs::create_dir_all(&self.cache_dir)?;\n }\n Ok(())\n }\n\n /// Gets a reference to the config\n pub fn config(&self) -> &Config {\n &self._config\n }\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/vst3_plugin.rs", "// ===== sps-core/src/build/cask/artifacts/vst3_plugin.rs =====\n\nuse std::fs;\nuse std::os::unix::fs::symlink;\nuse std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::helpers::remove_path_robustly;\n\n/// Installs `vst3_plugin` bundles from the staging area into\n/// `~/Library/Audio/Plug-Ins/VST3`, then symlinks them into the Caskroom.\n///\n/// Mirrors Homebrew’s `Vst3Plugin < Moved` pattern.\npub fn install_vst3_plugin(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n if let Some(artifacts_def) = &cask.artifacts {\n for art in artifacts_def {\n if let Some(obj) = art.as_object() {\n if let Some(entries) = obj.get(\"vst3_plugin\").and_then(|v| v.as_array()) {\n // Target directory for VST3 plugins\n let dest_dir = config\n .home_dir()\n .join(\"Library\")\n .join(\"Audio\")\n .join(\"Plug-Ins\")\n .join(\"VST3\");\n fs::create_dir_all(&dest_dir)?;\n\n for entry in entries {\n if let Some(bundle_name) = entry.as_str() {\n let src = stage_path.join(bundle_name);\n if !src.exists() {\n debug!(\n \"VST3 plugin '{}' not found in staging; skipping\",\n bundle_name\n );\n continue;\n }\n\n let dest = dest_dir.join(bundle_name);\n if dest.exists() {\n let _ = remove_path_robustly(&dest, config, true);\n }\n\n debug!(\n \"Installing VST3 plugin '{}' → '{}'\",\n src.display(),\n dest.display()\n );\n // Try move, fallback to copy\n let status = Command::new(\"mv\").arg(&src).arg(&dest).status()?;\n if !status.success() {\n Command::new(\"cp\").arg(\"-R\").arg(&src).arg(&dest).status()?;\n }\n\n // Record moved plugin\n installed.push(InstalledArtifact::MovedResource { path: dest.clone() });\n\n // Symlink into Caskroom for reference\n let link = cask_version_install_path.join(bundle_name);\n let _ = crate::install::cask::helpers::remove_path_robustly(\n &link, config, true,\n );\n symlink(&dest, &link)?;\n installed.push(InstalledArtifact::CaskroomLink {\n link_path: link,\n target_path: dest.clone(),\n });\n }\n }\n break; // single stanza\n }\n }\n }\n }\n\n Ok(installed)\n}\n"], ["/sps/sps-net/src/validation.rs", "// sps-io/src/checksum.rs\n//use std::sync::Arc;\nuse std::fs::File;\nuse std::io;\nuse std::path::Path;\n\nuse infer;\nuse sha2::{Digest, Sha256};\nuse sps_common::error::{Result, SpsError};\nuse url::Url;\n//use tokio::fs::File;\n//use tokio::io::AsyncReadExt;\n//use tracing::debug; // Use tracing\n\n///// Asynchronously verifies the SHA256 checksum of a file.\n///// Reads the file asynchronously but performs hashing synchronously.\n//pub async fn verify_checksum_async(path: &Path, expected: &str) -> Result<()> {\n//debug!(\"Async Verifying checksum for: {}\", path.display());\n// let file = File::open(path).await;\n// let mut file = match file {\n// Ok(f) => f,\n// Err(e) => {\n// return Err(SpsError::Io(Arc::new(e))); // Wrap IO error\n// }\n// };\n//\n// let mut hasher = Sha256::new();\n// let mut buffer = Vec::with_capacity(8192); // Use a Vec as buffer for read_buf\n// let mut total_bytes_read = 0;\n//\n// loop {\n// buffer.clear();\n// match file.read_buf(&mut buffer).await {\n// Ok(0) => break, // End of file\n// Ok(n) => {\n// hasher.update(&buffer[..n]);\n// total_bytes_read += n as u64;\n// }\n// Err(e) => {\n// return Err(SpsError::Io(Arc::new(e))); // Wrap IO error\n// }\n// }\n// }\n//\n// let hash_bytes = hasher.finalize();\n// let actual = hex::encode(hash_bytes);\n//\n// debug!(\n// \"Async Calculated SHA256: {} ({} bytes read)\",\n// actual, total_bytes_read\n// );\n// debug!(\"Expected SHA256: {}\", expected);\n//\n// if actual.eq_ignore_ascii_case(expected) {\n// Ok(())\n// } else {\n// Err(SpsError::ChecksumError(format!(\n// \"Checksum mismatch for {}: expected {}, got {}\",\n// path.display(),\n// expected,\n// actual\n// )))\n// }\n//}\n\n// Keep the synchronous version for now if needed elsewhere or for comparison\npub fn verify_checksum(path: &Path, expected: &str) -> Result<()> {\n tracing::debug!(\"Verifying checksum for: {}\", path.display());\n let mut file = File::open(path)?;\n let mut hasher = Sha256::new();\n let bytes_copied = io::copy(&mut file, &mut hasher)?;\n let hash_bytes = hasher.finalize();\n let actual = hex::encode(hash_bytes);\n tracing::debug!(\n \"Calculated SHA256: {} ({} bytes read)\",\n actual,\n bytes_copied\n );\n tracing::debug!(\"Expected SHA256: {}\", expected);\n if actual.eq_ignore_ascii_case(expected) {\n Ok(())\n } else {\n Err(SpsError::ChecksumError(format!(\n \"Checksum mismatch for {}: expected {}, got {}\",\n path.display(),\n expected,\n actual\n )))\n }\n}\n\n/// Verifies that the detected content type of the file matches the expected extension.\npub fn verify_content_type(path: &Path, expected_ext: &str) -> Result<()> {\n let kind_opt = infer::get_from_path(path)?;\n if let Some(kind) = kind_opt {\n let actual_ext = kind.extension();\n if actual_ext.eq_ignore_ascii_case(expected_ext) {\n tracing::debug!(\n \"Content type verified: {} matches expected {}\",\n actual_ext,\n expected_ext\n );\n Ok(())\n } else {\n Err(SpsError::Generic(format!(\n \"Content type mismatch for {}: expected extension '{}', but detected '{}'\",\n path.display(),\n expected_ext,\n actual_ext\n )))\n }\n } else {\n Err(SpsError::Generic(format!(\n \"Could not determine content type for {}\",\n path.display()\n )))\n }\n}\n\n/// Validates a URL, ensuring it uses the HTTPS scheme.\npub fn validate_url(url_str: &str) -> Result<()> {\n let url = Url::parse(url_str)\n .map_err(|e| SpsError::Generic(format!(\"Failed to parse URL '{url_str}': {e}\")))?;\n if url.scheme() == \"https\" {\n Ok(())\n } else {\n Err(SpsError::ValidationError(format!(\n \"Invalid URL scheme for '{}': Must be https, but got '{}'\",\n url_str,\n url.scheme()\n )))\n }\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/uninstall.rs", "use std::path::PathBuf;\n\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\n\n/// At install time, scan the `uninstall` stanza and turn each directive\n/// into an InstalledArtifact variant, so it can later be torn down.\npub fn record_uninstall(cask: &Cask) -> Result> {\n let mut artifacts = Vec::new();\n\n if let Some(entries) = &cask.artifacts {\n for entry in entries.iter().filter_map(|v| v.as_object()) {\n if let Some(steps) = entry.get(\"uninstall\").and_then(|v| v.as_array()) {\n for step in steps.iter().filter_map(|v| v.as_object()) {\n for (key, val) in step {\n match key.as_str() {\n \"pkgutil\" => {\n if let Some(id) = val.as_str() {\n artifacts.push(InstalledArtifact::PkgUtilReceipt {\n id: id.to_string(),\n });\n }\n }\n \"delete\" => {\n if let Some(arr) = val.as_array() {\n for p in arr.iter().filter_map(|v| v.as_str()) {\n artifacts.push(InstalledArtifact::MovedResource {\n path: PathBuf::from(p),\n });\n }\n }\n }\n \"rmdir\" => {\n if let Some(arr) = val.as_array() {\n for p in arr.iter().filter_map(|v| v.as_str()) {\n artifacts.push(InstalledArtifact::MovedResource {\n path: PathBuf::from(p),\n });\n }\n }\n }\n \"launchctl\" => {\n if let Some(arr) = val.as_array() {\n for lbl in arr.iter().filter_map(|v| v.as_str()) {\n artifacts.push(InstalledArtifact::Launchd {\n label: lbl.to_string(),\n path: None,\n });\n }\n }\n }\n // Add other uninstall keys similarly...\n _ => {}\n }\n }\n }\n }\n }\n }\n\n Ok(artifacts)\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/input_method.rs", "// ===== sps-core/src/build/cask/artifacts/input_method.rs =====\n\nuse std::fs;\nuse std::os::unix::fs as unix_fs;\nuse std::path::Path;\n\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_common::model::artifact::InstalledArtifact;\nuse sps_common::model::cask::Cask;\n\nuse crate::install::cask::helpers::remove_path_robustly;\nuse crate::install::cask::write_cask_manifest;\n\n/// Install `input_method` artifacts from the staged directory into\n/// `~/Library/Input Methods` and record installed artifacts.\npub fn install_input_method(\n cask: &Cask,\n stage_path: &Path,\n cask_version_install_path: &Path,\n config: &Config,\n) -> Result> {\n let mut installed = Vec::new();\n\n // Ensure we have an array of input_method names\n if let Some(artifacts_def) = &cask.artifacts {\n for artifact_value in artifacts_def {\n if let Some(obj) = artifact_value.as_object() {\n if let Some(names) = obj.get(\"input_method\").and_then(|v| v.as_array()) {\n for name_val in names {\n if let Some(name) = name_val.as_str() {\n let source = stage_path.join(name);\n if source.exists() {\n // Target directory: ~/Library/Input Methods\n let target_dir =\n config.home_dir().join(\"Library\").join(\"Input Methods\");\n if !target_dir.exists() {\n fs::create_dir_all(&target_dir)?;\n }\n let target = target_dir.join(name);\n\n // Remove existing input method if present\n if target.exists() {\n let _ = remove_path_robustly(&target, config, true);\n }\n\n // Move (or rename) the staged bundle\n fs::rename(&source, &target)\n .or_else(|_| unix_fs::symlink(&source, &target))?;\n\n // Record the main artifact\n installed.push(InstalledArtifact::MovedResource {\n path: target.clone(),\n });\n\n // Create a caskroom symlink for uninstallation\n let link_path = cask_version_install_path.join(name);\n if link_path.exists() {\n let _ = remove_path_robustly(&link_path, config, true);\n }\n #[cfg(unix)]\n std::os::unix::fs::symlink(&target, &link_path)?;\n\n installed.push(InstalledArtifact::CaskroomLink {\n link_path,\n target_path: target,\n });\n }\n }\n }\n }\n }\n }\n }\n\n // Write manifest for these artifacts\n write_cask_manifest(cask, cask_version_install_path, installed.clone())?;\n Ok(installed)\n}\n"], ["/sps/sps/src/cli/update.rs", "//! Contains the logic for the `update` command.\nuse std::fs;\nuse std::sync::Arc;\n\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_net::api;\n\n#[derive(clap::Args, Debug)]\npub struct Update;\n\nimpl Update {\n pub async fn run(&self, config: &Config, cache: Arc) -> Result<()> {\n tracing::debug!(\"Running manual update...\"); // Log clearly it's the manual one\n\n // Use the ui utility function to create the spinner\n println!(\"Updating package lists\"); // <-- CHANGED\n\n tracing::debug!(\"Using cache directory: {:?}\", config.cache_dir());\n\n // Fetch and store raw formula data\n match api::fetch_all_formulas().await {\n Ok(raw_data) => {\n cache.store_raw(\"formula.json\", &raw_data)?;\n tracing::debug!(\"✓ Successfully cached formulas data\");\n println!(\"Cached formulas data\");\n }\n Err(e) => {\n let err_msg = format!(\"Failed to fetch/store formulas from API: {e}\");\n tracing::error!(\"{}\", err_msg);\n println!(); // Clear spinner on error\n return Err(e);\n }\n }\n\n // Fetch and store raw cask data\n match api::fetch_all_casks().await {\n Ok(raw_data) => {\n cache.store_raw(\"cask.json\", &raw_data)?;\n tracing::debug!(\"✓ Successfully cached casks data\");\n println!(\"Cached casks data\");\n }\n Err(e) => {\n let err_msg = format!(\"Failed to fetch/store casks from API: {e}\");\n tracing::error!(\"{}\", err_msg);\n return Err(e);\n }\n }\n\n // Update timestamp file\n let timestamp_file = config.state_dir().join(\".sps_last_update_check\");\n tracing::debug!(\n \"Manual update successful. Updating timestamp file: {}\",\n timestamp_file.display()\n );\n match fs::File::create(×tamp_file) {\n Ok(_) => {\n tracing::debug!(\"Updated timestamp file successfully.\");\n }\n Err(e) => {\n tracing::warn!(\n \"Failed to create or update timestamp file '{}': {}\",\n timestamp_file.display(),\n e\n );\n }\n }\n\n println!(\"Update completed successfully!\");\n Ok(())\n }\n}\n"], ["/sps/sps-common/src/model/version.rs", "// **File:** sps-core/src/model/version.rs (New file)\nuse std::fmt;\nuse std::str::FromStr;\n\nuse serde::{Deserialize, Deserializer, Serialize, Serializer};\n\nuse crate::error::{Result, SpsError};\n\n/// Wrapper around semver::Version for formula versions.\n#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]\npub struct Version(semver::Version);\n\nimpl Version {\n pub fn parse(s: &str) -> Result {\n // Attempt standard semver parse first\n semver::Version::parse(s).map(Version).or_else(|_| {\n // Homebrew often uses versions like \"1.2.3_1\" (revision) or just \"123\"\n // Try to handle these by stripping suffixes or padding\n // This is a simplified handling, Homebrew's PkgVersion is complex\n let cleaned = s.split('_').next().unwrap_or(s); // Take part before _\n let parts: Vec<&str> = cleaned.split('.').collect();\n let padded = match parts.len() {\n 1 => format!(\"{}.0.0\", parts[0]),\n 2 => format!(\"{}.{}.0\", parts[0], parts[1]),\n _ => cleaned.to_string(), // Use original if 3+ parts\n };\n semver::Version::parse(&padded).map(Version).map_err(|e| {\n SpsError::VersionError(format!(\n \"Failed to parse version '{s}' (tried '{padded}'): {e}\"\n ))\n })\n })\n }\n}\n\nimpl FromStr for Version {\n type Err = SpsError;\n fn from_str(s: &str) -> std::result::Result {\n Self::parse(s)\n }\n}\n\nimpl fmt::Display for Version {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n // TODO: Preserve original format if possible? PkgVersion complexity.\n // For now, display the parsed semver representation.\n write!(f, \"{}\", self.0)\n }\n}\n\n// Manual Serialize/Deserialize to handle the Version<->String conversion\nimpl Serialize for Version {\n fn serialize(&self, serializer: S) -> std::result::Result\n where\n S: Serializer,\n {\n serializer.serialize_str(&self.to_string())\n }\n}\n\nimpl AsRef for Version {\n fn as_ref(&self) -> &Self {\n self\n }\n}\n\n// Removed redundant ToString implementation as it conflicts with the blanket implementation in std.\n\nimpl From for semver::Version {\n fn from(version: Version) -> Self {\n version.0\n }\n}\n\nimpl<'de> Deserialize<'de> for Version {\n fn deserialize(deserializer: D) -> std::result::Result\n where\n D: Deserializer<'de>,\n {\n let s = String::deserialize(deserializer)?;\n Self::from_str(&s).map_err(serde::de::Error::custom)\n }\n}\n\n// Add to sps-core/src/utils/error.rs:\n// #[error(\"Version error: {0}\")]\n// VersionError(String),\n\n// Add to sps-core/Cargo.toml:\n// [dependencies]\n// semver = \"1.0\"\n"], ["/sps/sps-common/src/pipeline.rs", "// sps-common/src/pipeline.rs\nuse std::path::PathBuf;\nuse std::sync::Arc; // Required for Arc in JobProcessingState\n\nuse serde::{Deserialize, Serialize};\n\nuse crate::dependency::ResolvedGraph; // Needed for planner output\nuse crate::error::SpsError;\nuse crate::model::InstallTargetIdentifier;\n\n// --- Shared Enums / Structs ---\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]\npub enum PipelinePackageType {\n Formula,\n Cask,\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] // Added PartialEq, Eq\npub enum JobAction {\n Install,\n Upgrade {\n from_version: String,\n old_install_path: PathBuf,\n },\n Reinstall {\n version: String,\n current_install_path: PathBuf,\n },\n}\n\n#[derive(Debug, Clone)]\npub struct PlannedJob {\n pub target_id: String,\n pub target_definition: InstallTargetIdentifier,\n pub action: JobAction,\n pub is_source_build: bool,\n pub use_private_store_source: Option,\n}\n\n#[derive(Debug, Clone)]\npub struct WorkerJob {\n pub request: PlannedJob,\n pub download_path: PathBuf,\n pub download_size_bytes: u64,\n pub is_source_from_private_store: bool,\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub enum PipelineEvent {\n PipelineStarted {\n total_jobs: usize,\n },\n PipelineFinished {\n duration_secs: f64,\n success_count: usize,\n fail_count: usize,\n },\n PlanningStarted,\n DependencyResolutionStarted,\n DependencyResolutionFinished,\n PlanningFinished {\n job_count: usize,\n // Optionally, we can pass the ResolvedGraph here if the status handler needs it,\n // but it might be too large for a broadcast event.\n // resolved_graph: Option>, // Example\n },\n DownloadStarted {\n target_id: String,\n url: String,\n },\n DownloadFinished {\n target_id: String,\n path: PathBuf,\n size_bytes: u64,\n },\n DownloadProgressUpdate {\n target_id: String,\n bytes_so_far: u64,\n total_size: Option,\n },\n DownloadCached {\n target_id: String,\n size_bytes: u64,\n },\n DownloadFailed {\n target_id: String,\n url: String,\n error: String, // Keep as String for simplicity in events\n },\n JobProcessingStarted {\n // From core worker\n target_id: String,\n },\n JobDispatchedToCore {\n // New: From runner to UI when job sent to worker pool\n target_id: String,\n },\n UninstallStarted {\n target_id: String,\n version: String,\n },\n UninstallFinished {\n target_id: String,\n version: String,\n },\n BuildStarted {\n target_id: String,\n },\n InstallStarted {\n target_id: String,\n pkg_type: PipelinePackageType,\n },\n LinkStarted {\n target_id: String,\n pkg_type: PipelinePackageType,\n },\n JobSuccess {\n // From core worker\n target_id: String,\n action: JobAction,\n pkg_type: PipelinePackageType,\n },\n JobFailed {\n // From core worker or runner (propagated)\n target_id: String,\n action: JobAction, // Action that was attempted\n error: String, // Keep as String\n },\n LogInfo {\n message: String,\n },\n LogWarn {\n message: String,\n },\n LogError {\n message: String,\n },\n}\n\nimpl PipelineEvent {\n // SpsError kept for internal use, but events use String for error messages\n pub fn job_failed(target_id: String, action: JobAction, error: &SpsError) -> Self {\n PipelineEvent::JobFailed {\n target_id,\n action,\n error: error.to_string(),\n }\n }\n pub fn download_failed(target_id: String, url: String, error: &SpsError) -> Self {\n PipelineEvent::DownloadFailed {\n target_id,\n url,\n error: error.to_string(),\n }\n }\n}\n\n// --- New Structs and Enums for Refactored Runner ---\n\n/// Represents the current processing state of a job in the pipeline.\n#[derive(Debug, Clone)]\npub enum JobProcessingState {\n /// Waiting for download to be initiated.\n PendingDownload,\n /// Download is in progress (managed by DownloadCoordinator).\n Downloading,\n /// Download completed successfully, artifact at PathBuf.\n Downloaded(PathBuf),\n /// Downloaded, but waiting for dependencies to be in Succeeded state.\n WaitingForDependencies(PathBuf),\n /// Dispatched to the core worker pool for installation/processing.\n DispatchedToCore(PathBuf),\n /// Installation/processing is in progress by a core worker.\n Installing(PathBuf), // Path is still relevant\n /// Job completed successfully.\n Succeeded,\n /// Job failed. The String contains the error message. Arc for cheap cloning.\n Failed(Arc),\n}\n\n/// Outcome of a download attempt, sent from DownloadCoordinator to the main runner loop.\n#[derive(Debug)] // Clone not strictly needed if moved\npub struct DownloadOutcome {\n pub planned_job: PlannedJob, // The job this download was for\n pub result: Result, // Path to downloaded file or error\n}\n\n/// Structure returned by the planner, now including the ResolvedGraph.\n#[derive(Debug, Default)]\npub struct PlannedOperations {\n pub jobs: Vec, // Topologically sorted for formulae\n pub errors: Vec<(String, SpsError)>, // Errors from planning phase\n pub already_installed_or_up_to_date: std::collections::HashSet,\n pub resolved_graph: Option>, // Graph for dependency checking in runner\n}\n"], ["/sps/sps-core/src/upgrade/cask.rs", "// sps-core/src/upgrade/cask.rs\n\nuse std::path::Path;\n\nuse sps_common::config::Config;\nuse sps_common::error::{Result as SpsResult, SpsError};\nuse sps_common::model::cask::Cask;\nuse sps_common::pipeline::JobAction; // Required for install_cask\nuse tracing::{debug, error};\n\nuse crate::check::installed::InstalledPackageInfo;\nuse crate::{install, uninstall};\n\n/// Upgrades a cask package using Homebrew's proven strategy.\npub async fn upgrade_cask_package(\n cask: &Cask,\n new_cask_download_path: &Path,\n old_install_info: &InstalledPackageInfo,\n config: &Config,\n) -> SpsResult<()> {\n debug!(\n \"Upgrading cask {} from {} to {}\",\n cask.token,\n old_install_info.version,\n cask.version.as_deref().unwrap_or(\"latest\")\n );\n\n // 1. Soft-uninstall the old version\n // This removes linked artifacts and updates the old manifest's is_installed flag.\n // It does not remove the old Caskroom version directory itself yet.\n debug!(\n \"Soft-uninstalling old cask version: {} at {}\",\n old_install_info.version,\n old_install_info.path.display()\n );\n uninstall::cask::uninstall_cask_artifacts(old_install_info, config).map_err(|e| {\n error!(\n \"Failed to soft-uninstall old version {} of cask {}: {}\",\n old_install_info.version, cask.token, e\n );\n SpsError::InstallError(format!(\n \"Failed to soft-uninstall old version during upgrade of {}: {e}\",\n cask.token\n ))\n })?;\n debug!(\n \"Successfully soft-uninstalled old version of {}\",\n cask.token\n );\n\n // 2. Install the new version\n // The install_cask function, particularly install_app_from_staged,\n // should handle the upgrade logic (like syncing app data) when\n // passed the JobAction::Upgrade.\n debug!(\n \"Installing new version for cask {} from {}\",\n cask.token,\n new_cask_download_path.display()\n );\n\n let job_action_for_install = JobAction::Upgrade {\n from_version: old_install_info.version.clone(),\n old_install_path: old_install_info.path.clone(),\n };\n\n install::cask::install_cask(\n cask,\n new_cask_download_path,\n config,\n &job_action_for_install,\n )\n .map_err(|e| {\n error!(\n \"Failed to install new version of cask {}: {}\",\n cask.token, e\n );\n SpsError::InstallError(format!(\n \"Failed to install new version during upgrade of {}: {e}\",\n cask.token\n ))\n })?;\n debug!(\"Successfully installed new version of cask {}\", cask.token);\n\n Ok(())\n}\n"], ["/sps/sps-core/src/install/cask/artifacts/preflight.rs", "use std::path::Path;\nuse std::process::Command;\n\nuse sps_common::config::Config;\nuse sps_common::error::{Result, SpsError};\nuse sps_common::model::cask::Cask;\nuse tracing::debug;\n\nuse crate::install::cask::InstalledArtifact;\n\n/// Execute any `preflight` commands listed in the Cask’s JSON artifact stanza.\n/// Returns an empty Vec since preflight does not produce install artifacts.\npub fn run_preflight(\n cask: &Cask,\n stage_path: &Path,\n _config: &Config,\n) -> Result> {\n // Iterate over artifacts, look for \"preflight\" keys\n if let Some(entries) = &cask.artifacts {\n for entry in entries.iter().filter_map(|v| v.as_object()) {\n if let Some(cmds) = entry.get(\"preflight\").and_then(|v| v.as_array()) {\n for cmd_val in cmds.iter().filter_map(|v| v.as_str()) {\n // Substitute $STAGEDIR placeholder\n let cmd_str = cmd_val.replace(\"$STAGEDIR\", stage_path.to_str().unwrap());\n debug!(\"Running preflight: {}\", cmd_str);\n let status = Command::new(\"sh\").arg(\"-c\").arg(&cmd_str).status()?;\n if !status.success() {\n return Err(SpsError::InstallError(format!(\n \"preflight failed: {cmd_str}\"\n )));\n }\n }\n }\n }\n }\n\n // No install artifacts to return\n Ok(Vec::new())\n}\n"], ["/sps/sps-common/src/dependency/definition.rs", "// **File:** sps-core/src/dependency/dependency.rs // Should be in the model module\nuse std::fmt;\n\nuse bitflags::bitflags;\nuse serde::{Deserialize, Serialize};\n\nbitflags! {\n #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]\n pub struct DependencyTag: u8 {\n const RUNTIME = 0b00000001;\n const BUILD = 0b00000010;\n const TEST = 0b00000100;\n const OPTIONAL = 0b00001000;\n const RECOMMENDED = 0b00010000;\n }\n}\n\nimpl Default for DependencyTag {\n fn default() -> Self {\n Self::RUNTIME\n }\n}\n\nimpl fmt::Display for DependencyTag {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"{self:?}\")\n }\n}\n\n#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]\npub struct Dependency {\n pub name: String,\n #[serde(default)]\n pub tags: DependencyTag,\n}\n\nimpl Dependency {\n pub fn new_runtime(name: impl Into) -> Self {\n Self {\n name: name.into(),\n tags: DependencyTag::RUNTIME,\n }\n }\n\n pub fn new_with_tags(name: impl Into, tags: DependencyTag) -> Self {\n Self {\n name: name.into(),\n tags,\n }\n }\n}\n\npub trait DependencyExt {\n fn filter_by_tags(&self, include: DependencyTag, exclude: DependencyTag) -> Vec<&Dependency>;\n fn runtime(&self) -> Vec<&Dependency>;\n fn build_time(&self) -> Vec<&Dependency>;\n}\n\nimpl DependencyExt for Vec {\n fn filter_by_tags(&self, include: DependencyTag, exclude: DependencyTag) -> Vec<&Dependency> {\n self.iter()\n .filter(|dep| dep.tags.contains(include) && !dep.tags.intersects(exclude))\n .collect()\n }\n\n fn runtime(&self) -> Vec<&Dependency> {\n // A dependency is runtime if its tags indicate it's needed at runtime.\n // This includes standard runtime, recommended, or optional dependencies.\n // Build-only or Test-only dependencies (without other runtime flags) are excluded.\n self.iter()\n .filter(|dep| {\n dep.tags.intersects(\n DependencyTag::RUNTIME | DependencyTag::RECOMMENDED | DependencyTag::OPTIONAL,\n )\n })\n .collect()\n }\n\n fn build_time(&self) -> Vec<&Dependency> {\n self.filter_by_tags(DependencyTag::BUILD, DependencyTag::empty())\n }\n}\n"], ["/sps/sps/src/cli.rs", "// sps/src/cli.rs\n//! Defines the command-line argument structure using clap.\nuse std::sync::Arc;\n\nuse clap::{ArgAction, Parser, Subcommand};\nuse sps_common::error::Result;\nuse sps_common::{Cache, Config};\n\n// Module declarations\npub mod info;\npub mod init;\npub mod install;\npub mod list;\npub mod reinstall;\npub mod search;\npub mod status;\npub mod uninstall;\npub mod update;\npub mod upgrade;\n// Re-export InitArgs to make it accessible as cli::InitArgs\n// Import other command Args structs\nuse crate::cli::info::Info;\npub use crate::cli::init::InitArgs;\nuse crate::cli::install::InstallArgs;\nuse crate::cli::list::List;\nuse crate::cli::reinstall::ReinstallArgs;\nuse crate::cli::search::Search;\nuse crate::cli::uninstall::Uninstall;\nuse crate::cli::update::Update;\nuse crate::cli::upgrade::UpgradeArgs;\n\n#[derive(Parser, Debug)]\n#[command(author, version, about, long_about = None, name = \"sps\", bin_name = \"sps\")]\n#[command(propagate_version = true)]\npub struct CliArgs {\n #[arg(short, long, action = ArgAction::Count, global = true)]\n pub verbose: u8,\n\n #[command(subcommand)]\n pub command: Command,\n}\n\n#[derive(Subcommand, Debug)]\npub enum Command {\n Init(InitArgs),\n Search(Search),\n List(List),\n Info(Info),\n Update(Update),\n Install(InstallArgs),\n Uninstall(Uninstall),\n Reinstall(ReinstallArgs),\n Upgrade(UpgradeArgs),\n}\n\nimpl Command {\n pub async fn run(&self, config: &Config, cache: Arc) -> Result<()> {\n match self {\n Self::Init(command) => command.run(config).await,\n Self::Search(command) => command.run(config, cache).await,\n Self::List(command) => command.run(config, cache).await,\n Self::Info(command) => command.run(config, cache).await,\n Self::Update(command) => command.run(config, cache).await,\n // Commands that use the pipeline\n Self::Install(command) => command.run(config, cache).await,\n Self::Reinstall(command) => command.run(config, cache).await,\n Self::Upgrade(command) => command.run(config, cache).await,\n Self::Uninstall(command) => command.run(config, cache).await,\n }\n }\n}\n\n// In install.rs, reinstall.rs, upgrade.rs, their run methods will now call\n// sps::cli::pipeline_runner::run_pipeline(...)\n// e.g., in sps/src/cli/install.rs:\n// use crate::cli::pipeline_runner::{self, CommandType, PipelineFlags};\n// ...\n// pipeline_runner::run_pipeline(&initial_targets, CommandType::Install, config, cache,\n// &flags).await\n"], ["/sps/sps/src/cli/install.rs", "// sps-cli/src/cli/install.rs\n\nuse std::sync::Arc;\n\nuse clap::Args;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse tracing::instrument;\n\n// Import pipeline components from the new module\nuse crate::pipeline::runner::{self, CommandType, PipelineFlags};\n\n// Keep the Args struct specific to 'install' if needed, or reuse a common one\n#[derive(Debug, Args)]\npub struct InstallArgs {\n #[arg(required = true)]\n names: Vec,\n\n // Keep flags relevant to install/pipeline\n #[arg(long)]\n skip_deps: bool, // Note: May not be fully supported by core resolution yet\n #[arg(long, help = \"Force install specified targets as casks\")]\n cask: bool,\n #[arg(long, help = \"Force install specified targets as formulas\")]\n formula: bool,\n #[arg(long)]\n include_optional: bool,\n #[arg(long)]\n skip_recommended: bool,\n #[arg(\n long,\n help = \"Force building the formula from source, even if a bottle is available\"\n )]\n build_from_source: bool,\n // Worker/Queue size flags might belong here or be global CLI flags\n // #[arg(long, value_name = \"sps_WORKERS\")]\n // max_workers: Option,\n // #[arg(long, value_name = \"sps_QUEUE\")]\n // queue_size: Option,\n}\n\nimpl InstallArgs {\n #[instrument(skip(self, config, cache), fields(targets = ?self.names))]\n pub async fn run(&self, config: &Config, cache: Arc) -> Result<()> {\n // --- Argument Validation (moved from old run) ---\n if self.formula && self.cask {\n return Err(sps_common::error::SpsError::Generic(\n \"Cannot use --formula and --cask together.\".to_string(),\n ));\n }\n // Add validation for skip_deps if needed\n\n // --- Prepare Pipeline Flags ---\n let flags = PipelineFlags {\n build_from_source: self.build_from_source,\n include_optional: self.include_optional,\n skip_recommended: self.skip_recommended,\n // Add other flags...\n };\n\n // --- Determine Initial Targets based on --formula/--cask flags ---\n // (This logic might be better inside plan_package_operations based on CommandType)\n let initial_targets = self.names.clone(); // For install, all names are initial targets\n\n // --- Execute the Pipeline ---\n runner::run_pipeline(\n &initial_targets,\n CommandType::Install, // Specify the command type\n config,\n cache,\n &flags, // Pass the flags struct\n )\n .await\n }\n}\n"], ["/sps/sps/src/cli/upgrade.rs", "use std::sync::Arc;\n\nuse clap::Args;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::error::Result;\nuse sps_core::check::installed;\n\nuse crate::pipeline::runner::{self, CommandType, PipelineFlags};\n\n#[derive(Args, Debug)]\npub struct UpgradeArgs {\n #[arg()]\n pub names: Vec,\n\n #[arg(long, conflicts_with = \"names\")]\n pub all: bool,\n\n #[arg(long)]\n pub build_from_source: bool,\n}\n\nimpl UpgradeArgs {\n pub async fn run(&self, config: &Config, cache: Arc) -> Result<()> {\n let targets = if self.all {\n // Get all installed package names\n let installed = installed::get_installed_packages(config).await?;\n installed.into_iter().map(|p| p.name).collect()\n } else {\n self.names.clone()\n };\n\n if targets.is_empty() {\n return Ok(());\n }\n\n let flags = PipelineFlags {\n // Populate flags from args\n build_from_source: self.build_from_source,\n // Upgrade should respect original install options ideally,\n // but for now let's default them. This could be enhanced later\n // by reading install receipts.\n include_optional: false,\n skip_recommended: false,\n // ... add other common flags if needed ...\n };\n\n runner::run_pipeline(\n &targets,\n CommandType::Upgrade { all: self.all },\n config,\n cache,\n &flags,\n )\n .await\n }\n}\n"], ["/sps/sps/src/cli/reinstall.rs", "// sps-cli/src/cli/reinstall.rs\nuse std::sync::Arc;\n\nuse clap::Args;\nuse sps_common::cache::Cache;\nuse sps_common::config::Config;\nuse sps_common::error::Result;\n\nuse crate::pipeline::runner::{self, CommandType, PipelineFlags};\n\n#[derive(Args, Debug)]\npub struct ReinstallArgs {\n #[arg(required = true)]\n pub names: Vec,\n\n #[arg(\n long,\n help = \"Force building the formula from source, even if a bottle is available\"\n )]\n pub build_from_source: bool,\n}\n\nimpl ReinstallArgs {\n pub async fn run(&self, config: &Config, cache: Arc) -> Result<()> {\n let flags = PipelineFlags {\n // Populate flags from args\n build_from_source: self.build_from_source,\n include_optional: false, // Reinstall usually doesn't change optional deps\n skip_recommended: true, /* Reinstall usually doesn't change recommended deps\n * ... add other common flags if needed ... */\n };\n runner::run_pipeline(&self.names, CommandType::Reinstall, config, cache, &flags).await\n }\n}\n"], ["/sps/sps-common/src/model/artifact.rs", "// sps-common/src/model/artifact.rs\nuse std::path::PathBuf;\n\nuse serde::{Deserialize, Serialize};\n\n/// Represents an item installed or managed by sps, recorded in the manifest.\n#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)] // Added Hash\n#[serde(tag = \"type\", rename_all = \"snake_case\")]\npub enum InstalledArtifact {\n /// The main application bundle (e.g., in /Applications).\n AppBundle { path: PathBuf },\n /// A command-line binary symlinked into the prefix's bin dir.\n BinaryLink {\n link_path: PathBuf,\n target_path: PathBuf,\n },\n /// A man page symlinked into the prefix's man dir.\n ManpageLink {\n link_path: PathBuf,\n target_path: PathBuf,\n },\n /// A resource moved to a standard system/user location (e.g., Font, PrefPane).\n MovedResource { path: PathBuf },\n /// A macOS package receipt ID managed by pkgutil.\n PkgUtilReceipt { id: String },\n /// A launchd service (Agent/Daemon).\n Launchd {\n label: String,\n path: Option,\n }, // Path is the plist file\n /// A symlink created within the Caskroom pointing to the actual installed artifact.\n /// Primarily for internal reference and potentially easier cleanup if needed.\n CaskroomLink {\n link_path: PathBuf,\n target_path: PathBuf,\n },\n /// A file copied *into* the Caskroom (e.g., a .pkg installer).\n CaskroomReference { path: PathBuf },\n}\n\n// Optional: Helper methods if needed\n// impl InstalledArtifact { ... }\n"], ["/sps/sps-common/src/error.rs", "use std::sync::Arc;\n\nuse thiserror::Error;\n\n#[derive(Error, Debug, Clone)]\npub enum SpsError {\n #[error(\"I/O Error: {0}\")]\n Io(#[from] Arc),\n\n #[error(\"HTTP Request Error: {0}\")]\n Http(#[from] Arc),\n\n #[error(\"JSON Parsing Error: {0}\")]\n Json(#[from] Arc),\n\n #[error(\"Semantic Versioning Error: {0}\")]\n SemVer(#[from] Arc),\n\n #[error(\"Object File Error: {0}\")]\n Object(#[from] Arc),\n\n #[error(\"Configuration Error: {0}\")]\n Config(String),\n\n #[error(\"API Error: {0}\")]\n Api(String),\n\n #[error(\"API Request Error: {0}\")]\n ApiRequestError(String),\n\n #[error(\"DownloadError: Failed to download '{0}' from '{1}': {2}\")]\n DownloadError(String, String, String),\n\n #[error(\"Cache Error: {0}\")]\n Cache(String),\n\n #[error(\"Resource Not Found: {0}\")]\n NotFound(String),\n\n #[error(\"Installation Error: {0}\")]\n InstallError(String),\n\n #[error(\"Generic Error: {0}\")]\n Generic(String),\n\n #[error(\"HttpError: {0}\")]\n HttpError(String),\n\n #[error(\"Checksum Mismatch: {0}\")]\n ChecksumMismatch(String),\n\n #[error(\"Validation Error: {0}\")]\n ValidationError(String),\n\n #[error(\"Checksum Error: {0}\")]\n ChecksumError(String),\n\n #[error(\"Parsing Error in {0}: {1}\")]\n ParseError(&'static str, String),\n\n #[error(\"Version error: {0}\")]\n VersionError(String),\n\n #[error(\"Dependency Error: {0}\")]\n DependencyError(String),\n\n #[error(\"Build environment setup failed: {0}\")]\n BuildEnvError(String),\n\n #[error(\"IoError: {0}\")]\n IoError(String),\n\n #[error(\"Failed to execute command: {0}\")]\n CommandExecError(String),\n\n #[error(\"Mach-O Error: {0}\")]\n MachOError(String),\n\n #[error(\"Mach-O Modification Error: {0}\")]\n MachOModificationError(String),\n\n #[error(\"Mach-O Relocation Error: Path too long - {0}\")]\n PathTooLongError(String),\n\n #[error(\"Codesign Error: {0}\")]\n CodesignError(String),\n}\n\nimpl From for SpsError {\n fn from(err: std::io::Error) -> Self {\n SpsError::Io(Arc::new(err))\n }\n}\n\nimpl From for SpsError {\n fn from(err: reqwest::Error) -> Self {\n SpsError::Http(Arc::new(err))\n }\n}\n\nimpl From for SpsError {\n fn from(err: serde_json::Error) -> Self {\n SpsError::Json(Arc::new(err))\n }\n}\n\nimpl From for SpsError {\n fn from(err: semver::Error) -> Self {\n SpsError::SemVer(Arc::new(err))\n }\n}\n\nimpl From for SpsError {\n fn from(err: object::read::Error) -> Self {\n SpsError::Object(Arc::new(err))\n }\n}\n\npub type Result = std::result::Result;\n"], ["/sps/sps-common/src/model/mod.rs", "// src/model/mod.rs\n// Declares the modules within the model directory.\nuse std::sync::Arc;\n\npub mod artifact;\npub mod cask;\npub mod formula;\npub mod tap;\npub mod version;\n\n// Re-export\npub use artifact::InstalledArtifact;\npub use cask::Cask;\npub use formula::Formula;\n\n#[derive(Debug, Clone)]\npub enum InstallTargetIdentifier {\n Formula(Arc),\n Cask(Arc),\n}\n"], ["/sps/sps-common/src/lib.rs", "// sps-common/src/lib.rs\npub mod cache;\npub mod config;\npub mod dependency;\npub mod error;\npub mod formulary;\npub mod keg;\npub mod model;\npub mod pipeline;\n// Optional: pub mod dependency_def;\n\n// Re-export key types\npub use cache::Cache;\npub use config::Config;\npub use error::{Result, SpsError};\npub use model::{Cask, Formula, InstalledArtifact}; // etc.\n // Optional: pub use dependency_def::{Dependency, DependencyTag};\n"], ["/sps/sps-core/src/install/mod.rs", "// ===== sps-core/src/build/mod.rs =====\n// Main module for build functionality\n// Removed deprecated functions and re-exports.\n\nuse std::path::PathBuf;\n\nuse sps_common::config::Config;\nuse sps_common::model::formula::Formula;\n\n// --- Submodules ---\npub mod bottle;\npub mod cask;\npub mod devtools;\npub mod extract;\n\n// --- Path helpers using Config ---\npub fn get_formula_opt_path(formula: &Formula, config: &Config) -> PathBuf {\n // Use new Config method\n config.formula_opt_path(formula.name())\n}\n\n// --- DEPRECATED EXTRACTION FUNCTIONS REMOVED ---\n"], ["/sps/sps-common/src/dependency/requirement.rs", "// **File:** sps-core/src/dependency/requirement.rs (New file)\nuse std::fmt;\n\nuse serde::{Deserialize, Serialize};\n\n#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]\npub enum Requirement {\n MacOS(String),\n Xcode(String),\n Other(String),\n}\n\nimpl fmt::Display for Requirement {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n match self {\n Self::MacOS(v) => write!(f, \"macOS >= {v}\"),\n Self::Xcode(v) => write!(f, \"Xcode >= {v}\"),\n Self::Other(s) => write!(f, \"Requirement: {s}\"),\n }\n }\n}\n"], ["/sps/sps-net/src/lib.rs", "// spm-fetch/src/lib.rs\npub mod api;\npub mod http;\npub mod oci;\npub mod validation;\n\n// Re-export necessary types from sps-core IF using Option A from Step 3\n// If using Option B (DTOs), you wouldn't depend on sps-core here for models.\n// Re-export the public fetching functions - ensure they are `pub`\npub use api::{\n fetch_all_casks, fetch_all_formulas, fetch_cask, fetch_formula, get_cask, /* ... */\n get_formula,\n};\npub use http::{fetch_formula_source_or_bottle, fetch_resource /* ... */};\npub use oci::{build_oci_client /* ... */, download_oci_blob, fetch_oci_manifest_index};\npub use sps_common::{\n model::{\n cask::{Sha256Field, UrlField},\n formula::ResourceSpec,\n Cask, Formula,\n }, // Example types needed\n {\n cache::Cache,\n error::{Result, SpsError},\n Config,\n }, // Need Config, Result, SpsError, Cache\n};\n\npub use crate::validation::{validate_url, verify_checksum, verify_content_type /* ... */};\n"], ["/sps/sps-core/src/uninstall/mod.rs", "// sps-core/src/uninstall/mod.rs\n\npub mod cask;\npub mod common;\npub mod formula;\n\n// Re-export key functions and types\npub use cask::{uninstall_cask_artifacts, zap_cask_artifacts};\npub use common::UninstallOptions;\npub use formula::uninstall_formula_artifacts;\n"], ["/sps/sps-core/src/install/cask/artifacts/mod.rs", "pub mod app;\npub mod audio_unit_plugin;\npub mod binary;\npub mod colorpicker;\npub mod dictionary;\npub mod font;\npub mod input_method;\npub mod installer;\npub mod internet_plugin;\npub mod keyboard_layout;\npub mod manpage;\npub mod mdimporter;\npub mod pkg;\npub mod preflight;\npub mod prefpane;\npub mod qlplugin;\npub mod screen_saver;\npub mod service;\npub mod suite;\npub mod uninstall;\npub mod vst3_plugin;\npub mod vst_plugin;\npub mod zap;\n\n// Re‑export a single enum if you like:\npub use self::app::install_app_from_staged;\npub use self::audio_unit_plugin::install_audio_unit_plugin;\npub use self::binary::install_binary;\npub use self::colorpicker::install_colorpicker;\npub use self::dictionary::install_dictionary;\npub use self::font::install_font;\npub use self::input_method::install_input_method;\npub use self::installer::run_installer;\npub use self::internet_plugin::install_internet_plugin;\npub use self::keyboard_layout::install_keyboard_layout;\npub use self::manpage::install_manpage;\npub use self::mdimporter::install_mdimporter;\npub use self::pkg::install_pkg_from_path;\npub use self::preflight::run_preflight;\npub use self::prefpane::install_prefpane;\npub use self::qlplugin::install_qlplugin;\npub use self::screen_saver::install_screen_saver;\npub use self::service::install_service;\npub use self::suite::install_suite;\npub use self::uninstall::record_uninstall;\npub use self::vst3_plugin::install_vst3_plugin;\npub use self::vst_plugin::install_vst_plugin;\n"], ["/sps/sps-core/src/lib.rs", "// sps-core/src/lib.rs\n\n// Declare the top-level modules within the library crate\npub mod build;\npub mod check;\npub mod install;\npub mod pipeline;\npub mod uninstall;\npub mod upgrade; // New\n#[cfg(target_os = \"macos\")]\npub mod utils; // New\n //pub mod utils;\n\n// Re-export key types for easier use by the CLI crate\n// Define InstallTargetIdentifier here or ensure it's public from cli/pipeline\n// For simplicity, let's define it here for now:\n\n// New\npub use uninstall::UninstallOptions; // New\n // New\n"], ["/sps/sps-core/src/upgrade/mod.rs", "// sps-core/src/upgrade/mod.rs\n\npub mod bottle;\npub mod cask;\npub mod source;\n\n// Re-export key upgrade functions\npub use self::bottle::upgrade_bottle_formula;\npub use self::cask::upgrade_cask_package;\npub use self::source::upgrade_source_formula;\n"], ["/sps/sps-core/src/check/mod.rs", "pub mod installed;\npub mod update;\n\npub use installed::{InstalledPackageInfo, PackageType};\npub use update::UpdateInfo;\n"], ["/sps/sps-common/src/dependency/mod.rs", "pub mod definition; // Renamed from 'dependency'\npub mod requirement;\npub mod resolver;\n\n// Re-export key types for easier access\npub use definition::{Dependency, DependencyExt, DependencyTag}; // Updated source module\npub use requirement::Requirement;\npub use resolver::{\n DependencyResolver, ResolutionContext, ResolutionStatus, ResolvedDependency, ResolvedGraph,\n};\n"], ["/sps/sps-core/src/utils/mod.rs", "#[cfg(target_os = \"macos\")]\npub mod applescript;\n#[cfg(target_os = \"macos\")]\npub mod xattr;\n"], ["/sps/sps/src/pipeline.rs", "pub mod downloader;\npub mod planner;\npub mod runner;\n"], ["/sps/sps-core/src/pipeline/mod.rs", "pub mod engine;\npub mod worker;\n"]], "task_instance_info": {"created_time": "2025-08-21 01:45:07", "created_task_model": "DeepSeek-R1", "function_skeleton": "pub fn get_installed_keg (&self, name: &str) -> Result> {}", "code_description": "This code segment functions to: Locate the most recent version of a specific software component within a hierarchical storage structure by iterating through versioned directories and performing lexicographical comparison of identifiers, while handling potential errors in directory traversal and invalid entries through logging mechanisms."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```rust\n[TASK_BEGIN]\n pub fn get_installed_keg(&self, name: &str) -> Result> {\n let formula_path = self.formula_cellar_path(name);\n debug!(\n \"[KEG_REGISTRY:{}] get_installed_keg: Checking formula path: {}\",\n name,\n formula_path.display()\n );\n\n if !formula_path.is_dir() {\n debug!(\"[KEG_REGISTRY] get_installed_keg: Formula '{}' not found in cellar\", name);\n return Ok(None);\n }\n\n let mut versions = Vec::new();\n for entry_res in fs::read_dir(&formula_path)? {\n let entry = match entry_res {\n Ok(e) => e,\n Err(e) => {\n warn!(\n \"[KEG_REGISTRY:{}] get_installed_keg: Error reading directory entry: {}. Skipping.\",\n name, e\n );\n continue;\n }\n };\n\n let version_path = entry.path();\n if version_path.is_dir() {\n if let Some(version_str) = version_path.file_name().and_then(|n| n.to_str()) {\n debug!(\n \"[KEG_REGISTRY:{}] get_installed_keg: Found version directory '{}'\",\n name,\n version_path.display()\n );\n versions.push(version_str.to_string());\n }\n }\n }\n\n if let Some(latest_version) = versions.iter().max() {\n debug!(\n \"[KEG_REGISTRY:{}] get_installed_keg: Latest version is '{}'\",\n name, latest_version\n );\n Ok(Some(InstalledKeg {\n name: name.to_string(),\n version_str: latest_version.clone(),\n path: formula_path.join(latest_version),\n }))\n } else {\n debug!(\n \"[KEG_REGISTRY:{}] get_installed_keg: No valid versions found\",\n name\n );\n Ok(None)\n }\n }\n[TASK_END]\n```", "inference_time": "2025-08-21 01-46-17"}, "editdistance_info": {"edit_distance": 26.5252, "calculate_time": "2025-08-21 01:46:17", "true_code_clean": "pub fn get_installed_keg(&self, name: &str) -> Result> {\n let formula_dir = self.formula_cellar_path(name);\n debug!(\n \"[KEG_REGISTRY:{}] get_installed_keg: Checking for formula '{}'. Path to check: {}\",\n name,\n name,\n formula_dir.display()\n );\n if !formula_dir.is_dir() {\n debug!(\"[KEG_REGISTRY:{}] get_installed_keg: Formula directory '{}' NOT FOUND or not a directory. Returning None.\", name, formula_dir.display());\n return Ok(None);\n }\n let mut latest_keg: Option = None;\n debug!(\n \"[KEG_REGISTRY:{}] get_installed_keg: Reading entries in formula directory '{}'\",\n name,\n formula_dir.display()\n );\n match fs::read_dir(&formula_dir) {\n Ok(entries) => {\n for entry_result in entries {\n match entry_result {\n Ok(entry) => {\n let path = entry.path();\n debug!(\n \"[KEG_REGISTRY:{}] get_installed_keg: Examining entry '{}'\",\n name,\n path.display()\n );\n if path.is_dir() {\n if let Some(version_str_full) =\n path.file_name().and_then(|n| n.to_str())\n {\n debug!(\"[KEG_REGISTRY:{}] get_installed_keg: Entry is a directory with name: {}\", name, version_str_full);\n let current_keg_candidate = InstalledKeg {\n name: name.to_string(),\n version_str: version_str_full.to_string(),\n path: path.clone(),\n };\n match latest_keg {\n Some(ref current_latest) => {\n if version_str_full\n > current_latest.version_str.as_str()\n {\n debug!(\"[KEG_REGISTRY:{}] get_installed_keg: Updating latest keg (lexicographical) to: {}\", name, path.display());\n latest_keg = Some(current_keg_candidate);\n }\n }\n None => {\n debug!(\"[KEG_REGISTRY:{}] get_installed_keg: Setting first found keg as latest: {}\", name, path.display());\n latest_keg = Some(current_keg_candidate);\n }\n }\n } else {\n debug!(\"[KEG_REGISTRY:{}] get_installed_keg: Could not get filename as string for path '{}'\", name, path.display());\n }\n } else {\n debug!(\"[KEG_REGISTRY:{}] get_installed_keg: Entry '{}' is not a directory.\", name, path.display());\n }\n }\n Err(e) => {\n warn!(\"[KEG_REGISTRY:{}] get_installed_keg: Error reading a directory entry in '{}': {}. Skipping entry.\", name, formula_dir.display(), e);\n }\n }\n }\n }\n Err(e) => {\n error!(\"[KEG_REGISTRY:{}] get_installed_keg: Failed to read_dir for formula directory '{}' (error: {}). Returning error.\", name, formula_dir.display(), e);\n return Err(SpsError::Io(std::sync::Arc::new(e)));\n }\n }\n if let Some(keg) = &latest_keg {\n debug!(\"[KEG_REGISTRY:{}] get_installed_keg: For formula '{}', latest keg found: path={}, version_str={}\", name, name, keg.path.display(), keg.version_str);\n } else {\n debug!(\"[KEG_REGISTRY:{}] get_installed_keg: For formula '{}', no installable keg version found in directory '{}'.\", name, name, formula_dir.display());\n }\n Ok(latest_keg)\n }", "predict_code_clean": "pub fn get_installed_keg(&self, name: &str) -> Result> {\n let formula_path = self.formula_cellar_path(name);\n debug!(\n \"[KEG_REGISTRY:{}] get_installed_keg: Checking formula path: {}\",\n name,\n formula_path.display()\n );\n if !formula_path.is_dir() {\n debug!(\"[KEG_REGISTRY] get_installed_keg: Formula '{}' not found in cellar\", name);\n return Ok(None);\n }\n let mut versions = Vec::new();\n for entry_res in fs::read_dir(&formula_path)? {\n let entry = match entry_res {\n Ok(e) => e,\n Err(e) => {\n warn!(\n \"[KEG_REGISTRY:{}] get_installed_keg: Error reading directory entry: {}. Skipping.\",\n name, e\n );\n continue;\n }\n };\n let version_path = entry.path();\n if version_path.is_dir() {\n if let Some(version_str) = version_path.file_name().and_then(|n| n.to_str()) {\n debug!(\n \"[KEG_REGISTRY:{}] get_installed_keg: Found version directory '{}'\",\n name,\n version_path.display()\n );\n versions.push(version_str.to_string());\n }\n }\n }\n if let Some(latest_version) = versions.iter().max() {\n debug!(\n \"[KEG_REGISTRY:{}] get_installed_keg: Latest version is '{}'\",\n name, latest_version\n );\n Ok(Some(InstalledKeg {\n name: name.to_string(),\n version_str: latest_version.clone(),\n path: formula_path.join(latest_version),\n }))\n } else {\n debug!(\n \"[KEG_REGISTRY:{}] get_installed_keg: No valid versions found\",\n name\n );\n Ok(None)\n }\n }"}}