From 62dcdce77f89b947f2908094f79763ae51ee04ea Mon Sep 17 00:00:00 2001 From: Deng Liu Date: Thu, 26 Nov 2026 14:15:56 -0800 Subject: [PATCH] feat(tools,github): add optional managed GitHub CLI installer --- Cargo.lock | 1 - crates/ide-core/src/tool_path.rs | 32 ++++++++ crates/ide-github/Cargo.toml | 1 - crates/ide-github/src/lib.rs | 55 +++++++++----- crates/ide-host/src/ops/tools.rs | 10 ++- crates/ide-tools/src/jdk.rs | 6 +- crates/ide-tools/src/lib.rs | 13 +++- crates/ide-tools/src/process.rs | 11 +++ crates/ide-tools/src/registry.rs | 74 +++++++++++++++++++ crates/ide-tools/src/sources.rs | 27 +++++++ crates/ide-tools/src/tests.rs | 24 ++++++ docs/en/guide/github.mdx | 8 +- docs/zh/guide/github.mdx | 7 +- .../github/clone/GitHubCloneSource.test.tsx | 25 ++++++- .../github/clone/GitHubCloneSource.tsx | 46 +++++++++--- .../toolwindow/PullRequestsToolWindow.tsx | 32 +++++++- .../github/toolwindow/toolwindow.test.tsx | 24 ++++-- src/platform/ghTool.ts | 55 ++++++++++++++ src/platform/locales/text/en.json | 4 +- src/platform/locales/text/es.json | 1 - src/platform/locales/text/fr.json | 1 - src/platform/locales/text/ko.json | 1 - src/platform/locales/text/pl.json | 1 - src/platform/locales/text/pt.json | 1 - src/platform/locales/text/ru.json | 1 - src/platform/locales/text/tr.json | 1 - src/platform/locales/text/zh-TW.json | 1 - src/platform/locales/text/zh.json | 5 +- 28 files changed, 398 insertions(+), 70 deletions(-) create mode 100644 src/platform/ghTool.ts diff --git a/Cargo.lock b/Cargo.lock index e27dc5f386..8960c68560 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4440,7 +4440,6 @@ dependencies = [ "serde_json", "specta", "tracing", - "which", ] [[package]] diff --git a/crates/ide-core/src/tool_path.rs b/crates/ide-core/src/tool_path.rs index b0c363cf42..44f327884a 100644 --- a/crates/ide-core/src/tool_path.rs +++ b/crates/ide-core/src/tool_path.rs @@ -73,6 +73,38 @@ pub fn find_command(command: &str, search: &OsStr, root: &Path) -> Option Option { + let explicit = std::env::var_os("OPENIDEA_GH").map(PathBuf::from); + find_gh_in(explicit.as_deref(), &search_path(), GH_FALLBACK_PATHS) +} + +/// Locates a pre-installed `gh` outside [`search_path`] (`OPENIDEA_GH`, Windows Program Files, +/// Linux Snap) so tool detection reports it as available without prompting for a duplicate install. +pub fn find_gh_outside_search_path() -> Option { + if let Some(explicit) = std::env::var_os("OPENIDEA_GH").map(PathBuf::from).filter(|p| is_executable(p)) { + return Some(explicit); + } + GH_FALLBACK_PATHS.iter().map(PathBuf::from).find(|p| is_executable(p)) +} + +pub fn find_gh_in(explicit: Option<&Path>, search: &OsStr, fallbacks: &[&str]) -> Option { + if let Some(explicit) = explicit.filter(|p| is_executable(p)) { + return Some(explicit.to_path_buf()); + } + if let Some(found) = find_command("gh", search, Path::new("")) { + return Some(found); + } + fallbacks.iter().map(PathBuf::from).find(|p| is_executable(p)) +} + fn is_executable(path: &Path) -> bool { let Ok(metadata) = path.metadata() else { return false }; #[cfg(unix)] diff --git a/crates/ide-github/Cargo.toml b/crates/ide-github/Cargo.toml index 5d67e56a24..08ea689dc3 100644 --- a/crates/ide-github/Cargo.toml +++ b/crates/ide-github/Cargo.toml @@ -12,4 +12,3 @@ serde.workspace = true serde_json.workspace = true specta.workspace = true tracing.workspace = true -which = "8" diff --git a/crates/ide-github/src/lib.rs b/crates/ide-github/src/lib.rs index 6004a41dff..3bf434694f 100644 --- a/crates/ide-github/src/lib.rs +++ b/crates/ide-github/src/lib.rs @@ -16,30 +16,15 @@ use serde::{Deserialize, Serialize}; use specta::Type; use std::path::{Path, PathBuf}; use std::process::Command; -use std::sync::OnceLock; use std::time::Duration; /// API calls normally answer within a few seconds. const QUICK: Duration = Duration::from_secs(60); -/// Locates the gh executable once per process (GUI apps on macOS have a minimal `PATH`). +/// Locates the gh executable (GUI apps on macOS have a minimal `PATH`, and the IDE can +/// install or remove a managed copy in its tools directory at runtime). pub fn gh_executable() -> Option { - static GH: OnceLock> = OnceLock::new(); - GH.get_or_init(|| { - if let Some(explicit) = std::env::var_os("OPENIDEA_GH").map(PathBuf::from).filter(|p| p.is_file()) { - return Some(explicit); - } - if let Ok(found) = which::which("gh") { - return Some(found); - } - let candidates: &[&str] = if cfg!(windows) { - &[r"C:\Program Files\GitHub CLI\gh.exe"] - } else { - &["/opt/homebrew/bin/gh", "/usr/local/bin/gh", "/usr/bin/gh", "/snap/bin/gh"] - }; - candidates.iter().map(PathBuf::from).find(|p| p.is_file()) - }) - .clone() + ide_core::tool_path::find_gh_executable() } fn command(root: &Path, args: &[&str]) -> IdeResult { @@ -386,3 +371,37 @@ pub fn prepare_diff( let files = repo.diff_files(&base, head_oid)?; Ok(PrDiffRevisions { base, head: head_oid.to_owned(), files, root: ide_core::IpcPath(repo.root().to_path_buf()) }) } + +#[cfg(test)] +mod tests { + #[test] + fn gh_executable_picks_up_newly_installed_binary_without_restart() { + let dir = std::env::temp_dir().join(format!("openidea-gh-test-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let search = std::env::join_paths([&dir]).unwrap(); + assert_eq!(ide_core::tool_path::find_gh_in(None, &search, &[]), None); + + let gh = dir.join(if cfg!(windows) { "gh.exe" } else { "gh" }); + std::fs::write(&gh, "#!/bin/sh\n").unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&gh, std::fs::Permissions::from_mode(0o755)).unwrap(); + } + assert_eq!(ide_core::tool_path::find_gh_in(None, &search, &[]), Some(gh.clone())); + + let explicit = dir.join(if cfg!(windows) { "custom-gh.exe" } else { "custom-gh" }); + std::fs::write(&explicit, "#!/bin/sh\n").unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&explicit, std::fs::Permissions::from_mode(0o755)).unwrap(); + } + assert_eq!(ide_core::tool_path::find_gh_in(Some(&explicit), &search, &[]), Some(explicit)); + + std::fs::remove_file(&gh).unwrap(); + assert_eq!(ide_core::tool_path::find_gh_in(None, &search, &[]), None); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/ide-host/src/ops/tools.rs b/crates/ide-host/src/ops/tools.rs index e3b689e644..fda5d9c65b 100644 --- a/crates/ide-host/src/ops/tools.rs +++ b/crates/ide-host/src/ops/tools.rs @@ -29,15 +29,19 @@ fn tools(host: &Host, window: &str) -> IdeResult { &root, &settings, )); - // Godot is usually an app bundle / Flatpak outside the search path. - let found = ide_sdk::godot::find(None).map(|p| (ide_sdk::godot::COMMAND.to_owned(), p)); + // Godot and GitHub CLI can live in app bundles / MSI / Snap folders outside the search path. + let mut found: std::collections::BTreeMap<_, _> = + ide_sdk::godot::find(None).map(|p| (ide_sdk::godot::COMMAND.to_owned(), p)).into_iter().collect(); + if let Some(gh) = ide_core::tool_path::find_gh_outside_search_path() { + found.insert("gh".to_owned(), gh); + } let runtime = ide_sdk::apply::tool_install_environment(&root, &settings); let work_dir = (!root.as_os_str().is_empty()).then_some(root); Ok(Tools::new(&data) .with_downloads(settings.tool_downloads.clone()) .with_runtime(runtime.commands, runtime.env) .with_custom_paths(custom) - .with_found_paths(found.into_iter().collect()) + .with_found_paths(found) .with_work_dir(work_dir)) } diff --git a/crates/ide-tools/src/jdk.rs b/crates/ide-tools/src/jdk.rs index fc460ce29b..394ea19b60 100644 --- a/crates/ide-tools/src/jdk.rs +++ b/crates/ide-tools/src/jdk.rs @@ -4,7 +4,7 @@ //! without network. use crate::platform::{Arch, Os, Platform}; -use crate::process::{Emit, Http}; +use crate::process::Emit; use crate::sources::Download; use crate::{InstallEvent, InstallGuard, Tools, archive, clear_quarantine, fetch_verified}; use ide_core::error::ErrorKind; @@ -240,10 +240,6 @@ fn unpacked_root(pkg: &Path, home: &Path) -> PathBuf { } impl Tools { - fn http(&self) -> IdeResult { - Http::new(&self.system_path) - } - /// Java versions `vendor` publishes. pub fn jdk_releases(&self, vendor: &str, cancel: &CancellationToken) -> IdeResult { vendor_or_err(vendor)?; diff --git a/crates/ide-tools/src/lib.rs b/crates/ide-tools/src/lib.rs index a8204af060..b85c3c14cf 100644 --- a/crates/ide-tools/src/lib.rs +++ b/crates/ide-tools/src/lib.rs @@ -557,6 +557,10 @@ impl Tools { &self.root } + pub(crate) fn http(&self) -> IdeResult { + Ok(Http::new(&self.system_path)?.with_gh_from(&self.child_path)) + } + /// [`Tools::command`] in the project directory. fn command_in_project(&self, program: impl AsRef) -> Command { let mut cmd = self.command(program); @@ -902,7 +906,7 @@ impl Tools { _ => (ToolStatus::Missing, None, None), } } - _ => match self.which(main) { + _ => match self.which(main).or_else(|| self.found.get(main).cloned()) { Some(path) => { let version = self.query_version(spec, &path); (ToolStatus::OnPath, Some(path), version) @@ -1250,7 +1254,8 @@ impl Tools { dotnet::SDK_DOWNLOAD_URL ))); }; - let pick = Http::new(&self.system_path) + let pick = self + .http() .and_then(|http| dotnet::pick_tool_version(package, sdk.major, |url| http.get_text(url, cancel))); match pick { Ok(dotnet::ToolPick::Latest) => Ok(None), @@ -1542,7 +1547,7 @@ impl Tools { cancel: &CancellationToken, emit: Emit, ) -> IdeResult<()> { - let http = Http::new(&self.system_path)?; + let http = self.http()?; let message = match source { ReleaseSource::GitHubTag { tag, .. } => format!("Resolving release {tag}…"), _ => "Resolving the latest release…".into(), @@ -1683,7 +1688,7 @@ impl Tools { fn latest_version(&self, method: Method, cancel: &CancellationToken) -> IdeResult> { match method { Method::Release { source, assets, .. } => { - let http = Http::new(&self.system_path)?; + let http = self.http()?; Ok(Some(self.resolve_release(&http, source, assets, cancel)?.version)) } Method::Npm { packages } => { diff --git a/crates/ide-tools/src/process.rs b/crates/ide-tools/src/process.rs index 296fc6e732..5017e3ab19 100644 --- a/crates/ide-tools/src/process.rs +++ b/crates/ide-tools/src/process.rs @@ -441,6 +441,17 @@ impl Http { self } + /// Looks up `gh` on `search_path` (e.g. a path that includes IDE-managed tools). + pub(crate) fn with_gh_from(mut self, search_path: &std::ffi::OsStr) -> Self { + self.gh = which::which_in("gh", Some(search_path), ".").ok(); + self + } + + #[cfg(test)] + pub(crate) fn gh_path(&self) -> Option<&Path> { + self.gh.as_deref() + } + /// Skips `GITHUB_TOKEN` / `GH_TOKEN` / `gh auth token` (e.g. retrying a public GitHub endpoint after HTTP 401). pub fn without_github_auth(mut self) -> Self { self.gh = None; diff --git a/crates/ide-tools/src/registry.rs b/crates/ide-tools/src/registry.rs index 0119bbb062..0f4d275dd6 100644 --- a/crates/ide-tools/src/registry.rs +++ b/crates/ide-tools/src/registry.rs @@ -181,6 +181,28 @@ pub static TOOLS: &[ToolSpec] = &[ needs: NODE, homepage: "https://github.com/devcontainers/cli", }, + ToolSpec { + name: "gh", + display: "GitHub CLI", + kind: Cli, + commands: &["gh"], + method: Method::Release { + source: ReleaseSource::GitHub { repo: "cli/cli" }, + assets: &[ + rule(Mac, Arm64, "gh_*_macOS_arm64.zip"), + rule(Mac, X64, "gh_*_macOS_amd64.zip"), + rule(Linux, Arm64, "gh_*_linux_arm64.tar.gz"), + rule(Linux, X64, "gh_*_linux_amd64.tar.gz"), + rule(Windows, Arm64, "gh_*_windows_arm64.zip"), + rule(Windows, X64, "gh_*_windows_amd64.zip"), + ], + locate: &["gh"], + }, + fallback: None, + version: ver("gh"), + needs: &[], + homepage: "https://cli.github.com", + }, ToolSpec { name: "oxfmt", display: "oxfmt", @@ -1483,4 +1505,56 @@ mod tests { let win_arm = Platform { os: Windows, arch: Arm64 }; assert_eq!(select_asset(&names, rules, win_arm), Some("kotlin-server-263.7084.0-aarch64.win.zip")); } + + #[test] + fn gh_release_picks_portable_archive_for_every_supported_platform() { + use crate::platform::{Platform, select_asset}; + let names = [ + "gh_2.106.0_checksums.txt", + "gh_2.106.0_linux_386.deb", + "gh_2.106.0_linux_386.tar.gz", + "gh_2.106.0_linux_amd64.deb", + "gh_2.106.0_linux_amd64.rpm", + "gh_2.106.0_linux_amd64.tar.gz", + "gh_2.106.0_linux_arm64.deb", + "gh_2.106.0_linux_arm64.tar.gz", + "gh_2.106.0_linux_armv6.tar.gz", + "gh_2.106.0_macOS_amd64.zip", + "gh_2.106.0_macOS_arm64.zip", + "gh_2.106.0_macOS_universal.pkg", + "gh_2.106.0_windows_386.zip", + "gh_2.106.0_windows_amd64.msi", + "gh_2.106.0_windows_amd64.zip", + "gh_2.106.0_windows_arm64.msi", + "gh_2.106.0_windows_arm64.zip", + ]; + let spec = find("gh").unwrap(); + assert_eq!(spec.kind, Cli); + let rules = spec.asset_rules(); + for (os, arch, expected) in [ + (Mac, Arm64, "gh_2.106.0_macOS_arm64.zip"), + (Mac, X64, "gh_2.106.0_macOS_amd64.zip"), + (Linux, Arm64, "gh_2.106.0_linux_arm64.tar.gz"), + (Linux, X64, "gh_2.106.0_linux_amd64.tar.gz"), + (Windows, Arm64, "gh_2.106.0_windows_arm64.zip"), + (Windows, X64, "gh_2.106.0_windows_amd64.zip"), + ] { + assert_eq!(select_asset(&names, rules, Platform { os, arch }), Some(expected)); + } + + let Method::Release { locate, .. } = &spec.method else { unreachable!() }; + let tmp = tempfile::tempdir().unwrap(); + let unix_bin = tmp.path().join("gh_2.106.0_macOS_arm64/bin/gh"); + std::fs::create_dir_all(unix_bin.parent().unwrap()).unwrap(); + std::fs::write(&unix_bin, "").unwrap(); + let unix_names: Vec = locate.iter().map(|n| (*n).to_owned()).collect(); + assert_eq!(crate::archive::locate(tmp.path(), &unix_names), Some(unix_bin)); + + let win_dir = tempfile::tempdir().unwrap(); + let win_bin = win_dir.path().join("bin/gh.exe"); + std::fs::create_dir_all(win_bin.parent().unwrap()).unwrap(); + std::fs::write(&win_bin, "").unwrap(); + let win_names: Vec = locate.iter().map(|n| format!("{n}.exe")).collect(); + assert_eq!(crate::archive::locate(win_dir.path(), &win_names), Some(win_bin)); + } } diff --git a/crates/ide-tools/src/sources.rs b/crates/ide-tools/src/sources.rs index 54536347f4..a37213bfe2 100644 --- a/crates/ide-tools/src/sources.rs +++ b/crates/ide-tools/src/sources.rs @@ -147,6 +147,11 @@ fn pick_release( let checksum_url = assets .iter() .find(|c| c.name == format!("{name}.sha256") || c.name == format!("{name}.sha256sum")) + .or_else(|| { + assets + .iter() + .find(|c| c.name.eq_ignore_ascii_case("checksums.txt") || c.name.ends_with("_checksums.txt")) + }) .map(|c| c.url.clone()); return Ok(Download { version, @@ -622,6 +627,28 @@ mod tests { let sums = format!("{} other.zip\n{} *wanted.zip\n", "b".repeat(64), "C".repeat(64)); assert_eq!(parse_checksum(&sums, "wanted.zip"), Some("c".repeat(64))); assert_eq!(parse_checksum(&sums, "missing.zip"), None); + + let gh = serde_json::json!({ + "tag_name": "v2.106.0", + "assets": [ + { + "name": "gh_2.106.0_macOS_arm64.zip", + "browser_download_url": "https://github.com/cli/cli/releases/download/v2.106.0/gh_2.106.0_macOS_arm64.zip" + }, + { + "name": "gh_2.106.0_checksums.txt", + "browser_download_url": "https://github.com/cli/cli/releases/download/v2.106.0/gh_2.106.0_checksums.txt" + } + ] + }) + .to_string(); + let dl = github_pick(&gh, find("gh").unwrap().asset_rules(), MAC_ARM).unwrap(); + assert_eq!(dl.version, "2.106.0"); + assert_eq!(dl.name, "gh_2.106.0_macOS_arm64.zip"); + assert_eq!( + dl.checksum_url.as_deref(), + Some("https://github.com/cli/cli/releases/download/v2.106.0/gh_2.106.0_checksums.txt") + ); } #[test] diff --git a/crates/ide-tools/src/tests.rs b/crates/ide-tools/src/tests.rs index f45461b738..06a141dde6 100644 --- a/crates/ide-tools/src/tests.rs +++ b/crates/ide-tools/src/tests.rs @@ -1428,3 +1428,27 @@ fn a_mirror_never_installs_what_it_alone_vouches_for() { let err = check_sha256(&archive, &dl(Some(&digest)), Some(&"0".repeat(64)), true, &emit).unwrap_err(); assert!(err.message.contains("checksum mismatch"), "{}", err.message); } + +#[cfg(unix)] +#[test] +fn managed_gh_is_detected_on_tools_bin_dirs_and_available_to_http() { + let env = Env::new(); + env.script(&env.sys, "curl", "exit 0"); + let app_data = env.root.parent().unwrap(); + let gh_bin = env.root.join("gh/bin"); + assert!(tools_bin_dirs(app_data).contains(&gh_bin)); + + let missing = env.tools().info("gh", &[]).unwrap(); + assert_eq!(missing.kind, ToolKind::Cli); + assert_eq!(missing.status, ToolStatus::Missing); + assert!(missing.can_install); + + env.script(&gh_bin, "gh", "echo 'gh version 2.106.0 (2026-11-20)'"); + let installed = env.tools().info("gh", &[]).unwrap(); + assert_eq!(installed.status, ToolStatus::Installed); + assert_eq!(installed.version.as_deref(), Some("2.106.0")); + assert!(installed.can_uninstall); + + let http = env.tools().http().unwrap(); + assert_eq!(http.gh_path(), Some(gh_bin.join("gh").as_path())); +} diff --git a/docs/en/guide/github.mdx b/docs/en/guide/github.mdx index 85523ebfca..2c1f9d99c8 100644 --- a/docs/en/guide/github.mdx +++ b/docs/en/guide/github.mdx @@ -9,9 +9,11 @@ OpenIDEA works with GitHub through the [GitHub CLI](https://cli.github.com) (`gh - Install the GitHub CLI. OpenIDEA looks for it in `OPENIDEA_GH` (a full path), then on `PATH`, then in - `/opt/homebrew/bin`, `/usr/local/bin`, `/usr/bin`, `/snap/bin` (macOS/Linux) or `C:\Program Files\GitHub CLI\gh.exe` - (Windows). + Install the GitHub CLI, either from OpenIDEA's **Install GitHub CLI** button (in the **Pull Requests** tool window, + **Clone Repository › GitHub**, **Settings › Agents › GitHub Copilot**, or **Settings › Languages & Frameworks › + Language Servers › Other Tools**) or manually. OpenIDEA looks for it in `OPENIDEA_GH` (a full path), then on `PATH` + (including IDE-managed tools), then in `/opt/homebrew/bin`, `/usr/local/bin`, `/usr/bin`, `/snap/bin` (macOS/Linux) + or `C:\Program Files\GitHub CLI\gh.exe` (Windows). Run `gh auth login` in a terminal. If you open the **Pull Requests** tool window while signed out, it shows **Not diff --git a/docs/zh/guide/github.mdx b/docs/zh/guide/github.mdx index adb4b61886..3378d5af88 100644 --- a/docs/zh/guide/github.mdx +++ b/docs/zh/guide/github.mdx @@ -9,9 +9,10 @@ OpenIDEA 通过 [GitHub CLI](https://cli.github.com)(`gh`)对接 GitHub: - 安装 GitHub CLI。OpenIDEA 依次在 `OPENIDEA_GH`(完整路径)、`PATH`,以及 - `/opt/homebrew/bin`、`/usr/local/bin`、`/usr/bin`、`/snap/bin`(macOS/Linux)或 `C:\Program Files\GitHub - CLI\gh.exe`(Windows)中查找。 + 安装 GitHub CLI:可以直接点击 OpenIDEA 里的 **安装 GitHub CLI** 按钮(位于 **拉取请求** 工具窗口、**克隆仓库 › + GitHub**、**设置 › 智能体 › GitHub Copilot** 或 **设置 › 语言与框架 › 语言服务器 › 其他工具**),也可以手动安装。 + OpenIDEA 依次在 `OPENIDEA_GH`(完整路径)、`PATH`(包含 IDE 管理的工具目录),以及 `/opt/homebrew/bin`、 + `/usr/local/bin`、`/usr/bin`、`/snap/bin`(macOS/Linux)或 `C:\Program Files\GitHub CLI\gh.exe`(Windows)中查找。 在终端运行 `gh auth login`。未登录时打开 **拉取请求** 工具窗口,会显示 **未登录 GitHub** 和 **运行 gh auth login** diff --git a/src/features/github/clone/GitHubCloneSource.test.tsx b/src/features/github/clone/GitHubCloneSource.test.tsx index b8b6f181d3..9c1614343f 100644 --- a/src/features/github/clone/GitHubCloneSource.test.tsx +++ b/src/features/github/clone/GitHubCloneSource.test.tsx @@ -2,13 +2,18 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react"; const ghAccountRepos = vi.fn(); +const toolsList = vi.fn(); vi.mock("@/platform/ipc", async (importOriginal) => ({ ...(await importOriginal()), isTauri: () => true, - commands: { ghAccountRepos: () => ghAccountRepos() }, + commands: { + ghAccountRepos: () => ghAccountRepos(), + toolsList: () => toolsList(), + }, })); import type { GhAccountRepo } from "@/bindings"; +import { registerAction } from "@/platform/actions"; import { GitHubCloneSource, matchRepos } from "./GitHubCloneSource"; const repo = (nameWithOwner: string, extra: Partial = {}): GhAccountRepo => ({ @@ -25,6 +30,7 @@ const repos = [repo("me/app", { private: true, description: "The app" }), repo(" afterEach(() => { cleanup(); ghAccountRepos.mockReset(); + toolsList.mockReset(); }); describe("GitHub clone source", () => { @@ -64,4 +70,21 @@ describe("GitHub clone source", () => { fireEvent.click(screen.getByRole("button", { name: "Retry" })); await waitFor(() => expect(screen.getByRole("option", { name: /me\/app/ })).toBeInTheDocument()); }); + + it("installs GitHub CLI in-app when missing and reloads repositories", async () => { + const install = vi.fn().mockResolvedValue(undefined); + const dispose = registerAction({ id: "tools.install", title: "Install", run: install }); + ghAccountRepos.mockResolvedValueOnce({ status: "ok", data: { kind: "notInstalled" } }); + toolsList.mockResolvedValue({ status: "ok", data: [{ name: "gh", status: "installed" }] }); + ghAccountRepos.mockResolvedValueOnce({ status: "ok", data: { kind: "ready", login: "me", repos } }); + try { + render( {}} onClone={() => {}} disabled={false} />); + expect(await screen.findByText("GitHub CLI is not installed")).toBeInTheDocument(); + fireEvent.click(screen.getByRole("button", { name: "Install GitHub CLI" })); + await waitFor(() => expect(install).toHaveBeenCalledWith(expect.objectContaining({ arg: "gh" }))); + await waitFor(() => expect(screen.getByRole("option", { name: /me\/app/ })).toBeInTheDocument()); + } finally { + dispose(); + } + }); }); diff --git a/src/features/github/clone/GitHubCloneSource.tsx b/src/features/github/clone/GitHubCloneSource.tsx index 1bec8493fe..b1a22bfdbe 100644 --- a/src/features/github/clone/GitHubCloneSource.tsx +++ b/src/features/github/clone/GitHubCloneSource.tsx @@ -1,8 +1,9 @@ /** Clone Repository › GitHub: the repositories of the account gh is signed in to. */ import { useEffect, useMemo, useState, type KeyboardEvent } from "react"; import type { GhAccountRepo, GhAccountRepos } from "@/bindings"; +import { GH_MANUAL_INSTALL_URL, installGhTool } from "@/platform/ghTool"; import { tx } from "@/platform/i18n"; -import { call, commands } from "@/platform/ipc"; +import { call, commands, isCancelled } from "@/platform/ipc"; import { Button, EmptyState, @@ -37,6 +38,8 @@ export function GitHubCloneSource({ url, onUrl, onClone, disabled }: CloneSource const [state, setState] = useState(null); const [query, setQuery] = useState(""); const [attempt, setAttempt] = useState(0); + const [installingGh, setInstallingGh] = useState(false); + const [installError, setInstallError] = useState(null); useEffect(() => { let alive = true; @@ -50,14 +53,26 @@ export function GitHubCloneSource({ url, onUrl, onClone, disabled }: CloneSource const rows = useMemo(() => (state?.kind === "ready" ? matchRepos(state.repos, query) : []), [state, query]); const active = rows.findIndex((r) => r.repo.cloneUrl === url); + const reload = () => { + setInstallError(null); + setState(null); + setAttempt((n) => n + 1); + }; + const installGh = () => { + if (installingGh) return; + setInstallingGh(true); + setInstallError(null); + void installGhTool() + .promise.then((installed) => { + if (installed) reload(); + }) + .catch((e: unknown) => { + if (!isCancelled(e)) setInstallError(e instanceof Error ? e.message : String(e)); + }) + .finally(() => setInstallingGh(false)); + }; const retry = ( - ); @@ -77,15 +92,24 @@ export function GitHubCloneSource({ url, onUrl, onClone, disabled }: CloneSource title="GitHub CLI is not installed" actions={ <> - + {retry} } > GitHub repositories are listed with the gh command line tool. Install it, then run{" "} - gh auth login. + gh auth login.{installError &&
{installError}
} ); if (state.kind === "notLoggedIn") diff --git a/src/features/github/toolwindow/PullRequestsToolWindow.tsx b/src/features/github/toolwindow/PullRequestsToolWindow.tsx index 74f7d3c7b0..04d3d74874 100644 --- a/src/features/github/toolwindow/PullRequestsToolWindow.tsx +++ b/src/features/github/toolwindow/PullRequestsToolWindow.tsx @@ -7,6 +7,8 @@ import { useEffect, useRef, useState, type RefObject } from "react"; import type { GhAvailability } from "@/platform/ipc"; import { executeAction } from "@/platform/actions"; +import { GH_MANUAL_INSTALL_URL, installGhTool } from "@/platform/ghTool"; +import { isCancelled } from "@/platform/ipc"; import { tx } from "@/platform/i18n"; import { Button, EmptyState, IconButton, Select, Spinner, Tabs, T, showContextMenu, type MenuItem } from "@/ui"; import { CreatePanel } from "../create/CreatePanel"; @@ -28,6 +30,21 @@ import { closeTab, selectTab, tabId, useGhTabs, type GhTabId } from "./store"; import styles from "./ToolWindow.module.css"; function Unavailable({ availability }: { availability: GhAvailability }) { + const [installingGh, setInstallingGh] = useState(false); + const [installError, setInstallError] = useState(null); + const installGh = () => { + if (installingGh) return; + setInstallingGh(true); + setInstallError(null); + void installGhTool() + .promise.then((installed) => { + if (installed) void refreshConnection(); + }) + .catch((e: unknown) => { + if (!isCancelled(e)) setInstallError(e instanceof Error ? e.message : String(e)); + }) + .finally(() => setInstallingGh(false)); + }; const retry = ( + {retry} } > Pull requests use the gh command line tool. Install it, then run{" "} - gh auth login. + gh auth login.{installError &&
{installError}
} ); case "notLoggedIn": diff --git a/src/features/github/toolwindow/toolwindow.test.tsx b/src/features/github/toolwindow/toolwindow.test.tsx index fd40645f40..7c701db20e 100644 --- a/src/features/github/toolwindow/toolwindow.test.tsx +++ b/src/features/github/toolwindow/toolwindow.test.tsx @@ -1,12 +1,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { act, render, screen } from "@testing-library/react"; -import { getAction } from "@/platform/actions"; +import { act, fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { getAction, registerAction } from "@/platform/actions"; import { getContext } from "@/platform/context"; import * as ipc from "@/platform/ipc"; import { provideToolWindowService, useContributions, type ToolWindowService } from "@/workbench/contributions"; import { activate } from "../index"; import { setCurrentRepository } from "../api/client"; import type { GHRepository, GHUser } from "../api/types"; +import * as repositoryData from "../data/repository"; import { useGhRepository } from "../data/repository"; import { PullRequestsTabs, PullRequestsToolWindow } from "./PullRequestsToolWindow"; import { @@ -122,10 +123,21 @@ describe("tool window", () => { expect(show).toHaveBeenCalledWith("pullRequests", true); }); - it("shows gh's state when it is not ready", () => { - useGhRepository.setState({ availability: { kind: "notInstalled" } }); - render(); - expect(screen.getByText("GitHub CLI is not installed")).toBeTruthy(); + it("shows gh's state when it is not ready and installs gh on click", async () => { + const install = vi.fn().mockResolvedValue(undefined); + const dispose = registerAction({ id: "tools.install", title: "Install", run: install }); + const refresh = vi.spyOn(repositoryData, "refreshConnection").mockResolvedValue(undefined); + try { + useGhRepository.setState({ availability: { kind: "notInstalled" } }); + render(); + expect(screen.getByText("GitHub CLI is not installed")).toBeTruthy(); + fireEvent.click(screen.getByRole("button", { name: "Install GitHub CLI" })); + await waitFor(() => expect(install).toHaveBeenCalledWith(expect.objectContaining({ arg: "gh" }))); + await waitFor(() => expect(refresh).toHaveBeenCalledOnce()); + } finally { + refresh.mockRestore(); + dispose(); + } }); it("offers the repository selector for several GitHub remotes", () => { diff --git a/src/platform/ghTool.ts b/src/platform/ghTool.ts new file mode 100644 index 0000000000..75f3cf517b --- /dev/null +++ b/src/platform/ghTool.ts @@ -0,0 +1,55 @@ +/** + * Optional GitHub CLI (`gh`) installer shared by GitHub Pull Requests, + * Clone Repository › GitHub, and Settings › Agents › GitHub Copilot. + * Uses the `tools.install` action when available (workbench window, for + * status-bar progress and notifications) and falls back to `commands.toolsInstall` + * directly in standalone windows such as Settings. + */ +import { Channel } from "@tauri-apps/api/core"; +import { executeAction, getAction } from "./actions"; +import { call, commands, isTauri, nextRequestId, type InstallEvent, type ToolInfo } from "./ipc"; + +const GH_TOOL_NAME = "gh"; +export const GH_MANUAL_INSTALL_URL = "https://cli.github.com"; + +interface GhInstallHandle { + promise: Promise; + /** Cancels a direct install; null when delegated to the `tools.install` task queue. */ + cancel: (() => void) | null; +} + +/** Returns the `ide-tools` entry for `gh`, or null outside the desktop app or on lookup error. */ +async function getGhToolInfo(): Promise { + if (!isTauri()) return null; + try { + const tools = await call(commands.toolsList()); + return tools.find((tool) => tool.name === GH_TOOL_NAME) ?? null; + } catch { + return null; + } +} + +/** + * Installs `gh` into OpenIDEA's managed tools directory. Resolves to `true` when + * `gh` is available afterwards, or `false` if cancelled or not installed. + * Propagates errors when running directly (the `tools.install` action reports + * its own errors via notifications). + */ +export function installGhTool(onEvent?: (event: InstallEvent) => void): GhInstallHandle { + if (getAction("tools.install")) { + const promise = (async () => { + await executeAction("tools.install", GH_TOOL_NAME); + const info = await getGhToolInfo(); + return info ? info.status !== "missing" : true; + })(); + return { promise, cancel: null }; + } + const request = nextRequestId(); + const channel = new Channel(); + channel.onmessage = (event) => onEvent?.(event); + const promise = call(commands.toolsInstall(GH_TOOL_NAME, request, channel)).then((info) => info.status !== "missing"); + return { + promise, + cancel: () => void commands.cancelRequest(request).catch(() => {}), + }; +} diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 019702e843..89b2203aeb 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -4178,5 +4178,7 @@ "SQL DELETE": "SQL DELETE", "SVG editor layout": "SVG editor layout", "Resize SVG preview": "Resize SVG preview", - "The SVG source is not valid.": "The SVG source is not valid." + "The SVG source is not valid.": "The SVG source is not valid.", + "Install GitHub CLI": "Install GitHub CLI", + "Download manually…": "Download manually…" } diff --git a/src/platform/locales/text/es.json b/src/platform/locales/text/es.json index 80c772af32..fbead74afd 100644 --- a/src/platform/locales/text/es.json +++ b/src/platform/locales/text/es.json @@ -1081,7 +1081,6 @@ "Install a plugin folder with": "Instala una carpeta de complemento con", "Install and Debug": "Instalar y depurar", "Reinstall and Debug": "Reinstalar y depurar", - "Install gh…": "Instalar gh…", "Installed": "Instalados", "Installed packages": "Paquetes instalados", "Installed plugins": "Complementos instalados", diff --git a/src/platform/locales/text/fr.json b/src/platform/locales/text/fr.json index 331f5340e3..aacf157b82 100644 --- a/src/platform/locales/text/fr.json +++ b/src/platform/locales/text/fr.json @@ -1019,7 +1019,6 @@ "Install a plugin folder with": "Installez un dossier de plugin avec", "Install and Debug": "Installer et déboguer", "Reinstall and Debug": "Réinstaller et déboguer", - "Install gh…": "Installer gh…", "Installed": "Installés", "Installed packages": "Paquets installés", "Installed plugins": "Plugins installés", diff --git a/src/platform/locales/text/ko.json b/src/platform/locales/text/ko.json index d9da6430d0..f886c0bd9f 100644 --- a/src/platform/locales/text/ko.json +++ b/src/platform/locales/text/ko.json @@ -1117,7 +1117,6 @@ "Install a plugin folder with": "다음으로 플러그인 폴더 설치", "Install and Debug": "설치 및 디버그", "Reinstall and Debug": "다시 설치 및 디버그", - "Install gh…": "gh 설치…", "Installed": "설치됨", "Installed packages": "설치된 패키지", "Installed plugins": "설치된 플러그인", diff --git a/src/platform/locales/text/pl.json b/src/platform/locales/text/pl.json index b83b2d382c..025d6405e5 100644 --- a/src/platform/locales/text/pl.json +++ b/src/platform/locales/text/pl.json @@ -1073,7 +1073,6 @@ "Install a plugin folder with": "Zainstaluj folder wtyczki za pomocą", "Install and Debug": "Zainstaluj i debuguj", "Reinstall and Debug": "Zainstaluj ponownie i debuguj", - "Install gh…": "Zainstaluj gh…", "Installed": "Zainstalowane", "Installed packages": "Zainstalowane pakiety", "Installed plugins": "Zainstalowane wtyczki", diff --git a/src/platform/locales/text/pt.json b/src/platform/locales/text/pt.json index 26a1d94726..30f2450ab0 100644 --- a/src/platform/locales/text/pt.json +++ b/src/platform/locales/text/pt.json @@ -1073,7 +1073,6 @@ "Install a plugin folder with": "Instalar uma pasta de plugin com", "Install and Debug": "Instalar e depurar", "Reinstall and Debug": "Reinstalar e depurar", - "Install gh…": "Instalar gh…", "Installed": "Instalados", "Installed packages": "Pacotes instalados", "Installed plugins": "Plugins instalados", diff --git a/src/platform/locales/text/ru.json b/src/platform/locales/text/ru.json index 8392637f06..12f0db0955 100644 --- a/src/platform/locales/text/ru.json +++ b/src/platform/locales/text/ru.json @@ -2144,7 +2144,6 @@ "Install a plugin folder with": "Установить папку плагина с", "Install and Debug": "Установить и отладить", "Reinstall and Debug": "Переустановить и отладить", - "Install gh…": "Установить gh…", "Installed": "Установлено", "Installed packages": "Установленные пакеты", "Installed plugins": "Установленные плагины", diff --git a/src/platform/locales/text/tr.json b/src/platform/locales/text/tr.json index fdddd2daff..b96ff8dd5d 100644 --- a/src/platform/locales/text/tr.json +++ b/src/platform/locales/text/tr.json @@ -3839,7 +3839,6 @@ "Install a plugin folder with": "Şu klasörden eklenti yükle:", "Install and Debug": "Yükle ve Hata Ayıkla", "Reinstall and Debug": "Yeniden Yükle ve Hata Ayıkla", - "Install gh…": "gh Yükle…", "Installed": "Yüklü", "Installed packages": "Yüklü paketler", "Installed plugins": "Yüklü eklentiler", diff --git a/src/platform/locales/text/zh-TW.json b/src/platform/locales/text/zh-TW.json index 1ea34631ff..0f2a2cc226 100644 --- a/src/platform/locales/text/zh-TW.json +++ b/src/platform/locales/text/zh-TW.json @@ -1765,7 +1765,6 @@ "Install a plugin folder with": "安裝外掛資料夾:", "Install and Debug": "安裝並偵錯", "Reinstall and Debug": "重新安裝並偵錯", - "Install gh…": "安裝 gh…", "Installed": "已安裝", "Installed packages": "已安裝的軟體包", "Installed plugins": "已安裝的外掛", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 9ffe84fe44..5d865d7950 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -2220,7 +2220,6 @@ "Install a plugin folder with": "安装插件文件夹:", "Install and Debug": "安装并调试", "Reinstall and Debug": "重新安装并调试", - "Install gh…": "安装 gh…", "Installed": "已安装", "Installed packages": "已安装的软件包", "Installed plugins": "已安装的插件", @@ -10628,5 +10627,7 @@ "Column comment": "列注释", "SVG editor layout": "SVG 编辑器布局", "Resize SVG preview": "调整 SVG 预览大小", - "The SVG source is not valid.": "SVG 源代码无效。" + "The SVG source is not valid.": "SVG 源代码无效。", + "Install GitHub CLI": "安装 GitHub CLI", + "Download manually…": "手动下载…" }