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
//! Repository selection step for the deployment wizard
//!
//! Detects the repository from local git remote or asks user to select.

use crate::platform::api::PlatformApiClient;
use crate::platform::api::types::{AvailableRepository, ProjectRepository};
use crate::wizard::render::{display_step_header, wizard_render_config};
use colored::Colorize;
use inquire::{Confirm, InquireError, Select};
use std::fmt;
use std::path::Path;
use std::process::Command;

/// Result of repository selection step
#[derive(Debug, Clone)]
pub enum RepositorySelectionResult {
    /// User selected a repository (already connected)
    Selected(ProjectRepository),
    /// User chose to connect a new repository
    ConnectNew(AvailableRepository),
    /// Need GitHub App installation for this org
    NeedsGitHubApp {
        installation_url: String,
        org_name: String,
    },
    /// No GitHub App installations found
    NoInstallations { installation_url: String },
    /// No repositories connected to project
    NoRepositories,
    /// User cancelled the wizard
    Cancelled,
    /// An error occurred
    Error(String),
}

/// Wrapper for displaying repository options in the selection menu
struct RepositoryOption {
    repository: ProjectRepository,
    is_detected: bool,
}

impl fmt::Display for RepositoryOption {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let marker = if self.is_detected { " (detected)" } else { "" };
        write!(
            f,
            "{}{}  {}",
            self.repository.repository_full_name.cyan(),
            marker.green(),
            self.repository
                .default_branch
                .as_deref()
                .unwrap_or("main")
                .dimmed()
        )
    }
}

/// Detect the git remote URL from the current directory
fn detect_git_remote(project_path: &Path) -> Option<String> {
    let output = Command::new("git")
        .args(["remote", "get-url", "origin"])
        .current_dir(project_path)
        .output()
        .ok()?;

    if output.status.success() {
        let url = String::from_utf8(output.stdout).ok()?;
        Some(url.trim().to_string())
    } else {
        None
    }
}

/// Parse repository full name from git remote URL
/// Handles both SSH (git@github.com:owner/repo.git) and HTTPS (https://github.com/owner/repo.git)
fn parse_repo_from_url(url: &str) -> Option<String> {
    let url = url.trim();

    // SSH format: git@github.com:owner/repo.git
    if url.starts_with("git@") {
        let parts: Vec<&str> = url.split(':').collect();
        if parts.len() == 2 {
            let path = parts[1].trim_end_matches(".git");
            return Some(path.to_string());
        }
    }

    // HTTPS format: https://github.com/owner/repo.git
    if url.starts_with("https://") || url.starts_with("http://") {
        if let Some(path) = url
            .split('/')
            .skip(3)
            .collect::<Vec<_>>()
            .join("/")
            .strip_suffix(".git")
        {
            return Some(path.to_string());
        }
        // Without .git suffix
        let path: String = url.split('/').skip(3).collect::<Vec<_>>().join("/");
        if !path.is_empty() {
            return Some(path);
        }
    }

    None
}

/// Find a repository in the available repositories list by full name
fn find_in_available<'a>(
    repo_full_name: &str,
    available: &'a [AvailableRepository],
) -> Option<&'a AvailableRepository> {
    available
        .iter()
        .find(|r| r.full_name.eq_ignore_ascii_case(repo_full_name))
}

/// Check if a repository ID is in the connected list
fn is_repo_connected(repo_id: i64, connected_ids: &[i64]) -> bool {
    connected_ids.contains(&repo_id)
}

/// Extract organization/owner name from a repo full name
fn extract_org_name(repo_full_name: &str) -> String {
    repo_full_name
        .split('/')
        .next()
        .unwrap_or(repo_full_name)
        .to_string()
}

