forked from realpython/materials
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
217 lines (193 loc) · 5.94 KB
/
Copy pathcli.py
File metadata and controls
217 lines (193 loc) · 5.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
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
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
"""This module provides the RP To-Do CLI."""
from pathlib import Path
from typing import List, Optional
import typer
from rptodo import ERRORS, __app_name__, __version__, config, database, rptodo
app = typer.Typer()
@app.command()
def init(
db_path: str = typer.Option(
str(database.DEFAULT_DB_FILE_PATH),
"--db-path",
"-db",
prompt="to-do database location?",
),
) -> None:
"""Initialize the to-do database."""
app_init_error = config.init_app(db_path)
if app_init_error:
typer.secho(
f'Creating config file failed with "{ERRORS[app_init_error]}"',
fg=typer.colors.RED,
)
raise typer.Exit(1)
db_init_error = database.init_database(Path(db_path))
if db_init_error:
typer.secho(
f'Creating database failed with "{ERRORS[db_init_error]}"',
fg=typer.colors.RED,
)
raise typer.Exit(1)
else:
typer.secho(f"The to-do database is {db_path}", fg=typer.colors.GREEN)
def get_todoer() -> rptodo.Todoer:
if config.CONFIG_FILE_PATH.exists():
db_path = database.get_database_path(config.CONFIG_FILE_PATH)
else:
typer.secho(
'Config file not found. Please, run "rptodo init"',
fg=typer.colors.RED,
)
raise typer.Exit(1)
if db_path.exists():
return rptodo.Todoer(db_path)
else:
typer.secho(
'Database not found. Please, run "rptodo init"',
fg=typer.colors.RED,
)
raise typer.Exit(1)
@app.command()
def add(
description: List[str] = typer.Argument(...),
priority: int = typer.Option(2, "--priority", "-p", min=1, max=3),
) -> None:
"""Add a new to-do with a DESCRIPTION."""
todoer = get_todoer()
todo, error = todoer.add(description, priority)
if error:
typer.secho(
f'Adding to-do failed with "{ERRORS[error]}"', fg=typer.colors.RED
)
raise typer.Exit(1)
else:
typer.secho(
f"""to-do: "{todo['Description']}" was added """
f"""with priority: {priority}""",
fg=typer.colors.GREEN,
)
@app.command(name="list")
def list_all() -> None:
"""List all to-dos."""
todoer = get_todoer()
todo_list = todoer.get_todo_list()
if len(todo_list) == 0:
typer.secho(
"There are no tasks in the to-do list yet", fg=typer.colors.RED
)
raise typer.Exit()
typer.secho("\nto-do list:\n", fg=typer.colors.BLUE, bold=True)
columns = (
"ID. ",
"| Priority ",
"| Done ",
"| Description ",
)
headers = "".join(columns)
typer.secho(headers, fg=typer.colors.BLUE, bold=True)
typer.secho("-" * len(headers), fg=typer.colors.BLUE)
for id, todo in enumerate(todo_list, 1):
desc, priority, done = todo.values()
typer.secho(
f"{id}{(len(columns[0]) - len(str(id))) * ' '}"
f"| ({priority}){(len(columns[1]) - len(str(priority)) - 4) * ' '}"
f"| {done}{(len(columns[2]) - len(str(done)) - 2) * ' '}"
f"| {desc}",
fg=typer.colors.BLUE,
)
typer.secho("-" * len(headers) + "\n", fg=typer.colors.BLUE)
@app.command(name="complete")
def set_done(todo_id: int = typer.Argument(...)) -> None:
"""Complete a to-do by setting it as done using its TODO_ID."""
todoer = get_todoer()
todo, error = todoer.set_done(todo_id)
if error:
typer.secho(
f'Completing to-do # "{todo_id}" failed with "{ERRORS[error]}"',
fg=typer.colors.RED,
)
raise typer.Exit(1)
else:
typer.secho(
f"""to-do # {todo_id} "{todo['Description']}" completed!""",
fg=typer.colors.GREEN,
)
@app.command()
def remove(
todo_id: int = typer.Argument(...),
force: bool = typer.Option(
False,
"--force",
"-f",
help="Force deletion without confirmation.",
),
) -> None:
"""Remove a to-do using its TODO_ID."""
todoer = get_todoer()
def _remove():
todo, error = todoer.remove(todo_id)
if error:
typer.secho(
f'Removing to-do # {todo_id} failed with "{ERRORS[error]}"',
fg=typer.colors.RED,
)
raise typer.Exit(1)
else:
typer.secho(
f"""to-do # {todo_id}: '{todo["Description"]}' was removed""",
fg=typer.colors.GREEN,
)
if force:
_remove()
else:
todo_list = todoer.get_todo_list()
try:
todo = todo_list[todo_id - 1]
except IndexError:
typer.secho("Invalid TODO_ID", fg=typer.colors.RED)
raise typer.Exit(1)
delete = typer.confirm(
f"Delete to-do # {todo_id}: {todo['Description']}?"
)
if delete:
_remove()
else:
typer.echo("Operation canceled")
@app.command(name="clear")
def remove_all(
force: bool = typer.Option(
...,
prompt="Delete all to-dos?",
help="Force deletion without confirmation.",
),
) -> None:
"""Remove all to-dos."""
todoer = get_todoer()
if force:
error = todoer.remove_all().error
if error:
typer.secho(
f'Removing to-dos failed with "{ERRORS[error]}"',
fg=typer.colors.RED,
)
raise typer.Exit(1)
else:
typer.secho("All to-dos were removed", fg=typer.colors.GREEN)
else:
typer.echo("Operation canceled")
def _version_callback(value: bool) -> None:
if value:
typer.echo(f"{__app_name__} v{__version__}")
raise typer.Exit()
@app.callback()
def main(
version: Optional[bool] = typer.Option(
None,
"--version",
"-v",
help="Show the application's version and exit.",
callback=_version_callback,
is_eager=True,
)
) -> None:
return