-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcli.py
361 lines (252 loc) · 10.1 KB
/
cli.py
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
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
import typer
from prompt_toolkit import prompt
from prompt_toolkit.completion import WordCompleter
from app.func import (
generate_markdown,
initialize_database,
get_connection,
add_collection as db_add_collection,
get_collections as db_get_collections,
add_tag as db_add_tag,
get_tags as db_get_tags,
add_paragraph as db_add_paragraph,
get_paragraphs as db_get_paragraphs,
update_paragraph as db_update_paragraph,
delete_paragraph as db_delete_paragraph,
open_content_text_editor,
TextEditor,
Paragraph
)
def _modify_paragraph_menu(paragraph: Paragraph, text_editor: TextEditor):
typer.echo("Leave the field empty to keep the current value.")
title = prompt("Title: ", default= paragraph.title).strip()
user_instruction = (
'You are about to modify the content of the document in a text editor.\n'
'Please SAVE and CLOSE the editor to proceed.\n'
'Warning: If you do not save the file, the content will not be updated and '
'the content cannot be empty.\n'
'Press Enter to continue.'
)
input(user_instruction)
content = open_content_text_editor(
content= paragraph.content, editor= text_editor).strip()
# Clear screen
typer.echo("\033c")
if not content:
typer.echo("Content cannot be empty")
raise typer.Abort()
tags = db_get_tags(connection= conn)
tags_dict = {tag.name: tag for tag in tags}
tag_completer = WordCompleter(tags_dict.keys(), ignore_case= True)
tag_list = []
typer.echo("Enter tags from the list. Press Enter without typing anything to finish.")
while True:
tag_name = prompt("Tag: ", completer= tag_completer)
if not tag_name:
break
if tag_name not in tags_dict:
typer.echo("Tag not found")
continue
tag_list.append(tag_name.strip())
tag_ids = set()
new_tags = set()
for tag in tag_list:
if tag not in tags_dict:
continue
tag_ids.add(tags_dict[tag].id)
db_update_paragraph(
connection= conn,
paragraph_id= paragraph.id,
title= title,
content= content,
tag_ids= tag_ids
)
typer.echo("Document modified successfully")
conn = get_connection()
try:
app = typer.Typer()
@app.command()
def add_collection(name: str):
"""Add a new collection."""
db_add_collection(connection= conn, name= name)
@app.command()
def list_collections():
"""List all collections."""
collections = db_get_collections(connection= conn)
for collection in collections:
typer.echo(f"{collection.id}. {collection.name}")
@app.command()
def add_tag(description: str, name: str|None = None):
"""Add a new tag."""
db_add_tag(connection= conn, name= name, description= description)
typer.echo("Tag added successfully")
@app.command()
def list_tags():
"""List all tags."""
tags = db_get_tags(connection= conn)
for tag in tags:
typer.echo(f"{tag.id}. {tag.name} - {tag.description}")
@app.command()
def add_paragraph(text_editor: TextEditor = TextEditor.NANO, collection_id: int = None):
"""Add a new paragraph."""
typer.echo("Registering a new document...")
collections = db_get_collections(connection= conn)
tags = db_get_tags(connection= conn)
tags_dict = {t.name: t for t in tags}
tag_completer = WordCompleter(tags_dict.keys(), ignore_case= True)
if not collection_id:
collections_dict = {c.name: c for c in collections}
collection_completer = WordCompleter(collections_dict.keys(), ignore_case= True)
# Collection selection
collection_name = prompt("Collection: ", completer= collection_completer)
if not collection_name in collections_dict:
typer.echo("Invalid collection")
raise typer.Abort()
collection_id = collections_dict[collection_name].id
else:
collection = next((c for c in collections if c.id == collection_id), None)
if not collection:
typer.echo("Collection not found")
raise typer.Abort()
# Title
while True:
title = prompt("Title: ").strip()
if title:
break
typer.echo("Title cannot be empty")
user_instruction = (
'You are about to modify the content of the document in a text editor.\n'
'Please SAVE and CLOSE the editor to proceed.\n'
'Warning: If you do not save the file, the content will not be updated and '
'the content cannot be empty.\n'
'Press Enter to continue.'
)
input(user_instruction)
# Multi-line input for document content
content = open_content_text_editor(content= '', editor= text_editor).strip()
if not content:
typer.echo("Content cannot be empty")
raise typer.Abort()
# Interactive tag selection. Input several until an empty line is entered
tag_list = []
typer.echo("Enter tags from the list. Press Enter without typing anything to finish.")
while True:
tag_name = prompt("Tag: ", completer= tag_completer)
if not tag_name:
break
tag_list.append(tag_name.strip())
tag_ids = set()
new_tags = set()
for tag in tag_list:
if tag in tags_dict:
tag_ids.add(tags_dict[tag].id)
else:
continue
db_add_paragraph(
connection= conn,
collection_id= collection_id,
title= title,
content= content,
tag_ids= tag_ids
)
typer.echo("Document added successfully")
@app.command(help= (
"Show a paragraph. If an ID is not provided, "
"a list of paragraphs is shown, and the user can select one to show."
)
)
def show_paragraph(id: int = None):
"""Show a paragraph, with an option to modify it."""
if id is None:
paragraphs = db_get_paragraphs(connection= conn)
paragraph_dict = {p.id: p for p in paragraphs}
for paragraph in paragraphs:
typer.echo(f"{paragraph.id}. {paragraph.title}")
paragraph_id = typer.prompt("Enter the paragraph ID", type= int)
if not paragraph_id or paragraph_id not in paragraph_dict:
typer.echo("Invalid paragraph ID")
raise typer.Abort()
paragraph = paragraph_dict[ paragraph_id ]
else:
paragraphs = db_get_paragraphs(connection= conn, paragraph_id= id)
if not paragraphs:
typer.echo("Paragraph not found")
raise typer.Abort()
paragraph = paragraphs[0]
# Clear screen
typer.echo("\033c")
typer.echo("Collection: " + paragraph.collection.name)
typer.echo(f"ID: {paragraph.id}")
typer.echo(f"Title: {paragraph.title}")
typer.echo(f"Content:\n{paragraph.content}")
typer.echo(f"Tags: {', '.join(tag.name for tag in paragraph.tags)}")
typer.echo("\n\n")
while True:
user_input = typer.prompt("Do you want to modify this excerpt? (y/n)", type= str).strip().lower()
if user_input not in ('y', 'n'):
continue
break
if user_input == 'n':
return
text_editors = [editor.name for editor in TextEditor]
text_editor_completer = WordCompleter(text_editors, ignore_case= True)
text_editor = prompt(
"Select a text editor. Leave empty to use the default editor (nano): ",
completer= text_editor_completer,
default= TextEditor.NANO.name)
if text_editor not in text_editors:
typer.echo("Invalid text editor")
raise typer.Abort()
_modify_paragraph_menu(paragraph, TextEditor[text_editor])
@app.command()
def modify_paragraph(id: int, text_editor: TextEditor = TextEditor.NANO):
"""Modify a paragraph."""
paragraphs = db_get_paragraphs(connection= conn, paragraph_id= id)
if not paragraphs:
typer.echo("Paragraph not found")
raise typer.Abort()
paragraph = paragraphs[0]
_modify_paragraph_menu(paragraph, text_editor)
@app.command()
def delete_paragraph(id: int):
"""Delete a paragraph."""
paragraphs = db_get_paragraphs(connection= conn, paragraph_id= id)
if not paragraphs:
typer.echo("Paragraph not found")
raise typer.Abort()
paragraph = paragraphs[0]
db_delete_paragraph(connection= conn, paragraph_id= paragraph.id)
typer.echo("Document deleted successfully")
@app.command()
def add_tag(paragraph_id: int, tag_description: str, tag_name: str = None):
"""Add a tag to a paragraph."""
paragraphs = db_get_paragraphs(connection= conn, paragraph_id= paragraph_id)
if not paragraphs:
typer.echo("Paragraph not found")
raise typer.Abort()
paragraph = paragraphs[0]
db_add_tag(
connection= conn,
name= tag_name,
description= tag_description,
paragraph_id= paragraph.id
)
typer.echo("Tag added successfully")
@app.command()
def generate(collection_id: int, output: str = None):
"""Generate Markdown file."""
markdown = generate_markdown(connection= conn, collection_id= collection_id)
if output:
with open(output, 'w', encoding='utf8') as f:
f.write(markdown)
typer.echo(f"Markdown file saved to {output}")
else:
typer.echo(markdown)
@app.command()
def init():
"""Initialize the database."""
initialize_database(connection= conn)
if __name__ == "__main__":
app()
finally:
conn.close()