gitsw 0.1.0

A smart Git branch switcher with automatic stash management and dependency installation
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
use anyhow::{anyhow, Result};
use clap::Parser;
use colored::Colorize;
use git2::Oid;

use gitsw::git::GitRepo;
use gitsw::hooks;
use gitsw::prompt::{self, StashAction, UnstashAction};
use gitsw::state::StateManager;

#[derive(Parser, Debug)]
#[command(name = "gitsw")]
#[command(
    author,
    version,
    about = "Contextual Git branch switcher with automatic stash management"
)]
struct Args {
    /// Target branch to switch to (interactive picker if omitted)
    #[arg(value_name = "BRANCH")]
    branch: Option<String>,

    /// List branches with stashes
    #[arg(short, long)]
    list: bool,

    /// Show recent branches
    #[arg(short, long)]
    recent: bool,

    /// Show current status (branch, stash, changes)
    #[arg(short, long)]
    status: bool,

    /// Delete a branch (with stash cleanup)
    #[arg(short, long, value_name = "BRANCH")]
    delete: Option<String>,

    /// Track and switch to a remote branch
    #[arg(short = 't', long, value_name = "REMOTE/BRANCH")]
    track: Option<String>,

    /// Skip automatic stash behavior
    #[arg(long)]
    no_stash: bool,

    /// Skip automatic package install
    #[arg(long)]
    no_install: bool,

    /// Create branch if it doesn't exist
    #[arg(short = 'c', long)]
    create: bool,

    /// Pull latest changes after switching
    #[arg(short = 'p', long)]
    pull: bool,
}

fn main() {
    if let Err(e) = run() {
        eprintln!("{}: {}", "error".red().bold(), e);
        std::process::exit(1);
    }
}

fn run() -> Result<()> {
    let args = Args::parse();

    // Handle --status flag
    if args.status {
        return show_status();
    }

    // Handle --list flag
    if args.list {
        return list_stashes();
    }

    // Handle --recent flag
    if args.recent {
        return show_recent();
    }

    // Handle --delete flag
    if let Some(branch) = args.delete {
        return delete_branch(&branch);
    }

    // Handle --track flag
    if let Some(remote_branch) = args.track {
        return track_remote(&remote_branch, !args.no_stash, !args.no_install, args.pull);
    }

    // Interactive picker if no branch specified
    let target_branch = match args.branch {
        Some(b) => b,
        None => prompt::select_branch()?,
    };

    switch_branch(
        &target_branch,
        !args.no_stash,
        !args.no_install,
        args.create,
        args.pull,
    )
}

fn show_status() -> Result<()> {
    let mut repo = GitRepo::open()?;
    let state = StateManager::load(repo.git_dir())?;
    let workdir = repo.workdir()?.to_path_buf();

    let current_branch = repo.get_current_branch()?;
    println!("{} {}", "Branch:".bold(), current_branch.green());

    // Check for uncommitted changes
    if repo.has_uncommitted_changes()? {
        let summary = repo.get_changes_summary()?;
        println!("{} {}", "Changes:".bold(), summary.yellow());
    } else {
        println!("{} {}", "Changes:".bold(), "clean".dimmed());
    }

    // Check for stash
    if let Some(branch_state) = state.get_branch(&current_branch) {
        if branch_state.stash_id.is_some() {
            let stashes = repo.list_stashes()?;
            let stash_exists = branch_state.stash_id.as_ref().is_some_and(|id| {
                Oid::from_str(id)
                    .map(|oid| stashes.iter().any(|s| s.oid == oid))
                    .unwrap_or(false)
            });
            if stash_exists {
                println!("{} {}", "Stash:".bold(), "present".yellow());
            }
        }
    }

    // Check package manager
    if let Some((pm, _)) = hooks::get_lock_file_hash(&workdir)? {
        println!("{} {}", "Package manager:".bold(), pm.name());
    }

    // Check remote tracking
    if let Some(remote) = repo.get_tracking_remote(&current_branch)? {
        println!("{} {}", "Tracking:".bold(), remote);
    }

    Ok(())
}

