vibe-workspace 0.0.12

Extremely lightweight CLI for managing multiple git repositories and workspace 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
use anyhow::Result;
use colored::*;
use console::style;
use inquire::{Confirm, Select};
use std::path::PathBuf;

use crate::git::bulk_clone::{BulkCloneCommand, BulkCloneOptions};
use crate::git::provider::github_cli::GitHubCliProvider;
use crate::git::{GitConfig, Repository};
use crate::workspace::install::RepositoryInstaller;
use crate::workspace::manager::WorkspaceManager;

pub struct CloneCommand;

impl CloneCommand {
    pub async fn execute(
        url: String,
        path: Option<PathBuf>,
        open: bool,
        install: bool,
        workspace_manager: &mut WorkspaceManager,
        git_config: &GitConfig,
    ) -> Result<PathBuf> {
        // Get workspace root from manager
        let workspace_root = workspace_manager.config().workspace.root.clone();

        // Create installer
        let installer = RepositoryInstaller::new(workspace_root, git_config.clone());

        // Clone repository
        let installed = installer
            .install_from_url_with_options(&url, path, open, install)
            .await?;

        // Add to workspace configuration
        workspace_manager
            .add_repository(installed.repository.clone())
            .await?;

        // Execute post-install actions
        if !installed.post_install_actions.is_empty() {
            installer
                .execute_post_install_actions(&installed.post_install_actions, &installed.path)
                .await?;
        }

        println!(
            "\n{} Repository successfully added to workspace!",
            "🎉".green()
        );

        println!("Path: {}", installed.path.display().to_string().cyan());

        Ok(installed.path)
    }

    /// Execute clone with interactive post-clone workflow
    pub async fn execute_interactive(
        url: String,
        path: Option<PathBuf>,
        workspace_manager: &mut WorkspaceManager,
        git_config: &GitConfig,
    ) -> Result<PathBuf> {
        // Clone the repository first
        let cloned_path = Self::execute(
            url.clone(),
            path,
            false,
            false,
            workspace_manager,
            git_config,
        )
        .await?;

        // Extract repository name from path
        let repo_name = cloned_path
            .file_name()
            .and_then(|n| n.to_str())
            .ok_or_else(|| anyhow::anyhow!("Could not determine repository name"))?;

        // Run interactive post-clone workflow
        Self::interactive_post_clone_workflow(repo_name, workspace_manager).await?;

        Ok(cloned_path)
    }

    pub async fn clone_from_search_result(
        repo: Repository,
        workspace_manager: &mut WorkspaceManager,
        git_config: &GitConfig,
    ) -> Result<()> {
        println!(
            "\n{} Selected: {}",
            "✅".green(),
            repo.full_name.cyan().bold()
        );

        // Use HTTPS URL by default (more universal than SSH)
        let _cloned_path =
            Self::execute(repo.url, None, false, false, workspace_manager, git_config).await?;

        // Run interactive post-clone workflow
        Self::interactive_post_clone_workflow(&repo.name, workspace_manager).await?;

        Ok(())
    }

    /// Interactive workflow after cloning a repository
    pub async fn interactive_post_clone_workflow(
        repo_name: &str,
        workspace_manager: &mut WorkspaceManager,
    ) -> Result<()> {
        println!("\n{} Repository cloned successfully!", style("🎉").green());

        // Step 1: Ask if they want to configure apps
        let configure_apps = Confirm::new(&format!(
            "Would you like to configure apps for '{}'?",
            style(repo_name).cyan().bold()
        ))
        .with_default(true)
        .with_help_message(
            "Configure which applications can open this repository (VS Code, Warp, etc.)",
        )
        .prompt()?;

        if configure_apps {
            Self::configure_repository_apps(repo_name, workspace_manager).await?;
        }

        // Step 2: Ask if they want to open it now
        let open_now = Confirm::new(&format!(
            "Would you like to open '{}' now?",
            style(repo_name).cyan().bold()
        ))
        .with_default(true)
        .with_help_message("Open the repository with your configured app")
        .prompt()?;

        if open_now {
            Self::open_repository_interactive(repo_name, workspace_manager).await?;
        }

        Ok(())
    }

