spack.util package¶
Subpackages¶
- spack.util.unparse package
unparse()- Submodules
- spack.util.unparse.unparser module
NodeVisitorUnparserUnparser.binopUnparser.binop_precedenceUnparser.binop_rassocUnparser.block()Unparser.boolop_precedenceUnparser.boolopsUnparser.buffered()Unparser.cmpopsUnparser.delimit()Unparser.delimit_if()Unparser.do_visit_try()Unparser.fill()Unparser.get_precedence()Unparser.get_raw_docstring()Unparser.get_type_comment()Unparser.interleave()Unparser.items_view()Unparser.maybe_newline()Unparser.require_parens()Unparser.set_precedence()Unparser.traverse()Unparser.unopUnparser.unop_precedenceUnparser.visit()Unparser.visit_AnnAssign()Unparser.visit_Assert()Unparser.visit_Assign()Unparser.visit_AsyncFor()Unparser.visit_AsyncFunctionDef()Unparser.visit_AsyncWith()Unparser.visit_Attribute()Unparser.visit_AugAssign()Unparser.visit_Await()Unparser.visit_BinOp()Unparser.visit_BoolOp()Unparser.visit_Break()Unparser.visit_Call()Unparser.visit_ClassDef()Unparser.visit_Compare()Unparser.visit_Constant()Unparser.visit_Continue()Unparser.visit_Delete()Unparser.visit_Dict()Unparser.visit_DictComp()Unparser.visit_ExceptHandler()Unparser.visit_Expr()Unparser.visit_ExtSlice()Unparser.visit_For()Unparser.visit_FormattedValue()Unparser.visit_FunctionDef()Unparser.visit_FunctionType()Unparser.visit_GeneratorExp()Unparser.visit_Global()Unparser.visit_If()Unparser.visit_IfExp()Unparser.visit_Import()Unparser.visit_ImportFrom()Unparser.visit_Index()Unparser.visit_Interpolation()Unparser.visit_JoinedStr()Unparser.visit_Lambda()Unparser.visit_List()Unparser.visit_ListComp()Unparser.visit_Match()Unparser.visit_MatchAs()Unparser.visit_MatchClass()Unparser.visit_MatchMapping()Unparser.visit_MatchOr()Unparser.visit_MatchSequence()Unparser.visit_MatchSingleton()Unparser.visit_MatchStar()Unparser.visit_MatchValue()Unparser.visit_Module()Unparser.visit_Name()Unparser.visit_NamedExpr()Unparser.visit_Nonlocal()Unparser.visit_ParamSpec()Unparser.visit_Pass()Unparser.visit_Raise()Unparser.visit_Return()Unparser.visit_Set()Unparser.visit_SetComp()Unparser.visit_Slice()Unparser.visit_Starred()Unparser.visit_Subscript()Unparser.visit_TemplateStr()Unparser.visit_Try()Unparser.visit_TryStar()Unparser.visit_Tuple()Unparser.visit_TypeAlias()Unparser.visit_TypeVar()Unparser.visit_TypeVarTuple()Unparser.visit_UnaryOp()Unparser.visit_While()Unparser.visit_With()Unparser.visit_Yield()Unparser.visit_YieldFrom()Unparser.visit_alias()Unparser.visit_arg()Unparser.visit_arguments()Unparser.visit_comprehension()Unparser.visit_keyword()Unparser.visit_match_case()Unparser.visit_withitem()Unparser.write()
is_non_empty_non_star_tuple()iter_fields()nullcontext()
Submodules¶
spack.util.archive module¶
- class spack.util.archive.ChecksumWriter(fileobj, algorithm=hashlib.sha256)[source]¶
Bases:
BufferedIOBaseChecksum writer computes a checksum while writing to a file.
- close()[source]¶
Flush and close the IO object.
This method has no effect if the file is already closed.
- property closed¶
- fileno()[source]¶
Return underlying file descriptor if one exists.
Raise OSError if the IO object does not use a file descriptor.
- flush()[source]¶
Flush write buffers, if applicable.
This is not implemented for read-only and non-blocking streams.
- myfileobj¶
- read(size=-1)[source]¶
Read and return up to n bytes.
If the size argument is omitted, None, or negative, read and return all data until EOF.
If the size argument is positive, and the underlying raw stream is not ‘interactive’, multiple raw reads may be issued to satisfy the byte count (unless EOF is reached first). However, for interactive raw streams (as well as sockets and pipes), at most one raw read will be issued, and a short result does not imply that EOF is imminent.
Return an empty bytes object on EOF.
Return None if the underlying raw stream was open in non-blocking mode and no data is available at the moment.
- read1(size=-1)[source]¶
Read and return up to size bytes, with at most one read() call to the underlying raw stream.
Return an empty bytes object on EOF. A short result does not imply that EOF is imminent.
- readable()[source]¶
Return whether object was opened for reading.
If False, read() will raise OSError.
- readline(size=-1)[source]¶
Read and return a line from the stream.
If size is specified, at most size bytes will be read.
The line terminator is always b’n’ for binary files; for text files, the newlines argument to open can be used to select the line terminator(s) recognized.
- seek(offset, whence=io.SEEK_SET)[source]¶
Change the stream position to the given byte offset.
- offset
The stream position, relative to ‘whence’.
- whence
The relative position to seek from.
The offset is interpreted relative to the position indicated by whence. Values for whence are:
os.SEEK_SET or 0 – start of stream (the default); offset should be zero or positive
os.SEEK_CUR or 1 – current stream position; offset may be negative
os.SEEK_END or 2 – end of stream; offset is usually negative
Return the new absolute position.
- seekable()[source]¶
Return whether object supports random access.
If False, seek(), tell() and truncate() will raise OSError. This method may need to do a test seek().
- spack.util.archive.default_path_to_name(path: str) str[source]¶
Converts a path to a tarfile name, which uses posix path separators.
- spack.util.archive.gzip_compressed_tarfile(path: str) Generator[Tuple[TarFile, ChecksumWriter, ChecksumWriter], None, None][source]¶
Create a reproducible, gzip compressed tarfile, and keep track of shasums of both the compressed and uncompressed tarfile. Reproducibility is achieved by normalizing the gzip header (no file name and zero mtime).
- Yields:
A tuple of three elements
tarfile.TarFile: tarfile objectChecksumWriter: checksum of the gzip compressed tarfileChecksumWriter: checksum of the uncompressed tarfile
- spack.util.archive.reproducible_tarfile_from_prefix(tar: TarFile, prefix: str, *, include_parent_directories: bool = False, skip: Callable[[DirEntry], bool] = lambda entry: ..., path_to_name: Callable[[str], str] = default_path_to_name, add_file: Callable[[TarFile, TarInfo, str], None] = default_add_file, add_symlink: Callable[[TarFile, TarInfo, str], None] = default_add_link, add_hardlink: Callable[[TarFile, TarInfo, str], None] = default_add_link) None[source]¶
Create a tarball from a given directory. Only adds regular files, symlinks and dirs. Skips devices, fifos. Preserves hardlinks. Normalizes permissions like git. Tar entries are added in depth-first pre-order, with dir entries partitioned by file | dir, and sorted lexicographically, for reproducibility. Partitioning ensures only one dir is in memory at a time, and sorting improves compression.
- Parameters:
tar – tarfile object opened in write mode
prefix – path to directory to tar (either absolute or relative)
include_parent_directories – whether to include every directory leading up to
prefixin the tarballskip – function that receives a DirEntry and returns True if the entry should be skipped, whether it is a file or directory. Default implementation does not skip anything.
path_to_name – function that converts a path string to a tarfile entry name, which should be in posix format. Not only is it necessary to transform paths in certain cases, such as windows path to posix format, but it can also be used to prepend a directory to each entry even if it does not exist on the filesystem. The default implementation drops the leading slash on posix and the drive letter on windows for absolute paths, and formats as a posix.
- spack.util.archive.retrieve_commit_from_archive(archive_path, ref)[source]¶
Extract git data from an archive with out expanding it
Open the archive and searches for .git/HEAD. Return if HEAD is a commit (detached head or tag) Otherwise attempt to read the ref that .git/HEAD is pointing to and return the commit associated with it.
spack.util.compression module¶
- class spack.util.compression.BZipFileType[source]¶
Bases:
CompressedFileTypeInterface
- class spack.util.compression.CompressedFileTypeInterface[source]¶
Bases:
FileTypeInterfaceInterface class for FileTypes that include compression information
- class spack.util.compression.FileTypeInterface[source]¶
Bases:
objectBase interface class for describing and querying file type information. FileType describes information about a single file type such as typical extension and byte header properties, and provides an interface to check a given file against said type based on magic number.
This class should be subclassed each time a new type is to be described.
Subclasses should each describe a different type of file. In order to do so, they must define the extension string, magic number, and header offset (if non zero). If a class has multiple magic numbers, it will need to override the method describing that file type’s magic numbers and the method that checks a types magic numbers against a given file’s.
- OFFSET¶
- classmethod header_size() int[source]¶
Return size of largest magic number associated with file type
- classmethod magic_numbers() List[bytes][source]¶
Return a list of all potential magic numbers for a filetype
- class spack.util.compression.GZipFileType[source]¶
Bases:
CompressedFileTypeInterface
- class spack.util.compression.LzmaFileType[source]¶
Bases:
CompressedFileTypeInterface
- spack.util.compression.MAX_BYTES_ARCHIVE_HEADER¶
Maximum number of bytes to read from a file to determine any archive type. Tar is the largest.
- spack.util.compression.SUPPORTED_FILETYPES: List[FileTypeInterface]¶
Collection of supported archive and compression file type identifier classes.
- class spack.util.compression.TarFileType[source]¶
Bases:
FileTypeInterface- OFFSET¶
- class spack.util.compression.ZCompressedFileType[source]¶
Bases:
CompressedFileTypeInterface
- class spack.util.compression.ZipFleType[source]¶
Bases:
FileTypeInterface
- spack.util.compression.decompressor_for(path: str, extension: str | None = None)[source]¶
Returns appropriate decompression/extraction algorithm function pointer for provided extension. If extension is none, it is computed from the
pathand the decompression function is derived from that information.
- spack.util.compression.decompressor_for_nix(extension: str) Callable[[str], Any][source]¶
Returns a function pointer to appropriate decompression algorithm based on extension type and unix specific considerations i.e. a reasonable expectation system utils like gzip, bzip2, and xz are available
- Parameters:
extension – path of the archive file requiring decompression
- spack.util.compression.decompressor_for_win(extension: str) Callable[[str], Any][source]¶
Returns a function pointer to appropriate decompression algorithm based on extension type and Windows specific considerations
Windows natively vendors only tar, no other archive/compression utilities So we must rely exclusively on Python module support for all compression operations, tar for tarballs and zip files, and 7zip for Z compressed archives and files as Python does not provide support for the UNIX compress algorithm
- spack.util.compression.extension_from_magic_numbers(path: str, decompress: bool = False) str | None[source]¶
Return typical extension without leading
.of a compressed file or archive at the given path, based on its magic numbers, similar to thefileutility. Notice that the extension returned from this function may not coincide with the file’s given extension.- Parameters:
path – file to determine extension of
decompress – If True, method will peek into decompressed file to check for archive file types. If False, the method will return only the top-level extension (for example
gzand nottar.gz).
- Returns:
Spack recognized archive file extension as determined by file’s magic number and file name. If file is not on system or is of a type not recognized by Spack as an archive or compression type, None is returned. If the file is classified as a compressed tarball, the extension is abbreviated (for instance
tgznottar.gz) if that matches the file’s given extension.
- spack.util.compression.extension_from_magic_numbers_by_stream(stream: BinaryIO, decompress: bool = False) str | None[source]¶
Returns the typical extension for the opened file, without leading
., based on its magic numbers.If the stream does not represent file type recognized by Spack (see
SUPPORTED_FILETYPES), the method will return None- Parameters:
stream – stream representing a file on system
decompress – if True, compressed files are checked for archive types beneath compression. For example tar.gz if True versus only gz if False.
spack.util.cpus module¶
- spack.util.cpus.cpus_available()[source]¶
Returns the number of CPUs available for the current process, or the number of physical CPUs when that information cannot be retrieved. The number of available CPUs might differ from the number of physical CPUs when using spack through Slurm or container runtimes.
spack.util.crypto module¶
- class spack.util.crypto.Checker(hexdigest: str, **kwargs)[source]¶
Bases:
objectA checker checks files against one particular hex digest. It will automatically determine what hashing algorithm to used based on the length of the digest it’s initialized with. e.g., if the digest is 32 hex characters long this will use md5.
Example: know your tarball should hash to
abc123. You want to check files against this. You would use this class like so:hexdigest = 'abc123' checker = Checker(hexdigest) success = checker.check('downloaded.tar.gz')
After the call to check, the actual checksum is available in checker.sum, in case it’s needed for error output.
You can trade read performance and memory usage by adjusting the block_size optional arg. By default it’s a 1MB (2**20 bytes) buffer.
- class spack.util.crypto.DeprecatedHash(hash_alg, alert_fn, disable_security_check)[source]¶
Bases:
object
- spack.util.crypto.bit_length(num)[source]¶
Number of bits required to represent an integer in binary.
- spack.util.crypto.checksum(hashlib_algo: Callable[[], hashlib._Hash], filename: str, *, block_size: int = 2**20) str[source]¶
Returns a hex digest of the filename generated using an algorithm from hashlib.
- spack.util.crypto.checksum_stream(hashlib_algo: Callable[[], hashlib._Hash], fp: BinaryIO, *, block_size: int = 2**20) str[source]¶
Returns a hex digest of the stream generated using given algorithm from hashlib.
- spack.util.crypto.hash_algo_for_digest(hexdigest: str) str[source]¶
Gets name of the hash algorithm for a hex digest.
- spack.util.crypto.hash_fun_for_algo(algo: str) Callable[[], hashlib._Hash][source]¶
Get a function that can perform the specified hash algorithm.
- spack.util.crypto.hash_fun_for_digest(hexdigest: str) Callable[[], hashlib._Hash][source]¶
Gets a hash function corresponding to a hex digest.
- spack.util.crypto.hashes¶
Set of hash algorithms that Spack can use, mapped to digest size in bytes
spack.util.ctest_log_parser module¶
Functions to parse build logs and extract error messages.
This is a python port of the regular expressions CTest uses to parse log files here:
https://github.com/Kitware/CMake/blob/master/Source/CTest/cmCTestBuildHandler.cxx
This file takes the regexes verbatim from there and adds some parsing
algorithms that duplicate the way CTest scrapes log files. To keep this
up to date with CTest, just make sure the *_matches and
*_exceptions lists are kept up to date with CTest’s build handler.
- class spack.util.ctest_log_parser.BuildError(text: str, line_no: int, source_file: str | None = None, source_line_no: str | None = None, pre_context: List[str] | None = None, post_context: List[str] | None = None)[source]¶
Bases:
LogEventLogEvent subclass for build errors.
- color¶
color name when rendering in the terminal
- class spack.util.ctest_log_parser.BuildWarning(text: str, line_no: int, source_file: str | None = None, source_line_no: str | None = None, pre_context: List[str] | None = None, post_context: List[str] | None = None)[source]¶
Bases:
LogEventLogEvent subclass for build warnings.
- color¶
color name when rendering in the terminal
- class spack.util.ctest_log_parser.CTestLogParser(profile: bool = False)[source]¶
Bases:
objectLog file parser that extracts errors and warnings.
- parse(stream: str | TextIO | List[str], context: int = 6, tail: int = 0) Tuple[List[BuildError], List[BuildWarning], LogEvent | None][source]¶
Parse a log file by searching each line for errors and warnings.
- Parameters:
stream – filename or stream to read from
context – lines of context to extract around each log event
tail – if > 0, also return a
LogEventwith the lasttaillines
- Returns:
two lists containing
BuildErrorandBuildWarningobjects, plus an optionalLogEventfor the tail (None whentail=0).
- class spack.util.ctest_log_parser.LogEvent(text: str, line_no: int, source_file: str | None = None, source_line_no: str | None = None, pre_context: List[str] | None = None, post_context: List[str] | None = None)[source]¶
Bases:
objectClass representing interesting events (e.g., errors) in a build log.
- color¶
color name when rendering in the terminal
spack.util.editor module¶
Module for finding the user’s preferred text editor.
Defines one function, editor(), which invokes the editor defined by the user’s VISUAL environment variable if set. We fall back to the editor defined by the EDITOR environment variable if VISUAL is not set or the specified editor fails (e.g. no DISPLAY for a graphical editor). If neither variable is set, we fall back to one of several common editors, raising an OSError if we are unable to find one.
- spack.util.editor.editor(*args: str, exec_fn: Callable[[str, List[str]], int] = os.execv) bool[source]¶
Invoke the user’s editor.
This will try to execute the following, in order:
$VISUAL <args>: the “visual” editor (per POSIX)$EDITOR <args>: the regular editor (per POSIX)some default editor (see
_default_editors) with <args>
If an environment variable isn’t defined, it is skipped. If it points to something that can’t be executed, we’ll print a warning. And if we can’t find anything that can be executed after searching the full list above, we’ll raise an error.
- Parameters:
args – args to pass to editor
exec_fn – invoke this function to run; use
spack.util.editor.executableif you want something that returns, instead of the defaultos.execv().
spack.util.elf module¶
- class spack.util.elf.ELF_CONSTANTS[source]¶
Bases:
object- CLASS32¶
- CLASS64¶
- DATA2LSB¶
- DATA2MSB¶
- DT_NEEDED¶
- DT_NULL¶
- DT_RPATH¶
- DT_RUNPATH¶
- DT_SONAME¶
- DT_STRTAB¶
- ET_DYN¶
- ET_EXEC¶
- MAGIC¶
- PT_DYNAMIC¶
- PT_INTERP¶
- PT_LOAD¶
- SHT_STRTAB¶
- exception spack.util.elf.ElfCStringUpdatesFailed(rpath: UpdateCStringAction | None, pt_interp: UpdateCStringAction | None)[source]¶
Bases:
Exception
- class spack.util.elf.ElfHeader(e_type, e_machine, e_version, e_entry, e_phoff, e_shoff, e_flags, e_ehsize, e_phentsize, e_phnum, e_shentsize, e_shnum, e_shstrndx)[source]¶
Bases:
NamedTuple
- class spack.util.elf.ProgramHeader32(p_type, p_offset, p_vaddr, p_paddr, p_filesz, p_memsz, p_flags, p_align)[source]¶
Bases:
NamedTuple
- class spack.util.elf.ProgramHeader64(p_type, p_flags, p_offset, p_vaddr, p_paddr, p_filesz, p_memsz, p_align)[source]¶
Bases:
NamedTuple
- class spack.util.elf.SectionHeader(sh_name, sh_type, sh_flags, sh_addr, sh_offset, sh_size, sh_link, sh_info, sh_addralign, sh_entsize)[source]¶
Bases:
NamedTuple
- class spack.util.elf.UpdateCStringAction(old_value: bytes, new_value: bytes, offset: int)[source]¶
Bases:
object
- spack.util.elf.delete_needed_from_elf(f: BinaryIO, elf: ElfFile, needed: bytes) None[source]¶
Delete a needed library from the dynamic section of an ELF file
- spack.util.elf.delete_rpath(path: str) None[source]¶
Modifies a binary to remove the rpath. It zeros out the rpath string and also drops the
DT_RPATH/DT_RUNPATHentry from the dynamic section, so it doesn’t show up inreadelf -d file, nor instrings file.
- spack.util.elf.find_strtab_size_at_offset(f: BinaryIO, elf: ElfFile, offset: int) int[source]¶
Retrieve the size of a string table section at a particular known offset
- Parameters:
f – file handle
elf – ELF file parser data
offset – offset of the section in the file (i.e.
sh_offset)
- Returns:
the size of the string table in bytes
- Return type:
- spack.util.elf.get_elf_compat(path: str) Tuple[bool, bool, int][source]¶
Get a triplet (is_64_bit, is_little_endian, e_machine) from an ELF file, which can be used to see if two ELF files are compatible.
- spack.util.elf.get_interpreter(path: str) str | None[source]¶
Returns the interpreter of the given file as UTF-8 string, or None if not set.
- spack.util.elf.get_rpaths(path: str) List[str] | None[source]¶
Returns list of rpaths of the given file as UTF-8 strings, or None if not set.
- spack.util.elf.parse_c_string(byte_string: bytes, start: int = 0) bytes[source]¶
Retrieve a C-string at a given offset in a byte string
- Parameters:
byte_string – String
start – Offset into the string
- Returns:
A copy of the C-string excluding the terminating null byte
- Return type:
- spack.util.elf.parse_elf(f: BinaryIO, interpreter: bool = False, dynamic_section: bool = False, only_header: bool = False) ElfFile[source]¶
Given a file handle
ffor an ELF file opened in binary mode, return anElfFileobject with the parsed contents.
- spack.util.elf.parse_program_headers(f: BinaryIO, elf: ElfFile) None[source]¶
Parse program headers
- Parameters:
f – file handle
elf – ELF file parser data
- spack.util.elf.parse_pt_dynamic(f: BinaryIO, elf: ElfFile) None[source]¶
Parse the dynamic section of an ELF file
- Parameters:
f – file handle
elf – ELF file parse data
- spack.util.elf.parse_pt_interp(f: BinaryIO, elf: ElfFile) None[source]¶
Parse the interpreter (i.e. absolute path to the dynamic linker)
- Parameters:
f – file handle
elf – ELF file parser data
- spack.util.elf.pt_interp(path: str) str | None[source]¶
Retrieve the interpreter of an executable at
path.
- spack.util.elf.read_exactly(f: BinaryIO, num_bytes: int, msg: str) bytes[source]¶
Read exactly num_bytes at the current offset, otherwise raise a parsing error with the given error message.
- Parameters:
f – file handle
num_bytes – Number of bytes to read
msg – Error to show when bytes cannot be read
- Returns:
the
num_bytesbytes that were read.- Return type:
- spack.util.elf.retrieve_strtab(f: BinaryIO, elf: ElfFile, offset: int) bytes[source]¶
Read a full string table at the given offset, which requires looking it up in the section headers.
- Parameters:
elf – ELF file parser data
vaddr – virtual address
Returns: file offset
- spack.util.elf.substitute_rpath_and_pt_interp_in_place_or_raise(path: str, substitutions: Dict[bytes, bytes]) bool[source]¶
Returns true if the rpath and interpreter were modified, false if there was nothing to do. Raises ElfCStringUpdatesFailed if the ELF file cannot be updated in-place. This exception contains a list of actions to perform with other tools. The file is left untouched in this case.
spack.util.environment module¶
Set, unset or modify environment variables.
- class spack.util.environment.AppendFlagsEnv(name: str, value: str, *, separator: str = os.pathsep, trace: Trace | None = None)[source]¶
Bases:
NameValueModifier- execute(env: MutableMapping[str, str])[source]¶
Apply the modification to the mapping passed as input
- name¶
- separator¶
- trace¶
- value¶
- class spack.util.environment.AppendPath(name: str, value: str | PurePath, *, separator: str = os.pathsep, trace: Trace | None = None)[source]¶
Bases:
NamePathModifier- execute(env: MutableMapping[str, str])[source]¶
Apply the modification to the mapping passed as input
- class spack.util.environment.DeprioritizeSystemPaths(name: str, *, separator: str = os.pathsep, trace: Trace | None = None)[source]¶
Bases:
NameModifier- execute(env: MutableMapping[str, str])[source]¶
Apply the modification to the mapping passed as input
- name¶
- separator¶
- trace¶
- class spack.util.environment.EnvironmentModifications(other: EnvironmentModifications | None = None, traced: None | bool = None)[source]¶
Bases:
objectTracks and applies a sequence of environment variable modifications.
This class provides a high-level interface for building up a list of environment changes, such as setting, unsetting, appending, prepending, or removing values from environment variables. Modifications are stored and can be applied to a given environment dictionary, or rendered as shell code.
Package authors typically receive an instance of this class and call
set(),unset(),prepend_path(),remove_path(), etc., to queue up modifications. Spack runsapply_modifications()to apply these modifications to the environment when needed.Modifications can be grouped by variable name, reversed (where possible), validated for suspicious patterns, and extended from other instances. The class also supports tracing the origin of modifications for debugging.
Example
env = EnvironmentModifications() env.set("FOO", "bar") env.prepend_path("PATH", "/custom/bin") env.apply_modifications() # applies changes to os.environ
- append_flags(name: str, value: str, sep: str = ' ') None[source]¶
Stores a request to append flags to an environment variable.
- Parameters:
name – name of the environment variable
value – flags to be appended
sep – separator for the flags (default:
" ")
- append_path(name: str, path: str | PurePath, separator: str = os.pathsep) None[source]¶
Stores a request to append a path to list of paths.
- Parameters:
name – name of the environment variable
path – path to be appended
separator – separator for the paths (default:
os.pathsep)
- apply_modifications(env: MutableMapping[str, str] | None = None)[source]¶
Applies the modifications to the environment.
- Parameters:
env – environment to be modified. If None,
os.environwill be used.
- deprioritize_system_paths(name: str, separator: str = os.pathsep) None[source]¶
Stores a request to deprioritize system paths in a path list, otherwise preserving the order.
- Parameters:
name – name of the environment variable
separator – separator for the paths (default:
os.pathsep)
- env_modifications: List[NameModifier | NameValueModifier]¶
- extend(other: EnvironmentModifications)[source]¶
Extends the current instance with modifications from another instance.
- static from_environment_diff(before: MutableMapping[str, str], after: MutableMapping[str, str], clean: bool = False) EnvironmentModifications[source]¶
Constructs the environment modifications from the diff of two environments.
- Parameters:
before – environment before the modifications are applied
after – environment after the modifications are applied
clean – in addition to removing empty entries, also remove duplicate entries
- static from_sourcing_file(filename: str, *arguments: str, **kwargs: Any) EnvironmentModifications[source]¶
Returns the environment modifications that have the same effect as sourcing the input file in a shell.
- Parameters:
filename – the file to be sourced
*arguments – arguments to pass on the command line
- Keyword Arguments:
shell (str) – the shell to use (default:
bash)shell_options (str) – options passed to the shell (default:
-c)source_command (str) – the command to run (default:
source)suppress_output (str) – redirect used to suppress output of command (default:
&> /dev/null)concatenate_on_success (str) – operator used to execute a command only when the previous command succeeds (default:
&&)exclude ([str or re.Pattern[str]]) – ignore any modifications of these variables (default: [])
include ([str or re.Pattern[str]]) – always respect modifications of these variables (default: []). Supersedes any excluded variables.
clean (bool) – in addition to removing empty entries, also remove duplicate entries (default: False).
- group_by_name() Dict[str, List[NameModifier | NameValueModifier]][source]¶
Returns a dict of the current modifications keyed by variable name.
- is_unset(variable_name: str) bool[source]¶
Returns
Trueif the last modification to a variable is to unset it,Falseotherwise.
- prepend_path(name: str, path: str | PurePath, separator: str = os.pathsep) None[source]¶
Stores a request to prepend a path to list of paths.
- Parameters:
name – name of the environment variable
path – path to be prepended
separator – separator for the paths (default:
os.pathsep)
- prune_duplicate_paths(name: str, separator: str = os.pathsep) None[source]¶
Stores a request to remove duplicates from a path list, otherwise preserving the order.
- Parameters:
name – name of the environment variable
separator – separator for the paths (default:
os.pathsep)
- remove_first_path(name: str, path: str | PurePath, separator: str = os.pathsep) None[source]¶
Stores a request to remove first instance of path from a list of paths.
- Parameters:
name – name of the environment variable
path – path to be removed
separator – separator for the paths (default:
os.pathsep)
- remove_flags(name: str, value: str, sep: str = ' ') None[source]¶
Stores a request to remove flags from an environment variable
- Parameters:
name – name of the environment variable
value – flags to be removed
sep – separator for the flags (default:
" ")
- remove_last_path(name: str, path: str | PurePath, separator: str = os.pathsep) None[source]¶
Stores a request to remove last instance of path from a list of paths.
- Parameters:
name – name of the environment variable
path – path to be removed
separator – separator for the paths (default:
os.pathsep)
- remove_path(name: str, path: str | PurePath, separator: str = os.pathsep) None[source]¶
Stores a request to remove a path from a list of paths.
- Parameters:
name – name of the environment variable
path – path to be removed
separator – separator for the paths (default:
os.pathsep)
- reversed() EnvironmentModifications[source]¶
Returns the EnvironmentModifications object that will reverse self
Only creates reversals for additions to the environment, as reversing
unset()andremove_path()modifications is impossible.Reversible operations are
set(),prepend_path(),append_path(),set_path(), andappend_flags().
- set(name: str, value: str, *, force: bool = False, raw: bool = False) None[source]¶
Stores a request to set an environment variable.
- Parameters:
name – name of the environment variable
value – value of the environment variable
force – if True, audit will not consider this modification a warning
raw – if True, format of value string is skipped
- set_path(name: str, elements: List[str] | List[PurePath] | List[str | PurePath], separator: str = os.pathsep) None[source]¶
Stores a request to set an environment variable to a list of paths, separated by a character defined in input.
- Parameters:
name – name of the environment variable
elements – ordered list paths
separator – separator for the paths (default:
os.pathsep)
- class spack.util.environment.NameModifier(name: str, *, separator: str = os.pathsep, trace: Trace | None = None)[source]¶
Bases:
objectBase class for modifiers that act on the environment variable as a whole, and thus store just its name
- execute(env: MutableMapping[str, str])[source]¶
Apply the modification to the mapping passed as input
- name¶
- separator¶
- trace¶
- class spack.util.environment.NamePathModifier(name: str, value: str | PurePath, *, separator: str = os.pathsep, trace: Trace | None = None)[source]¶
Bases:
NameValueModifierBase class for modifiers that modify the value of an environment variable that is a path.
- class spack.util.environment.NameValueModifier(name: str, value: str, *, separator: str = os.pathsep, trace: Trace | None = None)[source]¶
Bases:
objectBase class for modifiers that modify the value of an environment variable.
- execute(env: MutableMapping[str, str])[source]¶
Apply the modification to the mapping passed as input
- name¶
- separator¶
- trace¶
- value¶
- class spack.util.environment.PrependPath(name: str, value: str | PurePath, *, separator: str = os.pathsep, trace: Trace | None = None)[source]¶
Bases:
NamePathModifier- execute(env: MutableMapping[str, str])[source]¶
Apply the modification to the mapping passed as input
- class spack.util.environment.PruneDuplicatePaths(name: str, *, separator: str = os.pathsep, trace: Trace | None = None)[source]¶
Bases:
NameModifier- execute(env: MutableMapping[str, str])[source]¶
Apply the modification to the mapping passed as input
- name¶
- separator¶
- trace¶
- class spack.util.environment.RemoveFirstPath(name: str, value: str | PurePath, *, separator: str = os.pathsep, trace: Trace | None = None)[source]¶
Bases:
NamePathModifier- execute(env: MutableMapping[str, str])[source]¶
Apply the modification to the mapping passed as input
- class spack.util.environment.RemoveFlagsEnv(name: str, value: str, *, separator: str = os.pathsep, trace: Trace | None = None)[source]¶
Bases:
NameValueModifier- execute(env: MutableMapping[str, str])[source]¶
Apply the modification to the mapping passed as input
- name¶
- separator¶
- trace¶
- value¶
- class spack.util.environment.RemoveLastPath(name: str, value: str | PurePath, *, separator: str = os.pathsep, trace: Trace | None = None)[source]¶
Bases:
NamePathModifier- execute(env: MutableMapping[str, str])[source]¶
Apply the modification to the mapping passed as input
- class spack.util.environment.RemovePath(name: str, value: str | PurePath, *, separator: str = os.pathsep, trace: Trace | None = None)[source]¶
Bases:
NamePathModifier- execute(env: MutableMapping[str, str])[source]¶
Apply the modification to the mapping passed as input
- spack.util.environment.SYSTEM_DIR_CASE_ENTRY¶
used in the compiler wrapper’s
/usr/lib|/usr/lib64|...)case entry
- class spack.util.environment.SetEnv(name: str, value: str, *, trace: Trace | None = None, force: bool = False, raw: bool = False)[source]¶
Bases:
NameValueModifier- execute(env: MutableMapping[str, str])[source]¶
Apply the modification to the mapping passed as input
- force¶
- raw¶
- class spack.util.environment.SetPath(name: str, value: List[str] | List[PurePath] | List[str | PurePath], *, separator: str = os.pathsep, trace: Trace | None = None)[source]¶
Bases:
NameValueModifier- execute(env: MutableMapping[str, str])[source]¶
Apply the modification to the mapping passed as input
- name¶
- separator¶
- trace¶
- value¶
- class spack.util.environment.Trace(*, filename: str, lineno: int, context: str)[source]¶
Bases:
objectTrace information on a function call
- context¶
- filename¶
- lineno¶
- class spack.util.environment.UnsetEnv(name: str, *, separator: str = os.pathsep, trace: Trace | None = None)[source]¶
Bases:
NameModifier- execute(env: MutableMapping[str, str])[source]¶
Apply the modification to the mapping passed as input
- name¶
- separator¶
- trace¶
- spack.util.environment.deprioritize_system_paths(paths: List[str]) List[str][source]¶
Reorders input paths by putting system paths at the end of the list, otherwise preserving order.
- spack.util.environment.dump_environment(path: str, environment: MutableMapping[str, str] | None = None)[source]¶
Dump an environment dictionary to a source-able file.
- Parameters:
path – path of the file to write
environment – environment to be written. If None os.environ is used.
- spack.util.environment.env_flag(name: str) bool[source]¶
Given the name of an environment variable, returns True if the lowercase value is set to
trueor to1, False otherwise.
- spack.util.environment.environment_after_sourcing_files(*files: str | Tuple[str, ...], **kwargs) Dict[str, str][source]¶
Returns a dictionary with the environment that one would have after sourcing the files passed as argument.
- Parameters:
*files – each item can either be a string containing the path of the file to be sourced or a sequence, where the first element is the file to be sourced and the remaining are arguments to be passed to the command line
- Keyword Arguments:
env (dict) – the initial environment (default: current environment)
shell (str) – the shell to use (default:
/bin/bashorcmd.exe(Windows))shell_options (str) – options passed to the shell (default:
-cor/C(Windows))source_command (str) – the command to run (default:
source)suppress_output (str) – redirect used to suppress output of command (default:
&> /dev/null)concatenate_on_success (str) – operator used to execute a command only when the previous command succeeds (default:
&&)
- spack.util.environment.filter_system_paths(paths: Iterable[str]) List[str][source]¶
Returns a copy of the input where system paths are filtered out.
- spack.util.environment.get_path(name: str) List[str][source]¶
Given the name of an environment variable containing multiple paths separated by
os.pathsep, returns a list of the paths.
- spack.util.environment.inspect_path(root: str, inspections: MutableMapping[str, List[str]], exclude: Callable[[str], bool] | None = None) EnvironmentModifications[source]¶
Inspects
rootto search for the subdirectories ininspections. Adds every path found to a list of prepend-path commands and returns it.- Parameters:
root – absolute path where to search for subdirectories
inspections – maps relative paths to a list of environment variables that will be modified if the path exists. The modifications are not performed immediately, but stored in a command object that is returned to client
exclude – optional callable. If present it must accept an absolute path and return True if it should be excluded from the inspection
Examples:
The following lines execute an inspection in
/usrto search for/usr/includeand/usr/lib64. If found we want to prepend/usr/includetoCPATHand/usr/lib64toMY_LIB64_PATH.# Set up the dictionary containing the inspection inspections = { "include": ["CPATH"], "lib64": ["MY_LIB64_PATH"] } # Get back the list of command needed to modify the environment env = inspect_path("/usr", inspections) # Eventually execute the commands env.apply_modifications()
- spack.util.environment.is_system_path(path: str) bool[source]¶
Returns True if the argument is a system path, False otherwise.
- spack.util.environment.path_put_first(var_name: str, directories: List[str])[source]¶
Puts the provided directories first in the path, adding them if they’re not already there.
- spack.util.environment.path_set(var_name: str, directories: List[str])[source]¶
Sets the variable passed as input to the
os.pathsepjoined list of directories.
- spack.util.environment.pickle_environment(path: str, environment: Dict[str, str] | None = None)[source]¶
Pickle an environment dictionary to a file.
- spack.util.environment.preserve_environment(*variables: str)[source]¶
Ensures that the value of the environment variables passed as arguments is the same before entering to the context manager and after exiting it.
Variables that are unset before entering the context manager will be explicitly unset on exit.
- Parameters:
variables – list of environment variables to be preserved
- spack.util.environment.prune_duplicate_paths(paths: List[str]) List[str][source]¶
Returns the input list with duplicates removed, otherwise preserving order.
- spack.util.environment.sanitize(environment: MutableMapping[str, str], exclude: List[str], include: List[str]) Dict[str, str][source]¶
Returns a copy of the input dictionary where all the keys that match an excluded pattern and don’t match an included pattern are removed.
- spack.util.environment.set_env(**kwargs)[source]¶
Temporarily sets and restores environment variables. Variables can be set as keyword arguments to this function.
Note
If the goal is to set environment variables for a subprocess, it is strongly recommended to use the
extra_envargument ofspack.util.executable.Executable.__call__()instead of this function.This function is intended to modify the current process’s environment (which is an unsafe operation in general).
- spack.util.environment.validate(env: EnvironmentModifications, errstream: Callable[[str], None])[source]¶
Validates the environment modifications to check for the presence of suspicious patterns. Prompts a warning for everything that was found.
Current checks: - set or unset variables after other changes on the same variable
- Parameters:
env – list of environment modifications
errstream – callable to log error messages
spack.util.executable module¶
- class spack.util.executable.Executable(name: str | Path)[source]¶
Bases:
objectRepresent an executable file that can be run as a subprocess.
This class provides a simple interface for running executables with custom arguments and environment variables. It supports setting default arguments and environment modifications, copying instances, and running commands with various options for input/output/error handling.
Example usage:
ls = Executable("ls") ls.add_default_arg("-l") ls.add_default_env("LC_ALL", "C") output = ls("-a", output=str) # Run 'ls -l -a' and capture output as string
- __call__(*args: str, fail_on_error: bool = True, ignore_errors: int | Sequence[int] = (), ignore_quotes: bool | None = None, timeout: int | None = None, env: Dict[str, str] | EnvironmentModifications | None = None, extra_env: Dict[str, str] | EnvironmentModifications | None = None, input: BinaryIO | None = None, output: BinaryIO | None | str = None, error: BinaryIO | None | str = None, _dump_env: Dict[str, str] | None = None) None[source]¶
- __call__(*args: str, fail_on_error: bool = True, ignore_errors: int | Sequence[int] = (), ignore_quotes: bool | None = None, timeout: int | None = None, env: Dict[str, str] | EnvironmentModifications | None = None, extra_env: Dict[str, str] | EnvironmentModifications | None = None, input: BinaryIO | None = None, output: Type[str] | Callable, error: BinaryIO | None | str | Type[str] | Callable = None, _dump_env: Dict[str, str] | None = None) str
- __call__(*args: str, fail_on_error: bool = True, ignore_errors: int | Sequence[int] = (), ignore_quotes: bool | None = None, timeout: int | None = None, env: Dict[str, str] | EnvironmentModifications | None = None, extra_env: Dict[str, str] | EnvironmentModifications | None = None, input: BinaryIO | None = None, output: BinaryIO | None | str | Type[str] | Callable = None, error: Type[str] | Callable, _dump_env: Dict[str, str] | None = None) str
Runs this executable in a subprocess.
- Parameters:
*args – command-line arguments to the executable to run
fail_on_error – if True, raises an exception if the subprocess returns an error The return code is available as
returncodeignore_errors – a sequence of error codes to ignore. If these codes are returned, this process will not raise an exception, even if
fail_on_erroris set toTrueignore_quotes – if False, warn users that quotes are not needed, as Spack does not use a shell. If None, use
ignore_quotes.timeout – the number of seconds to wait before killing the child process
env – the environment with which to run the executable
extra_env – extra items to add to the environment (neither requires nor precludes env)
input – where to read stdin from
output – where to send stdout
error – where to send stderr
_dump_env – dict to be set to the environment actually used (envisaged for testing purposes only)
Accepted values for
input,output, anderror:Python streams: open Python file objects or
os.devnullstr: the Python string type. If you set these tostr, output and error will be written to pipes and returned as a string. If bothoutputanderrorare set tostr, then one string is returned containing output concatenated with error. Not valid forinput.str.split: the split method of the Python string type. Behaves the same asstr, except that value is also written tostdoutorstderr.
For
outputanderrorit’s also accepted to pass a string with a filename, which will be automatically opened for writing.By default, the subprocess inherits the parent’s file descriptors.
- add_default_env(key: str, value: str) None[source]¶
Set an environment variable when the command is run.
- Parameters:
key – The environment variable to set
value – The value to set it to
- add_default_envmod(envmod: EnvironmentModifications) None[source]¶
Set an
spack.util.environment.EnvironmentModificationsto use when the command is run.
- copy() Executable[source]¶
Return a copy of this Executable.
- ignore_quotes: bool¶
Whether to warn users that quotes are not needed, as Spack does not use a shell.
- with_default_args(*args: str) Executable[source]¶
Same as add_default_arg, but returns a copy of the executable.
- exception spack.util.executable.ProcessError(message: str, long_message: str | None = None)[source]¶
Bases:
SpackErrorRaised when
Executableexits with an error code.
- spack.util.executable.which(*args: str, path: str | List[str] | None = None, required: Literal[True]) Executable[source]¶
- spack.util.executable.which(*args: str, path: str | List[str] | None = None, required: bool = False) Executable | None
Finds an executable in the path like command-line which.
If given multiple executables, returns the first one that is found. If no executables are found, returns None.
- spack.util.executable.which_string(*args: str, path: str | List[str] | None = None, required: Literal[True]) str[source]¶
- spack.util.executable.which_string(*args: str, path: str | List[str] | None = None, required: bool = False) str | None
Like
which(), but returns a string instead of anExecutable.
spack.util.file_cache module¶
- exception spack.util.file_cache.CacheError(message: str, long_message: str | None = None)[source]¶
Bases:
SpackError
- class spack.util.file_cache.FileCache(root: str | Path, timeout=120)[source]¶
Bases:
objectThis class manages cached data in the filesystem.
Cache files are fetched and stored by unique keys. Keys can be relative paths, so that there can be some hierarchy in the cache.
The FileCache handles locking cache files for reading and writing, so client code need not manage locks for cache entries.
- read_transaction(key: str | Path) Iterator[IO[str] | None][source]¶
Get a read transaction on a file cache item.
Returns a context manager that yields an open file object for reading, or None if the cache file does not exist. You can use it like this:
with file_cache_object.read_transaction(key) as cache_file: if cache_file is not None: cache_file.read()
- write_transaction(key: str | Path) Iterator[Tuple[IO[str] | None, IO[str]]][source]¶
Get a write transaction on a file cache item.
Returns a context manager that yields (old_file, new_file) where old_file is the existing cache file (or None), and new_file is a writable temporary file. Once the context manager exits cleanly, moves the temporary file into place atomically.
spack.util.file_permissions module¶
spack.util.filesystem module¶
Utilities for interacting with files, like those in spack.llnl.util.filesystem, but which require logic from spack.util
- spack.util.filesystem.fix_darwin_install_name(path: str) None[source]¶
Fix install name of dynamic libraries on Darwin to have full path.
There are two parts of this task:
Use
install_name -id ...to change install name of a single libUse
install_name -change ...to change the cross linking between libs. The function assumes that all libraries are in one folder and currently won’t follow subfolders.
- Parameters:
path – directory in which
.dylibfiles are located
spack.util.format module¶
- spack.util.format.get_version_lines(version_hashes_dict: dict) str[source]¶
Renders out a set of versions like those found in a package’s package.py file for a given set of versions and hashes.
- Parameters:
version_hashes_dict – A dictionary of the form: version -> checksum.
Returns: Rendered version lines.
spack.util.gcs module¶
This file contains the definition of the GCS Blob storage Class used to integrate GCS Blob storage with spack buildcache.
- class spack.util.gcs.GCSBlob(url, client=None)[source]¶
Bases:
objectGCS Blob object
Wraps some blob methods for spack functionality
- class spack.util.gcs.GCSBucket(url, client=None)[source]¶
Bases:
objectGCS Bucket Object Create a wrapper object for a GCS Bucket. Provides methods to wrap spack related tasks, such as destroy.
- destroy(recursive=False, **kwargs)[source]¶
Bucket destruction method
Deletes all blobs within the bucket, and then deletes the bucket itself.
Uses GCS Batch operations to bundle several delete operations together.
- get_all_blobs(recursive: bool = True, relative: bool = True) List[str][source]¶
Get a list of all blobs
Returns: a list of all blobs within this bucket.
- Parameters:
relative – If true (default), print blob paths relative to ‘build_cache’ directory. If false, print absolute blob paths (useful for destruction of bucket)
- class spack.util.gcs.GCSHandler[source]¶
Bases:
BaseHandler
spack.util.git module¶
Single util module where Spack should get a git executable.
- class spack.util.git.GitExecutable(name=None)[source]¶
Bases:
ExecutableSpecialized executable that encodes the git version for optimized option selection
- property version¶
- class spack.util.git.VersionConditionalOption(key, value=None, min_version=(0, 0, 0), max_version=(99, 99, 99))[source]¶
Bases:
object
- spack.util.git.extract_git_version_str(git_exe: Executable) str[source]¶
- spack.util.git.get_commit_sha(path: str, ref: str) str | None[source]¶
Get a commit sha for an arbitrary ref using ls-remote
- spack.util.git.get_modified_files(from_ref: str = 'HEAD~1', to_ref: str = 'HEAD', git_exe: Executable | None = None) List[str][source]¶
Get a list of files modified between
from_refandto_ref:param from_ref: oldest git ref, defaults toHEAD~1:type from_ref: str :param to_ref: newer git ref, defaults toHEAD:type to_ref: strReturns: list of file paths
- spack.util.git.git(required: Literal[True]) GitExecutable[source]¶
- spack.util.git.git(required: bool = False) GitExecutable | None
Get a git executable.
The returned executable automatically unsets
GIT_EXTERNAL_DIFFandGIT_DIFF_OPTSenvironment variables that can interfere with spack git diff operations.- Parameters:
required (bool) – if True, raises CommandNotFoundError when git is not found
Returns: GitExecutable, or None if git is not found and required is False
- spack.util.git.git_checkout(ref: str | None = None, sparse_paths: List[str] = [], debug: bool = False, dest: str | None = None, git_exe: GitExecutable | None = None)[source]¶
A generic method for running
git checkoutthat integrates sparse-checkout Several methods in this module explicitly delay checkout so sparse-checkout can be called. It is intended to be used withgit clone --no-checkoutorgit init && git fetch. There is minimal impact to performance since the initial clone operation filters blobs and has to download a minimal subset of git data.
- spack.util.git.git_clone(url: str, ref: str | None = None, full_repo: bool = False, depth: int | None = None, debug: bool = False, dest: str | None = None, git_exe: GitExecutable | None = None)[source]¶
A git clone that prefers deferring expensive blob fetching for modern git installations This is our fallback method for capturing more git data than the
init && fetchmodel. It is still optimized to capture a minimal set of./.gitdata and expects to be paired with a call togit checkoutto fully download the source code.
- spack.util.git.git_init_fetch(url, ref, depth=None, debug=False, dest=None, git_exe=None)[source]¶
Utilize
git initand thengit fetchfor a minimal clone of a single git ref This method runs git init, repo add, fetch to get a minimal set of source data. Profiling has shown this method can be 10-20% less storage than purely using sparse-checkout, and is even smaller than git clone –depth 1. This makes it the preferred method for single commit checkouts and source mirror population.There is a trade off since less git data means less flexibility with additional git operations. Technically adding the remote is not necessary, but we do it since there are test cases where we may want to fetch additional data.
Checkout is explicitly deferred to a second method so we can intercept and add sparse-checkout options uniformly whether we use git clone or init fetch
- spack.util.git.init_git_repo(repository: str, remote: str = 'origin', git_exe: Executable | None = None)[source]¶
Initialize a new Git repository and configure it with a remote.
- spack.util.git.protocol_supports_shallow_clone(url)[source]¶
Shallow clone operations (
--depth #) are not supported by the basic HTTP protocol or by no-protocol file specifications. Use (e.g.)https://orfile://instead.
- spack.util.git.pull_checkout_branch(branch: str, remote: str = 'origin', depth: int | None = None, git_exe: Executable | None = None)[source]¶
Fetch and checkout branch, then rebase with remote tracking branch.
spack.util.gpg module¶
- spack.util.gpg.GNUPGHOME¶
GNUPGHOME environment variable in the context of this Python module
- spack.util.gpg.GPG¶
Executable instance for “gpg”, initialized lazily
- spack.util.gpg.GPGCONF¶
Executable instance for “gpgconf”, initialized lazily
- spack.util.gpg.SOCKET_DIR¶
Socket directory required if a non default home directory is used
- exception spack.util.gpg.SpackGPGError(message: str, long_message: str | None = None)[source]¶
Bases:
SpackErrorClass raised when GPG errors are detected.
- spack.util.gpg.export_keys(location, keys, secret=False)[source]¶
Export public keys to a location passed as argument.
- spack.util.gpg.gnupghome_override(dir)[source]¶
Set the GNUPGHOME to a new location for this context.
- Parameters:
dir (str) – new value for GNUPGHOME
- spack.util.gpg.init(gnupghome=None, force=False)[source]¶
Initialize the global objects in the module, if not set.
When calling any gpg executable, the GNUPGHOME environment variable is set to:
The value of the
gnupghomeargument, if not NoneThe value of the “SPACK_GNUPGHOME” environment variable, if set
The default gpg path for Spack otherwise
- spack.util.gpg.public_keys_to_fingerprint(*args)[source]¶
Return the keys that can be used to verify binaries.
- spack.util.gpg.signing_keys(*args) List[str][source]¶
Return the keys that can be used to sign binaries.
- spack.util.gpg.trust(keyfile)[source]¶
Import a public key from a file and trust it.
- Parameters:
keyfile (str) – file with the public key
- spack.util.gpg.untrust(signing, *keys)[source]¶
Delete known keys.
- Parameters:
signing (bool) – if True deletes the secret keys
*keys – keys to be deleted
spack.util.hash module¶
spack.util.ld_so_conf module¶
- spack.util.ld_so_conf.host_dynamic_linker_search_paths()[source]¶
Retrieve the current host runtime search paths for shared libraries; for GNU and musl Linux we try to retrieve the dynamic linker from the current Python interpreter and then find the corresponding config file (e.g. ld.so.conf or ld-musl-<arch>.path). Similar can be done for BSD and others, but this is not implemented yet. The default paths are always returned. We don’t check if the listed directories exist.
spack.util.libc module¶
- spack.util.libc.GLIBC_PATTERN¶
Pattern to distinguish glibc from other libc implementations
- spack.util.libc.default_search_paths_from_dynamic_linker(dynamic_linker: str) List[str][source]¶
If the dynamic linker is glibc at a certain version, we can query the hard-coded library search paths
spack.util.lock module¶
Wrapper for spack.llnl.util.lock allows locking to be enabled/disabled.
- class spack.util.lock.Lock(path: str, *, start: int = 0, length: int = 0, default_timeout: float | None = None, debug: bool = False, desc: str = '', enable: bool = True)[source]¶
Bases:
LockLock that can be disabled.
This overrides the
_lock()and_unlock()methods fromspack.llnl.util.lockso that all the lock API calls will succeed, but the actual locking mechanism can be disabled via_enable_locks.
- exception spack.util.lock.LockError[source]¶
Bases:
ExceptionRaised for any errors related to locks.
- exception spack.util.lock.LockTimeoutError(lock_type: int, path: str, time: float, attempts: int)[source]¶
Bases:
LockErrorRaised when an attempt to acquire a lock times out.
- exception spack.util.lock.LockUpgradeError(path: str)[source]¶
Bases:
LockErrorRaised when unable to upgrade from a read to a write lock.
- class spack.util.lock.ReadTransaction(lock: Lock, acquire: Callable[[], None] | None = None, release: Callable[[Type[BaseException] | None, BaseException | None, TracebackType | None], bool | None] | None = None, timeout: float | None = None)[source]¶
Bases:
LockTransactionLockTransaction context manager that does a read and releases it.
- class spack.util.lock.WriteTransaction(lock: Lock, acquire: Callable[[], None] | None = None, release: Callable[[Type[BaseException] | None, BaseException | None, TracebackType | None], bool | None] | None = None, timeout: float | None = None)[source]¶
Bases:
LockTransactionLockTransaction context manager that does a write and releases it.
- spack.util.lock.check_lock_safety(path: str) None[source]¶
Do some extra checks to ensure disabling locks is safe.
This will raise an error if
pathcan is group- or world-writable AND the current user can write to the directory (i.e., if this user AND others could write to the path).This is intended to run on the Spack prefix, but can be run on any path for testing.
spack.util.log_parse module¶
- spack.util.log_parse.make_log_context(log_events: List[LogEvent]) str[source]¶
Get error context from a log file.
- Parameters:
log_events – list of events created by
ctest_log_parser.parse()- Returns:
context from the build log with errors highlighted
- Return type:
Parses the log file for lines containing errors, and prints them out with context. Errors are highlighted in red and warnings in yellow. Events are sorted by line number.
- spack.util.log_parse.parse_log_events(stream: str | TextIO, context: int = 6, profile: bool = False, tail: int = 0) Tuple[List[BuildError], List[BuildWarning], LogEvent | None][source]¶
Extract interesting events from a log file.
- Parameters:
stream – build log name or file object
context – lines of context to extract around each log event
profile – print out profile information for parsing
tail – if > 0, also return the last
taillines
- Returns:
two lists containing
BuildErrorandBuildWarningobjects, plus an optionalLogEventfor the tail (None whentail=0).
spack.util.module_cmd module¶
This module contains routines related to the module command for accessing and parsing environment modules.
- exception spack.util.module_cmd.ModuleLoadError(module)[source]¶
Bases:
SpackErrorRaised when a module cannot be loaded.
- spack.util.module_cmd.load_module(mod)[source]¶
Takes a module name and removes modules until it is possible to load that module. It then loads the provided module. Depends on the modulecmd implementation of modules used in cray and lmod.
- Raises:
ModuleLoadError – if the module could not be loaded
- spack.util.module_cmd.module(*args: str, module_template: str | None = None, module_src_cmd: str | None = None, environb: MutableMapping[bytes, bytes] | None = None)[source]¶
Run the
moduleshell function in a/bin/bashsubprocess, and either collect its changes to environment variables and apply them in the current process (formodule load,module swap, etc.), or return its output as a string (formodule show, etc.).This requires
/bin/bashto be available on the system andawkto be inPATH.- Parameters:
args – Command line arguments for the module command.
environb – (Binary) environment variables dictionary. If not provided, the current process’s environment is modified.
- spack.util.module_cmd.path_from_modules(modules)[source]¶
Inspect a list of Tcl modules for entries that indicate the absolute path at which the library supported by said module can be found.
- Parameters:
modules (list) – module files to be loaded to get an external package
- Returns:
Guess of the prefix path where the package
spack.util.naming module¶
- spack.util.naming.pkg_name_to_class_name(pkg_name: str)[source]¶
Convert a Spack package name to a class name, based on PEP-8:
Module and package names use lowercase_with_underscores.
Class names use the CapWords convention.
Not all package names are valid Python identifiers:
They can contain
-, but cannot start with-.They can start with numbers, e.g.
3proxy.
This function converts from the package name to the class convention by removing
_and-, and converting surrounding lowercase text to CapWords. If package name starts with a number, the class name returned will be prepended with_to make a valid Python identifier.
- spack.util.naming.possible_spack_module_names(python_mod_name: str) List[str][source]¶
Given a Python module name, return a list of all possible spack module names that could correspond to it.
spack.util.package_hash module¶
- exception spack.util.package_hash.PackageHashError(message: str, long_message: str | None = None)[source]¶
Bases:
SpackErrorRaised for all errors encountered during package hashing.
- class spack.util.package_hash.RemoveDirectives(spec)[source]¶
Bases:
NodeTransformerRemove Spack directives from a package AST.
This removes Spack directives (e.g.,
depends_on,conflicts, etc.) and metadata attributes (e.g.,tags,homepage,url) in a top-level class definition within apackage.py, but it does not modify nested classes or functions.If removing directives causes a
for,with, orwhilestatement to have an empty body, we remove the entire statement. Similarly, If removing directives causes anifstatement to have an empty body orelseblock, we’ll remove the block (or replace the body withpassif there is anelseblock but no body).- metadata_attrs¶
List of attributes to be excluded from a package’s hash.
- class spack.util.package_hash.RemoveDocstrings[source]¶
Bases:
NodeTransformerTransformer that removes docstrings from a Python AST.
This removes all strings that aren’t on the RHS of an assignment statement from the body of functions, classes, and modules – even if they’re not directly after the declaration.
- class spack.util.package_hash.ResolveMultiMethods(methods)[source]¶
Bases:
NodeTransformerRemove multi-methods when we know statically that they won’t be used.
Say we have multi-methods like this:
class SomePackage: def foo(self): print("implementation 1") @when("@1.0") def foo(self): print("implementation 2") @when("@2.0") @when(sys.platform == "darwin") def foo(self): print("implementation 3") @when("@3.0") def foo(self): print("implementation 4")
The multimethod that will be chosen at runtime depends on the package spec and on whether we’re on the darwin platform at build time (the darwin condition for implementation 3 is dynamic). We know the package spec statically; we don’t know statically what the runtime environment will be. We need to include things that can possibly affect package behavior in the package hash, and we want to exclude things when we know that they will not affect package behavior.
If we’re at version 4.0, we know that implementation 1 will win, because some @when for 2, 3, and 4 will be
False. We should only include implementation 1.If we’re at version 1.0, we know that implementation 2 will win, because it overrides implementation 1. We should only include implementation 2.
If we’re at version 3.0, we know that implementation 4 will win, because it overrides implementation 1 (the default), and some @when on all others will be False.
If we’re at version 2.0, it’s a bit more complicated. We know we can remove implementations 2 and 4, because their @when’s will never be satisfied. But, the choice between implementations 1 and 3 will happen at runtime (this is a bad example because the spec itself has platform information, and we should prefer to use that, but we allow arbitrary boolean expressions in @when’s, so this example suffices). For this case, we end up needing to include both implementation 1 and 3 in the package hash, because either could be chosen.
- resolve(impl_conditions)[source]¶
Given list of nodes and conditions, figure out which node will be chosen.
- visit_FunctionDef(node: FunctionDef) FunctionDef | None[source]¶
- class spack.util.package_hash.TagMultiMethods(spec: Spec)[source]¶
Bases:
NodeVisitorTag @when-decorated methods in a package AST.
- visit_FunctionDef(node: FunctionDef) AST[source]¶
- spack.util.package_hash.canonical_source(spec: Spec, filter_multimethods: bool = True, source: bytes | None = None) str[source]¶
Get canonical source for a spec’s package.py by unparsing its AST.
- Parameters:
filter_multimethods – By default, filter multimethods out of the AST if they are known statically to be unused. Supply False to disable.
source – Optionally provide a string to read python code from.
- spack.util.package_hash.package_ast(spec: Spec, filter_multimethods: bool = True, source: bytes | None = None) AST[source]¶
Get the AST for the
package.pyfile corresponding tospec.- Parameters:
filter_multimethods – By default, filter multimethods out of the AST if they are known statically to be unused. Supply False to disable.
source – Optionally provide a string to read python code from.
- spack.util.package_hash.package_hash(spec: Spec, source: bytes | None = None) str[source]¶
Get a hash of a package’s canonical source code.
This function is used to determine whether a spec needs a rebuild when a package’s source code changes.
- Parameters:
source – Optionally provide a string to read python code from.
spack.util.parallel module¶
- spack.util.parallel.ENABLE_PARALLELISM¶
Used in tests to disable parallelism, as tests themselves are parallelized
- class spack.util.parallel.ErrorFromWorker(exc_cls, exc, tb)[source]¶
Bases:
objectWrapper class to report an error from a worker process
- property stacktrace¶
- class spack.util.parallel.SequentialExecutor[source]¶
Bases:
ExecutorExecutor that runs tasks sequentially in the current thread.
- class spack.util.parallel.Task(func)[source]¶
Bases:
objectWrapped task that trap every Exception and return it as an ErrorFromWorker object.
We are using a wrapper class instead of a decorator since the class is pickleable, while a decorator with an inner closure is not.
- spack.util.parallel.imap_unordered(f, list_of_args, *, processes: int, maxtaskperchild: int | None = None, debug=False)[source]¶
Wrapper around multiprocessing.Pool.imap_unordered.
- Parameters:
f – function to apply
list_of_args – list of tuples of args for the task
processes – maximum number of processes allowed
debug – if False, raise an exception containing just the error messages from workers, if True an exception with complete stacktraces
maxtaskperchild – number of tasks to be executed by a child before being killed and substituted
- Raises:
RuntimeError – if any error occurred in the worker processes
- spack.util.parallel.make_concurrent_executor(jobs: int | None = None, *, require_fork: bool = True) Executor[source]¶
Create a concurrent executor. If require_fork is True, then the executor is sequential if the platform does not enable forking as the default start method. Effectively require_fork=True makes the executor sequential in the current process on Windows, macOS, and Linux from Python 3.14+ (which changes defaults)
spack.util.path module¶
Utilities for managing paths in Spack.
TODO: this is really part of spack.config. Consolidate it.
- spack.util.path.canonicalize_path(path: str, default_wd: str | None = None) str[source]¶
Same as substitute_path_variables, but also take absolute path.
If the string is a yaml object with file annotations, make absolute paths relative to that file’s directory. Otherwise, use
default_wdif specified, otherwiseos.getcwd()- Parameters:
path – path being converted as needed
default_wd – optional working directory/root for non-yaml string paths
Returns: An absolute path or non-file URL with path variable substitution
- spack.util.path.substitute_config_variables(path)[source]¶
Substitute placeholders into paths.
Spack allows paths in configs to have some placeholders, as follows:
$env The active Spack environment.
$spack The Spack instance’s prefix
$tempdir Default temporary directory returned by tempfile.gettempdir()
$user The current user’s username
$user_cache_path The user cache directory (~/.spack, unless overridden)
$spack_instance_id Hash that distinguishes Spack instances on the filesystem
$architecture The spack architecture triple for the current system
$arch The spack architecture triple for the current system
$platform The spack platform for the current system
$os The OS of the current system
$operating_system The OS of the current system
$target The ISA target detected for the system
$target_family The family of the target detected for the system
$date The current date (YYYY-MM-DD)
$spack_short_version The spack short version
These are substituted case-insensitively into the path, and users can use either
$varor${var}syntax for the variables. $env is only replaced if there is an active environment, and should only be used in environment yaml files.
spack.util.pattern module¶
spack.util.prefix module¶
This file contains utilities for managing the installation prefix of a package.
- class spack.util.prefix.Prefix[source]¶
Bases:
strThis class represents an installation prefix, but provides useful attributes for referring to directories inside the prefix.
Attributes of this object are created on the fly when you request them, so any of the following are valid:
>>> prefix = Prefix("/usr") >>> prefix.bin /usr/bin >>> prefix.lib64 /usr/lib64 >>> prefix.share.man /usr/share/man >>> prefix.foo.bar.baz /usr/foo/bar/baz >>> prefix.join("dashed-directory").bin64 /usr/dashed-directory/bin64
Prefix objects behave identically to strings. In fact, they subclass
str, so operators like+are legal:print("foobar " + prefix)
This prints
foobar /usr. All of this is meant to make custom installs easy.
spack.util.remote_file_cache module¶
- spack.util.remote_file_cache.fetch_remote_text_file(url: str, dest_dir: str) str[source]¶
Retrieve the text file from the url into the destination directory.
- Parameters:
url – URL for the remote text file
dest_dir – destination directory in which to stage the file locally
- Returns:
Path to the fetched file
- Raises:
ValueError – if there are missing required arguments
- spack.util.remote_file_cache.local_path(raw_path: str, sha256: str, dest: str | None = None) str[source]¶
Determine the actual path and, if remote, stage its contents locally.
- Parameters:
raw_path – raw path with possible variables needing substitution
sha256 – the expected sha256 if the file is remote
dest – destination path
Returns: resolved, normalized local path
- Raises:
ValueError – missing or mismatched arguments, unsupported URL scheme
spack.util.s3 module¶
- class spack.util.s3.UrllibS3Handler[source]¶
Bases:
BaseHandler
- class spack.util.s3.WrapStream(raw)[source]¶
Bases:
BufferedReader- detach()[source]¶
Disconnect this buffer from its underlying raw stream and return it.
After the raw stream has been detached, the buffer is in an unusable state.
- read(*args, **kwargs)[source]¶
Read and return up to n bytes.
If the size argument is omitted, None, or negative, read and return all data until EOF.
If the size argument is positive, and the underlying raw stream is not ‘interactive’, multiple raw reads may be issued to satisfy the byte count (unless EOF is reached first). However, for interactive raw streams (as well as sockets and pipes), at most one raw read will be issued, and a short result does not imply that EOF is imminent.
Return an empty bytes object on EOF.
Return None if the underlying raw stream was open in non-blocking mode and no data is available at the moment.
spack.util.socket module¶
Optimized Spack implementations of methods from socket module.
spack.util.spack_json module¶
Simple wrapper around JSON to guarantee consistent use of load/dump.
- exception spack.util.spack_json.SpackJSONError(msg: str, json_error: BaseException)[source]¶
Bases:
SpackErrorRaised when there are issues with JSON parsing.
- spack.util.spack_json.dump(data: Any, stream: IO[str], pretty: bool = False) None[source]¶
Wrapper around json.dump with different default arguments
spack.util.spack_yaml module¶
Enhanced YAML parsing for Spack.
load()preserves YAML Marks on returned objects – this allows us to access file and line information later.Our load methods use ``OrderedDictclass instead of YAML’s default unordered dict.
- exception spack.util.spack_yaml.SpackYAMLError(msg, yaml_error, filename=None)[source]¶
Bases:
SpackErrorRaised when there are issues with YAML parsing.
spack.util.timer module¶
Debug signal handler: prints a stack trace and enters interpreter.
register_interrupt_handler() enables a ctrl-C handler that prints
a stack trace and drops the user into an interpreter.
- spack.util.timer.NULL_TIMER¶
instance of a do-nothing timer
- class spack.util.timer.NullTimer[source]¶
Bases:
BaseTimerTimer interface that does nothing, useful in for “tell don’t ask” style code when timers are optional.
- class spack.util.timer.TimeTracker(total, start, count, path)¶
Bases:
tuple- count¶
Alias for field number 2
- path¶
Alias for field number 3
- start¶
Alias for field number 1
- total¶
Alias for field number 0
- class spack.util.timer.Timer(now: Callable[[], float] = time.time)[source]¶
Bases:
BaseTimerSimple interval timer
- duration(name=global_timer_name)[source]¶
Get the time in seconds of a named timer, or the total time if no name is passed. The duration is always 0 for timers that have not been started, no error is raised.
- measure(name)[source]¶
Context manager that allows you to time a block of code.
- Parameters:
name (str) – Name of the timer
- property phases¶
Get all named timers (excluding the global/total timer)
- start(name=global_timer_name)[source]¶
Start or restart a named timer, or the global timer when no name is given.
- Parameters:
name (str) – Optional name of the timer. When no name is passed, the global timer is started.
- class spack.util.timer.TimerEvent(time, running, label)¶
Bases:
tuple- label¶
Alias for field number 2
- running¶
Alias for field number 1
- time¶
Alias for field number 0
- spack.util.timer.global_timer_name¶
name for the global timer (used in start(), stop(), duration() without arguments)
spack.util.typing module¶
Extra support for type checking in Spack.
Protocols here that have runtime overhead should be set to object when
TYPE_CHECKING is not enabled, as they can incur unreasonable runtime overheads.
In particular, Protocols intended for use on objects that have many isinstance()
calls can be very expensive.
spack.util.url module¶
Utility functions for parsing, formatting, and manipulating URLs.
- spack.util.url.default_download_filename(url: str) str[source]¶
This method computes a default file name for a given URL. Note that it makes no request, so this is not the same as the option curl -O, which uses the remote file name from the response header.
- spack.util.url.format(parsed_url)[source]¶
Format a URL string
Returns a canonicalized format of the given URL as a string.
- spack.util.url.is_path_instead_of_url(path_or_url)[source]¶
Historically some config files and spack commands used paths where urls should be used. This utility can be used to validate and promote paths to urls.
- spack.util.url.join(base: str, *components: str, resolve_href: bool = False, **kwargs) str[source]¶
Convenience wrapper around
urllib.parse.urljoin(), with a few differences:By default
resolve_href=False, which makes the function likeos.path.join(). For examplehttps://example.com/a/b + c/d = https://example.com/a/b/c/d. Ifresolve_href=True, the behavior is how a browser would resolve the URL:https://example.com/a/c/d.s3://,gs://,oci://URLs are joined likehttp://URLs.It accepts multiple components for convenience. Note that
components[1:]are treated as literal path components and appended tocomponents[0]separated by slashes.
- spack.util.url.local_file_path(url)[source]¶
Get a local file path from a url.
If url is a
file://URL, return the absolute path to the local file or directory referenced by it. Otherwise, return None.
spack.util.web module¶
- exception spack.util.web.DetailedHTTPError(req: Request, code: int, msg: str, hdrs: Message, fp: IO | None)[source]¶
Bases:
HTTPError
- class spack.util.web.ExtractMetadataParser[source]¶
Bases:
HTMLParserThis parser takes an HTML page and selects the include-fragments, used on GitHub, https://github.github.io/include-fragment-element, as well as a possible base url.
- class spack.util.web.LinkParser[source]¶
Bases:
HTMLParserThis parser just takes an HTML page and strips out the hrefs on the links, as well as some javascript tags used on GitLab servers. Good enough for a really simple spider.
- exception spack.util.web.NoNetworkConnectionError(message, url)[source]¶
Bases:
SpackWebErrorRaised when an operation can’t get an internet connection.
- spack.util.web.SPACK_USER_AGENT¶
User-Agent used in Request objects
- class spack.util.web.SpackHTTPDefaultErrorHandler[source]¶
Bases:
HTTPDefaultErrorHandler
- class spack.util.web.SpackHTTPSHandler(debuglevel=None, context=None, check_hostname=None)[source]¶
Bases:
HTTPSHandlerA custom HTTPS handler that shows more detailed error messages on connection failure.
- exception spack.util.web.SpackWebError(message: str, long_message: str | None = None)[source]¶
Bases:
SpackErrorSuperclass for Spack web spidering errors.
- spack.util.web.base_curl_fetch_args(url, timeout=0)[source]¶
Return the basic fetch arguments typically used in calls to curl.
The arguments include those for ensuring behaviors such as failing on errors for codes over 400, printing HTML headers, resolving 3xx redirects, status or failure handling, and connection timeouts.
It also uses the following configuration option to set an additional argument as needed:
config:connect_timeout (int): connection timeout
config:verify_ssl (str): Perform SSL verification
- Parameters:
Returns (list): list of argument strings
- spack.util.web.check_curl_code(returncode: int) None[source]¶
Check standard return code failures for provided arguments.
- Parameters:
returncode – curl return code
Raises FetchError if the curl returncode indicates failure
- spack.util.web.custom_ssl_certs() Tuple[bool, str] | None[source]¶
Returns a tuple (is_file, path) if custom SSL certifates are configured and valid.
- spack.util.web.fetch_url_text(url, curl: Executable | None = None, dest_dir='.')[source]¶
Retrieves text-only URL content using the configured fetch method. It determines the fetch method from:
config:url_fetch_method (str): fetch method to use (e.g., ‘curl’)
If the method is
curl, it also uses the following configuration options:config:connect_timeout (int): connection time out
config:verify_ssl (str): Perform SSL verification
- Parameters:
url (str) – URL whose contents are to be fetched
curl (spack.util.executable.Executable or None) – (optional) curl executable if curl is the configured fetch method
dest_dir (str) – (optional) destination directory for fetched text file
Returns (str or None): path to the fetched file
Raises FetchError if the curl returncode indicates failure
- spack.util.web.get_header(headers, header_name)[source]¶
Looks up a dict of headers for the given header value.
Looks up a dict of headers, [headers], for a header value given by [header_name]. Returns headers[header_name] if header_name is in headers. Otherwise, the first fuzzy match is returned, if any.
This fuzzy matching is performed by discarding word separators and capitalization, so that for example, “Content-length”, “content_length”, “conTENtLength”, etc., all match. In the case of multiple fuzzy-matches, the returned value is the “first” such match given the underlying mapping’s ordering, or unspecified if no such ordering is defined.
If header_name is not in headers, and no such fuzzy match exists, then a KeyError is raised.
- spack.util.web.is_transient_error(e: Exception) bool[source]¶
Return True for HTTP/network errors that are worth retrying.
- spack.util.web.parse_etag(header_value)[source]¶
Parse a strong etag from an ETag: <value> header value. We don’t allow for weakness indicators because it’s unclear what that means for cache invalidation.
- spack.util.web.push_to_url(local_file_path, remote_path, keep_original=True, extra_args=None)[source]¶
- spack.util.web.read_text(url: str) str[source]¶
Fetch url and return the response body decoded as UTF-8 text.
- spack.util.web.require_curl() Executable[source]¶
- spack.util.web.retry_on_transient_error(f: Callable[[_P], _R], retries: int = 5, sleep: Callable[[float], None] | None = None) Callable[[_P], _R][source]¶
Retry a function on transient HTTP/network errors with exponential backoff.
- spack.util.web.set_curl_env_for_ssl_certs(curl: Executable) None[source]¶
configure curl to use custom certs in a file at runtime. See: https://curl.se/docs/sslcerts.html item 4
- spack.util.web.spider(root_urls: str | Iterable[str], depth: int = 0, concurrency: int | None = None)[source]¶
Get web pages from root URLs.
If depth is specified (e.g., depth=2), then this will also follow up to <depth> levels of links from each root.
- Parameters:
root_urls – root urls used as a starting point for spidering
depth – level of recursion into links
concurrency – number of simultaneous requests that can be sent
- Returns:
A dict of pages visited (URL) mapped to their full text and the set of visited links.
- spack.util.web.ssl_create_default_context()[source]¶
Create the default SSL context for urllib with custom certificates if configured.
- spack.util.web.stat_url(url: str) Tuple[int, float] | None[source]¶
Get stat result for a URL.
- Parameters:
url – URL to get stat result for
- Returns:
A tuple of (size, mtime) if the URL exists, None otherwise.
- spack.util.web.url_exists(url, curl=None)[source]¶
Determines whether url exists.
A scheme-specific process is used for Google Storage (
gs) and Amazon Simple Storage Service (s3) URLs; otherwise, the configured fetch method defined byconfig:url_fetch_methodis used.- Parameters:
url (str) – URL whose existence is being checked
curl (spack.util.executable.Executable or None) – (optional) curl executable if curl is the configured fetch method
Returns (bool): True if it exists; False otherwise.
- spack.util.web.urlopen¶
Dispatches to the correct OpenerDirector.open, based on Spack configuration.
spack.util.windows_registry module¶
Utility module for dealing with Windows Registry.
- class spack.util.windows_registry.HKEY[source]¶
Bases:
objectPredefined, open registry HKEYs From the Microsoft docs: An application must open a key before it can read data from the registry. To open a key, an application must supply a handle to another key in the registry that is already open. The system defines predefined keys that are always open. Predefined keys help an application navigate in the registry.
- HKEY_CLASSES_ROOT¶
- HKEY_CURRENT_CONFIG¶
- HKEY_CURRENT_USER¶
- HKEY_LOCAL_MACHINE¶
- HKEY_PERFORMANCE_DATA¶
- HKEY_USERS¶
- exception spack.util.windows_registry.InvalidKeyError(key)[source]¶
Bases:
RegistryErrorRuntime Error describing issue with invalid key access to Windows registry
- exception spack.util.windows_registry.InvalidRegistryOperation(name, e, *args, **kwargs)[source]¶
Bases:
RegistryErrorA Runtime Error encountered when a registry operation is invalid for an indeterminate reason
- exception spack.util.windows_registry.RegistryError[source]¶
Bases:
ExceptionRunTime Error concerning the Windows Registry
- class spack.util.windows_registry.RegistryKey(name, handle)[source]¶
Bases:
objectClass wrapping a Windows registry key
- property hkey¶
- property subkeys¶
Returns list of all subkeys of this key as RegistryKey objects
- property values¶
Returns all subvalues of this key as RegistryValue objects in dictionary of value name : RegistryValue object
- class spack.util.windows_registry.RegistryValue(name, value, parent_key)[source]¶
Bases:
objectClass defining a Windows registry entry
- class spack.util.windows_registry.WindowsRegistryView(key, root_key=HKEY.HKEY_CURRENT_USER)[source]¶
Bases:
objectInterface to provide access, querying, and searching to Windows registry entries. This class represents a single key entrypoint into the Windows registry and provides an interface to this key’s values, its subkeys, and those subkey’s values. This class cannot be used to move freely about the registry, only subkeys/values of the root key used to instantiate this class.
- find_matching_subkey(subkey_name: str, recursive: bool = True)[source]¶
Perform a BFS of subkeys until a key matching subkey name regex is found Returns None or the first RegistryKey object corresponding to requested key name
- Parameters:
subkey_name – subkey to be searched for
recursive – perform a recursive search
- Returns:
the desired subkey as a RegistryKey object, or none
- find_subkey(subkey_name: str, recursive: bool = True)[source]¶
Perform a BFS of subkeys until desired key is found Returns None or RegistryKey object corresponding to requested key name
- Parameters:
subkey_name – subkey to be searched for
recursive – perform a recursive search
- Returns:
the desired subkey as a RegistryKey object, or none
- find_subkeys(subkey_name: str, recursive: bool = True)[source]¶
Exactly the same as find_subkey, except this function tries to match a regex to multiple keys
- Parameters:
subkey_name – subkey to be searched for
- Returns:
the desired subkeys as a list of RegistryKey object, or none
- find_value(val_name: str, recursive: bool = True)[source]¶
If non recursive, return RegistryValue object corresponding to name
- Parameters:
val_name – name of value desired from registry
recursive – optional argument, if True, the registry is searched recursively for the value of name val_name, else only the current key is searched
- Returns:
The desired registry value as a RegistryValue object if it exists, otherwise, None
- get_matching_subkeys(subkey_name)[source]¶
Returns all subkeys regex matching subkey name
Note: this method obtains only direct subkeys of the given key and does not descend to transitive subkeys. For this behavior, see
find_matching_subkeys
- get_value(value_name)[source]¶
Return registry value corresponding to provided argument (if it exists)
- property reg¶