дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-27 21:12:34 +02:00
Порівняти коміти
20
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
bcb2728bcd | ||
|
|
5c50215d39 | ||
|
|
03ed6be82d | ||
|
|
beee4cb633 | ||
|
|
21c2934a36 | ||
|
|
d9ff048a14 | ||
|
|
a8ce8048f8 | ||
|
|
831cd59ab0 | ||
|
|
ec41d3c4a0 | ||
|
|
6bcf99778a | ||
|
|
6d59cf377c | ||
|
|
0217586e2e | ||
|
|
db3b17d863 | ||
|
|
f0261719b8 | ||
|
|
b556a064e3 | ||
|
|
feb882ed10 | ||
|
|
e82d766804 | ||
|
|
5e099ecb5b | ||
|
|
7531834b3c | ||
|
|
0ab50e0dd4 |
No files matched your search
@@ -1,2 +0,0 @@
|
||||
# Repository-wide oxfmt formatting (#135)
|
||||
55836e1b4961c9d87df8503ec374e624c81d6bf6
|
||||
@@ -81,7 +81,6 @@ jobs:
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- run: pnpm typecheck
|
||||
- run: pnpm lint
|
||||
- run: pnpm format:check
|
||||
- run: pnpm test
|
||||
- run: pnpm build
|
||||
|
||||
|
||||
@@ -33,6 +33,3 @@ playwright-report/
|
||||
# Local AI agent files
|
||||
CLAUDE.md
|
||||
.claude/
|
||||
|
||||
# Local reference screenshots
|
||||
pycharm-screenshots/
|
||||
@@ -1,26 +0,0 @@
|
||||
{
|
||||
"$schema": "./node_modules/oxfmt/configuration_schema.json",
|
||||
"printWidth": 120,
|
||||
"semi": true,
|
||||
"singleQuote": false,
|
||||
"trailingComma": "all",
|
||||
"sortPackageJson": false,
|
||||
"ignorePatterns": [
|
||||
"dist",
|
||||
"target",
|
||||
"src/bindings.ts",
|
||||
"docs/plugins/themes.md",
|
||||
"pnpm-lock.yaml",
|
||||
"**/*.toml",
|
||||
"fixtures",
|
||||
"crates/**/tests/fixtures"
|
||||
],
|
||||
"overrides": [
|
||||
{
|
||||
"files": ["**/*.md"],
|
||||
"options": {
|
||||
"embeddedLanguageFormatting": "off"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,150 +0,0 @@
|
||||
{
|
||||
"$schema": "./node_modules/oxlint/configuration_schema.json",
|
||||
"plugins": ["typescript", "react"],
|
||||
"categories": {
|
||||
"correctness": "off"
|
||||
},
|
||||
"env": {
|
||||
"builtin": true
|
||||
},
|
||||
"ignorePatterns": [
|
||||
"dist",
|
||||
"target",
|
||||
"src-tauri",
|
||||
"crates",
|
||||
"src/bindings.ts",
|
||||
"fixtures",
|
||||
"plugins",
|
||||
"test-results",
|
||||
"playwright-report",
|
||||
".claude"
|
||||
],
|
||||
"rules": {
|
||||
"constructor-super": "error",
|
||||
"for-direction": "error",
|
||||
"getter-return": "error",
|
||||
"no-async-promise-executor": "error",
|
||||
"no-case-declarations": "error",
|
||||
"no-class-assign": "error",
|
||||
"no-compare-neg-zero": "error",
|
||||
"no-cond-assign": "error",
|
||||
"no-const-assign": "error",
|
||||
"no-constant-binary-expression": "error",
|
||||
"no-constant-condition": "error",
|
||||
"no-control-regex": "error",
|
||||
"no-debugger": "error",
|
||||
"no-delete-var": "error",
|
||||
"no-dupe-class-members": "error",
|
||||
"no-dupe-else-if": "error",
|
||||
"no-dupe-keys": "error",
|
||||
"no-duplicate-case": "error",
|
||||
"no-empty": "error",
|
||||
"no-empty-character-class": "error",
|
||||
"no-empty-pattern": "error",
|
||||
"no-empty-static-block": "error",
|
||||
"no-ex-assign": "error",
|
||||
"no-extra-boolean-cast": "error",
|
||||
"no-fallthrough": "error",
|
||||
"no-func-assign": "error",
|
||||
"no-global-assign": "error",
|
||||
"no-import-assign": "error",
|
||||
"no-invalid-regexp": "error",
|
||||
"no-irregular-whitespace": "error",
|
||||
"no-loss-of-precision": "error",
|
||||
"no-misleading-character-class": "error",
|
||||
"no-new-native-nonconstructor": "error",
|
||||
"no-nonoctal-decimal-escape": "error",
|
||||
"no-obj-calls": "error",
|
||||
"no-prototype-builtins": "error",
|
||||
"no-redeclare": "error",
|
||||
"no-regex-spaces": "error",
|
||||
"no-self-assign": "error",
|
||||
"no-setter-return": "error",
|
||||
"no-shadow-restricted-names": "error",
|
||||
"no-sparse-arrays": "error",
|
||||
"no-this-before-super": "error",
|
||||
"no-unassigned-vars": "error",
|
||||
"no-unexpected-multiline": "error",
|
||||
"no-unreachable": "error",
|
||||
"no-unsafe-finally": "error",
|
||||
"no-unsafe-negation": "error",
|
||||
"no-unsafe-optional-chaining": "error",
|
||||
"no-unused-labels": "error",
|
||||
"no-unused-private-class-members": "error",
|
||||
"no-unused-vars": [
|
||||
"error",
|
||||
{
|
||||
"argsIgnorePattern": "^_",
|
||||
"varsIgnorePattern": "^_"
|
||||
}
|
||||
],
|
||||
"no-useless-backreference": "error",
|
||||
"no-useless-catch": "error",
|
||||
"no-useless-escape": "error",
|
||||
"no-with": "error",
|
||||
"preserve-caught-error": "error",
|
||||
"require-yield": "error",
|
||||
"use-isnan": "error",
|
||||
"valid-typeof": "error",
|
||||
"no-array-constructor": "error",
|
||||
"no-unused-expressions": "error",
|
||||
"react/rules-of-hooks": "error",
|
||||
"react/exhaustive-deps": "warn",
|
||||
"react/static-components": "error",
|
||||
"react/use-memo": "error",
|
||||
"react/preserve-manual-memoization": "error",
|
||||
"react/incompatible-library": "warn",
|
||||
"react/immutability": "error",
|
||||
"react/globals": "error",
|
||||
"react/refs": "error",
|
||||
"react/set-state-in-effect": "error",
|
||||
"react/error-boundaries": "error",
|
||||
"react/purity": "error",
|
||||
"react/set-state-in-render": "error",
|
||||
"react/unsupported-syntax": "warn",
|
||||
"typescript/ban-ts-comment": "error",
|
||||
"typescript/no-duplicate-enum-values": "error",
|
||||
"typescript/no-empty-object-type": "error",
|
||||
"typescript/no-explicit-any": "error",
|
||||
"typescript/no-extra-non-null-assertion": "error",
|
||||
"typescript/no-misused-new": "error",
|
||||
"typescript/no-namespace": "error",
|
||||
"typescript/no-non-null-asserted-optional-chain": "error",
|
||||
"typescript/no-require-imports": "error",
|
||||
"typescript/no-this-alias": "error",
|
||||
"typescript/no-unnecessary-type-constraint": "error",
|
||||
"typescript/no-unsafe-declaration-merging": "error",
|
||||
"typescript/no-unsafe-function-type": "error",
|
||||
"typescript/no-wrapper-object-types": "error",
|
||||
"typescript/prefer-as-const": "error",
|
||||
"typescript/prefer-namespace-keyword": "error",
|
||||
"typescript/triple-slash-reference": "error"
|
||||
},
|
||||
"overrides": [
|
||||
{
|
||||
"files": ["**/*.ts", "**/*.tsx", "**/*.mts", "**/*.cts"],
|
||||
"rules": {
|
||||
"constructor-super": "off",
|
||||
"getter-return": "off",
|
||||
"no-class-assign": "off",
|
||||
"no-const-assign": "off",
|
||||
"no-dupe-class-members": "off",
|
||||
"no-dupe-keys": "off",
|
||||
"no-func-assign": "off",
|
||||
"no-import-assign": "off",
|
||||
"no-new-native-nonconstructor": "off",
|
||||
"no-obj-calls": "off",
|
||||
"no-redeclare": "off",
|
||||
"no-setter-return": "off",
|
||||
"no-this-before-super": "off",
|
||||
"no-unreachable": "off",
|
||||
"no-unsafe-negation": "off",
|
||||
"no-var": "error",
|
||||
"no-with": "off",
|
||||
"prefer-const": "error",
|
||||
"prefer-rest-params": "error",
|
||||
"prefer-spread": "error"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
dist
|
||||
target
|
||||
src/bindings.ts
|
||||
pnpm-lock.yaml
|
||||
@@ -0,0 +1 @@
|
||||
{ "printWidth": 120, "semi": true, "singleQuote": false, "trailingComma": "all" }
|
||||
Створено
+33
-36
@@ -3974,7 +3974,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
|
||||
|
||||
[[package]]
|
||||
name = "ide-agent"
|
||||
version = "0.1.22"
|
||||
version = "0.1.18"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-jsonrpc",
|
||||
@@ -3992,7 +3992,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-analysis"
|
||||
version = "0.1.22"
|
||||
version = "0.1.18"
|
||||
dependencies = [
|
||||
"ast-grep-core",
|
||||
"ide-core",
|
||||
@@ -4006,7 +4006,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-build"
|
||||
version = "0.1.22"
|
||||
version = "0.1.18"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"dunce",
|
||||
@@ -4021,24 +4021,23 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-clipboard"
|
||||
version = "0.1.22"
|
||||
version = "0.1.18"
|
||||
|
||||
[[package]]
|
||||
name = "ide-core"
|
||||
version = "0.1.22"
|
||||
version = "0.1.18"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"specta",
|
||||
"specta-typescript",
|
||||
"thiserror 2.0.21",
|
||||
"tokio-util",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ide-coverage"
|
||||
version = "0.1.22"
|
||||
version = "0.1.18"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
@@ -4052,7 +4051,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-dap"
|
||||
version = "0.1.22"
|
||||
version = "0.1.18"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-jsonrpc",
|
||||
@@ -4069,7 +4068,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-db"
|
||||
version = "0.1.22"
|
||||
version = "0.1.18"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"futures",
|
||||
@@ -4088,7 +4087,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-docker"
|
||||
version = "0.1.22"
|
||||
version = "0.1.18"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
@@ -4102,7 +4101,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-github"
|
||||
version = "0.1.22"
|
||||
version = "0.1.18"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-vcs",
|
||||
@@ -4116,7 +4115,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-host"
|
||||
version = "0.1.22"
|
||||
version = "0.1.18"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"dunce",
|
||||
@@ -4157,7 +4156,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-http"
|
||||
version = "0.1.22"
|
||||
version = "0.1.18"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot",
|
||||
@@ -4175,7 +4174,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-index"
|
||||
version = "0.1.22"
|
||||
version = "0.1.18"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4197,7 +4196,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jsonrpc"
|
||||
version = "0.1.22"
|
||||
version = "0.1.18"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"futures",
|
||||
@@ -4213,7 +4212,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-language"
|
||||
version = "0.1.22"
|
||||
version = "0.1.18"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4222,7 +4221,6 @@ dependencies = [
|
||||
"parking_lot",
|
||||
"regex-lite",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"specta",
|
||||
"toml 0.9.12+spec-1.1.0",
|
||||
"tracing",
|
||||
@@ -4267,7 +4265,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-lsp"
|
||||
version = "0.1.22"
|
||||
version = "0.1.18"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"globset",
|
||||
@@ -4290,7 +4288,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-plugin"
|
||||
version = "0.1.22"
|
||||
version = "0.1.18"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4308,7 +4306,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-profiler"
|
||||
version = "0.1.22"
|
||||
version = "0.1.18"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
@@ -4321,7 +4319,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-remote"
|
||||
version = "0.1.22"
|
||||
version = "0.1.18"
|
||||
dependencies = [
|
||||
"globset",
|
||||
"ide-core",
|
||||
@@ -4338,7 +4336,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-run"
|
||||
version = "0.1.22"
|
||||
version = "0.1.18"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"ide-core",
|
||||
@@ -4358,7 +4356,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-sdk"
|
||||
version = "0.1.22"
|
||||
version = "0.1.18"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"ide-core",
|
||||
@@ -4372,13 +4370,12 @@ dependencies = [
|
||||
"tempfile",
|
||||
"toml 0.9.12+spec-1.1.0",
|
||||
"tracing",
|
||||
"which",
|
||||
"zip 2.4.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ide-search"
|
||||
version = "0.1.22"
|
||||
version = "0.1.18"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"globset",
|
||||
@@ -4398,7 +4395,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-spell"
|
||||
version = "0.1.22"
|
||||
version = "0.1.18"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot",
|
||||
@@ -4411,7 +4408,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-ssh"
|
||||
version = "0.1.22"
|
||||
version = "0.1.18"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"flate2",
|
||||
@@ -4430,7 +4427,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-syntax"
|
||||
version = "0.1.22"
|
||||
version = "0.1.18"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4445,7 +4442,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-terminal"
|
||||
version = "0.1.22"
|
||||
version = "0.1.18"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
@@ -4458,7 +4455,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-text"
|
||||
version = "0.1.22"
|
||||
version = "0.1.18"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -4470,7 +4467,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-tools"
|
||||
version = "0.1.22"
|
||||
version = "0.1.18"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hex",
|
||||
@@ -4490,7 +4487,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vcs"
|
||||
version = "0.1.22"
|
||||
version = "0.1.18"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"gix",
|
||||
@@ -4507,7 +4504,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vfs"
|
||||
version = "0.1.22"
|
||||
version = "0.1.18"
|
||||
dependencies = [
|
||||
"chardetng",
|
||||
"dunce",
|
||||
@@ -4528,7 +4525,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-web"
|
||||
version = "0.1.22"
|
||||
version = "0.1.18"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"open",
|
||||
@@ -4544,7 +4541,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-workspace"
|
||||
version = "0.1.22"
|
||||
version = "0.1.18"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -5969,7 +5966,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "openidea"
|
||||
version = "0.1.22"
|
||||
version = "0.1.18"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dirs 6.0.0",
|
||||
|
||||
+3
-6
@@ -3,7 +3,7 @@ resolver = "3"
|
||||
members = ["crates/*", "src-tauri"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.22"
|
||||
version = "0.1.18"
|
||||
edition = "2024"
|
||||
rust-version = "1.96"
|
||||
license = "Apache-2.0"
|
||||
@@ -46,7 +46,6 @@ serde_json = "1"
|
||||
toml = "0.9"
|
||||
toml_edit = "0.25"
|
||||
specta = { version = "=2.0.0-rc.25", features = ["derive"] }
|
||||
specta-typescript = "0.0.12"
|
||||
|
||||
# async & concurrency
|
||||
tokio = { version = "1", features = ["rt-multi-thread", "macros", "sync", "time", "process", "io-util", "fs"] }
|
||||
@@ -108,7 +107,5 @@ opt-level = 2
|
||||
codegen-units = 1
|
||||
lto = true
|
||||
opt-level = 3
|
||||
# Unwind, so a panic fails one task or command instead of quitting the IDE.
|
||||
panic = "unwind"
|
||||
# Keep the symbol table: crash reports and logged backtraces name functions.
|
||||
strip = "debuginfo"
|
||||
panic = "abort"
|
||||
strip = true
|
||||
@@ -6,10 +6,6 @@ contributors as part of the IntelliJ Platform (https://github.com/JetBrains/inte
|
||||
https://github.com/JetBrains/intellij-plugins), licensed under the Apache License 2.0.
|
||||
Copyright 2000-2026 JetBrains s.r.o. and contributors.
|
||||
|
||||
Some Simplified Chinese UI terms follow the Visual Studio Code Simplified Chinese
|
||||
language pack (https://github.com/microsoft/vscode-loc), Copyright (c) Microsoft
|
||||
Corporation, licensed under the MIT License.
|
||||
|
||||
OpenIDEA is not affiliated with, endorsed by or sponsored by JetBrains s.r.o.
|
||||
IntelliJ and IntelliJ IDEA are trademarks of JetBrains s.r.o.
|
||||
|
||||
|
||||
+8
-8
@@ -30,14 +30,14 @@ for 60+ languages. Builds for macOS, Windows and Linux.
|
||||
Opening [freqtrade](https://github.com/freqtrade/freqtrade) (Python, ~770 files)
|
||||
with warm caches, median of 5 runs:
|
||||
|
||||
| | OpenIDEA | IntelliJ IDEA 2026.2.3 |
|
||||
| --------------------------- | ----------------- | ---------------------- |
|
||||
| Window with the project | **0.9 s** | 3.1 s |
|
||||
| Ready (CPU settled) | **1.1 s** | 13.2 s |
|
||||
| Memory (USS, all processes) | **169 MB** | 2011 MB |
|
||||
| CPU time until ready | **2.4 s** | 47.9 s |
|
||||
| Idle CPU | **4 %** of a core | 7 % of a core |
|
||||
| Quit | **0.3 s** | 5.9 s |
|
||||
| | OpenIDEA | IntelliJ IDEA 2026.2.3 |
|
||||
|---|---|---|
|
||||
| Window with the project | **0.9 s** | 3.1 s |
|
||||
| Ready (CPU settled) | **1.1 s** | 13.2 s |
|
||||
| Memory (USS, all processes) | **169 MB** | 2011 MB |
|
||||
| CPU time until ready | **2.4 s** | 47.9 s |
|
||||
| Idle CPU | **4 %** of a core | 7 % of a core |
|
||||
| Quit | **0.3 s** | 5.9 s |
|
||||
|
||||
A release build of OpenIDEA from `main` and IDEA with default settings and plugins, on
|
||||
Windows 11, 32-core AMD, 62 GB RAM.
|
||||
|
||||
@@ -79,25 +79,15 @@ user's app-data directory only when the user asks; none of them ships with OpenI
|
||||
unmodified, and its source is available from the repository above.
|
||||
- **Eclipse JDT Language Server** (jdtls): EPL-2.0, from download.eclipse.org.
|
||||
|
||||
## en_US / en_GB Hunspell dictionaries
|
||||
## en_US Hunspell dictionary
|
||||
|
||||
`crates/ide-spell/src/dict/en_US.{aff,dic}` (the spell checker's bundled dictionary) is the
|
||||
SCOWL-derived en_US Hunspell dictionary (version 2020.12.07, from the `dictionary-en` npm
|
||||
package 4.0.0), copied unmodified. Copyright Kevin Atkinson and the SCOWL / Hunspell
|
||||
dictionary contributors; MIT- and BSD-style licences, full text in
|
||||
`crates/ide-spell/src/dict/LICENSE-en_US`. `crates/ide-spell/src/dict/en_GB-extra.dic` holds the
|
||||
entries of the matching en_GB dictionary (`dictionary-en-gb` npm package 3.0.0, same SCOWL
|
||||
version, licence and affix file) that en_US lacks. They are checked with the
|
||||
`crates/ide-spell/src/dict/LICENSE-en_US`. It is checked with the
|
||||
[spellbook](https://github.com/helix-editor/spellbook) crate (MPL-2.0).
|
||||
|
||||
## cspell-dicts word lists
|
||||
|
||||
`crates/ide-spell/src/dict/cspell-terms.txt` (programming terms the spell checker accepts)
|
||||
is derived from the software-terms, typescript, node, rust, fullstack, golang, java, cpp,
|
||||
shell and css dictionaries of [cspell-dicts](https://github.com/streetsidesoftware/cspell-dicts)
|
||||
(October 2026): lowercased, filtered and merged by OpenIDEA. Copyright Street Side Software;
|
||||
MIT licence, full text in `crates/ide-spell/src/dict/LICENSE-cspell-dicts`.
|
||||
|
||||
## nvim-treesitter queries
|
||||
|
||||
`crates/ide-syntax/queries/<grammar>/locals.scm` are derived from the `locals.scm`
|
||||
@@ -116,7 +106,7 @@ Apache License
|
||||
|
||||
Version 2.0, January 2004
|
||||
|
||||
http://www.apache.org/licenses/
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
@@ -250,41 +240,3 @@ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
```
|
||||
|
||||
## Chinese UI terminology from Visual Studio Code
|
||||
|
||||
Some Simplified Chinese terms in `src/platform/locales/text/zh.json` follow the
|
||||
wording of the Visual Studio Code Simplified Chinese language pack
|
||||
([microsoft/vscode-loc](https://github.com/microsoft/vscode-loc), MIT), e.g.
|
||||
"未跟踪" (untracked), "合并冲突" (merge conflicts), "当前" (current), "已修改"
|
||||
(modified), "已过时" (outdated), "中止" (abort), "正在卸载" (uninstalling),
|
||||
"深色" / "浅色" (dark / light) and "只读" (read-only). The remaining translations
|
||||
are written for this project.
|
||||
|
||||
```
|
||||
Visual Studio Code Localization Packs
|
||||
|
||||
Copyright (c) Microsoft Corporation
|
||||
|
||||
All rights reserved.
|
||||
|
||||
MIT License
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE
|
||||
```
|
||||
@@ -104,10 +104,17 @@ pub(crate) fn commands_of(update: &Value) -> Vec<AgentCommand> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `usage_update`: `{ used, size }`.
|
||||
/// `usage_update`: `{ used, size, cost?: { amount, currency } }`.
|
||||
pub(crate) fn usage_of(update: &Value) -> Option<AgentUsage> {
|
||||
let tokens = |key: &str| update.get(key)?.as_f64().map(|n| n.clamp(0.0, f64::from(u32::MAX)) as u32);
|
||||
Some(AgentUsage { used: tokens("used")?, size: tokens("size").filter(|s| *s > 0)? })
|
||||
let used = tokens("used")?;
|
||||
let size = tokens("size").filter(|s| *s > 0)?;
|
||||
Some(AgentUsage {
|
||||
used,
|
||||
size,
|
||||
cost: update.pointer("/cost/amount").and_then(Value::as_f64),
|
||||
currency: update.pointer("/cost/currency").and_then(Value::as_str).map(str::to_owned),
|
||||
})
|
||||
}
|
||||
|
||||
fn legacy(
|
||||
@@ -211,7 +218,7 @@ mod tests {
|
||||
assert_eq!(cmds[0].hint.as_deref(), Some("what to review"));
|
||||
assert_eq!((cmds[1].name.as_str(), cmds[1].hint.as_ref()), ("init", None));
|
||||
let u = usage_of(&json!({"used": 1200, "size": 200000, "cost": {"amount": 0.42, "currency": "USD"}})).unwrap();
|
||||
assert_eq!((u.used, u.size), (1200, 200000));
|
||||
assert_eq!((u.used, u.cost, u.currency.as_deref()), (1200, Some(0.42), Some("USD")));
|
||||
assert!(usage_of(&json!({"used": 1, "size": 0})).is_none());
|
||||
}
|
||||
}
|
||||
@@ -1,281 +0,0 @@
|
||||
//! A task's conversation and those of its subagents.
|
||||
//!
|
||||
//! An agent that supports ACP subagent sessions runs each subagent (Claude Code's Agent
|
||||
//! tool, Codex's spawned agents) as a child session: `subagent_update` on the parent
|
||||
//! announces it and reports its state, its own updates carry its session id, and
|
||||
//! `session_message`s carry what it was asked and what it answered. The parent's
|
||||
//! timeline shows a card per subagent; each subagent keeps its own timeline.
|
||||
|
||||
use crate::model::AgentEntry;
|
||||
use crate::timeline::{Timeline, blocks_text, content_text};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
/// Where an entry lives: the task's own conversation (`None`) or a subagent's session.
|
||||
pub(crate) type Session = Option<String>;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Conversation {
|
||||
pub main: Timeline,
|
||||
/// In the order they started.
|
||||
subagents: Vec<Subagent>,
|
||||
}
|
||||
|
||||
struct Subagent {
|
||||
id: String,
|
||||
/// The session that started it.
|
||||
parent: Session,
|
||||
timeline: Timeline,
|
||||
}
|
||||
|
||||
/// A subagent's conversation, as saved with its task.
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(crate) struct SavedSubagent {
|
||||
pub id: String,
|
||||
pub parent: Option<String>,
|
||||
pub entries: Vec<AgentEntry>,
|
||||
}
|
||||
|
||||
impl Conversation {
|
||||
pub fn restore(main: Vec<AgentEntry>, subagents: Vec<SavedSubagent>) -> Self {
|
||||
Self {
|
||||
main: Timeline::from_entries(main),
|
||||
subagents: subagents
|
||||
.into_iter()
|
||||
.map(|s| Subagent { id: s.id, parent: s.parent, timeline: Timeline::from_entries(s.entries) })
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn saved_subagents(&self) -> Vec<SavedSubagent> {
|
||||
self.subagents
|
||||
.iter()
|
||||
.map(|s| SavedSubagent { id: s.id.clone(), parent: s.parent.clone(), entries: s.timeline.entries.clone() })
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn timeline(&self, session: &Session) -> Option<&Timeline> {
|
||||
match session {
|
||||
None => Some(&self.main),
|
||||
Some(id) => self.subagents.iter().find(|s| &s.id == id).map(|s| &s.timeline),
|
||||
}
|
||||
}
|
||||
|
||||
fn timeline_mut(&mut self, session: &Session) -> Option<&mut Timeline> {
|
||||
match session {
|
||||
None => Some(&mut self.main),
|
||||
Some(id) => self.subagents.iter_mut().find(|s| &s.id == id).map(|s| &mut s.timeline),
|
||||
}
|
||||
}
|
||||
|
||||
fn parent_of(&self, id: &str) -> Option<&Session> {
|
||||
self.subagents.iter().find(|s| s.id == id).map(|s| &s.parent)
|
||||
}
|
||||
|
||||
/// The session an update for session id `session` belongs to: a known subagent's, else the task's.
|
||||
pub fn owner(&self, session: Option<&str>) -> Session {
|
||||
session.filter(|s| self.parent_of(s).is_some()).map(str::to_owned)
|
||||
}
|
||||
|
||||
/// The parent's title (or description) for subagent `id`.
|
||||
pub fn label(&self, id: &str) -> Option<String> {
|
||||
let parent = self.parent_of(id)?;
|
||||
self.timeline(parent)?.entries.iter().find_map(|e| match e {
|
||||
AgentEntry::Subagent { id: card, title, description, .. } if card == id => {
|
||||
title.clone().or_else(|| description.clone())
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Applies one `session/update` of session id `session` (the task's own when unknown);
|
||||
/// returns the entries it added or changed.
|
||||
pub fn apply(&mut self, session: Option<&str>, update: &Value, now: f64) -> Vec<(Session, usize)> {
|
||||
let owner = self.owner(session);
|
||||
let kind = update.get("sessionUpdate").and_then(Value::as_str).unwrap_or_default();
|
||||
let mut out = Vec::new();
|
||||
match kind {
|
||||
"subagent_update" => {
|
||||
let Some(id) = update.get("sessionId").and_then(Value::as_str) else { return out };
|
||||
if self.parent_of(id).is_none() {
|
||||
self.subagents.push(Subagent { id: id.to_owned(), parent: owner, timeline: Timeline::default() });
|
||||
}
|
||||
let parent = self.parent_of(id).cloned().flatten();
|
||||
let Some(timeline) = self.timeline_mut(&parent) else { return out };
|
||||
let (index, stopped) = timeline.subagent(id, update, now);
|
||||
out.push((parent, index));
|
||||
if stopped && let Some(child) = self.timeline_mut(&Some(id.to_owned())) {
|
||||
let id = Some(id.to_owned());
|
||||
out.extend(child.end_turn(None).into_iter().map(|i| (id.clone(), i)));
|
||||
}
|
||||
}
|
||||
"session_message" | "session_message_chunk" => {
|
||||
let append = kind == "session_message_chunk";
|
||||
let text = if append {
|
||||
content_text(update.get("content")).unwrap_or_default()
|
||||
} else {
|
||||
blocks_text(update.get("content"))
|
||||
};
|
||||
let field = |k: &str| update.get(k).and_then(Value::as_str).map(str::to_owned);
|
||||
let (sender, recipient) = (field("senderSessionId"), field("recipientSessionId"));
|
||||
let ours =
|
||||
|s: &Option<String>| s.as_deref().filter(|s| self.parent_of(s) == Some(&owner)).map(str::to_owned);
|
||||
// Between this session and a subagent of it: the subagent's task or answer, on its card.
|
||||
let card = ours(&recipient).map(|c| (c, false)).or_else(|| ours(&sender).map(|c| (c, true)));
|
||||
let Some(timeline) = self.timeline_mut(&owner) else { return out };
|
||||
let index = match card {
|
||||
Some((child, reply)) => timeline.card_message(&child, reply, &text, append),
|
||||
None => {
|
||||
let id = field("messageId").unwrap_or_default();
|
||||
Some(timeline.message(&id, sender != owner, &text, append))
|
||||
}
|
||||
};
|
||||
out.extend(index.map(|i| (owner, i)));
|
||||
}
|
||||
_ => {
|
||||
let Some(timeline) = self.timeline_mut(&owner) else { return out };
|
||||
out.extend(timeline.apply(update).changed.into_iter().map(|i| (owner.clone(), i)));
|
||||
if let Some(id) = owner.as_deref()
|
||||
&& matches!(kind, "tool_call" | "tool_call_update")
|
||||
{
|
||||
out.extend(self.refresh_card(id));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Updates subagent `id`'s card from its timeline.
|
||||
fn refresh_card(&mut self, id: &str) -> Option<(Session, usize)> {
|
||||
let parent = self.parent_of(id)?.clone();
|
||||
let child = self.subagents.iter().position(|s| s.id == id)?;
|
||||
let timeline = std::mem::take(&mut self.subagents[child].timeline);
|
||||
let changed = self.timeline_mut(&parent).and_then(|p| p.card_activity(id, &timeline));
|
||||
self.subagents[child].timeline = timeline;
|
||||
changed.map(|i| (parent, i))
|
||||
}
|
||||
|
||||
/// Settles what an ended turn of the task left open. Subagents work on (in the background).
|
||||
pub fn end_turn(&mut self, done: Option<f64>) -> Vec<(Session, usize)> {
|
||||
self.main.end_turn(done).into_iter().map(|i| (None, i)).collect()
|
||||
}
|
||||
|
||||
/// Settles everything left open once the agent is gone, subagents included.
|
||||
pub fn settle(&mut self, now: f64) -> Vec<(Session, usize)> {
|
||||
let mut out: Vec<(Session, usize)> = self.main.end_turn(None).into_iter().map(|i| (None, i)).collect();
|
||||
out.extend(self.main.stop_subagents(now).into_iter().map(|i| (None, i)));
|
||||
for s in &mut self.subagents {
|
||||
let id = Some(s.id.clone());
|
||||
let mut changed = s.timeline.end_turn(None);
|
||||
changed.extend(s.timeline.stop_subagents(now));
|
||||
out.extend(changed.into_iter().map(|i| (id.clone(), i)));
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::model::{AgentSubagentStatus, AgentToolStatus};
|
||||
use serde_json::json;
|
||||
|
||||
fn card(c: &Conversation, session: &Session, index: usize) -> AgentEntry {
|
||||
c.timeline(session).unwrap().entries[index].clone()
|
||||
}
|
||||
|
||||
/// Claude Code's Agent tool, as `claude-agent-acp` reports it to a client with subagent sessions.
|
||||
#[test]
|
||||
fn a_subagent_gets_a_card_in_its_parent_and_its_own_timeline() {
|
||||
let mut c = Conversation::default();
|
||||
let sub = Some("child".to_owned());
|
||||
let announce = json!({"sessionUpdate": "subagent_update", "sessionId": "child", "title": "Explore",
|
||||
"description": "Find the parser", "capabilities": {"cancel": {}}, "state": {"state": "running"}});
|
||||
assert_eq!(c.apply(Some("root"), &announce, 10.0), vec![(None, 0)]);
|
||||
// The launch prompt: the parent's outgoing view, then the child's incoming one.
|
||||
let prompt = json!({"sessionUpdate": "session_message", "messageId": "toolu_1",
|
||||
"senderSessionId": "root", "recipientSessionId": "child",
|
||||
"content": [{"type": "text", "text": "Look for it"}]});
|
||||
assert_eq!(c.apply(Some("root"), &prompt, 11.0), vec![(None, 0)]);
|
||||
assert_eq!(c.apply(Some("child"), &prompt, 11.0), vec![(sub.clone(), 0)]);
|
||||
assert_eq!(card(&c, &sub, 0), AgentEntry::Message { incoming: true, text: "Look for it".into() });
|
||||
|
||||
// The child's own work stays out of the parent's timeline; its card follows it.
|
||||
c.apply(
|
||||
Some("child"),
|
||||
&json!({"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": "hm"}}),
|
||||
12.0,
|
||||
);
|
||||
let changed = c.apply(
|
||||
Some("child"),
|
||||
&json!({"sessionUpdate": "tool_call", "toolCallId": "t1", "title": "Read lib.rs", "kind": "read", "status": "in_progress"}),
|
||||
12.0,
|
||||
);
|
||||
assert_eq!(changed, vec![(sub.clone(), 2), (None, 0)]);
|
||||
assert_eq!(c.main.entries.len(), 1);
|
||||
// Settings of the child session don't touch the task.
|
||||
assert_eq!(c.owner(Some("child")), sub);
|
||||
assert_eq!(c.owner(Some("root")), None);
|
||||
|
||||
let done = json!({"sessionUpdate": "subagent_update", "sessionId": "child", "state": {"state": "idle", "stopReason": "end_turn"}});
|
||||
let changed = c.apply(Some("root"), &done, 20.0);
|
||||
// Its tool calls left open are settled when it stops.
|
||||
assert_eq!(changed, vec![(None, 0), (sub.clone(), 2)]);
|
||||
let reply = json!({"sessionUpdate": "session_message", "messageId": "toolu_1:reply", "senderSessionId": "child",
|
||||
"recipientSessionId": "root", "content": [{"type": "text", "text": "In "}, {"type": "text", "text": "parser.rs"}]});
|
||||
c.apply(Some("root"), &reply, 20.0);
|
||||
assert_eq!(
|
||||
c.main.entries[0],
|
||||
AgentEntry::Subagent {
|
||||
id: "child".into(),
|
||||
title: Some("Explore".into()),
|
||||
description: Some("Find the parser".into()),
|
||||
status: AgentSubagentStatus::Done,
|
||||
error: None,
|
||||
prompt: Some("Look for it".into()),
|
||||
reply: Some("In \nparser.rs".into()),
|
||||
tools: 1,
|
||||
activity: Some("Read lib.rs".into()),
|
||||
started_ms: 10.0,
|
||||
ended_ms: Some(20.0),
|
||||
cancellable: true,
|
||||
}
|
||||
);
|
||||
assert_eq!(c.label("child").as_deref(), Some("Explore"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_subagents_and_failures() {
|
||||
let mut c = Conversation::default();
|
||||
c.apply(
|
||||
None,
|
||||
&json!({"sessionUpdate": "subagent_update", "sessionId": "a", "state": {"state": "running"}}),
|
||||
1.0,
|
||||
);
|
||||
c.apply(
|
||||
Some("a"),
|
||||
&json!({"sessionUpdate": "subagent_update", "sessionId": "b", "description": "deeper"}),
|
||||
2.0,
|
||||
);
|
||||
let a = Some("a".to_owned());
|
||||
assert!(matches!(card(&c, &a, 0), AgentEntry::Subagent { ref id, .. } if id == "b"));
|
||||
let failed = json!({"sessionUpdate": "subagent_update", "sessionId": "b",
|
||||
"state": {"state": "idle", "stopReason": "error", "error": {"code": -32603, "message": "boom"}}});
|
||||
assert_eq!(c.apply(Some("a"), &failed, 3.0), vec![(a.clone(), 0)]);
|
||||
assert!(matches!(card(&c, &a, 0),
|
||||
AgentEntry::Subagent { status: AgentSubagentStatus::Failed, error: Some(ref e), ended_ms: Some(3.0), .. } if e == "boom"));
|
||||
|
||||
// Saved and restored, then the agent is gone: what still works is stopped.
|
||||
let mut c = Conversation::restore(c.main.entries.clone(), c.saved_subagents());
|
||||
c.apply(
|
||||
Some("a"),
|
||||
&json!({"sessionUpdate": "tool_call", "toolCallId": "t", "title": "Run", "status": "in_progress"}),
|
||||
4.0,
|
||||
);
|
||||
let settled = c.settle(9.0);
|
||||
assert_eq!(settled, vec![(None, 0), (a.clone(), 1)]);
|
||||
assert!(matches!(c.main.entries[0], AgentEntry::Subagent { status: AgentSubagentStatus::Cancelled, .. }));
|
||||
assert!(matches!(card(&c, &a, 1), AgentEntry::Tool { status: AgentToolStatus::Failed, .. }));
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,6 @@
|
||||
//! next prompt when the agent supports `session/load`.
|
||||
|
||||
mod config;
|
||||
mod conversation;
|
||||
mod model;
|
||||
mod provider;
|
||||
mod skills;
|
||||
@@ -17,17 +16,17 @@ mod worktree;
|
||||
|
||||
pub use model::*;
|
||||
|
||||
use conversation::{Conversation, SavedSubagent, Session};
|
||||
use ide_core::{IdeError, IdeResult, IpcPath};
|
||||
use ide_jsonrpc::{Framing, Handler, Peer, RpcError, codes};
|
||||
use parking_lot::{Mutex, RwLock};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque};
|
||||
use std::collections::{BTreeSet, HashMap, VecDeque};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
|
||||
use std::sync::{Arc, Weak};
|
||||
use std::time::Duration;
|
||||
use timeline::Timeline;
|
||||
|
||||
/// Receives the events of one project's tasks.
|
||||
pub type AgentSink = Arc<dyn Fn(AgentEvent) + Send + Sync>;
|
||||
@@ -40,9 +39,6 @@ const REPLAY_GRACE: Duration = Duration::from_millis(300);
|
||||
/// can trail its `session/prompt` response by this much.
|
||||
const TURN_GRACE: Duration = Duration::from_millis(100);
|
||||
const STDERR_LINES: usize = 20;
|
||||
/// Updates of a session's state rather than its conversation.
|
||||
const SESSION_STATE: [&str; 5] =
|
||||
["session_info_update", "config_option_update", "current_mode_update", "available_commands_update", "usage_update"];
|
||||
/// Referenced files up to this size are embedded in the prompt (when the agent takes it).
|
||||
const MAX_EMBED: u64 = 256 * 1024;
|
||||
|
||||
@@ -156,19 +152,13 @@ struct TaskFile {
|
||||
/// Settings the user chose, re-applied to every new or reloaded session.
|
||||
#[serde(default)]
|
||||
wanted: Vec<AgentConfigChoice>,
|
||||
/// In the project's own checkout: files already changed when the task started.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
before: BTreeMap<String, worktree::Stamp>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
subagents: Vec<SavedSubagent>,
|
||||
}
|
||||
|
||||
struct TaskState {
|
||||
task: AgentTask,
|
||||
session_id: Option<String>,
|
||||
conversation: Conversation,
|
||||
timeline: Timeline,
|
||||
wanted: Vec<AgentConfigChoice>,
|
||||
before: Arc<BTreeMap<String, worktree::Stamp>>,
|
||||
/// A turn is running or about to (prompts arriving now are queued).
|
||||
busy: bool,
|
||||
}
|
||||
@@ -198,10 +188,10 @@ struct Task {
|
||||
replaying: AtomicBool,
|
||||
/// The current turn is being cancelled to send the first queued message right away.
|
||||
send_now: AtomicBool,
|
||||
dirty: Mutex<BTreeSet<(Session, usize)>>,
|
||||
dirty: Mutex<BTreeSet<usize>>,
|
||||
flush_scheduled: AtomicBool,
|
||||
stderr: Mutex<VecDeque<String>>,
|
||||
/// Set by `delete`; held while saving.
|
||||
/// Set by `delete`; held while saving, so a late save can't bring the file back.
|
||||
deleted: Mutex<bool>,
|
||||
}
|
||||
|
||||
@@ -241,9 +231,11 @@ impl AgentManager {
|
||||
// The agent process did not survive the restart: whatever was in flight is over.
|
||||
if matches!(f.task.status, AgentStatus::Running | AgentStatus::NeedsInput | AgentStatus::Starting) {
|
||||
f.task.status = AgentStatus::Ready;
|
||||
let mut timeline = Timeline::from_entries(std::mem::take(&mut f.entries));
|
||||
timeline.end_turn();
|
||||
f.entries = timeline.entries;
|
||||
}
|
||||
let task = Task::restore(f, shared.clone());
|
||||
task.state.lock().conversation.settle(now_ms());
|
||||
tasks.insert(task.id.clone(), task);
|
||||
}
|
||||
Err(e) => tracing::warn!("skipping agent task {}: {e}", path.display()),
|
||||
@@ -305,12 +297,8 @@ impl AgentManager {
|
||||
self.tasks.read().get(id).cloned().ok_or_else(|| IdeError::not_found(format!("no agent task {id}")))
|
||||
}
|
||||
|
||||
/// The entries of the task's conversation, or of its subagent `subagent`'s.
|
||||
pub fn entries(&self, id: &str, subagent: Option<String>) -> IdeResult<Vec<AgentEntry>> {
|
||||
let task = self.task(id)?;
|
||||
let s = task.state.lock();
|
||||
let timeline = s.conversation.timeline(&subagent).ok_or_else(|| IdeError::not_found("no such subagent"))?;
|
||||
Ok(timeline.entries.clone())
|
||||
pub fn entries(&self, id: &str) -> IdeResult<Vec<AgentEntry>> {
|
||||
Ok(self.task(id)?.state.lock().timeline.entries.clone())
|
||||
}
|
||||
|
||||
/// Creates the task (and its worktree) and sends `req.prompt` as its first message.
|
||||
@@ -322,20 +310,18 @@ impl AgentManager {
|
||||
let prompt = clean(req.prompt).ok_or_else(|| IdeError::invalid("describe the task first"))?;
|
||||
let title = title_of(&prompt);
|
||||
let root = self.shared.paths.project_root.clone();
|
||||
let (cwd, branch, base, base_commit, before) = match req.isolation {
|
||||
let (cwd, branch, base, base_commit) = match req.isolation {
|
||||
Isolation::Worktree => {
|
||||
let dir = self.shared.paths.worktrees_dir.clone();
|
||||
let (t, b) = (title.clone(), req.base.clone());
|
||||
let c = blocking(move || worktree::create(&root, &dir, &t, b.as_deref())).await?;
|
||||
(c.path, Some(c.branch), Some(c.base), Some(c.base_commit), BTreeMap::new())
|
||||
(c.path, Some(c.branch), Some(c.base), Some(c.base_commit))
|
||||
}
|
||||
Isolation::Local => {
|
||||
let r = root.clone();
|
||||
let (head, before) =
|
||||
blocking(move || Ok((worktree::head_of(&r).ok(), worktree::snapshot(&r).unwrap_or_default())))
|
||||
.await?;
|
||||
let head = blocking(move || worktree::head_of(&r)).await.ok();
|
||||
let (base, commit) = head.unzip();
|
||||
(root, None, base, commit, before)
|
||||
(root, None, base, commit)
|
||||
}
|
||||
};
|
||||
// Until the session reports its own, show what the agent offered last time with the choices applied.
|
||||
@@ -365,14 +351,7 @@ impl AgentManager {
|
||||
usage: None,
|
||||
queue: Vec::new(),
|
||||
};
|
||||
let file = TaskFile {
|
||||
task: task.clone(),
|
||||
session_id: None,
|
||||
entries: Vec::new(),
|
||||
wanted: req.config,
|
||||
before,
|
||||
subagents: Vec::new(),
|
||||
};
|
||||
let file = TaskFile { task: task.clone(), session_id: None, entries: Vec::new(), wanted: req.config };
|
||||
let handle = Task::restore(file, self.shared.clone());
|
||||
handle.state.lock().busy = true;
|
||||
self.tasks.write().insert(task.id.clone(), handle.clone());
|
||||
@@ -502,17 +481,9 @@ impl AgentManager {
|
||||
}
|
||||
|
||||
/// Stops the current turn (`session/cancel`); pending permission requests are cancelled.
|
||||
/// Queued messages stay queued. With `subagent`, stops only that subagent's work.
|
||||
pub fn cancel(&self, id: &str, subagent: Option<String>) -> IdeResult<()> {
|
||||
let task = self.task(id)?;
|
||||
match subagent {
|
||||
None => task.cancel(),
|
||||
Some(sub) => {
|
||||
if let Some(live) = task.live.lock().clone() {
|
||||
let _ = live.peer.notify("session/cancel", json!({ "sessionId": sub }));
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Queued messages stay queued.
|
||||
pub fn cancel(&self, id: &str) -> IdeResult<()> {
|
||||
self.task(id)?.cancel();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -558,10 +529,8 @@ impl AgentManager {
|
||||
|
||||
/// Files the task changed since it started.
|
||||
pub async fn changes(&self, id: &str) -> IdeResult<Vec<AgentChange>> {
|
||||
let task = self.task(id)?;
|
||||
let (cwd, base) = task.cwd_and_base();
|
||||
let before = task.state.lock().before.clone();
|
||||
blocking(move || Ok(worktree::without_untouched(worktree::changes(&cwd, &base)?, &before))).await
|
||||
let (cwd, base) = self.task(id)?.cwd_and_base();
|
||||
blocking(move || worktree::changes(&cwd, &base)).await
|
||||
}
|
||||
|
||||
/// Content of `path` (in the task's directory) when the task started.
|
||||
@@ -574,8 +543,6 @@ impl AgentManager {
|
||||
pub fn shutdown(&self) {
|
||||
for task in self.tasks.read().values() {
|
||||
task.kill();
|
||||
// What arrived after the last save (a subagent's late updates).
|
||||
task.persist();
|
||||
}
|
||||
*self.shared.sink.write() = None;
|
||||
}
|
||||
@@ -584,16 +551,15 @@ impl AgentManager {
|
||||
impl Task {
|
||||
fn restore(file: TaskFile, shared: Arc<Shared>) -> Arc<Self> {
|
||||
let task = file.task;
|
||||
let conversation = Conversation::restore(file.entries, file.subagents);
|
||||
let timeline = Timeline::from_entries(file.entries);
|
||||
Arc::new(Self {
|
||||
id: task.id.clone(),
|
||||
shared,
|
||||
state: Mutex::new(TaskState {
|
||||
task,
|
||||
session_id: file.session_id,
|
||||
conversation,
|
||||
timeline,
|
||||
wanted: file.wanted,
|
||||
before: Arc::new(file.before),
|
||||
busy: false,
|
||||
}),
|
||||
live: Mutex::new(None),
|
||||
@@ -611,13 +577,7 @@ impl Task {
|
||||
|
||||
fn cwd_and_base(&self) -> (PathBuf, String) {
|
||||
let s = self.state.lock();
|
||||
// In the project's own checkout the user commits too: compare against the current HEAD,
|
||||
// as the Commit tool window does, so commits made since the task started drop out.
|
||||
let base = match s.task.isolation {
|
||||
Isolation::Local => None,
|
||||
Isolation::Worktree => s.task.base_commit.clone(),
|
||||
};
|
||||
(s.task.cwd.0.clone(), base.unwrap_or_else(|| "HEAD".into()))
|
||||
(s.task.cwd.0.clone(), s.task.base_commit.clone().unwrap_or_else(|| "HEAD".into()))
|
||||
}
|
||||
|
||||
fn emit_task(&self) {
|
||||
@@ -638,29 +598,26 @@ impl Task {
|
||||
}
|
||||
|
||||
fn persist(&self) {
|
||||
// Held from snapshot to rename, so saves land in order and none follows a delete.
|
||||
let deleted = self.deleted.lock();
|
||||
if *deleted {
|
||||
return;
|
||||
}
|
||||
let bytes = {
|
||||
let s = self.state.lock();
|
||||
serde_json::to_vec(&TaskFile {
|
||||
task: s.task.clone(),
|
||||
session_id: s.session_id.clone(),
|
||||
entries: s.conversation.main.entries.clone(),
|
||||
entries: s.timeline.entries.clone(),
|
||||
wanted: s.wanted.clone(),
|
||||
before: (*s.before).clone(),
|
||||
subagents: s.conversation.saved_subagents(),
|
||||
})
|
||||
};
|
||||
let path = self.shared.paths.store_dir.join(format!("{}.json", self.id));
|
||||
let deleted = self.deleted.lock();
|
||||
if *deleted {
|
||||
return;
|
||||
}
|
||||
if let Err(e) = bytes.map_err(|e| e.to_string()).and_then(|b| write_file(&path, &b)) {
|
||||
tracing::warn!("saving agent task {}: {e}", self.id);
|
||||
}
|
||||
}
|
||||
|
||||
fn mark_dirty(self: &Arc<Self>, indices: impl IntoIterator<Item = (Session, usize)>) {
|
||||
fn mark_dirty(self: &Arc<Self>, indices: impl IntoIterator<Item = usize>) {
|
||||
self.dirty.lock().extend(indices);
|
||||
if !self.flush_scheduled.swap(true, Ordering::AcqRel) {
|
||||
let task = self.clone();
|
||||
@@ -678,9 +635,9 @@ impl Task {
|
||||
let s = self.state.lock();
|
||||
indices
|
||||
.into_iter()
|
||||
.filter_map(|(subagent, i)| {
|
||||
let entry = s.conversation.timeline(&subagent)?.entries.get(i)?.clone();
|
||||
Some(AgentEvent::Entry { task: self.id.clone(), subagent, index: i as u32, entry })
|
||||
.filter_map(|i| {
|
||||
let entry = s.timeline.entries.get(i)?.clone();
|
||||
Some(AgentEvent::Entry { task: self.id.clone(), index: i as u32, entry })
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
@@ -690,8 +647,8 @@ impl Task {
|
||||
}
|
||||
|
||||
fn push_entry(self: &Arc<Self>, entry: AgentEntry) -> usize {
|
||||
let i = self.state.lock().conversation.main.push(entry);
|
||||
self.mark_dirty([(None, i)]);
|
||||
let i = self.state.lock().timeline.push(entry);
|
||||
self.mark_dirty([i]);
|
||||
i
|
||||
}
|
||||
|
||||
@@ -701,7 +658,7 @@ impl Task {
|
||||
loop {
|
||||
let result = self.turn(&prompt).await;
|
||||
tokio::time::sleep(TURN_GRACE).await;
|
||||
let changed = self.state.lock().conversation.end_turn(Some(now_ms()));
|
||||
let changed = self.state.lock().timeline.end_turn();
|
||||
self.mark_dirty(changed);
|
||||
let send_now = self.send_now.swap(false, Ordering::AcqRel);
|
||||
let next = {
|
||||
@@ -745,12 +702,7 @@ impl Task {
|
||||
.map(|f| file_name(&f.0))
|
||||
.chain(prompt.images.iter().map(|i| i.name.clone().unwrap_or_else(|| "image".into())))
|
||||
.collect();
|
||||
self.push_entry(AgentEntry::User {
|
||||
text: prompt.text.clone(),
|
||||
attachments,
|
||||
sent_ms: Some(now_ms()),
|
||||
done_ms: None,
|
||||
});
|
||||
self.push_entry(AgentEntry::User { text: prompt.text.clone(), attachments });
|
||||
// Launching the agent can take a while (`npx` fetches its adapter on first use).
|
||||
let starting = self.live.lock().as_ref().is_none_or(|l| l.peer.is_closed());
|
||||
self.set_status(if starting { AgentStatus::Starting } else { AgentStatus::Running }, None);
|
||||
@@ -815,12 +767,7 @@ impl Task {
|
||||
"initialize",
|
||||
json!({
|
||||
"protocolVersion": 1,
|
||||
"clientCapabilities": {
|
||||
"fs": { "readTextFile": false, "writeTextFile": false },
|
||||
"terminal": false,
|
||||
// Subagents as sessions of their own (ACP subagents RFD).
|
||||
"subagents": {},
|
||||
},
|
||||
"clientCapabilities": { "fs": { "readTextFile": false, "writeTextFile": false }, "terminal": false },
|
||||
"clientInfo": { "name": "OpenIDEA", "version": env!("CARGO_PKG_VERSION") },
|
||||
}),
|
||||
None,
|
||||
@@ -921,26 +868,8 @@ impl Task {
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies a `session/update` of session `session` (the task's, or one of its subagents').
|
||||
fn on_update(self: &Arc<Self>, session: Option<&str>, update: &Value) {
|
||||
fn on_update(self: &Arc<Self>, update: &Value) {
|
||||
let kind = update.get("sessionUpdate").and_then(Value::as_str).unwrap_or_default();
|
||||
// A subagent's title, settings and usage are its own, not the task's.
|
||||
if self.state.lock().conversation.owner(session).is_some() {
|
||||
if !SESSION_STATE.contains(&kind) && !self.replaying.load(Ordering::Acquire) {
|
||||
self.apply(session, kind, update);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if kind == "session_info_update" {
|
||||
// The agent's own title for the session replaces the first line of the prompt.
|
||||
let title = update.get("title").and_then(Value::as_str).map(str::trim).filter(|t| !t.is_empty());
|
||||
if let Some(title) = title {
|
||||
self.state.lock().task.title = title.to_owned();
|
||||
self.persist();
|
||||
self.emit_task();
|
||||
}
|
||||
return;
|
||||
}
|
||||
// Session state (also while `session/load` replays history).
|
||||
let provider = self.state.lock().task.provider.clone();
|
||||
let task_changed = {
|
||||
@@ -985,16 +914,8 @@ impl Task {
|
||||
if self.replaying.load(Ordering::Acquire) {
|
||||
return;
|
||||
}
|
||||
self.apply(session, kind, update);
|
||||
}
|
||||
|
||||
fn apply(self: &Arc<Self>, session: Option<&str>, kind: &str, update: &Value) {
|
||||
let applied = self.state.lock().conversation.apply(session, update, now_ms());
|
||||
self.mark_dirty(applied);
|
||||
// A subagent can start or finish after the turn that started it: saved right away.
|
||||
if kind == "subagent_update" {
|
||||
self.persist();
|
||||
}
|
||||
let applied = self.state.lock().timeline.apply(update);
|
||||
self.mark_dirty(applied.changed);
|
||||
}
|
||||
|
||||
/// Blocks the calling (blocking-pool) thread until the user answers.
|
||||
@@ -1006,12 +927,6 @@ impl Task {
|
||||
.filter(|t| !t.is_empty())
|
||||
.unwrap_or("The agent asks for permission")
|
||||
.to_owned();
|
||||
// A subagent's request is answered in the task's conversation, named after the subagent.
|
||||
let session = params.get("sessionId").and_then(Value::as_str);
|
||||
let title = match session.and_then(|s| self.state.lock().conversation.label(s)) {
|
||||
Some(label) => format!("{label}: {title}"),
|
||||
None => title,
|
||||
};
|
||||
let options: Vec<AgentPermissionOption> = params
|
||||
.get("options")
|
||||
.and_then(Value::as_array)
|
||||
@@ -1039,11 +954,11 @@ impl Task {
|
||||
.map_or_else(|| "Cancelled".to_owned(), |o| o.name.clone());
|
||||
{
|
||||
let mut s = self.state.lock();
|
||||
if let Some(AgentEntry::Permission { chosen, .. }) = s.conversation.main.entries.get_mut(entry) {
|
||||
if let Some(AgentEntry::Permission { chosen, .. }) = s.timeline.entries.get_mut(entry) {
|
||||
*chosen = Some(name);
|
||||
}
|
||||
}
|
||||
self.mark_dirty([(None, entry)]);
|
||||
self.mark_dirty([entry]);
|
||||
let still_asking = !self.permissions.lock().is_empty();
|
||||
if !still_asking && self.state.lock().task.status == AgentStatus::NeedsInput {
|
||||
self.set_status(AgentStatus::Running, None);
|
||||
@@ -1085,7 +1000,7 @@ impl Handler for Client {
|
||||
if method == "session/update"
|
||||
&& let (Some(task), Some(update)) = (self.task.upgrade(), params.get("update"))
|
||||
{
|
||||
task.on_update(params.get("sessionId").and_then(Value::as_str), update);
|
||||
task.on_update(update);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -44,7 +44,7 @@ pub struct AgentTask {
|
||||
pub branch: Option<String>,
|
||||
/// Branch (or revision) the worktree was created from.
|
||||
pub base: Option<String>,
|
||||
/// Commit the task's changes are compared against (worktree tasks; local ones use `HEAD`).
|
||||
/// Commit the task's changes are compared against.
|
||||
pub base_commit: Option<String>,
|
||||
/// Why the task failed, when it did.
|
||||
pub error: Option<String>,
|
||||
@@ -114,6 +114,9 @@ pub struct AgentUsage {
|
||||
pub used: u32,
|
||||
/// Size of the context window.
|
||||
pub size: u32,
|
||||
/// Session cost so far.
|
||||
pub cost: Option<f64>,
|
||||
pub currency: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
@@ -166,18 +169,6 @@ pub struct AgentToolDiff {
|
||||
pub removed: u32,
|
||||
}
|
||||
|
||||
/// What a subagent is doing, as its parent reports it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AgentSubagentStatus {
|
||||
Running,
|
||||
/// One of its requests (a permission) waits for an answer.
|
||||
NeedsInput,
|
||||
Done,
|
||||
Cancelled,
|
||||
Failed,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentPlanItem {
|
||||
@@ -203,12 +194,6 @@ pub enum AgentEntry {
|
||||
text: String,
|
||||
/// Names of the files and images sent with it.
|
||||
attachments: Vec<String>,
|
||||
/// When it was sent (ms since the epoch); `None` in tasks saved before this was kept.
|
||||
#[serde(default)]
|
||||
sent_ms: Option<f64>,
|
||||
/// When the turn it started ended; `None` while it runs or when it was cut off.
|
||||
#[serde(default)]
|
||||
done_ms: Option<f64>,
|
||||
},
|
||||
Agent {
|
||||
text: String,
|
||||
@@ -230,33 +215,6 @@ pub enum AgentEntry {
|
||||
Plan {
|
||||
items: Vec<AgentPlanItem>,
|
||||
},
|
||||
/// A subagent the agent started: its own session, whose entries are listed separately.
|
||||
Subagent {
|
||||
/// The subagent's session id.
|
||||
id: String,
|
||||
title: Option<String>,
|
||||
description: Option<String>,
|
||||
status: AgentSubagentStatus,
|
||||
error: Option<String>,
|
||||
/// What it was asked to do, last.
|
||||
prompt: Option<String>,
|
||||
/// Its answer.
|
||||
reply: Option<String>,
|
||||
/// Tool calls it made.
|
||||
tools: u32,
|
||||
/// Title of its latest tool call.
|
||||
activity: Option<String>,
|
||||
started_ms: f64,
|
||||
/// When it last stopped working; `None` while it works.
|
||||
ended_ms: Option<f64>,
|
||||
/// Whether it can be stopped on its own.
|
||||
cancellable: bool,
|
||||
},
|
||||
/// A message between sessions in a subagent's conversation: its task (`incoming`) or its report.
|
||||
Message {
|
||||
incoming: bool,
|
||||
text: String,
|
||||
},
|
||||
Permission {
|
||||
id: u32,
|
||||
title: String,
|
||||
@@ -318,10 +276,9 @@ pub enum AgentEvent {
|
||||
Removed {
|
||||
id: String,
|
||||
},
|
||||
/// Entry `index` of `task` (of its subagent `subagent`) was added or replaced.
|
||||
/// Entry `index` of `task` was added or replaced.
|
||||
Entry {
|
||||
task: String,
|
||||
subagent: Option<String>,
|
||||
index: u32,
|
||||
entry: AgentEntry,
|
||||
},
|
||||
|
||||
@@ -25,44 +25,6 @@ impl FakeAgent {
|
||||
}
|
||||
}
|
||||
|
||||
impl FakeAgent {
|
||||
/// Runs a subagent in session `c1`, as an agent with ACP subagent sessions reports it.
|
||||
fn delegate(&self, root: &str) {
|
||||
let sub = |state: Value| json!({"sessionUpdate": "subagent_update", "sessionId": "c1", "state": state});
|
||||
let mut announce = sub(json!({"state": "running"}));
|
||||
announce["title"] = json!("Explore");
|
||||
self.update(root, announce);
|
||||
self.update(
|
||||
root,
|
||||
json!({"sessionUpdate": "session_message", "messageId": "m1", "senderSessionId": root,
|
||||
"recipientSessionId": "c1", "content": [{"type": "text", "text": "Find the lexer"}]}),
|
||||
);
|
||||
self.update("c1", json!({"sessionUpdate": "usage_update", "used": 900, "size": 1000}));
|
||||
self.update(
|
||||
"c1",
|
||||
json!({"sessionUpdate": "tool_call", "toolCallId": "c1-t1", "title": "Read lexer.rs",
|
||||
"kind": "read", "status": "completed"}),
|
||||
);
|
||||
let peer = self.peer.get().unwrap().clone();
|
||||
let _: Value = tokio::runtime::Handle::current()
|
||||
.block_on(peer.request(
|
||||
"session/request_permission",
|
||||
json!({"sessionId": "c1", "toolCall": {"toolCallId": "c1-t2", "title": "Run ls"},
|
||||
"options": [{"optionId": "yes", "name": "Allow", "kind": "allow_once"}]}),
|
||||
None,
|
||||
))
|
||||
.unwrap();
|
||||
self.say("c1", "It is in lexer.rs");
|
||||
self.update(root, sub(json!({"state": "idle", "stopReason": "end_turn"})));
|
||||
self.update(
|
||||
root,
|
||||
json!({"sessionUpdate": "session_message", "messageId": "m2", "senderSessionId": "c1",
|
||||
"recipientSessionId": root, "content": [{"type": "text", "text": "lexer.rs"}]}),
|
||||
);
|
||||
self.say(root, "Found it");
|
||||
}
|
||||
}
|
||||
|
||||
impl Handler for FakeAgent {
|
||||
fn on_notification(&self, method: &str, _: Value) {
|
||||
self.calls.lock().push(method.to_owned());
|
||||
@@ -72,12 +34,7 @@ impl Handler for FakeAgent {
|
||||
self.calls.lock().push(method.to_owned());
|
||||
let session = params.get("sessionId").and_then(Value::as_str).unwrap_or("s1").to_owned();
|
||||
match method {
|
||||
"initialize" => {
|
||||
if params.pointer("/clientCapabilities/subagents").is_some_and(Value::is_object) {
|
||||
self.calls.lock().push("subagents".into());
|
||||
}
|
||||
Ok(json!({"protocolVersion": 1, "agentCapabilities": {"loadSession": true}}))
|
||||
}
|
||||
"initialize" => Ok(json!({"protocolVersion": 1, "agentCapabilities": {"loadSession": true}})),
|
||||
"session/new" => Ok(json!({"sessionId": "s1",
|
||||
"modes": {"currentModeId": "ask", "availableModes": [{"id": "ask", "name": "Ask"}, {"id": "code", "name": "Code"}]},
|
||||
"configOptions": [{"id": "model", "category": "model", "type": "select", "currentValue": "big",
|
||||
@@ -96,10 +53,6 @@ impl Handler for FakeAgent {
|
||||
self.say(&session, "second turn");
|
||||
return Ok(json!({"stopReason": "end_turn"}));
|
||||
}
|
||||
if text == "delegate" {
|
||||
self.delegate(&session);
|
||||
return Ok(json!({"stopReason": "end_turn"}));
|
||||
}
|
||||
if text == "wait" {
|
||||
// Works until cancelled.
|
||||
while !self.calls.lock().iter().any(|c| c == "session/cancel") {
|
||||
@@ -113,7 +66,6 @@ impl Handler for FakeAgent {
|
||||
"availableCommands": [{"name": "review", "description": "Review", "input": {"hint": "focus"}}]}),
|
||||
);
|
||||
self.update(&session, json!({"sessionUpdate": "usage_update", "used": 50, "size": 1000}));
|
||||
self.update(&session, json!({"sessionUpdate": "session_info_update", "title": "Lexer fix"}));
|
||||
self.say(&session, "Hi");
|
||||
self.update(
|
||||
&session,
|
||||
@@ -241,7 +193,7 @@ async fn a_task_runs_asks_for_permission_and_survives_a_restart() {
|
||||
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
|
||||
|
||||
let permission = mgr
|
||||
.entries(&task.id, None)
|
||||
.entries(&task.id)
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find_map(|e| match e {
|
||||
@@ -252,7 +204,7 @@ async fn a_task_runs_asks_for_permission_and_survives_a_restart() {
|
||||
mgr.respond(&task.id, permission, Some("yes".into())).unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
|
||||
let entries = mgr.entries(&task.id, None).unwrap();
|
||||
let entries = mgr.entries(&task.id).unwrap();
|
||||
let kinds: Vec<String> = entries
|
||||
.iter()
|
||||
.map(|e| match e {
|
||||
@@ -274,7 +226,6 @@ async fn a_task_runs_asks_for_permission_and_survives_a_restart() {
|
||||
assert_eq!((modes.via, modes.current.as_deref()), (AgentConfigVia::Mode, Some("ask")));
|
||||
assert_eq!(t.commands.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["review"]);
|
||||
assert_eq!(t.usage.as_ref().map(|u| (u.used, u.size)), Some((50, 1000)));
|
||||
assert_eq!(t.title, "Lexer fix", "the agent's title replaces the prompt's first line");
|
||||
}
|
||||
mgr.set_config(&task.id, "mode", "code".into()).await.unwrap();
|
||||
assert!(agent.calls.lock().contains(&"session/set_mode \"code\"".to_owned()));
|
||||
@@ -287,17 +238,10 @@ async fn a_task_runs_asks_for_permission_and_survives_a_restart() {
|
||||
events.iter().any(|e| matches!(e, AgentEvent::Task { task } if task.status == AgentStatus::NeedsInput))
|
||||
);
|
||||
let last_entry = events.iter().rev().find_map(|e| match e {
|
||||
AgentEvent::Entry { index, entry, .. } if !matches!(entry, AgentEntry::User { .. }) => {
|
||||
Some((*index, entry.clone()))
|
||||
}
|
||||
AgentEvent::Entry { index, entry, .. } => Some((*index, entry.clone())),
|
||||
_ => None,
|
||||
});
|
||||
assert_eq!(last_entry, Some((4, AgentEntry::Agent { text: "chose yes".into() })));
|
||||
// The turn's end is recorded on the message that started it.
|
||||
assert!(events.iter().any(|e| matches!(
|
||||
e,
|
||||
AgentEvent::Entry { index: 0, entry: AgentEntry::User { sent_ms: Some(_), done_ms: Some(_), .. }, .. }
|
||||
)));
|
||||
}
|
||||
let providers = mgr.providers();
|
||||
let claude = providers.iter().find(|p| p.id == "claude").unwrap();
|
||||
@@ -308,13 +252,12 @@ async fn a_task_runs_asks_for_permission_and_survives_a_restart() {
|
||||
mgr.shutdown();
|
||||
let agent2 = Arc::new(FakeAgent::default());
|
||||
let mgr2 = manager(tmp.path(), agent2.clone());
|
||||
assert_eq!(mgr2.entries(&task.id, None).unwrap().len(), 5);
|
||||
assert_eq!(mgr2.task(&task.id).unwrap().state.lock().task.title, "Lexer fix");
|
||||
assert_eq!(mgr2.entries(&task.id).unwrap().len(), 5);
|
||||
assert_eq!(mgr2.providers().iter().find(|p| p.id == "claude").unwrap().config.len(), 2);
|
||||
mgr2.prompt(&task.id, text("again"), false).await.unwrap();
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
wait_for(&mgr2, &task.id, AgentStatus::Ready).await;
|
||||
let entries = mgr2.entries(&task.id, None).unwrap();
|
||||
let entries = mgr2.entries(&task.id).unwrap();
|
||||
assert_eq!(entries.len(), 7);
|
||||
assert_eq!(entries[6], AgentEntry::Agent { text: "second turn".into() });
|
||||
assert!(agent2.calls.lock().contains(&"session/load".to_owned()));
|
||||
@@ -350,14 +293,14 @@ async fn messages_sent_while_busy_are_queued_and_send_now_interrupts() {
|
||||
|
||||
mgr.send_queued_now(&task.id, &queue[0].id).unwrap();
|
||||
for _ in 0..500 {
|
||||
if mgr.entries(&task.id, None).unwrap().iter().any(|e| *e == AgentEntry::Agent { text: "second turn".into() }) {
|
||||
if mgr.entries(&task.id).unwrap().iter().any(|e| *e == AgentEntry::Agent { text: "second turn".into() }) {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
let users: Vec<String> = mgr
|
||||
.entries(&task.id, None)
|
||||
.entries(&task.id)
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.filter_map(|e| match e {
|
||||
@@ -373,7 +316,7 @@ async fn messages_sent_while_busy_are_queued_and_send_now_interrupts() {
|
||||
wait_for(&mgr, &task.id, AgentStatus::Running).await;
|
||||
agent.calls.lock().retain(|c| c != "session/cancel");
|
||||
mgr.prompt(&task.id, text("later"), false).await.unwrap();
|
||||
mgr.cancel(&task.id, None).unwrap();
|
||||
mgr.cancel(&task.id).unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
let queued = mgr.task(&task.id).unwrap().state.lock().task.queue.clone();
|
||||
assert_eq!(queued.len(), 1);
|
||||
@@ -381,68 +324,6 @@ async fn messages_sent_while_busy_are_queued_and_send_now_interrupts() {
|
||||
assert!(mgr.task(&task.id).unwrap().state.lock().task.queue.is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn subagents_get_their_own_conversation() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text("delegate"),
|
||||
provider: "claude".into(),
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
// The subagent's permission request is answered in the task's conversation.
|
||||
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
|
||||
let (id, title) = mgr
|
||||
.entries(&task.id, None)
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.find_map(|e| match e {
|
||||
AgentEntry::Permission { id, title, .. } => Some((id, title)),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(title, "Explore: Run ls");
|
||||
mgr.respond(&task.id, id, Some("yes".into())).unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
assert!(agent.calls.lock().iter().any(|c| c == "subagents"));
|
||||
|
||||
let check = |mgr: &AgentManager| {
|
||||
let main = mgr.entries(&task.id, None).unwrap();
|
||||
let card = main.iter().find(|e| matches!(e, AgentEntry::Subagent { .. })).unwrap();
|
||||
let AgentEntry::Subagent { title, status, prompt, reply, tools, activity, .. } = card else { unreachable!() };
|
||||
assert_eq!(title.as_deref(), Some("Explore"));
|
||||
assert_eq!(*status, AgentSubagentStatus::Done);
|
||||
assert_eq!((prompt.as_deref(), reply.as_deref()), (Some("Find the lexer"), Some("lexer.rs")));
|
||||
assert_eq!((*tools, activity.as_deref()), (1, Some("Read lexer.rs")));
|
||||
assert!(main.contains(&AgentEntry::Agent { text: "Found it".into() }));
|
||||
assert!(!main.iter().any(|e| matches!(e, AgentEntry::Tool { .. })));
|
||||
let sub = mgr.entries(&task.id, Some("c1".into())).unwrap();
|
||||
assert!(matches!(&sub[0], AgentEntry::Tool { title, .. } if title == "Read lexer.rs"));
|
||||
assert_eq!(sub[1], AgentEntry::Agent { text: "It is in lexer.rs".into() });
|
||||
};
|
||||
// Updates can trail the end of the turn.
|
||||
for _ in 0..500 {
|
||||
if mgr.entries(&task.id, None).unwrap().contains(&AgentEntry::Agent { text: "Found it".into() }) {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
check(&mgr);
|
||||
// The subagent's context use is not the task's.
|
||||
assert_ne!(mgr.task(&task.id).unwrap().state.lock().task.usage.as_ref().map(|u| u.used), Some(900));
|
||||
assert!(mgr.entries(&task.id, Some("nope".into())).is_err());
|
||||
|
||||
// Saved with the task.
|
||||
mgr.shutdown();
|
||||
check(&manager(tmp.path(), Arc::new(FakeAgent::default())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prompts_become_acp_content_blocks() {
|
||||
let p = AgentPrompt {
|
||||
@@ -490,15 +371,15 @@ async fn cancelling_resolves_the_open_permission_and_delete_forgets_the_task() {
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
|
||||
mgr.cancel(&task.id, None).unwrap();
|
||||
mgr.cancel(&task.id).unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
let entries = mgr.entries(&task.id, None).unwrap();
|
||||
let entries = mgr.entries(&task.id).unwrap();
|
||||
assert!(entries.iter().any(|e| matches!(e, AgentEntry::Permission { chosen: Some(c), .. } if c == "Cancelled")));
|
||||
assert_eq!(entries.last(), Some(&AgentEntry::Agent { text: "chose none".into() }));
|
||||
assert_eq!(mgr.task(&task.id).unwrap().state.lock().task.model.as_deref(), Some("big"), "the agent's default");
|
||||
|
||||
mgr.delete(&task.id, false).await.unwrap();
|
||||
assert!(mgr.entries(&task.id, None).is_err());
|
||||
assert!(mgr.entries(&task.id).is_err());
|
||||
assert!(!tmp.path().join("store").join(format!("{}.json", task.id)).exists());
|
||||
assert!(
|
||||
mgr.create(NewAgentTask {
|
||||
@@ -561,7 +442,7 @@ async fn real_claude_task_in_a_worktree() {
|
||||
let status = mgr.task(&task.id).unwrap().state.lock().task.status;
|
||||
match status {
|
||||
AgentStatus::NeedsInput => {
|
||||
let pending = mgr.entries(&task.id, None).unwrap().into_iter().rev().find_map(|e| match e {
|
||||
let pending = mgr.entries(&task.id).unwrap().into_iter().rev().find_map(|e| match e {
|
||||
AgentEntry::Permission { id, options, chosen: None, .. } => Some((id, options)),
|
||||
_ => None,
|
||||
});
|
||||
@@ -576,7 +457,7 @@ async fn real_claude_task_in_a_worktree() {
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
}
|
||||
for e in mgr.entries(&task.id, None).unwrap() {
|
||||
for e in mgr.entries(&task.id).unwrap() {
|
||||
eprintln!("{e:?}");
|
||||
}
|
||||
let t = mgr.task(&task.id).unwrap().state.lock().task.clone();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Folds ACP `session/update` notifications into a task's entries.
|
||||
|
||||
use crate::model::{AgentEntry, AgentPlanItem, AgentSubagentStatus, AgentToolDiff, AgentToolStatus};
|
||||
use crate::model::{AgentEntry, AgentPlanItem, AgentToolDiff, AgentToolStatus};
|
||||
use ide_core::IpcPath;
|
||||
use serde_json::Value;
|
||||
use std::collections::HashMap;
|
||||
@@ -13,10 +13,6 @@ pub(crate) struct Timeline {
|
||||
pub entries: Vec<AgentEntry>,
|
||||
tools: HashMap<String, usize>,
|
||||
plan: Option<usize>,
|
||||
/// Subagent cards, by the subagent's session id.
|
||||
cards: HashMap<String, usize>,
|
||||
/// Session messages, by message id.
|
||||
messages: HashMap<String, usize>,
|
||||
}
|
||||
|
||||
/// What a `session/update` changed in the timeline.
|
||||
@@ -35,9 +31,6 @@ impl Timeline {
|
||||
t.tools.insert(id.clone(), i);
|
||||
}
|
||||
AgentEntry::Plan { .. } => t.plan = Some(i),
|
||||
AgentEntry::Subagent { id, .. } => {
|
||||
t.cards.insert(id.clone(), i);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -173,130 +166,11 @@ impl Timeline {
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds or updates the card of subagent `id` from its `subagent_update`; returns the
|
||||
/// card's index and whether the subagent just stopped working.
|
||||
pub fn subagent(&mut self, id: &str, update: &Value, now: f64) -> (usize, bool) {
|
||||
let index = match self.cards.get(id) {
|
||||
Some(&i) => i,
|
||||
None => {
|
||||
let i = self.push(AgentEntry::Subagent {
|
||||
id: id.to_owned(),
|
||||
title: None,
|
||||
description: None,
|
||||
status: AgentSubagentStatus::Running,
|
||||
error: None,
|
||||
prompt: None,
|
||||
reply: None,
|
||||
tools: 0,
|
||||
activity: None,
|
||||
started_ms: now,
|
||||
ended_ms: None,
|
||||
cancellable: false,
|
||||
});
|
||||
self.cards.insert(id.to_owned(), i);
|
||||
i
|
||||
}
|
||||
};
|
||||
let AgentEntry::Subagent { title, description, status, error, ended_ms, cancellable, .. } =
|
||||
&mut self.entries[index]
|
||||
else {
|
||||
return (index, false);
|
||||
};
|
||||
// Patch semantics: an omitted field is unchanged, `null` clears it.
|
||||
if let Some(v) = update.get("title") {
|
||||
*title = v.as_str().map(str::to_owned);
|
||||
}
|
||||
if let Some(v) = update.get("description") {
|
||||
*description = v.as_str().map(str::to_owned);
|
||||
}
|
||||
if let Some(v) = update.get("capabilities") {
|
||||
*cancellable = v.get("cancel").is_some_and(Value::is_object);
|
||||
}
|
||||
let mut stopped = false;
|
||||
if let Some((next, message)) = update.get("state").and_then(subagent_status) {
|
||||
let working = matches!(next, AgentSubagentStatus::Running | AgentSubagentStatus::NeedsInput);
|
||||
stopped = !working && ended_ms.is_none();
|
||||
*ended_ms = if working { None } else { ended_ms.or(Some(now)) };
|
||||
*status = next;
|
||||
*error = message;
|
||||
}
|
||||
(index, stopped)
|
||||
}
|
||||
|
||||
/// Sets (or with `append`, extends) what subagent `id` was asked or answered, on its card.
|
||||
pub fn card_message(&mut self, id: &str, reply: bool, text: &str, append: bool) -> Option<usize> {
|
||||
let &index = self.cards.get(id)?;
|
||||
let AgentEntry::Subagent { prompt, reply: answer, .. } = &mut self.entries[index] else { return None };
|
||||
let field = if reply { answer } else { prompt };
|
||||
match field {
|
||||
Some(t) if append => t.push_str(text),
|
||||
_ => *field = Some(text.to_owned()),
|
||||
}
|
||||
Some(index)
|
||||
}
|
||||
|
||||
/// Adds, replaces or (with `append`) extends session message `id`.
|
||||
pub fn message(&mut self, id: &str, incoming: bool, text: &str, append: bool) -> usize {
|
||||
if let Some(&i) = self.messages.get(id)
|
||||
&& let AgentEntry::Message { text: t, .. } = &mut self.entries[i]
|
||||
{
|
||||
if append {
|
||||
t.push_str(text);
|
||||
} else {
|
||||
*t = text.to_owned();
|
||||
}
|
||||
return i;
|
||||
}
|
||||
let i = self.push(AgentEntry::Message { incoming, text: text.to_owned() });
|
||||
self.messages.insert(id.to_owned(), i);
|
||||
i
|
||||
}
|
||||
|
||||
/// Updates subagent `id`'s card with what its own timeline `of` shows: how many tool
|
||||
/// calls it made and its latest one. Returns the card's index when it changed.
|
||||
pub fn card_activity(&mut self, id: &str, of: &Timeline) -> Option<usize> {
|
||||
let &index = self.cards.get(id)?;
|
||||
let AgentEntry::Subagent { tools, activity, .. } = &mut self.entries[index] else { return None };
|
||||
let calls = of.entries.iter().filter_map(|e| match e {
|
||||
AgentEntry::Tool { title, kind, .. } => Some(if title.is_empty() { kind } else { title }),
|
||||
_ => None,
|
||||
});
|
||||
let count = calls.clone().count() as u32;
|
||||
let latest = calls.clone().next_back().cloned();
|
||||
if *tools == count && *activity == latest {
|
||||
return None;
|
||||
}
|
||||
*tools = count;
|
||||
*activity = latest;
|
||||
Some(index)
|
||||
}
|
||||
|
||||
/// Marks the subagents still working as stopped (their agent is gone).
|
||||
pub fn stop_subagents(&mut self, now: f64) -> Vec<usize> {
|
||||
/// Settles what an ended turn left open: running tools and pending permissions.
|
||||
pub fn end_turn(&mut self) -> Vec<usize> {
|
||||
let mut changed = Vec::new();
|
||||
for (i, e) in self.entries.iter_mut().enumerate() {
|
||||
if let AgentEntry::Subagent { status, ended_ms, .. } = e
|
||||
&& matches!(status, AgentSubagentStatus::Running | AgentSubagentStatus::NeedsInput)
|
||||
{
|
||||
*status = AgentSubagentStatus::Cancelled;
|
||||
*ended_ms = Some(now);
|
||||
changed.push(i);
|
||||
}
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// Settles what an ended turn left open: running tools and pending permissions,
|
||||
/// and records when the turn ended (`done`) on the message that started it.
|
||||
pub fn end_turn(&mut self, done: Option<f64>) -> Vec<usize> {
|
||||
let mut changed = Vec::new();
|
||||
let started = self.entries.iter().rposition(|e| matches!(e, AgentEntry::User { .. }));
|
||||
for (i, e) in self.entries.iter_mut().enumerate() {
|
||||
match e {
|
||||
AgentEntry::User { done_ms, .. } if Some(i) == started && done.is_some() && done_ms.is_none() => {
|
||||
*done_ms = done;
|
||||
changed.push(i);
|
||||
}
|
||||
AgentEntry::Tool { status, .. }
|
||||
if matches!(status, AgentToolStatus::Pending | AgentToolStatus::Running) =>
|
||||
{
|
||||
@@ -318,30 +192,7 @@ fn str_field(v: &Value, key: &str) -> String {
|
||||
v.get(key).and_then(Value::as_str).unwrap_or_default().to_owned()
|
||||
}
|
||||
|
||||
/// The status a subagent `state` reports, with its error message; `None` for an unknown state.
|
||||
fn subagent_status(state: &Value) -> Option<(AgentSubagentStatus, Option<String>)> {
|
||||
Some(match state.get("state")?.as_str()? {
|
||||
"running" => (AgentSubagentStatus::Running, None),
|
||||
"requires_action" => (AgentSubagentStatus::NeedsInput, None),
|
||||
"idle" => match state.get("stopReason").and_then(Value::as_str) {
|
||||
Some("cancelled") => (AgentSubagentStatus::Cancelled, None),
|
||||
Some("error") => (
|
||||
AgentSubagentStatus::Failed,
|
||||
state.pointer("/error/message").and_then(Value::as_str).map(str::to_owned),
|
||||
),
|
||||
_ => (AgentSubagentStatus::Done, None),
|
||||
},
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The text of a list of content blocks, one per line.
|
||||
pub(crate) fn blocks_text(content: Option<&Value>) -> String {
|
||||
let blocks = content.and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default();
|
||||
blocks.iter().filter_map(|b| content_text(Some(b))).collect::<Vec<_>>().join("\n")
|
||||
}
|
||||
|
||||
pub(crate) fn content_text(content: Option<&Value>) -> Option<String> {
|
||||
fn content_text(content: Option<&Value>) -> Option<String> {
|
||||
let c = content?;
|
||||
match c.get("type").and_then(Value::as_str) {
|
||||
Some("text") => c.get("text").and_then(Value::as_str).map(str::to_owned),
|
||||
@@ -435,27 +286,12 @@ mod tests {
|
||||
assert_eq!(t.apply(&plan("completed")).changed, vec![0]);
|
||||
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "c", "title": "Run", "status": "in_progress"}));
|
||||
t.push(AgentEntry::Permission { id: 1, title: "Run?".into(), options: vec![], chosen: None });
|
||||
assert_eq!(t.end_turn(None), vec![2, 3]);
|
||||
assert_eq!(t.end_turn(), vec![2, 3]);
|
||||
let again = Timeline::from_entries(t.entries.clone());
|
||||
assert_eq!(again.plan, Some(0));
|
||||
assert_eq!(again.tools.get("c"), Some(&2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn end_turn_records_when_the_last_message_was_answered() {
|
||||
let user =
|
||||
|sent: f64| AgentEntry::User { text: "q".into(), attachments: vec![], sent_ms: Some(sent), done_ms: None };
|
||||
let mut t = Timeline::default();
|
||||
t.push(user(1.0));
|
||||
t.push(AgentEntry::Agent { text: "a".into() });
|
||||
t.push(user(2.0));
|
||||
assert_eq!(t.end_turn(Some(5.0)), vec![2]);
|
||||
assert!(matches!(t.entries[0], AgentEntry::User { done_ms: None, .. }));
|
||||
assert!(matches!(t.entries[2], AgentEntry::User { done_ms: Some(5.0), .. }));
|
||||
// Settled once: a later end (a restart) doesn't move it.
|
||||
assert_eq!(t.end_turn(Some(9.0)), Vec::<usize>::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_output_keeps_its_tail() {
|
||||
let s = tail("é".repeat(MAX_OUTPUT));
|
||||
|
||||
@@ -3,9 +3,7 @@
|
||||
use crate::model::AgentChange;
|
||||
use ide_core::{IdeError, IdeResult, IpcPath};
|
||||
use ide_vcs::{ChangeKind, Repo};
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::UNIX_EPOCH;
|
||||
|
||||
pub(crate) struct Created {
|
||||
pub path: PathBuf,
|
||||
@@ -76,25 +74,6 @@ pub(crate) fn changes(cwd: &Path, base: &str) -> IdeResult<Vec<AgentChange>> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Size and modification time of a file, `None` once it is gone.
|
||||
pub(crate) type Stamp = Option<(u64, u128)>;
|
||||
|
||||
fn stamp(path: &Path) -> Stamp {
|
||||
let meta = std::fs::metadata(path).ok()?;
|
||||
let modified = meta.modified().ok()?.duration_since(UNIX_EPOCH).ok()?.as_nanos();
|
||||
Some((meta.len(), modified))
|
||||
}
|
||||
|
||||
/// The files already changed in `cwd` against `HEAD`, stamped so later edits to them show.
|
||||
pub(crate) fn snapshot(cwd: &Path) -> IdeResult<BTreeMap<String, Stamp>> {
|
||||
Ok(changes(cwd, "HEAD")?.into_iter().map(|c| (c.rel_path, stamp(&c.path))).collect())
|
||||
}
|
||||
|
||||
/// Drops the changes that were there before the task and haven't been touched since.
|
||||
pub(crate) fn without_untouched(changes: Vec<AgentChange>, before: &BTreeMap<String, Stamp>) -> Vec<AgentChange> {
|
||||
changes.into_iter().filter(|c| before.get(&c.rel_path).is_none_or(|s| *s != stamp(&c.path))).collect()
|
||||
}
|
||||
|
||||
pub(crate) fn file_at(cwd: &Path, path: &Path, rev: &str) -> IdeResult<Option<String>> {
|
||||
repo_at(cwd)?.file_at(path, Some(rev))
|
||||
}
|
||||
@@ -169,17 +148,6 @@ mod tests {
|
||||
let base_text = file_at(&created.path, &created.path.join("a.txt"), &created.base_commit).unwrap();
|
||||
assert_eq!(base_text.as_deref(), Some("one\ntwo\n"));
|
||||
|
||||
// Changes already in the checkout drop out until they are edited again.
|
||||
let before = snapshot(&created.path).unwrap();
|
||||
std::fs::write(created.path.join("b.txt"), "b\n").unwrap();
|
||||
let rels = |c: Vec<AgentChange>| c.into_iter().map(|c| c.rel_path).collect::<Vec<_>>();
|
||||
let after = changes(&created.path, "HEAD").unwrap();
|
||||
assert_eq!(rels(without_untouched(after, &before)), ["b.txt"]);
|
||||
std::thread::sleep(std::time::Duration::from_millis(10));
|
||||
std::fs::write(created.path.join("new.txt"), "x\ny\nz\n").unwrap();
|
||||
let after = changes(&created.path, "HEAD").unwrap();
|
||||
assert_eq!(rels(without_untouched(after, &before)), ["b.txt", "new.txt"]);
|
||||
|
||||
// A second task with the same title gets its own worktree.
|
||||
assert_eq!(create(&repo, &tmp.path().join("wt"), "Edit A", None).unwrap().branch, "agent/edit-a-2");
|
||||
remove(&repo, &created.path).unwrap();
|
||||
|
||||
@@ -52,7 +52,7 @@ pub(crate) fn run(
|
||||
use std::os::unix::process::CommandExt;
|
||||
command.process_group(0);
|
||||
}
|
||||
ide_core::process::prepare(&mut command);
|
||||
ide_core::process::no_window(&mut command);
|
||||
let mut child = command.spawn().map_err(|e| IdeError::unavailable(format!("cannot start {program}: {e}")))?;
|
||||
let (tx, rx) = mpsc::channel::<(Stream, String)>();
|
||||
let pump = |stream: Box<dyn Read + Send>, kind: Stream, tx: mpsc::Sender<(Stream, String)>| {
|
||||
|
||||
@@ -10,6 +10,5 @@ dunce.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
specta.workspace = true
|
||||
specta-typescript.workspace = true
|
||||
thiserror.workspace = true
|
||||
tokio-util.workspace = true
|
||||
@@ -55,13 +55,7 @@ pub struct EditorAppearanceSettings {
|
||||
pub caret_blinking: bool,
|
||||
/// Blink period in ms.
|
||||
pub caret_blink_period: u32,
|
||||
/// Fade the caret in and out instead of toggling it; rounds its corners.
|
||||
pub smooth_caret_blinking: bool,
|
||||
pub block_caret: bool,
|
||||
/// Animate the caret between positions when it is moved.
|
||||
pub smooth_caret_movement: bool,
|
||||
/// Smooth caret movement curve: `snappy` | `gliding`.
|
||||
pub caret_movement_style: String,
|
||||
pub line_numbers: bool,
|
||||
pub method_separators: bool,
|
||||
/// Sub-options of `editor.showWhitespace`.
|
||||
@@ -81,10 +75,7 @@ impl Default for EditorAppearanceSettings {
|
||||
Self {
|
||||
caret_blinking: true,
|
||||
caret_blink_period: 500,
|
||||
smooth_caret_blinking: false,
|
||||
block_caret: false,
|
||||
smooth_caret_movement: false,
|
||||
caret_movement_style: "snappy".into(),
|
||||
line_numbers: true,
|
||||
method_separators: false,
|
||||
whitespace_leading: true,
|
||||
|
||||
@@ -67,11 +67,6 @@ pub enum IdeEvent {
|
||||
status: ServerStatus,
|
||||
message: Option<String>,
|
||||
},
|
||||
/// A stopped language server left the project's list (disabled in settings, or a
|
||||
/// fallback that a preferred server took over from again).
|
||||
LanguageServerRemoved {
|
||||
server: ServerId,
|
||||
},
|
||||
/// A language server asked clients to re-request one kind of data for its
|
||||
/// open documents (`workspace/inlayHint/refresh`, …), e.g. after indexing.
|
||||
LspRefresh {
|
||||
|
||||
@@ -5,121 +5,22 @@ use std::process::Command;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
/// Windows `CREATE_NO_WINDOW` creation flag, for call sites that combine it
|
||||
/// with other flags (and then call [`host_env`] themselves). Prefer [`prepare`] otherwise.
|
||||
/// with other flags. Prefer [`no_window`] otherwise.
|
||||
pub const CREATE_NO_WINDOW: u32 = 0x0800_0000;
|
||||
|
||||
/// Readies `cmd` for spawning any child (java, node, curl, git, a language server, ...).
|
||||
/// For a `tokio::process::Command`, pass `cmd.as_std_mut()`.
|
||||
///
|
||||
/// - Windows: release builds use the GUI subsystem, so without `CREATE_NO_WINDOW` every
|
||||
/// console child flashes a `cmd` window.
|
||||
/// - Linux AppImage: see [`host_env`].
|
||||
///
|
||||
/// Variables the call site has already set are kept; call it before `env_clear`.
|
||||
pub fn prepare(cmd: &mut Command) -> &mut Command {
|
||||
/// Keeps a console child (java, node, curl, a language server, ...) from
|
||||
/// opening its own console window on Windows. Release builds use the GUI
|
||||
/// subsystem, so without this every spawn flashes a `cmd` window. A no-op
|
||||
/// elsewhere. For a `tokio::process::Command`, pass `cmd.as_std_mut()`.
|
||||
pub fn no_window(cmd: &mut Command) -> &mut Command {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
cmd.creation_flags(CREATE_NO_WINDOW);
|
||||
}
|
||||
host_env(cmd)
|
||||
}
|
||||
|
||||
/// Gives `cmd` the host's environment back when the IDE runs from an AppImage. `AppRun` and
|
||||
/// its hooks point `LD_LIBRARY_PATH`, `PATH`, `XDG_DATA_DIRS`, `GIO_MODULE_DIR`, `GTK_PATH`,
|
||||
/// `GST_PLUGIN_*`, ... into the mounted image for the IDE itself; a host program that
|
||||
/// inherits them loads the image's (older) libraries and plugins next to its own, e.g.
|
||||
/// `curl: symbol lookup error ... nghttp2_...`. The IDE process keeps its environment
|
||||
/// (WebKit and GTK still need it). Variables the call site has already set are kept.
|
||||
/// A no-op outside an AppImage.
|
||||
pub fn host_env(cmd: &mut Command) -> &mut Command {
|
||||
let fixes = appimage_fixes();
|
||||
if fixes.is_empty() {
|
||||
return cmd;
|
||||
}
|
||||
let explicit: Vec<OsString> = cmd.get_envs().map(|(k, _)| k.to_owned()).collect();
|
||||
for (key, value) in fixes.into_iter().filter(|(k, _)| !explicit.contains(k)) {
|
||||
match value {
|
||||
Some(v) => cmd.env(key, v),
|
||||
None => cmd.env_remove(key),
|
||||
};
|
||||
}
|
||||
cmd
|
||||
}
|
||||
|
||||
/// The [`host_env`] changes as `(name, value)` pairs, `None` meaning "remove", for spawners
|
||||
/// that are not a `std::process::Command` (a PTY `CommandBuilder`). Apply before the call
|
||||
/// site's own variables. Empty outside an AppImage.
|
||||
pub fn host_env_fixes() -> Vec<(OsString, Option<OsString>)> {
|
||||
appimage_fixes()
|
||||
}
|
||||
|
||||
/// This process's environment as a child should inherit it (see [`host_env`]), for call
|
||||
/// sites that build a child's environment from the IDE's own instead of inheriting it.
|
||||
pub fn host_vars() -> impl Iterator<Item = (OsString, OsString)> {
|
||||
let fixes = appimage_fixes();
|
||||
std::env::vars_os().filter_map(move |(k, v)| match fixes.iter().find(|(f, _)| *f == k) {
|
||||
Some((_, fixed)) => fixed.clone().map(|v| (k, v)),
|
||||
None => Some((k, v)),
|
||||
})
|
||||
}
|
||||
|
||||
/// [`std::env::var_os`] as a child should see it (see [`host_env`]).
|
||||
pub fn host_var_os(key: impl AsRef<OsStr>) -> Option<OsString> {
|
||||
let key = key.as_ref();
|
||||
match appimage_fixes().into_iter().find(|(k, _)| k == key) {
|
||||
Some((_, fixed)) => fixed,
|
||||
None => std::env::var_os(key),
|
||||
}
|
||||
}
|
||||
|
||||
/// Read on every call, not cached: startup rewrites `PATH` (login shell, managed tools).
|
||||
fn appimage_fixes() -> Vec<(OsString, Option<OsString>)> {
|
||||
if !cfg!(target_os = "linux") || std::env::var_os("APPDIR").is_none() {
|
||||
return Vec::new();
|
||||
}
|
||||
appimage_env_fixes(&std::env::vars_os().collect::<Vec<_>>())
|
||||
}
|
||||
|
||||
/// Variables the AppImage runtime sets to describe the IDE's own launch.
|
||||
const APPIMAGE_LAUNCH_VARS: [&str; 4] = ["APPDIR", "APPIMAGE", "ARGV0", "OWD"];
|
||||
|
||||
/// What to change in `vars` (an environment) so a child sees the host's environment rather
|
||||
/// than the AppImage's: every `:`-separated entry inside `$APPDIR` is dropped (a saved
|
||||
/// `<NAME>_ORIG` wins when present), variables left empty are removed, and so are the
|
||||
/// runtime's own launch variables. Nothing changes when `APPDIR` is not set.
|
||||
fn appimage_env_fixes(vars: &[(OsString, OsString)]) -> Vec<(OsString, Option<OsString>)> {
|
||||
let get = |name: &str| vars.iter().find(|(k, _)| k == name).map(|(_, v)| v);
|
||||
let Some(appdir) =
|
||||
get("APPDIR").and_then(|v| v.to_str()).map(|v| v.trim_end_matches('/')).filter(|v| !v.is_empty())
|
||||
else {
|
||||
return Vec::new();
|
||||
};
|
||||
let inside = |entry: &str| entry.strip_prefix(appdir).is_some_and(|rest| rest.is_empty() || rest.starts_with('/'));
|
||||
let mut fixes = Vec::new();
|
||||
for (key, value) in vars {
|
||||
let (Some(name), Some(value)) = (key.to_str(), value.to_str()) else { continue };
|
||||
let fixed = if APPIMAGE_LAUNCH_VARS.contains(&name) {
|
||||
None
|
||||
} else if value.split(':').any(inside) {
|
||||
match get(&format!("{name}_ORIG")) {
|
||||
Some(orig) => Some(orig.clone()),
|
||||
None => {
|
||||
let kept: Vec<&str> = value.split(':').filter(|e| !e.is_empty() && !inside(e)).collect();
|
||||
Some(OsString::from(kept.join(":")))
|
||||
}
|
||||
}
|
||||
} else if name == "GTK_THEME" && value.is_empty() {
|
||||
// linuxdeploy-plugin-gtk exports `GTK_THEME="$APPIMAGE_GTK_THEME"`, usually empty.
|
||||
None
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
fixes.push((key.clone(), fixed.filter(|v| !v.is_empty())));
|
||||
}
|
||||
fixes
|
||||
}
|
||||
|
||||
static SHELL_ENV: OnceLock<Vec<(OsString, OsString)>> = OnceLock::new();
|
||||
|
||||
/// Records the login shell's environment, read once at startup off the main thread.
|
||||
@@ -149,108 +50,4 @@ mod tests {
|
||||
let vars: Vec<_> = shell_env().collect();
|
||||
assert_eq!(vars, [(OsStr::new("OPENIDEA_SHELL_ONLY_VAR"), OsStr::new("1"))]);
|
||||
}
|
||||
|
||||
fn env(pairs: &[(&str, &str)]) -> Vec<(OsString, OsString)> {
|
||||
pairs.iter().map(|(k, v)| (OsString::from(k), OsString::from(v))).collect()
|
||||
}
|
||||
|
||||
fn fixes(pairs: &[(&str, &str)]) -> Vec<(String, Option<String>)> {
|
||||
appimage_env_fixes(&env(pairs))
|
||||
.into_iter()
|
||||
.map(|(k, v)| (k.into_string().unwrap(), v.map(|v| v.into_string().unwrap())))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn fix(name: &str, value: Option<&str>) -> (String, Option<String>) {
|
||||
(name.to_owned(), value.map(str::to_owned))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn appimage_entries_are_dropped_and_host_entries_kept() {
|
||||
let got = fixes(&[
|
||||
("APPDIR", "/tmp/.mount_OpenIDabc"),
|
||||
(
|
||||
"LD_LIBRARY_PATH",
|
||||
"/tmp/.mount_OpenIDabc/usr/lib/:/tmp/.mount_OpenIDabc/usr/lib/x86_64-linux-gnu/:/opt/cuda/lib64:/usr/local/lib",
|
||||
),
|
||||
("PATH", "/tmp/.mount_OpenIDabc/usr/bin/:/tmp/.mount_OpenIDabc/usr/sbin/:/usr/local/bin:/usr/bin"),
|
||||
("XDG_DATA_DIRS", "/tmp/.mount_OpenIDabc/usr/share:/usr/share:/usr/local/share:/usr/share"),
|
||||
("HOME", "/home/me"),
|
||||
("JAVA_HOME", "/tmp/.mount_OpenIDabcdef/jdk"),
|
||||
]);
|
||||
assert_eq!(
|
||||
got,
|
||||
[
|
||||
fix("APPDIR", None),
|
||||
fix("LD_LIBRARY_PATH", Some("/opt/cuda/lib64:/usr/local/lib")),
|
||||
fix("PATH", Some("/usr/local/bin:/usr/bin")),
|
||||
fix("XDG_DATA_DIRS", Some("/usr/share:/usr/local/share:/usr/share")),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn variables_left_empty_are_removed() {
|
||||
// AppRun prepends to an unset variable, leaving a trailing `:`; hooks set single paths.
|
||||
let got = fixes(&[
|
||||
("APPIMAGE", "/opt/openidea/OpenIDEA.AppImage"),
|
||||
("APPDIR", "/tmp/.mount_x/"),
|
||||
("ARGV0", "/opt/openidea/OpenIDEA.AppImage"),
|
||||
("OWD", "/home/me"),
|
||||
("LD_LIBRARY_PATH", "/tmp/.mount_x/usr/lib/:/tmp/.mount_x/lib/:"),
|
||||
("GIO_MODULE_DIR", "/tmp/.mount_x/usr/lib/gio/modules"),
|
||||
("GTK_DATA_PREFIX", "/tmp/.mount_x"),
|
||||
("GDK_PIXBUF_MODULE_FILE", "/tmp/.mount_x/usr/lib/gdk-pixbuf-2.0/2.10.0/loaders.cache"),
|
||||
("GST_PLUGIN_SYSTEM_PATH_1_0", "/tmp/.mount_x/usr/lib/gstreamer-1.0"),
|
||||
("GTK_THEME", ""),
|
||||
]);
|
||||
let names: Vec<_> = got.iter().filter(|(_, v)| v.is_none()).map(|(k, _)| k.as_str()).collect();
|
||||
assert_eq!(
|
||||
names,
|
||||
[
|
||||
"APPIMAGE",
|
||||
"APPDIR",
|
||||
"ARGV0",
|
||||
"OWD",
|
||||
"LD_LIBRARY_PATH",
|
||||
"GIO_MODULE_DIR",
|
||||
"GTK_DATA_PREFIX",
|
||||
"GDK_PIXBUF_MODULE_FILE",
|
||||
"GST_PLUGIN_SYSTEM_PATH_1_0",
|
||||
"GTK_THEME",
|
||||
]
|
||||
);
|
||||
assert_eq!(names.len(), got.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_saved_original_value_wins() {
|
||||
let got = fixes(&[
|
||||
("APPDIR", "/tmp/.mount_x"),
|
||||
("LD_LIBRARY_PATH", "/tmp/.mount_x/usr/lib:/opt/lib"),
|
||||
("LD_LIBRARY_PATH_ORIG", "/opt/lib:/home/me/lib"),
|
||||
("PYTHONHOME", "/tmp/.mount_x/usr"),
|
||||
("PYTHONHOME_ORIG", ""),
|
||||
]);
|
||||
assert_eq!(
|
||||
got,
|
||||
[fix("APPDIR", None), fix("LD_LIBRARY_PATH", Some("/opt/lib:/home/me/lib")), fix("PYTHONHOME", None)]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outside_an_appimage_nothing_changes() {
|
||||
let plain = [("LD_LIBRARY_PATH", "/opt/lib:"), ("PATH", "/usr/bin"), ("GTK_THEME", "")];
|
||||
assert!(fixes(&plain).is_empty());
|
||||
assert!(fixes(&[("APPDIR", ""), ("PATH", "/usr/bin")]).is_empty());
|
||||
assert!(fixes(&[("APPDIR", "/"), ("PATH", "/usr/bin")]).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_env_keeps_what_the_call_site_set() {
|
||||
let mut cmd = Command::new("true");
|
||||
cmd.env("PATH", "/custom");
|
||||
prepare(&mut cmd);
|
||||
assert_eq!(cmd.get_envs().find(|(k, _)| *k == "PATH").and_then(|(_, v)| v), Some(OsStr::new("/custom")));
|
||||
}
|
||||
}
|
||||
@@ -42,9 +42,6 @@ pub struct Settings {
|
||||
/// Language servers / debug adapters at a user-chosen location, by the
|
||||
/// command the language definition launches (`elixir-ls`, `codelldb`).
|
||||
pub tools: BTreeMap<String, ToolSettings>,
|
||||
/// Per language server, by name (`rust-analyzer`): launch and protocol
|
||||
/// options on top of the language definition, or a server defined here.
|
||||
pub language_servers: BTreeMap<String, LanguageServerSettings>,
|
||||
/// Editor › Inspections profiles.
|
||||
pub inspections: InspectionSettings,
|
||||
/// Editor › Natural Languages › Spelling.
|
||||
@@ -64,58 +61,6 @@ pub struct ToolSettings {
|
||||
pub path: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct LanguageServerSettings {
|
||||
/// `false` keeps the server from starting for any language.
|
||||
pub enabled: bool,
|
||||
/// Executable to launch instead of the definition's; required for a server
|
||||
/// defined here (one with `languages`).
|
||||
pub command: String,
|
||||
/// Replaces the definition's arguments.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub args: Option<Vec<String>>,
|
||||
/// Added to the server's environment.
|
||||
pub env: BTreeMap<String, String>,
|
||||
/// Merged over the definition's `initializationOptions` (sent once at startup).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional, type = Option<specta_typescript::Unknown>)]
|
||||
pub initialization_options: Option<serde_json::Value>,
|
||||
/// Answers the server's `workspace/configuration` requests; changes are pushed
|
||||
/// with `workspace/didChangeConfiguration` without a restart.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional, type = Option<specta_typescript::Unknown>)]
|
||||
pub settings: Option<serde_json::Value>,
|
||||
/// Language ids a server defined here serves (`python`); empty for the servers
|
||||
/// of the language definitions.
|
||||
pub languages: Vec<String>,
|
||||
/// Files marking a workspace root for a server defined here (`pyproject.toml`).
|
||||
pub root_markers: Vec<String>,
|
||||
}
|
||||
|
||||
impl Default for LanguageServerSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
enabled: true,
|
||||
command: String::new(),
|
||||
args: None,
|
||||
env: BTreeMap::new(),
|
||||
initialization_options: None,
|
||||
settings: None,
|
||||
languages: Vec::new(),
|
||||
root_markers: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl LanguageServerSettings {
|
||||
/// A server defined in settings rather than by a language definition.
|
||||
pub fn is_custom(&self) -> bool {
|
||||
!self.languages.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
impl Settings {
|
||||
/// The configured executable for `command`, if any (`~/` not yet expanded).
|
||||
pub fn tool_path(&self, command: &str) -> Option<&str> {
|
||||
@@ -144,7 +89,6 @@ impl Default for Settings {
|
||||
actions_on_save: ActionsOnSaveSettings::default(),
|
||||
external_tools: Vec::new(),
|
||||
tools: BTreeMap::new(),
|
||||
language_servers: BTreeMap::new(),
|
||||
inspections: InspectionSettings::default(),
|
||||
spelling: SpellingSettings::default(),
|
||||
ssh: SshSettings::default(),
|
||||
@@ -330,7 +274,7 @@ impl Default for AppearanceSettings {
|
||||
ide_antialiasing: "greyscale".into(),
|
||||
editor_antialiasing: "greyscale".into(),
|
||||
show_tool_window_bars: true,
|
||||
show_tool_window_names: false,
|
||||
show_tool_window_names: true,
|
||||
widescreen_tool_windows: false,
|
||||
status_bar_widgets: BTreeMap::new(),
|
||||
main_toolbar: None,
|
||||
|
||||
@@ -17,7 +17,6 @@ pub struct VcsSettings {
|
||||
pub git: GitSettings,
|
||||
pub commit: CommitSettings,
|
||||
pub confirmation: VcsConfirmationSettings,
|
||||
pub shelf: ShelfSettings,
|
||||
/// Issue Navigation: commit-message patterns turned into links.
|
||||
pub issue_navigation: Vec<IssueLink>,
|
||||
}
|
||||
@@ -32,7 +31,6 @@ impl Default for VcsSettings {
|
||||
git: GitSettings::default(),
|
||||
commit: CommitSettings::default(),
|
||||
confirmation: VcsConfirmationSettings::default(),
|
||||
shelf: ShelfSettings::default(),
|
||||
issue_navigation: Vec::new(),
|
||||
}
|
||||
}
|
||||
@@ -55,17 +53,6 @@ pub struct GitSettings {
|
||||
pub protected_branches: String,
|
||||
/// Initial state of Commit Options › Sign-off Commit.
|
||||
pub sign_off: bool,
|
||||
/// Ask before committing files larger than `large_file_mb`.
|
||||
pub warn_large_files: bool,
|
||||
pub large_file_mb: u32,
|
||||
/// Ask before committing names that are invalid on Windows or differ only in case.
|
||||
pub warn_bad_file_names: bool,
|
||||
/// Commit and Push opens the Push dialog; otherwise it pushes right away.
|
||||
pub show_push_dialog: bool,
|
||||
/// With `show_push_dialog`: only for commits to protected branches.
|
||||
pub push_dialog_only_protected: bool,
|
||||
/// Stashes and shelves share one tab.
|
||||
pub combine_stash_and_shelf: bool,
|
||||
}
|
||||
|
||||
impl Default for GitSettings {
|
||||
@@ -79,12 +66,6 @@ impl Default for GitSettings {
|
||||
incoming_check: "auto".into(),
|
||||
protected_branches: "master; main".into(),
|
||||
sign_off: false,
|
||||
warn_large_files: true,
|
||||
large_file_mb: 50,
|
||||
warn_bad_file_names: true,
|
||||
show_push_dialog: true,
|
||||
push_dialog_only_protected: false,
|
||||
combine_stash_and_shelf: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -93,11 +74,6 @@ impl Default for GitSettings {
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct CommitSettings {
|
||||
/// Commit from the Commit tool window; off = Local Changes in the Git tool
|
||||
/// window and a Commit dialog.
|
||||
pub non_modal: bool,
|
||||
/// Start with an empty message instead of the last one / the changelist's.
|
||||
pub clear_initial_message: bool,
|
||||
pub analyze_code: bool,
|
||||
pub check_todo: bool,
|
||||
pub reformat: bool,
|
||||
@@ -115,8 +91,6 @@ pub struct CommitSettings {
|
||||
impl Default for CommitSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
non_modal: true,
|
||||
clear_initial_message: false,
|
||||
analyze_code: true,
|
||||
check_todo: true,
|
||||
reformat: false,
|
||||
@@ -133,40 +107,20 @@ impl Default for CommitSettings {
|
||||
}
|
||||
}
|
||||
|
||||
/// Version Control › Confirmation.
|
||||
/// Version Control › Confirmation. Values: `ask` | `silently` | `never`.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct VcsConfirmationSettings {
|
||||
/// `ask` | `silently` | `never`.
|
||||
pub on_create: String,
|
||||
pub on_delete: String,
|
||||
/// Update Project opens its options dialog first.
|
||||
pub show_update_options: bool,
|
||||
pub confirm_drop_commits: bool,
|
||||
/// After a patch is saved: `ask` | `no` | `reveal` (show it in the file manager).
|
||||
pub on_patch_created: String,
|
||||
}
|
||||
|
||||
impl Default for VcsConfirmationSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
on_create: "ask".into(),
|
||||
on_delete: "ask".into(),
|
||||
show_update_options: true,
|
||||
confirm_drop_commits: true,
|
||||
on_patch_created: "ask".into(),
|
||||
}
|
||||
Self { on_create: "ask".into(), on_delete: "ask".into() }
|
||||
}
|
||||
}
|
||||
|
||||
/// Version Control › Shelf.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct ShelfSettings {
|
||||
/// Initial state of Unshelve's "Remove successfully applied files from the shelf".
|
||||
pub remove_applied: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct IssueLink {
|
||||
|
||||
@@ -206,7 +206,7 @@ pub fn collect(spec: &CoverageReportSpec) -> IdeResult<CoverageSuite> {
|
||||
CoverageReportSpec::Exported { runner, argv, cwd, env, lcov } => {
|
||||
let (program, args) =
|
||||
argv.split_first().ok_or_else(|| IdeError::invalid("empty coverage export command"))?;
|
||||
let out = ide_core::process::prepare(&mut Command::new(program))
|
||||
let out = ide_core::process::no_window(&mut Command::new(program))
|
||||
.args(args)
|
||||
.current_dir(cwd)
|
||||
.envs(env)
|
||||
|
||||
@@ -257,7 +257,7 @@ pub async fn prepare_debugpy(spec: &mut AdapterSpec) -> IdeResult<()> {
|
||||
return Ok(()); // Reported as a missing adapter when it is started.
|
||||
};
|
||||
let mut probe = Command::new(&python);
|
||||
ide_core::process::prepare(probe.as_std_mut());
|
||||
ide_core::process::no_window(probe.as_std_mut());
|
||||
let probe = probe
|
||||
.args(["-c", "import debugpy.adapter"])
|
||||
.current_dir(&spec.cwd)
|
||||
@@ -396,7 +396,7 @@ impl AdapterLauncher for ProcessLauncher {
|
||||
None => args,
|
||||
};
|
||||
let mut cmd = Command::new(&binary);
|
||||
ide_core::process::prepare(cmd.as_std_mut());
|
||||
ide_core::process::no_window(cmd.as_std_mut());
|
||||
cmd.args(&args)
|
||||
.envs(spec.env.iter().map(|(k, v)| (k, v)))
|
||||
.current_dir(&spec.cwd)
|
||||
|
||||
@@ -170,7 +170,7 @@ pub fn is_go_binary(exe: &str) -> bool {
|
||||
pub fn list_processes() -> IdeResult<Vec<RawProcess>> {
|
||||
use std::collections::HashMap;
|
||||
let ps = |fields: &str| -> IdeResult<String> {
|
||||
let out = ide_core::process::prepare(&mut std::process::Command::new("ps"))
|
||||
let out = std::process::Command::new("ps")
|
||||
.args(["-x", "-ww", "-o", fields])
|
||||
.output()
|
||||
.map_err(|e| IdeError::unavailable(format!("cannot list processes: {e}")))?;
|
||||
@@ -212,9 +212,7 @@ pub const NODE_INSPECTOR_PORT: u16 = 9229;
|
||||
/// picker does) and waits until it listens. Returns the inspector port.
|
||||
#[cfg(unix)]
|
||||
pub async fn enable_node_inspector(pid: u32) -> IdeResult<u16> {
|
||||
let mut kill = tokio::process::Command::new("kill");
|
||||
ide_core::process::prepare(kill.as_std_mut());
|
||||
let status = kill
|
||||
let status = tokio::process::Command::new("kill")
|
||||
.args(["-USR1", &pid.to_string()])
|
||||
.status()
|
||||
.await
|
||||
|
||||
@@ -55,7 +55,7 @@ pub async fn build(
|
||||
) -> IdeResult<PathBuf> {
|
||||
let cargo = find_binary("cargo", cwd).ok_or_else(|| IdeError::unavailable("`cargo` not found on PATH"))?;
|
||||
let mut cmd = tokio::process::Command::new(cargo);
|
||||
ide_core::process::prepare(cmd.as_std_mut());
|
||||
ide_core::process::no_window(cmd.as_std_mut());
|
||||
cmd.args(args)
|
||||
.arg("--message-format=json-render-diagnostics")
|
||||
.current_dir(cwd)
|
||||
|
||||
@@ -421,7 +421,7 @@ pub(crate) fn run_in_terminal(s: &Arc<Session>, args: &Value) -> Result<Value, S
|
||||
return Err("runInTerminal without args".into());
|
||||
};
|
||||
let mut cmd = tokio::process::Command::new(program);
|
||||
ide_core::process::prepare(cmd.as_std_mut());
|
||||
ide_core::process::no_window(cmd.as_std_mut());
|
||||
cmd.args(rest)
|
||||
.envs(ide_core::process::shell_env())
|
||||
.stdin(Stdio::null())
|
||||
|
||||
@@ -69,7 +69,7 @@ pub fn docker_executable() -> Option<PathBuf> {
|
||||
pub fn run_env(ep: &DockerEndpoint) -> std::collections::BTreeMap<String, String> {
|
||||
let mut env = ep.env_vars();
|
||||
if let Some(dir) = docker_executable().as_deref().and_then(Path::parent) {
|
||||
let current = ide_core::process::host_var_os("PATH").unwrap_or_default();
|
||||
let current = std::env::var_os("PATH").unwrap_or_default();
|
||||
let mut dirs: Vec<PathBuf> = vec![dir.to_path_buf()];
|
||||
dirs.extend(std::env::split_paths(¤t).filter(|d| d != dir));
|
||||
if let Ok(path) = std::env::join_paths(dirs) {
|
||||
|
||||
@@ -25,7 +25,7 @@ fn prepare(cmd: &mut Command) {
|
||||
use std::os::unix::process::CommandExt;
|
||||
cmd.process_group(0);
|
||||
}
|
||||
ide_core::process::prepare(cmd);
|
||||
ide_core::process::no_window(cmd);
|
||||
}
|
||||
|
||||
fn spawn(cmd: &mut Command) -> IdeResult<Child> {
|
||||
|
||||
@@ -25,7 +25,7 @@ fn prepare(cmd: &mut Command) {
|
||||
use std::os::unix::process::CommandExt;
|
||||
cmd.process_group(0);
|
||||
}
|
||||
ide_core::process::prepare(cmd);
|
||||
ide_core::process::no_window(cmd);
|
||||
}
|
||||
|
||||
fn spawn(cmd: &mut Command) -> IdeResult<Child> {
|
||||
|
||||
@@ -28,9 +28,8 @@ pub async fn commands(
|
||||
host.project(window)?.agents.commands(&provider, task.as_deref()).await
|
||||
}
|
||||
|
||||
/// Entries of `task`'s conversation, or of its subagent `subagent`'s.
|
||||
pub fn entries(host: &Host, window: &str, task: String, subagent: Option<String>) -> IdeResult<Vec<AgentEntry>> {
|
||||
host.project(window)?.agents.entries(&task, subagent)
|
||||
pub fn entries(host: &Host, window: &str, task: String) -> IdeResult<Vec<AgentEntry>> {
|
||||
host.project(window)?.agents.entries(&task)
|
||||
}
|
||||
|
||||
pub async fn create(host: &Host, window: &str, request: NewAgentTask) -> IdeResult<AgentTask> {
|
||||
@@ -57,9 +56,8 @@ pub async fn set_config(host: &Host, window: &str, task: String, option: String,
|
||||
host.project(window)?.agents.set_config(&task, &option, value).await
|
||||
}
|
||||
|
||||
/// Stops the task's current turn, or with `subagent` only that subagent's work.
|
||||
pub fn cancel(host: &Host, window: &str, task: String, subagent: Option<String>) -> IdeResult<()> {
|
||||
host.project(window)?.agents.cancel(&task, subagent)
|
||||
pub fn cancel(host: &Host, window: &str, task: String) -> IdeResult<()> {
|
||||
host.project(window)?.agents.cancel(&task)
|
||||
}
|
||||
|
||||
/// Answers a permission request; `option: None` cancels it.
|
||||
@@ -89,7 +87,7 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
d.add("agent_subscribe", |c| async move { subscribe(&c.host, &c.window, c.channel("onEvent")?) });
|
||||
d.add("agent_providers", |c| async move { providers(&c.host, &c.window) });
|
||||
d.add("agent_commands", |c| async move { commands(&c.host, &c.window, c.arg("provider")?, c.arg("task")?).await });
|
||||
d.add("agent_entries", |c| async move { entries(&c.host, &c.window, c.arg("task")?, c.arg("subagent")?) });
|
||||
d.add("agent_entries", |c| async move { entries(&c.host, &c.window, c.arg("task")?) });
|
||||
d.add("agent_create", |c| async move { create(&c.host, &c.window, c.arg("request")?).await });
|
||||
d.add("agent_prompt", |c| async move {
|
||||
prompt(&c.host, &c.window, c.arg("task")?, c.arg("prompt")?, c.arg("now")?).await
|
||||
@@ -102,7 +100,7 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
d.add("agent_set_config", |c| async move {
|
||||
set_config(&c.host, &c.window, c.arg("task")?, c.arg("option")?, c.arg("value")?).await
|
||||
});
|
||||
d.add("agent_cancel", |c| async move { cancel(&c.host, &c.window, c.arg("task")?, c.arg("subagent")?) });
|
||||
d.add("agent_cancel", |c| async move { cancel(&c.host, &c.window, c.arg("task")?) });
|
||||
d.add("agent_respond", |c| async move {
|
||||
respond(&c.host, &c.window, c.arg("task")?, c.arg("permission")?, c.arg("option")?)
|
||||
});
|
||||
|
||||
@@ -8,9 +8,6 @@ pub async fn open(host: &Host, window: &str, path: PathBuf) -> IdeResult<Documen
|
||||
host.blocking(move || {
|
||||
let info = project.documents.open(&path)?;
|
||||
project.index.mark_recent(&path);
|
||||
if let Some(dir) = path.parent().filter(|_| project.light) {
|
||||
project.watch_light_dir(dir);
|
||||
}
|
||||
Ok(info)
|
||||
})
|
||||
.await
|
||||
|
||||
@@ -241,11 +241,6 @@ pub fn lsp_servers(host: &Host, window: &str) -> IdeResult<Vec<ServerInfo>> {
|
||||
Ok(host.project(window)?.lsp.servers())
|
||||
}
|
||||
|
||||
pub fn lsp_resend_diagnostics(host: &Host, window: &str) -> IdeResult<()> {
|
||||
host.project(window)?.lsp.resend_diagnostics();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn lsp_restart(host: &Host, window: &str, server: ServerId) -> IdeResult<()> {
|
||||
host.project(window)?.lsp.restart(server).await
|
||||
}
|
||||
@@ -354,7 +349,6 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
lsp_type_hierarchy(&c.host, &c.window, c.arg("doc")?, c.arg("pos")?, c.arg("direction")?).await
|
||||
});
|
||||
d.add("lsp_servers", |c| async move { lsp_servers(&c.host, &c.window) });
|
||||
d.add("lsp_resend_diagnostics", |c| async move { lsp_resend_diagnostics(&c.host, &c.window) });
|
||||
d.add("lsp_restart", |c| async move { lsp_restart(&c.host, &c.window, c.arg("server")?).await });
|
||||
d.add("apply_workspace_edit", |c| async move { apply_workspace_edit(&c.host, &c.window, c.arg("edit")?) });
|
||||
d.add("lsp_execute_command", |c| async move {
|
||||
|
||||
@@ -38,7 +38,7 @@ pub async fn open(host: &Arc<Host>, window: &str, path: &Path) -> IdeResult<Arc<
|
||||
}
|
||||
|
||||
pub fn current(host: &Host, window: &str) -> Option<ProjectInfo> {
|
||||
host.project(window).ok().filter(|p| !p.light).map(|p| info(&p))
|
||||
host.project(window).ok().map(|p| info(&p))
|
||||
}
|
||||
|
||||
/// Effective settings for the window's project, or global settings without one.
|
||||
@@ -75,8 +75,7 @@ pub fn set_settings(
|
||||
let value: serde_json::Value =
|
||||
serde_json::from_str(value).map_err(|e| ide_core::IdeError::invalid(e.to_string()))?;
|
||||
let current = host.project(window).ok();
|
||||
// A LightEdit window has no project layer: its values are global.
|
||||
let project_scope = matches!(scope, SettingsScope::Project) && current.as_ref().is_some_and(|p| !p.light);
|
||||
let project_scope = matches!(scope, SettingsScope::Project) && current.is_some();
|
||||
let settings = match ¤t {
|
||||
Some(p) if project_scope => p.settings.set(scope, key, value)?,
|
||||
Some(p) => {
|
||||
@@ -91,7 +90,7 @@ pub fn set_settings(
|
||||
// A global value reaches every other open project too.
|
||||
if !project_scope {
|
||||
for project in host.projects() {
|
||||
if current.as_ref().is_some_and(|c| Arc::ptr_eq(c, &project)) {
|
||||
if current.as_ref().is_some_and(|c| c.root == project.root) {
|
||||
continue;
|
||||
}
|
||||
let effective = project.settings.reload();
|
||||
@@ -114,7 +113,7 @@ pub fn set_settings(
|
||||
host.ssh.set_configs(host.global_settings.effective().ssh.configs);
|
||||
}
|
||||
// A new interpreter / toolchain / server executable restarts the language servers it affects.
|
||||
if ["languages", "tools", "languageServers"].iter().any(|k| key == *k || key.starts_with(&format!("{k}."))) {
|
||||
if ["languages", "tools"].iter().any(|k| key == *k || key.starts_with(&format!("{k}."))) {
|
||||
for project in affected() {
|
||||
let lsp = project.lsp.clone();
|
||||
host.runtime.spawn(async move { lsp.reconfigure().await });
|
||||
|
||||
@@ -26,17 +26,6 @@ fn tools(host: &Host, window: &str) -> IdeResult<Tools> {
|
||||
Ok(Tools::new(&data).with_custom_paths(custom).with_found_paths(found.into_iter().collect()))
|
||||
}
|
||||
|
||||
/// The language definitions plus the servers defined in the window's settings.
|
||||
fn languages(host: &Host, window: &str) -> Vec<ide_language::LanguageConfig> {
|
||||
let settings = match host.project(window) {
|
||||
Ok(project) => project.settings.effective(),
|
||||
Err(_) => host.global_settings.effective(),
|
||||
};
|
||||
let mut langs = host.languages.all();
|
||||
ide_sdk::apply::with_custom_servers(&mut langs, &settings);
|
||||
langs
|
||||
}
|
||||
|
||||
fn join_err(e: impl std::fmt::Display) -> IdeError {
|
||||
IdeError::internal(e.to_string())
|
||||
}
|
||||
@@ -51,7 +40,7 @@ fn reconfigure_servers(host: &Host) {
|
||||
/// Status of every known language server / debug adapter and the languages using it.
|
||||
pub async fn tools_list(host: &Host, window: &str) -> IdeResult<Vec<ToolInfo>> {
|
||||
let tools = tools(host, window)?;
|
||||
let langs = languages(host, window);
|
||||
let langs = host.languages.all();
|
||||
tokio::task::spawn_blocking(move || tools.list(&langs)).await.map_err(join_err)
|
||||
}
|
||||
|
||||
@@ -65,7 +54,7 @@ pub async fn tools_install(
|
||||
on_event: Channel<InstallEvent>,
|
||||
) -> IdeResult<ToolInfo> {
|
||||
let tools = tools(host, window)?;
|
||||
let langs = languages(host, window);
|
||||
let langs = host.languages.all();
|
||||
let cancel = host.begin_request(request);
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
tools.install(&name, &langs, &cancel, &|e| {
|
||||
@@ -85,7 +74,7 @@ pub async fn tools_install(
|
||||
/// Removes a tool the IDE installed.
|
||||
pub async fn tools_uninstall(host: &Host, window: &str, name: String) -> IdeResult<ToolInfo> {
|
||||
let tools = tools(host, window)?;
|
||||
let langs = languages(host, window);
|
||||
let langs = host.languages.all();
|
||||
let info = tokio::task::spawn_blocking(move || tools.uninstall(&name, &langs)).await.map_err(join_err)??;
|
||||
reconfigure_servers(host);
|
||||
Ok(info)
|
||||
|
||||
@@ -50,9 +50,6 @@ pub struct Project {
|
||||
/// Watchers of the Project Structure content roots outside the project folder.
|
||||
pub(crate) content_watchers: Mutex<Vec<(PathBuf, Watcher)>>,
|
||||
pub(crate) _scratch_watcher: Option<Watcher>,
|
||||
/// A LightEdit window's loose files ([`Host::open_light`]): global settings only,
|
||||
/// nothing indexed, no language servers, repositories or project services.
|
||||
pub light: bool,
|
||||
}
|
||||
|
||||
impl Host {
|
||||
@@ -69,7 +66,6 @@ impl Host {
|
||||
// it, with its warm index, language servers and unsaved documents.
|
||||
if let Ok(current) = self.project(window)
|
||||
&& current.root == root
|
||||
&& !current.light
|
||||
{
|
||||
return Ok(current);
|
||||
}
|
||||
@@ -121,9 +117,7 @@ impl Host {
|
||||
let data_dir = self.data_dir.clone();
|
||||
lsp.set_config_hook(Box::new(move |cfg, server_root| {
|
||||
let effective = settings.effective();
|
||||
ide_sdk::apply::server_launch_overrides(cfg, &effective);
|
||||
ide_sdk::apply::configure_server(cfg, &root, server_root, &effective);
|
||||
ide_sdk::java::cap_java_home(cfg, &ide_sdk::java::installed_jdks());
|
||||
if cfg.name == "jdtls" {
|
||||
let bundles: Vec<PathBuf> =
|
||||
ide_tools::managed_bundle(&data_dir, "java-debug").into_iter().collect();
|
||||
@@ -155,13 +149,6 @@ impl Host {
|
||||
);
|
||||
ide_sdk::jdtls::launch_directly(cfg);
|
||||
}
|
||||
ide_sdk::apply::server_protocol_overrides(cfg, &effective);
|
||||
}));
|
||||
}
|
||||
{
|
||||
let settings = settings.clone();
|
||||
lsp.set_servers_hook(Box::new(move |language, defined| {
|
||||
ide_sdk::apply::language_servers(language.as_str(), defined, &settings.effective())
|
||||
}));
|
||||
}
|
||||
{
|
||||
@@ -279,7 +266,29 @@ impl Host {
|
||||
mark("git");
|
||||
tracing::info!("opened {} in window {window} in {} ms {laps:?}", root.display(), started.elapsed().as_millis());
|
||||
|
||||
let (db, http_history, agents) = self.project_services(&root, &project_key);
|
||||
let db = Arc::new(ide_db::DbManager::new(
|
||||
root.clone(),
|
||||
self.data_dir.join("db-passwords.json"),
|
||||
self.data_dir.join("db-history.json"),
|
||||
self.ssh.clone(),
|
||||
));
|
||||
let http_history = Arc::new(ide_http::History::new(self.data_dir.join("http-history").join(&project_key)));
|
||||
let agents = Arc::new(ide_agent::AgentManager::new(
|
||||
ide_agent::AgentPaths {
|
||||
project_root: root.clone(),
|
||||
store_dir: self.data_dir.join("agents").join(&project_key),
|
||||
// Outside the app data dir: its path has spaces on macOS, which trips up build scripts.
|
||||
worktrees_dir: dirs::home_dir()
|
||||
.unwrap_or_else(|| self.data_dir.clone())
|
||||
.join(".openidea")
|
||||
.join("worktrees")
|
||||
.join(&project_key),
|
||||
models_file: self.data_dir.join("agents").join("models.json"),
|
||||
custom_agents_dir: Some(self.config_dir.join("agents")),
|
||||
home_dir: dirs::home_dir(),
|
||||
},
|
||||
self.runtime.clone(),
|
||||
));
|
||||
let project = Arc::new(Project {
|
||||
root,
|
||||
sink,
|
||||
@@ -301,7 +310,6 @@ impl Host {
|
||||
watcher,
|
||||
content_watchers: Mutex::new(content_watchers),
|
||||
_scratch_watcher: scratch_watcher,
|
||||
light: false,
|
||||
});
|
||||
{
|
||||
let weak = Arc::downgrade(&project);
|
||||
@@ -312,146 +320,6 @@ impl Host {
|
||||
self.insert_project(window, project.clone());
|
||||
Ok(project)
|
||||
}
|
||||
|
||||
/// Database connections, HTTP Client history and coding agents of the project at `root`.
|
||||
pub(crate) fn project_services(
|
||||
&self,
|
||||
root: &Path,
|
||||
project_key: &str,
|
||||
) -> (Arc<ide_db::DbManager>, Arc<ide_http::History>, Arc<ide_agent::AgentManager>) {
|
||||
let db = Arc::new(ide_db::DbManager::new(
|
||||
root.to_path_buf(),
|
||||
self.data_dir.join("db-passwords.json"),
|
||||
self.data_dir.join("db-history.json"),
|
||||
self.ssh.clone(),
|
||||
));
|
||||
let http_history = Arc::new(ide_http::History::new(self.data_dir.join("http-history").join(project_key)));
|
||||
let agents = Arc::new(ide_agent::AgentManager::new(
|
||||
ide_agent::AgentPaths {
|
||||
project_root: root.to_path_buf(),
|
||||
store_dir: self.data_dir.join("agents").join(project_key),
|
||||
// Outside the app data dir: its path has spaces on macOS, which trips up build scripts.
|
||||
worktrees_dir: dirs::home_dir()
|
||||
.unwrap_or_else(|| self.data_dir.clone())
|
||||
.join(".openidea")
|
||||
.join("worktrees")
|
||||
.join(project_key),
|
||||
models_file: self.data_dir.join("agents").join("models.json"),
|
||||
custom_agents_dir: Some(self.config_dir.join("agents")),
|
||||
home_dir: dirs::home_dir(),
|
||||
},
|
||||
self.runtime.clone(),
|
||||
));
|
||||
(db, http_history, agents)
|
||||
}
|
||||
}
|
||||
|
||||
impl Host {
|
||||
/// Opens `window` for editing loose files (LightEdit), `file` first: documents
|
||||
/// with syntax highlighting, saving and Local History over the global settings,
|
||||
/// without an index, language servers, repositories or project settings. A
|
||||
/// window already in LightEdit keeps its session; only its watchers grow.
|
||||
pub fn open_light(&self, window: &str, file: &Path) -> IdeResult<Arc<Project>> {
|
||||
let file = dunce::canonicalize(file)?;
|
||||
if file.is_dir() {
|
||||
return Err(IdeError::invalid(format!("{} is a folder", file.display())));
|
||||
}
|
||||
let dir = file.parent().map(Path::to_path_buf).ok_or_else(|| IdeError::invalid("no parent folder"))?;
|
||||
if let Ok(current) = self.project(window)
|
||||
&& current.light
|
||||
{
|
||||
current.watch_light_dir(&dir);
|
||||
return Ok(current);
|
||||
}
|
||||
self.close_project(window);
|
||||
let sink: SharedSink = (self.sink_for)(window);
|
||||
let settings = Arc::new(SettingsStore::load(&self.config_dir, None));
|
||||
let effective = settings.effective();
|
||||
let languages = Arc::new(self.languages.fork());
|
||||
languages.set_file_types(FileTypes::from_settings(&effective.files, None));
|
||||
let documents = {
|
||||
let languages = languages.clone();
|
||||
Arc::new(Documents::new(
|
||||
sink.clone(),
|
||||
Box::new(move |p: &Path, first: Option<&str>| languages.detect(p, first)),
|
||||
))
|
||||
};
|
||||
documents.set_file_defaults(ide_workspace::FileDefaults::from_settings(&effective, None));
|
||||
let history = Arc::new(LocalHistory::open(&self.data_dir.join("history"), &dir)?);
|
||||
let index = ProjectIndex::unindexed(&dir, languages.clone(), self.syntax(), sink.clone())?;
|
||||
let lsp = LspManager::new(dir.clone(), languages.clone(), sink.clone());
|
||||
lsp.set_servers_hook(Box::new(|_, _| Vec::new()));
|
||||
let syntax = Arc::new(SyntaxCache::new(self.syntax()));
|
||||
documents.add_observer(Arc::new(SyntaxObserver(syntax.clone())));
|
||||
documents.add_observer(Arc::new(HistoryObserver(history.clone())));
|
||||
let watcher = light_watcher(&dir, &sink, &documents, &history)?;
|
||||
let project_key = project_key(&dir);
|
||||
let (db, http_history, agents) = self.project_services(&dir, &project_key);
|
||||
let project = Arc::new(Project {
|
||||
sink,
|
||||
languages,
|
||||
settings,
|
||||
documents,
|
||||
history,
|
||||
moves: FileMoves::new(),
|
||||
index,
|
||||
lsp,
|
||||
repos: Arc::default(),
|
||||
structure: Arc::new(StructureService::new(syntax.clone())),
|
||||
syntax,
|
||||
detected_roots: Arc::default(),
|
||||
cache_dir: self.data_dir.join("cache").join(&project_key),
|
||||
db,
|
||||
http_history,
|
||||
agents,
|
||||
watcher,
|
||||
content_watchers: Mutex::new(Vec::new()),
|
||||
_scratch_watcher: None,
|
||||
light: true,
|
||||
root: dir,
|
||||
});
|
||||
tracing::info!("window {window} edits {} without a project", file.display());
|
||||
self.insert_project(window, project.clone());
|
||||
Ok(project)
|
||||
}
|
||||
}
|
||||
|
||||
impl Project {
|
||||
/// LightEdit: follow external changes to the files of `dir` (its own entries only).
|
||||
pub fn watch_light_dir(&self, dir: &Path) {
|
||||
if !self.light {
|
||||
return;
|
||||
}
|
||||
let dir = dunce::canonicalize(dir).unwrap_or_else(|_| dir.to_path_buf());
|
||||
let mut watchers = self.content_watchers.lock();
|
||||
if dir == self.root || watchers.iter().any(|(p, _)| *p == dir) {
|
||||
return;
|
||||
}
|
||||
match light_watcher(&dir, &self.sink, &self.documents, &self.history) {
|
||||
Ok(w) => watchers.push((dir, w)),
|
||||
Err(e) => tracing::warn!("watching {}: {e}", dir.display()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn light_watcher(
|
||||
dir: &Path,
|
||||
sink: &SharedSink,
|
||||
documents: &Arc<Documents>,
|
||||
history: &Arc<LocalHistory>,
|
||||
) -> IdeResult<Watcher> {
|
||||
let (documents, history) = (documents.clone(), history.clone());
|
||||
Watcher::start_with(
|
||||
dir,
|
||||
Vec::new(),
|
||||
sink.clone(),
|
||||
Box::new(move |batch| {
|
||||
let changed: Vec<PathBuf> = batch.created.iter().chain(&batch.modified).cloned().collect();
|
||||
documents.on_disk_changed(&changed);
|
||||
record_external_changes(&history, &changed, &batch.removed);
|
||||
}),
|
||||
ide_vfs::WatchMode::Flat,
|
||||
)
|
||||
}
|
||||
|
||||
/// Looks for repositories nested below the project (and the one containing it);
|
||||
@@ -639,9 +507,6 @@ impl Project {
|
||||
/// Applies changed content roots and exclude settings to the index (which
|
||||
/// rescans in the background) and the file watchers, without reopening the project.
|
||||
pub fn refresh_index_scope(&self) {
|
||||
if self.light {
|
||||
return;
|
||||
}
|
||||
let (roots, excludes) = (self.content_roots(), self.exclude_globs());
|
||||
self.index.set_scope(roots.clone(), excludes.clone());
|
||||
self.watcher.set_excludes(&excludes);
|
||||
|
||||
@@ -79,7 +79,7 @@ fn read_login_env(timeout: std::time::Duration) -> Option<Vec<(OsString, OsStrin
|
||||
|
||||
let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/zsh".into());
|
||||
const MARK: &str = "__OPENIDEA_ENV__";
|
||||
let mut child = ide_core::process::prepare(&mut Command::new(&shell))
|
||||
let mut child = Command::new(&shell)
|
||||
.args(["-ilc", &format!("printf '{MARK}'; /usr/bin/env -0; printf '{MARK}'")])
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
|
||||
@@ -1,78 +0,0 @@
|
||||
//! LightEdit: a window editing loose files without a project.
|
||||
|
||||
use ide_core::{ChangeSet, NullSink, TextChange};
|
||||
use ide_host::{Host, HostConfig, ops};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
fn host(base: &std::path::Path) -> Arc<Host> {
|
||||
Arc::new(Host::new(HostConfig {
|
||||
config_dir: base.join("config"),
|
||||
data_dir: base.join("data"),
|
||||
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
|
||||
syntax: Arc::default(),
|
||||
sink_for: Box::new(|_| Arc::new(NullSink)),
|
||||
owner: |w| w,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
}))
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn edits_loose_files_without_project_services() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let tmp_root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let (a_dir, b_dir) = (tmp_root.join("a"), tmp_root.join("b"));
|
||||
std::fs::create_dir_all(a_dir.join(".git")).unwrap();
|
||||
std::fs::create_dir_all(&b_dir).unwrap();
|
||||
std::fs::write(a_dir.join("one.py"), "print(1)\n").unwrap();
|
||||
std::fs::write(b_dir.join("two.rs"), "fn main() {}\n").unwrap();
|
||||
let host = host(&tmp_root.join("app"));
|
||||
|
||||
let light = host.open_light("main", &a_dir.join("one.py")).unwrap();
|
||||
assert!(light.light);
|
||||
assert_eq!(light.root, a_dir);
|
||||
assert!(host.open_light("main", &b_dir).is_err(), "a folder is not opened for LightEdit");
|
||||
|
||||
let doc = ops::doc::open(&host, "main", a_dir.join("one.py")).await.unwrap();
|
||||
assert!(doc.text.starts_with("print"));
|
||||
let changes = ChangeSet { changes: vec![TextChange { from: 0, to: 0, insert: "#\n".into() }] };
|
||||
let version = ops::doc::edit(&host, "main", doc.id, doc.version, changes).unwrap();
|
||||
assert!(version > doc.version);
|
||||
ops::doc::save(&host, "main", doc.id).await.unwrap();
|
||||
assert_eq!(std::fs::read_to_string(a_dir.join("one.py")).unwrap(), "#\nprint(1)\n");
|
||||
|
||||
// More files join the same session, wherever they are.
|
||||
let again = host.open_light("main", &b_dir.join("two.rs")).unwrap();
|
||||
assert!(Arc::ptr_eq(&light, &again));
|
||||
ops::doc::open(&host, "main", b_dir.join("two.rs")).await.unwrap();
|
||||
|
||||
assert!(light.index.wait_idle(Duration::from_secs(10)));
|
||||
assert_eq!(light.index.status().files, 0, "nothing is indexed");
|
||||
assert!(light.lsp.servers().is_empty(), "no language servers");
|
||||
assert!(light.repos().is_empty(), "no repositories");
|
||||
|
||||
// Opening the folder as a project replaces the LightEdit session.
|
||||
let project = host.open_project("main", &a_dir).unwrap();
|
||||
assert!(!project.light);
|
||||
assert!(!Arc::ptr_eq(&project, &light));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn light_windows_ignore_project_scoped_settings() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = dunce::canonicalize(tmp.path()).unwrap().join("loose");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("notes.txt"), "x\n").unwrap();
|
||||
let host = host(&tmp.path().join("app"));
|
||||
host.open_light("main", &dir.join("notes.txt")).unwrap();
|
||||
let applied = ops::project::set_settings(
|
||||
&host,
|
||||
"main",
|
||||
ide_workspace::settings::SettingsScope::Project,
|
||||
"general.projectName",
|
||||
"\"loose\"",
|
||||
)
|
||||
.unwrap();
|
||||
assert!(!applied.project_scope);
|
||||
assert!(!dir.join(".openidea").exists(), "no project settings next to the file");
|
||||
}
|
||||
@@ -90,29 +90,11 @@ impl ProjectIndex {
|
||||
let store = store::Store::open(cache_dir, &root, &syntax.fingerprint());
|
||||
let filter = filter::PathFilter::new(&root, &content_roots, &excludes);
|
||||
let shared = Arc::new(Shared::new(filter, languages, syntax, sink, store));
|
||||
Self::start(shared, root, true)
|
||||
}
|
||||
|
||||
/// An index that never scans or persists anything (a window editing loose
|
||||
/// files): queries answer empty, recent files are kept in memory only.
|
||||
pub fn unindexed(
|
||||
root: &Path,
|
||||
languages: Arc<LanguageRegistry>,
|
||||
syntax: Arc<Syntax>,
|
||||
sink: SharedSink,
|
||||
) -> IdeResult<Arc<Self>> {
|
||||
let root = dunce::canonicalize(root).unwrap_or_else(|_| root.to_owned());
|
||||
let filter = filter::PathFilter::new(&root, &[], &[]);
|
||||
let shared = Arc::new(Shared::new(filter, languages, syntax, sink, None));
|
||||
Self::start(shared, root, false)
|
||||
}
|
||||
|
||||
fn start(shared: Arc<Shared>, root: PathBuf, scan: bool) -> IdeResult<Arc<Self>> {
|
||||
let worker = {
|
||||
let shared = shared.clone();
|
||||
std::thread::Builder::new()
|
||||
.name("openidea-index".into())
|
||||
.spawn(move || shared.run(scan))
|
||||
.spawn(move || shared.run())
|
||||
.map_err(|e| ide_core::IdeError::internal(format!("cannot start indexer: {e}")))?
|
||||
};
|
||||
Ok(Arc::new(Self { shared, worker: Mutex::new(Some(worker)), root }))
|
||||
@@ -218,11 +200,9 @@ impl ProjectIndex {
|
||||
self.shared.enqueue(Job::SaveRecent);
|
||||
}
|
||||
|
||||
/// Recently opened files, most recent first; files deleted since (also while
|
||||
/// the IDE was closed) are left out. Virtual documents are always listed.
|
||||
/// Recently opened files, most recent first.
|
||||
pub fn recent_files(&self) -> Vec<PathBuf> {
|
||||
let recent = self.shared.recent.lock().clone();
|
||||
recent.into_iter().filter(|p| p.to_str().is_some_and(ide_core::text::is_virtual_uri) || p.exists()).collect()
|
||||
self.shared.recent.lock().clone()
|
||||
}
|
||||
|
||||
/// Blocks until the initial scan and every queued update has been applied
|
||||
|
||||
@@ -178,19 +178,6 @@ fn symbol_ranking_is_idea_like() {
|
||||
assert!(idx.find_symbols("", SymbolFilter::All, 5).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recent_files_skip_deleted_files_but_keep_virtual_documents() {
|
||||
let fx = sample();
|
||||
let idx = fx.open();
|
||||
let app = fx.root.join("web/app.py");
|
||||
let virt = PathBuf::from("jdt://contents/rt.jar/java.lang/String.class");
|
||||
idx.mark_recent(&app);
|
||||
idx.mark_recent(&virt);
|
||||
assert_eq!(idx.recent_files(), vec![virt.clone(), app.clone()]);
|
||||
std::fs::remove_file(&app).unwrap();
|
||||
assert_eq!(idx.recent_files(), vec![virt]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn persistence_skips_unchanged_files_on_reopen() {
|
||||
let fx = sample();
|
||||
@@ -486,25 +473,3 @@ fn file_type_changes_reparse_affected_files() {
|
||||
assert_eq!(symbols(&idx, "beta", SymbolFilter::All), ["beta"]);
|
||||
assert_eq!(idx.shared.parsed.load(Ordering::SeqCst), parsed + 1, "only the affected file is re-parsed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unindexed_index_never_scans_or_persists() {
|
||||
let fx = Fixture::new(&[("a.rs", "fn alpha() {}\n")]);
|
||||
let events = Arc::new(Mutex::new(Vec::new()));
|
||||
let sink: SharedSink = {
|
||||
let events = events.clone();
|
||||
Arc::new(move |e: IdeEvent| events.lock().push(e))
|
||||
};
|
||||
let languages = Arc::new(LanguageRegistry::load(None).unwrap());
|
||||
let idx = ProjectIndex::unindexed(&fx.root, languages, Arc::new(Syntax::new()), sink).unwrap();
|
||||
assert!(idx.wait_idle(WAIT));
|
||||
let st = idx.status();
|
||||
assert!(!st.indexing);
|
||||
assert_eq!(st.files, 0);
|
||||
assert!(files(&idx, "a").is_empty());
|
||||
idx.mark_recent(&fx.root.join("a.rs"));
|
||||
assert!(idx.wait_idle(WAIT));
|
||||
assert_eq!(idx.recent_files(), vec![fx.root.join("a.rs")]);
|
||||
assert!(!fx.cache.exists());
|
||||
assert!(!events.lock().iter().any(|e| matches!(e, IdeEvent::Task { .. })), "no indexing task");
|
||||
}
|
||||
@@ -127,18 +127,13 @@ impl Shared {
|
||||
|
||||
// ---------------------------------------------------------------- thread
|
||||
|
||||
/// `scan`: load the persisted index and scan the roots before serving updates.
|
||||
pub(crate) fn run(&self, scan: bool) {
|
||||
pub(crate) fn run(&self) {
|
||||
{
|
||||
let mut q = self.queue.lock();
|
||||
q.busy = true;
|
||||
}
|
||||
if scan {
|
||||
self.load_persisted();
|
||||
self.full_scan();
|
||||
} else {
|
||||
self.indexing.store(false, Ordering::SeqCst);
|
||||
}
|
||||
self.load_persisted();
|
||||
self.full_scan();
|
||||
{
|
||||
let mut q = self.queue.lock();
|
||||
q.busy = false;
|
||||
|
||||
@@ -355,7 +355,7 @@ impl Peer {
|
||||
) -> std::io::Result<Self> {
|
||||
use std::process::Stdio;
|
||||
let mut cmd = tokio::process::Command::new(command);
|
||||
ide_core::process::prepare(cmd.as_std_mut());
|
||||
ide_core::process::no_window(cmd.as_std_mut());
|
||||
cmd.args(args)
|
||||
.current_dir(cwd)
|
||||
.envs(ide_core::process::shell_env())
|
||||
|
||||
@@ -9,7 +9,6 @@ license.workspace = true
|
||||
ide-core.workspace = true
|
||||
ide-text.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
specta.workspace = true
|
||||
toml.workspace = true
|
||||
tree-sitter.workspace = true
|
||||
|
||||
@@ -69,17 +69,9 @@ pub struct LanguageServerConfig {
|
||||
/// Files whose presence marks a workspace root, e.g. `Cargo.toml`.
|
||||
#[serde(default)]
|
||||
pub root_markers: Vec<String>,
|
||||
/// Serve only files below a root marker, not the whole project: a framework's
|
||||
/// server (Angular) next to the language's own one.
|
||||
#[serde(default)]
|
||||
pub require_root_marker: bool,
|
||||
/// JSON passed as `initializationOptions`.
|
||||
#[serde(default)]
|
||||
pub initialization_options: Option<toml::Value>,
|
||||
/// Answers `workspace/configuration`; without it the sections are looked up
|
||||
/// in `initialization_options`.
|
||||
#[serde(default)]
|
||||
pub settings: Option<serde_json::Value>,
|
||||
/// Human hint shown when the binary is missing.
|
||||
#[serde(default)]
|
||||
pub install_hint: Option<String>,
|
||||
@@ -95,10 +87,6 @@ pub struct LanguageServerConfig {
|
||||
/// basedpyright): only used while none of those is installed.
|
||||
#[serde(default)]
|
||||
pub fallback: bool,
|
||||
/// Newest Java release the server runs on (kotlin-language-server: 21). A
|
||||
/// newer `JAVA_HOME` is replaced by the newest installed JDK that fits.
|
||||
#[serde(default)]
|
||||
pub max_java: Option<u32>,
|
||||
/// Set by the settings hook when the server can't run here (jdtls without
|
||||
/// a JDK 21+); reported as the failure instead of launching it.
|
||||
#[serde(skip)]
|
||||
|
||||
@@ -518,37 +518,12 @@ mod tests {
|
||||
#[test]
|
||||
fn alternative_servers_are_fallbacks() {
|
||||
let reg = reg();
|
||||
for (lang, servers) in [
|
||||
("python", vec!["basedpyright", "pyright", "ty"]),
|
||||
("typescript", vec!["vtsls", "typescript-language-server"]),
|
||||
] {
|
||||
for (lang, servers) in
|
||||
[("python", ["basedpyright", "pyright"]), ("typescript", ["vtsls", "typescript-language-server"])]
|
||||
{
|
||||
let cfg = reg.get(&LanguageId::new(lang)).unwrap();
|
||||
let got: Vec<(&str, bool)> = cfg
|
||||
.language_servers
|
||||
.iter()
|
||||
.filter(|s| !s.require_root_marker)
|
||||
.map(|s| (s.name.as_str(), s.fallback))
|
||||
.collect();
|
||||
let expected: Vec<(&str, bool)> = servers.iter().enumerate().map(|(i, name)| (*name, i > 0)).collect();
|
||||
assert_eq!(got, expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn angular_server_joins_typescript_and_html_in_angular_projects() {
|
||||
let reg = reg();
|
||||
let names = |lang: &str| -> Vec<String> {
|
||||
reg.get(&LanguageId::new(lang)).unwrap().language_servers.iter().map(|s| s.name.clone()).collect()
|
||||
};
|
||||
// After the TypeScript fallback (an available server before it would hide
|
||||
// it); before the HTML server (hover, rename and symbols take the first).
|
||||
assert_eq!(names("typescript"), ["vtsls", "typescript-language-server", "angular-language-server"]);
|
||||
assert_eq!(names("html"), ["angular-language-server", "vscode-html-language-server"]);
|
||||
for lang in ["typescript", "html"] {
|
||||
let cfg = reg.get(&LanguageId::new(lang)).unwrap();
|
||||
let angular = cfg.language_servers.iter().find(|s| s.name == "angular-language-server").unwrap();
|
||||
assert!(angular.require_root_marker && !angular.fallback, "{lang}");
|
||||
assert_eq!(angular.root_markers, ["angular.json", "node_modules/@angular/core"], "{lang}");
|
||||
let got: Vec<(&str, bool)> = cfg.language_servers.iter().map(|s| (s.name.as_str(), s.fallback)).collect();
|
||||
assert_eq!(got, [(servers[0], false), (servers[1], true)]);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -79,24 +79,20 @@ fn is_name_leaf(kind: &str) -> bool {
|
||||
kind.contains("identifier") || kind == "name"
|
||||
}
|
||||
|
||||
/// Node kinds whose `name` field is a use, not a declaration.
|
||||
const USE_PARENTS: &[&str] =
|
||||
&["invocation", "call", "access", "scoped", "reference", "expression", "selector", "qualified", "use_", "import"];
|
||||
|
||||
/// Whether the identifier leaf under `cursor` is the name a declaration
|
||||
/// introduces (`fn name`, `let pattern`, `int *declarator`, parameters,
|
||||
/// `name = …` assignments) rather than a use of one.
|
||||
fn declares(cursor: &TreeCursor<'_>, node: &Node<'_>) -> bool {
|
||||
let parent = node.parent().map(|p| p.kind()).unwrap_or_default();
|
||||
// Paths and calls name what is declared elsewhere (`use a::b::name`, `a.name()`).
|
||||
let reference = ["scoped", "qualified", "invocation", "member_access", "use_", "import", "call"]
|
||||
.iter()
|
||||
.any(|k| parent.contains(k));
|
||||
match cursor.field_name() {
|
||||
// Uses name their target with a `name` field too: Java `s.substring()`,
|
||||
// C# `a.Name`, Rust `use a::b::name`.
|
||||
Some("name") => !USE_PARENTS.iter().any(|p| parent.contains(p)),
|
||||
Some("name") => !reference,
|
||||
Some("pattern" | "declarator") => true,
|
||||
Some("left") => parent.contains("assignment") || parent.contains("declarator"),
|
||||
// A parameter's name, not its type (`String text`).
|
||||
Some("type") => false,
|
||||
_ => parent.contains("parameter") && !node.kind().contains("type"),
|
||||
_ => parent.contains("parameter"),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1320,13 +1320,4 @@ fn spelling_regions_cover_declared_names_only() {
|
||||
.map(|r| &rs[r.start..r.end])
|
||||
.collect();
|
||||
assert_eq!(names, ["run", "n"]);
|
||||
let java = "class Bird { String fly(String text) { return text.substring(1); } }\n";
|
||||
let names: Vec<&str> = syntax()
|
||||
.spelling_regions(&lang("java"), java)
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter(|r| r.kind == SpellingKind::Name)
|
||||
.map(|r| &java[r.start..r.end])
|
||||
.collect();
|
||||
assert_eq!(names, ["Bird", "fly", "text"]);
|
||||
}
|
||||
@@ -1,273 +0,0 @@
|
||||
//! The Angular Language Server next to vtsls in TypeScript files, asked like
|
||||
//! VS Code's Angular extension asks it: about positions only inside a
|
||||
//! component's template and styles, since it answers nothing elsewhere and
|
||||
//! answers late while it analyses the project.
|
||||
|
||||
pub(crate) const SERVER: &str = "angular-language-server";
|
||||
|
||||
/// Decorator fields holding templates, styles and host bindings.
|
||||
const PROPERTIES: [&str; 6] = ["template", "templateUrl", "styles", "styleUrls", "styleUrl", "host"];
|
||||
/// Decorators taking host bindings as string arguments.
|
||||
const DECORATORS: [&str; 2] = ["HostBinding", "HostListener"];
|
||||
|
||||
/// Whether the Angular server is asked about the position at byte `offset` of
|
||||
/// a `language` document: anywhere in a template file, in TypeScript only in
|
||||
/// a string of a decorator field.
|
||||
pub(crate) fn serves_position(language: &str, text: &str, offset: usize) -> bool {
|
||||
language != "typescript" || in_decorator_field(text, offset)
|
||||
}
|
||||
|
||||
/// Whether the Angular server is asked for the inlay hints of a `language`
|
||||
/// document: in TypeScript only with Angular imported.
|
||||
pub(crate) fn serves_inlay_hints(language: &str, text: &str) -> bool {
|
||||
language != "typescript" || text.contains("@angular/core")
|
||||
}
|
||||
|
||||
/// Whether byte `offset` is inside a string of one of [`PROPERTIES`] (`template:
|
||||
/// '...'`, `styles: ['...']`) or of an argument of one of [`DECORATORS`]. A
|
||||
/// port of the VS Code extension's token scan: false positives are fine, the
|
||||
/// server has the last word.
|
||||
fn in_decorator_field(text: &str, offset: usize) -> bool {
|
||||
let mut scanner = Scanner { text: text.as_bytes(), pos: 0, braces: 0, substitutions: Vec::new() };
|
||||
let (mut last, mut second_last, mut last_text) = (None, None, "");
|
||||
let (mut braces, mut brackets, mut parens) = (0i32, 0i32, 0i32);
|
||||
// The brace and bracket depth of the property whose value is being read.
|
||||
let mut property: Option<(i32, i32)> = None;
|
||||
// The paren depth of the decorator whose arguments are being read.
|
||||
let mut decorator: Option<i32> = None;
|
||||
while let Some((tok, start, end)) = scanner.next() {
|
||||
if start >= offset {
|
||||
break;
|
||||
}
|
||||
if last == Some(Tok::Ident) && tok == Tok::Colon && PROPERTIES.contains(&last_text) {
|
||||
property = Some((braces, brackets));
|
||||
continue;
|
||||
}
|
||||
if property == Some((braces, brackets)) && matches!(tok, Tok::Comma | Tok::Semicolon | Tok::CloseBrace) {
|
||||
property = None;
|
||||
}
|
||||
if second_last == Some(Tok::At)
|
||||
&& last == Some(Tok::Ident)
|
||||
&& tok == Tok::OpenParen
|
||||
&& DECORATORS.contains(&last_text)
|
||||
{
|
||||
decorator = Some(parens);
|
||||
}
|
||||
if tok == Tok::CloseParen && decorator == Some(parens - 1) {
|
||||
decorator = None;
|
||||
}
|
||||
match tok {
|
||||
Tok::OpenBrace => braces += 1,
|
||||
Tok::CloseBrace => braces -= 1,
|
||||
Tok::OpenBracket => brackets += 1,
|
||||
Tok::CloseBracket => brackets -= 1,
|
||||
Tok::OpenParen => parens += 1,
|
||||
Tok::CloseParen => parens -= 1,
|
||||
_ => {}
|
||||
}
|
||||
if (property.is_some() || decorator.is_some()) && tok == Tok::Str && offset <= end {
|
||||
return true;
|
||||
}
|
||||
last_text = text.get(start..end).unwrap_or("");
|
||||
second_last = last;
|
||||
last = Some(tok);
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Tok {
|
||||
Ident,
|
||||
Colon,
|
||||
Comma,
|
||||
Semicolon,
|
||||
At,
|
||||
OpenBrace,
|
||||
CloseBrace,
|
||||
OpenBracket,
|
||||
CloseBracket,
|
||||
OpenParen,
|
||||
CloseParen,
|
||||
/// A string or a template literal without substitutions.
|
||||
Str,
|
||||
/// A part of a template literal with substitutions (`` `a${`` / `}b${` / `` }c` ``).
|
||||
Template,
|
||||
Other,
|
||||
}
|
||||
|
||||
/// TypeScript tokens, enough to tell strings, names and brackets apart.
|
||||
/// Like the TypeScript scanner without its parser, `/` is never a regex.
|
||||
struct Scanner<'a> {
|
||||
text: &'a [u8],
|
||||
pos: usize,
|
||||
/// Open `{`, not counting those of template substitutions.
|
||||
braces: usize,
|
||||
/// The brace depth each open `${` started at, innermost last.
|
||||
substitutions: Vec<usize>,
|
||||
}
|
||||
|
||||
impl Scanner<'_> {
|
||||
/// The next token and its byte range.
|
||||
fn next(&mut self) -> Option<(Tok, usize, usize)> {
|
||||
self.skip_trivia();
|
||||
let start = self.pos;
|
||||
let c = *self.text.get(start)?;
|
||||
self.pos += 1;
|
||||
let tok = match c {
|
||||
b'\'' | b'"' => {
|
||||
self.string(c);
|
||||
Tok::Str
|
||||
}
|
||||
b'`' => {
|
||||
if self.template() {
|
||||
Tok::Template
|
||||
} else {
|
||||
Tok::Str
|
||||
}
|
||||
}
|
||||
b'{' => {
|
||||
self.braces += 1;
|
||||
Tok::OpenBrace
|
||||
}
|
||||
// The end of a substitution: the template literal goes on.
|
||||
b'}' if self.substitutions.last() == Some(&self.braces) => {
|
||||
self.substitutions.pop();
|
||||
self.template();
|
||||
Tok::Template
|
||||
}
|
||||
b'}' => {
|
||||
self.braces = self.braces.saturating_sub(1);
|
||||
Tok::CloseBrace
|
||||
}
|
||||
b'[' => Tok::OpenBracket,
|
||||
b']' => Tok::CloseBracket,
|
||||
b'(' => Tok::OpenParen,
|
||||
b')' => Tok::CloseParen,
|
||||
b':' => Tok::Colon,
|
||||
b',' => Tok::Comma,
|
||||
b';' => Tok::Semicolon,
|
||||
b'@' => Tok::At,
|
||||
c if is_ident(c) => {
|
||||
while self.text.get(self.pos).is_some_and(|&c| is_ident(c)) {
|
||||
self.pos += 1;
|
||||
}
|
||||
if c.is_ascii_digit() { Tok::Other } else { Tok::Ident }
|
||||
}
|
||||
_ => Tok::Other,
|
||||
};
|
||||
Some((tok, start, self.pos))
|
||||
}
|
||||
|
||||
fn skip_trivia(&mut self) {
|
||||
loop {
|
||||
match (self.text.get(self.pos), self.text.get(self.pos + 1)) {
|
||||
(Some(c), _) if c.is_ascii_whitespace() => self.pos += 1,
|
||||
(Some(b'/'), Some(b'/')) => {
|
||||
while self.text.get(self.pos).is_some_and(|&c| c != b'\n') {
|
||||
self.pos += 1;
|
||||
}
|
||||
}
|
||||
(Some(b'/'), Some(b'*')) => {
|
||||
self.pos += 2;
|
||||
while self.pos < self.text.len() && !self.text[self.pos..].starts_with(b"*/") {
|
||||
self.pos += 1;
|
||||
}
|
||||
self.pos = (self.pos + 2).min(self.text.len());
|
||||
}
|
||||
_ => return,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The rest of a string opened by `quote`, which a line break ends too.
|
||||
fn string(&mut self, quote: u8) {
|
||||
while let Some(&c) = self.text.get(self.pos) {
|
||||
self.pos += if c == b'\\' { 2 } else { 1 };
|
||||
if c == quote || c == b'\n' {
|
||||
break;
|
||||
}
|
||||
}
|
||||
self.pos = self.pos.min(self.text.len());
|
||||
}
|
||||
|
||||
/// The rest of a template literal part; `true` when a substitution opens it.
|
||||
fn template(&mut self) -> bool {
|
||||
while let Some(&c) = self.text.get(self.pos) {
|
||||
match c {
|
||||
b'\\' => self.pos += 2,
|
||||
b'`' => {
|
||||
self.pos += 1;
|
||||
return false;
|
||||
}
|
||||
b'$' if self.text.get(self.pos + 1) == Some(&b'{') => {
|
||||
self.pos += 2;
|
||||
self.substitutions.push(self.braces);
|
||||
return true;
|
||||
}
|
||||
_ => self.pos += 1,
|
||||
}
|
||||
}
|
||||
self.pos = self.pos.min(self.text.len());
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Identifier bytes; any non-ASCII byte belongs to one too.
|
||||
fn is_ident(c: u8) -> bool {
|
||||
c.is_ascii_alphanumeric() || c == b'_' || c == b'$' || c >= 0x80
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Whether the position marked `|` in `src` is in a decorator field.
|
||||
fn at_marker(src: &str) -> bool {
|
||||
let offset = src.find('|').expect("marker");
|
||||
in_decorator_field(&src.replacen('|', "", 1), offset)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn template_and_style_strings_are_decorator_fields() {
|
||||
assert!(at_marker("@Component({ selector: 'a', template: `<p>{{ |x }}</p>` })"));
|
||||
assert!(at_marker("@Component({\n template: '<p>|</p>',\n})"));
|
||||
assert!(at_marker("@Component({ templateUrl: './a.|html' })"));
|
||||
assert!(at_marker("@Component({ styles: ['p {}', 'a { |}'] })"));
|
||||
assert!(at_marker("@Component({ host: { '(click)': 'on|Click()' } })"));
|
||||
assert!(at_marker("class A { @HostListener('click', ['$event.|target']) on() {} }"));
|
||||
// Still being typed: the string runs to the end of the line.
|
||||
assert!(at_marker("@Component({ template: '<p>|"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn code_and_other_strings_are_not() {
|
||||
assert!(!at_marker("@Component({ selector: 'app-|root', template: '' })"));
|
||||
assert!(!at_marker("@Component({ template: '' })\nclass A { t|itle = 'x'; }"));
|
||||
assert!(!at_marker("@Component({ template: '' })\nclass A { title = '|x'; }"));
|
||||
assert!(!at_marker("@Component({ template: |`<p></p>` })"));
|
||||
assert!(!at_marker("@Component({ template: '', imports: [A|] })"));
|
||||
assert!(!at_marker("class A { @HostListener('click') on() { const s = '|'; } }"));
|
||||
assert!(!at_marker("// template: '|'\nclass A {}"));
|
||||
assert!(!at_marker("/* template: '|' */"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn substitutions_dont_end_template_literals() {
|
||||
// `}` closing `${...}` is not the end of the object holding `template`.
|
||||
assert!(at_marker("const a = `${ {b: 1} }`;\n@Component({ template: '<p>|</p>' })"));
|
||||
assert!(!at_marker("@Component({ template: `<p>${x}|</p>` })"));
|
||||
assert!(at_marker("const s = `${'}'}`; @Component({ template: '<i>|</i>' })"));
|
||||
assert!(!at_marker("const s = `${`${'a'}`}`; class A { b = '|'; }"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typescript_positions_go_to_angular_only_in_decorator_fields() {
|
||||
let src = "@Component({ template: '<p></p>' })\nclass A {}";
|
||||
assert!(serves_position("html", src, src.find("class").unwrap()));
|
||||
assert!(!serves_position("typescript", src, src.find("class").unwrap()));
|
||||
assert!(serves_position("typescript", src, src.find("</p>").unwrap()));
|
||||
assert!(serves_inlay_hints("typescript", "import { Component } from '@angular/core';"));
|
||||
assert!(!serves_inlay_hints("typescript", "export const a = 1;"));
|
||||
assert!(serves_inlay_hints("html", ""));
|
||||
}
|
||||
}
|
||||
@@ -664,36 +664,6 @@ pub fn workspace_edit(conv: &Conv, e: lsp::WorkspaceEdit) -> WorkspaceEdit {
|
||||
WorkspaceEdit { files }
|
||||
}
|
||||
|
||||
/// Adds the changes of `extra`, another server's edit for the same request, to
|
||||
/// `edit` where they leave its own alone: what only the other server sees
|
||||
/// (Angular templates next to vtsls's TypeScript).
|
||||
pub fn merge_workspace_edit(edit: &mut WorkspaceEdit, extra: WorkspaceEdit) {
|
||||
let overlap =
|
||||
|a: &TextEdit, b: &TextEdit| a.range == b.range || (a.range.start < b.range.end && b.range.start < a.range.end);
|
||||
for file in extra.files {
|
||||
let FileEdit::Edit { path, edits } = file else {
|
||||
if !edit.files.contains(&file) {
|
||||
edit.files.push(file);
|
||||
}
|
||||
continue;
|
||||
};
|
||||
let own = edit.files.iter_mut().find_map(|f| match f {
|
||||
FileEdit::Edit { path: p, edits } if *p == path => Some(edits),
|
||||
_ => None,
|
||||
});
|
||||
match own {
|
||||
Some(own) => {
|
||||
let added: Vec<TextEdit> = edits.into_iter().filter(|e| !own.iter().any(|o| overlap(o, e))).collect();
|
||||
if !added.is_empty() {
|
||||
own.extend(added);
|
||||
own.sort_by_key(|e| e.range.start);
|
||||
}
|
||||
}
|
||||
None => edit.files.push(FileEdit::Edit { path, edits }),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- navigation
|
||||
|
||||
pub fn goto_response(conv: &Conv, r: lsp::GotoDefinitionResponse) -> Vec<Location> {
|
||||
@@ -1020,33 +990,6 @@ mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn merged_rename_edits_keep_the_first_servers_ones() {
|
||||
let edit = |l: u32, c: u32, text: &str| TextEdit {
|
||||
range: Range::new(Pos::new(l, c), Pos::new(l, c + 5)),
|
||||
new_text: text.into(),
|
||||
};
|
||||
let file = |p: &str, edits: Vec<TextEdit>| FileEdit::Edit { path: PathBuf::from(p).into(), edits };
|
||||
// vtsls renames a shorthand property with an alias; the Angular server
|
||||
// renames it plainly and adds the template.
|
||||
let mut merged =
|
||||
WorkspaceEdit { files: vec![file("/a.ts", vec![edit(3, 2, "items: entries"), edit(9, 4, "entries")])] };
|
||||
let angular = WorkspaceEdit {
|
||||
files: vec![
|
||||
file("/a.ts", vec![edit(9, 4, "entries"), edit(3, 2, "entries"), edit(1, 14, "entries")]),
|
||||
file("/a.html", vec![edit(0, 7, "entries")]),
|
||||
],
|
||||
};
|
||||
merge_workspace_edit(&mut merged, angular);
|
||||
assert_eq!(
|
||||
merged.files,
|
||||
[
|
||||
file("/a.ts", vec![edit(1, 14, "entries"), edit(3, 2, "items: entries"), edit(9, 4, "entries")]),
|
||||
file("/a.html", vec![edit(0, 7, "entries")]),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snippet_text_takes_placeholder_defaults() {
|
||||
assert_eq!(snippet_text("foo(${1:a}, $2)$0"), "foo(a, )");
|
||||
|
||||
@@ -12,9 +12,6 @@ use lsp_types as lsp;
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::{Arc, Weak};
|
||||
|
||||
/// Progress token standing for `angular/projectLoadingStart` … `Finish`.
|
||||
const ANGULAR_LOADING: &str = "angular/projectLoading";
|
||||
|
||||
pub struct ClientHandler {
|
||||
mgr: Weak<LspManager>,
|
||||
server: Arc<Server>,
|
||||
@@ -128,18 +125,20 @@ impl ClientHandler {
|
||||
}
|
||||
|
||||
fn configuration(&self, params: &Value) -> Value {
|
||||
let options = all_settings(&self.server.effective_config());
|
||||
let options = self
|
||||
.server
|
||||
.effective_config()
|
||||
.initialization_options
|
||||
.as_ref()
|
||||
.and_then(|v| serde_json::to_value(v).ok())
|
||||
.unwrap_or(Value::Null);
|
||||
let items = params.get("items").and_then(Value::as_array).cloned().unwrap_or_default();
|
||||
Value::Array(
|
||||
items
|
||||
.iter()
|
||||
// vtsls asks for the whole configuration as section `""`.
|
||||
.map(|item| match item.get("section").and_then(Value::as_str).filter(|s| !s.is_empty()) {
|
||||
// The server's own section: its block under `settings` (basedpyright asks
|
||||
// `basedpyright` and `basedpyright.analysis`), else the options themselves.
|
||||
Some(section) if section == self.server.name => {
|
||||
options.get("settings").and_then(|s| s.get(section)).unwrap_or(&options).clone()
|
||||
}
|
||||
Some(section) if section == self.server.name => options.clone(),
|
||||
// Servers that take settings under `initializationOptions.settings`
|
||||
// (jdtls) ask for the same sections later.
|
||||
Some(section) => [&options, options.get("settings").unwrap_or(&Value::Null)]
|
||||
@@ -204,17 +203,6 @@ impl Handler for ClientHandler {
|
||||
}
|
||||
}
|
||||
"tsserver/request" => mgr.forward_tsserver_requests(self.server.clone(), self.generation, params),
|
||||
// The Angular server's project loading, shown like `$/progress`; one
|
||||
// task while several projects load.
|
||||
"angular/projectLoadingStart" if !self.server.progress.lock().contains_key(ANGULAR_LOADING) => self
|
||||
.progress(
|
||||
&mgr,
|
||||
json!({ "token": ANGULAR_LOADING, "value": { "kind": "begin", "title": "Loading Angular project" } }),
|
||||
),
|
||||
"angular/projectLoadingStart" => {}
|
||||
"angular/projectLoadingFinish" => {
|
||||
self.progress(&mgr, json!({ "token": ANGULAR_LOADING, "value": { "kind": "end" } }))
|
||||
}
|
||||
"telemetry/event" | "$/logTrace" | "$/cancelRequest" => {}
|
||||
other => tracing::trace!("[{}] unhandled notification {other}", self.server.name),
|
||||
}
|
||||
@@ -256,29 +244,3 @@ impl Handler for ClientHandler {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What `workspace/configuration` sections are looked up in: the server's
|
||||
/// `initializationOptions` with its `settings` merged over them.
|
||||
pub(crate) fn all_settings(cfg: &ide_language::LanguageServerConfig) -> Value {
|
||||
let mut out = cfg.initialization_options.as_ref().and_then(|v| serde_json::to_value(v).ok()).unwrap_or(Value::Null);
|
||||
if let Some(settings) = &cfg.settings {
|
||||
merge(&mut out, settings.clone());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn merge(base: &mut Value, layer: Value) {
|
||||
match (base, layer) {
|
||||
(Value::Object(base), Value::Object(layer)) => {
|
||||
for (k, v) in layer {
|
||||
match base.get_mut(&k) {
|
||||
Some(existing) => merge(existing, v),
|
||||
None => {
|
||||
base.insert(k, v);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
(base, layer) => *base = layer,
|
||||
}
|
||||
}
|
||||
@@ -65,12 +65,8 @@ impl LspManager {
|
||||
/// run doesn't prompt to install every language it meets.
|
||||
pub fn serves_path(&self, path: &Path) -> bool {
|
||||
let lang = self.languages.detect(path, None);
|
||||
self.language_servers(&lang).iter().any(|ls| {
|
||||
if ls.require_root_marker
|
||||
&& crate::launch::marked_root(&self.project_root, path, &ls.root_markers).is_none()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let Some(config) = self.languages.get(&lang) else { return false };
|
||||
config.language_servers.iter().any(|ls| {
|
||||
let mut cfg = ls.clone();
|
||||
if let Some(hook) = self.config_hook.read().clone() {
|
||||
hook(&mut cfg, &self.project_root);
|
||||
|
||||
@@ -116,7 +116,7 @@ fn resolve_rustup_proxy(command: &str, binary: PathBuf) -> Option<PathBuf> {
|
||||
if !is_proxy || command.contains('/') {
|
||||
return Some(binary);
|
||||
}
|
||||
let works = ide_core::process::prepare(&mut std::process::Command::new(&binary))
|
||||
let works = ide_core::process::no_window(&mut std::process::Command::new(&binary))
|
||||
.arg("--version")
|
||||
.stdin(std::process::Stdio::null())
|
||||
.stdout(std::process::Stdio::null())
|
||||
@@ -190,7 +190,7 @@ fn login_shell_path() -> Option<OsString> {
|
||||
use std::time::{Duration, Instant};
|
||||
let shell = std::env::var_os("SHELL")?;
|
||||
const MARK: &str = "__OPENIDEA_PATH__";
|
||||
let mut child = ide_core::process::prepare(&mut Command::new(shell))
|
||||
let mut child = Command::new(shell)
|
||||
.args(["-l", "-c", &format!("printf '{MARK}%s{MARK}' \"$PATH\"")])
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
@@ -228,11 +228,6 @@ pub fn find_root(project_root: &Path, file: &Path, markers: &[String]) -> Option
|
||||
if !file.starts_with(project_root) {
|
||||
return None;
|
||||
}
|
||||
Some(marked_root(project_root, file, markers).unwrap_or_else(|| project_root.to_path_buf()))
|
||||
}
|
||||
|
||||
/// The outermost ancestor of `file` within `project_root` containing a root marker.
|
||||
pub fn marked_root(project_root: &Path, file: &Path, markers: &[String]) -> Option<PathBuf> {
|
||||
let mut best = None;
|
||||
for dir in file.ancestors().skip(1) {
|
||||
if !dir.starts_with(project_root) {
|
||||
@@ -242,7 +237,7 @@ pub fn marked_root(project_root: &Path, file: &Path, markers: &[String]) -> Opti
|
||||
best = Some(dir.to_path_buf());
|
||||
}
|
||||
}
|
||||
best
|
||||
Some(best.unwrap_or_else(|| project_root.to_path_buf()))
|
||||
}
|
||||
|
||||
fn has_marker(dir: &Path, marker: &str) -> bool {
|
||||
@@ -280,19 +275,6 @@ mod tests {
|
||||
std::fs::remove_dir_all(&tmp).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marked_root_needs_a_marker() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
let file = root.join("apps/web/src/app.ts");
|
||||
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
|
||||
let markers = vec!["angular.json".to_string(), "node_modules/@angular/core".to_string()];
|
||||
assert_eq!(marked_root(root, &file, &markers), None);
|
||||
std::fs::create_dir_all(root.join("apps/web/node_modules/@angular/core")).unwrap();
|
||||
assert_eq!(marked_root(root, &file, &markers), Some(root.join("apps/web")));
|
||||
assert_eq!(marked_root(root, &root.join("apps/api/main.ts"), &markers), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn search_path_contains_env_path() {
|
||||
let p = search_path();
|
||||
|
||||
@@ -6,7 +6,6 @@
|
||||
//! IDE coordinates (UTF-16, 0-based) and returns IDE types from [`types`],
|
||||
//! never `lsp-types`, so the IPC surface stays stable.
|
||||
|
||||
mod angular;
|
||||
mod caps;
|
||||
mod convert;
|
||||
mod file_ops;
|
||||
@@ -57,12 +56,6 @@ use types::*;
|
||||
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
const COMPLETION_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
const LONG_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
|
||||
/// How long a server may take to answer `initialize`. Some import the whole
|
||||
/// build there (kotlin-lsp, jdtls on a large Gradle project) and need minutes
|
||||
/// on a cold start; the status shows "starting" meanwhile, and a crash still
|
||||
/// ends the wait at once.
|
||||
const INITIALIZE_TIMEOUT: Duration = Duration::from_secs(300);
|
||||
/// How long a request waits for a server that is still initializing.
|
||||
const START_WAIT: Duration = Duration::from_secs(10);
|
||||
/// File moves may start a server (jdtls takes a while to import).
|
||||
@@ -75,9 +68,6 @@ pub type ApplyEditHook = Arc<dyn Fn(WorkspaceEdit) -> bool + Send + Sync>;
|
||||
/// settings before each launch; receives the server's workspace root.
|
||||
pub type ConfigFn = dyn Fn(&mut LanguageServerConfig, &Path) + Send + Sync;
|
||||
pub type ConfigHook = Arc<ConfigFn>;
|
||||
/// The servers a language uses, from its definition's list (user settings
|
||||
/// disable some and add others).
|
||||
pub type ServersFn = dyn Fn(&LanguageId, &[LanguageServerConfig]) -> Vec<LanguageServerConfig> + Send + Sync;
|
||||
|
||||
struct Attached {
|
||||
server: Arc<Server>,
|
||||
@@ -126,7 +116,6 @@ impl Target {
|
||||
struct DocSnap {
|
||||
path: PathBuf,
|
||||
uri: lsp::Uri,
|
||||
language: LanguageId,
|
||||
text: Arc<DocText>,
|
||||
servers: Vec<Arc<Server>>,
|
||||
}
|
||||
@@ -144,12 +133,6 @@ impl DocSnap {
|
||||
fn pos_params(&self, t: &Target, pos: Pos) -> Value {
|
||||
json!({ "textDocument": self.ident(), "position": self.position(t, pos) })
|
||||
}
|
||||
/// Whether `t` is asked about `pos`: the Angular server not about the
|
||||
/// TypeScript outside a component's template and styles (see [`angular`]).
|
||||
fn asks(&self, t: &Target, pos: Pos) -> bool {
|
||||
t.server.name != angular::SERVER
|
||||
|| angular::serves_position(self.language.as_str(), self.text.as_str(), self.text.byte_offset(pos))
|
||||
}
|
||||
}
|
||||
|
||||
pub struct LspManager {
|
||||
@@ -163,7 +146,6 @@ pub struct LspManager {
|
||||
docs: Mutex<HashMap<DocId, DocState>>,
|
||||
apply_edit_hook: RwLock<Option<ApplyEditHook>>,
|
||||
config_hook: RwLock<Option<ConfigHook>>,
|
||||
servers_hook: RwLock<Option<Arc<ServersFn>>>,
|
||||
candidates_hook: RwLock<Option<Arc<CandidateFn>>>,
|
||||
shutting_down: AtomicBool,
|
||||
/// `window/showMessage` texts already surfaced; servers repeat them on every restart/reconfigure.
|
||||
@@ -282,7 +264,6 @@ impl LspManager {
|
||||
docs: Mutex::new(HashMap::new()),
|
||||
apply_edit_hook: RwLock::new(None),
|
||||
config_hook: RwLock::new(None),
|
||||
servers_hook: RwLock::new(None),
|
||||
candidates_hook: RwLock::new(None),
|
||||
shutting_down: AtomicBool::new(false),
|
||||
shown_messages: Mutex::new(HashSet::new()),
|
||||
@@ -314,37 +295,24 @@ impl LspManager {
|
||||
}
|
||||
|
||||
/// The servers serving `path`: every regular one, and each `fallback` one
|
||||
/// only while all servers listed before it are missing. One that requires a
|
||||
/// root marker serves only files below one, and stands in for no other.
|
||||
/// only while all servers listed before it are missing.
|
||||
fn servers_for(&self, language: &LanguageId, path: &Path) -> Vec<Arc<Server>> {
|
||||
let Some(cfg) = self.languages.get(language) else { return Vec::new() };
|
||||
let mut out = Vec::new();
|
||||
let mut available_before = false;
|
||||
for sc in &self.language_servers(language) {
|
||||
for sc in &cfg.language_servers {
|
||||
if sc.fallback && available_before {
|
||||
continue;
|
||||
}
|
||||
if sc.require_root_marker && launch::marked_root(&self.project_root, path, &sc.root_markers).is_none() {
|
||||
continue;
|
||||
}
|
||||
let server = self.server_for(sc, language, path);
|
||||
available_before |= !sc.require_root_marker && server.status() != ide_core::event::ServerStatus::Missing;
|
||||
available_before |= server.status() != ide_core::event::ServerStatus::Missing;
|
||||
out.push(server);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The definitions of the servers `language` uses.
|
||||
fn language_servers(&self, language: &LanguageId) -> Vec<LanguageServerConfig> {
|
||||
let Some(cfg) = self.languages.get(language) else { return Vec::new() };
|
||||
match self.servers_hook.read().clone() {
|
||||
Some(hook) => hook(language, &cfg.language_servers),
|
||||
None => cfg.language_servers,
|
||||
}
|
||||
}
|
||||
|
||||
/// A server turned out to be missing: attach the fallbacks it was hiding
|
||||
/// to the open documents (and start them). Also attaches servers newly
|
||||
/// enabled in settings.
|
||||
/// to the open documents (and start them).
|
||||
fn attach_fallbacks(&self) {
|
||||
let open: Vec<(DocId, LanguageId, PathBuf)> =
|
||||
self.docs.lock().iter().map(|(id, d)| (*id, d.language.clone(), d.path.clone())).collect();
|
||||
@@ -355,24 +323,22 @@ impl LspManager {
|
||||
let mut docs = self.docs.lock();
|
||||
for (id, servers) in wanted {
|
||||
let Some(d) = docs.get_mut(&id) else { continue };
|
||||
for server in &servers {
|
||||
for server in servers {
|
||||
if d.servers.iter().any(|a| a.server.id == server.id) {
|
||||
continue;
|
||||
}
|
||||
let mut attached = Attached { server: server.clone(), opened_gen: None };
|
||||
if let Some(run) = server.running() {
|
||||
if run.caps.read().open_close {
|
||||
user_did_open(server, &run, &d.path, &d.uri, d.did_open_params());
|
||||
user_did_open(&server, &run, &d.path, &d.uri, d.did_open_params());
|
||||
}
|
||||
attached.opened_gen = Some(run.generation);
|
||||
}
|
||||
d.servers.push(attached);
|
||||
if !start.iter().any(|s: &Arc<Server>| s.id == server.id) {
|
||||
start.push(server.clone());
|
||||
start.push(server);
|
||||
}
|
||||
}
|
||||
// In definition order: the first server answers hover, rename and symbols.
|
||||
d.servers.sort_by_key(|a| servers.iter().position(|s| s.id == a.server.id).unwrap_or(usize::MAX));
|
||||
}
|
||||
}
|
||||
for server in &start {
|
||||
@@ -441,7 +407,7 @@ impl LspManager {
|
||||
};
|
||||
|
||||
let init = self.initialize_params(&server);
|
||||
let result = tokio::time::timeout(INITIALIZE_TIMEOUT, peer.request::<_, Value>("initialize", init, None))
|
||||
let result = tokio::time::timeout(Duration::from_secs(60), peer.request::<_, Value>("initialize", init, None))
|
||||
.await
|
||||
.unwrap_or(Err(RpcError::Timeout));
|
||||
let caps = match result {
|
||||
@@ -466,14 +432,6 @@ impl LspManager {
|
||||
if let Err(e) = peer.notify("initialized", json!({})) {
|
||||
tracing::warn!("{}: {e}", server.name);
|
||||
}
|
||||
// Servers that don't ask with `workspace/configuration` only learn settings this way.
|
||||
let cfg = server.effective_config();
|
||||
if cfg.settings.is_some()
|
||||
&& let Err(e) =
|
||||
peer.notify("workspace/didChangeConfiguration", json!({ "settings": handler::all_settings(&cfg) }))
|
||||
{
|
||||
tracing::debug!("{}: didChangeConfiguration: {e}", server.name);
|
||||
}
|
||||
let run = Running { generation, peer: peer.clone(), caps: Arc::new(RwLock::new(caps)) };
|
||||
|
||||
// Publish readiness and (re)open attached documents atomically w.r.t. did_change.
|
||||
@@ -795,7 +753,6 @@ impl LspManager {
|
||||
Ok(DocSnap {
|
||||
path: d.path.clone(),
|
||||
uri: d.uri.clone(),
|
||||
language: d.language.clone(),
|
||||
text: d.text.clone(),
|
||||
servers: d.servers.iter().map(|a| a.server.clone()).collect(),
|
||||
})
|
||||
@@ -852,7 +809,7 @@ impl LspManager {
|
||||
cancel: CancellationToken,
|
||||
) -> IdeResult<CompletionList> {
|
||||
let (snap, targets) = self.doc_targets(doc, "completion", |c| c.has("completionProvider")).await?;
|
||||
let requests = targets.iter().filter(|t| snap.asks(t, pos)).map(|t| {
|
||||
let requests = targets.iter().map(|t| {
|
||||
let context = match &trigger {
|
||||
Some(ch) if t.caps().completion_triggers().contains(ch) => {
|
||||
json!({ "triggerKind": 2, "triggerCharacter": ch })
|
||||
@@ -939,7 +896,7 @@ impl LspManager {
|
||||
pub async fn hover(&self, doc: DocId, pos: Pos, cancel: CancellationToken) -> IdeResult<Option<Hover>> {
|
||||
let (snap, targets) = self.doc_targets(doc, "hover", |c| c.has("hoverProvider")).await?;
|
||||
let mut out = Outcome::new();
|
||||
for t in targets.iter().filter(|t| snap.asks(t, pos)) {
|
||||
for t in &targets {
|
||||
let r: IdeResult<Option<lsp::Hover>> =
|
||||
self.call(t, "textDocument/hover", snap.pos_params(t, pos), Some(&cancel), DEFAULT_TIMEOUT).await;
|
||||
match r {
|
||||
@@ -960,7 +917,7 @@ impl LspManager {
|
||||
pub async fn signature_help(&self, doc: DocId, pos: Pos) -> IdeResult<Option<SignatureHelp>> {
|
||||
let (snap, targets) = self.doc_targets(doc, "signature help", |c| c.has("signatureHelpProvider")).await?;
|
||||
let mut out = Outcome::new();
|
||||
for t in targets.iter().filter(|t| snap.asks(t, pos)) {
|
||||
for t in &targets {
|
||||
let mut params = snap.pos_params(t, pos);
|
||||
params["context"] = json!({ "triggerKind": 1, "isRetrigger": false });
|
||||
match self
|
||||
@@ -1022,7 +979,7 @@ impl LspManager {
|
||||
cancel: Option<&CancellationToken>,
|
||||
) -> IdeResult<Vec<Location>> {
|
||||
let mut out = Outcome::new();
|
||||
for t in targets.iter().filter(|t| snap.asks(t, pos)) {
|
||||
for t in targets {
|
||||
match self
|
||||
.call::<_, Option<lsp::GotoDefinitionResponse>>(
|
||||
t,
|
||||
@@ -1064,9 +1021,6 @@ impl LspManager {
|
||||
let requests = targets.iter().map(|t| {
|
||||
let (snap, cancel) = (&snap, &cancel);
|
||||
async move {
|
||||
// The Angular server searches the file's own project only: more open
|
||||
// files don't widen it.
|
||||
let angular = t.server.name == angular::SERVER;
|
||||
let query = || async move {
|
||||
let mut params = snap.pos_params(t, pos);
|
||||
params["context"] = json!({ "includeDeclaration": include_declaration });
|
||||
@@ -1077,7 +1031,7 @@ impl LspManager {
|
||||
};
|
||||
let files =
|
||||
|v: &Vec<Location>| v.iter().filter(|l| l.uri.is_none()).map(|l| l.path.to_path_buf()).collect();
|
||||
let result = if project_wide && !angular {
|
||||
let result = if project_wide {
|
||||
self.widened(snap, t, pos, cancel, query, files).await
|
||||
} else {
|
||||
query().await.map(|first| {
|
||||
@@ -1088,25 +1042,12 @@ impl LspManager {
|
||||
(t, result)
|
||||
}
|
||||
});
|
||||
// The Angular server lists the declaration even when not asked to: the one
|
||||
// the definition at `pos` points to is taken out of its answer.
|
||||
let declarations = async {
|
||||
if include_declaration || !targets.iter().any(|t| t.server.name == angular::SERVER) {
|
||||
return Vec::new();
|
||||
}
|
||||
let defining = self.ready_targets(&snap.servers, |c| c.has("definitionProvider")).await;
|
||||
self.goto_in(&snap, &defining, "textDocument/definition", pos, Some(&cancel)).await.unwrap_or_default()
|
||||
};
|
||||
let (results, declarations) = futures::join!(join_all(requests), declarations);
|
||||
let mut out = Outcome::new();
|
||||
for (t, r) in results {
|
||||
for (t, r) in join_all(requests).await {
|
||||
match r {
|
||||
Ok(w) => {
|
||||
let acc = out.value.get_or_insert_with(References::default);
|
||||
let mut locs: Vec<Location> = w.first.into_iter().chain(w.second.into_iter().flatten()).collect();
|
||||
if t.server.name == angular::SERVER {
|
||||
locs.retain(|l| !declarations.contains(l));
|
||||
}
|
||||
let locs: Vec<Location> = w.first.into_iter().chain(w.second.into_iter().flatten()).collect();
|
||||
self.note_virtual(&t.server, locs.iter().map(|l| l.uri.as_deref()));
|
||||
acc.locations.extend(locs);
|
||||
acc.incomplete = acc.incomplete.or(w.incomplete);
|
||||
@@ -1327,19 +1268,7 @@ impl LspManager {
|
||||
|
||||
pub async fn prepare_rename(&self, doc: DocId, pos: Pos) -> IdeResult<Option<Range>> {
|
||||
let (snap, targets) = self.doc_targets(doc, "rename", |c| c.has("renameProvider")).await?;
|
||||
let mut out = Outcome::new();
|
||||
for t in &targets {
|
||||
match self.prepare_rename_on(&snap, t, pos).await {
|
||||
Ok(Some(range)) => return Ok(Some(range)),
|
||||
Ok(None) => out.value = Some(None),
|
||||
Err(e) => out.fail(e),
|
||||
}
|
||||
}
|
||||
out.finish(None)
|
||||
}
|
||||
|
||||
/// What `t` renames at `pos`; one without `prepareRename` renames the word there.
|
||||
async fn prepare_rename_on(&self, snap: &DocSnap, t: &Target, pos: Pos) -> IdeResult<Option<Range>> {
|
||||
let t = &targets[0];
|
||||
if !t.caps().has_sub("renameProvider", "prepareProvider") {
|
||||
return Ok(snap.text.word_range_at(pos));
|
||||
}
|
||||
@@ -1362,50 +1291,15 @@ impl LspManager {
|
||||
|
||||
/// Renames across the project: like [`Self::references`], files outside the
|
||||
/// server's analysis scope that mention the name are opened for the request.
|
||||
/// Every server that can rename there does: the Angular server adds the
|
||||
/// templates to vtsls's edit, whose own edits win where both change the same text.
|
||||
pub async fn rename(&self, doc: DocId, pos: Pos, new_name: String) -> IdeResult<WorkspaceEdit> {
|
||||
let (snap, targets) = self.doc_targets(doc, "rename", |c| c.has("renameProvider")).await?;
|
||||
let renaming = self.rename_targets(&snap, &targets, pos).await;
|
||||
let edits = join_all(renaming.into_iter().map(|t| self.rename_on(&snap, t, pos, &new_name))).await;
|
||||
let mut out = Outcome::new();
|
||||
for edit in edits {
|
||||
match edit {
|
||||
Ok(edit) => match &mut out.value {
|
||||
Some(merged) => convert::merge_workspace_edit(merged, edit),
|
||||
None => out.value = Some(edit),
|
||||
},
|
||||
Err(e) => out.fail(e),
|
||||
}
|
||||
}
|
||||
out.finish(WorkspaceEdit::default())
|
||||
}
|
||||
|
||||
/// The servers that can rename at `pos`, the first one when none can (a
|
||||
/// single one is asked without `prepareRename`).
|
||||
async fn rename_targets<'t>(&self, snap: &DocSnap, targets: &'t [Target], pos: Pos) -> Vec<&'t Target> {
|
||||
if targets.len() > 1 {
|
||||
let prepared = join_all(targets.iter().map(|t| self.prepare_rename_on(snap, t, pos))).await;
|
||||
let able: Vec<&Target> =
|
||||
targets.iter().zip(prepared).filter(|(_, r)| matches!(r, Ok(Some(_)))).map(|(t, _)| t).collect();
|
||||
if !able.is_empty() {
|
||||
return able;
|
||||
}
|
||||
}
|
||||
vec![&targets[0]]
|
||||
}
|
||||
|
||||
async fn rename_on(&self, snap: &DocSnap, t: &Target, pos: Pos, new_name: &str) -> IdeResult<WorkspaceEdit> {
|
||||
let t = &targets[0];
|
||||
let query = || async {
|
||||
let mut params = snap.pos_params(t, pos);
|
||||
params["newName"] = json!(new_name);
|
||||
let r: Option<lsp::WorkspaceEdit> = self.call(t, "textDocument/rename", params, None, LONG_TIMEOUT).await?;
|
||||
Ok(r.map(|e| convert::workspace_edit(&self.conv(t.enc()), e)).unwrap_or_default())
|
||||
};
|
||||
// The Angular server renames in the file's own project only, whatever is open.
|
||||
if t.server.name == angular::SERVER {
|
||||
return query().await;
|
||||
}
|
||||
let files = |e: &WorkspaceEdit| {
|
||||
e.files
|
||||
.iter()
|
||||
@@ -1415,7 +1309,7 @@ impl LspManager {
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let w = self.widened(snap, t, pos, &CancellationToken::new(), query, files).await?;
|
||||
let w = self.widened(&snap, t, pos, &CancellationToken::new(), query, files).await?;
|
||||
// The second edit covers the first: its files stay analysed.
|
||||
Ok(w.second.unwrap_or(w.first))
|
||||
}
|
||||
@@ -1566,8 +1460,7 @@ impl LspManager {
|
||||
|
||||
pub async fn inlay_hints(&self, doc: DocId, range: Range) -> IdeResult<Vec<InlayHint>> {
|
||||
let (snap, targets) = self.doc_targets(doc, "inlay hints", |c| c.has("inlayHintProvider")).await?;
|
||||
let angular = angular::serves_inlay_hints(snap.language.as_str(), snap.text.as_str());
|
||||
let requests = targets.iter().filter(|t| angular || t.server.name != angular::SERVER).map(|t| {
|
||||
let requests = targets.iter().map(|t| {
|
||||
let params = json!({ "textDocument": snap.ident(), "range": snap.range(t, range) });
|
||||
async move {
|
||||
(
|
||||
@@ -1885,11 +1778,6 @@ impl LspManager {
|
||||
*self.config_hook.write() = Some(Arc::from(hook));
|
||||
}
|
||||
|
||||
/// Installed by `src-tauri` to apply the servers enabled / defined in settings.
|
||||
pub fn set_servers_hook(&self, hook: Box<ServersFn>) {
|
||||
*self.servers_hook.write() = Some(Arc::from(hook));
|
||||
}
|
||||
|
||||
/// The server's base configuration with the settings hook applied.
|
||||
fn configured(&self, server: &Server) -> LanguageServerConfig {
|
||||
let mut cfg = server.config.clone();
|
||||
@@ -1901,26 +1789,11 @@ impl LspManager {
|
||||
|
||||
/// Restarts running servers whose settings-derived configuration changed
|
||||
/// (e.g. a new project interpreter); stopped ones pick it up on their next start.
|
||||
/// A change of `settings` alone reaches a running server without a restart.
|
||||
/// Servers no longer enabled stop; newly enabled ones attach to open documents.
|
||||
pub async fn reconfigure(&self) {
|
||||
self.stop_unlisted().await;
|
||||
let servers: Vec<Arc<Server>> = self.servers.lock().clone();
|
||||
for s in servers {
|
||||
let next = self.configured(&s);
|
||||
let current = s.effective_config();
|
||||
if next == current {
|
||||
continue;
|
||||
}
|
||||
let without_settings = |c: &LanguageServerConfig| LanguageServerConfig { settings: None, ..c.clone() };
|
||||
if let Some(run) = s.running()
|
||||
&& without_settings(&next) == without_settings(¤t)
|
||||
{
|
||||
s.set_effective_config(next);
|
||||
let params = json!({ "settings": handler::all_settings(&s.effective_config()) });
|
||||
if let Err(e) = run.peer.notify("workspace/didChangeConfiguration", params) {
|
||||
tracing::debug!("{}: didChangeConfiguration: {e}", s.name);
|
||||
}
|
||||
if next == s.effective_config() {
|
||||
continue;
|
||||
}
|
||||
match s.status() {
|
||||
@@ -1942,128 +1815,12 @@ impl LspManager {
|
||||
ide_core::event::ServerStatus::Stopped => {}
|
||||
}
|
||||
}
|
||||
self.attach_fallbacks();
|
||||
self.detach_shadowed_fallbacks().await;
|
||||
}
|
||||
|
||||
/// A server enabled again shadows the fallbacks attached in its place: they
|
||||
/// leave the open documents, and stop once no document uses them.
|
||||
async fn detach_shadowed_fallbacks(&self) {
|
||||
let open: Vec<(DocId, LanguageId, PathBuf)> =
|
||||
self.docs.lock().iter().map(|(id, d)| (*id, d.language.clone(), d.path.clone())).collect();
|
||||
let mut shadowed: Vec<(DocId, Vec<ide_core::ServerId>)> = Vec::new();
|
||||
for (id, language, path) in open {
|
||||
let configs = self.language_servers(&language);
|
||||
let wanted = self.servers_for(&language, &path);
|
||||
let docs = self.docs.lock();
|
||||
let Some(d) = docs.get(&id) else { continue };
|
||||
let gone: Vec<ide_core::ServerId> = d
|
||||
.servers
|
||||
.iter()
|
||||
.filter(|a| {
|
||||
!wanted.iter().any(|w| w.id == a.server.id)
|
||||
&& configs.iter().any(|c| c.fallback && c.name == a.server.name)
|
||||
})
|
||||
.map(|a| a.server.id)
|
||||
.collect();
|
||||
if !gone.is_empty() {
|
||||
shadowed.push((id, gone));
|
||||
}
|
||||
}
|
||||
if shadowed.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut detached: Vec<Arc<Server>> = Vec::new();
|
||||
{
|
||||
let mut docs = self.docs.lock();
|
||||
for (id, gone) in shadowed {
|
||||
let Some(d) = docs.get_mut(&id) else { continue };
|
||||
let (leaving, staying): (Vec<Attached>, Vec<Attached>) =
|
||||
d.servers.drain(..).partition(|a| gone.contains(&a.server.id));
|
||||
d.servers = staying;
|
||||
for a in leaving {
|
||||
if let Some(run) = a.server.running()
|
||||
&& a.opened_gen == Some(run.generation)
|
||||
&& run.caps.read().open_close
|
||||
&& let Err(e) =
|
||||
run.peer.notify("textDocument/didClose", json!({ "textDocument": { "uri": d.uri } }))
|
||||
{
|
||||
tracing::debug!("{}: didClose: {e}", a.server.name);
|
||||
}
|
||||
self.sink.emit(ide_core::IdeEvent::Diagnostics {
|
||||
path: d.path.clone().into(),
|
||||
source: a.server.name.clone(),
|
||||
items: Vec::new(),
|
||||
});
|
||||
if !detached.iter().any(|s| s.id == a.server.id) {
|
||||
detached.push(a.server);
|
||||
}
|
||||
}
|
||||
}
|
||||
let in_use = |s: &Arc<Server>| docs.values().any(|d| d.servers.iter().any(|a| a.server.id == s.id));
|
||||
detached.retain(|s| !in_use(s));
|
||||
}
|
||||
if detached.is_empty() {
|
||||
return;
|
||||
}
|
||||
for s in &detached {
|
||||
tracing::info!("{}: shadowed by an enabled server, stopping", s.name);
|
||||
self.stop_instance(s, true).await;
|
||||
}
|
||||
self.forget(&detached);
|
||||
}
|
||||
|
||||
/// Stops and forgets the servers that none of their languages uses any more.
|
||||
async fn stop_unlisted(&self) {
|
||||
let servers: Vec<Arc<Server>> = self.servers.lock().clone();
|
||||
let unlisted: Vec<Arc<Server>> = servers
|
||||
.into_iter()
|
||||
.filter(|s| !s.languages().iter().any(|l| self.language_servers(l).iter().any(|c| c.name == s.name)))
|
||||
.collect();
|
||||
if unlisted.is_empty() {
|
||||
return;
|
||||
}
|
||||
for s in &unlisted {
|
||||
tracing::info!("{}: no longer enabled, stopping", s.name);
|
||||
self.stop_instance(s, true).await;
|
||||
}
|
||||
let gone = |s: &Arc<Server>| unlisted.iter().any(|u| u.id == s.id);
|
||||
for d in self.docs.lock().values_mut() {
|
||||
d.servers.retain(|a| !gone(&a.server));
|
||||
}
|
||||
self.forget(&unlisted);
|
||||
}
|
||||
|
||||
/// Drops stopped servers from the list and tells the UI they are gone.
|
||||
fn forget(&self, gone: &[Arc<Server>]) {
|
||||
self.servers.lock().retain(|s| !gone.iter().any(|g| g.id == s.id));
|
||||
for s in gone {
|
||||
self.sink.emit(ide_core::IdeEvent::LanguageServerRemoved { server: s.id });
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_apply_edit_hook(&self, hook: Box<dyn Fn(WorkspaceEdit) -> bool + Send + Sync>) {
|
||||
*self.apply_edit_hook.write() = Some(Arc::from(hook));
|
||||
}
|
||||
|
||||
/// Emits every server's current diagnostics again: a UI that (re)loaded
|
||||
/// after they were published has missed those events.
|
||||
pub fn resend_diagnostics(&self) {
|
||||
let servers: Vec<Arc<Server>> = self.servers.lock().clone();
|
||||
for server in servers {
|
||||
let encoding = server.running().map(|r| r.caps.read().encoding).unwrap_or_default();
|
||||
let conv = self.conv(encoding);
|
||||
for (path, items) in server.diagnostics_by_path() {
|
||||
let items = items.into_iter().map(|d| convert::diagnostic(&conv, &path, d, &server.name)).collect();
|
||||
self.sink.emit(ide_core::IdeEvent::Diagnostics {
|
||||
path: path.into(),
|
||||
source: server.name.clone(),
|
||||
items,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn servers(&self) -> Vec<ServerInfo> {
|
||||
self.servers
|
||||
.lock()
|
||||
|
||||
@@ -461,11 +461,6 @@ impl Server {
|
||||
d.iter().flat_map(|(p, items)| items.iter().map(move |i| (p.clone(), i.clone()))).collect()
|
||||
}
|
||||
|
||||
/// The current diagnostics of each file that has some.
|
||||
pub fn diagnostics_by_path(&self) -> Vec<(PathBuf, Vec<lsp::Diagnostic>)> {
|
||||
self.diagnostics.lock().iter().map(|(p, d)| (p.clone(), d.clone())).collect()
|
||||
}
|
||||
|
||||
pub fn take_diagnostic_paths(&self) -> Vec<PathBuf> {
|
||||
self.published.lock().clear();
|
||||
self.diagnostics.lock().drain().map(|(p, _)| p).collect()
|
||||
|
||||
@@ -94,7 +94,7 @@ pub(crate) fn connect_or_start(
|
||||
let args = substitute_args(&config.args, port, root);
|
||||
|
||||
let mut cmd = tokio::process::Command::new(binary);
|
||||
ide_core::process::prepare(cmd.as_std_mut());
|
||||
ide_core::process::no_window(cmd.as_std_mut());
|
||||
cmd.args(&args)
|
||||
.current_dir(root)
|
||||
.envs(env.iter().map(|(k, v)| (k.as_str(), v.as_str())))
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Protocol tests against in-memory mock language servers.
|
||||
|
||||
use ide_core::event::ServerStatus;
|
||||
use ide_core::{DocId, FileEdit, IdeEvent, LanguageId, Pos, Range, ServerId, Severity, WorkspaceEdit};
|
||||
use ide_core::{DocId, FileEdit, IdeEvent, LanguageId, Pos, Range, Severity, WorkspaceEdit};
|
||||
use ide_jsonrpc::{Handler, NoopHandler, Peer};
|
||||
use ide_language::{LanguageConfig, LanguageRegistry, LanguageServerConfig};
|
||||
use ide_lsp::types::*;
|
||||
@@ -9,7 +9,7 @@ use ide_lsp::{LaunchError, Launcher, LspManager};
|
||||
use ide_text::AppliedChange;
|
||||
use parking_lot::Mutex;
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
@@ -202,13 +202,10 @@ fn server_cfg(name: &str) -> LanguageServerConfig {
|
||||
args: vec![],
|
||||
env: Default::default(),
|
||||
root_markers: vec!["mock.toml".into()],
|
||||
require_root_marker: false,
|
||||
initialization_options: Some(toml::Value::Table(toml::toml! { flag = true nested = { deep = 1 } })),
|
||||
settings: None,
|
||||
install_hint: Some(format!("install {name}")),
|
||||
connect: None,
|
||||
fallback: false,
|
||||
max_java: None,
|
||||
launch_error: None,
|
||||
}
|
||||
}
|
||||
@@ -223,16 +220,6 @@ fn harness_with_fallbacks(servers: &[(&str, Value)], fallbacks: &[&str]) -> Harn
|
||||
}
|
||||
|
||||
fn harness_for(lang_id: &str, ext: &str, servers: &[(&str, Value)], fallbacks: &[&str]) -> Harness {
|
||||
harness_configured(lang_id, ext, servers, |cfg| cfg.fallback = fallbacks.contains(&cfg.name.as_str()))
|
||||
}
|
||||
|
||||
/// `adjust` changes each server's configuration.
|
||||
fn harness_configured(
|
||||
lang_id: &str,
|
||||
ext: &str,
|
||||
servers: &[(&str, Value)],
|
||||
adjust: impl Fn(&mut LanguageServerConfig),
|
||||
) -> Harness {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path().to_path_buf();
|
||||
let lang = LanguageConfig {
|
||||
@@ -248,11 +235,7 @@ fn harness_configured(
|
||||
tree_sitter: None,
|
||||
language_servers: servers
|
||||
.iter()
|
||||
.map(|(n, _)| {
|
||||
let mut cfg = server_cfg(n);
|
||||
adjust(&mut cfg);
|
||||
cfg
|
||||
})
|
||||
.map(|(n, _)| LanguageServerConfig { fallback: fallbacks.contains(n), ..server_cfg(n) })
|
||||
.collect(),
|
||||
debugger: None,
|
||||
};
|
||||
@@ -290,22 +273,6 @@ impl Harness {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether every instance of `name` was reported as removed from the server list.
|
||||
fn removed(&self, name: &str) -> bool {
|
||||
let events = self.events.lock();
|
||||
let ids: HashSet<ServerId> = events
|
||||
.iter()
|
||||
.filter_map(|e| match e {
|
||||
IdeEvent::LanguageServer { server, name: n, .. } if n == name => Some(*server),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
!ids.is_empty()
|
||||
&& ids.iter().all(|id| {
|
||||
events.iter().any(|e| matches!(e, IdeEvent::LanguageServerRemoved { server } if server == id))
|
||||
})
|
||||
}
|
||||
|
||||
async fn wait_status(&self, name: &str, status: ServerStatus) {
|
||||
eventually(|| self.statuses(name).last() == Some(&status)).await;
|
||||
}
|
||||
@@ -554,15 +521,6 @@ async fn diagnostics_become_events_and_feed_code_actions() {
|
||||
assert_eq!(items[0].range, rng(0, 4, 0, 10));
|
||||
}
|
||||
|
||||
// A reloaded UI asks for them again.
|
||||
h.events.lock().clear();
|
||||
h.mgr.resend_diagnostics();
|
||||
let again = h.events.lock().iter().find_map(|e| match e {
|
||||
IdeEvent::Diagnostics { path, items, .. } => Some((path.clone(), items.len())),
|
||||
_ => None,
|
||||
});
|
||||
assert_eq!(again, Some((path.clone().into(), 2)));
|
||||
|
||||
s.respond(
|
||||
"textDocument/codeAction",
|
||||
json!([
|
||||
@@ -728,28 +686,6 @@ async fn progress_tasks_and_busy_status() {
|
||||
assert!(tasks[2].3);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn angular_project_loading_shows_as_progress() {
|
||||
let h = harness(&[("mock", incremental_caps())]);
|
||||
h.open("a.mk", "x");
|
||||
h.wait_status("mock", ServerStatus::Ready).await;
|
||||
let peer = h.launcher.state("mock").peer();
|
||||
peer.notify("angular/projectLoadingStart", Value::Null).unwrap();
|
||||
h.wait_status("mock", ServerStatus::Busy).await;
|
||||
peer.notify("angular/projectLoadingFinish", Value::Null).unwrap();
|
||||
h.wait_status("mock", ServerStatus::Ready).await;
|
||||
let tasks: Vec<(String, bool)> = h
|
||||
.events
|
||||
.lock()
|
||||
.iter()
|
||||
.filter_map(|e| match e {
|
||||
IdeEvent::Task { title, done, .. } => Some((title.clone(), *done)),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(tasks, [("Loading Angular project".into(), false), ("Loading Angular project".into(), true)]);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn crash_restarts_and_reopens_documents() {
|
||||
let h = harness(&[("mock", incremental_caps())]);
|
||||
@@ -859,56 +795,6 @@ async fn launch_error_fails_without_starting_the_server() {
|
||||
assert!(!h.statuses("mock").contains(&ServerStatus::Crashed));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn settings_changes_reach_servers_without_restarts() {
|
||||
let h = harness(&[("mock", incremental_caps()), ("extra", incremental_caps())]);
|
||||
let settings: Arc<Mutex<Option<Value>>> = Default::default();
|
||||
let disabled: Arc<Mutex<Vec<String>>> = Default::default();
|
||||
{
|
||||
let settings = settings.clone();
|
||||
h.mgr.set_config_hook(Box::new(move |cfg, _| cfg.settings = settings.lock().clone()));
|
||||
}
|
||||
{
|
||||
let disabled = disabled.clone();
|
||||
h.mgr.set_servers_hook(Box::new(move |_, defined| {
|
||||
defined.iter().filter(|c| !disabled.lock().contains(&c.name)).cloned().collect()
|
||||
}));
|
||||
}
|
||||
h.open("a.mk", "x");
|
||||
h.wait_status("mock", ServerStatus::Ready).await;
|
||||
h.wait_status("extra", ServerStatus::Ready).await;
|
||||
|
||||
// Only `settings` changed: pushed to the running server, which keeps running.
|
||||
let s = h.launcher.state("mock");
|
||||
*settings.lock() = Some(json!({ "nested": { "other": 2 } }));
|
||||
h.mgr.reconfigure().await;
|
||||
eventually(|| !s.notified("workspace/didChangeConfiguration").is_empty()).await;
|
||||
assert_eq!(
|
||||
s.notified("workspace/didChangeConfiguration")[0],
|
||||
json!({ "settings": { "flag": true, "nested": { "deep": 1, "other": 2 } } })
|
||||
);
|
||||
assert_eq!(s.launches.load(Ordering::SeqCst), 1);
|
||||
let cfg: Value = s
|
||||
.peer()
|
||||
.request("workspace/configuration", json!({ "items": [{ "section": "nested.other" }] }), None)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(cfg, json!([2]));
|
||||
|
||||
// Disabled: stopped and forgotten; enabled again: attached to the open document.
|
||||
disabled.lock().push("extra".into());
|
||||
h.mgr.reconfigure().await;
|
||||
assert_eq!(h.mgr.servers().iter().map(|s| s.name.as_str()).collect::<Vec<_>>(), ["mock"]);
|
||||
assert_eq!(h.statuses("extra").last(), Some(&ServerStatus::Stopped));
|
||||
assert!(h.removed("extra"));
|
||||
assert!(!h.removed("mock"));
|
||||
disabled.lock().clear();
|
||||
h.mgr.reconfigure().await;
|
||||
h.wait_status("extra", ServerStatus::Ready).await;
|
||||
eventually(|| h.launcher.state("extra").notified("textDocument/didOpen").len() == 2).await;
|
||||
assert_eq!(s.launches.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn fallback_servers_only_run_when_the_preferred_one_is_missing() {
|
||||
// Preferred installed: the alternative is never started.
|
||||
@@ -933,81 +819,6 @@ async fn fallback_servers_only_run_when_the_preferred_one_is_missing() {
|
||||
assert!(h.mgr.hover(doc, Pos::new(0, 0), Default::default()).await.is_ok());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_server_requiring_a_root_marker_serves_only_files_below_one() {
|
||||
// `framework` next to `main` (one instance for the whole project), like the
|
||||
// Angular server next to vtsls.
|
||||
let servers = [("main", incremental_caps()), ("framework", incremental_caps())];
|
||||
let h = harness_configured("mock", "mk", &servers, |cfg| match cfg.name.as_str() {
|
||||
"framework" => cfg.require_root_marker = true,
|
||||
_ => cfg.root_markers.clear(),
|
||||
});
|
||||
for dir in ["plain", "app"] {
|
||||
std::fs::create_dir_all(h.root.join(dir)).unwrap();
|
||||
}
|
||||
std::fs::write(h.root.join("app/mock.toml"), "").unwrap();
|
||||
let (_, plain) = h.open("plain/a.mk", "x");
|
||||
h.wait_status("main", ServerStatus::Ready).await;
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
assert!(h.statuses("framework").is_empty());
|
||||
|
||||
let (_, app) = h.open("app/b.mk", "y");
|
||||
h.wait_status("framework", ServerStatus::Ready).await;
|
||||
let framework = h.launcher.state("framework");
|
||||
eventually(|| framework.docs.lock().contains_key(&uri_of(&app))).await;
|
||||
assert!(!framework.docs.lock().contains_key(&uri_of(&plain)));
|
||||
eventually(|| h.launcher.state("main").docs.lock().len() == 2).await;
|
||||
|
||||
// It stands in for no other server: with `ghost` missing, its fallback serves too.
|
||||
let servers = [("ghost", json!({})), ("framework", incremental_caps()), ("alt", incremental_caps())];
|
||||
let h = harness_configured("mock", "mk", &servers, |cfg| match cfg.name.as_str() {
|
||||
"framework" => cfg.require_root_marker = true,
|
||||
"alt" => cfg.fallback = true,
|
||||
_ => {}
|
||||
});
|
||||
h.launcher.state("ghost").missing.store(true, Ordering::SeqCst);
|
||||
std::fs::write(h.root.join("mock.toml"), "").unwrap();
|
||||
h.open("a.mk", "x");
|
||||
h.wait_status("framework", ServerStatus::Ready).await;
|
||||
h.wait_status("alt", ServerStatus::Ready).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_fallback_leaves_when_the_preferred_server_is_enabled_again() {
|
||||
let h = harness_with_fallbacks(&[("main", incremental_caps()), ("alt", incremental_caps())], &["alt"]);
|
||||
let disabled: Arc<Mutex<Vec<String>>> = Default::default();
|
||||
{
|
||||
let disabled = disabled.clone();
|
||||
h.mgr.set_servers_hook(Box::new(move |_, defined| {
|
||||
defined.iter().filter(|c| !disabled.lock().contains(&c.name)).cloned().collect()
|
||||
}));
|
||||
}
|
||||
let (doc, path) = h.open("a.mk", "x");
|
||||
let uri = uri_of(&path);
|
||||
h.wait_status("main", ServerStatus::Ready).await;
|
||||
assert!(h.statuses("alt").is_empty());
|
||||
|
||||
// Preferred disabled: the fallback takes over the open document.
|
||||
disabled.lock().push("main".into());
|
||||
h.mgr.reconfigure().await;
|
||||
h.wait_status("alt", ServerStatus::Ready).await;
|
||||
eventually(|| h.launcher.state("alt").docs.lock().contains_key(&uri)).await;
|
||||
assert_eq!(h.mgr.servers().iter().map(|s| s.name.as_str()).collect::<Vec<_>>(), ["alt"]);
|
||||
assert!(h.removed("main"));
|
||||
|
||||
// Enabled again: the fallback closes the document and stops.
|
||||
disabled.lock().clear();
|
||||
h.mgr.reconfigure().await;
|
||||
h.wait_status("main", ServerStatus::Ready).await;
|
||||
eventually(|| h.launcher.state("main").docs.lock().contains_key(&uri)).await;
|
||||
assert!(!h.launcher.state("alt").notified("textDocument/didClose").is_empty());
|
||||
assert_eq!(h.statuses("alt").last(), Some(&ServerStatus::Stopped));
|
||||
assert!(h.removed("alt"));
|
||||
assert_eq!(h.mgr.servers().iter().map(|s| s.name.as_str()).collect::<Vec<_>>(), ["main"]);
|
||||
assert!(h.mgr.hover(doc, Pos::new(0, 0), Default::default()).await.is_ok());
|
||||
assert_eq!(h.launcher.state("alt").requested("textDocument/hover").len(), 0);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn implementations_per_position() {
|
||||
let caps = json!({ "textDocumentSync": 1, "implementationProvider": true });
|
||||
@@ -1120,128 +931,6 @@ async fn navigation_rename_format_and_decorations() {
|
||||
assert_eq!(h.mgr.document_symbols(doc).await.unwrap(), None);
|
||||
}
|
||||
|
||||
/// The edits of `edit` in `path`, by range.
|
||||
fn edits_in(edit: &WorkspaceEdit, path: &Path) -> Vec<(Range, String)> {
|
||||
edit.files
|
||||
.iter()
|
||||
.filter_map(|f| match f {
|
||||
FileEdit::Edit { path: p, edits } if p.to_path_buf() == path => {
|
||||
Some(edits.iter().map(|e| (e.range, e.new_text.clone())))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.flatten()
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn rename_merges_the_servers_that_can_rename_there() {
|
||||
// `ts` can't rename inside a template string (its `prepareRename` is null), `ng` can.
|
||||
let h = harness(&[("ts", incremental_caps()), ("ng", incremental_caps())]);
|
||||
let (doc, path) = h.open("a.mk", "template: `{{ title }}`\ntitle = 1\n");
|
||||
h.wait_status("ts", ServerStatus::Ready).await;
|
||||
h.wait_status("ng", ServerStatus::Ready).await;
|
||||
let html = h.root.join("a.html");
|
||||
let (uri, html_uri) = (uri_of(&path), uri_of(&html));
|
||||
let r = |l: u32, c0: u32, c1: u32| json!({"start":{"line":l,"character":c0},"end":{"line":l,"character":c1}});
|
||||
let ng = h.launcher.state("ng");
|
||||
ng.respond("textDocument/prepareRename", json!({ "range": r(0, 14, 19), "placeholder": "title" }));
|
||||
ng.respond(
|
||||
"textDocument/rename",
|
||||
json!({ "changes": {
|
||||
uri.clone(): [{ "range": r(0, 14, 19), "newText": "heading" }, { "range": r(1, 0, 5), "newText": "heading" }],
|
||||
html_uri: [{ "range": r(0, 3, 8), "newText": "heading" }],
|
||||
} }),
|
||||
);
|
||||
|
||||
assert_eq!(h.mgr.prepare_rename(doc, Pos::new(0, 15)).await.unwrap(), Some(rng(0, 14, 0, 19)));
|
||||
let edit = h.mgr.rename(doc, Pos::new(0, 15), "heading".into()).await.unwrap();
|
||||
assert_eq!(edits_in(&edit, &path).len(), 2);
|
||||
assert!(h.launcher.state("ts").requested("textDocument/rename").is_empty());
|
||||
|
||||
// Both can rename the declaration: `ng` adds what `ts` doesn't see, and
|
||||
// `ts`'s own edits win where both change the same text.
|
||||
let ts = h.launcher.state("ts");
|
||||
ts.respond("textDocument/prepareRename", json!({ "range": r(1, 0, 5), "placeholder": "title" }));
|
||||
ts.respond(
|
||||
"textDocument/rename",
|
||||
json!({ "changes": { uri: [{ "range": r(1, 0, 5), "newText": "heading: x" }] } }),
|
||||
);
|
||||
let edit = h.mgr.rename(doc, Pos::new(1, 2), "heading".into()).await.unwrap();
|
||||
assert_eq!(edits_in(&edit, &path), [(rng(0, 14, 0, 19), "heading".into()), (rng(1, 0, 1, 5), "heading: x".into())]);
|
||||
assert_eq!(edits_in(&edit, &html), [(rng(0, 3, 0, 8), "heading".into())]);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn angular_server_is_asked_about_typescript_only_in_component_templates() {
|
||||
let servers = [("vtsls", incremental_caps()), ("angular-language-server", incremental_caps())];
|
||||
let h = harness_for("typescript", "ts", &servers, &[]);
|
||||
let (doc, _) = h.open("a.ts", "@Component({ template: '<p>{{ title }}</p>' })\nclass A { title = 1; }\n");
|
||||
h.wait_status("vtsls", ServerStatus::Ready).await;
|
||||
h.wait_status("angular-language-server", ServerStatus::Ready).await;
|
||||
let ng = h.launcher.state("angular-language-server");
|
||||
let asked = |method: &str| ng.requested(method).len();
|
||||
let mgr = &h.mgr;
|
||||
let ask = |pos: Pos| async move {
|
||||
mgr.completion(doc, pos, None, Default::default()).await.unwrap();
|
||||
mgr.hover(doc, pos, Default::default()).await.unwrap();
|
||||
mgr.goto(doc, pos, GotoKind::Definition).await.unwrap();
|
||||
};
|
||||
|
||||
// In the class: vtsls alone, though it has no answer.
|
||||
ask(Pos::new(1, 12)).await;
|
||||
assert_eq!(
|
||||
(asked("textDocument/completion"), asked("textDocument/hover"), asked("textDocument/definition")),
|
||||
(0, 0, 0)
|
||||
);
|
||||
// In the template: the Angular server too.
|
||||
ask(Pos::new(0, 31)).await;
|
||||
assert_eq!(
|
||||
(asked("textDocument/completion"), asked("textDocument/hover"), asked("textDocument/definition")),
|
||||
(1, 1, 1)
|
||||
);
|
||||
|
||||
// Inlay hints only where Angular is imported.
|
||||
let lines = rng(0, 0, 2, 0);
|
||||
h.mgr.inlay_hints(doc, lines).await.unwrap();
|
||||
assert_eq!(asked("textDocument/inlayHint"), 0);
|
||||
let (doc, _) = h.open("b.ts", "import { Component } from '@angular/core';\n");
|
||||
h.mgr.inlay_hints(doc, lines).await.unwrap();
|
||||
assert_eq!(asked("textDocument/inlayHint"), 1);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn angular_references_leave_out_the_declaration_unless_asked() {
|
||||
let servers = [("vtsls", incremental_caps()), ("angular-language-server", incremental_caps())];
|
||||
let h = harness_for("typescript", "ts", &servers, &[]);
|
||||
let (doc, path) = h.open("a.ts", "class A { title = 1; }\n");
|
||||
h.wait_status("vtsls", ServerStatus::Ready).await;
|
||||
h.wait_status("angular-language-server", ServerStatus::Ready).await;
|
||||
let html = h.root.join("a.html");
|
||||
let declaration =
|
||||
json!({ "uri": uri_of(&path), "range": {"start":{"line":0,"character":10},"end":{"line":0,"character":15}} });
|
||||
let usage =
|
||||
json!({ "uri": uri_of(&html), "range": {"start":{"line":0,"character":3},"end":{"line":0,"character":8}} });
|
||||
// Like ngserver, it lists the declaration whatever `includeDeclaration` says;
|
||||
// vtsls knows where it is.
|
||||
let ng = h.launcher.state("angular-language-server");
|
||||
ng.respond("textDocument/references", json!([declaration, usage]));
|
||||
let vtsls = h.launcher.state("vtsls");
|
||||
vtsls.respond("textDocument/definition", json!([declaration]));
|
||||
|
||||
let mgr = &h.mgr;
|
||||
let found = |include_declaration: bool| async move {
|
||||
let refs = mgr.references(doc, Pos::new(0, 11), include_declaration, false, Default::default()).await;
|
||||
let mut v: Vec<(PathBuf, Range)> =
|
||||
refs.unwrap().locations.iter().map(|l| (l.path.to_path_buf(), l.range)).collect();
|
||||
v.sort();
|
||||
v
|
||||
};
|
||||
assert_eq!(found(false).await, [(html.clone(), rng(0, 3, 0, 8))]);
|
||||
assert_eq!(found(true).await, [(html, rng(0, 3, 0, 8)), (path, rng(0, 10, 0, 15))]);
|
||||
assert_eq!(vtsls.requested("textDocument/definition").len(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn utf8_server_positions_are_converted() {
|
||||
let h = harness(&[(
|
||||
|
||||
@@ -69,13 +69,10 @@ async fn missing_binary_is_reported_with_install_hint() {
|
||||
args: vec![],
|
||||
env: Default::default(),
|
||||
root_markers: vec![],
|
||||
require_root_marker: false,
|
||||
initialization_options: None,
|
||||
settings: None,
|
||||
install_hint: Some("npm i -g nope-ls".into()),
|
||||
connect: None,
|
||||
fallback: false,
|
||||
max_java: None,
|
||||
launch_error: None,
|
||||
};
|
||||
let (mgr, events) = manager(dir.path(), LanguageRegistry::from_configs(vec![lang("nope", "nope", server)]));
|
||||
@@ -106,44 +103,6 @@ fn main() {
|
||||
}
|
||||
";
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore = "requires ty on PATH"]
|
||||
async fn ty_python_end_to_end() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path().canonicalize().unwrap();
|
||||
let path = root.join("example.py");
|
||||
let source = "def greet(name: str) -> str:\n return name\n\nresult = greet('Ada')\nbad: int = 'wrong'\n";
|
||||
std::fs::write(&path, source).unwrap();
|
||||
let mut python = LanguageRegistry::load(None).unwrap().get(&LanguageId::new("python")).unwrap();
|
||||
python.language_servers.retain(|server| server.name == "ty");
|
||||
assert_eq!(python.language_servers.len(), 1);
|
||||
let (mgr, events) = manager(&root, LanguageRegistry::from_configs(vec![python]));
|
||||
let doc = DocId::next();
|
||||
mgr.did_open(doc, &path, &LanguageId::new("python"), 1, source);
|
||||
retry("ty ready", Duration::from_secs(30), || {
|
||||
let status = last_status(&events, "ty");
|
||||
if let Some((ServerStatus::Crashed | ServerStatus::Missing | ServerStatus::Misconfigured, msg)) = &status {
|
||||
panic!("ty failed: {msg:?}");
|
||||
}
|
||||
async move { matches!(status, Some((ServerStatus::Ready | ServerStatus::Busy, _))).then_some(()) }
|
||||
})
|
||||
.await;
|
||||
let defs = retry("ty definition", Duration::from_secs(30), || {
|
||||
let mgr = mgr.clone();
|
||||
async move { mgr.goto(doc, Pos::new(3, 10), GotoKind::Definition).await.ok().filter(|d| !d.is_empty()) }
|
||||
})
|
||||
.await;
|
||||
assert_eq!(defs[0].path, path);
|
||||
assert_eq!(defs[0].range.start.line, 0);
|
||||
retry("ty diagnostics", Duration::from_secs(30), || {
|
||||
let found = events.lock().iter().any(
|
||||
|event| matches!(event, IdeEvent::Diagnostics { source, items, .. } if source == "ty" && !items.is_empty()),
|
||||
);
|
||||
async move { found.then_some(()) }
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore = "requires rust-analyzer"]
|
||||
async fn rust_analyzer_end_to_end() {
|
||||
@@ -238,13 +197,10 @@ async fn typescript_language_server_end_to_end() {
|
||||
args: vec!["--stdio".into()],
|
||||
env: Default::default(),
|
||||
root_markers: vec!["tsconfig.json".into()],
|
||||
require_root_marker: false,
|
||||
initialization_options: None,
|
||||
settings: None,
|
||||
install_hint: None,
|
||||
connect: None,
|
||||
fallback: false,
|
||||
max_java: None,
|
||||
launch_error: None,
|
||||
};
|
||||
let (mgr, events) = manager(&root, LanguageRegistry::from_configs(vec![lang("typescript", "ts", server)]));
|
||||
@@ -283,13 +239,10 @@ fn npm_server(tools: &Path, name: &str, bin: &str, init: Option<serde_json::Valu
|
||||
args: vec!["--stdio".into()],
|
||||
env: Default::default(),
|
||||
root_markers: vec!["package.json".into()],
|
||||
require_root_marker: false,
|
||||
initialization_options: init.map(|v| toml::Value::try_from(v).unwrap()),
|
||||
settings: None,
|
||||
install_hint: None,
|
||||
connect: None,
|
||||
fallback: false,
|
||||
max_java: None,
|
||||
launch_error: None,
|
||||
}
|
||||
}
|
||||
@@ -349,114 +302,3 @@ async fn vue_hybrid_mode_end_to_end() {
|
||||
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
const NG_APP_TS: &str = "import { Component } from '@angular/core';\n\n@Component({\n selector: 'app-root',\n templateUrl: './app.html',\n})\nexport class App {\n title = 'demo';\n}\n";
|
||||
const NG_APP_HTML: &str = "<h1>{{ title }}</h1>\n<p>{{ missing }}</p>\n";
|
||||
const NG_INLINE_TS: &str = "import { Component } from '@angular/core';\n\n@Component({\n selector: 'app-inline',\n template: `<b>{{ count }}</b>`,\n})\nexport class Inline {\n count = 1;\n}\n";
|
||||
|
||||
/// The lines `edit` changes in `path`, in order.
|
||||
fn edited_lines(edit: &ide_core::WorkspaceEdit, path: &Path) -> Vec<u32> {
|
||||
let mut lines: Vec<u32> = edit
|
||||
.files
|
||||
.iter()
|
||||
.filter_map(|f| match f {
|
||||
ide_core::FileEdit::Edit { path: p, edits } if p.to_path_buf() == path => {
|
||||
Some(edits.iter().map(|e| e.range.start.line))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.flatten()
|
||||
.collect();
|
||||
lines.sort();
|
||||
lines
|
||||
}
|
||||
|
||||
/// The Angular Language Server next to vtsls, in an external and an inline
|
||||
/// template. Set `OPENIDEA_TEST_NPM_TOOLS` to a dir with `npm i
|
||||
/// @angular/language-server @vtsls/language-server @angular/core @angular/common
|
||||
/// @angular/compiler rxjs`; the project is created inside it, so that it
|
||||
/// resolves `@angular/core`.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore = "requires @angular/language-server, @vtsls/language-server and @angular/core (OPENIDEA_TEST_NPM_TOOLS)"]
|
||||
async fn angular_language_server_end_to_end() {
|
||||
let tools = std::path::PathBuf::from(std::env::var("OPENIDEA_TEST_NPM_TOOLS").expect("OPENIDEA_TEST_NPM_TOOLS"));
|
||||
let dir = tempfile::tempdir_in(&tools).unwrap();
|
||||
let root = dir.path().canonicalize().unwrap();
|
||||
std::fs::write(root.join("angular.json"), "{\"version\":1,\"projects\":{}}").unwrap();
|
||||
std::fs::write(
|
||||
root.join("tsconfig.json"),
|
||||
"{\"compilerOptions\":{\"strict\":true},\"angularCompilerOptions\":{\"strictTemplates\":true},\"include\":[\"src/**/*.ts\"]}",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::create_dir_all(root.join("src/app")).unwrap();
|
||||
let app_ts = root.join("src/app/app.ts");
|
||||
let app_html = root.join("src/app/app.html");
|
||||
let inline_ts = root.join("src/app/inline.ts");
|
||||
for (path, text) in [(&app_ts, NG_APP_TS), (&app_html, NG_APP_HTML), (&inline_ts, NG_INLINE_TS)] {
|
||||
std::fs::write(path, text).unwrap();
|
||||
}
|
||||
|
||||
// The built-in definitions, with vtsls and the Angular server, and the probe
|
||||
// locations the settings hook adds.
|
||||
let builtin = LanguageRegistry::load(None).unwrap();
|
||||
let probes = tools.join("node_modules/@angular/language-server").to_string_lossy().into_owned();
|
||||
let languages = ["typescript", "html"].map(|id| {
|
||||
let mut cfg = builtin.get(&LanguageId::new(id)).unwrap();
|
||||
cfg.language_servers.retain(|s| s.name == "angular-language-server" || s.name == "vtsls");
|
||||
for server in &mut cfg.language_servers {
|
||||
let bin = if server.name == "vtsls" { "vtsls" } else { "ngserver" };
|
||||
server.command = tools.join("node_modules/.bin").join(bin).to_string_lossy().into_owned();
|
||||
}
|
||||
let server = cfg.language_servers.iter_mut().find(|s| s.name == "angular-language-server").unwrap();
|
||||
server.args.extend(["--ngProbeLocations".into(), probes.clone(), "--tsProbeLocations".into(), probes.clone()]);
|
||||
cfg
|
||||
});
|
||||
let (mgr, events) = manager(&root, LanguageRegistry::from_configs(languages.to_vec()));
|
||||
let (html, ts, inline) = (DocId::next(), DocId::next(), DocId::next());
|
||||
mgr.did_open(ts, &app_ts, &LanguageId::new("typescript"), 1, NG_APP_TS);
|
||||
mgr.did_open(html, &app_html, &LanguageId::new("html"), 1, NG_APP_HTML);
|
||||
mgr.did_open(inline, &inline_ts, &LanguageId::new("typescript"), 1, NG_INLINE_TS);
|
||||
|
||||
// `title` in `{{ title }}`.
|
||||
let hover = retry("hover", Duration::from_secs(90), || {
|
||||
let mgr = mgr.clone();
|
||||
async move { mgr.hover(html, Pos::new(0, 8), Default::default()).await.ok().flatten() }
|
||||
})
|
||||
.await;
|
||||
assert!(hover.contents.value.contains("title"), "{}", hover.contents.value);
|
||||
let defs = mgr.goto(html, Pos::new(0, 8), GotoKind::Definition).await.unwrap();
|
||||
assert_eq!(defs[0].path, app_ts);
|
||||
assert_eq!(defs[0].range.start.line, 7);
|
||||
|
||||
// `missing` is no member of `App`.
|
||||
retry("template diagnostics", Duration::from_secs(60), || {
|
||||
let found = events
|
||||
.lock()
|
||||
.iter()
|
||||
.any(|e| matches!(e, IdeEvent::Diagnostics { path, items, .. } if path == &app_html && !items.is_empty()));
|
||||
async move { found.then_some(()) }
|
||||
})
|
||||
.await;
|
||||
|
||||
// `count` in the inline template, which vtsls can't rename: renamed there
|
||||
// and in the class.
|
||||
let count = Pos::new(4, 20);
|
||||
let range = mgr.prepare_rename(inline, count).await.unwrap();
|
||||
assert_eq!(range, Some(Range::new(Pos::new(4, 19), Pos::new(4, 24))));
|
||||
let edit = mgr.rename(inline, count, "total".into()).await.unwrap();
|
||||
assert_eq!(edited_lines(&edit, &inline_ts), [4, 7], "{edit:?}");
|
||||
|
||||
// `title` in the class, which both servers rename: vtsls's edit and the
|
||||
// template's from the Angular server.
|
||||
let title = Pos::new(7, 3);
|
||||
let edit = mgr.rename(ts, title, "heading".into()).await.unwrap();
|
||||
assert_eq!((edited_lines(&edit, &app_ts), edited_lines(&edit, &app_html)), (vec![7], vec![0]), "{edit:?}");
|
||||
// Its usage in the template, the declaration left out, from either file.
|
||||
for (doc, pos) in [(ts, title), (html, Pos::new(0, 8))] {
|
||||
let refs = mgr.references(doc, pos, false, false, Default::default()).await.unwrap();
|
||||
let found: Vec<(std::path::PathBuf, u32)> =
|
||||
refs.locations.iter().map(|l| (l.path.to_path_buf(), l.range.start.line)).collect();
|
||||
assert_eq!(found, [(app_html.clone(), 0)]);
|
||||
}
|
||||
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
|
||||
}
|
||||
@@ -161,7 +161,7 @@ pub fn collect(spec: &ProfileSpec) -> IdeResult<Profile> {
|
||||
if !data.is_file() {
|
||||
return Err(nothing_recorded("perf wrote no data"));
|
||||
}
|
||||
let out = ide_core::process::prepare(&mut Command::new(perf))
|
||||
let out = ide_core::process::no_window(&mut Command::new(perf))
|
||||
.args(["script", "-i"])
|
||||
.arg(data.as_ref() as &Path)
|
||||
.current_dir(cwd)
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//! Run configuration detection from build files at the project root, or from the
|
||||
//! builds nested in a folder that holds several repositories.
|
||||
//! Run configuration detection from build files found at the project root.
|
||||
//!
|
||||
//! Detection never fails: unreadable or malformed files simply contribute nothing.
|
||||
|
||||
@@ -462,89 +461,22 @@ fn applies_application_plugin(text: &str) -> bool {
|
||||
})
|
||||
}
|
||||
|
||||
/// How deep a build is looked for when the project root has none (a folder holding
|
||||
/// several repositories: `backend/pom.xml`, `apps/server/settings.gradle`).
|
||||
const NESTED_BUILD_DEPTH: usize = 3;
|
||||
|
||||
/// The builds marked by any of `markers`: the root itself, else the shallowest marked
|
||||
/// folder of each branch, up to [`NESTED_BUILD_DEPTH`] levels down.
|
||||
fn build_dirs(root: &Path, markers: &[&str]) -> Vec<PathBuf> {
|
||||
let marked = |d: &Path| markers.iter().any(|m| d.join(m).is_file());
|
||||
if marked(root) {
|
||||
return vec![root.to_path_buf()];
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
let mut level = vec![root.to_path_buf()];
|
||||
for _ in 0..NESTED_BUILD_DEPTH {
|
||||
let mut next = Vec::new();
|
||||
for sub in level.iter().flat_map(|d| subdirs(d)).filter(|d| !d.ends_with("src") && !d.ends_with("out")) {
|
||||
if marked(&sub) {
|
||||
out.push(sub);
|
||||
} else {
|
||||
next.push(sub);
|
||||
}
|
||||
}
|
||||
level = next;
|
||||
}
|
||||
out.sort();
|
||||
out
|
||||
}
|
||||
|
||||
/// Ids, names and working directory of the configurations of a build nested in
|
||||
/// `rel` (`None`: the build at the project root).
|
||||
struct Scope(Option<String>);
|
||||
|
||||
impl Scope {
|
||||
fn new(root: &Path, dir: &Path) -> Self {
|
||||
Self((dir != root).then(|| relative(root, dir).to_string_lossy().replace('\\', "/")))
|
||||
}
|
||||
fn id(&self, base: &str) -> String {
|
||||
match &self.0 {
|
||||
Some(l) => format!("{base}:{l}"),
|
||||
None => base.to_owned(),
|
||||
}
|
||||
}
|
||||
fn name(&self, base: &str) -> String {
|
||||
match &self.0 {
|
||||
Some(l) => format!("{l}: {base}"),
|
||||
None => base.to_owned(),
|
||||
}
|
||||
}
|
||||
fn cwd(&self) -> Option<PathBuf> {
|
||||
self.0.as_ref().map(PathBuf::from)
|
||||
}
|
||||
}
|
||||
|
||||
const GRADLE_SETTINGS: &[&str] = &["settings.gradle.kts", "settings.gradle"];
|
||||
const GRADLE_BUILDS: &[&str] = &["build.gradle.kts", "build.gradle"];
|
||||
|
||||
fn detect_gradle(root: &Path, out: &mut Vec<RunConfig>) {
|
||||
let markers: Vec<&str> = GRADLE_SETTINGS.iter().chain(GRADLE_BUILDS).copied().collect();
|
||||
for dir in build_dirs(root, &markers) {
|
||||
detect_gradle_build(root, &dir, out);
|
||||
}
|
||||
}
|
||||
|
||||
fn detect_gradle_build(root: &Path, dir: &Path, out: &mut Vec<RunConfig>) {
|
||||
let has_settings = first_existing(dir, GRADLE_SETTINGS).is_some();
|
||||
let text = match collect_texts(dir, GRADLE_BUILDS) {
|
||||
let names = ["build.gradle.kts", "build.gradle"];
|
||||
let has_settings = first_existing(root, &["settings.gradle.kts", "settings.gradle"]).is_some();
|
||||
let text = match collect_texts(root, &names) {
|
||||
Some(t) => t,
|
||||
None if has_settings => collect_texts_from_subdirs(dir, GRADLE_BUILDS),
|
||||
None if has_settings => collect_texts_from_subdirs(root, &names),
|
||||
None => return,
|
||||
};
|
||||
let scope = Scope::new(root, dir);
|
||||
let cmd = wrapper(dir, "gradlew", "gradlew.bat", "gradle");
|
||||
let gradle = |id: &str, task: &str| {
|
||||
config(scope.id(id), scope.name(&format!("gradle {task}")), "gradle", &cmd, &[task]).in_dir(scope.cwd())
|
||||
};
|
||||
spring_boot_apps(root, dir, out);
|
||||
out.push(gradle("gradle:build", "build"));
|
||||
out.push(gradle("gradle:test", "test").test());
|
||||
let cmd = wrapper(root, "gradlew", "gradlew.bat", "gradle");
|
||||
out.push(config("gradle:build", "gradle build", "gradle", &cmd, &["build"]));
|
||||
out.push(config("gradle:test", "gradle test", "gradle", &cmd, &["test"]).test());
|
||||
if applies_application_plugin(&text) {
|
||||
out.push(gradle("gradle:run", "run"));
|
||||
out.push(config("gradle:run", "gradle run", "gradle", &cmd, &["run"]));
|
||||
}
|
||||
if text.contains("org.springframework.boot") {
|
||||
out.push(gradle("gradle:bootRun", "bootRun"));
|
||||
out.push(config("gradle:bootRun", "gradle bootRun", "gradle", &cmd, &["bootRun"]));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -562,170 +494,15 @@ fn collect_texts_from_subdirs(root: &Path, names: &[&str]) -> String {
|
||||
}
|
||||
|
||||
fn detect_maven(root: &Path, out: &mut Vec<RunConfig>) {
|
||||
for dir in build_dirs(root, &["pom.xml"]) {
|
||||
detect_maven_build(root, &dir, out);
|
||||
}
|
||||
}
|
||||
|
||||
fn detect_maven_build(root: &Path, dir: &Path, out: &mut Vec<RunConfig>) {
|
||||
let Some(text) = collect_texts(dir, &["pom.xml"]) else { return };
|
||||
let scope = Scope::new(root, dir);
|
||||
let cmd = wrapper(dir, "mvnw", "mvnw.cmd", "mvn");
|
||||
let maven = |id: &str, goal: &str| {
|
||||
config(scope.id(id), scope.name(&format!("mvn {goal}")), "maven", &cmd, &[goal]).in_dir(scope.cwd())
|
||||
};
|
||||
spring_boot_apps(root, dir, out);
|
||||
out.push(maven("maven:package", "package"));
|
||||
out.push(maven("maven:test", "test").test());
|
||||
let Some(text) = collect_texts(root, &["pom.xml"]) else { return };
|
||||
let cmd = wrapper(root, "mvnw", "mvnw.cmd", "mvn");
|
||||
out.push(config("maven:package", "mvn package", "maven", &cmd, &["package"]));
|
||||
out.push(config("maven:test", "mvn test", "maven", &cmd, &["test"]).test());
|
||||
if text.contains("spring-boot-maven-plugin") {
|
||||
out.push(maven("maven:spring-boot:run", "spring-boot:run"));
|
||||
out.push(config("maven:spring-boot:run", "mvn spring-boot:run", "maven", &cmd, &["spring-boot:run"]));
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- spring boot
|
||||
|
||||
/// Source files read per build when looking for `@SpringBootApplication` classes.
|
||||
const SPRING_SCAN_FILES: usize = 400;
|
||||
|
||||
/// "Spring Boot" configurations for the `@SpringBootApplication` main classes of the
|
||||
/// modules of the build in `build` that apply the Spring Boot plugin:
|
||||
/// `java -cp ${classpath} <class>` in the module, the classpath resolved at launch.
|
||||
fn spring_boot_apps(root: &Path, build: &Path, out: &mut Vec<RunConfig>) {
|
||||
let mut budget = SPRING_SCAN_FILES;
|
||||
let mut modules = vec![build.to_path_buf()];
|
||||
let mut level = vec![build.to_path_buf()];
|
||||
for _ in 0..NESTED_BUILD_DEPTH {
|
||||
level = level.iter().flat_map(|d| subdirs(d)).filter(|d| !d.ends_with("src")).collect();
|
||||
modules.extend(level.iter().cloned());
|
||||
}
|
||||
for module in modules {
|
||||
if budget == 0 {
|
||||
break;
|
||||
}
|
||||
if !applies_spring_boot(&module) {
|
||||
continue;
|
||||
}
|
||||
let module_rel = (module != root).then(|| relative(root, &module).to_string_lossy().replace('\\', "/"));
|
||||
for class in spring_boot_classes(&module, &mut budget) {
|
||||
let simple = class.rsplit(['.', '$']).next().unwrap_or(&class).to_owned();
|
||||
let id = match &module_rel {
|
||||
Some(m) => format!("application:{m}:{class}"),
|
||||
None => format!("application:{class}"),
|
||||
};
|
||||
out.push(
|
||||
config(id, simple, "spring-boot", "java", &["-cp", "${classpath}", &class])
|
||||
.in_dir(module_rel.as_ref().map(PathBuf::from))
|
||||
.debug("java-debug"),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The module's own build applies the Spring Boot plugin, and it has main sources.
|
||||
fn applies_spring_boot(module: &Path) -> bool {
|
||||
if !["java", "kotlin"].iter().any(|l| module.join("src/main").join(l).is_dir()) {
|
||||
return false;
|
||||
}
|
||||
if let Some(pom) = read(&module.join("pom.xml")) {
|
||||
return pom.contains("spring-boot-maven-plugin") && !pom.contains("<packaging>pom</packaging>");
|
||||
}
|
||||
GRADLE_BUILDS.iter().filter_map(|n| read(&module.join(n))).any(|text| {
|
||||
text.lines().any(|l| {
|
||||
let l = l.split("//").next().unwrap_or_default();
|
||||
// The plugin id (`id("org.springframework.boot")`), not a dependency (`org.springframework.boot:…`).
|
||||
["org.springframework.boot\"", "org.springframework.boot'"].iter().any(|p| l.contains(p))
|
||||
&& !l.contains("apply false")
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Binary names of the `@SpringBootApplication` classes with a `main` under
|
||||
/// `src/main/{java,kotlin}`, from the shallowest packages that declare one (the
|
||||
/// application class sits in the root package of the code it scans).
|
||||
fn spring_boot_classes(module: &Path, budget: &mut usize) -> Vec<String> {
|
||||
let mut found = Vec::new();
|
||||
let mut level: Vec<PathBuf> =
|
||||
["java", "kotlin"].iter().map(|l| module.join("src/main").join(l)).filter(|d| d.is_dir()).collect();
|
||||
while !level.is_empty() && found.is_empty() && *budget > 0 {
|
||||
let mut next = Vec::new();
|
||||
for dir in &level {
|
||||
let Ok(entries) = fs::read_dir(dir) else { continue };
|
||||
let mut files = Vec::new();
|
||||
for e in entries.filter_map(Result::ok) {
|
||||
let path = e.path();
|
||||
match e.file_type() {
|
||||
Ok(t) if t.is_dir() => next.push(path),
|
||||
Ok(t) if t.is_file() && path.extension().is_some_and(|x| x == "java" || x == "kt") => {
|
||||
files.push(path)
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
files.sort();
|
||||
for file in files {
|
||||
if *budget == 0 {
|
||||
break;
|
||||
}
|
||||
*budget -= 1;
|
||||
if fs::metadata(&file).is_ok_and(|m| m.len() > 256 * 1024) {
|
||||
continue;
|
||||
}
|
||||
if let Some(class) = read(&file).and_then(|src| spring_boot_class(&src, &file)) {
|
||||
found.push(class);
|
||||
}
|
||||
}
|
||||
}
|
||||
next.sort();
|
||||
level = next;
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// The class to launch for a source file declaring a `@SpringBootApplication` with a `main`.
|
||||
pub(crate) fn spring_boot_class(src: &str, file: &Path) -> Option<String> {
|
||||
let code: Vec<&str> = src.lines().map(|l| l.split("//").next().unwrap_or_default()).collect();
|
||||
let code = code.join("\n");
|
||||
let at = code.find("@SpringBootApplication")?;
|
||||
let package = code
|
||||
.lines()
|
||||
.map(str::trim)
|
||||
.find_map(|l| l.strip_prefix("package "))
|
||||
.map(|p| p.trim_end_matches(';').trim().to_owned())
|
||||
.filter(|p| !p.is_empty());
|
||||
let qualify = |name: &str| match &package {
|
||||
Some(p) => format!("{p}.{name}"),
|
||||
None => name.to_owned(),
|
||||
};
|
||||
if file.extension().is_some_and(|x| x == "kt") {
|
||||
// A top-level `fun main` compiles into the file facade (`AppKt`, or `@file:JvmName`).
|
||||
if code.lines().any(|l| l.starts_with("fun main(")) {
|
||||
let jvm_name = code
|
||||
.lines()
|
||||
.find_map(|l| l.trim().strip_prefix("@file:JvmName(")?.split('"').nth(1).map(str::to_owned));
|
||||
let facade = jvm_name.unwrap_or_else(|| {
|
||||
let stem = file.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let mut chars = stem.chars();
|
||||
let upper: String = chars.next().map(|c| c.to_uppercase().chain(chars).collect()).unwrap_or_default();
|
||||
format!("{upper}Kt")
|
||||
});
|
||||
return Some(qualify(&facade));
|
||||
}
|
||||
if !code.contains("fun main(") {
|
||||
return None;
|
||||
}
|
||||
} else if !code.contains("void main(") {
|
||||
return None;
|
||||
}
|
||||
let name: String = code[at..]
|
||||
.split_whitespace()
|
||||
.skip_while(|t| *t != "class")
|
||||
.nth(1)?
|
||||
.chars()
|
||||
.take_while(|c| c.is_alphanumeric() || *c == '_' || *c == '$')
|
||||
.collect();
|
||||
(!name.is_empty()).then(|| qualify(&name))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- go
|
||||
|
||||
fn is_go_main_package(dir: &Path) -> bool {
|
||||
|
||||
@@ -5,7 +5,6 @@ mod detect;
|
||||
pub mod envfile;
|
||||
pub mod java_cmdline;
|
||||
pub mod junit;
|
||||
mod output_encoding;
|
||||
mod process;
|
||||
mod utf8;
|
||||
pub mod which;
|
||||
@@ -210,7 +209,7 @@ pub fn save_templates(root: &Path, templates: &[RunConfig]) -> IdeResult<()> {
|
||||
|
||||
/// The environment runs inherit (unless "Include system environment variables" is off).
|
||||
pub fn system_env() -> BTreeMap<String, String> {
|
||||
ide_core::process::host_vars().filter_map(|(k, v)| Some((k.into_string().ok()?, v.into_string().ok()?))).collect()
|
||||
std::env::vars().collect()
|
||||
}
|
||||
|
||||
/// Path of the user run configuration file for `root`.
|
||||
|
||||
@@ -1,167 +0,0 @@
|
||||
//! Makes the output of JVM and Python processes match the console's encoding.
|
||||
//!
|
||||
//! On Windows both write piped output in the ANSI code page (GBK on a Chinese
|
||||
//! system: `javac` errors, Maven / Gradle logs, `print`), while the console decodes
|
||||
//! the configured encoding (UTF-8 by default). They are told which one to use:
|
||||
//! `java` through `stdout.encoding` / `stderr.encoding` (JDK 19+) and their
|
||||
//! `sun.*` forerunners (JDK 8–18), Maven and Gradle through `MAVEN_OPTS` /
|
||||
//! `GRADLE_OPTS`, Python through `PYTHONIOENCODING`.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
const JAVA_PROPERTIES: &[&str] = &["stdout.encoding", "stderr.encoding", "sun.stdout.encoding", "sun.stderr.encoding"];
|
||||
|
||||
/// What a launch needs: `-D` options to put first on a `java` command line, and
|
||||
/// environment variables to set.
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub struct EncodingFix {
|
||||
pub java_args: Vec<String>,
|
||||
pub env: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
fn is_utf8(encoding: &str) -> bool {
|
||||
matches!(encoding.to_ascii_lowercase().replace('_', "-").as_str(), "utf-8" | "utf8")
|
||||
}
|
||||
|
||||
fn java_options(encoding: &str) -> Vec<String> {
|
||||
JAVA_PROPERTIES.iter().map(|p| format!("-D{p}={encoding}")).collect()
|
||||
}
|
||||
|
||||
fn sets_java_encoding(text: &str) -> bool {
|
||||
JAVA_PROPERTIES.iter().any(|p| text.contains(&format!("-D{p}=")))
|
||||
}
|
||||
|
||||
/// The options for a launch of `program` (`args`, environment `vars` over the
|
||||
/// `inherited` one) whose output is decoded as `encoding`; nothing when the
|
||||
/// process already writes it (UTF-8 off Windows) or the user chose the options.
|
||||
pub fn fix(
|
||||
program: &str,
|
||||
args: &[String],
|
||||
vars: &BTreeMap<String, String>,
|
||||
inherited: impl Fn(&str) -> Option<String>,
|
||||
encoding: &str,
|
||||
windows: bool,
|
||||
) -> EncodingFix {
|
||||
let encoding = encoding.trim();
|
||||
let mut out = EncodingFix::default();
|
||||
if encoding.is_empty() || (!windows && is_utf8(encoding)) {
|
||||
return out;
|
||||
}
|
||||
let current = |key: &str| vars.get(key).cloned().or_else(|| inherited(key));
|
||||
let name = crate::wrap::program_name(program).to_ascii_lowercase();
|
||||
match name.as_str() {
|
||||
"java" | "javaw" => {
|
||||
if !args.iter().any(|a| sets_java_encoding(a))
|
||||
&& !current("JDK_JAVA_OPTIONS").is_some_and(|o| sets_java_encoding(&o))
|
||||
{
|
||||
out.java_args = java_options(encoding);
|
||||
}
|
||||
}
|
||||
"mvn" | "mvnw" | "mvnd" | "gradle" | "gradlew" => {
|
||||
let key = if name.starts_with("gradle") { "GRADLE_OPTS" } else { "MAVEN_OPTS" };
|
||||
let opts = current(key).unwrap_or_default();
|
||||
if !sets_java_encoding(&opts) {
|
||||
let added = java_options(encoding).join(" ");
|
||||
let value = if opts.trim().is_empty() { added } else { format!("{} {added}", opts.trim()) };
|
||||
out.env.push((key.to_owned(), value));
|
||||
}
|
||||
}
|
||||
_ if is_python(&name) && current("PYTHONIOENCODING").is_none_or(|v| v.trim().is_empty()) => {
|
||||
out.env.push(("PYTHONIOENCODING".to_owned(), encoding.to_owned()));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `python`, `python3`, `python3.12`, `py`, and the runners that start one.
|
||||
fn is_python(name: &str) -> bool {
|
||||
name == "python"
|
||||
|| name == "py"
|
||||
|| name.strip_prefix("python").is_some_and(|v| v.chars().all(|c| c.is_ascii_digit() || c == '.'))
|
||||
|| matches!(name, "uv" | "poetry" | "pdm" | "pytest" | "pipenv")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn run(program: &str, args: &[&str], vars: &[(&str, &str)], encoding: &str, windows: bool) -> EncodingFix {
|
||||
let args: Vec<String> = args.iter().map(|a| (*a).to_owned()).collect();
|
||||
let vars: BTreeMap<String, String> = vars.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect();
|
||||
fix(program, &args, &vars, |_| None, encoding, windows)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn java_launches_write_the_console_encoding_on_windows() {
|
||||
let expected = [
|
||||
"-Dstdout.encoding=UTF-8",
|
||||
"-Dstderr.encoding=UTF-8",
|
||||
"-Dsun.stdout.encoding=UTF-8",
|
||||
"-Dsun.stderr.encoding=UTF-8",
|
||||
];
|
||||
// The reported case: a source-file launch through the Oracle `javapath` shim.
|
||||
let java = "C:/Program Files/Common Files/Oracle/Java/javapath/java.exe";
|
||||
for program in [java, "java", "javaw.exe", r"C:\jdk\bin\java.exe"] {
|
||||
let f = run(program, &["Main.java"], &[], "UTF-8", true);
|
||||
assert_eq!(f.java_args, expected, "{program}");
|
||||
assert!(f.env.is_empty());
|
||||
}
|
||||
assert_eq!(run("java", &["-cp", "x", "a.Main"], &[], "GBK", true).java_args[0], "-Dstdout.encoding=GBK");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_changes_where_output_already_matches() {
|
||||
for (program, args) in [("java", vec!["Main.java"]), ("mvn", vec!["package"]), ("python3", vec!["a.py"])] {
|
||||
assert_eq!(run(program, &args, &[], "UTF-8", false), EncodingFix::default(), "{program}");
|
||||
assert_eq!(run(program, &args, &[], "utf8", false), EncodingFix::default(), "{program}");
|
||||
assert_eq!(run(program, &args, &[], "", true), EncodingFix::default(), "{program}");
|
||||
}
|
||||
for program in ["node", "cargo", "go", "npm.cmd", "cmd.exe"] {
|
||||
assert_eq!(run(program, &[], &[], "UTF-8", true), EncodingFix::default(), "{program}");
|
||||
}
|
||||
// A console set to another encoding elsewhere still gets it.
|
||||
assert_eq!(run("java", &["Main"], &[], "GBK", false).java_args.len(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_chosen_by_the_user_win() {
|
||||
assert!(run("java", &["-Dstdout.encoding=GBK", "Main"], &[], "UTF-8", true).java_args.is_empty());
|
||||
assert!(
|
||||
run("java", &["Main"], &[("JDK_JAVA_OPTIONS", "-Dsun.stdout.encoding=GBK")], "UTF-8", true)
|
||||
.java_args
|
||||
.is_empty()
|
||||
);
|
||||
assert!(run("mvn.cmd", &[], &[("MAVEN_OPTS", "-Dstdout.encoding=GBK")], "UTF-8", true).env.is_empty());
|
||||
assert!(run("python.exe", &[], &[("PYTHONIOENCODING", "gbk")], "UTF-8", true).env.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_tools_and_python_get_environment_variables() {
|
||||
let opts =
|
||||
"-Dstdout.encoding=UTF-8 -Dstderr.encoding=UTF-8 -Dsun.stdout.encoding=UTF-8 -Dsun.stderr.encoding=UTF-8";
|
||||
for program in ["mvn.cmd", "mvnw.cmd", r"C:\maven\bin\mvn.cmd"] {
|
||||
assert_eq!(
|
||||
run(program, &["package"], &[], "UTF-8", true).env,
|
||||
[("MAVEN_OPTS".to_owned(), opts.to_owned())]
|
||||
);
|
||||
}
|
||||
for program in ["gradlew.bat", "gradle.bat"] {
|
||||
assert_eq!(run(program, &["build"], &[], "UTF-8", true).env, [("GRADLE_OPTS".to_owned(), opts.to_owned())]);
|
||||
}
|
||||
// Existing options are kept, from the configuration or the inherited environment.
|
||||
let f = run("mvn.cmd", &[], &[("MAVEN_OPTS", "-Xmx1g")], "UTF-8", true);
|
||||
assert_eq!(f.env, [("MAVEN_OPTS".to_owned(), format!("-Xmx1g {opts}"))]);
|
||||
let inherited =
|
||||
fix("gradlew.bat", &[], &BTreeMap::new(), |k| (k == "GRADLE_OPTS").then(|| "-Xmx2g".into()), "UTF-8", true);
|
||||
assert_eq!(inherited.env, [("GRADLE_OPTS".to_owned(), format!("-Xmx2g {opts}"))]);
|
||||
for program in ["python.exe", "python3", "python3.12", "py.exe", "uv.exe", "poetry"] {
|
||||
assert_eq!(
|
||||
run(program, &[], &[], "UTF-8", true).env,
|
||||
[("PYTHONIOENCODING".to_owned(), "UTF-8".to_owned())],
|
||||
"{program}"
|
||||
);
|
||||
}
|
||||
assert_eq!(run("python3", &[], &[], "GBK", false).env, [("PYTHONIOENCODING".to_owned(), "GBK".to_owned())]);
|
||||
}
|
||||
}
|
||||
@@ -171,33 +171,6 @@ fn shorten_java(inv: &mut Invocation, config: &RunConfig, cwd: &Path) -> IdeResu
|
||||
Ok(TempFile(Some(s.file)))
|
||||
}
|
||||
|
||||
/// Tells JVM and Python processes to write the encoding the console decodes (see
|
||||
/// [`crate::output_encoding`]).
|
||||
fn match_console_encoding(inv: &mut Invocation, env: &mut LaunchEnv, config: &RunConfig, options: &StartOptions) {
|
||||
if inv.raw_args {
|
||||
return;
|
||||
}
|
||||
let inherit = !env.clear;
|
||||
let fix = crate::output_encoding::fix(
|
||||
&inv.program.to_string_lossy(),
|
||||
&inv.args,
|
||||
&env.vars,
|
||||
|key| if inherit { std::env::var(key).ok() } else { None },
|
||||
options.encoding.as_deref().unwrap_or("UTF-8"),
|
||||
cfg!(windows),
|
||||
);
|
||||
env.vars.extend(fix.env);
|
||||
if !fix.java_args.is_empty() {
|
||||
inv.args.splice(0..0, fix.java_args);
|
||||
let mut display = quote(config.command.trim());
|
||||
for a in &inv.args {
|
||||
display.push(' ');
|
||||
display.push_str("e(a));
|
||||
}
|
||||
inv.display = display;
|
||||
}
|
||||
}
|
||||
|
||||
/// A launch's pathing jar / argfile, deleted when dropped (the process exited, or never started).
|
||||
struct TempFile(Option<PathBuf>);
|
||||
|
||||
@@ -302,7 +275,7 @@ impl ProcessManager {
|
||||
if extras.emulate_terminal && extras.stdin_file.is_some() {
|
||||
return Err(IdeError::invalid("input cannot be redirected from a file when emulating a terminal"));
|
||||
}
|
||||
let mut env = launch_env(root, config)?;
|
||||
let env = launch_env(root, config)?;
|
||||
let on_output: OutputFn = Arc::from(on_output);
|
||||
let on_output = match extras.output_file.as_deref() {
|
||||
Some(file) => tee_output(&resolve_cwd(root, Some(Path::new(file))), on_output)?,
|
||||
@@ -313,10 +286,6 @@ impl ProcessManager {
|
||||
cwd: cwd.clone(),
|
||||
env: env.clone(),
|
||||
});
|
||||
if !extras.emulate_terminal {
|
||||
// A terminal re-encodes output itself; pipes carry the process's bytes as they are.
|
||||
match_console_encoding(&mut inv, &mut env, config, options);
|
||||
}
|
||||
let temp = shorten_java(&mut inv, config, &cwd)?;
|
||||
if extras.emulate_terminal {
|
||||
return self.start_pty(config, &inv, &cwd, &env, stop, options, sink, on_output, temp);
|
||||
@@ -438,12 +407,6 @@ impl ProcessManager {
|
||||
if env.clear {
|
||||
cmd.env_clear();
|
||||
} else {
|
||||
for (k, v) in ide_core::process::host_env_fixes() {
|
||||
match v {
|
||||
Some(v) => cmd.env(k, v),
|
||||
None => cmd.env_remove(k),
|
||||
}
|
||||
}
|
||||
for (k, v) in ide_core::process::shell_env() {
|
||||
cmd.env(k, v);
|
||||
}
|
||||
@@ -639,7 +602,7 @@ fn launch_env(root: &Path, config: &RunConfig) -> IdeResult<LaunchEnv> {
|
||||
BTreeMap::new()
|
||||
} else {
|
||||
let base: BTreeMap<String, String> =
|
||||
if extras.include_system_env { crate::system_env() } else { BTreeMap::new() };
|
||||
if extras.include_system_env { std::env::vars().collect() } else { BTreeMap::new() };
|
||||
let paths: Vec<PathBuf> = extras.env_files.iter().map(|f| resolve_cwd(root, Some(Path::new(f)))).collect();
|
||||
crate::envfile::load(&paths, &base).map_err(|e| IdeError::not_found(format!("cannot read .env file: {e}")))?
|
||||
};
|
||||
@@ -657,7 +620,7 @@ fn apply_env(cmd: &mut Command, env: &LaunchEnv) {
|
||||
if env.clear {
|
||||
cmd.env_clear();
|
||||
} else {
|
||||
ide_core::process::host_env(cmd).envs(ide_core::process::shell_env());
|
||||
cmd.envs(ide_core::process::shell_env());
|
||||
}
|
||||
cmd.envs(&env.vars);
|
||||
}
|
||||
@@ -668,7 +631,6 @@ fn run_stop_command(stop: &StopCommand, output: &OutputFn) {
|
||||
output(OutputChunk::System { text: format!("{}\n", stop.line) });
|
||||
let inv = shell_invocation(&stop.line, cfg!(windows), std::env::var("COMSPEC").ok());
|
||||
let mut cmd = Command::new(&inv.program);
|
||||
ide_core::process::prepare(&mut cmd);
|
||||
if inv.raw_args {
|
||||
add_raw_args(&mut cmd, &inv.args);
|
||||
} else {
|
||||
@@ -676,6 +638,7 @@ fn run_stop_command(stop: &StopCommand, output: &OutputFn) {
|
||||
}
|
||||
cmd.current_dir(&stop.cwd).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::piped());
|
||||
apply_env(&mut cmd, &stop.env);
|
||||
ide_core::process::no_window(&mut cmd);
|
||||
let mut child = match cmd.spawn() {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
|
||||
@@ -93,7 +93,7 @@ pub fn find_tool(name: &str, config: &RunConfig, dir: &Path, root: &Path) -> Opt
|
||||
pub fn probe(argv: &[String], dir: &Path, config: &RunConfig) -> bool {
|
||||
let Some((program, args)) = argv.split_first() else { return false };
|
||||
let program = resolve(program, config);
|
||||
ide_core::process::prepare(&mut Command::new(program))
|
||||
ide_core::process::no_window(&mut Command::new(program))
|
||||
.args(args)
|
||||
.current_dir(dir)
|
||||
.envs(&config.env)
|
||||
|
||||
@@ -184,130 +184,6 @@ fn maven_projects() {
|
||||
assert_eq!(c[0].command, "mvn");
|
||||
}
|
||||
|
||||
const BOOT_POM: &str = "<project><artifactId>app</artifactId><build><plugins><plugin>\
|
||||
<artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>";
|
||||
const PARENT_POM: &str = "<project><packaging>pom</packaging><modules><module>app</module></modules>\
|
||||
<build><pluginManagement><plugins><plugin>\
|
||||
<artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></pluginManagement>\
|
||||
</build></project>";
|
||||
const BOOT_MAIN: &str = "package org.dromara;\n\nimport org.springframework.boot.SpringApplication;\n\
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;\n\n\
|
||||
/** Entry. */\n@SpringBootApplication\npublic class DromaraApplication {\n\
|
||||
\x20 public static void main(String[] args) {\n\
|
||||
\x20 SpringApplication.run(DromaraApplication.class, args);\n }\n}\n";
|
||||
|
||||
/// A folder holding a Maven back end and an npm front end, each its own repository
|
||||
/// (RuoYi-Vue-Plus + plus-ui): the Maven build is detected where it is.
|
||||
#[test]
|
||||
fn builds_nested_in_a_folder_of_repositories() {
|
||||
let dir = project(&[
|
||||
("RuoYi-Vue-Plus/pom.xml", PARENT_POM),
|
||||
("RuoYi-Vue-Plus/ruoyi-admin/pom.xml", BOOT_POM),
|
||||
("RuoYi-Vue-Plus/ruoyi-admin/src/main/java/org/dromara/DromaraApplication.java", BOOT_MAIN),
|
||||
("RuoYi-Vue-Plus/ruoyi-admin/src/main/java/org/dromara/web/Controller.java", "package org.dromara.web;"),
|
||||
("RuoYi-Vue-Plus/ruoyi-common/pom.xml", "<project><packaging>pom</packaging></project>"),
|
||||
("RuoYi-Vue-Plus/ruoyi-common/ruoyi-common-core/pom.xml", "<project/>"),
|
||||
("RuoYi-Vue-Plus/ruoyi-common/ruoyi-common-core/src/main/java/A.java", "class A {}"),
|
||||
("plus-ui/package.json", r#"{"scripts":{"dev":"vite"}}"#),
|
||||
]);
|
||||
let c = detect(dir.path());
|
||||
let app = find(&c, "application:RuoYi-Vue-Plus/ruoyi-admin:org.dromara.DromaraApplication");
|
||||
assert_eq!(app.name, "DromaraApplication");
|
||||
assert_eq!(app.kind, "spring-boot");
|
||||
assert_eq!(cmdline(app), "java -cp ${classpath} org.dromara.DromaraApplication");
|
||||
assert_eq!(app.cwd.as_deref(), Some(Path::new("RuoYi-Vue-Plus/ruoyi-admin")));
|
||||
assert_eq!(app.debug_adapter.as_deref(), Some("java-debug"));
|
||||
let package = find(&c, "maven:package:RuoYi-Vue-Plus");
|
||||
assert_eq!(package.name, "RuoYi-Vue-Plus: mvn package");
|
||||
assert_eq!(cmdline(package), "mvn package");
|
||||
assert_eq!(package.cwd.as_deref(), Some(Path::new("RuoYi-Vue-Plus")));
|
||||
assert!(find(&c, "maven:test:RuoYi-Vue-Plus").is_test);
|
||||
assert!(ids(&c).contains(&"maven:spring-boot:run:RuoYi-Vue-Plus"));
|
||||
assert!(ids(&c).contains(&"npm:plus-ui:dev"));
|
||||
// Modules of the nested build are not builds of their own; only one application.
|
||||
assert!(!ids(&c).iter().any(|id| id.contains("ruoyi-common")));
|
||||
assert_eq!(c.iter().filter(|c| c.kind == "spring-boot").count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_builds_of_every_kind_and_depth() {
|
||||
let dir = project(&[
|
||||
("services/api/settings.gradle.kts", "include(\"app\")"),
|
||||
("services/api/gradlew", "#!/bin/sh"),
|
||||
("services/api/app/build.gradle.kts", "plugins { id(\"org.springframework.boot\") version \"3.3.0\" }\n"),
|
||||
(
|
||||
"services/api/app/src/main/kotlin/com/acme/Api.kt",
|
||||
"package com.acme\n\n@SpringBootApplication\nclass Api\n\nfun main(args: Array<String>) {\n runApplication<Api>(*args)\n}\n",
|
||||
),
|
||||
("billing/pom.xml", BOOT_POM),
|
||||
("billing/mvnw", "#!/bin/sh"),
|
||||
(
|
||||
"billing/src/main/java/Billing.java",
|
||||
"@SpringBootApplication\nclass Billing { public static void main(String[] a) {} }",
|
||||
),
|
||||
// Deeper than a build is looked for.
|
||||
("a/b/c/d/pom.xml", "<project/>"),
|
||||
// Build output and sources are not searched.
|
||||
("web/node_modules/x/pom.xml", "<project/>"),
|
||||
("tool/src/pom.xml", "<project/>"),
|
||||
]);
|
||||
let c = detect(dir.path());
|
||||
let boot = find(&c, "gradle:bootRun:services/api");
|
||||
assert_eq!(boot.name, "services/api: gradle bootRun");
|
||||
assert_eq!(boot.cwd.as_deref(), Some(Path::new("services/api")));
|
||||
if cfg!(unix) {
|
||||
assert_eq!(cmdline(boot), "./gradlew bootRun");
|
||||
assert_eq!(cmdline(find(&c, "maven:package:billing")), "./mvnw package");
|
||||
}
|
||||
assert!(find(&c, "gradle:test:services/api").is_test);
|
||||
let api = find(&c, "application:services/api/app:com.acme.ApiKt");
|
||||
assert_eq!(api.cwd.as_deref(), Some(Path::new("services/api/app")));
|
||||
let billing = find(&c, "application:billing:Billing");
|
||||
assert_eq!(billing.cwd.as_deref(), Some(Path::new("billing")));
|
||||
let builds: Vec<&str> =
|
||||
ids(&c).into_iter().filter(|id| id.starts_with("maven:package") || id.starts_with("gradle:build")).collect();
|
||||
assert_eq!(builds, ["gradle:build:services/api", "maven:package:billing"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_root_build_disables_the_nested_scan() {
|
||||
let dir = project(&[
|
||||
("pom.xml", BOOT_POM),
|
||||
(
|
||||
"src/main/java/demo/App.java",
|
||||
"package demo;\n@SpringBootApplication public class App {\n public static void main(String[] args) {}\n}\n",
|
||||
),
|
||||
("tools/gen/pom.xml", "<project/>"),
|
||||
]);
|
||||
let c = detect(dir.path());
|
||||
assert!(ids(&c).contains(&"maven:package"));
|
||||
assert!(!ids(&c).iter().any(|id| id.contains("tools")));
|
||||
let app = find(&c, "application:demo.App");
|
||||
assert_eq!(app.cwd, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spring_boot_applications_need_the_plugin_and_a_main() {
|
||||
let main =
|
||||
"package demo;\n@SpringBootApplication\npublic class App {\n public static void main(String[] args) {}\n}\n";
|
||||
// A library using Spring Boot without the plugin, a configuration class without `main`,
|
||||
// the annotation in a comment, a parent POM.
|
||||
let dir = project(&[
|
||||
("lib/pom.xml", "<project><dependencies>spring-boot-starter</dependencies></project>"),
|
||||
("lib/src/main/java/demo/App.java", main),
|
||||
("svc/pom.xml", BOOT_POM),
|
||||
("svc/src/main/java/demo/Config.java", "package demo;\n@SpringBootApplication\npublic class Config {}\n"),
|
||||
(
|
||||
"svc/src/main/java/demo/Old.java",
|
||||
"package demo;\n// @SpringBootApplication\nclass Old { public static void main(String[] a) {} }\n",
|
||||
),
|
||||
("gr/build.gradle", "dependencies { implementation 'org.springframework.boot:spring-boot-starter' }\n"),
|
||||
("gr/src/main/java/demo/App.java", main),
|
||||
]);
|
||||
let c = detect(dir.path());
|
||||
assert!(!c.iter().any(|c| c.kind == "spring-boot"), "{:?}", ids(&c));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn go_projects() {
|
||||
let dir = project(&[
|
||||
|
||||
@@ -17,7 +17,6 @@ serde_json.workspace = true
|
||||
specta.workspace = true
|
||||
toml.workspace = true
|
||||
tracing.workspace = true
|
||||
which = "8"
|
||||
zip = { version = "=2.4.2", default-features = false, features = ["deflate"] }
|
||||
|
||||
[dev-dependencies]
|
||||
|
||||
@@ -1,90 +0,0 @@
|
||||
//! Angular Language Server (`ngserver`): its package, where TypeScript and
|
||||
//! `@angular/language-service` come from, and the project's Angular version.
|
||||
|
||||
use crate::npm::package_dir;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub(crate) const SERVER: &str = "angular-language-server";
|
||||
const PACKAGE: &str = "@angular/language-server";
|
||||
|
||||
/// `@angular/language-server`'s directory for an `ngserver` executable.
|
||||
pub(crate) fn server_package(bin: &Path) -> Option<PathBuf> {
|
||||
package_dir(bin, PACKAGE)
|
||||
}
|
||||
|
||||
/// Why an `ngserver` whose package isn't found can't start: it loads TypeScript
|
||||
/// and `@angular/language-service` from there.
|
||||
pub(crate) fn missing_package_message(bin: &Path) -> String {
|
||||
format!(
|
||||
"Can't find the @angular/language-server package of {}, which brings the TypeScript and Angular \
|
||||
language service the server loads. Reinstall it in Settings › Languages & Frameworks › Language \
|
||||
Servers or with `npm i -g @angular/language-server`.",
|
||||
bin.display()
|
||||
)
|
||||
}
|
||||
|
||||
/// Why a server installed in a directory whose path has a comma can't start.
|
||||
pub(crate) fn comma_message(package: &str) -> String {
|
||||
format!(
|
||||
"The Angular Language Server can't load from {package}: its path has a comma. Install it in a \
|
||||
directory without one."
|
||||
)
|
||||
}
|
||||
|
||||
/// The version of the `@angular/core` that `dir` resolves (from its own or an
|
||||
/// ancestor's `node_modules`, like Node).
|
||||
pub(crate) fn core_version(dir: &Path) -> Option<String> {
|
||||
dir.ancestors().find_map(|a| {
|
||||
let text = std::fs::read_to_string(a.join("node_modules/@angular/core/package.json")).ok()?;
|
||||
let json: serde_json::Value = serde_json::from_str(&text).ok()?;
|
||||
json.get("version")?.as_str().map(str::to_owned)
|
||||
})
|
||||
}
|
||||
|
||||
/// Arguments telling the server the project's Angular `version`: templates of
|
||||
/// projects before 17 have no blocks (`@if`), before 18.1 no `@let`.
|
||||
pub(crate) fn version_args(version: &str) -> Vec<String> {
|
||||
let mut parts = version.split(['.', '-', '+']).map(|p| p.parse::<u32>().ok());
|
||||
let (Some(Some(major)), Some(Some(minor))) = (parts.next(), parts.next()) else { return Vec::new() };
|
||||
// 0.0.0: a local build of Angular.
|
||||
if major == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut args = vec!["--angularCoreVersion".to_owned(), version.to_owned()];
|
||||
if major < 17 {
|
||||
args.push("--disableBlockSyntax".into());
|
||||
}
|
||||
if (major, minor) < (18, 1) {
|
||||
args.push("--disableLetSyntax".into());
|
||||
}
|
||||
args
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn template_syntax_follows_the_angular_version() {
|
||||
let args = |v: &str| version_args(v).into_iter().skip(2).collect::<Vec<_>>();
|
||||
assert_eq!(version_args("22.2.3")[..2], ["--angularCoreVersion", "22.2.3"]);
|
||||
assert_eq!(args("22.0.0-next.1"), Vec::<String>::new());
|
||||
assert_eq!(args("18.1.0"), Vec::<String>::new());
|
||||
assert_eq!(args("18.0.5"), ["--disableLetSyntax"]);
|
||||
assert_eq!(args("17.3.12"), ["--disableLetSyntax"]);
|
||||
assert_eq!(args("16.2.0"), ["--disableBlockSyntax", "--disableLetSyntax"]);
|
||||
assert!(version_args("0.0.0-PLACEHOLDER").is_empty());
|
||||
assert!(version_args("next").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn core_version_is_found_in_an_ancestor() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let core = tmp.path().join("node_modules/@angular/core");
|
||||
std::fs::create_dir_all(&core).unwrap();
|
||||
std::fs::write(core.join("package.json"), r#"{"name":"@angular/core","version":"19.2.1"}"#).unwrap();
|
||||
let app = tmp.path().join("apps/web");
|
||||
std::fs::create_dir_all(&app).unwrap();
|
||||
assert_eq!(core_version(&app).as_deref(), Some("19.2.1"));
|
||||
}
|
||||
}
|
||||
@@ -3,13 +3,12 @@
|
||||
|
||||
use crate::discover::{project_venv_python, workspace_tsdk};
|
||||
use crate::exec::{path_with, search_path};
|
||||
use crate::{angular, godot, vue};
|
||||
use crate::{bin_dir, exe, venv_of};
|
||||
use ide_core::settings::{LanguageServerSettings, Settings};
|
||||
use ide_language::{LanguageConfig, LanguageServerConfig};
|
||||
use crate::{godot, vue};
|
||||
use ide_core::settings::Settings;
|
||||
use ide_language::LanguageServerConfig;
|
||||
use ide_run::RunConfig;
|
||||
use serde_json::{Value, json};
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
fn non_empty(s: &str) -> Option<&str> {
|
||||
@@ -135,7 +134,7 @@ pub fn tsdk(root: &Path, s: &Settings) -> Option<PathBuf> {
|
||||
}
|
||||
}
|
||||
|
||||
const PYTHON_SERVERS: [&str; 6] = ["basedpyright", "pyright", "ty", "pylsp", "jedi-language-server", "ruff"];
|
||||
const PYTHON_SERVERS: [&str; 5] = ["basedpyright", "pyright", "pylsp", "jedi-language-server", "ruff"];
|
||||
|
||||
fn merge(base: &mut Value, layer: Value) {
|
||||
match (base, layer) {
|
||||
@@ -301,84 +300,6 @@ pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root
|
||||
let dirs: Vec<&Path> = path_dirs.iter().map(PathBuf::as_path).collect();
|
||||
cfg.env.insert("PATH".into(), path_with(&dirs));
|
||||
}
|
||||
|
||||
// Last: it finds the server on the `PATH` set above.
|
||||
if name == angular::SERVER {
|
||||
configure_angular(cfg, root, server_root, s);
|
||||
}
|
||||
}
|
||||
|
||||
/// The servers `language` uses after Settings › Language Servers: the
|
||||
/// definition's ones that aren't disabled, then the ones defined in settings for it.
|
||||
pub fn language_servers(language: &str, defined: &[LanguageServerConfig], s: &Settings) -> Vec<LanguageServerConfig> {
|
||||
let enabled = |name: &str| s.language_servers.get(name).is_none_or(|ls| ls.enabled);
|
||||
let mut out: Vec<LanguageServerConfig> = defined.iter().filter(|c| enabled(&c.name)).cloned().collect();
|
||||
for (name, ls) in &s.language_servers {
|
||||
if ls.enabled && ls.languages.iter().any(|l| l == language) && !out.iter().any(|c| &c.name == name) {
|
||||
out.push(custom_server(name, ls));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Adds the servers defined in settings to the languages they serve (to list
|
||||
/// them with the tools); disabled ones stay so they can be turned back on.
|
||||
pub fn with_custom_servers(langs: &mut [LanguageConfig], s: &Settings) {
|
||||
for (name, ls) in s.language_servers.iter().filter(|(_, ls)| ls.is_custom()) {
|
||||
for lang in langs.iter_mut().filter(|l| ls.languages.iter().any(|id| id == l.id.as_str())) {
|
||||
if !lang.language_servers.iter().any(|c| &c.name == name) {
|
||||
lang.language_servers.push(custom_server(name, ls));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn custom_server(name: &str, ls: &LanguageServerSettings) -> LanguageServerConfig {
|
||||
LanguageServerConfig {
|
||||
name: name.to_owned(),
|
||||
command: ls.command.trim().to_owned(),
|
||||
args: Vec::new(),
|
||||
env: Default::default(),
|
||||
root_markers: ls.root_markers.clone(),
|
||||
require_root_marker: false,
|
||||
initialization_options: None,
|
||||
settings: None,
|
||||
install_hint: Some(match ls.command.trim() {
|
||||
"" => format!("Set the command of `{name}` in Settings › Language Servers"),
|
||||
command => format!("`{command}` was not found: install it, or set its path in Settings › Language Servers"),
|
||||
}),
|
||||
connect: None,
|
||||
fallback: false,
|
||||
max_java: None,
|
||||
launch_error: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Command and arguments from Settings › Language Servers; applied before
|
||||
/// [`configure_server`] so toolchain adjustments (a custom path, JVM args) still follow.
|
||||
pub fn server_launch_overrides(cfg: &mut LanguageServerConfig, s: &Settings) {
|
||||
let Some(ls) = s.language_servers.get(&cfg.name) else { return };
|
||||
if let Some(command) = non_empty(ls.command.trim()) {
|
||||
cfg.command = command.to_owned();
|
||||
}
|
||||
if let Some(args) = &ls.args {
|
||||
cfg.args = args.clone();
|
||||
}
|
||||
}
|
||||
|
||||
/// Environment, `initializationOptions` and `workspace/configuration` settings
|
||||
/// from Settings › Language Servers; applied last so they win over derived values.
|
||||
pub fn server_protocol_overrides(cfg: &mut LanguageServerConfig, s: &Settings) {
|
||||
let Some(ls) = s.language_servers.get(&cfg.name) else { return };
|
||||
cfg.env.extend(ls.env.iter().map(|(k, v)| (k.clone(), v.clone())));
|
||||
if let Some(options) = &ls.initialization_options {
|
||||
merge_init_options(cfg, options.clone());
|
||||
}
|
||||
if let Some(settings) = &ls.settings {
|
||||
let mut current = cfg.settings.take().filter(Value::is_object).unwrap_or_else(|| json!({}));
|
||||
merge(&mut current, settings.clone());
|
||||
cfg.settings = Some(current);
|
||||
}
|
||||
}
|
||||
|
||||
/// vue-language-server loads TypeScript as a library (`--tsdk`, else its own
|
||||
@@ -401,38 +322,6 @@ fn configure_vue_typescript(cfg: &mut LanguageServerConfig, root: &Path, server_
|
||||
}
|
||||
}
|
||||
|
||||
/// ngserver loads TypeScript and `@angular/language-service` from probe
|
||||
/// locations: its own package (it depends on both), then the project. A selected
|
||||
/// TypeScript version goes first (`--tsdk`); the project's Angular version decides
|
||||
/// the template syntax. Without its package the server can't start.
|
||||
fn configure_angular(cfg: &mut LanguageServerConfig, root: &Path, server_root: &Path, s: &Settings) {
|
||||
// Found as the launcher finds it; missing, it asks to be installed.
|
||||
let path = cfg.env.get("PATH").map_or_else(search_path, OsString::from);
|
||||
let Ok(bin) = which::which_in(&cfg.command, Some(path), server_root) else { return };
|
||||
let Some(package) = angular::server_package(&bin) else {
|
||||
cfg.launch_error = Some(angular::missing_package_message(&bin));
|
||||
return;
|
||||
};
|
||||
let package = package.to_string_lossy().into_owned();
|
||||
// The server splits the list at commas.
|
||||
if package.contains(',') {
|
||||
cfg.launch_error = Some(angular::comma_message(&package));
|
||||
return;
|
||||
}
|
||||
// Launch the server whose package is probed, not another one on the path.
|
||||
cfg.command = bin.to_string_lossy().into_owned();
|
||||
let project = server_root.to_string_lossy();
|
||||
let probes = if project.contains(',') { package } else { format!("{package},{project}") };
|
||||
cfg.args.extend(["--ngProbeLocations".into(), probes.clone(), "--tsProbeLocations".into(), probes]);
|
||||
if let Some(lib) = tsdk(server_root, s).or_else(|| tsdk(root, s)) {
|
||||
cfg.args.extend(["--tsdk".into(), lib.to_string_lossy().into_owned()]);
|
||||
}
|
||||
// The project root is an ancestor of the server's.
|
||||
if let Some(version) = angular::core_version(server_root) {
|
||||
cfg.args.extend(angular::version_args(&version));
|
||||
}
|
||||
}
|
||||
|
||||
fn is_python_command(cmd: &str) -> bool {
|
||||
let name = Path::new(cmd).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let name = name.strip_suffix(".exe").unwrap_or(&name);
|
||||
|
||||
@@ -14,15 +14,9 @@ pub fn search_path() -> OsString {
|
||||
let mut dirs: Vec<PathBuf> =
|
||||
std::env::var_os("PATH").map(|p| std::env::split_paths(&p).collect()).unwrap_or_default();
|
||||
if let Some(home) = crate::home_dir() {
|
||||
for rel in [".cargo/bin", ".local/bin", "go/bin", ".pyenv/shims", ".bun/bin", ".npm-global/bin", ".volta/bin"] {
|
||||
for rel in [".cargo/bin", ".local/bin", "go/bin", ".pyenv/shims", ".volta/bin"] {
|
||||
dirs.push(home.join(rel));
|
||||
}
|
||||
// nvm: newest installed node's bin, as language servers are launched.
|
||||
if let Ok(entries) = std::fs::read_dir(home.join(".nvm/versions/node")) {
|
||||
let mut versions: Vec<PathBuf> = entries.flatten().map(|e| e.path().join("bin")).collect();
|
||||
versions.sort();
|
||||
dirs.extend(versions.into_iter().rev());
|
||||
}
|
||||
}
|
||||
for d in ["/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin"] {
|
||||
dirs.push(PathBuf::from(d));
|
||||
@@ -65,7 +59,7 @@ pub(crate) fn query_in(
|
||||
if let Some(cwd) = cwd {
|
||||
cmd.current_dir(cwd);
|
||||
}
|
||||
let mut child = ide_core::process::prepare(&mut cmd)
|
||||
let mut child = ide_core::process::no_window(&mut cmd)
|
||||
.args(args)
|
||||
.env("PATH", search_path())
|
||||
.envs(env.iter().copied())
|
||||
@@ -118,7 +112,7 @@ pub(crate) fn stream(
|
||||
on_line: &dyn Fn(String),
|
||||
) -> IdeResult<String> {
|
||||
let mut cmd = Command::new(program);
|
||||
ide_core::process::prepare(&mut cmd);
|
||||
ide_core::process::no_window(&mut cmd);
|
||||
cmd.args(args).env("PATH", search_path()).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
cmd.envs(env.iter().map(|(k, v)| (k, v)));
|
||||
if let Some(cwd) = cwd {
|
||||
|
||||
@@ -161,19 +161,6 @@ pub fn jdtls_jdks(min_java: u32) -> Arc<[Jdk]> {
|
||||
}
|
||||
}
|
||||
|
||||
/// For a server with `max-java`: when the `JAVA_HOME` it would get (its env,
|
||||
/// else the IDE's) is a newer JDK, points it at the newest of `jdks` that fits.
|
||||
pub fn cap_java_home(cfg: &mut LanguageServerConfig, jdks: &[Jdk]) {
|
||||
let Some(max) = cfg.max_java else { return };
|
||||
let current = cfg.env.get("JAVA_HOME").cloned().or_else(|| std::env::var("JAVA_HOME").ok());
|
||||
if current.as_deref().and_then(|h| jdk_at(Path::new(h))).is_some_and(|j| j.major <= max) {
|
||||
return;
|
||||
}
|
||||
if let Some(jdk) = jdks.iter().filter(|j| j.major <= max).max_by_key(|j| j.major) {
|
||||
cfg.env.insert("JAVA_HOME".into(), jdk.home.to_string_lossy().into_owned());
|
||||
}
|
||||
}
|
||||
|
||||
/// Oldest Java version jdtls runs on when its install can't tell (its launcher's check).
|
||||
pub const JDTLS_MIN_JAVA: u32 = 21;
|
||||
|
||||
|
||||
@@ -5,7 +5,6 @@
|
||||
//! - applying the selected toolchains from settings to language-server launch
|
||||
//! configs, run configurations and new terminal sessions ([`apply`]).
|
||||
|
||||
mod angular;
|
||||
pub mod apply;
|
||||
mod discover;
|
||||
mod exec;
|
||||
@@ -15,7 +14,6 @@ pub mod jdtls;
|
||||
pub mod libraries;
|
||||
pub mod locate;
|
||||
pub mod lombok;
|
||||
mod npm;
|
||||
pub mod python;
|
||||
mod vue;
|
||||
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
//! Node-based language servers installed with npm: the package behind a command.
|
||||
|
||||
use std::ffi::OsStr;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// `command` as given (a path) or found on `path`, npm shims included.
|
||||
pub(crate) fn find_command(command: &str, path: &OsStr) -> Option<PathBuf> {
|
||||
let p = Path::new(command);
|
||||
if p.is_absolute() {
|
||||
return p.is_file().then(|| p.to_path_buf());
|
||||
}
|
||||
let exts: &[&str] = if cfg!(windows) { &[".cmd", ".exe", ""] } else { &[""] };
|
||||
std::env::split_paths(path)
|
||||
.flat_map(|d| exts.iter().map(move |e| d.join(format!("{command}{e}"))))
|
||||
.find(|c| c.is_file())
|
||||
}
|
||||
|
||||
/// The npm package an executable comes from: next to a `node_modules/.bin` shim
|
||||
/// (the IDE's tools dir, a project), a Windows global shim (`%APPDATA%\npm`), a
|
||||
/// Unix global `<prefix>/bin` or a symlink into the package.
|
||||
pub(crate) fn package_dir(bin: &Path, package: &str) -> Option<PathBuf> {
|
||||
let dir = bin.parent()?;
|
||||
let mut candidates = vec![dir.join("node_modules").join(package)];
|
||||
if dir.file_name() == Some(OsStr::new(".bin"))
|
||||
&& let Some(node_modules) = dir.parent()
|
||||
{
|
||||
candidates.push(node_modules.join(package));
|
||||
}
|
||||
if let Ok(real) = dunce::canonicalize(bin) {
|
||||
candidates.extend(real.ancestors().filter(|a| a.ends_with(package)).map(Path::to_path_buf));
|
||||
}
|
||||
if let Some(prefix) = dir.parent() {
|
||||
candidates.push(prefix.join("lib").join("node_modules").join(package));
|
||||
}
|
||||
candidates.into_iter().find(|c| c.join("package.json").is_file())
|
||||
}
|
||||
@@ -27,13 +27,10 @@ fn server(name: &str) -> LanguageServerConfig {
|
||||
args: vec![],
|
||||
env: BTreeMap::new(),
|
||||
root_markers: vec![],
|
||||
require_root_marker: false,
|
||||
initialization_options: None,
|
||||
settings: None,
|
||||
install_hint: None,
|
||||
connect: None,
|
||||
fallback: false,
|
||||
max_java: None,
|
||||
launch_error: None,
|
||||
}
|
||||
}
|
||||
@@ -208,59 +205,6 @@ fn project_jdk_and_maven_settings() {
|
||||
assert_eq!(project_jdk(tmp.path(), &s), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn language_server_settings_disable_add_and_override() {
|
||||
use crate::apply::{language_servers, server_launch_overrides, server_protocol_overrides, with_custom_servers};
|
||||
use ide_core::settings::LanguageServerSettings;
|
||||
use serde_json::json;
|
||||
|
||||
let mut s = Settings::default();
|
||||
s.language_servers.insert("pylsp".into(), LanguageServerSettings { enabled: false, ..Default::default() });
|
||||
s.language_servers.insert(
|
||||
"ruff".into(),
|
||||
LanguageServerSettings {
|
||||
command: "ruff".into(),
|
||||
args: Some(vec!["server".into()]),
|
||||
languages: vec!["python".into()],
|
||||
root_markers: vec!["pyproject.toml".into()],
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
let defined = [server("basedpyright"), server("pylsp")];
|
||||
let names = |v: Vec<LanguageServerConfig>| v.into_iter().map(|c| c.name).collect::<Vec<_>>();
|
||||
assert_eq!(names(language_servers("python", &defined, &s)), ["basedpyright", "ruff"]);
|
||||
assert_eq!(names(language_servers("rust", &[server("rust-analyzer")], &s)), ["rust-analyzer"]);
|
||||
|
||||
// Listed with the tools even while disabled.
|
||||
let mut langs = ide_language::LanguageRegistry::load(None).unwrap().all();
|
||||
with_custom_servers(&mut langs, &s);
|
||||
let python = langs.iter().find(|l| l.id.as_str() == "python").unwrap();
|
||||
let mut ruff = python.language_servers.iter().find(|c| c.name == "ruff").unwrap().clone();
|
||||
assert_eq!(ruff.root_markers, ["pyproject.toml"]);
|
||||
server_launch_overrides(&mut ruff, &s);
|
||||
assert_eq!((ruff.command.as_str(), ruff.args.as_slice()), ("ruff", &["server".to_string()][..]));
|
||||
|
||||
s.language_servers.insert(
|
||||
"rust-analyzer".into(),
|
||||
LanguageServerSettings {
|
||||
env: BTreeMap::from([("RA_LOG".into(), "info".into())]),
|
||||
initialization_options: Some(json!({ "check": { "command": "clippy" } })),
|
||||
settings: Some(json!({ "rust-analyzer": { "cargo": { "features": "all" } } })),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
let mut ra = server("rust-analyzer");
|
||||
ra.args = vec!["--stdio".into()];
|
||||
ra.initialization_options = Some(toml::Value::Table(toml::toml! { checkOnSave = false }));
|
||||
server_launch_overrides(&mut ra, &s);
|
||||
assert_eq!(ra.args, ["--stdio"], "no args setting keeps the definition's");
|
||||
server_protocol_overrides(&mut ra, &s);
|
||||
assert_eq!(ra.env["RA_LOG"], "info");
|
||||
let init = serde_json::to_value(ra.initialization_options.unwrap()).unwrap();
|
||||
assert_eq!(init, json!({ "checkOnSave": false, "check": { "command": "clippy" } }));
|
||||
assert_eq!(ra.settings, Some(json!({ "rust-analyzer": { "cargo": { "features": "all" } } })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jdtls_jdk_setting() {
|
||||
if cfg!(windows) {
|
||||
@@ -600,101 +544,3 @@ fn vue_language_server_gets_a_typescript_with_the_language_service_api() {
|
||||
let lib = project.join("node_modules/typescript/lib");
|
||||
assert_eq!(cfg.args, [format!("--tsdk={}", lib.to_string_lossy())]);
|
||||
}
|
||||
|
||||
/// An npm shim for `name` in `dir`: `name.cmd` on Windows, an executable elsewhere.
|
||||
fn npm_shim(dir: &Path, name: &str) -> std::path::PathBuf {
|
||||
std::fs::create_dir_all(dir).unwrap();
|
||||
let shim = dir.join(if cfg!(windows) { format!("{name}.cmd") } else { name.to_owned() });
|
||||
std::fs::write(&shim, "").unwrap();
|
||||
#[cfg(unix)]
|
||||
std::fs::set_permissions(&shim, std::os::unix::fs::PermissionsExt::from_mode(0o755)).unwrap();
|
||||
shim
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn angular_language_server_probes_its_own_package_then_the_project() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let tools = tmp.path().join("tools/node_modules");
|
||||
let project = tmp.path().join("app");
|
||||
let ngserver = npm_shim(&tools.join(".bin"), "ngserver");
|
||||
for (p, content) in [
|
||||
(tools.join("@angular/language-server/package.json"), "{}"),
|
||||
(project.join("node_modules/@angular/core/package.json"), r#"{"version":"17.3.0"}"#),
|
||||
(project.join("node_modules/typescript/lib/tsserver.js"), ""),
|
||||
] {
|
||||
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
|
||||
std::fs::write(p, content).unwrap();
|
||||
}
|
||||
let configured = |command: &str, s: &Settings| {
|
||||
let mut cfg = server("angular-language-server");
|
||||
cfg.command = command.into();
|
||||
cfg.args = vec!["--stdio".into()];
|
||||
configure_server(&mut cfg, &project, &project, s);
|
||||
cfg
|
||||
};
|
||||
let probes = format!("{},{}", tools.join("@angular/language-server").to_string_lossy(), project.to_string_lossy());
|
||||
let cfg = configured(&ngserver.to_string_lossy(), &Settings::default());
|
||||
assert_eq!(
|
||||
cfg.args,
|
||||
[
|
||||
"--stdio",
|
||||
"--ngProbeLocations",
|
||||
&probes,
|
||||
"--tsProbeLocations",
|
||||
&probes,
|
||||
"--angularCoreVersion",
|
||||
"17.3.0",
|
||||
"--disableLetSyntax"
|
||||
]
|
||||
);
|
||||
assert_eq!(cfg.launch_error, None);
|
||||
|
||||
// The project's TypeScript when selected.
|
||||
let mut s = Settings::default();
|
||||
s.languages.typescript.version = "workspace".into();
|
||||
let args = configured(&ngserver.to_string_lossy(), &s).args;
|
||||
let tsdk = args.iter().position(|a| a == "--tsdk").map(|i| args[i + 1].clone());
|
||||
assert_eq!(tsdk, Some(project.join("node_modules/typescript/lib").to_string_lossy().into_owned()));
|
||||
|
||||
// Found on the selected Node.js's PATH like the launcher finds it, and
|
||||
// launched from there.
|
||||
let mut s = Settings::default();
|
||||
s.languages.node.interpreter = tools.join(".bin/node").to_string_lossy().into_owned();
|
||||
let cfg = configured("ngserver", &s);
|
||||
assert_eq!(dunce::canonicalize(&cfg.command).unwrap(), dunce::canonicalize(&ngserver).unwrap());
|
||||
assert!(cfg.args.contains(&probes));
|
||||
|
||||
// Without its package the server can't start; not installed, it asks to be.
|
||||
let lone = npm_shim(&tmp.path().join("bin"), "ngserver");
|
||||
let cfg = configured(&lone.to_string_lossy(), &Settings::default());
|
||||
assert!(cfg.launch_error.is_some_and(|m| m.contains("@angular/language-server")));
|
||||
assert_eq!(cfg.args, ["--stdio"]);
|
||||
let cfg = configured(&tmp.path().join("nowhere/ngserver").to_string_lossy(), &Settings::default());
|
||||
assert_eq!((cfg.launch_error, cfg.args), (None, vec!["--stdio".to_owned()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn max_java_picks_an_older_jdk() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let jdk = |major: u32| {
|
||||
let home = dir.path().join(format!("jdk-{major}"));
|
||||
std::fs::create_dir_all(home.join("bin")).unwrap();
|
||||
std::fs::write(home.join("release"), format!("JAVA_VERSION=\"{major}.0.1\"\n")).unwrap();
|
||||
std::fs::write(home.join("bin").join(exe("java")), "").unwrap();
|
||||
crate::java::jdk_at(&home).unwrap()
|
||||
};
|
||||
let (j17, j21, j25) = (jdk(17), jdk(21), jdk(25));
|
||||
let jdks = [j25.clone(), j21.clone(), j17];
|
||||
let mut cfg = LanguageServerConfig { max_java: Some(21), ..server("kotlin-language-server") };
|
||||
cfg.env.insert("JAVA_HOME".into(), j25.home.to_string_lossy().into_owned());
|
||||
crate::java::cap_java_home(&mut cfg, &jdks);
|
||||
assert_eq!(cfg.env["JAVA_HOME"], j21.home.to_string_lossy());
|
||||
|
||||
// A JAVA_HOME that fits, or no limit: left alone.
|
||||
crate::java::cap_java_home(&mut cfg, &[]);
|
||||
assert_eq!(cfg.env["JAVA_HOME"], j21.home.to_string_lossy());
|
||||
let mut free = server("other");
|
||||
free.env.insert("JAVA_HOME".into(), j25.home.to_string_lossy().into_owned());
|
||||
crate::java::cap_java_home(&mut free, &jdks);
|
||||
assert_eq!(free.env["JAVA_HOME"], j25.home.to_string_lossy());
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
//! Vue Language Server (Volar 3): the TypeScript it loads as a library, and the
|
||||
//! `@vue/typescript-plugin` that vtsls' tsserver hosts for it (hybrid mode).
|
||||
|
||||
use crate::npm::{find_command, package_dir};
|
||||
use std::ffi::OsStr;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
@@ -15,6 +14,38 @@ pub(crate) fn has_ts_api(lib: &Path) -> bool {
|
||||
lib.join("typescript.js").is_file()
|
||||
}
|
||||
|
||||
/// `command` as given (a path) or found on `path`, npm shims included.
|
||||
fn find_command(command: &str, path: &OsStr) -> Option<PathBuf> {
|
||||
let p = Path::new(command);
|
||||
if p.is_absolute() {
|
||||
return p.is_file().then(|| p.to_path_buf());
|
||||
}
|
||||
let exts: &[&str] = if cfg!(windows) { &[".cmd", ".exe", ""] } else { &[""] };
|
||||
std::env::split_paths(path)
|
||||
.flat_map(|d| exts.iter().map(move |e| d.join(format!("{command}{e}"))))
|
||||
.find(|c| c.is_file())
|
||||
}
|
||||
|
||||
/// The npm package an executable comes from: next to a `node_modules/.bin` shim
|
||||
/// (the IDE's tools dir, a project), a Windows global shim (`%APPDATA%\npm`), a
|
||||
/// Unix global `<prefix>/bin` or a symlink into the package.
|
||||
fn package_dir(bin: &Path, package: &str) -> Option<PathBuf> {
|
||||
let dir = bin.parent()?;
|
||||
let mut candidates = vec![dir.join("node_modules").join(package)];
|
||||
if dir.file_name() == Some(OsStr::new(".bin"))
|
||||
&& let Some(node_modules) = dir.parent()
|
||||
{
|
||||
candidates.push(node_modules.join(package));
|
||||
}
|
||||
if let Ok(real) = dunce::canonicalize(bin) {
|
||||
candidates.extend(real.ancestors().filter(|a| a.ends_with(package)).map(Path::to_path_buf));
|
||||
}
|
||||
if let Some(prefix) = dir.parent() {
|
||||
candidates.push(prefix.join("lib").join("node_modules").join(package));
|
||||
}
|
||||
candidates.into_iter().find(|c| c.join("package.json").is_file())
|
||||
}
|
||||
|
||||
/// `@vue/language-server`'s directory for the `vue-language-server` command.
|
||||
pub(crate) fn server_package(command: &str, path: &OsStr) -> Option<PathBuf> {
|
||||
package_dir(&find_command(command, path)?, PACKAGE)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "ide-spell"
|
||||
description = "Spell checking (Proofreading › Typo): word extraction from comments, strings and declared names, Hunspell en_US / en_GB dictionary, programming terms, user dictionaries"
|
||||
description = "Spell checking (Proofreading › Typo): word extraction from comments, strings and declared names, Hunspell en_US dictionary, user dictionaries"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2017-2025 Street Side Software <[email protected]>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
@@ -1,246 +0,0 @@
|
||||
# Tool and file names, abbreviations and words common in code the other lists lack.
|
||||
# Accepted on their own, never as part of a compound (`conf` would pass `conflift`).
|
||||
# One lowercase word per line; checked case-insensitively.
|
||||
accel
|
||||
acked
|
||||
adoc
|
||||
adoptium
|
||||
allman
|
||||
askpass
|
||||
assignees
|
||||
avif
|
||||
basedpyright
|
||||
bytea
|
||||
canceller
|
||||
cand
|
||||
cands
|
||||
cjs
|
||||
closable
|
||||
clsx
|
||||
codelldb
|
||||
colima
|
||||
commitish
|
||||
condvar
|
||||
conf
|
||||
conftest
|
||||
conns
|
||||
cte
|
||||
ctes
|
||||
cts
|
||||
customizations
|
||||
dap
|
||||
ddl
|
||||
debuggee
|
||||
decapitalize
|
||||
deemphasize
|
||||
defmodule
|
||||
desync
|
||||
dialogs
|
||||
dic
|
||||
disassembler
|
||||
dists
|
||||
dlsym
|
||||
dlv
|
||||
dnd
|
||||
dup
|
||||
emmet
|
||||
envrc
|
||||
eslintrc
|
||||
expando
|
||||
exs
|
||||
fallbacks
|
||||
fixup
|
||||
fori
|
||||
gdscript
|
||||
gdshader
|
||||
gfm
|
||||
gitattributes
|
||||
gitoxide
|
||||
gix
|
||||
glyphs
|
||||
gomod
|
||||
gopath
|
||||
gopls
|
||||
goroot
|
||||
gpgsign
|
||||
gradle
|
||||
gradlew
|
||||
graphql
|
||||
guice
|
||||
hamcrest
|
||||
haspopup
|
||||
hcl
|
||||
hotswap
|
||||
htdocs
|
||||
hxx
|
||||
ideavimrc
|
||||
ime
|
||||
inflight
|
||||
inlines
|
||||
inplace
|
||||
integrations
|
||||
intelephense
|
||||
interp
|
||||
inv
|
||||
ipynb
|
||||
jacoco
|
||||
javac
|
||||
javaw
|
||||
javax
|
||||
jdt
|
||||
jdtls
|
||||
jdwp
|
||||
jenkinsfile
|
||||
jre
|
||||
jsdom
|
||||
jshell
|
||||
jsonl
|
||||
kapt
|
||||
kotlinc
|
||||
kts
|
||||
labelledby
|
||||
latencies
|
||||
lcov
|
||||
lemminx
|
||||
lexically
|
||||
lezer
|
||||
linkify
|
||||
lldb
|
||||
lockb
|
||||
logpoint
|
||||
logpoints
|
||||
lombok
|
||||
lossily
|
||||
lossy
|
||||
mapleader
|
||||
matview
|
||||
memmem
|
||||
menlo
|
||||
menuitemcheckbox
|
||||
mjs
|
||||
msvc
|
||||
mts
|
||||
mvn
|
||||
mvnw
|
||||
natively
|
||||
nextest
|
||||
nocapture
|
||||
nodelay
|
||||
nonmatching
|
||||
noopener
|
||||
noreferrer
|
||||
noremap
|
||||
notif
|
||||
notnull
|
||||
nvm
|
||||
ord
|
||||
osgi
|
||||
pathing
|
||||
pdm
|
||||
pipfile
|
||||
pred
|
||||
preds
|
||||
prunable
|
||||
psvm
|
||||
publickey
|
||||
pwa
|
||||
pyc
|
||||
pycache
|
||||
pyenv
|
||||
pyi
|
||||
pylsp
|
||||
pyvenv
|
||||
recency
|
||||
recents
|
||||
redb
|
||||
redecl
|
||||
reformats
|
||||
reinstalls
|
||||
rekey
|
||||
replit
|
||||
rerunnable
|
||||
rescan
|
||||
restorable
|
||||
retarget
|
||||
rfind
|
||||
rollup
|
||||
rsplit
|
||||
rsplitn
|
||||
rss
|
||||
rst
|
||||
runserver
|
||||
sbt
|
||||
scm
|
||||
sdkman
|
||||
segs
|
||||
sel
|
||||
severities
|
||||
shorthands
|
||||
sig
|
||||
sigil
|
||||
solarized
|
||||
sout
|
||||
specta
|
||||
splitn
|
||||
storable
|
||||
stty
|
||||
subclassed
|
||||
subsequence
|
||||
subsequences
|
||||
subtest
|
||||
subtests
|
||||
supabase
|
||||
sym
|
||||
syms
|
||||
taplo
|
||||
tauri
|
||||
tcpip
|
||||
tcsh
|
||||
temurin
|
||||
texlab
|
||||
tgz
|
||||
timescaledb
|
||||
timestamptz
|
||||
toks
|
||||
topo
|
||||
tpl
|
||||
tsdk
|
||||
tsv
|
||||
unclosed
|
||||
unformatted
|
||||
unlisten
|
||||
unmarking
|
||||
unmatch
|
||||
unminimize
|
||||
unqueue
|
||||
unshelve
|
||||
unsplit
|
||||
unsub
|
||||
unsubs
|
||||
untag
|
||||
untagged
|
||||
uptime
|
||||
vcs
|
||||
vendored
|
||||
vimrc
|
||||
visibilities
|
||||
vite
|
||||
vitest
|
||||
vmargs
|
||||
volar
|
||||
vsix
|
||||
vtsls
|
||||
wasi
|
||||
wasmtime
|
||||
webflux
|
||||
webmanifest
|
||||
wip
|
||||
xcrun
|
||||
xdebug
|
||||
zig
|
||||
zlogin
|
||||
zls
|
||||
zprofile
|
||||
zshenv
|
||||
zshrc
|
||||
zustand
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -551,15 +551,3 @@ vulkan
|
||||
wgpu
|
||||
woff
|
||||
woff2
|
||||
breakpoint
|
||||
sku
|
||||
dropdown
|
||||
navbar
|
||||
superclass
|
||||
typedef
|
||||
eslint
|
||||
unittest
|
||||
jvm
|
||||
jdk
|
||||
ux
|
||||
endpoint
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Spell checking for IDEA's "Proofreading › Typo" inspection: words of
|
||||
//! comments, string literals and declared names (regions come from the
|
||||
//! syntax layer), checked against the bundled en_US / en_GB Hunspell dictionary, a
|
||||
//! syntax layer), checked against the bundled en_US Hunspell dictionary, a
|
||||
//! list of programming terms and the user's accepted words and dictionaries.
|
||||
//! Regular agent nouns of known words (`checkpointer`) pass everywhere; in
|
||||
//! identifiers so do closed compounds of known words (`codebase`).
|
||||
@@ -98,17 +98,12 @@ impl SpellScope {
|
||||
/// At most this many typos are reported per text.
|
||||
pub const MAX_TYPOS: usize = 2000;
|
||||
|
||||
/// The en_GB entries en_US lacks (`colour`, `behaviour`, `normalise`), in the
|
||||
/// same affix scheme: either spelling passes.
|
||||
const EN_GB_EXTRA: &str = include_str!("dict/en_GB-extra.dic");
|
||||
|
||||
/// The en_US dictionary plus [`EN_GB_EXTRA`].
|
||||
fn english() -> &'static spellbook::Dictionary {
|
||||
static DICT: OnceLock<spellbook::Dictionary> = OnceLock::new();
|
||||
DICT.get_or_init(|| {
|
||||
let aff = include_str!("dict/en_US.aff");
|
||||
let dic = format!("{}{EN_GB_EXTRA}", include_str!("dict/en_US.dic"));
|
||||
spellbook::Dictionary::new(aff, &dic).expect("bundled en dictionary parses")
|
||||
let dic = include_str!("dict/en_US.dic");
|
||||
spellbook::Dictionary::new(aff, dic).expect("bundled en_US dictionary parses")
|
||||
})
|
||||
}
|
||||
|
||||
@@ -119,7 +114,6 @@ fn lemmas() -> &'static HashSet<&'static str> {
|
||||
include_str!("dict/en_US.dic")
|
||||
.lines()
|
||||
.skip(1)
|
||||
.chain(EN_GB_EXTRA.lines())
|
||||
.map(|l| l.split('/').next().unwrap_or(l).trim())
|
||||
.filter(|w| !w.is_empty() && w.chars().all(|c| c.is_ascii_lowercase()))
|
||||
.collect()
|
||||
@@ -142,12 +136,13 @@ fn doubles_final_consonant(stem: &str) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether dropping one letter or swapping two adjacent ones gives a `known`
|
||||
/// Whether dropping one letter or swapping two adjacent ones gives a dictionary
|
||||
/// word: then a compound (`writ`+`ting`) is more likely a typo of
|
||||
/// it (`writing`), as Hunspell's CHECKCOMPOUNDREP reasons.
|
||||
fn near_word(lower: &str, known: impl Fn(&str) -> bool) -> bool {
|
||||
fn near_word(lower: &str) -> bool {
|
||||
let b = lower.as_bytes();
|
||||
let check = |v: &[u8]| std::str::from_utf8(v).is_ok_and(&known);
|
||||
let dict = english();
|
||||
let check = |v: &[u8]| std::str::from_utf8(v).is_ok_and(|w| dict.check(w));
|
||||
(0..b.len()).any(|i| check(&[&b[..i], &b[i + 1..]].concat()))
|
||||
|| (0..b.len().saturating_sub(1)).any(|i| {
|
||||
let mut v = b.to_vec();
|
||||
@@ -156,43 +151,17 @@ fn near_word(lower: &str, known: impl Fn(&str) -> bool) -> bool {
|
||||
})
|
||||
}
|
||||
|
||||
fn term_list(text: &'static str) -> HashSet<&'static str> {
|
||||
text.lines().map(str::trim).filter(|l| !l.is_empty() && !l.starts_with('#')).collect()
|
||||
}
|
||||
|
||||
/// Hand-picked programming terms: short ones (`url`) may be part of a compound.
|
||||
fn curated_terms() -> &'static HashSet<&'static str> {
|
||||
static TERMS: OnceLock<HashSet<&'static str>> = OnceLock::new();
|
||||
TERMS.get_or_init(|| term_list(include_str!("dict/software.txt")))
|
||||
}
|
||||
|
||||
/// Imported programming terms, tool and library names, and abbreviations:
|
||||
/// never part of a compound.
|
||||
fn other_terms() -> &'static HashSet<&'static str> {
|
||||
fn software_terms() -> &'static HashSet<&'static str> {
|
||||
static TERMS: OnceLock<HashSet<&'static str>> = OnceLock::new();
|
||||
TERMS.get_or_init(|| {
|
||||
let mut terms = term_list(include_str!("dict/cspell-terms.txt"));
|
||||
terms.extend(term_list(include_str!("dict/code-words.txt")));
|
||||
terms
|
||||
include_str!("dict/software.txt")
|
||||
.lines()
|
||||
.map(str::trim)
|
||||
.filter(|l| !l.is_empty() && !l.starts_with('#'))
|
||||
.collect()
|
||||
})
|
||||
}
|
||||
|
||||
fn term(lower: &str) -> bool {
|
||||
curated_terms().contains(lower) || other_terms().contains(lower)
|
||||
}
|
||||
|
||||
/// A software term, or the plural of one Hunspell doesn't know (`endpoints`,
|
||||
/// `regexes`; not `filess`, `contextes`, `checkings`). [`other_terms`] need
|
||||
/// 4+ letters for that (`acses` stays flagged).
|
||||
fn software_term(lower: &str) -> bool {
|
||||
let plural_of = |w: &str| (curated_terms().contains(w) || w.len() >= MIN_PART && term(w)) && !english().check(w);
|
||||
term(lower)
|
||||
|| lower.strip_suffix('s').is_some_and(|w| !w.ends_with('s') && plural_of(w))
|
||||
|| lower
|
||||
.strip_suffix("es")
|
||||
.is_some_and(|w| ["s", "x", "z", "ch", "sh"].iter().any(|e| w.ends_with(e)) && plural_of(w))
|
||||
}
|
||||
|
||||
/// Words of a custom dictionary file: a plain word list or a Hunspell `.dic`
|
||||
/// (leading count line and `/FLAGS` ignored). Cached by modification time.
|
||||
fn dictionary_file(path: &Path) -> Arc<HashSet<String>> {
|
||||
@@ -247,15 +216,11 @@ impl Speller {
|
||||
|
||||
/// Whether `word` (of prose, a comment or a string) is spelt correctly.
|
||||
/// Case is forgiven the way identifiers need it: `url` passes for `URL`,
|
||||
/// `paris` for `Paris`. Possessives (`backend's`), regular agent nouns
|
||||
/// (`checkpointer`, `serializers`) and `-ed` / `-ing` / `-able` forms of
|
||||
/// programming terms (`stringified`) pass too.
|
||||
/// `paris` for `Paris`. Regular agent nouns of known words pass too
|
||||
/// (`checkpointer`, `serializers`).
|
||||
pub fn is_correct(&self, word: &str) -> bool {
|
||||
if let Some(base) = word.strip_suffix("'s") {
|
||||
return self.is_correct(base);
|
||||
}
|
||||
let lower = word.to_lowercase();
|
||||
self.listed(word, &lower) || self.agent_noun(&lower) || self.term_form(&lower)
|
||||
self.listed(word, &lower) || self.agent_noun(&lower)
|
||||
}
|
||||
|
||||
/// [`Self::is_correct`] for a part of an identifier, which may also be two
|
||||
@@ -265,7 +230,9 @@ impl Speller {
|
||||
}
|
||||
|
||||
fn user_word(&self, lower: &str) -> bool {
|
||||
self.accepted.contains(lower) || software_term(lower) || self.custom.iter().any(|d| d.contains(lower))
|
||||
self.accepted.contains(lower)
|
||||
|| software_terms().contains(lower)
|
||||
|| self.custom.iter().any(|d| d.contains(lower))
|
||||
}
|
||||
|
||||
/// In a dictionary, in any case style.
|
||||
@@ -288,63 +255,30 @@ impl Speller {
|
||||
let singular = lower.strip_suffix('s').unwrap_or(lower);
|
||||
let Some(before_r) = singular.strip_suffix('r') else { return false };
|
||||
let Some(before_er) = before_r.strip_suffix('e') else { return false };
|
||||
let mut stems = vec![before_r.to_string()];
|
||||
// (stem, root the `-or` noun would be built on)
|
||||
let mut stems = vec![(before_r.to_string(), before_er)];
|
||||
if let Some(y) = before_er.strip_suffix('i') {
|
||||
stems.push(format!("{y}y"));
|
||||
stems.push((format!("{y}y"), before_er));
|
||||
} else if !before_er.ends_with('e') && !doubles_final_consonant(before_er) {
|
||||
stems.push(before_er.to_string());
|
||||
stems.push((before_er.to_string(), before_er));
|
||||
}
|
||||
let or_noun = format!("{before_er}or");
|
||||
stems
|
||||
.into_iter()
|
||||
.any(|stem| stem.len() >= MIN_PART && (lemmas().contains(stem.as_str()) || self.term_stem(&stem)))
|
||||
&& !self.listed(&or_noun, &or_noun)
|
||||
}
|
||||
|
||||
/// A programming term or accepted word of 5+ letters Hunspell doesn't know
|
||||
/// (`stringify`; not `calls` or `calc`), to derive other words from.
|
||||
fn term_stem(&self, s: &str) -> bool {
|
||||
s.len() > MIN_PART && self.user_word(s) && !english().check(s)
|
||||
}
|
||||
|
||||
/// `<term>ed` / `<term>ing` / `<term>able` of a programming term or an
|
||||
/// accepted word of 5+ letters: `stringified` (stringify), `memoizing`
|
||||
/// (memoize), `upserted`. Dictionary words only take the endings Hunspell
|
||||
/// knows: `falled`, `quiting` stay flagged. Not when one letter off a known
|
||||
/// word (`preprocesssing`).
|
||||
fn term_form(&self, lower: &str) -> bool {
|
||||
if !lower.bytes().all(|c| c.is_ascii_lowercase()) {
|
||||
return false;
|
||||
}
|
||||
let stem = |s: &str| self.term_stem(s);
|
||||
let derived = ["ed", "ing", "able"].into_iter().any(|suffix| {
|
||||
let Some(root) = lower.strip_suffix(suffix) else { return false };
|
||||
let b = root.as_bytes();
|
||||
(stem(root) && !doubles_final_consonant(root))
|
||||
|| stem(&format!("{root}e"))
|
||||
|| (suffix != "ing" && root.strip_suffix('i').is_some_and(|y| stem(&format!("{y}y"))))
|
||||
|| (b.len() > 2 && b[b.len() - 1] == b[b.len() - 2] && stem(&root[..root.len() - 1]))
|
||||
});
|
||||
derived && !near_word(lower, |w| english().check(w) || self.user_word(w))
|
||||
stems.into_iter().any(|(stem, root)| {
|
||||
stem.len() >= MIN_PART
|
||||
&& (lemmas().contains(stem.as_str()) || self.user_word(&stem))
|
||||
&& !english().check(&format!("{root}or"))
|
||||
})
|
||||
}
|
||||
|
||||
/// Two known words run together, each at least [`MIN_PART`] letters (or a
|
||||
/// hand-picked or accepted 3-letter term: `urlpath`). Proper nouns and
|
||||
/// [`other_terms`] don't count (`guid` + `lines` would pass `guidlines`).
|
||||
/// 3-letter programming term: `urlpath`). Proper nouns don't count.
|
||||
fn compound(&self, lower: &str) -> bool {
|
||||
if lower.len() < 6 || !lower.bytes().all(|c| c.is_ascii_lowercase()) || NOT_COMPOUNDS.contains(&lower) {
|
||||
return false;
|
||||
}
|
||||
let known = |p: &str| {
|
||||
self.accepted.contains(p) || curated_terms().contains(p) || self.custom.iter().any(|d| d.contains(p))
|
||||
let part = |p: &str| {
|
||||
(p.len() >= 3 && self.user_word(p)) || (p.len() >= MIN_PART && (english().check(p) || self.agent_noun(p)))
|
||||
};
|
||||
let part = |p: &str| match p.len() {
|
||||
0..3 => false,
|
||||
3 => known(p),
|
||||
_ => known(p) || english().check(p) || self.agent_noun(p),
|
||||
};
|
||||
(3..=lower.len() - 3).any(|i| part(&lower[..i]) && part(&lower[i..]))
|
||||
&& !near_word(lower, |w| english().check(w))
|
||||
(3..=lower.len() - 3).any(|i| part(&lower[..i]) && part(&lower[i..])) && !near_word(lower)
|
||||
}
|
||||
|
||||
/// Replacements for `word`, best first, in the word's case style.
|
||||
@@ -361,15 +295,6 @@ impl Speller {
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether the letter run `w` was split from is a known term as a whole:
|
||||
/// `IntelliJ` (`Intelli` + `J`), `PostgreSQL` (`Postgre` + `SQL`).
|
||||
fn known_run(&self, text: &str, w: &WordSpan) -> bool {
|
||||
let start =
|
||||
text[..w.start].char_indices().rev().find(|(_, c)| !c.is_alphabetic()).map_or(0, |(i, c)| i + c.len_utf8());
|
||||
let end = text[w.end..].find(|c: char| !c.is_alphabetic()).map_or(text.len(), |i| w.end + i);
|
||||
(start, end) != (w.start, w.end) && self.user_word(&text[start..end].to_lowercase())
|
||||
}
|
||||
|
||||
/// Misspelt words of `regions` (document order) in `text`; `None` when
|
||||
/// `cancelled` fires.
|
||||
pub fn check(&self, text: &str, regions: &[Region], cancelled: &dyn Fn() -> bool) -> Option<Vec<Typo>> {
|
||||
@@ -388,7 +313,7 @@ impl Speller {
|
||||
let ok = *verdicts
|
||||
.entry((word, name))
|
||||
.or_insert_with(|| if name { self.is_correct_identifier(word) } else { self.is_correct(word) });
|
||||
if !ok && !self.known_run(text, w) {
|
||||
if !ok {
|
||||
bad.push((*w, r.kind));
|
||||
}
|
||||
}
|
||||
@@ -505,14 +430,6 @@ mod tests {
|
||||
assert_eq!(typos[0].range, Range::new(Pos::new(0, 3), Pos::new(0, 10)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn misspellings_after_unicode_punctuation_do_not_panic() {
|
||||
let text = "// 状态:Recieve and 【mesage】 😀writting";
|
||||
let typos = Speller::default().check(text, &whole(text, RegionKind::Comment), &|| false).unwrap();
|
||||
let words: Vec<_> = typos.iter().map(|t| t.word.as_str()).collect();
|
||||
assert_eq!(words, ["Recieve", "mesage", "writting"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identifiers_forgive_case_and_terms() {
|
||||
let s = Speller::default();
|
||||
@@ -522,53 +439,6 @@ mod tests {
|
||||
assert!(!s.is_correct("lenght"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn software_terms_and_their_plurals() {
|
||||
let s = Speller::default();
|
||||
for ok in ["breakpoint", "breakpoints", "endpoints", "datasets", "regexes"] {
|
||||
assert!(s.is_correct(ok), "{ok}");
|
||||
}
|
||||
for ok in
|
||||
["stringify", "instanceof", "keydown", "submenu", "truthy", "vitest", "gradle", "unstaged", "rebasing"]
|
||||
{
|
||||
assert!(s.is_correct(ok), "{ok}");
|
||||
}
|
||||
for bad in ["filess", "contextes", "checkings", "acses"] {
|
||||
assert!(!s.is_correct(bad), "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn british_spellings() {
|
||||
let s = Speller::default();
|
||||
for ok in ["colour", "behaviours", "normalised", "centred", "analyse", "cancelled", "dialogs"] {
|
||||
assert!(s.is_correct(ok), "{ok}");
|
||||
}
|
||||
for bad in ["colur", "behavour", "normalsed"] {
|
||||
assert!(!s.is_correct(bad), "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn split_terms_checked_whole() {
|
||||
let s = Speller::default();
|
||||
let text = "// Open IntelliJ or PostgreSQL, not Intelli alone";
|
||||
let words: Vec<_> =
|
||||
s.check(text, &whole(text, RegionKind::Comment), &|| false).unwrap().into_iter().map(|t| t.word).collect();
|
||||
assert_eq!(words, ["Intelli"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn possessives_and_term_forms() {
|
||||
let s = Speller::default();
|
||||
for ok in ["backend's", "commit's", "stringified", "memoizing", "upserted"] {
|
||||
assert!(s.is_correct(ok), "{ok}");
|
||||
}
|
||||
for bad in ["recieve's", "falled", "quiting", "preprocesssing", "perfer", "callser"] {
|
||||
assert!(!s.is_correct(bad), "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn agent_nouns_of_known_words() {
|
||||
let s = Speller::default();
|
||||
@@ -587,7 +457,7 @@ mod tests {
|
||||
for ok in ["filepath", "dataframe", "username", "codebase", "pathname", "urlpath", "timestampfile"] {
|
||||
assert!(s.is_correct_identifier(ok), "{ok}");
|
||||
}
|
||||
assert!(!s.is_correct("timestampfile"));
|
||||
assert!(!s.is_correct("dataframe"));
|
||||
for bad in ["eachother", "everytime", "publically", "mesage", "lenght", "recieve", "comming", "withold"] {
|
||||
assert!(!s.is_correct_identifier(bad), "{bad}");
|
||||
}
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
//! Shell integration (Settings › Tools › Terminal › Shell integration): the
|
||||
//! shell reports its working directory (OSC 7) at every prompt, so links and
|
||||
//! new splits resolve against the directory the user `cd`-ed into, and marks
|
||||
//! where a command starts and ends (OSC 133 C / D), so the tab shows the
|
||||
//! running program's title only while one runs.
|
||||
//! new splits resolve against the directory the user `cd`-ed into.
|
||||
//!
|
||||
//! zsh starts with `ZDOTDIR` pointing at generated startup files that source
|
||||
//! the user's own ones first; bash gets an `--init-file` that replays the
|
||||
@@ -31,11 +29,8 @@ ZDOTDIR=$OPENIDEA_USER_ZDOTDIR
|
||||
[[ -f $ZDOTDIR/.zshrc ]] && . $ZDOTDIR/.zshrc
|
||||
OPENIDEA_USER_ZDOTDIR=$ZDOTDIR
|
||||
ZDOTDIR=$_openidea_dir
|
||||
_openidea_osc7() { printf '\e]133;D\a\e]7;file://%s%s\a' "${HOST}" "${PWD}" }
|
||||
_openidea_preexec() { printf '\e]133;C\a' }
|
||||
# First, so the command counts as finished before other hooks set the prompt's title.
|
||||
precmd_functions=(_openidea_osc7 ${precmd_functions:#_openidea_osc7})
|
||||
preexec_functions+=(_openidea_preexec)
|
||||
_openidea_osc7() { printf '\e]7;file://%s%s\a' "${HOST}" "${PWD}" }
|
||||
autoload -Uz add-zsh-hook 2>/dev/null && add-zsh-hook precmd _openidea_osc7
|
||||
if [[ ! -o login ]]; then
|
||||
ZDOTDIR=$OPENIDEA_USER_ZDOTDIR
|
||||
unset OPENIDEA_USER_ZDOTDIR _openidea_dir
|
||||
@@ -59,22 +54,15 @@ if [ "${OPENIDEA_LOGIN:-}" = 1 ]; then
|
||||
else
|
||||
[ -f ~/.bashrc ] && . ~/.bashrc
|
||||
fi
|
||||
__openidea_osc7() { printf '\e]133;D\a\e]7;file://%s%s\a' "${HOSTNAME}" "${PWD}"; }
|
||||
__openidea_osc7() { printf '\e]7;file://%s%s\a' "${HOSTNAME}" "${PWD}"; }
|
||||
case ";${PROMPT_COMMAND:-};" in
|
||||
*";__openidea_osc7;"*) ;;
|
||||
*) PROMPT_COMMAND="__openidea_osc7${PROMPT_COMMAND:+;$PROMPT_COMMAND}" ;;
|
||||
esac
|
||||
# PS0 (bash 4.4+) prints before each command runs.
|
||||
case "${PS0:-}" in
|
||||
*'133;C'*) ;;
|
||||
*) PS0="${PS0:-}\e]133;C\a" ;;
|
||||
esac
|
||||
"#;
|
||||
|
||||
const FISH_INIT: &str = concat!(
|
||||
r#"function __openidea_osc7 --on-event fish_prompt; printf '\e]133;D\a\e]7;file://%s%s\a' (hostname) $PWD; end; "#,
|
||||
r#"function __openidea_preexec --on-event fish_preexec; printf '\e]133;C\a'; end"#,
|
||||
);
|
||||
const FISH_INIT: &str =
|
||||
r#"function __openidea_osc7 --on-event fish_prompt; printf '\e]7;file://%s%s\a' (hostname) $PWD; end"#;
|
||||
|
||||
/// Directory holding the generated startup files (written on demand).
|
||||
fn scripts_dir() -> PathBuf {
|
||||
|
||||
@@ -97,12 +97,6 @@ impl TerminalManager {
|
||||
let mut cmd = CommandBuilder::new(&shell);
|
||||
cmd.args(&args);
|
||||
cmd.cwd(resolve_cwd(&options.cwd));
|
||||
for (k, v) in ide_core::process::host_env_fixes() {
|
||||
match v {
|
||||
Some(v) => cmd.env(k, v),
|
||||
None => cmd.env_remove(k),
|
||||
}
|
||||
}
|
||||
for (k, v) in env {
|
||||
cmd.env(k, v);
|
||||
}
|
||||
|
||||
@@ -113,7 +113,7 @@ fn extract_zip(archive: &Path, dest: &Path) -> IdeResult<()> {
|
||||
/// `.tar.xz` goes through the system `tar` (bsdtar on macOS/Windows, GNU tar + xz on Linux).
|
||||
fn extract_tar_xz(archive: &Path, dest: &Path) -> IdeResult<()> {
|
||||
let tar = which::which("tar").map_err(|_| IdeError::unavailable("`tar` is required to unpack .tar.xz archives"))?;
|
||||
let out = ide_core::process::prepare(&mut std::process::Command::new(tar))
|
||||
let out = ide_core::process::no_window(&mut std::process::Command::new(tar))
|
||||
.arg("-xJf")
|
||||
.arg(archive)
|
||||
.arg("-C")
|
||||
|
||||
@@ -72,10 +72,6 @@ pub struct ToolInfo {
|
||||
pub homepage: Option<String>,
|
||||
/// Why the executable chosen in settings cannot be used (status is then `Missing`).
|
||||
pub custom_error: Option<String>,
|
||||
/// A language server's arguments from its language definition.
|
||||
pub default_args: Vec<String>,
|
||||
/// A language server's `initializationOptions` from its language definition, as JSON text.
|
||||
pub default_initialization_options: Option<String>,
|
||||
}
|
||||
|
||||
/// Streamed install progress.
|
||||
@@ -165,7 +161,7 @@ pub fn extend_process_path(app_data: &Path) {
|
||||
/// `PATH` plus the usual per-user tool locations (GUI apps on macOS start with a minimal `PATH`).
|
||||
pub fn default_search_path() -> OsString {
|
||||
let mut dirs: Vec<PathBuf> =
|
||||
ide_core::process::host_var_os("PATH").map(|p| std::env::split_paths(&p).collect()).unwrap_or_default();
|
||||
std::env::var_os("PATH").map(|p| std::env::split_paths(&p).collect()).unwrap_or_default();
|
||||
if let Some(home) = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).map(PathBuf::from) {
|
||||
for rel in [".cargo/bin", ".local/bin", "go/bin", ".bun/bin", ".volta/bin", ".npm-global/bin", "Library/pnpm"] {
|
||||
dirs.push(home.join(rel));
|
||||
@@ -213,8 +209,6 @@ struct Usage {
|
||||
command: Option<String>,
|
||||
kind: Option<ToolKind>,
|
||||
install_hint: Option<String>,
|
||||
args: Vec<String>,
|
||||
initialization_options: Option<String>,
|
||||
}
|
||||
|
||||
fn usages(langs: &[LanguageConfig]) -> BTreeMap<String, Usage> {
|
||||
@@ -249,14 +243,6 @@ fn usages(langs: &[LanguageConfig]) -> BTreeMap<String, Usage> {
|
||||
let languages = map.get(*host).map(|u| u.languages.clone()).unwrap_or_default();
|
||||
map.entry(plugin.to_string()).or_default().languages = languages;
|
||||
}
|
||||
// A server's defaults come from the first definition using it.
|
||||
for s in langs.iter().flat_map(|l| &l.language_servers).rev() {
|
||||
if let Some(u) = map.get_mut(&s.name) {
|
||||
u.args = s.args.clone();
|
||||
u.initialization_options =
|
||||
s.initialization_options.as_ref().and_then(|v| serde_json::to_value(v).ok()).map(|v| v.to_string());
|
||||
}
|
||||
}
|
||||
map
|
||||
}
|
||||
|
||||
@@ -343,7 +329,7 @@ impl Tools {
|
||||
|
||||
fn command(&self, program: impl AsRef<std::ffi::OsStr>) -> Command {
|
||||
let mut cmd = Command::new(program);
|
||||
ide_core::process::prepare(&mut cmd).env("PATH", &self.child_path);
|
||||
ide_core::process::no_window(&mut cmd).env("PATH", &self.child_path);
|
||||
cmd
|
||||
}
|
||||
|
||||
@@ -469,8 +455,6 @@ impl Tools {
|
||||
install_hint,
|
||||
homepage: None,
|
||||
custom_error: None,
|
||||
default_args: u.args.clone(),
|
||||
default_initialization_options: u.initialization_options.clone(),
|
||||
})
|
||||
.map(|info| self.apply_custom(info, None));
|
||||
};
|
||||
@@ -493,8 +477,6 @@ impl Tools {
|
||||
install_hint,
|
||||
homepage: Some(spec.homepage.to_string()),
|
||||
custom_error: None,
|
||||
default_args: usage.map(|u| u.args.clone()).unwrap_or_default(),
|
||||
default_initialization_options: usage.and_then(|u| u.initialization_options.clone()),
|
||||
})
|
||||
.map(|info| self.apply_custom(info, Some(spec)))
|
||||
}
|
||||
|
||||
@@ -48,7 +48,7 @@ pub fn run_streamed(cmd: Command, cancel: &CancellationToken, emit: Emit) -> Ide
|
||||
/// Like [`run_streamed`] but returns `(success, output, status text)` instead of failing on a non-zero exit.
|
||||
pub fn run_collect(mut cmd: Command, cancel: &CancellationToken, emit: Emit) -> IdeResult<(bool, String, String)> {
|
||||
emit(InstallEvent::Line { text: format!("$ {}", describe(&cmd)) });
|
||||
ide_core::process::prepare(&mut cmd).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
ide_core::process::no_window(&mut cmd).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
let mut child = cmd.spawn().map_err(|e| IdeError::unavailable(format!("cannot run {}: {e}", describe(&cmd))))?;
|
||||
let (tx, rx) = mpsc::channel::<String>();
|
||||
let pipes: [Option<Box<dyn Read + Send>>; 2] = [
|
||||
@@ -94,7 +94,7 @@ pub fn run_collect(mut cmd: Command, cancel: &CancellationToken, emit: Emit) ->
|
||||
|
||||
/// Runs `cmd` to completion within `timeout`; returns (success, stdout + stderr).
|
||||
pub fn run_quiet(mut cmd: Command, timeout: Duration) -> Option<(bool, String)> {
|
||||
ide_core::process::prepare(&mut cmd).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
ide_core::process::no_window(&mut cmd).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
let mut child = cmd.spawn().ok()?;
|
||||
let mut stdout = child.stdout.take()?;
|
||||
let mut stderr = child.stderr.take()?;
|
||||
@@ -161,7 +161,7 @@ impl Http {
|
||||
|
||||
fn base(&self, url: &str) -> Command {
|
||||
let mut cmd = Command::new(&self.curl);
|
||||
ide_core::process::prepare(&mut cmd);
|
||||
ide_core::process::no_window(&mut cmd);
|
||||
cmd.args(["-fsSL", "--retry", "2", "--connect-timeout", "20", "-A", "openidea"]);
|
||||
if url.starts_with("https://api.github.com/")
|
||||
&& let Ok(token) = std::env::var("GITHUB_TOKEN").or_else(|_| std::env::var("GH_TOKEN"))
|
||||
|
||||
@@ -167,16 +167,6 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
homepage: "https://docs.basedpyright.com",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "ty",
|
||||
display: "ty (Python)",
|
||||
kind: LanguageServer,
|
||||
commands: &["ty"],
|
||||
method: Method::PipVenv { package: "ty" },
|
||||
version: ver("ty"),
|
||||
homepage: "https://docs.astral.sh/ty/",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "bash-language-server",
|
||||
display: "Bash Language Server",
|
||||
@@ -257,17 +247,6 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
homepage: "https://github.com/vuejs/language-tools",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "angular-language-server",
|
||||
display: "Angular Language Server",
|
||||
kind: LanguageServer,
|
||||
commands: &["ngserver"],
|
||||
// Brings the TypeScript and `@angular/language-service` it loads.
|
||||
method: Method::Npm { packages: &["@angular/language-server"] },
|
||||
version: V,
|
||||
homepage: "https://angular.dev/tools/language-service",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "graphql-lsp",
|
||||
display: "GraphQL Language Server",
|
||||
|
||||
@@ -67,15 +67,6 @@ fn everything_missing_on_an_empty_system() {
|
||||
let vtsls = find(&list, "vtsls");
|
||||
assert!(vtsls.languages.iter().any(|l| l == "TypeScript"));
|
||||
assert!(vtsls.unavailable_reason.as_deref().unwrap().contains("npm"));
|
||||
let ty = find(&list, "ty");
|
||||
assert_eq!(ty.status, ToolStatus::Missing);
|
||||
assert_eq!(ty.command, "ty");
|
||||
assert_eq!(ty.install_method.as_deref(), Some("pip (virtualenv)"));
|
||||
assert!(ty.languages.iter().any(|language| language == "Python"));
|
||||
let angular = find(&list, "angular-language-server");
|
||||
assert_eq!(angular.command, "ngserver");
|
||||
assert_eq!(angular.install_method.as_deref(), Some("npm"));
|
||||
assert_eq!(angular.languages, ["HTML", "TypeScript"]);
|
||||
// Servers without an installer are listed with their manual hint.
|
||||
let hls = find(&list, "haskell-language-server");
|
||||
assert_eq!(hls.install_method, None);
|
||||
|
||||
@@ -72,7 +72,7 @@ pub fn git_version(executable: Option<&Path>) -> IdeResult<String> {
|
||||
};
|
||||
let mut cmd = Command::new(&exe);
|
||||
cmd.arg("--version").stdin(Stdio::null()).env("LC_ALL", "C");
|
||||
ide_core::process::prepare(&mut cmd);
|
||||
ide_core::process::no_window(&mut cmd);
|
||||
let out = cmd.output().map_err(|e| IdeError::unavailable(format!("cannot run {}: {e}", exe.display())))?;
|
||||
let text = String::from_utf8_lossy(&out.stdout).trim().to_string();
|
||||
if !out.status.success() || !text.starts_with("git version") {
|
||||
@@ -106,7 +106,7 @@ pub(crate) fn command(root: &Path) -> IdeResult<Command> {
|
||||
for (k, v) in ASKPASS.read().unwrap_or_else(|e| e.into_inner()).iter() {
|
||||
cmd.env(k, v);
|
||||
}
|
||||
ide_core::process::prepare(&mut cmd);
|
||||
ide_core::process::no_window(&mut cmd);
|
||||
Ok(cmd)
|
||||
}
|
||||
|
||||
|
||||
@@ -32,8 +32,6 @@ pub enum WatchMode {
|
||||
/// One non-recursive watch per directory, skipping excluded and ignored
|
||||
/// directories; new directories are picked up as they appear.
|
||||
PerDirectory,
|
||||
/// The root's own entries only (loose files edited outside a project).
|
||||
Flat,
|
||||
}
|
||||
|
||||
impl Default for WatchMode {
|
||||
@@ -83,8 +81,7 @@ impl Watcher {
|
||||
on_change(batch);
|
||||
};
|
||||
let inner = match mode {
|
||||
WatchMode::Recursive => Self::start_recursive(root, filter, emit, RecursiveMode::Recursive),
|
||||
WatchMode::Flat => Self::start_recursive(root, filter, emit, RecursiveMode::NonRecursive),
|
||||
WatchMode::Recursive => Self::start_recursive(root, filter, emit),
|
||||
WatchMode::PerDirectory => Self::start_per_directory(root, filter, emit),
|
||||
}?;
|
||||
Ok(Self { inner, excludes: shared })
|
||||
@@ -97,7 +94,7 @@ impl Watcher {
|
||||
*self.excludes.write() = ExcludeMatcher::new(excludes);
|
||||
}
|
||||
|
||||
/// Number of OS-level watches (1 in recursive and flat mode).
|
||||
/// Number of OS-level watches (1 in recursive mode).
|
||||
pub fn watch_count(&self) -> usize {
|
||||
match &self.inner {
|
||||
Inner::Recursive(_) => 1,
|
||||
@@ -109,7 +106,6 @@ impl Watcher {
|
||||
root: PathBuf,
|
||||
filter: EventFilter,
|
||||
emit: impl Fn(&FsBatch) + Send + 'static,
|
||||
recursive: RecursiveMode,
|
||||
) -> IdeResult<Inner> {
|
||||
// No file-id cache: building it walks and stats the whole tree before `watch` returns,
|
||||
// which made opening large projects block for seconds. Renames arrive as remove + create.
|
||||
@@ -129,7 +125,9 @@ impl Watcher {
|
||||
let mut debouncer =
|
||||
new_debouncer_opt::<_, RecommendedWatcher, _>(DEBOUNCE, None, handler, NoCache, notify::Config::default())
|
||||
.map_err(|e| io_error(format!("cannot start file watcher: {e}")))?;
|
||||
debouncer.watch(&root, recursive).map_err(|e| io_error(format!("cannot watch {}: {e}", root.display())))?;
|
||||
debouncer
|
||||
.watch(&root, RecursiveMode::Recursive)
|
||||
.map_err(|e| io_error(format!("cannot watch {}: {e}", root.display())))?;
|
||||
Ok(Inner::Recursive(debouncer))
|
||||
}
|
||||
|
||||
@@ -789,30 +787,4 @@ mod tests {
|
||||
std::thread::sleep(Duration::from_millis(400));
|
||||
assert_eq!(batches.lock().len(), n, "no events after drop");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flat_mode_reports_the_roots_own_entries_only() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
std::fs::create_dir_all(root.join("sub")).unwrap();
|
||||
let batches: Arc<Mutex<Vec<FsBatch>>> = Arc::default();
|
||||
let sink: SharedSink = Arc::new(|_e: IdeEvent| {});
|
||||
let watcher = {
|
||||
let batches = batches.clone();
|
||||
Watcher::start_with(
|
||||
&root,
|
||||
Vec::new(),
|
||||
sink,
|
||||
Box::new(move |b| batches.lock().push(b.clone())),
|
||||
WatchMode::Flat,
|
||||
)
|
||||
.unwrap()
|
||||
};
|
||||
assert_eq!(watcher.watch_count(), 1);
|
||||
std::fs::write(root.join("sub/deep.txt"), "x").unwrap();
|
||||
std::fs::write(root.join("a.txt"), "x").unwrap();
|
||||
assert!(wait_for(&batches, |b| all_paths(b).contains(&root.join("a.txt"))), "{:?}", batches.lock());
|
||||
std::thread::sleep(Duration::from_millis(300));
|
||||
assert!(!all_paths(&batches.lock()).contains(&root.join("sub/deep.txt")));
|
||||
}
|
||||
}
|
||||
@@ -96,46 +96,18 @@ pub fn open(url: &str, id: Option<&str>) -> IdeResult<()> {
|
||||
if !(url.starts_with("http://") || url.starts_with("https://") || url.starts_with("file://")) {
|
||||
return Err(IdeError::invalid(format!("not a web URL: {url}")));
|
||||
}
|
||||
let app = match id {
|
||||
None => None,
|
||||
let result = match id {
|
||||
None => open::that_detached(url),
|
||||
Some(id) => {
|
||||
let known =
|
||||
KNOWN.iter().find(|k| k.id == id).ok_or_else(|| IdeError::invalid(format!("unknown browser: {id}")))?;
|
||||
Some(locate(known).ok_or_else(|| IdeError::unavailable(format!("{} is not installed", known.name)))?)
|
||||
let app = locate(known).ok_or_else(|| IdeError::unavailable(format!("{} is not installed", known.name)))?;
|
||||
open::with_detached(url, app.to_string_lossy().as_ref())
|
||||
}
|
||||
};
|
||||
#[cfg(target_os = "linux")]
|
||||
let result = spawn_with_host_env(match &app {
|
||||
None => open::commands(url),
|
||||
Some(app) => vec![open::with_command(url, app.to_string_lossy())],
|
||||
});
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
let result = match &app {
|
||||
None => open::that_detached(url),
|
||||
Some(app) => open::with_detached(url, app.to_string_lossy().as_ref()),
|
||||
};
|
||||
result.map_err(|e| IdeError::unavailable(format!("cannot open the browser: {e}")))
|
||||
}
|
||||
|
||||
/// Starts the first launcher that runs (`xdg-open`, `gio`, ...), with the host's environment
|
||||
/// rather than an AppImage's, and reaps it in the background.
|
||||
#[cfg(target_os = "linux")]
|
||||
fn spawn_with_host_env(commands: Vec<std::process::Command>) -> std::io::Result<()> {
|
||||
use std::process::Stdio;
|
||||
let mut last_err = None;
|
||||
for mut cmd in commands {
|
||||
ide_core::process::prepare(&mut cmd).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null());
|
||||
match cmd.spawn() {
|
||||
Ok(mut child) => {
|
||||
std::thread::spawn(move || child.wait());
|
||||
return Ok(());
|
||||
}
|
||||
Err(e) => last_err = Some(e),
|
||||
}
|
||||
}
|
||||
Err(last_err.unwrap_or_else(|| std::io::Error::other("no launcher available")))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -98,8 +98,7 @@ fn json_to_toml(value: &Json) -> IdeResult<toml_edit::Value> {
|
||||
}
|
||||
Json::Object(map) => {
|
||||
let mut t = toml_edit::InlineTable::new();
|
||||
// TOML has no null: an unset optional field is left out.
|
||||
for (k, v) in map.iter().filter(|(_, v)| !v.is_null()) {
|
||||
for (k, v) in map {
|
||||
t.insert(k, json_to_toml(v)?);
|
||||
}
|
||||
t.into()
|
||||
@@ -107,33 +106,20 @@ fn json_to_toml(value: &Json) -> IdeResult<toml_edit::Value> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Sets (or removes, for `None`) a dotted key in a TOML document. A new
|
||||
/// `map_entry` object becomes a `[languageServers.ruff]` table rather than an
|
||||
/// inline table under an explicit `[languageServers]` header.
|
||||
fn set_in_document(doc: &mut DocumentMut, segments: &[&str], value: Option<toml_edit::Value>, map_entry: bool) {
|
||||
/// Sets (or removes, for `None`) a dotted key in a TOML document.
|
||||
fn set_in_document(doc: &mut DocumentMut, segments: &[&str], value: Option<toml_edit::Value>) {
|
||||
let (last, parents) = segments.split_last().expect("non-empty key");
|
||||
let mut table: &mut dyn TableLike = doc.as_table_mut();
|
||||
let mut in_inline = false;
|
||||
for seg in parents {
|
||||
if !table.get(seg).is_some_and(Item::is_table_like) {
|
||||
if value.is_none() {
|
||||
return;
|
||||
}
|
||||
// Implicit: no `[languageServers]` header above `[languageServers.ruff]`.
|
||||
let mut new = Table::new();
|
||||
new.set_implicit(true);
|
||||
table.insert(seg, Item::Table(new));
|
||||
table.insert(seg, Item::Table(Table::new()));
|
||||
}
|
||||
let item = table.get_mut(seg).expect("table just ensured");
|
||||
in_inline |= item.is_inline_table();
|
||||
table = item.as_table_like_mut().expect("table just ensured");
|
||||
table = table.get_mut(seg).and_then(Item::as_table_like_mut).expect("table just ensured");
|
||||
}
|
||||
match value {
|
||||
Some(toml_edit::Value::InlineTable(t))
|
||||
if map_entry && !in_inline && !matches!(table.get(last), Some(Item::Value(_))) =>
|
||||
{
|
||||
table.insert(last, Item::Table(t.into_table()));
|
||||
}
|
||||
Some(v) => match table.get_mut(last) {
|
||||
// Keep the key's decor (comments, spacing) when replacing a value.
|
||||
Some(Item::Value(existing)) => {
|
||||
@@ -202,19 +188,9 @@ impl SettingsStore {
|
||||
if segments.iter().any(|s| s.is_empty()) {
|
||||
return Err(IdeError::invalid(format!("invalid settings key {key:?}")));
|
||||
}
|
||||
let defaults = defaults_json();
|
||||
let mut cursor = &defaults;
|
||||
let mut map_entry = false;
|
||||
for (i, seg) in segments.iter().enumerate() {
|
||||
match cursor.get(seg) {
|
||||
Some(next) => cursor = next,
|
||||
// An entry of a map setting (`languageServers.rust-analyzer`): the merge below validates it.
|
||||
None if cursor.as_object().is_some_and(|m| m.is_empty()) => {
|
||||
map_entry = i + 1 == segments.len();
|
||||
break;
|
||||
}
|
||||
None => return Err(IdeError::invalid(format!("unknown setting {key:?}"))),
|
||||
}
|
||||
let mut cursor = &defaults_json();
|
||||
for seg in &segments {
|
||||
cursor = cursor.get(seg).ok_or_else(|| IdeError::invalid(format!("unknown setting {key:?}")))?;
|
||||
}
|
||||
|
||||
let text = match std::fs::read_to_string(&file) {
|
||||
@@ -226,7 +202,7 @@ impl SettingsStore {
|
||||
.parse()
|
||||
.map_err(|e| IdeError::invalid(format!("{} is not valid TOML; fix it first: {e}", file.display())))?;
|
||||
let new_value = if value.is_null() { None } else { Some(json_to_toml(&value)?) };
|
||||
set_in_document(&mut doc, &segments, new_value, map_entry);
|
||||
set_in_document(&mut doc, &segments, new_value);
|
||||
let new_text = doc.to_string();
|
||||
|
||||
// Validate the resulting stack before touching the disk.
|
||||
@@ -362,11 +338,6 @@ mod tests {
|
||||
assert_eq!(s.files.exclude, vec!["**/dist".to_string()]);
|
||||
let s = store.set(SettingsScope::Global, "editor.lineHeight", json!(22.5)).unwrap();
|
||||
assert_eq!(s.editor.line_height, 22.5);
|
||||
// An unset optional field (null) inside an object is left out.
|
||||
let ssh = json!([{ "id": "a", "name": "mac", "host": "macmini", "port": null, "user": "" }]);
|
||||
let s = store.set(SettingsScope::Global, "ssh.configs", ssh).unwrap();
|
||||
assert_eq!(s.ssh.configs[0].port, None);
|
||||
assert!(!std::fs::read_to_string(cfg.join("settings.toml")).unwrap().contains("port"));
|
||||
// Map-valued setting whose keys contain dots, replaced as a whole.
|
||||
let s = store
|
||||
.set(
|
||||
@@ -379,47 +350,6 @@ mod tests {
|
||||
let s =
|
||||
store.set(SettingsScope::Global, "appearance.statusBarWidgets", json!({"editor.caret": false})).unwrap();
|
||||
assert_eq!(s.appearance.status_bar_widgets.len(), 1);
|
||||
// One entry of a map setting, set and removed on its own.
|
||||
let s = store
|
||||
.set(
|
||||
SettingsScope::Global,
|
||||
"languageServers.rust-analyzer",
|
||||
json!({"args": ["--log"], "initializationOptions": {"check": {"command": "clippy"}}}),
|
||||
)
|
||||
.unwrap();
|
||||
let ra = &s.language_servers["rust-analyzer"];
|
||||
assert!(ra.enabled);
|
||||
assert_eq!(ra.args.as_deref(), Some(&["--log".to_string()][..]));
|
||||
assert_eq!(ra.initialization_options, Some(json!({"check": {"command": "clippy"}})));
|
||||
assert_eq!(
|
||||
store
|
||||
.set(SettingsScope::Global, "languageServers.rust-analyzer", json!({"enabled": "no"}))
|
||||
.unwrap_err()
|
||||
.kind,
|
||||
ide_core::error::ErrorKind::InvalidInput
|
||||
);
|
||||
let s = store.set(SettingsScope::Global, "languageServers.rust-analyzer", json!(null)).unwrap();
|
||||
assert!(s.language_servers.is_empty());
|
||||
// New parent tables stay implicit: no empty `[languageServers]` header.
|
||||
let fresh = tmp.path().join("fresh");
|
||||
let s = SettingsStore::load(&fresh, None)
|
||||
.set(SettingsScope::Global, "languageServers.ruff.languages", json!(["python"]))
|
||||
.unwrap();
|
||||
assert!(s.language_servers["ruff"].is_custom());
|
||||
let text = std::fs::read_to_string(fresh.join("settings.toml")).unwrap();
|
||||
assert_eq!(text, "[languageServers.ruff]\nlanguages = [\"python\"]\n");
|
||||
// A whole new entry: a table of its own, still under an implicit parent.
|
||||
let added = tmp.path().join("added");
|
||||
let s = SettingsStore::load(&added, None)
|
||||
.set(
|
||||
SettingsScope::Global,
|
||||
"languageServers.ruff",
|
||||
json!({"command": "ruff", "args": ["server"], "languages": ["python"]}),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(s.language_servers["ruff"].command, "ruff");
|
||||
let text = std::fs::read_to_string(added.join("settings.toml")).unwrap();
|
||||
assert_eq!(text, "[languageServers.ruff]\nargs = [\"server\"]\ncommand = \"ruff\"\nlanguages = [\"python\"]\n");
|
||||
|
||||
// Project layer is created on demand and wins.
|
||||
let s = store.set(SettingsScope::Project, "editor.fontSize", json!(12)).unwrap();
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
# 核心体验运行验收补测(2026-10-25)
|
||||
|
||||
本轮按用户缩小后的“核心体验”范围执行,**27个明确场景:修复复测后27通过、0失败**。这不是原94项清单全量完成声明;首轮发现的中文漏译及原清单未完成项仍保留。
|
||||
|
||||
实际版本:`d3feb05`(功能提交 `1e00ea5` 加版本更新)。macOS 原生调试应用,使用真实窗口、编辑器、已安装语言服务器、实际子进程与磁盘结果。测试项目是 `fixtures/ts-app` 的 `/tmp/idea-parity-qa/core-ts` 副本;Python调试和终端脚本仅写入该副本。首次验收未修改产品源码;随后按用户要求修复下列两处问题,运行版本为 `d3feb05` 加工作区改动,未在本仓库提交;Git验收仅在独立core-git副本里创建QA提交。
|
||||
|
||||
通过判定仅针对表内明确写出的步骤。重点编辑、查找、导航、补全、格式化、项目视图和 npm 运行做了亮/暗复测;调试、启动链等执行逻辑没有逐一覆盖所有主题和语言组合。数据库、Docker部署、复杂Git图/merge/rebase/worktree、设置导入导出、完整书签/布局/宏管理不在这次缩小后的核心范围内,原清单相关待测项仍保留。
|
||||
|
||||
## 修复复测(同日)
|
||||
|
||||
- IN-2:保留未过滤的服务器诊断;检查方案编辑时重新投影已完成或进行中的结果,同步严重级别和问题计数,保留排除状态。原生应用亮/暗各验证 error → warning → disabled → restored;还验证了禁用时执行检查,再启用无需重跑即恢复2条诊断。[结构化证据](/tmp/idea-parity-qa/fix-IN2-results.json)、[暗色恢复截图](/tmp/idea-parity-qa/fix-IN2-dark-restored.png)。
|
||||
- CSS:为共享语言服务器的 CSS、SCSS、Less 配置提供默认对象,避免 workspace/configuration 返回 null。三种文件分别打开 `.qa { colr: red; }`,均返回 unknownProperties 警告;新进程日志无 validProperties 异常。[诊断证据](/tmp/idea-parity-qa/fix-css-results.json)、[原生日志](/tmp/idea-parity-qa/fix-app.log)。
|
||||
- 验证:前端分析相关10项测试、LSP协议26项测试均通过;pnpm typecheck、原生 debug build、cargo clippy -p ide-lsp --all-targets -- -D warnings、cargo fmt 与 git diff --check 通过。新增回归覆盖方案修改、禁用后恢复、流式检查中修改方案、计数和原始严重级别恢复,以及真实内置配置的协议响应。
|
||||
|
||||
## 首次失败记录(已修复,保留复现过程)
|
||||
|
||||
### A. IN-2:旧 Inspect Code 结果不随检查方案更新
|
||||
|
||||
1. 打开 `src/qa-diagnostic.ts`:`const qaNumber: number = "wrong";`。
|
||||
2. 默认方案执行 Code › Inspect Code,仅检查当前文件,得到2条 TypeScript 错误。
|
||||
3. 将 TypeScript 检查严重级别设为 warning:编辑器变为黄色波浪线、Problems 显示 warning;旧 Inspection Results 仍是红色错误。
|
||||
4. 禁用该检查:编辑器无波浪线、Problems 清空;旧 Inspection Results 仍显示“2 problems in 1 file”。
|
||||
|
||||
期望:按 IN-2 的“同时变化”要求,三处采用同一有效方案。实际只有前两处即时更新。亮/暗均复现。[暗色截图](/tmp/idea-parity-qa/core-IN2-repro-dark.png)、[亮色截图](/tmp/idea-parity-qa/core-IN2-batch-disabled.png)、[结构化结果](/tmp/idea-parity-qa/core-IN2-repro-dark.json)。
|
||||
|
||||
**边界:重新执行 Inspect Code 后确实得到0条结果**,所以不是方案永远无效,而是已有批量结果的实时同步缺失。[重跑结果](/tmp/idea-parity-qa/core-IN2-rerun-disabled.json)。
|
||||
|
||||
实现线索:[inspect.ts](/Users/thomas/repo/kalo/idea/src/features/analysis/inspect.ts:183) 在启动时取得方案,接收事件时过滤一次并保存;[InspectionView.tsx](/Users/thomas/repo/kalo/idea/src/features/analysis/InspectionView.tsx:219) 的树以已有 files 构建,没有将方案变化作为依赖。这与首次运行现象一致;现已按上节修复。
|
||||
|
||||
### B. CSS 语言服务器校验抛异常
|
||||
|
||||
1. 在副本新建并打开 `src/qa-validation.css`:`.qa { colr: red; }`。
|
||||
2. 等待已安装的 `vscode-css-language-server` 校验。
|
||||
3. 日志出现 `TypeError: Cannot read properties of null (reading 'validProperties')`,诊断列表为空,错误属性没有提示。
|
||||
|
||||
期望:默认 CSS 校验正常运行并对未知属性给出诊断,不抛异常。新建两个空 CSS 时已出现同一异常;专用错误样例和原生进程重启后再次复现。[运行日志及诊断](/tmp/idea-parity-qa/core-css-validation.json)、[编辑器截图](/tmp/idea-parity-qa/core-css-validation.png)、[重启日志](/tmp/idea-parity-qa/core-app-restart.log)。
|
||||
|
||||
首次排查线索为 [handler.rs](/Users/thomas/repo/kalo/idea/crates/ide-lsp/src/handler.rs:119) 的 workspace/configuration:未配置 section 返回 null。现已验证默认配置对象可修复该异常,见上节。
|
||||
|
||||
## 完成的核心场景
|
||||
|
||||
| 编号 | 结果 | 场景 | 实际验证 | 证据 |
|
||||
|---|---|---|---|---|
|
||||
| C01 | 通过 | 编辑与保存 | 输入、撤销、重做、保存磁盘、外部写入自动重载;亮/暗各复测。 | [记录](/tmp/idea-parity-qa/core-edit-confirm-results.json) |
|
||||
| C02 | 通过 | 常用编辑命令 | 同一行注释/取消注释、复制行,验证实际文档结果;亮/暗各复测。注释命令会移动到下一行,复测时重新定位原行。 | [记录](/tmp/idea-parity-qa/core-edit-commands-final-dark.json) |
|
||||
| C03 | 通过 | 项目视图与恢复 | 五种视图均切换;Open Files 成目录树;All Changed Files 仅包含被修改的已跟踪 index.ts。结束并重新启动原生进程后仍为 Open Files,23个打开路径与重启前完全一致。 | [记录](/tmp/idea-parity-qa/core-persist-after.json) |
|
||||
| C04 | 通过 | New 搜索和创建 | 项目树焦点下 ⌘N 出现 Search for file type;css 能找到 Stylesheet。CSS/SCSS/Less、Dockerfile、EditorConfig、gitignore、JSON/YAML/TOML/Shell/HTTP 的磁盘结果沿用首轮实际创建证据。 | [记录](/tmp/idea-parity-qa/core-NF1-dark.png) |
|
||||
| C05 | 通过 | ⌘N 上下文路由 | Python/Markdown 打开 New,并实际在当前文件的 src 目录创建 CSS;Java/Kotlin/TS 的动作轨迹为 code.generate,未打开 New。Kotlin 只验证路由,未声称生成代码可用。 | [记录](/tmp/idea-parity-qa/core-lastkeys.log) |
|
||||
| C06 | 通过 | 项目树文件操作 | 从选中的 src 目录 New › File 创建 qa-tree-created.txt;Rename 后旧路径消失、新路径存在;确认移至 Trash 后新路径消失。 | [记录](/tmp/idea-parity-qa/core-tree-deleted.json) |
|
||||
| C07 | 通过 | 文件内上下文查找 | In Comments 仅选中三个注释内的 shared(含 shared_history),Next/Previous 在位置3/38/78间导航,不命中代码和字符串;亮/暗各复测。 | [记录](/tmp/idea-parity-qa/core-find-final.log) |
|
||||
| C08 | 通过 | 替换大小写与排除 | Preserve Case 实际得到 bar/Bar/BAR;排除项出现删除线,Replace All 保留该项、替换其余项;亮/暗重新验证。 | [记录](/tmp/idea-parity-qa/core-FB4-final-dark.png) |
|
||||
| C09 | 通过 | 多行及搜索历史 | ⇧⌘↵ 输入跨行 alpha/beta 后计数1/1并选中完整跨行文本;⌥↓ 能打开编辑器历史,Find in Files 也显示新增 QA_shared_history。 | [记录](/tmp/idea-parity-qa/core-FB5-dark-confirm.png) |
|
||||
| C10 | 通过 | 自定义搜索范围 | 三个文件同一标记:不限定时3个文件;file:src//*.ts&&!file:*test* 仅命中 qa_scope.ts;Inspect Code 的 Custom scope 可选同一 Core TS Scope。 | [记录](/tmp/idea-parity-qa/core-FF3-final.png) |
|
||||
| C11 | 通过 | 跨文件替换与预览 | 两个文本文件6处替换,预览显示 Bar/BAR/bar,确认后磁盘一致;多行搜索可命中多个文件。保留大小写在亮/暗分别确认。 | [记录](/tmp/idea-parity-qa/core-FF4-dark-final.json) |
|
||||
| C12 | 通过 | 搜索排除归档 | 在项目内放入含唯一标记的 zip、jar,Find in Files 返回 No matches;不是只根据代码推断。 | [记录](/tmp/idea-parity-qa/core-FF5-archive.png) |
|
||||
| C13 | 通过 | 文件/类型/符号导航 | Go to File 打开 money.ts,Go to Class 打开 Cart,Go to Symbol 打开 formatMoney;调用点转到 Cart 定义,Back/Forward 正确返回和前进;亮/暗各复测。 | [记录](/tmp/idea-parity-qa/core-navigation.log) |
|
||||
| C14 | 通过 | Search Everywhere 筛选 | Files 排除 TypeScript、Classes 排除 Classes、Symbols 排除 Functions、Text 设 *.py,结果分别被过滤;切换页后各页值独立保留;亮/暗各复测。 | [记录](/tmp/idea-parity-qa/core-filters-final.log) |
|
||||
| C15 | 通过 | Actions 跳转设置 | 复选框为 Include disabled actions;搜索 code completion 有 Settings: Editor | General,选中后回车打开原生 Settings 的 Code Completion 页。 | [记录](/tmp/idea-parity-qa/core-NV2-target-final.png) |
|
||||
| C16 | 通过 | 重命名与 Generate | ⇧F6 原地重命名,第二次 ⇧F6 打开名称对话框;qaOriginalName 的声明和引用一起改为 qaRenamed。TS ⌘N 对缺失接口方法执行 Generate,生成 run() 实现。 | [记录](/tmp/idea-parity-qa/core-rename-clean.log) |
|
||||
| C17 | 通过 | LSP 补全 | 单候选自动插入开关实际改变行为;字母排序有效;函数补全插入(),有参数时光标在括号内且显示参数提示;无参光标在括号后;已有(不重复。亮/暗各复测。 | [记录](/tmp/idea-parity-qa/core-completion.log) |
|
||||
| C18 | 通过 | 格式化保护区 | 手动 Reformat 与保存时格式化都格式化保护区外的代码,@formatter:off/on 中间保持逐字不变;亮/暗各复测。 | [记录](/tmp/idea-parity-qa/core-IN7-save-dark.json) |
|
||||
| C19 | 通过 | 检查结果同步(IN-2) | 修复后亮/暗均验证严重级别、禁用和恢复即时同步,禁用时运行后重新启用也可恢复旧结果,无需重跑。 | [记录](/tmp/idea-parity-qa/fix-IN2-results.json) |
|
||||
| C20 | 通过 | 运行与测试反馈 | npm start 输出购物车合计 $134.97、退出0;正常测试通过;开启 opt-in 失败测试后树显示1 failed/4 passed、断言和源文件行、退出1。亮/暗各复测。 | [记录](/tmp/idea-parity-qa/core-runactual-final.log) |
|
||||
| C21 | 通过 | Current File 与调试 | Current File 直接运行 TS 输出 QA_CURRENT_FILE_OK;Python Current File 调试命中断点,显示 number=21,进入 double、越过后 answer=42,求值返回42,跳出、恢复后输出42、退出0。TS 调试器另列环境阻塞。 | [记录](/tmp/idea-parity-qa/core-debug-final-console.png) |
|
||||
| C22 | 通过 | Before launch 执行链 | 先运行子配置,再成功 Build,再 shell,最后主进程;记录 child/shell/main,Build 成功且主子退出0。额外验证非0步骤阻止启动并通知、循环引用被拒绝。 | [记录](/tmp/idea-parity-qa/core-RC6-success.json) |
|
||||
| C23 | 通过 | Compound | 两个成员17ms间隔启动并同时处于 running;选择 compound、从编辑器触发 Stop 后两个成员均 finished/130。 | [记录](/tmp/idea-parity-qa/core-RC7-stopped.json) |
|
||||
| C24 | 通过 | 交互终端 | PTY 输入 hello 得到回显;QA_RED 在亮/暗为红色;窗口缩放使子进程收到尺寸233→89列,恢复后120列;输入exit正常退出0,另一次Stop退出130。 | [记录](/tmp/idea-parity-qa/core-RC9-resize.png) |
|
||||
| C25 | 通过 | Power Save 核心行为 | 正常模式自动补全弹出;开启后同样输入不弹出,编辑器有横幅;有效配置同时关闭 usages Code Vision 等后台提示。随后关闭并确认重启后 false;未把这等同于全部后台任务性能验证。 | [记录](/tmp/idea-parity-qa/core-WB7-enabled.json) |
|
||||
| C26 | 通过 | CSS 校验集成 | 修复后重新编译并启动原生应用,CSS/SCSS/Less 均对 colr 返回 unknownProperties 警告,日志无原异常。 | [记录](/tmp/idea-parity-qa/fix-css-results.json) |
|
||||
| C27 | 通过 | Git常用流程 | 独立Python副本中查看HEAD与工作区diff,显示唯一QA标记差异;Commit先报告已有2个警告,选择Commit Anyway后实际提交,git diff为空,Git Log显示新提交。未推送。 | [记录](/tmp/idea-parity-qa/core-git-final.json) |
|
||||
|
||||
## 环境和验证边界
|
||||
|
||||
- Python debugpy 1.8.22 已安装,断点、变量、求值、三种单步和正常退出都实际验证。`js-debug` 未安装,**TypeScript/Node 调试没有通过判定**,没有拿 Python 的结果替代它。
|
||||
- Kotlin 两个语言服务器和 Marksman 缺失。Kotlin 的 ⌘N 仅确认路由到 Generate;未声称 Kotlin 代码生成/补全/重构已通过。
|
||||
- 部分配置通过真实 settings IPC 写入副本,运行配置执行链通过真实注册动作启动;没有把这些视作配置编辑器每个鼠标流程都已验收。
|
||||
- 第一次应用运行经过热更新,产生过状态模块/焦点残留;已关闭该调试进程、单独启动Vite和编译好的原生二进制后复测快捷键。干净启动后重命名和 Generate 正常,因此不列为产品失败。
|
||||
- `document.execCommand` 在终端缩放后的第二次注入没有发送文本;改用 textarea 的 InputEvent 后回显与正常退出均成功。这是驱动差异,不列为产品键入失败。使用的桥接输入均未被等同于人工键盘全矩阵验证。
|
||||
- 已结束并重启原生进程,Open Files 模式和23个打开路径完整恢复。[重启前](/tmp/idea-parity-qa/core-persist-before.json)、[重启后](/tmp/idea-parity-qa/core-persist-after.json)。记录中的 `/tmp` 与 `/private/tmp` 双路径是测试脚本先后用两种路径打开同一文件造成,没有将其直接列为正常用户路径问题。
|
||||
- 本轮没有应用崩溃;没有做量化卡顿测试。故意失败的测试、Before launch失败和Stop后的130通知均为测试输入产生;独立异常是上面的CSS服务器错误。
|
||||
- 本轮无产品代码改动,因此没有重复运行完整构建测试;首轮的 typecheck 与30个相关Vitest结果仍单独记录,不作为运行场景的替代。
|
||||
- 测试进程已停止;Power Save 恢复为false;全局语言/主题未新增改动。副本和截图保留供复核。
|
||||
@@ -0,0 +1,125 @@
|
||||
# IDEA 对齐运行验收记录(2026-10-25)
|
||||
|
||||
结论:**尚未达到全量验收通过条件**。累计94项中,功能断言通过35项、失败1项、部分验证58项。IN-2与清单外CSS校验异常已修复并经原生应用复测。核心复测27场景的具体范围、修复后27通过/0失败结论见[核心补测报告](acceptance-idea-core-result.md);不能把本次核心补测当作原94项全部完成。
|
||||
|
||||
目标提交为 `1e00ea5`;启动后仓库由外部更新为 `d3feb05 chore: v0.1.14`,仅版本文件变化,实际后续验收运行此版本。首次验收未改动产品源码;随后按用户要求修复IN-2和CSS配置,版本为 `d3feb05` 加工作区改动,未提交。测试均使用 `/tmp/idea-parity-qa/` 下的 fixture 副本。
|
||||
|
||||
使用 `pnpm tauri dev` 启动真实 macOS Tauri 应用,桥接操作真实 DOM、注册动作,并读取运行结果。部分设置通过真实 IPC 写入测试项目配置,以核对运行时行为;这不替代 Settings 原始鼠标路径或快捷键验证。热更新造成的旧模块实例问题已识别,相关外部库检查重新使用运行中的模块后重做;以 `libraries-final.log` 为准。
|
||||
|
||||
亮/暗主题已抽查 New、查找、运行配置、数据库、工具栏、Cleanup;未做到94项各自双主题全覆盖,主题总要求仍未完成。中文抽查发现可复现漏译。未观察到功能整体缺失;未覆盖项不能据此判定已实现。
|
||||
|
||||
辅助检查:`pnpm typecheck` 退出码0;4个相关 Vitest 文件共30个测试通过(libraries、NewPopup、file templates、run-anything)。没有重新运行完整 Rust/前端测试,不沿用清单中旧提交的通过数作为本轮证据。
|
||||
|
||||
## 逐项记录
|
||||
|
||||
| 编号 | 结果 | 现象、范围和证据 |
|
||||
|---|---|---|
|
||||
| PV-1 | 通过 | 真实 Project 标题下拉列出五种要求的模式;[证据](/tmp/idea-parity-qa/PV-1-menu.png) |
|
||||
| PV-2 | 通过 | 核心复测:五种模式已操作;Open Files 成树、All Changed Files 仅显示修改的已跟踪文件;原生进程重启后 Open Files 和23个打开路径恢复。[证据](/tmp/idea-parity-qa/core-persist-after.json) |
|
||||
| PV-3 | 通过 | Open Files 中定位未打开的 README.md,自动回到 Project 并选中 |
|
||||
| PV-4 | 部分 | Python 副本已建 .venv,External Libraries 注册标准库、venv 库和 site-packages;.venv 下逐级展开对照未完成;[证据](/tmp/idea-parity-qa/PV-6-python-app.png) |
|
||||
| PV-5 | 部分 | 在副本 site-packages 新建 qa_library.py,经编辑器插入文字后内容和磁盘均不变,readOnly=true,横幅正常;节点重命名/删除/新建/拖拽未逐项操作;[证据](/tmp/idea-parity-qa/PV-5-blocked-input.png) |
|
||||
| PV-6 | 部分 | Rust stdlib、Go SDK、JDK/src.zip、Gradle junit-jupiter 源码 jar、TS 的 typescript/vitest 直接依赖均已识别并注册到树;Cargo 依赖、Go 模块和 Maven 分组未完整覆盖;[证据](/tmp/idea-parity-qa/libraries-final.log) |
|
||||
| PV-7 | 部分 | JDK src.zip!/java.base/java/lang/String.java 实际打开,语法高亮、readOnly=true;树内逐级浏览及另一个 jar 未完整操作;[证据](/tmp/idea-parity-qa/PV-7-archive.png) |
|
||||
| PV-8 | 通过 | TS 副本 package.json 添加已在 node_modules 中的 qa-dep;857ms 后 External Libraries 已出现该依赖,随后恢复清单;[证据](/tmp/idea-parity-qa/PV-8-refresh.json) |
|
||||
| NF-1 | 通过 | 核心复测:项目树选中src,⌘N 打开带搜索框的 New;css 找到 Stylesheet。随后 New › File 实际在src创建文件。[证据](/tmp/idea-parity-qa/core-tree-new-parent.json) |
|
||||
| NF-2 | 通过 | 实际创建 CSS、SCSS、Less、Dockerfile、.editorconfig、.gitignore、JSON、YAML、TOML、Shell 和 HTTP 文件;核对磁盘扩展名及模板内容;[证据](/tmp/idea-parity-qa/templatesactual.log) |
|
||||
| NF-3 | 通过 | 核心复测:Python/Markdown 的 ⌘N 均打开 New,实际创建的CSS都在当前文件的src目录。[证据](/tmp/idea-parity-qa/core-lastkeys.log) |
|
||||
| NF-4 | 通过 | 核心复测:Java/Kotlin/TS 的 ⌘N 动作轨迹为 code.generate,均不打开 New;TS 实际生成缺失接口方法。Kotlin只验证路由,语言服务器缺失。[证据](/tmp/idea-parity-qa/core-NF4-generate.png) |
|
||||
| NF-5 | 部分 | 动作能弹出 New 并在当前 worker 目录创建文件;任意焦点和 ⌃⌥N 按键矩阵未完整验证;[证据](/tmp/idea-parity-qa/NF-5.png) |
|
||||
| NF-6 | 通过 | 创建 /tmp/idea-parity-qa/qa-new-project,勾选 Git,磁盘 .git 存在,出现独立 project-1 窗口;[证据](/tmp/idea-parity-qa/NF-6-created.json) |
|
||||
| NF-7 | 部分 | 重命名为 QA renamed project 后原生窗口标题更新,polyglot 磁盘目录保持原名;最近项目列表未单独检查;[证据](/tmp/idea-parity-qa/NF-7-renamed.png) |
|
||||
| FB-1 | 通过 | 漏斗列出 Search In Selection 和清单中的六种上下文范围;[证据](/tmp/idea-parity-qa/FB-1-filter.png) |
|
||||
| FB-2 | 通过 | 核心复测:In Comments 计数3;Next/Previous在三个注释位置间跳转,不命中代码/字符串;亮暗均验证。[证据](/tmp/idea-parity-qa/core-find-final.log) |
|
||||
| FB-3 | 通过 | 9 处 foo/Foo/FOO 替换为 bar/Bar/BAR,磁盘副本编辑内容符合预期;[证据](/tmp/idea-parity-qa/FB-3-result.png) |
|
||||
| FB-4 | 通过 | 排除第一处匹配后显示删除线,Replace All 保留该处 bar,其余变为 baz;[证据](/tmp/idea-parity-qa/FB-4-result.png) |
|
||||
| FB-5 | 通过 | 核心复测:⇧⌘↵ 后跨行输入alpha/beta,计数1/1、选择完整跨行内容;亮暗均确认。[证据](/tmp/idea-parity-qa/core-FB5-dark-confirm.png) |
|
||||
| FB-6 | 通过 | 核心复测:⌥↓ 打开编辑器最近搜索,新增QA_shared_history同时出现在 Find in Files 的最近搜索。[证据](/tmp/idea-parity-qa/core-find-final.log) |
|
||||
| FF-1 | 通过 | 真实窗口显示 In Project/Module/Directory/Scope,polyglot Module 下拉含根模块及 api、web;[证据](/tmp/idea-parity-qa/FF-1-options.json) |
|
||||
| FF-2 | 通过 | 新建并保存自定义 scope;!(file:src//* 实时显示 Missing `)` 错误,合法表达式出现在下拉;[证据](/tmp/idea-parity-qa/FF-2-real-invalid.png) |
|
||||
| FF-3 | 通过 | 核心复测:自定义Scope将3个标记文件缩至唯一qa_scope.ts;Inspect Code的Custom scope也能选Core TS Scope。[证据](/tmp/idea-parity-qa/core-FF3-final.png) |
|
||||
| FF-4 | 通过 | 核心复测:跨文件多行搜索命中;6处替换的保留大小写预览与磁盘Bar/BAR/bar一致;亮暗均确认。[证据](/tmp/idea-parity-qa/core-FF4-dark-final.json) |
|
||||
| FF-5 | 通过 | 核心复测:项目内jar/zip包含唯一标记,Find in Files不命中。[证据](/tmp/idea-parity-qa/core-FF5-archive.png) |
|
||||
| NV-1 | 通过 | 核心复测:四页分别过滤文件类型/类种类/符号种类/文件掩码,结果变化且各页保留独立选择;亮暗均验证。[证据](/tmp/idea-parity-qa/core-filters-final.log) |
|
||||
| NV-2 | 通过 | 核心复测:文案正确;Settings: Code Completion结果回车打开原生设置的对应页面。[证据](/tmp/idea-parity-qa/core-NV2-target-final.png) |
|
||||
| NV-3 | 部分 | 未执行:动作快捷键录入、生效与三种冲突解决 |
|
||||
| NV-4 | 部分 | 未执行:书签列表新建/重命名/删除/默认列表/移动矩阵 |
|
||||
| NV-5 | 部分 | 书签弹窗入口存在且空状态正常;文件、文件夹、行书签及按列表分组跳转未执行;[证据](/tmp/idea-parity-qa/NV-5.png) |
|
||||
| NV-6 | 部分 | 未执行:Structure 字段/非公开成员/可见性排序 |
|
||||
| NV-7 | 部分 | 未执行:支持 typeHierarchy 的 TS/Java 继承成员及跳转 |
|
||||
| NV-8 | 部分 | Recent Locations 有相对时间和代码片段;类/方法面包屑和片段高亮未完整核对;[证据](/tmp/idea-parity-qa/NV-8.png) |
|
||||
| NV-9 | 部分 | 已提交 fixture 的 Python 函数出现 Thomas Hong 作者;Settings 有 Code author;多人 +N 及关闭效果未验证 |
|
||||
| ED-1 | 通过 | 核心复测:关闭单候选自动插入时保留一个候选,开启后实际自动插入;亮暗均确认。[证据](/tmp/idea-parity-qa/core-completion.log) |
|
||||
| ED-2 | 通过 | 核心复测:打开Sort suggestions alphabetically后真实候选按名称排序,popup含Sort by name;通过设置开关路径验证。[证据](/tmp/idea-parity-qa/core-ED2-sorted-dark.png) |
|
||||
| ED-3 | 通过 | 核心复测:有参/无参函数自动括号、光标落点和参数提示符合要求;已有(不重复;亮暗均验证。[证据](/tmp/idea-parity-qa/core-completion.log) |
|
||||
| ED-4 | 部分 | Top/Bottom/Left/Right/None 均切换并截图,左右为竖排,None 隐藏标签;滚动、拖拽和菜单一致性未逐项验证;[证据](/tmp/idea-parity-qa/ED-4-none.png) |
|
||||
| ED-5 | 部分 | Editor Tabs 的相关设置项齐全;每种选项实际行为未逐项验证;[证据](/tmp/idea-parity-qa/settings-Editor-Tabs.png) |
|
||||
| ED-6 | 部分 | Inline Completion 设置页存在;未配置支持 inlineCompletion 的服务,运行预览及快捷键跳过,不能视为通过;[证据](/tmp/idea-parity-qa/settings-Inline-Completion.png) |
|
||||
| IN-1 | 部分 | Inspections 页面有方案、搜索、按语言树和描述区域;三态与 Severity 的编辑操作未完成;[证据](/tmp/idea-parity-qa/IN-1-settings.png) |
|
||||
| IN-2 | 通过 | 修复复测:亮/暗下编辑器和旧Inspect Code结果随严重级别、禁用、恢复即时同步,计数同步;禁用时运行后也能重新启用恢复诊断,无需重跑。[证据](/tmp/idea-parity-qa/fix-IN2-results.json) |
|
||||
| IN-3 | 部分 | 未执行:检查方案 Duplicate/Copy/Rename/Delete 和内置方案保护 |
|
||||
| IN-4 | 部分 | 测试副本已写入 recieve;注释/字符串/声明和调用名的诊断对照未完成 |
|
||||
| IN-5 | 部分 | Spelling 设置页面存在;Typo 上下文候选及保存两类词典未执行;[证据](/tmp/idea-parity-qa/settings-Spelling.png) |
|
||||
| IN-6 | 部分 | Code Style 页面有 Default (IDE) Scheme 与 Copy to Project;语言子页面联动未完整操作;[证据](/tmp/idea-parity-qa/settings-Code-Style.png) |
|
||||
| IN-7 | 通过 | 核心复测:手动及保存格式化都格式化保护区之外,formatter:off/on之间逐字保持;亮暗均验证。[证据](/tmp/idea-parity-qa/core-IN7-save-dark.json) |
|
||||
| IN-8 | 通过 | 项目配置 Do not format 为 *.json,执行 Reformat Code 出现明确跳过提示;[证据](/tmp/idea-parity-qa/IN-8-excluded.png) |
|
||||
| IN-9 | 部分 | Cleanup 范围及 fix/import/format 选项存在,可取消;实际清理结果和中途取消未执行;[证据](/tmp/idea-parity-qa/IN-9.png) |
|
||||
| FT-1 | 部分 | 打开 x.foo 后添加 YAML 关联,现有 editor context 立即变为 yaml/YAML;图标及 Go to File 未独立核对;[证据](/tmp/idea-parity-qa/FT-1-yaml.png) |
|
||||
| FT-2 | 部分 | 调用同名注册动作使 YAML→JSON→YAML,现有编辑器立即更新;右键菜单路径及撤销未操作;[证据](/tmp/idea-parity-qa/FT-2-revert.json) |
|
||||
| FT-3 | 通过 | 无扩展名 qa-hashbang 带 #!/usr/bin/env python3,实际 editor context 为 python/Python;[证据](/tmp/idea-parity-qa/FT-3-hashbang.png) |
|
||||
| PS-1 | 部分 | 添加外部 extra-root 后树出现根,Find in Files 命中 extra.ts;Go to File 和外部文件修改刷新未完整验证;[证据](/tmp/idea-parity-qa/PS-1-search.png) |
|
||||
| PS-2 | 部分 | 即时设置 *.log;tmp* 后 Find in Files 不再命中 qa.log 中的唯一标记;树与索引侧未独立核对;[证据](/tmp/idea-parity-qa/PS-2-search.png) |
|
||||
| TP-1 | 部分 | File and Code Templates 页面包含 Includes,说明支持 #parse;编辑 File Header 后新建 Java/Kotlin 未执行 |
|
||||
| TP-2 | 部分 | 模板页有 Code 标签;修改测试方法模板并生成测试未执行 |
|
||||
| TP-3 | 部分 | Reformat according to style 默认已勾选;$END$ 光标及格式化效果未单独验证;[证据](/tmp/idea-parity-qa/settings-File-and-Code-Templates.png) |
|
||||
| RC-1 | 通过 | 核心复测:Current File保持可选,直接运行TS输出正确;Python Current File调试命中断点并可单步/求值/正常退出。Node调试器缺失单独记为环境阻塞。[证据](/tmp/idea-parity-qa/core-debug-final-console.png) |
|
||||
| RC-2 | 通过 | + 菜单列出所有要求类型,含 Compound 与 Docker 三种子类型,搜索输入存在;[证据](/tmp/idea-parity-qa/RC-2-types.png) |
|
||||
| RC-3 | 部分 | 实际新建 Shell/Program,Program env 运行成功,检测配置正常;其余每种类型执行及旧配置兼容未覆盖;[证据](/tmp/idea-parity-qa/RC-8-process-output.png) |
|
||||
| RC-4 | 部分 | 表单支持复制/分组/排序/Templates;对话框 Run 成功,local TOML 已落盘且 git check-ignore 命中 .openidea/.gitignore;其余子流程未逐项执行 |
|
||||
| RC-5 | 部分 | Modify options 显示各类可选项;移除控件与各选项的运行效果未完整验证;[证据](/tmp/idea-parity-qa/RC-5.json) |
|
||||
| RC-6 | 通过 | 核心复测:实际子配置→Build→Shell→主进程;Build成功,记录child/shell/main;失败步骤中止并通知,循环被拒绝。[证据](/tmp/idea-parity-qa/core-RC6-success.json) |
|
||||
| RC-7 | 通过 | 核心复测:两成员17ms间隔启动并同时running,选中compound从编辑器触发Stop后都结束、退出130。[证据](/tmp/idea-parity-qa/core-RC7-stopped.json) |
|
||||
| RC-8 | 部分 | A=1;B=2 输入后对话框拆成两行,关闭系统环境后 /usr/bin/env 仅输出 A/B,退出码 0;独立 Paste 按钮未操作;[证据](/tmp/idea-parity-qa/RC-8-process-output.png) |
|
||||
| RC-9 | 通过 | 核心复测:PTY回显、亮暗ANSI颜色、resize传到子进程(233→89列)均正常;输入exit退出0,另次Stop退出130。[证据](/tmp/idea-parity-qa/core-RC9-resize.png) |
|
||||
| RC-10 | 部分 | 空 Run 显示三条提示及 run configuration 链接;点击链接未操作 |
|
||||
| RC-11 | 部分 | 本机 Docker 可用,但未运行/停止 fixture Docker 和 Compose,不能视为通过 |
|
||||
| GT-1 | 部分 | Graph Options 所列排序和分支选项齐全;复杂分支图下的效果未执行;[证据](/tmp/idea-parity-qa/GT-1-options.png) |
|
||||
| GT-2 | 部分 | View Options 所列显示项和 Highlight 存在;开关效果及重启持久化未完整验证;[证据](/tmp/idea-parity-qa/GT-2-options.png) |
|
||||
| GT-3 | 部分 | 未执行:Log 焦点 ⌘F、补全、跳转及自动加载更多 |
|
||||
| GT-4 | 部分 | 未执行:设置 Date 过滤后图仍保留 |
|
||||
| GT-5 | 部分 | 七种对话框均实际打开,选项可见;未执行 pull/merge/rebase/worktree/clone 的磁盘变化;[证据](/tmp/idea-parity-qa/gitcheck.log) |
|
||||
| SV-1 | 部分 | Add Service 菜单有三类要求入口;⌘N 和无连接空状态未完整验证;[证据](/tmp/idea-parity-qa/SV-1.png) |
|
||||
| SV-2 | 部分 | 实际 Program/Run Anything/PTY 均已启动;Services 中运行配置分组与停止/重跑/输出跳转未验证 |
|
||||
| SV-3 | 部分 | 自动连接 orbstack,显示容器、镜像、卷和网络;新建多个连接及绑定操作路由未执行;[证据](/tmp/idea-parity-qa/SV-1.png) |
|
||||
| TD-1 | 部分 | TODO 有 Scope Based、Changes,显示7条 fixture TODO/FIXME;自定义范围和多个 changelist 下拉未验证;[证据](/tmp/idea-parity-qa/TD-1.png) |
|
||||
| CV-1 | 部分 | LCOV 导入显示 app.ts 50%(1/2),管理弹窗列出报告;Go/JaCoCo、多报告切换和 gutter 未完整验证;[证据](/tmp/idea-parity-qa/CV-1-import.png) |
|
||||
| DB-1 | 部分 | Driver 下拉按字母列出 CockroachDB/Redshift/TiDB 等;逐种默认端口未核对;[证据](/tmp/idea-parity-qa/DB-1-list.png) |
|
||||
| DB-2 | 通过 | 指定 JDBC URL 解析出 h、5432、db,SSL 页为 Verify Full;[证据](/tmp/idea-parity-qa/DB-2-ssl.png) |
|
||||
| DB-3 | 部分 | Options/Schemas/Advanced 页签存在;未连 SQLite/Postgres 验证只读/启动脚本/时区/过滤/驱动属性 |
|
||||
| DB-4 | 部分 | 颜色和 Add comment 控件存在;树节点、console 标签及 hover 效果未验证 |
|
||||
| WB-1 | 部分 | Run Anything 执行 pwd,输出进入 Run,cwd 为 fixture,退出码0,并列出检测配置;双 Ctrl、Maven/Gradle 和新历史未完整验证;[证据](/tmp/idea-parity-qa/WB-1-output.png) |
|
||||
| WB-2 | 部分 | Customize Main Toolbar 可打开并显示增删/排序/恢复控件;实际保存和重启持久化未执行;[证据](/tmp/idea-parity-qa/WB-2.png) |
|
||||
| WB-3 | 部分 | Save Current Layout as 弹出命名输入;另存、恢复、重命名、删除完整流程未执行;[证据](/tmp/idea-parity-qa/WB-3-save.json) |
|
||||
| WB-4 | 部分 | 未执行:原生 View › Tool Windows 与注册表的一一核对 |
|
||||
| WB-5 | 部分 | Quick Switch Scheme 弹出四类选项;其余菜单命令及所有效果未完整验证;[证据](/tmp/idea-parity-qa/WB-5.png) |
|
||||
| WB-6 | 部分 | 无可用重构位置弹出 Nothing here;原生菜单上下文置灰未验证;[证据](/tmp/idea-parity-qa/WB-6.png) |
|
||||
| WB-7 | 部分 | Power Save Mode 切换后编辑器出现横幅,随后关闭恢复;后台高亮与自动弹出抑制未完整验证;[证据](/tmp/idea-parity-qa/WB-7-real.png) |
|
||||
| WB-8 | 部分 | 未执行:完整 Export/Import 设置与快捷键、模板、宏、布局恢复 |
|
||||
| WB-9 | 部分 | 录制 QA macro 后回放,内容为 QA macroQA macro;保存命名和 Keymap 绑定未执行;[证据](/tmp/idea-parity-qa/WB-9-replay-result.png) |
|
||||
| WB-10 | 部分 | Coverage 导入的信息通知显示 Don’t Show Again;点击后同类通知抑制未验证 |
|
||||
| I18N-1 | 失败 | 复现:切换中文,打开 Code › Code Cleanup。实际 Whole project、Module or directory、Uncommitted files 和底部说明仍为英文;打开 Customize Main Toolbar 后 Project Widget/VCS Widget/Build Project/Run Widget 仍为英文;Services 的 Containers/Images/Volumes/Networks 仍为英文。期望这些新增界面文案均翻译;均不属于清单已知例外;[证据](/tmp/idea-parity-qa/IN-zh-dark.png) |
|
||||
|
||||
## 独立问题与环境说明
|
||||
|
||||
- 崩溃:已执行流程中未观察到应用崩溃。版本更新引起的 dev 自动重编译不是崩溃。
|
||||
- 控制台:有自动化自身造成的错误(错误 action id、首次尝试不存在的文件、带换行注入脚本的 Unexpected EOF)和手动 reload 后 Tauri callback 警告;不归为产品功能失败。尚不能声明控制台全量无错误。应用日志在 [/tmp/idea-parity-qa.log](/tmp/idea-parity-qa.log)。
|
||||
- 卡顿:未观察到已执行操作中的明显持续卡顿;没有完成量化性能验收。桥接脚本等待用户输入对话框导致的超时不按应用卡顿计。
|
||||
- 核心补测新增的CSS语言服务器validProperties空值异常已修复;CSS/SCSS/Less真实校验均返回未知属性警告,见核心报告修复复测。
|
||||
- Python REPL 的 Stop 先发中断(出现 KeyboardInterrupt),随后超时强制结束,最终137/SIGKILL;这是本轮观察结果,未仅凭此判失败。
|
||||
- 首轮安装TS依赖时pnpm提示esbuild脚本未批准;核心补测已实际运行npm start及正常/故意失败测试。Build通过专用最小TS目标验证,未据此宣称所有原始QA文件能通过类型检查。
|
||||
- 全量放行前仍需完成表中的未执行子项,包括所有语言/运行类型、Docker、复杂Git图与合并/变基、数据库、设置导入导出、完整书签/布局管理等;双主题逐项与中文复测也未全覆盖。Before launch、Compound、补全和基础运行/调试已有核心复测证据,见对应行。
|
||||
|
||||
截图和结构化证据目录:[/tmp/idea-parity-qa](/tmp/idea-parity-qa)。验收期间使用的全局主题、语言和 Power Save Mode 已恢复;最后录制宏为 QA 样例,测试项目仍保留供复核。
|
||||
|
||||
|
||||
核心补测:新增真实编辑、导航、补全、重命名、检查同步、运行/调试、Before launch/Compound、PTY和原生重启验证;详情见[核心补测报告](acceptance-idea-core-result.md)。原表中其他待测子项仍保留,不因核心补测而自动变绿。
|
||||
Бінарний файл не відображається.
|
Після Ширина: | Висота: | Розмір: 169 KiB |
Бінарний файл не відображається.
|
Після Ширина: | Висота: | Розмір: 133 KiB |
Бінарний файл не відображається.
|
Після Ширина: | Висота: | Розмір: 171 KiB |
Loaded 100 of 777 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача