syncable-cli 0.37.1

A Rust-based CLI that analyzes code repositories and generates Infrastructure as Code configurations
Documentation
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
//! Wizard orchestration - ties all steps together

use crate::analyzer::discover_dockerfiles_for_deployment;
use crate::platform::api::PlatformApiClient;
use crate::platform::api::types::{
    CloudProvider, CloudRunnerConfigInput, ConnectRepositoryRequest, CreateDeploymentConfigRequest,
    DeploymentTarget, ProjectRepository, TriggerDeploymentRequest, WizardDeploymentConfig,
    build_cloud_runner_config_v2,
};
use crate::wizard::{
    ClusterSelectionResult, ConfigFormResult, DockerfileSelectionResult,
    InfrastructureSelectionResult, ProviderSelectionResult, RegistryProvisioningResult,
    RegistrySelectionResult, RepositorySelectionResult, TargetSelectionResult, collect_config,
    collect_env_vars, collect_service_endpoint_env_vars, filter_endpoints_for_provider,
    get_available_endpoints, get_provider_deployment_statuses, provision_registry, select_cluster,
    select_dockerfile, select_infrastructure, select_provider, select_registry, select_repository,
    select_target,
};
use colored::Colorize;
use inquire::{Confirm, InquireError};
use std::path::Path;

/// Deployment result with task ID for tracking
#[derive(Debug, Clone)]
pub struct DeploymentInfo {
    /// The deployment config ID
    pub config_id: String,
    /// Backstage task ID for tracking progress
    pub task_id: String,
    /// Service name that was deployed
    pub service_name: String,
}

/// Result of running the wizard
#[derive(Debug)]
pub enum WizardResult {
    /// Wizard completed and deployment triggered
    Deployed(DeploymentInfo),
    /// Wizard completed successfully (config created but not deployed)
    Success(WizardDeploymentConfig),
    /// User wants to start agent to create Dockerfile
    StartAgent(String),
    /// User cancelled the wizard
    Cancelled,
    /// An error occurred
    Error(String),
}

