дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-04 01:01:17 +02:00
Порівняти коміти
1
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
62dcdce77f |
No files matched your search
Створено
@@ -4440,7 +4440,6 @@ dependencies = [
|
||||
"serde_json",
|
||||
"specta",
|
||||
"tracing",
|
||||
"which",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
@@ -73,6 +73,38 @@ pub fn find_command(command: &str, search: &OsStr, root: &Path) -> Option<PathBu
|
||||
dirs.into_iter().find_map(|dir| names.iter().map(|name| dir.join(name)).find(|p| is_executable(p)))
|
||||
}
|
||||
|
||||
const GH_FALLBACK_PATHS: &[&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"]
|
||||
};
|
||||
|
||||
/// Locates `gh` across `OPENIDEA_GH`, [`search_path`] (which includes IDE-managed tools
|
||||
/// only when installed, then the user's `PATH`), and standard OS install locations.
|
||||
pub fn find_gh_executable() -> Option<PathBuf> {
|
||||
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<PathBuf> {
|
||||
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<PathBuf> {
|
||||
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)]
|
||||
|
||||
@@ -12,4 +12,3 @@ serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
specta.workspace = true
|
||||
tracing.workspace = true
|
||||
which = "8"
|
||||
@@ -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<PathBuf> {
|
||||
static GH: OnceLock<Option<PathBuf>> = 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<Command> {
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -29,15 +29,19 @@ fn tools(host: &Host, window: &str) -> IdeResult<Tools> {
|
||||
&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))
|
||||
}
|
||||
|
||||
|
||||
@@ -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> {
|
||||
Http::new(&self.system_path)
|
||||
}
|
||||
|
||||
/// Java versions `vendor` publishes.
|
||||
pub fn jdk_releases(&self, vendor: &str, cancel: &CancellationToken) -> IdeResult<JdkReleases> {
|
||||
vendor_or_err(vendor)?;
|
||||
|
||||
@@ -557,6 +557,10 @@ impl Tools {
|
||||
&self.root
|
||||
}
|
||||
|
||||
pub(crate) fn http(&self) -> IdeResult<Http> {
|
||||
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<std::ffi::OsStr>) -> 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<Option<String>> {
|
||||
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 } => {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<String> = 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<String> = locate.iter().map(|n| format!("{n}.exe")).collect();
|
||||
assert_eq!(crate::archive::locate(win_dir.path(), &win_names), Some(win_bin));
|
||||
}
|
||||
}
|
||||
@@ -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]
|
||||
|
||||
@@ -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()));
|
||||
}
|
||||
@@ -9,9 +9,11 @@ OpenIDEA works with GitHub through the [GitHub CLI](https://cli.github.com) (`gh
|
||||
|
||||
<Steps>
|
||||
<Step title="Install 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).
|
||||
</Step>
|
||||
<Step title="Sign in">
|
||||
Run `gh auth login` in a terminal. If you open the **Pull Requests** tool window while signed out, it shows **Not
|
||||
|
||||
@@ -9,9 +9,10 @@ OpenIDEA 通过 [GitHub CLI](https://cli.github.com)(`gh`)对接 GitHub:
|
||||
|
||||
<Steps>
|
||||
<Step title="安装 gh">
|
||||
安装 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)中查找。
|
||||
</Step>
|
||||
<Step title="登录">
|
||||
在终端运行 `gh auth login`。未登录时打开 **拉取请求** 工具窗口,会显示 **未登录 GitHub** 和 **运行 gh auth login**
|
||||
|
||||
@@ -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<typeof import("@/platform/ipc")>()),
|
||||
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> = {}): 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(<GitHubCloneSource url="" onUrl={() => {}} 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();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -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<GhAccountRepos | null>(null);
|
||||
const [query, setQuery] = useState("");
|
||||
const [attempt, setAttempt] = useState(0);
|
||||
const [installingGh, setInstallingGh] = useState(false);
|
||||
const [installError, setInstallError] = useState<string | null>(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 = (
|
||||
<Button
|
||||
size="small"
|
||||
onClick={() => {
|
||||
setState(null);
|
||||
setAttempt((n) => n + 1);
|
||||
}}
|
||||
>
|
||||
<Button size="small" onClick={reload}>
|
||||
<T>Retry</T>
|
||||
</Button>
|
||||
);
|
||||
@@ -77,15 +92,24 @@ export function GitHubCloneSource({ url, onUrl, onClone, disabled }: CloneSource
|
||||
title="GitHub CLI is not installed"
|
||||
actions={
|
||||
<>
|
||||
<Button size="small" onClick={() => void openInBrowser("https://cli.github.com")}>
|
||||
<T>Install gh…</T>
|
||||
<Button size="small" variant="primary" disabled={installingGh} onClick={installGh}>
|
||||
{installingGh ? (
|
||||
<>
|
||||
<Spinner size={12} /> <T>Installing…</T>
|
||||
</>
|
||||
) : (
|
||||
<T>Install GitHub CLI</T>
|
||||
)}
|
||||
</Button>
|
||||
<Button size="small" onClick={() => void openInBrowser(GH_MANUAL_INSTALL_URL)}>
|
||||
<T>Download manually…</T>
|
||||
</Button>
|
||||
{retry}
|
||||
</>
|
||||
}
|
||||
>
|
||||
<T>GitHub repositories are listed with the</T> <code>gh</code> <T>command line tool. Install it, then run</T>{" "}
|
||||
<code>gh auth login</code>.
|
||||
<code>gh auth login</code>.{installError && <div className={styles.muted}>{installError}</div>}
|
||||
</EmptyState>
|
||||
);
|
||||
if (state.kind === "notLoggedIn")
|
||||
|
||||
@@ -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<string | null>(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 = (
|
||||
<Button size="small" onClick={() => void refreshConnection()}>
|
||||
<T>Retry</T>
|
||||
@@ -40,15 +57,24 @@ function Unavailable({ availability }: { availability: GhAvailability }) {
|
||||
title="GitHub CLI is not installed"
|
||||
actions={
|
||||
<>
|
||||
<Button size="small" onClick={() => void openInBrowser("https://cli.github.com")}>
|
||||
<T>Install gh…</T>
|
||||
<Button size="small" variant="primary" disabled={installingGh} onClick={installGh}>
|
||||
{installingGh ? (
|
||||
<>
|
||||
<Spinner size={12} /> <T>Installing…</T>
|
||||
</>
|
||||
) : (
|
||||
<T>Install GitHub CLI</T>
|
||||
)}
|
||||
</Button>
|
||||
<Button size="small" onClick={() => void openInBrowser(GH_MANUAL_INSTALL_URL)}>
|
||||
<T>Download manually…</T>
|
||||
</Button>
|
||||
{retry}
|
||||
</>
|
||||
}
|
||||
>
|
||||
<T>Pull requests use the</T> <code>gh</code> <T>command line tool. Install it, then run</T>{" "}
|
||||
<code>gh auth login</code>.
|
||||
<code>gh auth login</code>.{installError && <div className={styles.hint}>{installError}</div>}
|
||||
</EmptyState>
|
||||
);
|
||||
case "notLoggedIn":
|
||||
|
||||
@@ -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(<PullRequestsToolWindow />);
|
||||
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(<PullRequestsToolWindow />);
|
||||
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", () => {
|
||||
|
||||
@@ -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<boolean>;
|
||||
/** 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<ToolInfo | null> {
|
||||
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<InstallEvent>();
|
||||
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(() => {}),
|
||||
};
|
||||
}
|
||||
@@ -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…"
|
||||
}
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -1117,7 +1117,6 @@
|
||||
"Install a plugin folder with": "다음으로 플러그인 폴더 설치",
|
||||
"Install and Debug": "설치 및 디버그",
|
||||
"Reinstall and Debug": "다시 설치 및 디버그",
|
||||
"Install gh…": "gh 설치…",
|
||||
"Installed": "설치됨",
|
||||
"Installed packages": "설치된 패키지",
|
||||
"Installed plugins": "설치된 플러그인",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -2144,7 +2144,6 @@
|
||||
"Install a plugin folder with": "Установить папку плагина с",
|
||||
"Install and Debug": "Установить и отладить",
|
||||
"Reinstall and Debug": "Переустановить и отладить",
|
||||
"Install gh…": "Установить gh…",
|
||||
"Installed": "Установлено",
|
||||
"Installed packages": "Установленные пакеты",
|
||||
"Installed plugins": "Установленные плагины",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -1765,7 +1765,6 @@
|
||||
"Install a plugin folder with": "安裝外掛資料夾:",
|
||||
"Install and Debug": "安裝並偵錯",
|
||||
"Reinstall and Debug": "重新安裝並偵錯",
|
||||
"Install gh…": "安裝 gh…",
|
||||
"Installed": "已安裝",
|
||||
"Installed packages": "已安裝的軟體包",
|
||||
"Installed plugins": "已安裝的外掛",
|
||||
|
||||
@@ -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…": "手动下载…"
|
||||
}
|
||||
Reference in new issue
Заблокувати користувача