Builtin Functions

The contents of this page can be generated using:

spaces docs

abs()

def abs()

Take the absolute value of an int.

abs(0)   == 0
abs(-10) == 10
abs(10)  == 10
abs(10.0) == 10.0
abs(-12.34) == 12.34

all()

def all() -> bool

all: returns true if all values in the iterable object have a truth value of true.

all([1, True]) == True
all([1, 1]) == True
all([0, 1, True]) == False
all([True, 1, True]) == True
all([0, 0]) == False
all([0, False]) == False
all([True, 0]) == False
all([1, False]) == False

any()

def any() -> bool

any: returns true if any value in the iterable object have a truth value of true.

any([0, True]) == True
any([0, 1]) == True
any([0, 1, True]) == True
any([0, 0]) == False
any([0, False]) == False

checkout

add_any_assets()

def add_any_assets() -> NoneType

Adds any number of assets, with support for different asset types.

checkout.add_any_assets(
    rule = {
        "name": "add_multiple_files",
    },
    assets = [
        { "type": "hardlink", "source": "path/to/file1.txt", "destination": "sysroot/file1.txt" },
        { "type": "symlink", "source": "path/to/file2.txt", "destination": "sysroot/file2.txt" }
    ]
)

Args

  • rule: A dict rule definition.
  • assets: A list of asset dictionaries, where each dictionary specifies the asset’s type and its properties (e.g., source and destination).

update_env()

def update_env() -> NoneType

Creates or updates the environment in the workspace during checkout.

checkout.update_env(
    rule = {"name": "update_env"},
    env = {
        "paths": [],
        "system_paths": ["/usr/bin", "/bin"],
        "vars": {
            "PS1": '"(spaces) $PS1"',
        },
        "inherited_vars": ["HOME", "SHELL", "USER"],
        "optional_inherited_vars": ["TERM"],
        "secret_inherited_vars": ["SSH_AUTH_SOCK"],
    },
)

Args

  • rule: A dict rule definition containing name (str), deps (list), platforms (list), type (str), and help (str).
  • env: A dict containing environment details. Variables are execution-phase dependent; they are available in subsequent modules during checkout and fully available during spaces run. * vars (dict): Environment variables to set. * paths (list): Paths to prepend to PATH. * system_paths (list): Paths appended to the end of PATH. * inherited_vars (list): Variables fixed from the calling environment at checkout. * secret_inherited_vars (list): Variables inherited on demand with masked log values.

store_value()

def store_value(key, value) -> NoneType

Stores a key-value pair in the workspace settings, namespaced by the calling module’s member path in the workspace.

The value is available immediately after storing and persists across checkout evaluations. Use workspace.load_value() to retrieve stored values.

checkout.store_value("my_key", {"version": "1.0", "enabled": True})
checkout.store_value("build_count", 42)
checkout.store_value("name", "my_project")

Args

  • key: string: A string key to identify the stored value.
  • value: Any JSON-compatible value (string, number, bool, list, dict, None).

add_soft_link_asset()

def add_soft_link_asset() -> NoneType

Creates a symbolic link from a source to a destination path.

checkout.add_soft_link_asset(
    rule = {
        "name": "symlink_file",
    },
    asset = {
        "source": "path/to/original/file.txt",
        "destination": "sysroot/symlink/to/file.txt"
    }
)

Args

  • rule: A dict rule definition.
  • asset: A dict containing source and destination paths for the symbolic link.

add_archive()

def add_archive() -> NoneType

Adds an archive to the workspace.

checkout.add_archive(
    # the rule name is the path in the workspace where the archive will be extracted
    rule = {"name": "llvm-project"},
    archive = {
        "url": "[https://github.com/llvm/llvm-project/archive/refs/tags/llvmorg-](https://github.com/llvm/llvm-project/archive/refs/tags/llvmorg-){}.zip".format(version),
        "sha256": "27b5c7c745ead7e9147c78471b9053d4f6fc3bed94baf45f4e8295439f564bb8",
        "link": "Hard",
        "strip_prefix": "llvm-project-llvmorg-{}".format(version),
        "add_prefix": "llvm-project",
    },
)

Args

  • rule: A dict rule definition containing name (str), deps (list), platforms (list), type (str), and help (str).
  • archive: A dict containing url (str), sha256 (str), link (None|Hard), globs (list), strip_prefix (str), and add_prefix (str).

add_exec()

def add_exec() -> NoneType

Adds a process to execute during checkout.

checkout.add_exec(
    rule = {"name": "my_rule", "deps": ["my_other_rule"]},
    exec = {"command": "ls", "arguments": ["-l"]}
)

Args

  • rule: A dict containing the rule definition.
  • exec: A dict containing the execution details.

add_repo()

def add_repo() -> NoneType

Adds a git repository to the workspace.

checkout.add_repo(
    # the rule name is also the path in the workspace where the clone will be
    rule = { "name": "spaces" },
    repo = {
        "url": "[https://github.com/work-spaces/spaces](https://github.com/work-spaces/spaces)",
        "rev": "main",
        "checkout": "Revision",
        "clone": "Default",
        "is_evaluate_spaces_modules": True
    }
)

Args

  • rule: rule definition containing
  • repo: repository details containing

add_platform_archive()

def add_platform_archive() -> NoneType

Adds an archive to the workspace based on the platform.