    /// Configure apps for a repository interactively
    async fn configure_repository_apps(
        repo_name: &str,
        workspace_manager: &mut WorkspaceManager,
    ) -> Result<()> {
        // Get available app choices (hardcoded for now, could be made configurable)
        let available_apps = [
            ("vscode", "Visual Studio Code - Code editor"),
            ("warp", "Warp - Modern terminal"),
            ("iterm2", "iTerm2 - Terminal emulator"),
        ];

        println!(
            "\n{} Select an application to configure for this repository:",
            style("📱").green()
        );

        let app_choices: Vec<String> = available_apps
            .iter()
            .map(|(name, desc)| format!("{name} - {desc}"))
            .collect();

        let selected_display = Select::new("Choose an application:", app_choices)
            .with_help_message("Select an application to configure for this repository")
            .prompt()?;

        // Extract app name from the display string
        let app_name = selected_display
            .split(" - ")
            .next()
            .unwrap_or(&selected_display);

        // Configure the app for this repository using the existing method
        workspace_manager
            .configure_app_for_repo(repo_name, app_name, "default")
            .await?;

        println!(
            "{} Configured {} for {}",
            style("✅").green(),
            style(app_name).blue(),
            style(repo_name).cyan()
        );

        Ok(())
    }

    /// Open repository interactively with app selection
    async fn open_repository_interactive(
        repo_name: &str,
        workspace_manager: &mut WorkspaceManager,
    ) -> Result<()> {
        // Get the repository configuration
        if let Some(repo_info) = workspace_manager.get_repository(repo_name) {
            if repo_info.apps.is_empty() {
                println!(
                    "{} No apps configured for this repository",
                    style("âš ī¸").yellow()
                );
                println!("   Configure apps first using the configuration workflow");
                return Ok(());
            }

            // If only one app is configured, use it directly
            let app_to_use = if repo_info.apps.len() == 1 {
                repo_info.apps.keys().next().unwrap().clone()
            } else {
                // Multiple apps, let user choose
                let app_choices: Vec<String> = repo_info.apps.keys().cloned().collect();
                Select::new("Choose an app to open with:", app_choices)
                    .with_help_message("Select which application to use")
                    .prompt()?
            };

            // Open the repository
            workspace_manager
                .open_repo_with_app(repo_name, &app_to_use)
                .await?;

            println!(
                "{} Opened {} with {}",
                style("🚀").green(),
                style(repo_name).cyan().bold(),
                style(&app_to_use).blue()
            );
        } else {
            println!(
                "{} Repository '{}' not found in workspace",
                style("❌").red(),
                repo_name
            );
        }

        Ok(())
    }
}

/// Enhanced clone command with bulk detection capabilities
pub struct EnhancedCloneCommand;

impl EnhancedCloneCommand {
    /// Execute clone with automatic detection of user/org patterns
    pub async fn execute_with_detection(
        url_or_target: String,
        app: Option<String>,
        no_configure: bool,
        no_open: bool,
        workspace_manager: &mut WorkspaceManager,
        git_config: &GitConfig,
    ) -> Result<()> {
        let contains_slash = url_or_target.contains('/');
        let is_url = url_or_target.starts_with("http") || url_or_target.starts_with("git@");

        // Route based on input pattern
        match (contains_slash, is_url) {
            // Traditional repository URL or owner/repo format
            (true, _) | (false, true) => {
                Self::single_repository_workflow(
                    url_or_target,
                    app,
                    no_configure,
                    no_open,
                    workspace_manager,
                    git_config,
                )
                .await
            }

            // Potential user/org name - check if it exists
            (false, false) => {
                Self::detect_and_route(
                    url_or_target,
                    app,
                    no_configure,
                    no_open,
                    workspace_manager,
                    git_config,
                )
                .await
            }
        }
    }

