дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-04 17:21:13 +02:00
Порівняти коміти
1
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
f25740f14d |
No files matched your search
Створено
+2
-3
@@ -12152,15 +12152,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "zip"
|
||||
version = "9.2.3"
|
||||
version = "9.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "00fb4744e923442ecadfd3f85f51a5d24e03bf43d53813b81ebb4c91d02baa62"
|
||||
checksum = "1156b39d142a34b999c2310a50455e0cb3760bf7efad0122f796d813bee26ccb"
|
||||
dependencies = [
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
"getrandom 0.4.3",
|
||||
"indexmap 2.14.2",
|
||||
"libc",
|
||||
"memchr",
|
||||
"nix 0.31.3",
|
||||
"typed-path",
|
||||
|
||||
+1
-1
@@ -82,7 +82,7 @@ trash = "5"
|
||||
blake3 = "1"
|
||||
dunce = "1"
|
||||
dirs = "6"
|
||||
zip = { version = "9.2.3", default-features = false, features = ["deflate"] }
|
||||
zip = { version = "9", default-features = false, features = ["deflate"] }
|
||||
|
||||
# search, index, language
|
||||
grep-searcher = "0.1"
|
||||
|
||||
@@ -18,7 +18,6 @@ semver = "1"
|
||||
blake3.workspace = true
|
||||
zip.workspace = true
|
||||
base64.workspace = true
|
||||
dunce.workspace = true
|
||||
ed25519-dalek = "3"
|
||||
|
||||
[dev-dependencies]
|
||||
|
||||
@@ -441,13 +441,11 @@ pub fn resolve_program(name: &str, path_var: Option<&OsStr>) -> Result<PathBuf,
|
||||
/// `p` with its parent canonicalized but the file name as found: PATH
|
||||
/// entries like `/var` → `/private/var` (macOS) or `~` links collapse to
|
||||
/// their real directory, while a linked program (`cargo` → rustup) keeps
|
||||
/// its link name so the shim still dispatches on argv[0]. `dunce` keeps the
|
||||
/// path in its usual form on Windows: a `\\?\`-prefixed pin would never
|
||||
/// match the path the program was actually started with.
|
||||
/// its link name so the shim still dispatches on argv[0].
|
||||
fn canonical_dir(p: &Path) -> PathBuf {
|
||||
let Some(dir) = p.parent() else { return p.to_path_buf() };
|
||||
let Some(name) = p.file_name() else { return p.to_path_buf() };
|
||||
dunce::canonicalize(dir).map(|d| d.join(name)).unwrap_or_else(|_| p.to_path_buf())
|
||||
std::fs::canonicalize(dir).map(|d| d.join(name)).unwrap_or_else(|_| p.to_path_buf())
|
||||
}
|
||||
|
||||
fn is_executable(p: &Path) -> bool {
|
||||
@@ -500,20 +498,6 @@ mod tests {
|
||||
list.iter().map(|s| s.parse().unwrap()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(windows)]
|
||||
fn pinned_program_path_has_no_verbatim_prefix() {
|
||||
// std::fs::canonicalize returns \\?\-prefixed paths on Windows; a pin
|
||||
// stored in that form would never match the plain path the program is
|
||||
// started with. dunce keeps the usual form.
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::write(dir.path().join("cargo.exe"), b"").unwrap();
|
||||
let pinned = resolve_program("cargo.exe", Some(dir.path().as_os_str())).unwrap();
|
||||
let shown = pinned.to_string_lossy();
|
||||
assert!(!shown.starts_with(r"\\?\"), "verbatim prefix leaked into the pin: {shown}");
|
||||
assert!(pinned.is_absolute());
|
||||
}
|
||||
|
||||
fn req<'a>(version: &'a str, hash: &'a str, required: &[&str], optional: &[&str]) -> Request<'a> {
|
||||
Request {
|
||||
subject: Subject::Installed("p".into()),
|
||||
|
||||
@@ -52,8 +52,6 @@ fn search_dirs(file: Option<&Path>, root: Option<&Path>) -> Vec<PathBuf> {
|
||||
}
|
||||
|
||||
fn parse_env(text: &str) -> IdeResult<EnvMap> {
|
||||
// Editors on Windows (Notepad) save UTF-8 with a byte order mark, which serde_json rejects.
|
||||
let text = text.strip_prefix('\u{feff}').unwrap_or(text);
|
||||
let value: serde_json::Value =
|
||||
serde_json::from_str(text).map_err(|e| IdeError::invalid(format!("invalid environment file: {e}")))?;
|
||||
let mut out = EnvMap::new();
|
||||
@@ -264,12 +262,4 @@ mod tests {
|
||||
let envs = Environments::load(Some(&other.path().join("s.http")), Some(root)).unwrap();
|
||||
assert_eq!(envs.names(), vec!["dev"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_env_files_saved_with_a_byte_order_mark() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
std::fs::write(tmp.path().join(PUBLIC_FILE), "\u{feff}{\"dev\":{\"host\":\"h\"}}").unwrap();
|
||||
let envs = Environments::load(Some(&tmp.path().join("a.http")), Some(tmp.path())).unwrap();
|
||||
assert_eq!(envs.names(), vec!["dev"]);
|
||||
}
|
||||
}
|
||||
@@ -1228,48 +1228,6 @@ mod tests {
|
||||
}
|
||||
zip.finish().unwrap();
|
||||
}
|
||||
#[test]
|
||||
fn explodes_wars_with_multibyte_path_components() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let war = tmp.path().join("app.war");
|
||||
let entries = [
|
||||
("bdms300-front/dist/img/ZC机柜.jpg", "reported case"),
|
||||
("img/A机柜.jpg", "one ASCII byte"),
|
||||
("img/😀.jpg", "four-byte character"),
|
||||
("img/abé.jpg", "two-byte character"),
|
||||
("ZC机柜/index.jsp", "multibyte directory"),
|
||||
("img/普通.jpg", "character boundary"),
|
||||
];
|
||||
archive(&war, &entries);
|
||||
for resources_only in [false, true] {
|
||||
let destination = tmp.path().join(format!("out-{resources_only}"));
|
||||
explode(&war, &destination, resources_only).unwrap();
|
||||
for (name, text) in entries {
|
||||
assert_eq!(fs::read_to_string(destination.join(name)).unwrap(), text, "{name}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_war_path_traversal() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let war = tmp.path().join("app.war");
|
||||
archive(&war, &[("../escape.txt", "outside")]);
|
||||
assert!(explode(&war, &tmp.path().join("out"), false).is_err());
|
||||
assert!(!tmp.path().join("escape.txt").exists());
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn rejects_war_reserved_device_paths() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let war = tmp.path().join("app.war");
|
||||
for name in ["CON.txt", "NUL", "COM1.txt", "LPT¹", "img/aux.jpg"] {
|
||||
archive(&war, &[(name, "device")]);
|
||||
assert!(explode(&war, &tmp.path().join("out"), false).is_err(), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_apps_own_context_descriptor() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -99,15 +99,8 @@ fn config(line: &str) -> RunConfig {
|
||||
}
|
||||
|
||||
fn holder_port(dir: &std::path::Path) -> u16 {
|
||||
// The file appears as soon as the holder creates it, before the port is written and
|
||||
// the handle closed: on a loaded machine (defender, indexer) the first reads can hit
|
||||
// a sharing violation or a partial write, so keep reading until it parses.
|
||||
let mut port = None;
|
||||
wait_for("the holder's port", || {
|
||||
port = std::fs::read_to_string(dir.join("port")).ok().and_then(|s| s.trim().parse().ok());
|
||||
port.is_some()
|
||||
});
|
||||
port.unwrap()
|
||||
wait_for("the holder's port", || std::fs::metadata(dir.join("port")).is_ok());
|
||||
std::fs::read_to_string(dir.join("port")).unwrap().trim().parse().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -101,22 +101,6 @@ fn new_id() -> String {
|
||||
uuid::Uuid::new_v4().to_string()
|
||||
}
|
||||
|
||||
/// Runs a credential-store operation off the async runtime.
|
||||
///
|
||||
/// The Linux Secret Service client is blocking (`zbus`) and starts a runtime of
|
||||
/// its own; calling it while a runtime already drives the current thread panics
|
||||
/// with "Cannot start a runtime from within a runtime". The store may also wait
|
||||
/// on an OS prompt, so run it on a plain thread when called from async code.
|
||||
fn off_runtime<R: Send>(f: impl FnOnce() -> R + Send) -> R {
|
||||
if tokio::runtime::Handle::try_current().is_err() {
|
||||
return f();
|
||||
}
|
||||
std::thread::scope(|scope| match scope.spawn(f).join() {
|
||||
Ok(value) => value,
|
||||
Err(panic) => std::panic::resume_unwind(panic),
|
||||
})
|
||||
}
|
||||
|
||||
impl SecretFile {
|
||||
pub fn new(path: PathBuf) -> Self {
|
||||
Self::with_legacy(path, |v| serde_json::from_value(v).ok())
|
||||
@@ -131,95 +115,85 @@ impl SecretFile {
|
||||
}
|
||||
|
||||
pub fn get(&self, key: &str) -> Option<String> {
|
||||
off_runtime(|| {
|
||||
let _g = LOCK.lock();
|
||||
match self.load() {
|
||||
Contents::Index(mut index) if index.keys.contains(key) => {
|
||||
match self.vault.get(&service(&index.id), key) {
|
||||
Ok(secret) => Some(secret),
|
||||
Err(StoreError::NoEntry) => {
|
||||
// Removed outside the app: stop listing it.
|
||||
index.keys.remove(key);
|
||||
self.write_logged(&index);
|
||||
None
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("saved passwords: {key}: {e}");
|
||||
None
|
||||
}
|
||||
}
|
||||
let _g = LOCK.lock();
|
||||
match self.load() {
|
||||
Contents::Index(mut index) if index.keys.contains(key) => match self.vault.get(&service(&index.id), key) {
|
||||
Ok(secret) => Some(secret),
|
||||
Err(StoreError::NoEntry) => {
|
||||
// Removed outside the app: stop listing it.
|
||||
index.keys.remove(key);
|
||||
self.write_logged(&index);
|
||||
None
|
||||
}
|
||||
Contents::Index(_) => None,
|
||||
Contents::Plaintext(mut old, _) => old.remove(key),
|
||||
}
|
||||
})
|
||||
Err(e) => {
|
||||
tracing::warn!("saved passwords: {key}: {e}");
|
||||
None
|
||||
}
|
||||
},
|
||||
Contents::Index(_) => None,
|
||||
Contents::Plaintext(mut old, _) => old.remove(key),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set(&self, key: &str, secret: &str) -> IdeResult<()> {
|
||||
off_runtime(|| {
|
||||
let _g = LOCK.lock();
|
||||
let mut index = match self.load() {
|
||||
Contents::Index(index) => index,
|
||||
Contents::Plaintext(_, why) => return Err(unavailable(&why)),
|
||||
};
|
||||
let service = service(&index.id);
|
||||
self.vault.set(&service, key, secret).map_err(|e| unavailable(&e.to_string()))?;
|
||||
if index.keys.insert(key.to_owned())
|
||||
&& let Err(e) = self.write(&index)
|
||||
{
|
||||
let _ = self.vault.delete(&service, key);
|
||||
return Err(e);
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
let _g = LOCK.lock();
|
||||
let mut index = match self.load() {
|
||||
Contents::Index(index) => index,
|
||||
Contents::Plaintext(_, why) => return Err(unavailable(&why)),
|
||||
};
|
||||
let service = service(&index.id);
|
||||
self.vault.set(&service, key, secret).map_err(|e| unavailable(&e.to_string()))?;
|
||||
if index.keys.insert(key.to_owned())
|
||||
&& let Err(e) = self.write(&index)
|
||||
{
|
||||
let _ = self.vault.delete(&service, key);
|
||||
return Err(e);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn delete(&self, key: &str) {
|
||||
off_runtime(|| {
|
||||
let _g = LOCK.lock();
|
||||
match self.load() {
|
||||
Contents::Index(mut index) => {
|
||||
if !index.keys.contains(key) {
|
||||
return;
|
||||
}
|
||||
match self.vault.delete(&service(&index.id), key) {
|
||||
Ok(()) | Err(StoreError::NoEntry) => {}
|
||||
Err(e) => {
|
||||
// Kept in the index so that the next delete tries again.
|
||||
tracing::warn!("saved passwords: could not forget {key}: {e}");
|
||||
return;
|
||||
}
|
||||
}
|
||||
index.keys.remove(key);
|
||||
self.write_logged(&index);
|
||||
let _g = LOCK.lock();
|
||||
match self.load() {
|
||||
Contents::Index(mut index) => {
|
||||
if !index.keys.contains(key) {
|
||||
return;
|
||||
}
|
||||
Contents::Plaintext(mut old, _) => {
|
||||
if old.remove(key).is_none() {
|
||||
return;
|
||||
}
|
||||
// A move halfway may have copied it already.
|
||||
if let Some(id) = self.pending_id()
|
||||
&& let Err(e) = self.vault.delete(&service(&id), key)
|
||||
&& !matches!(e, StoreError::NoEntry)
|
||||
{
|
||||
match self.vault.delete(&service(&index.id), key) {
|
||||
Ok(()) | Err(StoreError::NoEntry) => {}
|
||||
Err(e) => {
|
||||
// Kept in the index so that the next delete tries again.
|
||||
tracing::warn!("saved passwords: could not forget {key}: {e}");
|
||||
return;
|
||||
}
|
||||
self.write_logged(&old);
|
||||
}
|
||||
index.keys.remove(key);
|
||||
self.write_logged(&index);
|
||||
}
|
||||
})
|
||||
Contents::Plaintext(mut old, _) => {
|
||||
if old.remove(key).is_none() {
|
||||
return;
|
||||
}
|
||||
// A move halfway may have copied it already.
|
||||
if let Some(id) = self.pending_id()
|
||||
&& let Err(e) = self.vault.delete(&service(&id), key)
|
||||
&& !matches!(e, StoreError::NoEntry)
|
||||
{
|
||||
tracing::warn!("saved passwords: could not forget {key}: {e}");
|
||||
return;
|
||||
}
|
||||
self.write_logged(&old);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Every stored key, sorted (the secrets themselves stay private).
|
||||
pub fn keys(&self) -> Vec<String> {
|
||||
off_runtime(|| {
|
||||
let _g = LOCK.lock();
|
||||
match self.load() {
|
||||
Contents::Index(index) => index.keys.into_iter().collect(),
|
||||
Contents::Plaintext(old, _) => old.into_keys().collect(),
|
||||
}
|
||||
})
|
||||
let _g = LOCK.lock();
|
||||
match self.load() {
|
||||
Contents::Index(index) => index.keys.into_iter().collect(),
|
||||
Contents::Plaintext(old, _) => old.into_keys().collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn load(&self) -> Contents {
|
||||
@@ -584,50 +558,4 @@ mod tests {
|
||||
assert_eq!(mode & 0o777, 0o600);
|
||||
}
|
||||
}
|
||||
|
||||
/// A credential store that behaves like the Linux Secret Service client:
|
||||
/// its blocking API runs a tokio runtime.
|
||||
#[derive(Default)]
|
||||
struct NestedRuntimeVault {
|
||||
entries: Mutex<HashMap<(String, String), String>>,
|
||||
}
|
||||
|
||||
fn nested_runtime() {
|
||||
tokio::runtime::Builder::new_multi_thread().build().expect("a nested runtime").block_on(async {});
|
||||
}
|
||||
|
||||
impl Vault for NestedRuntimeVault {
|
||||
fn available(&self) -> bool {
|
||||
true
|
||||
}
|
||||
fn get(&self, service: &str, key: &str) -> StoreResult<String> {
|
||||
nested_runtime();
|
||||
self.entries.lock().get(&(service.to_owned(), key.to_owned())).cloned().ok_or(StoreError::NoEntry)
|
||||
}
|
||||
fn set(&self, service: &str, key: &str, secret: &str) -> StoreResult<()> {
|
||||
nested_runtime();
|
||||
self.entries.lock().insert((service.to_owned(), key.to_owned()), secret.to_owned());
|
||||
Ok(())
|
||||
}
|
||||
fn delete(&self, service: &str, key: &str) -> StoreResult<()> {
|
||||
nested_runtime();
|
||||
self.entries.lock().remove(&(service.to_owned(), key.to_owned())).map(|_| ()).ok_or(StoreError::NoEntry)
|
||||
}
|
||||
}
|
||||
|
||||
/// Saving a password from a Tauri command runs on a tokio runtime; the
|
||||
/// Secret Service's blocking client starts a runtime of its own and panics
|
||||
/// when both share a thread ("Cannot start a runtime from within a runtime").
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn credential_store_access_leaves_the_async_runtime_first() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let vault = Arc::new(NestedRuntimeVault::default());
|
||||
let file =
|
||||
SecretFile::with_vault(tmp.path().join("db-passwords.json"), |v| serde_json::from_value(v).ok(), vault);
|
||||
file.set("s1", "hunter2").unwrap();
|
||||
assert_eq!(file.get("s1").as_deref(), Some("hunter2"));
|
||||
assert_eq!(file.keys(), ["s1"]);
|
||||
file.delete("s1");
|
||||
assert_eq!(file.get("s1"), None);
|
||||
}
|
||||
}
|
||||
@@ -443,24 +443,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extracts_zip_with_multibyte_path_components() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let archive = tmp.path().join("tool.zip");
|
||||
let entries: &[(&str, &[u8], u32)] = &[
|
||||
("bdms300-front/dist/img/ZC机柜.jpg", b"reported case", 0o644),
|
||||
("A机柜/file", b"directory", 0o644),
|
||||
("abé.txt", b"two-byte character", 0o644),
|
||||
("😀.txt", b"four-byte character", 0o644),
|
||||
];
|
||||
zip_file(&archive, entries);
|
||||
let dest = tmp.path().join("out");
|
||||
extract(&archive, ArchiveKind::Zip, &dest, "x", &CancellationToken::new()).unwrap();
|
||||
for (name, data, _) in entries {
|
||||
assert_eq!(fs::read(dest.join(name)).unwrap(), *data, "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extracts_zip_with_modes_and_nested_dirs() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
import "../src/styles/global.css";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { usePlatform } from "../src/platform/platformInfo";
|
||||
import { Dialog } from "../src/ui/Dialog";
|
||||
|
||||
usePlatform.setState({ os: "macos", overlayTitleBar: true });
|
||||
document.body.innerHTML = `<div id="root"></div>`;
|
||||
createRoot(document.querySelector("#root")!).render(
|
||||
<Dialog open title="Push Commits to origin/main" onClose={() => {}} width={860} maxHeight={720} resizable="both">
|
||||
<div style={{ height: 2000 }} />
|
||||
</Dialog>,
|
||||
);
|
||||
@@ -1,10 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>Dialog title bar fixture</title>
|
||||
</head>
|
||||
<body>
|
||||
<script type="module" src="./dialogTitleBar.fixture.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,28 +0,0 @@
|
||||
import { test, expect, type Page } from "@playwright/test";
|
||||
|
||||
async function titleBarHeight(page: Page) {
|
||||
return page.evaluate(() => parseFloat(getComputedStyle(document.documentElement).getPropertyValue("--h-titlebar")));
|
||||
}
|
||||
|
||||
// Reduced motion skips the opening animation, which scales the dialog while it runs.
|
||||
test.use({ viewport: { width: 1200, height: 640 }, reducedMotion: "reduce" });
|
||||
|
||||
test("a dialog taller than the window stays below the macOS window buttons", async ({ page }) => {
|
||||
await page.goto("/e2e/dialogTitleBar.html");
|
||||
const dialog = page.getByRole("dialog");
|
||||
await expect(dialog).toBeVisible();
|
||||
const box = (await dialog.boundingBox())!;
|
||||
expect(box.y).toBeGreaterThanOrEqual(await titleBarHeight(page));
|
||||
});
|
||||
|
||||
test("dragging a dialog up stops below the macOS window buttons", async ({ page }) => {
|
||||
await page.goto("/e2e/dialogTitleBar.html");
|
||||
const title = page.getByRole("dialog").locator("[data-dialog-titlebar] span").last();
|
||||
const start = (await title.boundingBox())!;
|
||||
await page.mouse.move(start.x + 40, start.y + start.height / 2);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(start.x + 40, 0, { steps: 8 });
|
||||
await page.mouse.up();
|
||||
const box = (await page.getByRole("dialog").boundingBox())!;
|
||||
expect(box.y).toBeGreaterThanOrEqual(await titleBarHeight(page));
|
||||
});
|
||||
@@ -72,16 +72,6 @@ test("plugin markers render names and package SVG variants and keep the indexed
|
||||
await expect(markers.locator('[title="Database marker"] svg')).toHaveAttribute("data-icon", "database");
|
||||
const custom = markers.locator('[title="Package marker"] svg');
|
||||
await expect(custom).toHaveAttribute("data-icon", /^ext:pluginIcon\/hello\//);
|
||||
// CodeMirror clips every gutter column to its width (`overflow: hidden`), so an icon wider than
|
||||
// the column loses its edges: each line-marker icon stays inside the 14px column.
|
||||
const outside = await markers.evaluate((column) => {
|
||||
const bounds = column.getBoundingClientRect();
|
||||
return [...column.querySelectorAll("svg")].filter((svg) => {
|
||||
const box = svg.getBoundingClientRect();
|
||||
return box.left < bounds.left - 0.5 || box.right > bounds.right + 0.5;
|
||||
}).length;
|
||||
});
|
||||
expect(outside).toBe(0);
|
||||
await page.evaluate(async () => {
|
||||
const path = "/src/workbench/theme.ts";
|
||||
await (await import(path)).setTheme("dark");
|
||||
|
||||
+3
-17
@@ -31,13 +31,7 @@
|
||||
const message = String(reason);
|
||||
return reason.stack.includes(message) ? reason.stack : `${message}\n${reason.stack}`;
|
||||
}
|
||||
if (typeof reason === "string") return reason;
|
||||
// WebKit's fetch / network TypeErrors carry no stack and serialise to "{}".
|
||||
if (reason instanceof Error || typeof reason?.message === "string") {
|
||||
const name = typeof reason.name === "string" ? reason.name : "Error";
|
||||
return `${name}: ${reason.message}`;
|
||||
}
|
||||
return JSON.stringify(reason) || String(reason);
|
||||
return (typeof reason === "string" ? reason : JSON.stringify(reason)) || String(reason);
|
||||
} catch {
|
||||
return "Unknown startup error";
|
||||
}
|
||||
@@ -108,12 +102,7 @@
|
||||
show(event.error || `${event.message}\n${event.filename || ""}:${event.lineno || 0}:${event.colno || 0}`);
|
||||
}
|
||||
};
|
||||
// An unhandled rejection doesn't stop startup by itself (a failed background request
|
||||
// rejects too); keep the first one for the timeout report instead of failing on it.
|
||||
let rejection;
|
||||
const onRejection = (event) => {
|
||||
if (rejection === undefined) rejection = describe(event.reason);
|
||||
};
|
||||
const onRejection = (event) => show(event.reason);
|
||||
const onBootError = (event) => show(event.detail);
|
||||
const onReady = () => {
|
||||
ready = true;
|
||||
@@ -123,10 +112,7 @@
|
||||
window.removeEventListener("openidea:boot-error", onBootError);
|
||||
window.removeEventListener("openidea:boot-ready", onReady);
|
||||
};
|
||||
const timer = window.setTimeout(
|
||||
() => show(rejection === undefined ? text.timeout : `${text.timeout}\n\nUnhandled rejection: ${rejection}`),
|
||||
30_000,
|
||||
);
|
||||
const timer = window.setTimeout(() => show(text.timeout), 30_000);
|
||||
window.addEventListener("error", onError, true);
|
||||
window.addEventListener("unhandledrejection", onRejection);
|
||||
window.addEventListener("openidea:boot-error", onBootError);
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { Text } from "@codemirror/state";
|
||||
import { Tree } from "@lezer/common";
|
||||
import { semanticRanges } from "../index";
|
||||
|
||||
describe("Kotlin semantic tokens", () => {
|
||||
@@ -43,42 +42,4 @@ describe("Kotlin semantic tokens", () => {
|
||||
)[0]?.className,
|
||||
).toBe("cm-sem-property");
|
||||
});
|
||||
|
||||
it("colours annotation names as annotations, not as the constructor calls the server reports", () => {
|
||||
const lines = [
|
||||
'@Column(name = "x")',
|
||||
"@field:Inject @Outer.Inner",
|
||||
"list.forEach { return@forEach }",
|
||||
"[email protected]()",
|
||||
];
|
||||
const doc = Text.of(lines);
|
||||
const types = ["method", "class", "label"];
|
||||
const tok = (line: number, word: string, type: string) => [
|
||||
line,
|
||||
lines[line]!.lastIndexOf(word),
|
||||
word.length,
|
||||
types.indexOf(type),
|
||||
0,
|
||||
];
|
||||
const data = [
|
||||
tok(0, "Column", "method"),
|
||||
tok(1, "Inject", "class"),
|
||||
tok(1, "Outer", "class"),
|
||||
tok(1, "Inner", "class"),
|
||||
tok(2, "forEach", "label"),
|
||||
tok(3, "Outer", "class"),
|
||||
].flat();
|
||||
const tokens = { tokenTypes: types, tokenModifiers: [], data };
|
||||
const ranges = semanticRanges(doc, tokens, false, "kotlin", Tree.empty);
|
||||
const classOf = (line: number, word: string) => {
|
||||
const from = doc.line(line + 1).from + lines[line]!.lastIndexOf(word);
|
||||
return ranges.find((r) => r.from === from)?.className;
|
||||
};
|
||||
expect(classOf(0, "Column")).toBe("cm-sem-annotation");
|
||||
expect(classOf(1, "Inject")).toBe("cm-sem-annotation");
|
||||
expect(classOf(1, "Outer")).toBe("cm-sem-annotation");
|
||||
expect(classOf(1, "Inner")).toBe("cm-sem-annotation");
|
||||
expect(classOf(2, "forEach")).toBe("cm-sem-constant");
|
||||
expect(classOf(3, "Outer")).not.toBe("cm-sem-annotation");
|
||||
});
|
||||
});
|
||||
@@ -1,49 +1,7 @@
|
||||
import type { Text } from "@codemirror/state";
|
||||
import { registerLanguageSemantics, type LanguageSemantics } from "../languages";
|
||||
|
||||
const NAME = /[A-Za-z_][\w]*/y;
|
||||
|
||||
/**
|
||||
* The names of annotation usages (`@Column`, `@field:Column`, `@Outer.Inner`), as `"from:to"` → `"annotation"`.
|
||||
* An `@` right after a name is a label (`return@forEach`, `this@Outer`, `loop@`), not an annotation.
|
||||
*/
|
||||
function annotationNames(doc: Text): Map<string, string> {
|
||||
const out = new Map<string, string>();
|
||||
const text = doc.toString();
|
||||
for (let at = text.indexOf("@"); at >= 0; at = text.indexOf("@", at + 1)) {
|
||||
if (/[\w`]/.test(text[at - 1] ?? "")) continue;
|
||||
let pos = at + 1;
|
||||
const name = () => {
|
||||
NAME.lastIndex = pos;
|
||||
const m = NAME.exec(text);
|
||||
return m ? { from: pos, to: pos + m[0].length } : null;
|
||||
};
|
||||
let first = name();
|
||||
// A use-site target (`@field:`, `@get:`, `@file:`) precedes the annotation's name.
|
||||
if (first && text[first.to] === ":" && text[first.to + 1] !== ":") {
|
||||
pos = first.to + 1;
|
||||
first = name();
|
||||
}
|
||||
for (let part = first; part;) {
|
||||
out.set(`${part.from}:${part.to}`, "annotation");
|
||||
if (text[part.to] !== ".") break;
|
||||
pos = part.to + 1;
|
||||
part = name();
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const kotlinSemantics: LanguageSemantics = {
|
||||
symbolKinds: (_tree, doc) => annotationNames(doc),
|
||||
tokenClasses({ type, modifiers, kind, classes }) {
|
||||
// JetBrains Kotlin LSP reports an annotation usage as a constructor call (`method`);
|
||||
// IDEA colours the name as an annotation (Metadata), like its `@`.
|
||||
if (kind === "annotation" && type !== "label") {
|
||||
classes.length = 0;
|
||||
classes.push("cm-sem-annotation");
|
||||
return;
|
||||
}
|
||||
tokenClasses({ type, modifiers, classes }) {
|
||||
if (type === "operator" && modifiers.includes("declaration")) classes.push("cm-sem-function");
|
||||
// JetBrains Kotlin LSP uses `modification` for mutable declarations and references.
|
||||
if ((type === "variable" || type === "property" || type === "parameter") && modifiers.includes("modification"))
|
||||
|
||||
@@ -30,7 +30,6 @@ import {
|
||||
javaTypeFromHover,
|
||||
literalType,
|
||||
replacesBareStatement,
|
||||
trailingName,
|
||||
variableDeclaration,
|
||||
type DeclContext,
|
||||
type DeclResult,
|
||||
@@ -379,17 +378,17 @@ function usesSemicolons(doc: Text, statement: SyntaxNode): boolean {
|
||||
|
||||
/** Return / declared type of a Java call or name from the server's hover, if it answers. */
|
||||
async function javaHoverType(p: Prepared, expr: SyntaxNode, text: string): Promise<string | null> {
|
||||
const last = trailingName(text);
|
||||
if (!last || !/method_invocation|identifier|field_access/.test(expr.kind)) return null;
|
||||
const m = /([A-Za-z_$][\w$]*)\s*(\([\s\S]*\))?\s*$/.exec(text);
|
||||
if (!m || !/method_invocation|identifier|field_access/.test(expr.kind)) return null;
|
||||
const { from } = rangeToOffsets(p.doc, expr.range);
|
||||
const pos = p.doc.lineAt(from + last.index);
|
||||
const at = { line: pos.number - 1, col: from + last.index - pos.from };
|
||||
const pos = p.doc.lineAt(from + m.index);
|
||||
const at = { line: pos.number - 1, col: from + m.index - pos.from };
|
||||
try {
|
||||
const hover = await Promise.race([
|
||||
call(commands.lspHover(nextRequestId(), p.ctx.doc, at)),
|
||||
new Promise<null>((resolve) => setTimeout(() => resolve(null), 1500)),
|
||||
]);
|
||||
return hover ? javaTypeFromHover(hover.contents.value, last.name) : null;
|
||||
return hover ? javaTypeFromHover(hover.contents.value, m[1]!) : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -5,7 +5,6 @@ import {
|
||||
isLiteral,
|
||||
javaConstructedType,
|
||||
javaTypeFromHover,
|
||||
trailingName,
|
||||
literalType,
|
||||
replacesBareStatement,
|
||||
variableDeclaration,
|
||||
@@ -153,15 +152,6 @@ describe("templates", () => {
|
||||
expect(isLiteral("kotlin", "identifier", "true")).toBe(true);
|
||||
});
|
||||
|
||||
it("finds the name a chained expression ends in, for the hover that types it", () => {
|
||||
expect(trailingName("demo.getList().get(0)")).toEqual({ name: "get", index: 15 });
|
||||
expect(trailingName("a.b(c(d)).e")).toEqual({ name: "e", index: 10 });
|
||||
expect(trailingName("names()")).toEqual({ name: "names", index: 0 });
|
||||
expect(trailingName("list.get(i) ")).toEqual({ name: "get", index: 5 });
|
||||
expect(trailingName("(a + b)")).toBeNull();
|
||||
expect(trailingName("x)")).toBeNull();
|
||||
});
|
||||
|
||||
it("reads a Java type from a jdtls hover", () => {
|
||||
expect(javaTypeFromHover("```java\nString java.lang.String.trim()\n```", "trim")).toBe("String");
|
||||
expect(javaTypeFromHover("```java\njava.util.List<java.lang.String> a.B.names()\n```", "names")).toBe(
|
||||
|
||||
@@ -229,27 +229,6 @@ export function javaConstructedType(text: string): string | null {
|
||||
return obj[1]!.replace(/\s+/g, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* The name an expression ends in — the last call's method (`a.b().c(0)` → `c`) or the last
|
||||
* name (`a.b` → `b`) — with its offset in `text`. Null when it ends in something else.
|
||||
*/
|
||||
export function trailingName(text: string): { name: string; index: number } | null {
|
||||
let end = text.trimEnd().length;
|
||||
if (text[end - 1] === ")") {
|
||||
// Back to the `(` that opens the trailing argument list.
|
||||
let depth = 0;
|
||||
let i = end - 1;
|
||||
for (; i >= 0; i--) {
|
||||
if (text[i] === ")") depth++;
|
||||
else if (text[i] === "(" && --depth === 0) break;
|
||||
}
|
||||
if (i < 0) return null;
|
||||
end = text.slice(0, i).trimEnd().length;
|
||||
}
|
||||
const m = /[A-Za-z_$][\w$]*$/.exec(text.slice(0, end));
|
||||
return m ? { name: m[0], index: m.index } : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Type of a Java expression from a jdtls-style hover (```java\nString java.lang.String.trim()\n```
|
||||
* or `String name`), for a call / name ending in `name`. Null when unclear.
|
||||
|
||||
@@ -17,13 +17,11 @@ import {
|
||||
} from "@/ui";
|
||||
import { openLocation } from "./ipc";
|
||||
import {
|
||||
closeHierarchy,
|
||||
ROOT_ID,
|
||||
directionLabel,
|
||||
hierarchyTitle,
|
||||
hierarchyTarget,
|
||||
loadChildren,
|
||||
prefetchLevels,
|
||||
refreshHierarchy,
|
||||
noneFoundLabel,
|
||||
setDirection,
|
||||
@@ -66,10 +64,9 @@ export function HierarchyTabs() {
|
||||
variant="compact"
|
||||
className={styles.tabs}
|
||||
aria-label="Hierarchies"
|
||||
items={[{ id: "current", label, closable: true }]}
|
||||
items={[{ id: "current", label }]}
|
||||
activeId="current"
|
||||
onSelect={() => undefined}
|
||||
onClose={closeHierarchy}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -223,10 +220,6 @@ export function HierarchyView() {
|
||||
getChildren={getChildren}
|
||||
isExpandable={isExpandable}
|
||||
loadChildren={(n) => (n.kind === "item" ? loadChildren(n.node) : undefined)}
|
||||
onExpandedChange={(_expanded, n, open) => {
|
||||
const shown = open ? children.get(n.id) : undefined;
|
||||
if (shown) prefetchLevels(shown);
|
||||
}}
|
||||
defaultExpanded={[ROOT_ID]}
|
||||
handleRef={tree}
|
||||
isOccurrence={() => true}
|
||||
|
||||
@@ -2,10 +2,9 @@ import { describe, expect, it, vi } from "vitest";
|
||||
import type { HierarchyItem, OutlineItem, ReferencesIncomplete, SymbolKind } from "@/bindings";
|
||||
|
||||
const hint = vi.fn();
|
||||
const hide = vi.hoisted(() => vi.fn());
|
||||
vi.mock("@/workbench/contributions", async (orig) => ({
|
||||
...(await orig<typeof import("@/workbench/contributions")>()),
|
||||
toolWindowService: () => ({ show: () => undefined, hide }),
|
||||
toolWindowService: () => ({ show: () => undefined }),
|
||||
}));
|
||||
|
||||
const range = (l1: number, c1: number, l2: number, c2: number) => ({
|
||||
@@ -55,20 +54,6 @@ const callHierarchy = vi.fn((): { items: HierarchyItem[]; incomplete: References
|
||||
incomplete: null,
|
||||
}));
|
||||
const cancelRequest = vi.fn(async () => undefined);
|
||||
// Subtypes by the line of the type asked about: the caret's type → Long (30), Striped64 (40); Striped64 → LongAdder (50).
|
||||
const typeItem = (name: string, line: number): HierarchyItem => ({
|
||||
...item(name),
|
||||
kind: "class",
|
||||
path: "/p/Types.java",
|
||||
selectionRange: range(line, 0, line, name.length),
|
||||
});
|
||||
const typeHierarchy = vi.fn((pos: { line: number; col: number }): HierarchyItem[] =>
|
||||
pos.line === 40
|
||||
? [typeItem("LongAdder", 50)]
|
||||
: pos.line < 30
|
||||
? [typeItem("Long", 30), typeItem("Striped64", 40)]
|
||||
: [],
|
||||
);
|
||||
// The positions a hierarchy request is answered at; anything else is "no symbol".
|
||||
let servedAt = (pos: { line: number; col: number }) => pos.line === 2 && pos.col === 7;
|
||||
|
||||
@@ -81,7 +66,6 @@ vi.mock("@/platform/ipc", async (orig) => {
|
||||
...real.commands,
|
||||
docOutline: async () => OUTLINE,
|
||||
cancelRequest,
|
||||
lspTypeHierarchy: async (_doc: number, pos: { line: number; col: number }) => typeHierarchy(pos),
|
||||
lspCallHierarchy: async (_request: number, _doc: number, pos: { line: number; col: number }) => {
|
||||
// The server prepares a hierarchy only on the method name.
|
||||
if (!servedAt(pos)) throw new real.IpcError({ kind: "notFound", message: "No symbol" });
|
||||
@@ -183,35 +167,3 @@ describe("hierarchy", () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("type hierarchy", () => {
|
||||
it("loads each shown type's level ahead, so a type without subtypes shows no expand arrow", async () => {
|
||||
servedAt = () => true;
|
||||
try {
|
||||
useHierarchy.setState({ mode: "type", direction: "outgoing" });
|
||||
await showHierarchy("type");
|
||||
const [long, striped] = useHierarchy.getState().children.get(ROOT_ID) ?? [];
|
||||
await vi.waitFor(() => {
|
||||
const { children } = useHierarchy.getState();
|
||||
expect(children.get(long!.id)).toEqual([]);
|
||||
expect(children.get(striped!.id)?.map((n) => n.item.name)).toEqual(["LongAdder"]);
|
||||
});
|
||||
const { children } = useHierarchy.getState();
|
||||
// Only the shown levels: LongAdder's subtypes wait until Striped64 is expanded.
|
||||
expect(children.has(children.get(striped!.id)![0]!.id)).toBe(false);
|
||||
} finally {
|
||||
servedAt = (pos) => pos.line === 2 && pos.col === 7;
|
||||
useHierarchy.setState({ mode: "call", direction: "incoming" });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("closing the hierarchy tab", () => {
|
||||
it("clears the tree and hides the tool window", async () => {
|
||||
const { closeHierarchy, useHierarchy } = await import("./hierarchy");
|
||||
useHierarchy.setState({ root: { name: "Number", path: "/p/Number.java", line: 0, col: 0 } as never });
|
||||
closeHierarchy();
|
||||
expect(useHierarchy.getState().root).toBeNull();
|
||||
expect(hide).toHaveBeenCalledWith("hierarchy");
|
||||
});
|
||||
});
|
||||
@@ -73,12 +73,6 @@ export function resetHierarchy() {
|
||||
}));
|
||||
}
|
||||
|
||||
/** Closes the hierarchy's content tab; with no content left the tool window hides. */
|
||||
export function closeHierarchy() {
|
||||
resetHierarchy();
|
||||
toolWindowService().hide("hierarchy");
|
||||
}
|
||||
|
||||
/** The empty-result line of the hierarchy tree. */
|
||||
export function noneFoundLabel(mode: HierarchyMode, direction: HierarchyDirection): string {
|
||||
if (mode === "call") return direction === "incoming" ? tx`— no callers found` : tx`— no callees found`;
|
||||
@@ -177,7 +171,6 @@ async function loadRoot(quiet = false): Promise<RootResult> {
|
||||
request(s.mode, doc, root.line, root.col, s.direction),
|
||||
);
|
||||
setChildren(generation, ROOT_ID, [rootKey(root)], items, incomplete && incompleteNote(incomplete, root.name));
|
||||
prefetchLevels(useHierarchy.getState().children.get(ROOT_ID) ?? []);
|
||||
return "loaded";
|
||||
} catch (e) {
|
||||
if (useHierarchy.getState().generation !== generation) return "stale";
|
||||
@@ -221,8 +214,7 @@ async function enclosingRoot(c: CaretContext, mode: HierarchyMode): Promise<Hier
|
||||
return null;
|
||||
}
|
||||
}
|
||||
/** Loads `node`'s level. `ahead`: a look-ahead load (prefetchLevels), which reports nothing. */
|
||||
export async function loadChildren(node: HierarchyNode, ahead = false) {
|
||||
export async function loadChildren(node: HierarchyNode) {
|
||||
const { mode, direction, generation } = useHierarchy.getState();
|
||||
const at = node.item.selectionRange.start;
|
||||
try {
|
||||
@@ -236,9 +228,8 @@ export async function loadChildren(node: HierarchyNode, ahead = false) {
|
||||
items,
|
||||
incomplete && incompleteNote(incomplete, node.item.name),
|
||||
);
|
||||
if (!ahead) prefetchLevels(useHierarchy.getState().children.get(node.id) ?? []);
|
||||
} catch (e) {
|
||||
if (ahead || useHierarchy.getState().generation !== generation) return;
|
||||
if (useHierarchy.getState().generation !== generation) return;
|
||||
useHierarchy.setState((st) => ({
|
||||
failed: new Set(st.failed).add(node.id),
|
||||
children: new Map(st.children).set(node.id, []),
|
||||
@@ -247,40 +238,6 @@ export async function loadChildren(node: HierarchyNode, ahead = false) {
|
||||
}
|
||||
}
|
||||
|
||||
const AHEAD_CONCURRENCY = 4;
|
||||
const ahead: HierarchyNode[] = [];
|
||||
let aheadRunning = 0;
|
||||
let aheadGeneration = -1;
|
||||
|
||||
/**
|
||||
* IDEA's type hierarchy shows no expand arrow on a type without subtypes (or supertypes): the
|
||||
* level below each shown node is loaded ahead, a few requests at a time. Call hierarchies stay
|
||||
* lazy, as in IDEA.
|
||||
*/
|
||||
export function prefetchLevels(nodes: readonly HierarchyNode[]) {
|
||||
const { mode, generation, children } = useHierarchy.getState();
|
||||
if (mode !== "type") return;
|
||||
if (aheadGeneration !== generation) {
|
||||
ahead.length = 0;
|
||||
aheadGeneration = generation;
|
||||
}
|
||||
for (const n of nodes) if (!n.recursion && !children.has(n.id) && !ahead.includes(n)) ahead.push(n);
|
||||
pumpAhead();
|
||||
}
|
||||
|
||||
function pumpAhead() {
|
||||
while (aheadRunning < AHEAD_CONCURRENCY && ahead.length) {
|
||||
const node = ahead.shift()!;
|
||||
const { generation, children } = useHierarchy.getState();
|
||||
if (generation !== aheadGeneration || children.has(node.id)) continue;
|
||||
aheadRunning++;
|
||||
void loadChildren(node, true).finally(() => {
|
||||
aheadRunning--;
|
||||
pumpAhead();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export async function showHierarchy(mode: HierarchyMode) {
|
||||
const c = caretContext();
|
||||
if (!c) {
|
||||
|
||||
@@ -134,11 +134,6 @@ describe("debug tool window", () => {
|
||||
expect(console.getAttribute("aria-selected")).toBe("true");
|
||||
act(() => useDebug.setState({ sessions: { 1: session } }));
|
||||
expect(variables.getAttribute("aria-selected")).toBe("true");
|
||||
// Stepping from the Console keeps it in front.
|
||||
fireEvent.click(console);
|
||||
act(() => useDebug.setState({ sessions: { 1: { ...session, status: "running" } } }));
|
||||
act(() => useDebug.setState({ sessions: { 1: { ...session, stopReason: "step" } } }));
|
||||
expect(console.getAttribute("aria-selected")).toBe("true");
|
||||
});
|
||||
|
||||
it("renders session tabs, views, frames and typed variables", async () => {
|
||||
|
||||
@@ -153,14 +153,7 @@ export function DebugToolWindow() {
|
||||
setView({
|
||||
session: active.startedAt,
|
||||
status: active.status,
|
||||
// A breakpoint or exception brings Threads & Variables to the front; finishing a step keeps
|
||||
// the tab the user is on (e.g. Console, to watch the output while stepping).
|
||||
tab:
|
||||
active.status === "starting"
|
||||
? "console"
|
||||
: active.status === "paused" && active.stopReason !== "step"
|
||||
? "variables"
|
||||
: view.tab,
|
||||
tab: active.status === "starting" ? "console" : active.status === "paused" ? "variables" : view.tab,
|
||||
});
|
||||
const tab = view.tab;
|
||||
|
||||
|
||||
@@ -97,10 +97,7 @@ export function indexedMarkers(path: string): Extension {
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
},
|
||||
// Only the indexed-marker column sizes its icons to 16px. Line markers reuse the button class
|
||||
// in their own 14px column (lineMarkerGutter.ts, LineMarkers.module.css), whose `overflow: hidden`
|
||||
// would clip an icon this size at its edges.
|
||||
".cm-plugin-mapping-gutter .cm-plugin-mapping-button svg": { width: "16px", height: "16px" },
|
||||
".cm-plugin-mapping-button svg": { width: "16px", height: "16px" },
|
||||
".cm-plugin-mapping-button:focus-visible": { outline: "1px solid var(--accent)" },
|
||||
}),
|
||||
ViewPlugin.fromClass(
|
||||
|
||||
@@ -339,15 +339,13 @@ export function nodeMenu(
|
||||
},
|
||||
]
|
||||
: []),
|
||||
// Both destinations, as in the project view's Git menu.
|
||||
...(toIgnore.length
|
||||
? [
|
||||
{
|
||||
kind: "action" as const,
|
||||
action: "vcs.ignoreShared",
|
||||
arg: toIgnore,
|
||||
label: "Add to .gitignore",
|
||||
submenu: [
|
||||
{ kind: "action" as const, action: "vcs.ignoreShared", arg: toIgnore, label: ".gitignore" },
|
||||
{ kind: "action" as const, action: "vcs.ignoreLocal", arg: toIgnore, label: ".git/info/exclude" },
|
||||
],
|
||||
},
|
||||
]
|
||||
: []),
|
||||
|
||||
@@ -1,74 +0,0 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { FileStatus } from "@/bindings";
|
||||
import type { MenuItem } from "@/ui";
|
||||
import type { ChangeNode } from "../changes";
|
||||
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
const real = await importOriginal<typeof import("@/platform/ipc")>();
|
||||
return { ...real, call: vi.fn() };
|
||||
});
|
||||
|
||||
import { nodeMenu } from "../CommitView";
|
||||
|
||||
const file = (rel: string, unstaged: FileStatus["unstaged"] = "modified"): ChangeNode => {
|
||||
const f: FileStatus = {
|
||||
path: `/p/${rel}`,
|
||||
relPath: rel,
|
||||
staged: null,
|
||||
unstaged,
|
||||
renamedFrom: null,
|
||||
};
|
||||
return {
|
||||
key: f.path,
|
||||
type: "file",
|
||||
label: rel,
|
||||
group: "unversioned",
|
||||
files: [f],
|
||||
path: f.path,
|
||||
};
|
||||
};
|
||||
|
||||
const item = (menu: MenuItem[], label: string) =>
|
||||
menu.find((m) => m.kind !== "separator" && "label" in m && m.label === label);
|
||||
|
||||
describe("Add to .gitignore in the changes view", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("offers both destinations in a submenu, as the project view's Git menu does", () => {
|
||||
const menu = nodeMenu([file("new.txt", "untracked")], ["/p"]);
|
||||
expect(item(menu, "Add to .gitignore")).toMatchObject({
|
||||
submenu: [
|
||||
{
|
||||
kind: "action",
|
||||
action: "vcs.ignoreShared",
|
||||
arg: ["/p/new.txt"],
|
||||
label: ".gitignore",
|
||||
},
|
||||
{
|
||||
kind: "action",
|
||||
action: "vcs.ignoreLocal",
|
||||
arg: ["/p/new.txt"],
|
||||
label: ".git/info/exclude",
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("targets only the unversioned files of a mixed selection", () => {
|
||||
const menu = nodeMenu([file("a.ts", "modified"), file("new.txt", "untracked")], ["/p"]);
|
||||
const parent = item(menu, "Add to .gitignore");
|
||||
expect(parent).toMatchObject({
|
||||
submenu: [
|
||||
{ action: "vcs.ignoreShared", arg: ["/p/new.txt"] },
|
||||
{ action: "vcs.ignoreLocal", arg: ["/p/new.txt"] },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("offers nothing when no unversioned file is selected", () => {
|
||||
const menu = nodeMenu([file("a.ts", "modified")], ["/p"]);
|
||||
expect(item(menu, "Add to .gitignore")).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -59,10 +59,10 @@ describe("ignore action", () => {
|
||||
await addToIgnore(["/p/pkg/a.txt"], "gitignore");
|
||||
expect(mocks.open).toHaveBeenCalledWith("/p/pkg/.gitignore", { focus: true });
|
||||
});
|
||||
it("opens the local exclude file the rule was written to", async () => {
|
||||
it("opens nothing for the local exclude file", async () => {
|
||||
mocks.write.mockResolvedValue(["/p/.git/info/exclude"]);
|
||||
await addToIgnore(["/p/a.txt"], "localExclude");
|
||||
expect(mocks.open).toHaveBeenCalledWith("/p/.git/info/exclude", { focus: true });
|
||||
expect(mocks.open).not.toHaveBeenCalled();
|
||||
});
|
||||
it("reports an already ignored selection instead of opening an unchanged file", async () => {
|
||||
mocks.write.mockResolvedValue([]);
|
||||
|
||||
@@ -22,5 +22,5 @@ export async function addToIgnore(paths: string[], destination: IgnoreDestinatio
|
||||
}
|
||||
// Show the rule where it was written: the nearest .gitignore may be a nested one.
|
||||
const file = changed?.[0];
|
||||
if (file) await editorService().openFile(file, { focus: true });
|
||||
if (destination === "gitignore" && file) await editorService().openFile(file, { focus: true });
|
||||
}
|
||||
@@ -66,39 +66,20 @@ it.each(resizeObserverMessages)("ignores the loop notification delivered as an E
|
||||
expect(document.getElementById("boot-error")).toBeNull();
|
||||
});
|
||||
|
||||
const reject = (reason: unknown) => {
|
||||
it.each(resizeObserverMessages)("keeps rejections with the same message fatal: %s", (message) => {
|
||||
const event = new Event("unhandledrejection");
|
||||
Object.defineProperty(event, "reason", { value: reason });
|
||||
Object.defineProperty(event, "reason", { value: message });
|
||||
window.dispatchEvent(event);
|
||||
};
|
||||
|
||||
it("keeps starting after an unhandled rejection", () => {
|
||||
reject(new TypeError("Load failed"));
|
||||
expect(document.getElementById("splash")).not.toBeNull();
|
||||
expect(document.getElementById("boot-error")).toBeNull();
|
||||
expect(document.documentElement.dataset.boot).toBeUndefined();
|
||||
window.dispatchEvent(new Event("openidea:boot-ready"));
|
||||
vi.advanceTimersByTime(30_000);
|
||||
expect(document.getElementById("boot-error")).toBeNull();
|
||||
expect(document.getElementById("splash")).toBeNull();
|
||||
expect(document.querySelector("textarea")?.value).toContain(message);
|
||||
});
|
||||
|
||||
it("reports the first rejection when startup then times out", () => {
|
||||
const error = new TypeError("Load failed");
|
||||
// WebKit's network TypeErrors have no stack; JSON.stringify turns them into "{}".
|
||||
Object.defineProperty(error, "stack", { value: undefined });
|
||||
reject(error);
|
||||
reject({ message: "later rejection" });
|
||||
vi.advanceTimersByTime(30_000);
|
||||
const details = document.querySelector("textarea")?.value;
|
||||
expect(details).toContain("Startup did not finish within 30 seconds.");
|
||||
expect(details).toContain("TypeError: Load failed");
|
||||
expect(details).not.toContain("later rejection");
|
||||
});
|
||||
|
||||
it("preserves the first failure", () => {
|
||||
window.dispatchEvent(new ErrorEvent("error", { error: new Error("startup failed") }));
|
||||
it("handles startup rejections and preserves the first failure", () => {
|
||||
const event = new Event("unhandledrejection");
|
||||
Object.defineProperty(event, "reason", { value: { message: "startup rejected" } });
|
||||
window.dispatchEvent(event);
|
||||
window.dispatchEvent(new ErrorEvent("error", { message: "later failure" }));
|
||||
expect(document.querySelector("textarea")?.value).toContain("startup failed");
|
||||
expect(document.querySelector("textarea")?.value).toContain("startup rejected");
|
||||
expect(document.querySelector("textarea")?.value).not.toContain("later failure");
|
||||
});
|
||||
|
||||
|
||||
@@ -13,13 +13,6 @@
|
||||
align-items: flex-start;
|
||||
padding-top: 10vh;
|
||||
}
|
||||
/* macOS draws its window buttons over the page; keep dialogs out of that band. */
|
||||
.belowTitleBar {
|
||||
padding-top: max(24px, var(--h-titlebar));
|
||||
}
|
||||
.belowTitleBar.top {
|
||||
padding-top: max(10vh, var(--h-titlebar));
|
||||
}
|
||||
.dialog {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
@@ -231,7 +231,6 @@ function DialogInner({
|
||||
}: DialogProps) {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const platform = useDialogPlatform(platformOverride);
|
||||
const overlayTitleBar = usePlatform((s) => s.overlayTitleBar);
|
||||
const given = useGivenTx();
|
||||
if (typeof title === "string") title = given(title);
|
||||
// Choosers and untitled dialogs (Recent Files, About) are IDEA popups.
|
||||
@@ -342,7 +341,6 @@ function DialogInner({
|
||||
const start = { x: e.clientX - offset.x, y: e.clientY - offset.y };
|
||||
const rect = el.getBoundingClientRect();
|
||||
const base = { left: rect.left - offset.x, top: rect.top - offset.y };
|
||||
const minTop = overlayTitleBar && el.parentElement ? parseFloat(getComputedStyle(el.parentElement).paddingTop) : 0;
|
||||
const move = (ev: globalThis.PointerEvent) => {
|
||||
if (!(ev.buttons & 1)) return up();
|
||||
// Keep the title bar reachable.
|
||||
@@ -350,7 +348,7 @@ function DialogInner({
|
||||
Math.max(ev.clientX - start.x, -base.left - rect.width + 80),
|
||||
window.innerWidth - base.left - 80,
|
||||
);
|
||||
const y = Math.min(Math.max(ev.clientY - start.y, minTop - base.top), window.innerHeight - base.top - 28);
|
||||
const y = Math.min(Math.max(ev.clientY - start.y, -base.top), window.innerHeight - base.top - 28);
|
||||
setOffset({ x, y });
|
||||
};
|
||||
const up = () => {
|
||||
@@ -403,7 +401,7 @@ function DialogInner({
|
||||
|
||||
return createPortal(
|
||||
<div
|
||||
className={clsx(styles.backdrop, position === "top" && styles.top, overlayTitleBar && styles.belowTitleBar)}
|
||||
className={clsx(styles.backdrop, position === "top" && styles.top)}
|
||||
onPointerDown={(e) => {
|
||||
if ((dismissOnBackdrop ?? popup) && e.target === e.currentTarget) onClose();
|
||||
}}
|
||||
|
||||
@@ -215,7 +215,7 @@ function MainMenuBar({ merged, onExpandedChange }: MainMenuProps & { merged: boo
|
||||
else void expand();
|
||||
}}
|
||||
>
|
||||
<Icon name="main-menu" size={20} />
|
||||
<Icon name="main-menu" size={16} />
|
||||
</button>
|
||||
);
|
||||
const titles = (
|
||||
|
||||
@@ -126,16 +126,11 @@
|
||||
/* Frameless window (Windows, Linux): caption buttons sit flush with the right and top edges. */
|
||||
.frameless {
|
||||
padding-right: 0;
|
||||
/* The main menu button leads the left stripe, so the bar starts where the
|
||||
stripe's own padding does and the two share a centre line. */
|
||||
padding-left: var(--stripe-outer-padding);
|
||||
}
|
||||
/* The button heads the tool window stripe below it, so it takes the stripe's
|
||||
size: both shrink in compact mode. */
|
||||
.mainMenuButton {
|
||||
flex: none;
|
||||
width: var(--stripe-icon-button);
|
||||
height: var(--stripe-icon-button);
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
margin-right: 4px;
|
||||
padding: 0;
|
||||
display: inline-flex;
|
||||
@@ -152,13 +147,11 @@
|
||||
outline-offset: -2px;
|
||||
}
|
||||
/* Preserve the menu's natural width while allowing its slot to yield to toolbar controls. */
|
||||
/* Ends where the stripe column below it does, the bar's padding being the
|
||||
stripe's own. */
|
||||
.mainMenuSlot {
|
||||
position: relative;
|
||||
flex: 0 1 auto;
|
||||
min-width: calc(var(--stripe-icon-button) + var(--island-gap));
|
||||
height: var(--stripe-icon-button);
|
||||
min-width: 34px;
|
||||
height: 30px;
|
||||
overflow: hidden;
|
||||
}
|
||||
.mainMenuSlot ~ .item,
|
||||
|
||||
Reference in new issue
Заблокувати користувача