batcave package

Submodules

batcave.automation module

This module provides utilities for building automation.

class batcave.automation.Action(**_unused_kwargs: Any)

Bases: object

The common base class for all actions.

This is a virtual class and the inheriting class must at least include a _execute() method.

The action is invoked by calling the execute() method which will run the following methods:

pre()
_execute()
post()

These are run in a try to catch any exceptions with the always_post() method run in the finally block.

message_guard

This string is printed by logger if the value of guard passed to logger is true.

always_post() None

Always executed after _execute() as in finally in try/catch/finally.

Returns:

Nothing.

execute() None

Run the _execute() method from the child class.

Returns:

Nothing.

log_message(message: str, /, guard: bool = False, leader: str = 'INFO') None

Log a message to stdout and flushes the stream.

Parameters:
  • message – The message to be printed.

  • guard (optional, default=False) – If True, message_guard will be printed on a line before the message.

  • leader (optional, default='INFO') – If it does not evaluate to False, it will be prepended to every printed line, including the guard.

Returns:

Nothing.

message_guard = '**********************************************************************'
post() None

Executed after _execute().

Returns:

Nothing.

pre() None

Executed before _execute().

Returns:

Nothing.

property project_root

A read-only property which returns the root of the automation.

class batcave.automation.ActionCommandRunner(command: str, /, *args, logger: ~typing.Callable | ~logging.Logger | None = <built-in function print>, guard: str = '', syscmd_args: ~typing.Dict[~typing.Any, ~typing.Any] | None = None, **kwargs)

Bases: SysCmdRunner

Class to wrap SysCmdRunner for simple usage with auto-logging.

run(message: str, *args, post_option_args: Dict | None = None, syscmd_args: Dict[Any, Any] | None = None, **kwargs) CommandResult

Run the action.

Parameters:
  • message – The message to log if a logger has been set.

  • post_option_args (optional, default=[]) – The list of post_option_args passed to SysCmdRunner.

  • syscmd_args (optional, default={}) – The syscmd_args passed to SysCmdRunner.

  • *args (optional, default=[]) – The list of args passed to SysCmdRunner.

  • **kwargs (optional, default={}) – The list of named args passed to SysCmdRunner.

Returns:

Returns whatever is returned by SysCmdRunner.

batcave.cloudmgr module

This module provides utilities for managing cloud resources.

batcave.cloudmgr.CloudType

The cloud providers supported by the Cloud class.

Type:

Enum

batcave.cloudmgr.gcloud

A simple interface to the gcloud command line tool.

Type:

SysCmdRunner.run

class batcave.cloudmgr.Cloud(ctype: CloudType, /, *, auth: Sequence[str] = ('', ''), login: bool = True)

Bases: object

Class to create a universal abstract interface for a cloud instance.

property client

A read-only property which returns the client reference.

property containers: List[Container]

A read-only property which calls the get_containers() method with no filters.

exec(*args, **kwargs) CommandResult

Execute a command against the cloud API.

Parameters:
  • *args (optional, default=[]) – A list of arguments to pass to the API.

  • **kwargs (optional, default={}) – A dictionary to pass to the API.

Returns:

The result of the API call.

Raises:

CloudError.INVALID_OPERATION – If the cloud type does not support an API call.

get_container(name: str, /) Container

Get a container from the cloud.

Parameters:

name – The container name to retrieve.

Returns:

The container object.

get_containers(filters: str | None = None, /) List[Container]

Get a possibly filtered list of containers.

Parameters:

filter (optional, default=None) – the container name to retrieve.

Returns:

The container object.

Raises:

CloudError.INVALID_OPERATION – If the cloud type does not support login.

get_image(tag: str, /) Image

Get an image from the cloud container registry.

Parameters:

tag – The container image tag to retrieve.

Returns:

The image object.

login() None

Perform a login to the cloud provider.

Returns:

Nothing.

property type

A read-only property which returns the cloud type.

exception batcave.cloudmgr.CloudError(err_obj: BatCaveError, /, **variables)

Bases: BatCaveException

Cloud Exceptions.

IMAGE_ERROR

There was an error working with a container image.

INVALID_OPERATION

The specified cloud type does not support the requested operation.

INVALID_TYPE

An invalid cloud type was specified.

IMAGE_ERROR = BatCaveError(code=1, msg=<string.Template object>)
INVALID_OPERATION = BatCaveError(code=2, msg=<string.Template object>)
INVALID_TYPE = BatCaveError(code=3, msg=<string.Template object>)
class batcave.cloudmgr.CloudType(*values)

Bases: Enum

dockerhub = 3
gcloud = 2
local = 1
class batcave.cloudmgr.Container(cloud: Cloud, name: str, /)

Bases: object

Class to create a universal abstract interface to a container.

property cloud

A read-only property which returns the container cloud object.

property name

A read-only property which returns the name of the container.

stop() Container

Stop a running container.

Returns:

A reference to the stopped container.

Raises:

CloudError.INVALID_OPERATION – If the cloud type does not support stopping an container.

class batcave.cloudmgr.Image(cloud: Cloud, name: str, /)

Bases: object

Class to create a universal abstract interface to a container image.

property cloud

A read-only property which returns the container cloud object.

property containers

A read-only property which returns all the containers for this image.

get_tags() List[str]

Get a list of tags applied to the image.

Returns:

The sorted list of tags applied to the image.

property name

A read-only property which returns the name of the image.

pull() Image

Pull the image from the registry.

Returns:

The image object.

push() List[str]

Push the image to the registry.

Returns:

The server log from the push.

run(*, detach: bool = True, update: bool = True, **kwargs) Container

Run an image to create an active container.

Parameters:
  • detach (optional, default=True) – If True, do not wait for the container to complete.

  • update (optional, default=True) – If True, perform a pull of the image from the registry before running.

  • **kwargs (optional, default={}) – A dictionary of arguments to pass to the run command.

Returns:

A reference to the active container.

Raises:

CloudError.INVALID_OPERATION – If the cloud type does not support running an image.

tag(new_tag: str, /) Image | None

Tag an image in the registry.

Returns:

The tagged image.

property tags: List[str]

A read-only property which calls the get_tags() method with no filters.

batcave.cloudmgr.validate_type(ctype: CloudType) None

Determine if the specified Cloud type is valid.

Parameters:

ctype – The Cloud type.

Returns:

Nothing.

Raises

CloudError.INVALID_TYPE: If the cloud type is not valid.

batcave.cms module

This module provides utilities for managing source code systems.

batcave.cms.P4_LOADED

If not empty then it is the string version of the Perforce API.

Type:

str

batcave.cms.GIT_LOADED

If not empty then it is the string version of the GitPython API.

Type:

str

batcave.cms.ClientType

The CMS providers supported by the Client class.

Type:

Enum

exception batcave.cms.CMSError(err_obj: BatCaveError, /, **variables)

Bases: BatCaveException

CMS Exceptions.

CHANGELIST_NOT_EDITABLE

An attempt was made to edit a readonly changelist.

CLIENT_DATA_INVALID

The root and mapping arguments cannot be specified if create=False.

CLIENT_NAME_REQUIRED

A client name is required if create=False.

CLIENT_NOT_FOUND

The specified client was not found.

CONNECT_FAILED

Error connecting to the CMS system.

CONNECT_INFO_REQUIRED

Connection info is required for the specified CMS type.

GIT_FAILURE

Gir returned an error.

INVALID_OPERATION

The specified CMS type does not support the requested operation.

INVALID_TYPE

An invalid CMS type was specified.

CHANGELIST_NOT_EDITABLE = BatCaveError(code=1, msg=<string.Template object>)
CLIENT_DATA_INVALID = BatCaveError(code=2, msg=<string.Template object>)
CLIENT_NAME_REQUIRED = BatCaveError(code=3, msg='Name required if client is not being created')
CLIENT_NOT_FOUND = BatCaveError(code=4, msg=<string.Template object>)
CONNECT_FAILED = BatCaveError(code=5, msg=<string.Template object>)
CONNECT_INFO_REQUIRED = BatCaveError(code=6, msg=<string.Template object>)
GIT_FAILURE = BatCaveError(code=7, msg=<string.Template object>)
INVALID_OPERATION = BatCaveError(code=8, msg=<string.Template object>)
INVALID_TYPE = BatCaveError(code=9, msg=<string.Template object>)
class batcave.cms.ChangeList(client: Client, chg_list_id: Any = None, /, editable: bool | None = None)

Bases: object

Class to create a universal abstract interface for a CMS changelist.

property desc: str

A read-write property which returns and sets the change list description.

property files: List[FileChangeRecord]

A read-only property which returns the list of files in the change list.

property name

A read-only property which returns the name of the change list.

store(*, no_execute: bool = False) None

Save the ChangeList to the CMS server.

Parameters:

no_execute (optional, default=False) – If True, run the command but don’t commit the results.

Returns:

Nothing.

property time: datetime

A read-write property which returns and sets the change list time.

property user: str

A read-write property which returns and sets the change list user.

class batcave.cms.CleanType(*values)

Bases: Enum

all = 3
members = 2
none = 1
class batcave.cms.Client(ctype: ClientType, /, name: str = '', connect_info: str = '', *, user: str = '', root: Path | None = None, alt_roots: Sequence[str] | None = None, mapping: List[str] | None = None, hostless: bool = False, changelist_options: str | None = None, line_style: LineStyle | None = None, cleanup: bool | None = None, create: bool | None = None, info: bool = False, password: str | None = None, branch: str | None = None)

Bases: object

Class to create a universal abstract interface for a CMS system client.

_DEFAULT_P4PORT

The default Perforce port.

_INFO_DUMMY_CLIENT

The default name for a dummy client.

property active_branch: str

A read-only property which returns the current active branch name.

add_files(*files: PathName, all_files: bool = False, no_execute: bool = False) List[str]

Add files to the client.

Parameters:
  • *files – The files to add.

  • all_files (optional, default=False) – If True, add all files.

  • no_execute (optional, default=False) – If True, run the command but don’t commit the results.

Returns:

The result of the add files command.

Raises:

CMSError.INVALID_OPERATION – If the client CMS type is not supported.

add_label(tag_name: str, tag_message: str, /, *, exists_ok: bool = False, no_execute: bool = False) List[str]

Add a label.

Parameters:
  • tag_name – The name of the label to add.

  • tag_message – The message used as a tag annotation.

  • exists_ok (optional, default=False) – If True and the label already exists, delete the label before adding it.

  • no_execute (optional, default=False) – If True, run the command but don’t revert the files.

Returns:

The list of label objects.

Raises:

CMSError.INVALID_OPERATION – If the client CMS type is not supported.

add_remote_ref(name: str, url: str, /, *, exists_ok: bool = False, no_execute: bool = False) List[str]

Add a remote reference for a DVCS client.

Parameters:
  • name – The name of the remote reference to add.

  • url – The URL of the remote reference to add.

  • exists_ok (optional, default=False) – If False, attempt to add the remote reference if it already exists, otherwise just return.

  • no_execute (optional, default=False) – If True, run the command but don’t revert the files.

Returns:

The result of the add remote command.

Raises:

CMSError.INVALID_OPERATION – If the client CMS type is not supported.

property branches: Any

A read-only property which returns the client branch list.

checkin_files(description: str, /, *files: str, all_branches: bool = False, all_files: bool = False, remote: str = 'origin', remote_ref: str | None = None, fail_on_empty: bool = False, no_execute: bool = False, **extra_args) List[str]

Commit open files on the client.

Parameters:
  • description – A description of the changes.

  • *files (optional) – If provided, a subset of the files to commit, otherwise all will be submitted.

  • all_branches (optional, default=False) – If True, commit all branches, otherwise only the current branch.

  • all_files (optional, default=False) – If True, commit all files, otherwise only the specified files.

  • remote (optional, default='origin') – The remote to which to push the changes for git clients.

  • remote_ref (optional, default=None) – The remote ref to which to push the changes for git clients. If not provided, the default remote ref will be used.

  • fail_on_empty (optional, default=False) – If True, raise an error if there are no files to commit, otherwise just return.

  • no_execute (optional, default=False) – If True, run the command but don’t commit the results.

  • **extra_args (optional) – Any extra API specific arguments or the commit.

Returns:

The result of the checkin command.

Raises:
  • CMSError.GIT_FAILURE – If there is a Git failure.

  • CMSError.INVALID_OPERATION – If the client CMS type is not supported.

checkout_files(*files: str, no_execute: bool = False) List[str]

Open files for editing on the client.

Parameters:
  • *files – The files to unlock.

  • no_execute (optional, default=False) – If True, run the command but don’t checkout the files.

Returns:

The result of the checkout command.

Raises:

CMSError.INVALID_OPERATION – If the client CMS type is not supported.

chmod_files(*files: str, mode: str, no_execute: bool = False) List[str]

Perform a chmod of the files.

Parameters:
  • *files – The files to chmod.

  • mode – The new mode to apply.

  • no_execute (optional, default=False) – If True, run the command but don’t commit the results.

Returns:

The result of the chmod command.

Raises:

CMSError.INVALID_OPERATION – If the client CMS type is not supported.

close() None

Close any persistent connections to the CMS system.

Returns:

Nothing.

property cms_info: str

A read-only property which returns the CMS info.

create_branch(name: str, /, *, branch_from: str = '', repo: str = '', branch_type: str = '', remote_branch: str = '', options: Dict[str, str] | None = None, no_execute: bool = False) List[str]

Create the specified branch.

Parameters:
  • name – The name of the branch to create.

  • branch_from (optional, default=None) – If None, use the current branch, otherwise use the branch specified.

  • repo (optional, default='') – If None, use the current repo, otherwise use the repo specified.

  • branch_type (optional, default='') – If None, use the default branch type, otherwise use the branch type specified.

  • options (optional, default='') – Any API specific options to use when creating the branch.

  • no_execute (optional, default=False) – If True, run the command but don’t revert the files.

Returns:

The result of the branch create command.

Raises:

CMSError.INVALID_OPERATION – If the client CMS type is not supported.

create_repo(repository: str, /, *, repo_type: str | None = None, no_execute: bool = False) List[str]

Create the specified repository.

Parameters:
  • repository – The name of the repository to create.

  • repo_type (optional, default=None) – If None, use the default repository type, otherwise use the type specified.

  • no_execute (optional, default=False) – If True, run the command but don’t revert the files.

Returns:

The result of the repository creation command.

Raises:

CMSError.INVALID_OPERATION – If the client CMS type is not supported.

delete_branch(name: str, /, *, no_execute: bool = False) List[str]

Delete the specified branch.

Parameters:
  • name – The name of the branch to delete.

  • no_execute (optional, default=False) – If True, run the command but don’t revert the files.

Returns:

The result of the branch delete command.

Raises:

CMSError.INVALID_OPERATION – If the client CMS type is not supported.

find(file_regex: str = '', /) List[str]

Search for files on the current client.

Parameters:

files_regex (optional, default='') – The regular expression to use to search for files.

Returns:

The list of files that were found.

Raises:

CMSError.INVALID_OPERATION – If the client CMS type is not supported.

get_changelist(name: str, /, *files: str, edit: bool = False) ChangeList

Get a ChangeList objects for the specified changelist.

Parameters:
  • name – The name of the changelist.

  • *files (optional) – Restrict the list based on the list of files.

  • edit (optional, default=False) – If True, return and editable ChangeList object.

Returns:

The changelist object.

get_changelists(*names: Iterable[str] | None, for_files: Iterable[str] | None = (), count: int | None = None) List[ChangeList]

Get a list of changelist objects for the specified changelist names.

Parameters:
  • *names – The list of changelist names.

  • for_files (optional, default=None) – If not none, restrict the list based on the list of files.

  • count (optional, default=None) – If not None, the number of objects to return, otherwise return all.

Returns:

The changelist objects.

Raises:

CMSError.INVALID_OPERATION – If the client CMS type is not supported.

get_clients(*args) List[Client]

Get the clients in the CMS system.

Parameters:

*args (optional) – Any API specific arguments to use.

Returns:

The list of clients.

Raises:

CMSError.INVALID_OPERATION – If the client CMS type is not supported.

get_cms_sys_value(var: str, /) str

Get a configuration value from the CMS system.

Parameters:

var – The configuration value to return.

Returns:

The value of the specified configuration item.

Raises:

CMSError.INVALID_OPERATION – If the client CMS type is not supported.

get_file(filename: str, /, *, checkout: bool = False) List[str]

Get the contents of the specified file.

Parameters:
  • filename – The name of the file for which to return the contents.

  • checkout (optional, default=False) – If True, update and checkout the files before retrieving the contents.

Returns:

The contents of the specified file.

Raises:

CMSError.INVALID_OPERATION – If the client CMS type is not supported.