base = {
    "add_prefix": "sysroot/bin",
    "strip_prefix": "target/release",
    "link": "Hard",
}

macos_x86_64 = base | {
    "url": "[https://github.com/work-spaces/spaces/releases/download/v0.6.0-beta.13/spaces-macos-latest-x86_64-v0.6.0-beta.13.zip](https://github.com/work-spaces/spaces/releases/download/v0.6.0-beta.13/spaces-macos-latest-x86_64-v0.6.0-beta.13.zip)",
    "sha256": "47d325145e6f7f870426f1b123c781f89394b0458bb43f5abe2d36ac3543f7ef",
}

macos_aarch64 = base | {
    "url": "[https://github.com/work-spaces/spaces/releases/download/v0.6.0-beta.13/spaces-macos-latest-aarch64-v0.6.0-beta.13.zip](https://github.com/work-spaces/spaces/releases/download/v0.6.0-beta.13/spaces-macos-latest-aarch64-v0.6.0-beta.13.zip)",
    "sha256": "6dd972454942faa609670679c53b6876ab8e66bcfd0b583ee5a8d13c93b2e879",
}

linux_x86_64 = base | {
    "url": "[https://github.com/work-spaces/spaces/releases/download/v0.6.0-beta.13/spaces-linux-gnu-x86_64-v0.6.0-beta.13.zip](https://github.com/work-spaces/spaces/releases/download/v0.6.0-beta.13/spaces-linux-gnu-x86_64-v0.6.0-beta.13.zip)",
    "sha256": "39030124f18b338eceee09061fb305b522ada76f6a0562f9926ea0747b3ad440",
}

linux_aarch64 = base | {
    "url": "https://github.com/work-spaces/spaces/releases/download/v0.6.0-beta.13/spaces-linux-gnu-aarch64-v0.6.0-beta.13.zip",
    "sha256": "39030124f18b338eceee09061fb305b522ada76f6a0562f9926ea0747b3ad440",
}

windows_x86_64 = base | {
    "url": "[https://github.com/work-spaces/spaces/releases/download/v0.6.0-beta.13/spaces-windows-latest-x86_64-v0.6.0-beta.13.exe](https://github.com/work-spaces/spaces/releases/download/v0.6.0-beta.13/spaces-windows-latest-x86_64-v0.6.0-beta.13.exe)",
    "sha256": "b93dc96b2c66fcfc4aef851db2064f6e6ecb54b29968ca5174f6b892b99651c8",
}

windows_aarch64 = base | {
    "url": "[https://github.com/work-spaces/spaces/releases/download/v0.6.0-beta.13/spaces-windows-latest-aarch64-v0.6.0-beta.13.exe](https://github.com/work-spaces/spaces/releases/download/v0.6.0-beta.13/spaces-windows-latest-aarch64-v0.6.0-beta.13.exe)",
    "sha256": "c67c7b23897e0949843e248465d5444428fb287f89dcd45cec76dde4b2cdc6a9",
}

checkout.add_platform_archive(
    # rule name is only the path in the workspace if add_prefix is not set
    rule = {"name": "spaces"},
    platforms = {
        "macos-x86_64": macos_x86_64,
        "macos-aarch64": macos_aarch64,
        "windows-x86_64": windows_x86_64,
        "windows-aarch64": windows_aarch64,
        "linux-x86_64": linux_x86_64,
    },
)

Args

  • rule: A dict rule definition containing name (str), deps (list), platforms (list), type (str), and help (str).
  • platforms: A dict of platform keys (e.g., macos-aarch64, linux-x86_64) mapping to archive detail dicts.

add_env_vars()

def add_env_vars() -> NoneType

Creates or updates the environment in the workspace during checkout.

checkout.update_env(
    rule = {"name": "update_env"},
    env = {
        "paths": [],
        "system_paths": ["/usr/bin", "/bin"],
        "vars": {
            "PS1": '"(spaces) $PS1"',
        },
        "inherited_vars": ["HOME", "SHELL", "USER"],
        "optional_inherited_vars": ["TERM"],
        "secret_inherited_vars": ["SSH_AUTH_SOCK"],
    },
)

Args

  • rule: A dict rule definition containing name (str), deps (list), platforms (list), type (str), and help (str).
  • any_env:

add_hard_link_asset()

def add_hard_link_asset() -> NoneType

Creates a hardlink from a source to a destination path.

checkout.add_hard_link_asset(
    rule = {
        "name": "link_file",
    },
    asset = {
        "source": "path/to/original/file.txt",
        "destination": "sysroot/link/to/file.txt"
    }
)

Args

  • rule: A dict rule definition.
  • asset: A dict containing source and destination paths.

add_cargo_bin()

def add_cargo_bin() -> NoneType

Adds a binary crate using cargo-binstall.

checkout.add_cargo_bin(
    rule = {"name": "probe-rs-tools"},
    cargo_bin = {
        "crate": "probe-rs-tools",
        "version": "0.24.0",
        "bins": ["probe-rs", "cargo-embed", "cargo-flash"]
    },
)

Args

  • rule: A dict rule definition containing name (str), deps (list), platforms (list), type (str), and help (str).
  • cargo_bin: A dict of crate details containing crate (str), version (str), and bins (list).

abort()

def abort(message) -> NoneType

Abort script evaluation with a message.

