diff --git a/CHANGELOG.md b/CHANGELOG.md index d907a19..f34e9ba 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ ### Added - Add a confirmation dialog before deleting a repository +- Browse the files of a commit as of that commit from the Commits list, the short id on a row shows the commit's files in place of the worktree and the branch selector shows the commit until a branch or tag is picked again ### Changed @@ -14,6 +15,7 @@ - Reuse the rendered file tree, commit diffs, README previews and split pane instead of rebuilding them on every repaint - Truncate long tab and file tree labels with an ellipsis instead of letting them widen their row - Open the New issue form in a split panel instead of a dialog, it now stays open until the issue is published and shows a failed publish in the form +- Show each commit of the Commits list on one row with its author avatar and name, short id and summary ### Fixed diff --git a/crates/signed_app/src/repo/files.rs b/crates/signed_app/src/repo/files.rs index 0bc427a..5a6f944 100644 --- a/crates/signed_app/src/repo/files.rs +++ b/crates/signed_app/src/repo/files.rs @@ -38,6 +38,20 @@ enum FileContent { Failed(String), } +impl FileContent { + /// Classifies raw bytes, refusing files too large to preview. + fn from_bytes(bytes: Vec) -> 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, @@ -72,6 +86,8 @@ pub struct RepoFilesView { commits: HashMap, pending_commits: Vec, loading_commits: bool, + /// The commit whose tree is browsed instead of the worktree. + commit: Option, tasks: Vec>>, /// 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) { + self.commit = commit; + } + pub fn apply_entries( &mut self, tree: Vec, @@ -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) { + // 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; } diff --git a/crates/signed_app/src/repo/helpers.rs b/crates/signed_app/src/repo/helpers.rs index 7e8c99e..3312980 100644 --- a/crates/signed_app/src/repo/helpers.rs +++ b/crates/signed_app/src/repo/helpers.rs @@ -85,6 +85,14 @@ pub(super) struct RepoData { pub(super) head_commit: Option, } +/// A commit's tree and README, as the file explorer shows them. +pub(super) struct CommitTree { + pub(super) tree: Vec, + pub(super) paths: Vec, + pub(super) readme_path: Option, + pub(super) readme: Option>, +} + /// Sorted relative paths of a worktree snapshot. pub(crate) fn sorted_worktree_paths(entries: &[PathBuf]) -> Vec { let mut paths: Vec = 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 { + 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() diff --git a/crates/signed_app/src/repo/history.rs b/crates/signed_app/src/repo/history.rs index b7e1a8c..d168404 100644 --- a/crates/signed_app/src/repo/history.rs +++ b/crates/signed_app/src/repo/history.rs @@ -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) { + // 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(); diff --git a/crates/signed_app/src/repo/mod.rs b/crates/signed_app/src/repo/mod.rs index 764ce63..4bb2b9d 100644 --- a/crates/signed_app/src/repo/mod.rs +++ b/crates/signed_app/src/repo/mod.rs @@ -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, head_commit: Option, + /// The commit whose files are shown in place of the worktree. + browsed_commit: Option, refs: RefSwitcher, tasks: Vec>>, /// 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.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> = 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) { 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) { + /// Reloads the worktree, ending a browsed commit. + fn reload_worktree(&mut self, window: &mut Window, cx: &mut Context) { let Some(worktree) = self.worktree.clone() else { return; }; - let task: Task> = cx.spawn(async move |this, cx| { + let displayed = worktree.clone(); + + let task: Task> = 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, + ¤t_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) -> Option { - 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); diff --git a/crates/signed_app/src/repo/refs.rs b/crates/signed_app/src/repo/refs.rs index fd60ca3..3217f20 100644 --- a/crates/signed_app/src/repo/refs.rs +++ b/crates/signed_app/src/repo/refs.rs @@ -11,6 +11,8 @@ pub(super) struct RefSwitcher { ref_branches: Vec, ref_tags: Vec, pub(super) switching_ref: bool, + /// The commit shown in place of the branch while the panel browses one. + pub(super) commit_label: Option, } 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>, diff --git a/crates/signed_git/src/repo.rs b/crates/signed_git/src/repo.rs index 3617335..159be1e 100644 --- a/crates/signed_git/src/repo.rs +++ b/crates/signed_git/src/repo.rs @@ -1084,15 +1084,48 @@ impl Repo { /// Lists every worktree path relative to the root, directories first. pub fn entries(&self) -> Result> { let workdir = self.inner.workdir().context("repository has no worktree")?; - let mut entries: Vec<(PathBuf, bool)> = Vec::new(); - Self::collect_entries(workdir, workdir, &mut entries)?; + Self::collect_entries(workdir, workdir, &mut entries)?; + Self::sort_entries(&mut entries); + + Ok(entries.into_iter().map(|(path, _)| path).collect()) + } + + /// Sorts directories before files, each alphabetically. + fn sort_entries(entries: &mut [(PathBuf, bool)]) { entries.sort_by(|(a, a_is_dir), (b, b_is_dir)| { b_is_dir .cmp(a_is_dir) .then_with(|| a.as_os_str().cmp(b.as_os_str())) }); + } + + /// Lists every path in the tree of commit `id`, directories first like `entries`. + pub fn entries_at(&self, id: &str) -> Result> { + let commit_id = self.inner.rev_parse_single(id.as_bytes())?; + let tree = commit_id.object()?.into_commit().tree()?; + + let mut entries: Vec<(PathBuf, bool)> = Vec::new(); + for entry in tree.traverse().breadthfirst.files()? { + if !entry.mode.is_blob() { + continue; + } + + let path = gix::path::from_bstring(entry.filepath); + for dir in path + .ancestors() + .skip(1) + .filter(|dir| !dir.as_os_str().is_empty()) + { + entries.push((dir.to_path_buf(), true)); + } + entries.push((path, false)); + } + + Self::sort_entries(&mut entries); + entries.dedup_by(|a, b| a.0 == b.0); + Ok(entries.into_iter().map(|(path, _)| path).collect()) } @@ -1109,22 +1142,48 @@ impl Repo { } } + /// Reads a file from the tree of commit `id`, or `None` when it has no file at `rel`. + pub fn read_at(&self, id: &str, rel: &Path) -> Result>> { + let commit_id = self.inner.rev_parse_single(id.as_bytes())?; + let tree = commit_id.object()?.into_commit().tree()?; + + match tree.lookup_entry_by_path(rel)? { + Some(entry) if entry.mode().is_blob() => { + let mut blob = entry.object()?; + Ok(Some(std::mem::take(&mut blob.data))) + } + _ => Ok(None), + } + } + /// Finds the top-level README, preferring markdown extensions. pub fn find_readme(&self) -> Result> { let Some(workdir) = self.inner.workdir() else { return Ok(None); }; - let mut candidates: Vec = Vec::new(); + let mut names = Vec::new(); for entry in std::fs::read_dir(workdir)? { - let entry = entry?; - let name = entry.file_name(); - let Some(name) = name.to_str() else { continue }; - if name.to_ascii_lowercase().starts_with("readme") { - candidates.push(entry.path()); - } + names.push(PathBuf::from(entry?.file_name())); } + Ok(Self::pick_readme(&names)) + } + + /// The top-level README among `entries`, preferring markdown extensions. + pub fn pick_readme(entries: &[PathBuf]) -> Option { + let mut candidates: Vec = entries + .iter() + .filter(|path| { + path.components().count() == 1 + && path + .file_name() + .and_then(|name| name.to_str()) + .is_some_and(|name| name.to_ascii_lowercase().starts_with("readme")) + }) + .cloned() + .collect(); + candidates.sort_by_key(|path| { let ext = path .extension() @@ -1139,10 +1198,7 @@ impl Repo { } }); - Ok(candidates - .into_iter() - .next() - .and_then(|path| path.strip_prefix(workdir).ok().map(Path::to_path_buf))) + candidates.into_iter().next() } /// Captures worktree entries, README, and ref state in one pass. diff --git a/crates/signed_git/src/tests.rs b/crates/signed_git/src/tests.rs index 74dff0f..a56f6c9 100644 --- a/crates/signed_git/src/tests.rs +++ b/crates/signed_git/src/tests.rs @@ -992,3 +992,72 @@ fn parses_real_format_patch_output() { assert_eq!(file.insertions, 0); assert_eq!(file.deletions, 0); } + +#[test] +fn entries_at_lists_a_commits_files_directories_first() { + let (_dir, repo) = fixture(&[ + ("README", b"plain"), + ("docs/README.md", b"# Docs"), + ("notes.txt", b"one"), + ("readme.md", b"# Title"), + ("src/lib.rs", b"fn old() {}"), + ]); + commit_all(&repo, "initial"); + let first = repo.head_commit().expect("head").expect("commit").id; + + let expected = vec![ + PathBuf::from("docs"), + PathBuf::from("src"), + PathBuf::from("README"), + PathBuf::from("docs/README.md"), + PathBuf::from("notes.txt"), + PathBuf::from("readme.md"), + PathBuf::from("src/lib.rs"), + ]; + + let entries = repo.entries_at(&first).expect("entries"); + assert_eq!(entries, expected); + assert_eq!(repo.entries().expect("entries"), expected); + assert_eq!( + Repo::pick_readme(&entries).as_deref(), + Some(Path::new("readme.md")) + ); + assert_eq!( + repo.find_readme().expect("readme").as_deref(), + Some(Path::new("readme.md")) + ); +} + +#[test] +fn read_at_reads_the_files_of_that_commit() { + let (dir, repo) = fixture(&[("notes.txt", b"one"), ("src/lib.rs", b"fn old() {}")]); + commit_all(&repo, "initial"); + let first = repo.head_commit().expect("head").expect("commit").id; + + std::fs::write(dir.path().join("src/lib.rs"), b"fn new() {}").expect("write"); + std::fs::remove_file(dir.path().join("notes.txt")).expect("remove"); + commit_all(&repo, "second"); + let second = repo.head_commit().expect("head").expect("commit").id; + + assert_eq!( + repo.read_at(&first, Path::new("src/lib.rs")) + .expect("read") + .as_deref(), + Some(b"fn old() {}".as_slice()) + ); + assert_eq!( + repo.read_at(&second, Path::new("src/lib.rs")) + .expect("read") + .as_deref(), + Some(b"fn new() {}".as_slice()) + ); + assert_eq!( + repo.read_at(&second, Path::new("notes.txt")).expect("read"), + None + ); + assert_eq!(repo.read_at(&second, Path::new("src")).expect("read"), None); + assert!( + repo.read_at("0000000000000000000000000000000000000000", Path::new("src")) + .is_err() + ); +} diff --git a/crates/ui/src/components/combobox.rs b/crates/ui/src/components/combobox.rs index 4a16a39..c4c8e5a 100644 --- a/crates/ui/src/components/combobox.rs +++ b/crates/ui/src/components/combobox.rs @@ -180,6 +180,8 @@ where options: Vec>, /// The chosen value. `None` while the text names nothing. selected: Option, + /// A label shown in the field in place of a chosen option. + display_label: Option, query: Entity, /// Indices into `options` that survived the filter, in popup row order. visible: Vec, @@ -241,6 +243,7 @@ where placeholder: combobox.placeholder, options: combobox.options, selected: combobox.selected, + display_label: None, query, visible, highlight: None, @@ -262,6 +265,7 @@ where /// Replaces the value; reports it when it actually changed. pub fn set_selected(&mut self, value: Option, window: &mut Window, cx: &mut Context) { let changed = self.selected != value; + self.display_label = None; self.set_value(value, window, cx); if changed { let label = self.selected_label().unwrap_or_default(); @@ -279,13 +283,34 @@ where window: &mut Window, cx: &mut Context, ) { - if self.selected == value { + if self.selected == value && self.display_label.is_none() { return; } + + self.display_label = None; self.selected = value; + let label = self.selected_label().unwrap_or_default(); - self.query - .update(cx, |query, cx| query.set_value_silent(label, window, cx)); + self.query.update(cx, |query, cx| { + query.set_value_silent(label, window, cx); + }); + self.refilter(""); + + cx.notify(); + } + + /// Shows `label` in the field in place of the choice, reporting nothing; a choice replaces it. + pub fn set_display_label( + &mut self, + label: SharedString, + window: &mut Window, + cx: &mut Context, + ) { + self.selected = None; + self.display_label = Some(label.clone()); + self.query.update(cx, |query, cx| { + query.set_value_silent(label.to_string(), window, cx) + }); self.refilter(""); cx.notify(); } @@ -298,13 +323,16 @@ where cx.notify(); } - /// The label of the chosen option, if there is one. + /// The label of the chosen option, or the display label's. fn selected_label(&self) -> Option { - let selected = self.selected.as_ref()?; - self.options - .iter() - .find(|(value, _)| value == selected) - .map(|(_, label)| label.clone()) + if let Some(selected) = &self.selected { + return self + .options + .iter() + .find(|(value, _)| value == selected) + .map(|(_, label)| label.clone()); + } + self.display_label.clone() } /// Recomputes `visible` for `query` and clamps the highlight onto it. @@ -329,6 +357,7 @@ where if self.selected == value { return; } + self.display_label = None; self.selected = value.clone(); if let Some(on_change) = self.on_change.clone() { let value = value.clone(); @@ -526,7 +555,9 @@ where if state.highlight.is_some() { state.highlight = None; } else { - if state.selected.is_some() { + if state.selected.is_some() + || state.display_label.is_some() + { state.refilter(""); } else { let query =