goobits-repos 2.1.0

Fast Git repository management and synchronization tool
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
//! Repository staging command implementation
//!
//! This module handles staging operations across multiple repositories:
//! - Stage files matching patterns
//! - Unstage files matching patterns
//! - Show staging status across repositories
//! - Commit staged changes across repositories

use anyhow::Result;

use crate::core::{
    create_processing_context, init_command, set_terminal_title, set_terminal_title_and_flush,
    NO_REPOS_MESSAGE, GIT_CONCURRENT_CAP,
};
use crate::git::{
    commit_changes, get_staging_status, has_staged_changes, stage_files, unstage_files, Status,
};

const SCANNING_MESSAGE: &str = "🔍 Scanning for git repositories...";
const STAGING_MESSAGE: &str = "staging...";
const UNSTAGING_MESSAGE: &str = "unstaging...";
const STATUS_MESSAGE: &str = "checking status...";
const COMMITTING_MESSAGE: &str = "committing...";

/// Handles the repository stage command
pub async fn handle_stage_command(pattern: String) -> Result<()> {
    // Set terminal title to indicate repos is running
    set_terminal_title("🚀 repos stage");

    let (start_time, repos) = init_command(SCANNING_MESSAGE);

    if repos.is_empty() {
        println!("\r{}", NO_REPOS_MESSAGE);
        // Set terminal title to green checkbox to indicate completion
        set_terminal_title_and_flush("✅ repos stage");
        return Ok(());
    }

    let total_repos = repos.len();
    let repo_word = if total_repos == 1 {
        "repository"
    } else {
        "repositories"
    };
    print!(
        "\r🚀 Staging {} in {} {}                    \n",
        pattern, total_repos, repo_word
    );
    println!();

    // Create processing context
    let context = match create_processing_context(repos, start_time, GIT_CONCURRENT_CAP) {
        Ok(context) => context,
        Err(e) => {
            // If context creation fails, set completion title and return error
            set_terminal_title_and_flush("✅ repos stage");
            return Err(e);
        }
    };

    // Process all repositories concurrently
    process_staging_repositories(context, pattern, true).await;

    // Set terminal title to green checkbox to indicate completion
    set_terminal_title_and_flush("✅ repos stage");

    Ok(())
}

/// Handles the repository unstage command
pub async fn handle_unstage_command(pattern: String) -> Result<()> {
    // Set terminal title to indicate repos is running
    set_terminal_title("🚀 repos unstage");

    let (start_time, repos) = init_command(SCANNING_MESSAGE);

    if repos.is_empty() {
        println!("\r{}", NO_REPOS_MESSAGE);
        // Set terminal title to green checkbox to indicate completion
        set_terminal_title_and_flush("✅ repos unstage");
        return Ok(());
    }

    let total_repos = repos.len();
    let repo_word = if total_repos == 1 {
        "repository"
    } else {
        "repositories"
    };
    print!(
        "\r🚀 Unstaging {} in {} {}                    \n",
        pattern, total_repos, repo_word
    );
    println!();

    // Create processing context
    let context = match create_processing_context(repos, start_time, GIT_CONCURRENT_CAP) {
        Ok(context) => context,
        Err(e) => {
            // If context creation fails, set completion title and return error
            set_terminal_title_and_flush("✅ repos unstage");
            return Err(e);
        }
    };

    // Process all repositories concurrently
    process_staging_repositories(context, pattern, false).await;

    // Set terminal title to green checkbox to indicate completion
    set_terminal_title_and_flush("✅ repos unstage");

    Ok(())
}

/// Handles the repository staging status command
pub async fn handle_staging_status_command() -> Result<()> {
    // Set terminal title to indicate repos is running
    set_terminal_title("🚀 repos status");

    let (start_time, repos) = init_command(SCANNING_MESSAGE);

    if repos.is_empty() {
        println!("\r{}", NO_REPOS_MESSAGE);
        // Set terminal title to green checkbox to indicate completion
        set_terminal_title_and_flush("✅ repos status");
        return Ok(());
    }

    let total_repos = repos.len();
    let repo_word = if total_repos == 1 {
        "repository"
    } else {
        "repositories"
    };
    print!(
        "\r🚀 Checking status of {} {}                    \n",
        total_repos, repo_word
    );
    println!();

    // Create processing context
    let context = match create_processing_context(repos, start_time, GIT_CONCURRENT_CAP) {
        Ok(context) => context,
        Err(e) => {
            // If context creation fails, set completion title and return error
            set_terminal_title_and_flush("✅ repos status");
            return Err(e);
        }
    };

    // Process all repositories concurrently for status
    process_status_repositories(context).await;

    // Set terminal title to green checkbox to indicate completion
    set_terminal_title_and_flush("✅ repos status");

    Ok(())
}