get_filepath(file_name: str, /) Path

Get the full local OS path to the file.

Parameters:

file_name – The name of the file for which to return the path.

Returns:

The full local OS path to the file.

Raises:

CMSError.INVALID_OPERATION – If the client CMS type is not supported.

get_labels(*args) List[Label]

Get the labels in the CMS system.

Parameters:

*args (optional) – Any API specific arguments to use.

Returns:

The list of labels.

Raises:

CMSError.INVALID_OPERATION – If the client CMS type is not supported.

get_max_changelist(label: str = '', /) int

Get the highest changelist number.

Parameters:

label (optional, default='') – If not empty, limit the number by the specified label.

Returns:

The highest changelist number.

Raises:

CMSError.INVALID_OPERATION – If the client CMS type is not supported.

get_repos(*args) List[str]

Get the repositories in the CMS system.

Parameters:

*args (optional) – Any API specific arguments to use.

Returns:

The list of repositories.

Raises:

CMSError.INVALID_OPERATION – If the client CMS type is not supported.

get_server_connection() str

Get the name of the CMS server.

Returns:

The name of the CMS server.

Raises:

CMSError.INVALID_OPERATION – If the client CMS type is not supported.

get_user_record(username: str, /) Dict[str, str]

Get the CMS system information about the specified username.

Parameters:

username – The user for which to find the information.

Returns:

The information about the specified user.

Raises:

CMSError.INVALID_OPERATION – If the client CMS type is not supported.

get_users() List[str]

Get the list of users.

Returns:

The list of users.

Raises:

CMSError.INVALID_OPERATION – If the client CMS type is not supported.

integrate(source: str, target: str, /, *, no_execute: bool = False) List[str]

Integrate branches.

Parameters:
  • source – The source branch of the integration.

  • target – The target branch of the integration.

  • no_execute (optional, default=False) – If True, run the command but don’t commit the results.

Returns:

The result of the integration command.

Raises:

CMSError.INVALID_OPERATION – If the client CMS type is not supported.

list() List[str]

Get the local client files.

Returns:

The list of files on the current client.

Raises:

CMSError.INVALID_OPERATION – If the client CMS type is not supported.

lock_files(*files: str, no_execute: bool = False) List[str]

Place a lock on the files to prevent edits by other users.

Parameters:
  • *files – The files to lock.

  • no_execute (optional, default=False) – If True, run the command but don’t commit the results.

Returns:

The result of the lock files command.

Raises:

CMSError.INVALID_OPERATION – If the client CMS type is not supported.

property mapping: List[str]

A read-write property which returns and sets the client mapping.

merge(source_branch: str, /, *, checkin: bool = True, checkin_message: str | None = None, no_execute: bool = False) List[str]

Perform a merge from the specified branch.

Parameters:
  • source_branch – The source branch to use for the merge.

  • checkin (optional, default=True) – If True, checkin the changed files after the merge.

  • checkin_message (optional, default=None) – If None, generate a message for the merge.

  • no_execute (optional, default=False) – If True, run the command but don’t revert the files.

Returns:

The result of the merge command.

Raises:

CMSError.INVALID_OPERATION – If the client CMS type is not supported.

property name

A read-only property which returns the name of the client.

populate_branch(source: str, target: str, /, *, no_execute: bool = False) List[str]

Populate the target branch from the source.

Parameters:
  • source – The name of the source branch to use.

  • target – The name of the target branch to use.

  • no_execute (optional, default=False) – If True, run the command but don’t revert the files.

Returns:

The result of the populate command.

Raises:

CMSError.INVALID_OPERATION – If the client CMS type is not supported.

reconcile(*files: str, no_execute: bool = False) List[str]

Reconcile the workspace against the server and creates a changelist for the changes.

Parameters:
  • *files (optional) – The files to reconcile, otherwise all will be reconciled.

  • no_execute (optional, default=False) – If True, run the command but don’t commit the results.

Returns:

The result of the reconcile command.

Raises:

CMSError.INVALID_OPERATION – If the client CMS type is not supported.

remove(clean: CleanType = CleanType.none, /) List[str]

Delete the client object from the CMS system.

Parameters:

clean (optional, default=CleanType.none) – Specifies the amount of cleaning of the local file system.

Returns:

The result of the client removal command.

Raises:
  • CMSError.CLIENT_NOT_FOUND – If the client is not found.

  • CMSError.INVALID_OPERATION – If the client CMS type is not supported.

remove_files(*files: str, no_execute: bool = False) List[str]

Remove files from the client.

Parameters:
  • *files – The files to remove.

  • no_execute (optional, default=False) – If True, run the command but don’t commit the results.

Returns:

The result of the remove files command.

Raises:

CMSError.INVALID_OPERATION – If the client CMS type is not supported.

rename_remote_ref(old_name: str, new_name: str, /, *, no_execute: bool = False) List[str]

Rename a remote reference for a DVCS client.

Parameters:
  • old_name – The name of the remote reference to rename.

  • new_name – The new name of the remote.

  • no_execute (optional, default=False) – If True, run the command but don’t revert the files.

Returns:

The result of the rename command.

Raises:

CMSError.INVALID_OPERATION – If the client CMS type is not supported.

property root: Path

A read-only property which returns the root of the client.

property server_name
set_remote(branch: str, /, name: str = 'origin') List[str]

Set the remote for the specified branch.

Parameters:
  • branch – The branch for which to set the remote.

  • name (optional, default='origin') – The name of the remote.

Returns:

The result of the set remote command.

Raises:

CMSError.INVALID_OPERATION – If the client CMS type is not supported.

property streams: List[str]

A read-only property which returns the client stream list.

switch(branch: str, /, reset: bool = False) List[str]

Switch to the specified branch.

Parameters:
  • branch – The branch to which to switch.

  • reset (optional, default=False) – If True, reset the branch to the remote state.

Returns:

The result of the switch command.

Raises:

CMSError.INVALID_OPERATION – If the client CMS type is not supported.

property type

A read-only property which returns the CMS type.

unco_files(*files: str, unchanged_only: bool = False, no_execute: bool = False) List[str]

Revert open files for editing on the client.

Parameters:
  • *files (optional) – If provided, a subset of the files to revert, otherwise all will be reverted.

  • unchanged_only (optional, default=False) – If True, only revert unchanged files, otherwise all will be reverted.

  • no_execute (optional, default=False) – If True, run the command but don’t revert the files.

Returns:

The result of the revert command.

Raises:

CMSError.INVALID_OPERATION – If the client CMS type is not supported.

unlock_files(*files: str, no_execute: bool = False) List[str]

Remove a lock on the files to allow edits by other users.

Parameters:
  • *files – The files to unlock.

  • no_execute (optional, default=False) – If True, run the command but don’t commit the results.

Returns:

The result of the unlock files command.

Raises:

CMSError.INVALID_OPERATION – If the client CMS type is not supported.

update(*files: str, limiters: str | None = None, force: bool = False, parallel: bool = False, rebase: str | None = None, no_execute: bool = False) List[str]

Update the local client files.

Parameters:
  • *files (optional) – The files to update, otherwise all will be updated.

  • limiters (optional, default=None) – Arguments to limit the updated files.

  • force (optional, default=False) – If True update files that are already up-to-date.

  • parallel (optional, default=False) – If True update files in parallel.

  • rebase (optional, default=None) – If not None, rebase the changes onto the specified branch.

  • no_execute (optional, default=False) – If True, run the command but don’t commit the results.

Returns:

The list of files that were updated if provided by the underlying API.

Raises:

CMSError.INVALID_OPERATION – If the client CMS type is not supported.

class batcave.cms.ClientType(*values)

Bases: Enum

file = 1
git = 2
perforce = 3
class batcave.cms.FileChangeRecord(client: Client, filename: str, revision: str, type: str, changelist: str)

Bases: object

This class describes information about a file change.

client

The CMS Client object where this file change record is located.

Type:

batcave.cms.Client

filename

The name of the file.

Type:

str

revision

The revision number for this revision.

Type:

str

mod_type

The type of modification for the file.

changelist

The changelist number for the change record.

Type:

str

changelist: str
client: Client
filename: str
property fullname

A read-only property which returns the full name of the changed file.

revision: str
type: str
class batcave.cms.FileRevision(filename: str, revision: str, author: str, date: str, labels: List[str], description: str)

Bases: object

This class describes information about a file revision.

filename

The name of the file.

Type:

str

revision

The revision number for this revision.

Type:

str

description

The description for this revision.

Type:

str

author

The user that made this revision.

Type:

str

labels

A list of labels on this revision.

Type:

List[str]

author: str
date: str
description: str
filename: str
labels: List[str]
revision: str
class batcave.cms.InfoType(*values)

Bases: Enum

archive = 1
class batcave.cms.Label(name: str, label_type: LabelType, client: Client, /, *, description: str = '', selector: str = '', lock: bool = False)

Bases: object

Class to create a universal abstract interface for a CMS system label.

apply(*files: str, no_execute: bool = False) List[str]

Apply the label to a list of files.

Parameters:
  • files – The list of files to which to apply the label.

  • no_execute (optional, default=False) – If True, run the command but don’t commit the results.

Returns:

The result of the command from the CMS API.

Raises:

CMSError.INVALID_OPERATION – If the client CMS type is not supported.

property description

A read-only property which returns the description of the label.

lock() None

Set the label to read-only.

Returns:

Nothing.

Raises:

CMSError.INVALID_OPERATION – If the client CMS type is not supported.

property name

A read-only property which returns the name of the label.

remove(*files: str, no_execute: bool = False) List[str]

Remove the label from the list of files.

Parameters:
  • files – The list of files to which to apply the label.

  • no_execute (optional, default=False) – If True, run the command but don’t commit the results.

Returns:

The result of the command from the CMS API.

Raises:

CMSError.INVALID_OPERATION – If the client CMS type is not supported.

property root

A read-only property which returns the root for the label.

property type

A read-only property which returns the CMS type.

unlock() None

Set the label to read-write.

Returns:

Nothing.

Raises:

CMSError.INVALID_OPERATION – If the client CMS type is not supported.

class batcave.cms.LabelType(*values)

Bases: Enum

file = 1
project = 2
class batcave.cms.LineStyle(*values)

Bases: Enum

crlf = 8
lf = 7
local = 1
mac = 3
native = 6
share = 5
unix = 2
win = 4
class batcave.cms.ObjectType(*values)

Bases: Enum

changelist = 1
string = 2
batcave.cms.create_client_name(*, prefix: str | None = None, suffix: str | None = None, sep: str = '_', license_plate: bool = False) str

Automatically create a client name from the user and hostname.

batcave.cms.prefix

If not None, the prefix for the client.

Type:

optional, default=None

batcave.cms.suffix

If not None, the suffix for the client.

Type:

optional, default=None

batcave.cms.sep

The separator for the different pieces of the name.

Type:

optional, default=’_’

batcave.cms.license_plate

If not False, adds a random number to the end of the name. Will be appended after the suffix.

Type:

optional, default=False

Returns:

Returns the client name.

batcave.cms.validate_type(ctype: ClientType, /) None

Determine if the specified CMS type is valid.

Parameters:

ctype – The CMS type.

Returns:

Nothing.

Raises

CMSError.INVALID_TYPE: If the CMS type is not valid.

batcave.cms.walk_git_tree(tree: Tree, /, *, parent: str | None = '') Generator[Tuple, Tuple, None]

Walk the git tree similar to os.walk().

batcave.cms.tree

The git tree to walk.

batcave.cms.parent

Use a different parent than the root of the tree.

Type:

optional, default=None

Yields:
Runs like an iterator which yields tuples of

(the new parent, the tree names, the git blobs)

batcave.commander module

This module provides a simplified interface to the standard argparse module.

class batcave.commander.Argument(*names, **options)

Bases: object

This is a simple container class to encapsulate an argument definition passed to ArgumentParser.add_argument().

class batcave.commander.Commander(description: str, arguments: ~typing.Sequence[~batcave.commander.Argument] = (), subparsers: ~typing.Iterable[~batcave.commander.SubParser] = (), subparser_common_args: ~typing.Sequence[~batcave.commander.Argument] = (), default: ~typing.Callable | None = None, parents: ~typing.Sequence[~argparse.ArgumentParser] = (), parse_extra: bool = False, extra_var_sep: str = ':', convert_extra: bool = True, version: ~batcave.version.AppVersion | None = None, version_style: ~batcave.version.VersionStyle = VersionStyle.one_line, formatter_class: ~typing.Type[~argparse.HelpFormatter] = <class 'argparse.ArgumentDefaultsHelpFormatter'>)

Bases: object

This class provides a simplified interface to the argparse.ArgumentParser class.

execute(argv: Sequence[str] | None = None, use_args: Namespace | None = None) Any

Parse the command line and call the command_runner.

Parameters:
  • argv (optional, default=None) – The arguments to pass to the parser if use_args is None, otherwise sys.argv will be used.

  • use_args (optional, default=None) – The arguments to pass to the parser, otherwise argv will be used.

Returns:

The result of the called command_runner.

parse_args(argv: Sequence[str] | None = None, err_msg: str = 'No command specified', raise_on_error: BaseException | None = None) Namespace

Parse the command line.

Parameters:
  • argv (optional, default=None) – The arguments to pass to the parser, otherwise sys.argv will be used.

  • err_msg (optional, default='No command specified') – The error message to use if a bad subcommand is requested.

  • raise_on_error (optional, default=None) – If not None, use the value as the error to be raised on a failure.

Returns:

The parsed argument Namespace.

Raises:

The value of raise_on_error if not False.

class batcave.commander.SubParser(subcommand: str, command_runner: ~typing.Callable, arguments: ~typing.Sequence[~batcave.commander.Argument] = <factory>)

Bases: object

This is a simple container class to encapsulate a subparser definition.

subcommand

The subcommand name for the subparser.

Type:

str

command_runner

The function which runs the commands for the subparser.

Type:

Callable

arguments

A list of arguments for the subparser.

Type:

optional, default=None

arguments: Sequence[Argument]
command_runner: Callable
subcommand: str

batcave.configmgr module

This module provides utilities for managing configurations.

class batcave.configmgr.ConfigCollection(name: PathName, /, *, create: bool = False, suffix: str = '_config.xml')

Bases: object

This is a container class to hold a collection of configurations read from a file.

INCLUDE_CONFIG_TAG

The configuration tag which indicates an include file.

_CURRENT_CONFIG_SCHEMA

The default DataSource schema to use.

_MASK_MISSING

The parameter to indicate that child configurations should be ignored.

_PARAMS_CONFIGURATION

The configuration section which is used as configuration parameters for the collection.

_PARENT_CONFIGURATION

The parameter to indicate the parent configuration name.

INCLUDE_CONFIG_TAG = 'include'
add(name: str, /) str

Add an item to the configuration collection.

Parameters:

name – The name of the item to add.

Returns:

The value of the added item.

close() None

Close the underlying data source.

property name

A read-only property which returns the name of the configuration.

class batcave.configmgr.Configuration(config_source: DataSource, name: str, /, *, parent: Configuration | None = None, include: Configuration | None = None)

Bases: object

This is a container class to hold an individual configuration in a collection.

property name

A read-only property which returns the name of the configuration.

exception batcave.configmgr.ConfigurationError(err_obj: BatCaveError, /, **variables)

Bases: BatCaveException

Configuration Exceptions.

BAD_FORMAT

The configuration file format is invalid.

BAD_SCHEMA

The configuration schema is not supported.

CONFIG_NOT_FOUND

The specified configuration file was not found.

BAD_FORMAT = BatCaveError(code=1, msg=<string.Template object>)
BAD_SCHEMA = BatCaveError(code=2, msg=<string.Template object>)
CONFIG_NOT_FOUND = BatCaveError(code=3, msg=<string.Template object>)

batcave.data module

This module provides utilities for managing data sources.

Data source definitions:
TEXT

source - a text file with ‘>NAME’ delimiting tables table - a list of rows row - a line of the format column1:value1|column2:value2 column - delimited part of the line

INI

source - an ini file

table - an ini section of the form::

[TABLENAME] ROWS: 1,…,N

row - an ini section of the form::

[TABLENAME ROW N] col1: val1 col2: val2

column - a section option

PICKLE

source - a Python pickle file containing a single dictionary table - a member of the top level dictionary which is a list of rows row - a dictionary of column:value pairs

XML_SINGLE

This format is a kludge to support the old RCFile format source - an XML file with the top level element the name of the datasource table - there is only one table which has the same name as the top level element

row - an XML element of the form::

<environment name=COL-NAME-VALUE> COLUMNS </environment>

column - an XML element of the form::

<COL-NAME>COL-VALUE</COL-NAME>

XML_FLAT

source - an XML file with the top level element the name of the datasource table - a collection of XML elements