/// Prompt user to connect a detected repository
fn prompt_connect_repository(
    available: &AvailableRepository,
    connected: &[ProjectRepository],
) -> RepositorySelectionResult {
    println!(
        "\n{} Detected repository: {}",
        "→".cyan(),
        available.full_name.cyan()
    );
    println!(
        "{}",
        "This repository is not connected to the project.".dimmed()
    );

    // Build options
    let connect_option = format!("Connect {} (detected)", available.full_name);
    let mut options = vec![connect_option];

    // Add connected repos as alternatives
    for repo in connected {
        options.push(format!(
            "Use {} (already connected)",
            repo.repository_full_name
        ));
    }

    let selection = Select::new("What would you like to do?", options)
        .with_render_config(wizard_render_config())
        .with_help_message("Use ↑/↓ to navigate, Enter to select")
        .prompt();

    match selection {
        Ok(choice) if choice.starts_with("Connect") => {
            RepositorySelectionResult::ConnectNew(available.clone())
        }
        Ok(choice) => {
            // Find which connected repo was selected
            let repo_name = choice
                .split(" (already connected)")
                .next()
                .unwrap_or("")
                .trim()
                .trim_start_matches("Use ");
            if let Some(repo) = connected
                .iter()
                .find(|r| r.repository_full_name == repo_name)
            {
                RepositorySelectionResult::Selected(repo.clone())
            } else {
                RepositorySelectionResult::Cancelled
            }
        }
        Err(InquireError::OperationCanceled) | Err(InquireError::OperationInterrupted) => {
            RepositorySelectionResult::Cancelled
        }
        Err(_) => RepositorySelectionResult::Cancelled,
    }
}

/// Prompt user to install GitHub App
async fn prompt_github_app_install(
    client: &PlatformApiClient,
    org_name: &str,
) -> RepositorySelectionResult {
    println!(
        "\n{} GitHub App not installed for: {}",
        "âš ".yellow(),
        org_name.cyan()
    );
    println!(
        "{}",
        "The Syncable GitHub App needs to be installed to connect this repository.".dimmed()
    );

    match client.get_github_installation_url().await {
        Ok(response) => {
            let install = Confirm::new("Open browser to install GitHub App?")
                .with_default(true)
                .prompt();

            if let Ok(true) = install {
                if webbrowser::open(&response.installation_url).is_ok() {
                    println!(
                        "{} Opened browser. Complete the installation, then run this command again.",
                        "→".cyan()
                    );
                } else {
                    println!("Visit: {}", response.installation_url);
                }
            }
            RepositorySelectionResult::NeedsGitHubApp {
                installation_url: response.installation_url,
                org_name: org_name.to_string(),
            }
        }
        Err(e) => {
            RepositorySelectionResult::Error(format!("Failed to get installation URL: {}", e))
        }
    }
}