/// Processes all repositories concurrently for staging/unstaging operations
async fn process_staging_repositories(
    context: crate::core::ProcessingContext,
    pattern: String,
    is_staging: bool,
) {
    use crate::core::{acquire_semaphore_permit, acquire_stats_lock, create_progress_bar};
    use futures::stream::{FuturesUnordered, StreamExt};

    let mut futures = FuturesUnordered::new();

    // First, create all repository progress bars
    let mut repo_progress_bars = Vec::new();
    for (repo_name, _) in &context.repositories {
        let progress_bar =
            create_progress_bar(&context.multi_progress, &context.progress_style, repo_name);
        let message = if is_staging {
            STAGING_MESSAGE
        } else {
            UNSTAGING_MESSAGE
        };
        progress_bar.set_message(message);
        repo_progress_bars.push(progress_bar);
    }

    // Add a blank line before the footer
    let _separator_pb = crate::core::create_separator_progress_bar(&context.multi_progress);

    // Create the footer progress bar
    let footer_pb = crate::core::create_footer_progress_bar(&context.multi_progress);

    // Initial footer display
    let initial_stats = crate::core::SyncStatistics::new();
    let initial_summary =
        initial_stats.generate_summary(context.total_repos, context.start_time.elapsed());
    footer_pb.set_message(initial_summary);

    // Add another blank line after the footer
    let _separator_pb2 = crate::core::create_separator_progress_bar(&context.multi_progress);

    // Extract values we need in the async closures before moving context.repositories
    let max_name_length = context.max_name_length;
    let start_time = context.start_time;
    let total_repos = context.total_repos;

    for ((repo_name, repo_path), progress_bar) in
        context.repositories.into_iter().zip(repo_progress_bars)
    {
        let stats_clone = std::sync::Arc::clone(&context.statistics);
        let semaphore_clone = std::sync::Arc::clone(&context.semaphore);
        let footer_clone = footer_pb.clone();
        let pattern_clone = pattern.clone();

        let future = async move {
            let _permit = acquire_semaphore_permit(&semaphore_clone).await;

            let (status, message) = if is_staging {
                perform_staging_operation(&repo_path, &pattern_clone).await
            } else {
                perform_unstaging_operation(&repo_path, &pattern_clone).await
            };

            progress_bar.set_prefix(format!(
                "{} {:width$}",
                status.symbol(),
                repo_name,
                width = max_name_length
            ));
            progress_bar.set_message(format!("{:<12}   {}", status.text(), message));
            progress_bar.finish();

            // Update statistics based on operation result
            let stats_guard = acquire_stats_lock(&stats_clone);
            let repo_path_str = repo_path.to_string_lossy();
            stats_guard.update(
                &repo_name,
                &repo_path_str,
                &status,
                &message,
                false, // staging operations don't track uncommitted changes
            );

            // Update the footer summary after each repository completes
            let duration = start_time.elapsed();
            let summary = stats_guard.generate_summary(total_repos, duration);
            footer_clone.set_message(summary);
        };

        futures.push(future);
    }

    // Wait for all repository operations to complete
    while futures.next().await.is_some() {}

    // Finish the footer progress bar
    footer_pb.finish();

    // Print the final detailed summary if there are any issues to report
    let final_stats = acquire_stats_lock(&context.statistics);
    let detailed_summary = final_stats.generate_detailed_summary(false);
    if !detailed_summary.is_empty() {
        println!("\n{}", "".repeat(70));
        println!("{}", detailed_summary);
        println!("{}", "".repeat(70));
    }

    // Add final spacing
    println!();
}