/// Run the deployment wizard
pub async fn run_wizard(
    client: &PlatformApiClient,
    project_id: &str,
    environment_id: &str,
    project_path: &Path,
) -> WizardResult {
    println!();
    println!(
        "{}",
        "═══════════════════════════════════════════════════════════════".bright_cyan()
    );
    println!(
        "{}",
        "                    Deployment Wizard                          "
            .bright_cyan()
            .bold()
    );
    println!(
        "{}",
        "═══════════════════════════════════════════════════════════════".bright_cyan()
    );

    // Step 0: Repository selection (auto-detect or ask)
    let repository = match select_repository(client, project_id, project_path).await {
        RepositorySelectionResult::Selected(repo) => repo,
        RepositorySelectionResult::ConnectNew(available) => {
            // Connect the repository first
            println!("{} Connecting repository...", "".cyan());

            // Extract owner from full_name if not provided
            let owner = available.owner.clone().unwrap_or_else(|| {
                available
                    .full_name
                    .split('/')
                    .next()
                    .unwrap_or("")
                    .to_string()
            });

            let connect_request = ConnectRepositoryRequest {
                project_id: project_id.to_string(),
                repository_id: available.id,
                repository_name: available.name.clone(),
                repository_full_name: available.full_name.clone(),
                repository_owner: owner.clone(),
                repository_private: available.private,
                default_branch: available
                    .default_branch
                    .clone()
                    .or(Some("main".to_string())),
                connection_type: Some("app".to_string()),
                github_installation_id: available.installation_id,
                repository_type: Some("application".to_string()),
            };
            match client.connect_repository(&connect_request).await {
                Ok(response) => {
                    println!("{} Repository connected!", "".green());
                    // Construct ProjectRepository from the response and available info
                    ProjectRepository {
                        id: response.id,
                        project_id: response.project_id,
                        repository_id: response.repository_id,
                        repository_name: available.name,
                        repository_full_name: response.repository_full_name,
                        repository_owner: owner,
                        repository_private: available.private,
                        default_branch: available.default_branch,
                        is_active: response.is_active,
                        connection_type: Some("app".to_string()),
                        repository_type: Some("application".to_string()),
                        is_primary_git_ops: None,
                        github_installation_id: available.installation_id,
                        user_id: None,
                        created_at: None,
                        updated_at: None,
                    }
                }
                Err(e) => {
                    return WizardResult::Error(format!("Failed to connect repository: {}", e));
                }
            }
        }
        RepositorySelectionResult::NeedsGitHubApp {
            installation_url,
            org_name,
        } => {
            println!(
                "\n{} Please install the Syncable GitHub App for organization '{}' first.",
                "".yellow(),
                org_name.cyan()
            );
            println!("Installation URL: {}", installation_url);
            return WizardResult::Cancelled;
        }
        RepositorySelectionResult::NoInstallations { installation_url } => {
            println!(
                "\n{} No GitHub App installations found. Please install the app first.",
                "".yellow()
            );
            println!("Installation URL: {}", installation_url);
            return WizardResult::Cancelled;
        }
        RepositorySelectionResult::NoRepositories => {
            return WizardResult::Error(
                "No repositories available. Please install the Syncable GitHub App first."
                    .to_string(),
            );
        }
        RepositorySelectionResult::Cancelled => return WizardResult::Cancelled,
        RepositorySelectionResult::Error(e) => return WizardResult::Error(e),
    };

    // Step 1: Provider selection
    let provider_statuses = match get_provider_deployment_statuses(client, project_id).await {
        Ok(s) => s,
        Err(e) => {
            return WizardResult::Error(format!("Failed to fetch provider status: {}", e));
        }
    };

    let provider = match select_provider(&provider_statuses) {
        ProviderSelectionResult::Selected(p) => p,
        ProviderSelectionResult::Cancelled => return WizardResult::Cancelled,
    };

    // Get status for selected provider
    let provider_status = provider_statuses
        .iter()
        .find(|s| s.provider == provider)
        .expect("Selected provider must exist in statuses");

    // Step 2: Target selection (with back navigation)
    let target = match select_target(provider_status) {
        TargetSelectionResult::Selected(t) => t,
        TargetSelectionResult::Back => {
            // Restart from provider selection
            return Box::pin(run_wizard(client, project_id, environment_id, project_path)).await;
        }
        TargetSelectionResult::Cancelled => return WizardResult::Cancelled,
    };

    // Step 3: Infrastructure selection for Cloud Runner OR Cluster selection for K8s
    let (cluster_id, region, machine_type, cpu, memory) = if target == DeploymentTarget::CloudRunner
    {
        // Cloud Runner: Select region and machine type
        // Pass client and project_id for dynamic Hetzner availability fetching
        match select_infrastructure(&provider, 3, Some(client), Some(project_id)).await {
            InfrastructureSelectionResult::Selected {
                region,
                machine_type,
                cpu,
                memory,
            } => (None, Some(region), Some(machine_type), cpu, memory),
            InfrastructureSelectionResult::Back => {
                // Go back (restart wizard for simplicity)
                return Box::pin(run_wizard(client, project_id, environment_id, project_path))
                    .await;
            }
            InfrastructureSelectionResult::Cancelled => return WizardResult::Cancelled,
        }
    } else {
        // Kubernetes: Select cluster
        match select_cluster(&provider_status.clusters) {
            ClusterSelectionResult::Selected(c) => (Some(c.id), None, None, None, None),
            ClusterSelectionResult::Back => {
                // Go back to target selection (restart wizard for simplicity)
                return Box::pin(run_wizard(client, project_id, environment_id, project_path))
                    .await;
            }
            ClusterSelectionResult::Cancelled => return WizardResult::Cancelled,
        }
    };

    // Step 4: Registry selection
    let registry_id = loop {
        match select_registry(&provider_status.registries) {
            RegistrySelectionResult::Selected(r) => break Some(r.id),
            RegistrySelectionResult::ProvisionNew => {
                // Get cluster info for provisioning
                let (prov_cluster_id, prov_cluster_name, prov_region) =
                    if let Some(ref cid) = cluster_id {
                        // Use selected cluster
                        let cluster = provider_status
                            .clusters
                            .iter()
                            .find(|c| c.id == *cid)
                            .expect("Selected cluster must exist");
                        (cid.clone(), cluster.name.clone(), cluster.region.clone())
                    } else {
                        // For Cloud Runner, use first available cluster for registry provisioning
                        if let Some(cluster) = provider_status.clusters.first() {
                            (
                                cluster.id.clone(),
                                cluster.name.clone(),
                                cluster.region.clone(),
                            )
                        } else {
                            return WizardResult::Error(
                                "No cluster available for registry provisioning".to_string(),
                            );
                        }
                    };

                // Provision the registry
                match provision_registry(
                    client,
                    project_id,
                    &prov_cluster_id,
                    &prov_cluster_name,
                    provider.clone(),
                    &prov_region,
                    None, // GCP project ID resolved by backend
                )
                .await
                {
                    RegistryProvisioningResult::Success(registry) => {
                        break Some(registry.id);
                    }
                    RegistryProvisioningResult::Cancelled => {
                        return WizardResult::Cancelled;
                    }
                    RegistryProvisioningResult::Error(e) => {
                        eprintln!("{} {}", "Registry provisioning failed:".red(), e);
                        // Allow retry - loop back to selection
                        continue;
                    }
                }
            }
            RegistrySelectionResult::Back => {
                // Go back (restart wizard for simplicity)
                return Box::pin(run_wizard(client, project_id, environment_id, project_path))
                    .await;
            }
            RegistrySelectionResult::Cancelled => return WizardResult::Cancelled,
        }
    };

    // Step 5: Dockerfile selection
    let dockerfiles = discover_dockerfiles_for_deployment(project_path).unwrap_or_default();
    let (selected_dockerfile, build_context) = match select_dockerfile(&dockerfiles, project_path) {
        DockerfileSelectionResult::Selected {
            dockerfile,
            build_context,
        } => (dockerfile, build_context),
        DockerfileSelectionResult::StartAgent(prompt) => {
            return WizardResult::StartAgent(prompt);
        }
        DockerfileSelectionResult::Back => {
            // Go back (restart wizard for simplicity)
            return Box::pin(run_wizard(client, project_id, environment_id, project_path)).await;
        }
        DockerfileSelectionResult::Cancelled => return WizardResult::Cancelled,
    };

    // Construct dockerfile path from build_context and filename
    // This is more robust than strip_prefix which can have path matching edge cases
    // Docker's -f flag expects path relative to repo root (where docker is invoked)
    let dockerfile_name = selected_dockerfile
        .path
        .file_name()
        .map(|n| n.to_string_lossy().to_string())
        .unwrap_or_else(|| "Dockerfile".to_string());

    let dockerfile_path = if build_context == "." || build_context.is_empty() {
        dockerfile_name.clone() // Dockerfile at repo root
    } else {
        format!("{}/{}", build_context, dockerfile_name) // e.g., "services/foo/Dockerfile"
    };

    log::debug!(
        "Dockerfile path: {}, build_context: {}, dockerfile_name: {}",
        dockerfile_path,
        build_context,
        dockerfile_name
    );

    // Step 6: Config form
    let config = match collect_config(
        provider.clone(),
        target.clone(),
        cluster_id.clone(),
        registry_id.clone(),
        environment_id,
        &dockerfile_path,
        &build_context,
        &selected_dockerfile,
        region.clone(),
        machine_type.clone(),
        cpu.clone(),
        memory.clone(),
        6,
    ) {
        ConfigFormResult::Completed(config) => config,
        ConfigFormResult::Back => {
            // Restart wizard
            return Box::pin(run_wizard(client, project_id, environment_id, project_path)).await;
        }
        ConfigFormResult::Cancelled => return WizardResult::Cancelled,
    };

    // Step 6.5: Environment variables (optional)
    let secrets = collect_env_vars(project_path);
    let mut config = config;
    config.secrets = secrets;

    // Step 6.6: Offer deployed service endpoints as env vars
    let available_endpoints = match client.list_deployments(project_id, Some(50)).await {
        Ok(paginated) => {
            log::debug!(
                "Fetched {} deployment record(s) for endpoint discovery",
                paginated.data.len()
            );
            get_available_endpoints(&paginated.data)
        }
        Err(e) => {
            log::debug!("Could not fetch deployments for endpoint injection: {}", e);
            Vec::new()
        }
    };

    // Exclude the service being deployed
    let service_being_deployed = config.service_name.as_deref().unwrap_or("");
    let available_endpoints: Vec<_> = available_endpoints
        .into_iter()
        .filter(|ep| ep.service_name != service_being_deployed)
        .collect();
    // Only show private endpoints from the same cloud provider
    let available_endpoints = filter_endpoints_for_provider(available_endpoints, provider.as_str());

    if !available_endpoints.is_empty() {
        let endpoint_vars = collect_service_endpoint_env_vars(&available_endpoints);
        for ep_var in endpoint_vars {
            // Don't override vars already set by .env or manual entry
            if !config.secrets.iter().any(|s| s.key == ep_var.key) {
                config.secrets.push(ep_var);
            }
        }
    }

    // Show summary
    display_summary(&config);

    // Step 7: Confirm and deploy
    println!();
    let should_deploy = match Confirm::new("Deploy now?")
        .with_default(true)
        .with_help_message("This will create the deployment configuration and start the deployment")
        .prompt()
    {
        Ok(v) => v,
        Err(InquireError::OperationCanceled) | Err(InquireError::OperationInterrupted) => {
            return WizardResult::Cancelled;
        }
        Err(_) => return WizardResult::Cancelled,
    };

    if !should_deploy {
        println!("{}", "Deployment skipped. Configuration saved.".dimmed());
        return WizardResult::Success(config);
    }

    // Create deployment configuration
    println!();
    println!("{}", "Creating deployment configuration...".dimmed());

    let deploy_request = CreateDeploymentConfigRequest {
        project_id: project_id.to_string(),
        service_name: config.service_name.clone().unwrap_or_default(),
        repository_id: repository.repository_id,
        repository_full_name: repository.repository_full_name.clone(),
        // Send both field name variants for backend compatibility
        dockerfile_path: config.dockerfile_path.clone(),
        dockerfile: config.dockerfile_path.clone(), // Alias
        build_context: config.build_context.clone(),
        context: config.build_context.clone(), // Alias
        port: config.port.unwrap_or(8080) as i32,
        branch: config.branch.clone().unwrap_or_else(|| "main".to_string()),
        target_type: target.as_str().to_string(),
        cloud_provider: provider.as_str().to_string(),
        environment_id: environment_id.to_string(),
        cluster_id: cluster_id.clone(),
        registry_id: registry_id.clone(),
        auto_deploy_enabled: config.auto_deploy,
        is_public: Some(config.is_public),
        secrets: if config.secrets.is_empty() {
            None
        } else {
            Some(config.secrets.clone())
        },
        cloud_runner_config: if target == DeploymentTarget::CloudRunner {
            // Fetch provider credential for GCP project ID / Azure subscription ID
            let (gcp_project_id, subscription_id) = match provider {
                CloudProvider::Gcp | CloudProvider::Azure => {
                    match client
                        .check_provider_connection(&provider, project_id)
                        .await
                    {
                        Ok(Some(cred)) => match provider {
                            CloudProvider::Gcp => (cred.provider_account_id, None),
                            CloudProvider::Azure => (None, cred.provider_account_id),
                            _ => (None, None),
                        },
                        _ => (None, None),
                    }
                }
                _ => (None, None),
            };

            let config_input = CloudRunnerConfigInput {
                provider: Some(provider.clone()),
                region: region.clone(),
                server_type: if provider == CloudProvider::Hetzner {
                    machine_type.clone()
                } else {
                    None
                },
                gcp_project_id,
                cpu: config.cpu.clone(),
                memory: config.memory.clone(),
                allow_unauthenticated: Some(config.is_public),
                subscription_id,
                is_public: Some(config.is_public),
                health_check_path: config.health_check_path.clone(),
                ..Default::default()
            };
            Some(build_cloud_runner_config_v2(&config_input))
        } else {
            None
        },
    };

    // Debug output - show key fields being sent
    log::debug!("CreateDeploymentConfigRequest fields:");
    log::debug!("  projectId: {}", deploy_request.project_id);
    log::debug!("  serviceName: {}", deploy_request.service_name);
    log::debug!("  environmentId: {}", deploy_request.environment_id);
    log::debug!("  repositoryId: {}", deploy_request.repository_id);
    log::debug!(
        "  repositoryFullName: {}",
        deploy_request.repository_full_name
    );
    log::debug!("  dockerfilePath: {:?}", deploy_request.dockerfile_path);
    log::debug!("  buildContext: {:?}", deploy_request.build_context);
    log::debug!("  targetType: {}", deploy_request.target_type);
    log::debug!("  cloudProvider: {}", deploy_request.cloud_provider);
    log::debug!("  port: {}", deploy_request.port);
    log::debug!("  branch: {}", deploy_request.branch);
    if let Some(ref config) = deploy_request.cloud_runner_config {
        log::debug!("  cloudRunnerConfig: {}", config);
    }

    let deployment_config = match client.create_deployment_config(&deploy_request).await {
        Ok(config) => config,
        Err(e) => {
            return WizardResult::Error(format!("Failed to create deployment config: {}", e));
        }
    };

    println!(
        "{} Deployment configuration created: {}",
        "".green(),
        deployment_config.id.dimmed()
    );
    log::debug!("  Config ID: {}", deployment_config.id);
    log::debug!("  Service Name: {}", deployment_config.service_name);
    log::debug!("  Environment ID: {}", deployment_config.environment_id);

    // Trigger deployment
    println!("{}", "Triggering deployment...".dimmed());

    let trigger_request = TriggerDeploymentRequest {
        project_id: project_id.to_string(),
        config_id: deployment_config.id.clone(),
        commit_sha: None, // Use latest from branch
    };

    // Debug: Show trigger request
    log::debug!("Trigger request: configId={}", trigger_request.config_id);

    match client.trigger_deployment(&trigger_request).await {
        Ok(response) => {
            log::info!(
                "Deployment triggered successfully: taskId={}, status={}, message={}",
                response.backstage_task_id,
                response.status,
                response.message
            );

            println!();
            println!(
                "{}",
                "═══════════════════════════════════════════════════════════════".bright_green()
            );
            println!("{}  Deployment started!", "".bright_green().bold());
            println!(
                "{}",
                "═══════════════════════════════════════════════════════════════".bright_green()
            );
            println!();
            println!(
                "  Service:  {}",
                config.service_name.as_deref().unwrap_or("").cyan()
            );
            println!("  Task ID:  {}", response.backstage_task_id.dimmed());
            println!("  Status:   {}", response.status.yellow());
            println!();
            println!(
                "{}",
                "Track progress: sync-ctl deploy status <task-id>".dimmed()
            );
            println!();

            WizardResult::Deployed(DeploymentInfo {
                config_id: deployment_config.id,
                task_id: response.backstage_task_id,
                service_name: config.service_name.unwrap_or_default(),
            })
        }
        Err(e) => {
            log::error!("Failed to trigger deployment: {}", e);
            eprintln!(
                "\n{} {} {}\n",
                "".red().bold(),
                "Deployment trigger failed:".red().bold(),
                e
            );
            WizardResult::Error(format!("Failed to trigger deployment: {}", e))
        }
    }
}