row - an XML element of the form::

<TABLE-NAME COL-NAME=”COL-VAL” />

column - an XML element attribute

XML

source - an XML file with the top level element the name of the datasource

table - an XML element of the form::

<TABLE name=”TABLE-NAME”> ROWS </TABLE>

row - an XML element of the form::

<ROW> COLUMNS </ROW>

column - an XML element of the form::

<COL-NAME>COL-VALUE</COL-NAME>

batcave.data.SourceType

The source providers supported by the DataSource class.

Type:

Enum

exception batcave.data.DataError(err_obj: BatCaveError, /, **variables)

Bases: BatCaveException

Data related Exceptions.

BAD_COLUMN

The column specified was not found.

BAD_ROOT

The root element for the XML data source was not the one requested.

BAD_SCHEMA

The data source schema does not match the one requested.

BAD_TABLE

The requested table was not found.

BAD_URL

The URL specified does not contain a valid data source.

FILE_OPEN

Error opening the data source file.

INVALID_OPERATION

The specified data source type does not support the requested operation.

INVALID_TYPE

An invalid data source type was specified.

BAD_COLUMN = BatCaveError(code=1, msg=<string.Template object>)
BAD_ROOT = BatCaveError(code=2, msg=<string.Template object>)
BAD_SCHEMA = BatCaveError(code=3, msg=<string.Template object>)
BAD_TABLE = BatCaveError(code=4, msg=<string.Template object>)
BAD_URL = BatCaveError(code=5, msg=<string.Template object>)
FILE_OPEN = BatCaveError(code=6, msg=<string.Template object>)
INVALID_OPERATION = BatCaveError(code=7, msg=<string.Template object>)
INVALID_TYPE = BatCaveError(code=8, msg="Invalid data source type. Must be one of: ['text', 'ini', 'pickle', 'xml']")
class batcave.data.DataRow(data_type: SourceType, raw: Any, parent: Any, /)

Bases: object

Class to create a universal abstract interface for a data row.

del_column(col: str) None

Delete the named column from the row.

Parameters:

col – The name of the column to delete.

Returns:

Nothing.

delete() None

Delete this data row.

Returns:

Nothing.

get_columns() List[str]

Get all the columns from the row.

Returns:

The list of columns in the data row.

get_value(col: str, /) str

Get the value of the specified column.

Parameters:

col – The name of the column from which to retrieve the value.

Returns:

The value of the column.

has_col(col: str, /) bool

Determine if the named column exists in the row.

Parameters:

col – The name of the column to search for.

Returns:

Returns True if the named column exists in the data source, False otherwise.

property raw

A read-only property which returns the raw contents of the data row.

setvalue(col: str, value: str, /) None

Set the value of the specified column.

Parameters:
  • col – The name of the column for which to set the value.

  • value – The value to set for the column.

Returns:

Nothing.

property type

A read-only property which returns the type of the data source.

class batcave.data.DataSource(data_type: SourceType, connect_info: PathName, /, name: str, *, schema: int, create: bool = False)

Bases: object

Class to create a universal abstract interface for a data source.

INFO_TABLE

The table in the data source which has info about the source.

_SCHEMA_DATA

The row which contains the schema version.

INI_ROW_LIST_OPT

The INI file section which contains the rows.

INI_ROW_TAG

The INI file tag to mark a row.

_TEXT_TABLE_DELIMITER

The table delimiter for a text file.

_TEXT_VAL_DELIMITER

The value delimiter for a text file.

_XML_TABLE_TAG

The XML file tag to denote a table.

_XML_TABLE_NAME_ATTRIBUTE

The XML file attribute to denote a table name.

_XML_SINGLE_COL_NAME

The XML file attribute to denote a column name.

INFO_TABLE = 'DataSourceInfo'
INI_ROW_LIST_OPT = 'ROWS'
INI_ROW_TAG = ' ROW '
add_table(name: str, /) DataTable

Create a new table with the specified name.

Parameters:

name – The name of the table to add.

Returns:

The created table.

Raises:

DataError.INVALID_OPERATION – If the data source type does not support adding a table.

close() None

Close the data source.

Returns:

Nothing.

commit() None

Commit any changes in memory to the source.

Returns:

Nothing.

property dict_repr: dict

A read-only property which returns a the data source as a dictionary.

property filename

A read-only property which returns the file name of the data source.

get_table(name: str, /) DataTable

Get the requested data table.

Parameters:

name – The name of the table to return.

Returns:

The requested data table.

Raises:

DataError.BAD_TABLE – If the requested table is not found.

get_tables() List[DataTable]

Get all the tables from the data source.

Returns:

The list of table in the data source.

has_table(name: str, /) bool

Determine if the named table exists in the data source.

Parameters:

name – The name of the table to search for.

Returns:

Returns True if the named table exists in the data source, False otherwise.

property name

A read-only property which returns the name of the data source.

property schema: int

A read-only property which returns the schema value of the data source.

property type

A read-only property which returns the type of the data source.

class batcave.data.DataTable(data_type: SourceType, name: str, raw: Any, parent: Any, /)

Bases: object

Class to create a universal abstract interface for a data table.

The _parent meaning changes based on the source type:

TEXT = absolute path to the data directory PICKLE = top level dictionary XML_* = the parent element

_INI_ROW_FORMAT

The format for an INI file row.

_XML_ROW_TAG

The XML file tag to denote a row.

_XML_SINGLE_ROW_TAG

The XML file tag to denote a row (xml_single data source).

add_row(**values) DataRow

Create a new row with the specified values.

Parameters:

**values – A dictionary of the value to add.

Returns:

Nothing.

del_row(col: str, value: str, /) None

Delete the rows with the specified column value.

Parameters:
  • col – The column to select for.

  • value – The column value to select for.

Returns:

Nothing.

get_rows(col: str | None = None, value: str | None = None) List[DataRow]

Get all the rows matching the specified selector.

Parameters:
  • col (optional, default=None) – The column to select for if not None.

  • value (optional, default=None) – The column value to select for if not None.

Returns:

The list of rows matching the specified selector.

property name

A read-only property which returns the name of the data table.

property raw

A read-only property which returns the raw contents of the data table.

property type

A read-only property which returns the type of the data source.

class batcave.data.SourceType(*values)

Bases: Enum

ini = 2
pickle = 3
text = 1
xml = 4

batcave.expander module

This module provides utilities for managing file expansions.

An instantiation of this class will convert an XML into the procedure object:

<procedure schema = "{schema-version}" >
    <header>HEADER</header>

    <flags>
        <FlagName question="Some Question">True|False, Yes|No,  1,0</FlagName>
    </flags>

    <environments>
        <common>
            <VariableName1>Variable Value 1</VariableName1>
        </common>
        <Environment1>
            <VariableName2>Variable Value 2</VariableName1>
        <Environment2
    </environments>

    <directories>
        <directory>Directory - Path</directory>
    </directories>

    <steps>
        <step condition="Optional Condition Expression" vars="var1=val1, var2=val2", repeat="var=val1, val2">
            "Multi-Step Text"
            <step>Step Text</step>
            <step import="Library Step Name">Alternate Step Text</step>
        </step>
    </steps>

    <step-library>
        <step name="Import Name" />
    </step-library>
</procedure>
class batcave.expander.Expander(*, var_dict: Dict[str, str] | None = None, var_props: Any = None, prelim: str = '{var:', postlim: str = '}')

Bases: object

Class to handle interpolation of strings and files.

_PRELIM_DEFAULT

The prefix for a variable to be expanded.

_POSTLIM_DEFAULT

The suffix for a variable to be expanded.

evaluate_expression(expression: str, /) bool

Evaluate an expression in the expansion.

Parameters:

expression – The expression to evaluate.

Returns:

The evaluated expression.

Raises:

ExpanderError.NO_REPLACEMENT – If no replacement was found for the requested expansion variable.

expand(thing: Any, /) Any

Perform an expansion on a Python object.

Parameters:

thing – The object on which to perform an expansion.

Returns:

The object with expansions performed.

Raises:
  • ExpanderError.NO_POST_DELIMITER – If the closing delimiter was not found.

  • ExpanderError.NO_REPLACEMENT – If no replacement was found for the requested expansion variable.

expand_directory(source_dir: PathName, /, target_dir: PathName | None = None, *, ignore_files: Sequence[str] = (), no_expand_files: Sequence[str] = (), err_if_exists: bool = True) None

Perform an expansion on an entire directory tree.

Parameters:
  • source_dir – The name of the directory on which to perform the expansions.

  • target_dir (optional, default=None) – The name of the output directory for the expansion results if not None, otherwise the current directory is used.

  • ignore_files (optional, default=None) – A list of files for which should be ignored and will not be in the output directory.

  • no_expand_files (optional, default=None) – A list of files which expansion should not be performed but which will be copied to the output directory.

  • err_if_exists (optional, default=True) – If True, raise an error if the output directory exists.

Returns:

Nothing.

expand_file(in_file: PathName, out_file: PathName, /) None

Perform an expansion on an entire file.

Parameters:
  • in_file – The name of the file on which to perform the expansions.

  • out_file – The name of the output file for the expansion results.

Returns:

Nothing.

exception batcave.expander.ExpanderError(err_obj: BatCaveError, /, **variables)

Bases: BatCaveException

Expansion Exceptions.

NO_POST_DELIMITER

No postfix delimiter was found.

NO_REPLACEMENT

No replacement was found for the specified variable

NO_POST_DELIMITER = BatCaveError(code=1, msg=<string.Template object>)
NO_REPLACEMENT = BatCaveError(code=2, msg=<string.Template object>)
class batcave.expander.Formatter(output_format: OutputFormat, /)

Bases: object

Class to hold formatting information.

The prefix to indicate a hyperlink during formatting.

property bol: str

A read-only property which returns the beginning of line formatting.

Format the hyperlinks in a line.

Parameters:

line – The line for which to format hyperlinks.

Returns:

The formatted line.

Raises:

ProcedureError.BAD_FORMAT – If the requested format is not valid.

increment() None

Increment the counter at the current indentation level.

Returns:

Nothing.

indent() None

Increment the indentation level.

Returns:

Nothing.

outdent() None

Decrement the indentation level.

Returns:

Nothing.

class batcave.expander.OutputFormat(*values)

Bases: Enum

csv = 3
html = 2
text = 1
class batcave.expander.Procedure(proc_file: PathName, /, *, output_format: OutputFormat = OutputFormat.html, variable_overrides: Dict[str, str] | None = None)

Bases: object

Class to create a universal abstract interface for a procedure.

_SCHEMA_ATTR

The XML tag which contains the schema version.

_REQUIRED_PROCEDURE_SCHEMA

The schema supported by this class.

_HEADER_TAG

The XML tag which indicates the procedure header.

_FLAGS_TAG

The XML tag which indicates the procedure flags.

_DIRECTORIES_TAG

The XML tag which indicates the procedure directories.

_ENVIRONMENTS_TAG

The XML tag which indicates the procedure environments.

_STEPS_TAG

The XML tag which indicates the procedure steps.

_LIBRARY_TAG

The XML tag which indicates the procedure step library.

_COMMON_ENVIRONMENT

The XML tag which indicates the procedure common environment.

_ENVIRONMENT_VARIABLE

The XML tag which indicates an environment variable.

dump() Dict[str, str | Sequence | Dict]

Dump out the procedure contents.

Returns:

The contents of the procedure as an ordered dictionary.

expand(text: str, /) str

Expand the Procedure.

Parameters:

text – The text of the procedure.

Returns:

The expanded procedure.

Raises:

ProcedureError.EXPANSION_ERROR – If there is an missing value expansion error.

expand_directories(env: str, /, destination_root: PathName, *, source_root: PathName = PosixPath('.'), err_if_exists: bool = True) None

Perform variable expansion on the directories defined in the procedure.

Parameters:
  • env – The environment for which to expand the directories.

  • destination_root – That destination directory for the expansion.

  • source_root (optional, default=None) – Defined for recursion.

  • err_if_exists (optional, default=True) – If True, raise an error if destination_root exists.

Returns:

Nothing.

format(text: str, /) str

Format an output line including hyperlinks.

Parameters:

text – The line of text to format.

Returns:

The formatted output line.

realize(env: str, /) str

Realize the procedure for the specified environments based on the variables.

Parameters:

env – The environment for which to realize the procedure.

Returns:

The realized procedure.

Raises:

ProcedureError.BAD_FORMAT – If the format type is not defined.

realize_step(step: Step, /) str

Realize a step in the procedure.

Parameters:

step – The step to realize.

Returns:

The realized step.

Raises:

ProcedureError.BAD_LIBRARY – If the step specifies a library that is not defined.

setup_expander(environment: str, /) None

Setup the Expander for the requested environment.

Parameters:

environment – The environment for which to setup the expander.

Returns:

Nothing.

Raises:

ProcedureError.BAD_ENVIRONMENT – If the requested environment is not defined.

exception batcave.expander.ProcedureError(err_obj: BatCaveError, /, **variables)

Bases: BatCaveException

Procedure Exceptions.

BAD_ENVIRONMENT

The requested environment is not valid.

BAD_FLAG

The specified flag value is not value.

BAD_FORMAT

The requested output format is not valid.

BAD_LIBRARY

The requested library is not valid.

BAD_SCHEMA

The procedure schema is not supported.

EXPANSION_ERROR

The was an unspecified error during expansion.

BAD_ENVIRONMENT = BatCaveError(code=1, msg=<string.Template object>)
BAD_FLAG = BatCaveError(code=2, msg=<string.Template object>)
BAD_FORMAT = BatCaveError(code=3, msg=<string.Template object>)
BAD_LIBRARY = BatCaveError(code=4, msg=<string.Template object>)
BAD_SCHEMA = BatCaveError(code=5, msg=<string.Template object>)
EXPANSION_ERROR = BatCaveError(code=6, msg=<string.Template object>)
class batcave.expander.Step(step_def: Element, /)

Bases: object

Class to create a universal abstract interface for a procedure step.

NAME_ATTR

The XML attribute to indicate the step name.

_CONDITION_ATTR

The XML attribute to indicate the step condition.

_IMPORT_ATTR

The XML attribute to indicate the step import.

_REPEAT_ATTR

The XML attribute to indicate the step repeat condition.

_VARS_ATTR

The XML attribute to indicate the step variables.

NAME_ATTR = 'name'
dump() List

Dump out the step contents.

Returns:

The contents of the step as an list.

batcave.expander.file_expander(in_file: PathName, out_file: PathName, /, *, var_dict: Dict[str, str] | None = None, var_props: Any = None) None

Quick function for one-time file expansion.

Parameters:
  • in_file – The input file.

  • out_file – The output file.

  • var_dict (optional, default=None) – If not None, provides a dictionary of expansion values.

  • var_props (optional, default=None) – If not None, provides an object with properties to be used as expansion values.

Returns:

Nothing.

batcave.expander.parse_flag(flag: str, /) Any

Evaluate a parsing flag.

Parameters:

flag – The flag to evaluate.

Returns:

The evaluated value for the flag.

Raises:

ProcedureError.BAD_FLAG – If the evaluated flag is not of type bool.

batcave.fileutil module

This module provides utilities for working with files.

batcave.fileutil.ConversionMode

The conversion modes for the eol_convert function.

Type:

Enum

batcave.fileutil.PACKER_CLASSES

A mapping of file compression extensions to the classes that create them.

Type:

dict

batcave.fileutil.COMPRESSION_TYPE

A mapping of file compression extensions to compression types.

Type:

dict

class batcave.fileutil.BatCaveBZ2File(filename, mode='r', *, compresslevel=9)

Bases: BZ2File, CompressedFile

Add CompressedFile class methods to the BZ2File class.

class batcave.fileutil.BatCaveGzipFile(filename=None, mode=None, compresslevel=9, fileobj=None, mtime=None)

Bases: GzipFile, CompressedFile

Add CompressedFile class methods to the GzipFile class.

class batcave.fileutil.CompressedFile(filename: PathName, /, **_unused_attr)

Bases: object

Class to add support for compressed file types which are missing some methods.

namelist() Tuple[str]

Return the name of the file as the first item in a tuple.

Returns:

The name of the file.

class batcave.fileutil.ConversionMode(*values)

Bases: Enum

to_dos = 2
to_unix = 1
exception batcave.fileutil.ConvertError(err_obj: BatCaveError, /, **variables)

Bases: BatCaveException

File Conversion Exceptions.

BACKUP_EXISTS

The backup file already exists.

BACKUP_EXISTS = BatCaveError(code=1, msg=<string.Template object>)
exception batcave.fileutil.PackError(err_obj: BatCaveError, /, **variables)

Bases: BatCaveException

File Packing Exceptions.

INVALID_TYPE

An invalid archive type was specified.