checkout.abort("Failed to do something")

Args

  • message: string: Abort message to show the user.

update_asset()

def update_asset() -> NoneType

Creates or updates an existing file containing structured data in the workspace.

cargo_vscode_task = {
    "type": "cargo",
    "problemMatcher": ["$rustc"],
    "group": "build",
}

# Add some VS code tasks
checkout.update_asset(
    rule = {"name": "vscode_tasks"},
    asset = {
        "destination": ".vscode/tasks.json",
        "format": "json",
        "value": {
            "tasks": [
                cargo_vscode_task | {
                    "command": "build",
                    "args": ["--manifest-path=spaces/Cargo.toml"],
                    "label": "build:spaces",
                },
                cargo_vscode_task | {
                    "command": "install",
                    "args": ["--path=spaces", "--root=${userHome}/.local", "--profile=dev"],
                    "label": "install_dev:spaces",
                }
            ],
        },
    }
)

Args

  • rule: A dict rule definition containing name (str), deps (list), platforms (list), type (str), and help (str).
  • asset: A dict containing destination (str), format (json|toml|yaml), and value (dict). Supports multi-rule updates to the same file if keys are unique.

add_asset()

def add_asset() -> NoneType

Adds a file to the workspace.

content = "Hello. This is the content"

checkout.add_asset(
    rule = {"name": "README.md"},
    asset = {
        "destination": "README.md",
        "content": content,
    },
)

Args

  • rule: A dict rule definition containing name (str), deps (list), platforms (list), type (str), and help (str).
  • asset: A dict of asset details containing content (str) and destination (str).

add_target()

def add_target() -> NoneType

Adds a target to organize dependencies.

checkout.add_target(
    rule = {"name": "my_rule", "deps": ["my_other_rule"]},
)

Args

  • rule: A dict containing the rule definition (e.g., name, deps, platforms, type, and help).

add_oras_archive()

def add_oras_archive() -> NoneType

Args

  • rule:
  • oras_archive:

add_which_asset()

def add_which_asset() -> NoneType

Adds a hardlink to an executable file available on the PATH.

checkout.add_which_asset(
    rule = { "name": "which_pkg_config" },
    asset = {
        "which": "pkg-config",
        "destination": "sysroot/bin/pkg-config"
    }
)

Args

  • rule: A dict rule definition containing name (str), deps (list), platforms (list), type (str), and help (str).
  • asset: A dict containing which (str) and destination (str). Note: This creates system dependencies that may break workspace hermeticity.

chr()

def chr() -> string

chr: returns a string encoding a codepoint.

chr(i) returns a string that encodes the single Unicode code point whose value is specified by the integer i. chr fails unless 0 ≤ i ≤ 0x10FFFF.

chr(65) == 'A'
chr(1049) == 'Й'
chr(0x1F63F) == '😿'

debug()

def debug(content) -> NoneType

Args

  • content:

dir()

def dir() -> list

dir: list attributes of a value.

dir(x) returns a list of the names of the attributes (fields and methods) of its operand. The attributes of a value x are the names f such that x.f is a valid expression.

"capitalize" in dir("abc")

enumerate()

def enumerate(start) -> list

enumerate: return a list of (index, element) from an iterable.

enumerate(x) returns a list of (index, value) pairs, each containing successive values of the iterable sequence and the index of the value within the sequence.

The optional second parameter, start, specifies an integer value to add to each index.

enumerate(["zero", "one", "two"]) == [(0, "zero"), (1, "one"), (2, "two")]
enumerate(["one", "two"], 1) == [(1, "one"), (2, "two")]

Args

  • start: int:

fail()

def fail()

fail: fail the execution

fail("this is an error")  # fail: this is an error
fail("oops", 1, False)  # fail: oops 1 False

fs

append_string_to_file()

def append_string_to_file() -> NoneType

Appends a string to the end of a file at the specified path.

fs.append_string_to_file(path = "log/output.txt", content = "New log entry\n")

Args

  • path: string: The destination path relative to the workspace root.
  • content: string: The string data to append to the file.

exists()

def exists(path) -> bool

Returns true if the given path exists.

if fs.exists("config/settings.json"):
    print("Settings file found")

Args

  • path: string: The path to check relative to the workspace root.

Returns

  • bool: True if the path exists, False otherwise.

read_file_to_string()

def read_file_to_string(path) -> string

Reads the contents of a file and returns it as a string.

content = fs.read_file_to_string("config/settings.json")

Args

  • path: string: The path to the file relative to the workspace root.

Returns

  • str: The contents of the file as a string.

is_file()

def is_file(path) -> bool

Returns true if the given path is a file.

if fs.is_file("config/settings.json"):
    print("Path is a file")

Args

  • path: string: The path to check relative to the workspace root.

Returns

  • bool: True if the path is a file, False otherwise.

read_yaml_to_dict()

def read_yaml_to_dict(path)

Reads a YAML file and returns its contents as a dictionary.

config = fs.read_yaml_to_dict("config.yaml")
print(config["settings"]["theme"])

Args

  • path: string: The path to the YAML file relative to the workspace root.

Returns

  • dict: The parsed YAML contents as a dictionary.

write_string_to_file()

def write_string_to_file() -> NoneType

Writes a string to a file at the specified path relative to the workspace root.

If the file already exists, its contents will be truncated (overwritten). If the file does not exist, it will be created.