    /// Detect if target is user/org and route accordingly
    async fn detect_and_route(
        target: String,
        app: Option<String>,
        no_configure: bool,
        no_open: bool,
        workspace_manager: &mut WorkspaceManager,
        git_config: &GitConfig,
    ) -> Result<()> {
        println!("🔍 Analyzing '{}'...", style(&target).cyan());

        // Initialize GitHub CLI provider
        let github_cli = match GitHubCliProvider::new() {
            Ok(cli) => cli,
            Err(_) => {
                println!(
                    "{} GitHub CLI not available, searching repositories...",
                    style("âš ī¸").yellow()
                );
                return Self::fallback_to_search(target, workspace_manager, git_config).await;
            }
        };

        // Check if target exists as user or organization
        match github_cli.user_or_org_exists(&target).await {
            Ok(true) => {
                // Get repository count
                match github_cli.count_repositories(&target).await {
                    Ok(0) => {
                        println!(
                            "{} '{}' has no public repositories.",
                            style("â„šī¸").blue(),
                            style(&target).cyan()
                        );
                        Self::fallback_to_search(target, workspace_manager, git_config).await
                    }
                    Ok(count) => {
                        Self::interactive_clone_selection(
                            target,
                            count,
                            app,
                            no_configure,
                            no_open,
                            workspace_manager,
                            git_config,
                        )
                        .await
                    }
                    Err(_) => {
                        println!(
                            "{} Failed to count repositories for '{}', searching instead...",
                            style("âš ī¸").yellow(),
                            style(&target).cyan()
                        );
                        Self::fallback_to_search(target, workspace_manager, git_config).await
                    }
                }
            }
            Ok(false) => {
                println!(
                    "🔍 '{}' not found as a GitHub user or organization.",
                    &target
                );
                println!("🔍 Searching repositories for '{}'...", &target);
                Self::fallback_to_search(target, workspace_manager, git_config).await
            }
            Err(_) => {
                println!(
                    "{} Failed to check GitHub, searching repositories instead...",
                    style("âš ī¸").yellow()
                );
                Self::fallback_to_search(target, workspace_manager, git_config).await
            }
        }
    }

    /// Show interactive options for user/org with repositories
    async fn interactive_clone_selection(
        target: String,
        repo_count: usize,
        _app: Option<String>,
        _no_configure: bool,
        _no_open: bool,
        workspace_manager: &mut WorkspaceManager,
        git_config: &GitConfig,
    ) -> Result<()> {
        println!(
            "✅ Found GitHub target '{}' with {} repositories",
            style(&target).cyan().bold(),
            style(repo_count).green().bold()
        );

        let options = vec![
            format!("Clone all {} repositories", repo_count),
            "Search for specific repository".to_string(),
            "Cancel".to_string(),
        ];

        let selection = Select::new("What would you like to do?", options)
            .with_help_message("Choose how to proceed with this GitHub target")
            .prompt()?;

        match selection.as_str() {
            s if s.starts_with("Clone all") => {
                Self::bulk_clone_workflow(target, workspace_manager, git_config).await
            }
            "Search for specific repository" => {
                Self::fallback_to_search(target, workspace_manager, git_config).await
            }
            _ => {
                println!("{} Operation cancelled", style("â„šī¸").blue());
                Ok(())
            }
        }
    }

    /// Execute bulk cloning workflow
    async fn bulk_clone_workflow(
        target: String,
        workspace_manager: &mut WorkspaceManager,
        git_config: &GitConfig,
    ) -> Result<()> {
        let options = BulkCloneOptions {
            exclude_patterns: Vec::new(),
            include_patterns: Vec::new(),
            skip_existing: true,
            custom_path: None,
            force: false, // Always show confirmation in interactive mode
        };

        match BulkCloneCommand::execute(target, options, workspace_manager, git_config).await {
            Ok(result) => {
                println!(
                    "{} Bulk clone completed: {} successful, {} failed",
                    style("✅").green().bold(),
                    result.total_cloned,
                    result.failed.len()
                );
                Ok(())
            }
            Err(e) => {
                println!("{} Bulk clone failed: {}", style("❌").red(), e);
                Err(e)
            }
        }
    }

    /// Fallback to repository search when user/org detection fails
    async fn fallback_to_search(
        target: String,
        workspace_manager: &mut WorkspaceManager,
        git_config: &GitConfig,
    ) -> Result<()> {
        use crate::git::SearchCommand;

        // Use the existing search functionality
        SearchCommand::execute_with_query(&target, workspace_manager, git_config).await
    }

    /// Execute single repository clone workflow
    async fn single_repository_workflow(
        url: String,
        app: Option<String>,
        no_configure: bool,
        no_open: bool,
        workspace_manager: &mut WorkspaceManager,
        git_config: &GitConfig,
    ) -> Result<()> {
        use crate::ui::workflows::{execute_workflow, CloneWorkflow};

        // Use existing workflow system if not skipping steps
        if !no_configure || !no_open {
            let workflow = Box::new(CloneWorkflow {
                url: url.clone(),
                app: app.clone(),
            });

            execute_workflow(workflow, workspace_manager).await?;
        } else {
            // Just clone without workflow
            let _cloned_path =
                CloneCommand::execute(url, None, false, false, workspace_manager, git_config)
                    .await?;
        }

        Ok(())
    }
}