NO_FILES

No files were found to pack into the archive.

INVALID_TYPE = BatCaveError(code=1, msg=<string.Template object>)
NO_FILES = BatCaveError(code=2, msg='No files to add')
batcave.fileutil.eol_convert(filename: PathName, mode: ConversionMode, /, *, backup: bool = True) None

Perform end-of-line conversions from Windows to UNIX or vice versa.

batcave.fileutil.filename

The file to convert.

batcave.fileutil.mode

The direction of the conversion. Must be a member of ConversionMode.

batcave.fileutil.backup

If True, creates a backup of filename as filename.bak.

Type:

optional, default=True

Returns:

Nothing.

Raises:

ConvertError.BACKUP_EXISTS – If backup is True and the backup file already exists.

batcave.fileutil.pack(archive_file: PathName, items: Iterable, /, item_location: PathName | None = None, *, archive_type: str = '', ignore_empty: bool = True) None

Create a compressed archive.

batcave.fileutil.archive_file

The name of the archive file to create.

batcave.fileutil.items

The items to put in the archive.

batcave.fileutil.item_location

The root location of the items. If None, the current directory

Type:

optional, default=None

batcave.fileutil.archive_type

the type of archive to create. If None, the type is derived from the archive_file extension.

Type:

optional, default=None

batcave.fileutil.ignore_empty

If True, allows creating an empty archive.

Type:

optional, default=True

Returns:

Nothing.

Raises:

PackError.NO_FILES – If ignore_empty is False and there are no files to place in the archive.

batcave.fileutil.prune(directory: PathName, age: int, exts: Iterable[str] | None = None, force: bool = False, ignore_case: bool = False, log_handle: str | None = None) None

Prune a directory of files or directories based on age or count.

Parameters:
  • age – The number days after which to prune files.

  • directory – The directory from which to prune files.

  • exts (optional, default=all) – The extensions to prune.

  • force (optional, default=False) – If true, ignore permissions restricting removal.

  • ignore_case (optional, default=False) – If true, ignore case in extensions.

  • log_handle (optional, default=None) – If not None, status will be logged to the specified log handle.

Returns:

Nothing.

batcave.fileutil.slurp(filename: PathName, /) List[str]

Return all the lines of a file as a list.

Parameters:

filename – The filename to return the lines from.

Returns:

The list of lines from the file.

batcave.fileutil.spew(filename: PathName, outlines: Iterable, /) None

Write the list of lines to a file.

Parameters:
  • filename – The filename to which to write the lines.

  • outlines – The lines to write.

Returns:

Nothing.

batcave.fileutil.unpack(archive_file: PathName, dest: PathName | None = None, /, *, archive_type: str = '') None

Extract the contents of a compressed file.

batcave.fileutil.archive_file

The name of the archive file

batcave.fileutil.dest

The root location to which to extract. If None, the current directory

Type:

optional, default=None

batcave.fileutil.archive_type

the type of archive being extracted. If None, the type is derived from the archive_file extension.

Type:

optional, default=None

Returns:

Nothing.

Raises:

PackError.INVALID_TYPE – If the archive_type is unknown.

batcave.gui module

This module provides a simplified interface to the PyQt5 module.

batcave.gui.MessageType

The message types supported by the MessageBox class.

Type:

Enum

class batcave.gui.BatCaveBaseGUI(_unused_parent: QWidget | None = None, title: str = '', icon: QIcon | None = None)

Bases: object

The base class for the simplified GUI support.

This class cannot be used by itself but must be paired with another PyQt class.

closeEvent(event: QCloseEvent, /) None

Overload of standard Qt method called when the object is closed.

Returns:

Nothing.

redirect_output(widget: QWidget, /) None

Redirect stdout and stderr to the specified widget.

Returns:

Nothing.

validate() bool

Run the validators for the object.

Returns:

True if all the validators are True, False otherwise.

class batcave.gui.BatCaveDialog

Bases: QDialog, BatCaveBaseGUI

This class provides functionality for a dialog box window.

accept() bool

Overload of standard Qt method called when the dialog is accepted.

Returns:

The result of the validate method.

onGetDirectory() None

Show a simplified directory dialog.

Returns:

Nothing.

onGetFile(file_filter: str | None = None, /) None

Show a simplified file dialog.

Parameters:

file_filter (optional, default=None) – The file filter to pass to the standard Qt file dialog.

Returns:

Nothing.

class batcave.gui.BatCaveGUIOutput(widget: QWidget, /)

Bases: object

Class to manage output to a widget.

write(output: str, /) None

Write to the widget.

Parameters:

output – The text to write to the widget.

Returns:

Nothing.

class batcave.gui.BatCaveMainWindow(parent: QWidget | None = None, title: str = '', version: AppVersion | None = None, icon: QIcon | None = None)

Bases: QMainWindow, BatCaveBaseGUI

This class provides functionality for a main window.

OnAbout() None

Show the about box.

Returns:

Nothing.

class batcave.gui.BatCaveValidator(callback: Callable, false_val: Any, how: str, what: str)

Bases: object

Class to support control validation.

class batcave.gui.Brief(instr: str | Template = '', transform: str = '', **variables)

Bases: MsgStr

Class to extend the MsgStr class for handling short window messages.

_messages

The different message types.

Type:

Dict[str, str | string.Template]

class batcave.gui.Message(instr: str | Template = '', transform: str = '', **variables)

Bases: MsgStr

Class to extend the MsgStr class for handling messages.

_messages

The different message types.

Type:

Dict[str, str | string.Template]

class batcave.gui.MessageBox(parent: QWidget | BatCaveBaseGUI, message: str, /, msg_type: MessageType = MessageType.info, *, detail: str = '', image: str | None = None)

Bases: QMessageBox

This class provides functionality for a simplified message box.

_MESSAGE_ICONS

The supported message box icons.

class batcave.gui.MessageType(*values)

Bases: Enum

about = 1
error = 5
info = 2
question = 3
results = 6
warning = 4
class batcave.gui.Title(**kwargs)

Bases: MsgStr

Class to extend the MsgStr class for handling MessageBox titles.

_messages

The different message types.

Type:

Dict[str, str | string.Template]

batcave.gui.find_image(name: str, /) QImage

Locate the image based on whether the application has been frozen.

Parameters:

name – The name of the image to locate.

Returns:

The image object.

batcave.iispy module

This module provides a Pythonic interface to work with Internet Information Server.

exception batcave.iispy.AppCmdError(err_obj: BatCaveError, /, **variables)

Bases: BatCaveException

appcmd Exceptions.

APPCMD_ERROR

There was an error executing appcmd.exe.

APPCMD_ERROR = BatCaveError(code=1, msg=<string.Template object>)
exception batcave.iispy.IISAdvancedLogError(err_obj: BatCaveError, /, **variables)

Bases: BatCaveException

IIS AdvancedLog Exceptions.

BAD_FIELD

There was an attempt to add a non-existent field.

NOT_INSTALLED

Advanced logging is not installed.

BAD_FIELD = BatCaveError(code=1, msg=<string.Template object>)
NOT_INSTALLED = BatCaveError(code=2, msg='IIS Advanced Logging is not installed on the target system')
class batcave.iispy.IISAdvancedLogger(path: PathName | None, /, log_type: str, set_location: str, hostname: str | None = None, remote_powershell: bool | None = None)

Bases: IISConfigurationSection

Class to create a universal abstract interface for the IIS advanced logger.

add_field(field_id: str, field_values: Dict | None = None, /) None

Add a field to the advanced logger configuration.

Parameters:
  • field_id – The field ID to add.

  • field_values (optional, default={}) – Any field values to add to override the default values.

Returns:

Nothing.

add_log(log_name: str, /, log_values: Dict | None = None, fields: Dict | None = None) None

Add a log definition to the advanced logger configuration.

Parameters:
  • log_name – The name of the log to add.

  • log_values (optional, default=None) – Any log values to add to override the default values.

  • fields (optional, default=None) – Any fields to add to the log definition.

Returns:

Nothing.

add_logfield(log_name: str, field_name: str, field_values: Dict | None = None, /) None

Add a field to an advanced logger log definition.

Parameters:
  • log_name – The name of the log to which to add the field.

  • field_name – The name of the field to add.

  • field_values (optional, default=None) – Any fields values to add to the field.

Returns:

Nothing.

has_field(field_id: str, /) bool

Determine if the advanced logger configuration has the specified field.

Parameters:

field_id – The field ID for which to search.

Returns:

True if the advanced logger configuration has the specified field, False otherwise.

rm_field(field_id: str, /) None

Remove a field from the advanced logger configuration.

Parameters:

field_id – The field ID to remove.

Returns:

Nothing.

rm_log(log_name: str, /) None

Remove a log definition to the advanced logger configuration.

Parameters:

log_name – The name of the log to remove.

Returns:

Nothing.

exception batcave.iispy.IISConfigurationError(err_obj: BatCaveError, /, **variables)

Bases: BatCaveException

IIS Configuration Exceptions.

PARSE_ERROR

There was an error locating the specified configuration section.

PARSE_ERROR = BatCaveError(code=1, msg=<string.Template object>)
class batcave.iispy.IISConfigurationSection(name: str, /, path: PathName | None, set_location: str | None = None, hostname: str | None = None, remote_powershell: bool | None = None)

Bases: object

Class to create a universal abstract interface for an IIS configuration section.

add_collection_member(collection: str, /, properties: Dict, changes: Dict | None) None

Add the specified properties to the collection.

Parameters:
  • collection – The collection to which to add the properties.

  • properties – The properties to add to the collection.

  • changes – Changes to make to the properties before adding.

Returns:

Nothing.

add_property(prop_name: str, value: str, /) None

Add a property with the specified value.

Parameters:
  • prop_name – The name of the property to add.

  • value – The value of the property to add.

Returns:

Nothing.

has_collection_member(collection: str, /, filter_on: str, value: str) bool

Determine if a collection has a specified member.

Parameters:
  • collection – The collection to search.

  • filter_on – Then member to filter on.

  • value – The value for which to search.

Returns:

True if the collection has the specified member, False otherwise.

rm_collection_member(collection: str, /, selectors: Dict) None

Remove the specified properties from the collection.

Parameters:
  • collection – The collection from which to remove the properties.

  • selectors – The selectors to identify the properties.

Returns:

Nothing.

rm_property(prop_name: str, value: str | None = None, /) None

Remove a property conditionally with the specified value.

Parameters:
  • prop_name – The name of the property to remove.

  • value (optional, default=None) – If not None, only remove the property if it has the specified value.

Returns:

Nothing.

class batcave.iispy.IISInstance(hostname: str | None = None, /, *, remote_powershell: bool | None = None)

Bases: object

Class to create a universal abstract interface for an IIS instance.

_IIS_TYPE_MAP

Maps IIS object types to appcmd subcommands.

property advanced_logger: IISAdvancedLogger

A read-only property which returns the advanced logger object from the IIS instance.

create_virtual_dir(vdir_name: str, /, vdir_location: PathName, website: str) VirtualDirectory

Create the specified virtual directory in the IIS instance.

Parameters:
  • vdir_name – The name of the virtual directory to create.

  • vdir_location – The physical path for the virtual directory.

  • website – The website for which to create the virtual directory.

Returns:

The newly created virtual directory.

create_webapp(app_name: str, app_dir: PathName, website: str, pool: WebApplicationPool | None = None) WebApplication

Create the specified web application in the IIS instance.

Parameters:
  • app_name – The name of the web application to create.

  • app_dir – The physical path for the web application.

  • website – The website for which to create the virtual directory.

  • pool (optional, default=None) – If not None, the application pool to which to assign the web application.

Returns:

The newly created web application.

create_webapp_pool(pool_name: str, /) WebApplicationPool

Create the specified web application pool in the IIS instance.

Parameters:

pool_name – The name of the web application to create.

Returns:

The newly created web application pool.

exists() bool

Test for existence of the IIS instance.

Returns:

True if the instance exists, False, otherwise.

get_advanced_logger(path: PathName | None = None, log_type: str = 'server', set_location: str = 'apphost') IISAdvancedLogger

Get the advanced logger object from the IIS instance.

Parameters:
  • path (optional, default=None) – If not None, return the advanced logger from the specified path.

  • log_type (optional, default='server') – Use the specified set location to search for the advanced logger.

  • set_location (optional, default='apphost') – Use the specified set location to search for the advanced logger.

Returns:

The specified advanced logger.

get_configuration_section(name: str, /, path: PathName | None = None, set_location: str = 'apphost') IISConfigurationSection

Get the named configuration section from the IIS configuration files.

Parameters:
  • name – The name of the configuration section to return.

  • path (optional, default=None) – If not None, return the configuration section from the specified path.

  • set_location (optional, default='apphost') – Use the specified set location to search for the configuration section.

Returns:

The specified configuration section.

get_virtual_dir(vdir_name: str, /) VirtualDirectory

Get the specified virtual directory from the IIS instance.

Parameters:

vdir_name – The name of the virtual directory to return.

Returns:

The virtual directory from the IIS instance.

get_webapp(app_name: str, /) WebApplication

Get the specified web application from the IIS instance.

Parameters:

app_name – The name of the web application to return.

Returns:

The web application from the IIS instance.

get_webapp_pool(pool_name: str, /) WebApplicationPool

Get the specified web application pool from the IIS instance.

Parameters:

pool_name – The name of the web application pool to return.

Returns:

The web application pool from the IIS instance.

get_website(site_name: str, /) WebSite

Get the specified website from the IIS instance.

Parameters:

site_name – The name of the website to return.

Returns:

The website from the IIS instance.

has_item(item_type: Type[IISObject], item_name: str, /) bool

Determine if the specified item of the specified type exists in the IIS instance.

Parameters:
  • item_type – The type of the item for which to search.

  • item_name – The name of the item for which to search.

Returns:

True if the item exists in the IIS instance, False otherwise.

has_virtual_dir(vdir_name: str, /) bool

Determine if the IIS instance has the specified virtual directory.

Parameters:

vdir_name – The name of the virtual directory for which to search.

Returns:

True if the virtual directory exists in the IIS instance, False otherwise.

has_webapp(app_name: str, /) bool

Determine if the IIS instance has the specified web application.

Parameters:

app_name – The name of the web application for which to search.

Returns:

True if the web application exists in the IIS instance, False otherwise.

has_webapp_pool(pool_name: str, /) bool

Determine if the IIS instance has the specified web application pool.

Parameters:

pool_name – The name of the web application pool for which to search.

Returns:

True if the web application pool exists in the IIS instance, False otherwise.

has_website(site_name: str, /) bool

Determine if the IIS instance has the specified website.

Parameters:

site_name – The name of the web application for which to search.

Returns:

True if the website exists in the IIS instance, False otherwise.

property hostname

A read-only property which returns the hostname of the IIS server.

manage_item(action: str, item_type: Type[IISObject], /, *args) CommandResult

Manage an IIS object using the standard IIS appcmd.

Parameters:
  • action – The management action to perform.

  • item_type – The type of the item to manage.

  • *args (optional, default=[]) – Any other appcmd arguments to pass to the management action.

Returns:

The result of the appcmd command.

remove_webapp(app_name: str, /) None

Remove the specified web application from the IIS instance.

Parameters:

app_name – The name of the web application to remove.

Returns:

Nothing.

remove_webapp_pool(pool_name: str, /) None

Remove the specified web application pool from the IIS instance.

Parameters:

pool_name – The name of the web application pool to remove.

Returns:

Nothing.

reset(verbose: bool = True) CommandResult

Reset the IIS instance.

Parameters:

quiet (optional, default=False) – If True do not print result to standard output stream.

Returns:

The result of the reset command.

start(quiet: bool = False) CommandResult

Start the IIS instance.

Parameters:

quiet (optional, default=False) – If True do not print result to standard output stream.

Returns:

The result of the start command.

stop(quiet: bool = False) CommandResult

Stop the IIS instance.

Parameters:

quiet (optional, default=False) – If True do not print result to standard output stream.

Returns:

The result of the stop command.

class batcave.iispy.IISObject(name: str, iis_ref: IISInstance, /)

Bases: object

Class to create a universal abstract interface for an IIS object.

property iis_ref

A read-only property which returns the reference to the IIS object.

manage_item(action: str, /) None

Perform action on this object.

Parameters:

action – The action to perform on this object.

Returns:

Nothing.

property name

A read-only property which returns the name of the IIS object.

start() None

Start this object.

Returns:

Nothing.

stop() None

Stop this object.

Returns:

Nothing.

class batcave.iispy.VirtualDirectory(name: str, iis_ref: IISInstance, /)

Bases: IISObject

Class to create a universal abstract interface for an IIS virtual directory.

class batcave.iispy.WebApplication(name: str, iis_ref: IISInstance, /)