fs.write_string_to_file(path = "config/settings.json", content = '{"theme": "dark"}')

Args

  • path: string: The destination path relative to the workspace root.
  • content: string: The string data to write into the file.

read_toml_to_dict()

def read_toml_to_dict(path)

Reads a TOML file and returns its contents as a dictionary.

config = fs.read_toml_to_dict("Cargo.toml")
print(config["package"]["name"])

Args

  • path: string: The path to the TOML file relative to the workspace root.

Returns

  • dict: The parsed TOML contents as a dictionary.

is_symlink()

def is_symlink(path) -> bool

Returns true if the given path is a symbolic link.

if fs.is_symlink("bin/tool"):
    print("Path is a symlink")

Args

  • path: string: The path to check relative to the workspace root.

Returns

  • bool: True if the path is a symbolic link, False otherwise.

is_directory()

def is_directory(path) -> bool

Returns true if the given path is a directory.

if fs.is_directory("config"):
    print("Path is a directory")

Args

  • path: string: The path to check relative to the workspace root.

Returns

  • bool: True if the path is a directory, False otherwise.

read_json_to_dict()

def read_json_to_dict(path)

Reads a JSON file and returns its contents as a dictionary.

data = fs.read_json_to_dict("package.json")
print(data["name"])

Args

  • path: string: The path to the JSON file relative to the workspace root.

Returns

  • dict: The parsed JSON contents as a dictionary.

is_text_file()

def is_text_file(path) -> bool

Returns true if the given path is a text file.

if fs.is_text_file("output/result.dat"):
    print("File contains text")

Args

  • path: string: The path to check relative to the workspace root.

Returns

  • bool: True if the path is a text file, False otherwise.

read_directory()

def read_directory(path) -> list

Reads the contents of a directory and returns a list of paths.

entries = fs.read_directory("src")
for entry in entries:
    print(entry)

Args

  • path: string: The path to the directory relative to the workspace root.

Returns

  • list[str]: A list of paths for each entry in the directory.

getattr()

def getattr()

getattr: returns the value of an attribute

getattr(x, name) returns the value of the attribute (field or method) of x named name. It is a dynamic error if x has no such attribute.

getattr(x, "f") is equivalent to x.f.

getattr(x, "f", d) is equivalent to x.f if hasattr(x, "f") else d and will never raise an error.

getattr("banana", "split")("a") == ["b", "n", "n", ""] # equivalent to "banana".split("a")

hasattr()

def hasattr() -> bool

hasattr: test if an object has an attribute

hasattr(x, name) reports whether x has an attribute (field or method) named name.

hash

compute_sha256_from_file()

def compute_sha256_from_file(file_path) -> string

Computes the SHA-256 checksum for the contents of a file.

checksum = hash.compute_sha256_from_file("data/model.bin")
print(f"File SHA-256: {checksum}")

Args

  • file_path: string: The path to the file to be hashed.

Returns

  • str: The hex-encoded SHA-256 digest of the file.

compute_sha256_from_string()

def compute_sha256_from_string(input) -> string

Computes the SHA-256 checksum for a given string.

text_hash = hash.compute_sha256_from_string("my-unique-identity")
print(f"String Hash: {text_hash}")

Args

  • input: string: The raw string to be hashed.

Returns

  • str: The hex-encoded SHA-256 digest of the input string.

info

is_ci()

def is_ci() -> bool

Returns true if the --ci flag was passed on the command line.

if info.is_ci():
    # ...

Returns

  • bool: True if the --ci flag is present, False otherwise.

is_platform_windows()

def is_platform_windows() -> bool

Returns true if the current platform is Windows.

if info.is_platform_windows():
    # ...

Returns

  • bool: True if the platform is windows-x86_64 or windows-aarch64, False otherwise.

is_platform_aarch64()

def is_platform_aarch64() -> bool

Returns true if the current platform architecture is aarch64.

if info.is_platform_aarch64():
    # ...

Returns

  • bool: True if the platform architecture is aarch64, False otherwise.

get_supported_platforms()

def get_supported_platforms() -> list

Returns a list of all platforms supported by the system.

supported = info.get_supported_platforms()
if "macos-aarch64" in supported:
    print("This system supports Apple Silicon.")

Returns

  • list[str]: A list of supported platform identifiers, such as macos-aarch64, linux-x86_64, etc.

get_cpu_count()

def get_cpu_count() -> int

Returns the number of CPUs on the current machine.

num_cpus = info.get_cpu_count()

Returns

  • int: The total number of logical CPU cores available.

check_required_semver()

def check_required_semver(required) -> bool

Checks if the current version of spaces satisfies the given semver requirement.

is_compatible = info.check_required_semver("^2.1.0")
if not is_compatible:
    # ...

Args

  • required: string: The semantic version requirement string to check against.

Returns

  • bool: True if the current version satisfies the requirement, False otherwise.

get_path_to_spaces_tools()

def get_path_to_spaces_tools() -> string

Returns the path to the spaces tools directory.

tools_path = info.get_path_to_spaces_tools()

Returns

  • str: The absolute path to the spaces tools directory.

set_required_semver()

def set_required_semver(required) -> NoneType

Sets the semantic version of spaces required to run the workspace.

info.set_required_semver("^2.1.0")

