mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-18 08:09:25 +00:00
fix(git-toolbox): show the focused file's branch in workspace windows (#3159)
In a workspace window the plugin asked vcs_status of the window's project, the workspace container, which is usually not a git repository, so the branch item disappeared and Fetch Now fetched nothing. Git Toolbox now resolves the editor-focused file to the deepest open project containing it and shows that repository, falling back to the window's project, the one shown last, then the first open one. Fetch Now fetches only the repository the status bar shows. Covered by plugin unit tests and a host e2e test with a two-member workspace. Fixes #2556 Co-authored-by: Inf1mum <8135225+Inf1mum@users.noreply.github.com>
This commit is contained in:
@@ -2609,6 +2609,82 @@ fn git_toolbox_does_not_fetch_untrusted_projects() {
|
||||
assert!(err.contains("Restricted Mode"), "{err}");
|
||||
}
|
||||
|
||||
/// Git Toolbox in a workspace window whose container folder is not a
|
||||
/// repository (every member is its own clone): the status bar follows the
|
||||
/// focused file's repository, and the scheduled fetch covers every member.
|
||||
#[test]
|
||||
fn official_git_toolbox_follows_members_in_a_workspace() {
|
||||
let f = fixture(Limits { idle_timeout: Some(Duration::from_millis(50)), ..Limits::default() });
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
// A remote with `main`, cloned by member `a` (at `main`) and member `b`
|
||||
// (on its own branch, to tell the two apart in the status bar).
|
||||
let remote = tmp.path().join("remote.git");
|
||||
std::fs::create_dir(&remote).unwrap();
|
||||
git(&remote, &["init", "--bare", "-b", "main"]);
|
||||
let seed = tmp.path().join("seed");
|
||||
std::fs::create_dir(&seed).unwrap();
|
||||
git(&seed, &["init", "-b", "main"]);
|
||||
std::fs::write(seed.join("seed.txt"), "seed\n").unwrap();
|
||||
git(&seed, &["add", "."]);
|
||||
git(&seed, &["commit", "-m", "one"]);
|
||||
git(&seed, &["remote", "add", "origin", remote.to_str().unwrap()]);
|
||||
git(&seed, &["push", "-u", "origin", "main"]);
|
||||
let member_a = tmp.path().join("member-a");
|
||||
git(tmp.path(), &["clone", remote.to_str().unwrap(), member_a.to_str().unwrap()]);
|
||||
let member_a = dunce::canonicalize(member_a).unwrap();
|
||||
let member_b = tmp.path().join("member-b");
|
||||
git(tmp.path(), &["clone", remote.to_str().unwrap(), member_b.to_str().unwrap()]);
|
||||
let member_b = dunce::canonicalize(member_b).unwrap();
|
||||
git(&member_b, &["checkout", "-b", "feature"]);
|
||||
git(&member_b, &["push", "-u", "origin", "feature"]);
|
||||
// The window's project is the container; the members are attached to it.
|
||||
f.workspace.other_roots.lock().extend([member_a.clone(), member_b.clone()]);
|
||||
|
||||
f.install(&official("git-toolbox"));
|
||||
let item = |host: &PluginHost| {
|
||||
host.status_items().into_iter().find(|(p, id, _)| p == "openidea.git-toolbox" && id == "branch")
|
||||
};
|
||||
let now = Instant::now();
|
||||
let focus = |path: &Path| {
|
||||
f.host
|
||||
.post_events(Some("main"), vec![WorkbenchEvent::EditorFocused(Some(path.to_string_lossy().into_owned()))]);
|
||||
f.host.flush_events_at(now + Duration::from_secs(3));
|
||||
f.host.wait_events(Duration::from_secs(10));
|
||||
};
|
||||
// Focusing a file of member `a` shows that member's branch: the window's
|
||||
// project is the container, which is no repository.
|
||||
focus(&member_a.join("seed.txt"));
|
||||
assert_eq!(item(&f.host).map(|(_, _, i)| i.text), Some("main".into()));
|
||||
// Fetch Now fetches the shown member; the container is not a repository.
|
||||
f.run("openidea.git-toolbox", "fetch", None).unwrap();
|
||||
let fetched = stored(&f, "openidea.git-toolbox");
|
||||
assert!(
|
||||
fetched.iter().any(|(key, _)| key == &format!("last-fetch:{}", to_ipc(&member_a))),
|
||||
"{member_a:?}: {fetched:?}"
|
||||
);
|
||||
assert_eq!(fetched.iter().filter(|(key, _)| key.starts_with("last-fetch:")).count(), 1, "{fetched:?}");
|
||||
// Switching to the other member follows it.
|
||||
focus(&member_b.join("seed.txt"));
|
||||
assert_eq!(item(&f.host).map(|(_, _, i)| i.text), Some("feature".into()));
|
||||
|
||||
// Idle: reclaimed; the schedule then wakes it to fetch every member (the
|
||||
// container is skipped: it has no repository).
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
f.host.tick();
|
||||
assert_eq!(item(&f.host).map(|(_, _, i)| i.text), Some("feature".into()), "the item stays while it sleeps");
|
||||
f.take_events();
|
||||
f.host.tick_at(Instant::now() + Duration::from_secs(301));
|
||||
assert!(f.host.wait_events(Duration::from_secs(30)));
|
||||
let fetched = stored(&f, "openidea.git-toolbox");
|
||||
for member in [&member_a, &member_b] {
|
||||
assert!(
|
||||
fetched.iter().any(|(key, _)| key == &format!("last-fetch:{}", to_ipc(member))),
|
||||
"{member:?}: {fetched:?}"
|
||||
);
|
||||
}
|
||||
assert_eq!(item(&f.host).map(|(_, _, i)| i.text), Some("feature".into()));
|
||||
}
|
||||
|
||||
/// A tiny HTTP server: each request is answered after `delay(n)` (n counts
|
||||
/// requests) with `body`. Returns its port and the request bodies it got.
|
||||
fn http_server(
|
||||
|
||||
BIN
Binary file not shown.
+1
-1
@@ -1 +1 @@
|
||||
63847067fc7b9931a3d697d8e6649cea04a0af7ad02d57e26a38f9acb2e6fcdd
|
||||
d6991b9065d8b623efdf9c03fb92b4875e95e666b3dadb3925ff5ad327f5fdcb
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Git Toolbox for OpenIDEA: background fetch of every open project's
|
||||
//! repository (on the plugin's `on-schedule`, which also fires after the
|
||||
//! instance was reclaimed while idle), and the focused project's branch with
|
||||
//! instance was reclaimed while idle), and the focused file's branch with
|
||||
//! its ahead/behind counts in the status bar.
|
||||
|
||||
use openidea_plugin::host::{self, storage};
|
||||
@@ -14,7 +14,12 @@ const LAST_FETCH: &str = "last-fetch:";
|
||||
const SHOWN: &str = "shown-root";
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct GitToolbox;
|
||||
pub struct GitToolbox {
|
||||
/// The focused editor's file path, from the last `editor-focused` event.
|
||||
/// Kept across events: the status bar keeps following that file's
|
||||
/// repository until another file takes focus.
|
||||
focused: Option<String>,
|
||||
}
|
||||
|
||||
fn now_secs() -> u64 {
|
||||
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
|
||||
@@ -67,31 +72,51 @@ fn tooltip(s: &RepositoryStatus) -> String {
|
||||
lines.join("\n")
|
||||
}
|
||||
|
||||
/// Shows `project`'s repository in the status bar (or hides the item).
|
||||
fn show(project: &Project) -> Result<(), Error> {
|
||||
match project.vcs_status()? {
|
||||
Some(s) => {
|
||||
/// Shows the first of `projects` that has a repository in the status bar (the
|
||||
/// item hides when none has). Returns the index of the one shown.
|
||||
fn show(projects: &[Project]) -> Result<Option<usize>, Error> {
|
||||
for (i, project) in projects.iter().enumerate() {
|
||||
if let Some(s) = project.vcs_status()? {
|
||||
let _ = storage::set(SHOWN, &project.root()?);
|
||||
host::set_status_item(
|
||||
ITEM,
|
||||
&StatusItem { text: label(&s), tooltip: Some(tooltip(&s)), command: Some("fetch".into()) },
|
||||
);
|
||||
return Ok(Some(i));
|
||||
}
|
||||
None => host::remove_status_item(ITEM),
|
||||
}
|
||||
Ok(())
|
||||
host::remove_status_item(ITEM);
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// The project the status bar follows: the invoking window's, else the one
|
||||
/// shown last, else the first open one.
|
||||
fn current(ctx: &Invocation) -> Option<Project> {
|
||||
if let Some(p) = ctx.project() {
|
||||
return Some(p);
|
||||
impl GitToolbox {
|
||||
/// The projects the status bar may follow, most specific first: the
|
||||
/// focused file's repository (a workspace window's project is the
|
||||
/// container folder, and its focused files belong to member
|
||||
/// repositories), the invoking window's, the one shown last, else the
|
||||
/// first open one.
|
||||
fn candidates(&self, ctx: &Invocation) -> Vec<Project> {
|
||||
let mut out: Vec<Project> = Vec::new();
|
||||
let editor = ctx.editor().map(|e| e.path());
|
||||
let mut push = |project: Option<Project>| {
|
||||
if let Some(p) = project
|
||||
&& let Ok(root) = p.root()
|
||||
&& out.iter().all(|q| q.root() != Ok(root.clone()))
|
||||
{
|
||||
out.push(p);
|
||||
}
|
||||
};
|
||||
push(self.focused.as_deref().or(editor.as_deref()).and_then(host::project_of));
|
||||
push(ctx.project());
|
||||
let projects = host::projects().unwrap_or_default();
|
||||
let shown = storage::get(SHOWN).ok().flatten();
|
||||
let index = projects.iter().position(|p| p.root().ok().as_deref() == shown.as_deref()).unwrap_or(0);
|
||||
let mut rest = projects;
|
||||
if index < rest.len() {
|
||||
push(Some(rest.swap_remove(index)));
|
||||
}
|
||||
out
|
||||
}
|
||||
let projects = host::projects().ok()?;
|
||||
let shown = storage::get(SHOWN).ok().flatten();
|
||||
let index = projects.iter().position(|p| p.root().ok() == shown).unwrap_or(0);
|
||||
projects.into_iter().nth(index)
|
||||
}
|
||||
|
||||
/// Fetches `projects` in one cancellable task. Returns how many were fetched.
|
||||
@@ -131,15 +156,22 @@ fn fetch(projects: &[Project]) -> Result<usize, Error> {
|
||||
|
||||
impl Plugin for GitToolbox {
|
||||
fn run_command(&mut self, id: &str, ctx: &Invocation, _arg: Option<&str>) -> Result<Option<String>, Error> {
|
||||
let project = current(ctx).ok_or("no project is open")?;
|
||||
let projects = self.candidates(ctx);
|
||||
if projects.is_empty() {
|
||||
return Err("no project is open".into());
|
||||
}
|
||||
match id {
|
||||
"fetch" => {
|
||||
let n = fetch(std::slice::from_ref(&project))?;
|
||||
show(&project)?;
|
||||
// Only the repository the status bar shows, not every candidate.
|
||||
let Some(i) = show(&projects)? else {
|
||||
return Ok(Some("The project is not in a git repository.".to_owned()));
|
||||
};
|
||||
let n = fetch(std::slice::from_ref(&projects[i]))?;
|
||||
show(&projects)?;
|
||||
Ok((n == 0).then(|| "The project is not in a git repository.".to_owned()))
|
||||
}
|
||||
"refresh" => {
|
||||
show(&project)?;
|
||||
show(&projects)?;
|
||||
Ok(None)
|
||||
}
|
||||
_ => Err(Error::NotFound(format!("command {id}"))),
|
||||
@@ -155,9 +187,12 @@ impl Plugin for GitToolbox {
|
||||
host::notify(NotificationLevel::Warning, "Git Toolbox: fetch failed", &e.to_string());
|
||||
}
|
||||
}
|
||||
if let Some(p) = current(ctx) {
|
||||
let _ = show(&p);
|
||||
for e in events {
|
||||
if let Event::EditorFocused(Some(path)) = e {
|
||||
self.focused = Some(path.clone());
|
||||
}
|
||||
}
|
||||
let _ = show(&self.candidates(ctx));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -195,7 +230,7 @@ mod tests {
|
||||
let host = MockHost::install();
|
||||
host.add_project("/other");
|
||||
host.set_vcs_status(Some(status(0, 4)));
|
||||
GitToolbox.handle_events(&[Event::Scheduled], &host.invocation());
|
||||
GitToolbox::default().handle_events(&[Event::Scheduled], &host.invocation());
|
||||
assert_eq!(host.fetches(), 2, "every open project");
|
||||
let item = &host.status_items()["branch"];
|
||||
assert_eq!(item.text, "main ↓4");
|
||||
@@ -208,26 +243,72 @@ mod tests {
|
||||
#[test]
|
||||
fn focus_changes_only_refresh() {
|
||||
let host = MockHost::install();
|
||||
let mut plugin = GitToolbox::default();
|
||||
host.set_vcs_status(Some(status(1, 0)));
|
||||
GitToolbox.handle_events(&[Event::EditorFocused(Some("/project/a.rs".into()))], &host.invocation());
|
||||
plugin.handle_events(&[Event::EditorFocused(Some("/project/a.rs".into()))], &host.invocation());
|
||||
assert_eq!(host.fetches(), 0);
|
||||
assert_eq!(host.status_items()["branch"].text, "main ↑1");
|
||||
host.set_vcs_status(None);
|
||||
GitToolbox.handle_events(&[Event::VcsChanged("/project".into())], &host.invocation());
|
||||
plugin.handle_events(&[Event::VcsChanged("/project".into())], &host.invocation());
|
||||
assert!(host.status_items().is_empty(), "not a repository any more");
|
||||
}
|
||||
|
||||
/// A workspace window's project is the container folder, which is no
|
||||
/// repository: the focused file's member repository is shown instead, and
|
||||
/// follows the focus between members.
|
||||
#[test]
|
||||
fn workspace_windows_follow_the_focused_members_repository() {
|
||||
let host = MockHost::install();
|
||||
let mut plugin = GitToolbox::default();
|
||||
host.set_project_root(Some("/workspace"));
|
||||
host.add_project("/repos/a");
|
||||
host.add_project("/repos/b");
|
||||
host.set_vcs_status(Some(status(1, 2)));
|
||||
plugin.handle_events(&[Event::EditorFocused(Some("/repos/a/src/main.rs".into()))], &host.invocation());
|
||||
assert_eq!(host.storage()["shown-root"], "/repos/a", "the focused file's member, not the container");
|
||||
assert_eq!(host.status_items()["branch"].text, "main ↑1 ↓2");
|
||||
plugin.handle_events(&[Event::EditorFocused(Some("/repos/b/src/lib.rs".into()))], &host.invocation());
|
||||
assert_eq!(host.storage()["shown-root"], "/repos/b", "the focus moved to the other member");
|
||||
// A scheduled tick keeps following the focused member.
|
||||
plugin.handle_events(&[Event::Scheduled], &host.invocation());
|
||||
assert_eq!(host.storage()["shown-root"], "/repos/b");
|
||||
}
|
||||
|
||||
/// Fetch Now fetches the repository the status bar shows, not every
|
||||
/// other open project.
|
||||
#[test]
|
||||
fn fetch_now_fetches_only_the_shown_repository() {
|
||||
let host = MockHost::install();
|
||||
host.add_project("/other");
|
||||
storage::set(SHOWN, "/other").unwrap();
|
||||
host.set_vcs_status(Some(status(0, 0)));
|
||||
GitToolbox::default().run_command("fetch", &host.invocation(), None).unwrap();
|
||||
assert_eq!(host.fetches(), 1);
|
||||
assert_eq!(host.storage()["shown-root"], "/project");
|
||||
}
|
||||
|
||||
/// A focused path outside every open project falls back to the window's
|
||||
/// project, whose repository is shown as before.
|
||||
#[test]
|
||||
fn an_unresolvable_focused_path_falls_back_to_the_window_project() {
|
||||
let host = MockHost::install();
|
||||
host.set_vcs_status(Some(status(0, 0)));
|
||||
GitToolbox::default().handle_events(&[Event::EditorFocused(Some("src/main.rs".into()))], &host.invocation());
|
||||
assert_eq!(host.storage()["shown-root"], "/project");
|
||||
assert_eq!(host.status_items()["branch"].text, "main");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failures_and_cancellation() {
|
||||
let host = MockHost::install();
|
||||
host.set_vcs_status(Some(status(0, 0)));
|
||||
host.fail_fetch(Some(Error::Failed("no network".into())));
|
||||
GitToolbox.handle_events(&[Event::Scheduled], &host.invocation());
|
||||
GitToolbox::default().handle_events(&[Event::Scheduled], &host.invocation());
|
||||
assert_eq!(host.notifications()[0].body, "no network");
|
||||
let err = GitToolbox.run_command("fetch", &host.invocation(), None).unwrap_err();
|
||||
let err = GitToolbox::default().run_command("fetch", &host.invocation(), None).unwrap_err();
|
||||
assert_eq!(err, Error::Failed("no network".into()));
|
||||
host.fail_fetch(Some(Error::Cancelled));
|
||||
GitToolbox.handle_events(&[Event::Scheduled], &host.invocation());
|
||||
GitToolbox::default().handle_events(&[Event::Scheduled], &host.invocation());
|
||||
assert_eq!(host.notifications().len(), 1, "a cancelled fetch is not an error to report");
|
||||
}
|
||||
|
||||
@@ -235,7 +316,7 @@ mod tests {
|
||||
fn without_vcs_write_it_still_shows_the_branch() {
|
||||
let host = MockHost::install().with_capabilities(&["project.read", "vcs.read", "storage"]);
|
||||
host.set_vcs_status(Some(status(0, 1)));
|
||||
GitToolbox.handle_events(&[Event::Scheduled], &host.invocation());
|
||||
GitToolbox::default().handle_events(&[Event::Scheduled], &host.invocation());
|
||||
assert!(host.notifications()[0].body.contains("vcs.write"));
|
||||
assert_eq!(host.status_items()["branch"].text, "main ↓1");
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user