Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ pub enum Commands {
Push(PushArgs),
/// Switch to a branch tracked by gw
Switch(SwitchArgs),
/// Show status of the current branch in its stack
Status,
/// Show log of all stacks with branches and commits
#[command(alias = "tree")]
Log(TreeArgs),
Expand Down
1 change: 1 addition & 0 deletions src/commands/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ pub mod mcp_setup;
pub mod push;
pub mod rebase;
pub mod stack;
pub mod status;
pub mod switch;
pub mod sync;
pub mod tree;
242 changes: 242 additions & 0 deletions src/commands/status.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,242 @@
use anyhow::{bail, Result};
use colored::Colorize;

use crate::context::Ctx;

pub fn run(ctx: &Ctx) -> Result<()> {
let current = ctx.git.current_branch()?;

let stack = match ctx.find_stack_for_branch(&current)? {
Some(s) => s,
None => bail!(
"Branch '{}' is not in any stack.\n\
Use `gw adopt` to add it.",
current
),
};

let idx = stack.branch_index(&current).unwrap();
let total = stack.branches.len();
let parent = stack.parent_of(&current).unwrap();
let children: Vec<&str> = if idx + 1 < total {
vec![&stack.branches[idx + 1].name]
} else {
vec![]
};

let is_root = idx == 0;
let is_leaf = idx == total - 1;

// Gather git info
let merge_base = ctx.git.merge_base(&parent, &current)?;
let commits = ctx.git.log_oneline(&merge_base, "HEAD", 100)?;
let parent_sha = ctx.git.rev_parse(&parent)?;
let needs_rebase = merge_base != parent_sha;

// Remote status
let remote_status = remote_info(ctx, &current);

// Working tree
let wt = working_tree_info(ctx);

// === Render ===

// Branch + stack header
let position_label = if is_root && is_leaf {
"only branch".dimmed().to_string()
} else if is_root {
"root".blue().dimmed().to_string()
} else if is_leaf {
"leaf".blue().dimmed().to_string()
} else {
format!("{}", format!("{} of {total}", idx + 1).dimmed())
};

println!(
"{} {} {}",
format!("@").green().bold(),
current.green().bold(),
position_label,
);

println!(
"{} {}",
"stack".dimmed(),
stack.name.magenta().bold(),
);

// Navigation: parent and child
println!(
" {} {}",
"↑".dimmed(),
if is_root {
format!("{} {}", parent.cyan(), "(base)".dimmed())
} else {
parent.white().bold().to_string()
},
);

if let Some(child) = children.first() {
println!(
" {} {}",
"↓".dimmed(),
child.white().bold(),
);
}

println!();

// Commits
let commit_label = format!(
"{} commit{}",
commits.len(),
if commits.len() == 1 { "" } else { "s" }
);
println!("{}", commit_label.dimmed());
for (sha, subject) in &commits {
println!(" {} {}", sha.yellow(), subject);
}
if commits.is_empty() {
println!(" {}", "(no commits yet)".dimmed());
}

println!();

// Status flags
let mut flags: Vec<String> = vec![];

match &wt {
WorkingTree::Clean => flags.push(format!("{}", "clean".green())),
WorkingTree::Dirty { staged, unstaged, untracked } => {
let mut parts: Vec<String> = vec![];
if *staged > 0 {
parts.push(format!("{} staged", staged).green().to_string());
}
if *unstaged > 0 {
parts.push(format!("{} modified", unstaged).yellow().to_string());
}
if *untracked > 0 {
parts.push(format!("{} untracked", untracked).dimmed().to_string());
}
flags.push(parts.join(" "));
}
}

match &remote_status {
RemoteStatus::UpToDate => flags.push(format!("{}", "pushed".green())),
RemoteStatus::NeedsPush(ahead) => {
flags.push(format!("{}", format!("{ahead} ahead, needs push").yellow()));
}
RemoteStatus::Diverged => {
flags.push(format!("{}", "diverged from remote".yellow()));
}
RemoteStatus::NoRemote => {
flags.push(format!("{}", "not pushed".dimmed()));
}
}

if needs_rebase {
flags.push(format!("{}", "needs rebase".yellow()));
}

for flag in &flags {
println!(" {} {flag}", "•".dimmed());
}

Ok(())
}

enum WorkingTree {
Clean,
Dirty {
staged: usize,
unstaged: usize,
untracked: usize,
},
}

fn working_tree_info(ctx: &Ctx) -> WorkingTree {
let output = ctx.git.run(&["status", "--porcelain"]);
let output = match output {
Ok(o) if o.is_empty() => return WorkingTree::Clean,
Ok(o) => o,
Err(_) => return WorkingTree::Clean,
};

let mut staged = 0usize;
let mut unstaged = 0usize;
let mut untracked = 0usize;

for line in output.lines() {
if line.len() < 2 {
continue;
}
let x = line.as_bytes()[0];
let y = line.as_bytes()[1];

if x == b'?' {
untracked += 1;
} else {
if x != b' ' && x != b'?' {
staged += 1;
}
if y != b' ' && y != b'?' {
unstaged += 1;
}
}
}

WorkingTree::Dirty {
staged,
unstaged,
untracked,
}
}

enum RemoteStatus {
UpToDate,
NeedsPush(usize),
Diverged,
NoRemote,
}

fn remote_info(ctx: &Ctx, branch: &str) -> RemoteStatus {
let output = ctx.git.run(&[
"for-each-ref",
&format!("--format=%(upstream:short)\t%(upstream:track)"),
&format!("refs/heads/{branch}"),
]);

let output = match output {
Ok(o) => o,
Err(_) => return RemoteStatus::NoRemote,
};

let parts: Vec<&str> = output.split('\t').collect();
let upstream = parts.first().unwrap_or(&"");
let track = parts.get(1).unwrap_or(&"");

if upstream.is_empty() {
return RemoteStatus::NoRemote;
}

if track.is_empty() {
return RemoteStatus::UpToDate;
}

if track.contains("ahead") && track.contains("behind") {
return RemoteStatus::Diverged;
}

if track.contains("ahead") {
// Parse the number from "[ahead N]"
let ahead = track
.split("ahead ")
.nth(1)
.and_then(|s| s.trim_end_matches(']').parse::<usize>().ok())
.unwrap_or(1);
return RemoteStatus::NeedsPush(ahead);
}

RemoteStatus::UpToDate
}
4 changes: 3 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ fn main() -> Result<()> {
&command,
Commands::Rebase(args) if args.cont || args.abort
) || matches!(&command, Commands::Log(_))
|| matches!(&command, Commands::Switch(_));
|| matches!(&command, Commands::Switch(_))
|| matches!(&command, Commands::Status);

if !allowed {
let op = match prop_state.operation {
Expand All @@ -54,6 +55,7 @@ fn main() -> Result<()> {
}

match command {
Commands::Status => commands::status::run(&ctx),
Commands::Stack(args) => commands::stack::run(args.command, &ctx),
Commands::Branch(args) => commands::branch::run(args.command, &ctx),
Commands::Adopt(args) => commands::adopt::run(args, &ctx),
Expand Down