/// Processes all repositories concurrently for status checking
async fn process_status_repositories(context: crate::core::ProcessingContext) {
    use crate::core::{acquire_semaphore_permit, create_progress_bar};
    use futures::stream::{FuturesUnordered, StreamExt};

    let mut futures = FuturesUnordered::new();

    // First, create all repository progress bars
    let mut repo_progress_bars = Vec::new();
    for (repo_name, _) in &context.repositories {
        let progress_bar =
            create_progress_bar(&context.multi_progress, &context.progress_style, repo_name);
        progress_bar.set_message(STATUS_MESSAGE);
        repo_progress_bars.push(progress_bar);
    }

    // Add a blank line before results
    let _separator_pb = crate::core::create_separator_progress_bar(&context.multi_progress);

    // Extract values we need in the async closures before moving context.repositories
    let max_name_length = context.max_name_length;

    for ((repo_name, repo_path), progress_bar) in
        context.repositories.into_iter().zip(repo_progress_bars)
    {
        let semaphore_clone = std::sync::Arc::clone(&context.semaphore);

        let future = async move {
            let _permit = acquire_semaphore_permit(&semaphore_clone).await;

            let status_result = get_staging_status(&repo_path).await;
            let (status, message) = match status_result {
                Ok((stdout, _)) => {
                    if stdout.trim().is_empty() {
                        (Status::NoChanges, "no changes".to_string())
                    } else {
                        let lines: Vec<&str> = stdout.trim().lines().collect();
                        let staged_count = lines
                            .iter()
                            .filter(|line| {
                                let chars: Vec<char> = line.chars().collect();
                                chars.len() >= 2 && chars[0] != ' ' && chars[0] != '?'
                            })
                            .count();
                        let unstaged_count = lines
                            .iter()
                            .filter(|line| {
                                let chars: Vec<char> = line.chars().collect();
                                chars.len() >= 2 && chars[1] != ' '
                            })
                            .count();
                        let untracked_count =
                            lines.iter().filter(|line| line.starts_with("??")).count();

                        let mut parts = Vec::new();
                        if staged_count > 0 {
                            parts.push(format!("{} staged", staged_count));
                        }
                        if unstaged_count > 0 {
                            parts.push(format!("{} unstaged", unstaged_count));
                        }
                        if untracked_count > 0 {
                            parts.push(format!("{} untracked", untracked_count));
                        }

                        if parts.is_empty() {
                            (Status::NoChanges, "no changes".to_string())
                        } else {
                            (Status::Synced, parts.join(", "))
                        }
                    }
                }
                Err(e) => (Status::StagingError, format!("error: {}", e)),
            };

            progress_bar.set_prefix(format!(
                "{} {:width$}",
                status.symbol(),
                repo_name,
                width = max_name_length
            ));
            progress_bar.set_message(format!("{:<12}   {}", status.text(), message));
            progress_bar.finish();
        };

        futures.push(future);
    }

    // Wait for all repository operations to complete
    while futures.next().await.is_some() {}

    // Add final spacing
    println!();
}

/// Handles the repository commit command
pub async fn handle_commit_command(message: String, include_empty: bool) -> Result<()> {
    // Set terminal title to indicate repos is running
    set_terminal_title("🚀 repos commit");

    let (start_time, repos) = init_command(SCANNING_MESSAGE);

    if repos.is_empty() {
        println!("\r{}", NO_REPOS_MESSAGE);
        // Set terminal title to green checkbox to indicate completion
        set_terminal_title_and_flush("✅ repos commit");
        return Ok(());
    }

    let total_repos = repos.len();
    let repo_word = if total_repos == 1 {
        "repository"
    } else {
        "repositories"
    };
    print!(
        "\r🚀 Committing changes in {} {}                    \n",
        total_repos, repo_word
    );
    println!();

    // Create processing context
    let context = match create_processing_context(repos, start_time, GIT_CONCURRENT_CAP) {
        Ok(context) => context,
        Err(e) => {
            // If context creation fails, set completion title and return error
            set_terminal_title_and_flush("✅ repos commit");
            return Err(e);
        }
    };

    // Process all repositories concurrently
    process_commit_repositories(context, message, include_empty).await;

    // Set terminal title to green checkbox to indicate completion
    set_terminal_title_and_flush("✅ repos commit");

    Ok(())
}

/// Processes all repositories concurrently for commit operations
async fn process_commit_repositories(
    context: crate::core::ProcessingContext,
    message: String,
    include_empty: bool,
) {
    use crate::core::{acquire_semaphore_permit, acquire_stats_lock, create_progress_bar};
    use futures::stream::{FuturesUnordered, StreamExt};

    let mut futures = FuturesUnordered::new();

    // First, create all repository progress bars
    let mut repo_progress_bars = Vec::new();
    for (repo_name, _) in &context.repositories {
        let progress_bar =
            create_progress_bar(&context.multi_progress, &context.progress_style, repo_name);
        progress_bar.set_message(COMMITTING_MESSAGE);
        repo_progress_bars.push(progress_bar);
    }

    // Add a blank line before the footer
    let _separator_pb = crate::core::create_separator_progress_bar(&context.multi_progress);

    // Create the footer progress bar
    let footer_pb = crate::core::create_footer_progress_bar(&context.multi_progress);

    // Initial footer display
    let initial_stats = crate::core::SyncStatistics::new();
    let initial_summary =
        initial_stats.generate_summary(context.total_repos, context.start_time.elapsed());
    footer_pb.set_message(initial_summary);

    // Add another blank line after the footer
    let _separator_pb2 = crate::core::create_separator_progress_bar(&context.multi_progress);

    // Extract values we need in the async closures before moving context.repositories
    let max_name_length = context.max_name_length;
    let start_time = context.start_time;
    let total_repos = context.total_repos;

    for ((repo_name, repo_path), progress_bar) in
        context.repositories.into_iter().zip(repo_progress_bars)
    {
        let stats_clone = std::sync::Arc::clone(&context.statistics);
        let semaphore_clone = std::sync::Arc::clone(&context.semaphore);
        let footer_clone = footer_pb.clone();
        let message_clone = message.clone();

        let future = async move {
            let _permit = acquire_semaphore_permit(&semaphore_clone).await;

            let (status, message) =
                perform_commit_operation(&repo_path, &message_clone, include_empty).await;

            progress_bar.set_prefix(format!(
                "{} {:width$}",
                status.symbol(),
                repo_name,
                width = max_name_length
            ));
            progress_bar.set_message(format!("{:<12}   {}", status.text(), message));
            progress_bar.finish();

            // Update statistics based on operation result
            let stats_guard = acquire_stats_lock(&stats_clone);
            let repo_path_str = repo_path.to_string_lossy();
            stats_guard.update(
                &repo_name,
                &repo_path_str,
                &status,
                &message,
                false, // commit operations don't track uncommitted changes
            );

            // Update the footer summary after each repository completes
            let duration = start_time.elapsed();
            let summary = stats_guard.generate_summary(total_repos, duration);
            footer_clone.set_message(summary);
        };

        futures.push(future);
    }

    // Wait for all repository operations to complete
    while futures.next().await.is_some() {}

    // Finish the footer progress bar
    footer_pb.finish();

    // Print the final detailed summary if there are any issues to report
    let final_stats = acquire_stats_lock(&context.statistics);
    let detailed_summary = final_stats.generate_detailed_summary(false);
    if !detailed_summary.is_empty() {
        println!("\n{}", "".repeat(70));
        println!("{}", detailed_summary);
        println!("{}", "".repeat(70));
    }

    // Add final spacing
    println!();
}

