-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
321 lines (270 loc) · 13.1 KB
/
Copy pathcli.py
File metadata and controls
321 lines (270 loc) · 13.1 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
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
import typer
from typing import Any, Dict, Optional, List
from typing_extensions import Annotated
from rich.console import Console
from rich.table import Table
from rich.panel import Panel
from auth import TrelloAuth
from api_client import TrelloAPIClient
from trello_service import TrelloService
console = Console()
# Parser functions for optional fields
# Convert empty string to None, otherwise return the string
def parse_optional_string(value: str) -> Optional[str]:
return value.strip() or None
# Parse space-separated labels, return None if empty.
def parse_labels(value: str) -> Optional[List[str]]:
if not value.strip():
return None
return [label.strip().lower() for label in value.split() if label.strip()]
# Global service instance (initialized lazily)
service = None
def get_service() -> TrelloService:
global service
if service is None:
try:
auth = TrelloAuth()
client = TrelloAPIClient(auth)
service = TrelloService(client)
except ValueError as e:
console.print(f"[red]Authentication Error: {e}[/red]")
console.print("[yellow]Please check your Trello API credentials.[/yellow]")
raise typer.Exit(1)
return service
app = typer.Typer(
help="Trello CLI - Add cards with labels and comments to Trello boards",
context_settings={"help_option_names": ["-h", "--help"]}
)
# Create sub-apps for nested commands
card_app = typer.Typer()
app.add_typer(card_app, name="card", help="Card operations")
board_app = typer.Typer()
app.add_typer(board_app, name="board", help="Board operations")
# List all boards in your workspace.
@app.command("workspace")
def workspace(
verbose: bool = typer.Option(False, "--verbose", "-v", help="Show detailed info")
):
try:
# Get boards from service
boards = get_service().get_boards()
if not boards:
console.print("[yellow]No boards found in your workspace.[/yellow]")
return
# Create table for boards
table = Table(title="📋 Your Workspace Boards", show_header=True, header_style="bold magenta")
table.add_column("#", style="dim", width=3)
table.add_column("Board Name", style="cyan")
if verbose:
table.add_column("ID", style="dim")
# Add board rows
for i, board in enumerate(boards, 1):
row = [str(i), board.get("name")]
if verbose:
row.append(board.get("id"))
table.add_row(*row)
console.print(table)
console.print(f"\n[green]Found {len(boards)} boards in your workspace.[/green]")
except Exception as e:
console.print(f"[red]Error: {e}[/red]")
# Create a card with labels and comments.
@card_app.command("create")
def create_card(
board: Annotated[str, typer.Option("--board", "-b", help="Trello board name", prompt="Board name", show_default=False)],
list_name: Annotated[str, typer.Option("--list", "-l", help="List/column name", prompt="List/column name", show_default=False)],
title: Annotated[str, typer.Option("--title", "-t", help="Card title", prompt="Card title", show_default=False)],
description: Annotated[Optional[str], typer.Option("--description", "-d", help="Card description", parser=parse_optional_string, prompt="Card description (optional)", metavar="TEXT", show_default="None")] = "",
labels: Annotated[Optional[str], typer.Option("--labels", help="Label colors (space-separated)", parser=parse_optional_string, prompt="Labels (space-separated colors, optional)", metavar="TEXT", show_default="None")] = "",
comment: Annotated[Optional[str], typer.Option("--comment", "-c", help="Comment to add", parser=parse_optional_string, prompt="Comment (optional)", metavar="TEXT", show_default="None")] = "",
verbose: Annotated[bool, typer.Option("--verbose", "-v", help="Verbose output")] = False,
):
try:
# Parse labels string into list or None
label_colors = parse_labels(labels) if labels else None
print("board:", board)
print("list_name:", list_name)
print("title:", title)
print("description:", description)
print("label_colors:", label_colors)
print("comment:", comment)
# Create the card using service
result = get_service().add_card_to_board(
board_name=board,
list_name=list_name,
card_name=title,
description=description,
label_colors=label_colors,
comment=comment
)
# Display success information
card = result.get("card")
if not card:
console.print("[red]Card creation failed.[/red]")
return
console.print(Panel(
f"[bold green]✅ Card created successfully![/bold green]\n"
f"Title: [cyan]{card.get('name')}[/cyan]\n"
f"Board: [yellow]{result.get('board')}[/yellow]\n"
f"List: [magenta]{result.get('list')}[/magenta]",
title="Card Created"
))
if verbose:
console.print(f"[dim]Card ID: {card['id']}[/dim]")
if card.get('url'):
console.print(f"[dim]URL: {card['url']}[/dim]")
# Show labels results
labels_added = result.get("labels_added", [])
if labels_added:
labels_table = Table(title="🏷️ Labels", show_header=True, header_style="bold green")
labels_table.add_column("Color", style="yellow")
labels_table.add_column("Status", style="green")
for label in labels_added:
if "error" in label:
labels_table.add_row(label['color'], f"[red]❌ {label['error']}[/red]")
else:
status = label.get("status", "added")
labels_table.add_row(label['color'], f"[green]✅ {status}[/green]")
console.print(labels_table)
# Show comment result
if result.get("comment_added"):
console.print("[green]💬 Comment added successfully[/green]")
elif "comment_error" in result:
console.print(f"[red]❌ Comment failed: {result['comment_error']}[/red]")
except ValueError as e:
console.print(f"[red]Error: {e}[/red]")
except Exception as e:
console.print(f"[red]Unexpected error: {e}[/red]")
# Add comment and/or label to an existing card
@card_app.command("add")
def add_to_card(
board: Annotated[str, typer.Option("--board", "-b", help="Trello board name", prompt="Board name", show_default=False)],
card_name: Annotated[str, typer.Option("--card", "-c", help="Card name/title", prompt="Card name", show_default=False)],
comment: Annotated[Optional[str], typer.Option("--comment", help="Comment text", parser=parse_optional_string, prompt="Comment (optional)", metavar="TEXT", show_default="None")] = "",
label_color: Annotated[Optional[str], typer.Option("--label", help="Label color", parser=parse_optional_string, prompt="Label color (optional)", metavar="TEXT", show_default="None")] = ""
):
try:
# Find the board
board_obj = get_service().get_board_by_name(board)
if not board_obj:
console.print(f"[red]Board '{board}' not found.[/red]")
return
# Find the card
card = get_service().get_card_by_name(str(board_obj.get("id")), card_name)
if not card:
console.print(f"[red]Card '{card_name}' not found in board '{board}'.[/red]")
return
results = []
# Add comment if provided
if comment:
try:
get_service().client.add_comment_to_card(str(card.get("id")), comment)
results.append(f"[green]💬 Comment added: {comment}[/green]")
except Exception as e:
results.append(f"[red]❌ Comment failed: {e}[/red]")
# Add label if provided
if label_color:
try:
label_info = get_service().find_or_create_labels(board, [label_color.lower()])
label = label_info[0]
if label.get("exists"):
get_service().client.add_label_to_card(str(card.get("id")), label.get("id"))
status = "existing label applied"
else:
get_service().client.create_label_on_card(str(card.get("id")), label_color.lower())
status = "new label created and applied"
results.append(f"[green]🏷️ Label {label_color.lower()}: {status}[/green]")
except Exception as e:
results.append(f"[red]❌ Label failed: {e}[/red]")
if not comment and not label_color:
console.print("[yellow]No comment or label provided. Nothing to add.[/yellow]")
return
# Display results
console.print(Panel(
f"[bold green]✅ Updates applied to card![/bold green]\n"
f"Card: [cyan]{card['name']}[/cyan]\n"
f"Board: [yellow]{board}[/yellow]",
title="Card Updated"
))
for result in results:
console.print(result)
except Exception as e:
console.print(f"[red]Error: {e}[/red]")
# Show board information (lists, labels).
@board_app.command("info")
def board_info(
board: Annotated[str, typer.Option("--board", "-b", help="Board name", prompt="Board name")],
verbose: Annotated[bool, typer.Option("--verbose", "-v", help="Show IDs")] = False
):
try:
# Get board info from service
info = get_service().get_board_info(board)
if not info:
console.print(f"[red]Board '{board}' not found.[/red]")
return
# Display board information
board_data: Dict[str, Optional[str]] = info.get("board") or {}
if board_data:
console.print(Panel(f"[bold blue]{board_data.get('name')}[/bold blue]", title="📋 Board Info"))
else:
console.print("[yellow]No board information available.[/yellow]")
return
# Lists table
lists: List[Dict[str, Optional[str]]] = info.get("lists") or []
if lists:
lists_table = Table(title="📝 Lists", show_header=True, header_style="bold magenta")
lists_table.add_column("#", style="dim", width=3)
lists_table.add_column("List Name", style="cyan")
if verbose:
lists_table.add_column("ID", style="dim")
for i, lst in enumerate(lists, 1):
row = [str(i), lst.get("name")]
if verbose:
row.append(lst.get("id"))
lists_table.add_row(*row)
console.print(lists_table)
else:
console.print("[yellow]No lists found in this board.[/yellow]")
# Labels table
labels: List[Dict[str, Optional[str]]] = info.get("labels") or []
if labels:
labels_table = Table(title="🏷️ Labels", show_header=True, header_style="bold green")
labels_table.add_column("#", style="dim", width=3)
labels_table.add_column("Color", style="yellow")
labels_table.add_column("Name", style="cyan")
if verbose:
labels_table.add_column("ID", style="dim")
for i, label in enumerate(labels, 1):
color = label.get("color")
name = label.get("name")
row = [str(i), color, name]
if verbose:
row.append(label.get("id"))
labels_table.add_row(*row)
console.print(labels_table)
else:
console.print("[yellow]No labels found in this board.[/yellow]")
# Cards table
cards: List[Dict[str, Optional[str]]] = info.get("cards") or []
if cards:
# Create list lookup for card display
list_lookup = {lst.get("id"): lst.get("name") for lst in lists}
cards_table = Table(title="📄 Cards", show_header=True, header_style="bold blue")
cards_table.add_column("#", style="dim", width=3)
cards_table.add_column("Card Name", style="cyan")
cards_table.add_column("List", style="magenta")
if verbose:
cards_table.add_column("ID", style="dim")
for i, card in enumerate(cards, 1):
list_name = list_lookup.get(card.get("list_id"))
row = [str(i), card.get("name"), list_name]
if verbose:
row.append(card.get("id"))
cards_table.add_row(*row)
console.print(cards_table)
else:
console.print("[yellow]No cards found in this board.[/yellow]")
console.print(f"\n[green]Board has {len(lists)} lists, {len(labels)} labels, and {len(cards)} cards.[/green]")
except Exception as e:
console.print(f"[red]Error: {e}[/red]")
if __name__ == "__main__":
app()