fn list_stashes() -> Result<()> {
    let mut repo = GitRepo::open()?;
    let state = StateManager::load(repo.git_dir())?;

    let current_branch = repo.get_current_branch()?;
    let stashes = repo.list_stashes()?;
    let branches_with_stashes = state.branches_with_stashes();

    if branches_with_stashes.is_empty() {
        println!("{}", "No branches with git-switch stashes found.".dimmed());
        return Ok(());
    }

    println!("{}", "Branches with stashed changes:".bold());
    println!();

    for (branch_name, branch_state) in branches_with_stashes {
        let is_current = branch_name == current_branch;
        let marker = if is_current { "* " } else { "  " };

        let branch_display = if is_current {
            branch_name.green().bold()
        } else {
            branch_name.normal()
        };

        let stash_exists = branch_state.stash_id.as_ref().is_some_and(|id| {
            Oid::from_str(id)
                .map(|oid| stashes.iter().any(|s| s.oid == oid))
                .unwrap_or(false)
        });

        let stash_status = if stash_exists {
            "stash present".yellow()
        } else {
            "stash missing".red()
        };

        let time_display = format_time_ago(branch_state.last_visited);

        println!(
            "{}{} ({}, last visited {})",
            marker,
            branch_display,
            stash_status,
            time_display.dimmed()
        );
    }

    Ok(())
}

fn show_recent() -> Result<()> {
    let repo = GitRepo::open()?;
    let state = StateManager::load(repo.git_dir())?;

    let current_branch = repo.get_current_branch()?;
    let mut recent = state.recent_branches(10);

    if recent.is_empty() {
        println!("{}", "No recent branches tracked yet.".dimmed());
        return Ok(());
    }

    println!("{}", "Recent branches:".bold());
    println!();

    // Sort by last visited (most recent first)
    recent.sort_by(|a, b| b.1.last_visited.cmp(&a.1.last_visited));

    for (i, (branch_name, branch_state)) in recent.iter().enumerate() {
        let is_current = *branch_name == current_branch;
        let marker = if is_current { "* " } else { "  " };

        let branch_display = if is_current {
            branch_name.green().bold()
        } else {
            branch_name.normal()
        };

        let time_display = format_time_ago(branch_state.last_visited);
        let stash_indicator = if branch_state.stash_id.is_some() {
            " [stash]".yellow()
        } else {
            "".normal()
        };

        println!(
            "{}{} {}{} ({})",
            marker,
            format!("[{}]", i + 1).dimmed(),
            branch_display,
            stash_indicator,
            time_display.dimmed()
        );
    }

    Ok(())
}

fn delete_branch(branch_name: &str) -> Result<()> {
    let mut repo = GitRepo::open()?;
    let mut state = StateManager::load(repo.git_dir())?;

    let current_branch = repo.get_current_branch()?;

    if branch_name == current_branch {
        return Err(anyhow!("Cannot delete the current branch"));
    }

    if !repo.branch_exists(branch_name) {
        return Err(anyhow!("Branch '{}' not found", branch_name));
    }

    // Check for stash and offer to clean up
    if let Some(branch_state) = state.get_branch(branch_name) {
        if let Some(stash_id) = &branch_state.stash_id {
            if let Ok(stash_oid) = Oid::from_str(stash_id) {
                println!(
                    "{} Branch has a stash. It will be dropped.",
                    "warning:".yellow().bold()
                );
                if prompt::confirm_delete(branch_name)? {
                    let _ = repo.stash_drop(stash_oid);
                } else {
                    println!("{} Delete aborted.", "info:".blue().bold());
                    return Ok(());
                }
            }
        }
    } else if !prompt::confirm_delete(branch_name)? {
        println!("{} Delete aborted.", "info:".blue().bold());
        return Ok(());
    }

    // Delete the branch
    repo.delete_branch(branch_name)?;
    state.remove_branch(branch_name);
    state.save()?;

    println!(
        "{} Deleted branch '{}'",
        "done:".green().bold(),
        branch_name
    );

    Ok(())
}