/// Performs a staging operation on a single repository
async fn perform_staging_operation(repo_path: &std::path::Path, pattern: &str) -> (Status, String) {
    use crate::core::clean_error_message;

    match stage_files(repo_path, pattern).await {
        Ok((true, _, _)) => (Status::Staged, format!("staged {}", pattern)),
        Ok((false, _, stderr)) => {
            let error_message = clean_error_message(&stderr);
            if error_message.contains("pathspec") && error_message.contains("did not match") {
                (Status::NoChanges, format!("no files match {}", pattern))
            } else {
                (Status::StagingError, error_message)
            }
        }
        Err(e) => {
            let error_message = clean_error_message(&e.to_string());
            (Status::StagingError, error_message)
        }
    }
}

/// Performs a commit operation on a single repository
async fn perform_commit_operation(
    repo_path: &std::path::Path,
    message: &str,
    include_empty: bool,
) -> (Status, String) {
    use crate::core::clean_error_message;

    // First check if there are staged changes (unless we're allowing empty commits)
    if !include_empty {
        match has_staged_changes(repo_path).await {
            Ok(false) => {
                return (Status::NoChanges, "no staged changes".to_string());
            }
            Ok(true) => {
                // Has staged changes, proceed with commit
            }
            Err(e) => {
                let error_message = clean_error_message(&e.to_string());
                return (
                    Status::CommitError,
                    format!("error checking changes: {}", error_message),
                );
            }
        }
    }

    // Perform the commit
    match commit_changes(repo_path, message, include_empty).await {
        Ok((true, stdout, _)) => {
            // Parse commit output to get commit hash (first 7 chars of first line usually)
            let commit_info = if let Some(first_line) = stdout.lines().next() {
                if first_line.len() > 7 {
                    &first_line[0..7]
                } else {
                    "committed"
                }
            } else {
                "committed"
            };
            (Status::Committed, format!("committed {}", commit_info))
        }
        Ok((false, _, stderr)) => {
            let error_message = clean_error_message(&stderr);
            if error_message.contains("nothing to commit")
                || error_message.contains("no changes added")
            {
                (Status::NoChanges, "nothing to commit".to_string())
            } else {
                (Status::CommitError, error_message)
            }
        }
        Err(e) => {
            let error_message = clean_error_message(&e.to_string());
            (Status::CommitError, error_message)
        }
    }
}

/// Performs an unstaging operation on a single repository
async fn perform_unstaging_operation(
    repo_path: &std::path::Path,
    pattern: &str,
) -> (Status, String) {
    use crate::core::clean_error_message;

    match unstage_files(repo_path, pattern).await {
        Ok((true, _, _)) => (Status::Unstaged, format!("unstaged {}", pattern)),
        Ok((false, _, stderr)) => {
            let error_message = clean_error_message(&stderr);
            if error_message.contains("pathspec") && error_message.contains("did not match") {
                (
                    Status::NoChanges,
                    format!("no staged files match {}", pattern),
                )
            } else {
                (Status::StagingError, error_message)
            }
        }
        Err(e) => {
            let error_message = clean_error_message(&e.to_string());
            (Status::StagingError, error_message)
        }
    }
}