-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
980 lines (844 loc) Β· 32.1 KB
/
main.py
File metadata and controls
980 lines (844 loc) Β· 32.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
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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
#!/usr/bin/env python3
"""
FUSE - (python dev tool) - CLI Main Entry Point
CLI - Terminal UI
"""
# sys imports
import asyncio
from enum import Enum
from pathlib import Path
from typing import Optional
# 3rd party imports
import typer
from rich.console import Console
from rich.panel import Panel
from rich.table import Table
from rich.progress import Progress, SpinnerColumn, TextColumn
# local imports
from python_dev_tool.core.config import Config
from python_dev_tool.core.exceptions import DevToolError
from python_dev_tool.utils.validation import validate_project_path
from python_dev_tool.cli.theme import DEV_THEME
# Initiate console
console = Console(theme=DEV_THEME, highlight=False)
error_console = Console(stderr=True, style="bold red")
# typer app
app = typer.Typer(
name="fuse",
help="π Python Development Tool - Supercharge your Python development workflow",
add_completion=False,
no_args_is_help=False,
rich_markup_mode="rich", # or markdown
context_settings={"help_option_names": ["-h", "--help"]},
)
# version info
__version__ = "0.0.1"
class LogLevel(str, Enum):
DEBUG = "debug"
INFO = "info"
WARNING = "warning"
ERROR = "error"
CRITICAL = "critical"
def version_callback(value: bool) -> None:
"""Display version information and exit."""
if value:
console.print(
f"[bold blue]Python Dev Tool[/bold blue] version [bold green]{__version__}[/bold green]"
)
console.print("π Supercharge your Python development workflow")
raise typer.Exit()
def verbose_callback(value: bool) -> None:
"""Enable verbose mode."""
if value:
import logging
logging.basicConfig(level=logging.DEBUG)
# default message when no subcommand is provided
def show_welcome():
"""Show welcome screen message and help information."""
console.print(
Panel.fit(
"[bold blue]π Welcome to the Python Dev Tool![/bold blue]",
style="blue",
)
)
console.print(
"[bold yellow]π Supercharge your Python development workflow[/bold yellow]"
)
console.print(
"A comprehensive development tool that provides:\n"
" β’ Live development server with hot reload\n"
" β’ Beautiful web-based debugging UI\n"
" β’ Multi-framework support (Django, Flask, FastAPI, etc.)\n"
" β’ One-click deployment to multiple platforms\n"
" β’ Real-time logs and performance monitoring\n"
)
console.print(
"[bold yellow]π Documentation: https://python-dev-tool.readthedocs.io[/bold yellow]"
)
console.print(
"[bold yellow]π¬ Community: https://github.com/lyznne/python-dev-tool/discussions[/bold yellow]"
)
console.print("\n[bold yellow]π‘ Next steps:[/bold yellow]")
console.print(
" β’ Run [bold]fuse init[/bold] to create a new project\n"
" β’ Run [bold]fuse dev[/bold] to start the development server\n"
" β’ Run [bold]fuse build[/bold] to build your project\n"
" β’ Run [bold]fuse deploy[/bold] to deploy your project\n"
" β’ Run [bold]fuse status[/bold] to check the status of your project\n"
)
@app.callback(invoke_without_command=True)
def main(
ctx: typer.Context,
version: bool = typer.Option(
None,
"--version",
"-V",
help="Show version information and exit.",
callback=version_callback,
is_eager=True,
# is_flag=True,
),
verbose: bool = typer.Option(
False,
"--verbose",
"-v",
help="Enable verbose mode.",
callback=verbose_callback,
is_eager=True,
# is_flag=True,
),
log_level: LogLevel = typer.Option(
LogLevel.INFO,
"--log-level",
"-l",
help="Set the log level.",
),
config_file: Optional[Path] = typer.Option(
None, "--config", "-c", help="Path to configuration file"
),
) -> None:
"""π Python Development Tool - Supercharge your Python development workflow
A comprehensive development tool that provides:
β’ Live development server with hot reload
β’ Beautiful web-based debugging UI
β’ Multi-framework support (Django, Flask, FastAPI, etc.)
β’ One-click deployment to multiple platforms
β’ Real-time logs and performance monitoring
"""
# set global config if provided
if config_file:
Config.set_config_file(config_file)
if ctx.invoked_subcommand is None:
# Show welcome message if no subcommand is provided
show_welcome()
# Command: init
@app.command()
def init(
project_path: Path = typer.Argument(
Path.cwd(), help="Path to initialize the project"
),
framework: Optional[str] = typer.Option(
None,
"--framework",
"-f",
help="Framework to use (django, flask, fastapi, streamlit, tornado, sanic, python)",
rich_help_panel="Project Configuration",
),
name: Optional[str] = typer.Option(
None,
"--name",
"-n",
help="Project name (defaults to directory name)",
rich_help_panel="Project Configuration",
),
template: Optional[str] = typer.Option(
None,
"--template",
"-t",
help="Project template to use (future feature)",
rich_help_panel="Project Configuration",
),
force: bool = typer.Option(
False,
"--force",
help="Force initialization even if directory is not empty",
rich_help_panel="Advanced Options",
),
verbose: bool = typer.Option(
False,
"--verbose",
"-v",
help="Enable verbose output for debugging",
rich_help_panel="Advanced Options",
),
install_deps: bool = typer.Option(
True,
"--install-deps/--no-install-deps",
help="Install Initial dependencies of the project.",
rich_help_panel="Advanced options",
),
python_executable: Optional[str] = typer.Option(
None,
"--python-bin",
help="Python executable to use. Uses the defoult of Your System.",
),
) -> None:
"""
π― Initialize a new Python project with FUSE development tools.
Creates a comprehensive development environment with:
β’ π§ Framework-specific configuration and setup
β’ π Virtual environment management
β’ π¦ Dependency management (requirements.txt)
β’ π₯ Hot-reload development server
β’ π Web-based development dashboard
β’ π³ Docker configuration templates
β’ π Built-in monitoring and logging
β’ π One-click deployment configurations
Examples:
# Initialize in current directory (interactive)
fuse init
# Initialize Django project
fuse init --framework django --name mysite
# Initialize FastAPI project in specific directory
fuse init /path/to/project --framework fastapi
# Force initialization in non-empty directory
fuse init --force --framework flask
# Disable installation of dependencies
fuse init --no-install-deps
# Pass Custom python executable
fuse init --python-bin /bin/script/python3.15
"""
try:
# Validate project path
validate_project_path(project_path)
# Display initialization banner
console.print(
Panel.fit(
"[bold blue]π― FUSE - Python Development Tool[/bold blue]\n"
"[dim]Initializing your development environment...[/dim]",
style="blue",
padding=(1, 2),
)
)
# Run initialization
# import init command
from python_dev_tool.cli.commands.init import init_project
result = init_project(
project_path=project_path,
framework=framework,
name=name,
template=template,
force=force,
verbose=verbose,
install_deps=install_deps,
python_executable=python_executable,
)
# Display success message
console.print(
f"\n[bold green]π Project initialized successfully![/bold green]"
)
console.print(f"π Location: [bold cyan]{result['project_path']}[/bold cyan]")
console.print(
f"π§ Framework: [bold magenta]{result['framework'].title()}[/bold magenta]"
)
console.print(f"π Name: [bold yellow]{result['name']}[/bold yellow]")
# Display next steps
if result.get("next_steps"):
console.print(
Panel(
"\n".join(
[
f"[bold cyan]{i + 1}.[/bold cyan] {step}"
for i, step in enumerate(result["next_steps"])
]
),
title="[bold green]π Next Steps[/bold green]",
border_style="green",
padding=(1, 2),
)
)
# Additional helpful information
console.print(
f"\n[dim]π‘ Pro tip: Run [bold]fuse --help[/bold] to see all available commands[/dim]"
)
except DevToolError as e:
error_console.print(
Panel(
f"[bold red]β Initialization Error[/bold red]\n\n{str(e)}",
border_style="red",
padding=(1, 2),
)
)
if verbose:
error_console.print_exception()
raise typer.Exit(1)
except KeyboardInterrupt:
console.print(f"\n[yellow]β οΈ Initialization cancelled by user[/yellow]")
raise typer.Exit(130)
except Exception as e:
error_console.print(
Panel(
f"[bold red]π₯ Unexpected Error[/bold red]\n\n{str(e)}",
border_style="red",
padding=(1, 2),
)
)
if verbose:
error_console.print_exception()
raise typer.Exit(1)
# command: dev
@app.command()
def dev(
project_path: Path = typer.Argument(Path.cwd(), help="Path to the project"),
port: int = typer.Option(
8000, "--port", "-p", help="Port to run the development server on"
),
host: str = typer.Option(
"127.0.0.1", "--host", "-h", help="Host to run the development server on"
),
debug: bool = typer.Option(
True, "--debug/--no-debug", help="Enable/disable debugging"
),
reload: bool = typer.Option(
True, "--reload/--no-reload", help="Enable/disable hot reload"
),
ui_port: int = typer.Option(
8001, "--ui-port", help="Port to run the debugging UI on"
),
open_browser: bool = typer.Option(
True, "--open-browser/--no-open-browser", help="Open the browser after starting"
),
verbose: bool = typer.Option(
False, "--verbose", "-v", help="Enable verbose output for debugging"
),
) -> None:
"""
π₯ Start the development server with live reload and debugging UI
Features:
β’ Live development server with hot reload
β’ Real-time web-based debugging interface
β’ Log streaming and error highlighting
β’ Performance monitoring
β’ Command execution interface
"""
try:
# validate project path
validate_project_path(project_path)
# show dev server banner
console.print(
Panel.fit(
"[bold blue]π₯ Starting Development Server[/bold blue]",
style="green",
)
)
# create dev server info table
info_table = Table(show_header=False, box=None, padding=(0, 1))
info_table.add_row("Project:", f"[bold]{project_path.name}[/bold]")
info_table.add_row("Server:", f"[bold]http://{host}:{port}[/bold]")
info_table.add_row("Debug UI:", f"[bold]http://{host}:{ui_port}[/bold]")
info_table.add_row(
"Reload:", f"[bold]{'Enabled' if reload else 'Disabled'}[/bold]"
)
info_table.add_row(
"π Debug:", f"[bold]{'Enabled' if debug else 'Disabled'}[/bold]"
)
console.print(info_table)
console.print()
# start dev server
from python_dev_tool.cli.commands.dev import DevCommand
dev_cmd = DevCommand(
project_path=project_path,
port=port,
host=host,
debug=debug,
reload=reload,
ui_port=ui_port,
open_browser=open_browser,
)
# Run dev server - this will block
asyncio.run(dev_cmd.run())
except KeyboardInterrupt:
console.print("\n[yellow]Development server stopped by user.[/yellow]")
raise typer.Exit(1)
except DevToolError as e:
console.print(f"[bold red]Error: {e}[/bold red]")
raise typer.Exit(1)
except Exception as e:
console.print(f"[bold red]Unexpected error occurred: {e}[/bold red]")
if verbose:
console.print_exception()
raise typer.Exit(1)
# Command: build
@app.command()
def build(
project_path: Path = typer.Argument(Path.cwd(), help="Path to the project"),
target: str = typer.Option("Production", "--target", "-t", help="Build target"),
output_dir: Path = typer.Option(
None, "--output-dir", "-o", help="Output directory"
),
clean: bool = typer.Option(
False, "--clean/--no-clean", help="Clean output directory before build"
),
optimize: bool = typer.Option(
True,
"--optimize/--no-optimize",
help="Enable asset optimization / Build optimizations",
),
verbose: bool = typer.Option(
False, "--verbose", "-v", help="Enable verbose output for debugging"
),
) -> None:
"""
ποΈ Build the project for deployment
Features:
β’ Multi-target builds (development, staging, production)
β’ Asset optimization and minification
β’ Docker image building
β’ Static file collection
β’ Dependency bundling
"""
try:
validate_project_path(project_path)
console.print(
Panel.fit(
"[bold blue]ποΈ Building Project[/bold blue]",
style="blue",
)
)
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
console=console,
) as progress:
task = progress.add_task("[bold blue]Building project...", total=None)
from python_dev_tool.cli.commands.build import BuildCommand
build_cmd = BuildCommand(
project_path=project_path,
target=target,
output_dir=output_dir,
clean=clean,
optimize=optimize,
)
result = build_cmd.run()
progress.update(task, description=" build complete successfully")
console.print(f"\n[bold green]Build completed successfully![/bold green]") # noqa: F541
console.print(f"Build artifacts: [bold]{result['output_path']}[/bold]")
if result.get("size_info"):
console.print(
f"\n[bold yellow]Build size: [bold]{result['size_info']}[/bold]"
)
except DevToolError as e:
console.print(f"[bold red]Build failed:: {e}[/bold red]")
raise typer.Exit(1)
except Exception as e:
console.print(f"[bold red]Unexpected error occurred: {e}[/bold red]")
if verbose:
console.print_exception()
raise typer.Exit(1)
# Command: deploy
@app.command()
def deploy(
project_path: Path = typer.Argument(
Path.cwd(), help="Path to the project directory"
),
platform: str = typer.Option(
...,
"--platform",
"-p",
help="Deployment platform (railway, render, heroku, vercel, aws, docker)",
),
environment: str = typer.Option(
"production", "--env", "-e", help="Deployment environment"
),
config_file: Optional[Path] = typer.Option(
None, "--config", "-c", help="Deployment configuration file"
),
dry_run: bool = typer.Option(
False, "--dry-run", help="Show deployment plan without executing"
),
auto_build: bool = typer.Option(
True, "--build/--no-build", help="Build project before deployment"
),
verbose: bool = typer.Option(
False, "--verbose", "-v", help="Enable verbose output for debugging"
),
) -> None:
"""
π Deploy the project to various platforms
Supported platforms:
β’ Railway, Render, Heroku (PaaS)
β’ Vercel, Netlify (Static/Serverless)
β’ AWS, GCP, Azure (Cloud providers)
β’ Docker registries
β’ Custom deployment scripts
"""
try:
validate_project_path(project_path)
console.print(
Panel.fit(
f"[bold magenta]π Deploying Project to [bold]{platform}[/bold magenta]",
style="magenta",
)
)
if dry_run:
console.print(
console.print(
"[yellow]Dry run mode - showing deployment plan[/yellow]\n"
)
)
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
console=console,
) as progress:
task = progress.add_task("[bold blue]Preparring Deployment...", total=None)
from python_dev_tool.cli.commands.deploy import DeployCommand
deploy_cmd = DeployCommand(
project_path=project_path,
platform=platform,
environment=environment,
config_file=config_file,
dry_run=dry_run,
auto_build=auto_build,
)
result = deploy_cmd.run()
if not dry_run:
progress.update(task, description=" deployment complete successfully")
else:
progress.update(task, description=" deployment plan generated")
if dry_run:
console.print(f"\n[bold yellow] Deployment Plan:[/bold yellow]") # noqa: F541
for step in result.get("plan", []):
console.print(f" β’ {step}")
else:
console.print(
f"\n[bold green]Deployment completed successfully![/bold green]" # noqa: F541
)
console.print(
f"π Application URL: [bold]{result.get('url', 'N/A')}[/bold]"
)
progress.update(task, description=" deployment complete")
except DevToolError as e:
console.print(f"[bold red]Deploy failed:: {e}[/bold red]")
raise typer.Exit(1)
except Exception as e:
console.print(f"[bold red]Unexpected error occurred: {e}[/bold red]")
if verbose:
console.print_exception()
raise typer.Exit(1)
# Command: config
@app.command()
def config_command(
action: str = typer.Argument(..., help="Action to perform (show, set, get, reset)"),
key: Optional[str] = typer.Argument(None, help="Configuration key"),
value: Optional[str] = typer.Argument(None, help="Configuration value"),
global_config: bool = typer.Option(
False, "--global", "-g", help="Use global configuration"
),
project_path: Path = typer.Option(
Path.cwd(), "--project", help="Project path for local configuration"
),
verbose: bool = typer.Option(
False, "--verbose", "-v", help="Enable verbose output for debugging"
),
) -> None:
"""
βοΈ Manage configuration settings
Actions:
β’ show: Display current configuration
β’ set: Set configuration value
β’ get: Get configuration value
β’ reset: Reset to default values
"""
try:
from python_dev_tool.cli.commands.config import ConfigCommand
config_cmd = ConfigCommand(
action=action,
key=key,
value=value,
global_config=global_config,
project_path=project_path,
)
result = config_cmd.run()
if action == "show":
console.print(
Panel.fit(
"[bold blue]βοΈ Configuration Settings[/bold blue]", style="blue"
)
)
config_table = Table(show_header=True, header_style="bold blue")
config_table.add_column("Key", style="cyan")
config_table.add_column("Value", style="green")
config_table.add_column("Source", style="yellow")
for item in result.get("config", []):
config_table.add_row(item["key"], item["value"], item["source"])
console.print(config_table)
elif action == "get":
console.print(
f"[bold blue]{key}:[/bold blue] [green]{result.get('value', 'Not set')}[/green]"
)
elif action == "set":
console.print(
f"[bold green]Configuration updated:[/bold green] {key} = {value}"
)
elif action == "reset":
console.print("[bold yellow]Configuration reset to defaults[/bold yellow]")
except DevToolError as e:
console.print(f"[bold red]Configuration failed:: {e}[/bold red]")
raise typer.Exit(1)
except Exception as e:
console.print(f"[bold red]Unexpected error occurred: {e}[/bold red]")
if verbose:
console.print_exception()
raise typer.Exit(1)
# Command: status
@app.command()
def status(
project_path: Path = typer.Argument(
Path.cwd(), help="Path to the project directory"
),
detailed: bool = typer.Option(
False, "--detailed", "-d", help="Show detailed status information"
),
verbose: bool = typer.Option(
False, "--verbose", "-v", help="Enable verbose output for debugging"
),
) -> None:
"""
π Show project status and health information
Displays:
β’ Project configuration
β’ Framework detection
β’ Service health
β’ Recent logs
β’ Performance metrics
"""
try:
validate_project_path(project_path)
console.print(
Panel.fit("[bold blue]π Project Status[/bold blue]", style="blue")
)
from python_dev_tool.core.app import DevToolApp
from python_dev_tool.cli.commands.status import StatusCommand
status_cmd = StatusCommand(
project_path=project_path, detailed=detailed, check_deps=True
)
status_info = status_cmd.run()
app_instance = DevToolApp(project_path)
app_status = app_instance.get_status()
status_info.update(app_status)
# Project info
info_table = Table(show_header=False, box=None, padding=(0, 1))
info_table.add_row("Project:", f"[bold]{status_info['project_name']}[/bold]")
info_table.add_row("Framework:", f"[bold]{status_info['framework']}[/bold]")
info_table.add_row(
"Status:",
f"[bold green]{'Running' if status_info['running'] else 'Stopped'}[/bold green]",
)
info_table.add_row("Config:", f"[bold]{status_info['config_file']}[/bold]")
console.print(info_table)
if detailed:
# Performance metrics
if status_info.get("metrics"):
console.print("\n[bold yellow]Performance Metrics:[/bold yellow]")
metrics_table = Table(show_header=True, header_style="bold yellow")
metrics_table.add_column("Metric", style="cyan")
metrics_table.add_column("Value", style="green")
for metric, value in status_info["metrics"].items():
metrics_table.add_row(metric, str(value))
console.print(metrics_table)
# Recent logs
if status_info.get("recent_logs"):
console.print("\n[bold yellow]Recent Logs:[/bold yellow]")
for log in status_info["recent_logs"][-5:]: # Show last 5 logs
console.print(f" {log}")
except DevToolError as e:
console.print(f"[bold red]β Status error:[/bold red] {e}")
raise typer.Exit(1)
except Exception as e:
console.print(f"[bold red]β Unexpected error:[/bold red] {e}")
if verbose:
console.print_exception()
raise typer.Exit(1)
# Command: help
# Command: update
@app.command()
def update(
version: Optional[str] = typer.Option(
None, "--version", "-V", help="Specific version to install (e.g., 1.2.3)"
),
pre_release: bool = typer.Option(
False, "--pre-release", "--pre", help="Include pre-release versions"
),
force: bool = typer.Option(
False, "--force", "-f", help="Force update even if already up to date"
),
check_only: bool = typer.Option(
False, "--check", "-c", help="Check for updates without installing"
),
verbose: bool = typer.Option(
False, "--verbose", "-v", help="Enable verbose output for debugging"
),
) -> None:
"""
π Update the python-dev-tool to the latest version
Features:
β’ Check for latest stable or pre-release versions
β’ Update to specific version
β’ Backup current installation
β’ Rollback on failure
β’ Check-only mode for CI/CD
"""
try:
console.print(
Panel.fit(
"[bold blue]π Python Dev Tool Updater[/bold blue]",
style="blue",
)
)
# Import update command
from python_dev_tool.cli.commands.update import UpdateCommand
update_cmd = UpdateCommand(
target_version=version,
include_pre_release=pre_release,
force=force,
check_only=check_only,
verbose=verbose,
)
if check_only:
# Just check for updates
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
console=console,
) as progress:
task = progress.add_task(
"[bold blue]Checking for updates...", total=None
)
result = update_cmd.check_for_updates()
progress.update(task, description="β Update check complete")
if result["update_available"]:
console.print(f"\n[bold yellow]π¦ Update available![/bold yellow]")
console.print(
f"Current version: [bold red]{result['current_version']}[/bold red]"
)
console.print(
f"Latest version: [bold green]{result['latest_version']}[/bold green]"
)
if result.get("changelog"):
console.print(f"\n[bold blue]What's new:[/bold blue]")
for change in result["changelog"][:3]: # Show top 3 changes
console.print(f" β’ {change}")
console.print(
f"\nRun [bold]fuse update[/bold] to install the latest version"
)
else:
console.print(
f"\n[bold green]β
You're already running the latest version ({result['current_version']})[/bold green]"
)
return
# Perform the update
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
console=console,
) as progress:
# Check for updates
check_task = progress.add_task(
"[bold blue]Checking for updates...", total=None
)
update_info = update_cmd.check_for_updates()
progress.update(check_task, description="β Update check complete")
if not update_info["update_available"] and not force:
progress.update(check_task, description="β Already up to date")
console.print(
f"\n[bold green]β
Already running the latest version ({update_info['current_version']})[/bold green]"
)
return
# Show update information
if update_info["update_available"]:
console.print(
f"\n[bold yellow]π¦ Updating from {update_info['current_version']} to {update_info['latest_version']}[/bold yellow]"
)
# Create backup
backup_task = progress.add_task("[bold blue]Creating backup...", total=None)
backup_result = update_cmd.create_backup()
progress.update(backup_task, description="β Backup created")
# Download and install update
download_task = progress.add_task(
"[bold blue]Downloading update...", total=None
)
try:
download_result = update_cmd.download_update(
update_info["latest_version"]
)
progress.update(download_task, description="β Download complete")
# Install update
install_task = progress.add_task(
"[bold blue]Installing update...", total=None
)
install_result = update_cmd.install_update(
download_result["package_path"]
)
progress.update(install_task, description="β Installation complete")
# Verify installation
verify_task = progress.add_task(
"[bold blue]Verifying installation...", total=None
)
verification_result = update_cmd.verify_installation()
progress.update(verify_task, description="β Verification complete")
if verification_result["success"]:
console.print(
f"\n[bold green]π Successfully updated to version {verification_result['new_version']}![/bold green]"
)
# Show what's new
if update_info.get("changelog"):
console.print(
f"\n[bold blue]π What's new in {verification_result['new_version']}:[/bold blue]"
)
for change in update_info["changelog"][
:5
]: # Show top 5 changes
console.print(f" β’ {change}")
# Clean up backup if successful
update_cmd.cleanup_backup(backup_result["backup_path"])
console.print(f"\n[dim]Backup cleaned up[/dim]")
else:
raise DevToolError("Installation verification failed")
except Exception as e:
# Rollback on failure
progress.add_task(
"[bold red]Update failed, rolling back...", total=None
)
rollback_result = update_cmd.rollback(backup_result["backup_path"])
if rollback_result["success"]:
console.print(
f"\n[bold yellow]β οΈ Update failed but successfully rolled back to {rollback_result['restored_version']}[/bold yellow]"
)
else:
console.print(
f"\n[bold red]β Update and rollback failed! Manual intervention required.[/bold red]"
)
console.print(f"Backup location: {backup_result['backup_path']}")
raise DevToolError(f"Update failed: {str(e)}")
# Show next steps
console.print(f"\n[bold blue]π‘ Next steps:[/bold blue]")
console.print(" β’ Restart any running development servers")
console.print(
" β’ Run [bold]fuse status[/bold] to verify everything is working"
)
console.print(" β’ Check the changelog for breaking changes")
except DevToolError as e:
error_console.print(f"[bold red]Update failed: {e}[/bold red]")
raise typer.Exit(1)
except KeyboardInterrupt:
console.print("\n[yellow]Update cancelled by user.[/yellow]")
raise typer.Exit(1)
except Exception as e:
console.print(f"[bold red]Unexpected error occurred: {e}[/bold red]")
if verbose:
console.print_exception()
raise typer.Exit(1)
#
# if __name__ == "__main__":
# app()