Bases: IISObject

Class to create a universal abstract interface for an IIS web application.

class batcave.iispy.WebApplicationPool(name: str, iis_ref: IISInstance, /)

Bases: IISObject

Class to create a universal abstract interface for an IIS web application pool.

class batcave.iispy.WebSite(name: str, iis_ref: IISInstance, /)

Bases: IISObject

Class to create a universal abstract interface for an IIS website.

batcave.iispy.appcmd(*cmd_args, hostname: str | None, **sys_cmd_args) CommandResult

Interface to run the standard IIS appcmd command-line tool.

Parameters:
  • *cmd_args – The arguments to pass to appcmd.

  • hostname – The hostname to pass to appcmd.

  • **sys_cmd_args – The arguments to pass to syscmd when running appcmd.

Returns:

The result of the appcmd call.

Raises:

AppCmdError.APPCMD_ERROR – If there are errors reported by appcmd.

batcave.iispy.dict2expat(py_dict: Dict, /) str

Converts Python dictionaries to the syntax understood by the IIS appcmd command-line tool.

Parameters:

py_dict – The Python dictionary to convert.

Returns:

The appcmd format for the dictionary.

batcave.k8s module

This module provides a simplified interface to the kubernetes module.

batcave.k8s.kubectl

A simple interface to the kubectl command line tool.

Type:

SysCmdRunner.run

class batcave.k8s.Binding(cluster: Cluster, object_ref: Any, /)

Bases: ClusterObject

Class to create a universal abstract interface for a Kubernetes cron job.

class batcave.k8s.Cluster(cluster_config: PathName | None = None, context: str | None = None)

Bases: object

Class to create a universal abstract interface for a Kubernetes cluster.

property config

A read-only property which returns configuration file for the cluster.

create_item(item_class: Type[K8sObject], item_spec: PathName, /, namespace: str = 'default', *, exists_ok: bool = False) K8sObject

Create a new item using the specified spec.

Parameters:
  • item_class – The class of the item to create.

  • item_spec – A file containing the Kubernetes specification.

  • namespace (optional, default='default') – The Kubernetes namespace in which to create the item.

  • exists_ok (optional, default=False) – If True and the item already exists, delete before creating.

Returns:

The created item.

create_job(job_spec: PathName, /, namespace: str = 'default', *, exists_ok: bool = False, wait_for: bool = False, check_every: int = 2, timeout: bool = False) Job

Create a job and wait for the specified condition.

Parameters:
  • job_spec – A file containing the Kubernetes job specification.

  • namespace (optional, default='default') – The Kubernetes namespace in which to create the job.

  • exists_ok (optional, default=False) – If True and the item already exists, delete before creating.

  • wait_for (optional, default=False) – If True, wait until the job completes before returning.

  • check_every (optional, default=2) – The number of seconds to wait between every check to see if the job has completed.

  • timeout (optional, default=False) – If not False, this is the maximum number of seconds to wait for the job to complete.

Raises:

ClusterError.TIMEOUT – If timeout is True and the maximum number of seconds is exceeded.

Returns:

The created job.

create_namespace(name: str, /, *, exists_ok: bool = False) Namespace

Create a namespace.

Parameters:
  • name – The name of the namespace to create.

  • exists_ok (optional, default=False) – If True and the item already exists, delete before creating.

Returns:

The created namespace.

delete_item(item_class: Type[K8sObject], name: str, /, namespace: str = 'default') None

Delete the named item.

Parameters:
  • item_class – The class of the item to create.

  • name – The name of the item to delete.

  • namespace (optional, default='default') – The Kubernetes namespace from which to return the item.

Returns:

Nothing.

find_method(item_class: Type[K8sObject], method: str, /, suffix: str = '') Callable

Search all the APIs for the specified method.

Parameters:
  • item_class – The item class to search.

  • method – The method for which to search.

  • suffix (optional, default=None) – If not None, append to the method name with an underscore when searching.

Returns:

A reference to method.

Raises:

AttributeError – If the method is not found.

get_item(item_class: Type[K8sObject], name: str, /, namespace: str = 'default') K8sObject

Get the requested item.

Parameters:
  • item_class – The item class.

  • item_name – The name of the item to return.

  • namespace (optional, default='default') – The Kubernetes namespace from which to return the item.

Returns:

The requested item.

get_items(item_class: Type[K8sObject], /, namespace: str = 'default', **keys) List[K8sObject]

Get all the item of the requested type.

Parameters:
  • item_class – The item class.

  • namespace (optional, default='default') – The Kubernetes namespace from which to return the items.

  • keys (optional) – A list of keys by which to filter the items.

Returns:

The requested item list.

has_item(item_class: Type[K8sObject], item_name: str, /, namespace: str = 'default') bool

Determine if the named items of the specified class exists.

Parameters:
  • item_class – The item class for which to search.

  • item_name – The name of the item to search for.

  • namespace (optional, default='default') – The Kubernetes namespace to search.

Returns:

Returns True if the named item exists, False otherwise.

kubectl(*args, **kwargs) CommandResult

Run a kubectl command.

Parameters:
  • *args – The arguments to pass to kubectl.

  • *kwargs – The named arguments to pass to kubectl.

Returns:

The result of the kubectl command.

patch_item(item_class: Type[K8sObject], name: str, item_spec: K8sObject, /, namespace: str = 'default') K8sObject

Patch the named item.

Parameters:
  • item_class – The class of the item to patch.

  • name – The name of the item to patch.

  • item_spec – The new specification for the patched item.

  • namespace (optional, default='default') – The Kubernetes namespace from which to return the item.

Returns:

The patched item.

property pod_exec

A read-only property which returns the pd exec function for the cluster.

exception batcave.k8s.ClusterError(err_obj: BatCaveError, /, **variables)

Bases: BatCaveException

Kubernetes Cluster Exceptions.

BAD_ARGS

Bad arguments were specified.

TIMEOUT

There was a timeout on the cluster.

BAD_ARGS = BatCaveError(code=1, msg=<string.Template object>)
TIMEOUT = BatCaveError(code=2, msg=<string.Template object>)
class batcave.k8s.ClusterObject(cluster: Cluster, object_ref: Any, /)

Bases: object

Class to create a universal abstract interface for a Kubernetes cluster object.

NAMESPACED

If True, the object is a cluster namespaced object.

NAMESPACED = True
property api_object

A read-only property which returns Kubernetes API object.

class batcave.k8s.Configmap(cluster: Cluster, object_ref: Any, /)

Bases: ClusterObject

Class to create a universal abstract interface for a Kubernetes cron job.

class batcave.k8s.Cronjob(cluster: Cluster, object_ref: Any, /)

Bases: ClusterObject

Class to create a universal abstract interface for a Kubernetes cron job.

class batcave.k8s.Daemonset(cluster: Cluster, object_ref: Any, /)

Bases: ClusterObject

Class to create a universal abstract interface for a Kubernetes cron job.

class batcave.k8s.Deployment(cluster: Cluster, object_ref: Any, /)

Bases: ClusterObject

Class to create a universal abstract interface for a Kubernetes deployment.

class batcave.k8s.Endpoints(cluster: Cluster, object_ref: Any, /)

Bases: ClusterObject

Class to create a universal abstract interface for a Kubernetes deployment.

class batcave.k8s.Event(cluster: Cluster, object_ref: Any, /)

Bases: ClusterObject

Class to create a universal abstract interface for a Kubernetes deployment.

class batcave.k8s.Job(cluster: Cluster, object_ref: Any, /)

Bases: ClusterObject

Class to create a universal abstract interface for a Kubernetes job.

class batcave.k8s.Limitrange(cluster: Cluster, object_ref: Any, /)

Bases: ClusterObject

Class to create a universal abstract interface for a Kubernetes deployment.

class batcave.k8s.Namespace(cluster: Cluster, object_ref: Any, /)

Bases: ClusterObject

Class to create a universal abstract interface for a Kubernetes namespace.

NAMESPACED = False
class batcave.k8s.Persistentvolumeclaim(cluster: Cluster, object_ref: Any, /)

Bases: ClusterObject

Class to create a universal abstract interface for a Kubernetes deployment.

class batcave.k8s.Pod(cluster: Cluster, object_ref: Any, /)

Bases: ClusterObject

Class to create a universal abstract interface for a Kubernetes pod.

cp_file(mode: str, source: PathName, target: PathName, /) None

Copy a file into or out of the pod.

Parameters:
  • mode – The direction of the copy (‘in’ or ‘out’).

  • source – The source file for the copy.

  • target – The target file for the copy.

Returns:

Nothing.

Raises:
  • PodError.BAD_COPY_FILENAME – If the source or target name was not found.

  • PodError.COPY_ERROR – If there was an error when copying the file.

  • PodError.INVALID_COPY_MODE – If the specified mode is not known.

exec(*command, **k8s_api_kwargs) str

Execute a command in the pod.

Parameters:
  • *command – The command and arguments to execute.

  • **k8s_api_kwargs – The Kubernetes API parameters to pass to the stream call.

Returns:

The output from the command.

Raises:

PodError.EXEC_ERROR – If the word ‘error’ occurs in the output.

get_file(source: str, target: PathName | None = None, /) None

Copy a file out of the pod.

Parameters:
  • source – The source for the copy.

  • target (optional, default=None) – If not None, the target for the copy.

Returns:

Nothing.

has_file(filename: str, /) bool

Determine if the pod has the specified file.

Parameters:

filename – The name of the file for which to search.

Returns:

True if the specified file exists, False otherwise.

property logs

A read-only property which returns the pod logs.

put_file(source: PathName, target: str, /) None

Copy a file into the pod.

Parameters:
  • source – The source for the copy.

  • target – The target for the copy.

Returns:

Nothing.

remove_file(filename: str, /, *, not_exists_ok: bool = False) None

Remove the specified file from the pod.

Parameters:
  • filename – The name of the file to remove.

  • not_exists_ok (optional, default=False) – If True, raise an exception if the file does not exist.

Returns:

Nothing.

Raises:

PodError.FILE_NOT_FOUND – If the file is not found.

exception batcave.k8s.PodError(err_obj: BatCaveError, /, **variables)

Bases: BatCaveException

Kubernetes Pod Exceptions.

BAD_COPY_FILENAME

The file specified for the copy was invalid.

COPY_ERROR

There was an error transferring a file to or from a pod.

EXEC_ERROR

There was an error executing a pod command.

FILE_NOT_FOUND

The file specified for the copy was not found in the pod.

INVALID_COPY_MODE

The copy mode was invalid.

BAD_COPY_FILENAME = BatCaveError(code=1, msg=<string.Template object>)
COPY_ERROR = BatCaveError(code=2, msg=<string.Template object>)
EXEC_ERROR = BatCaveError(code=3, msg=<string.Template object>)
FILE_NOT_FOUND = BatCaveError(code=4, msg=<string.Template object>)
INVALID_COPY_MODE = BatCaveError(code=5, msg=<string.Template object>)
class batcave.k8s.Replicaset(cluster: Cluster, object_ref: Any, /)

Bases: ClusterObject

Class to create a universal abstract interface for a Kubernetes service.

class batcave.k8s.Replicationcontroller(cluster: Cluster, object_ref: Any, /)

Bases: ClusterObject

Class to create a universal abstract interface for a Kubernetes service.

class batcave.k8s.Resourcequota(cluster: Cluster, object_ref: Any, /)

Bases: ClusterObject

Class to create a universal abstract interface for a Kubernetes service.

class batcave.k8s.Secret(cluster: Cluster, object_ref: Any, /)

Bases: ClusterObject

Class to create a universal abstract interface for a Kubernetes service.

class batcave.k8s.Service(cluster: Cluster, object_ref: Any, /)

Bases: ClusterObject

Class to create a universal abstract interface for a Kubernetes service.

class batcave.k8s.Serviceaccount(cluster: Cluster, object_ref: Any, /)

Bases: ClusterObject

Class to create a universal abstract interface for a Kubernetes service.

class batcave.k8s.Statefulset(cluster: Cluster, object_ref: Any, /)

Bases: ClusterObject

Class to create a universal abstract interface for a Kubernetes service.

batcave.lang module

This module provides Python language utilities.

batcave.lang.DEFAULT_ENCODING

The default encoding used for text file operations.

batcave.lang.BATCAVE_HOME

The home directory of the module.

batcave.lang.FROZEN

Is this module running in a frozen application. Quick version of sys.frozen

Type:

bool

batcave.lang.VALIDATE_PYTHON

Whether this module should validate the minimum version of Python when loaded.

Type:

bool, default=True

batcave.lang.WIN32

Is this module running on a Windows system. Quick version of (sys.platform == ‘win32’)

Type:

bool

class batcave.lang.BatCaveError(code: int, msg: MessageString)

Bases: object

A class to provide an interface for inspecting exceptions.

code

A unique error code for this error.

Type:

int

msg

A user-facing message for this error.

Type:

MessageString

code: int
msg: MessageString
exception batcave.lang.BatCaveException(err_obj: BatCaveError, /, **variables)

Bases: Exception, MsgStr

A base class to provide easier Exception management.

property code

A read-only property which returns the error code from the error object.

class batcave.lang.MsgStr(instr: str | Template = '', transform: str = '', **variables)

Bases: object

Class to create a universal abstract interface for message strings.

This class is only useful when subclassed where the subclass simply defines the _messages.

_message

A dictionary of messages provided by subclasses.

Example

class MyMsg(MsgStr):
_messages = {‘Message1’: ‘This is just a string’,

‘Message2’: Template(‘This is a $what template)}

where messages are retrieved with

MyMsg().Message1 MyMsg(what=’this’).Message2

exception batcave.lang.PythonVersionError(err_obj: BatCaveError, /, **variables)

Bases: BatCaveException

Invalid Python Version Exception.

BAD_VERSION

The version of Python is too low.

BAD_VERSION = BatCaveError(code=1, msg=<string.Template object>)
batcave.lang.bool_to_str(expr: bool | str, /) str

Converts an expression to a lowercase boolean string value.

Parameters:

expr – The expression to convert.

Returns:

‘true’ if the expression evaluates to True, ‘false’ otherwise.

batcave.lang.dotmap_to_yaml(dotmap_thing: DotMap, yaml_file: PathName, /) None

Convert a DotMap to a YAML file.

Parameters:
  • dotmap_thing – The DotMap to convert.

  • yaml_file – The YAML file to which to write the DotMap.

Returns:

Nothing.

batcave.lang.flatten(thing: Iterable[Any], /, *, recursive: bool = True) Iterable

Flatten an iterable of iterables.

Parameters:
  • thing – The thing to be flattened.

  • recursive (optional, default=True) – Whether or not to recursively flatten the item.

Returns:

The final single depth item as the same type as thing.

batcave.lang.flatten_string_list(iter_of_string: Iterable[str], /, *, remove_newlines: bool = True) str

Flatten an iterable of strings to a single string.

Parameters:
  • iter_of_string – The list of strings to be flattened to be flattened.

  • remove_newlines (optional, default=True) – Whether or not to remove newlines from the final list.

Returns:

The final string.

batcave.lang.is_debug(test_value: str | None = None, /) bool

Determine if the BATCAVE_DEBUG environment variable is set.

Parameters:

test_value (optional, default=False) – If set, only return true if the value of test_value is in BATCAVE_DEBUG.

Returns:

True if the OS environment variable BATCAVE_DEBUG is set, False otherwise.

batcave.lang.str_to_pythonval(the_string: str, /, *, parse_python: bool = False) Any

Converts a string to the closest Python object.

Parameters:
  • the_string – The string to evaluate.

  • parse_python (optional, default=False) – If the string contains a ‘~’ character, try to convert it to a more complex python object.

Returns:

  1. If the string represents an integer, return the value as an int.

  2. If the string represents an non-integer number, return the value as a float.

  3. If the string evaluates to ‘None’ (case-insensitive), return None.

  4. If the string evaluates to ‘True’ or ‘False’ (case-insensitive), return True/False.

  5. If parse_python is True and the_string contains ‘~’:

    Split the_string on the first ‘~’ and return the second part as the value of a type specified by the first part.

Raises:

ValueError – If the_string is not a string.

batcave.lang.validate_python(test_against: Tuple[int, int] = (3, 6), /) None

Checks to make sure that a minimum version of Python is used.

Parameters:

test_against (optional, default=(3,7)) – The value of Python to check.

Returns:

Nothing.

Raises:

PythonVersionError.BAD_VERSION – If the version is too low.

batcave.lang.xor(value1: Any, value2: Any, /) bool

Perform a logical exclusive-or evaluation.

Parameters:
  • value1 – The values on which to perform the operation.

  • value2 – The values on which to perform the operation.

Returns:

The logical exclusive-or of the values.