/// Select repository for deployment
///
/// Smart repository selection with connection flow:
/// 1. Check for GitHub App installations
/// 2. Fetch connected and available repositories
/// 3. Detect local git remote and match against repos
/// 4. Offer to connect if local repo available but not connected
/// 5. Fall back to manual selection from available repos
pub async fn select_repository(
    client: &PlatformApiClient,
    project_id: &str,
    project_path: &Path,
) -> RepositorySelectionResult {
    // Check for GitHub App installations first
    let installations = match client.list_github_installations().await {
        Ok(response) => response.installations,
        Err(e) => {
            return RepositorySelectionResult::Error(format!(
                "Failed to fetch GitHub installations: {}",
                e
            ));
        }
    };

    // If no installations, prompt to install GitHub App
    if installations.is_empty() {
        println!("\n{} No GitHub App installations found.", "âš ".yellow());
        match client.get_github_installation_url().await {
            Ok(response) => {
                println!("Install the Syncable GitHub App to connect repositories.");
                let install = Confirm::new("Open browser to install GitHub App?")
                    .with_default(true)
                    .prompt();

                if let Ok(true) = install {
                    if webbrowser::open(&response.installation_url).is_ok() {
                        println!(
                            "{} Opened browser. Complete the installation, then run this command again.",
                            "→".cyan()
                        );
                    } else {
                        println!("Visit: {}", response.installation_url);
                    }
                }
                return RepositorySelectionResult::NoInstallations {
                    installation_url: response.installation_url,
                };
            }
            Err(e) => {
                return RepositorySelectionResult::Error(format!(
                    "Failed to get installation URL: {}",
                    e
                ));
            }
        }
    }

    // Fetch connected repositories
    let repos_response = match client.list_project_repositories(project_id).await {
        Ok(response) => response,
        Err(e) => {
            return RepositorySelectionResult::Error(format!(
                "Failed to fetch repositories: {}",
                e
            ));
        }
    };
    let connected_repos = repos_response.repositories;

    // Fetch available repositories (from all GitHub installations)
    let available_response = match client
        .list_available_repositories(Some(project_id), None, None)
        .await
    {
        Ok(response) => response,
        Err(e) => {
            return RepositorySelectionResult::Error(format!(
                "Failed to fetch available repositories: {}",
                e
            ));
        }
    };
    let available_repos = available_response.repositories;
    let connected_ids = available_response.connected_repositories;

    // Try to auto-detect from git remote
    let detected_repo_name =
        detect_git_remote(project_path).and_then(|url| parse_repo_from_url(&url));

    if let Some(ref local_repo_name) = detected_repo_name {
        // Check if already connected to this project
        if let Some(connected) = connected_repos
            .iter()
            .find(|r| r.repository_full_name.eq_ignore_ascii_case(local_repo_name))
        {
            // Auto-select connected repo
            println!(
                "\n{} Using detected repository: {}",
                "✓".green(),
                connected.repository_full_name.cyan()
            );
            return RepositorySelectionResult::Selected(connected.clone());
        }

        // Check if available but not connected
        if let Some(available) = find_in_available(local_repo_name, &available_repos) {
            if !is_repo_connected(available.id, &connected_ids) {
                // Offer to connect this repository
                return prompt_connect_repository(available, &connected_repos);
            }
        }

        // Local repo not in available list - might need GitHub App for this org
        let org_name = extract_org_name(local_repo_name);
        let org_has_installation = installations
            .iter()
            .any(|i| i.account_login.eq_ignore_ascii_case(&org_name));

        if !org_has_installation {
            // Need to install GitHub App for this organization
            return prompt_github_app_install(client, &org_name).await;
        }

        // Org has installation but repo not available - might be private or restricted
        println!(
            "\n{} Repository {} not accessible.",
            "âš ".yellow(),
            local_repo_name.cyan()
        );
        println!(
            "{}",
            "Check that the Syncable GitHub App has access to this repository.".dimmed()
        );
    }

    // No local repo detected or couldn't match - show selection UI
    if connected_repos.is_empty() && available_repos.is_empty() {
        println!("\n{} No repositories available.", "âš ".yellow());
        println!(
            "{}",
            "Connect a repository using the GitHub App installation.".dimmed()
        );
        return RepositorySelectionResult::NoRepositories;
    }

    display_step_header(
        0,
        "Select Repository",
        "Choose which repository to deploy from.",
    );

    // Build options: connected repos first, then available (unconnected) repos
    let mut options: Vec<RepositoryOption> = connected_repos
        .iter()
        .map(|repo| {
            let is_detected = detected_repo_name
                .as_ref()
                .map(|name| repo.repository_full_name.eq_ignore_ascii_case(name))
                .unwrap_or(false);
            RepositoryOption {
                repository: repo.clone(),
                is_detected,
            }
        })
        .collect();

    // Put detected repo first if found
    options.sort_by(|a, b| b.is_detected.cmp(&a.is_detected));

    if options.is_empty() {
        // No connected repos - offer available repos to connect
        println!(
            "{}",
            "No repositories connected yet. Select one to connect:".dimmed()
        );

        let available_options: Vec<String> = available_repos
            .iter()
            .filter(|r| !is_repo_connected(r.id, &connected_ids))
            .map(|r| r.full_name.clone())
            .collect();

        if available_options.is_empty() {
            return RepositorySelectionResult::NoRepositories;
        }

        let selection = Select::new("Select repository to connect:", available_options)
            .with_render_config(wizard_render_config())
            .with_help_message("Use ↑/↓ to navigate, Enter to select")
            .prompt();

        match selection {
            Ok(selected_name) => {
                if let Some(available) = available_repos
                    .iter()
                    .find(|r| r.full_name == selected_name)
                {
                    return RepositorySelectionResult::ConnectNew(available.clone());
                }
                RepositorySelectionResult::Cancelled
            }
            Err(InquireError::OperationCanceled) | Err(InquireError::OperationInterrupted) => {
                RepositorySelectionResult::Cancelled
            }
            Err(_) => RepositorySelectionResult::Cancelled,
        }
    } else {
        // Show connected repos for selection
        let selection = Select::new("Select repository:", options)
            .with_render_config(wizard_render_config())
            .with_help_message("Use ↑/↓ to navigate, Enter to select")
            .prompt();

        match selection {
            Ok(selected) => {
                println!(
                    "\n{} Selected repository: {}",
                    "✓".green(),
                    selected.repository.repository_full_name.cyan()
                );
                RepositorySelectionResult::Selected(selected.repository)
            }
            Err(InquireError::OperationCanceled) | Err(InquireError::OperationInterrupted) => {
                RepositorySelectionResult::Cancelled
            }
            Err(_) => RepositorySelectionResult::Cancelled,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_repo_from_ssh_url() {
        let url = "git@github.com:owner/my-repo.git";
        assert_eq!(parse_repo_from_url(url), Some("owner/my-repo".to_string()));
    }

    #[test]
    fn test_parse_repo_from_https_url() {
        let url = "https://github.com/owner/my-repo.git";
        assert_eq!(parse_repo_from_url(url), Some("owner/my-repo".to_string()));
    }

    #[test]
    fn test_parse_repo_from_https_url_no_git() {
        let url = "https://github.com/owner/my-repo";
        assert_eq!(parse_repo_from_url(url), Some("owner/my-repo".to_string()));
    }

    #[test]
    fn test_repository_selection_result_variants() {
        let repo = ProjectRepository {
            id: "test".to_string(),
            project_id: "proj".to_string(),
            repository_id: 123,
            repository_name: "test".to_string(),
            repository_full_name: "owner/test".to_string(),
            repository_owner: "owner".to_string(),
            repository_private: false,
            default_branch: Some("main".to_string()),
            is_active: true,
            connection_type: None,
            repository_type: None,
            is_primary_git_ops: None,
            github_installation_id: None,
            user_id: None,
            created_at: None,
            updated_at: None,
        };
        let available = AvailableRepository {
            id: 456,
            name: "test-repo".to_string(),
            full_name: "owner/test-repo".to_string(),
            owner: Some("owner".to_string()),
            private: false,
            default_branch: Some("main".to_string()),
            description: None,
            html_url: None,
            installation_id: Some(789),
        };
        let _ = RepositorySelectionResult::Selected(repo);
        let _ = RepositorySelectionResult::ConnectNew(available);
        let _ = RepositorySelectionResult::NeedsGitHubApp {
            installation_url: "https://github.com/apps/syncable".to_string(),
            org_name: "my-org".to_string(),
        };
        let _ = RepositorySelectionResult::NoInstallations {
            installation_url: "https://github.com/apps/syncable".to_string(),
        };
        let _ = RepositorySelectionResult::NoRepositories;
        let _ = RepositorySelectionResult::Cancelled;
        let _ = RepositorySelectionResult::Error("test".to_string());
    }

    #[test]
    fn test_extract_org_name() {
        assert_eq!(extract_org_name("owner/repo"), "owner");
        assert_eq!(extract_org_name("my-org/my-app"), "my-org");
        assert_eq!(extract_org_name("repo-only"), "repo-only");
    }

    #[test]
    fn test_is_repo_connected() {
        let connected = vec![1, 2, 3, 5];
        assert!(is_repo_connected(1, &connected));
        assert!(is_repo_connected(3, &connected));
        assert!(!is_repo_connected(4, &connected));
        assert!(!is_repo_connected(100, &connected));
    }

    #[test]
    fn test_find_in_available() {
        let available = vec![
            AvailableRepository {
                id: 1,
                name: "repo-a".to_string(),
                full_name: "owner/repo-a".to_string(),
                owner: Some("owner".to_string()),
                private: false,
                default_branch: Some("main".to_string()),
                description: None,
                html_url: None,
                installation_id: Some(100),
            },
            AvailableRepository {
                id: 2,
                name: "repo-b".to_string(),
                full_name: "other/repo-b".to_string(),
                owner: Some("other".to_string()),
                private: true,
                default_branch: Some("main".to_string()),
                description: None,
                html_url: None,
                installation_id: Some(200),
            },
        ];

        let found = find_in_available("owner/repo-a", &available);
        assert!(found.is_some());
        assert_eq!(found.unwrap().id, 1);

        // Case insensitive
        let found_case = find_in_available("OWNER/REPO-A", &available);
        assert!(found_case.is_some());

        let not_found = find_in_available("nonexistent/repo", &available);
        assert!(not_found.is_none());
    }
}