fn track_remote(
    remote_branch: &str,
    auto_stash: bool,
    auto_install: bool,
    pull: bool,
) -> Result<()> {
    let repo = GitRepo::open()?;

    // Parse remote/branch format
    let parts: Vec<&str> = remote_branch.splitn(2, '/').collect();
    if parts.len() != 2 {
        return Err(anyhow!("Invalid format. Use: origin/branch-name"));
    }

    let remote = parts[0];
    let branch = parts[1];

    // Fetch from remote first
    println!("{} Fetching from '{}'...", "info:".blue().bold(), remote);
    repo.fetch(remote)?;

    // Check if local branch already exists
    if repo.branch_exists(branch) {
        println!(
            "{} Local branch '{}' already exists, switching to it",
            "info:".blue().bold(),
            branch
        );
        return switch_branch(branch, auto_stash, auto_install, false, pull);
    }

    // Create tracking branch
    println!(
        "{} Creating branch '{}' tracking '{}'...",
        "info:".blue().bold(),
        branch.green(),
        remote_branch
    );

    repo.create_tracking_branch(branch, remote_branch)?;
    switch_branch(branch, auto_stash, auto_install, false, pull)
}

fn switch_branch(
    target_branch: &str,
    auto_stash: bool,
    auto_install: bool,
    create: bool,
    pull: bool,
) -> Result<()> {
    let mut repo = GitRepo::open()?;
    let workdir = repo.workdir()?.to_path_buf();

    // Check if branch exists, create if requested
    let branch_exists = repo.branch_exists(target_branch);
    if !branch_exists && !create {
        return Err(anyhow!(
            "Branch '{}' not found. Use -c to create it.",
            target_branch
        ));
    }

    let current_branch = repo.get_current_branch()?;

    // Already on target branch
    if current_branch == target_branch {
        println!(
            "{} Already on '{}'",
            "info:".blue().bold(),
            target_branch.green()
        );

        // Still pull if requested
        if pull {
            do_pull(&mut repo)?;
        }
        return Ok(());
    }

    let mut state = StateManager::load(repo.git_dir())?;

    // Update last visited for current branch before leaving
    state.touch_branch(&current_branch);
    state.save()?;

    // Step 1: Handle uncommitted changes on current branch
    if auto_stash && repo.has_uncommitted_changes()? {
        let changes_summary = repo.get_changes_summary()?;

        match prompt::prompt_stash_conflict(&changes_summary)? {
            StashAction::Stash => {
                let message = format!("git-switch: {}", current_branch);
                println!(
                    "{} Stashing changes on '{}'...",
                    "info:".blue().bold(),
                    current_branch.yellow()
                );

                let stash_oid = repo.stash_save(&message)?;
                state.set_stash(&current_branch, Some(stash_oid.to_string()));

                if let Some((_, hash)) = hooks::get_lock_file_hash(&workdir)? {
                    state.set_lock_hash(&current_branch, Some(hash));
                }

                state.save()?;
                println!("{} Changes stashed.", "done:".green().bold());
            }
            StashAction::Discard => {
                if !prompt::confirm_discard()? {
                    println!("{} Switch aborted.", "info:".blue().bold());
                    return Ok(());
                }
                println!("{} Discarding changes...", "warning:".yellow().bold());
                repo.discard_changes()?;
                println!("{} Changes discarded.", "done:".green().bold());
            }
            StashAction::Abort => {
                println!("{} Switch aborted.", "info:".blue().bold());
                return Ok(());
            }
        }
    } else if !auto_stash && repo.has_uncommitted_changes()? {
        println!(
            "{} Skipping stash (--no-stash), uncommitted changes may prevent switch",
            "warning:".yellow().bold()
        );
    }

    // Step 2: Create branch if needed, then switch
    if !branch_exists && create {
        println!(
            "{} Creating branch '{}'...",
            "info:".blue().bold(),
            target_branch.green()
        );
        repo.create_branch(target_branch)?;
    }

    println!(
        "{} Switching to '{}'...",
        "info:".blue().bold(),
        target_branch.green()
    );

    repo.switch_branch(target_branch)?;

    println!(
        "{} Switched to '{}'",
        "done:".green().bold(),
        target_branch.green()
    );

    // Step 3: Check for stashed changes on target branch
    if let Some(branch_state) = state.get_branch(target_branch).cloned() {
        if let Some(stash_id) = &branch_state.stash_id {
            if let Ok(stash_oid) = Oid::from_str(stash_id) {
                println!(
                    "{} Found stashed changes for this branch",
                    "info:".blue().bold()
                );

                match repo.stash_apply(stash_oid) {
                    Ok(()) => {
                        println!("{} Restored stashed changes.", "done:".green().bold());
                        if let Err(e) = repo.stash_drop(stash_oid) {
                            eprintln!("{} Failed to drop stash: {}", "warning:".yellow().bold(), e);
                        }
                        state.clear_stash(target_branch);
                        state.save()?;
                    }
                    Err(_) => match prompt::prompt_unstash_conflict()? {
                        UnstashAction::Apply => {
                            println!(
                                "{} Please resolve conflicts manually. Stash preserved.",
                                "warning:".yellow().bold()
                            );
                        }
                        UnstashAction::Skip => {
                            println!(
                                "{} Skipping stash restoration. Stash preserved for later.",
                                "info:".blue().bold()
                            );
                        }
                        UnstashAction::Abort => {
                            println!(
                                "{} Switching back to '{}'...",
                                "info:".blue().bold(),
                                current_branch
                            );
                            repo.switch_branch(&current_branch)?;
                            return Ok(());
                        }
                    },
                }
            }
        }
    }

    // Step 4: Pull if requested
    if pull {
        do_pull(&mut repo)?;
    }

    // Step 5: Check for lock file changes and run install
    if auto_install {
        handle_package_install(&workdir, &mut state, target_branch)?;
    }

    // Update last visited for target branch
    state.touch_branch(target_branch);
    state.save()?;

    Ok(())
}