/// Display a summary of the deployment configuration
fn display_summary(config: &WizardDeploymentConfig) {
    println!();
    println!(
        "{}",
        "─────────────────────────────────────────────────────────────────".dimmed()
    );
    println!("{}", " Deployment Summary ".bright_green().bold());
    println!(
        "{}",
        "─────────────────────────────────────────────────────────────────".dimmed()
    );

    if let Some(ref name) = config.service_name {
        println!("  Service:      {}", name.cyan());
    }
    if let Some(ref target) = config.target {
        println!("  Target:       {}", target.display_name());
    }
    if let Some(ref provider) = config.provider {
        println!("  Provider:     {:?}", provider);
    }
    if let Some(ref region) = config.region {
        println!("  Region:       {}", region.cyan());
    }
    if let Some(ref cpu) = config.cpu {
        if let Some(ref mem) = config.memory {
            println!("  Resources:    {} vCPU / {}", cpu.cyan(), mem.cyan());
        }
    } else if let Some(ref machine) = config.machine_type {
        println!("  Machine:      {}", machine.cyan());
    }
    if let Some(ref branch) = config.branch {
        println!("  Branch:       {}", branch);
    }
    if let Some(port) = config.port {
        println!("  Port:         {}", port);
    }
    println!(
        "  Public:       {}",
        if config.is_public {
            "Yes".green()
        } else {
            "No".yellow()
        }
    );
    if let Some(ref health) = config.health_check_path {
        println!("  Health check: {}", health.cyan());
    }
    println!(
        "  Auto-deploy:  {}",
        if config.auto_deploy {
            "Yes".green()
        } else {
            "No".yellow()
        }
    );
    if !config.secrets.is_empty() {
        let secret_count = config.secrets.iter().filter(|s| s.is_secret).count();
        let env_count = config.secrets.len() - secret_count;
        println!(
            "  Env vars:     {} env, {} secret",
            env_count.to_string().cyan(),
            secret_count.to_string().yellow()
        );
    }

    println!(
        "{}",
        "─────────────────────────────────────────────────────────────────".dimmed()
    );
    println!();
}