Args

  • required: string: The semantic version requirement string (e.g., “^2.1.0”).

get_log_divider_string()

def get_log_divider_string() -> string

Returns a string representing the end of the log header.

divider = info.get_log_divider_string()

Returns

  • str: The standard divider string used to separate log headers from the body.

parse_log_file()

def parse_log_file(path)

Parses a log file into its YAML header and message lines.

log_data = info.parse_log_file("outputs/build.log")
for line in log_data['lines']:
    # ...

Args

  • path: string: The absolute or relative path to the spaces log file.

Returns

  • dict: A dictionary containing header (dict) with the parsed YAML metadata and lines (list[str]) with the body of the log.

get_platform_name()

def get_platform_name() -> string

Returns the name of the current operating system and architecture platform.

platform = info.get_platform_name()
if "linux" in platform:
    # ...

Returns

  • str: The platform identifier, such as macos-aarch64, macos-x86_64, linux-x86_64, linux-aarch64, windows-x86_64, or windows-aarch64.

is_platform_linux()

def is_platform_linux() -> bool

Returns true if the current platform is Linux.

if info.is_platform_linux():
    # ...

Returns

  • bool: True if the platform is linux-x86_64 or linux-aarch64, False otherwise.

set_minimum_version()

def set_minimum_version(version) -> NoneType

Sets the minimum version of spaces required to run the script.

info.set_minimum_version("1.2.0")

Args

  • version: string: The minimum version string (e.g., “1.5.0”) required.

set_max_queue_count()

def set_max_queue_count(count) -> NoneType

Sets the maximum number of items that can be queued at one time.

info.set_max_queue_count(10)

Args

  • count: int: The maximum number of items to allow in the queue.

is_platform_x86_64()

def is_platform_x86_64() -> bool

Returns true if the current platform architecture is x86_64.

if info.is_platform_x86_64():
    # ...

Returns

  • bool: True if the platform architecture is x86_64, False otherwise.

abort()

def abort(message) -> NoneType

Abort script evaluation with a message.

info.abort("Failed to do something")

Args

  • message: string: Abort message to show the user.

get_path_to_store()

def get_path_to_store() -> string

Returns the path to the spaces store.

store_path = info.get_path_to_store()

Returns

  • str: The absolute path to the local spaces store directory.

get_execution_phase()

def get_execution_phase() -> string

Returns the current execution phase of the system.

phase = info.get_execution_phase()
if phase == "Run":
    # ...

Returns

  • str: The current phase, which will be “Run”, “Checkout”, or “Inspect”.

is_platform_macos()

def is_platform_macos() -> bool

Returns true if the current platform is macOS.

if info.is_platform_macos():
    # ...

Returns

  • bool: True if the platform is macos-aarch64 or macos-x86_64, False otherwise.

json

is_string_json()

def is_string_json(value) -> bool

Returns true if the given string is valid JSON.

if json.is_string_json('{"key": "value"}'):
    print("Valid JSON")

Args

  • value: string: The string to check.

Returns

  • bool: True if the string is valid JSON, False otherwise.

to_string()

def to_string(value) -> string

Converts a dictionary or Starlark value into a JSON-formatted string.

This is the inverse of string_to_dict. It takes structured data and serializes it into a string, making it ready to be written to a file or sent over a network.

data = {"name": "Project Alpha", "version": 1}
json_string = json.to_string(data)

Args

  • value: The dictionary or Starlark value to be serialized.

Returns

  • str: The JSON string representation of the input value.

string_to_dict()

def string_to_dict(content)

Converts a JSON formatted string into a Python dictionary.

This function acts as a parser, taking a raw JSON string and transforming it into a structured dictionary that you can easily manipulate in your scripts.

raw_data = '{"id": 101, "status": "active"}'
data_dict = json.string_to_dict(raw_data)
print(data_dict["status"])

Args

  • content: string: The JSON-formatted string to be converted.

Returns

  • dict: A dictionary representation of the JSON data.

to_string_pretty()

def to_string_pretty(value) -> string

Converts a dictionary or Starlark value into a “pretty-printed” JSON string.

Unlike to_string, this version adds newlines and indentation to make the output easily readable by humans. This is especially useful for generating configuration files or debug logs.

data = {"project": "Gemini", "active": True, "tags": ["ai", "helper"]}
pretty_json = json.to_string_pretty(data)
print(pretty_json)

Args

  • value: The dictionary or Starlark value to be serialized.

Returns

  • str: The formatted, multi-line JSON string.

len()

def len() -> int

len: get the length of a sequence

len(x) returns the number of elements in its argument.

It is a dynamic error if its argument is not a sequence.

len(()) == 0
len({}) == 0
len([]) == 0
len([1]) == 1
len([1,2]) == 2
len({'16': 10}) == 1
len(True)    # error: not supported

max()

def max()

max: returns the maximum of a sequence.

max(x) returns the greatest element in the iterable sequence x.

It is an error if any element does not support ordered comparison, or if the sequence is empty.

The optional named parameter key specifies a function to be applied to each element prior to comparison.

max([3, 1, 4, 1, 5, 9])               == 9
max("two", "three", "four")           == "two"    # the lexicographically greatest
max("two", "three", "four", key=len)  == "three"  # the longest

Args

  • key:

min()

def min()

min: returns the minimum of a sequence.

min(x) returns the least element in the iterable sequence x.