fn do_pull(repo: &mut GitRepo) -> Result<()> {
    println!("{} Pulling latest changes...", "info:".blue().bold());
    match repo.pull() {
        Ok(()) => {
            println!("{} Pull completed.", "done:".green().bold());
        }
        Err(e) => {
            eprintln!("{} Pull failed: {}", "warning:".yellow().bold(), e);
        }
    }
    Ok(())
}

fn handle_package_install(
    workdir: &std::path::Path,
    state: &mut StateManager,
    branch: &str,
) -> Result<()> {
    let lock_info = hooks::get_lock_file_hash(workdir)?;

    if let Some((pm, current_hash)) = lock_info {
        let stored_hash = state
            .get_branch(branch)
            .and_then(|s| s.lock_file_hash.as_ref());

        let should_install = match stored_hash {
            Some(hash) => hash != &current_hash,
            None => false,
        };

        if should_install && prompt::prompt_install(pm.name())? {
            println!("{} Running {} install...", "info:".blue().bold(), pm.name());

            if hooks::run_install(pm, workdir)? {
                println!("{} Install completed.", "done:".green().bold());
            } else {
                eprintln!(
                    "{} Install failed. Please run manually.",
                    "error:".red().bold()
                );
            }
        }

        state.set_lock_hash(branch, Some(current_hash));
        state.save()?;
    }

    Ok(())
}

fn format_time_ago(time: chrono::DateTime<chrono::Utc>) -> String {
    let duration = chrono::Utc::now().signed_duration_since(time);
    let minutes = duration.num_minutes();
    let hours = duration.num_hours();
    let days = duration.num_days();

    if minutes < 1 {
        "just now".to_string()
    } else if minutes < 60 {
        format!("{} min ago", minutes)
    } else if hours < 24 {
        format!("{} hour{} ago", hours, if hours == 1 { "" } else { "s" })
    } else if days == 1 {
        "yesterday".to_string()
    } else {
        format!("{} days ago", days)
    }
}