harbor_cli.utils
Attributes
BaseModelType = TypeVar('BaseModelType', bound=BaseModel)
module-attribute
PREFIX_ID = 'id:'
module-attribute
OPTION_QUERY = typer.Option(None, '--query', help='Query parameters to filter the results.')
module-attribute
OPTION_SORT = typer.Option(None, '--sort', help="Sorting order of the results. Example: [green]'name,-id'[/] to sort by name ascending and id descending.")
module-attribute
OPTION_PAGE_SIZE = typer.Option(10, '--page-size', help='(Advanced) Results to fetch per API call.')
module-attribute
OPTION_PAGE = typer.Option(1, '--page', help='(Advanced) Page to begin fetching from.')
module-attribute
OPTION_LIMIT = typer.Option(None, '--limit', help='Maximum number of results to fetch.')
module-attribute
OPTION_PROJECT_NAME_OR_ID = typer.Option(None, '--project', help=f'Project name or ID. {_USE_ID_HELP}')
module-attribute
OPTION_FORCE = typer.Option(False, '--force', help='Force deletion without confirmation.')
module-attribute
ARG_PROJECT_NAME = typer.Argument(None, help='Name of the project to use.')
module-attribute
ARG_PROJECT_NAME_OR_ID = _arg_project_name_or_id()
module-attribute
ARG_PROJECT_NAME_OR_ID_OPTIONAL = _arg_project_name_or_id(None)
module-attribute
ARG_REPO_NAME = typer.Argument(help='Name of the repository to use.')
module-attribute
ARG_USERNAME_OR_ID = typer.Argument(help=f'Username or ID of the user to use. {_USE_ID_HELP}')
module-attribute
ARG_LDAP_GROUP_DN_OR_ID = typer.Argument(help=f'LDAP Group DN or ID of the group to use. {_USE_ID_HELP}')
module-attribute
MutableMappingType = TypeVar('MutableMappingType', bound=MutableMapping[Any, Any])
module-attribute
Classes
CommandSummary
Bases: BaseModel
Convenience class for accessing information about a command.
Source code in harbor_cli/models.py
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 |
|
Attributes
category: Optional[str] = None
class-attribute
instance-attribute
deprecated: bool
instance-attribute
epilog: Optional[str]
instance-attribute
help: str
instance-attribute
hidden: bool
instance-attribute
name: str
instance-attribute
options_metavar: str
instance-attribute
params: List[ParamSummary] = []
class-attribute
instance-attribute
score: int = 0
class-attribute
instance-attribute
short_help: Optional[str]
instance-attribute
help_plain: str
property
help_md: str
property
usage: str
property
options: List[ParamSummary]
property
arguments: List[ParamSummary]
property
Functions
from_command(command: TyperCommand, name: str | None = None, category: str | None = None) -> CommandSummary
classmethod
Construct a new CommandSummary from a TyperCommand.
Source code in harbor_cli/models.py
PackageVersion
Bases: NamedTuple
Source code in harbor_cli/utils/utils.py
Attributes
package: str
instance-attribute
min_version: Optional[str] = None
class-attribute
instance-attribute
max_version: Optional[str] = None
class-attribute
instance-attribute
not_version: Optional[str] = None
class-attribute
instance-attribute
Functions
is_builtin_obj(obj: object) -> bool
exit_err(message: str, code: int = 1, **kwargs: Any) -> NoReturn
Logs a message with ERROR level and exits with the given code (default: 1).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
message |
str
|
Message to print. |
required |
code |
int
|
Exit code, by default 1 |
1
|
**kwargs |
Any
|
Additional keyword arguments to pass to the extra dict. |
{}
|
Source code in harbor_cli/output/console.py
model_params_from_ctx(ctx: typer.Context, model: Type[BaseModel], filter_none: bool = True) -> dict[str, Any]
Get CLI options from a Typer context that correspond with Pydantic model field names.
Given a command where the function parameter names match the model field names, the function returns a dict of the parameters that are valid for the model.
If filter_none
is True, then parameters that are None will be filtered out.
This is enabled by default, since most Harbor API model fields are optional,
and we want to signal to Pydantic that these fields should be treated
as unset rather than set to None.
Examples:
>>> from pydantic import BaseModel
>>> class Foo(BaseModel):
... foo: str
... bar: str
>>> foo = Foo(foo="foo", bar="bar")
>>> ctx = typer.Context(...) # some-cmd --bar grok --baz quux
>>> model_params_from_ctx(ctx, Foo)
{"bar": "grok"} # baz is not a valid field for Foo
Parameters:
Name | Type | Description | Default |
---|---|---|---|
ctx |
Context
|
The Typer context. |
required |
model |
Type[BaseModel]
|
The model to get the parameters for. |
required |
filter_none |
bool
|
Whether to filter out None values, by default True |
True
|
Returns:
Type | Description |
---|---|
dict[str, Any]
|
The model parameters. |
Source code in harbor_cli/utils/args.py
create_updated_model(existing: BaseModel, new: Type[BaseModelType], ctx: typer.Context, extra: bool = False, empty_ok: bool = False) -> BaseModelType
Given an existing model instance and another model type, instantiate other model based on the fields of the existing model combined with CLI args passed in by the user.
When we call a PUT enpdoint, the API expects the full model definition, but we want to allow the user to only specify the fields they want to update. This function allows us to do that, by taking an existing model fetched via a GET call and updating it with new values from the Typer context.
To further complicate things, Harbor API generally uses a different model definition for updating resources (PUT) than the one fetched from a GET call. For example, fetching information about a project returns a Project object, while updating a project requires a ProjectUpdateReq object.
These models largely contain the same fields, but might have certain deviations.
For example, the Project model has a creation_time
field, while the
ProjectUpdateReq model does not.
This function allows us to create, for example, a ProjectUpdateReq object from a combination of a Project object and CLI args that correspond with the fields of the ProjectUpdateReq model.
See model_params_from_ctx for more information on how the CLI context is used to provide the updated fields for the new model.
Examples:
>>> from pydantic import BaseModel
>>> class Foo(BaseModel):
... a: Optional[int]
... b: Optional[str]
... c: Optional[bool]
>>> class FooUpdateReq(BaseModel):
... a: Optional[int]
... b: Optional[str]
... c: Optional[bool]
... d: bool = False
>>> foo = Foo(a=1, b="foo", c=True)
>>> # we get a ctx object from a Typer command
>>> ctx = typer.Context(...) # update-foo --a 2 --b bar
>>> foo_update = create_updated_model(foo, FooUpdateReq, ctx)
>>> foo_update
FooUpdateReq(a=2, b='bar', c=True, d=False)
>>> # ^^^ ^^^^^^^
>>> # We created a FooUpdateReq with the new values from the context
Parameters:
Name | Type | Description | Default |
---|---|---|---|
existing |
BaseModel
|
The existing model to use as a base. |
required |
new |
Type[BaseModelType]
|
The new model type to construct. |
required |
ctx |
Context
|
The Typer context to get the updated model parameters from. |
required |
extra |
bool
|
Whether to include extra fields set on the existing model. |
False
|
empty_ok |
bool
|
Whether to allow the update to be empty. If False, an error will be raised if no parameters are provided to update. |
False
|
Returns:
Type | Description |
---|---|
BaseModelType
|
The updated model. |
Source code in harbor_cli/utils/args.py
parse_commalist(arg: Optional[List[str]]) -> List[str]
Parses an optional argument that can be specified multiple times, or as a comma-separated string, into a list of strings.
harbor subcmd --arg foo --arg bar,baz
will be parsed as: ["foo", "bar", "baz"]
Examples:
>>> parse_commalist(["foo", "bar,baz"])
["foo", "bar", "baz"]
>>> parse_commalist([])
[]
>>> parse_commalist(None)
[]
Source code in harbor_cli/utils/args.py
parse_commalist_int(arg: Optional[List[str]]) -> List[int]
Parses a comma-separated list and converts the values to integers.
Source code in harbor_cli/utils/args.py
parse_key_value_args(arg: list[str]) -> dict[str, str]
Parses a list of key=value arguments.
Examples:
Parameters:
Name | Type | Description | Default |
---|---|---|---|
arg |
list[str]
|
A list of key=value arguments. |
required |
Returns:
Type | Description |
---|---|
dict[str, str]
|
A dictionary mapping keys to values. |
Source code in harbor_cli/utils/args.py
as_query(**kwargs: Any) -> str
Converts keyword arguments into a query string.
Examples:
construct_query_list(*values: Any, union: bool = True, allow_empty: bool = False, comma: bool = False) -> str
Given a key and a list of values, returns a harbor API query string with values as a list with union or intersection relationship (default: union).
Falsey values are ignored if allow_empty is False (default).
Examples:
>>> construct_query_list("foo", "bar", "baz", union=True)
'{foo bar baz}'
>>> construct_query_list("foo", "bar", "baz", union=False)
'(foo bar baz)'
>>> construct_query_list("", "bar", "baz")
'{bar baz}'
>>> construct_query_list("", "bar", "baz", allow_empty=True)
'{ bar baz}'
>>> construct_query_list("", "bar", "baz", comma=True)
'{bar,baz}'
Source code in harbor_cli/utils/args.py
deconstruct_query_list(qlist: str) -> list[str]
Given a harbor API query string with values as a list (either union and intersection), returns a list of values. Will break if values contain spaces.
Examples:
>>> deconstruct_query_list("{foo bar baz}")
['foo', 'bar', 'baz']
>>> deconstruct_query_list("(foo bar baz)")
['foo', 'bar', 'baz']
>>> deconstruct_query_list("{}")
[]
Source code in harbor_cli/utils/args.py
add_to_query(query: str | None, **kwargs: str | list[str] | None) -> str
Given a query string and a set of keyword arguments, returns a new query string with the keyword arguments added to it. Keyword arguments that are already present in the query string will be overwritten.
Always returns a string, even if the resulting query string is empty.
TODO: allow fuzzy matching, e.g. foo=~bar
Examples:
>>> add_to_query("foo=bar", baz="qux")
'foo=bar,baz=qux'
>>> add_to_query("foo=bar", foo="baz")
'foo=baz'
>>> add_to_query(None, foo="baz")
'foo=baz'
>>> add_to_query("foo=foo", foo="bar")
'foo={foo bar}'
Source code in harbor_cli/utils/args.py
get_project_arg(project_name_or_id: str) -> str | int
Given a project name or ID argument (prefixed with 'id:'), return a project name (str) or project ID (int).
get_user_arg(username_or_id: str) -> str | int
Given a username or ID argument (prefixed with 'id:'), return a username (str) or user ID (int).
get_ldap_group_arg(group_dn_or_id: str) -> str | int
render_cli_value(value: Any) -> str
get_parent_ctx(ctx: typer.Context | click.core.Context) -> typer.Context | click.core.Context
Get the top-level parent context of a context.
get_command_help(command: typer.models.CommandInfo) -> str
Get the help text of a command.
Source code in harbor_cli/utils/commands.py
get_app_commands(app: typer.Typer) -> list[CommandSummary]
cached
get_app_callback_options(app: typer.Typer) -> list[typer.models.OptionInfo]
Get the options of the main callback of a Typer app.
Source code in harbor_cli/utils/commands.py
inject_help(model: Type[BaseModel], strict: bool = False, remove: Optional[List[str]] = None, **field_additions: str) -> Any
Injects a Pydantic model's field descriptions into the help attributes of Typer.Option() function parameters whose names match the field names.
Examples:
class MyModel(BaseModel):
my_field: str = Field(..., description="Description of my_field")
@app.command(name="my-command")
@inject_help(MyModel)
def my_command(my_field: str = typer.Option(...)):
...
# `my-app my-command --help`
# my_field's help text will be "Description of my_field"
NOTE
Does not modify the help text of options with existing help text!
Use the **field_additions
parameter to add additional help text to a field
in addition to the field's description. This text is appended to the
help text, separated by a space.
e.g. @inject_help(MyModel, my_field="Additional help text that is appended to the field's description.")
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model |
Type[BaseModel]
|
The pydantic model to use for help injection. |
required |
strict |
bool
|
If True, fail if a field in the model does not correspond to a function parameter of the same name with a typer.OptionInfo as a default value. |
False
|
remove |
Optional[List[str]]
|
List of strings to remove from descriptions before injecting them. |
None
|
**field_additions |
str
|
Additional help text to add to the help attribute of a field. The parameter name should be the name of the field, and the value should be the additional help text to add. This is useful when the field's description is not sufficient, and you want to add additional help text to supplement the existing description. |
{}
|
Source code in harbor_cli/utils/commands.py
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 |
|
inject_resource_options(f: Any = None, *, strict: bool = False, use_defaults: bool = True) -> Any
Decorator that calls inject_query, inject_sort, inject_page_size, inject_page and inject_limit to inject typer.Option() defaults for common options used when querying multiple resources.
NOTE: needs to be specified BEFORE @app.command() in order to work!
Not strict by default, so that it can be used on functions that only have a subset of the parameters (e.g. only query and sort).
The decorated function should always declare the parameters in the following order
if the parameters don't have defaults:
query
, sort
, page
, page_size
, limit
Examples:
@app.command()
@inject_resource_options()
def my_command(query: str, sort: str, page: int, page_size: int, limit: Optional[int]):
...
# OK
@app.command()
@inject_resource_options()
def my_command(query: str, sort: str):
...
# NOT OK (missing all required parameters)
@app.command()
@inject_resource_options(strict=True)
def my_command(query: str, sort: str):
...
# OK (inherits defaults)
@app.command()
@inject_resource_options()
def my_command(query: str, sort: str, page: int = typer.Option(1)):
...
# NOT OK (syntax error [non-default param after param with default])
# Use ellipsis to specify unset defaults
@app.command()
@inject_resource_options()
def my_command(query: str = typer.Option("tag=latest"), sort: str, page: int):
# OK (inherit default query, but override others)
# Use ellipsis to specify unset defaults
@app.command()
@inject_resource_options()
def my_command(query: str = typer.Option("my-query"), sort: str = ..., page: int = ...):
Parameters:
Name | Type | Description | Default |
---|---|---|---|
f |
Any
|
The function to decorate, by default None |
None
|
strict |
bool
|
If True, fail if function is missing any of the injected parameters, by default False
E.g. all of |
False
|
use_defaults |
bool
|
If True, use the default value specified by a parameter's typer.Option() field as the default value for the parameter, by default True. |
True
|
Returns:
Type | Description |
---|---|
Any
|
The decorated function |
Examples:
If use_defaults is True, the default value of page_size will be 20, instead of 10, which is the value inject_page_size() would use by default.Warning
inject_resource_options()
only accepts parameter defaults specified with typer.Option() and typer.Argument()!
@inject_resource_options(use_default=True)
my_func(page_size: int = 20) -> None: ... # will fail (for now)
Source code in harbor_cli/utils/commands.py
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 |
|
inject_query(f: Any = None, *, strict: bool = False, use_default: bool = True) -> Any
Source code in harbor_cli/utils/commands.py
inject_sort(f: Any = None, *, strict: bool = False, use_default: bool = True) -> Any
Source code in harbor_cli/utils/commands.py
inject_page_size(f: Any = None, *, strict: bool = False, use_default: bool = True) -> Any
Source code in harbor_cli/utils/commands.py
inject_page(f: Any = None, *, strict: bool = False, use_default: bool = True) -> Any
Source code in harbor_cli/utils/commands.py
inject_limit(f: Any = None, *, strict: bool = False, use_default: bool = False) -> Any
Source code in harbor_cli/utils/commands.py
inject_project_name(f: Any = None, *, strict: bool = False, use_default: bool = True) -> Any
Source code in harbor_cli/utils/commands.py
replace_none(d: Optional[MutableMappingType], replacement: Any = '') -> MutableMappingType
Replaces None values in a dict with a given replacement value. Iterates recursively through nested dicts and iterables.
Untested with iterables other than list, tuple, and set.
Source code in harbor_cli/utils/utils.py
parse_version_string(package: str) -> PackageVersion
Parse a PEP 440 package version string into a PackageVersion tuple.
Must be in the form of <package_name>[{~=,==,!=,<=,>=,<,>}{x.y.z}][,][{~=,==,!=,<=,>=,<,>}{x.y.z}]
Examples:
- "foo"
- "foo==1.2.3"
- "foo>=1.2.3"
- "foo>=1.2.3,<=2.3.4"