It is an error if any element does not support ordered comparison, or if the sequence is empty.

min([3, 1, 4, 1, 5, 9])                 == 1
min("two", "three", "four")             == "four"  # the lexicographically least
min("two", "three", "four", key=len)    == "two"   # the shortest

Args

  • key:

ord()

def ord() -> int

ord: returns the codepoint of a character

ord(s) returns the integer value of the sole Unicode code point encoded by the string s.

If s does not encode exactly one Unicode code point, ord fails. Each invalid code within the string is treated as if it encodes the Unicode replacement character, U+FFFD.

Example:

ord("A")                                == 65
ord("Й")                                == 1049
ord("😿")                               == 0x1F63F

print()

def print(content) -> NoneType

Args

  • content: string:

process

exec()

def exec(exec)

Executes a process and captures its output and status.

This function launches an external command within the specified environment and returns the results of that execution. It is the primary way to interact with system tools from your script.

result = process.exec({
    "command": "echo",
    "args": ["Hello from Spaces"],
    "env": {"DEBUG": "true"}
})

if result["status"] == 0:
    print(f"Success: {result['stdout']}")

Args

  • exec: A configuration dictionary containing command (str), args (list[str], optional), env (dict, optional), working_directory (str, optional), and stdin (str, optional).

Returns

  • dict: A dictionary containing status (int), stdout (str), and stderr (str).

repr()

def repr() -> string

repr: formats its argument as a string.

All strings in the result are double-quoted.

repr(1)                 == '1'
repr("x")               == "\"x\""
repr([1, "x"])          == "[1, \"x\"]"
repr("test \"'")        == "\"test \\\"'\""
repr("x\"y😿 \\'")      == "\"x\\\"y\\U0001f63f \\\\'\""

reversed()

def reversed() -> list

reversed: reverse a sequence

reversed(x) returns a new list containing the elements of the iterable sequence x in reverse order.

reversed(['a', 'b', 'c'])              == ['c', 'b', 'a']
reversed(range(5))                     == [4, 3, 2, 1, 0]
reversed("stressed".elems())           == ["d", "e", "s", "s", "e", "r", "t", "s"]
reversed({"one": 1, "two": 2}.keys())  == ["two", "one"]

run

add_kill_exec()

def add_kill_exec() -> NoneType

Adds a rule that will kill the execution of another rule.

run.add_kill_exec(
    rule = {"name": "stop_service", "type": "Run"},
    kill = {
        "signal": "Terminate",
        "target": "my_long_running_service",
        "expect": "Success",
    },
)

Args

  • rule: Rule definition containing name (str), deps (list), platforms (list), type (str), and help (str).
  • kill: Kill details containing signal (Hup|Int|Quit|Abort|Kill|Alarm|Terminate|User1|User2), target (str), and expect (Failure|Success|Any).

add_exec()

def add_exec() -> NoneType

Adds a rule that will execute a process.

run.add_exec(
    rule = {
        "name": name,
        "type": "Setup",
        "deps": ["sysroot-python:venv"],
    },
    exec = {
        "command": "pip3",
        "args": ["install"] + packages,
    },
)

Args

  • rule: Rule definition containing name (str), deps (list), platforms (list), type (str), and help (str).
  • exec: Execution details containing command (str), args (list), env (dict), working_directory (str), expect (Failure|Success|Any), and redirect_stdout (str).

abort()

def abort(message) -> NoneType

Abort script evaluation with a message.

run.abort("Failed to do something")

Args

  • message: string: Abort message to show the user.

add()

def add() -> NoneType

Adds a rule that depends on other rules but doesn’t execute any command.

There is no specific action for the rule, but this rule can be useful for organizing dependencies.

run.add(
    rule = {
        "name": "my_rule",
        "deps": ["my_other_rule"],
    },
)

Args

  • rule: Rule definition containing name (str), deps (list), platforms (list), type (str), and help (str).

add_target()

def add_target() -> NoneType

Adds a rule that depends on other rules.

This rule will be deprecated in favor of run.add.

Args

  • rule: Rule definition containing name (str), deps (list), platforms (list), type (str), and help (str).

add_archive()

def add_archive() -> NoneType

Adds a rule that will archive a directory.

run.add_archive(
    rule = {"name": name, "type": "Optional", "deps": ["sysroot-python:venv"]},
    archive = {
        "input": "build/install",
        "name": "my_archive",
        "version": "1.0",
        "driver": "tar.gz",
    },
)

Args

  • rule: Rule definition containing name (str), deps (list), platforms (list), type (str), and help (str).
  • archive: Archive details containing input (str), name (str), version (str), driver (tar.gz|tar.bz2|zip|tar.7z|tar.xz), platform (str), includes (list), and excludes (list).

add_from_clone()

def add_from_clone() -> NoneType

Adds a rule that will execute based on the cloned from rule.

The new rule is merged with the cloned rule: the new rule’s fields take precedence, and the exec/target is taken from the cloned rule.

run.add_from_clone(
    rule = {
        "name": "my_new_rule",
        "deps": ["other_dep"],
    },
    clone_from = "existing_rule",
)

Args

  • rule: Rule definition containing name (str), deps (list), type (str), and help (str).
  • clone_from: string: The name of an existing rule whose exec will be cloned.

script

get_arg()

def get_arg(offset) -> string

