xenfra 0.2.2__py3-none-any.whl → 0.2.4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,312 @@
1
+ """
2
+ AI-powered intelligence commands for Xenfra CLI.
3
+ Includes smart initialization, deployment diagnosis, and codebase analysis.
4
+ """
5
+ import os
6
+
7
+ import click
8
+ from rich.console import Console
9
+ from rich.panel import Panel
10
+ from rich.prompt import Confirm, Prompt
11
+ from rich.table import Table
12
+ from xenfra_sdk import XenfraClient
13
+ from xenfra_sdk.exceptions import XenfraAPIError, XenfraError
14
+ from xenfra_sdk.privacy import scrub_logs
15
+
16
+ from ..utils.auth import API_BASE_URL, get_auth_token
17
+ from ..utils.codebase import has_xenfra_config, scan_codebase
18
+ from ..utils.config import apply_patch, generate_xenfra_yaml, manual_prompt_for_config, read_xenfra_yaml
19
+
20
+ console = Console()
21
+
22
+
23
+ def get_client() -> XenfraClient:
24
+ """Get authenticated SDK client."""
25
+ token = get_auth_token()
26
+ if not token:
27
+ console.print("[bold red]Not logged in. Run 'xenfra login' first.[/bold red]")
28
+ raise click.Abort()
29
+
30
+ return XenfraClient(token=token, api_url=API_BASE_URL)
31
+
32
+
33
+ @click.command()
34
+ @click.option('--manual', is_flag=True, help='Skip AI detection, use interactive mode')
35
+ @click.option('--accept-all', is_flag=True, help='Accept AI suggestions without confirmation')
36
+ def init(manual, accept_all):
37
+ """
38
+ Initialize Xenfra configuration (AI-powered by default).
39
+
40
+ Scans your codebase, detects framework and dependencies,
41
+ and generates xenfra.yaml automatically.
42
+
43
+ Use --manual to skip AI and configure interactively.
44
+ Set XENFRA_NO_AI=1 environment variable to force manual mode globally.
45
+ """
46
+ # Check if config already exists
47
+ if has_xenfra_config():
48
+ console.print("[yellow]xenfra.yaml already exists.[/yellow]")
49
+ if not Confirm.ask("Overwrite existing configuration?"):
50
+ console.print("[dim]Cancelled.[/dim]")
51
+ return
52
+
53
+ # Check for XENFRA_NO_AI environment variable
54
+ no_ai = os.environ.get('XENFRA_NO_AI', '0') == '1'
55
+ if no_ai and not manual:
56
+ console.print("[yellow]XENFRA_NO_AI is set. Using manual mode.[/yellow]")
57
+ manual = True
58
+
59
+ # Manual mode - interactive prompts
60
+ if manual:
61
+ console.print("[cyan]Manual configuration mode[/cyan]\n")
62
+ try:
63
+ filename = manual_prompt_for_config()
64
+ console.print(f"\n[bold green]✓ xenfra.yaml created successfully![/bold green]")
65
+ console.print(f"[dim]Run 'xenfra deploy' to deploy your project.[/dim]")
66
+ except KeyboardInterrupt:
67
+ console.print("\n[dim]Cancelled.[/dim]")
68
+ except Exception as e:
69
+ console.print(f"[bold red]Error: {e}[/bold red]")
70
+ return
71
+
72
+ # AI-powered detection (default)
73
+ try:
74
+ # Use context manager for SDK client
75
+ with get_client() as client:
76
+ # Scan codebase
77
+ console.print("[cyan]Analyzing your codebase...[/cyan]")
78
+ code_snippets = scan_codebase()
79
+
80
+ if not code_snippets:
81
+ console.print("[bold red]No code files found to analyze.[/bold red]")
82
+ console.print("[dim]Make sure you're in a Python project directory.[/dim]")
83
+ return
84
+
85
+ console.print(f"[dim]Found {len(code_snippets)} files to analyze[/dim]")
86
+
87
+ # Call Intelligence Service
88
+ analysis = client.intelligence.analyze_codebase(code_snippets)
89
+
90
+ # Display results
91
+ console.print("\n[bold green]Analysis Complete![/bold green]\n")
92
+
93
+ # Handle package manager conflict
94
+ selected_package_manager = analysis.package_manager
95
+ selected_dependency_file = analysis.dependency_file
96
+
97
+ if analysis.has_conflict and analysis.detected_package_managers:
98
+ console.print("[yellow]Multiple package managers detected![/yellow]\n")
99
+
100
+ # Show options
101
+ for i, option in enumerate(analysis.detected_package_managers, 1):
102
+ console.print(f" {i}. [cyan]{option.manager}[/cyan] ({option.file})")
103
+
104
+ console.print(f"\n[dim]Recommended: {analysis.package_manager} (most modern)[/dim]")
105
+
106
+ # Prompt user to select
107
+ choice = Prompt.ask(
108
+ "\nWhich package manager do you want to use?",
109
+ choices=[str(i) for i in range(1, len(analysis.detected_package_managers) + 1)],
110
+ default="1"
111
+ )
112
+
113
+ # Update selection based on user choice
114
+ selected_option = analysis.detected_package_managers[int(choice) - 1]
115
+ selected_package_manager = selected_option.manager
116
+ selected_dependency_file = selected_option.file
117
+
118
+ console.print(f"\n[green]Using {selected_package_manager} ({selected_dependency_file})[/green]\n")
119
+
120
+ table = Table(show_header=False, box=None)
121
+ table.add_column("Property", style="cyan")
122
+ table.add_column("Value", style="white")
123
+
124
+ table.add_row("Framework", analysis.framework)
125
+ table.add_row("Port", str(analysis.port))
126
+ table.add_row("Database", analysis.database)
127
+ if analysis.cache:
128
+ table.add_row("Cache", analysis.cache)
129
+ if analysis.workers:
130
+ table.add_row("Workers", ", ".join(analysis.workers))
131
+ table.add_row("Package Manager", selected_package_manager)
132
+ table.add_row("Dependency File", selected_dependency_file)
133
+ table.add_row("Instance Size", analysis.instance_size)
134
+ table.add_row("Estimated Cost", f"${analysis.estimated_cost_monthly:.2f}/month")
135
+ table.add_row("Confidence", f"{analysis.confidence:.0%}")
136
+
137
+ console.print(Panel(table, title="[bold]Detected Configuration[/bold]"))
138
+
139
+ if analysis.notes:
140
+ console.print(f"\n[dim]{analysis.notes}[/dim]")
141
+
142
+ # Confirm or edit
143
+ if accept_all:
144
+ confirmed = True
145
+ else:
146
+ confirmed = Confirm.ask("\nCreate xenfra.yaml with this configuration?", default=True)
147
+
148
+ if confirmed:
149
+ filename = generate_xenfra_yaml(analysis)
150
+ console.print(f"[bold green]xenfra.yaml created successfully![/bold green]")
151
+ console.print(f"[dim]Run 'xenfra deploy' to deploy your project.[/dim]")
152
+ else:
153
+ console.print("[yellow]Configuration cancelled.[/yellow]")
154
+
155
+ except XenfraAPIError as e:
156
+ console.print(f"[bold red]API Error: {e.detail}[/bold red]")
157
+ except XenfraError as e:
158
+ console.print(f"[bold red]Error: {e}[/bold red]")
159
+ except click.Abort:
160
+ pass
161
+ except Exception as e:
162
+ console.print(f"[bold red]Unexpected error: {e}[/bold red]")
163
+
164
+
165
+ @click.command()
166
+ @click.argument('deployment-id', required=False)
167
+ @click.option('--apply', is_flag=True, help='Auto-apply suggested patch (with confirmation)')
168
+ @click.option('--logs', type=click.File('r'), help='Diagnose from log file instead of deployment')
169
+ def diagnose(deployment_id, apply, logs):
170
+ """
171
+ Diagnose deployment failures using AI.
172
+
173
+ Analyzes logs and provides diagnosis, suggestions, and optionally
174
+ an automatic patch to fix the issue.
175
+ """
176
+ try:
177
+ # Use context manager for all SDK operations
178
+ with get_client() as client:
179
+ # Get logs
180
+ if logs:
181
+ log_content = logs.read()
182
+ console.print(f"[cyan]Analyzing logs from file...[/cyan]")
183
+ elif deployment_id:
184
+ console.print(f"[cyan]Fetching logs for deployment {deployment_id}...[/cyan]")
185
+ log_content = client.deployments.get_logs(deployment_id)
186
+
187
+ if not log_content:
188
+ console.print("[yellow]No logs found for this deployment.[/yellow]")
189
+ return
190
+ else:
191
+ console.print("[bold red]Please specify a deployment ID or use --logs <file>[/bold red]")
192
+ console.print("[dim]Usage: xenfra diagnose <deployment-id> or xenfra diagnose --logs error.log[/dim]")
193
+ return
194
+
195
+ # Scrub sensitive data
196
+ scrubbed_logs = scrub_logs(log_content)
197
+
198
+ # Try to read package manager context from xenfra.yaml
199
+ package_manager = None
200
+ dependency_file = None
201
+ try:
202
+ config = read_xenfra_yaml()
203
+ package_manager = config.get('package_manager')
204
+ dependency_file = config.get('dependency_file')
205
+
206
+ if package_manager and dependency_file:
207
+ console.print(f"[dim]Using context: {package_manager} ({dependency_file})[/dim]")
208
+ except FileNotFoundError:
209
+ # No config file - diagnosis will infer from logs
210
+ console.print("[dim]No xenfra.yaml found - inferring package manager from logs[/dim]")
211
+
212
+ # Diagnose with context
213
+ console.print("[cyan]Analyzing failure...[/cyan]")
214
+ result = client.intelligence.diagnose(
215
+ logs=scrubbed_logs,
216
+ package_manager=package_manager,
217
+ dependency_file=dependency_file
218
+ )
219
+
220
+ # Display diagnosis
221
+ console.print("\n")
222
+ console.print(Panel(result.diagnosis, title="[bold red]Diagnosis[/bold red]", border_style="red"))
223
+ console.print(Panel(result.suggestion, title="[bold yellow]Suggestion[/bold yellow]", border_style="yellow"))
224
+
225
+ # Handle patch
226
+ if result.patch and result.patch.file:
227
+ console.print("\n[bold green]Automatic fix available![/bold green]")
228
+ console.print(f" File: [cyan]{result.patch.file}[/cyan]")
229
+ console.print(f" Operation: [yellow]{result.patch.operation}[/yellow]")
230
+ console.print(f" Value: [white]{result.patch.value}[/white]")
231
+
232
+ if apply or Confirm.ask("\nApply this patch?", default=False):
233
+ try:
234
+ apply_patch(result.patch.model_dump())
235
+ console.print("[bold green]Patch applied successfully![/bold green]")
236
+ console.print("[cyan]Run 'xenfra deploy' to retry deployment.[/cyan]")
237
+ except FileNotFoundError as e:
238
+ console.print(f"[bold red]Error: {e}[/bold red]")
239
+ except Exception as e:
240
+ console.print(f"[bold red]Failed to apply patch: {e}[/bold red]")
241
+ else:
242
+ console.print("[dim]Patch not applied. Follow manual steps above.[/dim]")
243
+ else:
244
+ console.print("\n[yellow]No automatic fix available.[/yellow]")
245
+ console.print("[dim]Please follow the manual steps in the suggestion above.[/dim]")
246
+
247
+ except XenfraAPIError as e:
248
+ console.print(f"[bold red]API Error: {e.detail}[/bold red]")
249
+ except XenfraError as e:
250
+ console.print(f"[bold red]Error: {e}[/bold red]")
251
+ except click.Abort:
252
+ pass
253
+ except Exception as e:
254
+ console.print(f"[bold red]Unexpected error: {e}[/bold red]")
255
+
256
+
257
+ @click.command()
258
+ def analyze():
259
+ """
260
+ Analyze codebase without creating configuration.
261
+
262
+ Shows what AI would detect, useful for previewing before running init.
263
+ """
264
+ try:
265
+ # Use context manager for SDK client
266
+ with get_client() as client:
267
+ # Scan codebase
268
+ console.print("[cyan]Analyzing your codebase...[/cyan]")
269
+ code_snippets = scan_codebase()
270
+
271
+ if not code_snippets:
272
+ console.print("[bold red]No code files found to analyze.[/bold red]")
273
+ return
274
+
275
+ # Call Intelligence Service
276
+ analysis = client.intelligence.analyze_codebase(code_snippets)
277
+
278
+ # Display results
279
+ console.print("\n[bold green]Analysis Results:[/bold green]\n")
280
+
281
+ table = Table(show_header=False, box=None)
282
+ table.add_column("Property", style="cyan")
283
+ table.add_column("Value", style="white")
284
+
285
+ table.add_row("Framework", analysis.framework)
286
+ table.add_row("Port", str(analysis.port))
287
+ table.add_row("Database", analysis.database)
288
+ if analysis.cache:
289
+ table.add_row("Cache", analysis.cache)
290
+ if analysis.workers:
291
+ table.add_row("Workers", ", ".join(analysis.workers))
292
+ if analysis.env_vars:
293
+ table.add_row("Environment Variables", ", ".join(analysis.env_vars))
294
+ table.add_row("Instance Size", analysis.instance_size)
295
+ table.add_row("Estimated Cost", f"${analysis.estimated_cost_monthly:.2f}/month")
296
+ table.add_row("Confidence", f"{analysis.confidence:.0%}")
297
+
298
+ console.print(table)
299
+
300
+ if analysis.notes:
301
+ console.print(f"\n[dim]Notes: {analysis.notes}[/dim]")
302
+
303
+ console.print(f"\n[dim]Run 'xenfra init' to create xenfra.yaml with this configuration.[/dim]")
304
+
305
+ except XenfraAPIError as e:
306
+ console.print(f"[bold red]API Error: {e.detail}[/bold red]")
307
+ except XenfraError as e:
308
+ console.print(f"[bold red]Error: {e}[/bold red]")
309
+ except click.Abort:
310
+ pass
311
+ except Exception as e:
312
+ console.print(f"[bold red]Unexpected error: {e}[/bold red]")
@@ -0,0 +1,163 @@
1
+ """
2
+ Project management commands for Xenfra CLI.
3
+ """
4
+ import click
5
+ from rich.console import Console
6
+ from rich.table import Table
7
+ from xenfra_sdk import XenfraClient
8
+ from xenfra_sdk.exceptions import XenfraAPIError, XenfraError
9
+
10
+ from ..utils.auth import API_BASE_URL, get_auth_token
11
+
12
+ console = Console()
13
+
14
+
15
+ def get_client() -> XenfraClient:
16
+ """Get authenticated SDK client."""
17
+ token = get_auth_token()
18
+ if not token:
19
+ console.print("[bold red]Not logged in. Run 'xenfra login' first.[/bold red]")
20
+ raise click.Abort()
21
+
22
+ return XenfraClient(token=token, api_url=API_BASE_URL)
23
+
24
+
25
+ @click.group()
26
+ def projects():
27
+ """Manage projects."""
28
+ pass
29
+
30
+
31
+ @projects.command()
32
+ def list():
33
+ """List all projects."""
34
+ try:
35
+ # Use context manager for proper cleanup
36
+ with get_client() as client:
37
+ projects_list = client.projects.list()
38
+
39
+ if not projects_list:
40
+ console.print("[bold yellow]No projects found.[/bold yellow]")
41
+ return
42
+
43
+ # Create a rich table
44
+ table = Table(title="Projects")
45
+ table.add_column("ID", style="cyan")
46
+ table.add_column("Name", style="green")
47
+ table.add_column("Status", style="yellow")
48
+ table.add_column("Region", style="blue")
49
+ table.add_column("IP Address", style="magenta")
50
+ table.add_column("Cost/Month", style="red")
51
+
52
+ for project in projects_list:
53
+ cost = f"${project.estimated_monthly_cost:.2f}" if project.estimated_monthly_cost else "N/A"
54
+ table.add_row(
55
+ str(project.id),
56
+ project.name,
57
+ project.status,
58
+ project.region,
59
+ project.ip_address or "N/A",
60
+ cost
61
+ )
62
+
63
+ console.print(table)
64
+
65
+ except XenfraAPIError as e:
66
+ console.print(f"[bold red]API Error: {e.detail}[/bold red]")
67
+ except XenfraError as e:
68
+ console.print(f"[bold red]Error: {e}[/bold red]")
69
+ except click.Abort:
70
+ pass
71
+
72
+
73
+ @projects.command()
74
+ @click.argument('project_id', type=int)
75
+ def show(project_id):
76
+ """Show details for a specific project."""
77
+ try:
78
+ with get_client() as client:
79
+ project = client.projects.show(project_id)
80
+
81
+ # Create detailed panel
82
+ from rich.panel import Panel
83
+
84
+ details = f"""[cyan]Name:[/cyan] {project.name}
85
+ [cyan]Status:[/cyan] {project.status}
86
+ [cyan]Region:[/cyan] {project.region}
87
+ [cyan]IP Address:[/cyan] {project.ip_address or 'N/A'}
88
+ [cyan]Size:[/cyan] {project.size_slug}
89
+ [cyan]Cost/Month:[/cyan] ${project.estimated_monthly_cost:.2f} USD
90
+ [cyan]Created:[/cyan] {project.created_at}"""
91
+
92
+ panel = Panel(
93
+ details,
94
+ title=f"[bold green]Project {project.id}[/bold green]",
95
+ border_style="green"
96
+ )
97
+ console.print(panel)
98
+
99
+ except XenfraAPIError as e:
100
+ console.print(f"[bold red]API Error: {e.detail}[/bold red]")
101
+ except XenfraError as e:
102
+ console.print(f"[bold red]Error: {e}[/bold red]")
103
+ except click.Abort:
104
+ pass
105
+
106
+
107
+ @projects.command()
108
+ @click.argument('project_id', type=int)
109
+ @click.confirmation_option(prompt='Are you sure you want to delete this project?')
110
+ def delete(project_id):
111
+ """Delete a project."""
112
+ try:
113
+ with get_client() as client:
114
+ client.projects.delete(str(project_id))
115
+ console.print(f"[bold green]Project {project_id} deletion initiated.[/bold green]")
116
+
117
+ except XenfraAPIError as e:
118
+ console.print(f"[bold red]API Error: {e.detail}[/bold red]")
119
+ except XenfraError as e:
120
+ console.print(f"[bold red]Error: {e}[/bold red]")
121
+ except click.Abort:
122
+ pass
123
+
124
+
125
+ @projects.command()
126
+ @click.argument('name')
127
+ @click.option('--region', default='nyc3', help='DigitalOcean region (default: nyc3)')
128
+ @click.option('--size', 'size_slug', default='s-1vcpu-1gb', help='Droplet size (default: s-1vcpu-1gb)')
129
+ def create(name, region, size_slug):
130
+ """Create a new project."""
131
+ try:
132
+ with get_client() as client:
133
+ console.print(f"[cyan]Creating project '{name}'...[/cyan]")
134
+
135
+ # Create project
136
+ project = client.projects.create(name=name, region=region, size_slug=size_slug)
137
+
138
+ # Display success message
139
+ console.print(f"[bold green]✓[/bold green] Project created successfully!")
140
+
141
+ # Show project details
142
+ from rich.panel import Panel
143
+
144
+ details = f"""[cyan]ID:[/cyan] {project.id}
145
+ [cyan]Name:[/cyan] {project.name}
146
+ [cyan]Status:[/cyan] {project.status}
147
+ [cyan]Region:[/cyan] {project.region}
148
+ [cyan]Size:[/cyan] {project.size_slug}
149
+ [cyan]Estimated Cost:[/cyan] ${project.estimated_monthly_cost:.2f}/month"""
150
+
151
+ panel = Panel(
152
+ details,
153
+ title="[bold green]New Project[/bold green]",
154
+ border_style="green"
155
+ )
156
+ console.print(panel)
157
+
158
+ except XenfraAPIError as e:
159
+ console.print(f"[bold red]API Error: {e.detail}[/bold red]")
160
+ except XenfraError as e:
161
+ console.print(f"[bold red]Error: {e}[/bold red]")
162
+ except click.Abort:
163
+ pass