### Handle Package Loading and Install Reason Source: https://context7.com/archlinux/pyalpm/llms.txt Explains how to load a local package tarball into a Package object and how to manage the installation reason for local packages. ```APIDOC ## Handle — Package Loading and Install Reason ### `handle.load_pkg(path)` / `handle.set_pkgreason(pkg, reason)` — Load a local tarball and manage install reasons ### Description `load_pkg()` reads a `.pkg.tar.*` tarball from disk and returns a `Package` object without installing it. `set_pkgreason()` changes whether a locally installed package is recorded as explicitly installed (`0`) or a dependency (`1`). ### Methods - **load_pkg(path)**: Loads a package tarball from the specified path. - **set_pkgreason(pkg, reason)**: Sets the installation reason for a package. ### Parameters - **path** (str) - Required - The path to the package tarball for `load_pkg`. - **pkg** (Package) - Required - The Package object for `set_pkgreason`. - **reason** (int) - Required - The installation reason (0 for explicit, 1 for dependency) for `set_pkgreason`. ### Properties of Package Object - **name** (str) - The name of the package. - **version** (str) - The version of the package. - **files** (list[tuple]) - List of files owned by the package. ### Request Example ```python import pyalpm from pyalpm import Handle handle = Handle('/', '/var/lib/pacman') pkg = handle.load_pkg('/var/cache/pacman/pkg/coreutils-9.1-1-x86_64.pkg.tar.zst') print(pkg.name) print(pkg.version) ``` ### Response Example ``` coreutils 9.1-1 ``` ``` -------------------------------- ### set_pkgreason(package: Package, reason: int) Source: https://github.com/archlinux/pyalpm/blob/master/doc/pyalpm/Handle.md Set the installation reason for a given package. ```APIDOC ## set_pkgreason(package: [Package](Package.md#Package), reason: int) ### Description Sets the reason for this package installation’s (e.g., explicitly or as a dependency). ### Parameters * **package** ([*Package*](Package.md#Package)) – the package. * **reason** (*int*) – 0 for explicitly requrested by a user or 1 for as dependency of another package ### Returns Nothing ``` -------------------------------- ### Initialize Pyalpm Handle and Get Local Database Source: https://github.com/archlinux/pyalpm/blob/master/doc/pyalpm/pyalpm.md Initializes a Handle object for interacting with pacman databases and retrieves the local package database. Requires specifying root directory and database path. ```python from pyalpm import Handle handle = Handle(".", "/var/lib/pacman") localdb = handle.get_localdb() ``` -------------------------------- ### handle.init_transaction Source: https://context7.com/archlinux/pyalpm/llms.txt Initializes a package operation transaction. Transactions allow for atomic package installations, removals, or upgrades. Use boolean flag keyword arguments to set transaction properties, add or remove target packages, then call `prepare()` and `commit()`. Always ensure `release()` is called when done, preferably using a try/finally block. ```APIDOC ## handle.init_transaction(**flags) ### Description Executes package operations atomically. Transactions are used to install, remove, or upgrade packages. Initialize with boolean flag keyword arguments, add/remove target packages, then call `prepare()` and `commit()`. Always call `release()` when done (use try/finally). ### Parameters #### Flags (Keyword Arguments) - **needed** (bool) - If True, only install packages that are not already installed or are older than the target version. - **noscriptlet** (bool) - If True, do not run scriptlets during the transaction. - **cascade** (bool) - If True, remove dependencies of removed packages as well. - **nosave** (bool) - If True, do not save the package list before removal. - **downloadonly** (bool) - If True, only download packages without installing them. - **nodeps** (bool) - If True, do not check for dependencies. - **dbonly** (bool) - If True, only perform database operations, no actual file changes. ### Method `handle.init_transaction()` ### Returns - **Transaction** - An object representing the transaction, with methods like `sysupgrade()`, `add_pkg()`, `remove_pkg()`, `prepare()`, `commit()`, `interrupt()`, and `release()`. ``` -------------------------------- ### Search and Get Package from Synchronized Database Source: https://github.com/archlinux/pyalpm/blob/master/doc/pyalpm/pyalpm.md Searches for packages within a registered synchronized database using a regular expression and retrieves a specific package, accessing its download size. ```python core.search("linux.* பகு") # a bunch of packages with linux in their name linux = core.get_pkg("linux") print(linux.download_size) # around 70 megabytes ``` -------------------------------- ### Change install reason for an installed package Source: https://context7.com/archlinux/pyalpm/llms.txt Marks a package as explicitly installed. Handles potential pyalpm errors during the operation. ```python localdb = handle.get_localdb() linux = localdb.get_pkg('linux') if linux: # Mark as explicitly installed (0 = explicit, 1 = dependency) try: handle.set_pkgreason(linux, 0) except pyalpm.error as e: print(f"Failed: {e}") ``` -------------------------------- ### Change install reason for an installed package Source: https://context7.com/archlinux/pyalpm/llms.txt This snippet demonstrates how to change the installation reason for a package from dependency to explicit. ```APIDOC ## Change install reason for an installed package This operation allows you to mark a package as explicitly installed or as a dependency. ### Usage ```python localdb = handle.get_localdb() linux = localdb.get_pkg('linux') if linux: # Mark as explicitly installed (0 = explicit, 1 = dependency) try: handle.set_pkgreason(linux, 0) except pyalpm.error as e: print(f"Failed: {e}") ``` ``` -------------------------------- ### pyalpm.sync_newversion(pkg, databases) / pyalpm.find_grp_pkgs(databases, group) Source: https://context7.com/archlinux/pyalpm/llms.txt Provides cross-database lookup capabilities. `sync_newversion` checks synchronized databases for available upgrades of an installed package, while `find_grp_pkgs` collects all packages belonging to a specified group across multiple databases. ```APIDOC ## pyalpm.sync_newversion(pkg, databases) / pyalpm.find_grp_pkgs(databases, group) — Cross-database lookups ### Description `sync_newversion()` checks sync databases for an available upgrade of a given installed package. `find_grp_pkgs()` collects all packages belonging to a group across multiple databases. ### Parameters - **sync_newversion**: - **pkg** (Package) - The installed package to check for upgrades. - **databases** (list[Database]) - A list of synchronized databases to search within. - **find_grp_pkgs**: - **databases** (list[Database]) - A list of databases to search within. - **group** (string) - The name of the package group to find. ### Returns - **sync_newversion**: `Package | None` - The `Package` object representing the new version if an upgrade is found, otherwise `None`. - **find_grp_pkgs**: `list[Package]` - A list of `Package` objects belonging to the specified group. ### Example ```python import pyalpm from pyalpm import Handle handle = Handle('/', '/var/lib/pacman') localdb = handle.get_localdb() core = handle.register_syncdb('core', pyalpm.SIG_DATABASE_OPTIONAL) extra = handle.register_syncdb('extra', pyalpm.SIG_DATABASE_OPTIONAL) syncdbs = handle.get_syncdbs() # Check for an upgrade of every installed package upgrades = [] for pkg in localdb.pkgcache: candidate = pyalpm.sync_newversion(pkg, syncdbs) if candidate: upgrades.append((pkg.name, pkg.version, candidate.version)) for name, old, new in upgrades: print(f"{name}: {old} -> {new}") # linux: 6.0.1-1 -> 6.1.1-1 # Collect all packages in the 'gnome' group across all sync dbs gnome_pkgs = pyalpm.find_grp_pkgs(syncdbs, 'gnome') for pkg in gnome_pkgs: print(f"{pkg.db.name}/{pkg.name}") # TypeError if list contains non-Database items try: pyalpm.find_grp_pkgs([None], 'gnome') except TypeError as e: print(e) # 'list must contain only Database objects' ``` ``` -------------------------------- ### Load Local Package Tarball Source: https://context7.com/archlinux/pyalpm/llms.txt Loads a package tarball from disk into a `Package` object without installing it. Useful for inspecting package metadata before installation. ```python import pyalpm from pyalpm import Handle handle = Handle('/', '/var/lib/pacman') # Load a package file from disk (does not install it) pkg = handle.load_pkg('/var/cache/pacman/pkg/coreutils-9.1-1-x86_64.pkg.tar.zst') print(pkg.name) # 'coreutils' print(pkg.version) # '9.1-1' ``` -------------------------------- ### Checking for Package Upgrades with pyalpm.sync_newversion Source: https://context7.com/archlinux/pyalpm/llms.txt Query synchronized databases to find if a newer version of an installed package is available. Requires a pyalpm Handle and registered sync databases. ```python import pyalpm from pyalpm import Handle handle = Handle('/', '/var/lib/pacman') localdb = handle.get_localdb() core = handle.register_syncdb('core', pyalpm.SIG_DATABASE_OPTIONAL) extra = handle.register_syncdb('extra', pyalpm.SIG_DATABASE_OPTIONAL) syncdbs = handle.get_syncdbs() # Check for an upgrade of every installed package upgrades = [] for pkg in localdb.pkgcache: candidate = pyalpm.sync_newversion(pkg, syncdbs) if candidate: upgrades.append((pkg.name, pkg.version, candidate.version)) for name, old, new in upgrades: print(f"{name}: {old} -> {new}") # linux: 6.0.1-1 -> 6.1.1-1 ``` -------------------------------- ### Getting pyalpm and ALPM Library Versions Source: https://context7.com/archlinux/pyalpm/llms.txt Retrieve the version of the pyalpm library and the underlying ALPM library it interfaces with. ```python import pyalpm # Version and library version introspection print(pyalpm.version()) # e.g. '0.11.1' print(pyalpm.alpmversion()) # e.g. '13.0.2' ``` -------------------------------- ### Handle Initialization and Configuration Source: https://context7.com/archlinux/pyalpm/llms.txt Demonstrates how to create a Handle object, configure its properties, and manage ignore lists. It also shows how to set up logging and download progress callbacks. ```APIDOC ## Handle(rootpath, dbpath) — Create an alpm context handle ### Description The `Handle` is the entry point for all pyalpm operations. It is initialized with a root installation path and a database path. All database access and transaction management flows through this object. Raises `pyalpm.error` if the handle cannot be created (e.g., invalid root path). ### Method ```python Handle(rootpath, dbpath) ``` ### Parameters - **rootpath** (str) - Required - The root installation path. - **dbpath** (str) - Required - The database path. ### Properties - **logfile** (str) - Path to the pacman log file. - **gpgdir** (str) - Path to the GPG directory. - **cachedirs** (list[str]) - List of package cache directories. - **arch** (list[str]) - List of supported architectures. - **usesyslog** (bool) - Whether to use syslog for logging. - **checkspace** (bool) - Whether to check disk space before operations. ### Methods - **add_noupgrade(pkgname)**: Adds a package to the no-upgrade list. - **add_ignorepkg(pkgname)**: Adds a package to the ignore list. - **add_ignoregrp(grpname)**: Adds a package group to the ignore list. - **add_noextract(filename)**: Adds a file to the no-extract list. - **remove_noupgrade(pkgname)**: Removes a package from the no-upgrade list. - **remove_ignorepkg(pkgname)**: Removes a package from the ignore list. - **remove_ignoregrp(grpname)**: Removes a package group from the ignore list. - **remove_noextract(filename)**: Removes a file from the no-extract list. ### Callbacks - **logcb** (callable) - Callback function for logging messages. - **dlcb** (callable) - Callback function for download progress. ### Request Example ```python import pyalpm from pyalpm import Handle handle = Handle('/', '/var/lib/pacman') handle.logfile = '/var/log/pacman.log' handle.add_noupgrade('linux') print(handle.root) print(handle.noupgrades) ``` ### Response Example ``` / ['linux'] ``` ### Error Handling Raises `pyalpm.error` if the handle cannot be created. ``` -------------------------------- ### Create and Configure Alpm Handle Source: https://context7.com/archlinux/pyalpm/llms.txt Initializes an alpm context handle with root and database paths. Configures optional properties like log file, GPG directory, cache directories, architecture, and logging behavior. Allows adding and removing packages/groups to ignore for upgrades or extraction. ```python import pyalpm from pyalpm import Handle # Create a handle pointing at the real system pacman database handle = Handle('/', '/var/lib/pacman') # Configure optional handle properties handle.logfile = '/var/log/pacman.log' handle.gpgdir = '/etc/pacman.d/gnupg/' handle.cachedirs = ['/var/cache/pacman/pkg/'] handle.arch = ['x86_64'] handle.usesyslog = False handle.checkspace = True # Add packages/groups that pacman should never upgrade or extract handle.add_noupgrade('linux') handle.add_ignorepkg('grub') handle.add_ignoregrp('base-devel') handle.add_noextract('index.php') # Inspect current settings print(handle.root) # '/' print(handle.cachedirs) # ['/var/cache/pacman/pkg/'] print(handle.noupgrades) # ['linux'] print(handle.ignorepkgs) # ['grub'] print(handle.ignoregrps) # ['base-devel'] # Remove entries handle.remove_noupgrade('linux') handle.remove_ignorepkg('grub') handle.remove_ignoregrp('base-devel') handle.remove_noextract('index.php') # Set a log callback import sys def cb_log(level, line): if level & pyalpm.LOG_ERROR: sys.stderr.write("ERROR: " + line) elif level & pyalpm.LOG_WARNING: sys.stderr.write("WARNING: " + line) handle.logcb = cb_log # Set a download progress callback def cb_download(filename, transferred, total): print(f"Downloading {filename}: {transferred}/{total}") handle.dlcb = cb_download # Error case: invalid rootdir try: bad = Handle('/non-existent', '/') except pyalpm.error as e: print(e) # 'could not create a libalpm handle' ``` -------------------------------- ### Build pyalpm with Meson Source: https://github.com/archlinux/pyalpm/blob/master/README.md Standard procedure to set up the build environment and compile the pyalpm package using Meson. ```bash meson setup build meson compile -C build ``` -------------------------------- ### Build pyalpm Documentation with Meson Source: https://github.com/archlinux/pyalpm/blob/master/README.md Command to compile the documentation for pyalpm using Meson. ```bash meson compile -C build doc ``` -------------------------------- ### Handle Class Initialization Source: https://github.com/archlinux/pyalpm/blob/master/doc/pyalpm/Handle.md Initialize a Handle object with the root and database paths. ```APIDOC ## Handle(rootpath: string, dbpath: string) ### Description A handle object is initialized with a root path (i.e., where do packages get installed) and a dbpath (i.e., where is the database information located). Generally, these parameters default to root path being ‘/’ and a dbpath being ‘/var/lib/pacman’. ### Parameters * **rootpath** (*str*) - The root directory for package installation. * **dbpath** (*str*) - The directory for pacman database information. ``` -------------------------------- ### Package Attributes Source: https://github.com/archlinux/pyalpm/blob/master/doc/pyalpm/Package.md Access various attributes of a package object to get information like its name, build date, size, dependencies, and more. ```APIDOC ## Package Attributes ### Description Access various attributes of a package object to get information like its name, build date, size, dependencies, and more. ### Attributes - **name** (str) - The name of the package - **base** (str) - The package base name - **builddate** (Long long) - The date on which this package was built - **installdate** (Long Long) - The date in which this package was installed (only in localdb) - **size** (Long Long) - The archive size - **isize** (Long Long) - The installed size - **files** (list) - A list of files in this package - **db** (Database) - A reference to the database this package belongs to - **has_scriptlet** (boolean) - Whether this package has a scriptlet - **licenses** (list) - A list of licenses for this package. - **desc** (string) - Package description. - **depends** (list) - A list of dependencies for this package - **optdepends** (list) - A list of the optional dependencies for this package - **checkdepends** (list) - A list of the check dependencies for this package (syncdb only) - **makedepends** (list) - A list of the make dependencies for this package (syncdb only) - **replaces** (list) - A list of packages this package replaces - **provides** (list) - A list of strings of what this package provides - **conflicts** (list) - A list of packages this package conflicts with - **backup** (list) - A list of backup tuples (filename, md5sum) - **groups** (list) - The groups this package belongs to - **arch** (string) - The CPU architecture for this package - **packager** (string) - The packager for this package - **md5sum** (string) - The package md5sum as hexadecimal digits - **sha256sum** (string) - The package sha256sum as hexadecimal digits - **base64_sig** (string) - The package signature encoded as base64 - **filename** (string) - The package filename - **url** (string) - The package URL ``` -------------------------------- ### Initialize Handle with Pacman Configuration Source: https://context7.com/archlinux/pyalpm/llms.txt Use `pycman.config` to parse `pacman.conf` and initialize a `Handle`. This is the recommended approach for production environments to ensure system configuration is respected. Options can be overridden using `argparse.Namespace`. ```python from pycman.config import PacmanConfig, init_with_config, init_with_config_and_options # Quickest path: read /etc/pacman.conf and get a fully-configured handle handle = init_with_config('/etc/pacman.conf') localdb = handle.get_localdb() print([p.name for p in localdb.pkgcache[:5]]) # Full PacmanConfig object for inspection or modification config = PacmanConfig(conf='/etc/pacman.conf') print(config.options['RootDir']) # '/' print(config.options['DBPath']) # '/var/lib/pacman' print(list(config.repos.keys())) # ['core', 'extra', 'community', ...] # Override settings from argparse Namespace import argparse opts = argparse.Namespace( root=None, dbpath='/tmp/testdb', gpgdir=None, arch=None, logfile=None, cachedir=None, config='/etc/pacman.conf', debug=False ) handle = init_with_config_and_options(opts) # Manually apply config to an existing handle import pyalpm h = pyalpm.Handle('/', '/var/lib/pacman') config.apply(h) # sets logfile, gpgdir, arch, cachedirs, sync repos, etc. # Use a custom log callback via pycman defaults import pyalpm, sys def cb_log(level, line): if level & pyalpm.LOG_ERROR: sys.stderr.write("ERROR: " + line) elif level & pyalpm.LOG_WARNING: sys.stderr.write("WARNING: " + line) handle.logcb = cb_log ``` ```python from pycman.config import PacmanConfig, init_with_config, init_with_config_and_options # Quickest path: read /etc/pacman.conf and get a fully-configured handle handle = init_with_config('/etc/pacman.conf') localdb = handle.get_localdb() print([p.name for p in localdb.pkgcache[:5]]) ``` ```python from pycman.config import PacmanConfig, init_with_config, init_with_config_and_options # Full PacmanConfig object for inspection or modification config = PacmanConfig(conf='/etc/pacman.conf') print(config.options['RootDir']) # '/' print(config.options['DBPath']) # '/var/lib/pacman' print(list(config.repos.keys())) # ['core', 'extra', 'community', ...] ``` ```python from pycman.config import PacmanConfig, init_with_config, init_with_config_and_options # Override settings from argparse Namespace import argparse opts = argparse.Namespace( root=None, dbpath='/tmp/testdb', gpgdir=None, arch=None, logfile=None, cachedir=None, config='/etc/pacman.conf', debug=False ) handle = init_with_config_and_options(opts) ``` ```python from pycman.config import PacmanConfig, init_with_config, init_with_config_and_options # Manually apply config to an existing handle import pyalpm h = pyalpm.Handle('/', '/var/lib/pacman') config.apply(h) # sets logfile, gpgdir, arch, cachedirs, sync repos, etc. ``` ```python from pycman.config import PacmanConfig, init_with_config, init_with_config_and_options # Use a custom log callback via pycman defaults import pyalpm, sys def cb_log(level, line): if level & pyalpm.LOG_ERROR: sys.stderr.write("ERROR: " + line) elif level & pyalpm.LOG_WARNING: sys.stderr.write("WARNING: " + line) handle.logcb = cb_log ``` -------------------------------- ### Query Package Files from Synchronized Database Source: https://github.com/archlinux/pyalpm/blob/master/doc/pyalpm/pyalpm.md Configures the Handle to query package file lists from a synchronized database by setting the 'dbext' attribute to '.files'. Then, retrieves and prints the first file entry for a package. ```python handle = Handle(".", "/var/lib/pacman") handle.dbext = ".files" core = handle.register_syncdb("core", pyalpm.SIG_DATABASE_OPTIONAL) coreutils = core.get_pkg("coreutils") print(coreutils.files[0]) # ('usr/', 0, 0) ``` -------------------------------- ### get_pkg(name: string) Source: https://github.com/archlinux/pyalpm/blob/master/doc/pyalpm/Database.md Retrieves a package instance from the database by its name. ```APIDOC ## get_pkg ### Description Retrieves a package instance with the name ‘name’. ### Parameters #### Path Parameters - **name** (str) - Required - The name of the package (e.g., ‘coreutils’) ### Returns a reference to the Package object with the name ‘name’ or None if it doesn’t exist ``` -------------------------------- ### Run pyalpm Unit Tests with Meson Source: https://github.com/archlinux/pyalpm/blob/master/README.md Execute unit tests for pyalpm using the Meson build system. ```bash meson test -C build ``` -------------------------------- ### Upload pyalpm to PyPI Source: https://github.com/archlinux/pyalpm/blob/master/README.md Steps to create a source distribution and upload the pyalpm package to the Python Package Index (PyPI). ```bash python3 setup.py sdist twine upload -s dist/* --verbose ``` -------------------------------- ### db.get_pkg(name) Source: https://context7.com/archlinux/pyalpm/llms.txt Look up a package by its exact name in a database. Returns a Package object if found, otherwise None. ```APIDOC ## `db.get_pkg(name)` — Look up a package by exact name Returns a `Package` object if found, or `None`. Works on both local and sync databases. ### Usage ```python import pyalpm from pyalpm import Handle handle = Handle('/', '/var/lib/pacman') localdb = handle.get_localdb() # Look up an installed package pkg = localdb.get_pkg('coreutils') if pkg: print(pkg.name) # 'coreutils' print(pkg.version) # '9.1-1' print(pkg.desc) # 'The basic file, shell and text manipulation utilities...' else: print("Package not found") # Look up in a sync database core = handle.register_syncdb('core', pyalpm.SIG_DATABASE_OPTIONAL) linux = core.get_pkg('linux') if linux: print(linux.download_size) # ~70000000 (bytes) print(linux.isize) # installed size in bytes ``` ``` -------------------------------- ### Access Alpm Databases Source: https://context7.com/archlinux/pyalpm/llms.txt Retrieves the local installed-packages database using `get_localdb()`. Fetches all registered sync databases with `get_syncdbs()`. Registers new remote sync repositories using `register_syncdb()` and allows setting mirror servers for them. Can also query file ownership using the `.files` extension. ```python import pyalpm from pyalpm import Handle handle = Handle('/', '/var/lib/pacman') # Access the local (installed) database localdb = handle.get_localdb() print(localdb.name) # 'local' # Register sync databases with signature verification flags core = handle.register_syncdb('core', pyalpm.SIG_DATABASE_OPTIONAL) extra = handle.register_syncdb('extra', pyalpm.SIG_DATABASE_OPTIONAL) # Assign mirrors core.servers = ['https://mirror.example.com/$repo/os/$arch'] extra.servers = ['https://mirror.example.com/$repo/os/$arch'] # Retrieve all registered sync dbs for db in handle.get_syncdbs(): print(db.name, db.servers) # core ['https://mirror.example.com/core/os/x86_64'] # extra ['https://mirror.example.com/extra/os/x86_64'] # Use .files extension to query file ownership (like pacman -F) handle.dbext = '.files' core_files = handle.register_syncdb('core', pyalpm.SIG_DATABASE_OPTIONAL) coreutils = core_files.get_pkg('coreutils') if coreutils: print(coreutils.files[0]) # ('usr/', 0, 0) ``` -------------------------------- ### Enable Coverage for pyalpm Build Source: https://github.com/archlinux/pyalpm/blob/master/README.md Configure Meson to build pyalpm with coverage enabled and then run tests to generate coverage reports. ```bash meson setup build --reconfigure -Dcoverage=true meson compile -C build meson test -C build ninja coverage -C build ``` -------------------------------- ### Build pyalpm Against Pacman Git Master Source: https://github.com/archlinux/pyalpm/blob/master/README.md Instructions for cloning pacman's master branch, building it, and then configuring pyalpm to build against the locally built pacman libraries. ```bash git clone https://gitlab.archlinux.org/pacman/pacman.git mkdir build cd build && meson .. && ninja PKG_CONFIG_PATH=/path/to/pacman/build/meson-uninstalled make build ``` -------------------------------- ### init_transaction() Source: https://github.com/archlinux/pyalpm/blob/master/doc/pyalpm/Handle.md Initialize a package transaction with various options. ```APIDOC ## init_transaction() ### Description Initializes a transaction ### Parameters * **nodeps** (*bool*) – skip dependency checks * **force** (*bool*) – overwrite existing packages (deprecated) * **nosave** (*bool*) – do not save .pacsave files * **nodepversion** (*bool*) – undocumented * **cascade** (*bool*) – remove all dependent packages * **recurse** (*bool*) – remove also explicitly installed unneeded dependent packages * **dbonly** (*bool*) – only remove database entry, do not remove files * **alldeps** (*bool*) – mark packages as non-explicitly installed * **downloadonly** (*bool*) – download pakcages but do not install/upgrade anything * **noscriptlet** (*bool*) – do not execute the install scriptlet of one exists * **noconflicts** (*bool*) – ignore conflicts * **needed** (*bool*) – do not reinstall the targets that are already up-to-date. * **allexplicit** (*bool*) – undocmented * **unneeded** (*bool*) – remove also explicitly unneeded deps * **recurseall** (*bool*) – undocumented * **nolock** (*bool*) – do not database ### Returns a [`Transaction`](Transaction.md#Transaction) object ``` -------------------------------- ### Enumerate packages and groups Source: https://context7.com/archlinux/pyalpm/llms.txt Provides methods to access group memberships and package/group caches within a database. `read_grp` lists packages in a group, `pkgcache` lists all packages, and `grpcache` lists group-to-package mappings. ```python import pyalpm from pyalpm import Handle handle = Handle('/', '/var/lib/pacman') localdb = handle.get_localdb() # Get all packages in a group base_pkgs = localdb.read_grp('base') if base_pkgs: for pkg in base_pkgs: print(pkg.name) else: print("Group not found") # returns None if group doesn't exist # Iterate all installed packages all_pkgs = localdb.pkgcache print(f"Total installed packages: {len(all_pkgs)}") for pkg in all_pkgs[:5]: print(pkg.name, pkg.version) # Inspect group cache: list of ('groupname', [pkg, ...]) tuples for group_name, group_pkgs in localdb.grpcache: print(f"Group '{group_name}': {len(group_pkgs)} packages") ``` -------------------------------- ### pyalpm.sync_newversion(package, databases) Source: https://github.com/archlinux/pyalpm/blob/master/doc/pyalpm/Pyalpm.md Finds an available upgrade for a given package from a list of databases. ```APIDOC ## pyalpm.sync_newversion(package, databases) ### Description Finds an available upgrade for a package in a list of databases. ### Parameters #### Path Parameters - **package** (Package) - The package to check for upgrades. - **databases** (list) - A list of databases to search for upgrades. ### Returns - returns an upgrade [`Package`](Package.md#Package) candidate or none. ``` -------------------------------- ### pycman.config Source: https://context7.com/archlinux/pyalpm/llms.txt The `pycman.config` module provides utilities for parsing pacman configuration files and initializing pyalpm handles with system settings. It is the recommended approach for setting up a production-ready alpm handle. ```APIDOC ## pycman.config — PacmanConfig ### `PacmanConfig(conf, options)` / `init_with_config(path)` — Parse pacman.conf and initialize a handle The `pycman.config` module reads `/etc/pacman.conf` (or a custom path) and applies all settings to a `Handle` in one call. This is the recommended way to create a production-ready alpm handle that respects the system configuration. ### Functions - **`init_with_config(path)`** - Parses the pacman configuration from the specified path and returns a fully configured `pyalpm.Handle`. - **`init_with_config_and_options(options)`** - Initializes a `pyalpm.Handle` using a `argparse.Namespace` object for options, in addition to reading the configuration file. ### Class `PacmanConfig` - **`__init__(conf)`** - Initializes a `PacmanConfig` object by parsing the pacman configuration file at the given path. - **Parameters**: - **conf** (str): The path to the pacman configuration file. - **Attributes**: - **options** (dict): A dictionary containing the parsed configuration options. - **repos** (dict): A dictionary of repository configurations. - **`apply(handle)`** - Applies the parsed configuration settings to an existing `pyalpm.Handle` object. ``` -------------------------------- ### Look up a package by exact name Source: https://context7.com/archlinux/pyalpm/llms.txt Retrieves a Package object from the local or a synchronized database by its exact name. Returns None if the package is not found. ```python import pyalpm from pyalpm import Handle handle = Handle('/', '/var/lib/pacman') localdb = handle.get_localdb() # Look up an installed package pkg = localdb.get_pkg('coreutils') if pkg: print(pkg.name) # 'coreutils' print(pkg.version) # '9.1-1' print(pkg.desc) # 'The basic file, shell and text manipulation utilities...' else: print("Package not found") # Look up in a sync database core = handle.register_syncdb('core', pyalpm.SIG_DATABASE_OPTIONAL) linux = core.get_pkg('linux') if linux: print(linux.download_size) # ~70000000 (bytes) print(linux.isize) # installed size in bytes ``` -------------------------------- ### Initialize and Execute Package Transactions Source: https://context7.com/archlinux/pyalpm/llms.txt Use `init_transaction` to create a transaction object for package operations. Always call `release()` when done, preferably using a try/finally block. Various flags control transaction behavior like dependency checking and scriptlet execution. ```python import pyalpm from pyalpm import Handle handle = Handle('/', '/var/lib/pacman') core = handle.register_syncdb('core', pyalpm.SIG_DATABASE_OPTIONAL) core.servers = ['https://mirror.example.com/core/os/x86_64'] core.update(False) # --- System upgrade --- t = handle.init_transaction(needed=True) try: t.sysupgrade(False) # False = do not downgrade print("To add:", [p.name for p in t.to_add]) print("To remove:", [p.name for p in t.to_remove]) t.prepare() t.commit() except pyalpm.error as e: print(f"Transaction error: {e}") t.interrupt() finally: t.release() # --- Install a specific package --- linux_pkg = core.get_pkg('linux') t = handle.init_transaction(needed=True, noscriptlet=False) try: t.add_pkg(linux_pkg) t.prepare() t.commit() except pyalpm.error as e: print(f"Could not install: {e}") # e.g. 'could not satisfy dependencies' finally: t.release() # --- Remove a package --- localdb = handle.get_localdb() old_pkg = localdb.get_pkg('some-old-pkg') if old_pkg: t = handle.init_transaction(cascade=False, nosave=False) try: t.remove_pkg(old_pkg) t.prepare() t.commit() except pyalpm.error as e: print(f"Removal failed: {e}") finally: t.release() # Download-only (no install) — useful for prefetching t = handle.init_transaction(downloadonly=True) try: t.add_pkg(linux_pkg) t.prepare() t.commit() finally: t.release() # Inspect transaction flags t = handle.init_transaction(nodeps=True, dbonly=True) print(t.flags) # {'nodeps': True, 'dbonly': True, ...} t.release() ``` ```python import pyalpm from pyalpm import Handle handle = Handle('/', '/var/lib/pacman') core = handle.register_syncdb('core', pyalpm.SIG_DATABASE_OPTIONAL) core.servers = ['https://mirror.example.com/core/os/x86_64'] core.update(False) # --- System upgrade --- t = handle.init_transaction(needed=True) try: t.sysupgrade(False) # False = do not downgrade print("To add:", [p.name for p in t.to_add]) print("To remove:", [p.name for p in t.to_remove]) t.prepare() t.commit() except pyalpm.error as e: print(f"Transaction error: {e}") t.interrupt() finally: t.release() ``` ```python import pyalpm from pyalpm import Handle handle = Handle('/', '/var/lib/pacman') core = handle.register_syncdb('core', pyalpm.SIG_DATABASE_OPTIONAL) core.servers = ['https://mirror.example.com/core/os/x86_64'] core.update(False) # --- Install a specific package --- linux_pkg = core.get_pkg('linux') t = handle.init_transaction(needed=True, noscriptlet=False) try: t.add_pkg(linux_pkg) t.prepare() t.commit() except pyalpm.error as e: print(f"Could not install: {e}") # e.g. 'could not satisfy dependencies' finally: t.release() ``` ```python import pyalpm from pyalpm import Handle handle = Handle('/', '/var/lib/pacman') core = handle.register_syncdb('core', pyalpm.SIG_DATABASE_OPTIONAL) core.servers = ['https://mirror.example.com/core/os/x86_64'] core.update(False) # --- Remove a package --- localdb = handle.get_localdb() old_pkg = localdb.get_pkg('some-old-pkg') if old_pkg: t = handle.init_transaction(cascade=False, nosave=False) try: t.remove_pkg(old_pkg) t.prepare() t.commit() except pyalpm.error as e: print(f"Removal failed: {e}") finally: t.release() ``` ```python import pyalpm from pyalpm import Handle handle = Handle('/', '/var/lib/pacman') core = handle.register_syncdb('core', pyalpm.SIG_DATABASE_OPTIONAL) core.servers = ['https://mirror.example.com/core/os/x86_64'] core.update(False) # Download-only (no install) — useful for prefetching t = handle.init_transaction(downloadonly=True) try: t.add_pkg(linux_pkg) t.prepare() t.commit() finally: t.release() ``` ```python import pyalpm from pyalpm import Handle handle = Handle('/', '/var/lib/pacman') core = handle.register_syncdb('core', pyalpm.SIG_DATABASE_OPTIONAL) core.servers = ['https://mirror.example.com/core/os/x86_64'] core.update(False) # Inspect transaction flags t = handle.init_transaction(nodeps=True, dbonly=True) print(t.flags) # {'nodeps': True, 'dbonly': True, ...} t.release() ``` -------------------------------- ### db.read_grp(group) / db.pkgcache / db.grpcache Source: https://context7.com/archlinux/pyalpm/llms.txt Enumerate packages and groups within a database. `read_grp` lists packages in a group, `pkgcache` lists all packages, and `grpcache` lists group-to-package mappings. ```APIDOC ## `db.read_grp(group)` / `db.pkgcache` / `db.grpcache` — Enumerate packages and groups `read_grp()` returns a list of packages belonging to a named group. `pkgcache` gives all packages in the database. `grpcache` gives all group-to-package mappings. ### Usage ```python import pyalpm from pyalpm import Handle handle = Handle('/', '/var/lib/pacman') localdb = handle.get_localdb() # Get all packages in a group base_pkgs = localdb.read_grp('base') if base_pkgs: for pkg in base_pkgs: print(pkg.name) else: print("Group not found") # returns None if group doesn't exist # Iterate all installed packages all_pkgs = localdb.pkgcache print(f"Total installed packages: {len(all_pkgs)}") for pkg in all_pkgs[:5]: print(pkg.name, pkg.version) # Inspect group cache: list of ('groupname', [pkg, ...]) tuples for group_name, group_pkgs in localdb.grpcache: print(f"Group '{group_name}': {len(group_pkgs)} packages") ``` ``` -------------------------------- ### Finding Packages in a Group with pyalpm.find_grp_pkgs Source: https://context7.com/archlinux/pyalpm/llms.txt Collect all packages belonging to a specified group from multiple synchronized databases. Requires a list of Database objects. ```python import pyalpm from pyalpm import Handle handle = Handle('/', '/var/lib/pacman') localdb = handle.get_localdb() core = handle.register_syncdb('core', pyalpm.SIG_DATABASE_OPTIONAL) extra = handle.register_syncdb('extra', pyalpm.SIG_DATABASE_OPTIONAL) syncdbs = handle.get_syncdbs() # Collect all packages in the 'gnome' group across all sync dbs gnome_pkgs = pyalpm.find_grp_pkgs(syncdbs, 'gnome') for pkg in gnome_pkgs: print(f"{pkg.db.name}/{pkg.name}") # TypeError if list contains non-Database items try: pyalpm.find_grp_pkgs([None], 'gnome') except TypeError as e: print(e) # 'list must contain only Database objects' ``` -------------------------------- ### db.search(query) Source: https://context7.com/archlinux/pyalpm/llms.txt Search packages within a database by a regular expression matching their names. Returns a list of matching Package objects. ```APIDOC ## `db.search(query)` — Search packages by name regexp Returns a list of `Package` objects whose names match the given regular expression string. ### Usage ```python import pyalpm from pyalpm import Handle handle = Handle('/', '/var/lib/pacman') core = handle.register_syncdb('core', pyalpm.SIG_DATABASE_OPTIONAL) core.update(False) # Search for all packages with 'linux' in the name results = core.search('linux.*') for pkg in results: print(f"{pkg.db.name}/{pkg.name} {pkg.version}") print(f" {pkg.desc}") # core/linux 6.1.1-1 # The Linux kernel and modules # core/linux-headers 6.1.1-1 # Headers and scripts for building modules for the Linux kernel # Search the local database localdb = handle.get_localdb() installed = localdb.search('py.*') print([p.name for p in installed]) # ['python', 'python-pip', 'pyalpm', ...] ``` ``` -------------------------------- ### Query Package Information from Local Database Source: https://github.com/archlinux/pyalpm/blob/master/doc/pyalpm/pyalpm.md Retrieves a specific package from the local database using its name and accesses its properties like packager, licenses, and version. ```python coreutils = localdb.get_pkg("coreutils") print(coreutils.packager) # 'John Doe ' print(coreutils.licenses) # ['GPL3'] print(coreutils.version) # '8.30-1' ``` -------------------------------- ### search(query: string) Source: https://github.com/archlinux/pyalpm/blob/master/doc/pyalpm/Database.md Searches the database for packages matching a given query. ```APIDOC ## search ### Description Search this database for a package with the name matching the query. ### Parameters #### Path Parameters - **query** (str) - Required - a regexp representing the package searched for. ### Returns a list of package objects matching the query by name ``` -------------------------------- ### pyalpm.alpmversion() Source: https://github.com/archlinux/pyalpm/blob/master/doc/pyalpm/Pyalpm.md Returns the ALPM library version string. ```APIDOC ## pyalpm.alpmversion() ### Description Returns the ALPM library version. ### Returns - the string containing the ALPM version ``` -------------------------------- ### Configure PGP Signature Verification Levels Source: https://context7.com/archlinux/pyalpm/llms.txt Use `pyalpm.SIG_DATABASE_*` constants with `handle.register_syncdb()` to control PGP signature verification policy for sync databases. These flags determine whether signatures are optional, required, or if marginal/unknown trust keys are accepted. ```python import pyalpm from pyalpm import Handle handle = Handle('/', '/var/lib/pacman') # SIG_DATABASE_OPTIONAL: signatures checked if present; missing sig is not an error db1 = handle.register_syncdb('core', pyalpm.SIG_DATABASE_OPTIONAL) # SIG_DATABASE: signatures required (exact constant value, generally same as REQUIRED) db2 = handle.register_syncdb('extra', pyalpm.SIG_DATABASE) # SIG_DATABASE_MARGINAL_OK: signatures required; marginal trust keys are accepted db3 = handle.register_syncdb('community', pyalpm.SIG_DATABASE_MARGINAL_OK) # SIG_DATABASE_UNKNOWN_OK: signatures required; unknown trust keys are accepted db4 = handle.register_syncdb('multilib', pyalpm.SIG_DATABASE_UNKNOWN_OK) # 0 = no signature verification at all (useful for local/testing repos) test_db = handle.register_syncdb('local-repo', 0) test_db.servers = ['file:///home/user/local-repo'] print(pyalpm.SIG_DATABASE_OPTIONAL) # integer constant print(pyalpm.SIG_DATABASE_MARGINAL_OK) # integer constant print(pyalpm.SIG_DATABASE_UNKNOWN_OK) # integer constant ``` ```python import pyalpm from pyalpm import Handle handle = Handle('/', '/var/lib/pacman') # SIG_DATABASE_OPTIONAL: signatures checked if present; missing sig is not an error db1 = handle.register_syncdb('core', pyalpm.SIG_DATABASE_OPTIONAL) ``` ```python import pyalpm from pyalpm import Handle handle = Handle('/', '/var/lib/pacman') # SIG_DATABASE: signatures required (exact constant value, generally same as REQUIRED) db2 = handle.register_syncdb('extra', pyalpm.SIG_DATABASE) ``` ```python import pyalpm from pyalpm import Handle handle = Handle('/', '/var/lib/pacman') # SIG_DATABASE_MARGINAL_OK: signatures required; marginal trust keys are accepted db3 = handle.register_syncdb('community', pyalpm.SIG_DATABASE_MARGINAL_OK) ``` ```python import pyalpm from pyalpm import Handle handle = Handle('/', '/var/lib/pacman') # SIG_DATABASE_UNKNOWN_OK: signatures required; unknown trust keys are accepted db4 = handle.register_syncdb('multilib', pyalpm.SIG_DATABASE_UNKNOWN_OK) ``` ```python import pyalpm from pyalpm import Handle handle = Handle('/', '/var/lib/pacman') # 0 = no signature verification at all (useful for local/testing repos) test_db = handle.register_syncdb('local-repo', 0) test_db.servers = ['file:///home/user/local-repo'] print(pyalpm.SIG_DATABASE_OPTIONAL) # integer constant print(pyalpm.SIG_DATABASE_MARGINAL_OK) # integer constant print(pyalpm.SIG_DATABASE_UNKNOWN_OK) # integer constant ```