### Loading Packages from Files Source: https://context7.com/pacman/alpm.rs/llms.txt Demonstrates how to load package files (.pkg.tar.xz, .pkg.tar.zst) directly from disk for inspection or installation using the `alpm` crate. ```APIDOC ## Loading Packages from Files Load package files (.pkg.tar.xz, .pkg.tar.zst) directly from disk for inspection or installation without using a database. ### Method ```rust use alpm::{Alpm, SigLevel}; fn main() -> alpm::Result<()> { let handle = Alpm::new("/", "/var/lib/pacman")?; // Load a package file from disk let pkg = handle.pkg_load( "/var/cache/pacman/pkg/pacman-6.0.2-1-x86_64.pkg.tar.zst", true, // full metadata parsing SigLevel::USE_DEFAULT, // signature verification level )?; // Inspect package metadata println!("Package: {} {}", pkg.name(), pkg.version()); println!("Description: {}", pkg.desc().unwrap_or("N/A")); println!("Architecture: {}", pkg.arch().unwrap_or("N/A")); println!("Package size: {} bytes", pkg.size()); println!("Installed size: {} bytes", pkg.isize()); println!("SHA256: {}", pkg.sha256sum().unwrap_or("N/A")); // List files in the package let files = pkg.files(); println!("Contains {} files:", files.files().len()); for file in files.files().iter().take(10) { println!(" {}", String::from_utf8_lossy(file.name())); } // Check if package contains a specific file if files.contains("etc/pacman.conf").is_some() { println!("Package contains pacman.conf"); } // List backup files (files preserved on upgrade) for backup in pkg.backup() { println!("Backup: {} (hash: {})", backup.name(), backup.hash()); } // Check for scriptlet if pkg.has_scriptlet() { println!("Package has install scriptlet"); } // List licenses for license in pkg.licenses() { println!("License: {}", license); } Ok(()) } ``` ``` -------------------------------- ### Querying and Searching Packages with ALPM in Rust Source: https://context7.com/pacman/alpm.rs/llms.txt Demonstrates how to query specific packages by name, search for packages using regex patterns, and list explicitly installed packages. It also shows how to retrieve package metadata like description, size, URL, and dependencies. ```rust use alpm::{Alpm, PackageReason, SigLevel}; fn main() -> alpm::Result<()> { let handle = Alpm::new("/", "/var/lib/pacman")?; handle.register_syncdb("core", SigLevel::USE_DEFAULT)?; handle.register_syncdb("extra", SigLevel::USE_DEFAULT)?; // Get a specific package by name (fast hashmap lookup) for db in handle.syncdbs() { if let Ok(pkg) = db.pkg("linux") { println!("Found {} {} in {}", pkg.name(), pkg.version(), db.name()); println!(" Description: {}", pkg.desc().unwrap_or("N/A")); println!(" Size: {} bytes", pkg.size()); println!(" Installed size: {} bytes", pkg.isize()); println!(" URL: {}", pkg.url().unwrap_or("N/A")); println!(" Packager: {}", pkg.packager().unwrap_or("N/A")); println!(" Architecture: {}", pkg.arch().unwrap_or("N/A")); } } // Search packages with regex patterns for db in handle.syncdbs() { let results = db.search(["linux-[a-z]+", "headers"].iter())?; for pkg in results.iter() { println!("{}: {}", pkg.name(), pkg.desc().unwrap_or("No description")); } } // List explicitly installed packages from localdb let localdb = handle.localdb(); for pkg in localdb.pkgs() { if pkg.reason() == PackageReason::Explicit { println!("Explicit: {} {}", pkg.name(), pkg.version()); } } // Get package dependencies if let Ok(pkg) = localdb.pkg("pacman") { println!("Dependencies of {}:", pkg.name()); for dep in pkg.depends() { println!(" - {}", dep); } println!("Optional dependencies:"); for dep in pkg.optdepends() { println!(" - {} ({})", dep.name(), dep.desc().unwrap_or("")); } } Ok(()) } ``` -------------------------------- ### Rust: Listing Package Files with alpm.rs Source: https://context7.com/pacman/alpm.rs/llms.txt Demonstrates how to retrieve and inspect the list of files belonging to an installed package using alpm.rs. It covers iterating through files, checking if a package owns a specific path, and reading the package's changelog. ```rust use alpm::{Alpm, SigLevel}; use std::io::Read; fn main() -> alpm::Result<()> { let handle = Alpm::new("/", "/var/lib/pacman")?; let localdb = handle.localdb(); // Get file list from installed package let pkg = localdb.pkg("filesystem")?; let files = pkg.files(); println!("Package {} contains {} files", pkg.name(), files.files().len()); // Iterate through files for file in files.files().iter().take(20) { let name = String::from_utf8_lossy(file.name()); println!(" {}", name); } // Check if package owns a specific file if let Some(file) = files.contains("etc/") { println!("Package owns /etc/ directory"); } // Check for a specific file path if files.contains("etc/fstab").is_some() { println!("Package provides /etc/fstab"); } // Read package changelog (if available) if let Ok(pkg) = localdb.pkg("pacman") { if let Ok(mut changelog) = pkg.changelog() { let mut content = String::new(); changelog.read_to_string(&mut content).ok(); if !content.is_empty() { println!("Changelog excerpt:\n{}", &content[..content.len().min(500)]); } } } Ok(()) } ``` -------------------------------- ### Package File Listing Source: https://context7.com/pacman/alpm.rs/llms.txt Details how to access file lists, check file ownership, and read changelogs from installed packages. ```APIDOC ## Package File Listing ### Description Access the list of files contained in an installed package, including checking for specific files and examining backup configurations. ### Method N/A (Library API) ### Parameters - **pkg_name** (String) - Required - The name of the package to query. ### Response - **Files** - A struct containing the list of files and methods to check for file existence. ``` -------------------------------- ### Package Transactions API Source: https://context7.com/pacman/alpm.rs/llms.txt Demonstrates how to perform package installations, removals, and system upgrades using transactions. Transactions involve initialization, preparation, and commitment. ```APIDOC ## Package Transactions Perform package installations, removals, and system upgrades using transactions. Transactions must be initialized, prepared, and committed in order. ### Method Rust (using alpm.rs library) ### Endpoint N/A (Local library operations) ### Parameters N/A (Library functions) ### Request Example ```rust use alpm::{Alpm, Error, SigLevel, TransFlag}; fn main() -> alpm::Result<()> { let mut handle = Alpm::new("/", "/var/lib/pacman")?; // Register and configure database let db = handle.register_syncdb_mut("core", SigLevel::NONE)?; db.add_server("https://mirror.example.com/archlinux/core/os/x86_64")?; // Get package reference before starting transaction let core = handle.syncdbs().iter().find(|db| db.name() == "core").unwrap(); let pkg = core.pkg("filesystem")?; // Configure transaction flags let flags = TransFlag::DB_ONLY // Only modify database, don't extract files | TransFlag::NO_DEPS // Skip dependency checks | TransFlag::NEEDED; // Don't reinstall up-to-date packages // Initialize transaction handle.trans_init(flags)?; // Add package to install handle.trans_add_pkg(pkg).map_err(|e| e.error)?; // Or schedule a system upgrade handle.sync_sysupgrade(false)?; // Prepare transaction (resolve dependencies, check conflicts) match handle.trans_prepare() { Ok(()) => println!("Transaction prepared successfully"), Err(e) => { eprintln!("Prepare failed: {}", e.error()); if let Some(data) = e.data() { println!("Additional data: {:?}", data); } return Err(e.error().into()); } } // Review packages to be installed/removed println!("Packages to install:"); for pkg in handle.trans_add() { println!(" {} {}", pkg.name(), pkg.version()); } println!("Packages to remove:"); for pkg in handle.trans_remove() { println!(" {} {}", pkg.name(), pkg.version()); } // Commit the transaction (actually perform operations) match handle.trans_commit() { Ok(()) => println!("Transaction completed successfully"), Err(e) => { eprintln!("Commit failed: {}", e.error()); if e.error() == Error::Retrieve { eprintln!("Failed to download packages"); } } } // Release transaction (cleanup) handle.trans_release()?; Ok(()) } ``` ``` -------------------------------- ### Compare Package Versions with Rust ALPM Source: https://context7.com/pacman/alpm.rs/llms.txt Demonstrates comparing package version strings and actual package versions using the `alpm::Version` type and the `alpm::vercmp` function. It covers direct comparisons, using `Ordering`, and comparing installed package versions against specified versions. Dependencies include the `alpm` crate. ```rust use std::cmp::Ordering; use alpm::{Alpm, SigLevel, Version, vercmp}; fn main() -> alpm::Result<()> { // Compare version strings directly assert!(Version::new("2.0.0") > Version::new("1.9.9")); assert!(Version::new("1.10.0") > Version::new("1.9.0")); assert!(Version::new("2.0.0-1") == Version::new("2.0.0")); // Release suffix ignored // Use vercmp function for Ordering result match vercmp("2.1.0", "2.0.5") { Ordering::Greater => println!("2.1.0 is newer"), Ordering::Less => println!("2.0.5 is newer"), Ordering::Equal => println!("Same version"), } // Compare package versions let handle = Alpm::new("/", "/var/lib/pacman")?; let core = handle.register_syncdb("core", SigLevel::USE_DEFAULT)?; if let Ok(linux) = core.pkg("linux") { let current = linux.version(); if current > Version::new("5.0.0") { println!("Linux {} is newer than 5.0.0", current); } // Using vercmp method match current.vercmp(Version::new("6.0.0")) { Ordering::Less => println!("Older than 6.0.0"), Ordering::Equal => println!("Is 6.0.0"), Ordering::Greater => println!("Newer than 6.0.0"), } } // Sort packages by version let mut pkgs: Vec<_> = core.pkgs().iter().collect(); pkgs.sort_by(|a, b| a.version().vercmp(b.version())); Ok(()) } ``` -------------------------------- ### Configure ALPM Handle Options with Rust Source: https://context7.com/pacman/alpm.rs/llms.txt Configures various ALPM handle options using the alpm Rust library, including cache directories, hook directories, GPG directory, log file, ignore lists for packages and groups, noextracts, noupgrades, target architectures, assumed installed packages, signature levels, and download/disk space settings. Dependencies include the 'alpm' crate. ```rust use alpm::{Alpm, Depend, SigLevel}; fn main() -> alpm::Result<()> { let mut handle = Alpm::new("/", "/var/lib/pacman")?; // Cache directories for downloaded packages handle.add_cachedir("/var/cache/pacman/pkg")?; handle.set_cachedirs(["/var/cache/pacman/pkg", "/tmp/pacman-cache"].iter())?; // Hook directories for pacman hooks handle.add_hookdir("/etc/pacman.d/hooks")?; handle.set_hookdirs(["/etc/pacman.d/hooks", "/usr/share/libalpm/hooks"].iter())?; // GPG directory for signature verification handle.set_gpgdir("/etc/pacman.d/gnupg")?; // Log file location handle.set_logfile("/var/log/pacman.log")?; // Packages to ignore during upgrades handle.set_ignorepkgs(["linux-lts", "nvidia"].iter())?; handle.add_ignorepkg("firefox")?; // Groups to ignore handle.set_ignoregroups(["gnome"].iter())?; // Files to not extract during installation handle.set_noextracts(["usr/share/doc/*", "usr/share/man/*"].iter())?; // Files to not upgrade (preserve local modifications) handle.set_noupgrades(["etc/pacman.conf", "etc/fstab"].iter())?; // Target architectures handle.set_architectures(["x86_64"].iter())?; // Packages to assume are installed (for dependency resolution) let dep = Depend::new("custom-package=1.0"); handle.add_assume_installed(&dep)?; // Signature verification levels handle.set_default_siglevel(SigLevel::PACKAGE | SigLevel::DATABASE)?; // Download settings handle.set_parallel_downloads(5); handle.set_disable_dl_timeout(false); // Disk space checking handle.set_check_space(true); // Enable syslog handle.set_use_syslog(true); // Query current settings println!("Root: {}", handle.root()); println!("DB Path: {}", handle.dbpath()); println!("Cache dirs: {:?}", handle.cachedirs().iter().collect::>()); println!("Check space: {}", handle.check_space()); println!("Default siglevel: {:?}", handle.default_siglevel()); Ok(()) } ``` -------------------------------- ### Handle Configuration Options Source: https://context7.com/pacman/alpm.rs/llms.txt Illustrates how to configure various ALPM handle options, including cache directories, signature levels, architectures, and package ignore lists using the `alpm` crate. ```APIDOC ## Handle Configuration Options Configure various alpm handle options including cache directories, signature levels, architectures, and package ignore lists. ### Method ```rust use alpm::{Alpm, Depend, SigLevel}; fn main() -> alpm::Result<()> { let mut handle = Alpm::new("/", "/var/lib/pacman")?; // Cache directories for downloaded packages handle.add_cachedir("/var/cache/pacman/pkg")?; handle.set_cachedirs(["/var/cache/pacman/pkg", "/tmp/pacman-cache"].iter())?; // Hook directories for pacman hooks handle.add_hookdir("/etc/pacman.d/hooks")?; handle.set_hookdirs(["/etc/pacman.d/hooks", "/usr/share/libalpm/hooks"].iter())?; // GPG directory for signature verification handle.set_gpgdir("/etc/pacman.d/gnupg")?; // Log file location handle.set_logfile("/var/log/pacman.log")?; // Packages to ignore during upgrades handle.set_ignorepkgs(["linux-lts", "nvidia"].iter())?; handle.add_ignorepkg("firefox")?; // Groups to ignore handle.set_ignoregroups(["gnome"].iter())?; // Files to not extract during installation handle.set_noextracts(["usr/share/doc/*", "usr/share/man/*"].iter())?; // Files to not upgrade (preserve local modifications) handle.set_noupgrades(["etc/pacman.conf", "etc/fstab"].iter())?; // Target architectures handle.set_architectures(["x86_64"].iter())?; // Packages to assume are installed (for dependency resolution) let dep = Depend::new("custom-package=1.0"); handle.add_assume_installed(&dep)?; // Signature verification levels handle.set_default_siglevel(SigLevel::PACKAGE | SigLevel::DATABASE)?; // Download settings handle.set_parallel_downloads(5); handle.set_disable_dl_timeout(false); // Disk space checking handle.set_check_space(true); // Enable syslog handle.set_use_syslog(true); // Query current settings println!("Root: {}", handle.root()); println!("DB Path: {}", handle.dbpath()); println!("Cache dirs: {:?}", handle.cachedirs().iter().collect::>()); println!("Check space: {}", handle.check_space()); println!("Default siglevel: {:?}", handle.default_siglevel()); Ok(()) } ``` ``` -------------------------------- ### Initialize Alpm Handle Source: https://context7.com/pacman/alpm.rs/llms.txt Demonstrates how to initialize the Alpm handle with root and database paths, configure package ignore lists, and register sync databases. This is the primary entry point for using the library. ```rust use alpm::{Alpm, SigLevel}; fn main() -> alpm::Result<()> { let mut handle = Alpm::new("/", "/var/lib/pacman")?; handle.set_ignorepkgs(["firefox", "chromium"].iter())?; handle.add_cachedir("/var/cache/pacman/pkg")?; handle.set_check_space(true); handle.register_syncdb("core", SigLevel::USE_DEFAULT)?; handle.register_syncdb("extra", SigLevel::USE_DEFAULT)?; handle.register_syncdb("community", SigLevel::USE_DEFAULT)?; println!("libalpm version: {}", alpm::version()); println!("Root: {}", handle.root()); println!("DB Path: {}", handle.dbpath()); Ok(()) } ``` -------------------------------- ### Manage Databases and Mirrors Source: https://context7.com/pacman/alpm.rs/llms.txt Shows how to register mutable sync databases, add mirror servers, configure database usage flags, and perform database updates. It also covers accessing the local database and iterating over registered sync databases. ```rust use alpm::{Alpm, SigLevel, Usage}; fn main() -> alpm::Result<()> { let mut handle = Alpm::new("/", "/var/lib/pacman")?; let core = handle.register_syncdb_mut("core", SigLevel::USE_DEFAULT)?; core.add_server("https://mirror.example.com/archlinux/core/os/x86_64")?; core.add_server("https://mirror2.example.com/archlinux/core/os/x86_64")?; core.set_usage(Usage::SYNC | Usage::SEARCH | Usage::INSTALL)?; let localdb = handle.localdb(); println!("Local database: {}", localdb.name()); for db in handle.syncdbs() { println!("Sync DB: {} (siglevel: {:?})", db.name(), db.siglevel()); } match handle.syncdbs_mut().update(false) { Ok(updated) => println!("Databases updated: {}", updated), Err(e) => eprintln!("Update failed: {}", e), } Ok(()) } ``` -------------------------------- ### Perform Package Transactions with ALPM Source: https://context7.com/pacman/alpm.rs/llms.txt Demonstrates how to initialize, configure, prepare, and commit a package transaction. It covers adding packages, scheduling system upgrades, and handling transaction errors. ```rust use alpm::{Alpm, Error, SigLevel, TransFlag}; fn main() -> alpm::Result<()> { let mut handle = Alpm::new("/", "/var/lib/pacman")?; let db = handle.register_syncdb_mut("core", SigLevel::NONE)?; db.add_server("https://mirror.example.com/archlinux/core/os/x86_64")?; let core = handle.syncdbs().iter().find(|db| db.name() == "core").unwrap(); let pkg = core.pkg("filesystem")?; let flags = TransFlag::DB_ONLY | TransFlag::NO_DEPS | TransFlag::NEEDED; handle.trans_init(flags)?; handle.trans_add_pkg(pkg).map_err(|e| e.error)?; handle.sync_sysupgrade(false)?; match handle.trans_prepare() { Ok(()) => println!("Transaction prepared successfully"), Err(e) => return Err(e.error().into()), } match handle.trans_commit() { Ok(()) => println!("Transaction completed successfully"), Err(e) => eprintln!("Commit failed: {}", e.error()), } handle.trans_release()?; Ok(()) } ``` -------------------------------- ### Checking Library Capabilities Source: https://context7.com/pacman/alpm.rs/llms.txt Demonstrates how to query libalpm for supported features like signature verification and download support. ```APIDOC ## Checking Capabilities ### Description Query the capabilities of the libalpm library at runtime to determine available features. ### Method N/A (Library API) ### Response - **Capabilities** - An object containing boolean flags for features like NLS, downloader, and signatures. ``` -------------------------------- ### Version Comparison API Source: https://context7.com/pacman/alpm.rs/llms.txt Demonstrates how to compare package versions using pacman's vercmp algorithm and Rust's comparison traits. ```APIDOC ## Version Comparison Compare package versions using pacman's vercmp algorithm. The `Version` type implements Rust comparison traits for natural version ordering. ### Method N/A (Illustrative Example) ### Endpoint N/A (Illustrative Example) ### Parameters N/A ### Request Example N/A ### Response N/A ## Code Example (Rust) ```rust use std::cmp::Ordering; use alpm::{Alpm, SigLevel, Version, vercmp}; fn main() -> alpm::Result<()> { // Compare version strings directly assert!(Version::new("2.0.0") > Version::new("1.9.9")); assert!(Version::new("1.10.0") > Version::new("1.9.0")); assert!(Version::new("2.0.0-1") == Version::new("2.0.0")); // Release suffix ignored // Use vercmp function for Ordering result match vercmp("2.1.0", "2.0.5") { Ordering::Greater => println!("2.1.0 is newer"), Ordering::Less => println!("2.0.5 is newer"), Ordering::Equal => println!("Same version"), } // Compare package versions let handle = Alpm::new("/", "/var/lib/pacman")?; let core = handle.register_syncdb("core", SigLevel::USE_DEFAULT)?; if let Ok(linux) = core.pkg("linux") { let current = linux.version(); if current > Version::new("5.0.0") { println!("Linux {} is newer than 5.0.0", current); } // Using vercmp method match current.vercmp(Version::new("6.0.0")) { Ordering::Less => println!("Older than 6.0.0"), Ordering::Equal => println!("Is 6.0.0"), Ordering::Greater => println!("Newer than 6.0.0"), } } // Sort packages by version let mut pkgs: Vec<_> = core.pkgs().iter().collect(); pkgs.sort_by(|a, b| a.version().vercmp(b.version())); Ok(()) } ``` ``` -------------------------------- ### Implement ALPM Event and Log Callbacks Source: https://context7.com/pacman/alpm.rs/llms.txt Shows how to register callbacks for logging and transaction events. It demonstrates handling stateful callbacks using Rc and RefCell for shared data access. ```rust use std::cell::RefCell; use std::rc::Rc; use alpm::{Alpm, Event, LogLevel, SigLevel}; fn main() -> alpm::Result<()> { let handle = Alpm::new("/", "/var/lib/pacman")?; handle.set_log_cb((), |level, msg, _data| { match level { LogLevel::ERROR => eprintln!("[ERROR] {}", msg), _ => println!("{}", msg), } }); let message_count = Rc::new(RefCell::new(0)); handle.set_log_cb(message_count.clone(), |_level, _msg, data| { *data.borrow_mut() += 1; }); handle.set_event_cb((), |event, _data| { match event.event() { Event::TransactionStart => println!(">>> Transaction starting..."), _ => {} } }); handle.register_syncdb("core", SigLevel::USE_DEFAULT)?; println!("Total log messages: {}", message_count.borrow()); Ok(()) } ``` -------------------------------- ### Rust: Checking libalpm Capabilities with alpm.rs Source: https://context7.com/pacman/alpm.rs/llms.txt Shows how to query the runtime capabilities of the libalpm library using the `Capabilities` struct in alpm.rs. This includes checking for support for NLS (translations), downloaders, and signature verification, and using bitflags for combined checks. ```rust use alpm::Capabilities; fn main() { let caps = Capabilities::new(); println!("libalpm capabilities:"); println!(" NLS (translations): {}", caps.nls()); println!(" Downloader: {}", caps.downloader()); println!(" Signatures: {}", caps.signatures()); if !caps.signatures() { println!("Warning: Signature verification not available"); println!("Package signatures will not be checked!"); } // Use bitflags operations if caps.contains(Capabilities::DOWNLOADER | Capabilities::SIGNATURES) { println!("Full download and verification support available"); } } ``` -------------------------------- ### Managing Package Groups with ALPM in Rust Source: https://context7.com/pacman/alpm.rs/llms.txt Shows how to access and list packages within specific package groups, such as 'base' or 'base-devel'. It also covers how to list all available groups in a database and find packages belonging to a group across all databases. ```rust use alpm::{Alpm, SigLevel}; fn main() -> alpm::Result<()> { let handle = Alpm::new("/", "/var/lib/pacman")?; let core = handle.register_syncdb("core", SigLevel::USE_DEFAULT)?; // Get all packages in a group if let Ok(group) = core.group("base") { println!("Group '{}' contains {} packages:", group.name(), group.packages().len()); for pkg in group.packages() { println!(" {} - {}", pkg.name(), pkg.desc().unwrap_or("")); } } // List all groups in a database if let Ok(groups) = core.groups() { println!("Available groups:"); for group in groups.iter() { println!(" {} ({} packages)", group.name(), group.packages().len()); } } // Find packages from a group across all databases let pkgs = handle.find_group_pkgs(handle.syncdbs(), "base-devel"); for pkg in pkgs.iter() { println!("{} from {}", pkg.name(), pkg.db().map(|d| d.name()).unwrap_or("unknown")); } Ok(()) } ``` -------------------------------- ### Load and Inspect Package Files with Rust Source: https://context7.com/pacman/alpm.rs/llms.txt Loads package files (.pkg.tar.xz, .pkg.tar.zst) directly from disk using the alpm Rust library. It allows inspection of package metadata, listing files, and checking for specific file contents or scriptlets. Dependencies include the 'alpm' crate. ```rust use alpm::{Alpm, SigLevel}; fn main() -> alpm::Result<()> { let handle = Alpm::new("/", "/var/lib/pacman")?; // Load a package file from disk let pkg = handle.pkg_load( "/var/cache/pacman/pkg/pacman-6.0.2-1-x86_64.pkg.tar.zst", true, // full metadata parsing SigLevel::USE_DEFAULT, // signature verification level )?; // Inspect package metadata println!("Package: {} {}", pkg.name(), pkg.version()); println!("Description: {}", pkg.desc().unwrap_or("N/A")); println!("Architecture: {}", pkg.arch().unwrap_or("N/A")); println!("Package size: {} bytes", pkg.size()); println!("Installed size: {} bytes", pkg.isize()); println!("SHA256: {}", pkg.sha256sum().unwrap_or("N/A")); // List files in the package let files = pkg.files(); println!("Contains {} files:", files.files().len()); for file in files.files().iter().take(10) { println!(" {}", String::from_utf8_lossy(file.name())); } // Check if package contains a specific file if files.contains("etc/pacman.conf").is_some() { println!("Package contains pacman.conf"); } // List backup files (files preserved on upgrade) for backup in pkg.backup() { println!("Backup: {} (hash: {})", backup.name(), backup.hash()); } // Check for scriptlet if pkg.has_scriptlet() { println!("Package has install scriptlet"); } // List licenses for license in pkg.licenses() { println!("License: {}", license); } Ok(()) } ``` -------------------------------- ### Rust: Comprehensive Error Handling with alpm.rs Source: https://context7.com/pacman/alpm.rs/llms.txt Demonstrates how to handle various libalpm errors in Rust using the `Error` enum and `Result` type. It covers initialization, database, and package-specific errors, along with using the `?` operator for concise error propagation. ```rust use alpm::{Alpm, Error, SigLevel}; fn main() { // Handle initialization errors let handle = match Alpm::new("/nonexistent", "/var/lib/pacman") { Ok(h) => h, Err(e) => { eprintln!("Failed to initialize alpm: {}", e); match e { Error::BadPerms => eprintln!("Check file permissions"), Error::NotADir => eprintln!("Path is not a directory"), Error::HandleLock => eprintln!("Another process has the lock"), _ => eprintln!("Error code: {:?}", e), } return; } }; // Handle database errors match handle.register_syncdb("nonexistent-repo", SigLevel::USE_DEFAULT) { Ok(db) => println!("Registered: {}", db.name()), Err(e) if e == Error::DbNotFound => eprintln!("Repository not found"), Err(e) if e == Error::DbInvalidSig => eprintln!("Invalid signature"), Err(e) => eprintln!("Database error: {}", e), } // Handle package errors let localdb = handle.localdb(); match localdb.pkg("nonexistent-package") { Ok(pkg) => println!("Found: {}", pkg.name()), Err(Error::PkgNotFound) => eprintln!("Package not found"), Err(e) => eprintln!("Package error: {}", e), } // Check last error on handle let last = handle.last_error(); if !last.ok() { println!("Last error: {}", last); } // Using ? operator with Result fn do_operations(handle: &Alpm) -> alpm::Result<()> { let db = handle.register_syncdb("core", SigLevel::USE_DEFAULT)?; let pkg = db.pkg("linux")?; println!("Found {} {}", pkg.name(), pkg.version()); Ok(()) } if let Err(e) = do_operations(&handle) { eprintln!("Operation failed: {}", e); } } ``` -------------------------------- ### Dependency Resolution and Satisfiers with ALPM in Rust Source: https://context7.com/pacman/alpm.rs/llms.txt Explains how to find packages that satisfy versioned dependency requirements across different databases using `find_satisfier`. It also covers creating and inspecting dependency objects and checking which packages require a specific package. ```rust use alpm::{Alpm, Depend, SigLevel}; fn main() -> alpm::Result<()> { let handle = Alpm::new("/", "/var/lib/pacman")?; handle.register_syncdb("core", SigLevel::USE_DEFAULT)?; handle.register_syncdb("extra", SigLevel::USE_DEFAULT)?; // Find a package satisfying a dependency string if let Some(pkg) = handle.syncdbs().find_satisfier("linux>5.0") { println!("Found {} {} satisfies 'linux>5.0'", pkg.name(), pkg.version()); } // Find satisfier in local database if let Some(pkg) = handle.localdb().pkgs().find_satisfier("python>=3.10") { println!("Installed: {} {}", pkg.name(), pkg.version()); } // Create and inspect dependency objects let dep = Depend::new("glibc>=2.35"); println!("Dependency: {}", dep); println!(" Name: {}", dep.name()); println!(" Version: {:?}", dep.version()); println!(" Modifier: {:?}", dep.depmod()); // Check what packages depend on a specific package let core = handle.syncdbs().iter().find(|db| db.name() == "core").unwrap(); if let Ok(pkg) = core.pkg("glibc") { let required_by = pkg.required_by(); println!("Packages requiring glibc:"); for name in required_by.iter().take(10) { println!(" {}", name); } } Ok(()) } ``` -------------------------------- ### Callbacks for Events and Logging API Source: https://context7.com/pacman/alpm.rs/llms.txt Allows setting callbacks to receive log messages, events, and download progress during package operations. Callbacks can maintain state. ```APIDOC ## Callbacks for Events and Logging Set callbacks to receive log messages, events, and download progress during package operations. Callbacks can maintain state that persists across invocations. ### Method Rust (using alpm.rs library) ### Endpoint N/A (Local library operations) ### Parameters N/A (Library functions) ### Request Example ```rust use std::cell::RefCell; use std::rc::Rc; use alpm::{Alpm, Event, LogLevel, SigLevel}; fn main() -> alpm::Result<()> { let handle = Alpm::new("/", "/var/lib/pacman")?; // Simple log callback with no state handle.set_log_cb((), |level, msg, _data| { match level { LogLevel::ERROR => eprintln!("[ERROR] {}", msg), LogLevel::WARNING => eprintln!("[WARN] {}", msg), LogLevel::DEBUG => println!("[DEBUG] {}", msg), _ => println!("{}", msg), } }); // Log callback with mutable counter state handle.set_log_cb(0u32, |level, msg, count| { *count += 1; println!("[{}] {:?}: {}", count, level, msg); }); // Shared state accessible outside callback let message_count = Rc::new(RefCell::new(0)); handle.set_log_cb(message_count.clone(), |_level, _msg, data| { *data.borrow_mut() += 1; }); // Event callback for transaction events handle.set_event_cb((), |event, _data| { match event.event() { Event::TransactionStart => println!(">>> Transaction starting..."), Event::TransactionDone => println!(">>> Transaction complete!"), Event::PackageOperationStart(op) => { println!(">>> Processing package operation..."); } Event::DatabaseMissing(db) => { eprintln!("Warning: Database '{}' not found", db.dbname()); } _ => {} } }); // Register databases (triggers events) handle.register_syncdb("core", SigLevel::USE_DEFAULT)?; handle.register_syncdb("extra", SigLevel::USE_DEFAULT)?; println!("Total log messages: {}", message_count.borrow()); Ok(()) } ``` ``` -------------------------------- ### Manage Package Lists with Rust ALPM Source: https://context7.com/pacman/alpm.rs/llms.txt Illustrates how to use `AlpmList` (immutable) and `AlpmListMut` (mutable) types for managing package lists, similar to slices and vectors in Rust. It covers iterating, summing sizes, converting between mutable and immutable lists, filtering, adding, and extending lists with dependencies. Requires the `alpm` crate. ```rust use alpm::{Alpm, AlpmListMut, Depend, SigLevel}; fn main() -> alpm::Result<()> { let handle = Alpm::new("/", "/var/lib/pacman")?; let core = handle.register_syncdb("core", SigLevel::USE_DEFAULT)?; // AlpmList is borrowed and immutable (like &[T]) let pkgs = core.pkgs(); let total_size: i64 = pkgs.iter().map(|pkg| pkg.isize()).sum(); println!("Total installed size: {} bytes", total_size); // Convert to mutable list for modifications let mut pkgs_mut = pkgs.to_list_mut(); // Remove by index pkgs_mut.remove(0).ok(); // Filter packages pkgs_mut.retain(|pkg| pkg.name().starts_with("lib")); // Add a package reference if let Ok(linux) = core.pkg("linux") { pkgs_mut.push(linux); } println!("Filtered list has {} packages", pkgs_mut.len()); // Create a new list from scratch let mut deps: AlpmListMut = AlpmListMut::new(); deps.push(Depend::new("glibc>=2.35")); deps.push(Depend::new("gcc")); deps.push(Depend::new("make")); // Extend from iterator if let Ok(pkg) = core.pkg("linux") { deps.extend(pkg.depends().iter().map(|d| d.to_depend())); } for dep in deps.iter() { println!("Dep: {}", dep); } Ok(()) } ``` -------------------------------- ### List Operations API Source: https://context7.com/pacman/alpm.rs/llms.txt Explains the usage of `AlpmList` (immutable) and `AlpmListMut` (mutable) for managing package lists, similar to slices and vectors. ```APIDOC ## List Operations (AlpmList and AlpmListMut) alpm.rs provides `AlpmList` (borrowed, immutable) and `AlpmListMut` (owned, mutable) types that wrap libalpm's linked list. These work similarly to `&[T]` and `Vec`. ### Method N/A (Illustrative Example) ### Endpoint N/A (Illustrative Example) ### Parameters N/A ### Request Example N/A ### Response N/A ## Code Example (Rust) ```rust use alpm::{Alpm, AlpmListMut, Depend, SigLevel}; fn main() -> alpm::Result<()> { let handle = Alpm::new("/", "/var/lib/pacman")?; let core = handle.register_syncdb("core", SigLevel::USE_DEFAULT)?; // AlpmList is borrowed and immutable (like &[T]) let pkgs = core.pkgs(); let total_size: i64 = pkgs.iter().map(|pkg| pkg.isize()).sum(); println!("Total installed size: {} bytes", total_size); // Convert to mutable list for modifications let mut pkgs_mut = pkgs.to_list_mut(); // Remove by index pkgs_mut.remove(0).ok(); // Filter packages pkgs_mut.retain(|pkg| pkg.name().starts_with("lib")); // Add a package reference if let Ok(linux) = core.pkg("linux") { pkgs_mut.push(linux); } println!("Filtered list has {} packages", pkgs_mut.len()); // Create a new list from scratch let mut deps: AlpmListMut = AlpmListMut::new(); deps.push(Depend::new("glibc>=2.35")); deps.push(Depend::new("gcc")); deps.push(Depend::new("make")); // Extend from iterator if let Ok(pkg) = core.pkg("linux") { deps.extend(pkg.depends().iter().map(|d| d.to_depend())); } for dep in deps.iter() { println!("Dep: {}", dep); } Ok(()) } ``` ``` -------------------------------- ### Error Handling in alpm.rs Source: https://context7.com/pacman/alpm.rs/llms.txt Explains how to handle libalpm errors using the Error enum and Result type. ```APIDOC ## Error Handling ### Description Functions in alpm.rs return `Result` to handle libalpm error conditions. Users should match on the `Error` enum to handle specific scenarios like `DbNotFound` or `PkgNotFound`. ### Method N/A (Library API) ### Parameters - **handle** (Alpm) - Required - The active alpm handle. ### Response - **Result** - Returns the requested data or an Error enum variant. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.