batcave.lang.yaml_to_dotmap(yaml_info: str | PathName, /) DotMap

Converts a YAML file to a DotMap.

Parameters:

yaml_info – The YAML to which to read into a DotMap. If this is a string it is presumed to be raw YAML otherwise it is expected to be a Path object which can be open and read.

Returns:

A DotMap representing the YAML content.

batcave.menu module

This module provides utilities for creating command line menus.

class batcave.menu.Menu(items: List[MenuItem], title: str = '\nSelect one of the following\n', prompt: str = '-> ', invalid_msg: str = '\nInvalid choice\n', multiselect: bool = False, ignorecase: bool = True)

Bases: object

Class to create a universal abstract interface for a command-line menu.

items

The list of items for the menu.

Type:

List[batcave.menu.MenuItem]

title

The title for the menu.

Type:

optional, default=_DEFAULT_TITLE

prompt

The prompt for the menu.

Type:

optional, default=_DEFAULT_PROMPT

invalid_msg

The invalid choice message.

Type:

optional, default=_DEFAULT_INVALID_MESSAGE

multiselect

If True, multiple options can be selected.

Type:

optional, default=False

ignorecase

If True, menu input will be case insensitive.

Type:

optional, default=True

ignorecase: bool = True
invalid_msg: str = '\nInvalid choice\n'
items: List[MenuItem]
multiselect: bool = False
prompt: str = '-> '
show() str | List[str]

Show the menu.

Returns:

The choice selected from the menu.

title: str = '\nSelect one of the following\n'
class batcave.menu.MenuItem(key: str, desc: str)

Bases: object

Class to represent a single menu item.

key

The key input for the menu selection.

Type:

str

desc

The text description for the menu selection.

Type:

str

desc: str
key: str
class batcave.menu.SimpleMenu(items: List[MenuItem], title: str = '\nSelect one of the following\n', prompt: str = '-> ', invalid_msg: str = '\nInvalid choice\n', multiselect: bool = False, ignorecase: bool = True, return_text: bool = False)

Bases: Menu

A simplified version of the Menu class.

return_text

If True the text of the menu selection will be returned instead of the key.

Type:

optional, default=False

return_text: bool = False
show() str

Show the menu.

Returns:

The choice selected from the menu.

batcave.netutil module

This module provides utilities for working with network services.

batcave.netutil.download(url: str, /, target: str | None = None, *, auth: Tuple[str, str] | AuthBase | Callable[[PreparedRequest], PreparedRequest] | None = None) None

Download a file from a URL target.

Parameters:
  • url – The URL to download from.

  • target (optional, default=None) – The file to which to download. If None, the last part of the URL will be used.

  • auth (optional, default=None) – If not None, it must be a (username, password) tuple.

Returns:

Nothing.

Raises:

Uses the requests module raise_for_status() function to raise on download errors.

batcave.netutil.send_email(smtp_server: str, receiver: str, sender: str, subject: str, body: str, /, content_type: str = 'text/plain') Dict[str, Tuple[int, bytes]]

Send an SMTP email message.

Parameters:
  • smtp_server – The SMTP server to send the email through.

  • receiver – The email address to which to send.

  • sender – The return address for the email.

  • subject – The email message subject.

  • body – The email message body.

  • content_type (optional, default='text/plain') – The content type for the email.

Returns:

The result of the sendmail call.

batcave.platarch module

This module provides a simplified interface to the standard platform module.

class batcave.platarch.OsType(*values)

Bases: Enum

linux = 1
windows = 2
class batcave.platarch.Platform

Bases: object

A class to provide a simplified interface to the platform and sys.version_info standard modules.

batcave.qbpy module

This module provides a Pythonic interface to the QuickBuild RESTful API.

class batcave.qbpy.QuickBuildBuild(console: QuickBuildConsole, object_id: int | str, /)

Bases: QuickBuildObject

Class to create a universal abstract interface for a QuickBuild configuration run.

class batcave.qbpy.QuickBuildCfg(console: QuickBuildConsole, object_id: int | str, /)

Bases: QuickBuildObject

Class to create a universal abstract interface for a QuickBuild configuration.

change_var(var: str, val: str, /) QuickBuildCfg

Change the value of a variable in this configuration.

Parameters:
  • var – The variable to change.

  • val – The new value of the variable.

Returns:

The configuration.

property children: List[QuickBuildCfg]

A read-only property which returns a list of children for the object.

copy(parent: QuickBuildCfg, name: str, /, *, recurse: bool = False) QuickBuildCfg

Copy this configuration to a new configuration.

Parameters:
  • parent – The parent to which to copy the configuration.

  • name – The name of the new configuration.

  • recurse (optional, default=False) – If True, copy the children configurations also.

Returns:

The new configuration.

disable(*, wait: bool = False) None

Disable this configuration.

Parameters:

wait (optional, default=False) – If True, wait for the configuration to be disabled.

Returns:

Nothing.

enable() None

Enable this configuration.

Returns:

Nothing.

get_children(*, recurse: bool = False) List[QuickBuildCfg]

Get the child configurations.

Parameters:

recurse (optional, default=False) – Get the children recursively.

Returns:

The list of child configurations.

property latest_build: QuickBuildBuild

A read-only property which returns the latest build for this configuration.

remove() None

Remove this configuration.

Returns:

Nothing.

rename(newname: str, /) QuickBuildCfg

Rename this configuration.

Parameters:

newname – The new name for the configuration.

Returns:

The renamed configuration.

reparent(new_parent: QuickBuildCfg, /, *, rename: bool = False) QuickBuildCfg

Reparent this configuration.

Parameters:
  • new_parent – The new parent for the configuration.

  • rename (optional, default=False) – If not False, rename the configuration when moved.

Returns:

The moved configuration.

class batcave.qbpy.QuickBuildConsole(host: str, /, *, user: str, password: str)

Bases: object

Class to create a universal abstract interface for a QuickBuild console.

create_dashboard(name: str, dashboard: str | QuickBuildDashboard, /) QuickBuildDashboard

Create a dashboard from an existing one.

Parameters:
  • name – The name of the new dashboard.

  • dashboard – The dashboard from which to make the copy.

Returns:

The new dashboard.

get_dashboard(dashboard: str, /) QuickBuildDashboard

Get the named dashboard.

Parameters:

dashboard – The dashboard to return.

Returns:

The requested dashboard.

has_dashboard(dashboard: str, /) bool

Determine if the specified dashboard exists.

Parameters:

dashboard – The dashboard for which to search.

Returns:

True if the requested dashboard exists, False otherwise.

qb_runner(cmd: str, /, *, xml_data: Any | None = None, delete: bool = False) Response

Provide an interface to the RESTful API.

Parameters:
  • cmd – The API command to run.

  • xml_data (optional, default=None) – Any data to pass to the command.

  • delete (optional, default=False) – If True, use delete, otherwise use get.

Returns:

The result of the API call.

property update: bool

A read-write property which returns and sets the update state for the console.

updater() None

Update the configuration list.

Returns:

Nothing.

class batcave.qbpy.QuickBuildDashboard(console: QuickBuildConsole, object_id: int | str, /)

Bases: QuickBuildObject

Class to create a universal abstract interface for a QuickBuild dashboard.

class batcave.qbpy.QuickBuildObject(console: QuickBuildConsole, object_id: int | str, /)

Bases: object

Class to create a universal abstract interface for a QuickBuild object.

property id

A read-only property which returns the QuickBuild object ID.

batcave.reporter module

This module provides utilities for creating reports.

Examples

The simplest usage would be:

report = reporter.Report('REPORT HEADER', 'REPORT FOOTER')

To add a line to the report:

line = reporter.Line('a line')
report.add_line(line)

To add a section:

section1 = reporter.Section('Section 1 Header', 'Section 1 Footer')
report.add_section(section1)

To add a link:

link = reporter.Link('Link Text', 'URL')
report.register_link(link)
report.add_line(reporter.Line(f'Line with a {link} in it'))

To add a list of links:

links = reporter.LinkList({'link1': 'http://link1', 'link2': 'http://link2'})
report.register_link(links)
report.add_line(reporter.Line(f'Line with {links}s in it'))

A table is a list of lists with each outer list a row

To add a table:

rows = [['11', '12'], ['21', '22']]
table = reporter.Table(rows, 'Table Header', 'Table Footer')
report.add_table(table)

To embed a link in a table:

link = reporter.Link('Table Text', 'http://table')
report.register_link(link)
rows = [['11', '12'], ['21', link]]
table = reporter.Table(rows, 'Table Header', 'Table Footer')
report.add_table(table)

A simple report can be output with:

print(report)
Each attribute is made up of what it affects and where that effect takes place.

i.e. PART_PIECE_WHERE

Part abbreviations

rpt = report sec = section tbl = table lin = line lnk = link lst = list

Piece abbreviations

hdr = header bdy = body row = DUH! cel = cell ftr = footer

Where abbreviations

ldr = leader int = interstitial trm = terminator

The report/section structure is
sec_ldr - header - body - footer - sec_trm
batcave.reporter.where
header = sec_hdr_ldr - HEADER - sec_hdr_trm
body = sec_bdy_ldr - BODY - sec_bdy_trm
footer = sec_ftr_ldr - FOOTER - sec_ftr_trm
The table structure is
tbl_ldr - header - body - footer - tbl_trm
where the body is
tbl_bdy_ldr - rows - tbl_bdr_trm
and rows are
tbl_row_ldr - cell - tbl_row_trm
and cells are
tbl_cel_ldr - data - tbl_cel_trm
The general line structure is
lin_ldr - LINE - lin_trm
The general list structure is
lst_ldr - ITEM - lst_int ITEM - lst_trm
class batcave.reporter.Cell(data: str, cont: Type[ReportObject] | None = None, /, **attr)

Bases: ReportObject

Class to create a universal abstract interface for a cell in a table in a report.

class batcave.reporter.Line(text: str, cont: Type[ReportObject] | None = None, /, **attr)

Bases: ReportObject

Class to create a universal abstract interface for a report section line.

Bases: Line

Class to create a universal abstract interface for a report hyperlink.

Bases: Section

Class to create a universal abstract interface for a list of hyperlinks in a report.

class batcave.reporter.MetaAttribute(attr: str, /, **val_map)

Bases: object

Class to create a universal abstract interface for a report attribute which returns a value based on the value of a SimpleAttribute.

get_value(attr: str, /) str

Get the value of an attribute.

Parameters:

attr – The attribute for which to return the value.

Returns:

The value of the attribute.

property simple_attr_name

A read-only property which returns the simple attribute name.

property values

A read-only property which returns the values of the attribute as a dictionary.

class batcave.reporter.Report(*, header: str = '', footer: str = '', cont: Type[ReportObject] | None = None, **attr)

Bases: Section

Class to create a universal abstract interface for a report.

class batcave.reporter.ReportObject(container: Type[ReportObject] | None = None, /, **attributes)

Bases: object

Class to create a universal abstract interface for a report object.

property depth: int

A read-only property which returns the report depth of this object.

property lin_ldr

A read-write property for the line leader attribute.

property lin_trm

A read-write property for the line terminator attribute.

property lnk_ldr

A read-write property for the link leader attribute.

property lnk_trm

A read-write property for the link terminator attribute.

property lst_int

A read-write property for the list separator attribute.

property lst_ldr

A read-write property for the list leader attribute.

property lst_trm

A read-write property for the list terminator attribute.

property output

A read-write property for the output attribute.

property rpt_bdy_ldr

A read-write property for the report body leader attribute.

property rpt_bdy_trm

A read-write property for the report body terminator attribute.

property rpt_ftr_ldr

A read-write property for the report footer leader attribute.

property rpt_ftr_trm

A read-write property for the report footer terminator attribute.

property rpt_hdr_ldr

A read-write property for the report header leader attribute.

property rpt_hdr_trm

A read-write property for the report header terminator attribute.

property rpt_ldr

A read-write property for the report leader attribute.

property rpt_trm

A read-write property for the report terminator attribute.

property sec_bdy_ldr

A read-write property for the section body leader attribute.

property sec_bdy_trm

A read-write property for the section body terminator attribute.

property sec_ftr_ldr

A read-write property for the section footer leader attribute.

property sec_ftr_trm

A read-write property for the section footer terminator attribute.

property sec_hdr_ldr

A read-write property for the section header leader attribute.

property sec_hdr_trm

A read-write property for the section header terminator attribute.

property sec_ldr

A read-write property for the section leader attribute.

property sec_trm

A read-write property for the section terminator attribute.

property tbl_bdy_ldr

A read-write property for the table body leader attribute.

property tbl_bdy_trm

A read-write property for the table body terminator attribute.

property tbl_cel_ldr

A read-write property for the table cell leader attribute.

property tbl_cel_trm

A read-write property for the table cell terminator attribute.

property tbl_ftr_ldr

A read-write property for the table footer leader attribute.

property tbl_ftr_trm

A read-write property for the table footer terminator attribute.

property tbl_hdr_ldr

A read-write property for the table header leader attribute.

property tbl_hdr_trm

A read-write property for the table header terminator attribute.

property tbl_ldr

A read-write property for the table leader attribute.

property tbl_row_ldr

A read-write property for the table row leader attribute.

property tbl_row_trm

A read-write property for the table row terminator attribute.

property tbl_trm

A read-write property for the table terminator attribute.

class batcave.reporter.Section(*, header: str = '', footer: str = '', cont: Type[ReportObject] | None = None, **attr)

Bases: ReportObject

Class to create a universal abstract interface for a report section.

add_line(line: Type[Line], /) None

Add a line to the section.

Parameters:

line – The line to add to the section.

Returns:

Nothing.

add_member(thing: Type[ReportObject], /) None

Add a member to the section.

Parameters:

thing – The member to add to the section.

Returns:

Nothing.

add_section(section: Type[Section], /) None

Add a sub-section to the section.

Parameters:

section – The sub-section to add to the section.

Returns:

Nothing.

add_table(table: Type[Table], /) None

Add a table to the section.

Parameters:

table – The table to add to the section.

Returns:

Nothing.

Register a hyperlink in the section.

Parameters:

link – The hyperlink to register.

Returns:

Nothing.

class batcave.reporter.SimpleAttribute(default: str, /, *other)

Bases: object

Class to create a universal abstract interface for a report attribute which has a default value and a list of valid values.

property count

A read-only property which returns the number of valid attribute values.

is_valid(attr: str, /) bool

Determine if the specified attribute is valid.

Parameters:

attr – The attribute to validate.

Returns:

True if the attribute it valid, False otherwise.

property value: str

A read-write property which returns and sets the value of the attribute.

class batcave.reporter.Table(data: List[List[str]], /, *, header: str = '', footer: str = '', **attr)

Bases: ReportObject

Class to create a universal abstract interface for a report section table.

batcave.servermgr module

This module provides utilities for working with servers.

batcave.servermgr._STATUS_CHECK_INTERVAL

This is the default wait in seconds when performing any checks.

Type:

int, default=2

class batcave.servermgr.LinuxProcess(ProcessId: int, /)

Bases: object

Class to create a universal abstract interface for a Linux process.

property CommandLine

A read-only property which returns the command line for the process.

property ExecutablePath

A read-only property which returns the executable path for the process.

Kill() None

Kill the process.

Returns:

Nothing.

property Name

A read-only property which returns the name of the process.

Terminate() None

Terminate the process.

Returns:

Nothing.

class batcave.servermgr.LinuxScheduledTask

Bases: object

Class to create a universal abstract interface for a Linux cron job.

class batcave.servermgr.LinuxService(Name: str, computer: str, auth: ServerAuthType, service_type: ServiceType, /)

Bases: NamedOSObject

Class to create a universal abstract interface for a Linux daemon service.

DisableService() None

Disable the service.

Returns:

Nothing.

EnableService() None

Enable the service.

Returns:

Nothing.

RestartService() None

Restart the service.

Returns:

Nothing.

StartService() None

Start the service.

Returns:

Nothing.

StopService() None

Stop the service.

Returns:

Nothing.

property state: str

A read-only property which returns the state value of the service.

validate() None

Determine if the service exists.

Returns:

Nothing.

Raises:

ServerObjectManagementError.OBJECT_NOT_FOUND – If the service is not found.

class batcave.servermgr.ManagementObject(object_ref: ManagementObject, manager: OSManager, key: str, value: str, /, **key_values)

Bases: object

Management object to provide OS independent interface.

OBJECT_PREFIX

The prefix to use to correctly translate to a NamesOSObject type.

OBJECT_PREFIX = 'Linux'
refresh() None

Refresh the state of the object.

Returns:

Nothing.

Raises:

ServerObjectManagementError.NOT_UNIQUE – If the object is not unique.

class batcave.servermgr.NamedOSObject(Name: str, computer: str, auth: ServerAuthType, /)

