utils
log
as_bytes
def as_bytes(file_: Union[bytes, bytearray, io.BytesIO])
Returns file_ as bytes.
Arguments:
file_Union[bytes, bytearray, io.BytesIO] - The file
Returns:
bytes
Raises:
TypeError- If file_ is not an instance of: bytes, bytearray, io.BytesIO
as_io_BytesIO
def as_io_BytesIO(file_: Union[bytes, bytearray])
Returns file_ as io.BytesIO object.
Arguments:
file_Union[bytes, bytearray] - The bytes or bytearray of the file
Returns:
io.BytesIO object
Raises:
TypeError- If file_ is not an instance of: bytes, bytearray, io.BytesIO
as_snake_case
def as_snake_case(string)
as_title
def as_title(string)
buffer_to_bytes
def buffer_to_bytes(buffer: ct.c_void_p, buffer_length: ct.c_size_t)
Convert ctypes buffer and buffer_length to bytes.
Arguments:
buffer (ct.c_void_p()): The file buffer. buffer_length (ct.c_size_t()): The file buffer length.
Returns:
bytesbytes - The file as bytes.
CwdHandler
class CwdHandler()
Changes the current working directory to new_cwd on enter, and back to previous cwd on exit.
Arguments:
new_cwdstr - The new current working directory to temporarily change to.
__init__
def __init__(new_cwd: str)
__enter__
def __enter__()
__exit__
def __exit__(type, value, traceback)
delete_directory
def delete_directory(directory: str, keep_folder: bool = False)
Delete a directory and its contents.
Arguments:
directorystr - The directory path.keep_folderbool, optional - Default False. If False, only delete contents.
delete_empty_subdirectories
def delete_empty_subdirectories(directory: str)
Deletes all empty subdirectories of a given directory.
Arguments:
directorystr - The directory to delete subdirectories from.
Returns:
None
flatten_list
def flatten_list(list_: Iterable)
Returns a flattened list. [[1, 2], ["3"], (4, 5,), [6]] --> [1, 2, "3", 4, 5, 6]
get_file_type
def get_file_type(file_path: str)
Returns the filetype of a file. "data/files/splat.zip" -> "zip"
get_libraries
def get_libraries(directory: str,
library_names: Optional[List[str]] = None,
ignore_errors: bool = False)
Recursively calls get_library on each library from glasswall.libraries.os_info on the given directory.
Arguments:
directorystr - The directory to search from.library_namesList[str], optional - List of libraries to return, if None iterates all libraries found in glasswall.libraries.os_infoignore_errorsbool, optional - Default False, prevents get_library raising FileNotFoundError when True.
Returns:
librariesdict[str, str] - A dictionary of library names and their absolute file paths.
get_library
def get_library(library: str, directory: str)
Returns a path to the specified library found from the current directory or any subdirectory. If multiple libraries exist, returns the file with the latest modified time.
Arguments:
librarystr - The library to search for, ie: "rebuild", "word_search"directorystr - The directory to search from.
Returns:
library_file_pathstr - The absolute file path to the library.
Raises:
KeyError- Unsupported OS or library name was not found in glasswall.libraries.os_info.FileNotFoundError- Library was not found.
iterate_directory_entries
def iterate_directory_entries(directory: str,
file_type: str = 'all',
absolute: bool = True,
recursive: bool = True,
followlinks: bool = True,
start_directory: str = None)
Generate entries (files, directories, or both) in a given directory using os.scandir().
Arguments:
directorystr - The path to the directory whose entries are to be listed.file_typestr, optional - Type of entries to return.- 'all': Return both files and directories (default).
- 'files': Return only files.
- 'directories': Return only directories.
absolutebool, optional - Whether to return absolute paths (default) or relative paths.recursivebool, optional - Whether to recurse into subdirectories (default is True).followlinksbool, optional - Whether to follow symbolic links and yield entries from the target directory (default is True).start_directorystr, optional - The starting directory used to calculate relative paths (default is None).
Yields:
str- The full path of each file or directory found in the specified directory.
Raises:
ValueError- If an invalid 'file_type' value is provided.NotADirectoryError- If the directory does not exist.
Example:
directory = '/path/to/your/directory'
Iterate through all entries (files and directories) in the directory
for entry in iterate_directory_entries(directory): print(entry)
Iterate through only file entries in the directory
for file in iterate_directory_entries(directory, file_type='files'): print("File:", file)
Iterate through only directory entries in the directory
for directory in iterate_directory_entries(directory, file_type='directories'): print("Directory:", directory)
list_file_paths
def list_file_paths(directory: str,
file_type: str = 'files',
absolute: bool = True,
recursive: bool = True,
followlinks: bool = True) -> list
List all file paths in a given directory and its subdirectories.
Arguments:
directorystr - The path to the directory whose file paths are to be listed.file_typestr, optional - Type of entries to return.- 'all': Return both files and directories.
- 'files': Return only files (default).
- 'directories': Return only directories.
absolutebool, optional - Whether to return absolute paths (default is True).recursivebool, optional - Whether to recurse into subdirectories (default is True).followlinksbool, optional - Whether to follow symbolic links and list file paths from the target directory (default is True).
Returns:
list- A list of file paths found in the specified directory and its subdirectories.
Example:
directory = '/path/to/your/directory' file_paths = list_file_paths(directory) print(file_paths)
list_subdirectory_paths
def list_subdirectory_paths(directory: str,
recursive: bool = False,
absolute: bool = True)
Returns a list of paths to subdirectories in a directory.
Arguments:
directorystr - The directory to list subdirectories from.recursivebool, optional - Default False. Include subdirectories of subdirectories.absolutebool, optional - Default True. Return paths as absolute paths. If False, returns relative paths.
Returns:
subdirectorieslist - A list of subdirectory paths.
load_dependencies
def load_dependencies(dependencies: list, ignore_errors: bool = False)
Calls ctypes.cdll.LoadLibrary on each file path in dependencies.
Arguments:
dependencieslist - A list of absolute file paths of library dependencies.ignore_errorsbool, optional - Default False, avoid raising exceptions from ct.cdll.LoadLibrary if ignore_errors is True.
Returns:
missing_dependencieslist - A list of missing dependencies, or an empty list.
round_up
def round_up(number: float, decimals=0) -> float
Rounds a number up to a specified number of decimal places.
Arguments:
numberfloat - The number to be rounded.decimalsint, optional - The number of decimal places to round to. Defaults to 0.
Returns:
float- The rounded number.
Examples:
>>> round_up(105, 0) 105.0 >>> round_up(0.015, 2) 0.02 >>> round_up(0.025, 2) 0.03 >>> round_up(0.00001, 2) 0.01
TempDirectoryPath
class TempDirectoryPath()
Gives a path to a uniquely named temporary directory that does not currently exist on enter, deletes the directory if it exists on exit.
Arguments:
deletebool, optional - Default True. Delete the temporary directory on exit
__init__
def __init__(delete: bool = True)
__enter__
def __enter__()
__exit__
def __exit__(type, value, traceback)
TempFilePath
class TempFilePath()
Gives a path to a uniquely named temporary file that does not currently exist on enter, deletes the file if it exists on exit.
Arguments:
directoryUnion[str, None], optional - The directory to create a temporary file in.deletebool, optional - Default True. Delete the temporary file on on exit
__init__
def __init__(directory: Union[str, None] = None, delete: bool = True)
__enter__
def __enter__()
__exit__
def __exit__(type, value, traceback)
validate_xml
def validate_xml(
xml: Union[str, bytes, bytearray, io.BytesIO,
"glasswall.content_management.policies.policy.Policy"])
Attempts to parse the xml provided, returning the xml as string. Raises ValueError if the xml cannot be parsed.
Arguments:
xmlUnion[str, bytes, bytearray, io.BytesIO, glasswall.content_management.policies.policy.Policy] - The xml string, or file path, bytes, or ContentManagementPolicy instance to parse.
Returns:
xml_stringstr - A string representation of the xml.
Raises:
ValueError- if the xml cannot be parsed.TypeError- if the type of arg "xml" is invalid
xml_as_dict
def xml_as_dict(xml)
Converts a simple single-level xml into a dictionary.
Arguments:
xmlUnion[str, bytes, bytearray, io.BytesIO] - The xml string, or file path, or bytes to parse.
Returns:
dict_dict - A dictionary of element tag : text
deprecated_alias
def deprecated_alias(**aliases: str) -> Callable
Decorator for deprecated function and method arguments.
Use as follows:
@deprecated_alias(old_arg='new_arg') def myfunc(new_arg): ...
https://stackoverflow.com/a/49802489
rename_kwargs
def rename_kwargs(func_name: str, kwargs: Dict[str, Any], aliases: Dict[str,
str])
Helper function for deprecating function arguments.
https://stackoverflow.com/a/49802489
deprecated_function
def deprecated_function(replacement_function)