Skip to content

cmd_demo

WithStateAttribute

Bases: Protocol

Protocol for classes that have a state attribute.

Source code in src/artificial_artwork/cmd_demo.py
10
11
12
13
class WithStateAttribute(t.Protocol):
    """Protocol for classes that have a state attribute."""

    state: t.Any

validate_and_normalize_path(ctx, param, value)

Custom function to validate and normalize a path.

Source code in src/artificial_artwork/cmd_demo.py
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
def validate_and_normalize_path(ctx, param, value):
    """Custom function to validate and normalize a path."""
    if value is None:
        return None
    path = Path(value)

    if path.is_absolute():
        abs_path = path
    else:
        current_directory = Path.cwd()
        abs_path = current_directory / path

    if not abs_path.exists():
        abs_path.mkdir()
        click.echo(f'Folder "{abs_path}" created')
    else:
        # get files inside the folder
        folder_files = [f for f in abs_path.iterdir() if f.is_file()]
        if len(folder_files) > 0:
            # ask user whether to delete everything, process as it is or exit
            click.echo(f'Folder "{abs_path}" already exists and is not empty.')
            click.echo("What do you want to do?")
            click.echo("1. Delete everything and start from scratch")
            click.echo("2. Process the existing files")
            click.echo("3. Exit")
            choice = click.prompt("Enter your choice", type=int)
            if choice == 1:
                click.echo("Deleting everything...")
                for file in folder_files:
                    file.unlink()
            elif choice == 2:
                click.echo("Processing existing files...")
            elif choice == 3:
                click.echo("Exiting...")
                ctx.exit()
            else:
                raise click.BadParameter(f'Invalid choice "{choice}".')
    return abs_path