Bases: object

Class to allow management of all OS objects using a similar interface.

class batcave.servermgr.OSManager(computer: str = '', auth: ServerAuthType = None)

Bases: object

Class to make non WMI OS management look like WMI management.

LinuxProcess(CommandLine: str | None = None, ExecutablePath: str | None = None, Name: str | None = None, ProcessId: int | None = None) List[LinuxProcess]

Get the specified Linux process.

Parameters:
  • specified (Exactly one of these options must be)

  • CommandLine (optional, default=None) – The command line for the process.

  • ExecutablePath (optional, default=None) – The command line for the process.

  • Name (optional, default=None) – The command line for the process.

  • ProcessId (optional, default=None) – The command line for the process.

Returns:

The specified Linux process.

Raises:

ServerObjectManagementError.BAD_FILTER – If more than one selection option is specified.

LinuxService(Name: str, service_type: ServiceType, /) LinuxService

Get the specified Linux service.

Parameters:
  • Name – The name of the service to return.

  • service_type – The type of service to return.

Returns:

The specified Linux service.

Win32_ScheduledTask(Name: str, /) ScheduledTask

Get the specified Windows Scheduled Task.

Parameters:

Name – The name of the scheduled task to return.

Returns:

The specified Windows scheduled task.

get_object_as_list(object_type: str, /, *, Name: str, **key_args) List[ManagementObject]

Get the specified OS object.

Parameters:
  • object_type – The object type.

  • Name – The name of the object to return.

  • **key_args (optional, default={}) – A dictionary of filters to pass to the manager to filter the objects returned.

Returns:

The list of management objects.

class batcave.servermgr.Process(object_ref: ManagementObject, manager: OSManager, key: str, value: str, /, **key_values)

Bases: ManagementObject

Class to create a universal abstract interface for an OS process.

manage(signal: ProcessSignal, /, *, wait: bool = True, timeout: bool = False) None

Manage the process.

Parameters:
  • signal – The signal to send to the process.

  • wait (optional, default=True) – If True, wait for the action to complete.

  • timeout (optional, default=False) – If wait is True, the number of seconds to wait for the action to complete, indefinitely if False.

Returns:

Nothing.

Raises:
  • ServerObjectManagementError.BAD_OBJECT_SIGNAL – If the requested action is invalid.

  • ServerObjectManagementError.STATUS_CHECK_TIMEOUT – If wait is True and timeout is not False and the object has not reached the required state.

class batcave.servermgr.ProcessSignal(*values)

Bases: Enum

kill = 2
stop = 1
class batcave.servermgr.ScheduledTask(object_ref: ManagementObject, manager: OSManager, key: str, value: str, /, **key_values)

Bases: ManagementObject

Class to create a universal abstract interface for an OS scheduled task.

TASK_HOME

The directory where task definitions are stored.

TASK_NAMESPACE

The Windows task namespace needed to parse the XML task definitions.

TASK_HOME = PosixPath('/opt/cronjobs')
TASK_NAMESPACE = 'http://schemas.microsoft.com/windows/2004/02/mit/task'
class batcave.servermgr.Server(hostname: str | None = None, domain: str | None = None, *, auth: ServerAuthType | None = None, defer_wmi: bool = True, ip: str = '', os_type: OsType = OsType.linux)

Bases: object

Class to create a universal abstract interface for a server.

_WSA_NAME_OR_SERVICE_NOT_KNOWN

Error code indicating the service is unknown.

_WSAHOST_NOT_FOUND

Error code indicating the host was not found.

_WMI_SERVICE_CREATE_ERRORS

A dictionary to map WMI errors to errors messages.

create_management_object(item_type: str, unique_id: str, wmi: WMIObject = False, /, *, error_if_exists: bool = True, **key_args) ManagementObject

Create a management object of the specified type.

Parameters:
  • item_type – The item type of the object to create.

  • unique_id – The unique object identifier.

  • wmi (optional) – True if this is a Windows platform, False otherwise.

  • error_if_exists (optional, default=True) – If True raise an error if the object already exists.

  • **key_args (optional, default={}) – A dictionary of key value pairs to pass to add to the create object.

Returns:

The created management object.

Raises:

ServerObjectManagementError.WMI_ERROR – If there was an error creating the object.

create_scheduled_task(task: str, /, *, exe: str, schedule_type: str, schedule: str, user: str = '', password: str = '', start_in: PathName | None = None, disable: bool = False) ScheduledTask

Create a scheduled task.

Parameters:
  • task – The name of the scheduled task to create.

  • exe – The executable the scheduled task will run.

  • schedule_type – The schedule type.

  • schedule – The schedule on which to run the task.

  • user (optional, default='') – In not None, the user account that the task will run under.

  • password (optional, default='') – The password for the user account that the task will run under.

  • start_in (optional, default=None) – If not None, the directory in which the task will start.

  • disable (optional, default=False) – If True the task will be created as disabled.

Returns:

The created scheduled task.

create_service(service: str, /, *, exe: str, user: str = '', password: str = '', start: bool = False, timeout: int = 0, error_if_exists: bool = True) Service

Create a service.

Parameters:
  • service – The name of the service to create.

  • exe – The executable the service will run.

  • user (optional, default='') – In not None, the user account that the service will run under.

  • password (optional, default='') – The password for the user account that the service will run under.

  • timeout (optional, default=0) – If not 0, the number of seconds to wait for the service to start.

  • error_if_exists (optional, default=True) – If True raise an error if the object already exists.

Returns:

The created service.

property domain

A read-only property which returns the domain of the server.

property fqdn

A read-only property which returns the full-qualified domain name of the server.

get_management_objects(item_type: str, wmi: WMIObject = False, /, **filters) List[NamedOSObject]

Get a list of management objects.

Parameters:
  • item_type – The item type of the objects.

  • wmi (optional) – True if this is a Windows platform, False otherwise.

  • **filters (optional, default={}) – A dictionary of filters to pass to the manager to filter the objects returned.

Returns:

The list of management objects.

get_object_by_name(item_type: str, name: str, wmi: bool = False, /, **filters) NamedOSObject | None

Get a management object by name.

Parameters:
  • item_type – The item type of the object.

  • name – The name of the object.

  • wmi (optional) – True if this is a Windows platform, False otherwise.

  • **filters (optional, default={}) – A dictionary of filters to pass to the manager to filter for the object.

Returns:

The requested management object.

Raises:

ServerObjectManagementError.NOT_UNIQUE – If more than one management object was found.

get_path(the_path: str, /) ServerPath

Get the specified path as a ServerPath object.

Parameters:

the_path – The path to return.

Returns:

The specified path as a ServerPath object.

get_process_list(**filters) List[Process]

Get the process list for this server.

Returns:

The process list for this server.

get_scheduled_task(task: str, /) ScheduledTask

Get the specified scheduled task.

Returns:

The specified scheduled task.

get_scheduled_task_list() List[ScheduledTask]

Get the scheduled tasks for this server.

Returns:

The scheduled tasks for this server.

get_service(service: str, /, **key_args) Service

Get the specified service.

Parameters:

**key_args (optional, default={}) – A dictionary of key value pairs to apply as filters when retrieving the service.

Returns:

The specified service.

get_service_list(service_type: ServiceType | None = None, /) List[Service]

Get the services for this server.

Parameters:

service_type (optional, default=None) – If None, determine the service type based on the OS.

Returns:

The services for this server.

get_unique_object(item_type: str, wmi: WMIObject = False, /, **filters) NamedOSObject | None

Get the requested management object which must be unique.

Parameters:
  • item_type – The item type of the object.

  • wmi (optional) – True if this is a Windows platform, False otherwise.

  • **filters (optional, default={}) – A dictionary of filters to pass to the manager to filter for the object.

Returns:

The requested management object.

Raises:

ServerObjectManagementError.NOT_UNIQUE – If more than one management object was found.

property hostname

A read-only property which returns the hostname of the server.

property ip

A read-only property which returns IP for the server.

property is_local

A read-only property which returns True if the server is the local host.

property os_type

A read-only property which returns the OS type of the server.

remove_management_object(item_type: str, unique_id: str, wmi: WMIObject = False, /, *, error_if_not_exists: bool = False) None

Remove a management object.

Parameters:
  • item_type – The item type of the object to remove.

  • unique_id – The unique identifier of the object to remove.

  • wmi (optional) – True if this is a Windows platform, False otherwise.

  • error_if_not_exists (optional, default=False) – If False raise an error if the object does not exist.

Returns:

Nothing.

Raises:

ServerObjectManagementError.WMI_ERROR – If there was an error removing the object.

remove_scheduled_task(task: str, /) None

Remove the specified scheduled task.

Parameters:

task – The name of the scheduled task to remove.

Returns:

Nothing.

remove_service(service: str, /, *, error_if_not_exists: bool = False) None

Remove the specified service.

Parameters:
  • service – The name of the service to remove.

  • error_if_not_exists (optional, default=False) – If False raise an error if the object does not exist.

Returns:

Nothing.

run_command(command: str, /, *cmd_args, **sys_cmd_args) CommandResult

Run a command on the server.

Parameters:
  • command – The command to run.

  • *cmd_args (optional, default=[]) – The arguments to pass to the command.

  • *sys_cmd_args (optional, default={}) – A dictionary of named arguments to pass to the command.

Returns:

The result of the command.

exception batcave.servermgr.ServerObjectManagementError(err_obj: BatCaveError, /, **variables)

Bases: BatCaveException

Server Exceptions.

BAD_FILTER

Multiple filters were specified when only one is allowed.

BAD_OBJECT_SIGNAL

The signal type is invalid.

BAD_OBJECT_STATE

The object state is unknown.

BAD_TRANSITION

The object state transition was unexpected.

OBJECT_NOT_FOUND

The requested object was not found.

REMOTE_CONNECTION_ERROR

The was an error attempting to connect to the remote server.

REMOTE_NOT_SUPPORTED

The request action is not supported for remote servers.

SERVER_NOT_FOUND

The requested server was not found.

NOT_UNIQUE

A unique instance of the object was not found.

STATUS_CHECK_TIMEOUT

The was a timeout checking for the status of the object.

WMI_ERROR

The was a WMI error.

BAD_FILTER = BatCaveError(code=1, msg='One and only one filter must be provided for this object')
BAD_OBJECT_SIGNAL = BatCaveError(code=2, msg=<string.Template object>)
BAD_OBJECT_STATE = BatCaveError(code=3, msg=<string.Template object>)
BAD_TRANSITION = BatCaveError(code=4, msg=<string.Template object>)
NOT_UNIQUE = BatCaveError(code=5, msg=<string.Template object>)
OBJECT_NOT_FOUND = BatCaveError(code=6, msg=<string.Template object>)
REMOTE_CONNECTION_ERROR = BatCaveError(code=7, msg=<string.Template object>)
REMOTE_NOT_SUPPORTED = BatCaveError(code=8, msg='Remote objects are not supported for Linux servers')
SERVER_NOT_FOUND = BatCaveError(code=9, msg=<string.Template object>)
STATUS_CHECK_TIMEOUT = BatCaveError(code=10, msg=<string.Template object>)
WMI_ERROR = BatCaveError(code=11, msg=<string.Template object>)
class batcave.servermgr.Service(object_ref: ManagementObject, manager: OSManager, key: str, value: str, /, **key_values)

Bases: ManagementObject

Class to create a universal abstract interface for an OS service.

manage(signal: ServiceSignal, /, *, wait: bool = True, ignore_state: bool = False, timeout: int = False) None

Manage the service.

Parameters:
  • signal – The signal to send to the service.

  • wait (optional, default=True) – If True, wait for the action to complete.

  • ignore_state (optional, default=False) – If False, do not check the initial state before performing the action.

  • timeout (optional, default=0) – If wait is True, the number of seconds to wait for the action to complete, indefinitely if 0.

Returns:

Nothing.

Raises:
  • ServerObjectManagementError.BAD_OBJECT_SIGNAL – If the requested action is invalid.

  • ServerObjectManagementError.BAD_OBJECT_STATE – If ignore_state is False and the current state is invalid.

  • ServerObjectManagementError.BAD_TRANSITION – If ignore_state is False and the requested action is not valid for the current state.

  • ServerObjectManagementError.STATUS_CHECK_TIMEOUT – If wait is True and timeout is not False and the object has not reached the required state.

class batcave.servermgr.ServiceSignal(*values)

Bases: Enum

disable = 1
enable = 2
pause = 5
restart = 7
resume = 6
start = 3
stop = 4
class batcave.servermgr.ServiceState(*values)

Bases: Enum

ContinuePending = 2
PausePending = 6
Paused = 7
Running = 3
StartPending = 1
StopPending = 4
Stopped = 5
class batcave.servermgr.ServiceType(*values)

Bases: Enum

systemd = 1
sysv = 2
upstart = 3
windows = 4
class batcave.servermgr.TaskSignal(*values)

Bases: Enum

disable = 2
enable = 1
end = 4
run = 3
class batcave.servermgr.WMI(*args, **kwargs)

Bases: object

Needed to avoid errors on Linux

class batcave.servermgr.Win32_ScheduledTask(Name: str, computer: str, auth: ServerAuthType, /)

Bases: NamedOSObject

Class to abstract a Windows Scheduled Task since they are not available using WMI.

manage(signal: TaskSignal, /, *, wait: bool = True) None

Manage the scheduled task.

Parameters:
  • signal – The signal to send to the scheduled task.

  • wait (optional, default=True) – If True, wait for the action to complete.

Returns:

Nothing.

Raises:

ServerObjectManagementError.BAD_OBJECT_SIGNAL – If the signal is unknown.

remove() CommandResult

Remove the scheduled task.

Returns:

The result of the remove command.

validate() None

Determine if the scheduled task exists.

Returns:

Nothing.

Raises:

ServerObjectManagementError.OBJECT_NOT_FOUND – If the scheduled task is not found.

batcave.servermgr.get_server_object(server: ServerType, /) Server

Get a server object for the specific fqdn.

Parameters:

server – The fqdn string for the server

Returns:

Returns the Server object.

exception batcave.servermgr.x_wmi

Bases: Exception

Needed to avoid errors on Linux

batcave.serverpath module

This module provides a generic interface for local and remote server paths.

class batcave.serverpath.ServerPath(server: Server, the_path: PathName, /)

Bases: object

Class to create a universal abstract interface for an OS directory such that remote and local paths can be managed with the same code.

DEFAULT_REMOTE_COPY_COMMAND

The default command to perform a remote copy based on the OS of the source.

DEFAULT_REMOTE_COPY_ARGS

The default arguments used to perform a remote copy based on the OS of the source.

DEFAULT_REMOTE_COPY_ARGS = {OsType.linux: ['-r', '-batch'], OsType.windows: ['/MIR', '/MT', '/R:0', '/NFL', '/NDL', '/NP', '/NJH', '/NJS']}
DEFAULT_REMOTE_COPY_COMMAND = {OsType.linux: 'scp', OsType.windows: 'robocopy'}
copy(sp_dest: ServerPath, /, remote_cp_command: str | None = None, remote_cp_args: List[str] | None = None) CommandResult

Implementation of shutil.copy() adding remote server support.

Parameters:
  • sp_dest – The destination of the copy.

  • remote_cp_command (optional, default=None) – If not None, the command to use if the path is remote other than the default.

  • remote_cp_args (optional, default=None) – If not None, the arguments to use if the path is remote other than the default.

Returns:

The result of the copy.

Raises:

ServerPathError.REMOTE_COPY_SPACE_ERROR – If the remote destination is out of space.

exists() bool

Implementation of pathlib.Path.exists() adding remote server support.

Returns:

True if this path exists, False otherwise.

property is_win

A read-only property which returns True if the path is on a Windows server.

iterdir() CommandResult | List[Path]

Implementation of pathlib.Path.iterdir() adding remote server support.

Returns:

The contents of this directory path.

property local

A read-only property which returns the value of the the_path argument when referenced locally on the server.

mkdir(mode: int = 511, /, *, parents: bool = False, exist_ok: bool = False) None

Implementation of pathlib.Path.mkdir() adding remote server support.

Parameters:
  • mode (optional, default=0o777) – The access mode of the created directory.

  • parents (optional, default=False) – If True, also create intermediate directories.

  • exist_ok (optional, default=False) – If True, do not throw an exception if the path already exists.

Returns:

Nothing.

property parent

A read-only property which returns the parent of the path.

property path_type

A read-only property which returns the path type.

property remote: PathName

A read-only property which returns the name of this remote server which hosts the path.

rename(new: str, /) CommandResult | PathName

Implementation of pathlib.Path.rename() adding remote server support.

Parameters:

new – The new path name.

Returns:

The result of the rename.