Retrieves a specific command-line argument by its index.

If no argument exists at the given offset, an empty string is returned.

first_arg = script.get_arg(0)
print(f"First argument: {first_arg}")

Args

  • offset: int: The positional index of the argument (0-based).

Returns

  • str: The argument value or an empty string.

abort()

def abort(message) -> NoneType

Aborts execution immediately.

This function terminates the script with a non-zero exit code (indicating failure) and prints the provided message to the standard error stream (stderr).

script.abort("Failed to do something")

Args

  • message: string: The error message to display upon termination.

print()

def print(content) -> NoneType

Outputs a string to the standard output (stdout).

This is intended for use within script execution to provide feedback or data to the user.

script.print("Hello, world!")

Args

  • content: string: The message to print.

get_args()

def get_args()

Parses command-line arguments into structured categories.

This function separates “ordered” arguments (standalone values) from “named” arguments (key=value pairs).

args = script.get_args()
for arg in args["ordered"]:
    print(arg)

Returns

  • dict: A dictionary containing ordered (list[str]) and named (dict).

set_exit_code()

def set_exit_code(exit_code) -> NoneType

Sets the final exit code for the script without terminating it.

Use 0 for success and non-zero for failure. The script will continue executing until it reaches the end or an abort call.

script.set_exit_code(1)

Args

  • exit_code: int: The integer exit code to be returned upon completion.

sorted()

def sorted() -> list

sorted: sort a sequence

sorted(x) returns a new list containing the elements of the iterable sequence x, in sorted order. The sort algorithm is stable.

The optional named parameter reverse, if true, causes sorted to return results in reverse sorted order.

The optional named parameter key specifies a function of one argument to apply to obtain the value’s sort key. The default behavior is the identity function.

sorted([3, 1, 4, 1, 5, 9])                               == [1, 1, 3, 4, 5, 9]
sorted([3, 1, 4, 1, 5, 9], reverse=True)                 == [9, 5, 4, 3, 1, 1]
sorted(["two", "three", "four"], key=len)                == ["two", "four", "three"] # shortest to longest
sorted(["two", "three", "four"], key=len, reverse=True)  == ["three", "four", "two"] # longest to shortest

Args

  • key:
  • reverse: bool:

time

now()

def now() -> tuple

Returns the current system time as a tuple.

This provides a high-precision snapshot of the current time, represented as two distinct integer values.

(secs, nsec) = time.now()
print("Seconds:", secs)
print("Nanoseconds:", nsec)

Returns

  • (int, int): A tuple containing seconds since the Unix epoch and fractional nanoseconds.

sleep()

def sleep(nanoseconds) -> NoneType

Pauses the execution of the script for a specified duration.

This is useful for waiting between retries, slowing down loops, or giving external processes time to initialize.

time.sleep(1000000000)

Args

  • nanoseconds: int: The number of nanoseconds to pause execution.

workspace

set_default_module_visibility_private()

def set_default_module_visibility_private() -> NoneType

Sets the default visibility to private for the current module.

workspace.set_default_module_visibility_private()

set_env()

def set_env() -> NoneType

Sets the workspace environment.

This is meant for internal use only from the env.spaces.star module.

workspace.set_env(
    env = {
        "vars": {"CC": "clang", "CXX": "clang++"},
    },
)

Args

  • env: Environment definition containing vars (dict), paths (list), and inherited (list).

set_locks()

def set_locks() -> NoneType

Sets the workspace locks.

This is meant for internal use only from a lock module.

workspace.set_locks(
    locks = {"my_lock": "lock_value"},
)

Args

  • locks: A dictionary of lock names to lock values.

get_env_var()

def get_env_var(var_name) -> string

Returns the value of a workspace environment variable.

home_dir = workspace.get_env_var("HOME")

Args

  • var_name: string: The name of the environment variable.

Returns

  • str: The value of the environment variable.

get_path_to_log_file()

def get_path_to_log_file(rule) -> string

Returns the relative workspace path to the log file for the specified target.

log_file = workspace.get_path_to_log_file("build_service")

Args

  • rule: string: The name of the target rule.

Returns

  • str: The relative path to the log file within the workspace.

is_env_var_set()

def is_env_var_set(var_name) -> bool

Returns true if the workspace environment variable is set.

if workspace.is_env_var_set("DEBUG_MODE"):
    # ...

Args

  • var_name: string: The name of the environment variable to check.

Returns

  • bool: True if the variable exists in the workspace environment, False otherwise.

get_path_to_build_archive()

def get_path_to_build_archive() -> string

Returns the path to where run.add_archive() creates the output archive.

archive_info = {
    "input": "dist",
    "name": "release_pkg",
    "version": "2.1.0",
    "driver": "zip",
}
path = workspace.get_path_to_build_archive(rule_name = "package_rule", archive = archive_info)

Args

  • rule_name: string: The name of the rule used to create the archive.
  • archive: The archive info used to create the archive.

Returns

  • str: The path to the generated output archive.

get_absolute_path()

def get_absolute_path() -> string

Returns the absolute path to the workspace.

workspace_path = workspace.get_absolute_path()

Returns

  • str: The absolute path to the workspace.

is_path_to_member_available()

def is_path_to_member_available() -> bool

Returns true if the workspace satisfies the specified member requirements.

