Skip to main content

pacsea/logic/files/
backup.rs

1//! Backup file detection and retrieval functions.
2
3use super::pkgbuild_cache::{PkgbuildSourceKind, parse_pkgbuild_cached};
4use super::pkgbuild_fetch::{fetch_pkgbuild_sync, fetch_srcinfo_sync};
5use super::pkgbuild_parse::parse_backup_from_srcinfo;
6use crate::state::types::Source;
7use std::process::Command;
8
9/// What: Identify files marked for backup handling during install or removal operations.
10///
11/// Inputs:
12/// - `name`: Package whose backup array should be inspected.
13/// - `source`: Source descriptor to decide how to gather backup information.
14///
15/// Output:
16/// - Returns a list of backup file paths or an empty list when the data cannot be retrieved.
17///
18/// # Errors
19/// - Returns `Err` when `pacman -Qii` command execution fails for installed packages
20/// - Returns `Err` when PKGBUILD or .SRCINFO fetch fails and no fallback is available
21///
22/// Details:
23/// - Prefers querying the installed package via `pacman -Qii`; falls back to best-effort heuristics.
24pub fn get_backup_files(name: &str, source: &Source) -> Result<Vec<String>, String> {
25    // First try: if package is installed, use pacman -Qii
26    if let Ok(backup_files) = get_backup_files_from_installed(name)
27        && !backup_files.is_empty()
28    {
29        tracing::debug!(
30            "Found {} backup files from installed package {}",
31            backup_files.len(),
32            name
33        );
34        return Ok(backup_files);
35    }
36
37    // Second try: parse from PKGBUILD/.SRCINFO (best-effort, may fail)
38    match source {
39        Source::Official { .. } => {
40            // Try to fetch PKGBUILD and parse backup array
41            match fetch_pkgbuild_sync(name) {
42                Ok(pkgbuild) => {
43                    let entry =
44                        parse_pkgbuild_cached(name, None, PkgbuildSourceKind::Official, &pkgbuild);
45                    let backup_files = entry.backup_files;
46                    if !backup_files.is_empty() {
47                        tracing::debug!(
48                            "Found {} backup files from PKGBUILD for {}",
49                            backup_files.len(),
50                            name
51                        );
52                        return Ok(backup_files);
53                    }
54                }
55                Err(e) => {
56                    tracing::debug!("Failed to fetch PKGBUILD for {}: {}", name, e);
57                }
58            }
59        }
60        Source::Aur => {
61            // Try to fetch .SRCINFO first (more reliable for AUR)
62            match fetch_srcinfo_sync(name) {
63                Ok(srcinfo) => {
64                    let backup_files = parse_backup_from_srcinfo(&srcinfo);
65                    if !backup_files.is_empty() {
66                        tracing::debug!(
67                            "Found {} backup files from .SRCINFO for {}",
68                            backup_files.len(),
69                            name
70                        );
71                        return Ok(backup_files);
72                    }
73                }
74                Err(e) => {
75                    tracing::debug!("Failed to fetch .SRCINFO for {}: {}", name, e);
76                }
77            }
78            // Fallback to PKGBUILD if .SRCINFO failed
79            match fetch_pkgbuild_sync(name) {
80                Ok(pkgbuild) => {
81                    let entry =
82                        parse_pkgbuild_cached(name, None, PkgbuildSourceKind::Aur, &pkgbuild);
83                    let backup_files = entry.backup_files;
84                    if !backup_files.is_empty() {
85                        tracing::debug!(
86                            "Found {} backup files from PKGBUILD for {}",
87                            backup_files.len(),
88                            name
89                        );
90                        return Ok(backup_files);
91                    }
92                }
93                Err(e) => {
94                    tracing::debug!("Failed to fetch PKGBUILD for {}: {}", name, e);
95                }
96            }
97        }
98    }
99    Ok(Vec::new())
100}
101
102/// What: Collect backup file entries for an installed package through `pacman -Qii`.
103///
104/// Inputs:
105/// - `name`: Installed package identifier.
106///
107/// Output:
108/// - Returns the backup array as a vector of file paths or an empty list when not installed.
109///
110/// # Errors
111/// - Returns `Err` when `pacman -Qii` command execution fails (I/O error)
112/// - Returns `Err` when `pacman -Qii` exits with non-zero status for reasons other than package not found
113///
114/// Details:
115/// - Parses the `Backup Files` section, handling wrapped lines to ensure complete coverage.
116pub fn get_backup_files_from_installed(name: &str) -> Result<Vec<String>, String> {
117    tracing::debug!("Running: pacman -Qii {}", name);
118    let output = Command::new("pacman")
119        .args(["-Qii", name])
120        .env("LC_ALL", "C")
121        .env("LANG", "C")
122        .output()
123        .map_err(|e| {
124            tracing::error!("Failed to execute pacman -Qii {}: {}", name, e);
125            format!("pacman -Qii failed: {e}")
126        })?;
127
128    if !output.status.success() {
129        // Package not installed - this is OK
130        let stderr = String::from_utf8_lossy(&output.stderr);
131        if stderr.contains("was not found") {
132            tracing::debug!("Package {} is not installed", name);
133            return Ok(Vec::new());
134        }
135        tracing::error!(
136            "pacman -Qii {} failed with status {:?}: {}",
137            name,
138            output.status.code(),
139            stderr
140        );
141        return Err(format!("pacman -Qii failed for {name}: {stderr}"));
142    }
143
144    let text = String::from_utf8_lossy(&output.stdout);
145    let mut backup_files = Vec::new();
146    let mut in_backup_section = false;
147
148    // Parse pacman -Qii output: look for "Backup Files" field
149    for line in text.lines() {
150        if line.starts_with("Backup Files") {
151            in_backup_section = true;
152            // Extract files from the same line if present
153            if let Some(colon_pos) = line.find(':') {
154                let files_str = line[colon_pos + 1..].trim();
155                if !files_str.is_empty() && files_str != "None" {
156                    for file in files_str.split_whitespace() {
157                        backup_files.push(file.to_string());
158                    }
159                }
160            }
161        } else if in_backup_section {
162            // Continuation lines (indented)
163            if line.starts_with("    ") || line.starts_with('\t') {
164                for file in line.split_whitespace() {
165                    backup_files.push(file.to_string());
166                }
167            } else {
168                // End of backup section
169                break;
170            }
171        }
172    }
173
174    tracing::debug!(
175        "Found {} backup files for installed package {}",
176        backup_files.len(),
177        name
178    );
179    Ok(backup_files)
180}