rmdir(remote_rm_command: List[PathName] | None = None, *, recursive: bool = False) None

Implementation of pathlib.Path.rmdir() adding remote server support.

Parameters:
  • remote_rm_command (optional, default=None) – If not None, the command to use if the path is remote other than the default.

  • recursive (optional, default=False) – If True, also remove all subdirectories.

Returns:

Nothing.

property server

A read-only property which returns the owning server of the path.

walk() Iterator[Tuple[str, List[str], List[str]]]

Implementation of os.walk() adding remote server support.

Returns:

The result of the walk.

Raises:

ServerPathError.INVALID_OPERATION – If the command is not supported on the target path.

property win_to_win

A read-only property which returns True if the both the local and remote systems are Windows servers.

exception batcave.serverpath.ServerPathError(err_obj: BatCaveError, /, **variables)

Bases: BatCaveException

ServerPath Exceptions.

INVALID_OPERATION

The specified server type does not support the requested operation.

REMOTE_COPY_SPACE_ERROR

The remote server did not have enough disk space for the copy.

INVALID_OPERATION = BatCaveError(code=1, msg='This function is only supported for remote Windows servers from Windows servers')
REMOTE_COPY_SPACE_ERROR = BatCaveError(code=2, msg=<string.Template object>)

batcave.statemachine module

This module implements a simple state machine.

class batcave.statemachine.StateMachine(states: Sequence, /, *, statefile: PathName = PosixPath('state'), lockfile: PathName = PosixPath('lock'), autostart: bool = True)

Bases: object

This class implements a classic state machine.

_DEFAULT_STATEFILE

The default file to use to store the current state information.

_DEFAULT_LOGFILE

The default file to use to store the log information.

_DEFAULT_LOCKFILE

The default file to use for file locking.

done() None

Shutdown the state machine.

Returns:

Nothing.

enter_next_state() None

Enter the next state.

Returns:

Nothing.

Raises:
  • StateMachineError.BAD_ENTRY – If the state machine has not exitted from the previous start.

  • StateMachineError.DONE – If the state machine has already completed.

  • StateMachineError.NOT_STARTED – If the state machine has not been started.

exit_state() None

Exit the current state.

Returns:

Nothing.

Raises:
  • StateMachineError.BAD_EXIT – If the state machine has not entered a state.

  • StateMachineError.NOT_STARTED – If the state machine has not been started.

reset() None

Reset the state machine.

Returns:

Nothing.

rollback() None

Rollback to the previous state.

Returns:

Nothing.

Raises:

StateMachineError.BAD_ROLLBACK – If the state machine has not entered a state.

start() None

Start the state machine.

Returns:

Nothing.

Raises:
  • StateMachineError.CRASHED – If the state machine crashed on the previous run.

  • StateMachineError.ALREADY_STARTED – If the state machine has already been started.

exception batcave.statemachine.StateMachineError(err_obj: BatCaveError, /, **variables)

Bases: BatCaveException

State Machine Exceptions.

ALREADY_STARTED

There was an attempt to start a state machine that is already in progress.

BAD_ENTRY

There was an attempt to enter next state before exiting current one.

BAD_EXIT

There was an attempt to exit the state before it was entered.

BAD_ROLLBACK

There was an attempt to rollback a state before it entered.

BAD_STATUS

An invalid status was requested.

CRASHED

The state machine crashed in a state.

DONE

There was an attempt to enter a state after the final state.

NOT_STARTED

There was an attempt to continue a state machine that has not started.

ALREADY_STARTED = BatCaveError(code=1, msg='State machine already started')
BAD_ENTRY = BatCaveError(code=2, msg='Attempt to enter next state before exiting current one')
BAD_EXIT = BatCaveError(code=3, msg='Attempt to exit state before entering')
BAD_ROLLBACK = BatCaveError(code=4, msg='Attempt to rollback state before entering')
BAD_STATUS = BatCaveError(code=5, msg=<string.Template object>)
CRASHED = BatCaveError(code=6, msg=<string.Template object>)
DONE = BatCaveError(code=7, msg='Attempt to enter state after final state')
NOT_STARTED = BatCaveError(code=8, msg='State machine not started')
class batcave.statemachine.StateStatus(*values)

Bases: Enum

entering = 1
exited = 2

batcave.sysutil module

This module provides a Pythonic interface to work with system utilities.

batcave.sysutil.PROG_FILES

The default software installation location For 32-bit Windows systems this is the value of the ProgramFiles(x86) environment variable. For 64-bit Windows systems this is the value of the ProgramFiles environment variable. For all other systems it is /usr/local.

Type:

dict

batcave.sysutil.S_660

A quick version of the UNIX 0660 mode.

batcave.sysutil.S_664

A quick version of the UNIX 0664 mode.

batcave.sysutil.S_770

A quick version of the UNIX 0770 mode.

batcave.sysutil.S_775

A quick version of the UNIX 0775 mode.

exception batcave.sysutil.CMDError(err_obj: BatCaveError, /, **variables)

Bases: BatCaveException

System Command Exceptions.

CMD_ERROR

Generic command error.

CMD_NOT_FOUND

The command was not found.

INVALID_OPERATION

The requested operation is not supported in the current context.

CMD_ERROR = BatCaveError(code=1, msg='')
CMD_NOT_FOUND = BatCaveError(code=2, msg=<string.Template object>)
INVALID_OPERATION = BatCaveError(code=3, msg=<string.Template object>)
exception batcave.sysutil.LockError(err_obj: BatCaveError, /, **variables)

Bases: BatCaveException

Lock File Exceptions.

NO_LOCK

There was a failure attempting to get a lock on the lock file.

NO_LOCK = BatCaveError(code=1, msg=<string.Template object>)
class batcave.sysutil.LockFile(filename: PathName, /, handle: TextIO | None = None, *, cleanup: bool = True)

Bases: object

Class to create a universal abstract interface for an OS lock file.

action(mode: LockMode, /) None

Perform the requested action on the lock file.

Parameters:

mode – The action to perform on the lock file.

Returns:

Nothing.

Raises:

LockError.NO_LOCK – If it was not possible to obtain a system level lock on the lock file.

close() None

Close the lock file.

Returns:

Nothing.

class batcave.sysutil.LockMode(*values)

Bases: Enum

lock = 1
unlock = 2
exception batcave.sysutil.OSUtilError(err_obj: BatCaveError, /, **variables)

Bases: BatCaveException

Operating System Exceptions.

GROUP_EXISTS

The specified group already exists.

INVALID_OPERATION

The requested operation is not supported on the current platform.

USER_EXISTS

The specified user already exists.

GROUP_EXISTS = BatCaveError(code=1, msg=<string.Template object>)
INVALID_OPERATION = BatCaveError(code=2, msg=<string.Template object>)
USER_EXISTS = BatCaveError(code=3, msg=<string.Template object>)
class batcave.sysutil.SysCmdRunner(command: str, /, *args, show_cmd: bool = True, show_stdout: bool = True, syscmd_args: Dict[Any, Any] | None = None, **kwargs)

Bases: object

This class provides a simplified interface to sysutil.syscmd().

run(*args, post_option_args: Dict | None = None, syscmd_args: Dict[Any, Any] | None = None, **kwargs) CommandResult

Run the defined command with the additional specified arguments.

Parameters:
  • post_option_args (optional, default=[]) – The list of args to pass after the options.

  • syscmd_args (optional, default={}) – The list of default args passed to syscmd.

  • *args (optional, default=[]) – Any extra arguments to pass to the command.

  • **kwargs (optional, default={}) – Any extra keyword arguments to pass to the command.

Returns:

The result of the syscmd call.

batcave.sysutil.chmod(dirname: PathName, mode: int, *, recursive: bool = False, files_only: bool = False) None

Perform chmod recursively if requested.

Parameters:
  • dirname – The directory for which to set the mode.

  • mode – The mode to set as would be specified for os.chmod().

  • recursive (optional, default=False) – Also perform setting recursively on all children.

  • files_only (optional, default=False) – Only affect files.

Returns:

Nothing.

batcave.sysutil.chown(pathname: PathName, user: str | int, group: str | int | None = None, *, recursive: bool = False) None

Perform chown and chgrp together, recursively if requested.

Parameters:
  • user (optional, default=None) – The user to set as the owner, if specified.

  • group (optional, default=None) – The group to set as the owner, if specified.

  • recursive (optional, default=False) – Also perform the user/owner settings recursively on all children.

Returns:

Nothing.

batcave.sysutil.create_group(group_name: str, /, *, exists_ok: bool = True) None

Create the system group at the OS level.

Parameters:
  • group_name – The group to create.

  • exists_ok (optional, default=True) – Do not raise an error if the group exists.

Returns:

Nothing.

Raises:
  • OSUtilError.GROUP_EXISTS – If the group exists and exists_ok is False.

  • OSUtilError.INVALID_OPERATION – If this is a Windows platform.

batcave.sysutil.create_user(username: str, /, groups: Tuple = (), *, exists_ok: bool = True) None

Create the user account at the OS level.

Parameters:
  • username – The user account to create.

  • exists_ok (optional, default=True) – Do not raise an error if the user exists.

Returns:

Nothing.

Raises:
  • OSUtilError.USER_EXISTS – If the user exists and exists_ok is False.

  • OSUtilError.INVALID_OPERATION – If this is a Windows platform.

batcave.sysutil.get_app_config_dir(app_name: str, /) Path

Return the platform-appropriate application configuration directory.

The returned path follows OS conventions:

Windows: %APPDATA%/app_name macOS: ~/Library/Preferences/app_name Linux/other: $XDG_CONFIG_HOME/app_name (defaults to ~/.config/app_name)

Parameters:

app_name – The application name used as the directory name.

Returns:

The Path to the application configuration directory.

batcave.sysutil.get_app_data_dir(app_name: str, /) Path

Return the platform-appropriate application data directory.

The returned path follows OS conventions:

Windows: %LOCALAPPDATA%/app_name macOS: ~/Library/Application Support/app_name Linux/other: $XDG_DATA_HOME/app_name (defaults to ~/.local/share/app_name)

Parameters:

app_name – The application name used as the directory name.

Returns:

The Path to the application data directory.

batcave.sysutil.is_user_administrator() bool

Determines if the current user is an OS administrator.

Parameters:

None

Returns:

True if the user is an administrator, False otherwise.

batcave.sysutil.popd() int | PathName

Implements the pop function for a directory stack.

Parameters:

None.

Returns:

The value of the directory removed from the stack.

Raises:

IndexError – If the stack is empty.

batcave.sysutil.pushd(dirname: PathName, /) PathName

Implements the push function for a directory stack.

Parameters:

dirname – The directory to which to change.

Returns:

The value of the directory pushed to the stack.

batcave.sysutil.rmpath(path_name: PathName, /) None

Remove the specified path object. If a directory, remove recursively.

Parameters:

path_name – The name of the path object to remove.

Returns:

Nothing.

batcave.sysutil.rmtree_hard(tree: PathName, /) None

Recursively, remove a directory and try to avoid non-fatal errors.

Parameters:

tree – The directory tree to remove.

Returns:

Nothing.

batcave.sysutil.syscmd(command: PathName, /, *cmd_args, input_lines: Iterable | None = None, show_stdout: bool = False, ignore_stderr: bool = False, append_stderr: bool = False, fail_on_error: bool = True, show_cmd: bool = False, use_shell: bool = False, flatten_output: bool = False, remote: bool | str | None = False, remote_is_windows: bool | None = None, copy_for_remote: bool = False, remote_auth: ServerAuthType | None = None, remote_powershell: bool = False) CommandResult

Wrapper to provide a better interface to subprocess.Popen().

Parameters:
  • command

  • *cmd_args

  • input_lines=None

  • show_stdout=False

  • ignore_stderr=False

  • append_stderr=False

  • fail_on_error=True

  • show_cmd=False

  • use_shell=False

  • flatten_output=False

  • remote=False

  • remote_is_windows=None

  • copy_for_remote=False

  • remote_auth=False

  • remote_powershell=False

Returns:

The string (or string-list) output of the command.

Raises:
  • CMDError.INVALID_OPERATION – If any remote options are provided but remote is False.

  • CMDError.CMD_NOT_FOUND – If the requested command is not found.

  • CMDError.CMD_ERROR – If fail_on_error is True, and the return code is non-zero, or there is output on stderr if ignore_stderr is True.

batcave.tcpy module

This module provides a Pythonic interface to the TeamCity RESTful API.

class batcave.tcpy.TCBuildConfig(server: TeamCityServer, config_id: str, /)

Bases: object

Class to create a universal abstract interface for a TeamCity build configuration.

exception batcave.tcpy.TeamCityError(err_obj: BatCaveError, /, **variables)

Bases: BatCaveException

TeamCity Exceptions.

BAD_CONFIG

The requested configuration was not found.

BAD_CONFIG = BatCaveError(code=1, msg=<string.Template object>)
class batcave.tcpy.TeamCityServer(host: str, /, user: str, passwd: str, port: str = '80')

Bases: object

Class to create a universal abstract interface for a TeamCity server.

api_call(call_type: str, api_call: str, /, **params) Dict[str, Any]

Provide an interface to the TeamCity RESTful API.

Parameters:
  • call_type – The API call type.

  • api_call – The API call.

  • **params (optional, default={}) – Any parameters to pass to the API call.

Returns:

The result of the API call.

Raises:

An error unless the result of the API call is OK.

property build_configs

A read-only property which returns a list of the build configurations.

create_group(name: str, key: str | None = None, /, description: str = '') Dict[str, Any]

Create a user group.

Parameters:
  • name – The name of user group.

  • key (optional, default=None) – The key name to use for the user group.

  • description (optional, default='') – The description to use for the user group.

Returns:

The result of the API call to create the user group.

create_user(username: str, /) Dict[str, Any]

Create a user.

Parameters:

username – The name of user.

Returns:

The result of the API call to create the user group.

get_build_config(config: str, /) TCBuildConfig

Get the named build configuration.

Parameters:

config – The build configuration to return.

Returns:

The requested build configuration.

property groups

A read-only property which returns a list of the TeamCity groups.

property users

A read-only property which returns a list of the TeamCity users.

batcave.time module

This module provides improved date/time support.

class batcave.time.BatCaveDateTime(time_info: BatCaveDateTimeType | None = None)

Bases: object

Class to manage date/time values.

ctime() str

Return the ctime representation.

property datetime

A read-only property which returns the datetime representation.

exception batcave.time.TimeError(err_obj: BatCaveError, /, **variables)

Bases: BatCaveException

Class for time exceptions.

BAD_CONVERSION_TYPE = BatCaveError(code=1, msg=<string.Template object>)

batcave.version module

This module provides utilities for working with versions.

batcave.version.PYQT_LOADED

If not False then it is the string version of the PyQt API.

Type:

bool/str

batcave.version.VersionStyle

The version output styles.

Type:

Enum

class batcave.version.AppVersion(title: str, version: str, build_date: str = '', build_name: str = '', copyright: str = '')

Bases: object

This class holds the version information for the running application.

title

The application title.

Type:

str

version

The application version.

Type:

str

build_date

The application build date.

Type:

str

build_name

The application build name.

Type:

str

copyright

The application copyright.

Type:

str

build_date: str = ''
build_name: str = ''
copyright: str = ''
get_info(style: VersionStyle = VersionStyle.full, /, plattype: str = 'batcave_run', extra_info: str = '') str

Get the version information about the currently running application.

Parameters:
  • style (optional, default=full) – The format for the version string to be returned.

  • plattype (optional, default='batcave_run') – The platform type for the architecture information in the version string.

  • extra_info (optional, default='') – A line to append after the version info but before the copyright.

Returns:

Returns the version string.

title: str
version: str
class batcave.version.VersionStyle(*values)

Bases: Enum

about_box = 4
brief = 2
full = 1
one_line = 3

Module contents

BatCave Utilities module.

This module provides utilities for making it easier to write Python programs.

The exported modules fall into several categories:

Modules that provide simplified interfaces to standard modules:
  • commander - argparse

  • platarch - platform

Modules that provide simplified interfaces to third-party modules:
  • gui - PyQt5

  • k8s - kubernetes

Modules that provide Pythonic interfaces to external systems:
  • cloudmgr - cloud resources

  • cms - code management systems

  • data - data sources

  • iispy - Internet Information Server

  • netutil - network services

  • qbpy - QuickBuild

  • servermgr - OS-independent servers

  • sysutil - system utilities

  • tcpy - TeamCity

Modules that provide utilities for accomplishing specific programming tasks:
  • automation - building automation

  • configmgr - managing configurations

  • expander - working with string expansion

  • fileutil - working with files

  • lang - Python language utilities

  • menu - creating command line menus

  • statemachine - a simple state machine

  • reporter - creating reports

  • version - reporting version information