member_req = {
    "url": "https://github.com/example/repo.git",
    "required": {"Revision": "a1b2c3d4e5f6"}
}
if workspace.is_path_to_member_available(member = member_req):
    # ...

Args

  • member: The requirements for the member, containing url (str) and required (dict).

Returns

  • bool: True if the workspace contains a member matching the requirements, False otherwise.

is_env_var_set_to()

def is_env_var_set_to(var_name, var_value) -> bool

Returns true if the workspace environment variable is set.

if workspace.is_env_var_set_to("DEBUG_MODE", "ON"):
    # ...

Args

  • var_name: string: The name of the environment variable to check.
  • var_value: string: The expected value of the environment variable.

Returns

  • bool: True if the variable exists and is equal to the expected value, False otherwise.

get_path_to_shell_config()

def get_path_to_shell_config() -> string

Returns the path to the shell config file.

shell_config = workspace.get_path_to_shell_config()

Returns

  • str: The path to the shell configuration file used by the workspace.

set_always_evaluate()

def set_always_evaluate(always_evaluate) -> NoneType

Sets whether the workspace should always evaluate scripts.

workspace.set_always_evaluate(True)

Args

  • always_evaluate: bool: If True, scripts will always be evaluated regardless of caching.

is_reproducible()

def is_reproducible() -> bool

Returns true if the workspace is reproducible.

if workspace.is_reproducible():
    # ...

Returns

  • bool: True if the workspace is reproducible, False otherwise.

get_path_to_checkout()

def get_path_to_checkout() -> string

Returns the repository path in the workspace of the calling script.

script_location = workspace.get_path_to_checkout()

Returns

  • str: The path to the directory containing the current script.

load_value()

def load_value(key)

Loads a value from the checkout store.

Values can be set in three ways, listed from highest to lowest priority:

  1. Command line: --store=KEY=VALUE (on checkout, checkout-repo, co, sync, or run). These are stored with path // and url <command line>, and always take precedence over all other sources regardless of the url or path argument.
  2. co.spaces.toml: The store table in a [entry.Repo] or [entry.Workflow] section. TOML values preserve their types (strings, integers, bools, arrays, tables).
  3. checkout.store_value(): Called from starlark scripts during checkout or sync.

Returns the stored value associated with the given key, or None if the key does not exist. Values are namespaced by the member path in the workspace.

Exactly one of url or path may be specified. If neither is given, all members are searched and the first match is returned. Note that command-line values are checked first and returned immediately if the key matches, before consulting url or path.

# Load from a specific member URL (command-line values still take priority)
value = workspace.load_value("my_key", url = "https://github.com/example/repo")

# Load from a specific path in the workspace
value = workspace.load_value("my_key", path = "spaces")

# Search all members for the key, returning the first match
value = workspace.load_value("my_key")

Args

  • key: string: The string key to look up.
  • url: Optional member URL to load from (ignored when a command-line value exists for the key).
  • path: Optional workspace path to identify the member. The member with the longest matching path prefix is used (ignored when a command-line value exists for the key).

Returns

  • The stored JSON value (string, number, bool, list, dict), or None if the key is not found.

get_short_digest()

def get_short_digest() -> string

Returns the short digest of the workspace.

short_digest = workspace.get_short_digest()

Returns

  • str: The short digest string of the workspace.

get_path_to_build_checkout()

def get_path_to_build_checkout() -> string

Returns the path to the workspace build folder for the current script.

build_path = workspace.get_path_to_build_checkout(rule_name = "my_rule")

Args

  • rule_name: string: The name of the rule to get the build checkout path for.

Returns

  • str: The path to the build directory associated with the current script evaluation.

get_digest()

def get_digest() -> string

Returns the digest of the workspace.

This is only meaningful if the workspace is reproducible, which is typically determined after the checkout process is complete.

digest = workspace.get_digest()

Returns

  • str: The unique digest string of the workspace.

get_path_to_member()

def get_path_to_member() -> string

Returns the path to the workspace member matching the specified requirement.

If the member cannot be found, an error is raised.

member_req = {
    "url": "https://github.com/example/repo.git",
    "required": {"SemVer": "^1.2.0"}
}
path = workspace.get_path_to_member(member = member_req)

Args

  • member: The requirements for the member, containing url (str) and required (dict).

Returns

  • str: The workspace path to the matching member.

get_build_archive_info()

def get_build_archive_info()

Returns the archive and sha256 file paths for a build archive.

archive_info = {
    "input": "build/install",
    "name": "my_archive",
    "version": "1.0",
    "driver": "tar.gz",
}
info = workspace.get_build_archive_info(rule_name = "my_rule", archive = archive_info)

Args

  • rule_name: string: The name of the rule used to create the archive.
  • archive: The archive info used to create the archive.

Returns

  • dict: A dictionary containing archive_path (str) and sha256_path (str).

zip()

def zip() -> list

zip: zip several iterables together

zip() returns a new list of n-tuples formed from corresponding elements of each of the n iterable sequences provided as arguments to zip. That is, the first tuple contains the first element of each of the sequences, the second element contains the second element of each of the sequences, and so on. The result list is only as long as the shortest of the input sequences.

zip()                           == []
zip(range(5))                   == [(0,), (1,), (2,), (3,), (4,)]
zip(range(5), "abc".elems())    == [(0, "a"), (1, "b"), (2, "c")]