Skip to content

harbor_cli.output.formatting

Attributes

EMOJI_NO = ':cross_mark:' module-attribute

EMOJI_YES = ':white_check_mark:' module-attribute

state = get_state() module-attribute

FALSE_STR = 'False' module-attribute

TRUE_STR = 'True' module-attribute

NONE_STR = 'None' module-attribute

logger = logging.getLogger('harbor-cli') module-attribute

Functions

get_state() -> State

Returns the global state object.

Instantiates a new state object with defaults if it doesn't exist.

Source code in harbor_cli/state.py
def get_state() -> State:
    """Returns the global state object.

    Instantiates a new state object with defaults if it doesn't exist.
    """
    return State()

str_str(value: Optional[str]) -> str

Format an optional string value as a string.

Source code in harbor_cli/output/formatting/builtin.py
def str_str(value: Optional[str]) -> str:
    """Format an optional string value as a string."""
    return str(value if value is not None else NONE_STR)

float_str(value: Optional[float], precision: int = 2) -> str

Format a float value as a string.

Source code in harbor_cli/output/formatting/builtin.py
def float_str(value: Optional[float], precision: int = 2) -> str:
    """Format a float value as a string."""
    if value is None:
        return NONE_STR
    return f"{value:.{precision}f}"

int_str(value: Optional[int]) -> str

Format an integer value as a string.

Source code in harbor_cli/output/formatting/builtin.py
def int_str(value: Optional[int]) -> str:
    """Format an integer value as a string."""
    if value is None:
        return NONE_STR
    return str(value)

plural_str(value: str, sequence: Sequence[Any]) -> str

Format a string as a pluralized string if a given sequence is not of length 1.

Source code in harbor_cli/output/formatting/builtin.py
def plural_str(value: str, sequence: Sequence[Any]) -> str:
    """Format a string as a pluralized string if a given sequence is
    not of length 1.
    """
    if value.endswith("y"):
        plural_value = value[:-1] + "ies"
    elif value.endswith("ies"):
        plural_value = value
        value = value[:-3] + "y"
    elif value.endswith("s"):
        plural_value = value
        value = value[:-1]
    else:
        plural_value = value + "s"
    return value if len(sequence) == 1 else f"{plural_value}"

bytesize_str(b: int | None, decimal: bool = False) -> str

Source code in harbor_cli/output/formatting/bytes.py
def bytesize_str(b: int | None, decimal: bool = False) -> str:
    if b is None or b < 0:
        return NONE_STR
    return ByteSize(b).human_readable(decimal=decimal)

datetime_str(d: datetime | int | float | None, with_time: bool = True, subsecond: bool = False) -> str

Formats an optional datetime object as as a string.

Parameters:

Name Type Description Default
d datetime | None

The datetime object to format.

required
with_time bool

Whether to include the time in the formatted string, by default True

True
subsecond bool

Whether to include subsecond precision in the formatted string, by default False Has no effect if with_time is False.

False
Source code in harbor_cli/output/formatting/dates.py
def datetime_str(
    d: datetime | int | float | None, with_time: bool = True, subsecond: bool = False
) -> str:
    """Formats an optional datetime object as as a string.

    Parameters
    ----------
    d : datetime | None
        The datetime object to format.
    with_time : bool, optional
        Whether to include the time in the formatted string, by default True
    subsecond : bool, optional
        Whether to include subsecond precision in the formatted string, by default False
        Has no effect if `with_time` is False.
    """
    if d is None:
        return NONE_STR
    if isinstance(d, (int, float)):
        try:
            d = datetime.fromtimestamp(d)
        except (ValueError, OSError) as e:  # OSError if timestamp is out of range
            if isinstance(e, OSError):
                logger.error("Timestamp out of range: %s", d)
            return NONE_STR
    fmt = "%Y-%m-%d"
    if with_time:
        fmt = f"{fmt} %H:%M:%S"
        if subsecond:
            fmt = f"{fmt}.%f"
    return d.strftime(fmt)

bool_str(value: Optional[bool], none_is_false: bool = True) -> str

Format a boolean value as a string.

Source code in harbor_cli/output/formatting/builtin.py
def bool_str(value: Optional[bool], none_is_false: bool = True) -> str:
    """Format a boolean value as a string."""
    # Harbor API sometimes has None signify False
    # Why? I don't know.
    if value is None and none_is_false:
        value = False
    if state.config.output.table.style.bool_emoji:
        return EMOJI_YES if value else EMOJI_NO
    elif value is None:
        return NONE_STR  # should we return None in emoji mode as well?
    return TRUE_STR if value else FALSE_STR

boolstr_str(boolstr: str | bool | None, default: bool | None = False) -> str

Format a boolean string as a string.

ProjectMetadata has fields that can be the strings 'true' or 'false', or None. This function converts those values to a boolean if possible, then passes it to bool_str.

Parameters:

Name Type Description Default
boolstr str | bool | None

A string that is either 'true', 'false', or None, OR a boolean value, in case the API changes in the future and these fields are returned as booleans instead of strings.

required

Returns:

Type Description
str

A string representation of the value created by bool_str()

See Also

harbor_cli.output.formatting.builtin.bool_str https://unioslo.github.io/harborapi/usage/models/#string-fields-with-true-and-false-values-in-api-spec

Source code in harbor_cli/output/formatting/harbor.py
def boolstr_str(boolstr: str | bool | None, default: bool | None = False) -> str:
    """Format a boolean string as a string.

    ProjectMetadata has fields that can be the strings
    'true' or 'false', or None. This function converts
    those values to a boolean if possible, then passes
    it to bool_str.

    Parameters
    ----------
    boolstr : str | bool | None
        A string that is either 'true', 'false', or None,
        OR a boolean value, in case the API changes in the future
        and these fields are returned as booleans instead of strings.

    Returns
    -------
    str
        A string representation of the value created by `bool_str()`

    See Also
    --------
    [harbor_cli.output.formatting.builtin.bool_str][]
    <https://unioslo.github.io/harborapi/usage/models/#string-fields-with-true-and-false-values-in-api-spec>
    """
    # Strings that do not match either 'true' or 'false' are
    # treated as `None` by default, and then we let `bool_str`
    # figure out what that means. This is a narrow edge case, and
    # a direct result of Harbor's own mistakes, so we don't spend
    # too much energy trying to make this perfect here.
    if boolstr is None:
        return bool_str(boolstr)
    elif boolstr == "true":
        return bool_str(True)
    elif boolstr == "false":
        return bool_str(False)
    elif isinstance(boolstr, bool):  # spec has changed, is now a bool
        # NOTE: could add some sort of alert that the spec has changed here
        return bool_str(boolstr)
    else:
        return bool_str(default)

Return a link to a path.

Source code in harbor_cli/output/formatting/path.py
def path_link(path: Path, absolute: bool = True) -> str:
    """Return a link to a path."""
    abspath = path.resolve().absolute()
    if absolute:
        path_str = str(abspath)
    else:
        path_str = str(path)
    return f"[link=file://{abspath}]{path_str}[/link]"