Compare commits

..
Author SHA1 Message Date
l0ng-ai 3ccb499fec fix(search): exact Windows file URLs, and search again after a multi-line replace
- Search Everywhere decodes file URLs and strips the slash before a drive letter.
- A pattern that may match a line break, or a run that replaced fewer targets than planned, searches again instead of marking stale positions as replaced.
2026-11-18 11:34:48 +08:00
l0ng-ai cd370ed89a fix(search): a Windows workspace module scope searches the module's own folder 2026-11-18 11:34:48 +08:00
251 changed files with 1664 additions and 7576 deletions

No files matched your search

+15 -65
View File
@@ -32,12 +32,7 @@ jobs:
pull-requests: read
outputs:
rust: ${{ steps.classify.outputs.rust }}
server: ${{ steps.classify.outputs.server }}
plugins: ${{ steps.classify.outputs.plugins }}
deny: ${{ steps.classify.outputs.deny }}
frontend: ${{ steps.classify.outputs.frontend }}
e2e: ${{ steps.classify.outputs.e2e }}
catalog: ${{ steps.classify.outputs.catalog }}
steps:
- id: classify
env:
@@ -45,55 +40,26 @@ jobs:
PR: ${{ github.event.pull_request.number }}
run: |
set -euo pipefail
jobs="rust server plugins deny frontend e2e catalog"
if [ "$GITHUB_EVENT_NAME" != pull_request ]; then
for job in $jobs; do echo "$job=true" >> "$GITHUB_OUTPUT"; done
echo "rust=true" >> "$GITHUB_OUTPUT"
echo "frontend=true" >> "$GITHUB_OUTPUT"
exit 0
fi
gh api --paginate "repos/$GITHUB_REPOSITORY/pulls/$PR/files" \
--jq '.[] | .filename, (.previous_filename // empty)' > files.txt
cat files.txt
# A change to CI itself runs everything.
ci='^\.github/(workflows/ci\.yml|actions/)'
docs='^(docs/|\.agents/|\.claude/|\.idea/|\.github/ISSUE_TEMPLATE/|\.github/pull_request_template\.md$|[^/]+\.md$|LICENSE$|NOTICE$)'
# Frontend-only paths. The Rust code embeds a few files under src/; those stay out.
web='^(src/|e2e/|perf/|public/|scripts/|smoke/|evals/|index\.html$|vite\.config\.ts$|tsconfig[^/]*\.json$|knip\.ts$|playwright\.config\.ts$|\.oxlintrc\.json$|\.oxfmtrc\.json$)'
web='^(src/|e2e/|perf/|public/|scripts/|smoke/|index\.html$|vite\.config\.ts$|tsconfig[^/]*\.json$|knip\.ts$|playwright\.config\.ts$|\.oxlintrc\.json$|\.oxfmtrc\.json$)'
embedded='^src/(bindings\.ts|styles/tokens\.css|features/plugins/views/frame-bridge\.js|platform/keymaps/)'
# Plugin web pages are their own pnpm projects, checked by the Plugins job only.
plugin_web='^plugins/official/[^/]+/web-src/'
# Paths the frontend checks never read...
backend='^(crates/|src-tauri/|sdk/|wit/|java/|fixtures/|Cargo\.(toml|lock)$|deny\.toml$|rustfmt\.toml$|rust-toolchain(\.toml)?$|\.cargo/)'
# ...except these, which frontend tests and e2e fixtures load.
read_by_web='^(fixtures/(folding|django-app)/|crates/ide-plugin/tests/fixtures/|crates/ide-db/(src|tests/fixtures)/snowflake/|src-tauri/(icons|capabilities)/|src-tauri/tauri\.conf\.json$)'
# What the browser app and its e2e tests are built from.
app='^(src/|e2e/|public/|index\.html$|vite\.config\.ts$|tsconfig\.json$|playwright\.config\.ts$|package\.json$|pnpm-(lock|workspace)\.yaml$|crates/ide-plugin/tests/fixtures/|src-tauri/(icons|capabilities)/|src-tauri/tauri\.conf\.json$)'
# The plugin workspaces: the SDK, the plugins, their interface and the host's fixture plugins.
plugin_ws='^(sdk/|plugins/|wit/|crates/ide-plugin/tests/fixtures/|rust-toolchain(\.toml)?$)'
# Never compiled into the openidea-server binary.
not_server='^(src-tauri/|sdk/|fixtures/|crates/[^/]+/(tests|benches)/)'
deps='(^|/)Cargo\.(toml|lock)$|^deny\.toml$'
# The text catalog test reads the string literals of every Rust source.
rust_source='^(crates|src-tauri/src)/.*\.rs$'
any() { grep -Eq "$1" files.txt; }
outside() { [ -n "$(grep -Ev "$1" files.txt || true)" ]; }
set_job() { echo "$1=$2" | tee -a "$GITHUB_OUTPUT"; }
if any "$ci"; then
for job in $jobs; do set_job "$job" true; done
exit 0
fi
on() { if "${@:2}"; then set_job "$1" true; else set_job "$1" false; fi; }
rust_build() { outside "$1" || any "$embedded"; }
web_checks() { outside "$docs|$plugin_web|$backend" || any "$read_by_web"; }
catalog_only() { ! web_checks && any "$rust_source"; }
on rust rust_build "$docs|$web|$plugin_web"
on server rust_build "$docs|$web|$plugin_web|$not_server"
on plugins any "$plugin_ws"
on deny any "$deps"
on frontend web_checks
on e2e any "$app"
on catalog catalog_only
# A job runs when any changed file falls outside the paths that can't affect it.
rust=false
if grep -Ev "$docs|$web" files.txt | grep -q . || grep -Eq "$embedded" files.txt; then rust=true; fi
frontend=false
if grep -Ev "$docs" files.txt | grep -q .; then frontend=true; fi
echo "rust=$rust frontend=$frontend"
echo "rust=$rust" >> "$GITHUB_OUTPUT"
echo "frontend=$frontend" >> "$GITHUB_OUTPUT"
rust:
name: Rust (${{ matrix.os }})
@@ -145,7 +111,7 @@ jobs:
server:
name: Remote server (linux musl)
needs: changes
if: needs.changes.outputs.server == 'true'
if: needs.changes.outputs.rust == 'true'
timeout-minutes: 40
runs-on: ubuntu-22.04
steps:
@@ -163,7 +129,7 @@ jobs:
plugins:
name: Plugins (SDK, official, fixtures)
needs: changes
if: needs.changes.outputs.plugins == 'true'
if: needs.changes.outputs.rust == 'true'
timeout-minutes: 30
runs-on: ubuntu-22.04
env:
@@ -215,7 +181,7 @@ jobs:
deny:
name: Cargo deny
needs: changes
if: needs.changes.outputs.deny == 'true'
if: needs.changes.outputs.rust == 'true'
timeout-minutes: 15
runs-on: ubuntu-latest
steps:
@@ -244,26 +210,10 @@ jobs:
- run: pnpm test
- run: pnpm build
# A backend-only change can still drop a string the text catalog uses: run that one test.
catalog:
name: Text catalog
needs: changes
if: needs.changes.outputs.catalog == 'true'
timeout-minutes: 15
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- uses: pnpm/action-setup@v5
with: { version: 11 }
- uses: actions/setup-node@v5
with: { node-version: 22, cache: pnpm }
- run: pnpm install --frozen-lockfile
- run: pnpm vitest run src/platform/locales/textCatalog.test.ts
e2e:
name: E2E (${{ matrix.shard }}/2)
needs: changes
if: needs.changes.outputs.e2e == 'true'
if: needs.changes.outputs.frontend == 'true'
timeout-minutes: 30
runs-on: ubuntu-24.04
strategy:
+1 -67
View File
@@ -15,7 +15,6 @@ on:
- "crates/**"
- "languages/**"
- "fixtures/**"
- "java/**"
- "Cargo.toml"
- "Cargo.lock"
- "src/features/run/**"
@@ -42,77 +41,12 @@ env:
CARGO_INCREMENTAL: 0
jobs:
# The languages a pull request can affect: a change to one language's fixture, definition or
# JDT LS bundle runs that language; crates the smoke doesn't exercise and other crates' tests
# run none; anything else runs them all. Pushes and manual runs always run them all.
changes:
name: Changes
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
pull-requests: read
outputs:
languages: ${{ steps.classify.outputs.languages }}
steps:
- id: classify
env:
GH_TOKEN: ${{ github.token }}
PR: ${{ github.event.pull_request.number }}
run: |
set -euo pipefail
all="typescript python rust go java kotlin php c cpp"
emit() { tr ' ' '\n' <<< "$1" | { grep . || true; } | sort -u | jq -Rsc 'split("\n") | map(select(. != ""))'; }
if [ "$GITHUB_EVENT_NAME" != pull_request ]; then
echo "languages=$(emit "$all")" | tee -a "$GITHUB_OUTPUT"
exit 0
fi
gh api --paginate "repos/$GITHUB_REPOSITORY/pulls/$PR/files" \
--jq '.[] | .filename, (.previous_filename // empty)' > files.txt
cat files.txt
# Crates outside what the smoke runs (language servers, debuggers, run configurations,
# SDKs, build tools and the project model): cargo metadata, deps of ide-lsp/dap/run/sdk/tools.
unused='^crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-http|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-search|ide-spell|ide-ssh|ide-streams|ide-vcs|ide-web)/'
# The workflow's paths, less those handled per language below.
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger)/|src/platform/|smoke/|package\.json$|pnpm-lock\.yaml$|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
langs=""
while read -r f; do
case "$f" in
crates/ide-host/tests/language_smoke.rs | crates/ide-host/tests/project_smoke.rs) langs="$all"; break ;;
crates/*/tests/* | crates/*/benches/*) ;;
fixtures/ts-app/*) langs+=" typescript" ;;
fixtures/python-app/*) langs+=" python" ;;
fixtures/rust-app/*) langs+=" rust" ;;
fixtures/go-app/*) langs+=" go" ;;
fixtures/java-app/*) langs+=" java" ;;
fixtures/kotlin-gradle/*) langs+=" kotlin" ;;
fixtures/php-app/*) langs+=" php" ;;
fixtures/c-app/*) langs+=" c cpp" ;;
fixtures/*) ;;
languages/typescript.toml | languages/typescriptreact.toml | languages/javascript.toml | languages/javascriptreact.toml) langs+=" typescript" ;;
languages/python.toml) langs+=" python" ;;
languages/rust.toml) langs+=" rust" ;;
languages/go.toml | languages/gomod.toml | languages/gowork.toml) langs+=" go" ;;
languages/java.toml) langs+=" java" ;;
languages/kotlin.toml) langs+=" kotlin" ;;
languages/php.toml) langs+=" php" ;;
languages/c.toml) langs+=" c" ;;
languages/cpp.toml) langs+=" cpp" ;;
languages/*) ;;
java/kotlin-bridge/*) langs+=" kotlin" ;;
java/*) langs+=" java kotlin" ;;
*) if grep -Eq "$smoke" <<< "$f" && ! grep -Eq "$unused" <<< "$f"; then langs="$all"; break; fi ;;
esac
done < files.txt
echo "languages=$(emit "$langs")" | tee -a "$GITHUB_OUTPUT"
smoke:
name: Language smoke (${{ matrix.language }})
needs: changes
if: needs.changes.outputs.languages != '[]'
strategy:
fail-fast: false
matrix:
language: ${{ fromJSON(needs.changes.outputs.languages) }}
language: [typescript, python, rust, go, java, kotlin, php, c, cpp]
# C/C++ debug with GDB, whose DAP interpreter needs 14+: 22.04 ships 12.1, 24.04 ships 15.
runs-on: ${{ (matrix.language == 'c' || matrix.language == 'cpp') && 'ubuntu-24.04' || 'ubuntu-22.04' }}
timeout-minutes: 40
Generated
+46 -47
View File
@@ -4144,7 +4144,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
[[package]]
name = "ide-agent"
version = "0.1.48"
version = "0.1.47"
dependencies = [
"blake3",
"dunce",
@@ -4169,7 +4169,7 @@ dependencies = [
[[package]]
name = "ide-analysis"
version = "0.1.48"
version = "0.1.47"
dependencies = [
"ast-grep-core",
"ide-core",
@@ -4183,7 +4183,7 @@ dependencies = [
[[package]]
name = "ide-android"
version = "0.1.48"
version = "0.1.47"
dependencies = [
"ide-core",
"serde",
@@ -4194,7 +4194,7 @@ dependencies = [
[[package]]
name = "ide-build"
version = "0.1.48"
version = "0.1.47"
dependencies = [
"blake3",
"chardetng",
@@ -4212,7 +4212,7 @@ dependencies = [
[[package]]
name = "ide-cli"
version = "0.1.48"
version = "0.1.47"
dependencies = [
"dirs 6.0.0",
"serde",
@@ -4226,7 +4226,7 @@ dependencies = [
[[package]]
name = "ide-clipboard"
version = "0.1.48"
version = "0.1.47"
dependencies = [
"gtk",
"objc2 0.6.5",
@@ -4237,7 +4237,7 @@ dependencies = [
[[package]]
name = "ide-command"
version = "0.1.48"
version = "0.1.47"
dependencies = [
"heck 0.5.0",
"proc-macro2",
@@ -4248,7 +4248,7 @@ dependencies = [
[[package]]
name = "ide-core"
version = "0.1.48"
version = "0.1.47"
dependencies = [
"dunce",
"encoding_rs",
@@ -4265,7 +4265,7 @@ dependencies = [
[[package]]
name = "ide-coverage"
version = "0.1.48"
version = "0.1.47"
dependencies = [
"ide-core",
"ide-run",
@@ -4279,7 +4279,7 @@ dependencies = [
[[package]]
name = "ide-dap"
version = "0.1.48"
version = "0.1.47"
dependencies = [
"base64 0.22.1",
"futures",
@@ -4308,7 +4308,7 @@ dependencies = [
[[package]]
name = "ide-db"
version = "0.1.48"
version = "0.1.47"
dependencies = [
"base64 0.22.1",
"bb8",
@@ -4344,7 +4344,7 @@ dependencies = [
[[package]]
name = "ide-docker"
version = "0.1.48"
version = "0.1.47"
dependencies = [
"ide-core",
"serde",
@@ -4357,7 +4357,7 @@ dependencies = [
[[package]]
name = "ide-extension"
version = "0.1.48"
version = "0.1.47"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4378,7 +4378,7 @@ dependencies = [
[[package]]
name = "ide-fonts"
version = "0.1.48"
version = "0.1.47"
dependencies = [
"objc2-core-foundation",
"objc2-core-text",
@@ -4390,7 +4390,7 @@ dependencies = [
[[package]]
name = "ide-github"
version = "0.1.48"
version = "0.1.47"
dependencies = [
"ide-core",
"ide-vcs",
@@ -4403,7 +4403,7 @@ dependencies = [
[[package]]
name = "ide-heap"
version = "0.1.48"
version = "0.1.47"
dependencies = [
"criterion",
"ide-core",
@@ -4421,7 +4421,7 @@ dependencies = [
[[package]]
name = "ide-host"
version = "0.1.48"
version = "0.1.47"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4495,7 +4495,7 @@ dependencies = [
[[package]]
name = "ide-http"
version = "0.1.48"
version = "0.1.47"
dependencies = [
"ide-core",
"ide-vfs",
@@ -4514,7 +4514,7 @@ dependencies = [
[[package]]
name = "ide-index"
version = "0.1.48"
version = "0.1.47"
dependencies = [
"blake3",
"criterion",
@@ -4536,7 +4536,7 @@ dependencies = [
[[package]]
name = "ide-jdwp"
version = "0.1.48"
version = "0.1.47"
dependencies = [
"ide-jvm-inspect",
"proptest",
@@ -4548,7 +4548,7 @@ dependencies = [
[[package]]
name = "ide-jsonrpc"
version = "0.1.48"
version = "0.1.47"
dependencies = [
"encoding_rs",
"futures",
@@ -4565,7 +4565,7 @@ dependencies = [
[[package]]
name = "ide-jvm-attach"
version = "0.1.48"
version = "0.1.47"
dependencies = [
"libc",
"tempfile",
@@ -4574,7 +4574,7 @@ dependencies = [
[[package]]
name = "ide-jvm-inspect"
version = "0.1.48"
version = "0.1.47"
dependencies = [
"futures",
"serde",
@@ -4585,7 +4585,7 @@ dependencies = [
[[package]]
name = "ide-language"
version = "0.1.48"
version = "0.1.47"
dependencies = [
"blake3",
"criterion",
@@ -4644,7 +4644,7 @@ dependencies = [
[[package]]
name = "ide-lsp"
version = "0.1.48"
version = "0.1.47"
dependencies = [
"dunce",
"encoding_rs",
@@ -4672,7 +4672,7 @@ dependencies = [
[[package]]
name = "ide-mcp"
version = "0.1.48"
version = "0.1.47"
dependencies = [
"bytes",
"dunce",
@@ -4691,7 +4691,7 @@ dependencies = [
[[package]]
name = "ide-notebook"
version = "0.1.48"
version = "0.1.47"
dependencies = [
"futures",
"ide-core",
@@ -4714,7 +4714,7 @@ dependencies = [
[[package]]
name = "ide-plugin"
version = "0.1.48"
version = "0.1.47"
dependencies = [
"blake3",
"dunce",
@@ -4737,7 +4737,7 @@ dependencies = [
[[package]]
name = "ide-profiler"
version = "0.1.48"
version = "0.1.47"
dependencies = [
"ide-core",
"ide-jvm-attach",
@@ -4751,7 +4751,7 @@ dependencies = [
[[package]]
name = "ide-remote"
version = "0.1.48"
version = "0.1.47"
dependencies = [
"dunce",
"futures",
@@ -4771,7 +4771,7 @@ dependencies = [
[[package]]
name = "ide-run"
version = "0.1.48"
version = "0.1.47"
dependencies = [
"dunce",
"encoding_rs",
@@ -4795,7 +4795,7 @@ dependencies = [
[[package]]
name = "ide-scaffold"
version = "0.1.48"
version = "0.1.47"
dependencies = [
"ide-core",
"ide-tools",
@@ -4811,7 +4811,7 @@ dependencies = [
[[package]]
name = "ide-sdk"
version = "0.1.48"
version = "0.1.47"
dependencies = [
"dunce",
"flate2",
@@ -4834,7 +4834,7 @@ dependencies = [
[[package]]
name = "ide-search"
version = "0.1.48"
version = "0.1.47"
dependencies = [
"criterion",
"encoding_rs",
@@ -4855,7 +4855,7 @@ dependencies = [
[[package]]
name = "ide-spell"
version = "0.1.48"
version = "0.1.47"
dependencies = [
"ide-core",
"parking_lot",
@@ -4868,7 +4868,7 @@ dependencies = [
[[package]]
name = "ide-ssh"
version = "0.1.48"
version = "0.1.47"
dependencies = [
"dirs 6.0.0",
"flate2",
@@ -4893,7 +4893,7 @@ dependencies = [
[[package]]
name = "ide-streams"
version = "0.1.48"
version = "0.1.47"
dependencies = [
"ide-core",
"ide-language",
@@ -4906,7 +4906,7 @@ dependencies = [
[[package]]
name = "ide-syntax"
version = "0.1.48"
version = "0.1.47"
dependencies = [
"ide-core",
"ide-language",
@@ -4921,7 +4921,7 @@ dependencies = [
[[package]]
name = "ide-terminal"
version = "0.1.48"
version = "0.1.47"
dependencies = [
"ide-core",
"libc",
@@ -4934,7 +4934,7 @@ dependencies = [
[[package]]
name = "ide-text"
version = "0.1.48"
version = "0.1.47"
dependencies = [
"criterion",
"ide-core",
@@ -4947,7 +4947,7 @@ dependencies = [
[[package]]
name = "ide-tools"
version = "0.1.48"
version = "0.1.47"
dependencies = [
"flate2",
"hex",
@@ -4968,7 +4968,7 @@ dependencies = [
[[package]]
name = "ide-vcs"
version = "0.1.48"
version = "0.1.47"
dependencies = [
"blake3",
"dunce",
@@ -4989,7 +4989,7 @@ dependencies = [
[[package]]
name = "ide-vfs"
version = "0.1.48"
version = "0.1.47"
dependencies = [
"chardetng",
"dunce",
@@ -5015,7 +5015,7 @@ dependencies = [
[[package]]
name = "ide-web"
version = "0.1.48"
version = "0.1.47"
dependencies = [
"dirs 6.0.0",
"ide-core",
@@ -5031,7 +5031,7 @@ dependencies = [
[[package]]
name = "ide-workspace"
version = "0.1.48"
version = "0.1.47"
dependencies = [
"blake3",
"dunce",
@@ -6660,7 +6660,7 @@ dependencies = [
[[package]]
name = "openidea"
version = "0.1.48"
version = "0.1.47"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -6734,7 +6734,6 @@ dependencies = [
"tracing",
"tracing-appender",
"tracing-subscriber",
"webview2-com",
"windows",
"windows-sys 0.61.2",
]
+1 -1
View File
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
exclude = ["sdk", "plugins"]
[workspace.package]
version = "0.1.48"
version = "0.1.47"
edition = "2024"
rust-version = "1.96"
license = "Apache-2.0"
+51 -438
View File
@@ -399,429 +399,163 @@ pub fn apply_save_json(
Ok(saved_names)
}
const COPILOT_PLUGIN_MANIFESTS: &[&str] = &[
".github/plugin/plugin.json",
".plugin/plugin.json",
".claude-plugin/plugin.json",
".cursor-plugin/plugin.json",
"plugin.json",
];
#[derive(Clone, PartialEq, Eq)]
#[derive(Clone, Copy, PartialEq, Eq)]
enum SourceFormat {
Jsonc,
CodexToml,
CopilotPlugin { root: PathBuf },
}
#[derive(Clone)]
struct SourceSpec {
id: String,
label: String,
id: &'static str,
label: &'static str,
path: PathBuf,
format: SourceFormat,
suggested_scope: McpScope,
native_provider: Option<&'static str>,
claude_project_lookup: bool,
disabled_servers: std::sync::Arc<BTreeSet<String>>,
}
#[derive(Default)]
struct CopilotSettings {
disabled_mcp_servers: std::sync::Arc<BTreeSet<String>>,
disabled_plugins: BTreeSet<String>,
}
fn external_source_specs(home_dir: Option<&Path>, workspace_root: Option<&Path>) -> Vec<SourceSpec> {
let mut specs = Vec::new();
let no_disabled: std::sync::Arc<BTreeSet<String>> = std::sync::Arc::new(BTreeSet::new());
if let Some(root) = workspace_root {
specs.push(SourceSpec {
id: "workspace-mcp".into(),
label: "Project (.mcp.json)".into(),
id: "workspace-mcp",
label: "Project (.mcp.json)",
path: root.join(".mcp.json"),
format: SourceFormat::Jsonc,
suggested_scope: McpScope::Workspace,
native_provider: Some("claude"),
claude_project_lookup: false,
disabled_servers: no_disabled.clone(),
});
specs.push(SourceSpec {
id: "vscode-mcp".into(),
label: "VS Code (.vscode/mcp.json)".into(),
id: "vscode-mcp",
label: "VS Code (.vscode/mcp.json)",
path: root.join(".vscode").join("mcp.json"),
format: SourceFormat::Jsonc,
suggested_scope: McpScope::Workspace,
native_provider: None,
claude_project_lookup: false,
disabled_servers: no_disabled.clone(),
});
specs.push(SourceSpec {
id: "cursor-project".into(),
label: "Cursor Project (.cursor/mcp.json)".into(),
id: "cursor-project",
label: "Cursor Project (.cursor/mcp.json)",
path: root.join(".cursor").join("mcp.json"),
format: SourceFormat::Jsonc,
suggested_scope: McpScope::Workspace,
native_provider: Some("cursor"),
claude_project_lookup: false,
disabled_servers: no_disabled.clone(),
});
specs.push(SourceSpec {
id: "codex-project".into(),
label: "Codex Project (.codex/config.toml)".into(),
id: "codex-project",
label: "Codex Project (.codex/config.toml)",
path: root.join(".codex").join("config.toml"),
format: SourceFormat::CodexToml,
suggested_scope: McpScope::Workspace,
native_provider: Some("codex"),
claude_project_lookup: false,
disabled_servers: no_disabled.clone(),
});
specs.push(SourceSpec {
id: "gemini-project".into(),
label: "Gemini Project (.gemini/settings.json)".into(),
id: "gemini-project",
label: "Gemini Project (.gemini/settings.json)",
path: root.join(".gemini").join("settings.json"),
format: SourceFormat::Jsonc,
suggested_scope: McpScope::Workspace,
native_provider: Some("gemini"),
claude_project_lookup: false,
disabled_servers: no_disabled.clone(),
});
}
if let Some(home) = home_dir {
let copilot_dir = home.join(".copilot");
let copilot_settings = read_copilot_settings(&copilot_dir);
specs.push(SourceSpec {
id: "copilot-cli".into(),
label: "GitHub Copilot CLI".into(),
path: copilot_dir.join("mcp-config.json"),
id: "copilot-cli",
label: "GitHub Copilot CLI",
path: home.join(".copilot").join("mcp-config.json"),
format: SourceFormat::Jsonc,
suggested_scope: McpScope::User,
native_provider: Some("copilot"),
claude_project_lookup: false,
disabled_servers: copilot_settings.disabled_mcp_servers.clone(),
});
specs.extend(copilot_plugin_source_specs(&copilot_dir, &copilot_settings));
specs.push(SourceSpec {
id: "claude-code".into(),
label: "Claude Code".into(),
id: "claude-code",
label: "Claude Code",
path: home.join(".claude.json"),
format: SourceFormat::Jsonc,
suggested_scope: McpScope::User,
native_provider: Some("claude"),
claude_project_lookup: true,
disabled_servers: no_disabled.clone(),
});
specs.push(SourceSpec {
id: "codex".into(),
label: "Codex".into(),
id: "codex",
label: "Codex",
path: home.join(".codex").join("config.toml"),
format: SourceFormat::CodexToml,
suggested_scope: McpScope::User,
native_provider: Some("codex"),
claude_project_lookup: false,
disabled_servers: no_disabled.clone(),
});
specs.push(SourceSpec {
id: "cursor".into(),
label: "Cursor".into(),
id: "cursor",
label: "Cursor",
path: home.join(".cursor").join("mcp.json"),
format: SourceFormat::Jsonc,
suggested_scope: McpScope::User,
native_provider: Some("cursor"),
claude_project_lookup: false,
disabled_servers: no_disabled.clone(),
});
specs.push(SourceSpec {
id: "gemini".into(),
label: "Gemini CLI".into(),
id: "gemini",
label: "Gemini CLI",
path: home.join(".gemini").join("settings.json"),
format: SourceFormat::Jsonc,
suggested_scope: McpScope::User,
native_provider: Some("gemini"),
claude_project_lookup: false,
disabled_servers: no_disabled.clone(),
});
specs.push(SourceSpec {
id: "jetbrains-air".into(),
label: "JetBrains Air".into(),
id: "jetbrains-air",
label: "JetBrains Air",
path: home.join(".jetbrains").join("mcp").join("mcp.json"),
format: SourceFormat::Jsonc,
suggested_scope: McpScope::User,
native_provider: None,
claude_project_lookup: false,
disabled_servers: no_disabled.clone(),
});
specs.push(SourceSpec {
id: "copilot-intellij".into(),
label: "GitHub Copilot (JetBrains)".into(),
id: "copilot-intellij",
label: "GitHub Copilot (JetBrains)",
path: home.join(".config").join("github-copilot").join("intellij").join("mcp.json"),
format: SourceFormat::Jsonc,
suggested_scope: McpScope::User,
native_provider: None,
claude_project_lookup: false,
disabled_servers: no_disabled,
});
}
specs
}
fn read_copilot_settings(copilot_dir: &Path) -> CopilotSettings {
let Ok(text) = std::fs::read_to_string(copilot_dir.join("settings.json")) else {
return CopilotSettings::default();
};
let Ok(root) = parse_jsonc_value(&text) else {
return CopilotSettings::default();
};
let disabled_mcp_servers = root
.get("disabledMcpServers")
.and_then(Value::as_array)
.map(|arr| {
arr.iter()
.filter_map(|v| v.as_str().map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned))
.collect::<BTreeSet<_>>()
})
.unwrap_or_default();
let disabled_plugins = root
.get("enabledPlugins")
.and_then(Value::as_object)
.map(|obj| {
obj.iter()
.filter(|(_, v)| v.as_bool() == Some(false))
.map(|(k, _)| k.trim().to_owned())
.filter(|k| !k.is_empty())
.collect::<BTreeSet<_>>()
})
.unwrap_or_default();
CopilotSettings { disabled_mcp_servers: std::sync::Arc::new(disabled_mcp_servers), disabled_plugins }
}
fn copilot_plugin_source_specs(copilot_dir: &Path, settings: &CopilotSettings) -> Vec<SourceSpec> {
let Ok(text) = std::fs::read_to_string(copilot_dir.join("config.json")) else {
return Vec::new();
};
let Ok(root) = parse_jsonc_value(&text) else {
return Vec::new();
};
let Some(installed) = root.get("installedPlugins").and_then(Value::as_array) else {
return Vec::new();
};
let mut seen_ids = HashSet::new();
let mut specs = Vec::new();
for entry in installed {
let Some(obj) = entry.as_object() else { continue };
if obj.get("enabled").and_then(Value::as_bool) == Some(false) {
continue;
}
let Some(name) = obj.get("name").and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()) else {
continue;
};
let marketplace = obj.get("marketplace").and_then(Value::as_str).map(str::trim).unwrap_or_default();
if settings.disabled_plugins.contains(name)
|| (!marketplace.is_empty()
&& (settings.disabled_plugins.contains(&format!("{name}@{marketplace}"))
|| settings.disabled_plugins.contains(&format!("{marketplace}/{name}"))))
{
continue;
}
let Some(raw_cache) = obj.get("cache_path").and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty())
else {
continue;
};
let plugin_root =
if Path::new(raw_cache).is_relative() { copilot_dir.join(raw_cache) } else { PathBuf::from(raw_cache) };
if !plugin_root.is_dir() {
continue;
}
let Some((manifest_path, _)) = read_copilot_plugin_servers(&plugin_root) else {
continue;
};
let base_id = if marketplace.is_empty() {
format!("copilot-plugin:{name}")
} else {
format!("copilot-plugin:{marketplace}/{name}")
};
let mut id = base_id.clone();
let mut suffix = 2usize;
while !seen_ids.insert(id.clone()) {
id = format!("{base_id}#{suffix}");
suffix += 1;
}
let label = if marketplace.is_empty() {
format!("GitHub Copilot Plugin ({name})")
} else {
format!("GitHub Copilot Plugin ({name} · {marketplace})")
};
specs.push(SourceSpec {
id,
label,
path: manifest_path,
format: SourceFormat::CopilotPlugin { root: plugin_root },
suggested_scope: McpScope::User,
native_provider: Some("copilot"),
claude_project_lookup: false,
disabled_servers: settings.disabled_mcp_servers.clone(),
});
}
specs
}
fn resolve_within_dir(base_dir: &Path, candidate: &Path) -> Option<PathBuf> {
if candidate.as_os_str().is_empty() {
return None;
}
let base_canon = dunce::canonicalize(base_dir).ok()?;
let clean = candidate.strip_prefix(".").unwrap_or(candidate);
let joined = if clean.is_relative() { base_dir.join(clean) } else { clean.to_path_buf() };
let meta = std::fs::metadata(&joined).ok()?;
if !meta.is_file() {
return None;
}
let target_canon = dunce::canonicalize(&joined).ok()?;
target_canon.starts_with(&base_canon).then_some(joined)
}
fn expand_plugin_root_vars(value: &str, root: &str) -> String {
value.replace("${COPILOT_PLUGIN_ROOT}", root).replace("${CLAUDE_PLUGIN_ROOT}", root).replace("${PLUGIN_ROOT}", root)
}
fn expand_plugin_servers(servers: &mut BTreeMap<String, AgentMcpServer>, plugin_root: &Path) {
let root = plugin_root.to_string_lossy();
for srv in servers.values_mut() {
if let Some(cmd) = srv.command.as_mut() {
*cmd = expand_plugin_root_vars(cmd, &root);
}
for arg in &mut srv.args {
*arg = expand_plugin_root_vars(arg, &root);
}
if let Some(url) = srv.url.as_mut() {
*url = expand_plugin_root_vars(url, &root);
}
for val in srv.env.values_mut() {
*val = expand_plugin_root_vars(val, &root);
}
for val in srv.headers.values_mut() {
*val = expand_plugin_root_vars(val, &root);
}
}
}
fn extract_plugin_manifest_servers(
plugin_root: &Path,
manifest_path: &Path,
mcp_val: &Value,
) -> (PathBuf, BTreeMap<String, AgentMcpServer>) {
match mcp_val {
Value::String(rel) => {
if let Some(path) = resolve_within_dir(plugin_root, Path::new(rel.trim())) {
let map = read_external_file(&path);
return (path, map);
}
(manifest_path.to_path_buf(), BTreeMap::new())
}
Value::Object(_) => {
let wrapper = json!({ "mcpServers": mcp_val });
(manifest_path.to_path_buf(), extract_servers_from_root(&wrapper, None))
}
Value::Array(items) => {
let mut merged = BTreeMap::new();
let mut first_path: Option<PathBuf> = None;
for item in items {
match item {
Value::String(rel) => {
if let Some(path) = resolve_within_dir(plugin_root, Path::new(rel.trim())) {
let map = read_external_file(&path);
if !map.is_empty() && first_path.is_none() {
first_path = Some(path);
}
merged.extend(map);
}
}
Value::Object(_) => {
let map = extract_servers_from_root(item, None);
if !map.is_empty() && first_path.is_none() {
first_path = Some(manifest_path.to_path_buf());
}
merged.extend(map);
}
_ => {}
}
}
(first_path.unwrap_or_else(|| manifest_path.to_path_buf()), merged)
}
_ => (manifest_path.to_path_buf(), BTreeMap::new()),
}
}
fn read_copilot_plugin_servers(plugin_root: &Path) -> Option<(PathBuf, BTreeMap<String, AgentMcpServer>)> {
if let Some(dot_mcp) = resolve_within_dir(plugin_root, Path::new(".mcp.json")) {
let mut servers = read_external_file(&dot_mcp);
if !servers.is_empty() {
expand_plugin_servers(&mut servers, plugin_root);
return Some((dot_mcp, servers));
}
}
for rel in COPILOT_PLUGIN_MANIFESTS {
let Some(manifest_path) = resolve_within_dir(plugin_root, Path::new(rel)) else {
continue;
};
let Ok(text) = std::fs::read_to_string(&manifest_path) else {
continue;
};
let Ok(manifest) = parse_jsonc_value(&text) else {
continue;
};
let Some(mcp_val) = manifest.get("mcpServers") else {
continue;
};
let (source_path, mut servers) = extract_plugin_manifest_servers(plugin_root, &manifest_path, mcp_val);
if !servers.is_empty() {
expand_plugin_servers(&mut servers, plugin_root);
return Some((source_path, servers));
}
}
None
}
fn read_source_servers(spec: &SourceSpec, workspace_root: Option<&Path>) -> BTreeMap<String, AgentMcpServer> {
let mut servers = match &spec.format {
SourceFormat::CopilotPlugin { root } => {
read_copilot_plugin_servers(root).map(|(_, map)| map).unwrap_or_default()
}
SourceFormat::CodexToml => {
let Ok(text) = std::fs::read_to_string(&spec.path) else {
return BTreeMap::new();
};
parse_codex_toml_servers(&text)
}
SourceFormat::Jsonc => {
let Ok(text) = std::fs::read_to_string(&spec.path) else {
return BTreeMap::new();
};
let Ok(root) = parse_jsonc_value(&text) else {
return BTreeMap::new();
};
let mut map = extract_servers_from_root(&root, None);
if spec.claude_project_lookup
&& let Some(ws) = workspace_root
&& let Some(projects) = root.get("projects").and_then(Value::as_object)
{
let ws_canon = dunce::canonicalize(ws).unwrap_or_else(|_| ws.to_path_buf());
for (proj_key, proj_val) in projects {
let matches =
Path::new(proj_key) == ws || dunce::canonicalize(proj_key).is_ok_and(|c| c == ws_canon);
if matches {
for (name, srv) in extract_servers_from_root(proj_val, None) {
map.insert(name, srv);
}
}
let Ok(text) = std::fs::read_to_string(&spec.path) else {
return BTreeMap::new();
};
if spec.format == SourceFormat::CodexToml {
return parse_codex_toml_servers(&text);
}
let Ok(root) = parse_jsonc_value(&text) else {
return BTreeMap::new();
};
let mut servers = extract_servers_from_root(&root, None);
if spec.claude_project_lookup
&& let Some(ws) = workspace_root
&& let Some(projects) = root.get("projects").and_then(Value::as_object)
{
let ws_canon = dunce::canonicalize(ws).unwrap_or_else(|_| ws.to_path_buf());
for (proj_key, proj_val) in projects {
let matches = Path::new(proj_key) == ws || dunce::canonicalize(proj_key).is_ok_and(|c| c == ws_canon);
if matches {
for (name, srv) in extract_servers_from_root(proj_val, None) {
servers.insert(name, srv);
}
}
map
}
};
for name in spec.disabled_servers.iter() {
if let Some(srv) = servers.get_mut(name) {
srv.enabled = false;
}
}
servers
@@ -878,8 +612,8 @@ pub fn discover_external_sources(home_dir: Option<&Path>, workspace_root: Option
})
.collect();
out.push(McpExternalSource {
id: spec.id,
label: spec.label,
id: spec.id.to_owned(),
label: spec.label.to_owned(),
path: IpcPath(spec.path),
suggested_scope: spec.suggested_scope,
native_provider: spec.native_provider.map(str::to_owned),
@@ -907,7 +641,7 @@ pub fn apply_import_selected(
let mut by_source: BTreeMap<&str, BTreeMap<String, AgentMcpServer>> = BTreeMap::new();
for spec in &specs {
if selections.iter().any(|s| s.source_id == spec.id) {
by_source.insert(spec.id.as_str(), read_source_servers(spec, workspace_root));
by_source.insert(spec.id, read_source_servers(spec, workspace_root));
}
}
let target = match scope {
@@ -1636,125 +1370,4 @@ mod tests {
assert_eq!(workspace["events-sse"].transport, McpTransport::Sse);
assert_eq!(workspace["events-sse"].url.as_deref(), Some("https://sse.example.com/events"));
}
#[test]
fn discovers_and_imports_copilot_installed_plugin_mcp_servers() {
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path().join("home");
let copilot = home.join(".copilot");
let azure_root = copilot.join("installed-plugins/_direct/azure-skills");
let inline_root = copilot.join("installed-plugins/awesome-copilot/inline-tools");
let disabled_root = copilot.join("installed-plugins/_direct/disabled-plug");
let outside_root = tmp.path().join("outside");
std::fs::create_dir_all(azure_root.join(".plugin")).unwrap();
std::fs::create_dir_all(inline_root.join(".claude-plugin")).unwrap();
std::fs::create_dir_all(&disabled_root).unwrap();
std::fs::create_dir_all(&outside_root).unwrap();
std::fs::write(
azure_root.join(".plugin/plugin.json"),
r#"{"name":"azure","version":"1.2.106","mcpServers":"./.mcp.json"}"#,
)
.unwrap();
std::fs::write(
azure_root.join(".mcp.json"),
r#"{"mcpServers":{"azure":{"command":"npx","args":["-y","@azure/mcp@latest","${COPILOT_PLUGIN_ROOT}/cfg"],"env":{"PLUG_DIR":"${CLAUDE_PLUGIN_ROOT}"}}}}"#,
)
.unwrap();
std::fs::write(
inline_root.join(".claude-plugin/plugin.json"),
r#"{"name":"inline-tools","version":"0.1.0","mcpServers":{"inline-srv":{"command":"${PLUGIN_ROOT}/bin/run","args":["--stdio"]},"muted-srv":{"command":"echo","args":["off"]}}}"#,
)
.unwrap();
std::fs::write(
disabled_root.join(".mcp.json"),
r#"{"mcpServers":{"never":{"command":"npx","args":["never"]}}}"#,
)
.unwrap();
std::fs::write(outside_root.join("secret.json"), r#"{"mcpServers":{"escaped":{"command":"sh"}}}"#).unwrap();
let escape_root = copilot.join("installed-plugins/_direct/escape-plug");
std::fs::create_dir_all(escape_root.join(".plugin")).unwrap();
std::fs::write(
escape_root.join(".plugin/plugin.json"),
r#"{"name":"escape-plug","mcpServers":"../../../../outside/secret.json"}"#,
)
.unwrap();
// `~/.copilot/config.json` includes leading `//` comments in Copilot CLI.
let config_json = format!(
"// Managed automatically.\n{}",
serde_json::json!({
"installedPlugins": [
{
"name": "azure",
"marketplace": "",
"enabled": true,
"cache_path": azure_root,
},
{
"name": "inline-tools",
"marketplace": "awesome-copilot",
"enabled": true,
"cache_path": inline_root,
},
{
"name": "disabled-plug",
"marketplace": "",
"enabled": false,
"cache_path": disabled_root,
},
{
"name": "escape-plug",
"marketplace": "",
"enabled": true,
"cache_path": escape_root,
}
]
})
);
std::fs::write(copilot.join("config.json"), config_json).unwrap();
std::fs::write(copilot.join("settings.json"), r#"{"disabledMcpServers":["muted-srv"]}"#).unwrap();
let sources = discover_external_sources(Some(&home), None);
assert_eq!(sources.len(), 2);
let azure_src = sources.iter().find(|s| s.id == "copilot-plugin:azure").unwrap();
assert_eq!(azure_src.label, "GitHub Copilot Plugin (azure)");
assert_eq!(azure_src.native_provider.as_deref(), Some("copilot"));
assert_eq!(azure_src.path.0, azure_root.join(".mcp.json"));
assert_eq!(azure_src.servers.len(), 1);
assert!(azure_src.servers[0].enabled);
assert_eq!(
azure_src.servers[0].args,
vec!["-y", "@azure/mcp@latest", &format!("{}/cfg", azure_root.display())]
);
let inline_src = sources.iter().find(|s| s.id == "copilot-plugin:awesome-copilot/inline-tools").unwrap();
assert_eq!(inline_src.label, "GitHub Copilot Plugin (inline-tools · awesome-copilot)");
assert_eq!(inline_src.path.0, inline_root.join(".claude-plugin/plugin.json"));
let active = inline_src.servers.iter().find(|s| s.name == "inline-srv").unwrap();
assert!(active.enabled);
assert_eq!(active.command.as_deref(), Some(format!("{}/bin/run", inline_root.display()).as_str()));
let muted = inline_src.servers.iter().find(|s| s.name == "muted-srv").unwrap();
assert!(!muted.enabled);
let mut user = BTreeMap::new();
let mut workspace = BTreeMap::new();
let imported = apply_import_selected(
&mut user,
&mut workspace,
Some(&home),
None,
McpScope::User,
&[McpImportSelection { source_id: "copilot-plugin:azure".into(), name: "azure".into() }],
false,
)
.unwrap();
assert_eq!(imported, vec!["azure".to_string()]);
assert_eq!(user["azure"].env.get("PLUG_DIR").map(String::as_str), Some(azure_root.to_str().unwrap()));
}
}
+6 -21
View File
@@ -1241,13 +1241,10 @@ fn file_stamp(path: &Path) -> FileStamp {
std::fs::metadata(path).ok().map(|m| (m.modified().ok(), m.len()))
}
/// The POM files a reactor walk read or looked for, the module folders it found outside the
/// root, and the folders of every project in the reactor (canonical, the root's first).
#[derive(Clone)]
/// The POM files a reactor walk read or looked for, and the module folders it found outside the root.
struct ReactorScan {
stamps: Vec<(PathBuf, FileStamp)>,
dirs: Vec<PathBuf>,
members: Vec<PathBuf>,
}
/// Folders of the modules that the reactor of `root/pom.xml` lists outside `root`
@@ -1257,28 +1254,18 @@ struct ReactorScan {
/// Callers keep the outermost directory only. Memoized on the POMs' modification times and
/// sizes: content roots are read on hot paths (every references search, Find in Files).
pub fn reactor_external_dirs(root: &Path, profiles: &[String], unlinked: &[String]) -> Vec<PathBuf> {
reactor(root, profiles, unlinked).dirs
}
/// Folders of every project in the reactor of `root/pom.xml` (canonical): `root` itself and its
/// modules, theirs in turn, including those of the active `profiles`. A POM elsewhere below `root`
/// that no `<module>` reaches is a separate build.
pub fn reactor_member_dirs(root: &Path, profiles: &[String]) -> Vec<PathBuf> {
reactor(root, profiles, &[]).members
}
fn reactor(root: &Path, profiles: &[String], unlinked: &[String]) -> ReactorScan {
type Memo = HashMap<(PathBuf, Vec<String>, Vec<String>), ReactorScan>;
static MEMO: std::sync::LazyLock<Mutex<Memo>> = std::sync::LazyLock::new(Default::default);
let key = (root.to_path_buf(), profiles.to_vec(), unlinked.to_vec());
if let Some(scan) = MEMO.lock().unwrap_or_else(|e| e.into_inner()).get(&key)
&& scan.stamps.iter().all(|(path, stamp)| file_stamp(path) == *stamp)
{
return scan.clone();
return scan.dirs.clone();
}
let scan = scan_reactor(root, profiles, unlinked);
MEMO.lock().unwrap_or_else(|e| e.into_inner()).insert(key, scan.clone());
scan
let dirs = scan.dirs.clone();
MEMO.lock().unwrap_or_else(|e| e.into_inner()).insert(key, scan);
dirs
}
/// Reads only the POMs the reactor lists (no parent resolution and no directory walk).
@@ -1287,8 +1274,7 @@ fn scan_reactor(root: &Path, profiles: &[String], unlinked: &[String]) -> Reacto
let chosen = Resolver::new(None, profiles);
let unlinked: HashSet<String> = unlinked.iter().map(|p| normalized_pom(p.trim())).collect();
let first = root.join("pom.xml");
let mut scan =
ReactorScan { stamps: vec![(first.clone(), file_stamp(&first))], dirs: Vec::new(), members: Vec::new() };
let mut scan = ReactorScan { stamps: vec![(first.clone(), file_stamp(&first))], dirs: Vec::new() };
let mut seen: HashSet<PathBuf> = HashSet::new();
let mut pending = vec![first];
while let Some(path) = pending.pop() {
@@ -1302,7 +1288,6 @@ fn scan_reactor(root: &Path, profiles: &[String], unlinked: &[String]) -> Reacto
let Some(pom) = xml::read_text(&path).as_deref().and_then(parse_pom) else { continue };
let dir = path.parent().unwrap_or(root).to_path_buf();
let dir_canon = dunce::canonicalize(&dir).unwrap_or_else(|_| dir.clone());
scan.members.push(dir_canon.clone());
if !dir_canon.starts_with(&canonical_root) {
if canonical_root.starts_with(&dir_canon) {
continue;
-6
View File
@@ -446,12 +446,6 @@ pub struct LanguageCodeStyle {
/// Comment Code › Add a space at line comment start.
#[serde(skip_serializing_if = "Option::is_none")]
pub line_comment_add_space: Option<bool>,
/// PHP: align `=>` in multi-line arrays after formatting (other languages ignore it).
#[serde(skip_serializing_if = "Option::is_none")]
pub align_key_value_pairs: Option<bool>,
/// PHP: align `=` of consecutive assignment statements after formatting.
#[serde(skip_serializing_if = "Option::is_none")]
pub align_consecutive_assignments: Option<bool>,
}
/// Editor › Code Style (General tab + per-language overrides).
+3 -5
View File
@@ -1062,13 +1062,11 @@ mod tests {
#[test]
fn a_child_inside_a_project_gets_its_environment() {
let root = std::path::Path::new("/openidea-test-process/project");
// Absolute on the platform: the search path drops relative entries.
let devshell = if cfg!(windows) { r"C:\nix\store\x-devshell\bin" } else { "/nix/store/x-devshell/bin" };
crate::project_env::set(
root,
vec![
("OPENIDEA_PROJECT_VAR".into(), Some("devshell".into())),
("PATH".into(), Some(devshell.into())),
("PATH".into(), Some("/nix/store/x-devshell/bin".into())),
("OPENIDEA_PROJECT_UNSET".into(), None),
],
);
@@ -1077,7 +1075,7 @@ mod tests {
let mut inside = Command::new("true");
inside.current_dir(root.join("src")).env("OPENIDEA_PROJECT_VAR", "call site");
host_env(&mut inside);
assert_eq!(get(&inside, "PATH"), Some(Some(devshell.into())));
assert_eq!(get(&inside, "PATH"), Some(Some("/nix/store/x-devshell/bin".into())));
assert_eq!(get(&inside, "OPENIDEA_PROJECT_UNSET"), Some(None));
assert_eq!(get(&inside, "OPENIDEA_PROJECT_VAR"), Some(Some("call site".into())), "the call site's value wins");
@@ -1095,7 +1093,7 @@ mod tests {
assert_eq!(host_var_os_in(root, "OPENIDEA_PROJECT_VAR"), Some("devshell".into()));
assert_eq!(host_var_os("OPENIDEA_PROJECT_VAR"), None);
let search = crate::tool_path::search_path_in(root);
assert_eq!(std::env::split_paths(&search).next(), Some(devshell.into()));
assert_eq!(std::env::split_paths(&search).next(), Some("/nix/store/x-devshell/bin".into()));
crate::project_env::remove(root);
assert!(host_vars_in(root).all(|(k, _)| k != "OPENIDEA_PROJECT_VAR"));
}
-4
View File
@@ -1504,10 +1504,6 @@ pub struct MavenSettings {
pub active_profiles: String,
/// Delegate IDE build/run actions to Maven: launches build with Maven (`javac`) instead of jdtls (ECJ).
pub delegate_build: bool,
/// Download `-sources.jar` of dependencies when the Java language server imports the
/// project (jdtls `java.maven.downloadSources`). Off: sources are fetched on demand
/// from a library class's Download Sources banner.
pub download_sources: bool,
}
impl MavenSettings {
+1 -15
View File
@@ -216,21 +216,7 @@ pub(crate) async fn serve(
}
}
if holding {
let (disable, command) = call("Fetch.disable", json!({}));
if write.send(command).await.is_ok() {
// Wait until the proxy has disabled interception before closing the
// socket. Dropping it with unread replies can reset the connection.
let _ = tokio::time::timeout(REQUEST_TIMEOUT, async {
while let Some(Ok(message)) = read.next().await {
let Ok(text) = message.to_text() else { continue };
let Ok(reply) = serde_json::from_str::<Value>(text) else { continue };
if reply.get("id").and_then(Value::as_u64) == Some(disable) {
break;
}
}
})
.await;
}
let _ = write.send(call("Fetch.disable", json!({})).1).await;
}
let _ = write.close().await;
}
+6 -42
View File
@@ -912,7 +912,7 @@ fn on_reverse_request(mgr: &Arc<DebugManager>, s: &Arc<Session>, seq: i64, comma
/// A `runInTerminal` program and the pseudo-terminal it runs in.
pub(crate) struct ProgramTerminal {
writer: Arc<ide_core::input::InputWriter>,
writer: ide_core::input::InputWriter,
killer: Box<dyn portable_pty::ChildKiller + Send + Sync>,
#[cfg_attr(not(unix), allow(dead_code))]
pid: Option<u32>,
@@ -1025,12 +1025,10 @@ pub(crate) fn run_in_terminal(s: &Arc<Session>, args: &Value) -> Result<Value, S
let _ = child.wait();
})
.map_err(|e| format!("terminal input worker: {e}"))?;
let writer = Arc::new(writer);
let pid = child.process_id();
forward_terminal_output(
s,
reader,
writer.clone(),
#[cfg(unix)]
wait_readable,
);
@@ -1045,35 +1043,10 @@ pub(crate) fn run_in_terminal(s: &Arc<Session>, args: &Value) -> Result<Value, S
Ok(json!({ "processId": pid }))
}
/// A terminal's cursor position query (DSR). ConPTY sends one when it starts and runs the program
/// only once the terminal answers; programs that lay out a prompt ask it too.
const CURSOR_QUERY: &[u8] = b"\x1b[6n";
/// `chunk` without its cursor position queries, and how many there were.
pub(crate) fn take_cursor_queries(chunk: &[u8]) -> (Vec<u8>, usize) {
let mut out = Vec::with_capacity(chunk.len());
let mut queries = 0;
let mut rest = chunk;
while let Some(at) = rest.windows(CURSOR_QUERY.len()).position(|w| w == CURSOR_QUERY) {
out.extend_from_slice(&rest[..at]);
rest = &rest[at + CURSOR_QUERY.len()..];
queries += 1;
}
out.extend_from_slice(rest);
(out, queries)
}
/// Length of the end of `pending` that may begin a cursor position query the next read completes.
pub(crate) fn partial_cursor_query(pending: &[u8]) -> usize {
(1..CURSOR_QUERY.len()).rev().find(|&n| pending.ends_with(&CURSOR_QUERY[..n])).unwrap_or(0)
}
/// The program's terminal output, as stdout lines (`\r\n` as `\n`; colours are kept). The debug
/// console is no terminal, so cursor position queries are answered here (top-left corner).
/// The program's terminal output, as stdout lines (`\r\n` as `\n`; colours are kept).
fn forward_terminal_output(
s: &Session,
mut reader: Box<dyn std::io::Read + Send>,
answer: Arc<ide_core::input::InputWriter>,
#[cfg(unix)] mut wait_readable: impl FnMut() -> std::io::Result<()> + Send + 'static,
) {
let session = s.id;
@@ -1105,20 +1078,11 @@ fn forward_terminal_output(
break;
}
}
let (rest, queries) = take_cursor_queries(&pending);
pending = rest;
for _ in 0..queries {
if let Err(e) = answer.write(b"\x1b[1;1R") {
tracing::warn!(%session, "debug terminal cursor position: {e}");
}
}
// Keep incomplete UTF-8 sequences, a `\r` that may start a `\r\n`, and the start of
// a cursor position query for the next chunk.
let keep = partial_cursor_query(&pending);
let mut valid = match std::str::from_utf8(&pending[..pending.len() - keep]) {
Ok(_) => pending.len() - keep,
// Keep incomplete UTF-8 sequences, and a `\r` that may start a `\r\n`, for the next chunk.
let mut valid = match std::str::from_utf8(&pending) {
Ok(_) => pending.len(),
Err(e) if e.error_len().is_none() => e.valid_up_to(),
Err(_) => pending.len() - keep,
Err(_) => pending.len(),
};
if valid > 0 && pending[valid - 1] == b'\r' {
valid -= 1;
-38
View File
@@ -1010,44 +1010,6 @@ async fn run_in_terminal_spawns_debuggee() {
assert!(response["body"]["processId"].as_u64().unwrap() > 0);
}
/// The debug console answers a terminal's cursor position query: ConPTY asks one before it runs
/// the program at all (Windows debuggees never started), and programs that lay out a prompt ask too.
#[tokio::test]
async fn run_in_terminal_answers_cursor_position_queries() {
#[cfg(unix)]
let program = vec![
"sh".into(),
"-c".into(),
r"stty -echo -icanon min 6; printf '\033[6n'; reply=$(dd bs=6 count=1 2>/dev/null); stty sane; case $reply in *'[1;1R') echo answered;; esac".into(),
];
#[cfg(windows)]
let program = vec!["cmd".into(), "/c".into(), "echo answered".into()];
let h = harness(Script { run_in_terminal: Some(program), ..Script::default() });
h.start(config()).await.unwrap();
h.wait_event(|e| matches!(e, DebugEvent::Output { output, .. } if output.contains("answered"))).await;
let output: String = h
.events
.lock()
.iter()
.filter_map(|e| match e {
IdeEvent::Debug { event: DebugEvent::Output { output, .. }, .. } => Some(output.clone()),
_ => None,
})
.collect();
assert!(!output.contains("\x1b[6n"), "{output:?}");
}
#[test]
fn cursor_position_queries_are_taken_out_of_the_output() {
use crate::session::{partial_cursor_query, take_cursor_queries};
assert_eq!(take_cursor_queries(b"a\x1b[6nb\x1b[6n"), (b"ab".to_vec(), 2));
assert_eq!(take_cursor_queries(b"\x1b[0mtext"), (b"\x1b[0mtext".to_vec(), 0));
assert_eq!(partial_cursor_query(b"text\x1b["), 2);
assert_eq!(partial_cursor_query(b"text\x1b[6"), 3);
assert_eq!(partial_cursor_query(b"text\x1b[0m"), 0);
assert_eq!(partial_cursor_query(b"text"), 0);
}
#[cfg(unix)]
#[tokio::test]
async fn run_in_terminal_program_reads_typed_input() {
-31
View File
@@ -916,37 +916,6 @@ impl DbManager {
self.tunnels.lock().remove(id);
}
/// Creates a database on the server of data source `id` by running `statement` on the data
/// source's own database, after closing the IDE's connections to `template`, the database
/// the server copies (PostgreSQL and SQL Server refuse to copy one that has sessions).
pub async fn create_database(&self, id: &str, template: &str, statement: &str) -> IdeResult<()> {
let id = split_target(id).0;
if self.source(id)?.read_only {
return Err(IdeError::new(ErrorKind::PermissionDenied, "the data source is read-only"));
}
self.disconnect(&format!("{id}:{template}")).await;
self.pool(id).await?.execute(statement, 0, &CancellationToken::new()).await?;
self.remember_statement(id, statement);
Ok(())
}
/// Drops `database` of the server of data source `id` by running `statement` on the data
/// source's own database, after closing the IDE's connections to `database`.
/// Refuses the database the data source connects to and read-only data sources.
pub async fn drop_database(&self, id: &str, database: &str, statement: &str) -> IdeResult<()> {
let id = split_target(id).0;
if self.source(id)?.read_only {
return Err(IdeError::new(ErrorKind::PermissionDenied, "the data source is read-only"));
}
if self.databases(id).await?.current == database {
return Err(IdeError::invalid(format!("the data source connects to {database}; it cannot drop it")));
}
self.disconnect(&format!("{id}:{database}")).await;
self.pool(id).await?.execute(statement, 0, &CancellationToken::new()).await?;
self.remember_statement(id, statement);
Ok(())
}
/// The databases of the server of data source `id` (PostgreSQL), the connected one first.
pub async fn databases(&self, id: &str) -> IdeResult<Databases> {
let id = split_target(id).0;
-38
View File
@@ -230,44 +230,6 @@ async fn opening_a_table_reads_multi_column_keys_in_order() -> IdeResult<()> {
}
/// Runs `job` with the newest installed copy of its tool, the way the dialogs do.
#[tokio::test]
async fn drops_a_database_the_ide_holds_connections_to() -> IdeResult<()> {
let tmp = tempfile::tempdir().unwrap();
let Some(db) = manager(&tmp).await else { return Ok(()) };
let c = CancellationToken::new();
db.execute("p", "DROP DATABASE IF EXISTS oi_drop_me", 0, &c).await?;
db.execute("p", "CREATE DATABASE oi_drop_me TEMPLATE template0", 0, &c).await?;
// What the tree and a manual-commit console leave open on the database.
db.schemas("p:oi_drop_me").await?;
db.set_manual_commit("p:oi_drop_me", true).await?;
db.execute("p:oi_drop_me", "SELECT 1", 1, &c).await?;
db.drop_database("p", "oi_drop_me", "drop database oi_drop_me").await?;
assert!(!db.is_connected("p:oi_drop_me"));
assert!(!db.databases("p").await?.names.iter().any(|n| n == "oi_drop_me"));
let current = db.databases("p").await?.current;
let refused = db.drop_database("p", &current, &format!("drop database \"{current}\"")).await;
assert!(refused.is_err());
Ok(())
}
#[tokio::test]
async fn creates_a_database_from_a_template_the_ide_holds_connections_to() -> IdeResult<()> {
let tmp = tempfile::tempdir().unwrap();
let Some(db) = manager(&tmp).await else { return Ok(()) };
let c = CancellationToken::new();
db.execute("p", "DROP DATABASE IF EXISTS oi_from_template", 0, &c).await?;
db.schemas("p:template1").await?;
db.create_database("p", "template1", "create database oi_from_template").await?;
assert!(!db.is_connected("p:template1"));
assert!(db.databases("p").await?.names.iter().any(|n| n == "oi_from_template"));
db.execute("p", "DROP DATABASE oi_from_template", 0, &c).await?;
Ok(())
}
async fn run_tool(db: &DbManager, target: &str, job: ide_db::tools::DbToolJob) -> IdeResult<()> {
let install = ide_db::tools::find_installs(job.tool()).into_iter().next().expect("installed");
let mut lines = Vec::new();
-41
View File
@@ -95,44 +95,3 @@ async fn sqlserver_values_paging_transactions_and_cancellation() {
task.await.unwrap();
assert_eq!(pool.rows("SELECT 1", 1).await.unwrap()[0][0].as_deref(), Some("1"));
}
#[tokio::test]
async fn sqlserver_creates_from_a_held_model_and_force_drops_a_held_database() {
let Ok(server) = std::env::var("OPENIDEA_TEST_SQLSERVER") else { return };
let mut parts = server.splitn(4, ':');
let (host, port, user, password) = (
parts.next().unwrap(),
parts.next().unwrap().parse().unwrap(),
parts.next().unwrap(),
parts.next().unwrap_or(""),
);
let source = |database: &str| DataSource {
id: "s".into(),
name: "sqlserver".into(),
driver: DbDriver::SqlServer,
host: host.into(),
port: Some(port),
user: user.into(),
database: database.into(),
ssl: DbSslMode::Disable,
..Default::default()
};
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().to_path_buf();
let ssh = std::sync::Arc::new(ide_ssh::SshManager::new(root.join("ssh-passwords.json")));
let db = ide_db::DbManager::new(root.clone(), root.join("passwords.json"), root.join("history.json"), ssh);
db.save_sources(vec![source("master")]).await.unwrap();
db.set_password("s", Some(password.into()), false).await.unwrap();
let name = format!("oi_force_drop_{}", std::process::id());
// The tree's connection to `model` would keep SQL Server from copying it.
db.schemas("s:model").await.unwrap();
db.create_database("s", "model", &format!("create database {name};")).await.unwrap();
assert!(!db.is_connected("s:model"));
let other = Pool::connect(&source(&name), Some(password), None).await.unwrap();
let held = Held::acquire(&other).await.unwrap();
let force = format!("alter database {name} set single_user with rollback immediate;\ndrop database {name};");
db.drop_database("s", &name, &force).await.unwrap();
assert!(!db.databases("s").await.unwrap().names.contains(&name));
drop(held);
}
+11 -198
View File
@@ -2,9 +2,9 @@
use crate::Host;
use ide_core::event::NotifyLevel;
use ide_core::settings::{ExternalFormatter, LanguagesSettings, Settings};
use ide_core::{ChangeSet, DocId, IdeError, IdeEvent, IdeResult, LanguageId, Pos, Range, TextEdit};
use ide_language::{LanguageConfig, PhpAlignment, Syntax};
use ide_core::settings::{ExternalFormatter, LanguagesSettings};
use ide_core::{DocId, IdeError, IdeEvent, IdeResult, Pos, Range, TextEdit};
use ide_language::LanguageConfig;
use ide_lsp::types::FormatOptions;
use ide_tools::{Tools, formatter};
use std::path::Path;
@@ -129,101 +129,12 @@ pub async fn format(
let project = host.project(window)?;
let snap = project.documents.snapshot(doc)?;
let settings = project.settings.effective();
let alignment = php_alignment(&settings, &snap.language);
let original = alignment.any().then(|| (snap.language.clone(), snap.text.clone()));
let Some(edits) = provider_edits(host, window, &project, snap, settings, range, options).await? else {
return Ok(Vec::new());
};
let Some((language, text)) = original else {
return Ok(edits);
};
let syntax = host.syntax();
tokio::task::spawn_blocking(move || align_formatted(&syntax, &language, &text, edits, range, alignment))
.await
.map_err(|e| IdeError::internal(e.to_string()))?
}
/// PHP Code Style › Align key-value pairs / Align consecutive assignments (off by default, as in PhpStorm).
fn php_alignment(settings: &Settings, language: &LanguageId) -> PhpAlignment {
let style = settings.editor.code_style.languages.get(language.as_str());
PhpAlignment {
key_value_pairs: style.and_then(|s| s.align_key_value_pairs).unwrap_or(false),
assignments: style.and_then(|s| s.align_consecutive_assignments).unwrap_or(false),
}
}
/// The formatter's `edits` to `text` followed by the alignment, as one set of edits to `text`.
/// With a `range`, only its lines (where the formatter left them) are aligned.
fn align_formatted(
syntax: &Syntax,
language: &LanguageId,
text: &str,
edits: Vec<TextEdit>,
range: Option<Range>,
alignment: PhpAlignment,
) -> IdeResult<Vec<TextEdit>> {
let mut formatted = ide_text::Document::new(text);
// Edits the editor has to sort out itself (overlapping ones) are passed on unaligned.
let Ok((changes, _)) = formatted.apply_edits(&edits) else {
return Ok(edits);
};
let lines = range.map(|range| {
let original = ide_text::Document::new(text);
let start = formatted.offset_to_pos(map_offset(&changes, original.pos_to_offset(range.start), false));
let end = formatted.offset_to_pos(map_offset(&changes, original.pos_to_offset(range.end), true));
let last = if end.col == 0 && end.line > start.line { end.line - 1 } else { end.line };
(start.line as usize, last as usize)
});
let Some(aligned) = syntax.align_php(language, &formatted.text(), lines, alignment) else {
return Ok(edits);
};
let original = ide_text::Document::new(text);
Ok(original
.diff(&aligned)
.changes
.into_iter()
.map(|c| TextEdit {
range: Range::new(original.offset_to_pos(c.from), original.offset_to_pos(c.to)),
new_text: c.insert,
})
.collect())
}
/// Where UTF-16 `offset` of the text before `changes` ends up after them; inside a replaced
/// part, at its start or (`end`) its end.
fn map_offset(changes: &ChangeSet, offset: u32, end: bool) -> u32 {
let mut shift: i64 = 0;
for c in &changes.changes {
let inserted = c.insert.encode_utf16().count() as i64;
if c.to < offset || (c.to == offset && (c.from < c.to || end)) {
shift += inserted - i64::from(c.to - c.from);
} else if c.from < offset {
return (i64::from(c.from) + shift + if end { inserted } else { 0 }) as u32;
} else {
break;
}
}
(i64::from(offset) + shift) as u32
}
/// The edits of the formatter that handles the document; `None` when it doesn't run
/// (formatting on save is off for it).
async fn provider_edits(
host: &Host,
window: &str,
project: &crate::Project,
snap: ide_workspace::documents::DocumentInfo,
settings: Settings,
range: Option<Range>,
options: FormatOptions,
) -> IdeResult<Option<Vec<TextEdit>>> {
let doc = snap.id;
let language = project.languages.get(&snap.language);
if options.tool.is_none()
&& let Some(id) = settings.languages.plugin_formatters.get(snap.language.as_str()).filter(|s| !s.is_empty())
{
if options.on_save && !settings.editor.format_on_save {
return Ok(None);
return Ok(Vec::new());
}
if snap.read_only {
return Err(IdeError::invalid("The file is read-only"));
@@ -249,8 +160,7 @@ async fn provider_edits(
)
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?
.map(Some);
.map_err(|e| IdeError::internal(e.to_string()))?;
}
// A committed PHP-CS-Fixer configuration takes over Reformat Code for `.php` files.
if options.tool.is_none()
@@ -258,7 +168,7 @@ async fn provider_edits(
&& let Some(fixer) = formatter::php_cs_fixer(&snap.path)
{
if options.on_save && !settings.editor.format_on_save {
return Ok(None);
return Ok(Vec::new());
}
host.require_trust(window)?;
if snap.read_only {
@@ -278,7 +188,7 @@ async fn provider_edits(
body: Some("PHP-CS-Fixer does not support selection formatting; formatted the whole file".into()),
});
}
return Ok(Some(edits));
return Ok(edits);
}
let mut selected = external_tool(options.tool, language.as_ref(), &snap.path, &settings.languages)?;
if let Some(tool) = selected
@@ -290,13 +200,13 @@ async fn provider_edits(
}
let Some(selected) = selected else {
if options.on_save && !settings.editor.format_on_save {
return Ok(None);
return Ok(Vec::new());
}
return project.lsp.format(doc, range, options).await.map(Some);
return project.lsp.format(doc, range, options).await;
};
let tool_settings = settings.languages.formatter(selected);
if options.on_save && !tool_settings.run_on_save {
return Ok(None);
return Ok(Vec::new());
}
host.require_trust(window)?;
if snap.read_only {
@@ -352,7 +262,7 @@ async fn provider_edits(
)),
});
}
edits.map(Some).map_err(|e| e.with_tool(tool))
edits.map_err(|e| e.with_tool(tool))
}
#[cfg(test)]
@@ -503,103 +413,6 @@ mod tests {
);
}
fn after(text: &str, edits: &[TextEdit]) -> String {
let mut doc = ide_text::Document::new(text);
doc.apply_edits(edits).unwrap();
doc.text()
}
fn whole_file(text: &str, formatted: &str) -> Vec<TextEdit> {
let doc = ide_text::Document::new(text);
doc.diff(formatted)
.changes
.into_iter()
.map(|c| TextEdit {
range: Range::new(doc.offset_to_pos(c.from), doc.offset_to_pos(c.to)),
new_text: c.insert,
})
.collect()
}
const ALIGN: PhpAlignment = PhpAlignment { key_value_pairs: true, assignments: true };
#[test]
fn php_alignment_is_off_unless_the_php_code_style_turns_it_on() {
let php = LanguageId::new("php");
let mut settings = Settings::default();
assert_eq!(php_alignment(&settings, &php), PhpAlignment::default());
let style =
ide_core::editor_settings::LanguageCodeStyle { align_key_value_pairs: Some(true), ..Default::default() };
settings.editor.code_style.languages.insert("php".into(), style);
assert_eq!(php_alignment(&settings, &php), PhpAlignment { key_value_pairs: true, assignments: false });
assert_eq!(php_alignment(&settings, &LanguageId::new("javascript")), PhpAlignment::default());
}
#[test]
fn alignment_follows_the_formatter_edits_even_when_there_are_none() {
let syntax = Syntax::new();
let php = LanguageId::new("php");
let text = "<?php\n$a = [\n 'a' => 1,\n 'bbb' => 2,\n];\n";
let edits = align_formatted(&syntax, &php, text, Vec::new(), None, ALIGN).unwrap();
assert_eq!(after(text, &edits), "<?php\n$a = [\n 'a' => 1,\n 'bbb' => 2,\n];\n");
// The language server re-indents the array: the alignment applies to its result.
let text = "<?php\n$a = [\n'a' => 1,\n'bbb' => 2,\n];\n";
let formatted = "<?php\n$a = [\n 'a' => 1,\n 'bbb' => 2,\n];\n";
let edits = align_formatted(&syntax, &php, text, whole_file(text, formatted), None, ALIGN).unwrap();
assert_eq!(after(text, &edits), "<?php\n$a = [\n 'a' => 1,\n 'bbb' => 2,\n];\n");
let unchanged = whole_file(text, formatted);
let off = align_formatted(&syntax, &php, text, unchanged.clone(), None, PhpAlignment::default()).unwrap();
assert_eq!(off, unchanged);
let overlapping = vec![
TextEdit { range: Range::new(Pos::new(1, 0), Pos::new(1, 4)), new_text: "x".into() },
TextEdit { range: Range::new(Pos::new(1, 2), Pos::new(1, 6)), new_text: "y".into() },
];
let passed = align_formatted(&syntax, &php, text, overlapping.clone(), None, ALIGN).unwrap();
assert_eq!(passed, overlapping);
}
#[test]
fn a_selection_aligns_only_its_lines_whatever_the_formatter_changed() {
let syntax = Syntax::new();
let php = LanguageId::new("php");
let text = "<?php\n$x = 1;\n$yyy = 2;\n$a = [\n 'a' => 1,\n 'bbb' => 2,\n];\n";
// PHP-CS-Fixer formats the whole file (here: adds a line at the top) whatever the selection.
let formatted = format!("<?php\n\ndeclare(strict_types=1);\n{}", &text["<?php\n".len()..]);
let edits = whole_file(text, &formatted);
// Lines 3..=6 select the array, up to the start of the line after it.
let range = Range::new(Pos::new(3, 0), Pos::new(7, 0));
let aligned = align_formatted(&syntax, &php, text, edits, Some(range), ALIGN).unwrap();
assert_eq!(aligned.len(), 2, "one edit per changed region: {aligned:?}");
assert_eq!(
after(text, &aligned),
"<?php\n\ndeclare(strict_types=1);\n$x = 1;\n$yyy = 2;\n$a = [\n 'a' => 1,\n 'bbb' => 2,\n];\n"
);
let range = Range::new(Pos::new(1, 0), Pos::new(2, 9));
let aligned = align_formatted(&syntax, &php, text, Vec::new(), Some(range), ALIGN).unwrap();
assert_eq!(after(text, &aligned), "<?php\n$x = 1;\n$yyy = 2;\n$a = [\n 'a' => 1,\n 'bbb' => 2,\n];\n");
}
#[test]
fn offsets_map_through_changes() {
let changes = ChangeSet {
changes: vec![
ide_core::TextChange { from: 2, to: 2, insert: "ab".into() },
ide_core::TextChange { from: 5, to: 8, insert: "x".into() },
],
};
assert_eq!(map_offset(&changes, 0, false), 0);
assert_eq!(map_offset(&changes, 2, false), 2);
assert_eq!(map_offset(&changes, 2, true), 4);
assert_eq!(map_offset(&changes, 4, false), 6);
assert_eq!(map_offset(&changes, 6, false), 7);
assert_eq!(map_offset(&changes, 6, true), 8);
assert_eq!(map_offset(&changes, 8, false), 8);
assert_eq!(map_offset(&changes, 10, false), 10);
}
#[test]
fn ruff_ranges_are_one_based_unicode_columns() {
let text = ide_text::Document::new("😀x = 1\ny = 2\n");
-10
View File
@@ -253,16 +253,6 @@ impl Host {
self.project(window)?.require_trust()
}
/// [`Self::require_trust`] for IDE-wide toolchain work (SDK detection, tool installs) that
/// also runs from a window without a project, such as Settings opened from the Welcome
/// screen: there is no project there to trust.
pub fn require_trust_if_project(&self, window: &str) -> IdeResult<()> {
match self.project(window) {
Ok(project) => project.require_trust(),
Err(_) => Ok(()),
}
}
/// The window that owns what `window` starts.
pub fn owner_window<'a>(&self, window: &'a str) -> &'a str {
(self.owner)(window)
-216
View File
@@ -356,13 +356,6 @@ async fn run_to_end(call: &Call, config: RunConfig, errors: &mut BuildErrors) ->
t.drain(..cut);
}
});
let config = match resolve_jvm_application(call, config, errors).await? {
Ok(config) => config,
Err(reason) => {
errors.process_outputs.push(reason);
return Ok(false);
}
};
let info = crate::ops::run::run_start(&call.host(), call.window(), config, emit, None).await?;
let exit = wait_exit(call, info.id, None).await?.flatten();
if exit == Some(0) {
@@ -374,177 +367,6 @@ async fn run_to_end(call: &Call, config: RunConfig, errors: &mut BuildErrors) ->
Ok(false)
}
/// Run configuration kinds launched as a JVM main class (`JVM_APPLICATION_KINDS` in the UI).
const JVM_APPLICATION_KINDS: [&str; 2] = ["application", "spring-boot"];
const CLASSPATH: &str = "${classpath}";
const TEST_CLASSPATH: &str = "${testClasspath}";
/// `java` options whose value is the next argument (`parseJavaArgs` in the UI).
const JAVA_OPTIONS_WITH_VALUE: [&str; 13] = [
"-cp",
"-classpath",
"--class-path",
"-p",
"--module-path",
"--upgrade-module-path",
"--add-modules",
"--add-opens",
"--add-exports",
"--add-reads",
"--patch-module",
"--limit-modules",
"--enable-native-access",
];
/// The main class of `java` arguments and which classpath placeholder they use (`Some(true)`:
/// `${testClasspath}`; `None`: an explicit classpath or none).
fn java_main_class(args: &[String]) -> (Option<&str>, Option<bool>) {
let mut test = None;
let mut i = 0;
while i < args.len() {
let a = args[i].as_str();
if a == "-jar" {
return (None, test);
}
if matches!(a, "-cp" | "-classpath" | "--class-path") {
match args.get(i + 1).map(String::as_str) {
Some(CLASSPATH) => test = Some(false),
Some(TEST_CLASSPATH) => test = Some(true),
_ => {}
}
i += 2;
continue;
}
if JAVA_OPTIONS_WITH_VALUE.contains(&a) {
i += 2;
continue;
}
if !a.starts_with('-') {
return (Some(a), test);
}
i += 1;
}
(None, test)
}
/// `args` with the classpath placeholders replaced and the module path added (`resolveJavaCommand`).
fn resolved_java_args(args: &[String], info: &ide_lsp::jdtls::JavaLaunchInfo) -> Vec<String> {
let cp = info.class_paths.join(&info.path_list_separator);
let mut out = Vec::with_capacity(args.len() + 2);
if !info.module_paths.is_empty() && !args.iter().any(|a| a == "-p" || a == "--module-path") {
out.push("--module-path".to_owned());
out.push(info.module_paths.join(&info.path_list_separator));
}
out.extend(args.iter().map(|a| if a == CLASSPATH || a == TEST_CLASSPATH { cp.clone() } else { a.clone() }));
out
}
/// The module (relative to the project root) of a JVM source file: the part before
/// `src/<set>/<language>/` (`jvmModuleDir` without a build model).
fn jvm_module_of(rel: &str) -> Option<String> {
let rel = rel.replace('\\', "/");
let parts: Vec<&str> = rel.split('/').collect();
(0..parts.len().saturating_sub(3)).find_map(|i| {
(parts[i] == "src" && matches!(parts[i + 2], "java" | "kotlin" | "scala" | "groovy"))
.then(|| parts[..i].join("/"))
})
}
/// The module of a configuration saved without one, found from its main class's source
/// (`findJavaModule`): `None` unless exactly one module declares it.
async fn find_java_module(call: &Call, main: &str) -> IdeResult<Option<String>> {
let outer = main.split('$').next().unwrap_or(main);
let (pkg, simple) = outer.rsplit_once('.').unwrap_or(("", outer));
let mut names = vec![format!("{simple}.java"), format!("{simple}.kt")];
if let Some(stem) = simple.strip_suffix("Kt") {
names.push(format!("{stem}.kt"));
}
let mut modules = std::collections::BTreeSet::new();
for name in names {
for path in crate::ops::nav::find_files_named(&call.host(), call.window(), name).await? {
let path = std::path::PathBuf::from(path);
let Ok(text) = std::fs::read_to_string(&path) else { continue };
let declared = text
.lines()
.map(str::trim)
.find_map(|l| l.strip_prefix("package "))
.map(|p| p.trim_end_matches(';').trim())
.unwrap_or("");
if declared != pkg {
continue;
}
let rel = path.strip_prefix(call.root()).unwrap_or(&path).to_string_lossy().into_owned();
modules.insert(jvm_module_of(&rel).unwrap_or_default());
}
}
Ok((modules.len() == 1).then(|| modules.into_iter().next().unwrap_or_default()))
}
/// A JVM application configuration ready to start, as the Run tool window launches it:
/// built per its before-launch build policy, with `${classpath}` / `${testClasspath}`, the
/// module path and the module's `java` resolved through jdtls. `Err` says why it cannot start
/// (compile errors are added to `errors`). Other configurations are returned as they are.
async fn resolve_jvm_application(
call: &Call,
config: RunConfig,
errors: &mut BuildErrors,
) -> IdeResult<Result<RunConfig, String>> {
if !JVM_APPLICATION_KINDS.contains(&config.kind.as_str()) {
return Ok(Ok(config));
}
let (main, test) = java_main_class(&config.args);
let Some(main) = main.map(str::to_owned) else {
return Ok(Err(format!("No main class in '{}'", config.name)));
};
let module = match config.extras.module.clone() {
Some(module) => module,
None => match find_java_module(call, &main).await? {
Some(module) => module,
None => return Ok(Err(format!("Cannot determine the module for main class '{main}'"))),
},
};
let policy = config.extras.build_policy.unwrap_or_default();
let cancel = ide_core::CancellationToken::new();
let host = call.host();
let info = crate::ops::java::resolve_launch(
&host,
call.window(),
std::path::PathBuf::from(&module),
test == Some(true),
policy,
&cancel,
)
.await?;
use ide_lsp::jdtls::JavaBuildStatus;
if matches!(info.build, Some(JavaBuildStatus::Failed | JavaBuildStatus::WithErrors))
&& policy != ide_run::BuildPolicy::MakeAndContinueOnErrors
{
for e in &info.errors {
errors.errors.push(format!(
"{}:{}: {}",
std::path::PathBuf::from(e.path.clone()).display(),
e.line,
e.message
));
}
let reason = if info.build == Some(JavaBuildStatus::Failed) {
format!("Build failed; '{}' was not started.", config.name)
} else {
format!("Build has compile errors; '{}' was not started.", config.name)
};
return Ok(Err(reason));
}
if test.is_some() && info.class_paths.is_empty() {
return Ok(Err("The classpath is empty: is the module imported by the Java language server?".to_owned()));
}
let args = resolved_java_args(&config.args, &info);
let command = match (&info.java_exec, config.command.as_str()) {
(Some(exec), "java") => exec.clone(),
_ => config.command.clone(),
};
Ok(Ok(RunConfig { command, args, ..config }))
}
/// The configuration's before-launch tasks, as the Run tool window runs them; returns why
/// the launch is aborted, if it is. Tool windows are not activated.
async fn before_launch(
@@ -786,10 +608,6 @@ one by one",
if let Some(reason) = before_launch(&call, &config, &configs, &mut Vec::new(), &mut errors).await? {
return Err(execution_failed(&[errors.text(), Some(reason)]));
}
let config = match resolve_jvm_application(&call, config, &mut errors).await? {
Ok(config) => config,
Err(reason) => return Err(execution_failed(&[errors.text(), Some(reason)])),
};
let collector = Arc::new(Mutex::new(OutputCollector::create(&config.name)?));
let output_path = collector.lock().path.clone();
let sink = collector.clone();
@@ -866,40 +684,6 @@ provided, values are merged over existing env.",
mod tests {
use super::*;
fn strings(args: &[&str]) -> Vec<String> {
args.iter().map(|a| (*a).to_owned()).collect()
}
#[test]
fn java_arguments_name_the_main_class_and_classpath_placeholder() {
let run = strings(&["-Xmx1g", "-cp", CLASSPATH, "--add-opens", "a/b=ALL-UNNAMED", "com.example.App", "x"]);
assert_eq!(java_main_class(&run), (Some("com.example.App"), Some(false)));
assert_eq!(java_main_class(&strings(&["-classpath", TEST_CLASSPATH, "T"])), (Some("T"), Some(true)));
assert_eq!(java_main_class(&strings(&["-cp", "lib/*", "Main"])), (Some("Main"), None));
assert_eq!(java_main_class(&strings(&["-jar", "app.jar"])), (None, None));
}
#[test]
fn resolved_java_arguments_replace_the_placeholder_and_add_the_module_path() {
let info = ide_lsp::jdtls::JavaLaunchInfo {
class_paths: vec!["/p/target/classes".into(), "/m2/a.jar".into()],
module_paths: vec!["/m2/mod.jar".into()],
path_list_separator: ":".into(),
..Default::default()
};
assert_eq!(
resolved_java_args(&strings(&["-cp", CLASSPATH, "App"]), &info),
strings(&["--module-path", "/m2/mod.jar", "-cp", "/p/target/classes:/m2/a.jar", "App"])
);
}
#[test]
fn a_source_file_belongs_to_the_module_before_its_source_set() {
assert_eq!(jvm_module_of("repro-dto/src/main/java/com/example/App.java").as_deref(), Some("repro-dto"));
assert_eq!(jvm_module_of("src/test/kotlin/AppTest.kt").as_deref(), Some(""));
assert_eq!(jvm_module_of("scripts/App.java"), None);
}
fn config() -> RunConfig {
RunConfig {
id: "user:x".into(),
-28
View File
@@ -139,32 +139,6 @@ pub async fn db_disconnect(host: &Host, window: &str, id: String) -> IdeResult<(
Ok(())
}
#[command(trust = trusted)]
pub async fn db_create_database(
host: &Host,
window: &str,
id: String,
template: String,
statement: String,
) -> IdeResult<()> {
// Creates a database on the server of data source `id` with `statement`, copied from `template` (New › Database).
let db = host.project(window)?.db.clone();
db.create_database(&id, &template, &statement).await
}
#[command(trust = trusted)]
pub async fn db_drop_database(
host: &Host,
window: &str,
id: String,
database: String,
statement: String,
) -> IdeResult<()> {
// Drops `database` of the server of data source `id` with `statement` (Drop… on a database node).
let db = host.project(window)?.db.clone();
db.drop_database(&id, &database, &statement).await
}
#[command(trust = trusted)]
pub async fn db_databases(host: &Host, window: &str, id: String) -> IdeResult<Databases> {
// Databases of the server of data source `id` (PostgreSQL); connect to one as `<id>:<database>`.
@@ -504,12 +478,10 @@ ide_command::domain!(
db_connected,
db_console_path,
db_consoles,
db_create_database,
db_database_catalog,
db_databases,
db_ddl,
db_disconnect,
db_drop_database,
db_execute,
db_explain,
db_finish_transaction,
-13
View File
@@ -70,18 +70,6 @@ pub async fn doc_save(host: &Host, window: &str, doc: DocId) -> IdeResult<()> {
host.debugger.refresh_source_mirrors(host.owner_window(window)).await
}
/// An automatic save: `false` (nothing written) when the file changed on disk after the
/// buffer was edited, which only an explicit save overwrites.
#[command(trust = always)]
pub async fn doc_autosave(host: &Host, window: &str, doc: DocId) -> IdeResult<bool> {
let project = host.project(window)?;
let saved = host.blocking(move || project.documents.autosave(doc)).await?;
if saved {
host.debugger.refresh_source_mirrors(host.owner_window(window)).await?;
}
Ok(saved)
}
#[command(trust = always)]
pub async fn doc_save_all(host: &Host, window: &str) -> IdeResult<()> {
let project = host.project(window)?;
@@ -121,7 +109,6 @@ ide_command::domain!(
doc_open,
doc_open_untitled,
doc_save,
doc_autosave,
doc_save_all,
doc_save_as,
doc_snapshot,
-5
View File
@@ -311,11 +311,6 @@ async fn shutdown_does_not_wait_forever_for_a_stuck_capture() {
shutdown_within(&f.host, std::time::Duration::from_millis(200)).await;
assert!(started.elapsed() < std::time::Duration::from_secs(5));
assert!(cancel.is_cancelled());
// The cleanup is only waited for briefly and finishes in the background on a busy machine.
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
while stuck_dir.exists() && std::time::Instant::now() < deadline {
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
}
assert!(!stuck_dir.exists(), "its directory is removed once the wait is over");
}
+1 -1
View File
@@ -34,7 +34,7 @@ pub async fn java_resolve_launch(
result
}
pub(crate) async fn resolve_launch(
async fn resolve_launch(
host: &Host,
window: &str,
module: PathBuf,
+12 -86
View File
@@ -108,53 +108,27 @@ fn detected_and_saved(
}
/// Folders of the Maven / Gradle builds linked explicitly (Add Maven Projects, linked Gradle
/// builds) that detection did not reach: deeper than its folder search, or inside the folder of
/// a build it found without being one of that build's projects (a separate build nested there).
/// builds) that detection did not reach: deeper than its folder search and outside the builds
/// it found, which own their nested folders.
fn linked_build_dirs(
root: &Path,
settings: &ide_core::settings::Settings,
gradle: Option<&[ide_build::GradleModel]>,
detected: &[RunConfig],
) -> Vec<std::path::PathBuf> {
let found = |kind: &str| -> Vec<std::path::PathBuf> {
let mut dirs: Vec<_> = detected
.iter()
.filter(|c| c.kind == kind)
.map(|c| ide_core::project_roots::resolve(root, c.cwd.as_deref().unwrap_or(Path::new(""))))
.collect();
dirs.dedup();
dirs
};
let canonical = |dir: &Path| dunce::canonicalize(dir).unwrap_or_else(|_| dir.to_path_buf());
let profiles = settings.languages.java.maven.profiles(&[]);
let maven_builds = found("maven");
let found: Vec<_> = detected
.iter()
.filter(|c| matches!(c.kind.as_str(), "maven" | "gradle"))
.map(|c| ide_core::project_roots::resolve(root, c.cwd.as_deref().unwrap_or(Path::new(""))))
.collect();
let poms = settings.languages.java.maven.linked_projects.iter().filter_map(|pom| {
let pom = root.join(pom.trim());
pom.is_file().then(|| pom.parent().map(Path::to_path_buf)).flatten()
});
let maven = poms.map(|dir| ide_core::project_roots::resolve(root, &dir)).filter(|dir| {
let dir_canon = canonical(dir);
!maven_builds.iter().any(|build| {
dir.starts_with(build) && ide_build::maven::reactor_member_dirs(build, &profiles).contains(&dir_canon)
})
});
let models = gradle.unwrap_or_default();
let gradle_builds = found("gradle");
let gradle =
models.iter().map(|build| ide_core::project_roots::resolve(root, &root.join(&build.dir))).filter(|dir| {
!gradle_builds.iter().any(|build| {
dir == build
|| (dir.starts_with(build)
&& models.iter().filter(|m| root.join(&m.dir) == *build).any(|m| {
m.projects
.iter()
.any(|p| ide_core::project_roots::resolve(root, &root.join(&p.dir)) == *dir)
}))
})
});
let mut dirs: Vec<_> = maven.chain(gradle).collect();
dirs.dedup();
dirs
poms.chain(gradle.unwrap_or_default().iter().map(|build| root.join(&build.dir)))
.map(|dir| ide_core::project_roots::resolve(root, &dir))
.filter(|dir| !found.iter().any(|build| dir.starts_with(build)))
.collect()
}
fn linked_config(
@@ -698,58 +672,10 @@ mod ownership_tests {
),
(
"linked module inside the root reactor belongs to the reactor",
vec![
(
"pom.xml".into(),
"<project><modules><module>site/service/03_src/demo-monitor</module></modules></project>",
),
(format!("{deep}/pom.xml"), BOOT_POM),
],
vec!["site/service/03_src/demo-monitor/pom.xml"],
None,
vec!["maven:package".into(), "maven:test".into()],
),
(
"a separate Maven build linked inside the root build's folder has its own configurations",
vec![("pom.xml".into(), "<project></project>"), (format!("{deep}/pom.xml"), BOOT_POM)],
vec!["site/service/03_src/demo-monitor/pom.xml"],
None,
vec![
"maven:package".into(),
"maven:test".into(),
format!("maven:package:{deep}"),
format!("maven:test:{deep}"),
format!("maven:spring-boot:run:{deep}"),
],
),
(
"a Gradle subproject linked as a build belongs to the root build",
vec![
("settings.gradle.kts".into(), "rootProject.name = \"root\"\ninclude(\"a:b:c:tool\")\n"),
("build.gradle.kts".into(), "plugins {\n java\n}"),
(format!("{tool}/build.gradle.kts"), "plugins {\n application\n}"),
],
vec![],
Some(vec![".", tool]),
vec!["gradle:build".into(), "gradle:test".into()],
),
(
"a separate Gradle build linked inside the root build's folder has its own configurations",
vec![
("settings.gradle.kts".into(), "rootProject.name = \"root\"\n"),
("build.gradle.kts".into(), "plugins {\n java\n}"),
(format!("{tool}/settings.gradle.kts"), "rootProject.name = \"tool\"\n"),
(format!("{tool}/build.gradle.kts"), "plugins {\n application\n}"),
],
vec![],
Some(vec![".", tool]),
vec![
"gradle:build".into(),
"gradle:test".into(),
format!("gradle:build:{tool}"),
format!("gradle:test:{tool}"),
format!("gradle:run:{tool}"),
],
vec!["maven:package".into(), "maven:test".into()],
),
(
"linked module within the search depth is not detected twice",
+12 -12
View File
@@ -34,9 +34,9 @@ pub struct ProjectInterpreter {
}
/// Installed interpreters / toolchains of `kind`; project-local ones first.
#[command(trust = outside_restricted)]
#[command(trust = trusted)]
pub async fn sdk_detect(host: &Host, window: &str, kind: SdkKind) -> IdeResult<Vec<Sdk>> {
host.require_trust_if_project(window)?;
host.require_trust(window)?;
let project = host.project(window).ok();
if kind == SdkKind::Jdk {
host.apply_added_jdks();
@@ -63,10 +63,10 @@ pub async fn sdk_detect(host: &Host, window: &str, kind: SdkKind) -> IdeResult<V
}
/// The Python interpreters of the recently opened projects, each with its project.
#[command(trust = outside_restricted)]
#[command(trust = trusted)]
pub async fn sdk_python_project_interpreters(host: &Host, window: &str) -> IdeResult<Vec<ProjectInterpreter>> {
// Newest first. The open project is skipped: `sdk_detect` lists its own.
host.require_trust_if_project(window)?;
host.require_trust(window)?;
let current = host.project(window).ok().map(|p| p.root.clone());
let config = host.config_dir.clone();
// Probing runs the project's interpreter (and its settings may name any program): only
@@ -111,9 +111,9 @@ pub async fn sdk_python_project_interpreters(host: &Host, window: &str) -> IdeRe
}
/// An existing Python executable or virtualenv folder as an SDK; `None` if Python cannot run.
#[command(trust = outside_restricted)]
#[command(trust = trusted)]
pub async fn sdk_python_interpreter(host: &Host, window: &str, path: PathBuf) -> IdeResult<Option<Sdk>> {
host.require_trust_if_project(window)?;
host.require_trust(window)?;
let root = host.project(window).ok().map(|p| p.root.clone());
tokio::task::spawn_blocking(move || Ok(ide_sdk::python_interpreter_sdk(&path, root.as_deref())))
.await
@@ -320,7 +320,7 @@ pub async fn sdk_locate_tools(
}
/// Creates a Python environment with `tool` (`venv` / `uv` / `poetry`); output streams through `on_output`.
#[command(trust = outside_restricted)]
#[command(trust = trusted)]
pub async fn sdk_python_create_venv(
host: &Host,
window: &str,
@@ -330,7 +330,7 @@ pub async fn sdk_python_create_venv(
request: RequestId,
on_output: Channel<String>,
) -> IdeResult<Sdk> {
host.require_trust_if_project(window)?;
host.require_trust(window)?;
let cancel = host.begin_project_request(window, request);
let result = tokio::task::spawn_blocking(move || {
ide_sdk::python::create_venv(tool, &base, &location, &cancel, &|line| {
@@ -343,14 +343,14 @@ pub async fn sdk_python_create_venv(
result?
}
#[command(trust = outside_restricted)]
#[command(trust = trusted)]
pub async fn sdk_python_packages(
host: &Host,
window: &str,
python: PathBuf,
request: RequestId,
) -> IdeResult<Vec<PythonPackage>> {
host.require_trust_if_project(window)?;
host.require_trust(window)?;
let cancel = host.begin_project_request(window, request);
let result =
tokio::task::spawn_blocking(move || ide_sdk::python::list_packages(&python, &cancel)).await.map_err(join_err);
@@ -360,7 +360,7 @@ pub async fn sdk_python_packages(
/// Installs (`uninstall = false`) or removes a package; output streams through `on_output`.
#[allow(clippy::too_many_arguments)]
#[command(trust = outside_restricted)]
#[command(trust = trusted)]
pub async fn sdk_python_pip(
host: &Host,
window: &str,
@@ -371,7 +371,7 @@ pub async fn sdk_python_pip(
request: RequestId,
on_output: Channel<String>,
) -> IdeResult<()> {
host.require_trust_if_project(window)?;
host.require_trust(window)?;
let project_root = host.project(window).ok().map(|p| p.root.clone());
let cancel = host.begin_project_request(window, request);
let result = tokio::task::spawn_blocking(move || {
+5 -5
View File
@@ -11,7 +11,7 @@ use std::path::PathBuf;
/// The installer, reporting the executables chosen in the window's settings.
fn tools(host: &Host, window: &str) -> IdeResult<Tools> {
host.require_trust_if_project(window)?;
host.require_trust(window)?;
let data = host.local_data_dir.clone();
let (settings, root) = match host.project(window) {
Ok(project) => (project.settings.effective(), project.root.clone()),
@@ -56,7 +56,7 @@ fn reconfigure_servers(host: &Host) {
}
/// Status of every known language server / debug adapter and the languages using it.
#[command(trust = outside_restricted)]
#[command(trust = trusted)]
pub async fn tools_list(host: &Host, window: &str) -> IdeResult<Vec<ToolInfo>> {
let tools = tools(host, window)?;
let langs = languages(host, window);
@@ -65,7 +65,7 @@ pub async fn tools_list(host: &Host, window: &str) -> IdeResult<Vec<ToolInfo>> {
/// Installs (or reinstalls) a tool into `<app-data>/tools`, streaming output through
/// `on_event`. Cancel with `cancel_request(request)`.
#[command(trust = outside_restricted)]
#[command(trust = trusted)]
pub async fn tools_install(
host: &Host,
window: &str,
@@ -93,7 +93,7 @@ pub async fn tools_install(
/// Newer versions of the tools the IDE installed (release downloads and npm packages).
/// Cancel with `cancel_request(request)`.
#[command(trust = outside_restricted)]
#[command(trust = trusted)]
pub async fn tools_updates(host: &Host, window: &str, request: RequestId) -> IdeResult<Vec<ToolUpdate>> {
let tools = tools(host, window)?;
let cancel = host.begin_request(request);
@@ -103,7 +103,7 @@ pub async fn tools_updates(host: &Host, window: &str, request: RequestId) -> Ide
}
/// Removes a tool the IDE installed.
#[command(trust = outside_restricted)]
#[command(trust = trusted)]
pub async fn tools_uninstall(host: &Host, window: &str, name: String) -> IdeResult<ToolInfo> {
let tools = tools(host, window)?;
let langs = languages(host, window);
+3 -10
View File
@@ -47,19 +47,12 @@ pub async fn serves_page(url: &str) -> bool {
response.status().is_success() && html
}
/// The built-in server's URL for `path` (started on first use). A file whose language is
/// HTML (Settings › File Types can make it so) is served as a page, whatever its extension.
/// The built-in server's URL for `path` (started on first use).
#[command(trust = always)]
pub async fn web_url(host: &Host, window: &str, path: IpcPath) -> IdeResult<String> {
// Under the window's project when it holds the file.
let project = host.project(window).ok();
let root = project.as_ref().map(|p| p.root.as_path());
let languages = project.as_ref().map_or(&host.languages, |p| &p.languages);
if matches!(languages.detect(&path, None).as_str(), "html" | "django-html") {
host.web.page_url_for(root, &path).await
} else {
host.web.url_for(root, &path).await
}
let root = host.project(window).ok().map(|p| p.root.clone());
host.web.url_for(root.as_deref(), &path).await
}
#[cfg(test)]
-3
View File
@@ -272,7 +272,6 @@ impl Host {
lombok.jar(),
);
ide_sdk::apply::configure_gradle_runtime(cfg, root, server_root, &effective);
ide_sdk::apply::configure_maven_sources(cfg, &effective);
ide_sdk::jdtls::launch_directly(cfg);
}
ide_sdk::apply::server_protocol_overrides(cfg, &effective);
@@ -286,8 +285,6 @@ impl Host {
effective.languages.java.gradle.linked_projects.as_deref(),
build_files.as_deref(),
);
// After the import settings: they extend the workspace folder's name.
ide_sdk::jdtls_workspaces::use_own_temp(cfg, &data_dir);
}
}));
}
+5 -11
View File
@@ -879,15 +879,16 @@ fn background_tasks_scale_and_renew_cpu_fuel_budget() {
// Room for activation (about 3_100 on macOS, more on Windows). A background task gets ten
// times it (5 s / 500 ms): enough for each step of `patient` with its CPU work (32_000 to
// 80_000), not for the whole run without the refill on each report.
let limits = Limits {
let f = fixture(Limits {
fuel: 40_000,
timeout: Duration::from_millis(500),
background: Duration::from_millis(5_000),
..Limits::default()
};
let f = fixture(limits);
});
f.install(&misbehave_pkg());
f.host.set_capability("misbehave", "process:git", true).expect("grant Git capability");
if f.host.set_capability("misbehave", "process:git", true).is_err() {
return;
}
// Warm up activation in its own call so `patient` starts with a fresh budget.
assert_eq!(f.run("misbehave", "echo", Some("warm")).unwrap().as_deref(), Some("warm"));
@@ -896,13 +897,6 @@ fn background_tasks_scale_and_renew_cpu_fuel_budget() {
let err = f.run("misbehave", "spin", None).unwrap_err();
assert!(err.contains("exceeded its CPU budget (40000 fuel per call)"), "{err}");
// Beginning a task alone must not renew its scaled budget.
let quiet = fixture(limits);
quiet.install(&misbehave_pkg());
quiet.host.set_capability("misbehave", "process:git", true).expect("grant Git capability");
let err = quiet.run("misbehave", "patient", Some("quiet:4000")).unwrap_err();
assert!(err.contains("exceeded its CPU budget (400000 fuel per call)"), "{err}");
}
#[test]
-3
View File
@@ -45,9 +45,6 @@ async fn a_commands_trust_class_decides_where_it_runs() {
assert_eq!(allowed("main", class), in_restricted, "{class:?} in Restricted Mode");
assert_eq!(allowed("welcome", class), without_project, "{class:?} without a project");
}
// Toolchain detection runs from Settings opened on the Welcome screen, but not in Restricted Mode.
assert!(ide_host::ops::sdk::sdk_detect(&host, "welcome", ide_sdk::SdkKind::Zig).await.is_ok());
assert!(ide_host::ops::sdk::sdk_detect(&host, "main", ide_sdk::SdkKind::Zig).await.is_err());
// These requests validate the vendor before any network access, independently of project trust.
let error = ide_host::ops::tools::jdk_download_releases(&host, "unknown-vendor".into(), ide_core::RequestId(901))
.await
+1 -1
View File
@@ -28,7 +28,7 @@ pub use syntax::{
VueComponentImport, VueRefAccess, VueRefElement, WebReference, WebReferenceKind, merge_visibility,
set_external_syntax, shift_pos, shift_range,
};
pub use syntax::{MethodBody, PhpAlignment, PythonClassFacts, PythonFacts, PythonMethodFacts};
pub use syntax::{MethodBody, PythonClassFacts, PythonFacts, PythonMethodFacts};
/// Parsed form of `languages/<id>.toml`. Backend-only; the UI gets [`LanguageInfo`].
#[derive(Clone, Debug, Serialize, Deserialize)]
-68
View File
@@ -118,16 +118,6 @@ pub(super) fn folding(
});
return true;
}
// Some languages write documentation as a string-like node rather than a
// lexical comment (Python docstrings, Elixir `@doc` / `@moduledoc`). The
// generic comment pass above never sees those, so fold them as documentation.
if node.is_named()
&& start != end
&& let Some(fold) = docstring_fold(spec, &node, kinds, text)
{
out.push(fold);
return false;
}
if start != end && !spec.imports.is_empty() && node.named_child_count() > 1 {
import_runs(kinds, node, text, &mut out);
}
@@ -216,64 +206,6 @@ pub(crate) fn is_comment(kind: &str) -> bool {
kind.contains("comment") || kind == "Comment"
}
/// Folds a documentation string written as a non-comment node. Returns `None`
/// for every other node; the caller skips its subtree only on a match.
fn docstring_fold(spec: &Spec, node: &Node, kinds: &KindTable, text: &str) -> Option<FoldRange> {
let multi_line = |n: &Node| n.start_position().row != n.end_position().row && kinds.has(n, FOLD_NODE);
let range = |n: &Node| FoldRange {
start_line: n.start_position().row as u32,
end_line: last_content_row(n, text) as u32,
kind: FoldKind::Comment,
};
match spec.name {
// A bare string as the first statement of a module/class/function body.
"python" if node.kind() == "expression_statement" => {
let string = node.named_child(0)?;
if string.kind() != "string" || !multi_line(&string) {
return None;
}
let parent = node.parent()?;
let mut cursor = parent.walk();
if parent.named_children(&mut cursor).find(|c| !kinds.has(c, COMMENT)) != Some(*node) {
return None;
}
Some(range(node))
}
// `@doc """…"""` / `@moduledoc """…"""`: an @-prefixed call whose
// argument is a multi-line string (or a sigil like `~S"""`).
"elixir" if node.kind() == "unary_operator" => {
let operand = node.child_by_field_name("operand")?;
if operand.kind() != "call" || !is_elixir_doc_attr(operand, text) {
return None;
}
// The string is the argument of the attribute call: `@doc """…"""`
// parses as unary_operator -> call(target: doc) -> arguments -> string.
let mut cursor = operand.walk();
let doc_string =
operand.named_children(&mut cursor).find(|c| c.kind() == "arguments").and_then(|args| {
let mut args_cursor = args.walk();
args.named_children(&mut args_cursor).find(|c| multi_line(c))
})?;
if !matches!(doc_string.kind(), "string" | "sigil") {
return None;
}
Some(range(&doc_string))
}
_ => None,
}
}
/// Whether an Elixir `call` is `@doc` / `@moduledoc` / `@typedoc` (the documented
/// attributes that take a string argument).
fn is_elixir_doc_attr(call: Node, text: &str) -> bool {
let Some(target) = call.child_by_field_name("target") else { return false };
let name = text.get(target.byte_range()).unwrap_or_default();
if target.kind() != "identifier" {
return false;
}
matches!(name, "doc" | "moduledoc" | "typedoc")
}
/// Row of the closing token when `node` is delimited by a matching bracket pair.
pub(crate) fn bracket_pair<'t>(node: &Node<'t>) -> Option<(Node<'t>, Node<'t>)> {
let count = node.child_count();
-2
View File
@@ -10,7 +10,6 @@ mod inheritance;
pub(crate) mod lines;
mod literals;
mod outline;
mod php_align;
mod python_facts;
mod rst;
mod selection;
@@ -29,7 +28,6 @@ pub use inheritance::ClassBases;
pub use lines::{shift_pos, shift_range};
pub use literals::{Literal, LiteralKind, SpellingKind, SpellingRegion};
pub use outline::merge_visibility;
pub use php_align::PhpAlignment;
pub use python_facts::{MethodBody, PythonClassFacts, PythonFacts, PythonMethodFacts};
use std::cell::RefCell;
use std::collections::HashMap;
-368
View File
@@ -1,368 +0,0 @@
//! PHP Code Style › Align key-value pairs and Align consecutive assignments (PhpStorm's
//! options of the same names), applied to text a formatter has already formatted.
//!
//! A block is a run of array elements, or of assignment statements, on consecutive lines of
//! the same array or statement list, one per line and each on a single line. A blank line,
//! a comment line, another statement or element, or one spanning several lines ends it.
//! Within a block the operators line up one space after the longest left-hand side; nested
//! arrays form blocks of their own. Only the whitespace before an operator token of the
//! syntax tree changes, so `=>` and `=` inside strings and comments are never touched.
use crate::{LanguageId, Syntax};
use tree_sitter::{Node, Tree};
/// Which alignments to apply.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct PhpAlignment {
/// `=>` of the elements of multi-line arrays.
pub key_value_pairs: bool,
/// `=` of consecutive assignment statements.
pub assignments: bool,
}
impl PhpAlignment {
pub fn any(self) -> bool {
self.key_value_pairs || self.assignments
}
}
impl Syntax {
/// `text` with its PHP alignment applied, changing only lines `lines` (0-based, inclusive;
/// `None`: all). A block reaching outside them still aligns with its lines there.
/// `None` when nothing changes or `lang` is not parsed with the PHP grammar.
pub fn align_php(
&self,
lang: &LanguageId,
text: &str,
lines: Option<(usize, usize)>,
options: PhpAlignment,
) -> Option<String> {
if !options.any() {
return None;
}
self.analyze(lang, text, |g, tree, text| (g.spec.name == "php").then(|| align(tree, text, lines, options)))
.flatten()
}
}
/// One line's operator: the whitespace `gap` before it and the width of the line up to it.
#[derive(Clone, Copy, Debug)]
struct Entry {
line: usize,
gap: (usize, usize),
/// Characters from the start of the line to the end of the left-hand side.
width: usize,
}
fn align(tree: &Tree, text: &str, lines: Option<(usize, usize)>, options: PhpAlignment) -> Option<String> {
let mut gaps: Vec<(usize, usize, usize)> = Vec::new();
let mut cursor = tree.walk();
visit(&mut cursor, &mut |node| {
// Error recovery can read string content as code, where whitespace matters.
if node.is_error() {
return;
}
let entries = match node.kind() {
"array_creation_expression" if options.key_value_pairs => run(node, text, key_value),
_ if options.assignments => run(node, text, assignment),
_ => return,
};
for block in blocks(&entries) {
let column = block.iter().map(|e| e.width).max().unwrap_or(0) + 1;
for e in block {
if lines.is_none_or(|(first, last)| (first..=last).contains(&e.line)) {
gaps.push((e.gap.0, e.gap.1, column - e.width));
}
}
}
});
gaps.sort_unstable();
let mut out = String::with_capacity(text.len());
let mut at = 0;
let mut changed = false;
for (from, to, spaces) in gaps {
if text[from..to].len() == spaces && text[from..to].bytes().all(|b| b == b' ') {
continue;
}
out.push_str(&text[at..from]);
out.extend(std::iter::repeat_n(' ', spaces));
at = to;
changed = true;
}
if !changed {
return None;
}
out.push_str(&text[at..]);
Some(out)
}
/// The named children of `parent` as alignment candidates in order: `None` breaks a block.
/// A comment ending the line of the child before it (`'a' => 1, // why`) is skipped; two
/// children sharing a line are both left alone.
fn run(parent: Node, text: &str, entry: fn(Node, &str) -> Option<Entry>) -> Vec<Option<Entry>> {
let mut out: Vec<Option<Entry>> = Vec::new();
let mut previous_end: Option<usize> = None;
let mut cursor = parent.walk();
for child in parent.named_children(&mut cursor) {
let start = child.start_position().row;
let shares_line = previous_end == Some(start);
if child.kind() == "comment" && shares_line {
continue;
}
if shares_line && let Some(last) = out.last_mut() {
*last = None;
}
out.push(if shares_line { None } else { entry(child, text) });
previous_end = Some(child.end_position().row);
}
out
}
/// Runs of entries on consecutive lines.
fn blocks(entries: &[Option<Entry>]) -> Vec<Vec<Entry>> {
let mut out: Vec<Vec<Entry>> = Vec::new();
let mut current: Vec<Entry> = Vec::new();
for entry in entries {
match entry {
Some(e) if current.last().is_none_or(|last| last.line + 1 == e.line) => current.push(*e),
Some(e) => out.push(std::mem::replace(&mut current, vec![*e])),
None if current.is_empty() => {}
None => out.push(std::mem::take(&mut current)),
}
}
if !current.is_empty() {
out.push(current);
}
out
}
/// `'key' => value` alone on one line.
fn key_value(element: Node, text: &str) -> Option<Entry> {
if element.kind() != "array_element_initializer" {
return None;
}
let mut cursor = element.walk();
let arrow = element.children(&mut cursor).find(|c| c.kind() == "=>")?;
let key = arrow.prev_sibling()?;
entry(element, key, arrow, text)
}
/// `$left = value;` (or `= &value`) alone on one line.
fn assignment(statement: Node, text: &str) -> Option<Entry> {
if statement.kind() != "expression_statement" {
return None;
}
let expression = statement.named_child(0)?;
if !matches!(expression.kind(), "assignment_expression" | "reference_assignment_expression") {
return None;
}
let left = expression.child_by_field_name("left")?;
let mut cursor = expression.walk();
let operator = expression.children(&mut cursor).find(|c| c.kind() == "=")?;
entry(statement, left, operator, text)
}
fn entry(whole: Node, left: Node, operator: Node, text: &str) -> Option<Entry> {
let line = whole.start_position().row;
if whole.has_error() || whole.end_position().row != line {
return None;
}
let line_start = whole.start_byte() - whole.start_position().column;
let starts_line = text[line_start..whole.start_byte()].bytes().all(|b| b == b' ' || b == b'\t');
let gap = (left.end_byte(), operator.start_byte());
let blank_gap = text[gap.0..gap.1].bytes().all(|b| b == b' ' || b == b'\t');
(starts_line && blank_gap).then(|| Entry { line, gap, width: text[line_start..gap.0].chars().count() })
}
fn visit(cursor: &mut tree_sitter::TreeCursor, f: &mut impl FnMut(Node)) {
loop {
f(cursor.node());
if cursor.goto_first_child() {
continue;
}
loop {
if cursor.goto_next_sibling() {
break;
}
if !cursor.goto_parent() {
return;
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::OnceLock;
const BOTH: PhpAlignment = PhpAlignment { key_value_pairs: true, assignments: true };
const PAIRS: PhpAlignment = PhpAlignment { key_value_pairs: true, assignments: false };
const ASSIGNMENTS: PhpAlignment = PhpAlignment { key_value_pairs: false, assignments: true };
fn syntax() -> &'static Syntax {
static S: OnceLock<Syntax> = OnceLock::new();
S.get_or_init(Syntax::new)
}
fn aligned(text: &str, lines: Option<(usize, usize)>, options: PhpAlignment) -> String {
let out = syntax().align_php(&LanguageId::new("php"), text, lines, options);
let result = out.clone().unwrap_or_else(|| text.to_owned());
let strip = |s: &str| s.chars().filter(|c| !c.is_whitespace()).collect::<String>();
assert_eq!(strip(&result), strip(text), "only whitespace changes");
assert_eq!(
syntax().align_php(&LanguageId::new("php"), &result, lines, options),
None,
"aligning again changes nothing:\n{result}"
);
result
}
fn check(options: PhpAlignment, before: &str, after: &str) {
assert_eq!(aligned(before, None, options), after);
}
#[test]
fn aligns_the_arrows_of_a_multi_line_array() {
check(
PAIRS,
"<?php\nreturn [\n 'name' => 'demo',\n 'description' => 'x',\n 'id' => 1,\n];\n",
"<?php\nreturn [\n 'name' => 'demo',\n 'description' => 'x',\n 'id' => 1,\n];\n",
);
check(
PAIRS,
"<?php\n$a = array(\n 1 => 'a',\n 1234 => 'b',\n);\n",
"<?php\n$a = array(\n 1 => 'a',\n 1234 => 'b',\n);\n",
);
}
#[test]
fn nested_arrays_align_per_level_and_a_multi_line_value_ends_a_block() {
check(
PAIRS,
"<?php\n$config = [\n 'a' => 1,\n 'bbb' => 2,\n 'nested' => [\n 'x' => 1,\n 'yyyy' => 2,\n ],\n 'c' => 3,\n 'dd' => 4,\n];\n",
"<?php\n$config = [\n 'a' => 1,\n 'bbb' => 2,\n 'nested' => [\n 'x' => 1,\n 'yyyy' => 2,\n ],\n 'c' => 3,\n 'dd' => 4,\n];\n",
);
}
#[test]
fn blank_lines_comment_lines_and_elements_without_a_key_end_a_block() {
check(
PAIRS,
"<?php\n$a = [\n 'a' => 1,\n 'bb' => 2,\n\n 'ccc' => 3,\n // section\n 'dddd' => 4,\n 'e' => 5,\n 6,\n 'ff' => 7,\n];\n",
"<?php\n$a = [\n 'a' => 1,\n 'bb' => 2,\n\n 'ccc' => 3,\n // section\n 'dddd' => 4,\n 'e' => 5,\n 6,\n 'ff' => 7,\n];\n",
);
}
#[test]
fn a_comment_at_the_end_of_a_line_keeps_the_block() {
check(
PAIRS,
"<?php\n$a = [\n 'a' => 1, // first\n 'bb' => 2, /* second */\n 'ccc' => 3,\n];\n",
"<?php\n$a = [\n 'a' => 1, // first\n 'bb' => 2, /* second */\n 'ccc' => 3,\n];\n",
);
}
#[test]
fn single_line_arrays_and_elements_sharing_a_line_stay_as_they_are() {
for text in [
"<?php\n$a = ['a' => 1, 'bbb' => 2];\n",
"<?php\n$a = [\n 'a' => 1, 'bbb' => 2,\n 'cc' => 3,\n];\n",
"<?php\n$a = ['a' => 1,\n 'bbb' => 2];\n",
] {
assert_eq!(aligned(text, None, BOTH), text);
}
}
#[test]
fn arrows_and_equals_signs_outside_arrays_and_assignments_are_not_touched() {
let text = "<?php\n\
$s = 'a => b';\n\
$t = \"x = y\";\n\
// 'k' => 1, $v = 2\n\
/* 'kk' => 1 */\n\
foreach ($items as $key => $value) {}\n\
$f = fn($x) => $x;\n\
$m = match ($x) {\n 1 => 'a',\n 100 => 'b',\n};\n\
for ($i = 0; $i < 3; $i++) {}\n\
function g($a = 1, $bbb = 2) {}\n\
g(a: 1, bbb: 2);\n\
$h = <<<EOT\n 'a' => 1,\n 'bbb' => 2,\nEOT;\n";
let out = aligned(text, None, PAIRS);
assert_eq!(out, text);
}
#[test]
fn aligns_consecutive_assignments() {
check(
ASSIGNMENTS,
"<?php\n$y = foo($x);\n$i = foo($i);\n$result = $result . $y . $i;\n$this->name = 'n';\n$ref = &$y;\n",
"<?php\n$y = foo($x);\n$i = foo($i);\n$result = $result . $y . $i;\n$this->name = 'n';\n$ref = &$y;\n",
);
}
#[test]
fn other_statements_blank_lines_and_multi_line_assignments_end_a_block() {
check(
ASSIGNMENTS,
"<?php\nfunction f() {\n $a = 1;\n $bb = 2;\n echo $a;\n $ccc = 3;\n $d = 4;\n\n $eeeee = 5;\n $f = 6;\n $g .= 'x';\n $hh = 7;\n $i = [\n 1,\n ];\n $jjj = 8;\n $k = 9;\n}\n",
"<?php\nfunction f() {\n $a = 1;\n $bb = 2;\n echo $a;\n $ccc = 3;\n $d = 4;\n\n $eeeee = 5;\n $f = 6;\n $g .= 'x';\n $hh = 7;\n $i = [\n 1,\n ];\n $jjj = 8;\n $k = 9;\n}\n",
);
}
#[test]
fn assignments_sharing_a_line_and_declarations_stay_as_they_are() {
let text = "<?php\n$a = 1; $bbb = 2;\n$cc = 3;\nclass C {\n public $x = 1;\n public $yyy = 2;\n const A = 1;\n const BBB = 2;\n}\n";
assert_eq!(aligned(text, None, ASSIGNMENTS), text);
}
#[test]
fn each_option_aligns_only_its_operator() {
let text = "<?php\n$a = [\n 'a' => 1,\n 'bbb' => 2,\n];\n$x = 1;\n$yyy = 2;\n";
assert_eq!(
aligned(text, None, PAIRS),
"<?php\n$a = [\n 'a' => 1,\n 'bbb' => 2,\n];\n$x = 1;\n$yyy = 2;\n"
);
assert_eq!(
aligned(text, None, ASSIGNMENTS),
"<?php\n$a = [\n 'a' => 1,\n 'bbb' => 2,\n];\n$x = 1;\n$yyy = 2;\n"
);
assert_eq!(syntax().align_php(&LanguageId::new("php"), text, None, PhpAlignment::default()), None);
assert_eq!(syntax().align_php(&LanguageId::new("javascript"), "a = {\n b: 1,\n};\n", None, BOTH), None);
}
#[test]
fn only_the_given_lines_change_and_they_align_with_the_whole_block() {
let text = "<?php\n$a = [\n 'a' => 1,\n 'bb' => 2,\n 'cccc' => 3,\n];\n";
assert_eq!(
aligned(text, Some((2, 3)), PAIRS),
"<?php\n$a = [\n 'a' => 1,\n 'bb' => 2,\n 'cccc' => 3,\n];\n"
);
assert_eq!(aligned(text, Some((5, 5)), PAIRS), text);
}
#[test]
fn widths_count_characters_not_bytes() {
check(
PAIRS,
"<?php\n$a = [\n '名前' => 1,\n 'name' => 2,\n];\n",
"<?php\n$a = [\n '名前' => 1,\n 'name' => 2,\n];\n",
);
}
#[test]
fn code_with_syntax_errors_is_aligned_only_where_it_parses() {
let text = "<?php\n$a = [\n 'a' => 1,\n 'bbb' => ,\n 'cc' => 3,\n];\n";
let out = aligned(text, None, PAIRS);
assert!(out.contains("'bbb' => ,"), "{out}");
}
#[test]
fn php_inside_html() {
check(
BOTH,
"<html>\n<?php\n$a = 1;\n$bbb = 2;\n?>\n<p>x = y</p>\n",
"<html>\n<?php\n$a = 1;\n$bbb = 2;\n?>\n<p>x = y</p>\n",
);
}
}
-71
View File
@@ -1103,77 +1103,6 @@ fn folding_python_bodies_start_at_header() {
);
}
#[test]
fn folding_python_docstrings_are_comments() {
let src = r#""""Module doc.
More.
"""
class A:
"""Class doc.
More.
"""
def f(self):
"""Method doc.
More.
"""
return 1
"#;
assert_eq!(
folds("python", src),
vec![
(0, 2, FoldKind::Comment),
(4, 12, FoldKind::Region),
(5, 7, FoldKind::Comment),
(8, 12, FoldKind::Region),
(9, 11, FoldKind::Comment),
]
);
}
#[test]
fn folding_python_single_line_or_later_strings_are_not_docstrings() {
// A one-line docstring has nothing to fold; a multi-line string that is not
// the opening statement stays an ordinary string fold, not a doc comment.
let src = r#"x = 1
"""Later string.
Still later.
"""
def f():
"""One line."""
return 1
"#;
let found = folds("python", src);
assert!(!found.contains(&(1, 3, FoldKind::Comment)), "later string must not be a doc comment: {found:?}");
assert!(found.contains(&(1, 3, FoldKind::Region)), "later string still folds as a string: {found:?}");
assert!(!found.iter().any(|f| f.2 == FoldKind::Comment), "single-line docstring has no fold: {found:?}");
}
#[test]
fn folding_elixir_doc_strings_are_comments() {
let src = r#"defmodule Foo do
@moduledoc """
Module doc.
More.
"""
@doc ~S"""
Function doc.
More.
"""
def bar, do: :ok
@doc "one line"
def baz, do: :ok
end
"#;
assert_eq!(
folds("elixir", src),
vec![(0, 14, FoldKind::Region), (1, 4, FoldKind::Comment), (6, 9, FoldKind::Comment),]
);
}
#[test]
fn folding_data_and_markup() {
assert_eq!(
+5 -46
View File
@@ -7,7 +7,6 @@
use crate::LspManager;
use crate::server::Server;
use ide_core::{CancellationToken, DocId, Pos, Range};
use ide_language::LanguageServerConfig;
use serde::Deserialize;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
@@ -129,7 +128,7 @@ impl LspManager {
let search = crate::launch::server_search_path(&config, &server.root);
let Some(dir) = path.parent().map(Path::to_path_buf) else { return };
let modules: Vec<String> = required.iter().map(|r| r.path.clone()).collect();
let Some(deprecated) = list_deprecations(&dir, &config, &search, &modules, cancel).await else { return };
let Some(deprecated) = list_deprecations(&dir, &search, &modules, cancel).await else { return };
// The document changed meanwhile: its own save runs again.
if cancel.is_cancelled() || self.docs.lock().get(&doc).is_none_or(|d| d.text.as_str() != text) {
return;
@@ -209,15 +208,16 @@ struct ListedModule {
/// `(module, message)` of each deprecated module in `modules`; `None` when `go` failed.
async fn list_deprecations(
dir: &Path,
config: &LanguageServerConfig,
search: &std::ffi::OsStr,
modules: &[String],
cancel: &CancellationToken,
) -> Option<Vec<(String, String)>> {
let (dir, config, search, modules) = (dir.to_path_buf(), config.clone(), search.to_owned(), modules.to_vec());
let (dir, search, modules) = (dir.to_path_buf(), search.to_owned(), modules.to_vec());
let command = tokio::task::spawn_blocking(move || {
let go: PathBuf = ide_core::tool_path::find_command("go", &search, &dir)?;
Some(deprecations_command(&go, &dir, &config, &search, &modules))
let mut command = Command::new(go);
command.args(["list", "-m", "-u", "-e", "-json"]).args(modules).current_dir(dir).env("PATH", search);
Some(command)
})
.await
.ok()??;
@@ -228,23 +228,6 @@ async fn list_deprecations(
tokio::task::spawn_blocking(move || parse_deprecations(&output)).await.ok()
}
fn deprecations_command(
go: &Path,
dir: &Path,
config: &LanguageServerConfig,
search: &std::ffi::OsStr,
modules: &[String],
) -> Command {
let mut command = Command::new(go);
command
.args(["list", "-m", "-u", "-e", "-json"])
.args(modules)
.current_dir(dir)
.envs(&config.env)
.env("PATH", search);
command
}
async fn run_query(command: Command, cancel: &CancellationToken, timeout: Duration) -> Option<Vec<u8>> {
let cancel = cancel.child_token();
let _cancel_on_drop = cancel.clone().drop_guard();
@@ -331,30 +314,6 @@ fn parse_deprecations(json: &[u8]) -> Vec<(String, String)> {
mod tests {
use super::*;
#[test]
fn deprecation_command_inherits_server_environment() {
let config: LanguageServerConfig = serde_json::from_value(serde_json::json!({
"name": "gopls", "command": "gopls", "env": {
"PATH": "selected-toolchain", "GOPROXY": "off", "GOPRIVATE": "example.invalid/*",
"GOTOOLCHAIN": "local", "GOWORK": "off"
}
}))
.unwrap();
let command = deprecations_command(
Path::new("go"),
Path::new("workspace"),
&config,
&crate::launch::server_search_path(&config, Path::new("workspace")),
&["example.invalid/lib".into()],
);
let env: std::collections::BTreeMap<_, _> = command.get_envs().collect();
for (key, value) in &config.env {
assert_eq!(env.get(std::ffi::OsStr::new(key)), Some(&Some(std::ffi::OsStr::new(value))), "missing {key}");
}
assert_eq!(command.get_current_dir(), Some(Path::new("workspace")));
assert_eq!(command.get_args().collect::<Vec<_>>(), ["list", "-m", "-u", "-e", "-json", "example.invalid/lib"]);
}
#[test]
fn queries_cancel_only_the_superseded_document() {
let mut queries = Queries::default();
-8
View File
@@ -435,14 +435,6 @@ impl ClientHandler {
.find_map(|base| section.split('.').try_fold(base, |v, key| v.get(key)))
.cloned()
.unwrap_or(Value::Null),
None if self.server.name == "eslint" => {
let mut settings = options.clone();
settings["workspaceFolder"] = json!({
"uri": crate::uri::path_to_uri(&self.server.root),
"name": self.server.root.file_name().map_or_else(|| "root".into(), |name| name.to_string_lossy().into_owned()),
});
settings
}
None => options.clone(),
})
.collect(),
+14 -44
View File
@@ -1833,11 +1833,8 @@ impl LspManager {
/// the same class from its Java model instead, decompiled with method bodies and navigable.
/// Its documents belong to jdtls ([`Self::virtual_document`] records it).
async fn jdt_library_classes(&self, snap: &DocSnap, pos: Pos, locs: Vec<Location>) -> Vec<Location> {
let lib_class = |u: &str| {
(u.starts_with("jar:") && u.ends_with(".class"))
|| (u.starts_with("jdt://contents/") && u.contains(".class"))
};
if !locs.iter().any(|l| l.uri.as_deref().is_some_and(lib_class))
let jar_class = |l: &Location| l.uri.as_deref().is_some_and(|u| u.starts_with("jar:") && u.ends_with(".class"));
if !locs.iter().any(jar_class)
|| !self.servers.lock().iter().any(|s| s.name == jdtls::SERVER && s.running().is_some())
{
return locs;
@@ -1845,54 +1842,27 @@ impl LspManager {
let name = library_source::identifier_at(snap.text.line(pos.line as usize), pos.col).map(str::to_owned);
let mut out = Vec::with_capacity(locs.len());
for loc in locs {
let Some(original) = loc.uri.as_deref().filter(|u| lib_class(u)) else {
let entry = loc.uri.as_deref().filter(|_| jar_class(&loc)).and_then(library_source::parse);
let Some(entry) = entry else {
out.push(loc);
continue;
};
let jdt = original.starts_with("jdt:");
let uri = if !jdt {
let Some(entry) = library_source::parse(original) else {
// The Kotlin server may name the jar by another path than jdtls (its own copy of a
// `system`-scope jar): its stub would be all the user gets, so take jdtls' only class
// of that name.
let uri = match self.archive_class(entry.jar, entry.entry, true).await {
Ok(uri) => uri,
Err(e) => {
tracing::info!("library class stays a stub: {}", e.message);
out.push(loc);
continue;
};
// The Kotlin server may name the jar by another path than jdtls (its own copy of a
// `system`-scope jar): its stub would be all the user gets, so take jdtls' only class
// of that name.
match self.archive_class(entry.jar, entry.entry, true).await {
Ok(uri) => uri,
Err(e) => {
tracing::info!("library class stays a stub: {}", e.message);
out.push(loc);
continue;
}
}
} else {
original.to_owned()
};
let doc = self.virtual_document(&uri).await.ok();
let range = match (&name, &doc) {
// jdtls' own class: its range is exact (overloads included) unless it maps a
// Lombok-generated member onto the annotation or class header, which doesn't
// name the member; only then look the declaration up in the source.
(Some(name), Some(doc)) if jdt => {
let line = doc.text.lines().nth(loc.range.start.line as usize).unwrap_or_default();
if library_source::identifier_at(line, loc.range.start.col) == Some(name.as_str()) {
loc.range
} else {
Some(library_source::declaration_range(&doc.text, name))
.filter(|r| *r != Range::default())
.unwrap_or(loc.range)
}
}
(Some(name), Some(doc)) => library_source::declaration_range(&doc.text, name),
_ if jdt => loc.range,
let range = match (&name, self.virtual_document(&uri).await) {
(Some(name), Ok(doc)) => library_source::declaration_range(&doc.text, name),
_ => Range::default(),
};
out.push(if jdt {
Location { range, ..loc }
} else {
Location { path: uri.clone().into(), range, uri: Some(uri) }
});
out.push(Location { path: uri.clone().into(), range, uri: Some(uri) });
}
out
}
+1 -62
View File
@@ -180,7 +180,6 @@ pub(crate) fn declaration_range(text: &str, name: &str) -> Range {
const KEYWORDS: [&str; 9] = ["fun", "class", "interface", "object", "val", "var", "typealias", "enum", "record"];
let is_ident = |c: char| c.is_alphanumeric() || c == '_' || c == '$';
let mut fallback = None;
let mut field = None;
let mut block_comment = false;
for (line_no, line) in text.lines().enumerate() {
let trimmed = line.trim_start();
@@ -224,40 +223,9 @@ pub(crate) fn declaration_range(text: &str, name: &str) -> Range {
if java_member && fallback.is_none() {
fallback = Some(range);
}
// A Java field (`private String name;`, `int age = 5;`): Lombok sources declare only
// the field, the accessors exist solely in the compiled class. A method of that name
// still wins, so a same-named local declared before it is not taken.
let java_field = matches!(line[end..].trim_start().chars().next(), Some(';' | '=' | ','))
&& !head.trim_end().ends_with('.')
&& !head.trim().is_empty()
&& !head.contains(['=', '('])
&& !words.iter().any(|w| matches!(*w, "return" | "throw" | "new" | "yield" | "assert"));
if java_field && field.is_none() {
field = Some(range);
}
}
}
if let Some(range) = fallback.or(field) {
return range;
}
accessor_field(name).map(|field| declaration_range(text, &field)).unwrap_or_default()
}
/// The field a Lombok/bean accessor stands for (`getName`/`setName` → `name`,
/// `isActive` → `active`); `None` for names that are not accessors.
fn accessor_field(name: &str) -> Option<String> {
let rest = ["get", "set", "is"]
.iter()
.find_map(|p| name.strip_prefix(p))
.filter(|r| r.chars().next().is_some_and(|c| c.is_uppercase()))?;
let mut chars = rest.chars();
let first = chars.next()?;
// Bean convention: `getURL` → `URL`, `getName` → `name`.
if rest.chars().nth(1).is_some_and(|c| c.is_uppercase()) {
Some(rest.to_owned())
} else {
Some(first.to_lowercase().collect::<String>() + chars.as_str())
}
fallback.unwrap_or_default()
}
/// The identifier around `col` (UTF-16) of `line`.
@@ -620,35 +588,6 @@ mod tests {
assert_eq!(declared_package("class A"), "");
}
#[test]
fn lombok_accessors_and_java_fields_locate_the_field() {
// Lombok sources declare only the field; the accessors exist only in the
// compiled class, so navigation must fall back to the underlying field.
let lombok = "package example.entity;\n\nimport lombok.Getter;\nimport lombok.Setter;\n\n@Getter\n@Setter\npublic class UserEntity {\n private String name;\n private int age;\n private boolean active;\n}\n";
for (name, line, col) in [
("getName", 8, 19),
("setName", 8, 19),
("name", 8, 19),
("getAge", 9, 16),
("isActive", 10, 20),
("active", 10, 20),
] {
let r = declaration_range(lombok, name);
assert_eq!((r.start.line, r.start.col), (line, col), "{name}");
}
// An explicitly declared accessor still wins over the field.
let plain = "class Plain {\n private String name;\n public String getName() { return name; }\n}\n";
assert_eq!(declaration_range(plain, "getName").start.line, 2);
// Initialized fields count; a method beats a same-named local declared before it.
let init = "class Init {\n private int count = 0;\n void a() {\n int size = 1;\n }\n int size() { return 2; }\n}\n";
assert_eq!(declaration_range(init, "getCount").start.line, 1);
assert_eq!(declaration_range(init, "size").start.line, 5);
// Bean convention keeps acronyms; non-accessors are not remapped.
assert_eq!(accessor_field("getURL").as_deref(), Some("URL"));
assert_eq!(accessor_field("getter"), None);
assert_eq!(declaration_range(lombok, "missing"), Range::default());
}
#[test]
fn locates_declarations_in_kotlin_and_java_sources() {
let at = |text: &str, name: &str| {
+3 -33
View File
@@ -2568,35 +2568,6 @@ async fn configuration_answer_resyncs_open_documents_of_opted_in_servers() {
assert_eq!(s.launches.load(Ordering::SeqCst), 1);
}
#[tokio::test(flavor = "multi_thread")]
async fn eslint_configuration_includes_workspace_folder() {
let h = harness_configured("mock", "mk", &[("eslint", incremental_caps()), ("mock", incremental_caps())], |cfg| {
if cfg.name == "eslint" {
cfg.settings = Some(json!({ "workingDirectory": { "mode": "auto" } }));
}
});
h.open("a.mk", "x");
h.wait_status("eslint", ServerStatus::Ready).await;
h.wait_status("mock", ServerStatus::Ready).await;
let items = json!({ "items": [{ "section": "" }] });
let eslint: Value =
h.launcher.state("eslint").peer().request("workspace/configuration", items.clone(), None).await.unwrap();
assert_eq!(
eslint,
json!([{
"flag": true,
"nested": { "deep": 1 },
"workingDirectory": { "mode": "auto" },
"workspaceFolder": {
"uri": uri_of(&h.root),
"name": h.root.file_name().unwrap().to_string_lossy(),
},
}])
);
let other: Value = h.launcher.state("mock").peer().request("workspace/configuration", items, None).await.unwrap();
assert_eq!(other, json!([{ "flag": true, "nested": { "deep": 1 } }]));
}
#[tokio::test(flavor = "multi_thread")]
async fn settings_changes_reach_servers_without_restarts() {
let h = harness(&[("mock", incremental_caps()), ("extra", incremental_caps())]);
@@ -3034,13 +3005,13 @@ async fn a_project_update_attaches_maven_generated_sources_before_rechecking() {
.as_array()
.unwrap()
.iter()
.map(|arg| (PathBuf::from(arg["path"].as_str().unwrap()), arg["test"].as_bool().unwrap()))
.map(|arg| (arg["path"].as_str().unwrap().to_owned(), arg["test"].as_bool().unwrap()))
.collect();
assert_eq!(
paths,
vec![
(h.root.join("target/generated-sources/protobuf/grpc-java"), false),
(h.root.join("target/generated-sources/protobuf/java"), false),
(h.root.join("target/generated-sources/protobuf/grpc-java").to_string_lossy().into_owned(), false),
(h.root.join("target/generated-sources/protobuf/java").to_string_lossy().into_owned(), false),
]
);
}
@@ -3683,7 +3654,6 @@ async fn a_framework_server_serves_files_spelt_differently_from_the_project() {
let range = json!({ "start": { "line": 1, "character": 2 }, "end": { "line": 1, "character": 11 } });
framework.respond("textDocument/definition", json!([{ "uri": uri_of(&component), "range": range }]));
#[cfg(unix)]
let links = tempfile::tempdir().unwrap();
let mut spellings = Vec::new();
#[cfg(unix)]
Binary file not shown.
@@ -1 +1 @@
b24fb8d5161006104698fb07a43432601b4f16fdc4a34cc70058cbef7e973066
1056d650117bc2216ac518aa26b27cf898f58db62369ae285b9d8925ada74dff
+3 -9
View File
@@ -181,13 +181,9 @@ impl commands::Guest for Misbehave {
};
let child = process::start(&cmd, None)?;
// CPU work per step (loop iterations), for fuel budget tests.
let arg = arg.as_deref().unwrap_or("");
let report = !arg.starts_with("quiet:");
let work: u64 = arg.strip_prefix("quiet:").unwrap_or(arg).parse().unwrap_or(0);
let work: u64 = arg.as_deref().and_then(|a| a.parse().ok()).unwrap_or(0);
for step in 0..25 {
if report {
task.report(step, Some(25), Some("waiting"));
}
task.report(step, Some(25), Some("waiting"));
let mut x: u64 = 0;
for _ in 0..work {
x = std::hint::black_box(x.wrapping_add(1));
@@ -199,9 +195,7 @@ impl commands::Guest for Misbehave {
// Let it finish on its own: no kill, no slow teardown.
child.close_stdin()?;
let _ = child.wait(5_000);
if report {
task.report(25, Some(25), Some("done"));
}
task.report(25, Some(25), Some("done"));
Ok(Some("still here".into()))
}
// `editor.write` is not granted: an error, not a trap.
-29
View File
@@ -537,16 +537,6 @@ pub fn configure_gradle_runtime(cfg: &mut LanguageServerConfig, root: &Path, bui
merge(cfg.settings.get_or_insert_with(|| json!({})), json!({"java": {"import": {"gradle": gradle}}}));
}
/// Settings › Build Tools › Maven › Automatically download sources → jdtls
/// `java.maven.downloadSources`.
pub fn configure_maven_sources(cfg: &mut LanguageServerConfig, s: &Settings) {
if cfg.name != "jdtls" {
return;
}
let download = s.languages.java.maven.download_sources;
merge(cfg.settings.get_or_insert_with(|| json!({})), json!({"java": {"maven": {"downloadSources": download}}}));
}
/// Maven options from settings, placed before the goals: `-s <settings.xml>`,
/// `-t <toolchains.xml>`, `-Dmaven.repo.local=<dir>`, `-T <count>` and `-P <profiles>`.
pub fn maven_options(root: &Path, s: &Settings) -> Vec<String> {
@@ -2360,25 +2350,6 @@ mod maven_linkage_tests {
assert_eq!(default_maven_repository_in(home), Some(home.join(".m2/repository")));
}
#[test]
fn maven_sources_download_follows_the_setting() {
let mut settings = Settings::default();
let mut cfg = custom_server("jdtls", &LanguageServerSettings::default());
cfg.settings = Some(json!({"java": {"maven": {"downloadSources": true, "updateSnapshots": false}}}));
configure_maven_sources(&mut cfg, &settings);
assert_eq!(
cfg.settings,
Some(json!({"java": {"maven": {"downloadSources": false, "updateSnapshots": false}}}))
);
settings.languages.java.maven.download_sources = true;
configure_maven_sources(&mut cfg, &settings);
assert_eq!(cfg.settings.unwrap()["java"]["maven"]["downloadSources"], json!(true));
let mut other = custom_server("kotlin", &LanguageServerSettings::default());
configure_maven_sources(&mut other, &settings);
assert_eq!(other.settings, None);
}
#[test]
fn gradle_import_runs_the_gradle_the_ide_builds_with() {
let root = Path::new("/p");
+4 -97
View File
@@ -21,67 +21,11 @@ fn root(data_dir: &Path) -> PathBuf {
data_dir.join("lsp").join("jdtls")
}
/// jdtls' temporary folder, inside its workspace.
const TEMP_DIR: &str = ".tmp";
fn workspace(cfg: &LanguageServerConfig) -> Option<&Path> {
cfg.args.iter().position(|a| a == "-data").and_then(|i| cfg.args.get(i + 1)).map(Path::new)
}
fn temp_arg(workspace: &Path) -> String {
format!("-Djava.io.tmpdir={}", workspace.join(TEMP_DIR).to_string_lossy())
}
/// Gives jdtls a temporary folder inside a workspace of ours (`<workspace>/.tmp`) unless the
/// user's JVM arguments choose one. JDT APT copies a project's annotation processor jars into a
/// new `jdt-apt-*` folder for each processor class loader and deletes it only when the JVM exits
/// normally — never on Windows, where the jars are still open then — so in the system temp
/// folder they pile up with every start; [`mark_used`] empties this one before each start.
pub fn use_own_temp(cfg: &mut LanguageServerConfig, data_dir: &Path) {
if cfg.name != "jdtls" || cfg.args.iter().any(|a| a.contains("-Djava.io.tmpdir=")) {
return;
}
let Some(arg) = workspace(cfg).filter(|w| w.starts_with(root(data_dir))).map(temp_arg) else { return };
// Launched directly, JVM options go before `-jar`; through the script, as `--jvm-arg=`.
match cfg.args.iter().position(|a| a == "-jar") {
Some(jar) => cfg.args.insert(jar, arg),
None => cfg.args.push(format!("--jvm-arg={arg}")),
}
}
/// Empties the temporary folder [`use_own_temp`] gave the workspace. Best effort: files a server
/// still has open on Windows stay until a later start.
fn clear_temp(cfg: &LanguageServerConfig, workspace: &Path) {
let arg = temp_arg(workspace);
if !cfg.args.iter().any(|a| a.strip_prefix("--jvm-arg=").unwrap_or(a) == arg) {
return;
}
let temp = workspace.join(TEMP_DIR);
for entry in std::fs::read_dir(&temp).into_iter().flatten().flatten() {
let path = entry.path();
let removed = if entry.file_type().is_ok_and(|t| t.is_dir()) {
std::fs::remove_dir_all(&path)
} else {
std::fs::remove_file(&path)
};
if let Err(e) = removed {
tracing::debug!("jdtls: cannot remove temporary {}: {e}", path.display());
}
}
if let Err(e) = std::fs::create_dir_all(&temp) {
tracing::warn!("jdtls: cannot create its temporary folder {}: {e}", temp.display());
}
}
/// Records that jdtls is starting on the workspace of `cfg` (its `-data` folder), and empties
/// the workspace's temporary folder.
/// Records that jdtls is starting on the workspace of `cfg` (its `-data` folder).
pub fn mark_used(cfg: &LanguageServerConfig) {
let Some(dir) = workspace(cfg) else { return };
clear_temp(cfg, dir);
if let Err(e) = std::fs::create_dir_all(dir).and_then(|()| {
let marker = std::fs::File::create(dir.join(USED_MARKER))?;
marker.set_modified(SystemTime::now())
}) {
let Some(dir) = cfg.args.iter().position(|a| a == "-data").and_then(|i| cfg.args.get(i + 1)) else { return };
let dir = Path::new(dir);
if let Err(e) = std::fs::create_dir_all(dir).and_then(|()| std::fs::write(dir.join(USED_MARKER), b"")) {
tracing::debug!("jdtls: cannot mark {} as used: {e}", dir.display());
}
}
@@ -195,43 +139,6 @@ mod tests {
assert!(ws.exists());
}
#[test]
fn jdtls_keeps_its_temporary_files_in_its_workspace_and_starts_with_none() {
let tmp = tempfile::tempdir().unwrap();
let ws = root(tmp.path()).join("p");
let temp = format!("-Djava.io.tmpdir={}", ws.join(TEMP_DIR).to_string_lossy());
// Through the launcher script.
let mut script = cfg(&ws);
use_own_temp(&mut script, tmp.path());
assert_eq!(script.args.last(), Some(&format!("--jvm-arg={temp}")));
// Launched directly: a JVM option, before `-jar`.
let mut direct = cfg(&ws);
direct.args.splice(0..0, ["-Xmx2G".to_owned(), "-jar".to_owned(), "launcher.jar".to_owned()]);
use_own_temp(&mut direct, tmp.path());
assert_eq!(direct.args[..3], ["-Xmx2G".to_owned(), temp.clone(), "-jar".to_owned()]);
let stale = ws.join(TEMP_DIR).join("jdt-apt-1");
std::fs::create_dir_all(&stale).unwrap();
std::fs::write(stale.join("0_processor.jar"), "").unwrap();
std::fs::write(ws.join(TEMP_DIR).join("file.tmp"), "").unwrap();
mark_used(&direct);
assert!(ws.join(TEMP_DIR).is_dir());
assert_eq!(std::fs::read_dir(ws.join(TEMP_DIR)).unwrap().count(), 0);
// The user's own choice, and a workspace that is not ours, are left alone.
let mut own = cfg(&ws);
own.args.push("--jvm-arg=-Djava.io.tmpdir=/elsewhere".into());
use_own_temp(&mut own, tmp.path());
assert_eq!(own.args.iter().filter(|a| a.contains("java.io.tmpdir")).count(), 1);
let mut theirs = cfg(&tmp.path().join("their-workspace"));
use_own_temp(&mut theirs, tmp.path());
assert!(!theirs.args.iter().any(|a| a.contains("java.io.tmpdir")));
std::fs::create_dir_all(ws.join(TEMP_DIR).join("kept")).unwrap();
mark_used(&cfg(&ws));
assert!(ws.join(TEMP_DIR).join("kept").exists());
}
#[cfg(unix)]
#[test]
fn a_workspace_from_before_markers_is_judged_by_its_folders_and_log() {
+1 -21
View File
@@ -86,25 +86,5 @@ fn excluded_subtrees(c: &mut Criterion) {
group.finish();
}
// Lockfile-sized files with a hit on every line, one per folder so every walker
// thread is inside its own dense file when the 10 000-match default limit is reached.
fn dense_files(c: &mut Criterion) {
let dir = tempfile::tempdir().unwrap();
for module in 0..24 {
let sub = dir.path().join(format!("packages/p{module}"));
std::fs::create_dir_all(&sub).unwrap();
let mut text = String::with_capacity(2 << 20);
for i in 0..40_000u32 {
text.push_str(&format!(" \"version\": \"{}.{}.{module}\",\n", i / 100, i % 100));
}
std::fs::write(sub.join("package-lock.json"), text).unwrap();
}
let q = query("version", false);
let mut group = c.benchmark_group("search_dense_files");
group.sample_size(15);
group.bench_function("24x40k_limit", |b| b.iter(|| black_box(run(dir.path(), &q))));
group.finish();
}
criterion_group!(benches, bench, excluded_subtrees, dense_files);
criterion_group!(benches, bench, excluded_subtrees);
criterion_main!(benches);
+20 -109
View File
@@ -22,9 +22,6 @@ pub(crate) const DEFAULT_MAX_MATCHES: u32 = 10_000;
/// How many matched lines a sink handles between cancellation-token checks
/// (reads from disk check on every buffer refill).
const CANCEL_CHECK_LINES: u32 = 256;
/// How many matches a file keeps before claiming them from the shared budget: each file
/// searched in parallel holds about this many unclaimed matches at most, not up to the whole budget.
const CLAIM_BATCH: u32 = 64;
pub(crate) struct Request<'a> {
pub root: &'a Path,
@@ -90,11 +87,6 @@ impl Control<'_> {
}
}
}
/// Returns matches claimed for a file whose matches are then dropped.
fn release(&self, n: u32) {
self.matches.fetch_sub(n, Relaxed);
}
}
struct Ctx<'a> {
@@ -330,16 +322,24 @@ impl Ctx<'_> {
None => self.search_disk(path, matcher, searcher, &mut sink),
},
};
if let Err(err) = result
&& !self.ctl.stopped()
{
tracing::debug!("search {}: {err}", path.display());
if let Err(err) = result {
if !self.ctl.stopped() {
tracing::debug!("search {}: {err}", path.display());
}
if sink.lines.is_empty() || self.ctl.cancelled.load(Relaxed) {
return;
}
}
if sink.binary || sink.lines.is_empty() || self.ctl.cancelled.load(Relaxed) {
self.ctl.release(sink.claimed);
return;
}
sink.settle();
let found = u32::try_from(sink.count).unwrap_or(u32::MAX);
let granted = self.ctl.reserve(found);
if granted < found {
self.ctl.limit_hit.store(true, Relaxed);
self.ctl.stop.store(true, Relaxed);
truncate(&mut sink.lines, granted as usize);
}
if sink.lines.is_empty() {
return;
}
@@ -364,17 +364,14 @@ impl Ctx<'_> {
} else {
!reader.is_utf8()
};
// A stopped search needs the decoded text only to fill what the byte search claimed.
if !decode || (self.ctl.stopped() && sink.claimed == 0) {
if !decode || self.ctl.stopped() {
return result;
}
let Some(text) = (self.text.decode)(path, &std::fs::read(path)?) else {
sink.binary = true;
return Ok(());
};
let claimed = sink.claimed;
*sink = FileSink::new(matcher, &self.ctl, None);
sink.claimed = claimed;
searcher.search_slice(matcher, text.as_bytes(), sink)
}
}
@@ -392,11 +389,8 @@ struct FileSink<'a> {
matcher: &'a RegexMatcher,
ctl: &'a Control<'a>,
lines: Vec<LineMatch>,
/// Match ranges kept so far.
count: u32,
/// Matches claimed from the shared budget: up to `count`, or more while a decoded
/// file is searched again under the claim of its byte search.
claimed: u32,
/// Match ranges collected so far.
count: usize,
binary: bool,
ticks: u32,
/// Scratch buffers reused across lines.
@@ -417,7 +411,6 @@ impl<'a> FileSink<'a> {
ctl,
lines: Vec::new(),
count: 0,
claimed: 0,
binary: false,
ticks: 0,
found: Vec::new(),
@@ -425,36 +418,6 @@ impl<'a> FileSink<'a> {
context,
}
}
/// Claims the matches kept since the last claim. When the budget cannot take them
/// all, keeps the ones it can, marks the limit hit and returns false.
fn claim(&mut self) -> bool {
if self.count <= self.claimed {
return true;
}
let unclaimed = self.count - self.claimed;
let granted = self.ctl.reserve(unclaimed);
self.claimed += granted;
if granted == unclaimed {
return true;
}
self.ctl.limit_hit.store(true, Relaxed);
self.ctl.stop.store(true, Relaxed);
truncate(&mut self.lines, self.claimed as usize);
self.count = self.claimed;
false
}
/// Makes the claim match the matches kept once the file is done: claims the rest, or
/// gives back the part of a byte search's claim the decoded text did not use.
fn settle(&mut self) {
if self.count < self.claimed {
self.ctl.release(self.claimed - self.count);
self.claimed = self.count;
} else {
self.claim();
}
}
}
/// Kind of the comment or string literal containing byte `pos` (`literals` sorted).
@@ -468,9 +431,7 @@ impl Sink for FileSink<'_> {
fn matched(&mut self, _searcher: &Searcher, m: &SinkMatch<'_>) -> Result<bool, io::Error> {
self.ticks += 1;
let stop = self.ctl.stopped() || (self.ticks.is_multiple_of(CANCEL_CHECK_LINES) && self.ctl.should_stop());
// Unless cancelled, a decoded file still fills the claim its byte search took.
if stop && (self.count >= self.claimed || self.ctl.cancelled.load(Relaxed)) {
if self.ctl.stopped() || (self.ticks.is_multiple_of(CANCEL_CHECK_LINES) && self.ctl.should_stop()) {
return Ok(false);
}
let buffer = m.buffer();
@@ -514,7 +475,7 @@ impl Sink for FileSink<'_> {
ranges.push((a - line_start, b - line_start));
}
if !ranges.is_empty() {
self.count = self.count.saturating_add(u32::try_from(ranges.len()).unwrap_or(u32::MAX));
self.count += ranges.len();
let line_no = u32::try_from(line_no).unwrap_or(u32::MAX);
self.lines.push(line_match(line_no, &block[line_start..content_end], &ranges));
}
@@ -524,8 +485,7 @@ impl Sink for FileSink<'_> {
self.found = found;
self.ranges = ranges;
// One match beyond the remaining budget is enough to know the limit is hit.
let unclaimed = self.count.saturating_sub(self.claimed);
Ok(if unclaimed >= CLAIM_BATCH || unclaimed > self.ctl.remaining() { self.claim() } else { true })
Ok(self.count <= self.ctl.remaining() as usize)
}
fn binary_data(&mut self, _searcher: &Searcher, _offset: u64) -> Result<bool, io::Error> {
@@ -682,52 +642,3 @@ mod walk_tests {
assert!(seen.lock().unwrap().is_empty());
}
}
#[cfg(test)]
mod budget_tests {
use super::*;
fn control(cancel: &CancellationToken, max: u32) -> Control<'_> {
Control {
cancel,
stop: AtomicBool::new(false),
cancelled: AtomicBool::new(false),
limit_hit: AtomicBool::new(false),
matches: AtomicU32::new(0),
files: AtomicU32::new(0),
max,
}
}
/// Searches `lines` matching lines without finishing the file, like a walker thread mid-file.
fn scan<'a>(ctl: &'a Control<'a>, matcher: &'a RegexMatcher, lines: usize) -> FileSink<'a> {
let mut sink = FileSink::new(matcher, ctl, None);
let mut searcher = SearcherBuilder::new().line_number(true).build();
searcher.search_slice(matcher, "x\n".repeat(lines).as_bytes(), &mut sink).unwrap();
sink
}
#[test]
fn files_in_flight_never_hold_more_matches_than_the_budget() {
let cancel = CancellationToken::new();
let ctl = control(&cancel, 100);
let matcher = RegexMatcher::new("x").unwrap();
let (first, second) = (scan(&ctl, &matcher, 150), scan(&ctl, &matcher, 150));
assert_eq!((first.lines.len(), second.lines.len()), (100, 0));
assert_eq!(ctl.matches.load(Relaxed), 100);
assert!(ctl.limit_hit.load(Relaxed));
}
#[test]
fn unclaimed_matches_of_a_file_in_flight_stay_within_the_budget() {
let cancel = CancellationToken::new();
let ctl = control(&cancel, 1000);
let matcher = RegexMatcher::new("x").unwrap();
let mut first = scan(&ctl, &matcher, 40);
let second = scan(&ctl, &matcher, 2000);
assert_eq!((first.lines.len(), second.lines.len()), (40, 1000));
assert!(!first.claim());
assert_eq!((first.lines.len(), ctl.matches.load(Relaxed)), (0, 1000));
assert!(ctl.limit_hit.load(Relaxed));
}
}
-44
View File
@@ -314,25 +314,6 @@ fn match_limit() {
assert_eq!(summary.matches, 14);
}
#[test]
fn match_limit_across_parallel_files() {
// One file per folder, so several walker threads search at once.
let content = "x\n".repeat(50);
let names: Vec<String> = (0..16).map(|i| format!("m{i}/a.txt")).collect();
let files: Vec<(&str, &[u8])> = names.iter().map(|n| (n.as_str(), content.as_bytes())).collect();
let p = project(&files);
for _ in 0..20 {
let (views, summary) = run(p.path(), &SearchQuery { max_matches: 800, ..query("x") });
assert!(!summary.limit_hit);
assert_eq!((total(&views), summary.matches, summary.files), (800, 800, 16));
let (views, summary) = run(p.path(), &SearchQuery { max_matches: 799, ..query("x") });
assert!(summary.limit_hit);
assert_eq!((total(&views), summary.matches), (799, 799));
assert_eq!(summary.files as usize, views.len());
}
}
#[test]
fn default_limit_is_ten_thousand() {
let content = "a\n".repeat(10_050);
@@ -794,31 +775,6 @@ fn non_utf8_files_are_searched_as_text() {
assert_eq!(views[0].matches[0].ranges, [(13, 20), (21, 28), (29, 36)]);
}
#[test]
fn dropped_matches_give_back_their_budget() {
// Matches claimed before a late NUL (binary) or late GBK bytes (searched again as text).
let head = b"needle\n".repeat(100);
let filler = b"a".repeat(200_000);
let binary = [head.as_slice(), &filler, b"\0\n"].concat();
let late_gbk = [head.as_slice(), &filler, b"\n", &gbk("中文\n")].concat();
// One project each: a thread's searcher keeps its grown buffer for the next file.
for (file, bytes, found) in [("bin.dat", binary, 0), ("late.txt", late_gbk, 100)] {
let p = project(&[(file, &bytes)]);
let (views, summary) = run(p.path(), &query("needle"));
assert_eq!((total(&views), summary.matches), (found, found as u32), "{file}");
assert!(!summary.limit_hit);
}
}
#[test]
fn non_utf8_files_past_the_limit_show_decoded_text() {
let p = project(&[("a.txt", &gbk(&"x 中文\n".repeat(200)))]);
let (views, summary) = run(p.path(), &SearchQuery { max_matches: 100, ..query("x") });
assert!(summary.limit_hit);
assert_eq!((total(&views), summary.matches), (100, 100));
assert!(views[0].matches.iter().all(|m| m.text == "x 中文"));
}
#[test]
fn non_utf8_files_use_the_given_decoder() {
// Text too short to detect reliably decodes with the configured encoding.
+6 -12
View File
@@ -1,15 +1,14 @@
//! `cargo bench -p ide-text`: change sets and coordinate conversion on a 1 MB document
//! (and a 5 MB one where whole-document copies would show).
//! `cargo bench -p ide-text`: change sets and coordinate conversion on a 1 MB document.
use criterion::{BatchSize, Criterion, black_box, criterion_group, criterion_main};
use ide_core::{ChangeSet, Pos, TextChange};
use ide_text::Document;
/// ~`bytes` of code-like text with some non-ASCII content.
fn sample_text(bytes: usize) -> String {
let mut s = String::with_capacity(bytes);
/// ~1 MB of code-like text with some non-ASCII content.
fn sample_text() -> String {
let mut s = String::with_capacity(1 << 20);
let mut i = 0u32;
while s.len() < bytes {
while s.len() < 1 << 20 {
s.push_str(&format!(" let value_{i} = compute(\"héllo 😀\", {i}) + other_{i};\n"));
i += 1;
}
@@ -48,7 +47,7 @@ fn change_set(doc: &Document, rng: &mut Lcg, n: usize) -> ChangeSet {
}
fn bench(c: &mut Criterion) {
let text = sample_text(1 << 20);
let text = sample_text();
c.bench_function("text/open_1mb", |b| b.iter(|| Document::new(black_box(&text))));
let base = Document::new(&text);
@@ -78,11 +77,6 @@ fn bench(c: &mut Criterion) {
c.bench_function("text/diff_two_edits_1mb", |b| b.iter(|| base.diff(black_box(&two_edits))));
let every_line = text.replace("compute", "calculate");
c.bench_function("text/diff_every_line_1mb", |b| b.iter(|| base.diff(black_box(&every_line))));
let large_text = sample_text(5 << 20);
let large = Document::new(&large_text);
let one_edit = large_text.replacen("value_40000 ", "renamed_40000 ", 1);
assert_ne!(one_edit, large_text);
c.bench_function("text/diff_one_edit_5mb", |b| b.iter(|| large.diff(black_box(&one_edit))));
c.bench_function("text/offset_to_pos_round_trip", |b| {
let mut rng = Lcg(3);
let len = base.len_utf16();
+4 -112
View File
@@ -93,54 +93,6 @@ fn common_ends(a: &str, b: &str) -> (usize, usize) {
(prefix, suffix)
}
/// [`common_ends`] of the rope's text and `b`, walking the rope's chunks instead
/// of copying it: whole chunks compare as slices, bytes only around the mismatch.
fn rope_common_ends(rope: &ropey::Rope, b: &str) -> (usize, usize) {
let bb = b.as_bytes();
let mut prefix = 0;
for chunk in rope.chunks() {
let n = common_prefix_len(chunk.as_bytes(), &bb[prefix..]);
prefix += n;
if n < chunk.len() {
break;
}
}
prefix = rope.char_to_byte(rope.byte_to_char(prefix));
let len = rope.len_bytes();
let limit = len.min(bb.len()) - prefix;
let mut suffix = 0;
let mut chunks = rope.chunks_at_byte(len).0.reversed();
while suffix < limit {
let Some(chunk) = chunks.next() else { break };
let n = common_suffix_len(chunk.as_bytes(), &bb[..bb.len() - suffix]).min(limit - suffix);
suffix += n;
if n < chunk.len() {
break;
}
}
let ch = rope.byte_to_char(len - suffix);
if rope.char_to_byte(ch) < len - suffix {
suffix = len - rope.char_to_byte(ch + 1);
}
(prefix, suffix)
}
fn common_prefix_len(a: &[u8], b: &[u8]) -> usize {
let n = a.len().min(b.len());
if a[..n] == b[..n] {
return n;
}
a.iter().zip(b).take_while(|(x, y)| x == y).count()
}
fn common_suffix_len(a: &[u8], b: &[u8]) -> usize {
let n = a.len().min(b.len());
if a[a.len() - n..] == b[b.len() - n..] {
return n;
}
a.iter().rev().zip(b.iter().rev()).take_while(|(x, y)| x == y).count()
}
/// Byte offset of each line, then the total length.
fn line_starts(lines: &[&str]) -> Vec<usize> {
let mut at = 0;
@@ -444,8 +396,9 @@ impl Document {
/// Past `deadline` the regions get coarser, never wrong.
fn diff_until(&self, text: &str, deadline: Instant) -> ChangeSet {
let new = normalize_line_endings(text);
let (prefix, suffix) = rope_common_ends(&self.rope, &new);
let old_rest = String::from(self.rope.byte_slice(prefix..self.rope.len_bytes() - suffix));
let old = self.rope.to_string();
let (prefix, suffix) = common_ends(&old, &new);
let old_rest = &old[prefix..old.len() - suffix];
let new_rest = &new[prefix..new.len() - suffix];
let old_lines: Vec<&str> = old_rest.split_inclusive('\n').collect();
@@ -454,7 +407,7 @@ impl Document {
let new_starts = line_starts(&new_lines);
let mut changes = Vec::new();
let mut utf16_at = self.byte_to_offset(prefix);
let mut utf16_at = utf16_len(&old[..prefix]);
let mut old_at = 0;
let mut region: Option<(LineRange, LineRange)> = None;
let ops =
@@ -757,67 +710,6 @@ mod tests {
assert_eq!(set.changes, vec![tc(3, 6, "ONE"), tc(15, 18, "TWO")]);
}
/// The rope scan must trim exactly what `common_ends` trims on the copied text.
fn assert_rope_ends(old: &str, new: &str) {
let doc = Document::new(old);
let (prefix, suffix) = rope_common_ends(&doc.rope, new);
assert_eq!((prefix, suffix), common_ends(old, new), "{old:?} -> {new:?}");
assert_eq!(doc.byte_to_offset(prefix), utf16_len(&old[..prefix]));
}
#[test]
fn rope_common_ends_matches_common_ends() {
let unit = "héllo 😀 wörld, ©\n";
let base = unit.repeat(400);
assert!(Document::new(&base).rope.chunks().count() > 4, "spans several chunks");
for (old, new) in [("", ""), ("", "abc"), ("abc", ""), ("é", "è"), ("😀", "😁"), ("é", "©")] {
assert_rope_ends(old, new);
}
assert_rope_ends(&base, &base);
assert_rope_ends(&base, "");
assert_rope_ends("", &base);
assert_rope_ends(&base, &format!("{base}tail"));
assert_rope_ends(&format!("{base}tail"), &base);
assert_rope_ends(&base, &base[unit.len()..]);
assert_rope_ends(&"a".repeat(5000), &"a".repeat(4999));
assert_rope_ends(&"ab".repeat(3000), &"ab".repeat(3001));
assert_rope_ends(&"😀".repeat(2000), &"😀".repeat(1999));
let boundaries: Vec<usize> = base.char_indices().map(|(i, _)| i).step_by(7).collect();
for at in boundaries {
let c = base[at..].chars().next().unwrap();
let rest = &base[at + c.len_utf8()..];
let swapped = match c {
'é' => 'è', // same lead byte
'😀' => '😁', // differs in the last byte only
'©' => 'é', // same trailing byte
_ => 'X',
};
let swap = format!("{}{swapped}{rest}", &base[..at]);
assert_rope_ends(&base, &swap);
// Deleting a char further on stops the suffix scan far from the prefix.
let mut far = at + (swap.len() - at) / 2;
while !swap.is_char_boundary(far) {
far += 1;
}
let gone = swap[far..].chars().next().unwrap().len_utf8();
assert_rope_ends(&base, &format!("{}{}", &swap[..far], &swap[far + gone..]));
assert_rope_ends(&base, &format!("{}{rest}", &base[..at]));
assert_rope_ends(&base, &format!("{}é{c}{rest}", &base[..at]));
}
}
#[test]
fn diff_of_a_large_document_counts_utf16_and_normalizes_crlf() {
let old = "😀 héllo\n".repeat(2000);
let at = old.len() / 2;
let new = format!("{}X{}", &old[..at], &old[at..]);
let doc = Document::new(&old);
let expected = vec![tc(utf16_len(&old[..at]), utf16_len(&old[..at]), "X")];
assert_eq!(doc.diff(&new).changes, expected);
assert_eq!(doc.diff(&new.replace('\n', "\r\n")).changes, expected);
assert!(doc.diff(&old.replace('\n', "\r\n")).changes.is_empty());
}
#[test]
fn diff_past_its_deadline_is_coarser_but_still_correct() {
let old = numbered_lines(5000);
-36
View File
@@ -277,25 +277,6 @@ pub fn copy_merge(
let target_base = project.filter(|p| to.starts_with(p)).or(Some(roots.1));
let rules = Rules::new(from, source_base, excludes);
let target_rules = Rules::new(to, target_base, excludes);
// Find a conflict before writing anything, so declining to overwrite leaves the
// destination untouched. Nothing below a missing destination can conflict.
if !overwrite {
let mut pending = vec![(from.to_path_buf(), to.to_path_buf())];
while let Some((src, dst)) = pending.pop() {
let meta = fs::symlink_metadata(&src)?;
if rules.excluded(&src, meta.is_dir()) || target_rules.excluded(&dst, meta.is_dir()) {
continue;
}
let Ok(existing) = fs::symlink_metadata(&dst) else { continue };
if !(meta.is_dir() && existing.is_dir()) {
return Err(std::io::Error::new(std::io::ErrorKind::AlreadyExists, dst.display().to_string()).into());
}
for entry in fs::read_dir(&src)? {
let entry = entry?;
pending.push((entry.path(), dst.join(entry.file_name())));
}
}
}
let mut pending = vec![(from.to_path_buf(), to.to_path_buf())];
while let Some((src, dst)) = pending.pop() {
let meta = fs::symlink_metadata(&src)?;
@@ -513,23 +494,6 @@ mod tests {
}
}
#[test]
fn a_declined_overwrite_writes_nothing() {
let tmp = tempfile::tempdir().unwrap();
let left = tmp.path().join("left");
let right = tmp.path().join("right");
put(&left, "merge/a-clash.txt", b"source");
put(&left, "merge/z-new.txt", b"source only");
put(&left, "merge/deep/new.txt", b"new");
put(&right, "merge/a-clash.txt", b"destination");
let error =
copy_merge(&left.join("merge"), &right.join("merge"), false, None, &[], (&left, &right)).unwrap_err();
assert_eq!(error.kind, ErrorKind::AlreadyExists);
assert_eq!(fs::read(right.join("merge/a-clash.txt")).unwrap(), b"destination");
assert!(!right.join("merge/z-new.txt").exists());
assert!(!right.join("merge/deep").exists());
}
#[test]
fn subtree_copy_keeps_excludes_anchored_to_each_comparison_root() {
let tmp = tempfile::tempdir().unwrap();
+5 -44
View File
@@ -1,8 +1,8 @@
use ide_core::{IdeError, IdeResult};
use percent_encoding::{AsciiSet, CONTROLS, percent_decode_str, utf8_percent_encode};
use std::collections::{HashMap, HashSet};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, PoisonError};
use std::sync::Arc;
use std::time::Duration;
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
use tokio::net::{TcpListener, TcpStream};
@@ -42,9 +42,6 @@ struct Root {
dir: PathBuf,
port: u16,
serves: Serves,
/// Files handed out by [`WebServer::page_url_for`], as requested. They stay here until
/// the app quits, even if the file stops being HTML: only its content type depends on it.
pages: Mutex<HashSet<PathBuf>>,
}
/// What of its directory a root serves.
@@ -90,18 +87,6 @@ impl WebServer {
/// A project that is the home folder, or holds it, is no boundary to serve whole: its
/// files are served like files outside a project.
pub async fn url_for(&self, root: Option<&Path>, file: &Path) -> IdeResult<String> {
Ok(self.locate(root, file).await?.1)
}
/// [`Self::url_for`] of a file that is an HTML page whatever its name (Settings › File
/// Types): it is served as HTML from now on.
pub async fn page_url_for(&self, root: Option<&Path>, file: &Path) -> IdeResult<String> {
let (served, url) = self.locate(root, file).await?;
served.pages.lock().unwrap_or_else(PoisonError::into_inner).insert(file.to_path_buf());
Ok(url)
}
async fn locate(&self, root: Option<&Path>, file: &Path) -> IdeResult<(Arc<Root>, String)> {
let (base, serves) = match root {
Some(r) if file.starts_with(r) && file != r && self.holds_home(r).await != Some(true) => (r, Serves::All),
_ => {
@@ -117,7 +102,7 @@ impl WebServer {
url.push('/');
url.push_str(&enc(&c.as_os_str().to_string_lossy()));
}
Ok((root, url))
Ok(url)
}
/// Whether `dir` is the home folder or lies above it; `None` when that cannot be told.
@@ -168,7 +153,6 @@ impl WebServer {
dir: dir.to_path_buf(),
port,
serves,
pages: Mutex::default(),
});
tokio::spawn(accept(listener, root.clone()));
tracing::info!("built-in web server on 127.0.0.1:{} for {}", root.port, dir.display());
@@ -336,9 +320,7 @@ async fn resolve(root: &Root, target: &str) -> Response {
_ => NOT_FOUND,
};
}
let page = root.pages.lock().unwrap_or_else(PoisonError::into_inner).contains(&file);
let mime = if page { HTML } else { content_type(&file) };
Response::File { path: real, len: meta.len(), mime }
Response::File { path: real, len: meta.len(), mime: content_type(&file) }
}
/// `path` with every symlink resolved, if `root` serves it: it lies inside `real_root`
@@ -361,12 +343,10 @@ fn dec(s: &str) -> Option<String> {
percent_decode_str(s).decode_utf8().ok().map(|s| s.into_owned())
}
const HTML: &str = "text/html; charset=utf-8";
fn content_type(path: &Path) -> &'static str {
let ext = path.extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default();
match ext.as_str() {
"html" | "htm" | "xhtml" => HTML,
"html" | "htm" | "xhtml" => "text/html; charset=utf-8",
"css" => "text/css; charset=utf-8",
"js" | "mjs" | "cjs" => "text/javascript; charset=utf-8",
"json" | "map" | "webmanifest" => "application/json; charset=utf-8",
@@ -415,25 +395,6 @@ mod tests {
out
}
#[tokio::test]
async fn a_page_is_html_whatever_its_name() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("site");
std::fs::create_dir_all(&root).unwrap();
std::fs::write(root.join("page.foo"), "<h1>hi</h1>").unwrap();
std::fs::write(root.join("other.foo"), "<h1>no</h1>").unwrap();
let server = server();
let plain = server.url_for(Some(&root), &root.join("page.foo")).await.unwrap();
assert!(get(&plain, None).await.contains("application/octet-stream"));
let page = server.page_url_for(Some(&root), &root.join("page.foo")).await.unwrap();
assert_eq!(page, plain);
assert!(get(&page, None).await.contains("Content-Type: text/html"));
let other = page.replace("page.foo", "other.foo");
assert!(get(&other, None).await.contains("application/octet-stream"), "only the named file");
}
#[tokio::test]
async fn serves_project_files() {
let dir = tempfile::tempdir().unwrap();
+2 -30
View File
@@ -172,9 +172,6 @@ struct DocState {
/// Disk state we last loaded or wrote; changes matching it are our own.
disk_mtime: f64,
disk_len: u64,
/// The file changed on disk while this buffer had unsaved changes; autosave leaves it
/// alone until the user saves explicitly or the buffer is reloaded.
disk_conflict: bool,
closed: bool,
/// URI of a virtual document (no file behind it).
uri: Option<String>,
@@ -267,7 +264,6 @@ impl Documents {
st.native_to_ascii = enabled;
st.disk_mtime = loaded.mtime_ms;
st.disk_len = disk_len(&st.path);
st.disk_conflict = false;
Ok(())
});
if let Err(e) = result {
@@ -461,7 +457,6 @@ impl Documents {
encoding_chosen: false,
disk_mtime: loaded.mtime_ms,
disk_len: disk_len(path),
disk_conflict: false,
closed: false,
uri: None,
};
@@ -534,7 +529,6 @@ impl Documents {
encoding_chosen: false,
disk_mtime: 0.0,
disk_len: 0,
disk_conflict: false,
closed: false,
uri: Some(uri.to_owned()),
};
@@ -593,7 +587,6 @@ impl Documents {
encoding_chosen: false,
disk_mtime: 0.0,
disk_len: 0,
disk_conflict: false,
closed: false,
uri: Some(key.to_string_lossy().into_owned()),
};
@@ -660,8 +653,6 @@ impl Documents {
};
let mut st = slot.lock();
st.closed = true;
// A buffer closed with changes (Don't Save) has nothing left to save.
self.set_dirty(doc, &mut st, false);
if st.observed {
for o in self.observers() {
o.closed(doc, &st.path);
@@ -819,22 +810,7 @@ impl Documents {
/// Writes the document with its original encoding, BOM and line ending.
/// A clean document is not rewritten.
pub fn save(&self, doc: DocId) -> IdeResult<()> {
self.with_doc(doc, |st| self.write(doc, st))
}
/// An automatic save (switching tabs, the window losing focus): `false` when the file changed
/// on disk after this buffer was edited, which only an explicit save may overwrite.
pub fn autosave(&self, doc: DocId) -> IdeResult<bool> {
self.with_doc(doc, |st| {
if st.dirty && st.disk_conflict {
return Ok(false);
}
self.write(doc, st).map(|()| true)
})
}
fn write(&self, doc: DocId, st: &mut DocState) -> IdeResult<()> {
{
if !st.dirty || st.uri.is_some() {
return Ok(());
}
@@ -846,7 +822,6 @@ impl Documents {
};
st.disk_mtime = mtime;
st.disk_len = disk_len(&st.path);
st.disk_conflict = false;
self.set_dirty(doc, st, false);
if st.observed {
let text = st.doc.text();
@@ -855,7 +830,7 @@ impl Documents {
}
}
Ok(())
}
})
}
/// Save As for an untitled buffer: writes it to `target` (creating missing
@@ -1115,7 +1090,6 @@ impl Documents {
st.has_bom = loaded.has_bom;
st.disk_mtime = loaded.mtime_ms;
st.disk_len = disk_len(&st.path);
st.disk_conflict = false;
self.replace_locked(doc, st, &loaded.text)?;
// Reloading is not an edit: the buffer matches the file again.
self.set_dirty(doc, st, false);
@@ -1288,14 +1262,13 @@ impl Documents {
if st.dirty {
st.disk_mtime = mtime;
st.disk_len = meta.len();
st.disk_conflict = true;
let name = st.path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
self.sink.emit(IdeEvent::Notify {
level: NotifyLevel::Warning,
title: format!("{name} changed on disk"),
body: Some(format!(
"{} was modified externally but has unsaved changes in the editor. \
Saving explicitly will overwrite the external changes; autosave leaves the file alone.",
Saving will overwrite the external changes.",
st.path.display()
)),
});
@@ -1316,7 +1289,6 @@ impl Documents {
};
st.disk_mtime = loaded.mtime_ms;
st.disk_len = disk_len(&st.path);
st.disk_conflict = false;
if loaded.binary || st.binary {
return Ok(());
}
-33
View File
@@ -228,39 +228,6 @@ fn dirty_events(events: &[IdeEvent]) -> Vec<bool> {
events.iter().filter_map(|e| if let IdeEvent::DocDirty { dirty, .. } = e { Some(*dirty) } else { None }).collect()
}
#[test]
fn autosave_leaves_a_file_changed_on_disk_after_an_edit() {
let f = fixture();
let path = f.root.join("notes.txt");
fs::write(&path, "alpha\nbeta\n").unwrap();
let info = f.docs.open(&path).unwrap();
f.docs.edit(info.id, 0, change(0, 5, "edited")).unwrap();
std::thread::sleep(std::time::Duration::from_millis(20));
fs::write(&path, "alpha\nbeta external\n").unwrap();
f.docs.on_disk_changed(std::slice::from_ref(&path));
assert!(!f.docs.autosave(info.id).unwrap());
assert_eq!(fs::read_to_string(&path).unwrap(), "alpha\nbeta external\n");
assert!(f.docs.snapshot(info.id).unwrap().dirty);
// An explicit save overwrites, as the warning says; autosave works again after it.
f.docs.save(info.id).unwrap();
assert_eq!(fs::read_to_string(&path).unwrap(), "edited\nbeta\n");
f.docs.edit(info.id, 1, change(0, 0, "x")).unwrap();
assert!(f.docs.autosave(info.id).unwrap());
assert_eq!(fs::read_to_string(&path).unwrap(), "xedited\nbeta\n");
}
#[test]
fn closing_a_modified_buffer_reports_it_clean() {
let f = fixture();
let info = f.docs.open_untitled(None).unwrap();
f.docs.edit(info.id, 0, change(0, 0, "draft")).unwrap();
assert_eq!(dirty_events(&f.events.lock()), vec![true]);
f.docs.close(info.id);
assert_eq!(dirty_events(&f.events.lock()), vec![true, false]);
}
#[test]
fn open_edit_save_close() {
let f = fixture();
+1 -1
View File
@@ -131,7 +131,7 @@ Tasks are saved per project and survive restarts. When the agent supports resumi
- **Global (`User`)**: saved in `settings.toml` with environment variable and HTTP header values stored in the OS credential store, shared across projects and agents (or scoped to selected agents).
- **Project (`Workspace`)**: saved in `.openidea/settings.toml`; entries with the same name override Global servers, and servers added outside OpenIDEA stay off until approved.
- **Agent Configs**: discovers servers already configured in `~/.copilot/mcp-config.json` (and installed Copilot CLI plugins), `~/.claude.json`, `~/.codex/config.toml`, `~/.cursor/mcp.json`, `~/.gemini/settings.json`, `~/.jetbrains/mcp/mcp.json`, `.mcp.json`, and `.vscode/mcp.json` so you can import them into Global or Project settings with one click. You can also add or edit servers via structured fields or raw `mcpServers` JSON (**Add from JSON**), and run **Test Connection** to inspect the tools a server advertises.
- **Agent Configs**: discovers servers already configured in `~/.copilot/mcp-config.json`, `~/.claude.json`, `~/.codex/config.toml`, `~/.cursor/mcp.json`, `~/.gemini/settings.json`, `~/.jetbrains/mcp/mcp.json`, `.mcp.json`, and `.vscode/mcp.json` so you can import them into Global or Project settings with one click. You can also add or edit servers via structured fields or raw `mcpServers` JSON (**Add from JSON**), and run **Test Connection** to inspect the tools a server advertises.
- **Per-session (`MCP` / `/mcp`)**: in both **New Agent Task** and active task conversations, open **MCP** in the composer toolbar (or run `/mcp`) to enable or disable individual servers—including the built-in `openidea` server—for that task only, or click **Reset** to return to the inherited defaults.
While the agent works, the line under the conversation says what it is doing: thinking, reading, editing, running a command, writing its reply. **Settings › Agents › Working Status** can show playful words for what it does there instead; they are off by default. Once turned on, they take turns from the moment the work changes, or only after the agent reports nothing new for a number of seconds (0 to 600, 0 by default); screen readers still hear what the agent is doing. Each word stays eight seconds while the agent keeps at the same work, and at least three when it moves on, so the line doesn't flicker. The same page replaces the words: pick what the status says (**Reading…**, **Running a command…**…) and add or remove its words. **Restore Built-in Words** brings back OpenIDEA's; an activity left without words keeps its plain status.
-1
View File
@@ -97,7 +97,6 @@ Open **Run › Edit Configurations…** (also in the run widget menu). The **Run
| **Gradle** / **Maven** | Gradle tasks or Maven goals, optionally through the wrapper |
| **Application** / **JAR Application** / **Spring Boot** | A Java main class, an executable JAR, a Spring Boot application |
| **Tomcat Server** | A WAR application in a local Tomcat |
| **Python** | A Python script or `-m` module |
| **pytest** / **Django tests** | pytest tests, `manage.py test` |
| **Ruby** / **Rake** / **RSpec** | A Ruby script, a Rake task, RSpec examples |
| **PHPUnit** | PHPUnit tests |
-1
View File
@@ -57,7 +57,6 @@ In a Composer project without `vendor/`, or whose installed packages differ from
- **PHPStan**: when the project has `vendor/bin/phpstan`, saved files are checked with it and its findings appear as diagnostics. The **PHPStan › Configuration file** setting picks the config; empty uses `phpstan.neon`, `phpstan.neon.dist` or `phpstan.dist.neon` in the project root.
- **PHP-CS-Fixer**: when a folder above the file has `.php-cs-fixer.php` or `.php-cs-fixer.dist.php` and the project has `vendor/bin/php-cs-fixer`, **Reformat Code** (`⌥⌘L` / `Ctrl+Alt+L`) uses PHP-CS-Fixer instead of the language server.
- **Alignment**: **Settings › Editor › Code Style › PHP › Alignment** has PhpStorm's **Align key-value pairs** (`=>` in multi-line arrays) and **Align consecutive assignments** (`=` in assignment statements on consecutive lines), both off by default. They apply after the language server or PHP-CS-Fixer formats, on save too; for a selection, only to its lines. A blank line, a comment line, another statement or a value spanning several lines starts a new group, and nested arrays align on their own.
## Run and test
+1 -1
View File
@@ -105,7 +105,7 @@ In the editor, gutter icons run or debug:
A test file runs with pytest even when the project declares no test setup (`python -m pytest` with the project interpreter, so pytest must be installed there). In a Django project, `TestCase` tests can also run with `manage.py test`. Results of pytest and of Django's unittest runner appear in the test tree, where **Rerun Failed Tests** runs only the failures.
You can also create **Python** (a script or module), **pytest** and **Django tests** configurations in **Run › Edit Configurations…**. See [Run configurations](/en/guide/run) and [Testing](/en/guide/testing).
You can also create **pytest** and **Django tests** configurations in **Run › Edit Configurations…**. See [Run configurations](/en/guide/run) and [Testing](/en/guide/testing).
| Action | macOS | Windows / Linux |
| --------------------------- | ----- | ---------------- |
+1 -4
View File
@@ -238,8 +238,7 @@ The full table is `UI_KEYS` in
| `--syn-tag`, `--syn-attribute`, `--syn-todo`, `--syn-invalid` | `DEFAULT_TAG`, `DEFAULT_ATTRIBUTE`, `TODO_DEFAULT_ATTRIBUTES`, `BAD_CHARACTER` |
| `--syn-rainbow-1` … `--syn-rainbow-5` (Semantic highlighting) | `RAINBOW_COLOR1` … `RAINBOW_COLOR5` |
| `--wave-error`, `--wave-warning` | `ERRORS_ATTRIBUTES`, `WARNING_ATTRIBUTES` (effect colour) |
| `--bg-matched-brace`, `--bg-identifier-under-caret`, `--fg-identifier-under-caret` | `MATCHED_BRACE_ATTRIBUTES`, `IDENTIFIER_UNDER_CARET_ATTRIBUTES` |
| `--bg-identifier-under-caret-write`, `--fg-identifier-under-caret-write` | `WRITE_IDENTIFIER_UNDER_CARET_ATTRIBUTES` |
| `--bg-matched-brace`, `--bg-identifier-under-caret` | `MATCHED_BRACE_ATTRIBUTES`, `IDENTIFIER_UNDER_CARET_ATTRIBUTES` |
| `--bg-text-search-result`, `--bg-search-result` | `TEXT_SEARCH_RESULT_ATTRIBUTES`, `SEARCH_RESULT_ATTRIBUTES` |
| `--syn-self`, `--syn-keyword-arg`, `--syn-docstring`, `--syn-predefined` | `PY.SELF_PARAMETER`, `PY.KEYWORD_ARGUMENT`, `PY.DOC_COMMENT`, `PY.BUILTIN_NAME` |
| `--ansi-*` | `CONSOLE_*_OUTPUT` (`CONSOLE_DARKGRAY_OUTPUT` is bright black, `CONSOLE_GRAY_OUTPUT` white) |
@@ -520,8 +519,6 @@ conventionally go in the theme file, groups marked _editor scheme_ in the scheme
| `--fg-unused` | `#6f737a` | `#8c8c8c` |
| `--bg-identifier-under-caret` | `#373b39` | `#edebfc` |
| `--bg-identifier-under-caret-write` | `#402f33` | `#fce8f4` |
| `--fg-identifier-under-caret` | `inherit` | `inherit` |
| `--fg-identifier-under-caret-write` | `inherit` | `inherit` |
| `--fg-inlay` | `#868a91` | `#73767c` |
| `--bg-inlay` | `#393b40` | `#00000012` |
| `--wave-error` | `#fa6675` | `#f50000` |
+1 -1
View File
@@ -131,7 +131,7 @@ agent 运行过一个任务后,新任务会以它自动批准所有操作的
- **全局(`用户`)**:保存在 `settings.toml` 中,环境变量与 HTTP 请求头的值保存在系统凭据存储里,跨项目与各智能体共享(也可限定给选定的智能体)。
- **项目(`工作区`)**:保存在 `.openidea/settings.toml` 中,同名服务器覆盖全局配置;在 OpenIDEA 外部写入的项目服务器在批准启用前保持关闭。
- **智能体配置**:自动发现 `~/.copilot/mcp-config.json`(及已安装的 Copilot CLI 插件)、`~/.claude.json`、`~/.codex/config.toml`、`~/.cursor/mcp.json`、`~/.gemini/settings.json`、`~/.jetbrains/mcp/mcp.json`、`.mcp.json` 和 `.vscode/mcp.json` 中已配置的服务器,可一键导入到全局或项目设置。添加或编辑服务器时既可使用表单,也可直接粘贴 `mcpServers` JSON(**从 JSON 添加**),并可通过 **测试连接** 查看服务器声明的工具列表。
- **智能体配置**:自动发现 `~/.copilot/mcp-config.json`、`~/.claude.json`、`~/.codex/config.toml`、`~/.cursor/mcp.json`、`~/.gemini/settings.json`、`~/.jetbrains/mcp/mcp.json`、`.mcp.json` 和 `.vscode/mcp.json` 中已配置的服务器,可一键导入到全局或项目设置。添加或编辑服务器时既可使用表单,也可直接粘贴 `mcpServers` JSON(**从 JSON 添加**),并可通过 **测试连接** 查看服务器声明的工具列表。
- **按会话覆盖(`MCP` / `/mcp`)**:在 **新建 Agent 任务** 和进行中的任务对话中,单击输入框工具栏的 **MCP**(或输入 `/mcp`),即可仅针对当前任务开启或关闭任意服务器(包括内置的 `openidea` 服务器),或点击 **重置** 恢复继承的默认状态。
agent 工作时,对话下方的状态行显示它正在做什么:思考、读取、编辑、运行命令、输出回复。在 **设置 › 智能体 › 工作状态** 中可以让这里改为显示与当前工作相关的趣味文字,默认关闭。开启后,工作一变化就轮换显示,也可以设置在 agent 无新进展多少秒后才显示(0 到 600,默认 0);屏幕阅读器读出的仍是 agent 实际在做的事。agent 持续做同一类工作时,每条文字停留八秒;转向其他工作时也至少停留三秒,状态行不会频繁跳动。同一页面还可以替换这些文字:选择状态(**正在读取…**、**正在运行命令…**…),再添加或移除对应的文字。**恢复内置文字** 会换回 OpenIDEA 自带的文字;没有任何文字的状态只显示实际进展。
-1
View File
@@ -93,7 +93,6 @@ description: "创建、编辑和启动运行配置,从装订区运行代码,
| **Gradle** / **Maven** | Gradle 任务或 Maven 目标,可选择通过 wrapper 运行 |
| **应用程序** / **JAR 应用程序** / **Spring Boot** | Java 主类、可执行 JAR、Spring Boot 应用 |
| **Tomcat 服务器** | 在本地 Tomcat 里运行 WAR 应用 |
| **Python** | Python 脚本或 `-m` 模块 |
| **pytest** / **Django 测试** | pytest 测试、`manage.py test` |
| **Ruby 语言** / **Rake 任务** / **RSpec 测试** | Ruby 脚本、Rake 任务、RSpec 用例 |
| **PHPUnit** | PHPUnit 测试 |
-1
View File
@@ -57,7 +57,6 @@ Composer 项目没有 `vendor/`,或已安装的包与 `composer.lock` 不一
- **PHPStan**:项目中有 `vendor/bin/phpstan` 时,保存的文件会交给它检查,结果显示为诊断。**PHPStan › 配置文件** 用于指定配置;留空则使用项目根目录下的 `phpstan.neon`、`phpstan.neon.dist` 或 `phpstan.dist.neon`。
- **PHP-CS-Fixer**:当文件上层目录中有 `.php-cs-fixer.php` 或 `.php-cs-fixer.dist.php`,且项目有 `vendor/bin/php-cs-fixer` 时,**重新格式化代码**(`⌥⌘L` / `Ctrl+Alt+L`)改用 PHP-CS-Fixer,而不是语言服务器。
- **对齐**:**设置 › 编辑器 › 代码样式 › PHP › 对齐** 提供与 PhpStorm 相同的 **对齐键值对**(多行数组中的 `=>`)和 **对齐连续赋值**(相邻行赋值语句中的 `=`),默认都关闭。它们在语言服务器或 PHP-CS-Fixer 格式化之后生效,保存时格式化也一样;格式化选区时只作用于选中的行。空行、注释行、其他语句或跨多行的值会开始新的一组,嵌套数组单独对齐。
## 运行与测试
+1 -1
View File
@@ -105,7 +105,7 @@ Ruff 只为位于 Ruff 配置之下的文件启动:`ruff.toml`、`.ruff.toml`
即使项目没有声明任何测试配置,测试文件也可以用 pytest 运行(用项目解释器执行 `python -m pytest`,因此该解释器里要装有 pytest)。在 Django 项目中,`TestCase` 测试也可以用 `manage.py test` 运行。pytest 和 Django unittest 运行器的结果显示在测试树中,**重新运行失败的测试** 只重跑失败的用例。
也可以在 **运行 › 编辑配置…** 中新建 **Python**(脚本或模块)、**pytest** 和 **Django 测试** 配置。详见[运行配置](/zh/guide/run)和[测试](/zh/guide/testing)。
也可以在 **运行 › 编辑配置…** 中新建 **pytest** 和 **Django 测试** 配置。详见[运行配置](/zh/guide/run)和[测试](/zh/guide/testing)。
| 操作 | macOS | Windows / Linux |
| -------------- | ----- | ---------------- |
+1 -4
View File
@@ -211,8 +211,7 @@ pnpm theme:import-intellij path/to/MyTheme.theme.json path/to/MyTheme.icls --out
| `--syn-tag`, `--syn-attribute`, `--syn-todo`, `--syn-invalid` | `DEFAULT_TAG`, `DEFAULT_ATTRIBUTE`, `TODO_DEFAULT_ATTRIBUTES`, `BAD_CHARACTER` |
| `--syn-rainbow-1` … `--syn-rainbow-5`(语义高亮) | `RAINBOW_COLOR1` … `RAINBOW_COLOR5` |
| `--wave-error`, `--wave-warning` | `ERRORS_ATTRIBUTES`, `WARNING_ATTRIBUTES`(效果颜色) |
| `--bg-matched-brace`, `--bg-identifier-under-caret`, `--fg-identifier-under-caret` | `MATCHED_BRACE_ATTRIBUTES`, `IDENTIFIER_UNDER_CARET_ATTRIBUTES` |
| `--bg-identifier-under-caret-write`, `--fg-identifier-under-caret-write` | `WRITE_IDENTIFIER_UNDER_CARET_ATTRIBUTES` |
| `--bg-matched-brace`, `--bg-identifier-under-caret` | `MATCHED_BRACE_ATTRIBUTES`, `IDENTIFIER_UNDER_CARET_ATTRIBUTES` |
| `--bg-text-search-result`, `--bg-search-result` | `TEXT_SEARCH_RESULT_ATTRIBUTES`, `SEARCH_RESULT_ATTRIBUTES` |
| `--syn-self`, `--syn-keyword-arg`, `--syn-docstring`, `--syn-predefined` | `PY.SELF_PARAMETER`, `PY.KEYWORD_ARGUMENT`, `PY.DOC_COMMENT`, `PY.BUILTIN_NAME` |
| `--ansi-*` | `CONSOLE_*_OUTPUT`(`CONSOLE_DARKGRAY_OUTPUT` 为亮黑,`CONSOLE_GRAY_OUTPUT` 为白色) |
@@ -486,8 +485,6 @@ VS Code 主题(扩展中的 `themes/*.json`)包含 `type`(`dark` / `light`
| `--fg-unused` | `#6f737a` | `#8c8c8c` |
| `--bg-identifier-under-caret` | `#373b39` | `#edebfc` |
| `--bg-identifier-under-caret-write` | `#402f33` | `#fce8f4` |
| `--fg-identifier-under-caret` | `inherit` | `inherit` |
| `--fg-identifier-under-caret-write` | `inherit` | `inherit` |
| `--fg-inlay` | `#868a91` | `#73767c` |
| `--bg-inlay` | `#393b40` | `#00000012` |
| `--wave-error` | `#fa6675` | `#f50000` |
-1
View File
@@ -416,7 +416,6 @@ test("dragging the Changes pane's edge resizes it for the next session too", asy
// The next session starts with the dragged width.
await page.reload();
await expect(page.getByRole("tree", { name: "Project" })).toBeVisible();
await seedTasks(page, "editor");
await seedChanges(page);
await expect.poll(async () => Math.round((await changes.boundingBox())!.width)).toBe(Math.round(widened));
-34
View File
@@ -1024,37 +1024,3 @@ test("aligns Mermaid diagrams in replies to their container align attribute", as
expect(Math.abs(offsets[2]!.rightGap)).toBeLessThanOrEqual(1);
expect(Math.abs(offsets[3]!.leftGap - offsets[3]!.rightGap)).toBeLessThanOrEqual(1.5);
});
test("renders LaTeX math formulas with KaTeX and keeps wide equations scrollable", async ({ page }) => {
const reply = await openReply(
page,
[
"Inline $E = mc^2$ and \\(a^2 + b^2 = c^2\\), prices $5 and $10 stay plain.",
"",
"$$",
"\\int_{-\\infty}^{\\infty} e^{-x^2} \\, dx = \\sqrt{\\pi}",
"$$",
"",
"```math",
"\\sum_{k=1}^{n} k = \\frac{n(n+1)}{2} + a_1 + a_2 + a_3 + a_4 + a_5 + a_6 + a_7 + a_8 + a_9 + a_{10}",
"```",
].join("\n"),
);
await expect(reply.locator(".katex")).toHaveCount(4);
await expect(reply.locator(".katex-display")).toHaveCount(2);
await expect(reply).toContainText("prices $5 and $10 stay plain.");
const layout = await reply.evaluate((el) => {
const firstKatex = el.querySelector<HTMLElement>(".katex")!;
const display = el.querySelectorAll<HTMLElement>(".katex-display");
const font = getComputedStyle(firstKatex).fontFamily;
return {
font,
height: firstKatex.getBoundingClientRect().height,
overflowX: getComputedStyle(display[1]!).overflowX,
};
});
expect(layout.font).toContain("KaTeX_Main");
expect(layout.height).toBeGreaterThan(10);
expect(layout.overflowX).toBe("auto");
});
+1 -1
View File
@@ -102,7 +102,7 @@ test("stripe themes inherit base tooltip tokens and keep shortcut text readable"
delete root.dataset.colorTheme;
root.dataset.theme = kind;
root.dataset.pluginTheme = "test/base-tooltip";
const path = "/src/features/plugins/themeRuntime.ts";
const path = "/src/features/plugins/bridge.ts";
const { pluginThemeCss } = await import(/* @vite-ignore */ path);
const style = document.createElement("style");
style.id = "test-plugin-theme";
+1 -1
View File
@@ -47,7 +47,7 @@ moveRefactoringSupport = true
[language-servers.initialization-options.settings.java]
autobuild = { enabled = true }
contentProvider = { preferred = "fernflowerContentProvider" }
maven = { downloadSources = false, updateSnapshots = false }
maven = { downloadSources = true, updateSnapshots = false }
eclipse = { downloadSources = true }
references = { includeDecompiledSources = true }
# The editor's usage lenses count usages; the server's own lenses would search every
+1 -2
View File
@@ -2,7 +2,7 @@
"name": "openidea",
"private": true,
"description": "An open-source IDE inspired by IntelliJ IDEA",
"version": "0.1.48",
"version": "0.1.47",
"license": "Apache-2.0",
"type": "module",
"scripts": {
@@ -80,7 +80,6 @@
"dompurify": "^3.4.17",
"emmet": "2.4.11",
"immer": "^11.1.21",
"katex": "^0.19.1",
"marked": "^18.1.1",
"mermaid": "12.1.0",
"react": "^19.1.0",
-2
View File
@@ -116,7 +116,6 @@
"text/apply_100_changes_1mb": 1000,
"text/diff_two_edits_1mb": 10000,
"text/diff_every_line_1mb": 100000,
"text/diff_one_edit_5mb": 2000,
"text/offset_to_pos_round_trip": 5,
"text/pos_to_byte": 5,
"text/text_for_save_crlf_1mb": 1000,
@@ -142,7 +141,6 @@
"search_5k/literal": 100000,
"search_5k/regex": 100000,
"search_5k/dense_limit": 20000,
"search_dense_files/24x40k_limit": 20000,
"plugins/load_50": 20000,
"plugins/cold_activation": 30000,
@@ -104,8 +104,6 @@
"--fg-deprecated": "#8c8f95",
"--bg-identifier-under-caret": "#2e353f",
"--bg-identifier-under-caret-write": "#402f33",
"--fg-identifier-under-caret": "inherit",
"--fg-identifier-under-caret-write": "inherit",
"--fg-inlay": "#75869d",
"--bg-inlay": "#303944",
"--wave-typo": "#59a869",
+2 -5
View File
@@ -232,8 +232,7 @@ The full table is `UI_KEYS` in [`src/features/plugins/intellijTheme.ts`](../src/
| `--syn-tag`, `--syn-attribute`, `--syn-todo`, `--syn-invalid` | `DEFAULT_TAG`, `DEFAULT_ATTRIBUTE`, `TODO_DEFAULT_ATTRIBUTES`, `BAD_CHARACTER` |
| `--syn-rainbow-1` … `--syn-rainbow-5` (Semantic highlighting, rainbow indent guides) | `RAINBOW_COLOR1` … `RAINBOW_COLOR5` |
| `--wave-error`, `--wave-warning` | `ERRORS_ATTRIBUTES`, `WARNING_ATTRIBUTES` (effect colour) |
| `--bg-matched-brace`, `--bg-identifier-under-caret`, `--fg-identifier-under-caret` | `MATCHED_BRACE_ATTRIBUTES`, `IDENTIFIER_UNDER_CARET_ATTRIBUTES` |
| `--bg-identifier-under-caret-write`, `--fg-identifier-under-caret-write` | `WRITE_IDENTIFIER_UNDER_CARET_ATTRIBUTES` |
| `--bg-matched-brace`, `--bg-identifier-under-caret` | `MATCHED_BRACE_ATTRIBUTES`, `IDENTIFIER_UNDER_CARET_ATTRIBUTES` |
| `--bg-text-search-result`, `--bg-search-result` | `TEXT_SEARCH_RESULT_ATTRIBUTES`, `SEARCH_RESULT_ATTRIBUTES` |
| `--syn-self`, `--syn-keyword-arg`, `--syn-docstring`, `--syn-predefined` | `PY.SELF_PARAMETER`, `PY.KEYWORD_ARGUMENT`, `PY.DOC_COMMENT`, `PY.BUILTIN_NAME` |
| `--ansi-*` | `CONSOLE_*_OUTPUT` (`CONSOLE_DARKGRAY_OUTPUT` is bright black, `CONSOLE_GRAY_OUTPUT` white) |
@@ -333,7 +332,7 @@ a token.
<!-- BEGIN GENERATED TOKEN REFERENCE: pnpm gen:theme-docs -->
271 themeable tokens: 125 in the UI theme file, 146 in the editor colour scheme file.
269 themeable tokens: 125 in the UI theme file, 144 in the editor colour scheme file.
### Surfaces (UI theme)
@@ -529,8 +528,6 @@ a token.
| `--fg-deprecated` | `#8c8f95` | `#6c707e` |
| `--bg-identifier-under-caret` | `#373b39` | `#edebfc` |
| `--bg-identifier-under-caret-write` | `#402f33` | `#fce8f4` |
| `--fg-identifier-under-caret` | `inherit` | `inherit` |
| `--fg-identifier-under-caret-write` | `inherit` | `inherit` |
| `--fg-inlay` | `#868a91` | `#73767c` |
| `--bg-inlay` | `#393b40` | `#00000012` |
| `--wave-error` | `#fa6675` | `#f50000` |
-11
View File
@@ -119,9 +119,6 @@ importers:
immer:
specifier: ^11.1.21
version: 11.1.21
katex:
specifier: ^0.19.1
version: 0.19.1
marked:
specifier: ^18.1.1
version: 18.1.1
@@ -1802,10 +1799,6 @@ packages:
resolution: {integrity: sha512-/B6p9eY9DX7aHBfpkHdpirDTZ5QH9xTwL9y837PWuzuv41O5jFdqNQwVQEQsimY0/iVNkwBY4+4hMfhQ7d4Dbw==}
hasBin: true
[email protected]:
resolution: {integrity: sha512-jG8uKntjSEcm2EpQOh0XturpPuuC9r3Sq5HLHdsFdWZT27E672SF19QEi+of0/YeOy15lDgRhKvr5614uRrEfA==}
hasBin: true
[email protected]:
resolution: {integrity: sha512-Ls993zuzfayK269Svk9hzpeGUKob/sIgZzyHYdjQoAdQetRKpOLj+k/QQQ/6Qi0Yz65mlROrfd+Ev+1+7dz9Kw==}
@@ -3799,10 +3792,6 @@ snapshots:
dependencies:
commander: 15.1.0
[email protected]:
dependencies:
commander: 15.1.0
[email protected]: {}
[email protected]:
-17
View File
@@ -170,23 +170,6 @@ describe("IntelliJ theme import", () => {
});
});
it("maps the caret identifier foregrounds (#4109)", () => {
const s = convertIcls(`<scheme name="Caret" version="142" parent_scheme="Darcula"><attributes>
<option name="IDENTIFIER_UNDER_CARET_ATTRIBUTES"><value>
<option name="FOREGROUND" value="aa0000" /><option name="BACKGROUND" value="220000" />
</value></option>
<option name="WRITE_IDENTIFIER_UNDER_CARET_ATTRIBUTES"><value>
<option name="FOREGROUND" value="00aa00" /><option name="BACKGROUND" value="002200" />
</value></option>
</attributes></scheme>`);
expect(s.tokens).toMatchObject({
"--fg-identifier-under-caret": "#aa0000",
"--bg-identifier-under-caret": "#220000",
"--fg-identifier-under-caret-write": "#00aa00",
"--bg-identifier-under-caret-write": "#002200",
});
});
it("only targets tokens that exist in tokens.css", () => {
const declared = new Set([...css.matchAll(/(--[a-z0-9-]+)\s*:/g)].map((m) => m[1]!));
// Read with a fallback by the editor (no tokens.css default), still themeable.
@@ -1,4 +1,4 @@
package openidea:[email protected]1.0;
package openidea:[email protected]0.0;
/// The commit being prepared in the window the current command or event came
/// from (the Commit tool window, or the Commit dialog while it is open): the
@@ -1,4 +1,4 @@
package openidea:[email protected]1.0;
package openidea:[email protected]0.0;
/// Plugin-owned project data sources. Requires database.sources and project trust.
/// Runs on the Database subsystem's host, including on remote project servers.
@@ -1,4 +1,4 @@
package openidea:[email protected]1.0;
package openidea:[email protected]0.0;
/// Editor and project-tree decorations (API 1.4). Requires project.read. An editor set
/// follows its file: the file's own project, or the nearest one when it is outside them all.
@@ -1,4 +1,4 @@
package openidea:[email protected]1.0;
package openidea:[email protected]0.0;
/// What the pane beside the Services tree shows for a plugin's node.
interface detail-types {
@@ -1,4 +1,4 @@
package openidea:[email protected]1.0;
package openidea:[email protected]0.0;
/// Optional export (world `plugin-diagnostics`): problems in the current,
/// possibly unsaved document, for the languages declared with the
@@ -1,4 +1,4 @@
package openidea:[email protected]1.0;
package openidea:[email protected]0.0;
/// HTTP endpoints found in a project (`[[contributes.endpoints]]`).
interface endpoints-provider {
@@ -1,4 +1,4 @@
package openidea:[email protected]1.0;
package openidea:[email protected]0.0;
/// Workbench events, delivered in batches to `event-handler.handle`.
interface events {
@@ -1,4 +1,4 @@
package openidea:[email protected]1.0;
package openidea:[email protected]0.0;
interface lifecycle {
use types.{context, error};
@@ -1,4 +1,4 @@
package openidea:[email protected]1.0;
package openidea:[email protected]0.0;
/// What other plugins contributed to the extension points this plugin declares
/// (`[[extension-points]]` in `plugin.toml`; the contributors list this plugin
@@ -1,4 +1,4 @@
package openidea:[email protected]1.0;
package openidea:[email protected]0.0;
/// Optional export (world `plugin-file-actions`): quick fixes and
/// refactorings that create, rename or delete files, next to the text edits
@@ -1,4 +1,4 @@
package openidea:[email protected]1.0;
package openidea:[email protected]0.0;
/// Files outside the open projects: the configuration of the program a
/// plugin integrates with, a tool installed elsewhere, a licence file.
@@ -1,4 +1,4 @@
package openidea:[email protected]1.0;
package openidea:[email protected]0.0;
/// Writes to the IDE log, tagged with the plugin id.
interface log {
@@ -75,21 +75,6 @@ interface ui {
remove-context: func(key: string);
/// Copies `text` to the system clipboard. Requires `clipboard`.
copy-to-clipboard: func(text: string) -> result<_, error>;
/// What `read-clipboard` found (API 1.11). Both `none`: the clipboard holds
/// neither text nor an image.
record clipboard-content {
text: option<string>,
/// An image (a screenshot), always as PNG bytes.
image: option<list<u8>>,
}
/// Reads the system clipboard of the user's machine (API 1.11). Requires
/// `clipboard.read`. Only in a command the user ran or a view action from
/// a window; anywhere else (event handlers, background and scheduled
/// work, web view messages, a command run through `command-runner`) it is
/// `denied`, so nothing reads the clipboard behind the user's back. Text
/// or an image over 16 MiB fails the call. In a remote project the user
/// confirms first; refusing is `denied`.
read-clipboard: func() -> result<clipboard-content, error>;
/// Opens an `http://` or `https://` URL in the user's default browser.
open-url: func(url: string) -> result<_, error>;
/// Shows a list and waits for the chosen key, or `none` when dismissed.
@@ -1,4 +1,4 @@
package openidea:[email protected]1.0;
package openidea:[email protected]0.0;
/// Optional export (world `plugin-hover`): Markdown added to the hover of
/// documents of the languages declared with the `hover` provider kind,
@@ -1,4 +1,4 @@
package openidea:[email protected]1.0;
package openidea:[email protected]0.0;
/// Cross-file associations a plugin publishes for the files it declares under
/// `[[contributes.documentIndexers]]`. The host calls `index` in cancellable
@@ -1,4 +1,4 @@
package openidea:[email protected]1.0;
package openidea:[email protected]0.0;
/// Embedded languages. The host routes plugin providers and configured language
/// servers inside these ranges, preserving host-document UTF-16 coordinates.
@@ -1,4 +1,4 @@
package openidea:[email protected]1.0;
package openidea:[email protected]0.0;
/// Optional export (world `plugin-inlay-hints`): inline hints in documents of
/// the languages declared with the `inlay-hints` provider kind, including
@@ -1,4 +1,4 @@
package openidea:[email protected]1.0;
package openidea:[email protected]0.0;
/// Problems in files, shown in the editor and the Problems view.
interface diagnostics {
@@ -1,4 +1,4 @@
package openidea:[email protected]1.0;
package openidea:[email protected]0.0;
/// Additional language features, called only for declared API 1.4 provider kinds.
/// Editor calls have a 50 ms soft / 500 ms hard budget; formatting has 5 seconds.
@@ -1,4 +1,4 @@
package openidea:[email protected]1.0;
package openidea:[email protected]0.0;
/// Discovery of the IDE's built-in MCP server; never exposes its URL or token.
interface mcp {
@@ -8,7 +8,7 @@
/// `fs` and `workspace`, and everything else goes through the imports below,
/// gated by the capabilities granted in `plugin.toml` (a missing one returns
/// `error::denied`).
package openidea:[email protected]1.0;
package openidea:[email protected]0.0;
world plugin {
import log;
@@ -1,4 +1,4 @@
package openidea:[email protected]1.0;
package openidea:[email protected]0.0;
/// Editor features a plugin provides for the languages it declares under
/// `[[contributes.providers]]` (the host calls only declared kinds). They run
@@ -1,4 +1,4 @@
package openidea:[email protected]1.0;
package openidea:[email protected]0.0;
/// Project-scoped targets owned by the registering plugin (API 1.4).
interface run-targets {
@@ -1,4 +1,4 @@
package openidea:[email protected]1.0;
package openidea:[email protected]0.0;
/// Launches this plugin's configurations in the invoking window's Run tool window.
interface run {
@@ -1,4 +1,4 @@
package openidea:[email protected]1.0;
package openidea:[email protected]0.0;
/// Optional export (world `plugin-semantic-tokens`): semantic colouring of
/// documents of the languages declared with the `semantic-tokens` provider
@@ -1,4 +1,4 @@
package openidea:[email protected]1.0;
package openidea:[email protected]0.0;
/// Shared types. Positions are 0-based lines and UTF-16 code unit columns,
/// as in the editor and LSP.
@@ -1,4 +1,4 @@
package openidea:[email protected]1.0;
package openidea:[email protected]0.0;
/// Declarative views: tool windows declared
/// under `[[contributes.views]]` and custom editors under
@@ -1,4 +1,4 @@
package openidea:[email protected]1.0;
package openidea:[email protected]0.0;
interface workspace {
use types.{error, location};
Loaded 100 of 251 files, more files were not shown because too many files have changed in this diff. Show more