feat: browse the files of a commit
Rust / build (macos-latest, stable) (push) Canceled after 0s
Rust / build (ubuntu-latest, stable) (push) Canceled after 0s
Rust / build (windows-latest, stable) (push) Canceled after 0s

This commit is contained in:
2026-11-26 08:37:43 +07:00
parent d421a10a3e
commit f57427d30d
9 changed files with 469 additions and 95 deletions
+53 -15
View File
@@ -38,6 +38,20 @@ enum FileContent {
Failed(String),
}
impl FileContent {
/// Classifies raw bytes, refusing files too large to preview.
fn from_bytes(bytes: Vec<u8>) -> Self {
if bytes.len() > MAX_PREVIEW_BYTES {
return Self::TooLarge;
}
match String::from_utf8(bytes) {
Ok(text) => Self::Text(text),
Err(_) => Self::Binary,
}
}
}
struct MarkdownView {
/// `None` means the repository README.
path: Option<SharedString>,
@@ -72,6 +86,8 @@ pub struct RepoFilesView {
commits: HashMap<String, FileCommit>,
pending_commits: Vec<String>,
loading_commits: bool,
/// The commit whose tree is browsed instead of the worktree.
commit: Option<FileCommit>,
tasks: Vec<Task<Result<(), Error>>>,
/// Bumped when the previews are cleared, so loads started before it are dropped.
generation: u64,
@@ -99,6 +115,7 @@ impl RepoFilesView {
commits: HashMap::new(),
pending_commits: Vec::new(),
loading_commits: false,
commit: None,
tasks: Vec::new(),
generation: 0,
}
@@ -108,6 +125,11 @@ impl RepoFilesView {
self.worktree = Some(path);
}
/// Browses the files of `commit` instead of the worktree, or the worktree when `None`.
pub fn pin_commit(&mut self, commit: Option<FileCommit>) {
self.commit = commit;
}
pub fn apply_entries(
&mut self,
tree: Vec<TreeItemSeed>,
@@ -544,6 +566,7 @@ impl RepoFilesView {
self.loading_files.insert(path.to_string());
let path = path.to_string();
let commit = self.commit.as_ref().map(|commit| commit.id.clone());
self.load_commit(&path, cx);
@@ -553,25 +576,34 @@ impl RepoFilesView {
let path_for_read = path.clone();
let content = cx
.background_spawn(async move {
let full = worktree.join(&path_for_read);
match commit {
Some(commit) => Repo::open_cached(&worktree)
.and_then(|repo| repo.read_at(&commit, Path::new(&path_for_read)))
.map(|bytes| {
bytes.map_or_else(
|| FileContent::Failed("File is not in this commit".into()),
FileContent::from_bytes,
)
}),
None => {
let full = worktree.join(&path_for_read);
let metadata = match std::fs::metadata(&full) {
Ok(metadata) => metadata,
Err(error) => return Err(anyhow::anyhow!("{}", error)),
};
let metadata = match std::fs::metadata(&full) {
Ok(metadata) => metadata,
Err(error) => return Err(anyhow::anyhow!("{}", error)),
};
if metadata.len() > MAX_PREVIEW_BYTES as u64 {
return Ok(FileContent::TooLarge);
}
if metadata.len() > MAX_PREVIEW_BYTES as u64 {
return Ok(FileContent::TooLarge);
}
let bytes = match std::fs::read(&full) {
Ok(bytes) => bytes,
Err(error) => return Err(anyhow::anyhow!("{}", error)),
};
let bytes = match std::fs::read(&full) {
Ok(bytes) => bytes,
Err(error) => return Err(anyhow::anyhow!("{}", error)),
};
match String::from_utf8(bytes) {
Ok(text) => Ok(FileContent::Text(text)),
Err(_) => Ok(FileContent::Binary),
Ok(FileContent::from_bytes(bytes))
}
}
})
.await;
@@ -668,6 +700,12 @@ impl RepoFilesView {
}
fn load_commit(&mut self, path: &str, cx: &mut Context<Self>) {
// A pinned tree labels every file with the commit being browsed.
if let Some(commit) = &self.commit {
self.commits.insert(path.to_string(), commit.clone());
return;
}
if self.commits.contains_key(path) || self.pending_commits.iter().any(|p| p == path) {
return;
}
+26
View File
@@ -85,6 +85,14 @@ pub(super) struct RepoData {
pub(super) head_commit: Option<FileCommit>,
}
/// A commit's tree and README, as the file explorer shows them.
pub(super) struct CommitTree {
pub(super) tree: Vec<TreeItemSeed>,
pub(super) paths: Vec<String>,
pub(super) readme_path: Option<PathBuf>,
pub(super) readme: Option<Vec<u8>>,
}
/// Sorted relative paths of a worktree snapshot.
pub(crate) fn sorted_worktree_paths(entries: &[PathBuf]) -> Vec<String> {
let mut paths: Vec<String> = entries
@@ -142,6 +150,24 @@ pub(super) fn snapshot_worktree(
Ok((snapshot, tree, paths))
}
/// Lists the tree and README of `commit` in the repository at `worktree`.
pub(super) fn snapshot_commit(worktree: &Path, commit: &str) -> Result<CommitTree, Error> {
let repo = Repo::open_cached(worktree)?;
let entries = repo.entries_at(commit)?;
let readme_path = Repo::pick_readme(&entries);
let readme = match &readme_path {
Some(path) => repo.read_at(commit, path)?,
None => None,
};
Ok(CommitTree {
tree: TreeItemSeed::from_paths(&entries),
paths: sorted_worktree_paths(&entries),
readme_path,
readme,
})
}
pub(super) fn clone_group(label: &str, id: SharedString, command: &SharedString) -> AnyElement {
v_flex()
.gap_1()
+89 -47
View File
@@ -4,14 +4,15 @@ use std::sync::Arc;
use anyhow::Error;
use gpui::prelude::FluentBuilder as _;
use gpui::{
AppContext as _, Context, Entity, InteractiveElement as _, IntoElement, ParentElement as _,
Render, SharedString, StatefulInteractiveElement as _, Styled as _, Task,
App, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement,
ParentElement as _, Render, SharedString, StatefulInteractiveElement as _, Styled as _, Task,
UniformListScrollHandle, WeakEntity, Window, div, uniform_list,
};
use signed_git::{CommitList, FileCommit, Repo};
use signed_state::{Backend, RepoStore, SyncStatusDirectory};
use ui::alert::{Alert, AlertSeverity, AlertStyle};
use ui::button::{Button, ButtonVariant};
use ui::avatar::IdentityRow;
use ui::button::{Button, ButtonSide, ButtonVariant};
use ui::common::{Sizable as _, h_flex, v_flex};
use ui::empty_state::EmptyState;
use ui::icons::{Icon, IconRole};
@@ -124,6 +125,14 @@ impl RepoHistoryView {
self.load_task = Some(task);
}
/// The panel id of `commit_id` in this repository's worktree, namespaced by `kind`.
fn panel_id(&self, kind: &str, commit_id: &str, worktree: &Path, cx: &App) -> SharedString {
match self.store.read(cx).addr() {
Some(addr) => SharedString::from(format!("{kind}:{addr}:{commit_id}")),
None => SharedString::from(format!("{kind}:{}:{commit_id}", worktree.display())),
}
}
pub fn open_commit_diff(
&mut self,
commit_id: &str,
@@ -134,12 +143,8 @@ impl RepoHistoryView {
return;
};
let store = self.store.clone();
let commit_id = commit_id.to_owned();
let id = match store.read(cx).addr() {
Some(addr) => SharedString::from(format!("commit:{addr}:{commit_id}")),
None => SharedString::from(format!("commit:{}:{}", worktree.display(), commit_id)),
};
let id = self.panel_id("commit", &commit_id, &worktree, cx);
let workspace = self.workspace.clone();
log_dropped(workspace.update(cx, |root, cx| {
@@ -164,6 +169,27 @@ impl RepoHistoryView {
})
}));
}
/// Shows the files of the listed commit `commit_id` in the repository panel.
fn browse_commit(&mut self, commit_id: &str, window: &mut Window, cx: &mut Context<Self>) {
// The list comes from this worktree, which may be another checkout than the panel shows.
let Some(source) = self.worktree.clone() else {
return;
};
let Some(commit) = self
.commits
.iter()
.find(|commit| commit.id == commit_id)
.cloned()
else {
return;
};
log_dropped(self.detail.update(cx, |detail, cx| {
detail.browse_commit(commit, source, window, cx);
}));
}
}
impl Render for RepoHistoryView {
@@ -250,7 +276,10 @@ impl Render for RepoHistoryView {
};
let row_id = commit.id.clone();
let browse_id = commit.id.clone();
let view = view.clone();
let browse_view = view.clone();
let ahead = ahead
.iter()
.find(|(id, _)| id.starts_with(commit.id.as_str()));
@@ -258,51 +287,64 @@ impl Render for RepoHistoryView {
h_flex()
.id(commit.id.clone())
.px_4()
.h_16()
.h_12()
.w_full()
.gap_3()
.gap_2()
.text_sm()
.border_b_1()
.border_color(cx.theme().colors.border)
.hover(|this| this.bg(cx.theme().colors.muted_hover))
.hover(|this| this.bg(cx.theme().colors.muted))
.child(
v_flex()
IdentityRow::new(
commit.author.clone(),
commit.author.clone(),
None,
)
.small()
.truncate()
.gap_2()
.flex_none()
.w_32()
.text_color(cx.theme().colors.muted_foreground),
)
.child(
h_flex().w_24().child(
Button::new(format!("browse-commit:{}", commit.id))
.label(short_id(&commit.id))
.variant(ButtonVariant::Ghost)
.side(ButtonSide::Left)
.small()
.tooltip(Tooltip::text(
"Browse files at commit",
))
.on_click(move |_, window, cx| {
cx.stop_propagation();
log_dropped(browse_view.update(
cx,
|this, cx| {
this.browse_commit(
&browse_id, window, cx,
);
},
));
}),
),
)
.child(
div()
.flex_1()
.min_w_0()
.justify_center()
.child(
h_flex()
.gap_2()
.overflow_hidden()
.child(
div()
.text_sm()
.text_color(
cx.theme()
.colors
.muted_foreground,
)
.child(short_id(&commit.id)),
)
.child(
div()
.flex_1()
.min_w_0()
.text_sm()
.text_ellipsis()
.whitespace_nowrap()
.child(commit.summary.clone()),
),
)
.child(
h_flex()
.gap_2()
.text_xs()
.text_color(
cx.theme().colors.muted_foreground,
)
.child(commit.author.clone())
.child(relative_time_secs(commit.time)),
),
.text_ellipsis()
.whitespace_nowrap()
.child(commit.summary.clone()),
)
.child(
div()
.flex_none()
.text_xs()
.text_color(cx.theme().colors.muted_foreground)
.whitespace_nowrap()
.child(relative_time_secs(commit.time)),
)
.when_some(ahead, |row, (ahead_id, path)| {
let detail = detail.clone();
+103 -10
View File
@@ -45,7 +45,7 @@ pub mod refs;
use files::RepoFilesView;
use helpers::{
RepoData, announcement_display_name, bound_repo_label, clone_group, fork_row, load_repo_data,
nostr_clone_url, repo_display_name, snapshot_worktree,
nostr_clone_url, repo_display_name, snapshot_commit, snapshot_worktree,
};
use history::RepoHistoryView;
use refs::RefSwitcher;
@@ -117,6 +117,8 @@ pub struct RepoDetailView {
loading: bool,
error: Option<SharedString>,
head_commit: Option<FileCommit>,
/// The commit whose files are shown in place of the worktree.
browsed_commit: Option<FileCommit>,
refs: RefSwitcher,
tasks: Vec<Task<Result<(), Error>>>,
/// Profiles rendered by the header and maintainers.
@@ -244,6 +246,7 @@ impl RepoDetailView {
loading: true,
error: None,
head_commit: None,
browsed_commit: None,
refs,
tasks: Vec::new(),
directory: ProfileDirectory::new(cx),
@@ -561,9 +564,12 @@ impl RepoDetailView {
self.worktree = Some(worktree.clone());
self.head_commit = head_commit;
self.browsed_commit = None;
self.refs.commit_label = None;
self.files.update(cx, |files, cx| {
files.set_worktree(worktree.clone());
files.pin_commit(None);
files.apply_entries(tree, sorted_worktree_paths(&entries), cx);
files.set_readme(readme_path, readme, cx);
});
@@ -583,6 +589,59 @@ impl RepoDetailView {
self.refs.set_tags(tags, window, cx);
}
/// Shows the files of `commit`, read from the repository at `source`, in place of the worktree.
fn browse_commit(
&mut self,
commit: FileCommit,
source: PathBuf,
window: &mut Window,
cx: &mut Context<Self>,
) {
self.active_section = RepoSection::Files;
self.browsed_commit = Some(commit.clone());
self.refs.show_commit(short_id(&commit.id), window, cx);
cx.notify();
let loaded_id = commit.id.clone();
let shown = source.clone();
let task: Task<Result<(), Error>> = cx.spawn_in(window, async move |this, cx| {
let result = cx
.background_spawn(async move { snapshot_commit(&source, &loaded_id) })
.await;
this.update_in(cx, |this, window, cx| {
// A later pick replaced this one while it loaded.
let current = this
.browsed_commit
.as_ref()
.is_some_and(|current| current.id == commit.id);
if !current {
return;
}
match result {
Ok(tree) => this.files.update(cx, |files, cx| {
files.set_worktree(shown);
files.clear_previews();
files.apply_entries(tree.tree, tree.paths, cx);
files.pin_commit(Some(commit));
files.set_readme(tree.readme_path, tree.readme, cx);
}),
Err(error) => {
this.error = Some(error.to_string().into());
this.reload_worktree(window, cx);
}
}
cx.notify();
})?;
Ok(())
});
self.push_task(task);
}
fn clone_to_folder(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let store = self.store.clone();
@@ -653,6 +712,8 @@ impl RepoDetailView {
return;
};
let name = name.into();
let browsing = self.browsed_commit.is_some();
self.refs.commit_label = None;
// Restored if the checkout fails while HEAD stays detached.
let previous_tag = match kind {
@@ -684,6 +745,13 @@ impl RepoDetailView {
// A failed checkout leaves HEAD alone; report the branch it is still on.
let current = repo.as_ref().ok().and_then(|repo| repo.current_branch());
let checkout = match kind {
// Browsing a commit leaves HEAD alone, so picking its branch again only
// returns to the worktree.
RefKind::Branch
if browsing && current.as_deref() == Some(checkout_name.as_ref()) =>
{
Ok(())
}
RefKind::Branch => {
repo.and_then(|repo| repo.checkout_branch(&checkout_name))
}
@@ -698,7 +766,7 @@ impl RepoDetailView {
this.update_in(cx, |this, window, cx| {
match outcome {
Ok(_) => this.reload_worktree(cx),
Ok(_) => this.reload_worktree(window, cx),
Err((error, current)) => {
this.error = Some(format!("Failed to check out {name}: {error}").into());
this.refs.switching_ref = false;
@@ -714,6 +782,10 @@ impl RepoDetailView {
let tag = if detached { previous_tag } else { None };
this.refs
.restore_selection(&this.refs.tag_select, &tag, window, cx);
if browsing {
this.reload_worktree(window, cx);
}
}
}
cx.notify();
@@ -725,29 +797,43 @@ impl RepoDetailView {
self.push_task(task);
}
fn reload_worktree(&mut self, cx: &mut Context<Self>) {
/// Reloads the worktree, ending a browsed commit.
fn reload_worktree(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let Some(worktree) = self.worktree.clone() else {
return;
};
let task: Task<Result<(), Error>> = cx.spawn(async move |this, cx| {
let displayed = worktree.clone();
let task: Task<Result<(), Error>> = cx.spawn_in(window, async move |this, cx| {
let result = cx
.background_spawn(async move { snapshot_worktree(worktree) })
.await;
this.update(cx, |this, cx| {
this.update_in(cx, |this, window, cx| {
this.refs.switching_ref = false;
this.browsed_commit = None;
this.refs.commit_label = None;
this.files.update(cx, |files, _| files.pin_commit(None));
match result {
Ok((snapshot, tree, paths)) => {
this.head_commit = snapshot.head_commit.clone();
let current_branch = snapshot.current_branch.map(Into::into);
let readme_path = snapshot.readme_path;
let readme = snapshot.readme;
this.files.update(cx, |files, cx| {
files.set_worktree(displayed);
files.clear_previews();
files.apply_entries(tree, paths, cx);
files.set_readme(readme_path, readme, cx);
});
this.refs.restore_selection(
&this.refs.branch_select,
&current_branch,
window,
cx,
);
this.history.update(cx, |history, cx| history.reload(cx));
}
Err(error) => {
@@ -782,9 +868,12 @@ impl RepoDetailView {
this.update(cx, |this, cx| match result {
Ok((snapshot, tree, paths)) => {
this.head_commit = snapshot.head_commit.clone();
this.files.update(cx, |files, cx| {
files.catch_up(&snapshot, tree, paths, cx);
});
// A browsed commit's tree does not follow the worktree.
if this.browsed_commit.is_none() {
this.files.update(cx, |files, cx| {
files.catch_up(&snapshot, tree, paths, cx);
});
}
cx.notify();
}
Err(error) => {
@@ -1434,16 +1523,20 @@ impl RepoDetailView {
}
fn render_last_commit(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
let commit = self.head_commit.as_ref()?;
let commit = self.browsed_commit.as_ref().or(self.head_commit.as_ref())?;
let short = commit.id.get(..8).unwrap_or(&commit.id).to_owned();
let history = self.history.clone();
let commit_id = commit.id.clone();
let tooltip = match self.browsed_commit {
Some(_) => "View commit",
None => "View latest commit",
};
Some(
Button::new("last-commit")
.variant(ButtonVariant::Ghost)
.fully_rounded(true)
.tooltip(Tooltip::text("View latest commit"))
.tooltip(Tooltip::text(tooltip))
.on_click(move |_, window, cx| {
history.update(cx, |history, cx| {
history.open_commit_diff(&commit_id, window, cx);
+17
View File
@@ -11,6 +11,8 @@ pub(super) struct RefSwitcher {
ref_branches: Vec<SharedString>,
ref_tags: Vec<SharedString>,
pub(super) switching_ref: bool,
/// The commit shown in place of the branch while the panel browses one.
pub(super) commit_label: Option<SharedString>,
}
impl RefSwitcher {
@@ -60,6 +62,7 @@ impl RefSwitcher {
ref_branches: Vec::new(),
ref_tags: Vec::new(),
switching_ref: false,
commit_label: None,
}
}
@@ -70,6 +73,13 @@ impl RefSwitcher {
window: &mut Window,
cx: &mut App,
) -> bool {
// A shown commit keeps its label until a ref is picked.
let selected = if self.commit_label.is_some() {
None
} else {
selected
};
sync_selector(
&self.branch_select,
&mut self.ref_branches,
@@ -89,6 +99,13 @@ impl RefSwitcher {
sync_selector(&self.tag_select, &mut self.ref_tags, tags, None, window, cx)
}
/// Shows `label` in the branch selector until a ref is picked.
pub(super) fn show_commit(&mut self, label: SharedString, window: &mut Window, cx: &mut App) {
self.commit_label = Some(label.clone());
self.branch_select
.update(cx, |state, cx| state.set_display_label(label, window, cx));
}
pub(super) fn restore_selection(
&self,
select: &Entity<ComboboxState<SharedString>>,