Skip to main content

pacsea/logic/sandbox/
mod.rs

1//! AUR sandbox preflight checks through the arch-toolkit integration boundary.
2
3use crate::integrations::arch_toolkit::ToolkitContext;
4use crate::state::types::PackageItem;
5
6/// What: Information about one dependency relative to the host environment.
7///
8/// Inputs:
9/// - Produced by arch-toolkit sandbox analysis.
10///
11/// Output:
12/// - Persisted installation and version-satisfaction state.
13///
14/// Details:
15/// - The shape remains compatible with existing Pacsea cache files.
16#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
17pub struct DependencyDelta {
18    /// Dependency specification as declared.
19    pub name: String,
20    /// Whether the dependency is installed or provided.
21    pub is_installed: bool,
22    /// Installed version when available.
23    pub installed_version: Option<String>,
24    /// Whether the installed version satisfies the declared constraint.
25    pub version_satisfied: bool,
26}
27
28/// What: Sandbox dependency analysis for one AUR package.
29///
30/// Inputs:
31/// - Produced from bounded `.SRCINFO` or PKGBUILD text.
32///
33/// Output:
34/// - Persisted dependency deltas grouped by package metadata category.
35///
36/// Details:
37/// - Fetching, cache fallback, scanners, and UI remain Pacsea-owned.
38#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
39pub struct SandboxInfo {
40    /// Package name.
41    pub package_name: String,
42    /// Runtime dependencies.
43    pub depends: Vec<DependencyDelta>,
44    /// Build-time dependencies.
45    pub makedepends: Vec<DependencyDelta>,
46    /// Test dependencies.
47    pub checkdepends: Vec<DependencyDelta>,
48    /// Optional dependencies.
49    pub optdepends: Vec<DependencyDelta>,
50}
51
52/// What: Resolve sandbox information with a standalone toolkit context.
53///
54/// Inputs:
55/// - `items`: Packages selected for preflight.
56///
57/// Output:
58/// - One sandbox record per AUR package.
59///
60/// Details:
61/// - Runtime workers use [`resolve_sandbox_info_with_context`] to share configured clients.
62pub async fn resolve_sandbox_info_async(items: &[PackageItem]) -> Vec<SandboxInfo> {
63    match ToolkitContext::new() {
64        Ok(context) => resolve_sandbox_info_with_context(&context, items).await,
65        Err(error) => {
66            tracing::warn!(error = %error, "sandbox client initialization failed");
67            Vec::new()
68        }
69    }
70}
71
72/// What: Resolve sandbox information with a caller-owned shared toolkit context.
73///
74/// Inputs:
75/// - `context`: Runtime integration context.
76/// - `items`: Packages selected for preflight.
77///
78/// Output:
79/// - One sandbox record per AUR package.
80///
81/// Details:
82/// - arch-toolkit owns parsing and host comparison; Pacsea owns fetch fallback and state.
83pub(crate) async fn resolve_sandbox_info_with_context(
84    context: &ToolkitContext,
85    items: &[PackageItem],
86) -> Vec<SandboxInfo> {
87    crate::integrations::arch_toolkit::sandbox::resolve(context, items).await
88}
89
90/// What: Parse PKGBUILD dependency categories through arch-toolkit.
91///
92/// Inputs:
93/// - `text`: PKGBUILD text that is never executed here.
94///
95/// Output:
96/// - Runtime, build, check, and optional dependency specs.
97///
98/// Details:
99/// - Pure parsing preserves the existing Pacsea helper surface.
100#[must_use]
101pub fn parse_pkgbuild_deps(text: &str) -> (Vec<String>, Vec<String>, Vec<String>, Vec<String>) {
102    arch_toolkit::deps::parse_pkgbuild_deps(text)
103}
104
105/// What: Parse PKGBUILD conflicts through arch-toolkit.
106///
107/// Inputs:
108/// - `text`: PKGBUILD text that is never executed here.
109///
110/// Output:
111/// - Conflicting package names.
112///
113/// Details:
114/// - Version constraints are normalized by the toolkit parser.
115#[must_use]
116pub fn parse_pkgbuild_conflicts(text: &str) -> Vec<String> {
117    arch_toolkit::deps::parse_pkgbuild_conflicts(text)
118}
119
120/// What: Extract a package name from a dependency specification through arch-toolkit.
121///
122/// Inputs:
123/// - `dependency`: Versioned or annotated dependency specification.
124///
125/// Output:
126/// - Bare package name.
127///
128/// Details:
129/// - Handles optional-dependency descriptions before comparison operators.
130#[must_use]
131pub fn extract_package_name(dependency: &str) -> String {
132    arch_toolkit::sandbox::extract_package_name(dependency)
133}
134
135#[cfg(test)]
136mod tests {
137    /// What: Verify Pacsea's public parser wrapper delegates all dependency categories.
138    ///
139    /// Inputs:
140    /// - Deterministic PKGBUILD text.
141    ///
142    /// Output:
143    /// - Expected runtime and build dependency lists.
144    ///
145    /// Details:
146    /// - The PKGBUILD is parsed as text and never executed.
147    #[test]
148    fn pkgbuild_parser_delegates_to_toolkit() {
149        let (depends, make, check, optional) =
150            super::parse_pkgbuild_deps("depends=('glibc')\nmakedepends=('rust')");
151        assert_eq!(depends, vec!["glibc"]);
152        assert_eq!(make, vec!["rust"]);
153        assert_eq!(check, [] as [String; 0]);
154        assert_eq!(optional, [] as [String; 0]);
155    }
156
157    /// What: Verify dependency-name extraction handles annotations and versions.
158    ///
159    /// Inputs:
160    /// - Optional dependency with a version and description.
161    ///
162    /// Output:
163    /// - Bare package name.
164    ///
165    /// Details:
166    /// - Protects UI optional-dependency matching.
167    #[test]
168    fn dependency_name_extraction_delegates_to_toolkit() {
169        assert_eq!(
170            super::extract_package_name("python>=3.12: scripting"),
171            "python"
172        );
173    }
174
175    /// What: Verify multiline and append dependency arrays retain legacy parser behavior.
176    ///
177    /// Inputs:
178    /// - A PKGBUILD containing a multiline `depends` array and appended build dependencies.
179    ///
180    /// Output:
181    /// - Complete dependency vectors in declaration order.
182    ///
183    /// Details:
184    /// - Restores representative coverage removed with the local parser migration.
185    #[test]
186    fn pkgbuild_parser_preserves_multiline_and_append_arrays() {
187        let pkgbuild = r"
188            depends=(
189                'foo'
190                'bar>=1.2'
191                'baz'
192            )
193            build() {
194                makedepends+=(cmake ninja)
195            }
196        ";
197
198        let (depends, make, check, optional) = super::parse_pkgbuild_deps(pkgbuild);
199
200        assert_eq!(depends, vec!["foo", "bar>=1.2", "baz"]);
201        assert_eq!(make, vec!["cmake", "ninja"]);
202        assert_eq!(check, [] as [String; 0]);
203        assert_eq!(optional, [] as [String; 0]);
204    }
205
206    /// What: Verify invalid package tokens and shared-library dependencies remain filtered.
207    ///
208    /// Inputs:
209    /// - Valid names mixed with malformed, too-short, and `.so` tokens.
210    ///
211    /// Output:
212    /// - Only valid package dependency specifications.
213    ///
214    /// Details:
215    /// - Encodes the pre-migration filtering contract from the deleted parser suite.
216    #[test]
217    fn pkgbuild_parser_filters_invalid_and_shared_library_tokens() {
218        let pkgbuild = r"
219            depends=('valid-package' 'invalid)' '=invalid' 'a' 'valid>=1.0' 'libc.so')
220        ";
221
222        let (depends, make, check, optional) = super::parse_pkgbuild_deps(pkgbuild);
223
224        assert_eq!(depends, vec!["valid-package", "valid>=1.0"]);
225        assert_eq!(make, [] as [String; 0]);
226        assert_eq!(check, [] as [String; 0]);
227        assert_eq!(optional, [] as [String; 0]);
228    }
229
230    /// What: Verify repeated dependency declarations use toolkit deduplication semantics.
231    ///
232    /// Inputs:
233    /// - The same package in an assignment and an appended dependency array.
234    ///
235    /// Output:
236    /// - One dependency entry rather than duplicate preflight rows.
237    ///
238    /// Details:
239    /// - Makes the v0.3.0 parser behavior explicit at Pacsea's public integration boundary.
240    #[test]
241    fn pkgbuild_parser_deduplicates_repeated_dependencies() {
242        let pkgbuild = "depends=('foo')\ndepends+=('foo' 'bar')";
243
244        let (depends, make, check, optional) = super::parse_pkgbuild_deps(pkgbuild);
245
246        assert_eq!(depends, vec!["foo", "bar"]);
247        assert_eq!(make, [] as [String; 0]);
248        assert_eq!(check, [] as [String; 0]);
249        assert_eq!(optional, [] as [String; 0]);
250    }
251
252    /// What: Verify conflict parsing strips versions and filters shared-library tokens.
253    ///
254    /// Inputs:
255    /// - Multiline conflicts containing version constraints and `.so` entries.
256    ///
257    /// Output:
258    /// - Bare package conflict names only.
259    ///
260    /// Details:
261    /// - Preserves the behavior covered by the deleted local sandbox tests.
262    #[test]
263    fn pkgbuild_conflicts_preserve_legacy_normalization() {
264        let pkgbuild = r"
265            conflicts=(
266                'old-pkg<2.0'
267                'new-pkg>=3.0'
268                'libcairo.so'
269                'libdbus-1.so=1-64'
270            )
271        ";
272
273        assert_eq!(
274            super::parse_pkgbuild_conflicts(pkgbuild),
275            vec!["old-pkg", "new-pkg"]
276        );
277    }
278
279    /// What: Verify dependency-name extraction handles every supported operator form.
280    ///
281    /// Inputs:
282    /// - Greater, less, single-equals, double-equals, annotation, and bare-name forms.
283    ///
284    /// Output:
285    /// - The same bare package name for every representation.
286    ///
287    /// Details:
288    /// - Locks the v0.3.0 normalization contract at the public integration boundary.
289    #[test]
290    fn extract_package_name_operator_matrix() {
291        for dependency in [
292            "foo>=1.0",
293            "foo<=1",
294            "foo==1",
295            "foo=1",
296            "foo: description",
297            "foo",
298        ] {
299            assert_eq!(
300                super::extract_package_name(dependency),
301                "foo",
302                "unexpected package name for {dependency}"
303            );
304        }
305    }
306}